diff --git a/include/echoion/plugin/PluginInterface.hpp b/include/echoion/plugin/PluginInterface.hpp index 2f7688d..280eb28 100644 --- a/include/echoion/plugin/PluginInterface.hpp +++ b/include/echoion/plugin/PluginInterface.hpp @@ -55,6 +55,15 @@ namespace Echoion::Plugin getClients() override; [[nodiscard]] Api::Result> getClient(uint64_t clientId) override; + [[nodiscard]] Api::Result> + getClientIp(uint64_t clientId) override; + [[nodiscard]] Api::Result> + getClientAvatarPath(uint64_t clientId) override; + [[nodiscard]] Api::Result> + getClientAvatarUrl(uint64_t clientId) override; + [[nodiscard]] Api::Result> + requestClientAvatar(uint64_t clientId, + const std::string& destDir) override; Api::Result moveClient(uint64_t clientId, uint64_t channelId) override; Api::Result kickClient(uint64_t clientId, @@ -90,6 +99,7 @@ namespace Echoion::Plugin void clearEventCallbacks(); // TeamSpeak event handlers (called by TeamSpeak SDK) + void onConnectionEstablished(uint64_t serverConnectionHandlerId); void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId); void onClientDisconnected(uint64_t serverConnectionHandlerId, diff --git a/src/CoreLoader.cpp b/src/CoreLoader.cpp index c09bef2..d3c7c66 100644 --- a/src/CoreLoader.cpp +++ b/src/CoreLoader.cpp @@ -184,7 +184,11 @@ namespace Echoion::Plugin if (deferredReloadThread_.joinable()) { deferredReloadThread_.join(); } - unload(); + if (auto result = unload(); !result) { + Void::Log::warn("CoreLoader", "{}", + std::format("Unload from destructor failed: {}", + result.error().message)); + } cleanupTempFiles(); } @@ -451,7 +455,12 @@ namespace Echoion::Plugin Void::Log::info("CoreLoader", "{}", "Unloading core library..."); if (core_) { - core_->shutdown(); + if (auto result = core_->shutdown(); !result) { + Void::Log::warn( + "CoreLoader", "{}", + std::format("Core shutdown reported failure: {}", + result.error().message)); + } core_.reset(); } diff --git a/src/Plugin.cpp b/src/Plugin.cpp index e141fc8..a6aa582 100644 --- a/src/Plugin.cpp +++ b/src/Plugin.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include namespace Echoion::Plugin @@ -163,14 +164,13 @@ namespace Echoion::Plugin if (core && g_pluginInterface) { core->setPluginInterface(g_pluginInterface); - // Register for plugin events from Core + // Register for plugin events from Core. Auto-connect is + // already triggered inside setPluginInterface() above. g_pluginInterface->registerEventCallback( [core](const Api::PluginEvent& event) { - core->onPluginEvent(event); + // Core logs dispatch failures itself. + std::ignore = core->onPluginEvent(event); }); - - // Trigger auto-connect now that plugin interface is set - core->triggerAutoConnect(); } return true; @@ -299,18 +299,20 @@ namespace Echoion::Plugin } } + // Teardown is best-effort: failures here can't be acted on and the + // individual calls log their own errors. if (g_pluginInterface) { - g_pluginInterface->disconnectFromServer(); + std::ignore = g_pluginInterface->disconnectFromServer(); } if (g_coreLoader) { g_coreLoader->disableAutoReload(); - g_coreLoader->unload(); + std::ignore = g_coreLoader->unload(); g_coreLoader.reset(); } if (g_pluginInterface) { - g_pluginInterface->shutdown(); + std::ignore = g_pluginInterface->shutdown(); g_pluginInterface = nullptr; } @@ -322,9 +324,10 @@ namespace Echoion::Plugin // Handle incoming text messages TS3_PLUGIN_API void ts3plugin_onTextMessageEvent( - uint64 serverConnectionHandlerId, anyID targetMode, anyID toID, - anyID fromID, const char* fromName, const char* fromUniqueIdentifier, - const char* message, int ffIgnored) + uint64 serverConnectionHandlerId, anyID targetMode, anyID /*toID*/, + anyID fromID, const char* /*fromName*/, + const char* /*fromUniqueIdentifier*/, const char* message, + int /*ffIgnored*/) { anyID myID = 0; @@ -345,7 +348,7 @@ namespace Echoion::Plugin // Handle client connect/disconnect TS3_PLUGIN_API void ts3plugin_onClientMoveEvent( uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, const char* moveMessage) + uint64 newChannelID, int /*visibility*/, const char* /*moveMessage*/) { if (!g_pluginInterface) { @@ -364,9 +367,32 @@ namespace Echoion::Plugin } } - TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent( + // Clients that become visible without moving — e.g. everyone already + // online when the bot itself connects, or channel-subscription changes. + // Without this, subscribers present before a restart never produce a + // ClientConnected event and restored playback stays paused. + TS3_PLUGIN_API void ts3plugin_onClientMoveSubscriptionEvent( uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID, - uint64 newChannelID, int visibility, const char* timeoutMessage) + uint64 newChannelID, int /*visibility*/) + { + + if (!g_pluginInterface) { + return; + } + + if (oldChannelID == 0) { + g_pluginInterface->onClientConnected(serverConnectionHandlerId, + clientID); + } else if (newChannelID == 0) { + g_pluginInterface->onClientDisconnected(serverConnectionHandlerId, + clientID); + } + } + + TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent( + uint64 serverConnectionHandlerId, anyID clientID, + uint64 /*oldChannelID*/, uint64 /*newChannelID*/, int /*visibility*/, + const char* /*timeoutMessage*/) { if (g_pluginInterface) { @@ -420,11 +446,14 @@ namespace Echoion::Plugin std::cout << "[Echoion] About to register new callback..." << '\n'; g_pluginInterface->registerEventCallback( [core](const Api::PluginEvent& event) { - core->onPluginEvent(event); + // Core logs dispatch failures itself. + std::ignore = core->onPluginEvent(event); }); std::cout << "[Echoion] New event callback registered" << '\n'; - core->skip(0); - core->resume(); + // Best-effort nudge so playback resumes after the reload; failures + // only mean nothing was playing. + std::ignore = core->skip(0); + std::ignore = core->resume(); std::cout << "[Echoion] Re-registration complete - bot should respond " "to commands" << '\n'; @@ -457,8 +486,8 @@ namespace Echoion::Plugin // Handle plugin commands from TS3 TS3_PLUGIN_API void - ts3plugin_onPluginCommandEvent(uint64 serverConnectionHandlerId, - const char* pluginName, + ts3plugin_onPluginCommandEvent(uint64 /*serverConnectionHandlerId*/, + const char* /*pluginName*/, const char* command) { @@ -508,9 +537,9 @@ namespace Echoion::Plugin // Menu item callbacks TS3_PLUGIN_API void - ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId, - enum PluginMenuType type, int menuItemID, - uint64 selectedItemID) + ts3plugin_onMenuItemEvent(uint64 /*serverConnectionHandlerId*/, + enum PluginMenuType /*type*/, int menuItemID, + uint64 /*selectedItemID*/) { if (!ensureCoreLoaded()) { @@ -522,24 +551,26 @@ namespace Echoion::Plugin return; } + // Menu actions are fire-and-forget: Core logs failures and there is + // no channel to report them back through the TS3 menu. switch (menuItemID) { case 1: { // Play/Pause auto state = core->getPlaybackSummary(); if (state) { if (state->isPlaying && !state->isPaused) { - core->pause(); + std::ignore = core->pause(); } else if (state->isPaused) { - core->resume(); + std::ignore = core->resume(); } } break; } case 2: // Skip - core->skip(1); + std::ignore = core->skip(1); break; case 3: // Stop - core->stop(); + std::ignore = core->stop(); break; case 4: // Hot Reload Core reloadCoreWithInterface(); @@ -547,7 +578,8 @@ namespace Echoion::Plugin case 5: // Connect/Disconnect if (g_pluginInterface) { if (g_pluginInterface->isConnected()) { - g_pluginInterface->disconnectFromServer(); + std::ignore = + g_pluginInterface->disconnectFromServer(); } else { // Core handles connection, just trigger reconnect if (auto result = g_pluginInterface->reconnect(); @@ -626,7 +658,7 @@ namespace Echoion::Plugin TS3_PLUGIN_API void ts3plugin_onConnectStatusChangeEvent(uint64 serverConnectionHandlerId, int newStatus, - unsigned int errorNumber) + unsigned int /*errorNumber*/) { if (g_pluginInterface) { @@ -641,18 +673,25 @@ namespace Echoion::Plugin case STATUS_CONNECTED: std::cout << "[Echoion] Connected" << '\n'; if (g_pluginInterface) { - g_pluginInterface->closeAudioDevice(); - g_pluginInterface->openAudioDevice(); + // Cycle the device best-effort; both calls log errors. + std::ignore = g_pluginInterface->closeAudioDevice(); + std::ignore = g_pluginInterface->openAudioDevice(); } break; case STATUS_CONNECTION_ESTABLISHED: std::cout << "[Echoion] Connection established" << '\n'; joinDefaultChannel(serverConnectionHandlerId); + // Tell the core the client list is now available so it can + // resolve online subscribers and resume a restored session. + if (g_pluginInterface) { + g_pluginInterface->onConnectionEstablished( + serverConnectionHandlerId); + } break; case STATUS_DISCONNECTED: std::cout << "[Echoion] Disconnected" << '\n'; if (g_pluginInterface) { - g_pluginInterface->closeAudioDevice(); + std::ignore = g_pluginInterface->closeAudioDevice(); } break; } diff --git a/src/PluginInterface.cpp b/src/PluginInterface.cpp index 317af24..0f00a8c 100644 --- a/src/PluginInterface.cpp +++ b/src/PluginInterface.cpp @@ -3,9 +3,14 @@ #include #include "teamspeak/public_definitions.h" #include "teamspeak/public_rare_definitions.h" +#include #include +#include #include +#include #include +#include +#include #include namespace Echoion::Plugin { @@ -27,11 +32,20 @@ namespace Echoion::Plugin return chunks; } + // A chunk that is only whitespace (the blank lines left between two + // collapsible blocks after a split) would be sent as a blank, + // content-free message. Never emit those. + auto isBlank = [](const std::string& s) { + return s.find_first_not_of(" \t\r\n") == std::string::npos; + }; + std::string current; int detailsDepth = 0; auto flush = [&] { if (!current.empty()) { - chunks.push_back(current); + if (!isBlank(current)) { + chunks.push_back(current); + } current.clear(); } }; @@ -77,7 +91,10 @@ namespace Echoion::Plugin cut = limit; // pathological line; avoid infinite loop } flush(); - chunks.push_back(line.substr(0, cut)); + auto piece = line.substr(0, cut); + if (!isBlank(piece)) { + chunks.push_back(piece); + } line.erase(0, cut); } } @@ -100,7 +117,12 @@ namespace Echoion::Plugin PluginInterface::~PluginInterface() { if (initialized_) { - shutdown(); + if (auto result = shutdown(); !result) { + Void::Log::warn( + "PluginInterface", "{}", + std::format("Shutdown from destructor failed: {}", + result.error().message)); + } } } @@ -185,15 +207,16 @@ namespace Echoion::Plugin } } + // Teardown steps are best-effort; each call logs its own failure. // Close audio device - closeAudioDevice(); + std::ignore = closeAudioDevice(); // Unregister audio device - unregisterAudioDevice(); + std::ignore = unregisterAudioDevice(); // Disconnect from server if (isConnected()) { - disconnectFromServer(); + std::ignore = disconnectFromServer(); } // Clear callbacks @@ -320,6 +343,170 @@ namespace Echoion::Plugin return info; } + Api::Result> + PluginInterface::getClientIp(uint64_t clientId) + { + if (!initialized_ || !ts3Functions_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized"); + } + + // CONNECTION_CLIENT_IP is only populated after connection info has + // been requested from the server, and only when the bot holds the + // b_client_remoteaddress_view permission. The answer arrives + // asynchronously, so request once and poll briefly. + for (int attempt = 0; attempt < 4; ++attempt) { + char* ip = nullptr; + if (ts3Functions_->getConnectionVariableAsString( + serverConnectionHandlerId_, static_cast(clientId), + CONNECTION_CLIENT_IP, &ip) == ERROR_ok && + ip) { + std::string address = ip; + ts3Functions_->freeMemory(ip); + if (!address.empty()) { + return std::optional{std::move(address)}; + } + } + if (attempt == 0) { + ts3Functions_->requestConnectionInfo( + serverConnectionHandlerId_, static_cast(clientId), + nullptr); + } + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + } + return std::optional{}; + } + + Api::Result> + PluginInterface::getClientAvatarPath(uint64_t clientId) + { + if (!initialized_ || !ts3Functions_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized"); + } + if (!ts3Functions_->getAvatar) { + return std::optional{}; + } + + // getAvatar answers from the TS client's local avatar cache: a file + // path once the avatar is downloaded, an empty string while a + // download is in flight, and an error when the client has no + // avatar. The cache is populated automatically for clients in view. + char path[512] = {}; + const unsigned int error = ts3Functions_->getAvatar( + serverConnectionHandlerId_, static_cast(clientId), path, + sizeof(path)); + if (error != ERROR_ok || path[0] == '\0') { + return std::optional{}; + } + return std::optional{std::string(path)}; + } + + Api::Result> + PluginInterface::getClientAvatarUrl(uint64_t clientId) + { + if (!initialized_ || !ts3Functions_ || + !ts3Functions_->getClientVariableAsString) { + return std::optional{}; + } + char* v = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, static_cast(clientId), + CLIENT_MYTS_AVATAR, &v) != ERROR_ok || + !v) { + return std::optional{}; + } + std::string raw(v); + ts3Functions_->freeMemory(v); + // Format is "," (e.g. "2,https://storage.googleapis.com/ + // ts-sys-myts-avatars/"). Take everything after the first comma. + const auto comma = raw.find(','); + if (comma == std::string::npos) { + return std::optional{}; + } + std::string url = raw.substr(comma + 1); + if (!url.starts_with("http")) { + return std::optional{}; + } + return std::optional{std::move(url)}; + } + + Api::Result> + PluginInterface::requestClientAvatar(uint64_t clientId, + const std::string& destDir) + { + // NOTE: the plugin's Void::Log sink is separate from Core's, so plugin + // logs don't reach the journal. Until that's unified, surface the + // diagnosis through the return value — Core logs Api::fail messages as + // "requestClientAvatar -> error: ". + if (!initialized_ || !ts3Functions_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "avatar: plugin not initialized"); + } + if (!ts3Functions_->getClientVariableAsString || + !ts3Functions_->requestFile) { + return Api::fail(Api::ErrorCode::NotSupported, + "avatar: SDK getClientVariableAsString/requestFile " + "unavailable"); + } + + // Read a client string variable into a std::string ("" on any error). + auto readVar = [&](std::size_t prop) -> std::string { + char* v = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, static_cast(clientId), + prop, &v) == ERROR_ok && + v) { + std::string s(v); + ts3Functions_->freeMemory(v); + return s; + } + return {}; + }; + + // Legacy file-based avatar hash. Modern clients set their avatar via + // myTeamSpeak instead (CLIENT_MYTS_AVATAR), which leaves this empty — + // so read both and report what we actually have. + std::string hash = readVar(CLIENT_FLAG_AVATAR); + std::string mytsAvatar = readVar(CLIENT_MYTS_AVATAR); + if (hash.empty()) { + return Api::fail( + Api::ErrorCode::NotFound, + std::format( + "avatar: CLIENT_FLAG_AVATAR empty; CLIENT_MYTS_AVATAR " + "len={} value(≤80)='{}'", + mytsAvatar.size(), mytsAvatar.substr(0, 80))); + } + + // Avatars are files in the virtual server's file repository (channel 0) + // named "/avatar_". requestFile downloads into destDir, where the + // file lands as "avatar_". + const std::string remote = "/avatar_" + hash; + const std::filesystem::path localPath = + std::filesystem::path(destDir) / ("avatar_" + hash); + + std::error_code ec; + std::filesystem::create_directories(destDir, ec); + + // Already downloaded (this or an earlier request finished): serve it. + if (std::filesystem::exists(localPath, ec)) { + return std::optional{localPath.string()}; + } + + // Kick off the async download; the file appears in destDir when the + // transfer completes, so a later call returns the path. overwrite=1 so + // a stale partial is replaced, resume=0. + anyID transferId = 0; + const unsigned int error = ts3Functions_->requestFile( + serverConnectionHandlerId_, 0, "", remote.c_str(), 1, 0, + destDir.c_str(), &transferId, nullptr); + return Api::fail( + Api::ErrorCode::PluginError, + std::format("avatar: download started hash={} result={:#x} " + "transferId={}", + hash, error, transferId)); + } + Api::Result PluginInterface::moveClient(uint64_t clientId, uint64_t channelId) { @@ -514,7 +701,6 @@ namespace Echoion::Plugin PluginInterface::sendAudioData(const std::span& data) { static int callCount = 0; - static int nonZeroTotal = 0; callCount++; // Debug: Check audio data on first few calls @@ -528,7 +714,6 @@ namespace Echoion::Plugin maxSample = std::max(maxSample, std::abs(static_cast(data[i]))); } - nonZeroTotal += nonZero; Void::Log::debug("PluginInterface", "{}", std::format( "sendAudioData {}: {} samples, nonZero={}/100, maxSample={}, " "queueSize={}", @@ -628,6 +813,19 @@ namespace Echoion::Plugin eventCallbacks_.clear(); } + void PluginInterface::onConnectionEstablished( + uint64_t serverConnectionHandlerId) + { + if (serverConnectionHandlerId != serverConnectionHandlerId_) { + return; + } + + broadcastEvent(Api::PluginEvent{ + .type = Api::PluginEventType::ConnectionEstablished, + .clientId = 0, + .timestamp = std::chrono::system_clock::now()}); + } + void PluginInterface::onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId) { @@ -670,7 +868,7 @@ namespace Echoion::Plugin } void PluginInterface::onTextMessageReceived( - uint64_t serverConnectionHandlerId, uint64_t targetMode, + uint64_t serverConnectionHandlerId, uint64_t /*targetMode*/, uint64_t fromId, const std::string& message) { if (serverConnectionHandlerId != serverConnectionHandlerId_) { @@ -686,7 +884,7 @@ namespace Echoion::Plugin void PluginInterface::onVoiceDataReceived( uint64_t serverConnectionHandlerId, uint64_t clientId, - const std::span& data) + const std::span& /*data*/) { if (serverConnectionHandlerId != serverConnectionHandlerId_) { return; @@ -707,12 +905,10 @@ namespace Echoion::Plugin } currentServerConfig_ = config; - // Prepare default channel array - const char* defaultChannelArray[2] = {nullptr, nullptr}; + // Default channel (guiConnect takes it as a plain string) std::string defaultChannelStr; if (config.defaultChannelId.has_value()) { defaultChannelStr = config.defaultChannelId.value(); - defaultChannelArray[0] = defaultChannelStr.c_str(); } unsigned int error = ts3Functions_->guiConnect( @@ -758,8 +954,8 @@ namespace Echoion::Plugin return {}; } - // Close audio device first - closeAudioDevice(); + // Close audio device first (best-effort; it logs failures). + std::ignore = closeAudioDevice(); // Stop connection unsigned int error = ts3Functions_->stopConnection( serverConnectionHandlerId_, "Echoion Bot disconnecting"); @@ -875,7 +1071,7 @@ namespace Echoion::Plugin return {}; } - closeAudioDevice(); + std::ignore = closeAudioDevice(); // Check if unregisterCustomDevice is available if (!ts3Functions_->unregisterCustomDevice) { @@ -1163,8 +1359,9 @@ namespace Echoion::Plugin } void PluginInterface::onServerGroupByClientID( - uint64_t serverConnectionHandlerId, uint64_t clientDatabaseId, - const char* groupName, uint64_t serverGroupId, uint64_t clientId) + uint64_t serverConnectionHandlerId, uint64_t /*clientDatabaseId*/, + const char* /*groupName*/, uint64_t /*serverGroupId*/, + uint64_t /*clientId*/) { if (serverConnectionHandlerId != serverConnectionHandlerId_) {