From 05c9f8bc6c8b528c234182de78e1b2bc9e9827fc Mon Sep 17 00:00:00 2001 From: Aleksey Selihov Date: Mon, 22 Jun 2026 15:53:30 +0300 Subject: [PATCH] Bump CMake minimum to 4.0 for VoidLibrary toolchain --- CMakeLists.txt | 79 +- include/echoion/plugin/CoreLoader.hpp | 147 +- include/echoion/plugin/FileWatcher.hpp | 97 +- include/echoion/plugin/PluginInterface.hpp | 259 ++- include/teamspeak/public_definitions.h | 20 +- include/teamspeak/public_rare_definitions.h | 4 +- include/ts3_functions.h | 2 +- src/CoreLoader.cpp | 812 +++---- src/FileWatcher.cpp | 154 +- src/Plugin.cpp | 914 ++++---- src/PluginInterface.cpp | 2161 ++++++++++--------- 11 files changed, 2524 insertions(+), 2125 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 293c64d..14cc008 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.28) +cmake_minimum_required(VERSION 4.0.0) project(EchoionPlugin VERSION 1.0.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 26) @@ -13,20 +13,32 @@ CPMAddPackage( OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON" ) -add_library(EchoionPlugin SHARED - src/PluginInterface.cpp - src/CoreLoader.cpp - src/Plugin.cpp - src/FileWatcher.cpp +file(GLOB_RECURSE PLUGIN_SOURCES + CONFIGURE_DEPENDS + "src/**.cpp" ) +add_library(EchoionPlugin SHARED ${PLUGIN_SOURCES}) add_library(Echoion::Plugin ALIAS EchoionPlugin) target_include_directories(EchoionPlugin PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ) - -target_link_libraries(EchoionPlugin PRIVATE Echoion::Api) +target_compile_definitions(EchoionPlugin PUBLIC PLUGIN=1) +# Plugin only needs minimal API (NO rebuild when Core changes): +# - ApiBase (Types.hpp - Error, Result, LogLevel) +# - ApiPlugin (PluginTypes.hpp - PluginEvent, ClientInfo, ServerConfig) +# - ApiOpaque (OpaqueHandle for type-safe void*) +# - ApiPluginInterface (IPluginInterface to implement) +# - ApiCoreInterface (ICoreInterface to call Core - decoupled) +target_link_libraries(EchoionPlugin PRIVATE + Echoion::ApiBase + Echoion::ApiPlugin + Echoion::ApiOpaque + Echoion::ApiPluginInterface + Echoion::ApiLogger + Echoion::ApiCoreInterface +) find_package(dylib CONFIG REQUIRED) target_link_libraries(EchoionPlugin PRIVATE dylib) @@ -34,15 +46,11 @@ target_link_libraries(EchoionPlugin PRIVATE dylib) find_package(Threads REQUIRED) target_link_libraries(EchoionPlugin PRIVATE Threads::Threads) -# Find glaze for JSON parsing -find_package(glaze REQUIRED) -target_link_libraries(EchoionPlugin PRIVATE glaze::glaze) - if(MSVC) target_compile_options(EchoionPlugin PRIVATE /W4 /WX-) target_compile_definitions(EchoionPlugin PRIVATE _CRT_SECURE_NO_WARNINGS) else() - target_compile_options(EchoionPlugin PRIVATE -Wall -Wextra -Wpedantic -fPIC) + target_compile_options(EchoionPlugin PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow -fPIC) endif() set_target_properties(EchoionPlugin PROPERTIES @@ -53,19 +61,46 @@ set_target_properties(EchoionPlugin PROPERTIES POSITION_INDEPENDENT_CODE ON ) -# Ensure dylib is compiled with -fPIC if(TARGET dylib) set_target_properties(dylib PROPERTIES POSITION_INDEPENDENT_CODE ON) endif() -# PackageProject.cmake configuration -packageProject( - NAME EchoionPlugin +# Export Plugin +target_include_directories(EchoionPlugin PUBLIC + $ + $ +) + +install(TARGETS EchoionPlugin + EXPORT EchoionPluginTargets + RUNTIME DESTINATION plugins + LIBRARY DESTINATION plugins + INCLUDES DESTINATION include +) + +install(EXPORT EchoionPluginTargets + FILE EchoionPluginTargets.cmake + NAMESPACE Echoion:: + DESTINATION lib/cmake/EchoionPlugin +) + +# Package config +include(CMakePackageConfigHelpers) +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfigVersion.cmake" 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 +) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfig.cmake" +"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionPluginTargets.cmake\") +include(CMakeFindDependencyMacro) +find_dependency(EchoionApi) +find_dependency(dylib) +") + +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfigVersion.cmake" + DESTINATION lib/cmake/EchoionPlugin ) diff --git a/include/echoion/plugin/CoreLoader.hpp b/include/echoion/plugin/CoreLoader.hpp index 0d65c02..1804146 100644 --- a/include/echoion/plugin/CoreLoader.hpp +++ b/include/echoion/plugin/CoreLoader.hpp @@ -1,78 +1,93 @@ #pragma once - -#include -#include #include "FileWatcher.hpp" -#include "echoion/api/ConfigTypes.hpp" +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include -#include +#include -namespace Echoion::Plugin { +namespace Echoion::Plugin +{ -class CoreLoader { -public: - CoreLoader(); - ~CoreLoader(); + class CoreLoader + { + public: - Api::Result load(const std::filesystem::path& libraryPath); - Api::Result unload(); - Api::Result hotReload(const std::filesystem::path& newLibraryPath); - [[nodiscard]] bool isLoaded() const noexcept; - [[nodiscard]] Api::CoreInterfacePtr getCore() const; - void setConfigPath(const std::filesystem::path& configPath); - [[nodiscard]] std::filesystem::path getConfigPath() const; - [[nodiscard]] bool isHotReloading() const noexcept; - - // Automatic hot reload - 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); } + CoreLoader(); + ~CoreLoader(); -private: - Api::Result loadLibraryInternal(const std::filesystem::path& path); - Api::Result unloadLibraryInternal(); - [[nodiscard]] Api::HotReloadState saveStateInternal(); - [[nodiscard]] Api::Result restoreStateInternal(const Api::HotReloadState& state); - [[nodiscard]] std::filesystem::path getTempLibraryPath(const std::filesystem::path& original) const; - void cleanupTempFiles(); + Api::Result load(const std::filesystem::path& libraryPath); + Api::Result unload(); + Api::Result + hotReload(const std::filesystem::path& newLibraryPath); + [[nodiscard]] bool isLoaded() const noexcept; + [[nodiscard]] Api::CoreInterfacePtr getCore() const; + void setConfigPath(const std::filesystem::path& configPath); + [[nodiscard]] std::filesystem::path getConfigPath() const; + [[nodiscard]] bool isHotReloading() const noexcept; - std::unique_ptr library_; - Api::CoreInterfacePtr core_; - std::filesystem::path currentLibraryPath_; - std::filesystem::path tempLibraryPath_; - std::filesystem::path configPath_; - mutable std::mutex mutex_; - std::atomic loaded_{false}; - std::atomic hotReloading_{false}; - - // Auto reload - 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; -}; + // Automatic hot reload + 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); + Api::Result unloadLibraryInternal(); + [[nodiscard]] Api::SerializedState saveStateInternal(); + [[nodiscard]] Api::Result + restoreStateInternal(const Api::SerializedState& state); + [[nodiscard]] std::filesystem::path + getTempLibraryPath(const std::filesystem::path& original) const; + void cleanupTempFiles(); + + std::unique_ptr library_; + Api::CoreInterfacePtr core_; + std::filesystem::path currentLibraryPath_; + std::filesystem::path tempLibraryPath_; + std::filesystem::path configPath_; + mutable std::mutex mutex_; + std::atomic loaded_{false}; + std::atomic hotReloading_{false}; + + // Auto reload + 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/FileWatcher.hpp b/include/echoion/plugin/FileWatcher.hpp index 6331f1c..ba0968b 100644 --- a/include/echoion/plugin/FileWatcher.hpp +++ b/include/echoion/plugin/FileWatcher.hpp @@ -1,62 +1,65 @@ #pragma once -#include -#include -#include #include -#include #include +#include +#include +#include +#include -namespace Echoion::Plugin { +namespace Echoion::Plugin +{ -/** - * @brief Simple file watcher that monitors a file for changes - * and triggers a callback when the file is modified. - */ -class FileWatcher { -public: - using ChangeCallback = std::function; + /** + * @brief Simple file watcher that monitors a file for changes + * and triggers a callback when the file is modified. + */ + class FileWatcher + { + public: - FileWatcher(); - ~FileWatcher(); + using ChangeCallback = std::function; - // Disable copy - FileWatcher(const FileWatcher&) = delete; - FileWatcher& operator=(const FileWatcher&) = delete; + FileWatcher(); + ~FileWatcher(); - /** - * @brief Start watching a file for changes - * @param filePath Path to the file to watch - * @param callback Function to call when file changes - * @param intervalMs Polling interval in milliseconds - */ - void startWatching( - const std::filesystem::path& filePath, - ChangeCallback callback, - std::chrono::milliseconds intervalMs = std::chrono::milliseconds(1000) - ); + // Disable copy + FileWatcher(const FileWatcher&) = delete; + FileWatcher& operator=(const FileWatcher&) = delete; - /** - * @brief Stop watching - */ - void stopWatching(); + /** + * @brief Start watching a file for changes + * @param filePath Path to the file to watch + * @param callback Function to call when file changes + * @param intervalMs Polling interval in milliseconds + */ + void startWatching(const std::filesystem::path& filePath, + ChangeCallback callback, + std::chrono::milliseconds intervalMs = + std::chrono::milliseconds(1000)); - [[nodiscard]] bool isWatching() const noexcept; + /** + * @brief Stop watching + */ + void stopWatching(); -private: - void watchLoop(); + [[nodiscard]] bool isWatching() const noexcept; - std::filesystem::path watchedPath_; - ChangeCallback callback_; - std::chrono::milliseconds intervalMs_{1000}; - std::atomic watching_{false}; - std::atomic stopRequested_{false}; - std::thread watchThread_; - std::mutex mutex_; - - // Store last modification time - std::filesystem::file_time_type lastWriteTime_; - std::uintmax_t lastFileSize_ = 0; -}; + private: + + void watchLoop(); + + std::filesystem::path watchedPath_; + ChangeCallback callback_; + std::chrono::milliseconds intervalMs_{1000}; + std::atomic watching_{false}; + std::atomic stopRequested_{false}; + std::thread watchThread_; + std::mutex mutex_; + + // Store last modification time + std::filesystem::file_time_type lastWriteTime_; + std::uint64_t lastFileSize_ = 0; + }; } // namespace Echoion::Plugin diff --git a/include/echoion/plugin/PluginInterface.hpp b/include/echoion/plugin/PluginInterface.hpp index df584b7..2f7688d 100644 --- a/include/echoion/plugin/PluginInterface.hpp +++ b/include/echoion/plugin/PluginInterface.hpp @@ -1,9 +1,10 @@ #pragma once - +#include +#include +#include #include #include #include -#include #include #include #include @@ -14,144 +15,170 @@ // TeamSpeak SDK headers #include "ts3_functions.h" -namespace Echoion::Plugin { +namespace Echoion::Plugin +{ -// Audio device configuration -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; // 192kHz for high quality audio (CODEC_OPUS_MUSIC) - static constexpr int CHANNELS = 2; - static constexpr int SAMPLE_SIZE = sizeof(int16_t); -}; + // Audio device configuration + 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; // 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; -}; + // 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 -class PluginInterface : public Api::IPluginInterface { -public: - PluginInterface(); - ~PluginInterface() override; + // Plugin implementation of IPluginInterface for the Core to use + class PluginInterface : public Api::IPluginInterface + { + public: - // Initialize with TeamSpeak functions - Api::Result initialize(TS3Functions* ts3Functions); + PluginInterface(); + ~PluginInterface() override; - // IPluginInterface implementation - Api::Result initialize() override; - Api::Result shutdown() override; + // Initialize with TeamSpeak functions + Api::Result initialize(TS3Functions* ts3Functions); - // Client operations - [[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; + // IPluginInterface implementation + Api::Result initialize() override; + Api::Result shutdown() override; - // Channel operations - [[nodiscard]] Api::Result> - getChannels() const override; - [[nodiscard]] Api::Result> getChannel(uint64_t channelId) const override; + // Client operations + [[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; - // Messaging - Api::Result sendTextMessage(uint64_t targetId, const std::string& message) override; - Api::Result sendChannelMessage(uint64_t channelId, const std::string& message) override; - Api::Result sendServerMessage(const std::string& message) override; + // Channel operations + [[nodiscard]] Api::Result> + getChannels() const override; + [[nodiscard]] Api::Result> + getChannel(uint64_t channelId) const override; - // Audio - Api::Result - sendAudioData(const std::span& data) override; - Api::Result - setWhisperList(const std::vector& clientIds) override; + // Messaging + Api::Result + sendTextMessage(uint64_t targetId, + const std::string& message) override; + Api::Result + sendChannelMessage(uint64_t channelId, + const std::string& message) override; + Api::Result + sendServerMessage(const std::string& message) override; - // Event subscription - void registerEventCallback(const Api::EventCallback& callback) override; - void unregisterEventCallback(const Api::EventCallback& callback) override; - void clearEventCallbacks(); + // Audio + Api::Result + sendAudioData(const std::span& data) override; + Api::Result + setWhisperList(const std::vector& clientIds) override; - // TeamSpeak event handlers (called by TeamSpeak SDK) - void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId); - void onClientDisconnected(uint64_t serverConnectionHandlerId, uint64_t clientId); - void onClientMoved(uint64_t serverConnectionHandlerId, uint64_t clientId, uint64_t newChannelId); - void onTextMessageReceived(uint64_t serverConnectionHandlerId, uint64_t targetMode, - uint64_t fromId, const std::string& message); - void onVoiceDataReceived(uint64_t serverConnectionHandlerId, uint64_t clientId, - const std::span& data); + // Event subscription + void registerEventCallback( + const Api::EventCallback& callback) override; + void unregisterEventCallback( + const Api::EventCallback& callback) override; + void clearEventCallbacks(); - // 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); + // TeamSpeak event handlers (called by TeamSpeak SDK) + void onClientConnected(uint64_t serverConnectionHandlerId, + uint64_t clientId); + void onClientDisconnected(uint64_t serverConnectionHandlerId, + uint64_t clientId); + void onClientMoved(uint64_t serverConnectionHandlerId, + uint64_t clientId, uint64_t newChannelId); + void onTextMessageReceived(uint64_t serverConnectionHandlerId, + uint64_t targetMode, uint64_t fromId, + const std::string& message); + 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 - Api::Result registerAudioDevice(); - Api::Result unregisterAudioDevice(); - Api::Result openAudioDevice(); - [[nodiscard]] bool isAudioDeviceRegistered() const { return audioDeviceRegistered_; } - Api::Result closeAudioDevice(); - [[nodiscard]] bool isAudioDeviceOpen() const; + // 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; - // Set server connection handler - void setServerConnectionHandlerId(uint64_t handlerId); - [[nodiscard]] uint64_t getServerConnectionHandlerId() const; + // Audio device management + Api::Result registerAudioDevice(); + Api::Result unregisterAudioDevice(); + Api::Result openAudioDevice(); + [[nodiscard]] bool isAudioDeviceRegistered() const noexcept + { + return audioDeviceRegistered_.load(); + } + Api::Result closeAudioDevice(); + [[nodiscard]] bool isAudioDeviceOpen() const noexcept; - // Audio data submission (for internal use) - void submitAudioData(const std::span samples); + // Set server connection handler + void setServerConnectionHandlerId(uint64_t handlerId) noexcept; + [[nodiscard]] uint64_t + getServerConnectionHandlerId() const noexcept; - // Automatic configuration - Api::Result configureAudioProfile(); - Api::Result checkAndHandleFirstRun(); + // Audio data submission (for internal use) + void submitAudioData(std::span samples); -private: - void broadcastEvent(const Api::PluginEvent& event); - std::string getClientName(uint64_t clientId) const; - std::string getChannelName(uint64_t channelId) const; + // Automatic configuration + Api::Result configureAudioProfile(); + Api::Result checkAndHandleFirstRun(); - // Fetch server groups for a client (returns future that completes when - // groups are received) - std::future> fetchServerGroups(uint64_t clientId); + private: - // Get cached server groups (or empty if not cached) - std::vector getCachedServerGroups(uint64_t clientId); + void broadcastEvent(const Api::PluginEvent& event); + [[nodiscard]] std::string getClientName(uint64_t clientId) const; + [[nodiscard]] 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) + [[nodiscard]] std::future> + fetchServerGroups(uint64_t clientId); - std::vector eventCallbacks_; - mutable std::mutex eventMutex_; + // Get cached server groups (or empty if not cached) + [[nodiscard]] std::vector + getCachedServerGroups(uint64_t clientId); - // Audio data queue - std::queue> audioQueue_; - std::mutex audioMutex_; - std::condition_variable audioCv_; - std::atomic stopAudioThread_{false}; - std::jthread audioThread_; + TS3Functions* ts3Functions_ = nullptr; + uint64_t serverConnectionHandlerId_ = 0; + std::atomic initialized_{false}; + std::atomic audioDeviceRegistered_{false}; + std::atomic audioDeviceOpen_{false}; - // Server groups cache - mutable std::mutex serverGroupsMutex_; - std::map serverGroupsCache_; - std::map>> - pendingServerGroupRequests_; + std::vector eventCallbacks_; + mutable std::mutex eventMutex_; - // Connection info - Api::ServerConfig currentServerConfig_; -}; + // Audio data queue + std::queue> audioQueue_; + std::mutex audioMutex_; + std::condition_variable audioCv_; + std::atomic stopAudioThread_{false}; + std::jthread audioThread_; + + // Server groups cache + mutable std::mutex serverGroupsMutex_; + std::map serverGroupsCache_; + std::map>> + pendingServerGroupRequests_; + + // Connection info + Api::ServerConfig currentServerConfig_; + }; } // namespace Echoion::Plugin diff --git a/include/teamspeak/public_definitions.h b/include/teamspeak/public_definitions.h index 7c45986..b61a68c 100644 --- a/include/teamspeak/public_definitions.h +++ b/include/teamspeak/public_definitions.h @@ -66,8 +66,8 @@ enum ConnectStatus { ///< yet, we haven't been accepted by the server STATUS_CONNECTED, ///< The server has accepted us, we can talk and hear and ///< we have a client id, but we don't have the channels - ///< and clients yet, we can get server infos (welcome msg - ///< etc.) + ///< and clients yet, we can get server infos (welcome msg + ///< etc.) STATUS_CONNECTION_ESTABLISHING, ///< we are connected and we are visible STATUS_CONNECTION_ESTABLISHED, ///< we are connected and we have the client ///< and channels available @@ -182,8 +182,8 @@ enum ChannelProperties { ///< ts3client_requestChannelDescription) CHANNEL_PASSWORD, ///< String. Read/Write. Password of the channel. Read ///< access is limited to the server. Clients will only - ///< ever see the last password they attempted to use when - ///< joining the channel. Always available. + ///< ever see the last password they attempted to use when + ///< joining the channel. Always available. CHANNEL_CODEC, ///< Integer. Read/Write. The codec this channel is using. ///< One of the values from the \ref CodecType enum. Always ///< available. @@ -536,8 +536,8 @@ enum ConnectionProperties { ///< client. CONNECTION_SERVER2CLIENT_PACKETLOSS_CONTROL, ///< Double. Probability with ///< which a control packet - ///< sent by the server was not - ///< received by the client. + ///< sent by the server was not + ///< received by the client. CONNECTION_SERVER2CLIENT_PACKETLOSS_TOTAL, ///< Double. Probability with ///< which a packet sent by the ///< server was not received by @@ -553,8 +553,8 @@ enum ConnectionProperties { ///< server. CONNECTION_CLIENT2SERVER_PACKETLOSS_CONTROL, ///< Double. Probability with ///< which a control packet - ///< sent by the client was not - ///< received by the server. + ///< sent by the client was not + ///< received by the server. CONNECTION_CLIENT2SERVER_PACKETLOSS_TOTAL, ///< Double. Probability with ///< which a packet sent by the ///< client was not received by @@ -597,8 +597,8 @@ enum ConnectionProperties { ///< the last second. CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_CONTROL, ///< UInt64. Number of ///< bytes received for - ///< control data in the - ///< last second. + ///< control data in the + ///< last second. CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_TOTAL, ///< UInt64. Number of ///< bytes received in the ///< last second. diff --git a/include/teamspeak/public_rare_definitions.h b/include/teamspeak/public_rare_definitions.h index 4e28559..a8790cf 100644 --- a/include/teamspeak/public_rare_definitions.h +++ b/include/teamspeak/public_rare_definitions.h @@ -271,8 +271,8 @@ enum VirtualServerPropertiesRare { // requestServerVariables) VIRTUALSERVER_LOG_SERVER, // only available on request (=> // requestServerVariables) - // VIRTUALSERVER_LOG_FILETRANSFER, // Moved to - // VirtualServerProperties due to SDK usage + // VIRTUALSERVER_LOG_FILETRANSFER, // Moved to + // VirtualServerProperties due to SDK usage VIRTUALSERVER_MIN_CLIENT_VERSION = 65, // only available on request (=> requestServerVariables) VIRTUALSERVER_NAME_PHONETIC, // available when connected, always up-to-date diff --git a/include/ts3_functions.h b/include/ts3_functions.h index 2d2f645..a6131c5 100644 --- a/include/ts3_functions.h +++ b/include/ts3_functions.h @@ -4,9 +4,9 @@ #ifdef __cplusplus extern "C" { #endif -#include #include "plugin_definitions.h" #include "teamspeak/public_definitions.h" +#include /* Functions exported to plugin from main binary */ struct TS3Functions { diff --git a/src/CoreLoader.cpp b/src/CoreLoader.cpp index 997bde7..07cee64 100644 --- a/src/CoreLoader.cpp +++ b/src/CoreLoader.cpp @@ -1,424 +1,498 @@ -#include "echoion/plugin/CoreLoader.hpp" +#include "LoggerInterface.hpp" #include "dylib.hpp" -#include -#include +#include "echoion/plugin/CoreLoader.hpp" #include +#include #include #include +#include -namespace Echoion::Plugin { +namespace Echoion::Plugin +{ -CoreLoader::CoreLoader() { - cleanupTempFiles(); -} + CoreLoader::CoreLoader() { cleanupTempFiles(); } -void CoreLoader::enableAutoReload() { - if (autoReloadEnabled_.exchange(true)) { - return; // Already enabled - } - - std::lock_guard lock(mutex_); - if (!currentLibraryPath_.empty() && std::filesystem::exists(currentLibraryPath_)) { - ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}", currentLibraryPath_.string())); - - // Create weak pointer to avoid circular reference in lambda - std::weak_ptr weakThis = - std::const_pointer_cast( - std::shared_ptr(this, [](const CoreLoader*){})); - - fileWatcher_.startWatching(currentLibraryPath_, [this]() { - onCoreFileChanged(); - }); - } -} + void CoreLoader::enableAutoReload() + { + if (autoReloadEnabled_.exchange(true)) { + return; // Already enabled + } -void CoreLoader::disableAutoReload() { - autoReloadEnabled_ = false; - fileWatcher_.stopWatching(); - ECHOION_LOG_INFO("Auto-reload disabled"); -} + std::lock_guard lock(mutex_); + if (!currentLibraryPath_.empty() && + std::filesystem::exists(currentLibraryPath_)) { + ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}", + currentLibraryPath_.string())); -bool CoreLoader::isAutoReloadEnabled() const noexcept { - return autoReloadEnabled_.load(); -} + fileWatcher_.startWatching(currentLibraryPath_, + [this]() { onCoreFileChanged(); }); + } + } -void CoreLoader::onCoreFileChanged() { - if (!autoReloadEnabled_.load() || hotReloading_.load()) { - return; - } - - 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)); - - // 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 { - // 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_(); - } - } - } -} + void CoreLoader::disableAutoReload() + { + autoReloadEnabled_ = false; + fileWatcher_.stopWatching(); + ECHOION_LOG_INFO("Auto-reload disabled"); + } -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::isAutoReloadEnabled() const noexcept + { + return autoReloadEnabled_.load(); + } -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::onCoreFileChanged() + { + if (!autoReloadEnabled_.load() || hotReloading_.load()) { + return; + } -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_(); - } - } -} + ECHOION_LOG_INFO( + "Core file changed, scheduling hot reload after current track..."); -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(); -} + // Small delay to ensure file write is complete + std::this_thread::sleep_for(std::chrono::milliseconds(500)); -Api::Result CoreLoader::load(const std::filesystem::path& libraryPath) { - std::lock_guard lock(mutex_); - - if (loaded_) { - return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already loaded")); - } + // Check if playback is active - if so, defer reload + if (isPlaybackActive()) { + std::string currentTrackId; + { + std::lock_guard lock(pendingReloadMutex_); + hasPendingReload_ = true; + pendingReloadPath_ = currentLibraryPath_; - if (!std::filesystem::exists(libraryPath)) { - return std::unexpected(Api::Error(Api::ErrorCode::NotFound, - std::format("Library not found: {}", libraryPath.string()))); - } + // Capture current track ID + auto state = core_->getPlaybackSummary(); + if (state && state->currentTrack.has_value()) { + pendingTrackId_ = state->currentTrack->id; + currentTrackId = pendingTrackId_; + } + } - tempLibraryPath_ = getTempLibraryPath(libraryPath); - - try { - std::filesystem::copy_file(libraryPath, tempLibraryPath_, - std::filesystem::copy_options::overwrite_existing); - } catch (const std::exception& e) { - return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, - std::format("Failed to copy library to temp: {}", e.what()))); - } + ECHOION_LOG_INFO( + std::format("Playback active (track: {}), deferring reload " + "until track finishes", + currentTrackId)); - auto result = loadLibraryInternal(tempLibraryPath_); - if (result) { - currentLibraryPath_ = libraryPath; - } else { - std::error_code ec; - std::filesystem::remove(tempLibraryPath_, ec); - } - - return result; -} + // Start background thread to wait for track end + if (deferredReloadThread_.joinable()) { + deferredReloadThread_.join(); + } + deferredReloadThread_ = std::thread([this, currentTrackId]() { + waitForTrackAndReload(pendingReloadPath_, currentTrackId); + }); + } else { + // 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_(); + } + } + } + } -Api::Result CoreLoader::unload() { - std::lock_guard lock(mutex_); - - auto result = unloadLibraryInternal(); - - if (!tempLibraryPath_.empty()) { - std::error_code ec; - std::filesystem::remove(tempLibraryPath_, ec); - } - - return result; -} + bool CoreLoader::isPlaybackActive() const + { + if (!core_) { + return false; + } -Api::Result CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { - std::lock_guard lock(mutex_); - - if (!loaded_) { - return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No core loaded to reload")); - } + auto state = core_->getPlaybackSummary(); + if (!state) { + return false; + } - hotReloading_ = true; - - ECHOION_LOG_INFO("Starting hot reload with temp file..."); + // Check if currently playing a track + return state->isPlaying && state->currentTrack.has_value(); + } - auto state = saveStateInternal(); - - auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; - - if (!std::filesystem::exists(targetPath)) { - hotReloading_ = false; - return std::unexpected(Api::Error(Api::ErrorCode::NotFound, - std::format("New library not found: {}", targetPath.string()))); - } + bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const + { + if (!core_ || trackId.empty()) { + return false; + } - std::filesystem::path newTempPath = getTempLibraryPath(targetPath); - - try { - std::filesystem::copy_file(targetPath, newTempPath, - std::filesystem::copy_options::overwrite_existing); - } catch (const std::exception& e) { - hotReloading_ = false; - std::error_code ec; - std::filesystem::remove(newTempPath, ec); - return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, - std::format("Failed to copy new library to temp: {}", e.what()))); - } + auto state = core_->getPlaybackSummary(); + if (!state || !state->currentTrack.has_value()) { + return false; + } - auto unloadResult = unloadLibraryInternal(); - if (!unloadResult) { - hotReloading_ = false; - std::error_code ec; - std::filesystem::remove(newTempPath, ec); - return unloadResult; - } + return state->currentTrack->id == trackId; + } - std::error_code ec; - std::filesystem::remove(tempLibraryPath_, ec); - tempLibraryPath_ = newTempPath; + 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)); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); + // 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)); + } - auto loadResult = loadLibraryInternal(tempLibraryPath_); - if (!loadResult) { - hotReloading_ = false; - return loadResult; - } + ECHOION_LOG_INFO("Track finished, starting hot reload"); - auto restoreResult = restoreStateInternal(state); - if (!restoreResult) { - ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", restoreResult.error().message)); - } + // Clear pending flag + { + std::lock_guard lock(pendingReloadMutex_); + hasPendingReload_ = false; + pendingTrackId_.clear(); + } - currentLibraryPath_ = targetPath; - hotReloading_ = false; - - ECHOION_LOG_INFO("Hot reload complete"); - return {}; -} + // 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_(); + } + } + } -bool CoreLoader::isLoaded() const noexcept { - return loaded_.load(); -} + 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(); + } -Api::CoreInterfacePtr CoreLoader::getCore() const { - std::lock_guard lock(mutex_); - return core_; -} + Api::Result CoreLoader::load(const std::filesystem::path& libraryPath) + { + std::lock_guard lock(mutex_); -void CoreLoader::setConfigPath(const std::filesystem::path& configPath) { - std::lock_guard lock(mutex_); - configPath_ = configPath; -} + if (loaded_) { + return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, + "Core already loaded")); + } -std::filesystem::path CoreLoader::getConfigPath() const { - std::lock_guard lock(mutex_); - return configPath_; -} + if (!std::filesystem::exists(libraryPath)) { + return std::unexpected(Api::Error( + Api::ErrorCode::NotFound, + std::format("Library not found: {}", libraryPath.string()))); + } -bool CoreLoader::isHotReloading() const noexcept { - return hotReloading_.load(); -} + tempLibraryPath_ = getTempLibraryPath(libraryPath); -Api::Result CoreLoader::loadLibraryInternal(const std::filesystem::path& path) { - try { - ECHOION_LOG_INFO(std::format("Loading core library: {}", path.string())); - // Use no decorations - the path already has the correct extension (.ts) - library_ = std::make_unique(path.string(), dylib::decorations::none()); - - auto createFunc = library_->get_function("CreateCore"); - auto versionFunc = library_->get_function("GetApiVersion"); - auto compatibleFunc = library_->get_function("IsApiCompatible"); + try { + std::filesystem::copy_file( + libraryPath, tempLibraryPath_, + std::filesystem::copy_options::overwrite_existing); + } catch (const std::exception& e) { + return std::unexpected(Api::Error( + Api::ErrorCode::UnknownError, + std::format("Failed to copy library to temp: {}", e.what()))); + } - if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) { - library_.reset(); - return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, - std::format("API version mismatch. Expected {}.{}, got {}", - Api::VERSION_MAJOR, Api::VERSION_MINOR, versionFunc()))); - } + auto result = loadLibraryInternal(tempLibraryPath_); + if (result) { + currentLibraryPath_ = libraryPath; + } else { + std::error_code ec; + std::filesystem::remove(tempLibraryPath_, ec); + } - core_ = createFunc(); - if (!core_) { - library_.reset(); - return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, - "Failed to create core instance")); - } + return result; + } - auto initResult = core_->initialize(configPath_); - if (!initResult) { - core_.reset(); - library_.reset(); - return initResult; - } + Api::Result CoreLoader::unload() + { + std::lock_guard lock(mutex_); - loaded_ = true; + auto result = unloadLibraryInternal(); - ECHOION_LOG_INFO(std::format("Core library loaded (API version: {})", versionFunc())); - return {}; + if (!tempLibraryPath_.empty()) { + std::error_code ec; + std::filesystem::remove(tempLibraryPath_, ec); + } - } catch (const dylib::load_error& e) { - return std::unexpected(Api::Error(Api::ErrorCode::PluginError, - std::format("Failed to load library: {}", e.what()))); - } catch (const dylib::symbol_error& e) { - return std::unexpected(Api::Error(Api::ErrorCode::PluginError, - std::format("Failed to find symbol: {}", e.what()))); - } catch (const std::exception& e) { - return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, - std::format("Unexpected error: {}", e.what()))); - } -} + return result; + } -Api::Result CoreLoader::unloadLibraryInternal() { - if (!loaded_) { - return {}; - } + Api::Result + CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) + { + std::lock_guard lock(mutex_); - ECHOION_LOG_INFO("Unloading core library..."); + if (!loaded_) { + return std::unexpected(Api::Error(Api::ErrorCode::NotFound, + "No core loaded to reload")); + } - if (core_) { - core_->shutdown(); - core_.reset(); - } + hotReloading_ = true; - library_.reset(); + ECHOION_LOG_INFO("Starting hot reload with temp file..."); - loaded_ = false; - ECHOION_LOG_INFO("Core library unloaded"); - return {}; -} + // Step 1: Save state as opaque blob (Plugin doesn't know contents) + Api::StateBlob stateBlob; + if (core_) { + stateBlob = core_->saveState(); + ECHOION_LOG_INFO( + std::format("Saved state: version={}, size={} bytes", + stateBlob.version, stateBlob.size())); + } -Api::HotReloadState CoreLoader::saveStateInternal() { - if (!core_) { - return Api::HotReloadState{}; - } + auto targetPath = + newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; - auto state = core_->prepareForHotReload(); - if (state) { - return *state; - } + if (!std::filesystem::exists(targetPath)) { + hotReloading_ = false; + return std::unexpected(Api::Error( + Api::ErrorCode::NotFound, + std::format("New library not found: {}", targetPath.string()))); + } - ECHOION_LOG_WARNING("Failed to save state for hot reload"); - return Api::HotReloadState{}; -} + std::filesystem::path newTempPath = getTempLibraryPath(targetPath); -Api::Result CoreLoader::restoreStateInternal(const Api::HotReloadState& state) { - if (!core_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Core not available for state restore")); - } + try { + std::filesystem::copy_file( + targetPath, newTempPath, + std::filesystem::copy_options::overwrite_existing); + } catch (const std::exception& e) { + hotReloading_ = false; + std::error_code ec; + std::filesystem::remove(newTempPath, ec); + return std::unexpected( + Api::Error(Api::ErrorCode::UnknownError, + std::format("Failed to copy new library to temp: {}", + e.what()))); + } - return core_->restoreAfterHotReload(state); -} + auto unloadResult = unloadLibraryInternal(); + if (!unloadResult) { + hotReloading_ = false; + std::error_code ec; + std::filesystem::remove(newTempPath, ec); + return unloadResult; + } -std::filesystem::path CoreLoader::getTempLibraryPath(const std::filesystem::path& original) const { - auto tempDir = std::filesystem::temp_directory_path(); - auto filename = original.filename().string(); - - auto now = std::chrono::system_clock::now(); - auto ms = std::chrono::duration_cast( - now.time_since_epoch()).count(); - - // Use the same extension as the original file (.ts for TeamSpeak plugin) - #ifdef _WIN32 - auto tempName = std::format("echoion_{}_{}.dll", ms, - std::hash{}(std::this_thread::get_id())); - #else - auto tempName = std::format("echoion_{}_{}.ts", ms, - std::hash{}(std::this_thread::get_id())); - #endif - - return tempDir / tempName; -} + std::error_code ec; + std::filesystem::remove(tempLibraryPath_, ec); + tempLibraryPath_ = newTempPath; -void CoreLoader::cleanupTempFiles() { - auto tempDir = std::filesystem::temp_directory_path(); - std::error_code ec; - - for (const auto& entry : std::filesystem::directory_iterator(tempDir, ec)) { - if (entry.is_regular_file()) { - auto name = entry.path().filename().string(); - if (name.starts_with("echoion_") && - (name.ends_with(".dll") || name.ends_with(".so") || name.ends_with(".ts"))) { - std::filesystem::remove(entry.path(), ec); - } - } - } -} + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + + auto loadResult = loadLibraryInternal(tempLibraryPath_); + if (!loadResult) { + hotReloading_ = false; + return loadResult; + } + + // Step 4: Ask new Core to restore state (it handles migration + // internally) + if (!stateBlob.empty()) { + auto coreVersion = core_->getStateFormatVersion(); + auto stateVersion = stateBlob.version; + + ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}", + stateVersion, coreVersion)); + + if (core_->canRestoreStateVersion(stateVersion)) { + auto restoreResult = core_->restoreState(stateBlob); + if (!restoreResult) { + ECHOION_LOG_ERROR( + std::format("Failed to restore state: {}", + restoreResult.error().message)); + + // Check if it's a version issue + if (restoreResult.error().code == + Api::ErrorCode::IncompatibleVersion) { + // Signal user to update/restart + ECHOION_LOG_WARNING("State version incompatible. " + "User needs to update/restart."); + // Optionally: notify through plugin interface + } + + // Continue with empty state - graceful degradation + } else { + ECHOION_LOG_INFO("State restored successfully"); + } + } else { + ECHOION_LOG_WARNING(std::format( + "Cannot restore state v{} in Core v{}. " + "Version age exceeds maximum supported ({} versions).", + stateVersion, coreVersion, + Api::MAX_SUPPORTED_STATE_VERSION_AGE)); + // Continue with empty state + } + } + + currentLibraryPath_ = targetPath; + hotReloading_ = false; + + ECHOION_LOG_INFO("Hot reload complete"); + return {}; + } + + bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); } + + Api::CoreInterfacePtr CoreLoader::getCore() const + { + std::lock_guard lock(mutex_); + return core_; + } + + void CoreLoader::setConfigPath(const std::filesystem::path& configPath) + { + std::lock_guard lock(mutex_); + configPath_ = configPath; + } + + std::filesystem::path CoreLoader::getConfigPath() const + { + std::lock_guard lock(mutex_); + return configPath_; + } + + bool CoreLoader::isHotReloading() const noexcept + { + return hotReloading_.load(); + } + + Api::Result + CoreLoader::loadLibraryInternal(const std::filesystem::path& path) + { + try { + + std::cout << std::format("[Echoion] Loading core library: {}", + path.string()) + << std::endl; + // Use no decorations - the path already has the correct extension + // (.ts) + library_ = std::make_unique( + path.string(), dylib::decorations::none()); + + auto createFunc = + library_->get_function("CreateCore"); + auto versionFunc = + library_->get_function("GetApiVersion"); + auto compatibleFunc = + library_->get_function( + "IsApiCompatible"); + + if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) { + library_.reset(); + return std::unexpected(Api::Error( + Api::ErrorCode::InvalidArgument, + std::format("API version mismatch. Expected {}.{}, got {}", + Api::VERSION_MAJOR, Api::VERSION_MINOR, + versionFunc()))); + } + + core_ = createFunc(); + if (!core_) { + library_.reset(); + return std::unexpected( + Api::Error(Api::ErrorCode::UnknownError, + "Failed to create core instance")); + } + + auto initResult = core_->initialize(configPath_); + if (!initResult) { + core_.reset(); + library_.reset(); + return initResult; + } + + loaded_ = true; + + ECHOION_LOG_INFO(std::format( + "Core library loaded (API version: {})", versionFunc())); + return {}; + + } catch (const dylib::load_error& e) { + return std::unexpected(Api::Error( + Api::ErrorCode::PluginError, + std::format("Failed to load library: {}", e.what()))); + } catch (const dylib::symbol_error& e) { + return std::unexpected( + Api::Error(Api::ErrorCode::PluginError, + std::format("Failed to find symbol: {}", e.what()))); + } catch (const std::exception& e) { + return std::unexpected( + Api::Error(Api::ErrorCode::UnknownError, + std::format("Unexpected error: {}", e.what()))); + } + } + + Api::Result CoreLoader::unloadLibraryInternal() + { + if (!loaded_) { + return {}; + } + + ECHOION_LOG_INFO("Unloading core library..."); + + if (core_) { + core_->shutdown(); + core_.reset(); + } + + library_.reset(); + + loaded_ = false; + std::cout << "[Echoion] Core library unloaded" << std::endl; + return {}; + } + + std::filesystem::path CoreLoader::getTempLibraryPath( + const std::filesystem::path& original) const + { + auto tempDir = std::filesystem::temp_directory_path(); + auto filename = original.filename().string(); + + auto now = std::chrono::system_clock::now(); + auto ms = std::chrono::duration_cast( + now.time_since_epoch()) + .count(); + +// Use the same extension as the original file (.ts for TeamSpeak plugin) +#ifdef _WIN32 + auto tempName = std::format( + "echoion_{}_{}.dll", ms, + std::hash{}(std::this_thread::get_id())); +#else + auto tempName = std::format( + "echoion_{}_{}.ts", ms, + std::hash{}(std::this_thread::get_id())); +#endif + + return tempDir / tempName; + } + + void CoreLoader::cleanupTempFiles() + { + auto tempDir = std::filesystem::temp_directory_path(); + std::error_code ec; + + for (const auto& entry : + std::filesystem::directory_iterator(tempDir, ec)) { + if (entry.is_regular_file()) { + auto name = entry.path().filename().string(); + if (name.starts_with("echoion_") && + (name.ends_with(".dll") || name.ends_with(".so") || + name.ends_with(".ts"))) { + std::filesystem::remove(entry.path(), ec); + } + } + } + } } // namespace Echoion::Plugin diff --git a/src/FileWatcher.cpp b/src/FileWatcher.cpp index 209f923..9f358b1 100644 --- a/src/FileWatcher.cpp +++ b/src/FileWatcher.cpp @@ -1,94 +1,98 @@ #include "echoion/plugin/FileWatcher.hpp" +#include #include #include -#include -namespace Echoion::Plugin { +namespace Echoion::Plugin +{ -FileWatcher::FileWatcher() = default; + FileWatcher::FileWatcher() = default; -FileWatcher::~FileWatcher() { - stopWatching(); -} + FileWatcher::~FileWatcher() { stopWatching(); } -void FileWatcher::startWatching( - const std::filesystem::path& filePath, - ChangeCallback callback, - std::chrono::milliseconds intervalMs) { - - std::lock_guard lock(mutex_); - - if (watching_.load()) { - stopWatching(); - } + void FileWatcher::startWatching(const std::filesystem::path& filePath, + ChangeCallback callback, + std::chrono::milliseconds intervalMs) + { - watchedPath_ = filePath; - callback_ = std::move(callback); - intervalMs_ = intervalMs; - stopRequested_ = false; + std::lock_guard lock(mutex_); - // Get initial file state - if (std::filesystem::exists(watchedPath_)) { - lastWriteTime_ = std::filesystem::last_write_time(watchedPath_); - lastFileSize_ = std::filesystem::file_size(watchedPath_); - } + if (watching_.load()) { + stopWatching(); + } - watching_ = true; - watchThread_ = std::thread(&FileWatcher::watchLoop, this); -} + watchedPath_ = filePath; + callback_ = std::move(callback); + intervalMs_ = intervalMs; + stopRequested_ = false; -void FileWatcher::stopWatching() { - stopRequested_ = true; - - if (watchThread_.joinable()) { - watchThread_.join(); - } - - watching_ = false; -} + // Get initial file state + if (std::filesystem::exists(watchedPath_)) { + lastWriteTime_ = std::filesystem::last_write_time(watchedPath_); + lastFileSize_ = std::filesystem::file_size(watchedPath_); + } -bool FileWatcher::isWatching() const noexcept { - return watching_.load(); -} + watching_ = true; + watchThread_ = std::thread(&FileWatcher::watchLoop, this); + } -void FileWatcher::watchLoop() { - while (!stopRequested_.load()) { - // Sleep first to avoid checking immediately - std::this_thread::sleep_for(intervalMs_); - - if (stopRequested_.load()) { - break; - } + void FileWatcher::stopWatching() + { + stopRequested_ = true; - std::lock_guard lock(mutex_); - - if (!std::filesystem::exists(watchedPath_)) { - continue; - } + if (watchThread_.joinable()) { + watchThread_.join(); + } - try { - auto currentWriteTime = std::filesystem::last_write_time(watchedPath_); - auto currentFileSize = std::filesystem::file_size(watchedPath_); + watching_ = false; + } - // Check if file has changed (time or size) - if (currentWriteTime != lastWriteTime_ || currentFileSize != lastFileSize_) { - // Update stored values - lastWriteTime_ = currentWriteTime; - lastFileSize_ = currentFileSize; + bool FileWatcher::isWatching() const noexcept { return watching_.load(); } - // Trigger callback - if (callback_) { - try { - callback_(); - } catch (const std::exception& e) { - std::cerr << std::format("FileWatcher callback error: {}", e.what()) << std::endl; - } - } - } - } catch (const std::exception& e) { - // Ignore errors (file might be locked during write) - } - } -} + void FileWatcher::watchLoop() + { + while (!stopRequested_.load()) { + // Sleep first to avoid checking immediately + std::this_thread::sleep_for(intervalMs_); + + if (stopRequested_.load()) { + break; + } + + std::lock_guard lock(mutex_); + + if (!std::filesystem::exists(watchedPath_)) { + continue; + } + + try { + auto currentWriteTime = + std::filesystem::last_write_time(watchedPath_); + auto currentFileSize = std::filesystem::file_size(watchedPath_); + + // Check if file has changed (time or size) + if (currentWriteTime != lastWriteTime_ || + currentFileSize != lastFileSize_) { + // Update stored values + lastWriteTime_ = currentWriteTime; + lastFileSize_ = currentFileSize; + + // Trigger callback + if (callback_) { + try { + callback_(); + } catch (const std::exception& e) { + std::cerr + << std::format("FileWatcher callback error: {}", + e.what()) + << std::endl; + } + } + } + } catch (const std::exception& e) { + // Ignore errors (file might be locked during write) + } + } + } } // namespace Echoion::Plugin diff --git a/src/Plugin.cpp b/src/Plugin.cpp index fc0a0da..1f669ab 100644 --- a/src/Plugin.cpp +++ b/src/Plugin.cpp @@ -1,460 +1,548 @@ // TeamSpeak Plugin Entry Point -#include -#include -#include "echoion/plugin/PluginInterface.hpp" #include "echoion/plugin/CoreLoader.hpp" +#include "echoion/plugin/PluginInterface.hpp" #include "teamspeak/public_errors.h" -#include -#include -#include -#include -#include +#include +#include +#include #include #include #include -#include +#include +#include #include +#include +#include #include +#include +#include +#include -namespace Echoion::Plugin { - -// Global plugin state -static std::shared_ptr g_pluginInterface; -static std::unique_ptr g_coreLoader; - -// TeamSpeak plugin info -static constexpr char PLUGIN_NAME[] = "Echoion Music Bot"; -static constexpr char PLUGIN_VERSION[] = "1.0.0"; -static constexpr char PLUGIN_AUTHOR[] = "Echoion Team"; -static constexpr char PLUGIN_DESCRIPTION[] = "Advanced music bot for TeamSpeak"; -static char *pluginID = NULL; -static std::jthread g_deferredInitThread; -static std::atomic g_deferredInitRunning{false}; -static std::atomic g_deferredInitComplete{false}; -static std::atomic g_ts3FunctionsReady{false}; -static std::shared_ptr g_ts3Functions = nullptr; - -// Helper to get config directory -std::filesystem::path getConfigDir() { - const char* configHome = std::getenv("XDG_CONFIG_HOME"); - if (configHome) { - return std::filesystem::path(configHome) / "echoion"; - } - const char* home = std::getenv("HOME"); - if (home) { - return std::filesystem::path(home) / ".config" / "echoion"; - } - return std::filesystem::path(".") / "echoion"; -} - -std::filesystem::path getConfigPath() { - return getConfigDir() / "config.json"; -} - -// Initialize the plugin -extern "C" { - -static std::filesystem::path getCorePath() +namespace Echoion::Plugin { - if (g_ts3FunctionsReady.load()) - { - char path[512]; - g_ts3Functions->getPluginPath(path, 512, pluginID); - return std::string(path) + "Echoion.ts"; - } - return "./plugins/Echoion.ts"; -} + + // Global plugin state + static std::shared_ptr g_pluginInterface; + static std::unique_ptr g_coreLoader; + + // TeamSpeak plugin info + static constexpr char PLUGIN_NAME[] = "Echoion Music Bot"; + static constexpr char PLUGIN_VERSION[] = "1.0.0"; + static constexpr char PLUGIN_AUTHOR[] = "Echoion Team"; + static constexpr char PLUGIN_DESCRIPTION[] = + "Advanced music bot for TeamSpeak"; + static std::unique_ptr pluginID; + static std::jthread g_deferredInitThread; + static std::atomic g_deferredInitRunning{false}; + static std::atomic g_deferredInitComplete{false}; + static std::atomic g_ts3FunctionsReady{false}; + static std::shared_ptr g_ts3Functions = nullptr; + + // Helper to get config directory + std::filesystem::path getConfigDir() + { + const char* configHome = std::getenv("XDG_CONFIG_HOME"); + if (configHome) { + return std::filesystem::path(configHome) / "echoion"; + } + const char* home = std::getenv("HOME"); + if (home) { + return std::filesystem::path(home) / ".config" / "echoion"; + } + return std::filesystem::path(".") / "echoion"; + } + + std::filesystem::path getConfigPath() + { + return getConfigDir() / "config.json"; + } + + // Initialize the plugin + extern "C" { + + static std::filesystem::path getCorePath() + { + if (g_ts3FunctionsReady.load()) { + char path[512]; + g_ts3Functions->getPluginPath(path, 512, pluginID.get()); + return std::string(path) + "Echoion.ts"; + } + return "./plugins/Echoion.ts"; + } // Required TeamSpeak plugin functions #ifdef _WIN32 - #define TS3_PLUGIN_API __declspec(dllexport) +#define TS3_PLUGIN_API __declspec(dllexport) #else - #define TS3_PLUGIN_API __attribute__((visibility("default"))) +#define TS3_PLUGIN_API __attribute__((visibility("default"))) #endif -TS3_PLUGIN_API const char* ts3plugin_name() { return PLUGIN_NAME; } -TS3_PLUGIN_API const char* ts3plugin_version() { return PLUGIN_VERSION; } -TS3_PLUGIN_API int ts3plugin_apiVersion() { return 26; } -TS3_PLUGIN_API const char* ts3plugin_author() { return PLUGIN_AUTHOR; } -TS3_PLUGIN_API const char* ts3plugin_description() { return PLUGIN_DESCRIPTION; } + TS3_PLUGIN_API const char* ts3plugin_name() { return PLUGIN_NAME; } + TS3_PLUGIN_API const char* ts3plugin_version() { return PLUGIN_VERSION; } + TS3_PLUGIN_API int ts3plugin_apiVersion() { return 26; } + TS3_PLUGIN_API const char* ts3plugin_author() { return PLUGIN_AUTHOR; } + TS3_PLUGIN_API const char* ts3plugin_description() + { + return PLUGIN_DESCRIPTION; + } -TS3_PLUGIN_API void ts3plugin_setFunctionPointers(const TS3Functions funcs) { - g_ts3Functions = std::make_shared(funcs); - - if (g_ts3Functions && g_ts3Functions->getConfigPath && g_ts3Functions->getPluginPath) { - g_ts3FunctionsReady.store(true); - std::cout << "[Echoion] TS3 function pointers set" << std::endl; - } else { - std::cerr << "[Echoion] TS3 function pointers incomplete" << std::endl; - } -} + TS3_PLUGIN_API void ts3plugin_setFunctionPointers(const TS3Functions funcs) + { + g_ts3Functions = std::make_shared(funcs); + + if (g_ts3Functions && g_ts3Functions->getConfigPath && + g_ts3Functions->getPluginPath) { + g_ts3FunctionsReady.store(true); + std::cout << "[Echoion] TS3 function pointers set" << std::endl; + } else { + std::cerr << "[Echoion] TS3 function pointers incomplete" + << std::endl; + } + } #define _strcpy(dest, destSize, src) \ - { \ - strncpy(dest, src, destSize - 1); \ - (dest)[destSize - 1] = '\0'; \ - } - -TS3_PLUGIN_API void ts3plugin_registerPluginID(const char *id) -{ - const size_t sz = strlen(id) + 1; - pluginID = (char *)malloc(sz * sizeof(char)); - _strcpy(pluginID, sz, 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; - } - - 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) - g_coreLoader->setConfigPath(getConfigPath()); - std::cout << std::format("[Echoion] Config path: {}", getConfigPath().string()) << std::endl; - - std::cout << std::format("[Echoion] Loading Core from: {}", getCorePath().string()) << std::endl; - auto loadResult = g_coreLoader->load(getCorePath()); - if (!loadResult) { - std::cerr << std::format("[Echoion] Failed to load core: {}", loadResult.error().message) << std::endl; - return false; - } - - // Get core and set plugin interface - auto core = g_coreLoader->getCore(); - if (core && g_pluginInterface) { - core->setPluginInterface(g_pluginInterface); - - // Register for plugin events from Core - g_pluginInterface->registerEventCallback([core](const Api::PluginEvent& event) { - core->onPluginEvent(event); - }); - - // Trigger auto-connect now that plugin interface is set - core->triggerAutoConnect(); - } - - return true; - } catch (const std::exception& e) { - std::cerr << std::format("[Echoion] Exception loading core: {}", e.what()) << std::endl; - return false; - } -} - -void deferredInitialization() { - g_deferredInitRunning = true; - - // Wait 3 seconds for TeamSpeak GUI to fully initialize - 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++; + { \ + strncpy(dest, src, destSize - 1); \ + (dest)[destSize - 1] = '\0'; \ } - if (!g_ts3FunctionsReady.load()) { - std::cerr << "[Echoion] TS3 functions not ready, aborting init" + TS3_PLUGIN_API void ts3plugin_registerPluginID(const char* id) + { + const size_t sz = strlen(id) + 1; + pluginID = std::make_unique(sz); + _strcpy(pluginID.get(), sz, id); + std::cout << std::format("[Echoion] Plugin ID: {}", pluginID.get()) << std::endl; - g_deferredInitRunning = false; - return; } - std::cout << "[Echoion] Starting deferred initialization..." << std::endl; + // Forward declarations for helper functions + static bool reregisterPluginInterface(); + static bool reloadCoreWithInterface(); - try { - // Create plugin interface - g_pluginInterface = std::make_shared(); - - // Initialize plugin interface with TS functions - auto result = g_pluginInterface->initialize(g_ts3Functions.get()); - if (!result) { - std::cerr << std::format("[Echoion] Failed to initialize plugin interface: {}", - result.error().message) << std::endl; - g_deferredInitRunning = false; - return; - } + static bool ensureCoreLoaded() + { + if (g_coreLoader && g_coreLoader->isLoaded()) { + return true; + } - // Register audio device - auto deviceResult = g_pluginInterface->registerAudioDevice(); - if (!deviceResult) { - std::cout << std::format("[Echoion] Audio device skipped: {}", - deviceResult.error().message) << std::endl; - } else { - std::cout << "[Echoion] Audio device registered" << std::endl; - } - - // Load Core library (Core will handle config loading and auto-connect) - if (ensureCoreLoaded()) { - std::cout << "[Echoion] Core loaded successfully" << std::endl; - if (g_coreLoader) { - g_coreLoader->enableAutoReload(); - } - } else { - std::cout << "[Echoion] Core failed to load" << std::endl; - } - - std::cout << "[Echoion] Initialization complete" << std::endl; - g_deferredInitComplete = true; - - } catch (const std::exception& e) { - std::cerr << std::format("[Echoion] Deferred init failed: {}", e.what()) << std::endl; - } - - g_deferredInitRunning = false; -} + 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(); + }); + } -TS3_PLUGIN_API int ts3plugin_init() { - std::cout << "[Echoion] Plugin init started" << std::endl; - g_deferredInitThread = std::jthread(deferredInitialization); - return 0; -} + // Pass config path to CoreLoader (Core will load config internally) + g_coreLoader->setConfigPath(getConfigPath()); + std::cout << std::format("[Echoion] Config path: {}", + getConfigPath().string()) + << std::endl; -TS3_PLUGIN_API void ts3plugin_shutdown() { - std::cout << "[Echoion] Shutting down..." << std::endl; + std::cout << std::format("[Echoion] Loading Core from: {}", + getCorePath().string()) + << std::endl; + auto loadResult = g_coreLoader->load(getCorePath()); + if (!loadResult) { + std::cerr << std::format("[Echoion] Failed to load core: {}", + loadResult.error().message) + << std::endl; + return false; + } - g_deferredInitRunning = false; - - if (g_deferredInitThread.joinable()) { - auto start = std::chrono::steady_clock::now(); - while (g_deferredInitRunning && - std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } - - if (g_deferredInitThread.joinable()) { - if (g_deferredInitRunning) { - g_deferredInitThread.detach(); - } else { - g_deferredInitThread.join(); - } - } - } + // Get core and set plugin interface + auto core = g_coreLoader->getCore(); + if (core && g_pluginInterface) { + core->setPluginInterface(g_pluginInterface); - if (g_pluginInterface) { - g_pluginInterface->disconnectFromServer(); - } + // Register for plugin events from Core + g_pluginInterface->registerEventCallback( + [core](const Api::PluginEvent& event) { + core->onPluginEvent(event); + }); - if (g_coreLoader) { - g_coreLoader->disableAutoReload(); - g_coreLoader->unload(); - g_coreLoader.reset(); - } + // Trigger auto-connect now that plugin interface is set + core->triggerAutoConnect(); + } - if (g_pluginInterface) { - g_pluginInterface->shutdown(); - g_pluginInterface = nullptr; - } + return true; + } catch (const std::exception& e) { + std::cerr << std::format("[Echoion] Exception loading core: {}", + e.what()) + << std::endl; + return false; + } + } - g_ts3Functions = nullptr; - g_ts3FunctionsReady = false; + void deferredInitialization() + { + g_deferredInitRunning = true; - std::cout << "[Echoion] Shutdown complete" << std::endl; -} + // Wait 3 seconds for TeamSpeak GUI to fully initialize + std::this_thread::sleep_for(std::chrono::seconds(30)); -// 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) { - - anyID myID = 0; - if (g_ts3Functions && g_ts3Functions->getClientID(serverConnectionHandlerId, &myID) == ERROR_ok) { - if (fromID == myID) return; - } + // 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_pluginInterface) { - g_pluginInterface->onTextMessageReceived(serverConnectionHandlerId, targetMode, - fromID, message); - } -} + if (!g_ts3FunctionsReady.load()) { + std::cerr << "[Echoion] TS3 functions not ready, aborting init" + << std::endl; + g_deferredInitRunning = false; + return; + } -// Handle client connect/disconnect -TS3_PLUGIN_API void ts3plugin_onClientMoveEvent(uint64 serverConnectionHandlerId, - anyID clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, - const char* moveMessage) { - - if (!g_pluginInterface) return; - - if (oldChannelID == 0) { - g_pluginInterface->onClientConnected(serverConnectionHandlerId, clientID); - } else if (newChannelID == 0) { - g_pluginInterface->onClientDisconnected(serverConnectionHandlerId, clientID); - } else { - g_pluginInterface->onClientMoved(serverConnectionHandlerId, clientID, newChannelID); - } -} + std::cout << "[Echoion] Starting deferred initialization..." + << std::endl; -TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent(uint64 serverConnectionHandlerId, - anyID clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, - const char* timeoutMessage) { - - if (g_pluginInterface) { - g_pluginInterface->onClientDisconnected(serverConnectionHandlerId, clientID); - } -} + try { + // Create plugin interface + g_pluginInterface = std::make_shared(); -// 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; -} + // Initialize plugin interface with TS functions + auto result = g_pluginInterface->initialize(g_ts3Functions.get()); + if (!result) { + std::cerr << std::format("[Echoion] Failed to initialize " + "plugin interface: {}", + result.error().message) + << std::endl; + g_deferredInitRunning = false; + return; + } -// 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(); -} + // Register audio device + auto deviceResult = g_pluginInterface->registerAudioDevice(); + if (!deviceResult) { + std::cout << std::format("[Echoion] Audio device skipped: {}", + deviceResult.error().message) + << std::endl; + } else { + std::cout << "[Echoion] Audio device registered" << std::endl; + } -// 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()) { - reloadCoreWithInterface(); - } - } -} + // Load Core library (Core will handle config loading and + // auto-connect) + if (ensureCoreLoaded()) { + std::cout << "[Echoion] Core loaded successfully" << std::endl; + if (g_coreLoader) { + g_coreLoader->enableAutoReload(); + } + } else { + std::cout << "[Echoion] Core failed to load" << std::endl; + } -// Menu item callbacks -TS3_PLUGIN_API void ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId, - enum PluginMenuType type, int menuItemID, uint64 selectedItemID) { - - if (!ensureCoreLoaded()) return; - - auto core = g_coreLoader->getCore(); - if (!core) return; - - switch (menuItemID) { - case 1: { // Play/Pause - auto state = core->getPlaybackState(); - if (state) { - if (state->isPlaying && !state->isPaused) { - core->pause(); - } else if (state->isPaused) { - core->resume(); - } - } - break; - } - case 2: // Skip - core->skip(1); - break; - case 3: // Stop - core->stop(); - break; - case 4: // Hot Reload Core - reloadCoreWithInterface(); - break; - case 5: // Connect/Disconnect - if (g_pluginInterface) { - if (g_pluginInterface->isConnected()) { - g_pluginInterface->disconnectFromServer(); - } else { - // Core handles connection, just trigger reconnect - if (auto result = g_pluginInterface->reconnect(); !result) { - std::cerr << std::format("[Echoion] Reconnect failed: {}", result.error().message) << std::endl; - } - } - } - break; - } -} + std::cout << "[Echoion] Initialization complete" << std::endl; + g_deferredInitComplete = true; -// Connection status changes -TS3_PLUGIN_API void ts3plugin_onConnectStatusChangeEvent(uint64 serverConnectionHandlerId, - int newStatus, unsigned int errorNumber) { - - if (g_pluginInterface) { - g_pluginInterface->setServerConnectionHandlerId(serverConnectionHandlerId); - } + } catch (const std::exception& e) { + std::cerr << std::format("[Echoion] Deferred init failed: {}", + e.what()) + << std::endl; + } - switch (newStatus) { - case STATUS_CONNECTING: - std::cout << "[Echoion] Connecting..." << std::endl; - break; - case STATUS_CONNECTED: - std::cout << "[Echoion] Connected" << std::endl; - if (g_pluginInterface) { - g_pluginInterface->closeAudioDevice(); - g_pluginInterface->openAudioDevice(); - } - break; - case STATUS_CONNECTION_ESTABLISHED: - std::cout << "[Echoion] Connection established" << std::endl; - break; - case STATUS_DISCONNECTED: - std::cout << "[Echoion] Disconnected" << std::endl; - if (g_pluginInterface) { - g_pluginInterface->closeAudioDevice(); - } - break; - } -} + g_deferredInitRunning = false; + } -} // extern "C" + TS3_PLUGIN_API int ts3plugin_init() + { + std::cout << "[Echoion] Plugin init started" << std::endl; + g_deferredInitThread = std::jthread(deferredInitialization); + return 0; + } + + TS3_PLUGIN_API void ts3plugin_shutdown() + { + std::cout << "[Echoion] Shutting down..." << std::endl; + + g_deferredInitRunning = false; + + if (g_deferredInitThread.joinable()) { + auto start = std::chrono::steady_clock::now(); + while (g_deferredInitRunning && + std::chrono::steady_clock::now() - start < + std::chrono::seconds(5)) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + + if (g_deferredInitThread.joinable()) { + if (g_deferredInitRunning) { + g_deferredInitThread.detach(); + } else { + g_deferredInitThread.join(); + } + } + } + + if (g_pluginInterface) { + g_pluginInterface->disconnectFromServer(); + } + + if (g_coreLoader) { + g_coreLoader->disableAutoReload(); + g_coreLoader->unload(); + g_coreLoader.reset(); + } + + if (g_pluginInterface) { + g_pluginInterface->shutdown(); + g_pluginInterface = nullptr; + } + + g_ts3Functions = nullptr; + g_ts3FunctionsReady = false; + + std::cout << "[Echoion] Shutdown complete" << std::endl; + } + + // 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) + { + + anyID myID = 0; + if (g_ts3Functions && + g_ts3Functions->getClientID(serverConnectionHandlerId, &myID) == + ERROR_ok) { + if (fromID == myID) { + return; + } + } + + if (g_pluginInterface) { + g_pluginInterface->onTextMessageReceived( + serverConnectionHandlerId, targetMode, fromID, message); + } + } + + // Handle client connect/disconnect + TS3_PLUGIN_API void ts3plugin_onClientMoveEvent( + uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, const char* moveMessage) + { + + if (!g_pluginInterface) { + return; + } + + if (oldChannelID == 0) { + g_pluginInterface->onClientConnected(serverConnectionHandlerId, + clientID); + } else if (newChannelID == 0) { + g_pluginInterface->onClientDisconnected(serverConnectionHandlerId, + clientID); + } else { + g_pluginInterface->onClientMoved(serverConnectionHandlerId, + clientID, newChannelID); + } + } + + TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent( + uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID, + uint64 newChannelID, int visibility, const char* timeoutMessage) + { + + if (g_pluginInterface) { + g_pluginInterface->onClientDisconnected(serverConnectionHandlerId, + clientID); + } + } + + // 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; + core->skip(0); + core->resume(); + 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()) { + reloadCoreWithInterface(); + } + } + } + + // Menu item callbacks + TS3_PLUGIN_API void + ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId, + enum PluginMenuType type, int menuItemID, + uint64 selectedItemID) + { + + if (!ensureCoreLoaded()) { + return; + } + + auto core = g_coreLoader->getCore(); + if (!core) { + return; + } + + switch (menuItemID) { + case 1: + { // Play/Pause + auto state = core->getPlaybackSummary(); + if (state) { + if (state->isPlaying && !state->isPaused) { + core->pause(); + } else if (state->isPaused) { + core->resume(); + } + } + break; + } + case 2: // Skip + core->skip(1); + break; + case 3: // Stop + core->stop(); + break; + case 4: // Hot Reload Core + reloadCoreWithInterface(); + break; + case 5: // Connect/Disconnect + if (g_pluginInterface) { + if (g_pluginInterface->isConnected()) { + g_pluginInterface->disconnectFromServer(); + } else { + // Core handles connection, just trigger reconnect + if (auto result = g_pluginInterface->reconnect(); + !result) { + std::cerr + << std::format("[Echoion] Reconnect failed: {}", + result.error().message) + << std::endl; + } + } + } + break; + } + } + + // Connection status changes + TS3_PLUGIN_API void + ts3plugin_onConnectStatusChangeEvent(uint64 serverConnectionHandlerId, + int newStatus, + unsigned int errorNumber) + { + + if (g_pluginInterface) { + g_pluginInterface->setServerConnectionHandlerId( + serverConnectionHandlerId); + } + + switch (newStatus) { + case STATUS_CONNECTING: + std::cout << "[Echoion] Connecting..." << std::endl; + break; + case STATUS_CONNECTED: + std::cout << "[Echoion] Connected" << std::endl; + if (g_pluginInterface) { + g_pluginInterface->closeAudioDevice(); + g_pluginInterface->openAudioDevice(); + } + break; + case STATUS_CONNECTION_ESTABLISHED: + std::cout << "[Echoion] Connection established" << std::endl; + break; + case STATUS_DISCONNECTED: + std::cout << "[Echoion] Disconnected" << std::endl; + if (g_pluginInterface) { + g_pluginInterface->closeAudioDevice(); + } + break; + } + } + + } // extern "C" } // namespace Echoion::Plugin diff --git a/src/PluginInterface.cpp b/src/PluginInterface.cpp index ce2b474..24da160 100644 --- a/src/PluginInterface.cpp +++ b/src/PluginInterface.cpp @@ -1,1069 +1,1222 @@ -#include "echoion/api/LoggerInterface.hpp" -#include "echoion/plugin/PluginInterface.hpp" +#include +#include "LoggerInterface.hpp" #include "teamspeak/public_definitions.h" #include "teamspeak/public_rare_definitions.h" #include #include #include -namespace Echoion::Plugin { - -PluginInterface::PluginInterface() = default; - -PluginInterface::~PluginInterface() { - if (initialized_) { - shutdown(); - } -} - -Api::Result PluginInterface::initialize(TS3Functions* ts3Functions) { - if (initialized_) { - return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, - "Plugin interface already initialized")); - } - - ts3Functions_ = ts3Functions; - - // 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_; }); - - if (stopAudioThread_) break; - - if (!audioQueue_.empty()) { - auto samples = std::move(audioQueue_.front()); - audioQueue_.pop(); - lock.unlock(); - - // Send audio data to TeamSpeak - if (ts3Functions_ && audioDeviceRegistered_ && ts3Functions_->processCustomCaptureData) { - auto res = ts3Functions_->processCustomCaptureData( - AudioDeviceConfig::DEVICE_ID, - samples.data(), - static_cast(samples.size() / AudioDeviceConfig::CHANNELS) - ); - if (res != ERROR_ok) - { - char *errorMsg = nullptr; - ts3Functions_->getErrorMessage(res, &errorMsg); - ECHOION_LOG_ERROR(std::format("Unable to register custom device: {}", errorMsg)); - ts3Functions_->freeMemory(errorMsg); - } - } - } - } - }); - - initialized_ = true; - ECHOION_LOG_INFO("PluginInterface initialized with TeamSpeak functions (audio deferred)"); - return {}; -} - -Api::Result PluginInterface::initialize() { - // Called by Core, already initialized via initialize(TS3Functions*) - return {}; -} - -Api::Result PluginInterface::shutdown() { - if (!initialized_) { - return {}; - } - - // Stop audio thread - stopAudioThread_ = true; - audioCv_.notify_all(); - if (audioThread_.joinable()) { - audioThread_.join(); - } - - // Clear audio queue - { - std::lock_guard lock(audioMutex_); - while (!audioQueue_.empty()) { - audioQueue_.pop(); - } - } - - // Close audio device - closeAudioDevice(); - - // Unregister audio device - unregisterAudioDevice(); - - // Disconnect from server - if (isConnected()) { - disconnectFromServer(); - } - - // Clear callbacks - { - std::lock_guard lock(eventMutex_); - eventCallbacks_.clear(); - } - - ts3Functions_ = nullptr; - initialized_ = false; - - ECHOION_LOG_INFO("PluginInterface shutdown"); - return {}; -} - -Api::Result> PluginInterface::getClients() +namespace Echoion::Plugin { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - std::vector clients; - anyID* clientList = nullptr; + PluginInterface::PluginInterface() = default; - 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; - info.id = clientList[i]; - - // Get nickname - char* name = nullptr; - if (ts3Functions_->getClientVariableAsString( - serverConnectionHandlerId_, clientList[i], CLIENT_NICKNAME, - &name) == ERROR_ok && - name) { - info.nickname = name; - ts3Functions_->freeMemory(name); - } - - // 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); - } - - // 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); + PluginInterface::~PluginInterface() + { + if (initialized_) { + shutdown(); } - ts3Functions_->freeMemory(clientList); } - return clients; -} + Api::Result PluginInterface::initialize(TS3Functions* ts3Functions) + { + if (initialized_) { + return std::unexpected( + Api::Error(Api::ErrorCode::AlreadyExists, + "Plugin interface already initialized")); + } -Api::Result> - PluginInterface::getClient(uint64_t clientId) -{ - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } + ts3Functions_ = ts3Functions; - Api::ClientInfo info; - info.id = clientId; + // 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_; + }); - // Get client nickname - char* name = nullptr; - if (ts3Functions_->getClientVariableAsString( - serverConnectionHandlerId_, static_cast(clientId), - CLIENT_NICKNAME, &name) != ERROR_ok) { - return std::nullopt; - } + if (stopAudioThread_) { + break; + } - if (name) { - info.nickname = name; - ts3Functions_->freeMemory(name); - } + if (!audioQueue_.empty()) { + auto samples = std::move(audioQueue_.front()); + audioQueue_.pop(); + lock.unlock(); - // 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); - } - - // 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) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - unsigned int error = ts3Functions_->requestClientMove(serverConnectionHandlerId_, - static_cast(clientId), channelId, "", nullptr); - - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to move client: {}", error))); - } - - return {}; -} - -Api::Result PluginInterface::kickClient(uint64_t clientId, const std::string& reason) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - unsigned int error = ts3Functions_->requestClientKickFromServer(serverConnectionHandlerId_, - static_cast(clientId), reason.c_str(), nullptr); - - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to kick client: {}", error))); - } - - return {}; -} - -Api::Result> PluginInterface::getChannels() const { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - std::vector channels; - uint64* channelList = nullptr; - - unsigned int error = ts3Functions_->getChannelList(serverConnectionHandlerId_, &channelList); - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to get channel list: {}", error))); - } - - if (channelList) { - for (int i = 0; channelList[i] != 0; ++i) { - Api::ChannelInfo info; - info.id = channelList[i]; - - char* name = nullptr; - if (ts3Functions_->getChannelVariableAsString(serverConnectionHandlerId_, - channelList[i], CHANNEL_NAME, &name) == ERROR_ok && name) { - info.name = name; - ts3Functions_->freeMemory(name); - } - - int parentId = 0; - if (ts3Functions_->getChannelVariableAsInt(serverConnectionHandlerId_, - channelList[i], CHANNEL_UNIQUE_IDENTIFIER, &parentId) == ERROR_ok) { - info.parentId = parentId; - } - - channels.push_back(info); - } - ts3Functions_->freeMemory(channelList); - } - - return channels; -} - -Api::Result> PluginInterface::getChannel(uint64_t channelId) const { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - Api::ChannelInfo info; - info.id = channelId; - - char* name = nullptr; - if (ts3Functions_->getChannelVariableAsString(serverConnectionHandlerId_, - channelId, CHANNEL_NAME, &name) != ERROR_ok) { - return std::nullopt; - } - - if (name) { - info.name = name; - ts3Functions_->freeMemory(name); - } - - return info; -} - -Api::Result PluginInterface::sendTextMessage(uint64_t targetId, const std::string& message) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - unsigned int error = ts3Functions_->requestSendPrivateTextMsg(serverConnectionHandlerId_, - message.c_str(), static_cast(targetId), nullptr); - - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to send text message: {}", error))); - } - - return {}; -} - -Api::Result PluginInterface::sendChannelMessage(uint64_t channelId, const std::string& message) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - unsigned int error = ts3Functions_->requestSendChannelTextMsg(serverConnectionHandlerId_, - message.c_str(), channelId, nullptr); - - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to send channel message: {}", error))); - } - - return {}; -} - -Api::Result PluginInterface::sendServerMessage(const std::string& message) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - unsigned int error = ts3Functions_->requestSendServerTextMsg(serverConnectionHandlerId_, - message.c_str(), nullptr); - - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to send server message: {}", error))); - } - - return {}; -} - -Api::Result - PluginInterface::sendAudioData(const std::span& data) -{ - static int callCount = 0; - static int nonZeroTotal = 0; - callCount++; - - // 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++; + // Send audio data to TeamSpeak + if (ts3Functions_ && audioDeviceRegistered_ && + ts3Functions_->processCustomCaptureData) { + auto res = ts3Functions_->processCustomCaptureData( + AudioDeviceConfig::DEVICE_ID, + samples.data(), + static_cast(samples.size() / + AudioDeviceConfig::CHANNELS)); + if (res != ERROR_ok) { + char* errorMsg = nullptr; + ts3Functions_->getErrorMessage(res, &errorMsg); + ECHOION_LOG_ERROR(std::format( + "Unable to register custom device: {}", + errorMsg)); + ts3Functions_->freeMemory(errorMsg); + } + } + } } - 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())); - } + }); - 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")); - } - - 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")); - } - - 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(); -} - -Api::Result PluginInterface::setWhisperList(const std::vector& clientIds) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - anyID clientId = 0; - if (ts3Functions_->getClientID(serverConnectionHandlerId_, &clientId) != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - "Failed to get own client ID")); - } - - // Convert to anyID array (null-terminated) - std::vector targets; - for (auto id : clientIds) { - targets.push_back(static_cast(id)); - } - targets.push_back(0); // Null terminate - - unsigned int error = ts3Functions_->requestClientSetWhisperList(serverConnectionHandlerId_, - clientId, nullptr, targets.data(), nullptr); - - if (error != ERROR_ok) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to set whisper list: {}", error))); - } - - return {}; -} - -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) { - std::lock_guard lock(eventMutex_); - std::erase_if(eventCallbacks_, [&callback](const auto& cb) { - return cb.target_type() == callback.target_type(); - }); -} - -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; - - broadcastEvent(Api::PluginEvent{ - .type = Api::PluginEventType::ClientConnected, - .clientId = clientId, - .timestamp = std::chrono::system_clock::now() - }); -} - -void PluginInterface::onClientDisconnected(uint64_t serverConnectionHandlerId, uint64_t clientId) { - if (serverConnectionHandlerId != serverConnectionHandlerId_) return; - - broadcastEvent(Api::PluginEvent{ - .type = Api::PluginEventType::ClientDisconnected, - .clientId = clientId, - .timestamp = std::chrono::system_clock::now() - }); -} - -void PluginInterface::onClientMoved(uint64_t serverConnectionHandlerId, uint64_t clientId, - uint64_t newChannelId) { - if (serverConnectionHandlerId != serverConnectionHandlerId_) return; - - broadcastEvent(Api::PluginEvent{ - .type = Api::PluginEventType::ClientMoved, - .clientId = clientId, - .targetChannelId = newChannelId, - .timestamp = std::chrono::system_clock::now() - }); -} - -void PluginInterface::onTextMessageReceived(uint64_t serverConnectionHandlerId, uint64_t targetMode, - uint64_t fromId, const std::string& message) { - if (serverConnectionHandlerId != serverConnectionHandlerId_) return; - - broadcastEvent(Api::PluginEvent{ - .type = Api::PluginEventType::TextMessageReceived, - .clientId = fromId, - .message = message, - .timestamp = std::chrono::system_clock::now() - }); -} - -void PluginInterface::onVoiceDataReceived(uint64_t serverConnectionHandlerId, uint64_t clientId, - const std::span& data) { - if (serverConnectionHandlerId != serverConnectionHandlerId_) return; - - broadcastEvent(Api::PluginEvent{ - .type = Api::PluginEventType::VoiceDataReceived, - .clientId = clientId, - .timestamp = std::chrono::system_clock::now() - }); -} - -Api::Result PluginInterface::connectToServer(const Api::ServerConfig& config) { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - currentServerConfig_ = config; - - // Prepare default channel array - const char* defaultChannelArray[2] = {nullptr, nullptr}; - std::string defaultChannelStr; - if (config.defaultChannelId.has_value()) { - defaultChannelStr = config.defaultChannelId.value(); - defaultChannelArray[0] = defaultChannelStr.c_str(); - } - - unsigned int error = ts3Functions_->guiConnect( - PLUGIN_CONNECT_TAB_CURRENT, "current", std::format("{}:{}",config.address.c_str(),config.port).c_str(), - config.serverPassword.c_str(), config.nickname.c_str(), - defaultChannelStr.c_str(), "", "", "", "", "", "", "", "", - &serverConnectionHandlerId_); - - if (error != ERROR_ok) { - serverConnectionHandlerId_ = 0; - char *msg; - ts3Functions_->getErrorMessage(error, &msg); - ECHOION_LOG_ERROR(std::format("GUI Connect failed: {}", msg)); - ts3Functions_->freeMemory(msg); - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - std::format("Failed to start connection: {}", error))); - } - - // Open audio device - auto audioResult = openAudioDevice(); - if (!audioResult) { - ECHOION_LOG_WARNING("Failed to open audio device, continuing without audio"); - } - - ECHOION_LOG_INFO(std::format("Connecting to server {}:{} as {}", - config.address, config.port, config.nickname)); - - return {}; -} - -Api::Result PluginInterface::disconnectFromServer() { - if (!initialized_ || !ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Plugin interface not initialized")); - } - - if (serverConnectionHandlerId_ == 0) { - return {}; - } - - // Close audio device first - closeAudioDevice(); - // Stop connection - unsigned int error = ts3Functions_->stopConnection(serverConnectionHandlerId_, "Echoion Bot disconnecting"); - if (error != ERROR_ok) { - ECHOION_LOG_WARNING(std::format("Error stopping connection: {}", error)); - } - - // Destroy connection handler - error = ts3Functions_->destroyServerConnectionHandler(serverConnectionHandlerId_); - if (error != ERROR_ok) { - ECHOION_LOG_WARNING(std::format("Error destroying connection handler: {}", error)); - } - - serverConnectionHandlerId_ = 0; - ECHOION_LOG_INFO("Disconnected from server"); - - return {}; -} - -bool PluginInterface::isConnected() const { - if (!initialized_ || !ts3Functions_ || serverConnectionHandlerId_ == 0) { - return false; - } - - int status = 0; - if (ts3Functions_->getConnectionStatus(serverConnectionHandlerId_, &status) != ERROR_ok) { - return false; - } - - return status == STATUS_CONNECTION_ESTABLISHED; -} - -Api::Result PluginInterface::reconnect() { - // Disconnect first - auto disconnectResult = disconnectFromServer(); - if (!disconnectResult) { - return disconnectResult; - } - - // Small delay to ensure clean disconnect - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - - // Reconnect with stored config - return connectToServer(currentServerConfig_); -} - -Api::Result PluginInterface::registerAudioDevice() { - ECHOION_LOG_DEBUG("registerAudioDevice called"); - - if (!ts3Functions_) { - ECHOION_LOG_ERROR("registerAudioDevice: ts3Functions_ is null"); - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "TS3 functions not available")); - } - - if (audioDeviceRegistered_) { - ECHOION_LOG_DEBUG("registerAudioDevice: already registered"); - return {}; - } - - // Check if registerCustomDevice is available (null pointer check) - if (!ts3Functions_->registerCustomDevice) { - ECHOION_LOG_WARNING("registerCustomDevice not available in this TeamSpeak version"); - return std::unexpected(Api::Error(Api::ErrorCode::NotSupported, - "Custom audio devices not supported by this TeamSpeak version")); - } - - // Register custom device for both capture and playback - ECHOION_LOG_DEBUG(std::format("Registering device: {} at {}Hz, {}ch", - AudioDeviceConfig::DEVICE_ID, AudioDeviceConfig::SAMPLE_RATE, AudioDeviceConfig::CHANNELS)); - - unsigned int error = ts3Functions_->registerCustomDevice( - AudioDeviceConfig::DEVICE_ID, - AudioDeviceConfig::DEVICE_NAME, - AudioDeviceConfig::SAMPLE_RATE, - AudioDeviceConfig::CHANNELS, - AudioDeviceConfig::SAMPLE_RATE, - AudioDeviceConfig::CHANNELS - ); - - if (error != ERROR_ok) { - ECHOION_LOG_ERROR(std::format("registerCustomDevice failed: {}", error)); - return std::unexpected(Api::Error(Api::ErrorCode::PluginError, - std::format("Failed to register custom audio device: {}", error))); - } - - audioDeviceRegistered_ = true; - ECHOION_LOG_INFO("Audio device registered successfully"); - return {}; -} - -Api::Result PluginInterface::unregisterAudioDevice() { - if (!ts3Functions_) { - return {}; - } - - if (!audioDeviceRegistered_) { - return {}; - } - - closeAudioDevice(); - - // Check if unregisterCustomDevice is available - if (!ts3Functions_->unregisterCustomDevice) { - ECHOION_LOG_WARNING("unregisterCustomDevice not available"); - audioDeviceRegistered_ = false; - return {}; - } - - unsigned int error = ts3Functions_->unregisterCustomDevice(AudioDeviceConfig::DEVICE_ID); - if (error != ERROR_ok) { - ECHOION_LOG_WARNING(std::format("Failed to unregister audio device: {}", error)); - } - - audioDeviceRegistered_ = false; - ECHOION_LOG_INFO("Audio device unregistered"); - return {}; -} - -Api::Result PluginInterface::openAudioDevice() { - if (auto res = closeAudioDevice(); !res.has_value()) - { - ECHOION_LOG_ERROR(std::format("Not closed devices: {}",res.error().toString())); - } - - ECHOION_LOG_DEBUG("openAudioDevice called"); - - if (!ts3Functions_) { - ECHOION_LOG_ERROR("openAudioDevice: ts3Functions_ is null"); - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "TS3 functions not available")); - } - - if (!audioDeviceRegistered_) { - ECHOION_LOG_ERROR("openAudioDevice: device not registered"); - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Audio device not registered")); - } - - if (audioDeviceOpen_) { - ECHOION_LOG_DEBUG("openAudioDevice: already open"); - return {}; - } - - if (serverConnectionHandlerId_ == 0) { - ECHOION_LOG_ERROR("openAudioDevice: not connected (handler=0)"); - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Not connected to server")); - } - - // Close any existing device first (in case it was left open) - ECHOION_LOG_DEBUG("Closing any existing device first..."); - ts3Functions_->closePlaybackDevice(serverConnectionHandlerId_); - ts3Functions_->closeCaptureDevice(serverConnectionHandlerId_); - - ECHOION_LOG_DEBUG("Opening playback device..."); - unsigned int err = ts3Functions_->openPlaybackDevice(serverConnectionHandlerId_, - "custom", AudioDeviceConfig::DEVICE_ID); - - if (err == ERROR_sound_device_already_registerred) { - ECHOION_LOG_WARNING("Playback device already registered, treating as open"); - audioDeviceOpen_ = true; - return {}; - } - - if (err != ERROR_ok) { - char *msg; - ts3Functions_->getErrorMessage(err, &msg); - std::string errStr = msg; - ts3Functions_->freeMemory(msg); - ECHOION_LOG_ERROR(std::format("openPlaybackDevice failed: {}", errStr)); - return std::unexpected(Api::Error(Api::ErrorCode::PluginError, - std::format("Failed to open playback device: {}", errStr))); - } - - ECHOION_LOG_DEBUG("Opening capture device..."); - err = ts3Functions_->openCaptureDevice(serverConnectionHandlerId_, - "custom", AudioDeviceConfig::DEVICE_ID); - - if (err != ERROR_ok && err != ERROR_sound_device_already_registerred) { - char *msg; - ts3Functions_->getErrorMessage(err, &msg); - std::string errStr = msg; - ts3Functions_->freeMemory(msg); - ECHOION_LOG_WARNING( - std::format("Failed to open capture device: {}", errStr)); - } - - audioDeviceOpen_ = true; - ECHOION_LOG_INFO("Audio device opened successfully"); - - // 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() { - if (!ts3Functions_ || serverConnectionHandlerId_ == 0) { - return {}; - } - - if (!audioDeviceOpen_) { - return {}; - } - - unsigned int error = ts3Functions_->closePlaybackDevice(serverConnectionHandlerId_); - if (error != ERROR_ok) { - ECHOION_LOG_WARNING(std::format("Error closing playback device: {}", error)); - } - - error = ts3Functions_->closeCaptureDevice(serverConnectionHandlerId_); - if (error != ERROR_ok) { - ECHOION_LOG_WARNING(std::format("Error closing capture device: {}", error)); - } - - audioDeviceOpen_ = false; - ECHOION_LOG_INFO("Audio device closed"); - return {}; -} - -bool PluginInterface::isAudioDeviceOpen() const { - return audioDeviceOpen_; -} - -void PluginInterface::setServerConnectionHandlerId(uint64_t handlerId) { - serverConnectionHandlerId_ = handlerId; -} - -uint64_t PluginInterface::getServerConnectionHandlerId() const { - return serverConnectionHandlerId_; -} - -void PluginInterface::broadcastEvent(const Api::PluginEvent& event) { - std::lock_guard lock(eventMutex_); - 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 { - 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: {}", i, e.what())); - } - } -} - -std::string PluginInterface::getClientName(uint64_t clientId) const { - if (!ts3Functions_) return "Unknown"; - - char* name = nullptr; - if (ts3Functions_->getClientVariableAsString(serverConnectionHandlerId_, - static_cast(clientId), CLIENT_NICKNAME, &name) == ERROR_ok && name) { - std::string result(name); - ts3Functions_->freeMemory(name); - return result; - } - return "Unknown"; -} - -std::string PluginInterface::getChannelName(uint64_t channelId) const { - if (!ts3Functions_) return "Unknown"; - - char* name = nullptr; - if (ts3Functions_->getChannelVariableAsString(serverConnectionHandlerId_, - channelId, CHANNEL_NAME, &name) == ERROR_ok && name) { - std::string result(name); - ts3Functions_->freeMemory(name); - return result; - } - return "Unknown"; -} - -std::vector PluginInterface::getCachedServerGroups(uint64_t clientId) -{ - if (!ts3Functions_) { + initialized_ = true; + ECHOION_LOG_INFO("PluginInterface initialized with TeamSpeak functions " + "(audio deferred)"); 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) { + Api::Result PluginInterface::initialize() + { + // Called by Core, already initialized via initialize(TS3Functions*) 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 + Api::Result PluginInterface::shutdown() + { + if (!initialized_) { + return {}; } - 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 + + // Stop audio thread + stopAudioThread_ = true; + audioCv_.notify_all(); + if (audioThread_.joinable()) { + audioThread_.join(); } + + // Clear audio queue + { + std::lock_guard lock(audioMutex_); + while (!audioQueue_.empty()) { + audioQueue_.pop(); + } + } + + // Close audio device + closeAudioDevice(); + + // Unregister audio device + unregisterAudioDevice(); + + // Disconnect from server + if (isConnected()) { + disconnectFromServer(); + } + + // Clear callbacks + { + std::lock_guard lock(eventMutex_); + eventCallbacks_.clear(); + } + + ts3Functions_ = nullptr; + initialized_ = false; + + ECHOION_LOG_INFO("PluginInterface shutdown"); + return {}; } - // Cache the result - auto& entry = serverGroupsCache_[clientId]; - entry.groups = groups; - entry.timestamp = std::chrono::steady_clock::now(); + Api::Result> PluginInterface::getClients() + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } - return groups; -} + std::vector clients; + anyID* clientList = nullptr; -void PluginInterface::onServerGroupByClientID( - uint64_t serverConnectionHandlerId, uint64_t clientDatabaseId, - const char* groupName, uint64_t serverGroupId, uint64_t clientId) -{ + 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 (serverConnectionHandlerId != serverConnectionHandlerId_) { - return; + if (clientList) { + for (int i = 0; clientList[i] != 0; ++i) { + Api::ClientInfo info; + info.id = clientList[i]; + + // Get nickname + char* name = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, clientList[i], + CLIENT_NICKNAME, &name) == ERROR_ok && + name) { + info.nickname = name; + ts3Functions_->freeMemory(name); + } + + // 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); + } + + // 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; } - // 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::getClient(uint64_t clientId) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } -Api::Result PluginInterface::configureAudioProfile() -{ - if (!ts3Functions_ || serverConnectionHandlerId_ == 0) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "Not connected to server")); + Api::ClientInfo info; + info.id = clientId; + + // 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); + } + + // 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); + } + + // 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; } - ECHOION_LOG_INFO("Configuring audio profile for music bot..."); + Api::Result PluginInterface::moveClient(uint64_t clientId, + uint64_t channelId) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } - // Configure preprocessor settings (noise reduction, echo cancellation, - // etc.) These settings optimize the audio for music playback rather than - // voice + unsigned int error = ts3Functions_->requestClientMove( + serverConnectionHandlerId_, static_cast(clientId), channelId, + "", nullptr); - // 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)); + if (error != ERROR_ok) { + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + std::format("Failed to move client: {}", error))); + } + + return {}; } - // 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)); + Api::Result PluginInterface::kickClient(uint64_t clientId, + const std::string& reason) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + unsigned int error = ts3Functions_->requestClientKickFromServer( + serverConnectionHandlerId_, static_cast(clientId), + reason.c_str(), nullptr); + + if (error != ERROR_ok) { + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + std::format("Failed to kick client: {}", error))); + } + + return {}; } - // 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)); + Api::Result> + PluginInterface::getChannels() const + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + std::vector channels; + uint64* channelList = nullptr; + + unsigned int error = ts3Functions_->getChannelList( + serverConnectionHandlerId_, &channelList); + if (error != ERROR_ok) { + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("Failed to get channel list: {}", error))); + } + + if (channelList) { + for (int i = 0; channelList[i] != 0; ++i) { + Api::ChannelInfo info; + info.id = channelList[i]; + + char* name = nullptr; + if (ts3Functions_->getChannelVariableAsString( + serverConnectionHandlerId_, channelList[i], + CHANNEL_NAME, &name) == ERROR_ok && + name) { + info.name = name; + ts3Functions_->freeMemory(name); + } + + int parentId = 0; + if (ts3Functions_->getChannelVariableAsInt( + serverConnectionHandlerId_, channelList[i], + CHANNEL_UNIQUE_IDENTIFIER, &parentId) == ERROR_ok) { + info.parentId = parentId; + } + + channels.push_back(info); + } + ts3Functions_->freeMemory(channelList); + } + + return channels; } - // Disable echo cancellation - error = ts3Functions_->setPreProcessorConfigValue( - serverConnectionHandlerId_, "echocancel", "false"); - if (error != ERROR_ok) { - ECHOION_LOG_WARNING( - std::format("Failed to disable echo cancellation: {}", error)); + Api::Result> + PluginInterface::getChannel(uint64_t channelId) const + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + Api::ChannelInfo info; + info.id = channelId; + + char* name = nullptr; + if (ts3Functions_->getChannelVariableAsString( + serverConnectionHandlerId_, channelId, CHANNEL_NAME, &name) != + ERROR_ok) { + return std::nullopt; + } + + if (name) { + info.name = name; + ts3Functions_->freeMemory(name); + } + + return info; } - // 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)); + Api::Result + PluginInterface::sendTextMessage(uint64_t targetId, + const std::string& message) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + unsigned int error = ts3Functions_->requestSendPrivateTextMsg( + serverConnectionHandlerId_, message.c_str(), + static_cast(targetId), nullptr); + + if (error != ERROR_ok) { + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("Failed to send text message: {}", error))); + } + + return {}; } - // 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)); + Api::Result + PluginInterface::sendChannelMessage(uint64_t channelId, + const std::string& message) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + unsigned int error = ts3Functions_->requestSendChannelTextMsg( + serverConnectionHandlerId_, message.c_str(), channelId, nullptr); + + if (error != ERROR_ok) { + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("Failed to send channel message: {}", error))); + } + + return {}; } - // 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); + Api::Result + PluginInterface::sendServerMessage(const std::string& message) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } - ECHOION_LOG_INFO("Audio profile configured successfully"); - return {}; -} + unsigned int error = ts3Functions_->requestSendServerTextMsg( + serverConnectionHandlerId_, message.c_str(), nullptr); -Api::Result PluginInterface::checkAndHandleFirstRun() -{ - if (!ts3Functions_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "TS3 functions not available")); + if (error != ERROR_ok) { + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("Failed to send server message: {}", error))); + } + + return {}; } - ECHOION_LOG_INFO("Checking for first-run setup..."); + Api::Result + PluginInterface::sendAudioData(const std::span& data) + { + static int callCount = 0; + static int nonZeroTotal = 0; + callCount++; - // 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 + // 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())); + } - char* identity = nullptr; - unsigned int error = ts3Functions_->getClientLibVersion(&identity); - if (error != ERROR_ok || !identity) { - ECHOION_LOG_WARNING( - "TeamSpeak client library not properly initialized"); + 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")); + } + + 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")); + } + + submitAudioData(data); + + return {}; + } + + void PluginInterface::submitAudioData(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) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + anyID clientId = 0; + if (ts3Functions_->getClientID(serverConnectionHandlerId_, &clientId) != + ERROR_ok) { + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + "Failed to get own client ID")); + } + + // Convert to anyID array (null-terminated) + std::vector targets; + for (auto id : clientIds) { + targets.push_back(static_cast(id)); + } + targets.push_back(0); // Null terminate + + unsigned int error = ts3Functions_->requestClientSetWhisperList( + serverConnectionHandlerId_, clientId, nullptr, targets.data(), + nullptr); + + if (error != ERROR_ok) { + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("Failed to set whisper list: {}", error))); + } + + return {}; + } + + void PluginInterface::registerEventCallback( + const Api::EventCallback& callback) + { + std::lock_guard lock(eventMutex_); + eventCallbacks_.push_back(callback); 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"); + std::format("Event callback registered, total callbacks: {}", + eventCallbacks_.size())); + } + + void PluginInterface::unregisterEventCallback( + const Api::EventCallback& callback) + { + std::lock_guard lock(eventMutex_); + std::erase_if(eventCallbacks_, [&callback](const auto& cb) { + return cb.target_type() == callback.target_type(); + }); + } + + 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; + } + + broadcastEvent( + Api::PluginEvent{.type = Api::PluginEventType::ClientConnected, + .clientId = clientId, + .timestamp = std::chrono::system_clock::now()}); + } + + void PluginInterface::onClientDisconnected( + uint64_t serverConnectionHandlerId, uint64_t clientId) + { + if (serverConnectionHandlerId != serverConnectionHandlerId_) { + return; + } + + broadcastEvent( + Api::PluginEvent{.type = Api::PluginEventType::ClientDisconnected, + .clientId = clientId, + .timestamp = std::chrono::system_clock::now()}); + } + + void PluginInterface::onClientMoved(uint64_t serverConnectionHandlerId, + uint64_t clientId, + uint64_t newChannelId) + { + if (serverConnectionHandlerId != serverConnectionHandlerId_) { + return; + } + + broadcastEvent( + Api::PluginEvent{.type = Api::PluginEventType::ClientMoved, + .clientId = clientId, + .targetChannelId = newChannelId, + .timestamp = std::chrono::system_clock::now()}); + } + + void PluginInterface::onTextMessageReceived( + uint64_t serverConnectionHandlerId, uint64_t targetMode, + uint64_t fromId, const std::string& message) + { + if (serverConnectionHandlerId != serverConnectionHandlerId_) { + return; + } + + broadcastEvent( + Api::PluginEvent{.type = Api::PluginEventType::TextMessageReceived, + .clientId = fromId, + .message = message, + .timestamp = std::chrono::system_clock::now()}); + } + + void PluginInterface::onVoiceDataReceived( + uint64_t serverConnectionHandlerId, uint64_t clientId, + const std::span& data) + { + if (serverConnectionHandlerId != serverConnectionHandlerId_) { + return; + } + + broadcastEvent( + Api::PluginEvent{.type = Api::PluginEventType::VoiceDataReceived, + .clientId = clientId, + .timestamp = std::chrono::system_clock::now()}); + } + + Api::Result + PluginInterface::connectToServer(const Api::ServerConfig& config) + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + currentServerConfig_ = config; + + // Prepare default channel array + const char* defaultChannelArray[2] = {nullptr, nullptr}; + std::string defaultChannelStr; + if (config.defaultChannelId.has_value()) { + defaultChannelStr = config.defaultChannelId.value(); + defaultChannelArray[0] = defaultChannelStr.c_str(); + } + + unsigned int error = ts3Functions_->guiConnect( + PLUGIN_CONNECT_TAB_CURRENT, "current", + std::format("{}:{}", config.address.c_str(), config.port).c_str(), + config.serverPassword.c_str(), config.nickname.c_str(), + defaultChannelStr.c_str(), "", "", "", "", "", "", "", "", + &serverConnectionHandlerId_); + + if (error != ERROR_ok) { + serverConnectionHandlerId_ = 0; + char* msg; + ts3Functions_->getErrorMessage(error, &msg); + ECHOION_LOG_ERROR(std::format("GUI Connect failed: {}", msg)); + ts3Functions_->freeMemory(msg); + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("Failed to start connection: {}", error))); + } + + // Open audio device + auto audioResult = openAudioDevice(); + if (!audioResult) { + ECHOION_LOG_WARNING( + "Failed to open audio device, continuing without audio"); + } + + ECHOION_LOG_INFO(std::format("Connecting to server {}:{} as {}", + config.address, config.port, + config.nickname)); + + return {}; + } + + Api::Result PluginInterface::disconnectFromServer() + { + if (!initialized_ || !ts3Functions_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Plugin interface not initialized")); + } + + if (serverConnectionHandlerId_ == 0) { + return {}; + } + + // Close audio device first + closeAudioDevice(); + // Stop connection + unsigned int error = ts3Functions_->stopConnection( + serverConnectionHandlerId_, "Echoion Bot disconnecting"); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Error stopping connection: {}", error)); + } + + // Destroy connection handler + error = ts3Functions_->destroyServerConnectionHandler( + serverConnectionHandlerId_); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Error destroying connection handler: {}", error)); + } + + serverConnectionHandlerId_ = 0; + ECHOION_LOG_INFO("Disconnected from server"); + + return {}; + } + + bool PluginInterface::isConnected() const + { + if (!initialized_ || !ts3Functions_ || + serverConnectionHandlerId_ == 0) { + return false; + } + + int status = 0; + if (ts3Functions_->getConnectionStatus(serverConnectionHandlerId_, + &status) != ERROR_ok) { + return false; + } + + return status == STATUS_CONNECTION_ESTABLISHED; + } + + Api::Result PluginInterface::reconnect() + { + // Disconnect first + auto disconnectResult = disconnectFromServer(); + if (!disconnectResult) { + return disconnectResult; + } + + // Small delay to ensure clean disconnect + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + // Reconnect with stored config + return connectToServer(currentServerConfig_); + } + + Api::Result PluginInterface::registerAudioDevice() + { + ECHOION_LOG_DEBUG("registerAudioDevice called"); + + if (!ts3Functions_) { + ECHOION_LOG_ERROR("registerAudioDevice: ts3Functions_ is null"); + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "TS3 functions not available")); + } + + if (audioDeviceRegistered_) { + ECHOION_LOG_DEBUG("registerAudioDevice: already registered"); + return {}; + } + + // Check if registerCustomDevice is available (null pointer check) + if (!ts3Functions_->registerCustomDevice) { + ECHOION_LOG_WARNING( + "registerCustomDevice not available in this TeamSpeak version"); + return std::unexpected( + Api::Error(Api::ErrorCode::NotSupported, + "Custom audio devices not supported by this " + "TeamSpeak version")); + } + + // Register custom device for both capture and playback + ECHOION_LOG_DEBUG(std::format("Registering device: {} at {}Hz, {}ch", + AudioDeviceConfig::DEVICE_ID, + AudioDeviceConfig::SAMPLE_RATE, + AudioDeviceConfig::CHANNELS)); + + unsigned int error = + ts3Functions_->registerCustomDevice(AudioDeviceConfig::DEVICE_ID, + AudioDeviceConfig::DEVICE_NAME, + AudioDeviceConfig::SAMPLE_RATE, + AudioDeviceConfig::CHANNELS, + AudioDeviceConfig::SAMPLE_RATE, + AudioDeviceConfig::CHANNELS); + + if (error != ERROR_ok) { + ECHOION_LOG_ERROR( + std::format("registerCustomDevice failed: {}", error)); + return std::unexpected(Api::Error( + Api::ErrorCode::PluginError, + std::format("Failed to register custom audio device: {}", + error))); + } + + audioDeviceRegistered_ = true; + ECHOION_LOG_INFO("Audio device registered successfully"); + return {}; + } + + Api::Result PluginInterface::unregisterAudioDevice() + { + if (!ts3Functions_) { + return {}; + } + + if (!audioDeviceRegistered_) { + return {}; + } + + closeAudioDevice(); + + // Check if unregisterCustomDevice is available + if (!ts3Functions_->unregisterCustomDevice) { + ECHOION_LOG_WARNING(""); + std::cerr << std::format( + "[WARNING] unregisterCustomDevice not available") + << std::endl; + audioDeviceRegistered_ = false; + return {}; + } + + unsigned int error = + ts3Functions_->unregisterCustomDevice(AudioDeviceConfig::DEVICE_ID); + if (error != ERROR_ok) { + std::cerr << std::format( + "[WARNING] Failed to unregister audio device: {}", + error) + << std::endl; + } + + audioDeviceRegistered_ = false; + std::cout << std::format("[INFO] Audio device unregistered") + << std::endl; + return {}; + } + + Api::Result PluginInterface::openAudioDevice() + { + if (auto res = closeAudioDevice(); !res.has_value()) { + ECHOION_LOG_ERROR( + std::format("Not closed devices: {}", res.error().toString())); + } + + ECHOION_LOG_DEBUG("openAudioDevice called"); + + if (!ts3Functions_) { + ECHOION_LOG_ERROR("openAudioDevice: ts3Functions_ is null"); + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "TS3 functions not available")); + } + + if (!audioDeviceRegistered_) { + ECHOION_LOG_ERROR("openAudioDevice: device not registered"); + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Audio device not registered")); + } + + if (audioDeviceOpen_) { + ECHOION_LOG_DEBUG("openAudioDevice: already open"); + return {}; + } + + if (serverConnectionHandlerId_ == 0) { + ECHOION_LOG_ERROR("openAudioDevice: not connected (handler=0)"); + return std::unexpected(Api::Error( + Api::ErrorCode::ServiceUnavailable, "Not connected to server")); + } + + // Close any existing device first (in case it was left open) + ECHOION_LOG_DEBUG("Closing any existing device first..."); + ts3Functions_->closePlaybackDevice(serverConnectionHandlerId_); + ts3Functions_->closeCaptureDevice(serverConnectionHandlerId_); + + ECHOION_LOG_DEBUG("Opening playback device..."); + unsigned int err = ts3Functions_->openPlaybackDevice( + serverConnectionHandlerId_, "custom", AudioDeviceConfig::DEVICE_ID); + + if (err == ERROR_sound_device_already_registerred) { + ECHOION_LOG_WARNING( + "Playback device already registered, treating as open"); + audioDeviceOpen_ = true; + return {}; + } + + if (err != ERROR_ok) { + char* msg; + ts3Functions_->getErrorMessage(err, &msg); + std::string errStr = msg; + ts3Functions_->freeMemory(msg); + ECHOION_LOG_ERROR( + std::format("openPlaybackDevice failed: {}", errStr)); + return std::unexpected(Api::Error( + Api::ErrorCode::PluginError, + std::format("Failed to open playback device: {}", errStr))); + } + + ECHOION_LOG_DEBUG("Opening capture device..."); + err = ts3Functions_->openCaptureDevice( + serverConnectionHandlerId_, "custom", AudioDeviceConfig::DEVICE_ID); + + if (err != ERROR_ok && err != ERROR_sound_device_already_registerred) { + char* msg; + ts3Functions_->getErrorMessage(err, &msg); + std::string errStr = msg; + ts3Functions_->freeMemory(msg); + ECHOION_LOG_WARNING( + std::format("Failed to open capture device: {}", errStr)); + } + + audioDeviceOpen_ = true; + ECHOION_LOG_INFO("Audio device opened successfully"); + + // 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() + { + if (!ts3Functions_ || serverConnectionHandlerId_ == 0) { + return {}; + } + + if (!audioDeviceOpen_) { + return {}; + } + + unsigned int error = + ts3Functions_->closePlaybackDevice(serverConnectionHandlerId_); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Error closing playback device: {}", error)); + } + + error = ts3Functions_->closeCaptureDevice(serverConnectionHandlerId_); + if (error != ERROR_ok) { + ECHOION_LOG_WARNING( + std::format("Error closing capture device: {}", error)); + } + + audioDeviceOpen_ = false; + ECHOION_LOG_INFO("Audio device closed"); + return {}; + } + + bool PluginInterface::isAudioDeviceOpen() const noexcept + { + return audioDeviceOpen_.load(); + } + + void PluginInterface::setServerConnectionHandlerId( + uint64_t handlerId) noexcept + { + serverConnectionHandlerId_ = handlerId; + } + + uint64_t PluginInterface::getServerConnectionHandlerId() const noexcept + { + return serverConnectionHandlerId_; + } + + void PluginInterface::broadcastEvent(const Api::PluginEvent& event) + { + std::lock_guard lock(eventMutex_); + 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 { + 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: {}", i, e.what())); + } + } + } + + std::string PluginInterface::getClientName(uint64_t clientId) const + { + if (!ts3Functions_) { + return "Unknown"; + } + + char* name = nullptr; + if (ts3Functions_->getClientVariableAsString( + serverConnectionHandlerId_, static_cast(clientId), + CLIENT_NICKNAME, &name) == ERROR_ok && + name) { + std::string result(name); + ts3Functions_->freeMemory(name); + return result; + } + return "Unknown"; + } + + std::string PluginInterface::getChannelName(uint64_t channelId) const + { + if (!ts3Functions_) { + return "Unknown"; + } + + char* name = nullptr; + if (ts3Functions_->getChannelVariableAsString( + serverConnectionHandlerId_, channelId, CHANNEL_NAME, &name) == + ERROR_ok && + name) { + std::string result(name); + ts3Functions_->freeMemory(name); + return result; + } + 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); } - 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 {}; } - ECHOION_LOG_INFO("TeamSpeak client is properly initialized"); - return {}; -} - } // namespace Echoion::Plugin