diff --git a/CMakeLists.txt b/CMakeLists.txt index a784d59..b4a27a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.28) +cmake_minimum_required(VERSION 4.0.0) project(EchoionCore VERSION 1.0.0 LANGUAGES CXX) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") set(CMAKE_CXX_STANDARD 26) @@ -6,38 +6,39 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) add_definitions(-DECHOION_API_EXPORT) - -add_library(EchoionCore SHARED - src/Logger.cpp - src/NetworkClient.cpp - src/SignatureCipher.cpp - src/YouTubeClient.cpp - src/YtDlpManager.cpp - src/UrlShortener.cpp - src/AudioDecoder.cpp - src/CommandManager.cpp - src/MusicManager.cpp - src/SubscriptionManager.cpp - src/Core.cpp - src/Export.cpp - src/EventBus.cpp - src/Cache.cpp - src/MemoryPool.cpp - src/Database.cpp - src/RpcServer.cpp - src/ConfigLoader.cpp +file(GLOB_RECURSE CORE_SOURCES + CONFIGURE_DEPENDS + "src/**.cpp" ) +add_library(EchoionCore SHARED ${CORE_SOURCES}) add_library(Echoion::Core ALIAS EchoionCore) target_include_directories(EchoionCore PUBLIC $ + $ $ ) -target_link_libraries(EchoionCore PUBLIC Echoion::Api) +# Core uses all API modules +target_link_libraries(EchoionCore PUBLIC + Echoion::ApiBase + Echoion::ApiAudio + Echoion::ApiTrack + Echoion::ApiNetwork + Echoion::ApiPlugin + Echoion::ApiConfig + Echoion::ApiRpc + Echoion::ApiYouTube + Echoion::ApiLogger + Echoion::ApiEventBus + Echoion::ApiDatabase + Echoion::ApiOpaque + Echoion::ApiPluginInterface + Echoion::ApiCoreInterface + Echoion::ApiUtils +) -find_package(glaze CONFIG REQUIRED) find_package(PkgConfig REQUIRED) pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET libavformat @@ -52,6 +53,21 @@ CPMAddPackage( GIT_TAG v0.11.0 ) +# quickjs-ng v0.11.0 compiles its C sources with -Werror, which trips newer GCC +# diagnostics (e.g. -Wmaybe-uninitialized / -Wdiscarded-qualifiers under GCC 16+). +# It is a vendored third-party dependency, so relax -Werror on every target it +# defines (qjs, qjsc, qjs-libc, ...) rather than guessing target names. +if(quickjs_SOURCE_DIR) + get_property(_qjs_targets DIRECTORY "${quickjs_SOURCE_DIR}" + PROPERTY BUILDSYSTEM_TARGETS) + foreach(_qjs_target ${_qjs_targets}) + get_target_property(_qjs_type ${_qjs_target} TYPE) + if(NOT _qjs_type STREQUAL "INTERFACE_LIBRARY") + target_compile_options(${_qjs_target} PRIVATE -Wno-error) + endif() + endforeach() +endif() + set(AddBoost.cmake_VERSION 3.7.3) CPMAddPackage( NAME AddBoost.cmake @@ -68,19 +84,25 @@ add_boost( BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore ) - find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(SQLite3 REQUIRED) find_package(TBB REQUIRED) -target_link_libraries(EchoionCore +target_link_libraries(EchoionCore PUBLIC PkgConfig::LIBAV TBB::tbb SQLite::SQLite3 + # VoidLibrary modules (migration target — replacing in-house infra) + Void::Data + Void::Functional + Void::System + Void::Log + Void::Async + Void::Containers + Void::Resilience PRIVATE - glaze::glaze Threads::Threads qjs Boost::beast @@ -88,7 +110,6 @@ target_link_libraries(EchoionCore Boost::asio OpenSSL::SSL OpenSSL::Crypto - ) if(MSVC) @@ -107,19 +128,46 @@ set_target_properties(EchoionCore PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) -# PackageProject.cmake configuration -packageProject( - NAME EchoionCore +# Export EchoionCore +target_include_directories(EchoionCore PUBLIC + $ + $ +) + +install(TARGETS EchoionCore + EXPORT EchoionCoreTargets + RUNTIME DESTINATION bin + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib + INCLUDES DESTINATION include +) + +install(EXPORT EchoionCoreTargets + FILE EchoionCoreTargets.cmake + NAMESPACE Echoion:: + DESTINATION lib/cmake/EchoionCore +) + +# Package config files +include(CMakePackageConfigHelpers) +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.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}/EchoionCoreConfig.cmake" +"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionCoreTargets.cmake\") +include(CMakeFindDependencyMacro) +find_dependency(EchoionApi) +") + +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake" + DESTINATION lib/cmake/EchoionCore ) -# Optional: Bundle FFmpeg libraries for distribution option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF) if(BUNDLE_FFMPEG) include(cmake/BundleFFmpeg.cmake) diff --git a/include/echoion/core/AudioDecoder.hpp b/include/echoion/core/AudioDecoder.hpp index df3a86d..e9e739d 100644 --- a/include/echoion/core/AudioDecoder.hpp +++ b/include/echoion/core/AudioDecoder.hpp @@ -1,146 +1,169 @@ #pragma once -#include -#include -#include -#include -#include +#include "NetworkTypes.hpp" +#include +#include #include -#include +#include +#include #include +#include +#include +#include // Forward declarations for FFmpeg extern "C" { - struct AVFormatContext; - struct AVCodecContext; - struct AVFrame; - struct AVPacket; - struct SwrContext; - struct AVBufferRef; +struct AVFormatContext; +struct AVCodecContext; +struct AVFrame; +struct AVPacket; +struct SwrContext; +struct AVBufferRef; } -namespace Echoion::Core { +namespace Echoion::Core +{ -class AudioDecoder { -public: - AudioDecoder(); - ~AudioDecoder(); + class AudioDecoder + { + public: - // Initialize decoder with optional hardware acceleration - Api::Result initialize(const Api::HwAccelConfig& hwConfig = {}); - void shutdown(); + AudioDecoder(); + ~AudioDecoder(); - // Open audio source (URL or file path) - Api::Result openSource(const std::string& url); - void closeSource(); + // Initialize decoder with optional hardware acceleration + Api::Result + initialize(const Api::HwAccelConfig& hwConfig = {}); + void shutdown(); - // Decode audio - returns zero-copy pooled buffer - [[nodiscard]] Api::Result decodeFrame(); - - // Seek to position - Api::Result seek(std::chrono::milliseconds position); + // Open audio source (URL or file path) + Api::Result openSource(const std::string& url); + void closeSource(); - // Get audio info - [[nodiscard]] Api::Result getStreamInfo() const; - - // Get current position - [[nodiscard]] std::chrono::milliseconds getPosition() const; - - // Check if decoder has more data - [[nodiscard]] bool hasMoreData() const; + // Decode audio - returns zero-copy pooled buffer + [[nodiscard]] Api::Result decodeFrame(); - // Set output format - void setOutputFormat(uint32_t sampleRate, uint32_t channels); + // Seek to position + Api::Result seek(std::chrono::milliseconds position); - // Set proxy configuration for network requests - void setProxyConfig(const std::optional& proxy); - - // Hardware acceleration - [[nodiscard]] bool isHardwareAccelerated() const { return hwAccelEnabled_; } - [[nodiscard]] Api::HwAccelType getHwAccelType() const { return hwAccelType_; } - - // Enable/disable zero-copy mode - void setZeroCopyEnabled(bool enabled) { zeroCopyEnabled_ = enabled; } - [[nodiscard]] bool isZeroCopyEnabled() const { return zeroCopyEnabled_; } - - // Get decoder statistics - struct Stats { - uint64_t framesDecoded = 0; - uint64_t framesDropped = 0; - uint64_t bytesDecoded = 0; - std::chrono::milliseconds totalDecodeTime{0}; - double averageDecodeTimeMs = 0.0; - bool hwAccelerationActive = false; - }; - [[nodiscard]] Stats getStats() const; - - // Get next S16 chunk (like reference implementation) - bool getNextChunk(std::vector& outChunk, bool blocking = false); - - // Check if decode is finished - [[nodiscard]] bool isFinished() const { return eof_.load(); } + // Get audio info + [[nodiscard]] Api::Result + getStreamInfo() const; -private: - void decodeThread(); - Api::Result readPacket(); - Api::Result convertFrame(); - void cleanupFfmpeg(); - - // Hardware acceleration setup - Api::Result initializeHardwareAccel(const Api::HwAccelConfig& config); - void cleanupHardwareAccel(); + // Get current position + [[nodiscard]] std::chrono::milliseconds getPosition() const; - // Frame conversion (returns int16 for direct playback) - Api::Result convertFramePooled(); + // Check if decoder has more data + [[nodiscard]] bool hasMoreData() const; - // FFmpeg contexts - AVFormatContext* formatContext_ = nullptr; - AVCodecContext* codecContext_ = nullptr; - AVFrame* frame_ = nullptr; - AVPacket* packet_ = nullptr; - SwrContext* swrContext_ = nullptr; - uint8_t* outputBuffer_ = nullptr; // For S16 output like reference - - // Hardware acceleration - AVBufferRef* hwDeviceContext_ = nullptr; - AVBufferRef* hwFramesContext_ = nullptr; - bool hwAccelEnabled_ = false; - Api::HwAccelType hwAccelType_ = Api::HwAccelType::None; - bool zeroCopyEnabled_ = true; + // Set output format + void setOutputFormat(uint32_t sampleRate, uint32_t channels); - // Stream info - int audioStreamIndex_ = -1; - Api::AudioStreamInfo streamInfo_; - - // Output format - uint32_t outputSampleRate_ = 192000; - uint32_t outputChannels_ = 2; + // Set proxy configuration for network requests + void setProxyConfig(const std::optional& proxy); - // Threading - std::jthread decodeThread_; - mutable std::mutex mutex_; - std::condition_variable cv_; - std::queue decodedQueue_; - static constexpr size_t MAX_QUEUE_SIZE = 50; - - // S16 audio queue (like reference) - avoids float conversion - std::deque> int16Queue_; - static constexpr size_t MAX_INT16_QUEUE_SIZE = 100; + // Hardware acceleration + [[nodiscard]] bool isHardwareAccelerated() const + { + return hwAccelEnabled_; + } + [[nodiscard]] Api::HwAccelType getHwAccelType() const + { + return hwAccelType_; + } - // State - std::atomic initialized_{false}; - std::atomic decoding_{false}; - std::atomic eof_{false}; - std::atomic shouldExit_{false}; // For FFmpeg interrupt callback - std::chrono::milliseconds currentPosition_{0}; - std::string currentUrl_; + // Enable/disable zero-copy mode + void setZeroCopyEnabled(bool enabled) + { + zeroCopyEnabled_ = enabled; + } + [[nodiscard]] bool isZeroCopyEnabled() const + { + return zeroCopyEnabled_; + } - std::atomic streamSampleRate_{48000}; - std::optional proxyConfig_; - - // Statistics - mutable std::mutex statsMutex_; - Stats stats_; -}; + // Get decoder statistics + struct Stats { + uint64_t framesDecoded = 0; + uint64_t framesDropped = 0; + uint64_t bytesDecoded = 0; + std::chrono::milliseconds totalDecodeTime{0}; + double averageDecodeTimeMs = 0.0; + bool hwAccelerationActive = false; + }; + [[nodiscard]] Stats getStats() const; + + // Get next S16 chunk (like reference implementation) + bool getNextChunk(std::vector& outChunk, + bool blocking = false); + + // Check if decode is finished + [[nodiscard]] bool isFinished() const { return eof_.load(); } + + private: + + void decodeThread(); + Api::Result readPacket(); + Api::Result convertFrame(); + void cleanupFfmpeg(); + + // Hardware acceleration setup + Api::Result + initializeHardwareAccel(const Api::HwAccelConfig& config); + void cleanupHardwareAccel(); + + // Frame conversion (returns int16 for direct playback) + Api::Result convertFramePooled(); + + // FFmpeg contexts + AVFormatContext* formatContext_ = nullptr; + AVCodecContext* codecContext_ = nullptr; + AVFrame* frame_ = nullptr; + AVPacket* packet_ = nullptr; + SwrContext* swrContext_ = nullptr; + uint8_t* outputBuffer_ = nullptr; // For S16 output like reference + + // Hardware acceleration + AVBufferRef* hwDeviceContext_ = nullptr; + AVBufferRef* hwFramesContext_ = nullptr; + bool hwAccelEnabled_ = false; + Api::HwAccelType hwAccelType_ = Api::HwAccelType::None; + bool zeroCopyEnabled_ = true; + + // Stream info + int audioStreamIndex_ = -1; + Api::AudioStreamInfo streamInfo_; + + // Output format + uint32_t outputSampleRate_ = 192000; + uint32_t outputChannels_ = 2; + + // Threading + std::jthread decodeThread_; + mutable std::mutex mutex_; + std::condition_variable cv_; + std::queue decodedQueue_; + static constexpr size_t MAX_QUEUE_SIZE = 50; + + // S16 audio queue (like reference) - avoids float conversion + std::deque> int16Queue_; + static constexpr size_t MAX_INT16_QUEUE_SIZE = 100; + + // State + std::atomic initialized_{false}; + std::atomic decoding_{false}; + std::atomic eof_{false}; + std::atomic shouldExit_{ + false}; // For FFmpeg interrupt callback + std::chrono::milliseconds currentPosition_{0}; + std::string currentUrl_; + + std::atomic streamSampleRate_{48000}; + std::optional proxyConfig_; + + // Statistics + mutable std::mutex statsMutex_; + Stats stats_; + }; } // namespace Echoion::Core diff --git a/include/echoion/core/CommandManager.hpp b/include/echoion/core/CommandManager.hpp index 88849fb..3f65c96 100644 --- a/include/echoion/core/CommandManager.hpp +++ b/include/echoion/core/CommandManager.hpp @@ -1,10 +1,11 @@ #pragma once #include "commands/Command.hpp" -#include "echoion/api/ConfigTypes.hpp" +#include +#include +#include #include #include -#include #include #include #include @@ -15,151 +16,163 @@ #include #include -namespace Echoion::Core { +namespace Echoion::Core +{ -class MusicManager; + class MusicManager; -// Function to check if client has permission (set by Core) -using PermissionCheckFunc = std::function; - -/** - * @brief Manages command registration and dispatch. - * - * Usage: - * CommandManager mgr; - * mgr.registerCommand("play"); - * mgr.dispatch(clientId, "play song name", musicManager, replyFunc); - */ -class CommandManager { -public: - CommandManager(); - ~CommandManager(); - - // Shutdown the command manager (stops thread pool) - void shutdown(); - - // Disable copy - CommandManager(const CommandManager&) = delete; - CommandManager& operator=(const CommandManager&) = delete; - - // Enable move - CommandManager(CommandManager&&) = default; - CommandManager& operator=(CommandManager&&) = default; - - /** - * @brief Registers a command class. - * @tparam T The command class (must inherit Command). - * @param primaryName The primary name/trigger (e.g., "play"). - */ - template - void registerCommand(const std::string& primaryName) { - auto cmd = std::make_shared(); - - std::lock_guard lock(mutex_); - - // Register primary name - commands_[primaryName] = cmd; - uniqueCommands_.push_back({primaryName, cmd}); - - // Register aliases automatically from the class itself - for (auto alias : cmd->getAliases()) { - commands_[std::string(alias)] = cmd; - } - } + // Function to check if client has permission (set by Core) + using PermissionCheckFunc = + std::function; /** - * @brief Dispatches a command message to the appropriate handler (ASYNC). - * Commands are executed in a thread pool, allowing multiple users to - * use the bot simultaneously without blocking. - * @param clientId The client ID who invoked the command. - * @param message The full message (including prefix, e.g., "!play song"). - * @param musicManager Weak pointer to the MusicManager. - * @param replyFunc Function to call to send a reply. - * @param invokerName Name of the invoking user. - * @return true if a command was found and queued for execution, false - * otherwise. + * @brief Manages command registration and dispatch. + * + * Usage: + * CommandManager mgr; + * mgr.registerCommand("play"); + * mgr.dispatch(clientId, "play song name", musicManager, replyFunc); */ - [[nodiscard]] bool dispatch(uint64_t clientId, - std::string_view message, - std::weak_ptr musicManager, - std::function replyFunc, - std::string_view invokerName = ""); + class CommandManager + { + public: - /** - * @brief Executes a command synchronously (for internal use). - * Prefer using dispatch() for normal command handling. - */ - [[nodiscard]] bool - dispatchSync(uint64_t clientId, - std::string_view message, - std::weak_ptr musicManager, - std::function replyFunc, - std::string_view invokerName = ""); + CommandManager(); + ~CommandManager(); - [[nodiscard]] bool hasCommand(std::string_view name) const; - [[nodiscard]] std::optional getCommand(std::string_view name) const; - [[nodiscard]] std::vector> getAllCommands() const; - - // Get commands visible to a specific client (for help) - [[nodiscard]] std::vector> getVisibleCommands(uint64_t clientId) const; - - // Check if client can execute a command - [[nodiscard]] bool canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const; + // Shutdown the command manager (stops thread pool) + void shutdown(); - void setPrefix(std::string_view prefix); - [[nodiscard]] std::string_view getPrefix() const { return prefix_; } - - // Set permission check function - void setPermissionCheckFunc(PermissionCheckFunc func); - // Set server config for permission checks - void setServerConfig(const Api::AppConfig& config); + // Disable copy + CommandManager(const CommandManager&) = delete; + CommandManager& operator=(const CommandManager&) = delete; -private: - struct CommandEntry { - std::string primaryName; - CommandPtr instance; - }; + // Enable move + CommandManager(CommandManager&&) = default; + CommandManager& operator=(CommandManager&&) = default; - void registerBuiltinCommands(); - - // Internal Help Command (defined in .cpp to access registry) - class HelpCommand; - void registerHelpCommand(); + /** + * @brief Registers a command class. + * @tparam T The command class (must inherit Command). + * @param primaryName The primary name/trigger (e.g., "play"). + */ + template + void registerCommand(const std::string& primaryName) + { + auto cmd = std::make_shared(); - std::string prefix_ = "!"; - - // Map for fast lookup: "play" -> PlayCommand - std::map> commands_; - - // List for generating help: {"play", PlayCommand} - std::vector uniqueCommands_; - - mutable std::mutex mutex_; - - // Permission checking - PermissionCheckFunc permissionCheck_; - std::optional serverConfig_; + std::lock_guard lock(mutex_); - // Async command execution - struct CommandTask { - uint64_t clientId; - std::string message; - std::weak_ptr musicManager; - std::function replyFunc; - std::string invokerName; - }; + // Register primary name + commands_[primaryName] = cmd; + uniqueCommands_.push_back({primaryName, cmd}); - void startThreadPool(); - void processCommandQueue(); - void executeCommandAsync(CommandTask task); + // Register aliases automatically from the class itself + for (auto alias : cmd->getAliases()) { + commands_[std::string(alias)] = cmd; + } + } - std::vector workerThreads_; - std::queue commandQueue_; - std::mutex queueMutex_; - std::condition_variable queueCv_; - std::atomic shutdown_{false}; - static constexpr size_t THREAD_POOL_SIZE = - 4; // Handle up to 4 concurrent commands + /** + * @brief Dispatches a command message to the appropriate handler + * (ASYNC). Commands are executed in a thread pool, allowing + * multiple users to use the bot simultaneously without blocking. + * @param clientId The client ID who invoked the command. + * @param message The full message (including prefix, e.g., "!play + * song"). + * @param musicManager Weak pointer to the MusicManager. + * @param replyFunc Function to call to send a reply. + * @param invokerName Name of the invoking user. + * @return true if a command was found and queued for execution, + * false otherwise. + */ + [[nodiscard]] bool + dispatch(uint64_t clientId, + std::string_view message, + std::weak_ptr musicManager, + std::function replyFunc, + std::string_view invokerName = ""); -}; // namespace Echoion::Core + /** + * @brief Executes a command synchronously (for internal use). + * Prefer using dispatch() for normal command handling. + */ + [[nodiscard]] bool + dispatchSync(uint64_t clientId, + std::string_view message, + std::weak_ptr musicManager, + std::function replyFunc, + std::string_view invokerName = ""); + + [[nodiscard]] bool hasCommand(std::string_view name) const; + [[nodiscard]] std::optional + getCommand(std::string_view name) const; + [[nodiscard]] std::vector> + getAllCommands() const; + + // Get commands visible to a specific client (for help) + [[nodiscard]] std::vector> + getVisibleCommands(uint64_t clientId) const; + + // Check if client can execute a command + [[nodiscard]] bool canExecuteCommand(uint64_t clientId, + const CommandPtr& cmd) const; + + void setPrefix(std::string_view prefix); + [[nodiscard]] std::string_view getPrefix() const { return prefix_; } + + // Set permission check function + void setPermissionCheckFunc(PermissionCheckFunc func); + // Set server config for permission checks + void setServerConfig(const Api::AppConfig& config); + + private: + + struct CommandEntry { + std::string primaryName; + CommandPtr instance; + }; + + void registerBuiltinCommands(); + + // Internal Help Command (defined in .cpp to access registry) + class HelpCommand; + void registerHelpCommand(); + + std::string prefix_ = "!"; + + // Map for fast lookup: "play" -> PlayCommand + std::map> commands_; + + // List for generating help: {"play", PlayCommand} + std::vector uniqueCommands_; + + mutable std::mutex mutex_; + + // Permission checking + PermissionCheckFunc permissionCheck_; + std::optional serverConfig_; + + // Async command execution + struct CommandTask { + uint64_t clientId; + std::string message; + std::weak_ptr musicManager; + std::function replyFunc; + std::string invokerName; + }; + + void startThreadPool(); + void processCommandQueue(); + void executeCommandAsync(CommandTask task); + + std::vector workerThreads_; + std::queue commandQueue_; + std::mutex queueMutex_; + std::condition_variable queueCv_; + std::atomic shutdown_{false}; + static constexpr size_t THREAD_POOL_SIZE = + 4; // Handle up to 4 concurrent commands + + }; // namespace Echoion::Core } // namespace Echoion::Core diff --git a/include/echoion/core/ConfigLoader.hpp b/include/echoion/core/ConfigLoader.hpp index 878b4c8..2db1487 100644 --- a/include/echoion/core/ConfigLoader.hpp +++ b/include/echoion/core/ConfigLoader.hpp @@ -1,30 +1,132 @@ #pragma once -#include +#include +#include #include #include -namespace Echoion::Core { +namespace Echoion::Core +{ -// Configuration loader for JSON config files (internal to Core) -class ConfigLoader { -public: - // Load configuration from JSON file - [[nodiscard]] static Api::Result loadFromFile(const std::filesystem::path& path); - - // Save configuration to JSON file - [[nodiscard]] static Api::Result saveToFile(const std::filesystem::path& path, const Api::AppConfig& config); - - // Get default configuration path - [[nodiscard]] static std::filesystem::path getDefaultConfigPath(); - - // Create default configuration - [[nodiscard]] static Api::AppConfig createDefaultConfig(); + // JSON structures for configuration (public for use by Core) + struct BotConfigJson { + std::string botName = "Echoion"; + std::string commandPrefix = "!"; + float defaultVolume = 0.5f; + uint32_t maxQueueSize = 100; + uint32_t trackTimeout = 30000; + bool autoReconnect = true; + uint32_t reconnectDelay = 5000; + uint32_t maxReconnectAttempts = 5; + std::string preferredQuality = "High"; + bool allowPlaylistImports = true; + }; -private: - // Parse quality string to enum - [[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str); - [[nodiscard]] static std::string qualityToString(Api::AudioQuality quality); -}; + struct YouTubeConfigJson { + std::optional youtubeApiKey; + std::optional youtubeCookiesPath; + std::optional cookiesFromBrowser; + uint32_t ytDlpMaxConcurrent = 4; + bool ytDlpAsyncEnabled = true; + bool enableUrlShortening = true; + }; + + struct NetworkConfigJson { + // Proxy settings (flat structure for backward compatibility) + std::string proxyType = "HTTP"; + std::optional proxyHost; + std::optional proxyPort; + std::optional proxyUsername; + std::optional proxyPassword; + // RPC settings + bool rpcEnabled = true; + uint16_t rpcPort = 8765; + std::string rpcBindAddress = "127.0.0.1"; + }; + + struct TeamSpeakConfigJson { + std::string address = "localhost"; + uint16_t port = 9987; + std::string serverPassword = ""; + std::string nickname = "EchoionBot"; + std::optional defaultChannelId; + std::optional channelPassword; + std::vector adminGroups; + std::vector djGroups; + std::vector bannedGroups; + }; + + struct SecurityConfigJson { + bool requireAuthForAdmin = true; + uint32_t maxLoginAttempts = 5; + uint32_t lockoutDuration = 300000; + uint32_t sessionTimeout = 3600000; + bool enableAuditLog = true; + std::optional apiKey; + bool allowCors = false; + std::vector corsOrigins; + }; + + struct FeaturesConfigJson { + bool enableHotReload = true; + bool enableAutoReload = false; + bool enableAutoUpdateCheck = true; + bool autoStartOnSubscribe = true; + bool pauseOnEmptySubscribers = true; + bool resumeOnSubscriberReturn = true; + std::string shuffleMode = "random"; + std::string repeatMode = "off"; + uint32_t maxHistorySize = 50; + }; + + struct AdvancedConfigJson { + uint32_t sampleRate = 192000; + uint32_t channels = 2; + uint32_t bufferSize = 7680; + uint32_t commandThreadPoolSize = 4; + uint32_t networkThreadPoolSize = 4; + uint32_t decoderThreads = 2; + bool cacheEnabled = true; + std::string cacheMaxSize = "1GB"; + uint32_t cacheTTL = 86400; + uint32_t tempCleanupInterval = 3600; + }; + + struct AppConfigJson { + BotConfigJson bot; + YouTubeConfigJson youtube; + NetworkConfigJson network; + TeamSpeakConfigJson teamspeak; + SecurityConfigJson security; + FeaturesConfigJson features; + AdvancedConfigJson advanced; + }; + + // Configuration loader for JSON config files (internal to Core) + class ConfigLoader + { + public: + + // Load configuration from JSON file + [[nodiscard]] static Api::Result + loadFromFile(const std::filesystem::path& path); + + // Save configuration to JSON file + [[nodiscard]] static Api::Result + saveToFile(const std::filesystem::path& path, + const Api::AppConfig& config); + + // Get default configuration path + [[nodiscard]] static std::filesystem::path getDefaultConfigPath(); + + // Create default configuration + [[nodiscard]] static Api::AppConfig createDefaultConfig(); + + // Parse quality string to enum + [[nodiscard]] static Api::AudioQuality + parseQuality(const std::string& str); + [[nodiscard]] static std::string + qualityToString(Api::AudioQuality quality); + }; } // namespace Echoion::Core diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index 9c34e66..049f03e 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -1,111 +1,181 @@ #pragma once -#include -#include -#include "MusicManager.hpp" #include "CommandManager.hpp" +#include "ConfigLoader.hpp" +#include "MusicManager.hpp" #include "NetworkClient.hpp" #include "RpcServer.hpp" -#include "ConfigLoader.hpp" -#include -#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include -namespace Echoion::Core { +namespace Echoion::Core +{ -// Main Core implementation of ICoreInterface -class Core : public Api::ICoreInterface { -public: - Core(); - ~Core() override; + // Main Core implementation of ICoreInterface + class Core : public Api::ICoreInterface + { + public: - // ICoreInterface implementation - Api::Result initialize(const std::filesystem::path& configPath) override; - Api::Result shutdown() override; - [[nodiscard]] bool isInitialized() const noexcept override; + Core(); + ~Core() override; - // Playback control - Api::Result play(const Api::TrackInfo& track) override; - Api::Result pause() override; - Api::Result resume() override; - Api::Result stop() override; - Api::Result skip(uint32_t count) override; - Api::Result seek(std::chrono::milliseconds position) override; - Api::Result setVolume(float volume) override; + // ICoreInterface - Lifecycle + Api::Result + initialize(const std::filesystem::path& configPath) override; + Api::Result shutdown() override; + [[nodiscard]] bool isInitialized() const noexcept override; - // Queue management - Api::Result queueTrack(const Api::TrackInfo& track, uint64_t clientId) override; - Api::Result removeFromQueue(uint64_t queueId) override; - Api::Result clearQueue() override; - [[nodiscard]] Api::Result> getQueue() const override; - Api::Result moveInQueue(uint64_t queueId, uint32_t newPosition) override; + // ICoreInterface - Playback control (decoupled) + Api::Result play(const std::string& trackId) override; + Api::Result pause() override; + Api::Result resume() override; + Api::Result stop() override; + Api::Result skip(uint32_t count) override; + Api::Result seek(std::chrono::milliseconds position) override; + Api::Result setVolume(float volume) override; - // Track info - [[nodiscard]] Api::Result> getCurrentTrack() const override; - [[nodiscard]] Api::Result getPlaybackState() const override; + // ICoreInterface - Queue management (decoupled) + Api::Result queueTrack(const std::string& trackId, + uint64_t clientId) override; + Api::Result removeFromQueue(uint64_t queueId) override; + Api::Result clearQueue() override; + [[nodiscard]] Api::Result> + getQueueSummaries() const override; + Api::Result moveInQueue(uint64_t queueId, + uint32_t newPosition) override; - // Playlist - Api::Result loadPlaylist(const std::string& playlistId, uint64_t clientId) override; - [[nodiscard]] Api::Result> getPlaylists() const override; + // ICoreInterface - Track info (decoupled) + [[nodiscard]] Api::Result> + getCurrentTrackSummary() const override; + [[nodiscard]] Api::Result + getPlaybackSummary() const override; - // Configuration - Api::Result updateConfig(const Api::AppConfig& config) override; - [[nodiscard]] Api::Result getConfig() const override; - // Reload config from disk (stored path from initialize) - Api::Result reloadConfig(); + // ICoreInterface - Playlist (decoupled) + Api::Result loadPlaylist(const std::string& playlistId, + uint64_t clientId) override; + [[nodiscard]] Api::Result> + getPlaylistIds() const override; - // Hot reload - Api::Result prepareForHotReload() override; - Api::Result restoreAfterHotReload(const Api::HotReloadState& state) override; + // ICoreInterface - Configuration (decoupled) + Api::Result + updateConfigJson(const std::string& configJson) override; + [[nodiscard]] Api::Result + getConfigJson() const override; - // Event handling - void registerEventCallback(const Api::EventCallback& callback) override; - void unregisterEventCallback(const Api::EventCallback& callback) override; + // ICoreInterface - Hot reload (decoupled) + [[nodiscard]] Api::Result + prepareForHotReload() override; + Api::Result + restoreAfterHotReload(const std::string& state) override; - // Plugin event processing - Api::Result onPluginEvent(const Api::PluginEvent& event) override; + // ICoreInterface - Decoupled state management + [[nodiscard]] Api::StateBlob saveState() override; + Api::Result + restoreState(const Api::StateBlob& state) override; + [[nodiscard]] uint32_t getStateFormatVersion() const override; + [[nodiscard]] bool + canRestoreStateVersion(uint32_t version) const override; - // Status - [[nodiscard]] std::string getVersion() const override; - [[nodiscard]] std::chrono::system_clock::time_point getUptime() const override; + // ICoreInterface - Event handling + void registerEventCallback( + const Api::EventCallback& callback) override; + void unregisterEventCallback( + const Api::EventCallback& callback) override; - // Additional methods for plugin integration - void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override; - void setAudioDataCallback(const MusicManager::AudioDataCallback& callback); - void triggerAutoConnect() override; + // ICoreInterface - Plugin event processing + Api::Result + onPluginEvent(const Api::PluginEvent& event) override; -private: - void onMusicEvent(const Api::PluginEvent& event); - void broadcastEvent(const Api::PluginEvent& event); - [[nodiscard]] bool isAdmin(uint64_t clientId) const; - void updateWhisperList(); - void setupRpcHandlers(); + // ICoreInterface - Status + [[nodiscard]] std::string getVersion() const override; + [[nodiscard]] std::chrono::system_clock::time_point + getUptime() const override; - // Components - std::shared_ptr networkClient_; - std::shared_ptr musicManager_; - std::unique_ptr commandManager_; - Api::PluginInterfacePtr pluginInterface_; + // ICoreInterface - Plugin interface + void setPluginInterface( + Api::PluginInterfacePtr pluginInterface) override; + void triggerAutoConnect() override; - // State - Api::AppConfig config_; // Config loaded internally - std::filesystem::path configPath_; // Path to config file for reload - std::chrono::system_clock::time_point startTime_; - std::atomic initialized_{false}; + // ICoreInterface - Advanced (for internal Core-to-Core use) + [[nodiscard]] Api::Result> + getCurrentTrackHandle() const override; + [[nodiscard]] Api::Result< + std::vector>> + getQueueHandles() const override; + [[nodiscard]] Api::Result + getConfigHandle() const override; + Api::Result + updateConfigFromHandle(Api::AppConfigHandle config) override; - // Event callbacks - std::vector eventCallbacks_; - mutable std::mutex eventMutex_; + // Additional methods for internal use (not in interface) + void setAudioDataCallback( + const MusicManager::AudioDataCallback& callback); + Api::Result reloadConfig(); - // Admin tracking - std::vector adminClients_; - mutable std::mutex adminMutex_; - - // Database for persistence - std::shared_ptr database_; - - // RPC server for Desktop/API clients - std::shared_ptr rpcServer_; -}; + // Internal implementations using full types + Api::Result playTrack(const Api::TrackInfo& track); + Api::Result queueTrackFull(const Api::TrackInfo& track, + uint64_t clientId); + [[nodiscard]] Api::Result> + getQueue() const; + [[nodiscard]] Api::Result> + getCurrentTrack() const; + [[nodiscard]] Api::Result + getPlaybackState() const; + [[nodiscard]] Api::Result> + getPlaylists() const; + Api::Result updateConfig(const Api::AppConfig& config); + [[nodiscard]] Api::Result getConfig() const; + [[nodiscard]] Api::Result + prepareForHotReloadFull(); + Api::Result + restoreAfterHotReloadFull(const Api::HotReloadState& state); + + // Generate RPC tokens for existing subscribers + void generateRpcTokensForSubscribers(); + + private: + + void onMusicEvent(const Api::PluginEvent& event); + void broadcastEvent(const Api::PluginEvent& event); + [[nodiscard]] bool isAdmin(uint64_t clientId) const; + void updateWhisperList(); + void setupRpcHandlers(); + void setupEventBusSubscriptions() const noexcept; + + // Components + std::shared_ptr networkClient_; + std::shared_ptr musicManager_; + std::unique_ptr commandManager_; + Api::PluginInterfacePtr pluginInterface_; + + // State + Api::AppConfig config_; + std::filesystem::path configPath_; + std::chrono::system_clock::time_point startTime_; + std::atomic initialized_{false}; + + // Event callbacks + std::vector eventCallbacks_; + mutable std::mutex eventMutex_; + + // Admin tracking + std::vector adminClients_; + mutable std::mutex adminMutex_; + + // Database for persistence + std::shared_ptr database_; + + // RPC server for Desktop/API clients + std::shared_ptr rpcServer_; + }; } // namespace Echoion::Core diff --git a/include/echoion/core/Logger.hpp b/include/echoion/core/Logger.hpp index 340becb..da1f833 100644 --- a/include/echoion/core/Logger.hpp +++ b/include/echoion/core/Logger.hpp @@ -1,79 +1,77 @@ #pragma once -#include -#include -#include -#include -#include -#include +#include #include +#include #include +#include +#include +#include #include -#include -#include -#include -namespace Echoion::Core { +namespace Void::Logging +{ + class MultiLogger; +} // namespace Void::Logging -// Log file info for rotation -struct LogFileInfo { - std::filesystem::path path; - std::ofstream stream; - uint64_t size = 0; - std::chrono::system_clock::time_point createdAt; -}; +namespace Echoion::Core +{ -class Logger : public Api::ILogger { -public: - explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion"); - ~Logger() override; + // ILogger implementation backed by the Void::Logging framework. + // + // Output is produced by a Void MultiLogger fanning out to: + // * a ConsoleLogger (stdout), + // * a SplitFileLogger writing per-level files (/.log) plus a + // combined /all.log, each rolling independently by size, and + // * a CallbackLogger bridging back to the registered ILogger callbacks. + // The ILogger surface (levels, callbacks, console/file toggles, rotation + // knobs) is preserved so existing call sites and the ECHOION_LOG_* macros + // keep working unchanged. + class Logger : public Api::ILogger + { + public: - void log(Api::LogLevel level, std::string_view message, - std::source_location location) override; - void setMinLevel(Api::LogLevel level) override; - [[nodiscard]] Api::LogLevel getMinLevel() const override; - void registerCallback(const LogCallback& callback) override; - void unregisterCallback(const LogCallback& callback) override; + explicit Logger(std::string_view logDir = "logs", + std::string_view baseName = "echoion"); + ~Logger() override; - void flush(); - void setConsoleOutput(bool enabled); - void setFileOutput(bool enabled); - void setMaxFileSize(uint64_t bytes); - void setMaxFiles(uint32_t count); + void log(Api::LogLevel level, std::string_view message, + std::source_location location) override; + void setMinLevel(Api::LogLevel level) override; + [[nodiscard]] Api::LogLevel getMinLevel() const override; + void registerCallback(const LogCallback& callback) override; + void unregisterCallback(const LogCallback& callback) override; -private: - void logWorker(); - void rotateIfNeeded(Api::LogLevel level); - void openLogFiles(); - void cleanupOldLogs(); - void moveToHistory(const std::filesystem::path& filePath); - void ensureHistoryDirExists(); - [[nodiscard]] std::string formatLogEntry(const Api::LogEntry& entry); - [[nodiscard]] std::string levelToString(Api::LogLevel level); - [[nodiscard]] std::filesystem::path generateLogFilePath(Api::LogLevel level); - [[nodiscard]] std::string formatTimestamp(const std::chrono::system_clock::time_point& tp); - void writeToFile(Api::LogLevel level, const std::string& formattedEntry); + void flush(); + void setConsoleOutput(bool enabled); + void setFileOutput(bool enabled); + void setMaxFileSize(uint64_t bytes); + void setMaxFiles(uint32_t count); - std::filesystem::path logDir_; - std::string baseName_; - - // Separate files for each level + combined file - std::map levelFiles_; - LogFileInfo combinedFile_; - - std::mutex fileMutex_; - std::mutex queueMutex_; - std::queue logQueue_; - std::thread workerThread_; - std::condition_variable cv_; - std::atomic running_{true}; - std::atomic minLevel_{Api::LogLevel::Info}; - std::atomic consoleOutput_{true}; - std::atomic fileOutput_{true}; - std::atomic maxFileSize_{10 * 1024 * 1024}; // 10 MB per file - std::atomic maxFiles_{5}; - std::vector callbacks_; - std::mutex callbackMutex_; -}; + private: + + // (Re)assemble the Void sink tree from the current toggles/limits. + void rebuildSinks(); + // Fan a Void log entry out to the registered ILogger callbacks. + void dispatchToCallbacks(Api::LogLevel level, + const std::string& message, + const std::string& file, uint32_t line, + const std::string& function); + + std::filesystem::path logDir_; + std::string baseName_; + + std::shared_ptr sink_; + std::mutex sinkMutex_; + + std::atomic minLevel_{Api::LogLevel::Info}; + std::atomic consoleOutput_{true}; + std::atomic fileOutput_{true}; + std::atomic maxFileSize_{10 * 1024 * 1024}; // 10 MB + std::atomic maxFiles_{5}; + + std::vector callbacks_; + std::mutex callbackMutex_; + }; } // namespace Echoion::Core diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 2e43f0c..4d4b17f 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -1,205 +1,271 @@ #pragma once -#include -#include "NetworkClient.hpp" -#include "YouTubeClient.hpp" #include "AudioDecoder.hpp" +#include "Database.hpp" +#include "NetworkClient.hpp" +#include "RpcTypes.hpp" #include "SubscriptionManager.hpp" -#include -#include +#include "YouTubeClient.hpp" +#include +#include +#include +#include #include +#include +#include +#include #include #include -#include -#include #include +#include +#include #include -#include -namespace Echoion::Core { +namespace Echoion::Core +{ -class MusicManager { -public: - MusicManager(); - ~MusicManager(); + class MusicManager + { + public: - Api::Result initialize(const Api::BotConfig& config, - std::shared_ptr networkClient, - std::shared_ptr database = nullptr); - void shutdown(); + MusicManager(); + ~MusicManager(); - [[nodiscard]] Api::Result play(const std::string& query, uint64_t clientId); - [[nodiscard]] Api::Result pause(); - [[nodiscard]] Api::Result resume(); - [[nodiscard]] Api::Result stop(); - [[nodiscard]] Api::Result skip(uint32_t count = 1); - [[nodiscard]] Api::Result seek(std::chrono::milliseconds position); - [[nodiscard]] Api::Result setVolume(float volume); + Api::Result + initialize(std::shared_ptr networkClient, + std::shared_ptr database = nullptr); + void shutdown(); - [[nodiscard]] Api::Result queueTrack(const Api::TrackInfo& track, uint64_t clientId); - [[nodiscard]] Api::Result removeFromQueue(uint32_t position); - [[nodiscard]] Api::Result clearQueue(); - [[nodiscard]] Api::Result> getQueue() const; - [[nodiscard]] Api::Result moveInQueue(uint32_t from, uint32_t to); - [[nodiscard]] Api::Result toggleShuffle(); - [[nodiscard]] Api::Result toggleRepeat(); + [[nodiscard]] Api::Result + play(const std::string& query, uint64_t clientId); + [[nodiscard]] Api::Result pause(); + [[nodiscard]] Api::Result resume(); + [[nodiscard]] Api::Result stop(); + [[nodiscard]] Api::Result skip(uint32_t count = 1); + [[nodiscard]] Api::Result + seek(std::chrono::milliseconds position); + [[nodiscard]] Api::Result setVolume(float volume); - // Load playlist asynchronously - returns immediately, processes in background - Api::Result loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId); - [[nodiscard]] bool isPlaylistLoading() const { return playlistLoading_.load(); } - [[nodiscard]] size_t getPlaylistLoadProgress() const { return playlistLoadedCount_.load(); } - [[nodiscard]] Api::Result> - getPlaylists() const; + [[nodiscard]] Api::Result + queueTrack(const Api::TrackInfo& track, uint64_t clientId); + [[nodiscard]] Api::Result removeFromQueue(uint32_t position); + [[nodiscard]] Api::Result clearQueue(); + [[nodiscard]] Api::Result> + getQueue() const; + [[nodiscard]] Api::Result moveInQueue(uint32_t from, + uint32_t to); + [[nodiscard]] Api::Result toggleShuffle(); + [[nodiscard]] Api::Result toggleRepeat(); + [[nodiscard]] Api::Result shuffleQueue(); - [[nodiscard]] Api::Result> - getCurrentTrack() const; - [[nodiscard]] Api::Result getPlaybackState() const; - [[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const; + // Load playlist asynchronously - returns immediately, processes in + // background + Api::Result loadPlaylist(const std::string& playlistIdOrUrl, + uint64_t clientId); + [[nodiscard]] bool isPlaylistLoading() const + { + return playlistLoading_.load(); + } + [[nodiscard]] size_t getPlaylistLoadProgress() const + { + return playlistLoadedCount_.load(); + } + [[nodiscard]] Api::Result> + getPlaylists() const; - [[nodiscard]] Api::Result search(const std::string& query); - - // Search result selection (client-specific) - void storePendingSearch(uint64_t clientId, const std::vector& results); - [[nodiscard]] std::optional> getPendingSearch(uint64_t clientId); - [[nodiscard]] Api::Result selectSearchResult( - uint64_t clientId, uint32_t index, const std::string& invokerName); + [[nodiscard]] Api::Result> + getCurrentTrack() const; + [[nodiscard]] Api::Result + getPlaybackState() const; + [[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const; - // Help command - [[nodiscard]] std::string getHelpText() const; + [[nodiscard]] Api::Result + search(const std::string& query); - // Subscription management (by client ID - internally uses UID for - // persistence) - [[nodiscard]] Api::Result subscribe(uint64_t clientId); - [[nodiscard]] Api::Result unsubscribe(uint64_t clientId); - [[nodiscard]] bool isSubscribed(uint64_t clientId) const; - [[nodiscard]] std::set getSubscribedClients() - const; // Returns only ONLINE subscribers' client IDs - [[nodiscard]] bool hasSubscribers() - const; // Returns true if any subscribers exist (online or offline) - [[nodiscard]] bool hasOnlineSubscribers() - const; // Returns true only if there are online subscribers - [[nodiscard]] std::vector - getSubscribers() const; - [[nodiscard]] Api::Result - unsubscribeByUid(const std::string& uid); - [[nodiscard]] Api::Result clearAllSubscriptions(); + // Search result selection (client-specific) + void storePendingSearch(uint64_t clientId, + const std::vector& results); + [[nodiscard]] std::optional> + getPendingSearch(uint64_t clientId); + [[nodiscard]] Api::Result + selectSearchResult(uint64_t clientId, + uint32_t index, + const std::string& invokerName); - // Get UIDs of subscribers who are currently online - [[nodiscard]] std::set getOnlineSubscriberUids() const; + // Help command + [[nodiscard]] std::string getHelpText() const; - // Called when a client connects to the server - void onClientConnected(uint64_t clientId); + // Subscription management (by client ID - internally uses UID for + // persistence) + [[nodiscard]] Api::Result subscribe(uint64_t clientId); + [[nodiscard]] Api::Result + unsubscribe(uint64_t clientId); + [[nodiscard]] bool isSubscribed(uint64_t clientId) const; + [[nodiscard]] std::set getSubscribedClients() + const; // Returns only ONLINE subscribers' client IDs + [[nodiscard]] bool + hasSubscribers() const; // Returns true if any subscribers exist + // (online or offline) + [[nodiscard]] bool hasOnlineSubscribers() + const; // Returns true only if there are online subscribers + [[nodiscard]] std::vector + getSubscribers() const; + [[nodiscard]] Api::Result + unsubscribeByUid(const std::string& uid); + [[nodiscard]] Api::Result clearAllSubscriptions(); - [[nodiscard]] Api::HotReloadState getStateForHotReload() const; - [[nodiscard]] Api::Result - restoreFromHotReload(const Api::HotReloadState& state); + // Get UIDs of subscribers who are currently online + [[nodiscard]] std::set getOnlineSubscriberUids() const; - using AudioDataCallback = std::function)>; - void setAudioDataCallback(const AudioDataCallback& callback); + // Called when a client connects to the server + void onClientConnected(uint64_t clientId); - using SubscriptionChangeCallback = std::function; - void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback); + [[nodiscard]] Api::HotReloadState getStateForHotReload() const; + [[nodiscard]] Api::Result + restoreFromHotReload(const Api::HotReloadState& state); - using PlaybackStartCallback = std::function; - void setPlaybackStartCallback(const PlaybackStartCallback& callback); + using AudioDataCallback = + std::function)>; + void setAudioDataCallback(const AudioDataCallback& callback); - // Callback to resolve client info (UID and nickname) from client ID - using ClientInfoCallback = - std::function>( - uint64_t clientId)>; - void setClientInfoCallback(const ClientInfoCallback& callback); + using SubscriptionChangeCallback = std::function; + void setSubscriptionChangeCallback( + const SubscriptionChangeCallback& callback); - // Callback to resolve client ID from UID - using UidToClientIdCallback = - std::function(const std::string& uid)>; - void setUidToClientIdCallback(const UidToClientIdCallback& callback); + using PlaybackStartCallback = std::function; + void + setPlaybackStartCallback(const PlaybackStartCallback& callback); - // Callback to resolve nickname from client ID - using NicknameCallback = - std::function(uint64_t clientId)>; - void setNicknameCallback(const NicknameCallback& callback); + // Callback to resolve client info (UID and nickname) from client ID + using ClientInfoCallback = std::function>(uint64_t clientId)>; + void setClientInfoCallback(const ClientInfoCallback& callback); - // Called when a client leaves the server - void onClientDisconnected(uint64_t clientId); + // Callback to resolve client ID from UID + using UidToClientIdCallback = + std::function(const std::string& uid)>; + void + setUidToClientIdCallback(const UidToClientIdCallback& callback); -private: - void playbackThread(); - [[nodiscard]] Api::Result resolveQuery(const std::string& query); - [[nodiscard]] Api::Result getStreamUrl(const Api::TrackInfo& track); - void onTrackFinished(); - [[nodiscard]] Api::TrackInfo getNextTrack(); - void shuffleQueue(); - - // Download audio through proxy for playback - [[nodiscard]] Api::Result downloadAudioForPlayback(const std::string& url); - void cleanupTempFile(const std::string& filepath); - - // Prefetch next track for seamless transitions - void prefetchNextTrack(); - [[nodiscard]] bool shouldPrefetch() const; - static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15); // Start prefetch 15s before end - - // Temporary file tracking - std::set tempFiles_; - mutable std::mutex tempFilesMutex_; - - // Prefetch state for seamless playback - struct PrefetchState { - std::future> streamUrlFuture; - std::atomic isPrefetching{false}; - std::atomic hasPrefetched{false}; - std::optional prefetchedUrl; - } prefetchState_; - - // Async playlist loading state - std::thread playlistLoadThread_; - std::atomic playlistLoading_{false}; - std::atomic playlistLoadedCount_{0}; - std::atomic playlistTotalCount_{0}; + // Callback to resolve nickname from client ID + using NicknameCallback = + std::function(uint64_t clientId)>; + void setNicknameCallback(const NicknameCallback& callback); - std::shared_ptr networkClient_; - std::unique_ptr youTubeClient_; - std::unique_ptr audioDecoder_; - std::unique_ptr subscriptionManager_; + // Called when a client leaves the server + void onClientDisconnected(uint64_t clientId); - Api::BotConfig config_; - std::vector queue_; - std::optional currentTrack_; - bool isPlaying_ = false; - bool isPaused_ = false; - bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused - - // Accurate playback position tracking - std::chrono::milliseconds playbackPosition_{0}; // Current position - std::chrono::steady_clock::time_point playbackStartTime_; // When current segment started - std::chrono::milliseconds playbackBasePosition_{0}; // Position at start of current segment - float volume_ = 0.5f; - bool shuffle_ = false; - bool repeat_ = false; - uint64_t nextQueueId_ = 1; + private: - std::jthread playbackThread_; - mutable std::mutex mutex_; - std::condition_variable cv_; - std::atomic playbackThreadRunning_{false}; // True while thread is actively running - - // Pending search results per client (for select command) - std::unordered_map> pendingSearches_; - mutable std::mutex pendingSearchMutex_; + void playbackThread(); + [[nodiscard]] Api::Result + resolveQuery(const std::string& query); + [[nodiscard]] Api::Result + getStreamUrl(const Api::TrackInfo& track); + void onTrackFinished(); + [[nodiscard]] Api::TrackInfo getNextTrack(); - AudioDataCallback audioCallback_; - SubscriptionChangeCallback subscriptionChangeCallback_; - PlaybackStartCallback playbackStartCallback_; - ClientInfoCallback clientInfoCallback_; - UidToClientIdCallback uidToClientIdCallback_; - NicknameCallback nicknameCallback_; - std::mt19937 rng_{std::random_device{}()}; + // Generate silence/sine wave to keep audio stream alive during + // transitions + void generateTransitionAudio(std::chrono::milliseconds duration); + void sendSilenceChunk(); + static constexpr auto TRANSITION_SILENCE_DURATION = + std::chrono::milliseconds(100); + static constexpr auto TRANSITION_FADE_DURATION = + std::chrono::milliseconds(50); - static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = - 192000; // Match TeamSpeak CODEC_OPUS_MUSIC - static constexpr uint32_t TEAMSPEAK_CHANNELS = 2; - static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo - static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4; -}; + // Download audio through proxy for playback + [[nodiscard]] Api::Result + downloadAudioForPlayback(const std::string& url); + void cleanupTempFile(const std::string& filepath); + + // Prefetch next track for seamless transitions + void prefetchNextTrack(); + [[nodiscard]] bool shouldPrefetch() const; + static constexpr auto PREFETCH_THRESHOLD = + std::chrono::seconds(15); // Start prefetch 15s before end + + // Temporary file tracking + std::set tempFiles_; + mutable std::shared_mutex tempFilesMutex_; + + // Prefetch state for seamless playback + struct PrefetchState { + std::future> streamUrlFuture; + std::atomic isPrefetching{false}; + std::atomic hasPrefetched{false}; + std::optional prefetchedUrl; + } prefetchState_; + + // Async playlist loading state + std::thread playlistLoadThread_; + std::atomic playlistLoading_{false}; + std::atomic playlistLoadedCount_{0}; + std::atomic playlistTotalCount_{0}; + + // Auto-start thread for playlist (must be joined, not detached) + std::thread playlistAutoStartThread_; + + std::shared_ptr networkClient_; + std::unique_ptr youTubeClient_; + std::unique_ptr audioDecoder_; + std::unique_ptr subscriptionManager_; + + Api::BotConfig config_; + std::vector queue_; + std::optional currentTrack_; + std::atomic isPlaying_{false}; + std::atomic isPaused_{false}; + std::atomic wasPausedForNoSubscribers_{ + false}; // Track if we auto-paused + + // Accurate playback position tracking + std::chrono::milliseconds playbackPosition_{0}; // Current position + std::chrono::steady_clock::time_point + playbackStartTime_; // When current segment started + std::chrono::milliseconds playbackBasePosition_{ + 0}; // Position at start of current segment + std::atomic volume_{0.5f}; + std::atomic shuffle_{false}; + std::atomic repeat_{false}; + uint64_t nextQueueId_ = 1; + + // Shuffle state - maintains shuffled order of queue indices + std::vector shuffledIndices_; + size_t shuffleIndex_ = 0; + void rebuildShuffledIndices(); + void reshuffleRemaining(); + + std::jthread playbackThread_; + mutable std::shared_mutex mutex_; + std::condition_variable_any cv_; + std::atomic playbackThreadRunning_{ + false}; // True while thread is actively running + + // Pending search results per client (for select command) + std::unordered_map> + pendingSearches_; + mutable std::mutex pendingSearchMutex_; + + AudioDataCallback audioCallback_; + SubscriptionChangeCallback subscriptionChangeCallback_; + PlaybackStartCallback playbackStartCallback_; + ClientInfoCallback clientInfoCallback_; + UidToClientIdCallback uidToClientIdCallback_; + NicknameCallback nicknameCallback_; + std::mt19937 rng_{std::random_device{}()}; + + // Position tracking for periodic event updates + std::chrono::steady_clock::time_point lastPositionUpdate_{}; + static constexpr auto POSITION_UPDATE_INTERVAL = + std::chrono::seconds(1); + + static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = + 192000; // Match TeamSpeak CODEC_OPUS_MUSIC + static constexpr uint32_t TEAMSPEAK_CHANNELS = 2; + static constexpr size_t AUDIO_BUFFER_SIZE = + 7680; // 20ms @ 192kHz stereo + static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4; + }; } // namespace Echoion::Core diff --git a/include/echoion/core/NetworkClient.hpp b/include/echoion/core/NetworkClient.hpp index 5a2bcb8..a3f7817 100644 --- a/include/echoion/core/NetworkClient.hpp +++ b/include/echoion/core/NetworkClient.hpp @@ -1,202 +1,238 @@ #pragma once #include "boost/asio/ssl/context.hpp" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include +#include +#include +#include +#include // Boost.Beast includes needed for template function #include #include +namespace Echoion::Core +{ + // Forward declaration for URL parsing + struct UrlComponents; + class NetworkClient : public Api::INetworkClient + { + public: + NetworkClient(); + ~NetworkClient() override; -namespace Echoion::Core { + // Initialize with optional proxy + Api::Result initialize( + const std::optional& proxy = std::nullopt); + void shutdown(); -// Forward declaration for URL parsing -struct UrlComponents; + // Synchronous requests + [[nodiscard]] Api::Result + get(std::string_view url, + const std::vector& headers = {}); + [[nodiscard]] Api::Result + post(std::string_view url, std::string_view body, + const std::vector& headers = {}); + [[nodiscard]] Api::Result + request(const Api::HttpRequest& req); -class NetworkClient : public Api::INetworkClient { -public: - NetworkClient(); - ~NetworkClient() override; + // Asynchronous requests + [[nodiscard]] std::future> + getAsync(std::string_view url, + const std::vector& headers = {}); + [[nodiscard]] std::future> + postAsync(std::string_view url, std::string_view body, + const std::vector& headers = {}); + [[nodiscard]] std::future> + requestAsync(const Api::HttpRequest& req); - // Initialize with optional proxy - Api::Result initialize(const std::optional& proxy = std::nullopt); - void shutdown(); + // Concurrent batch requests + [[nodiscard]] std::vector> + requestBatch(const std::vector& requests); - // Synchronous requests - [[nodiscard]] Api::Result get(std::string_view url, - const std::vector& headers = {}); - [[nodiscard]] Api::Result post(std::string_view url, - std::string_view body, const std::vector& headers = {}); - [[nodiscard]] Api::Result request(const Api::HttpRequest& req); + // JSON helpers using Void::Json reflection + template + [[nodiscard]] Api::Result + getJson(std::string_view url, + const std::vector& headers = {}) + { + auto response = get(url, headers); + if (!response) { + return std::unexpected(response.error()); + } + return parseJson(response->bodyAsString()); + } - // Asynchronous requests - [[nodiscard]] std::future> getAsync(std::string_view url, - const std::vector& headers = {}); - [[nodiscard]] std::future> postAsync(std::string_view url, - std::string_view body, const std::vector& headers = {}); - [[nodiscard]] std::future> requestAsync(const Api::HttpRequest& req); + template + [[nodiscard]] Api::Result + postJson(std::string_view url, const Body& body, + const std::vector& headers = {}) + { + std::string jsonBody = + Void::Json::serialize(Void::Json::to_json(body)); + auto response = post(url, jsonBody, headers); + if (!response) { + return std::unexpected(response.error()); + } + return parseJson(response->bodyAsString()); + } - // Concurrent batch requests - [[nodiscard]] std::vector> requestBatch( - const std::vector& requests); + private: - // JSON helpers using glaze - template - [[nodiscard]] Api::Result getJson(std::string_view url, - const std::vector& headers = {}) { - auto response = get(url, headers); - if (!response) { - return std::unexpected(response.error()); - } - - T result; - auto ec = glz::read_json(result, response->bodyAsString()); - if (ec) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString())))); - } - return result; - } + // Parse a response body into a reflectable type T via Void::Json. + template + [[nodiscard]] static Api::Result + parseJson(const std::string& body) + { + auto parsed = Void::Json::parse(body); + if (!parsed) { + return std::unexpected(Api::Error( + Api::ErrorCode::ParseError, + std::format("JSON parse error ({}:{}): {}", + parsed.error().line, parsed.error().col, + parsed.error().message))); + } + auto value = Void::Json::from_json(*parsed); + if (!value) { + return std::unexpected(Api::Error( + Api::ErrorCode::ParseError, + std::format("JSON decode error: field '{}': {}", + value.error().field, value.error().message))); + } + return std::move(*value); + } - template - [[nodiscard]] Api::Result postJson(std::string_view url, const Body& body, - const std::vector& headers = {}) { - std::string jsonBody = glz::write_json(body); - auto response = post(url, jsonBody, headers); - if (!response) { - return std::unexpected(response.error()); - } - - T result; - auto ec = glz::read_json(result, response->bodyAsString()); - if (ec) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString())))); - } - return result; - } + public: - // Proxy configuration - void setProxy(const std::optional& proxy); - [[nodiscard]] std::optional getProxy() const; - void clearProxy(); + // Proxy configuration + void setProxy(const std::optional& proxy); + [[nodiscard]] std::optional getProxy() const; + void clearProxy(); - // Retry configuration - void setRetryConfig(const Api::RetryConfig& config); - [[nodiscard]] Api::RetryConfig getRetryConfig() const; + // Retry configuration + void setRetryConfig(const Api::RetryConfig& config); + [[nodiscard]] Api::RetryConfig getRetryConfig() const; -private: - // Request execution - [[nodiscard]] Api::Result executeWithRetry(const Api::HttpRequest& req); - [[nodiscard]] Api::Result executeRequest(const Api::HttpRequest& req); - - // Proxy and direct execution methods - [[nodiscard]] Api::HttpResponse executeWithProxy( - boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout); - - [[nodiscard]] Api::HttpResponse executeWithHttpProxy( - boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout); - - [[nodiscard]] Api::HttpResponse executeWithSocks5Proxy( - boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy, - std::chrono::seconds timeout); - - [[nodiscard]] Api::HttpResponse executeDirect( - boost::asio::io_context& ioc, - boost::asio::ssl::context& ctx, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - std::chrono::seconds timeout); - - // HTTP request methods - // Note: sendHttpsRequest is a template, implemented in header below - template - [[nodiscard]] Api::HttpResponse sendHttpsRequest( - Stream& stream, - const UrlComponents& urlComp, - const Api::HttpRequest& req); - - [[nodiscard]] Api::HttpResponse sendHttpRequest( - boost::asio::ip::tcp::socket& socket, - const UrlComponents& urlComp, - const Api::HttpRequest& req); - - [[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy( - boost::asio::ip::tcp::socket& socket, - const UrlComponents& urlComp, - const Api::HttpRequest& req, - const Api::ProxyConfig& proxy); - - // Request/Response building - [[nodiscard]] boost::beast::http::request buildBeastRequest( - const UrlComponents& urlComp, - const Api::HttpRequest& req); - - [[nodiscard]] Api::HttpResponse convertBeastResponse( - const boost::beast::http::response& beastResponse); - - [[nodiscard]] std::vector addDefaultHeaders(const std::vector& headers); + private: - std::optional proxy_; - Api::RetryConfig retryConfig_; - mutable std::mutex mutex_; - std::atomic initialized_{false}; - std::atomic requestId_{0}; - - // Thread pool for async operations - std::vector threadPool_; - std::queue()>> taskQueue_; - std::mutex taskMutex_; - std::condition_variable taskCv_; - std::atomic stopThreads_{false}; - static constexpr size_t THREAD_POOL_SIZE = 4; -}; + // Request execution + [[nodiscard]] Api::Result + executeWithRetry(const Api::HttpRequest& req); + [[nodiscard]] Api::Result + executeRequest(const Api::HttpRequest& req); -// Template implementation for sendHttpsRequest -template -Api::HttpResponse NetworkClient::sendHttpsRequest( - Stream& stream, - const UrlComponents& urlComp, - const Api::HttpRequest& req) { - namespace http = boost::beast::http; - - // Build request - http::request request = buildBeastRequest(urlComp, req); - - // Send - http::write(stream, request); - - // Read response - boost::beast::flat_buffer buffer; - http::response response; - http::read(stream, buffer, response); - - // Convert to Api::HttpResponse - return convertBeastResponse(response); -} + // Proxy and direct execution methods + [[nodiscard]] Api::HttpResponse + executeWithProxy(boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy, + std::chrono::seconds timeout); + + [[nodiscard]] Api::HttpResponse + executeWithHttpProxy(boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy, + std::chrono::seconds timeout); + + [[nodiscard]] Api::HttpResponse + executeWithSocks5Proxy(boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy, + std::chrono::seconds timeout); + + [[nodiscard]] Api::HttpResponse + executeDirect(boost::asio::io_context& ioc, + boost::asio::ssl::context& ctx, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + std::chrono::seconds timeout); + + // HTTP request methods + // Note: sendHttpsRequest is a template, implemented in header below + template + [[nodiscard]] Api::HttpResponse + sendHttpsRequest(Stream& stream, + const UrlComponents& urlComp, + const Api::HttpRequest& req); + + [[nodiscard]] Api::HttpResponse + sendHttpRequest(boost::asio::ip::tcp::socket& socket, + const UrlComponents& urlComp, + const Api::HttpRequest& req); + + [[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy( + boost::asio::ip::tcp::socket& socket, + const UrlComponents& urlComp, + const Api::HttpRequest& req, + const Api::ProxyConfig& proxy); + + // Request/Response building + [[nodiscard]] boost::beast::http::request< + boost::beast::http::string_body> + buildBeastRequest(const UrlComponents& urlComp, + const Api::HttpRequest& req); + + [[nodiscard]] Api::HttpResponse convertBeastResponse( + const boost::beast::http::response< + boost::beast::http::dynamic_body>& beastResponse); + + [[nodiscard]] std::vector + addDefaultHeaders(const std::vector& headers); + + std::optional proxy_; + Api::RetryConfig retryConfig_; + mutable std::mutex mutex_; + std::atomic initialized_{false}; + std::atomic requestId_{0}; + + // Thread pool for async operations + std::vector threadPool_; + std::queue()>> + taskQueue_; + std::mutex taskMutex_; + std::condition_variable taskCv_; + std::atomic stopThreads_{false}; + static constexpr size_t THREAD_POOL_SIZE = 4; + }; + + // Template implementation for sendHttpsRequest + template + Api::HttpResponse + NetworkClient::sendHttpsRequest(Stream& stream, + const UrlComponents& urlComp, + const Api::HttpRequest& req) + { + namespace http = boost::beast::http; + + // Build request + http::request request = + buildBeastRequest(urlComp, req); + + // Send + http::write(stream, request); + + // Read response + boost::beast::flat_buffer buffer; + http::response response; + http::read(stream, buffer, response); + + // Convert to Api::HttpResponse + return convertBeastResponse(response); + } } // namespace Echoion::Core diff --git a/include/echoion/core/RpcServer.hpp b/include/echoion/core/RpcServer.hpp index b4d1523..64bd5ec 100644 --- a/include/echoion/core/RpcServer.hpp +++ b/include/echoion/core/RpcServer.hpp @@ -1,81 +1,98 @@ #pragma once -#include +#include +#include +#include +#include #include #include #include -#include +#include #include #include -#include +#include #include -namespace Echoion::Core { +namespace Echoion::Core +{ -namespace asio = boost::asio; -namespace beast = boost::beast; -namespace websocket = beast::websocket; + namespace asio = boost::asio; + namespace beast = boost::beast; + namespace websocket = beast::websocket; -class RpcServer : public std::enable_shared_from_this { -public: - using CommandHandler = std::function(const std::string& params, uint64_t clientId)>; + class RpcServer : public std::enable_shared_from_this + { + public: - RpcServer(); - ~RpcServer(); + using CommandHandler = std::function( + const std::string& params, uint64_t clientId)>; - // Initialize and start the server - Api::Result start(uint16_t port = 8765); - void stop(); - [[nodiscard]] bool isRunning() const { return running_; } - [[nodiscard]] uint16_t getPort() const { return port_; } + RpcServer(); + ~RpcServer(); - // Register command handlers - void registerHandler(const std::string& method, CommandHandler handler); - void unregisterHandler(const std::string& method); + // Initialize and start the server + Api::Result start(uint16_t port = 8765); + void stop(); + [[nodiscard]] bool isRunning() const { return running_; } + [[nodiscard]] uint16_t getPort() const { return port_; } - // Authentication - void setAuthToken(const std::string& token); - [[nodiscard]] bool authenticate(const std::string& token); - void addAuthenticatedClient(uint64_t clientId); - void removeAuthenticatedClient(uint64_t clientId); - [[nodiscard]] bool isClientAuthenticated(uint64_t clientId); + // Register command handlers + void registerHandler(const std::string& method, + CommandHandler handler); + void unregisterHandler(const std::string& method); - // Broadcast events to all connected clients - void broadcastEvent(const std::string& event, const std::string& data); + // Authentication + void setAuthToken(const std::string& token); + [[nodiscard]] bool authenticate(const std::string& token); + void addAuthenticatedClient(uint64_t clientId); + void removeAuthenticatedClient(uint64_t clientId); + [[nodiscard]] bool isClientAuthenticated(uint64_t clientId); - // Send event to specific client - void sendEvent(uint64_t clientId, const std::string& event, const std::string& data); + // Broadcast events to all connected clients + void broadcastEvent(const std::string& event, + const std::string& data); -private: - void acceptLoop(); - void handleClient(std::shared_ptr> ws); - void processMessage(uint64_t clientId, const std::string& message); - void sendResponse(uint64_t clientId, const Api::RpcResponse& response); - void sendNotification(uint64_t clientId, const Api::RpcNotification& notification); + // Send event to specific client + void sendEvent(uint64_t clientId, const std::string& event, + const std::string& data); - asio::io_context ioContext_; - std::optional acceptor_; - std::thread serverThread_; - std::atomic running_{false}; - uint16_t port_ = 8765; + private: - // Connected clients - std::unordered_map>> clients_; - std::mutex clientsMutex_; - std::atomic nextClientId_{1}; - - // Client threads (for proper cleanup) - std::vector clientThreads_; - std::mutex clientThreadsMutex_; + void acceptLoop(); + void handleClient( + std::shared_ptr> ws); + void processMessage(uint64_t clientId, const std::string& message); + void sendResponse(uint64_t clientId, + const Api::RpcResponse& response); + void sendNotification(uint64_t clientId, + const Api::RpcNotification& notification); - // Authenticated clients - std::set authenticatedClients_; - std::mutex authMutex_; - std::string authToken_; + asio::io_context ioContext_; + std::optional acceptor_; + std::thread serverThread_; + std::atomic running_{false}; + uint16_t port_ = 8765; - // Command handlers - std::unordered_map handlers_; - std::mutex handlersMutex_; -}; + // Connected clients + std::unordered_map< + uint64_t, + std::shared_ptr>> + clients_; + std::mutex clientsMutex_; + std::atomic nextClientId_{1}; + + // Client threads (for proper cleanup) + std::vector clientThreads_; + std::mutex clientThreadsMutex_; + + // Authenticated clients + std::set authenticatedClients_; + std::mutex authMutex_; + std::string authToken_; + + // Command handlers + std::unordered_map handlers_; + std::mutex handlersMutex_; + }; } // namespace Echoion::Core diff --git a/include/echoion/core/SessionManager.hpp b/include/echoion/core/SessionManager.hpp new file mode 100644 index 0000000..7c5178d --- /dev/null +++ b/include/echoion/core/SessionManager.hpp @@ -0,0 +1,87 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + + // Session management for RPC clients + // Supports 100+ concurrent authenticated sessions + class SessionManager + { + public: + + struct Session { + uint64_t clientId; + std::string authToken; + std::chrono::steady_clock::time_point lastActivity; + std::chrono::steady_clock::time_point createdAt; + bool isAuthenticated; + + // Optional: store client-specific state + struct ClientState { + std::optional currentPlaylist; + float preferredVolume = -1.0f; // -1 = use default + // Add more client preferences here + }; + std::optional clientState; + }; + + struct Config { + size_t maxSessions = 150; // 100 users + buffer + std::chrono::seconds sessionTimeout{3600}; // 1 hour timeout + std::chrono::seconds cleanupInterval{ + 300}; // Cleanup every 5 min + }; + + SessionManager(); + explicit SessionManager(const Config& config); + + // Initialize session manager + bool initialize(); + void shutdown(); + + // Create new session + std::string createSession(uint64_t clientId); + + // Authenticate session + bool authenticateSession(const std::string& token); + + // Validate and update session + bool validateSession(const std::string& token); + void updateActivity(const std::string& token); + + // Get session info + std::optional getSession(const std::string& token) const; + + // End session + void endSession(const std::string& token); + void endSessionByClientId(uint64_t clientId); + + // Get all active sessions + std::vector getAllSessions() const; + + // Get session count + size_t getSessionCount() const; + + // Cleanup expired sessions (call periodically) + size_t cleanupExpiredSessions(); + + // Check if at capacity + bool isAtCapacity() const; + + private: + + std::string generateToken(); + + Config config_; + std::unordered_map sessions_; + mutable std::mutex mutex_; + std::atomic running_{false}; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/SignatureCipher.hpp b/include/echoion/core/SignatureCipher.hpp index 6284d9c..360fcff 100644 --- a/include/echoion/core/SignatureCipher.hpp +++ b/include/echoion/core/SignatureCipher.hpp @@ -1,129 +1,138 @@ #pragma once +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include #include -namespace Echoion::Core { +namespace Echoion::Core +{ -/** - * Signature cipher for YouTube stream URLs - * Uses QuickJS (when available) to execute the JavaScript decipher functions from player JS - * - * Based on yt-dlp's signature extraction logic - */ -class SignatureCipher { -public: - SignatureCipher(); - ~SignatureCipher(); + /** + * Signature cipher for YouTube stream URLs + * Uses QuickJS (when available) to execute the JavaScript decipher + * functions from player JS + * + * Based on yt-dlp's signature extraction logic + */ + class SignatureCipher + { + public: - // Disable copy, enable move - SignatureCipher(const SignatureCipher&) = delete; - SignatureCipher& operator=(const SignatureCipher&) = delete; - SignatureCipher(SignatureCipher&&) noexcept; - SignatureCipher& operator=(SignatureCipher&&) noexcept; + SignatureCipher(); + ~SignatureCipher(); - /** - * Initialize the QuickJS solver with core libraries - * Must be called before using the cipher - */ - void initialize(); + // Disable copy, enable move + SignatureCipher(const SignatureCipher&) = delete; + SignatureCipher& operator=(const SignatureCipher&) = delete; + SignatureCipher(SignatureCipher&&) noexcept; + SignatureCipher& operator=(SignatureCipher&&) noexcept; - /** - * Set the player JS code and extract decipher functions - * @param playerJsCode The raw player JavaScript code from YouTube - * @return true if extraction succeeded - */ - bool setPlayerJs(std::string_view playerJsCode); + /** + * Initialize the QuickJS solver with core libraries + * Must be called before using the cipher + */ + void initialize(); - /** - * Check if the cipher is ready (has valid decipher function) - */ - [[nodiscard]] bool isReady() const; + /** + * Set the player JS code and extract decipher functions + * @param playerJsCode The raw player JavaScript code from YouTube + * @return true if extraction succeeded + */ + bool setPlayerJs(std::string_view playerJsCode); - /** - * Decipher a signature cipher string - * Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL - * @param signatureCipher The signature cipher string - * @return The full deciphered URL or empty string on failure - */ - [[nodiscard]] std::string decipher(std::string_view signatureCipher); + /** + * Check if the cipher is ready (has valid decipher function) + */ + [[nodiscard]] bool isReady() const; - /** - * Solve a challenge (signature or n-param) using the preprocessed player - * @param challenge The challenge string to solve - * @param type "sig" for signature, "n" for n-parameter - * @return The solved challenge or empty string on failure - */ - [[nodiscard]] std::string solveChallenge(const std::string& challenge, const std::string& type); + /** + * Decipher a signature cipher string + * Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL + * @param signatureCipher The signature cipher string + * @return The full deciphered URL or empty string on failure + */ + [[nodiscard]] std::string + decipher(std::string_view signatureCipher); - /** - * Decipher the n-parameter for throttling - * @param nParam The encoded n parameter - * @return The deciphered n parameter - */ - [[nodiscard]] std::string decipherNParam(std::string_view nParam); + /** + * Solve a challenge (signature or n-param) using the preprocessed + * player + * @param challenge The challenge string to solve + * @param type "sig" for signature, "n" for n-parameter + * @return The solved challenge or empty string on failure + */ + [[nodiscard]] std::string + solveChallenge(const std::string& challenge, + const std::string& type); - /** - * Clear the cipher state - */ - void clear(); + /** + * Decipher the n-parameter for throttling + * @param nParam The encoded n parameter + * @return The deciphered n parameter + */ + [[nodiscard]] std::string decipherNParam(std::string_view nParam); - /** - * Check if cipher has been initialized - */ - [[nodiscard]] bool isInitialized() const; + /** + * Clear the cipher state + */ + void clear(); -private: - /** - * Initialize QuickJS runtime and context with solver libraries - */ - void initSolver(); + /** + * Check if cipher has been initialized + */ + [[nodiscard]] bool isInitialized() const; - /** - * Download solver libraries from remote URL - * @param url The URL to download from - * @return The downloaded JS code or empty string on failure - */ - [[nodiscard]] std::optional downloadSolverLibrary( - std::string_view url); + private: - /** - * Get cache directory for storing solver libraries - */ - [[nodiscard]] std::filesystem::path getCacheDir(); + /** + * Initialize QuickJS runtime and context with solver libraries + */ + void initSolver(); - /** - * Execute JavaScript code in QuickJS and return result - */ - [[nodiscard]] std::optional executeJS( - std::string_view code, - std::string_view filename = "