diff --git a/CMakeLists.txt b/CMakeLists.txt index a03a272..293c64d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,12 +5,14 @@ set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) + CPMAddPackage( NAME dylib GITHUB_REPOSITORY martin-olivier/dylib GIT_TAG "v3.0.1" OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON" ) + add_library(EchoionPlugin SHARED src/PluginInterface.cpp src/CoreLoader.cpp @@ -56,19 +58,14 @@ if(TARGET dylib) set_target_properties(dylib PROPERTIES POSITION_INDEPENDENT_CODE ON) endif() -include(GNUInstallDirs) -install(TARGETS EchoionPlugin - EXPORT EchoionPluginTargets - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}/plugins - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/plugins -) - -install(EXPORT EchoionPluginTargets - FILE EchoionPluginTargets.cmake - NAMESPACE Echoion:: - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionPlugin -) - -install(DIRECTORY include/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +# PackageProject.cmake configuration +packageProject( + NAME EchoionPlugin + VERSION ${PROJECT_VERSION} + NAMESPACE Echoion + BINARY_DIR ${PROJECT_BINARY_DIR} + INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include + INCLUDE_DESTINATION include + COMPATIBILITY SameMajorVersion + DISABLE_VERSION_SUFFIX YES ) diff --git a/include/echoion/plugin/CoreLoader.hpp b/include/echoion/plugin/CoreLoader.hpp index d552993..0d65c02 100644 --- a/include/echoion/plugin/CoreLoader.hpp +++ b/include/echoion/plugin/CoreLoader.hpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace Echoion::Plugin { @@ -32,6 +33,10 @@ public: void enableAutoReload(); void disableAutoReload(); [[nodiscard]] bool isAutoReloadEnabled() const noexcept; + + // Callback for hot reload completion (called after auto-reload finishes) + using HotReloadCallback = std::function; + void setHotReloadCallback(HotReloadCallback callback) { hotReloadCallback_ = std::move(callback); } private: Api::Result loadLibraryInternal(const std::filesystem::path& path); @@ -54,7 +59,20 @@ private: FileWatcher fileWatcher_; std::atomic autoReloadEnabled_{false}; + // Deferred reload - waits for current track to finish + std::thread deferredReloadThread_; + std::atomic hasPendingReload_{false}; + std::filesystem::path pendingReloadPath_; + std::string pendingTrackId_; // Track ID that was playing when reload scheduled + mutable std::mutex pendingReloadMutex_; + + // Hot reload completion callback + HotReloadCallback hotReloadCallback_; + void onCoreFileChanged(); + void waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId); + [[nodiscard]] bool isPlaybackActive() const; + [[nodiscard]] bool isSameTrackPlaying(const std::string& trackId) const; }; } // namespace Echoion::Plugin diff --git a/include/echoion/plugin/PluginInterface.hpp b/include/echoion/plugin/PluginInterface.hpp index 2639cbb..df584b7 100644 --- a/include/echoion/plugin/PluginInterface.hpp +++ b/include/echoion/plugin/PluginInterface.hpp @@ -1,13 +1,15 @@ #pragma once -#include +#include +#include #include +#include +#include +#include #include #include -#include -#include #include -#include +#include // TeamSpeak SDK headers #include "ts3_functions.h" @@ -18,9 +20,16 @@ namespace Echoion::Plugin { struct AudioDeviceConfig { static constexpr const char* DEVICE_ID = "echoion_audio_device"; static constexpr const char* DEVICE_NAME = "Echoion Music Bot Audio"; - static constexpr int SAMPLE_RATE = 192000; // Match reference implementation - static constexpr int CHANNELS = 2; - static constexpr int SAMPLE_SIZE = sizeof(int16_t); + static constexpr int SAMPLE_RATE = + 192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC) + static constexpr int CHANNELS = 2; + static constexpr int SAMPLE_SIZE = sizeof(int16_t); +}; + +// Server groups cache entry +struct ServerGroupsCacheEntry { + std::vector groups; + std::chrono::steady_clock::time_point timestamp; }; // Plugin implementation of IPluginInterface for the Core to use @@ -37,14 +46,19 @@ public: Api::Result shutdown() override; // Client operations - [[nodiscard]] Api::Result> getClients() const override; - [[nodiscard]] Api::Result> getClient(uint64_t clientId) const override; - Api::Result moveClient(uint64_t clientId, uint64_t channelId) override; - Api::Result kickClient(uint64_t clientId, const std::string& reason) override; + [[nodiscard]] Api::Result> + getClients() override; + [[nodiscard]] Api::Result> + getClient(uint64_t clientId) override; + Api::Result moveClient(uint64_t clientId, + uint64_t channelId) override; + Api::Result kickClient(uint64_t clientId, + const std::string& reason) override; - // Channel operations - [[nodiscard]] Api::Result> getChannels() const override; - [[nodiscard]] Api::Result> getChannel(uint64_t channelId) const override; + // Channel operations + [[nodiscard]] Api::Result> + getChannels() const override; + [[nodiscard]] Api::Result> getChannel(uint64_t channelId) const override; // Messaging Api::Result sendTextMessage(uint64_t targetId, const std::string& message) override; @@ -52,12 +66,15 @@ public: Api::Result sendServerMessage(const std::string& message) override; // Audio - Api::Result sendAudioData(const std::span& data) override; - Api::Result setWhisperList(const std::vector& clientIds) override; + Api::Result + sendAudioData(const std::span& data) override; + Api::Result + setWhisperList(const std::vector& clientIds) override; - // Event subscription - void registerEventCallback(const Api::EventCallback& callback) override; + // Event subscription + void registerEventCallback(const Api::EventCallback& callback) override; void unregisterEventCallback(const Api::EventCallback& callback) override; + void clearEventCallbacks(); // TeamSpeak event handlers (called by TeamSpeak SDK) void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId); @@ -68,13 +85,19 @@ public: void onVoiceDataReceived(uint64_t serverConnectionHandlerId, uint64_t clientId, const std::span& data); - // Server connection management (IPluginInterface implementation) - Api::Result connectToServer(const Api::ServerConfig& config) override; - Api::Result disconnectFromServer() override; - [[nodiscard]] bool isConnected() const override; - Api::Result reconnect() override; + // Server group list callback (called by TeamSpeak SDK) + void onServerGroupByClientID(uint64_t serverConnectionHandlerId, + uint64_t clientDatabaseId, + const char* groupName, uint64_t serverGroupId, + uint64_t clientId); - // Audio device management + // Server connection management (IPluginInterface implementation) + Api::Result connectToServer(const Api::ServerConfig& config) override; + Api::Result disconnectFromServer() override; + [[nodiscard]] bool isConnected() const override; + Api::Result reconnect() override; + + // Audio device management Api::Result registerAudioDevice(); Api::Result unregisterAudioDevice(); Api::Result openAudioDevice(); @@ -87,31 +110,48 @@ public: [[nodiscard]] uint64_t getServerConnectionHandlerId() const; // Audio data submission (for internal use) - void submitAudioData(const std::span samples); + void submitAudioData(const std::span samples); + + // Automatic configuration + Api::Result configureAudioProfile(); + Api::Result checkAndHandleFirstRun(); private: void broadcastEvent(const Api::PluginEvent& event); std::string getClientName(uint64_t clientId) const; std::string getChannelName(uint64_t channelId) const; - TS3Functions* ts3Functions_ = nullptr; - uint64_t serverConnectionHandlerId_ = 0; - std::atomic initialized_{false}; - std::atomic audioDeviceRegistered_{false}; - std::atomic audioDeviceOpen_{false}; + // Fetch server groups for a client (returns future that completes when + // groups are received) + std::future> fetchServerGroups(uint64_t clientId); - std::vector eventCallbacks_; + // Get cached server groups (or empty if not cached) + std::vector getCachedServerGroups(uint64_t clientId); + + TS3Functions* ts3Functions_ = nullptr; + uint64_t serverConnectionHandlerId_ = 0; + std::atomic initialized_{false}; + std::atomic audioDeviceRegistered_{false}; + std::atomic audioDeviceOpen_{false}; + + std::vector eventCallbacks_; mutable std::mutex eventMutex_; // Audio data queue - std::queue> audioQueue_; - std::mutex audioMutex_; - std::condition_variable audioCv_; + std::queue> audioQueue_; + std::mutex audioMutex_; + std::condition_variable audioCv_; std::atomic stopAudioThread_{false}; std::jthread audioThread_; - // Connection info - Api::ServerConfig currentServerConfig_; + // Server groups cache + mutable std::mutex serverGroupsMutex_; + std::map serverGroupsCache_; + std::map>> + pendingServerGroupRequests_; + + // Connection info + Api::ServerConfig currentServerConfig_; }; } // namespace Echoion::Plugin diff --git a/src/CoreLoader.cpp b/src/CoreLoader.cpp index 41c40b0..997bde7 100644 --- a/src/CoreLoader.cpp +++ b/src/CoreLoader.cpp @@ -47,20 +47,116 @@ void CoreLoader::onCoreFileChanged() { return; } - ECHOION_LOG_INFO("Core file changed, triggering hot reload..."); + ECHOION_LOG_INFO("Core file changed, scheduling hot reload after current track..."); // Small delay to ensure file write is complete std::this_thread::sleep_for(std::chrono::milliseconds(500)); - auto result = hotReload(currentLibraryPath_); - if (!result) { - ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message)); + // Check if playback is active - if so, defer reload + if (isPlaybackActive()) { + std::string currentTrackId; + { + std::lock_guard lock(pendingReloadMutex_); + hasPendingReload_ = true; + pendingReloadPath_ = currentLibraryPath_; + + // Capture current track ID + auto state = core_->getPlaybackState(); + if (state && state->currentTrack.has_value()) { + pendingTrackId_ = state->currentTrack->track.id; + currentTrackId = pendingTrackId_; + } + } + + ECHOION_LOG_INFO(std::format("Playback active (track: {}), deferring reload until track finishes", currentTrackId)); + + // Start background thread to wait for track end + if (deferredReloadThread_.joinable()) { + deferredReloadThread_.join(); + } + deferredReloadThread_ = std::thread([this, currentTrackId]() { + waitForTrackAndReload(pendingReloadPath_, currentTrackId); + }); } else { - ECHOION_LOG_INFO("Auto hot-reload completed successfully"); + // No playback, reload immediately + auto result = hotReload(currentLibraryPath_); + if (!result) { + ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message)); + } else { + ECHOION_LOG_INFO("Auto hot-reload completed successfully"); + // Notify Plugin to re-register callbacks + if (hotReloadCallback_) { + hotReloadCallback_(); + } + } + } +} + +bool CoreLoader::isPlaybackActive() const { + if (!core_) { + return false; + } + + auto state = core_->getPlaybackState(); + if (!state) { + return false; + } + + // Check if currently playing a track + return state->isPlaying && state->currentTrack.has_value(); +} + +bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const { + if (!core_ || trackId.empty()) { + return false; + } + + auto state = core_->getPlaybackState(); + if (!state || !state->currentTrack.has_value()) { + return false; + } + + return state->currentTrack->track.id == trackId; +} + +void CoreLoader::waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId) { + ECHOION_LOG_INFO(std::format("Waiting for track {} to finish before reload...", trackId)); + + // Poll every 500ms to check if the specific track finished + // (playback may continue with next track, but we only care about THIS track) + while (isSameTrackPlaying(trackId)) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + + ECHOION_LOG_INFO("Track finished, starting hot reload"); + + // Clear pending flag + { + std::lock_guard lock(pendingReloadMutex_); + hasPendingReload_ = false; + pendingTrackId_.clear(); + } + + // Now do the reload + auto result = hotReload(targetPath); + if (!result) { + ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}", result.error().message)); + } else { + ECHOION_LOG_INFO("Deferred hot-reload completed successfully"); + // Notify Plugin to re-register callbacks + if (hotReloadCallback_) { + hotReloadCallback_(); + } } } CoreLoader::~CoreLoader() { + // Stop any deferred reload thread + if (deferredReloadThread_.joinable()) { + // We can't really stop it gracefully, but we can detach it + // to avoid hanging on shutdown + deferredReloadThread_.detach(); + } unload(); cleanupTempFiles(); } diff --git a/src/Plugin.cpp b/src/Plugin.cpp index 15e972c..fc0a0da 100644 --- a/src/Plugin.cpp +++ b/src/Plugin.cpp @@ -103,6 +103,10 @@ TS3_PLUGIN_API void ts3plugin_registerPluginID(const char *id) std::cout << std::format("[Echoion] Plugin ID: {}", pluginID) << std::endl; } +// Forward declarations for helper functions +static bool reregisterPluginInterface(); +static bool reloadCoreWithInterface(); + static bool ensureCoreLoaded() { if (g_coreLoader && g_coreLoader->isLoaded()) { return true; @@ -111,6 +115,11 @@ static bool ensureCoreLoaded() { try { if (!g_coreLoader) { g_coreLoader = std::make_unique(); + // Set up callback for auto-reload to re-register plugin interface + g_coreLoader->setHotReloadCallback([]() { + std::cout << "[Echoion] Auto-reload callback triggered, re-registering interface..." << std::endl; + reregisterPluginInterface(); + }); } // Pass config path to CoreLoader (Core will load config internally) @@ -149,24 +158,25 @@ void deferredInitialization() { g_deferredInitRunning = true; // Wait 3 seconds for TeamSpeak GUI to fully initialize - std::this_thread::sleep_for(std::chrono::seconds(3)); - - // Wait for TS functions to be set (up to 2 more seconds) - int waitCount = 0; - while (!g_ts3FunctionsReady.load() && waitCount < 20) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - waitCount++; - } - - if (!g_ts3FunctionsReady.load()) { - std::cerr << "[Echoion] TS3 functions not ready, aborting init" << std::endl; - g_deferredInitRunning = false; + std::this_thread::sleep_for(std::chrono::seconds(30)); + + // Wait for TS functions to be set (up to 2 more seconds) + int waitCount = 0; + while (!g_ts3FunctionsReady.load() && waitCount < 20) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + waitCount++; + } + + if (!g_ts3FunctionsReady.load()) { + std::cerr << "[Echoion] TS3 functions not ready, aborting init" + << std::endl; + g_deferredInitRunning = false; return; - } - - std::cout << "[Echoion] Starting deferred initialization..." << std::endl; - - try { + } + + std::cout << "[Echoion] Starting deferred initialization..." << std::endl; + + try { // Create plugin interface g_pluginInterface = std::make_shared(); @@ -297,16 +307,74 @@ TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent(uint64 serverConnectionHa } } +// Helper to re-register plugin interface after hot reload (Core already reloaded) +static bool reregisterPluginInterface() { + if (!g_coreLoader) { + std::cerr << "[Echoion] Cannot re-register: CoreLoader not available" << std::endl; + return false; + } + + std::cout << "[Echoion] Re-registering plugin interface after hot reload..." << std::endl; + + // Get the new core instance + auto core = g_coreLoader->getCore(); + if (!core) { + std::cerr << "[Echoion] ERROR: Core is null!" << std::endl; + return false; + } + + if (!g_pluginInterface) { + std::cerr << "[Echoion] ERROR: PluginInterface is null!" << std::endl; + return false; + } + + std::cout << std::format("[Echoion] New Core pointer: {}", reinterpret_cast(core.get())) << std::endl; + + // Set the plugin interface first (before registering callbacks) + core->setPluginInterface(g_pluginInterface); + std::cout << "[Echoion] Plugin interface set on new Core" << std::endl; + + // Clear old callbacks (they point to destroyed Core) and register new one + std::cout << "[Echoion] About to clear callbacks..." << std::endl; + g_pluginInterface->clearEventCallbacks(); + std::cout << "[Echoion] Old event callbacks cleared" << std::endl; + + std::cout << "[Echoion] About to register new callback..." << std::endl; + g_pluginInterface->registerEventCallback([core](const Api::PluginEvent& event) { + core->onPluginEvent(event); + }); + std::cout << "[Echoion] New event callback registered" << std::endl; + + std::cout << "[Echoion] Re-registration complete - bot should respond to commands" << std::endl; + return true; +} + +// Helper to reload core and re-register plugin interface (for manual reload) +static bool reloadCoreWithInterface() { + if (!g_coreLoader) { + std::cerr << "[Echoion] Cannot reload: CoreLoader not available" << std::endl; + return false; + } + + std::cout << "[Echoion] Starting hot reload (Plugin)..." << std::endl; + + auto result = g_coreLoader->hotReload(getCorePath()); + if (!result) { + std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl; + return false; + } + + // Now re-register the plugin interface + return reregisterPluginInterface(); +} + // Handle plugin commands from TS3 TS3_PLUGIN_API void ts3plugin_onPluginCommandEvent(uint64 serverConnectionHandlerId, const char* pluginName, const char* command) { if (std::strcmp(command, "reload") == 0) { if (ensureCoreLoaded()) { - auto result = g_coreLoader->hotReload(getCorePath()); - if (!result) { - std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl; - } + reloadCoreWithInterface(); } } } @@ -339,9 +407,7 @@ TS3_PLUGIN_API void ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId, core->stop(); break; case 4: // Hot Reload Core - if (auto result = g_coreLoader->hotReload(getCorePath()); !result) { - std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl; - } + reloadCoreWithInterface(); break; case 5: // Connect/Disconnect if (g_pluginInterface) { diff --git a/src/PluginInterface.cpp b/src/PluginInterface.cpp index eb78c8e..ce2b474 100644 --- a/src/PluginInterface.cpp +++ b/src/PluginInterface.cpp @@ -1,8 +1,9 @@ -#include "echoion/plugin/PluginInterface.hpp" #include "echoion/api/LoggerInterface.hpp" +#include "echoion/plugin/PluginInterface.hpp" #include "teamspeak/public_definitions.h" -#include +#include "teamspeak/public_rare_definitions.h" #include +#include #include namespace Echoion::Plugin { @@ -22,12 +23,9 @@ Api::Result PluginInterface::initialize(TS3Functions* ts3Functions) { ts3Functions_ = ts3Functions; - // Note: Audio device registration is now deferred to allow TeamSpeak GUI to initialize - // It will be called from Plugin::deferredInitialization() after a 3-second delay - - // Start audio processing thread (will wait until device is registered) - stopAudioThread_ = false; - audioThread_ = std::jthread([this] { + // Start audio processing thread (will wait until device is registered) + stopAudioThread_ = false; + audioThread_ = std::jthread([this] { while (!stopAudioThread_) { std::unique_lock lock(audioMutex_); audioCv_.wait(lock, [this] { return !audioQueue_.empty() || stopAudioThread_; }); @@ -112,74 +110,114 @@ Api::Result PluginInterface::shutdown() { return {}; } -Api::Result> PluginInterface::getClients() const { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } +Api::Result> PluginInterface::getClients() +{ + if (!initialized_ || !ts3Functions_) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } - std::vector clients; - anyID* clientList = nullptr; + std::vector clients; + anyID* clientList = nullptr; - unsigned int error = ts3Functions_->getClientList(serverConnectionHandlerId_, &clientList); - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to get client list: {}", error))); - } + unsigned int error = + ts3Functions_->getClientList(serverConnectionHandlerId_, &clientList); + if (error != ERROR_ok) { + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + std::format("Failed to get client list: {}", error))); + } - if (clientList) { - for (int i = 0; clientList[i] != 0; ++i) { - Api::ClientInfo info; + if (clientList) { + for (int i = 0; clientList[i] != 0; ++i) { + Api::ClientInfo info; info.id = clientList[i]; - - char* name = nullptr; - if (ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_, - clientList[i], CLIENT_NICKNAME, &name) == ERROR_ok && name) { - info.nickname = name; - ts3Functions_->freeMemory(name); - } - uint64 channelId = 0; - if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_, - clientList[i], &channelId) == ERROR_ok) { - info.channelId = channelId; - } + // Get nickname + char* name = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, clientList[i], CLIENT_NICKNAME, + &name) == ERROR_ok && + name) { + info.nickname = name; + ts3Functions_->freeMemory(name); + } - clients.push_back(info); - } - ts3Functions_->freeMemory(clientList); - } + // Get unique identifier (UID) + char* uid = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, clientList[i], + CLIENT_UNIQUE_IDENTIFIER, &uid) == ERROR_ok && + uid) { + info.uniqueIdentifier = uid; + ts3Functions_->freeMemory(uid); + } - return clients; + // Get channel ID + uint64 channelId = 0; + if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_, + clientList[i], + &channelId) == ERROR_ok) { + info.channelId = channelId; + } + + // Get cached server groups + info.serverGroups = getCachedServerGroups(clientList[i]); + + clients.push_back(info); + } + ts3Functions_->freeMemory(clientList); + } + + return clients; } -Api::Result> PluginInterface::getClient(uint64_t clientId) const { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } +Api::Result> + PluginInterface::getClient(uint64_t clientId) +{ + if (!initialized_ || !ts3Functions_) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } - Api::ClientInfo info; - info.id = clientId; + Api::ClientInfo info; + info.id = clientId; - char* name = nullptr; - if (ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_, - static_cast(clientId), CLIENT_NICKNAME, &name) != ERROR_ok) { - return std::nullopt; - } + // Get client nickname + char* name = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, static_cast(clientId), + CLIENT_NICKNAME, &name) != ERROR_ok) { + return std::nullopt; + } - if (name) { - info.nickname = name; - ts3Functions_->freeMemory(name); - } + if (name) { + info.nickname = name; + ts3Functions_->freeMemory(name); + } - uint64 channelId = 0; - if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_, - static_cast(clientId), &channelId) == ERROR_ok) { - info.channelId = channelId; - } + // Get client unique identifier (UID) + char* uid = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, static_cast(clientId), + CLIENT_UNIQUE_IDENTIFIER, &uid) == ERROR_ok && + uid) { + info.uniqueIdentifier = uid; + ts3Functions_->freeMemory(uid); + } - return info; + // Get client channel ID + uint64 channelId = 0; + if (ts3Functions_->getChannelOfClient(serverConnectionHandlerId_, + static_cast(clientId), + &channelId) == ERROR_ok) { + info.channelId = channelId; + } + + // Get cached server groups + info.serverGroups = getCachedServerGroups(clientId); + + return info; } Api::Result PluginInterface::moveClient(uint64_t clientId, uint64_t channelId) { @@ -331,40 +369,59 @@ Api::Result PluginInterface::sendServerMessage(const std::string& message) return {}; } -Api::Result PluginInterface::sendAudioData(const std::span& data) { - static int callCount = 0; - callCount++; - - if (!initialized_ || !ts3Functions_) { - if (callCount <= 10) { - ECHOION_LOG_ERROR(std::format("sendAudioData {}: not initialized", callCount)); - } - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } +Api::Result + PluginInterface::sendAudioData(const std::span& data) +{ + static int callCount = 0; + static int nonZeroTotal = 0; + callCount++; - if (!audioDeviceOpen_) { - if (callCount <= 10) { - ECHOION_LOG_ERROR(std::format("sendAudioData {}: audio device not open", callCount)); - } - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Audio device not open")); - } + // Debug: Check audio data on first few calls + if (callCount <= 5) { + int nonZero = 0; + int maxSample = 0; + for (size_t i = 0; i < std::min(size_t(100), data.size()); ++i) { + if (data[i] != 0) { + nonZero++; + } + maxSample = + std::max(maxSample, std::abs(static_cast(data[i]))); + } + nonZeroTotal += nonZero; + ECHOION_LOG_DEBUG(std::format( + "sendAudioData {}: {} samples, nonZero={}/100, maxSample={}, " + "queueSize={}", + callCount, data.size(), nonZero, maxSample, audioQueue_.size())); + } - // Convert bytes to int16 samples - size_t sampleCount = data.size() / sizeof(int16_t); - std::vector samples(sampleCount); - std::memcpy(samples.data(), data.data(), data.size()); + if (!initialized_ || !ts3Functions_) { + if (callCount <= 10) { + ECHOION_LOG_ERROR( + std::format("sendAudioData {}: not initialized", callCount)); + } + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } - submitAudioData(samples); + if (!audioDeviceOpen_) { + if (callCount <= 10) { + ECHOION_LOG_ERROR(std::format( + "sendAudioData {}: audio device not open", callCount)); + } + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "Audio device not open")); + } - return {}; + submitAudioData(data); + + return {}; } -void PluginInterface::submitAudioData(const std::span samples) { - std::lock_guard lock(audioMutex_); - audioQueue_.push(std::vector(samples.begin(), samples.end())); - audioCv_.notify_one(); +void PluginInterface::submitAudioData(const std::span samples) +{ + std::lock_guard lock(audioMutex_); + audioQueue_.push(std::vector(samples.begin(), samples.end())); + audioCv_.notify_one(); } Api::Result PluginInterface::setWhisperList(const std::vector& clientIds) { @@ -400,6 +457,7 @@ Api::Result PluginInterface::setWhisperList(const std::vector& c void PluginInterface::registerEventCallback(const Api::EventCallback& callback) { std::lock_guard lock(eventMutex_); eventCallbacks_.push_back(callback); + ECHOION_LOG_INFO(std::format("Event callback registered, total callbacks: {}", eventCallbacks_.size())); } void PluginInterface::unregisterEventCallback(const Api::EventCallback& callback) { @@ -409,6 +467,12 @@ void PluginInterface::unregisterEventCallback(const Api::EventCallback& callback }); } +void PluginInterface::clearEventCallbacks() { + std::lock_guard lock(eventMutex_); + ECHOION_LOG_INFO(std::format("Clearing {} event callbacks", eventCallbacks_.size())); + eventCallbacks_.clear(); +} + void PluginInterface::onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId) { if (serverConnectionHandlerId != serverConnectionHandlerId_) return; @@ -702,13 +766,22 @@ Api::Result PluginInterface::openAudioDevice() { ts3Functions_->getErrorMessage(err, &msg); std::string errStr = msg; ts3Functions_->freeMemory(msg); - ECHOION_LOG_WARNING(std::format("Failed to open capture device: {}", errStr)); - // Continue without capture - bot only needs playback - } + ECHOION_LOG_WARNING( + std::format("Failed to open capture device: {}", errStr)); + } - audioDeviceOpen_ = true; + audioDeviceOpen_ = true; ECHOION_LOG_INFO("Audio device opened successfully"); - return {}; + + // Configure audio profile for optimal music playback + auto profileResult = configureAudioProfile(); + if (!profileResult) { + ECHOION_LOG_WARNING(std::format("Failed to configure audio profile: {}", + profileResult.error().message)); + // Continue anyway - audio will still work with default settings + } + + return {}; } Api::Result PluginInterface::closeAudioDevice() { @@ -749,11 +822,18 @@ uint64_t PluginInterface::getServerConnectionHandlerId() const { void PluginInterface::broadcastEvent(const Api::PluginEvent& event) { std::lock_guard lock(eventMutex_); - for (const auto& callback : eventCallbacks_) { + if (eventCallbacks_.empty()) { + ECHOION_LOG_WARNING("No event callbacks registered, event will be dropped!"); + return; + } + ECHOION_LOG_DEBUG(std::format("Broadcasting event to {} callbacks", eventCallbacks_.size())); + for (size_t i = 0; i < eventCallbacks_.size(); ++i) { try { - callback(event); + ECHOION_LOG_DEBUG(std::format("Calling callback {}...", i)); + eventCallbacks_[i](event); + ECHOION_LOG_DEBUG(std::format("Callback {} completed", i)); } catch (const std::exception& e) { - ECHOION_LOG_ERROR(std::format("Event callback error: {}", e.what())); + ECHOION_LOG_ERROR(std::format("Event callback {} error: {}", i, e.what())); } } } @@ -784,4 +864,206 @@ std::string PluginInterface::getChannelName(uint64_t channelId) const { return "Unknown"; } +std::vector PluginInterface::getCachedServerGroups(uint64_t clientId) +{ + if (!ts3Functions_) { + return {}; + } + + std::lock_guard lock(serverGroupsMutex_); + + // Check cache first + auto it = serverGroupsCache_.find(clientId); + if (it != serverGroupsCache_.end()) { + // Check if cache is still valid (5 minutes) + auto now = std::chrono::steady_clock::now(); + auto age = std::chrono::duration_cast( + now - it->second.timestamp); + if (age.count() < 5) { + return it->second.groups; + } + } + + // Fetch server groups directly using CLIENT_SERVERGROUPS + // This returns a comma-separated string of group IDs + char* groupsStr = nullptr; + unsigned int error = + ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_, + static_cast(clientId), + CLIENT_SERVERGROUPS, + &groupsStr); + + if (error != ERROR_ok || !groupsStr) { + return {}; + } + + // Parse comma-separated group IDs + std::vector groups; + std::string groupsString(groupsStr); + ts3Functions_->freeMemory(groupsStr); + + size_t start = 0; + size_t end = groupsString.find(','); + while (end != std::string::npos) { + try { + uint64_t groupId = + std::stoull(groupsString.substr(start, end - start)); + groups.push_back(groupId); + } catch (...) { + // Ignore parse errors + } + start = end + 1; + end = groupsString.find(',', start); + } + // Parse last group + if (start < groupsString.size()) { + try { + uint64_t groupId = std::stoull(groupsString.substr(start)); + groups.push_back(groupId); + } catch (...) { + // Ignore parse errors + } + } + + // Cache the result + auto& entry = serverGroupsCache_[clientId]; + entry.groups = groups; + entry.timestamp = std::chrono::steady_clock::now(); + + return groups; +} + +void PluginInterface::onServerGroupByClientID( + uint64_t serverConnectionHandlerId, uint64_t clientDatabaseId, + const char* groupName, uint64_t serverGroupId, uint64_t clientId) +{ + + if (serverConnectionHandlerId != serverConnectionHandlerId_) { + return; + } + + // This callback is not used when fetching via CLIENT_SERVERGROUPS + // It's kept for compatibility with the async API if needed later +} + +Api::Result PluginInterface::configureAudioProfile() +{ + if (!ts3Functions_ || serverConnectionHandlerId_ == 0) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "Not connected to server")); + } + + ECHOION_LOG_INFO("Configuring audio profile for music bot..."); + + // Configure preprocessor settings (noise reduction, echo cancellation, + // etc.) These settings optimize the audio for music playback rather than + // voice + + // Disable denoiser (noise reduction) - we want to keep the full audio + // signal + unsigned int error = ts3Functions_->setPreProcessorConfigValue( + serverConnectionHandlerId_, "denoise", "false"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Failed to disable denoiser: {}", error)); + } + + // Disable AGC (Automatic Gain Control) - we handle volume ourselves + error = ts3Functions_->setPreProcessorConfigValue( + serverConnectionHandlerId_, "agc", "false"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING(std::format("Failed to disable AGC: {}", error)); + } + + // Disable VAD (Voice Activity Detection) - we use continuous transmission + error = ts3Functions_->setPreProcessorConfigValue( + serverConnectionHandlerId_, "vad", "false"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING(std::format("Failed to disable VAD: {}", error)); + } + + // Disable echo cancellation + error = ts3Functions_->setPreProcessorConfigValue( + serverConnectionHandlerId_, "echocancel", "false"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Failed to disable echo cancellation: {}", error)); + } + + // Disable echo reduction + error = ts3Functions_->setPreProcessorConfigValue( + serverConnectionHandlerId_, "echo_reduction", "false"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Failed to disable echo reduction: {}", error)); + } + + // Configure playback settings + // Disable typing attenuation (don't lower volume when typing) + error = ts3Functions_->setPlaybackConfigValue(serverConnectionHandlerId_, + "typing_attenuation", "0"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Failed to disable typing attenuation: {}", error)); + } + + // Enable continuous transmission (no voice activation) + // This is done by setting input deactivated to 0 (active) + error = ts3Functions_->setClientSelfVariableAsInt( + serverConnectionHandlerId_, CLIENT_INPUT_DEACTIVATED, 0); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Failed to enable continuous transmission: {}", error)); + } + const char* returnCode = nullptr; + // Flush the changes + ts3Functions_->flushClientSelfUpdates(serverConnectionHandlerId_, + returnCode); + + ECHOION_LOG_INFO("Audio profile configured successfully"); + return {}; +} + +Api::Result PluginInterface::checkAndHandleFirstRun() +{ + if (!ts3Functions_) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "TS3 functions not available")); + } + + ECHOION_LOG_INFO("Checking for first-run setup..."); + + // Check if we have a valid client identity + // TeamSpeak requires accepting TOS on first run, which is handled by the + // client We can detect if the client is properly configured by checking the + // identity + + char* identity = nullptr; + unsigned int error = ts3Functions_->getClientLibVersion(&identity); + if (error != ERROR_ok || !identity) { + ECHOION_LOG_WARNING( + "TeamSpeak client library not properly initialized"); + ECHOION_LOG_INFO( + "Please ensure TeamSpeak client is properly configured:"); + ECHOION_LOG_INFO(" 1. Accept the Terms of Service"); + ECHOION_LOG_INFO(" 2. Create/obtain your identity"); + ECHOION_LOG_INFO(" 3. Complete the initial setup wizard"); + + if (identity) { + ts3Functions_->freeMemory(identity); + } + return std::unexpected( + Api::Error(Api::ErrorCode::NotInitialized, + "TeamSpeak client not properly initialized. Please " + "complete first-run setup.")); + } + + if (identity) { + ts3Functions_->freeMemory(identity); + } + + ECHOION_LOG_INFO("TeamSpeak client is properly initialized"); + return {}; +} + } // namespace Echoion::Plugin