Compare commits

...
11 Commits
Author SHA1 Message Date
faumaray 470ab507e1 making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:46:06 +03:00
faumaray 06379fbd5c Release 1.0.0
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-04 01:49:55 +03:00
faumarayandClaude Opus 4.8 446416c723 Plugin: keep <details> blocks intact when chunking replies
A reply is split into <=900-byte TeamSpeak messages; never split inside a
<details>…</details> block (each top-level block starts a fresh message and is
kept whole), otherwise a collapsible section spanning two messages would not
render.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:15:40 +03:00
faumarayandClaude Opus 4.8 ac88cd6eb1 Plugin: log sendTextMessage size + chunk count (debug)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 02:39:10 +03:00
faumarayandClaude Opus 4.8 a356251c83 Plugin: chunk long text replies so search/queue results arrive
requestSendPrivateTextMsg rejects over-long messages, and sendTextMessage
ignored its error return — so long replies (e.g. a 5-result search list) were
silently dropped while short ones (!help, error messages) worked. Split
messages into UTF-8-safe <=900-byte chunks on line boundaries and send each;
log the TeamSpeak error code on failure instead of swallowing it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 21:49:52 +03:00
faumarayandClaude Opus 4.8 9a61e01fda Route plugin logging through the Void::Log facade
Rewrite the ~80 ECHOION_LOG_* sites in PluginInterface/CoreLoader to
Void::Log::<level>("<Subsystem>", "{}", <expr>); add <iostream> where the
deleted LoggerInterface.hpp previously pulled it in. The plugin shares the
process-wide Void::Log sink installed by Core.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:10:06 +03:00
faumarayandClaude Opus 4.8 b313ed7101 Use Api::fail() for error returns
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:07:18 +03:00
faumarayandClaude Opus 4.8 7c58af92cd Install a Void::Stacktrace crash handler at plugin init
ts3plugin_init() sets a std::terminate handler that captures and prints a
symbolized stack trace (with source snippets) before aborting — useful for
diagnosing crashes in the hot-reloadable plugin. Link Void::Stacktrace.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 21:27:00 +03:00
faumaray df1ea8d53f Merge branch 'eventbust' into 'main'
Bump CMake minimum to 4.0 for VoidLibrary toolchain

See merge request void/echoionplugin!1
2026-06-22 15:53:30 +03:00
faumaray 05c9f8bc6c Bump CMake minimum to 4.0 for VoidLibrary toolchain 2026-06-22 15:53:30 +03:00
faumaray 0fa9db4691 Hot reload fix 2026-02-03 04:48:29 +03:00
11 changed files with 3060 additions and 1700 deletions

No files matched your search

+54 -20
View File
@@ -1,30 +1,46 @@
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)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON)
CPMAddPackage( CPMAddPackage(
NAME dylib NAME dylib
GITHUB_REPOSITORY martin-olivier/dylib GITHUB_REPOSITORY martin-olivier/dylib
GIT_TAG "v3.0.1" GIT_TAG "v3.0.1"
OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON" OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON"
) )
add_library(EchoionPlugin SHARED
src/PluginInterface.cpp file(GLOB_RECURSE PLUGIN_SOURCES
src/CoreLoader.cpp CONFIGURE_DEPENDS
src/Plugin.cpp "src/**.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
Void::Data
Void::Stacktrace
)
find_package(dylib CONFIG REQUIRED) find_package(dylib CONFIG REQUIRED)
target_link_libraries(EchoionPlugin PRIVATE dylib) target_link_libraries(EchoionPlugin PRIVATE dylib)
@@ -32,15 +48,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
@@ -51,24 +63,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()
include(GNUInstallDirs) # Export Plugin
target_include_directories(EchoionPlugin PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
install(TARGETS EchoionPlugin install(TARGETS EchoionPlugin
EXPORT EchoionPluginTargets EXPORT EchoionPluginTargets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}/plugins RUNTIME DESTINATION plugins
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/plugins LIBRARY DESTINATION plugins
INCLUDES DESTINATION include
) )
install(EXPORT EchoionPluginTargets install(EXPORT EchoionPluginTargets
FILE EchoionPluginTargets.cmake FILE EchoionPluginTargets.cmake
NAMESPACE Echoion:: NAMESPACE Echoion::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionPlugin DESTINATION lib/cmake/EchoionPlugin
) )
install(DIRECTORY include/ # Package config
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfigVersion.cmake"
VERSION ${PROJECT_VERSION}
COMPATIBILITY SameMajorVersion
)
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
) )
+83 -48
View File
@@ -1,60 +1,95 @@
#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 <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
void enableAutoReload();
void disableAutoReload();
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
private: Api::Result<void> load(const std::filesystem::path& libraryPath);
Api::Result<void> loadLibraryInternal(const std::filesystem::path& path); Api::Result<void> unload();
Api::Result<void> unloadLibraryInternal(); Api::Result<void>
[[nodiscard]] Api::HotReloadState saveStateInternal(); hotReload(const std::filesystem::path& newLibraryPath);
[[nodiscard]] Api::Result<void> restoreStateInternal(const Api::HotReloadState& state); [[nodiscard]] bool isLoaded() const noexcept;
[[nodiscard]] std::filesystem::path getTempLibraryPath(const std::filesystem::path& original) const; [[nodiscard]] Api::CoreInterfacePtr getCore() const;
void cleanupTempFiles(); void setConfigPath(const std::filesystem::path& configPath);
[[nodiscard]] std::filesystem::path getConfigPath() const;
[[nodiscard]] bool isHotReloading() const noexcept;
std::unique_ptr<dylib::library> library_; // Automatic hot reload
Api::CoreInterfacePtr core_; void enableAutoReload();
std::filesystem::path currentLibraryPath_; void disableAutoReload();
std::filesystem::path tempLibraryPath_; [[nodiscard]] bool isAutoReloadEnabled() const noexcept;
std::filesystem::path configPath_;
mutable std::mutex mutex_; // Callback for hot reload completion (called after auto-reload
std::atomic<bool> loaded_{false}; // finishes)
std::atomic<bool> hotReloading_{false}; using HotReloadCallback = std::function<void()>;
void setHotReloadCallback(HotReloadCallback callback)
// Auto reload {
FileWatcher fileWatcher_; hotReloadCallback_ = std::move(callback);
std::atomic<bool> autoReloadEnabled_{false}; }
void onCoreFileChanged(); private:
};
Api::Result<void>
loadLibraryInternal(const std::filesystem::path& path);
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();
std::unique_ptr<dylib::library> library_;
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
FileWatcher fileWatcher_;
std::atomic<bool> autoReloadEnabled_{false};
// Deferred reload - waits for current track to finish
std::thread deferredReloadThread_;
std::atomic<bool> hasPendingReload_{false};
std::atomic<bool> stopDeferredReload_{false};
std::condition_variable deferredReloadCv_;
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
+50 -47
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}; void watchLoop();
std::atomic<bool> watching_{false};
std::atomic<bool> stopRequested_{false}; std::filesystem::path watchedPath_;
std::thread watchThread_; ChangeCallback callback_;
std::mutex mutex_; std::chrono::milliseconds intervalMs_{1000};
std::atomic<bool> watching_{false};
// Store last modification time std::atomic<bool> stopRequested_{false};
std::filesystem::file_time_type lastWriteTime_; std::thread watchThread_;
std::uintmax_t lastFileSize_ = 0; std::mutex mutex_;
};
// Store last modification time
std::filesystem::file_time_type lastWriteTime_;
std::uint64_t lastFileSize_ = 0;
};
} // namespace Echoion::Plugin } // namespace Echoion::Plugin
+164 -87
View File
@@ -1,117 +1,194 @@
#pragma once #pragma once
#include <PluginInterface.hpp>
#include <echoion/api.hpp> #include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <dylib.hpp> #include <dylib.hpp>
#include <future>
#include <map>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <atomic>
#include <thread>
#include <queue> #include <queue>
#include <condition_variable> #include <thread>
// 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 = 192000; // Match reference implementation "Echoion Music Bot Audio";
static constexpr int CHANNELS = 2; static constexpr int SAMPLE_RATE =
static constexpr int SAMPLE_SIZE = sizeof(int16_t); 192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC)
}; static constexpr int CHANNELS = 2;
static constexpr int SAMPLE_SIZE = sizeof(int16_t);
};
// Plugin implementation of IPluginInterface for the Core to use // Server groups cache entry
class PluginInterface : public Api::IPluginInterface { struct ServerGroupsCacheEntry {
public: std::vector<uint64_t> groups;
PluginInterface(); std::chrono::steady_clock::time_point timestamp;
~PluginInterface() override; };
// Initialize with TeamSpeak functions // Plugin implementation of IPluginInterface for the Core to use
Api::Result<void> initialize(TS3Functions* ts3Functions); class PluginInterface : public Api::IPluginInterface
{
public:
// IPluginInterface implementation PluginInterface();
Api::Result<void> initialize() override; ~PluginInterface() override;
Api::Result<void> shutdown() override;
// Client operations // Initialize with TeamSpeak functions
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>> getClients() const override; Api::Result<void> initialize(TS3Functions* ts3Functions);
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>> getClient(uint64_t clientId) const 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 // IPluginInterface implementation
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>> getChannels() const override; Api::Result<void> initialize() override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>> getChannel(uint64_t channelId) const override; Api::Result<void> shutdown() override;
// Messaging // Client operations
Api::Result<void> sendTextMessage(uint64_t targetId, const std::string& message) override; [[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
Api::Result<void> sendChannelMessage(uint64_t channelId, const std::string& message) override; getClients() override;
Api::Result<void> sendServerMessage(const std::string& message) override; [[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientIp(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarPath(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarUrl(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
requestClientAvatar(uint64_t clientId,
const std::string& destDir) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
// Audio // Channel operations
Api::Result<void> sendAudioData(const std::span<const uint8_t>& data) override; [[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
Api::Result<void> setWhisperList(const std::vector<uint64_t>& clientIds) override; getChannels() const override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
getChannel(uint64_t channelId) const override;
// Event subscription // Messaging
void registerEventCallback(const Api::EventCallback& callback) override; Api::Result<void>
void unregisterEventCallback(const Api::EventCallback& callback) override; sendTextMessage(uint64_t targetId,
const std::string& message) override;
Api::Result<void>
sendChannelMessage(uint64_t channelId,
const std::string& message) override;
Api::Result<void>
sendServerMessage(const std::string& message) override;
// TeamSpeak event handlers (called by TeamSpeak SDK) // Audio
void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId); Api::Result<void>
void onClientDisconnected(uint64_t serverConnectionHandlerId, uint64_t clientId); sendAudioData(const std::span<const short>& data) override;
void onClientMoved(uint64_t serverConnectionHandlerId, uint64_t clientId, uint64_t newChannelId); Api::Result<void>
void onTextMessageReceived(uint64_t serverConnectionHandlerId, uint64_t targetMode, setWhisperList(const std::vector<uint64_t>& clientIds) override;
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) // Event subscription
Api::Result<void> connectToServer(const Api::ServerConfig& config) override; void registerEventCallback(
Api::Result<void> disconnectFromServer() override; const Api::EventCallback& callback) override;
[[nodiscard]] bool isConnected() const override; void unregisterEventCallback(
Api::Result<void> reconnect() override; const Api::EventCallback& callback) override;
void clearEventCallbacks();
// Audio device management // TeamSpeak event handlers (called by TeamSpeak SDK)
Api::Result<void> registerAudioDevice(); void onConnectionEstablished(uint64_t serverConnectionHandlerId);
Api::Result<void> unregisterAudioDevice(); void onClientConnected(uint64_t serverConnectionHandlerId,
Api::Result<void> openAudioDevice(); uint64_t clientId);
[[nodiscard]] bool isAudioDeviceRegistered() const { return audioDeviceRegistered_; } void onClientDisconnected(uint64_t serverConnectionHandlerId,
Api::Result<void> closeAudioDevice(); uint64_t clientId);
[[nodiscard]] bool isAudioDeviceOpen() const; 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);
// Set server connection handler // Server group list callback (called by TeamSpeak SDK)
void setServerConnectionHandlerId(uint64_t handlerId); void onServerGroupByClientID(uint64_t serverConnectionHandlerId,
[[nodiscard]] uint64_t getServerConnectionHandlerId() const; uint64_t clientDatabaseId,
const char* groupName,
uint64_t serverGroupId,
uint64_t clientId);
// Audio data submission (for internal use) // Server connection management (IPluginInterface implementation)
void submitAudioData(const std::span<const int16_t> samples); Api::Result<void>
connectToServer(const Api::ServerConfig& config) override;
Api::Result<void> disconnectFromServer() override;
[[nodiscard]] bool isConnected() const override;
Api::Result<void> reconnect() override;
private: // Audio device management
void broadcastEvent(const Api::PluginEvent& event); Api::Result<void> registerAudioDevice();
std::string getClientName(uint64_t clientId) const; Api::Result<void> unregisterAudioDevice();
std::string getChannelName(uint64_t channelId) const; Api::Result<void> openAudioDevice();
[[nodiscard]] bool isAudioDeviceRegistered() const noexcept
{
return audioDeviceRegistered_.load();
}
Api::Result<void> closeAudioDevice();
[[nodiscard]] bool isAudioDeviceOpen() const noexcept;
TS3Functions* ts3Functions_ = nullptr; // Set server connection handler
uint64_t serverConnectionHandlerId_ = 0; void setServerConnectionHandlerId(uint64_t handlerId) noexcept;
std::atomic<bool> initialized_{false}; [[nodiscard]] uint64_t
std::atomic<bool> audioDeviceRegistered_{false}; getServerConnectionHandlerId() const noexcept;
std::atomic<bool> audioDeviceOpen_{false};
std::vector<Api::EventCallback> eventCallbacks_; // Audio data submission (for internal use)
mutable std::mutex eventMutex_; void submitAudioData(std::span<const short> samples);
// Audio data queue // Automatic configuration
std::queue<std::vector<int16_t>> audioQueue_; Api::Result<void> configureAudioProfile();
std::mutex audioMutex_; Api::Result<void> checkAndHandleFirstRun();
std::condition_variable audioCv_;
std::atomic<bool> stopAudioThread_{false};
std::jthread audioThread_;
// Connection info private:
Api::ServerConfig currentServerConfig_;
}; void broadcastEvent(const Api::PluginEvent& event);
[[nodiscard]] std::string getClientName(uint64_t clientId) const;
[[nodiscard]] std::string getChannelName(uint64_t channelId) const;
// Fetch server groups for a client (returns future that completes
// when groups are received)
[[nodiscard]] std::future<std::vector<uint64_t>>
fetchServerGroups(uint64_t clientId);
// Get cached server groups (or empty if not cached)
[[nodiscard]] std::vector<uint64_t>
getCachedServerGroups(uint64_t clientId);
TS3Functions* ts3Functions_ = nullptr;
uint64_t serverConnectionHandlerId_ = 0;
std::atomic<bool> initialized_{false};
std::atomic<bool> audioDeviceRegistered_{false};
std::atomic<bool> audioDeviceOpen_{false};
std::vector<Api::EventCallback> eventCallbacks_;
mutable std::mutex eventMutex_;
// Audio data queue
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 {
+465 -276
View File
@@ -1,328 +1,517 @@
#include "echoion/plugin/CoreLoader.hpp" #include <Void/Log/Log.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() { CoreLoader::CoreLoader() { cleanupTempFiles(); }
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_)) {
ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}", currentLibraryPath_.string()));
// Create weak pointer to avoid circular reference in lambda
std::weak_ptr<CoreLoader> weakThis =
std::const_pointer_cast<CoreLoader>(
std::shared_ptr<const CoreLoader>(this, [](const CoreLoader*){}));
fileWatcher_.startWatching(currentLibraryPath_, [this]() {
onCoreFileChanged();
});
}
}
void CoreLoader::disableAutoReload() { std::lock_guard<std::mutex> lock(mutex_);
autoReloadEnabled_ = false; if (!currentLibraryPath_.empty() &&
fileWatcher_.stopWatching(); std::filesystem::exists(currentLibraryPath_)) {
ECHOION_LOG_INFO("Auto-reload disabled"); Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
} currentLibraryPath_.string()));
bool CoreLoader::isAutoReloadEnabled() const noexcept { fileWatcher_.startWatching(currentLibraryPath_,
return autoReloadEnabled_.load(); [this]() { onCoreFileChanged(); });
} }
}
void CoreLoader::onCoreFileChanged() { void CoreLoader::disableAutoReload()
if (!autoReloadEnabled_.load() || hotReloading_.load()) { {
return; autoReloadEnabled_ = false;
} fileWatcher_.stopWatching();
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
ECHOION_LOG_INFO("Core file changed, triggering hot reload..."); }
// Small delay to ensure file write is complete
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto result = hotReload(currentLibraryPath_);
if (!result) {
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message));
} else {
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
}
}
CoreLoader::~CoreLoader() { bool CoreLoader::isAutoReloadEnabled() const noexcept
unload(); {
cleanupTempFiles(); return autoReloadEnabled_.load();
} }
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath) { void CoreLoader::onCoreFileChanged()
std::lock_guard<std::mutex> lock(mutex_); {
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
if (loaded_) { return;
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already loaded")); }
}
if (!std::filesystem::exists(libraryPath)) { Void::Log::info("CoreLoader", "{}",
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "Core file changed, scheduling hot reload after current track...");
std::format("Library not found: {}", libraryPath.string())));
}
tempLibraryPath_ = getTempLibraryPath(libraryPath); // Small delay to ensure file write is complete
std::this_thread::sleep_for(std::chrono::milliseconds(500));
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())));
}
auto result = loadLibraryInternal(tempLibraryPath_); // Check if playback is active - if so, defer reload
if (result) { if (isPlaybackActive()) {
currentLibraryPath_ = libraryPath; std::string currentTrackId;
} else { {
std::error_code ec; std::lock_guard<std::mutex> lock(pendingReloadMutex_);
std::filesystem::remove(tempLibraryPath_, ec); hasPendingReload_ = true;
} pendingReloadPath_ = currentLibraryPath_;
return result;
}
Api::Result<void> CoreLoader::unload() { // Capture current track ID
std::lock_guard<std::mutex> lock(mutex_); auto state = core_->getPlaybackSummary();
if (state && state->currentTrack.has_value()) {
auto result = unloadLibraryInternal(); pendingTrackId_ = state->currentTrack->id;
currentTrackId = pendingTrackId_;
if (!tempLibraryPath_.empty()) { }
std::error_code ec; }
std::filesystem::remove(tempLibraryPath_, ec);
}
return result;
}
Api::Result<void> CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) { Void::Log::info("CoreLoader", "{}",
std::lock_guard<std::mutex> lock(mutex_); std::format("Playback active (track: {}), deferring reload "
"until track finishes",
if (!loaded_) { currentTrackId));
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No core loaded to reload"));
}
hotReloading_ = true; // Start background thread to wait for track end
if (deferredReloadThread_.joinable()) {
ECHOION_LOG_INFO("Starting hot reload with temp file..."); deferredReloadThread_.join();
}
deferredReloadThread_ = std::thread([this, currentTrackId]() {
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
});
} else {
// No playback, reload immediately
auto result = hotReload(currentLibraryPath_);
if (!result) {
Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
}
auto state = saveStateInternal(); bool CoreLoader::isPlaybackActive() const
{
auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; if (!core_) {
return false;
if (!std::filesystem::exists(targetPath)) { }
hotReloading_ = false;
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
std::format("New library not found: {}", targetPath.string())));
}
std::filesystem::path newTempPath = getTempLibraryPath(targetPath); auto state = core_->getPlaybackSummary();
if (!state) {
try { return false;
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 unloadResult = unloadLibraryInternal(); // Check if currently playing a track
if (!unloadResult) { return state->isPlaying && state->currentTrack.has_value();
hotReloading_ = false; }
std::error_code ec;
std::filesystem::remove(newTempPath, ec);
return unloadResult;
}
std::error_code ec; bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
std::filesystem::remove(tempLibraryPath_, ec); {
tempLibraryPath_ = newTempPath; if (!core_ || trackId.empty()) {
return false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50)); auto state = core_->getPlaybackSummary();
if (!state || !state->currentTrack.has_value()) {
return false;
}
auto loadResult = loadLibraryInternal(tempLibraryPath_); return state->currentTrack->id == trackId;
if (!loadResult) { }
hotReloading_ = false;
return loadResult;
}
auto restoreResult = restoreStateInternal(state); void CoreLoader::waitForTrackAndReload(
if (!restoreResult) { const std::filesystem::path& targetPath, const std::string& trackId)
ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", restoreResult.error().message)); {
} Void::Log::info("CoreLoader", "{}", std::format(
"Waiting for track {} to finish before reload...", trackId));
currentLibraryPath_ = targetPath; // Poll every 500ms to check if the specific track finished
hotReloading_ = false; // (playback may continue with next track, but we only care about THIS
// track). The wait is interruptible so the destructor can join this
ECHOION_LOG_INFO("Hot reload complete"); // thread instead of detaching it (detaching risks use-after-free when
return {}; // the plugin unloads mid-wait).
} while (isSameTrackPlaying(trackId)) {
std::unique_lock<std::mutex> lock(pendingReloadMutex_);
if (deferredReloadCv_.wait_for(
lock, std::chrono::milliseconds(500),
[this] { return stopDeferredReload_.load(); })) {
Void::Log::info("CoreLoader", "{}",
"Deferred hot-reload cancelled (loader shutting down)");
return;
}
}
bool CoreLoader::isLoaded() const noexcept { if (stopDeferredReload_.load()) {
return loaded_.load(); return;
} }
Api::CoreInterfacePtr CoreLoader::getCore() const { Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload");
std::lock_guard<std::mutex> lock(mutex_);
return core_;
}
void CoreLoader::setConfigPath(const std::filesystem::path& configPath) { // Clear pending flag
std::lock_guard<std::mutex> lock(mutex_); {
configPath_ = configPath; std::lock_guard<std::mutex> lock(pendingReloadMutex_);
} hasPendingReload_ = false;
pendingTrackId_.clear();
}
std::filesystem::path CoreLoader::getConfigPath() const { // Now do the reload
std::lock_guard<std::mutex> lock(mutex_); auto result = hotReload(targetPath);
return configPath_; if (!result) {
} Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}",
result.error().message));
} else {
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
}
}
}
bool CoreLoader::isHotReloading() const noexcept { CoreLoader::~CoreLoader()
return hotReloading_.load(); {
} // Signal the deferred reload thread to stop and wait for it. It must
// never outlive this object: it dereferences core_ and this.
stopDeferredReload_ = true;
deferredReloadCv_.notify_all();
if (deferredReloadThread_.joinable()) {
deferredReloadThread_.join();
}
if (auto result = unload(); !result) {
Void::Log::warn("CoreLoader", "{}",
std::format("Unload from destructor failed: {}",
result.error().message));
}
cleanupTempFiles();
}
Api::Result<void> CoreLoader::loadLibraryInternal(const std::filesystem::path& path) { Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
try { {
ECHOION_LOG_INFO(std::format("Loading core library: {}", path.string())); std::lock_guard<std::mutex> lock(mutex_);
// Use no decorations - the path already has the correct extension (.ts)
library_ = std::make_unique<dylib::library>(path.string(), dylib::decorations::none());
auto createFunc = library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
auto versionFunc = library_->get_function<const char*()>("GetApiVersion");
auto compatibleFunc = library_->get_function<bool(uint32_t, uint32_t)>("IsApiCompatible");
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) { if (loaded_) {
library_.reset(); return Api::fail(Api::ErrorCode::AlreadyExists,
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Core already loaded");
std::format("API version mismatch. Expected {}.{}, got {}", }
Api::VERSION_MAJOR, Api::VERSION_MINOR, versionFunc())));
}
core_ = createFunc(); if (!std::filesystem::exists(libraryPath)) {
if (!core_) { return Api::fail(
library_.reset(); Api::ErrorCode::NotFound,
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError, std::format("Library not found: {}", libraryPath.string()));
"Failed to create core instance")); }
}
auto initResult = core_->initialize(configPath_); tempLibraryPath_ = getTempLibraryPath(libraryPath);
if (!initResult) {
core_.reset();
library_.reset();
return initResult;
}
loaded_ = true; try {
std::filesystem::copy_file(
libraryPath, tempLibraryPath_,
std::filesystem::copy_options::overwrite_existing);
} catch (const std::exception& e) {
return Api::fail(
Api::ErrorCode::UnknownError,
std::format("Failed to copy library to temp: {}", e.what()));
}
ECHOION_LOG_INFO(std::format("Core library loaded (API version: {})", versionFunc())); auto result = loadLibraryInternal(tempLibraryPath_);
return {}; if (result) {
currentLibraryPath_ = libraryPath;
} else {
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
}
} catch (const dylib::load_error& e) { return result;
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() { Api::Result<void> CoreLoader::unload()
if (!loaded_) { {
return {}; std::lock_guard<std::mutex> lock(mutex_);
}
ECHOION_LOG_INFO("Unloading core library..."); auto result = unloadLibraryInternal();
if (core_) { if (!tempLibraryPath_.empty()) {
core_->shutdown(); std::error_code ec;
core_.reset(); std::filesystem::remove(tempLibraryPath_, ec);
} }
library_.reset(); return result;
}
loaded_ = false; Api::Result<void>
ECHOION_LOG_INFO("Core library unloaded"); CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
return {}; {
} std::lock_guard<std::mutex> lock(mutex_);
Api::HotReloadState CoreLoader::saveStateInternal() { if (!loaded_) {
if (!core_) { return Api::fail(Api::ErrorCode::NotFound,
return Api::HotReloadState{}; "No core loaded to reload");
} }
auto state = core_->prepareForHotReload(); hotReloading_ = true;
if (state) {
return *state;
}
ECHOION_LOG_WARNING("Failed to save state for hot reload"); Void::Log::info("CoreLoader", "{}", "Starting hot reload with temp file...");
return Api::HotReloadState{};
}
Api::Result<void> CoreLoader::restoreStateInternal(const Api::HotReloadState& state) { // Step 1: Save state as opaque blob (Plugin doesn't know contents)
if (!core_) { Api::StateBlob stateBlob;
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, if (core_) {
"Core not available for state restore")); stateBlob = core_->saveState();
} Void::Log::info("CoreLoader", "{}",
std::format("Saved state: version={}, size={} bytes",
stateBlob.version, stateBlob.size()));
}
return core_->restoreAfterHotReload(state); auto targetPath =
} newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
std::filesystem::path CoreLoader::getTempLibraryPath(const std::filesystem::path& original) const { if (!std::filesystem::exists(targetPath)) {
auto tempDir = std::filesystem::temp_directory_path(); hotReloading_ = false;
auto filename = original.filename().string(); return Api::fail(
Api::ErrorCode::NotFound,
auto now = std::chrono::system_clock::now(); std::format("New library not found: {}", targetPath.string()));
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() { std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
auto tempDir = std::filesystem::temp_directory_path();
std::error_code ec; try {
std::filesystem::copy_file(
for (const auto& entry : std::filesystem::directory_iterator(tempDir, ec)) { targetPath, newTempPath,
if (entry.is_regular_file()) { std::filesystem::copy_options::overwrite_existing);
auto name = entry.path().filename().string(); } catch (const std::exception& e) {
if (name.starts_with("echoion_") && hotReloading_ = false;
(name.ends_with(".dll") || name.ends_with(".so") || name.ends_with(".ts"))) { std::error_code ec;
std::filesystem::remove(entry.path(), ec); std::filesystem::remove(newTempPath, ec);
} return Api::fail(Api::ErrorCode::UnknownError,
} std::format("Failed to copy new library to temp: {}",
} e.what()));
} }
auto unloadResult = unloadLibraryInternal();
if (!unloadResult) {
hotReloading_ = false;
std::error_code ec;
std::filesystem::remove(newTempPath, ec);
return unloadResult;
}
std::error_code ec;
std::filesystem::remove(tempLibraryPath_, ec);
tempLibraryPath_ = newTempPath;
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;
Void::Log::info("CoreLoader", "{}", std::format("Restoring state v{} to Core v{}",
stateVersion, coreVersion));
if (core_->canRestoreStateVersion(stateVersion)) {
auto restoreResult = core_->restoreState(stateBlob);
if (!restoreResult) {
Void::Log::error("CoreLoader", "{}",
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
Void::Log::warn("CoreLoader", "{}", "State version incompatible. "
"User needs to update/restart.");
// Optionally: notify through plugin interface
}
// Continue with empty state - graceful degradation
} else {
Void::Log::info("CoreLoader", "{}", "State restored successfully");
}
} else {
Void::Log::warn("CoreLoader", "{}", 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;
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
return {};
}
bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); }
Api::CoreInterfacePtr CoreLoader::getCore() const
{
std::lock_guard<std::mutex> lock(mutex_);
return core_;
}
void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
{
std::lock_guard<std::mutex> lock(mutex_);
configPath_ = configPath;
}
std::filesystem::path CoreLoader::getConfigPath() const
{
std::lock_guard<std::mutex> lock(mutex_);
return configPath_;
}
bool CoreLoader::isHotReloading() const noexcept
{
return hotReloading_.load();
}
Api::Result<void>
CoreLoader::loadLibraryInternal(const std::filesystem::path& path)
{
try {
std::cout << std::format("[Echoion] Loading core library: {}",
path.string())
<< '\n';
// Use no decorations - the path already has the correct extension
// (.ts)
library_ = std::make_unique<dylib::library>(
path.string(), dylib::decorations::none());
auto createFunc =
library_->get_function<Api::CoreInterfacePtr()>("CreateCore");
auto versionFunc =
library_->get_function<const char*()>("GetApiVersion");
auto compatibleFunc =
library_->get_function<bool(uint32_t, uint32_t)>(
"IsApiCompatible");
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
library_.reset();
return Api::fail(
Api::ErrorCode::InvalidArgument,
std::format("API version mismatch. Expected {}.{}, got {}",
Api::VERSION_MAJOR, Api::VERSION_MINOR,
versionFunc()));
}
core_ = createFunc();
if (!core_) {
library_.reset();
return Api::fail(Api::ErrorCode::UnknownError,
"Failed to create core instance");
}
auto initResult = core_->initialize(configPath_);
if (!initResult) {
core_.reset();
library_.reset();
return initResult;
}
loaded_ = true;
Void::Log::info("CoreLoader", "{}", std::format(
"Core library loaded (API version: {})", versionFunc()));
return {};
} catch (const dylib::load_error& e) {
return Api::fail(
Api::ErrorCode::PluginError,
std::format("Failed to load library: {}", e.what()));
} catch (const dylib::symbol_error& e) {
return Api::fail(Api::ErrorCode::PluginError,
std::format("Failed to find symbol: {}", e.what()));
} catch (const std::exception& e) {
return Api::fail(Api::ErrorCode::UnknownError,
std::format("Unexpected error: {}", e.what()));
}
}
Api::Result<void> CoreLoader::unloadLibraryInternal()
{
if (!loaded_) {
return {};
}
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
if (core_) {
if (auto result = core_->shutdown(); !result) {
Void::Log::warn(
"CoreLoader", "{}",
std::format("Core shutdown reported failure: {}",
result.error().message));
}
core_.reset();
}
library_.reset();
loaded_ = false;
std::cout << "[Echoion] Core library unloaded" << '\n';
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
+79 -75
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_);
if (watching_.load()) {
stopWatching();
}
watchedPath_ = filePath; std::lock_guard<std::mutex> lock(mutex_);
callback_ = std::move(callback);
intervalMs_ = intervalMs;
stopRequested_ = false;
// Get initial file state if (watching_.load()) {
if (std::filesystem::exists(watchedPath_)) { stopWatching();
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_); }
lastFileSize_ = std::filesystem::file_size(watchedPath_);
}
watching_ = true; watchedPath_ = filePath;
watchThread_ = std::thread(&FileWatcher::watchLoop, this); callback_ = std::move(callback);
} intervalMs_ = intervalMs;
stopRequested_ = false;
void FileWatcher::stopWatching() { // Get initial file state
stopRequested_ = true; if (std::filesystem::exists(watchedPath_)) {
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
if (watchThread_.joinable()) { lastFileSize_ = std::filesystem::file_size(watchedPath_);
watchThread_.join(); }
}
watching_ = false;
}
bool FileWatcher::isWatching() const noexcept { watching_ = true;
return watching_.load(); watchThread_ = std::thread(&FileWatcher::watchLoop, this);
} }
void FileWatcher::watchLoop() { void FileWatcher::stopWatching()
while (!stopRequested_.load()) { {
// Sleep first to avoid checking immediately stopRequested_ = true;
std::this_thread::sleep_for(intervalMs_);
if (stopRequested_.load()) {
break;
}
std::lock_guard<std::mutex> lock(mutex_); if (watchThread_.joinable()) {
watchThread_.join();
if (!std::filesystem::exists(watchedPath_)) { }
continue;
}
try { watching_ = false;
auto currentWriteTime = std::filesystem::last_write_time(watchedPath_); }
auto currentFileSize = std::filesystem::file_size(watchedPath_);
// Check if file has changed (time or size) bool FileWatcher::isWatching() const noexcept { return watching_.load(); }
if (currentWriteTime != lastWriteTime_ || currentFileSize != lastFileSize_) {
// Update stored values
lastWriteTime_ = currentWriteTime;
lastFileSize_ = currentFileSize;
// Trigger callback void FileWatcher::watchLoop()
if (callback_) { {
try { while (!stopRequested_.load()) {
callback_(); // Sleep first to avoid checking immediately
} catch (const std::exception& e) { std::this_thread::sleep_for(intervalMs_);
std::cerr << std::format("FileWatcher callback error: {}", e.what()) << std::endl;
} if (stopRequested_.load()) {
} break;
} }
} catch (const std::exception& e) {
// Ignore errors (file might be locked during write) std::lock_guard<std::mutex> 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())
<< '\n';
}
}
}
} catch (const std::exception& e) {
// Ignore errors (file might be locked during write)
}
}
}
} // namespace Echoion::Plugin } // namespace Echoion::Plugin
+660 -352
View File
File diff suppressed because it is too large. Load diff
+1492 -782
View File
File diff suppressed because it is too large. Load diff