Compare commits
10
Commits
0fa9db4691
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
470ab507e1 | ||
|
|
06379fbd5c | ||
|
|
446416c723 | ||
|
|
ac88cd6eb1 | ||
|
|
a356251c83 | ||
|
|
9a61e01fda | ||
|
|
b313ed7101 | ||
|
|
7c58af92cd | ||
|
|
df1ea8d53f | ||
|
|
05c9f8bc6c |
No files matched your search
+59
-22
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionPlugin VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
@@ -13,20 +13,34 @@ CPMAddPackage(
|
||||
OPTIONS "CMAKE_POSITION_INDEPENDENT_CODE ON"
|
||||
)
|
||||
|
||||
add_library(EchoionPlugin SHARED
|
||||
src/PluginInterface.cpp
|
||||
src/CoreLoader.cpp
|
||||
src/Plugin.cpp
|
||||
src/FileWatcher.cpp
|
||||
file(GLOB_RECURSE PLUGIN_SOURCES
|
||||
CONFIGURE_DEPENDS
|
||||
"src/**.cpp"
|
||||
)
|
||||
add_library(EchoionPlugin SHARED ${PLUGIN_SOURCES})
|
||||
|
||||
add_library(Echoion::Plugin ALIAS EchoionPlugin)
|
||||
|
||||
target_include_directories(EchoionPlugin PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
target_link_libraries(EchoionPlugin PRIVATE Echoion::Api)
|
||||
target_compile_definitions(EchoionPlugin PUBLIC PLUGIN=1)
|
||||
# Plugin only needs minimal API (NO rebuild when Core changes):
|
||||
# - ApiBase (Types.hpp - Error, Result, LogLevel)
|
||||
# - ApiPlugin (PluginTypes.hpp - PluginEvent, ClientInfo, ServerConfig)
|
||||
# - ApiOpaque (OpaqueHandle for type-safe void*)
|
||||
# - ApiPluginInterface (IPluginInterface to implement)
|
||||
# - ApiCoreInterface (ICoreInterface to call Core - decoupled)
|
||||
target_link_libraries(EchoionPlugin PRIVATE
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiOpaque
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiLogger
|
||||
Echoion::ApiCoreInterface
|
||||
Void::Data
|
||||
Void::Stacktrace
|
||||
)
|
||||
|
||||
find_package(dylib CONFIG REQUIRED)
|
||||
target_link_libraries(EchoionPlugin PRIVATE dylib)
|
||||
@@ -34,15 +48,11 @@ target_link_libraries(EchoionPlugin PRIVATE dylib)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(EchoionPlugin PRIVATE Threads::Threads)
|
||||
|
||||
# Find glaze for JSON parsing
|
||||
find_package(glaze REQUIRED)
|
||||
target_link_libraries(EchoionPlugin PRIVATE glaze::glaze)
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(EchoionPlugin PRIVATE /W4 /WX-)
|
||||
target_compile_definitions(EchoionPlugin PRIVATE _CRT_SECURE_NO_WARNINGS)
|
||||
else()
|
||||
target_compile_options(EchoionPlugin PRIVATE -Wall -Wextra -Wpedantic -fPIC)
|
||||
target_compile_options(EchoionPlugin PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow -fPIC)
|
||||
endif()
|
||||
|
||||
set_target_properties(EchoionPlugin PROPERTIES
|
||||
@@ -53,19 +63,46 @@ set_target_properties(EchoionPlugin PROPERTIES
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
|
||||
# Ensure dylib is compiled with -fPIC
|
||||
if(TARGET dylib)
|
||||
set_target_properties(dylib PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
endif()
|
||||
|
||||
# PackageProject.cmake configuration
|
||||
packageProject(
|
||||
NAME EchoionPlugin
|
||||
# Export Plugin
|
||||
target_include_directories(EchoionPlugin PUBLIC
|
||||
$<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}
|
||||
NAMESPACE Echoion
|
||||
BINARY_DIR ${PROJECT_BINARY_DIR}
|
||||
INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include
|
||||
INCLUDE_DESTINATION include
|
||||
COMPATIBILITY SameMajorVersion
|
||||
DISABLE_VERSION_SUFFIX YES
|
||||
)
|
||||
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfig.cmake"
|
||||
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionPluginTargets.cmake\")
|
||||
include(CMakeFindDependencyMacro)
|
||||
find_dependency(EchoionApi)
|
||||
find_dependency(dylib)
|
||||
")
|
||||
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfig.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionPluginConfigVersion.cmake"
|
||||
DESTINATION lib/cmake/EchoionPlugin
|
||||
)
|
||||
@@ -1,78 +1,95 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <dylib.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 <mutex>
|
||||
#include <atomic>
|
||||
#include <filesystem>
|
||||
#include <thread>
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Plugin {
|
||||
namespace Echoion::Plugin
|
||||
{
|
||||
|
||||
class CoreLoader {
|
||||
public:
|
||||
CoreLoader();
|
||||
~CoreLoader();
|
||||
class CoreLoader
|
||||
{
|
||||
public:
|
||||
|
||||
Api::Result<void> load(const std::filesystem::path& libraryPath);
|
||||
Api::Result<void> unload();
|
||||
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;
|
||||
|
||||
// Callback for hot reload completion (called after auto-reload finishes)
|
||||
using HotReloadCallback = std::function<void()>;
|
||||
void setHotReloadCallback(HotReloadCallback callback) { hotReloadCallback_ = std::move(callback); }
|
||||
CoreLoader();
|
||||
~CoreLoader();
|
||||
|
||||
private:
|
||||
Api::Result<void> loadLibraryInternal(const std::filesystem::path& path);
|
||||
Api::Result<void> unloadLibraryInternal();
|
||||
[[nodiscard]] Api::HotReloadState saveStateInternal();
|
||||
[[nodiscard]] Api::Result<void> restoreStateInternal(const Api::HotReloadState& state);
|
||||
[[nodiscard]] std::filesystem::path getTempLibraryPath(const std::filesystem::path& original) const;
|
||||
void cleanupTempFiles();
|
||||
Api::Result<void> load(const std::filesystem::path& libraryPath);
|
||||
Api::Result<void> unload();
|
||||
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;
|
||||
|
||||
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::filesystem::path pendingReloadPath_;
|
||||
std::string pendingTrackId_; // Track ID that was playing when reload scheduled
|
||||
mutable std::mutex pendingReloadMutex_;
|
||||
|
||||
// Hot reload completion callback
|
||||
HotReloadCallback hotReloadCallback_;
|
||||
|
||||
void onCoreFileChanged();
|
||||
void waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId);
|
||||
[[nodiscard]] bool isPlaybackActive() const;
|
||||
[[nodiscard]] bool isSameTrackPlaying(const std::string& trackId) const;
|
||||
};
|
||||
// Automatic hot reload
|
||||
void enableAutoReload();
|
||||
void disableAutoReload();
|
||||
[[nodiscard]] bool isAutoReloadEnabled() const noexcept;
|
||||
|
||||
// Callback for hot reload completion (called after auto-reload
|
||||
// finishes)
|
||||
using HotReloadCallback = std::function<void()>;
|
||||
void setHotReloadCallback(HotReloadCallback callback)
|
||||
{
|
||||
hotReloadCallback_ = std::move(callback);
|
||||
}
|
||||
|
||||
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
|
||||
@@ -1,62 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <filesystem>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#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
|
||||
* and triggers a callback when the file is modified.
|
||||
*/
|
||||
class FileWatcher {
|
||||
public:
|
||||
using ChangeCallback = std::function<void()>;
|
||||
/**
|
||||
* @brief Simple file watcher that monitors a file for changes
|
||||
* and triggers a callback when the file is modified.
|
||||
*/
|
||||
class FileWatcher
|
||||
{
|
||||
public:
|
||||
|
||||
FileWatcher();
|
||||
~FileWatcher();
|
||||
using ChangeCallback = std::function<void()>;
|
||||
|
||||
// Disable copy
|
||||
FileWatcher(const FileWatcher&) = delete;
|
||||
FileWatcher& operator=(const FileWatcher&) = delete;
|
||||
FileWatcher();
|
||||
~FileWatcher();
|
||||
|
||||
/**
|
||||
* @brief Start watching a file for changes
|
||||
* @param filePath Path to the file to watch
|
||||
* @param callback Function to call when file changes
|
||||
* @param intervalMs Polling interval in milliseconds
|
||||
*/
|
||||
void startWatching(
|
||||
const std::filesystem::path& filePath,
|
||||
ChangeCallback callback,
|
||||
std::chrono::milliseconds intervalMs = std::chrono::milliseconds(1000)
|
||||
);
|
||||
// Disable copy
|
||||
FileWatcher(const FileWatcher&) = delete;
|
||||
FileWatcher& operator=(const FileWatcher&) = delete;
|
||||
|
||||
/**
|
||||
* @brief Stop watching
|
||||
*/
|
||||
void stopWatching();
|
||||
/**
|
||||
* @brief Start watching a file for changes
|
||||
* @param filePath Path to the file to watch
|
||||
* @param callback Function to call when file changes
|
||||
* @param intervalMs Polling interval in milliseconds
|
||||
*/
|
||||
void startWatching(const std::filesystem::path& filePath,
|
||||
ChangeCallback callback,
|
||||
std::chrono::milliseconds intervalMs =
|
||||
std::chrono::milliseconds(1000));
|
||||
|
||||
[[nodiscard]] bool isWatching() const noexcept;
|
||||
/**
|
||||
* @brief Stop watching
|
||||
*/
|
||||
void stopWatching();
|
||||
|
||||
private:
|
||||
void watchLoop();
|
||||
[[nodiscard]] bool isWatching() const noexcept;
|
||||
|
||||
std::filesystem::path watchedPath_;
|
||||
ChangeCallback callback_;
|
||||
std::chrono::milliseconds intervalMs_{1000};
|
||||
std::atomic<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::uintmax_t lastFileSize_ = 0;
|
||||
};
|
||||
private:
|
||||
|
||||
void watchLoop();
|
||||
|
||||
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
|
||||
@@ -1,9 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginInterface.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <dylib.hpp>
|
||||
#include <echoion/api.hpp>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -14,144 +15,180 @@
|
||||
// TeamSpeak SDK headers
|
||||
#include "ts3_functions.h"
|
||||
|
||||
namespace Echoion::Plugin {
|
||||
namespace Echoion::Plugin
|
||||
{
|
||||
|
||||
// Audio device configuration
|
||||
struct AudioDeviceConfig {
|
||||
static constexpr const char* DEVICE_ID = "echoion_audio_device";
|
||||
static constexpr const char* DEVICE_NAME = "Echoion Music Bot Audio";
|
||||
static constexpr int SAMPLE_RATE =
|
||||
192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC)
|
||||
static constexpr int CHANNELS = 2;
|
||||
static constexpr int SAMPLE_SIZE = sizeof(int16_t);
|
||||
};
|
||||
// Audio device configuration
|
||||
struct AudioDeviceConfig {
|
||||
static constexpr const char* DEVICE_ID = "echoion_audio_device";
|
||||
static constexpr const char* DEVICE_NAME =
|
||||
"Echoion Music Bot Audio";
|
||||
static constexpr int SAMPLE_RATE =
|
||||
192000; // 192kHz for high quality audio (CODEC_OPUS_MUSIC)
|
||||
static constexpr int CHANNELS = 2;
|
||||
static constexpr int SAMPLE_SIZE = sizeof(int16_t);
|
||||
};
|
||||
|
||||
// Server groups cache entry
|
||||
struct ServerGroupsCacheEntry {
|
||||
std::vector<uint64_t> groups;
|
||||
std::chrono::steady_clock::time_point timestamp;
|
||||
};
|
||||
// Server groups cache entry
|
||||
struct ServerGroupsCacheEntry {
|
||||
std::vector<uint64_t> groups;
|
||||
std::chrono::steady_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
// Plugin implementation of IPluginInterface for the Core to use
|
||||
class PluginInterface : public Api::IPluginInterface {
|
||||
public:
|
||||
PluginInterface();
|
||||
~PluginInterface() override;
|
||||
// Plugin implementation of IPluginInterface for the Core to use
|
||||
class PluginInterface : public Api::IPluginInterface
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize with TeamSpeak functions
|
||||
Api::Result<void> initialize(TS3Functions* ts3Functions);
|
||||
PluginInterface();
|
||||
~PluginInterface() override;
|
||||
|
||||
// IPluginInterface implementation
|
||||
Api::Result<void> initialize() override;
|
||||
Api::Result<void> shutdown() override;
|
||||
// Initialize with TeamSpeak functions
|
||||
Api::Result<void> initialize(TS3Functions* ts3Functions);
|
||||
|
||||
// Client operations
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
|
||||
getClients() 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;
|
||||
// IPluginInterface implementation
|
||||
Api::Result<void> initialize() override;
|
||||
Api::Result<void> shutdown() override;
|
||||
|
||||
// Channel operations
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
|
||||
getChannels() const override;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>> getChannel(uint64_t channelId) const override;
|
||||
// Client operations
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
|
||||
getClients() 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;
|
||||
|
||||
// Messaging
|
||||
Api::Result<void> 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;
|
||||
// Channel operations
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
|
||||
getChannels() const override;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
|
||||
getChannel(uint64_t channelId) const override;
|
||||
|
||||
// Audio
|
||||
Api::Result<void>
|
||||
sendAudioData(const std::span<const short>& data) override;
|
||||
Api::Result<void>
|
||||
setWhisperList(const std::vector<uint64_t>& clientIds) override;
|
||||
// Messaging
|
||||
Api::Result<void>
|
||||
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;
|
||||
|
||||
// Event subscription
|
||||
void registerEventCallback(const Api::EventCallback& callback) override;
|
||||
void unregisterEventCallback(const Api::EventCallback& callback) override;
|
||||
void clearEventCallbacks();
|
||||
// Audio
|
||||
Api::Result<void>
|
||||
sendAudioData(const std::span<const short>& data) override;
|
||||
Api::Result<void>
|
||||
setWhisperList(const std::vector<uint64_t>& clientIds) override;
|
||||
|
||||
// TeamSpeak event handlers (called by TeamSpeak SDK)
|
||||
void onClientConnected(uint64_t serverConnectionHandlerId, uint64_t clientId);
|
||||
void onClientDisconnected(uint64_t serverConnectionHandlerId, uint64_t clientId);
|
||||
void onClientMoved(uint64_t serverConnectionHandlerId, uint64_t clientId, uint64_t newChannelId);
|
||||
void onTextMessageReceived(uint64_t serverConnectionHandlerId, uint64_t targetMode,
|
||||
uint64_t fromId, const std::string& message);
|
||||
void onVoiceDataReceived(uint64_t serverConnectionHandlerId, uint64_t clientId,
|
||||
const std::span<const uint8_t>& data);
|
||||
// Event subscription
|
||||
void registerEventCallback(
|
||||
const Api::EventCallback& callback) override;
|
||||
void unregisterEventCallback(
|
||||
const Api::EventCallback& callback) override;
|
||||
void clearEventCallbacks();
|
||||
|
||||
// Server group list callback (called by TeamSpeak SDK)
|
||||
void onServerGroupByClientID(uint64_t serverConnectionHandlerId,
|
||||
uint64_t clientDatabaseId,
|
||||
const char* groupName, uint64_t serverGroupId,
|
||||
uint64_t clientId);
|
||||
// TeamSpeak event handlers (called by TeamSpeak SDK)
|
||||
void onConnectionEstablished(uint64_t serverConnectionHandlerId);
|
||||
void onClientConnected(uint64_t serverConnectionHandlerId,
|
||||
uint64_t clientId);
|
||||
void onClientDisconnected(uint64_t serverConnectionHandlerId,
|
||||
uint64_t clientId);
|
||||
void onClientMoved(uint64_t serverConnectionHandlerId,
|
||||
uint64_t clientId, uint64_t newChannelId);
|
||||
void onTextMessageReceived(uint64_t serverConnectionHandlerId,
|
||||
uint64_t targetMode, uint64_t fromId,
|
||||
const std::string& message);
|
||||
void onVoiceDataReceived(uint64_t serverConnectionHandlerId,
|
||||
uint64_t clientId,
|
||||
const std::span<const uint8_t>& data);
|
||||
|
||||
// Server connection management (IPluginInterface implementation)
|
||||
Api::Result<void> connectToServer(const Api::ServerConfig& config) override;
|
||||
Api::Result<void> disconnectFromServer() override;
|
||||
[[nodiscard]] bool isConnected() const override;
|
||||
Api::Result<void> reconnect() override;
|
||||
// Server group list callback (called by TeamSpeak SDK)
|
||||
void onServerGroupByClientID(uint64_t serverConnectionHandlerId,
|
||||
uint64_t clientDatabaseId,
|
||||
const char* groupName,
|
||||
uint64_t serverGroupId,
|
||||
uint64_t clientId);
|
||||
|
||||
// Audio device management
|
||||
Api::Result<void> registerAudioDevice();
|
||||
Api::Result<void> unregisterAudioDevice();
|
||||
Api::Result<void> openAudioDevice();
|
||||
[[nodiscard]] bool isAudioDeviceRegistered() const { return audioDeviceRegistered_; }
|
||||
Api::Result<void> closeAudioDevice();
|
||||
[[nodiscard]] bool isAudioDeviceOpen() const;
|
||||
// Server connection management (IPluginInterface implementation)
|
||||
Api::Result<void>
|
||||
connectToServer(const Api::ServerConfig& config) override;
|
||||
Api::Result<void> disconnectFromServer() override;
|
||||
[[nodiscard]] bool isConnected() const override;
|
||||
Api::Result<void> reconnect() override;
|
||||
|
||||
// Set server connection handler
|
||||
void setServerConnectionHandlerId(uint64_t handlerId);
|
||||
[[nodiscard]] uint64_t getServerConnectionHandlerId() const;
|
||||
// Audio device management
|
||||
Api::Result<void> registerAudioDevice();
|
||||
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)
|
||||
void submitAudioData(const std::span<const short> samples);
|
||||
// Set server connection handler
|
||||
void setServerConnectionHandlerId(uint64_t handlerId) noexcept;
|
||||
[[nodiscard]] uint64_t
|
||||
getServerConnectionHandlerId() const noexcept;
|
||||
|
||||
// Automatic configuration
|
||||
Api::Result<void> configureAudioProfile();
|
||||
Api::Result<void> checkAndHandleFirstRun();
|
||||
// Audio data submission (for internal use)
|
||||
void submitAudioData(std::span<const short> samples);
|
||||
|
||||
private:
|
||||
void broadcastEvent(const Api::PluginEvent& event);
|
||||
std::string getClientName(uint64_t clientId) const;
|
||||
std::string getChannelName(uint64_t channelId) const;
|
||||
// Automatic configuration
|
||||
Api::Result<void> configureAudioProfile();
|
||||
Api::Result<void> checkAndHandleFirstRun();
|
||||
|
||||
// Fetch server groups for a client (returns future that completes when
|
||||
// groups are received)
|
||||
std::future<std::vector<uint64_t>> fetchServerGroups(uint64_t clientId);
|
||||
private:
|
||||
|
||||
// Get cached server groups (or empty if not cached)
|
||||
std::vector<uint64_t> getCachedServerGroups(uint64_t clientId);
|
||||
void broadcastEvent(const Api::PluginEvent& event);
|
||||
[[nodiscard]] std::string getClientName(uint64_t clientId) const;
|
||||
[[nodiscard]] std::string getChannelName(uint64_t channelId) const;
|
||||
|
||||
TS3Functions* ts3Functions_ = nullptr;
|
||||
uint64_t serverConnectionHandlerId_ = 0;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> audioDeviceRegistered_{false};
|
||||
std::atomic<bool> audioDeviceOpen_{false};
|
||||
// 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);
|
||||
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
// Get cached server groups (or empty if not cached)
|
||||
[[nodiscard]] std::vector<uint64_t>
|
||||
getCachedServerGroups(uint64_t clientId);
|
||||
|
||||
// Audio data queue
|
||||
std::queue<std::vector<short>> audioQueue_;
|
||||
std::mutex audioMutex_;
|
||||
std::condition_variable audioCv_;
|
||||
std::atomic<bool> stopAudioThread_{false};
|
||||
std::jthread audioThread_;
|
||||
TS3Functions* ts3Functions_ = nullptr;
|
||||
uint64_t serverConnectionHandlerId_ = 0;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> audioDeviceRegistered_{false};
|
||||
std::atomic<bool> audioDeviceOpen_{false};
|
||||
|
||||
// Server groups cache
|
||||
mutable std::mutex serverGroupsMutex_;
|
||||
std::map<uint64_t, ServerGroupsCacheEntry> serverGroupsCache_;
|
||||
std::map<uint64_t, std::promise<std::vector<uint64_t>>>
|
||||
pendingServerGroupRequests_;
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
|
||||
// Connection info
|
||||
Api::ServerConfig currentServerConfig_;
|
||||
};
|
||||
// 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
|
||||
@@ -66,8 +66,8 @@ enum ConnectStatus {
|
||||
///< yet, we haven't been accepted by the server
|
||||
STATUS_CONNECTED, ///< The server has accepted us, we can talk and hear and
|
||||
///< we have a client id, but we don't have the channels
|
||||
///< and clients yet, we can get server infos (welcome msg
|
||||
///< etc.)
|
||||
///< and clients yet, we can get server infos (welcome msg
|
||||
///< etc.)
|
||||
STATUS_CONNECTION_ESTABLISHING, ///< we are connected and we are visible
|
||||
STATUS_CONNECTION_ESTABLISHED, ///< we are connected and we have the client
|
||||
///< and channels available
|
||||
@@ -182,8 +182,8 @@ enum ChannelProperties {
|
||||
///< ts3client_requestChannelDescription)
|
||||
CHANNEL_PASSWORD, ///< String. Read/Write. Password of the channel. Read
|
||||
///< access is limited to the server. Clients will only
|
||||
///< ever see the last password they attempted to use when
|
||||
///< joining the channel. Always available.
|
||||
///< ever see the last password they attempted to use when
|
||||
///< joining the channel. Always available.
|
||||
CHANNEL_CODEC, ///< Integer. Read/Write. The codec this channel is using.
|
||||
///< One of the values from the \ref CodecType enum. Always
|
||||
///< available.
|
||||
@@ -536,8 +536,8 @@ enum ConnectionProperties {
|
||||
///< client.
|
||||
CONNECTION_SERVER2CLIENT_PACKETLOSS_CONTROL, ///< Double. Probability with
|
||||
///< which a control packet
|
||||
///< sent by the server was not
|
||||
///< received by the client.
|
||||
///< sent by the server was not
|
||||
///< received by the client.
|
||||
CONNECTION_SERVER2CLIENT_PACKETLOSS_TOTAL, ///< Double. Probability with
|
||||
///< which a packet sent by the
|
||||
///< server was not received by
|
||||
@@ -553,8 +553,8 @@ enum ConnectionProperties {
|
||||
///< server.
|
||||
CONNECTION_CLIENT2SERVER_PACKETLOSS_CONTROL, ///< Double. Probability with
|
||||
///< which a control packet
|
||||
///< sent by the client was not
|
||||
///< received by the server.
|
||||
///< sent by the client was not
|
||||
///< received by the server.
|
||||
CONNECTION_CLIENT2SERVER_PACKETLOSS_TOTAL, ///< Double. Probability with
|
||||
///< which a packet sent by the
|
||||
///< client was not received by
|
||||
@@ -597,8 +597,8 @@ enum ConnectionProperties {
|
||||
///< the last second.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_CONTROL, ///< UInt64. Number of
|
||||
///< bytes received for
|
||||
///< control data in the
|
||||
///< last second.
|
||||
///< control data in the
|
||||
///< last second.
|
||||
CONNECTION_BANDWIDTH_RECEIVED_LAST_SECOND_TOTAL, ///< UInt64. Number of
|
||||
///< bytes received in the
|
||||
///< last second.
|
||||
|
||||
@@ -271,8 +271,8 @@ enum VirtualServerPropertiesRare {
|
||||
// requestServerVariables)
|
||||
VIRTUALSERVER_LOG_SERVER, // only available on request (=>
|
||||
// requestServerVariables)
|
||||
// VIRTUALSERVER_LOG_FILETRANSFER, // Moved to
|
||||
// VirtualServerProperties due to SDK usage
|
||||
// VIRTUALSERVER_LOG_FILETRANSFER, // Moved to
|
||||
// VirtualServerProperties due to SDK usage
|
||||
VIRTUALSERVER_MIN_CLIENT_VERSION =
|
||||
65, // only available on request (=> requestServerVariables)
|
||||
VIRTUALSERVER_NAME_PHONETIC, // available when connected, always up-to-date
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
#include <cstddef>
|
||||
#include "plugin_definitions.h"
|
||||
#include "teamspeak/public_definitions.h"
|
||||
#include <cstddef>
|
||||
|
||||
/* Functions exported to plugin from main binary */
|
||||
struct TS3Functions {
|
||||
|
||||
+462
-369
@@ -1,424 +1,517 @@
|
||||
#include "echoion/plugin/CoreLoader.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "dylib.hpp"
|
||||
#include <format>
|
||||
#include <thread>
|
||||
#include "echoion/plugin/CoreLoader.hpp"
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Plugin {
|
||||
namespace Echoion::Plugin
|
||||
{
|
||||
|
||||
CoreLoader::CoreLoader() {
|
||||
cleanupTempFiles();
|
||||
}
|
||||
CoreLoader::CoreLoader() { cleanupTempFiles(); }
|
||||
|
||||
void CoreLoader::enableAutoReload() {
|
||||
if (autoReloadEnabled_.exchange(true)) {
|
||||
return; // Already enabled
|
||||
}
|
||||
|
||||
std::lock_guard<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::enableAutoReload()
|
||||
{
|
||||
if (autoReloadEnabled_.exchange(true)) {
|
||||
return; // Already enabled
|
||||
}
|
||||
|
||||
void CoreLoader::disableAutoReload() {
|
||||
autoReloadEnabled_ = false;
|
||||
fileWatcher_.stopWatching();
|
||||
ECHOION_LOG_INFO("Auto-reload disabled");
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!currentLibraryPath_.empty() &&
|
||||
std::filesystem::exists(currentLibraryPath_)) {
|
||||
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
|
||||
currentLibraryPath_.string()));
|
||||
|
||||
bool CoreLoader::isAutoReloadEnabled() const noexcept {
|
||||
return autoReloadEnabled_.load();
|
||||
}
|
||||
fileWatcher_.startWatching(currentLibraryPath_,
|
||||
[this]() { onCoreFileChanged(); });
|
||||
}
|
||||
}
|
||||
|
||||
void CoreLoader::onCoreFileChanged() {
|
||||
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("Core file changed, scheduling hot reload after current track...");
|
||||
|
||||
// Small delay to ensure file write is complete
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
|
||||
// Check if playback is active - if so, defer reload
|
||||
if (isPlaybackActive()) {
|
||||
std::string currentTrackId;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = true;
|
||||
pendingReloadPath_ = currentLibraryPath_;
|
||||
|
||||
// Capture current track ID
|
||||
auto state = core_->getPlaybackState();
|
||||
if (state && state->currentTrack.has_value()) {
|
||||
pendingTrackId_ = state->currentTrack->track.id;
|
||||
currentTrackId = pendingTrackId_;
|
||||
}
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Playback active (track: {}), deferring reload until track finishes", currentTrackId));
|
||||
|
||||
// Start background thread to wait for track end
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
deferredReloadThread_.join();
|
||||
}
|
||||
deferredReloadThread_ = std::thread([this, currentTrackId]() {
|
||||
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
|
||||
});
|
||||
} else {
|
||||
// No playback, reload immediately
|
||||
auto result = hotReload(currentLibraryPath_);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}", result.error().message));
|
||||
} else {
|
||||
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
|
||||
// Notify Plugin to re-register callbacks
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void CoreLoader::disableAutoReload()
|
||||
{
|
||||
autoReloadEnabled_ = false;
|
||||
fileWatcher_.stopWatching();
|
||||
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
|
||||
}
|
||||
|
||||
bool CoreLoader::isPlaybackActive() const {
|
||||
if (!core_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto state = core_->getPlaybackState();
|
||||
if (!state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if currently playing a track
|
||||
return state->isPlaying && state->currentTrack.has_value();
|
||||
}
|
||||
bool CoreLoader::isAutoReloadEnabled() const noexcept
|
||||
{
|
||||
return autoReloadEnabled_.load();
|
||||
}
|
||||
|
||||
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const {
|
||||
if (!core_ || trackId.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto state = core_->getPlaybackState();
|
||||
if (!state || !state->currentTrack.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return state->currentTrack->track.id == trackId;
|
||||
}
|
||||
void CoreLoader::onCoreFileChanged()
|
||||
{
|
||||
if (!autoReloadEnabled_.load() || hotReloading_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
void CoreLoader::waitForTrackAndReload(const std::filesystem::path& targetPath, const std::string& trackId) {
|
||||
ECHOION_LOG_INFO(std::format("Waiting for track {} to finish before reload...", trackId));
|
||||
|
||||
// Poll every 500ms to check if the specific track finished
|
||||
// (playback may continue with next track, but we only care about THIS track)
|
||||
while (isSameTrackPlaying(trackId)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("Track finished, starting hot reload");
|
||||
|
||||
// Clear pending flag
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = false;
|
||||
pendingTrackId_.clear();
|
||||
}
|
||||
|
||||
// Now do the reload
|
||||
auto result = hotReload(targetPath);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}", result.error().message));
|
||||
} else {
|
||||
ECHOION_LOG_INFO("Deferred hot-reload completed successfully");
|
||||
// Notify Plugin to re-register callbacks
|
||||
if (hotReloadCallback_) {
|
||||
hotReloadCallback_();
|
||||
}
|
||||
}
|
||||
}
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
"Core file changed, scheduling hot reload after current track...");
|
||||
|
||||
CoreLoader::~CoreLoader() {
|
||||
// Stop any deferred reload thread
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
// We can't really stop it gracefully, but we can detach it
|
||||
// to avoid hanging on shutdown
|
||||
deferredReloadThread_.detach();
|
||||
}
|
||||
unload();
|
||||
cleanupTempFiles();
|
||||
}
|
||||
// Small delay to ensure file write is complete
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
|
||||
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (loaded_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already loaded"));
|
||||
}
|
||||
// Check if playback is active - if so, defer reload
|
||||
if (isPlaybackActive()) {
|
||||
std::string currentTrackId;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = true;
|
||||
pendingReloadPath_ = currentLibraryPath_;
|
||||
|
||||
if (!std::filesystem::exists(libraryPath)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
std::format("Library not found: {}", libraryPath.string())));
|
||||
}
|
||||
// Capture current track ID
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (state && state->currentTrack.has_value()) {
|
||||
pendingTrackId_ = state->currentTrack->id;
|
||||
currentTrackId = pendingTrackId_;
|
||||
}
|
||||
}
|
||||
|
||||
tempLibraryPath_ = getTempLibraryPath(libraryPath);
|
||||
|
||||
try {
|
||||
std::filesystem::copy_file(libraryPath, tempLibraryPath_,
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy library to temp: {}", e.what())));
|
||||
}
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
std::format("Playback active (track: {}), deferring reload "
|
||||
"until track finishes",
|
||||
currentTrackId));
|
||||
|
||||
auto result = loadLibraryInternal(tempLibraryPath_);
|
||||
if (result) {
|
||||
currentLibraryPath_ = libraryPath;
|
||||
} else {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
// Start background thread to wait for track end
|
||||
if (deferredReloadThread_.joinable()) {
|
||||
deferredReloadThread_.join();
|
||||
}
|
||||
deferredReloadThread_ = std::thread([this, currentTrackId]() {
|
||||
waitForTrackAndReload(pendingReloadPath_, currentTrackId);
|
||||
});
|
||||
} else {
|
||||
// No playback, reload immediately
|
||||
auto result = hotReload(currentLibraryPath_);
|
||||
if (!result) {
|
||||
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_();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unload() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto result = unloadLibraryInternal();
|
||||
|
||||
if (!tempLibraryPath_.empty()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
bool CoreLoader::isPlaybackActive() const
|
||||
{
|
||||
if (!core_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (!loaded_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No core loaded to reload"));
|
||||
}
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (!state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
hotReloading_ = true;
|
||||
|
||||
ECHOION_LOG_INFO("Starting hot reload with temp file...");
|
||||
// Check if currently playing a track
|
||||
return state->isPlaying && state->currentTrack.has_value();
|
||||
}
|
||||
|
||||
auto state = saveStateInternal();
|
||||
|
||||
auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
||||
|
||||
if (!std::filesystem::exists(targetPath)) {
|
||||
hotReloading_ = false;
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
std::format("New library not found: {}", targetPath.string())));
|
||||
}
|
||||
bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const
|
||||
{
|
||||
if (!core_ || trackId.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
|
||||
|
||||
try {
|
||||
std::filesystem::copy_file(targetPath, newTempPath,
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
} catch (const std::exception& e) {
|
||||
hotReloading_ = false;
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(newTempPath, ec);
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy new library to temp: {}", e.what())));
|
||||
}
|
||||
auto state = core_->getPlaybackSummary();
|
||||
if (!state || !state->currentTrack.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto unloadResult = unloadLibraryInternal();
|
||||
if (!unloadResult) {
|
||||
hotReloading_ = false;
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(newTempPath, ec);
|
||||
return unloadResult;
|
||||
}
|
||||
return state->currentTrack->id == trackId;
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
tempLibraryPath_ = newTempPath;
|
||||
void CoreLoader::waitForTrackAndReload(
|
||||
const std::filesystem::path& targetPath, const std::string& trackId)
|
||||
{
|
||||
Void::Log::info("CoreLoader", "{}", std::format(
|
||||
"Waiting for track {} to finish before reload...", trackId));
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
// Poll every 500ms to check if the specific track finished
|
||||
// (playback may continue with next track, but we only care about THIS
|
||||
// track). The wait is interruptible so the destructor can join this
|
||||
// thread instead of detaching it (detaching risks use-after-free when
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
auto loadResult = loadLibraryInternal(tempLibraryPath_);
|
||||
if (!loadResult) {
|
||||
hotReloading_ = false;
|
||||
return loadResult;
|
||||
}
|
||||
if (stopDeferredReload_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto restoreResult = restoreStateInternal(state);
|
||||
if (!restoreResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Failed to restore state: {}", restoreResult.error().message));
|
||||
}
|
||||
Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload");
|
||||
|
||||
currentLibraryPath_ = targetPath;
|
||||
hotReloading_ = false;
|
||||
|
||||
ECHOION_LOG_INFO("Hot reload complete");
|
||||
return {};
|
||||
}
|
||||
// Clear pending flag
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingReloadMutex_);
|
||||
hasPendingReload_ = false;
|
||||
pendingTrackId_.clear();
|
||||
}
|
||||
|
||||
bool CoreLoader::isLoaded() const noexcept {
|
||||
return loaded_.load();
|
||||
}
|
||||
// Now do the reload
|
||||
auto result = hotReload(targetPath);
|
||||
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_();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Api::CoreInterfacePtr CoreLoader::getCore() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return core_;
|
||||
}
|
||||
CoreLoader::~CoreLoader()
|
||||
{
|
||||
// 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();
|
||||
}
|
||||
|
||||
void CoreLoader::setConfigPath(const std::filesystem::path& configPath) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
}
|
||||
Api::Result<void> CoreLoader::load(const std::filesystem::path& libraryPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
std::filesystem::path CoreLoader::getConfigPath() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
if (loaded_) {
|
||||
return Api::fail(Api::ErrorCode::AlreadyExists,
|
||||
"Core already loaded");
|
||||
}
|
||||
|
||||
bool CoreLoader::isHotReloading() const noexcept {
|
||||
return hotReloading_.load();
|
||||
}
|
||||
if (!std::filesystem::exists(libraryPath)) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Library not found: {}", libraryPath.string()));
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::loadLibraryInternal(const std::filesystem::path& path) {
|
||||
try {
|
||||
ECHOION_LOG_INFO(std::format("Loading core library: {}", path.string()));
|
||||
// Use no decorations - the path already has the correct extension (.ts)
|
||||
library_ = std::make_unique<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");
|
||||
tempLibraryPath_ = getTempLibraryPath(libraryPath);
|
||||
|
||||
if (!compatibleFunc(Api::VERSION_MAJOR, Api::VERSION_MINOR)) {
|
||||
library_.reset();
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
|
||||
std::format("API version mismatch. Expected {}.{}, got {}",
|
||||
Api::VERSION_MAJOR, Api::VERSION_MINOR, versionFunc())));
|
||||
}
|
||||
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()));
|
||||
}
|
||||
|
||||
core_ = createFunc();
|
||||
if (!core_) {
|
||||
library_.reset();
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::UnknownError,
|
||||
"Failed to create core instance"));
|
||||
}
|
||||
auto result = loadLibraryInternal(tempLibraryPath_);
|
||||
if (result) {
|
||||
currentLibraryPath_ = libraryPath;
|
||||
} else {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
auto initResult = core_->initialize(configPath_);
|
||||
if (!initResult) {
|
||||
core_.reset();
|
||||
library_.reset();
|
||||
return initResult;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
loaded_ = true;
|
||||
Api::Result<void> CoreLoader::unload()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Core library loaded (API version: {})", versionFunc()));
|
||||
return {};
|
||||
auto result = unloadLibraryInternal();
|
||||
|
||||
} 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())));
|
||||
}
|
||||
}
|
||||
if (!tempLibraryPath_.empty()) {
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(tempLibraryPath_, ec);
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::unloadLibraryInternal() {
|
||||
if (!loaded_) {
|
||||
return {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("Unloading core library...");
|
||||
Api::Result<void>
|
||||
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (core_) {
|
||||
core_->shutdown();
|
||||
core_.reset();
|
||||
}
|
||||
if (!loaded_) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
"No core loaded to reload");
|
||||
}
|
||||
|
||||
library_.reset();
|
||||
hotReloading_ = true;
|
||||
|
||||
loaded_ = false;
|
||||
ECHOION_LOG_INFO("Core library unloaded");
|
||||
return {};
|
||||
}
|
||||
Void::Log::info("CoreLoader", "{}", "Starting hot reload with temp file...");
|
||||
|
||||
Api::HotReloadState CoreLoader::saveStateInternal() {
|
||||
if (!core_) {
|
||||
return Api::HotReloadState{};
|
||||
}
|
||||
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
|
||||
Api::StateBlob stateBlob;
|
||||
if (core_) {
|
||||
stateBlob = core_->saveState();
|
||||
Void::Log::info("CoreLoader", "{}",
|
||||
std::format("Saved state: version={}, size={} bytes",
|
||||
stateBlob.version, stateBlob.size()));
|
||||
}
|
||||
|
||||
auto state = core_->prepareForHotReload();
|
||||
if (state) {
|
||||
return *state;
|
||||
}
|
||||
auto targetPath =
|
||||
newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
|
||||
|
||||
ECHOION_LOG_WARNING("Failed to save state for hot reload");
|
||||
return Api::HotReloadState{};
|
||||
}
|
||||
if (!std::filesystem::exists(targetPath)) {
|
||||
hotReloading_ = false;
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("New library not found: {}", targetPath.string()));
|
||||
}
|
||||
|
||||
Api::Result<void> CoreLoader::restoreStateInternal(const Api::HotReloadState& state) {
|
||||
if (!core_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"Core not available for state restore"));
|
||||
}
|
||||
std::filesystem::path newTempPath = getTempLibraryPath(targetPath);
|
||||
|
||||
return core_->restoreAfterHotReload(state);
|
||||
}
|
||||
try {
|
||||
std::filesystem::copy_file(
|
||||
targetPath, newTempPath,
|
||||
std::filesystem::copy_options::overwrite_existing);
|
||||
} catch (const std::exception& e) {
|
||||
hotReloading_ = false;
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(newTempPath, ec);
|
||||
return Api::fail(Api::ErrorCode::UnknownError,
|
||||
std::format("Failed to copy new library to temp: {}",
|
||||
e.what()));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
auto unloadResult = unloadLibraryInternal();
|
||||
if (!unloadResult) {
|
||||
hotReloading_ = false;
|
||||
std::error_code ec;
|
||||
std::filesystem::remove(newTempPath, ec);
|
||||
return unloadResult;
|
||||
}
|
||||
|
||||
void CoreLoader::cleanupTempFiles() {
|
||||
auto tempDir = std::filesystem::temp_directory_path();
|
||||
std::error_code ec;
|
||||
|
||||
for (const auto& entry : std::filesystem::directory_iterator(tempDir, ec)) {
|
||||
if (entry.is_regular_file()) {
|
||||
auto name = entry.path().filename().string();
|
||||
if (name.starts_with("echoion_") &&
|
||||
(name.ends_with(".dll") || name.ends_with(".so") || name.ends_with(".ts"))) {
|
||||
std::filesystem::remove(entry.path(), ec);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::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
|
||||
+79
-75
@@ -1,94 +1,98 @@
|
||||
#include "echoion/plugin/FileWatcher.hpp"
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
|
||||
namespace Echoion::Plugin {
|
||||
namespace Echoion::Plugin
|
||||
{
|
||||
|
||||
FileWatcher::FileWatcher() = default;
|
||||
FileWatcher::FileWatcher() = default;
|
||||
|
||||
FileWatcher::~FileWatcher() {
|
||||
stopWatching();
|
||||
}
|
||||
FileWatcher::~FileWatcher() { stopWatching(); }
|
||||
|
||||
void FileWatcher::startWatching(
|
||||
const std::filesystem::path& filePath,
|
||||
ChangeCallback callback,
|
||||
std::chrono::milliseconds intervalMs) {
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (watching_.load()) {
|
||||
stopWatching();
|
||||
}
|
||||
void FileWatcher::startWatching(const std::filesystem::path& filePath,
|
||||
ChangeCallback callback,
|
||||
std::chrono::milliseconds intervalMs)
|
||||
{
|
||||
|
||||
watchedPath_ = filePath;
|
||||
callback_ = std::move(callback);
|
||||
intervalMs_ = intervalMs;
|
||||
stopRequested_ = false;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
// Get initial file state
|
||||
if (std::filesystem::exists(watchedPath_)) {
|
||||
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
|
||||
lastFileSize_ = std::filesystem::file_size(watchedPath_);
|
||||
}
|
||||
if (watching_.load()) {
|
||||
stopWatching();
|
||||
}
|
||||
|
||||
watching_ = true;
|
||||
watchThread_ = std::thread(&FileWatcher::watchLoop, this);
|
||||
}
|
||||
watchedPath_ = filePath;
|
||||
callback_ = std::move(callback);
|
||||
intervalMs_ = intervalMs;
|
||||
stopRequested_ = false;
|
||||
|
||||
void FileWatcher::stopWatching() {
|
||||
stopRequested_ = true;
|
||||
|
||||
if (watchThread_.joinable()) {
|
||||
watchThread_.join();
|
||||
}
|
||||
|
||||
watching_ = false;
|
||||
}
|
||||
// Get initial file state
|
||||
if (std::filesystem::exists(watchedPath_)) {
|
||||
lastWriteTime_ = std::filesystem::last_write_time(watchedPath_);
|
||||
lastFileSize_ = std::filesystem::file_size(watchedPath_);
|
||||
}
|
||||
|
||||
bool FileWatcher::isWatching() const noexcept {
|
||||
return watching_.load();
|
||||
}
|
||||
watching_ = true;
|
||||
watchThread_ = std::thread(&FileWatcher::watchLoop, this);
|
||||
}
|
||||
|
||||
void FileWatcher::watchLoop() {
|
||||
while (!stopRequested_.load()) {
|
||||
// Sleep first to avoid checking immediately
|
||||
std::this_thread::sleep_for(intervalMs_);
|
||||
|
||||
if (stopRequested_.load()) {
|
||||
break;
|
||||
}
|
||||
void FileWatcher::stopWatching()
|
||||
{
|
||||
stopRequested_ = true;
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (!std::filesystem::exists(watchedPath_)) {
|
||||
continue;
|
||||
}
|
||||
if (watchThread_.joinable()) {
|
||||
watchThread_.join();
|
||||
}
|
||||
|
||||
try {
|
||||
auto currentWriteTime = std::filesystem::last_write_time(watchedPath_);
|
||||
auto currentFileSize = std::filesystem::file_size(watchedPath_);
|
||||
watching_ = false;
|
||||
}
|
||||
|
||||
// Check if file has changed (time or size)
|
||||
if (currentWriteTime != lastWriteTime_ || currentFileSize != lastFileSize_) {
|
||||
// Update stored values
|
||||
lastWriteTime_ = currentWriteTime;
|
||||
lastFileSize_ = currentFileSize;
|
||||
bool FileWatcher::isWatching() const noexcept { return watching_.load(); }
|
||||
|
||||
// Trigger callback
|
||||
if (callback_) {
|
||||
try {
|
||||
callback_();
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << std::format("FileWatcher callback error: {}", e.what()) << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
// Ignore errors (file might be locked during write)
|
||||
}
|
||||
}
|
||||
}
|
||||
void FileWatcher::watchLoop()
|
||||
{
|
||||
while (!stopRequested_.load()) {
|
||||
// Sleep first to avoid checking immediately
|
||||
std::this_thread::sleep_for(intervalMs_);
|
||||
|
||||
if (stopRequested_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
std::lock_guard<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
|
||||
+655
-413
File diff suppressed because it is too large.
Load diff
+1438
-1010
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user