Merge branch 'eventbust' into 'main'

Bump CMake minimum to 4.0 for VoidLibrary toolchain

See merge request void/echoionplugin!1
This commit is contained in:
faumaray committed 2026-06-22 15:53:30 +03:00
commit df1ea8d53f
11 files changed
+2532 -2133

No files matched your search

+57 -22
View File
@@ -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) project(EchoionPlugin VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD 26)
@@ -13,20 +13,32 @@ CPMAddPackage(
OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON" OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON"
) )
add_library(EchoionPlugin SHARED file(GLOB_RECURSE PLUGIN_SOURCES
src/PluginInterface.cpp CONFIGURE_DEPENDS
src/CoreLoader.cpp "src/**.cpp"
src/Plugin.cpp
src/FileWatcher.cpp
) )
add_library(EchoionPlugin SHARED ${PLUGIN_SOURCES})
add_library(Echoion::Plugin ALIAS EchoionPlugin) add_library(Echoion::Plugin ALIAS EchoionPlugin)
target_include_directories(EchoionPlugin PRIVATE target_include_directories(EchoionPlugin PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/include
) )
target_compile_definitions(EchoionPlugin PUBLIC PLUGIN=1)
target_link_libraries(EchoionPlugin PRIVATE Echoion::Api) # 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) find_package(dylib CONFIG REQUIRED)
target_link_libraries(EchoionPlugin PRIVATE dylib) target_link_libraries(EchoionPlugin PRIVATE dylib)
@@ -34,15 +46,11 @@ target_link_libraries(EchoionPlugin PRIVATE dylib)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
target_link_libraries(EchoionPlugin PRIVATE Threads::Threads) 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) if(MSVC)
target_compile_options(EchoionPlugin PRIVATE /W4 /WX-) target_compile_options(EchoionPlugin PRIVATE /W4 /WX-)
target_compile_definitions(EchoionPlugin PRIVATE _CRT_SECURE_NO_WARNINGS) target_compile_definitions(EchoionPlugin PRIVATE _CRT_SECURE_NO_WARNINGS)
else() else()
target_compile_options(EchoionPlugin PRIVATE -Wall -Wextra -Wpedantic -fPIC) target_compile_options(EchoionPlugin PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow -fPIC)
endif() endif()
set_target_properties(EchoionPlugin PROPERTIES set_target_properties(EchoionPlugin PROPERTIES
@@ -53,19 +61,46 @@ set_target_properties(EchoionPlugin PROPERTIES
POSITION_INDEPENDENT_CODE ON POSITION_INDEPENDENT_CODE ON
) )
# Ensure dylib is compiled with -fPIC
if(TARGET dylib) if(TARGET dylib)
set_target_properties(dylib PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(dylib PROPERTIES POSITION_INDEPENDENT_CODE ON)
endif() endif()
# PackageProject.cmake configuration # Export Plugin
packageProject( target_include_directories(EchoionPlugin PUBLIC
NAME EchoionPlugin $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
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} VERSION ${PROJECT_VERSION}
NAMESPACE Echoion
BINARY_DIR ${PROJECT_BINARY_DIR}
INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include
INCLUDE_DESTINATION include
COMPATIBILITY SameMajorVersion 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
) )
+75 -60
View File
@@ -1,78 +1,93 @@
#pragma once #pragma once
#include <echoion/api.hpp>
#include <dylib.hpp>
#include "FileWatcher.hpp" #include "FileWatcher.hpp"
#include "echoion/api/ConfigTypes.hpp" #include <CoreInterface.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <dylib.hpp>
#include <filesystem>
#include <functional>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <atomic>
#include <filesystem>
#include <thread>
#include <condition_variable>
#include <queue> #include <queue>
#include <functional> #include <thread>
namespace Echoion::Plugin { namespace Echoion::Plugin
{
class CoreLoader { class CoreLoader
public: {
CoreLoader(); public:
~CoreLoader();
Api::Result<void> load(const std::filesystem::path& libraryPath); CoreLoader();
Api::Result<void> unload(); ~CoreLoader();
Api::Result<void> 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 Api::Result<void> load(const std::filesystem::path& libraryPath);
void enableAutoReload(); Api::Result<void> unload();
void disableAutoReload(); Api::Result<void>
[[nodiscard]] bool isAutoReloadEnabled() const noexcept; 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;
// Callback for hot reload completion (called after auto-reload finishes) // Automatic hot reload
using HotReloadCallback = std::function<void()>; void enableAutoReload();
void setHotReloadCallback(HotReloadCallback callback) { hotReloadCallback_ = std::move(callback); } void disableAutoReload();
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
private: // Callback for hot reload completion (called after auto-reload
Api::Result<void> loadLibraryInternal(const std::filesystem::path& path); // finishes)
Api::Result<void> unloadLibraryInternal(); using HotReloadCallback = std::function<void()>;
[[nodiscard]] Api::HotReloadState saveStateInternal(); void setHotReloadCallback(HotReloadCallback callback)
[[nodiscard]] Api::Result<void> restoreStateInternal(const Api::HotReloadState& state); {
[[nodiscard]] std::filesystem::path getTempLibraryPath(const std::filesystem::path& original) const; hotReloadCallback_ = std::move(callback);
void cleanupTempFiles(); }
std::unique_ptr<dylib::library> library_; private:
Api::CoreInterfacePtr core_;
std::filesystem::path currentLibraryPath_;
std::filesystem::path tempLibraryPath_;
std::filesystem::path configPath_;
mutable std::mutex mutex_;
std::atomic<bool> loaded_{false};
std::atomic<bool> hotReloading_{false};
// Auto reload Api::Result<void>
FileWatcher fileWatcher_; loadLibraryInternal(const std::filesystem::path& path);
std::atomic<bool> autoReloadEnabled_{false}; Api::Result<void> unloadLibraryInternal();
[[nodiscard]] Api::SerializedState saveStateInternal();
[[nodiscard]] Api::Result<void>
restoreStateInternal(const Api::SerializedState& state);
[[nodiscard]] std::filesystem::path
getTempLibraryPath(const std::filesystem::path& original) const;
void cleanupTempFiles();
// Deferred reload - waits for current track to finish std::unique_ptr<dylib::library> library_;
std::thread deferredReloadThread_; Api::CoreInterfacePtr core_;
std::atomic<bool> hasPendingReload_{false}; std::filesystem::path currentLibraryPath_;
std::filesystem::path pendingReloadPath_; std::filesystem::path tempLibraryPath_;
std::string pendingTrackId_; // Track ID that was playing when reload scheduled std::filesystem::path configPath_;
mutable std::mutex pendingReloadMutex_; mutable std::mutex mutex_;
std::atomic<bool> loaded_{false};
std::atomic<bool> hotReloading_{false};
// Hot reload completion callback // Auto reload
HotReloadCallback hotReloadCallback_; FileWatcher fileWatcher_;
std::atomic<bool> autoReloadEnabled_{false};
void onCoreFileChanged(); // Deferred reload - waits for current track to finish
void waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId); std::thread deferredReloadThread_;
[[nodiscard]] bool isPlaybackActive() const; std::atomic<bool> hasPendingReload_{false};
[[nodiscard]] bool isSameTrackPlaying(const std::string& trackId) const; 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 } // namespace Echoion::Plugin
+49 -46
View File
@@ -1,62 +1,65 @@
#pragma once #pragma once
#include <functional>
#include <filesystem>
#include <thread>
#include <atomic> #include <atomic>
#include <mutex>
#include <chrono> #include <chrono>
#include <filesystem>
#include <functional>
#include <mutex>
#include <thread>
namespace Echoion::Plugin { namespace Echoion::Plugin
{
/** /**
* @brief Simple file watcher that monitors a file for changes * @brief Simple file watcher that monitors a file for changes
* and triggers a callback when the file is modified. * and triggers a callback when the file is modified.
*/ */
class FileWatcher { class FileWatcher
public: {
using ChangeCallback = std::function<void()>; public:
FileWatcher(); using ChangeCallback = std::function<void()>;
~FileWatcher();
// Disable copy FileWatcher();
FileWatcher(const FileWatcher&) = delete; ~FileWatcher();
FileWatcher& operator=(const FileWatcher&) = delete;
/** // Disable copy
* @brief Start watching a file for changes FileWatcher(const FileWatcher&) = delete;
* @param filePath Path to the file to watch FileWatcher& operator=(const FileWatcher&) = delete;
* @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)
);
/** /**
* @brief Stop watching * @brief Start watching a file for changes
*/ * @param filePath Path to the file to watch
void stopWatching(); * @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: [[nodiscard]] bool isWatching() const noexcept;
void watchLoop();
std::filesystem::path watchedPath_; private:
ChangeCallback callback_;
std::chrono::milliseconds intervalMs_{1000};
std::atomic<bool> watching_{false};
std::atomic<bool> stopRequested_{false};
std::thread watchThread_;
std::mutex mutex_;
// Store last modification time void watchLoop();
std::filesystem::file_time_type lastWriteTime_;
std::uintmax_t lastFileSize_ = 0; std::filesystem::path watchedPath_;
}; ChangeCallback callback_;
std::chrono::milliseconds intervalMs_{1000};
std::atomic<bool> watching_{false};
std::atomic<bool> 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 } // namespace Echoion::Plugin
+143 -116
View File
@@ -1,9 +1,10 @@
#pragma once #pragma once
#include <PluginInterface.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic> #include <atomic>
#include <condition_variable> #include <condition_variable>
#include <dylib.hpp> #include <dylib.hpp>
#include <echoion/api.hpp>
#include <future> #include <future>
#include <map> #include <map>
#include <memory> #include <memory>
@@ -14,144 +15,170 @@
// TeamSpeak SDK headers // TeamSpeak SDK headers
#include "ts3_functions.h" #include "ts3_functions.h"
namespace Echoion::Plugin { namespace Echoion::Plugin
{
// Audio device configuration // Audio device configuration
struct AudioDeviceConfig { struct AudioDeviceConfig {
static constexpr const char* DEVICE_ID = "echoion_audio_device"; static constexpr const char* DEVICE_ID = "echoion_audio_device";
static constexpr const char* DEVICE_NAME = "Echoion Music Bot Audio"; static constexpr const char* DEVICE_NAME =
static constexpr int SAMPLE_RATE = "Echoion Music Bot Audio";
192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC) static constexpr int SAMPLE_RATE =
static constexpr int CHANNELS = 2; 192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC)
static constexpr int SAMPLE_SIZE = sizeof(int16_t); static constexpr int CHANNELS = 2;
}; static constexpr int SAMPLE_SIZE = sizeof(int16_t);
};
// Server groups cache entry // Server groups cache entry
struct ServerGroupsCacheEntry { struct ServerGroupsCacheEntry {
std::vector<uint64_t> groups; std::vector<uint64_t> groups;
std::chrono::steady_clock::time_point timestamp; std::chrono::steady_clock::time_point timestamp;
}; };
// Plugin implementation of IPluginInterface for the Core to use // Plugin implementation of IPluginInterface for the Core to use
class PluginInterface : public Api::IPluginInterface { class PluginInterface : public Api::IPluginInterface
public: {
PluginInterface(); public:
~PluginInterface() override;
// Initialize with TeamSpeak functions PluginInterface();
Api::Result<void> initialize(TS3Functions* ts3Functions); ~PluginInterface() override;
// IPluginInterface implementation // Initialize with TeamSpeak functions
Api::Result<void> initialize() override; Api::Result<void> initialize(TS3Functions* ts3Functions);
Api::Result<void> shutdown() override;
// Client operations // IPluginInterface implementation
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>> Api::Result<void> initialize() override;
getClients() override; Api::Result<void> shutdown() override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
// Channel operations // Client operations
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>> [[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
getChannels() const override; getClients() override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>> getChannel(uint64_t channelId) const override; [[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
// Messaging // Channel operations
Api::Result<void> sendTextMessage(uint64_t targetId, const std::string& message) override; [[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
Api::Result<void> sendChannelMessage(uint64_t channelId, const std::string& message) override; getChannels() const override;
Api::Result<void> sendServerMessage(const std::string& message) override; [[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
getChannel(uint64_t channelId) const override;
// Audio // Messaging
Api::Result<void> Api::Result<void>
sendAudioData(const std::span<const short>& data) override; sendTextMessage(uint64_t targetId,
Api::Result<void> const std::string& message) override;
setWhisperList(const std::vector<uint64_t>& clientIds) override; Api::Result<void>
sendChannelMessage(uint64_t channelId,
const std::string& message) override;
Api::Result<void>
sendServerMessage(const std::string& message) override;
// Event subscription // Audio
void registerEventCallback(const Api::EventCallback& callback) override; Api::Result<void>
void unregisterEventCallback(const Api::EventCallback& callback) override; sendAudioData(const std::span<const short>& data) override;
void clearEventCallbacks(); Api::Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) override;
// TeamSpeak event handlers (called by TeamSpeak SDK) // Event subscription
void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId); void registerEventCallback(
void onClientDisconnected(uint64_t serverConnectionHandlerId, uint64_t clientId); const Api::EventCallback& callback) override;
void onClientMoved(uint64_t serverConnectionHandlerId, uint64_t clientId, uint64_t newChannelId); void unregisterEventCallback(
void onTextMessageReceived(uint64_t serverConnectionHandlerId, uint64_t targetMode, const Api::EventCallback& callback) override;
uint64_t fromId, const std::string& message); void clearEventCallbacks();
void onVoiceDataReceived(uint64_t serverConnectionHandlerId, uint64_t clientId,
const std::span<const uint8_t>& data);
// Server group list callback (called by TeamSpeak SDK) // TeamSpeak event handlers (called by TeamSpeak SDK)
void onServerGroupByClientID(uint64_t serverConnectionHandlerId, void onClientConnected(uint64_t serverConnectionHandlerId,
uint64_t clientDatabaseId, uint64_t clientId);
const char* groupName, uint64_t serverGroupId, void onClientDisconnected(uint64_t serverConnectionHandlerId,
uint64_t clientId); 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<const uint8_t>& data);
// Server connection management (IPluginInterface implementation) // Server group list callback (called by TeamSpeak SDK)
Api::Result<void> connectToServer(const Api::ServerConfig& config) override; void onServerGroupByClientID(uint64_t serverConnectionHandlerId,
Api::Result<void> disconnectFromServer() override; uint64_t clientDatabaseId,
[[nodiscard]] bool isConnected() const override; const char* groupName,
Api::Result<void> reconnect() override; uint64_t serverGroupId,
uint64_t clientId);
// Audio device management // Server connection management (IPluginInterface implementation)
Api::Result<void> registerAudioDevice(); Api::Result<void>
Api::Result<void> unregisterAudioDevice(); connectToServer(const Api::ServerConfig& config) override;
Api::Result<void> openAudioDevice(); Api::Result<void> disconnectFromServer() override;
[[nodiscard]] bool isAudioDeviceRegistered() const { return audioDeviceRegistered_; } [[nodiscard]] bool isConnected() const override;
Api::Result<void> closeAudioDevice(); Api::Result<void> reconnect() override;
[[nodiscard]] bool isAudioDeviceOpen() const;
// Set server connection handler // Audio device management
void setServerConnectionHandlerId(uint64_t handlerId); Api::Result<void> registerAudioDevice();
[[nodiscard]] uint64_t getServerConnectionHandlerId() const; Api::Result<void> unregisterAudioDevice();
Api::Result<void> openAudioDevice();
[[nodiscard]] bool isAudioDeviceRegistered() const noexcept
{
return audioDeviceRegistered_.load();
}
Api::Result<void> closeAudioDevice();
[[nodiscard]] bool isAudioDeviceOpen() const noexcept;
// Audio data submission (for internal use) // Set server connection handler
void submitAudioData(const std::span<const short> samples); void setServerConnectionHandlerId(uint64_t handlerId) noexcept;
[[nodiscard]] uint64_t
getServerConnectionHandlerId() const noexcept;
// Automatic configuration // Audio data submission (for internal use)
Api::Result<void> configureAudioProfile(); void submitAudioData(std::span<const short> samples);
Api::Result<void> checkAndHandleFirstRun();
private: // Automatic configuration
void broadcastEvent(const Api::PluginEvent& event); Api::Result<void> configureAudioProfile();
std::string getClientName(uint64_t clientId) const; Api::Result<void> checkAndHandleFirstRun();
std::string getChannelName(uint64_t channelId) const;
// Fetch server groups for a client (returns future that completes when private:
// groups are received)
std::future<std::vector<uint64_t>> fetchServerGroups(uint64_t clientId);
// Get cached server groups (or empty if not cached) void broadcastEvent(const Api::PluginEvent& event);
std::vector<uint64_t> getCachedServerGroups(uint64_t clientId); [[nodiscard]] std::string getClientName(uint64_t clientId) const;
[[nodiscard]] std::string getChannelName(uint64_t channelId) const;
TS3Functions* ts3Functions_ = nullptr; // Fetch server groups for a client (returns future that completes
uint64_t serverConnectionHandlerId_ = 0; // when groups are received)
std::atomic<bool> initialized_{false}; [[nodiscard]] std::future<std::vector<uint64_t>>
std::atomic<bool> audioDeviceRegistered_{false}; fetchServerGroups(uint64_t clientId);
std::atomic<bool> audioDeviceOpen_{false};
std::vector<Api::EventCallback> eventCallbacks_; // Get cached server groups (or empty if not cached)
mutable std::mutex eventMutex_; [[nodiscard]] std::vector<uint64_t>
getCachedServerGroups(uint64_t clientId);
// Audio data queue TS3Functions* ts3Functions_ = nullptr;
std::queue<std::vector<short>> audioQueue_; uint64_t serverConnectionHandlerId_ = 0;
std::mutex audioMutex_; std::atomic<bool> initialized_{false};
std::condition_variable audioCv_; std::atomic<bool> audioDeviceRegistered_{false};
std::atomic<bool> stopAudioThread_{false}; std::atomic<bool> audioDeviceOpen_{false};
std::jthread audioThread_;
// Server groups cache std::vector<Api::EventCallback> eventCallbacks_;
mutable std::mutex serverGroupsMutex_; mutable std::mutex eventMutex_;
std::map<uint64_t, ServerGroupsCacheEntry> serverGroupsCache_;
std::map<uint64_t, std::promise<std::vector<uint64_t>>>
pendingServerGroupRequests_;
// Connection info // Audio data queue
Api::ServerConfig currentServerConfig_; std::queue<std::vector<short>> audioQueue_;
}; std::mutex audioMutex_;
std::condition_variable audioCv_;
std::atomic<bool> stopAudioThread_{false};
std::jthread audioThread_;
// Server groups cache
mutable std::mutex serverGroupsMutex_;
std::map<uint64_t, ServerGroupsCacheEntry> serverGroupsCache_;
std::map<uint64_t, std::promise<std::vector<uint64_t>>>
pendingServerGroupRequests_;
// Connection info
Api::ServerConfig currentServerConfig_;
};
} // namespace Echoion::Plugin } // namespace Echoion::Plugin
+10 -10
View File
@@ -66,8 +66,8 @@ enum ConnectStatus {
///< yet, we haven't been accepted by the server ///< yet, we haven't been accepted by the server
STATUS_CONNECTED, ///< The server has accepted us, we can talk and hear and 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 ///< we have a client id, but we don't have the channels
///< and clients yet, we can get server infos (welcome msg ///< and clients yet, we can get server infos (welcome msg
///< etc.) ///< etc.)
STATUS_CONNECTION_ESTABLISHING, ///< we are connected and we are visible STATUS_CONNECTION_ESTABLISHING, ///< we are connected and we are visible
STATUS_CONNECTION_ESTABLISHED, ///< we are connected and we have the client STATUS_CONNECTION_ESTABLISHED, ///< we are connected and we have the client
///< and channels available ///< and channels available
@@ -182,8 +182,8 @@ enum ChannelProperties {
///< ts3client_requestChannelDescription) ///< ts3client_requestChannelDescription)
CHANNEL_PASSWORD, ///< String. Read/Write. Password of the channel. Read CHANNEL_PASSWORD, ///< String. Read/Write. Password of the channel. Read
///< access is limited to the server. Clients will only ///< access is limited to the server. Clients will only
///< ever see the last password they attempted to use when ///< ever see the last password they attempted to use when
///< joining the channel. Always available. ///< joining the channel. Always available.
CHANNEL_CODEC, ///< Integer. Read/Write. The codec this channel is using. CHANNEL_CODEC, ///< Integer. Read/Write. The codec this channel is using.
///< One of the values from the \ref CodecType enum. Always ///< One of the values from the \ref CodecType enum. Always
///< available. ///< available.
@@ -536,8 +536,8 @@ enum ConnectionProperties {
///< client. ///< client.
CONNECTION_SERVER2CLIENT_PACKETLOSS_CONTROL, ///< Double. Probability with CONNECTION_SERVER2CLIENT_PACKETLOSS_CONTROL, ///< Double. Probability with
///< which a control packet ///< which a control packet
///< sent by the server was not ///< sent by the server was not
///< received by the client. ///< received by the client.
CONNECTION_SERVER2CLIENT_PACKETLOSS_TOTAL, ///< Double. Probability with CONNECTION_SERVER2CLIENT_PACKETLOSS_TOTAL, ///< Double. Probability with
///< which a packet sent by the ///< which a packet sent by the
///< server was not received by ///< server was not received by
@@ -553,8 +553,8 @@ enum ConnectionProperties {
///< server. ///< server.
CONNECTION_CLIENT2SERVER_PACKETLOSS_CONTROL, ///< Double. Probability with CONNECTION_CLIENT2SERVER_PACKETLOSS_CONTROL, ///< Double. Probability with
///< which a control packet ///< which a control packet
///< sent by the client was not ///< sent by the client was not
///< received by the server. ///< received by the server.
CONNECTION_CLIENT2SERVER_PACKETLOSS_TOTAL, ///< Double. Probability with CONNECTION_CLIENT2SERVER_PACKETLOSS_TOTAL, ///< Double. Probability with
///< which a packet sent by the ///< which a packet sent by the
///< client was not received by ///< client was not received by
@@ -597,8 +597,8 @@ enum ConnectionProperties {
///< the last second. ///< the last second.
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_CONTROL, ///< UInt64. Number of CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_CONTROL, ///< UInt64. Number of
///< bytes received for ///< bytes received for
///< control data in the ///< control data in the
///< last second. ///< last second.
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_TOTAL, ///< UInt64. Number of CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_TOTAL, ///< UInt64. Number of
///< bytes received in the ///< bytes received in the
///< last second. ///< last second.
+2 -2
View File
@@ -271,8 +271,8 @@ enum VirtualServerPropertiesRare {
// requestServerVariables) // requestServerVariables)
VIRTUALSERVER_LOG_SERVER, // only available on request (=> VIRTUALSERVER_LOG_SERVER, // only available on request (=>
// requestServerVariables) // requestServerVariables)
// VIRTUALSERVER_LOG_FILETRANSFER, // Moved to // VIRTUALSERVER_LOG_FILETRANSFER, // Moved to
// VirtualServerProperties due to SDK usage // VirtualServerProperties due to SDK usage
VIRTUALSERVER_MIN_CLIENT_VERSION = VIRTUALSERVER_MIN_CLIENT_VERSION =
65, // only available on request (=> requestServerVariables) 65, // only available on request (=> requestServerVariables)
VIRTUALSERVER_NAME_PHONETIC, // available when connected, always up-to-date VIRTUALSERVER_NAME_PHONETIC, // available when connected, always up-to-date
+1 -1
View File
@@ -4,9 +4,9 @@
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
#include <cstddef>
#include "plugin_definitions.h" #include "plugin_definitions.h"
#include "teamspeak/public_definitions.h" #include "teamspeak/public_definitions.h"
#include <cstddef>
/* Functions exported to plugin from main binary */ /* Functions exported to plugin from main binary */
struct TS3Functions { struct TS3Functions {
+492 -418
View File
@@ -1,424 +1,498 @@
#include "echoion/plugin/CoreLoader.hpp" #include "LoggerInterface.hpp"
#include "dylib.hpp" #include "dylib.hpp"
#include <format> #include "echoion/plugin/CoreLoader.hpp"
#include <thread>
#include <chrono> #include <chrono>
#include <format>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <thread>
namespace Echoion::Plugin {
namespace Echoion::Plugin
CoreLoader::CoreLoader() { {
cleanupTempFiles();
} CoreLoader::CoreLoader() { cleanupTempFiles(); }
void CoreLoader::enableAutoReload() { void CoreLoader::enableAutoReload()
if (autoReloadEnabled_.exchange(true)) { {
return; // Already enabled if (autoReloadEnabled_.exchange(true)) {
} return; // Already enabled
}
std::lock_guard<std::mutex> lock(mutex_);
if (!currentLibraryPath_.empty() && std::filesystem::exists(currentLibraryPath_)) { std::lock_guard<std::mutex> lock(mutex_);
ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}", currentLibraryPath_.string())); if (!currentLibraryPath_.empty() &&
std::filesystem::exists(currentLibraryPath_)) {
// Create weak pointer to avoid circular reference in lambda ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}",
std::weak_ptr<CoreLoader> weakThis = currentLibraryPath_.string()));
std::const_pointer_cast<CoreLoader>(
std::shared_ptr<const CoreLoader>(this, [](const CoreLoader*){})); fileWatcher_.startWatching(currentLibraryPath_,
[this]() { onCoreFileChanged(); });
fileWatcher_.startWatching(currentLibraryPath_, [this]() { }
onCoreFileChanged(); }
});
} void CoreLoader::disableAutoReload()
} {
autoReloadEnabled_ = false;
void CoreLoader::disableAutoReload() { fileWatcher_.stopWatching();
autoReloadEnabled_ = false; ECHOION_LOG_INFO("Auto-reload disabled");
fileWatcher_.stopWatching(); }
ECHOION_LOG_INFO("Auto-reload disabled");
} bool CoreLoader::isAutoReloadEnabled() const noexcept
{
bool CoreLoader::isAutoReloadEnabled() const noexcept { return autoReloadEnabled_.load();
return autoReloadEnabled_.load(); }
}
void CoreLoader::onCoreFileChanged()
void CoreLoader::onCoreFileChanged() { {
if (!autoReloadEnabled_.load() || hotReloading_.load()) { if (!autoReloadEnabled_.load() || hotReloading_.load()) {
return; return;
} }
ECHOION_LOG_INFO("Core file changed, scheduling hot reload after current track..."); 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)); // 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()) { // Check if playback is active - if so, defer reload
std::string currentTrackId; if (isPlaybackActive()) {
{ std::string currentTrackId;
std::lock_guard<std::mutex> lock(pendingReloadMutex_); {
hasPendingReload_ = true; std::lock_guard<std::mutex> lock(pendingReloadMutex_);
pendingReloadPath_ = currentLibraryPath_; hasPendingReload_ = true;
pendingReloadPath_ = currentLibraryPath_;
// Capture current track ID
auto state = core_->getPlaybackState(); // Capture current track ID
if (state && state->currentTrack.has_value()) { auto state = core_->getPlaybackSummary();
pendingTrackId_ = state->currentTrack->track.id; if (state && state->currentTrack.has_value()) {
currentTrackId = pendingTrackId_; pendingTrackId_ = state->currentTrack->id;
} currentTrackId = pendingTrackId_;
} }
}
ECHOION_LOG_INFO(std::format("Playback active (track: {}), deferring reload until track finishes", currentTrackId));
ECHOION_LOG_INFO(
// Start background thread to wait for track end std::format("Playback active (track: {}), deferring reload "
if (deferredReloadThread_.joinable()) { "until track finishes",
deferredReloadThread_.join(); currentTrackId));
}
deferredReloadThread_ = std::thread([this, currentTrackId]() { // Start background thread to wait for track end
waitForTrackAndReload(pendingReloadPath_, currentTrackId); if (deferredReloadThread_.joinable()) {
}); deferredReloadThread_.join();
} else { }
// No playback, reload immediately deferredReloadThread_ = std::thread([this, currentTrackId]() {
auto result = hotReload(currentLibraryPath_); waitForTrackAndReload(pendingReloadPath_, currentTrackId);
if (!result) { });
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message)); } else {
} else { // No playback, reload immediately
ECHOION_LOG_INFO("Auto hot-reload completed successfully"); auto result = hotReload(currentLibraryPath_);
// Notify Plugin to re-register callbacks if (!result) {
if (hotReloadCallback_) { ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}",
hotReloadCallback_(); result.error().message));
} } else {
} ECHOION_LOG_INFO("Auto hot-reload completed successfully");
} // Notify Plugin to re-register callbacks
} if (hotReloadCallback_) {
hotReloadCallback_();
bool CoreLoader::isPlaybackActive() const { }
if (!core_) { }
return false; }
} }
auto state = core_->getPlaybackState(); bool CoreLoader::isPlaybackActive() const
if (!state) { {
return false; if (!core_) {
} return false;
}
// Check if currently playing a track
return state->isPlaying && state->currentTrack.has_value(); auto state = core_->getPlaybackSummary();
} if (!state) {
return false;
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const { }
if (!core_ || trackId.empty()) {
return false; // Check if currently playing a track
} return state->isPlaying && state->currentTrack.has_value();
}
auto state = core_->getPlaybackState();
if (!state || !state->currentTrack.has_value()) { bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
return false; {
} if (!core_ || trackId.empty()) {
return false;
return state->currentTrack->track.id == trackId; }
}
auto state = core_->getPlaybackSummary();
void CoreLoader::waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId) { if (!state || !state->currentTrack.has_value()) {
ECHOION_LOG_INFO(std::format("Waiting for track {} to finish before reload...", trackId)); return false;
}
// Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS track) return state->currentTrack->id == trackId;
while (isSameTrackPlaying(trackId)) { }
std::this_thread::sleep_for(std::chrono::milliseconds(500));
} void CoreLoader::waitForTrackAndReload(
const std::filesystem::path& targetPath, const std::string& trackId)
ECHOION_LOG_INFO("Track finished, starting hot reload"); {
ECHOION_LOG_INFO(std::format(
// Clear pending flag "Waiting for track {} to finish before reload...", trackId));
{
std::lock_guard<std::mutex> lock(pendingReloadMutex_); // Poll every 500ms to check if the specific track finished
hasPendingReload_ = false; // (playback may continue with next track, but we only care about THIS
pendingTrackId_.clear(); // track)
} while (isSameTrackPlaying(trackId)) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// Now do the reload }
auto result = hotReload(targetPath);
if (!result) { ECHOION_LOG_INFO("Track finished, starting hot reload");
ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}", result.error().message));
} else { // Clear pending flag
ECHOION_LOG_INFO("Deferred hot-reload completed successfully"); {
// Notify Plugin to re-register callbacks std::lock_guard<std::mutex> lock(pendingReloadMutex_);
if (hotReloadCallback_) { hasPendingReload_ = false;
hotReloadCallback_(); pendingTrackId_.clear();
} }
}
} // Now do the reload
auto result = hotReload(targetPath);
CoreLoader::~CoreLoader() { if (!result) {
// Stop any deferred reload thread ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}",
if (deferredReloadThread_.joinable()) { result.error().message));
// We can't really stop it gracefully, but we can detach it } else {
// to avoid hanging on shutdown ECHOION_LOG_INFO("Deferred hot-reload completed successfully");
deferredReloadThread_.detach(); // Notify Plugin to re-register callbacks
} if (hotReloadCallback_) {
unload(); hotReloadCallback_();
cleanupTempFiles(); }
} }
}
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath) {
std::lock_guard<std::mutex> lock(mutex_); CoreLoader::~CoreLoader()
{
if (loaded_) { // Stop any deferred reload thread
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already loaded")); if (deferredReloadThread_.joinable()) {
} // We can't really stop it gracefully, but we can detach it
// to avoid hanging on shutdown
if (!std::filesystem::exists(libraryPath)) { deferredReloadThread_.detach();
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, }
std::format("Library not found: {}", libraryPath.string()))); unload();
} cleanupTempFiles();
}
tempLibraryPath_ = getTempLibraryPath(libraryPath);
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
try { {
std::filesystem::copy_file(libraryPath, tempLibraryPath_, std::lock_guard<std::mutex> lock(mutex_);
std::filesystem::copy_options::overwrite_existing);
} catch (const std::exception& e) { if (loaded_) {
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
std::format("Failed to copy library to temp: {}", e.what()))); "Core already loaded"));
} }
auto result = loadLibraryInternal(tempLibraryPath_); if (!std::filesystem::exists(libraryPath)) {
if (result) { return std::unexpected(Api::Error(
currentLibraryPath_ = libraryPath; Api::ErrorCode::NotFound,
} else { std::format("Library not found: {}", libraryPath.string())));
std::error_code ec; }
std::filesystem::remove(tempLibraryPath_, ec);
} tempLibraryPath_ = getTempLibraryPath(libraryPath);
return result; try {
} std::filesystem::copy_file(
libraryPath, tempLibraryPath_,
Api::Result<void> CoreLoader::unload() { std::filesystem::copy_options::overwrite_existing);
std::lock_guard<std::mutex> lock(mutex_); } catch (const std::exception& e) {
return std::unexpected(Api::Error(
auto result = unloadLibraryInternal(); Api::ErrorCode::UnknownError,
std::format("Failed to copy library to temp: {}", e.what())));
if (!tempLibraryPath_.empty()) { }
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec); auto result = loadLibraryInternal(tempLibraryPath_);
} if (result) {
currentLibraryPath_ = libraryPath;
return result; } else {
} std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
Api::Result<void> CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { }
std::lock_guard<std::mutex> lock(mutex_);
return result;
if (!loaded_) { }
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No core loaded to reload"));
} Api::Result<void> CoreLoader::unload()
{
hotReloading_ = true; std::lock_guard<std::mutex> lock(mutex_);
ECHOION_LOG_INFO("Starting hot reload with temp file..."); auto result = unloadLibraryInternal();
auto state = saveStateInternal(); if (!tempLibraryPath_.empty()) {
std::error_code ec;
auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; std::filesystem::remove(tempLibraryPath_, ec);
}
if (!std::filesystem::exists(targetPath)) {
hotReloading_ = false; return result;
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, }
std::format("New library not found: {}", targetPath.string())));
} Api::Result<void>
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
std::filesystem::path newTempPath = getTempLibraryPath(targetPath); {
std::lock_guard<std::mutex> lock(mutex_);
try {
std::filesystem::copy_file(targetPath, newTempPath, if (!loaded_) {
std::filesystem::copy_options::overwrite_existing); return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
} catch (const std::exception& e) { "No core loaded to reload"));
hotReloading_ = false; }
std::error_code ec;
std::filesystem::remove(newTempPath, ec); hotReloading_ = true;
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
std::format("Failed to copy new library to temp: {}", e.what()))); ECHOION_LOG_INFO("Starting hot reload with temp file...");
}
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
auto unloadResult = unloadLibraryInternal(); Api::StateBlob stateBlob;
if (!unloadResult) { if (core_) {
hotReloading_ = false; stateBlob = core_->saveState();
std::error_code ec; ECHOION_LOG_INFO(
std::filesystem::remove(newTempPath, ec); std::format("Saved state: version={}, size={} bytes",
return unloadResult; stateBlob.version, stateBlob.size()));
} }
std::error_code ec; auto targetPath =
std::filesystem::remove(tempLibraryPath_, ec); newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
tempLibraryPath_ = newTempPath;
if (!std::filesystem::exists(targetPath)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50)); hotReloading_ = false;
return std::unexpected(Api::Error(
auto loadResult = loadLibraryInternal(tempLibraryPath_); Api::ErrorCode::NotFound,
if (!loadResult) { std::format("New library not found: {}", targetPath.string())));
hotReloading_ = false; }
return loadResult;
} std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
auto restoreResult = restoreStateInternal(state); try {
if (!restoreResult) { std::filesystem::copy_file(
ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", restoreResult.error().message)); targetPath, newTempPath,
} std::filesystem::copy_options::overwrite_existing);
} catch (const std::exception& e) {
currentLibraryPath_ = targetPath; hotReloading_ = false;
hotReloading_ = false; std::error_code ec;
std::filesystem::remove(newTempPath, ec);
ECHOION_LOG_INFO("Hot reload complete"); return std::unexpected(
return {}; Api::Error(Api::ErrorCode::UnknownError,
} std::format("Failed to copy new library to temp: {}",
e.what())));
bool CoreLoader::isLoaded() const noexcept { }
return loaded_.load();
} auto unloadResult = unloadLibraryInternal();
if (!unloadResult) {
Api::CoreInterfacePtr CoreLoader::getCore() const { hotReloading_ = false;
std::lock_guard<std::mutex> lock(mutex_); std::error_code ec;
return core_; std::filesystem::remove(newTempPath, ec);
} return unloadResult;
}
void CoreLoader::setConfigPath(const std::filesystem::path& configPath) {
std::lock_guard<std::mutex> lock(mutex_); std::error_code ec;
configPath_ = configPath; std::filesystem::remove(tempLibraryPath_, ec);
} tempLibraryPath_ = newTempPath;
std::filesystem::path CoreLoader::getConfigPath() const { std::this_thread::sleep_for(std::chrono::milliseconds(50));
std::lock_guard<std::mutex> lock(mutex_);
return configPath_; auto loadResult = loadLibraryInternal(tempLibraryPath_);
} if (!loadResult) {
hotReloading_ = false;
bool CoreLoader::isHotReloading() const noexcept { return loadResult;
return hotReloading_.load(); }
}
// Step 4: Ask new Core to restore state (it handles migration
Api::Result<void> CoreLoader::loadLibraryInternal(const std::filesystem::path& path) { // internally)
try { if (!stateBlob.empty()) {
ECHOION_LOG_INFO(std::format("Loading core library: {}", path.string())); auto coreVersion = core_->getStateFormatVersion();
// Use no decorations - the path already has the correct extension (.ts) auto stateVersion = stateBlob.version;
library_ = std::make_unique<dylib::library>(path.string(), dylib::decorations::none());
ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}",
auto createFunc = library_->get_function<Api::CoreInterfacePtr()>("CreateCore"); stateVersion, coreVersion));
auto versionFunc = library_->get_function<const char*()>("GetApiVersion");
auto compatibleFunc = library_->get_function<bool(uint32_t, uint32_t)>("IsApiCompatible"); if (core_->canRestoreStateVersion(stateVersion)) {
auto restoreResult = core_->restoreState(stateBlob);
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) { if (!restoreResult) {
library_.reset(); ECHOION_LOG_ERROR(
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, std::format("Failed to restore state: {}",
std::format("API version mismatch. Expected {}.{}, got {}", restoreResult.error().message));
Api::VERSION_MAJOR, Api::VERSION_MINOR, versionFunc())));
} // Check if it's a version issue
if (restoreResult.error().code ==
core_ = createFunc(); Api::ErrorCode::IncompatibleVersion) {
if (!core_) { // Signal user to update/restart
library_.reset(); ECHOION_LOG_WARNING("State version incompatible. "
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, "User needs to update/restart.");
"Failed to create core instance")); // Optionally: notify through plugin interface
} }
auto initResult = core_->initialize(configPath_); // Continue with empty state - graceful degradation
if (!initResult) { } else {
core_.reset(); ECHOION_LOG_INFO("State restored successfully");
library_.reset(); }
return initResult; } else {
} ECHOION_LOG_WARNING(std::format(
"Cannot restore state v{} in Core v{}. "
loaded_ = true; "Version age exceeds maximum supported ({} versions).",
stateVersion, coreVersion,
ECHOION_LOG_INFO(std::format("Core library loaded (API version: {})", versionFunc())); Api::MAX_SUPPORTED_STATE_VERSION_AGE));
return {}; // Continue with empty state
}
} catch (const dylib::load_error& e) { }
return std::unexpected(Api::Error(Api::ErrorCode::PluginError,
std::format("Failed to load library: {}", e.what()))); currentLibraryPath_ = targetPath;
} catch (const dylib::symbol_error& e) { hotReloading_ = false;
return std::unexpected(Api::Error(Api::ErrorCode::PluginError,
std::format("Failed to find symbol: {}", e.what()))); ECHOION_LOG_INFO("Hot reload complete");
} catch (const std::exception& e) { return {};
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, }
std::format("Unexpected error: {}", e.what())));
} bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); }
}
Api::CoreInterfacePtr CoreLoader::getCore() const
Api::Result<void> CoreLoader::unloadLibraryInternal() { {
if (!loaded_) { std::lock_guard<std::mutex> lock(mutex_);
return {}; return core_;
} }
ECHOION_LOG_INFO("Unloading core library..."); void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
{
if (core_) { std::lock_guard<std::mutex> lock(mutex_);
core_->shutdown(); configPath_ = configPath;
core_.reset(); }
}
std::filesystem::path CoreLoader::getConfigPath() const
library_.reset(); {
std::lock_guard<std::mutex> lock(mutex_);
loaded_ = false; return configPath_;
ECHOION_LOG_INFO("Core library unloaded"); }
return {};
} bool CoreLoader::isHotReloading() const noexcept
{
Api::HotReloadState CoreLoader::saveStateInternal() { return hotReloading_.load();
if (!core_) { }
return Api::HotReloadState{};
} Api::Result<void>
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
auto state = core_->prepareForHotReload(); {
if (state) { try {
return *state;
} std::cout << std::format("[Echoion] Loading core library: {}",
path.string())
ECHOION_LOG_WARNING("Failed to save state for hot reload"); << std::endl;
return Api::HotReloadState{}; // Use no decorations - the path already has the correct extension
} // (.ts)
library_ = std::make_unique<dylib::library>(
Api::Result<void> CoreLoader::restoreStateInternal(const Api::HotReloadState& state) { path.string(), dylib::decorations::none());
if (!core_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, auto createFunc =
"Core not available for state restore")); library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
} auto versionFunc =
library_->get_function<const char*()>("GetApiVersion");
return core_->restoreAfterHotReload(state); auto compatibleFunc =
} library_->get_function<bool(uint32_t, uint32_t)>(
"IsApiCompatible");
std::filesystem::path CoreLoader::getTempLibraryPath(const std::filesystem::path& original) const {
auto tempDir = std::filesystem::temp_directory_path(); if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
auto filename = original.filename().string(); library_.reset();
return std::unexpected(Api::Error(
auto now = std::chrono::system_clock::now(); Api::ErrorCode::InvalidArgument,
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::format("API version mismatch. Expected {}.{}, got {}",
now.time_since_epoch()).count(); Api::VERSION_MAJOR, Api::VERSION_MINOR,
versionFunc())));
// Use the same extension as the original file (.ts for TeamSpeak plugin) }
#ifdef _WIN32
auto tempName = std::format("echoion_{}_{}.dll", ms, core_ = createFunc();
std::hash<std::thread::id>{}(std::this_thread::get_id())); if (!core_) {
#else library_.reset();
auto tempName = std::format("echoion_{}_{}.ts", ms, return std::unexpected(
std::hash<std::thread::id>{}(std::this_thread::get_id())); Api::Error(Api::ErrorCode::UnknownError,
#endif "Failed to create core instance"));
}
return tempDir / tempName;
} auto initResult = core_->initialize(configPath_);
if (!initResult) {
void CoreLoader::cleanupTempFiles() { core_.reset();
auto tempDir = std::filesystem::temp_directory_path(); library_.reset();
std::error_code ec; return initResult;
}
for (const auto& entry : std::filesystem::directory_iterator(tempDir, ec)) {
if (entry.is_regular_file()) { loaded_ = true;
auto name = entry.path().filename().string();
if (name.starts_with("echoion_") && ECHOION_LOG_INFO(std::format(
(name.ends_with(".dll") || name.ends_with(".so") || name.ends_with(".ts"))) { "Core library loaded (API version: {})", versionFunc()));
std::filesystem::remove(entry.path(), ec); 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<void> 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<std::chrono::milliseconds>(
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::thread::id>{}(std::this_thread::get_id()));
#else
auto tempName = std::format(
"echoion_{}_{}.ts", ms,
std::hash<std::thread::id>{}(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 } // namespace Echoion::Plugin
+73 -69
View File
@@ -1,94 +1,98 @@
#include "echoion/plugin/FileWatcher.hpp" #include "echoion/plugin/FileWatcher.hpp"
#include <chrono>
#include <format> #include <format>
#include <iostream> #include <iostream>
#include <chrono>
namespace Echoion::Plugin { namespace Echoion::Plugin
{
FileWatcher::FileWatcher() = default; FileWatcher::FileWatcher() = default;
FileWatcher::~FileWatcher() { FileWatcher::~FileWatcher() { stopWatching(); }
stopWatching();
}
void FileWatcher::startWatching( void FileWatcher::startWatching(const std::filesystem::path& filePath,
const std::filesystem::path& filePath, ChangeCallback callback,
ChangeCallback callback, std::chrono::milliseconds intervalMs)
std::chrono::milliseconds intervalMs) { {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (watching_.load()) { if (watching_.load()) {
stopWatching(); stopWatching();
} }
watchedPath_ = filePath; watchedPath_ = filePath;
callback_ = std::move(callback); callback_ = std::move(callback);
intervalMs_ = intervalMs; intervalMs_ = intervalMs;
stopRequested_ = false; stopRequested_ = false;
// Get initial file state // Get initial file state
if (std::filesystem::exists(watchedPath_)) { if (std::filesystem::exists(watchedPath_)) {
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_); lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
lastFileSize_ = std::filesystem::file_size(watchedPath_); lastFileSize_ = std::filesystem::file_size(watchedPath_);
} }
watching_ = true; watching_ = true;
watchThread_ = std::thread(&FileWatcher::watchLoop, this); watchThread_ = std::thread(&FileWatcher::watchLoop, this);
} }
void FileWatcher::stopWatching() { void FileWatcher::stopWatching()
stopRequested_ = true; {
stopRequested_ = true;
if (watchThread_.joinable()) { if (watchThread_.joinable()) {
watchThread_.join(); watchThread_.join();
} }
watching_ = false; watching_ = false;
} }
bool FileWatcher::isWatching() const noexcept { bool FileWatcher::isWatching() const noexcept { return watching_.load(); }
return watching_.load();
}
void FileWatcher::watchLoop() { void FileWatcher::watchLoop()
while (!stopRequested_.load()) { {
// Sleep first to avoid checking immediately while (!stopRequested_.load()) {
std::this_thread::sleep_for(intervalMs_); // Sleep first to avoid checking immediately
std::this_thread::sleep_for(intervalMs_);
if (stopRequested_.load()) { if (stopRequested_.load()) {
break; break;
} }
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
if (!std::filesystem::exists(watchedPath_)) { if (!std::filesystem::exists(watchedPath_)) {
continue; continue;
} }
try { try {
auto currentWriteTime = std::filesystem::last_write_time(watchedPath_); auto currentWriteTime =
auto currentFileSize = std::filesystem::file_size(watchedPath_); std::filesystem::last_write_time(watchedPath_);
auto currentFileSize = std::filesystem::file_size(watchedPath_);
// Check if file has changed (time or size) // Check if file has changed (time or size)
if (currentWriteTime != lastWriteTime_ || currentFileSize != lastFileSize_) { if (currentWriteTime != lastWriteTime_ ||
// Update stored values currentFileSize != lastFileSize_) {
lastWriteTime_ = currentWriteTime; // Update stored values
lastFileSize_ = currentFileSize; lastWriteTime_ = currentWriteTime;
lastFileSize_ = currentFileSize;
// Trigger callback // Trigger callback
if (callback_) { if (callback_) {
try { try {
callback_(); callback_();
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << std::format("FileWatcher callback error: {}", e.what()) << std::endl; std::cerr
} << std::format("FileWatcher callback error: {}",
} e.what())
} << std::endl;
} catch (const std::exception& e) { }
// Ignore errors (file might be locked during write) }
} }
} } catch (const std::exception& e) {
} // Ignore errors (file might be locked during write)
}
}
}
} // namespace Echoion::Plugin } // namespace Echoion::Plugin
+473 -385
View File
@@ -1,460 +1,548 @@
// TeamSpeak Plugin Entry Point // TeamSpeak Plugin Entry Point
#include <ts3_functions.h>
#include <plugin_definitions.h>
#include "echoion/plugin/PluginInterface.hpp"
#include "echoion/plugin/CoreLoader.hpp" #include "echoion/plugin/CoreLoader.hpp"
#include "echoion/plugin/PluginInterface.hpp"
#include "teamspeak/public_errors.h" #include "teamspeak/public_errors.h"
#include <echoion/api.hpp> #include <CoreInterface.hpp>
#include <memory> #include <PluginTypes.hpp>
#include <cstring> #include <Types.hpp>
#include <filesystem>
#include <thread>
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <cstring>
#include <filesystem>
#include <fstream> #include <fstream>
#include <iostream>
#include <memory>
#include <mutex> #include <mutex>
#include <plugin_definitions.h>
#include <thread>
#include <ts3_functions.h>
namespace Echoion::Plugin { namespace Echoion::Plugin
// Global plugin state
static std::shared_ptr<PluginInterface> g_pluginInterface;
static std::unique_ptr<CoreLoader> 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<bool> g_deferredInitRunning{false};
static std::atomic<bool> g_deferredInitComplete{false};
static std::atomic<bool> g_ts3FunctionsReady{false};
static std::shared_ptr<TS3Functions> 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())
{ // Global plugin state
char path[512]; static std::shared_ptr<PluginInterface> g_pluginInterface;
g_ts3Functions->getPluginPath(path, 512, pluginID); static std::unique_ptr<CoreLoader> g_coreLoader;
return std::string(path) + "Echoion.ts";
} // TeamSpeak plugin info
return "./plugins/Echoion.ts"; 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<char[]> pluginID;
static std::jthread g_deferredInitThread;
static std::atomic<bool> g_deferredInitRunning{false};
static std::atomic<bool> g_deferredInitComplete{false};
static std::atomic<bool> g_ts3FunctionsReady{false};
static std::shared_ptr<TS3Functions> 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 // Required TeamSpeak plugin functions
#ifdef _WIN32 #ifdef _WIN32
#define TS3_PLUGIN_API __declspec(dllexport) #define TS3_PLUGIN_API __declspec(dllexport)
#else #else
#define TS3_PLUGIN_API __attribute__((visibility("default"))) #define TS3_PLUGIN_API __attribute__((visibility("default")))
#endif #endif
TS3_PLUGIN_API const char* ts3plugin_name() { return PLUGIN_NAME; } TS3_PLUGIN_API const char* ts3plugin_name() { return PLUGIN_NAME; }
TS3_PLUGIN_API const char* ts3plugin_version() { return PLUGIN_VERSION; } TS3_PLUGIN_API const char* ts3plugin_version() { return PLUGIN_VERSION; }
TS3_PLUGIN_API int ts3plugin_apiVersion() { return 26; } TS3_PLUGIN_API int ts3plugin_apiVersion() { return 26; }
TS3_PLUGIN_API const char* ts3plugin_author() { return PLUGIN_AUTHOR; } 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_description()
{
return PLUGIN_DESCRIPTION;
}
TS3_PLUGIN_API void ts3plugin_setFunctionPointers(const TS3Functions funcs) { TS3_PLUGIN_API void ts3plugin_setFunctionPointers(const TS3Functions funcs)
g_ts3Functions = std::make_shared<TS3Functions>(funcs); {
g_ts3Functions = std::make_shared<TS3Functions>(funcs);
if (g_ts3Functions && g_ts3Functions->getConfigPath && g_ts3Functions->getPluginPath) { if (g_ts3Functions && g_ts3Functions->getConfigPath &&
g_ts3FunctionsReady.store(true); g_ts3Functions->getPluginPath) {
std::cout << "[Echoion] TS3 function pointers set" << std::endl; g_ts3FunctionsReady.store(true);
} else { std::cout << "[Echoion] TS3 function pointers set" << std::endl;
std::cerr << "[Echoion] TS3 function pointers incomplete" << std::endl; } else {
} std::cerr << "[Echoion] TS3 function pointers incomplete"
} << std::endl;
}
}
#define _strcpy(dest, destSize, src) \ #define _strcpy(dest, destSize, src) \
{ \ { \
strncpy(dest, src, destSize - 1); \ strncpy(dest, src, destSize - 1); \
(dest)[destSize - 1] = '\0'; \ (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<CoreLoader>();
// 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++;
} }
if (!g_ts3FunctionsReady.load()) { TS3_PLUGIN_API void ts3plugin_registerPluginID(const char* id)
std::cerr << "[Echoion] TS3 functions not ready, aborting init" {
const size_t sz = strlen(id) + 1;
pluginID = std::make_unique<char[]>(sz);
_strcpy(pluginID.get(), sz, id);
std::cout << std::format("[Echoion] Plugin ID: {}", pluginID.get())
<< std::endl; << 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 { static bool ensureCoreLoaded()
// Create plugin interface {
g_pluginInterface = std::make_shared<PluginInterface>(); if (g_coreLoader && g_coreLoader->isLoaded()) {
return true;
}
// Initialize plugin interface with TS functions try {
auto result = g_pluginInterface->initialize(g_ts3Functions.get()); if (!g_coreLoader) {
if (!result) { g_coreLoader = std::make_unique<CoreLoader>();
std::cerr << std::format("[Echoion] Failed to initialize plugin interface: {}", // Set up callback for auto-reload to re-register plugin
result.error().message) << std::endl; // interface
g_deferredInitRunning = false; g_coreLoader->setHotReloadCallback([]() {
return; std::cout << "[Echoion] Auto-reload callback triggered, "
} "re-registering interface..."
<< std::endl;
reregisterPluginInterface();
});
}
// Register audio device // Pass config path to CoreLoader (Core will load config internally)
auto deviceResult = g_pluginInterface->registerAudioDevice(); g_coreLoader->setConfigPath(getConfigPath());
if (!deviceResult) { std::cout << std::format("[Echoion] Config path: {}",
std::cout << std::format("[Echoion] Audio device skipped: {}", getConfigPath().string())
deviceResult.error().message) << std::endl; << std::endl;
} else {
std::cout << "[Echoion] Audio device registered" << std::endl;
}
// Load Core library (Core will handle config loading and auto-connect) std::cout << std::format("[Echoion] Loading Core from: {}",
if (ensureCoreLoaded()) { getCorePath().string())
std::cout << "[Echoion] Core loaded successfully" << std::endl; << std::endl;
if (g_coreLoader) { auto loadResult = g_coreLoader->load(getCorePath());
g_coreLoader->enableAutoReload(); if (!loadResult) {
} std::cerr << std::format("[Echoion] Failed to load core: {}",
} else { loadResult.error().message)
std::cout << "[Echoion] Core failed to load" << std::endl; << std::endl;
} return false;
}
std::cout << "[Echoion] Initialization complete" << std::endl; // Get core and set plugin interface
g_deferredInitComplete = true; auto core = g_coreLoader->getCore();
if (core && g_pluginInterface) {
core->setPluginInterface(g_pluginInterface);
} catch (const std::exception& e) { // Register for plugin events from Core
std::cerr << std::format("[Echoion] Deferred init failed: {}", e.what()) << std::endl; g_pluginInterface->registerEventCallback(
} [core](const Api::PluginEvent& event) {
core->onPluginEvent(event);
});
g_deferredInitRunning = false; // Trigger auto-connect now that plugin interface is set
} core->triggerAutoConnect();
}
TS3_PLUGIN_API int ts3plugin_init() { return true;
std::cout << "[Echoion] Plugin init started" << std::endl; } catch (const std::exception& e) {
g_deferredInitThread = std::jthread(deferredInitialization); std::cerr << std::format("[Echoion] Exception loading core: {}",
return 0; e.what())
} << std::endl;
return false;
}
}
TS3_PLUGIN_API void ts3plugin_shutdown() { void deferredInitialization()
std::cout << "[Echoion] Shutting down..." << std::endl; {
g_deferredInitRunning = true;
g_deferredInitRunning = false; // Wait 3 seconds for TeamSpeak GUI to fully initialize
std::this_thread::sleep_for(std::chrono::seconds(30));
if (g_deferredInitThread.joinable()) { // Wait for TS functions to be set (up to 2 more seconds)
auto start = std::chrono::steady_clock::now(); int waitCount = 0;
while (g_deferredInitRunning && while (!g_ts3FunctionsReady.load() && waitCount < 20) {
std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) { std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::this_thread::sleep_for(std::chrono::milliseconds(10)); waitCount++;
} }
if (g_deferredInitThread.joinable()) { if (!g_ts3FunctionsReady.load()) {
if (g_deferredInitRunning) { std::cerr << "[Echoion] TS3 functions not ready, aborting init"
g_deferredInitThread.detach(); << std::endl;
} else { g_deferredInitRunning = false;
g_deferredInitThread.join(); return;
} }
}
}
if (g_pluginInterface) { std::cout << "[Echoion] Starting deferred initialization..."
g_pluginInterface->disconnectFromServer(); << std::endl;
}
if (g_coreLoader) { try {
g_coreLoader->disableAutoReload(); // Create plugin interface
g_coreLoader->unload(); g_pluginInterface = std::make_shared<PluginInterface>();
g_coreLoader.reset();
}
if (g_pluginInterface) { // Initialize plugin interface with TS functions
g_pluginInterface->shutdown(); auto result = g_pluginInterface->initialize(g_ts3Functions.get());
g_pluginInterface = nullptr; if (!result) {
} std::cerr << std::format("[Echoion] Failed to initialize "
"plugin interface: {}",
result.error().message)
<< std::endl;
g_deferredInitRunning = false;
return;
}
g_ts3Functions = nullptr; // Register audio device
g_ts3FunctionsReady = false; 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;
}
std::cout << "[Echoion] Shutdown complete" << 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;
}
// Handle incoming text messages std::cout << "[Echoion] Initialization complete" << std::endl;
TS3_PLUGIN_API void ts3plugin_onTextMessageEvent(uint64 serverConnectionHandlerId, g_deferredInitComplete = true;
anyID targetMode, anyID toID, anyID fromID, const char* fromName,
const char* fromUniqueIdentifier, const char* message, int ffIgnored) {
anyID myID = 0; } catch (const std::exception& e) {
if (g_ts3Functions && g_ts3Functions->getClientID(serverConnectionHandlerId, &myID) == ERROR_ok) { std::cerr << std::format("[Echoion] Deferred init failed: {}",
if (fromID == myID) return; e.what())
} << std::endl;
}
if (g_pluginInterface) { g_deferredInitRunning = false;
g_pluginInterface->onTextMessageReceived(serverConnectionHandlerId, targetMode, }
fromID, message);
}
}
// Handle client connect/disconnect TS3_PLUGIN_API int ts3plugin_init()
TS3_PLUGIN_API void ts3plugin_onClientMoveEvent(uint64 serverConnectionHandlerId, {
anyID clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, std::cout << "[Echoion] Plugin init started" << std::endl;
const char* moveMessage) { g_deferredInitThread = std::jthread(deferredInitialization);
return 0;
}
if (!g_pluginInterface) return; TS3_PLUGIN_API void ts3plugin_shutdown()
{
std::cout << "[Echoion] Shutting down..." << std::endl;
if (oldChannelID == 0) { g_deferredInitRunning = false;
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, if (g_deferredInitThread.joinable()) {
anyID clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, auto start = std::chrono::steady_clock::now();
const char* timeoutMessage) { while (g_deferredInitRunning &&
std::chrono::steady_clock::now() - start <
std::chrono::seconds(5)) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
if (g_pluginInterface) { if (g_deferredInitThread.joinable()) {
g_pluginInterface->onClientDisconnected(serverConnectionHandlerId, clientID); if (g_deferredInitRunning) {
} g_deferredInitThread.detach();
} } else {
g_deferredInitThread.join();
}
}
}
// Helper to re-register plugin interface after hot reload (Core already reloaded) if (g_pluginInterface) {
static bool reregisterPluginInterface() { g_pluginInterface->disconnectFromServer();
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; if (g_coreLoader) {
g_coreLoader->disableAutoReload();
g_coreLoader->unload();
g_coreLoader.reset();
}
// Get the new core instance if (g_pluginInterface) {
auto core = g_coreLoader->getCore(); g_pluginInterface->shutdown();
if (!core) { g_pluginInterface = nullptr;
std::cerr << "[Echoion] ERROR: Core is null!" << std::endl; }
return false;
}
if (!g_pluginInterface) { g_ts3Functions = nullptr;
std::cerr << "[Echoion] ERROR: PluginInterface is null!" << std::endl; g_ts3FunctionsReady = false;
return false;
}
std::cout << std::format("[Echoion] New Core pointer: {}", reinterpret_cast<uintptr_t>(core.get())) << std::endl; std::cout << "[Echoion] Shutdown complete" << std::endl;
}
// Set the plugin interface first (before registering callbacks) // Handle incoming text messages
core->setPluginInterface(g_pluginInterface); TS3_PLUGIN_API void ts3plugin_onTextMessageEvent(
std::cout << "[Echoion] Plugin interface set on new Core" << std::endl; uint64 serverConnectionHandlerId, anyID targetMode, anyID toID,
anyID fromID, const char* fromName, const char* fromUniqueIdentifier,
const char* message, int ffIgnored)
{
// Clear old callbacks (they point to destroyed Core) and register new one anyID myID = 0;
std::cout << "[Echoion] About to clear callbacks..." << std::endl; if (g_ts3Functions &&
g_pluginInterface->clearEventCallbacks(); g_ts3Functions->getClientID(serverConnectionHandlerId, &myID) ==
std::cout << "[Echoion] Old event callbacks cleared" << std::endl; ERROR_ok) {
if (fromID == myID) {
return;
}
}
std::cout << "[Echoion] About to register new callback..." << std::endl; if (g_pluginInterface) {
g_pluginInterface->registerEventCallback([core](const Api::PluginEvent& event) { g_pluginInterface->onTextMessageReceived(
core->onPluginEvent(event); serverConnectionHandlerId, targetMode, fromID, message);
}); }
std::cout << "[Echoion] New event callback registered" << std::endl; }
std::cout << "[Echoion] Re-registration complete - bot should respond to commands" << std::endl; // Handle client connect/disconnect
return true; TS3_PLUGIN_API void ts3plugin_onClientMoveEvent(
} uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility, const char* moveMessage)
{
// Helper to reload core and re-register plugin interface (for manual reload) if (!g_pluginInterface) {
static bool reloadCoreWithInterface() { return;
if (!g_coreLoader) { }
std::cerr << "[Echoion] Cannot reload: CoreLoader not available" << std::endl;
return false;
}
std::cout << "[Echoion] Starting hot reload (Plugin)..." << std::endl; if (oldChannelID == 0) {
g_pluginInterface->onClientConnected(serverConnectionHandlerId,
clientID);
} else if (newChannelID == 0) {
g_pluginInterface->onClientDisconnected(serverConnectionHandlerId,
clientID);
} else {
g_pluginInterface->onClientMoved(serverConnectionHandlerId,
clientID, newChannelID);
}
}
auto result = g_coreLoader->hotReload(getCorePath()); TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent(
if (!result) { uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID,
std::cerr << std::format("[Echoion] Hot reload failed: {}", result.error().message) << std::endl; uint64 newChannelID, int visibility, const char* timeoutMessage)
return false; {
}
// Now re-register the plugin interface if (g_pluginInterface) {
return reregisterPluginInterface(); g_pluginInterface->onClientDisconnected(serverConnectionHandlerId,
} clientID);
}
}
// Handle plugin commands from TS3 // Helper to re-register plugin interface after hot reload (Core already
TS3_PLUGIN_API void ts3plugin_onPluginCommandEvent(uint64 serverConnectionHandlerId, // reloaded)
const char* pluginName, const char* command) { static bool reregisterPluginInterface()
{
if (!g_coreLoader) {
std::cerr
<< "[Echoion] Cannot re-register: CoreLoader not available"
<< std::endl;
return false;
}
if (std::strcmp(command, "reload") == 0) { std::cout
if (ensureCoreLoaded()) { << "[Echoion] Re-registering plugin interface after hot reload..."
reloadCoreWithInterface(); << std::endl;
}
}
}
// Menu item callbacks // Get the new core instance
TS3_PLUGIN_API void ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId, auto core = g_coreLoader->getCore();
enum PluginMenuType type, int menuItemID, uint64 selectedItemID) { if (!core) {
std::cerr << "[Echoion] ERROR: Core is null!" << std::endl;
return false;
}
if (!ensureCoreLoaded()) return; if (!g_pluginInterface) {
std::cerr << "[Echoion] ERROR: PluginInterface is null!"
<< std::endl;
return false;
}
auto core = g_coreLoader->getCore(); std::cout << std::format("[Echoion] New Core pointer: {}",
if (!core) return; reinterpret_cast<uintptr_t>(core.get()))
<< std::endl;
switch (menuItemID) { // Set the plugin interface first (before registering callbacks)
case 1: { // Play/Pause core->setPluginInterface(g_pluginInterface);
auto state = core->getPlaybackState(); std::cout << "[Echoion] Plugin interface set on new Core" << std::endl;
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 // Clear old callbacks (they point to destroyed Core) and register new
TS3_PLUGIN_API void ts3plugin_onConnectStatusChangeEvent(uint64 serverConnectionHandlerId, // one
int newStatus, unsigned int errorNumber) { std::cout << "[Echoion] About to clear callbacks..." << std::endl;
g_pluginInterface->clearEventCallbacks();
std::cout << "[Echoion] Old event callbacks cleared" << std::endl;
if (g_pluginInterface) { std::cout << "[Echoion] About to register new callback..." << std::endl;
g_pluginInterface->setServerConnectionHandlerId(serverConnectionHandlerId); 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;
}
switch (newStatus) { // Helper to reload core and re-register plugin interface (for manual
case STATUS_CONNECTING: // reload)
std::cout << "[Echoion] Connecting..." << std::endl; static bool reloadCoreWithInterface()
break; {
case STATUS_CONNECTED: if (!g_coreLoader) {
std::cout << "[Echoion] Connected" << std::endl; std::cerr << "[Echoion] Cannot reload: CoreLoader not available"
if (g_pluginInterface) { << std::endl;
g_pluginInterface->closeAudioDevice(); return false;
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" 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 } // namespace Echoion::Plugin
+1157 -1004
View File
File diff suppressed because it is too large. Load diff