diff --git a/CMakeLists.txt b/CMakeLists.txt index 115de41..bc2152e 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(EchoionApi VERSION 1.0.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 26) @@ -6,38 +6,287 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) -# Create header-only interface library for API -add_library(EchoionApi INTERFACE) +find_package(Threads REQUIRED) -add_library(Echoion::Api ALIAS EchoionApi) +# ===== Granular API Libraries ===== +# Directory structure: +# include/echoion/api/ +# base/ - Types.hpp (Error, Result, LogLevel, LogEntry) +# audio/ - AudioTypes.hpp (AudioQuality, AudioFormat, AudioBuffer) +# track/ - TrackTypes.hpp (TrackInfo, QueueEntry, PlaybackState, etc.) +# network/ - NetworkTypes.hpp (HttpRequest, HttpResponse, ProxyConfig) +# plugin/ - PluginTypes.hpp (PluginEvent, ClientInfo, ChannelInfo, etc.) +# config/ - ConfigTypes.hpp (BotConfig, ServerConfig, AppConfig) +# rpc/ - RpcTypes.hpp (RpcMethod, RpcRequest, RpcResponse, HotReloadState) +# youtube/ - YouTubeTypes.hpp (YouTube types) +# logger/ - LoggerInterface.hpp (ILogger, LoggerRegistry) +# eventbus/ - EventBus.hpp (EventBus, all event types) +# database/ - Database.hpp (Database interface) +# interfaces/- CoreInterface.hpp, PluginInterface +# utils/ - Cache.hpp, MemoryPool.hpp -target_include_directories(EchoionApi INTERFACE - $ - $ +# 1. Base Types +add_library(EchoionApiBase INTERFACE) +add_library(Echoion::ApiBase ALIAS EchoionApiBase) +target_include_directories(EchoionApiBase INTERFACE + $ + $ +) +target_link_libraries(EchoionApiBase INTERFACE Void::Functional) + +# 2. Audio Types +add_library(EchoionApiAudio INTERFACE) +add_library(Echoion::ApiAudio ALIAS EchoionApiAudio) +target_include_directories(EchoionApiAudio INTERFACE + $ + $ +) +target_link_libraries(EchoionApiAudio INTERFACE Echoion::ApiBase Echoion::ApiUtils) + +# 3. Track Types (depends on Audio) +add_library(EchoionApiTrack INTERFACE) +add_library(Echoion::ApiTrack ALIAS EchoionApiTrack) +target_include_directories(EchoionApiTrack INTERFACE + $ + $ +) +target_link_libraries(EchoionApiTrack INTERFACE + Echoion::ApiBase + Echoion::ApiAudio + Void::Data ) -# Require glaze for JSON serialization (header-only) -find_package(glaze CONFIG REQUIRED) -target_link_libraries(EchoionApi INTERFACE glaze::glaze) +# 4. Network Types +add_library(EchoionApiNetwork INTERFACE) +add_library(Echoion::ApiNetwork ALIAS EchoionApiNetwork) +target_include_directories(EchoionApiNetwork INTERFACE + $ + $ +) +target_link_libraries(EchoionApiNetwork INTERFACE Echoion::ApiBase) -find_package(Threads REQUIRED) -target_link_libraries(EchoionApi INTERFACE Threads::Threads) +# 5. Plugin Types +add_library(EchoionApiPlugin INTERFACE) +add_library(Echoion::ApiPlugin ALIAS EchoionApiPlugin) +target_include_directories(EchoionApiPlugin INTERFACE + $ + $ +) +target_link_libraries(EchoionApiPlugin INTERFACE Echoion::ApiBase) -# Compiler-specific options (interface library, so use INTERFACE) +# 6. Config Types (depends on Network, Audio) +add_library(EchoionApiConfig INTERFACE) +add_library(Echoion::ApiConfig ALIAS EchoionApiConfig) +target_include_directories(EchoionApiConfig INTERFACE + $ + $ +) +target_link_libraries(EchoionApiConfig INTERFACE + Echoion::ApiBase + Echoion::ApiNetwork + Echoion::ApiAudio +) + +# 7. RPC Types (depends on Track) +add_library(EchoionApiRpc INTERFACE) +add_library(Echoion::ApiRpc ALIAS EchoionApiRpc) +target_include_directories(EchoionApiRpc INTERFACE + $ + $ +) +target_link_libraries(EchoionApiRpc INTERFACE + Echoion::ApiBase + Echoion::ApiTrack + Echoion::ApiConfig +) + +# 8. YouTube Types (depends on Track) +add_library(EchoionApiYouTube INTERFACE) +add_library(Echoion::ApiYouTube ALIAS EchoionApiYouTube) +target_include_directories(EchoionApiYouTube INTERFACE + $ + $ +) +target_link_libraries(EchoionApiYouTube INTERFACE + Echoion::ApiBase + Echoion::ApiTrack +) + +# 9. Logger (self-contained) +add_library(EchoionApiLogger INTERFACE) +add_library(Echoion::ApiLogger ALIAS EchoionApiLogger) +target_include_directories(EchoionApiLogger INTERFACE + $ + $ +) +target_link_libraries(EchoionApiLogger INTERFACE + Echoion::ApiBase + Threads::Threads +) + +# 10. EventBus (depends on Track, Config, Plugin) +add_library(EchoionApiEventBus INTERFACE) +add_library(Echoion::ApiEventBus ALIAS EchoionApiEventBus) +target_include_directories(EchoionApiEventBus INTERFACE + $ + $ +) +target_link_libraries(EchoionApiEventBus INTERFACE + Echoion::ApiBase + Echoion::ApiTrack + Echoion::ApiConfig + Echoion::ApiPlugin + Threads::Threads + Void::Async +) + +# 11. Database (depends on Track, Config) +add_library(EchoionApiDatabase INTERFACE) +add_library(Echoion::ApiDatabase ALIAS EchoionApiDatabase) +target_include_directories(EchoionApiDatabase INTERFACE + $ + $ +) +target_link_libraries(EchoionApiDatabase INTERFACE + Echoion::ApiBase + Echoion::ApiTrack + Echoion::ApiConfig + Echoion::ApiEventBus +) + +# 11b. OpaqueHandle (for breaking dependencies) +add_library(EchoionApiOpaque INTERFACE) +add_library(Echoion::ApiOpaque ALIAS EchoionApiOpaque) +target_include_directories(EchoionApiOpaque INTERFACE + $ + $ +) +target_link_libraries(EchoionApiOpaque INTERFACE Echoion::ApiBase) + +# 12a. PluginInterface only (minimal - for Plugin to implement) +add_library(EchoionApiPluginInterface INTERFACE) +add_library(Echoion::ApiPluginInterface ALIAS EchoionApiPluginInterface) +target_include_directories(EchoionApiPluginInterface INTERFACE + $ + $ + $ + $ + $ + $ +) +target_link_libraries(EchoionApiPluginInterface INTERFACE + Echoion::ApiBase + Echoion::ApiPlugin + Echoion::ApiOpaque +) + +# 12b. CoreInterface (decoupled - for Plugin to call Core) +add_library(EchoionApiCoreInterface INTERFACE) +add_library(Echoion::ApiCoreInterface ALIAS EchoionApiCoreInterface) +target_include_directories(EchoionApiCoreInterface INTERFACE + $ + $ +) +target_link_libraries(EchoionApiCoreInterface INTERFACE + Echoion::ApiBase + Echoion::ApiPlugin + Echoion::ApiPluginInterface + Echoion::ApiOpaque +) + +# 12c. Legacy Interfaces (both) +add_library(EchoionApiInterfaces INTERFACE) +add_library(Echoion::ApiInterfaces ALIAS EchoionApiInterfaces) +target_link_libraries(EchoionApiInterfaces INTERFACE + Echoion::ApiPluginInterface + Echoion::ApiCoreInterface + Echoion::ApiConfig +) + +# 13. Utilities (Cache, MemoryPool) +add_library(EchoionApiUtils INTERFACE) +add_library(Echoion::ApiUtils ALIAS EchoionApiUtils) +target_include_directories(EchoionApiUtils INTERFACE + $ + $ +) +target_link_libraries(EchoionApiUtils INTERFACE Echoion::ApiBase Void::Containers) + +# 14. Full API (backward compatibility) +add_library(EchoionApi INTERFACE) +add_library(Echoion::Api ALIAS EchoionApi) +target_include_directories(EchoionApi INTERFACE + $ + $ +) +target_link_libraries(EchoionApi INTERFACE + 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 +) + +# Compiler options if(MSVC) - target_compile_options(EchoionApi INTERFACE /W4 /WX-) + target_compile_options(EchoionApiBase INTERFACE /W4 /WX-) else() - target_compile_options(EchoionApi INTERFACE -Wall -Wextra -Wpedantic) + target_compile_options(EchoionApiBase INTERFACE -Wall -Wextra -Wpedantic) endif() -# PackageProject.cmake configuration -packageProject( - NAME EchoionApi +# Install and export all modules +install(TARGETS + EchoionApiBase + EchoionApiAudio + EchoionApiTrack + EchoionApiNetwork + EchoionApiPlugin + EchoionApiConfig + EchoionApiRpc + EchoionApiYouTube + EchoionApiLogger + EchoionApiEventBus + EchoionApiDatabase + EchoionApiOpaque + EchoionApiPluginInterface + EchoionApiCoreInterface + EchoionApiInterfaces + EchoionApiUtils + EchoionApi + EXPORT EchoionApiTargets + INCLUDES DESTINATION include +) + +install(EXPORT EchoionApiTargets + FILE EchoionApiTargets.cmake + NAMESPACE Echoion:: + DESTINATION lib/cmake/EchoionApi +) + +# Create package config files +include(CMakePackageConfigHelpers) +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.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}/EchoionApiConfig.cmake" +"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionApiTargets.cmake\") +") + +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/EchoionApiConfigVersion.cmake" + DESTINATION lib/cmake/EchoionApi ) diff --git a/REORGANIZE.md b/REORGANIZE.md new file mode 100644 index 0000000..090b384 --- /dev/null +++ b/REORGANIZE.md @@ -0,0 +1,165 @@ +# API Reorganization Guide + +## Directory Structure to Create + +``` +EchoionApi/include/echoion/api/ +├── base/ +│ └── Types.hpp # Error, Result, LogLevel, LogEntry, version constants +├── audio/ +│ └── AudioTypes.hpp # AudioQuality, AudioFormat, AudioBuffer +├── track/ +│ └── TrackTypes.hpp # TrackInfo, QueueEntry, PlaybackState, SearchResult +├── network/ +│ └── NetworkTypes.hpp # HttpHeader, HttpRequest, HttpResponse, ProxyConfig +├── plugin/ +│ └── PluginTypes.hpp # PluginEventType, PluginEvent, ClientInfo, ChannelInfo +├── config/ +│ └── ConfigTypes.hpp # BotConfig, ServerConfig, SecurityConfig, AppConfig +├── rpc/ +│ └── RpcTypes.hpp # RpcMethod, RpcRequest, RpcResponse, HotReloadState +├── youtube/ +│ └── YouTubeTypes.hpp # YouTubeVideoInfo, YouTubePlaylistInfo, etc. +├── logger/ +│ └── LoggerInterface.hpp # ILogger, LoggerRegistry, macros +├── eventbus/ +│ └── EventBus.hpp # EventBus, all event types +├── database/ +│ └── Database.hpp # Database interface +├── interfaces/ +│ ├── CoreInterface.hpp # ICoreInterface, INetworkClient +│ └── PluginInterface.hpp # IPluginInterface +└── utils/ + ├── Cache.hpp # Cache interface + └── MemoryPool.hpp # MemoryPool interface +``` + +## Files to Move + +### From root `include/echoion/api/` to subfolders: + +| Current Location | New Location | +|-----------------|--------------| +| `Types.hpp` | `base/Types.hpp` | +| `AudioTypes.hpp` | `audio/AudioTypes.hpp` | +| `TrackTypes.hpp` | `track/TrackTypes.hpp` | +| `NetworkTypes.hpp` | `network/NetworkTypes.hpp` | +| `PluginTypes.hpp` | `plugin/PluginTypes.hpp` | +| `ConfigTypes.hpp` | `config/ConfigTypes.hpp` | +| `RpcTypes.hpp` | `rpc/RpcTypes.hpp` | +| `YouTubeTypes.hpp` | `youtube/YouTubeTypes.hpp` | +| `LoggerInterface.hpp` | `logger/LoggerInterface.hpp` | +| `EventBus.hpp` | `eventbus/EventBus.hpp` | +| `Database.hpp` | `database/Database.hpp` | +| `CoreInterface.hpp` | `interfaces/CoreInterface.hpp` | +| `Cache.hpp` | `utils/Cache.hpp` | +| `MemoryPool.hpp` | `utils/MemoryPool.hpp` | + +## Files to Delete + +- `AudioTypesOnly.hpp` +- `ConfigTypesOnly.hpp` +- `LoggerTypesOnly.hpp` +- `NetworkTypesOnly.hpp` +- `PluginTypesOnly.hpp` +- `RpcTypesOnly.hpp` +- `TrackTypesOnly.hpp` +- `YouTubeTypesOnly.hpp` +- `BaseTypes.hpp` + +## Include Path Changes + +### For Plugin (minimal): + +**Before:** +```cpp +#include +``` + +**After:** +```cpp +#include +#include +#include +``` + +The CMake target `Echoion::ApiPlugin` will add the correct include paths. + +### For Core: + +**Before:** +```cpp +#include +``` + +**After:** +```cpp +#include +``` + +The CMake target `Echoion::ApiEventBus` adds `eventbus/` to the include path. + +## CMake Usage + +### Plugin only needs: +```cmake +target_link_libraries(EchoionPlugin PRIVATE + Echoion::ApiBase + Echoion::ApiPlugin + Echoion::ApiInterfaces +) +``` + +### Core uses everything: +```cmake +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::ApiInterfaces + Echoion::ApiUtils +) +``` + +## Commands to Execute + +Run these commands in the project root: + +```bash +# Create directory structure +cd EchoionApi/include/echoion/api +mkdir -p base audio track network plugin config rpc youtube logger eventbus database interfaces utils + +# Move files +mv Types.hpp base/ +mv AudioTypes.hpp audio/ +mv TrackTypes.hpp track/ +mv NetworkTypes.hpp network/ +mv PluginTypes.hpp plugin/ +mv ConfigTypes.hpp config/ +mv RpcTypes.hpp rpc/ +mv YouTubeTypes.hpp youtube/ +mv LoggerInterface.hpp logger/ +mv EventBus.hpp eventbus/ +mv Database.hpp database/ +mv CoreInterface.hpp interfaces/ +mv Cache.hpp utils/ +mv MemoryPool.hpp utils/ + +# Remove old files +rm -f *Only.hpp BaseTypes.hpp + +# Go back to project root +cd ../../../../.. + +# Create Export.hpp in interfaces (if not exists) +touch EchoionApi/include/echoion/api/interfaces/Export.hpp +``` diff --git a/include/echoion/api.hpp b/include/echoion/api.hpp index 2fef165..cb24d44 100644 --- a/include/echoion/api.hpp +++ b/include/echoion/api.hpp @@ -1,20 +1,33 @@ #pragma once -// Main Echoion API header - includes all types +// Main Echoion API header - backward compatibility +// Includes all submodules -#include "echoion/api/Types.hpp" -#include "echoion/api/AudioTypes.hpp" -#include "echoion/api/TrackTypes.hpp" -#include "echoion/api/NetworkTypes.hpp" -#include "echoion/api/PluginTypes.hpp" -#include "echoion/api/ConfigTypes.hpp" -// Note: ConfigManager is deprecated - config is now passed from Plugin to Core via initialize() -#include "echoion/api/RpcTypes.hpp" -#include "echoion/api/YouTubeTypes.hpp" -#include "echoion/api/LoggerInterface.hpp" -#include "echoion/api/CoreInterface.hpp" -#include "echoion/api/MemoryPool.hpp" -#include "echoion/api/Cache.hpp" -#include "echoion/api/EventBus.hpp" -#include "echoion/api/Database.hpp" -#include "echoion/api/Export.hpp" +// Base types +#include "api/base/Types.hpp" + +// Granular type modules +#include "api/audio/AudioTypes.hpp" +#include "api/config/ConfigTypes.hpp" +#include "api/logger/LoggerInterface.hpp" +#include "api/network/NetworkInterface.hpp" +#include "api/network/NetworkTypes.hpp" +#include "api/plugin/PluginTypes.hpp" +#include "api/rpc/RpcTypes.hpp" +#include "api/track/TrackTypes.hpp" +#include "api/youtube/YouTubeTypes.hpp" + +// Interfaces (decoupled) +#include "api/interfaces/CoreInterface.hpp" +#include "api/interfaces/OpaqueHandle.hpp" +#include "api/interfaces/PluginInterface.hpp" + +// Utilities +#include "api/utils/MemoryPool.hpp" + +// Core systems (for Core implementation only) +#include "api/database/Database.hpp" +#include "api/eventbus/EventBus.hpp" + +// Export macros +#include "api/interfaces/Export.hpp" diff --git a/include/echoion/api/AudioTypes.hpp b/include/echoion/api/AudioTypes.hpp deleted file mode 100644 index 70c1307..0000000 --- a/include/echoion/api/AudioTypes.hpp +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "MemoryPool.hpp" -#include -#include -#include - -namespace Echoion::Api { - -enum class AudioFormat : uint8_t { - Unknown = 0, - MP3, - AAC, - Opus, - Vorbis, - FLAC, - WAV -}; - -enum class AudioQuality : uint8_t { - Low = 0, // 64-96 kbps - Medium, // 128-160 kbps - High, // 192-256 kbps - VeryHigh, // 320 kbps - Lossless // FLAC or equivalent -}; - -// Hardware acceleration types -enum class HwAccelType : uint8_t { - None = 0, - CUDA, // NVIDIA CUDA - VAAPI, // Video Acceleration API (Linux) - DXVA2, // DirectX Video Acceleration 2 (Windows) - D3D11VA, // Direct3D 11 Video Acceleration - VideoToolbox, // Apple VideoToolbox - Vulkan // Vulkan Video -}; - -struct AudioFrame { - std::vector data; - std::chrono::milliseconds pts; - std::chrono::milliseconds duration; - bool isKeyFrame; -}; - -struct AudioStreamInfo { - AudioFormat format; - uint32_t sampleRate; - uint32_t channels; - uint32_t bitrate; - std::chrono::milliseconds duration; - std::optional quality; - bool hwAccelerated = false; - HwAccelType hwAccelType = HwAccelType::None; -}; - -// Zero-copy decoded audio using pooled memory (int16 for direct playback) -struct DecodedAudio { - // Use pooled buffer instead of std::vector for zero-copy - // Now using int16_t for direct TeamSpeak compatibility (no float conversion) - std::vector samples; - - // Non-owning view into the data - Int16AudioView view; - - uint32_t sampleRate; - uint32_t channels; - std::chrono::milliseconds timestamp; - - // Backwards compatibility - returns the samples - [[nodiscard]] std::vector getSamples() const { - return samples; - } - - // Check if valid - [[nodiscard]] bool isValid() const { - return !samples.empty(); - } - - // Apply volume in-place (int16 version) - void applyVolume(float volume) { - if (samples.empty()) return; - int32_t volInt = static_cast(volume * 32768); - for (auto& sample : samples) { - int32_t scaled = (static_cast(sample) * volInt) / 32768; - sample = static_cast(std::clamp(scaled, -32768, 32767)); - } - // Update view to point to new data - view = Int16AudioView(samples.data(), samples.size(), channels); - } -}; - -// Hardware acceleration configuration -struct HwAccelConfig { - HwAccelType type = HwAccelType::None; - int deviceIndex = -1; // -1 for auto-select - std::optional deviceName; - - [[nodiscard]] bool isEnabled() const { - return type != HwAccelType::None; - } -}; - -// Audio processing options -struct AudioProcessOptions { - float volume = 1.0f; - bool normalize = false; - bool highPassFilter = false; // Remove DC offset - float highPassFreq = 20.0f; // Hz - bool limiter = false; // Prevent clipping - float limiterThreshold = 0.95f; -}; - -using AudioBuffer = std::vector; -using AudioFramePtr = std::shared_ptr; - -} // namespace Echoion::Api diff --git a/include/echoion/api/Cache.hpp b/include/echoion/api/Cache.hpp deleted file mode 100644 index 6cd6b49..0000000 --- a/include/echoion/api/Cache.hpp +++ /dev/null @@ -1,389 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "NetworkTypes.hpp" -#include "TrackTypes.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -// Cache entry with metadata -template -struct CacheEntry { - T value; - std::chrono::system_clock::time_point created; - std::chrono::system_clock::time_point lastAccessed; - std::chrono::milliseconds ttl; - uint64_t accessCount = 0; - size_t size = 0; // Approximate memory size - - [[nodiscard]] bool isExpired() const { - auto now = std::chrono::system_clock::now(); - return (now - created) > ttl; - } -}; - -// Cache statistics -struct CacheStats { - size_t hits = 0; - size_t misses = 0; - size_t evictions = 0; - size_t inserts = 0; - size_t currentSize = 0; - size_t maxSize = 0; - size_t memoryUsage = 0; - double hitRate() const { - auto total = hits + misses; - return total > 0 ? static_cast(hits) / total : 0.0; - } -}; - -// Eviction policy -enum class EvictionPolicy { - LRU, // Least Recently Used - LFU, // Least Frequently Used - FIFO, // First In First Out - TTL // Time To Live only -}; - -// LRU Cache implementation -template -class LruCache { -public: - using Entry = CacheEntry; - using Loader = std::function(const Key&)>; - - explicit LruCache(size_t maxSize = 1000, - std::chrono::milliseconds defaultTtl = std::chrono::minutes(5), - EvictionPolicy policy = EvictionPolicy::LRU) - : maxSize_(maxSize) - , defaultTtl_(defaultTtl) - , policy_(policy) {} - - // Get value from cache (with optional loader for cache-aside pattern) - [[nodiscard]] std::optional get(const Key& key, Loader loader = nullptr) { - std::unique_lock lock(mutex_); - - auto it = cache_.find(key); - if (it != cache_.end()) { - // Check if expired - if (it->second.entry.isExpired()) { - // Remove expired entry - memoryUsage_ -= it->second.entry.size; - removeFromOrder(it->second.orderIt); - cache_.erase(it); - stats_.evictions++; - lock.unlock(); - stats_.misses++; - - // Try to load if loader provided - if (loader) { - auto value = loader(key); - if (value) { - put(key, *value); - return value; - } - } - return std::nullopt; - } - - // Update access info - it->second.entry.lastAccessed = std::chrono::system_clock::now(); - it->second.entry.accessCount++; - - // Move to front (MRU) for LRU policy - if (policy_ == EvictionPolicy::LRU) { - order_.splice(order_.begin(), order_, it->second.orderIt); - } - - stats_.hits++; - return it->second.entry.value; - } - - lock.unlock(); - stats_.misses++; - - // Try to load if loader provided - if (loader) { - auto value = loader(key); - if (value) { - put(key, *value); - return value; - } - } - - return std::nullopt; - } - - // Put value into cache - void put(const Key& key, const Value& value, - std::optional ttl = std::nullopt, - size_t estimatedSize = 0) { - - std::unique_lock lock(mutex_); - - // Check if key already exists - auto it = cache_.find(key); - if (it != cache_.end()) { - // Update existing entry - memoryUsage_ -= it->second.entry.size; - it->second.entry.value = value; - it->second.entry.created = std::chrono::system_clock::now(); - it->second.entry.lastAccessed = it->second.entry.created; - it->second.entry.ttl = ttl.value_or(defaultTtl_); - it->second.entry.size = estimatedSize; - memoryUsage_ += estimatedSize; - - // Move to front for LRU - if (policy_ == EvictionPolicy::LRU) { - order_.splice(order_.begin(), order_, it->second.orderIt); - } - return; - } - - // Evict entries if necessary - while (cache_.size() >= maxSize_ || - (maxMemory_ > 0 && memoryUsage_ + estimatedSize > maxMemory_)) { - if (!evictOne()) { - break; - } - } - - // Insert new entry - order_.push_front(key); - Entry entry{ - .value = value, - .created = std::chrono::system_clock::now(), - .lastAccessed = entry.created, - .ttl = ttl.value_or(defaultTtl_), - .accessCount = 1, - .size = estimatedSize - }; - - cache_[key] = { - .entry = std::move(entry), - .orderIt = order_.begin() - }; - - memoryUsage_ += estimatedSize; - stats_.inserts++; - stats_.currentSize = cache_.size(); - } - - // Remove specific key - bool remove(const Key& key) { - std::unique_lock lock(mutex_); - - auto it = cache_.find(key); - if (it == cache_.end()) { - return false; - } - - memoryUsage_ -= it->second.entry.size; - removeFromOrder(it->second.orderIt); - cache_.erase(it); - stats_.currentSize = cache_.size(); - return true; - } - - // Clear all entries - void clear() { - std::unique_lock lock(mutex_); - cache_.clear(); - order_.clear(); - memoryUsage_ = 0; - stats_.currentSize = 0; - } - - // Check if key exists (without updating access) - [[nodiscard]] bool contains(const Key& key) const { - std::shared_lock lock(mutex_); - return cache_.find(key) != cache_.end(); - } - - // Get cache statistics - [[nodiscard]] CacheStats getStats() const { - std::shared_lock lock(mutex_); - CacheStats stats = stats_; - stats.currentSize = cache_.size(); - stats.maxSize = maxSize_; - stats.memoryUsage = memoryUsage_; - return stats; - } - - // Reset statistics - void resetStats() { - std::unique_lock lock(mutex_); - stats_ = CacheStats{}; - } - - // Set max size - void setMaxSize(size_t maxSize) { - std::unique_lock lock(mutex_); - maxSize_ = maxSize; - - // Evict if necessary - while (cache_.size() > maxSize_) { - if (!evictOne()) { - break; - } - } - } - - // Set max memory (0 = unlimited) - void setMaxMemory(size_t maxMemory) { - std::unique_lock lock(mutex_); - maxMemory_ = maxMemory; - - // Evict if necessary - if (maxMemory_ > 0) { - while (memoryUsage_ > maxMemory_) { - if (!evictOne()) { - break; - } - } - } - } - - // Remove expired entries - size_t purgeExpired() { - std::unique_lock lock(mutex_); - size_t count = 0; - - auto now = std::chrono::system_clock::now(); - for (auto it = cache_.begin(); it != cache_.end();) { - if ((now - it->second.entry.created) > it->second.entry.ttl) { - memoryUsage_ -= it->second.entry.size; - removeFromOrder(it->second.orderIt); - it = cache_.erase(it); - count++; - } else { - ++it; - } - } - - stats_.evictions += count; - stats_.currentSize = cache_.size(); - return count; - } - -private: - struct Node { - Entry entry; - typename std::list::iterator orderIt; - }; - - bool evictOne() { - if (order_.empty()) { - return false; - } - - Key keyToEvict; - - switch (policy_) { - case EvictionPolicy::LRU: - case EvictionPolicy::FIFO: - // Evict from back (oldest/least recently used) - keyToEvict = order_.back(); - break; - - case EvictionPolicy::LFU: { - // Find least frequently used - auto minAccess = std::numeric_limits::max(); - for (const auto& [key, node] : cache_) { - if (node.entry.accessCount < minAccess) { - minAccess = node.entry.accessCount; - keyToEvict = key; - } - } - break; - } - - case EvictionPolicy::TTL: { - // Find soonest to expire - auto now = std::chrono::system_clock::now(); - auto minRemaining = std::chrono::milliseconds::max(); - for (const auto& [key, node] : cache_) { - auto remaining = node.entry.ttl - (now - node.entry.created); - if (remaining < minRemaining) { - minRemaining = remaining; - keyToEvict = key; - } - } - break; - } - } - - auto it = cache_.find(keyToEvict); - if (it != cache_.end()) { - memoryUsage_ -= it->second.entry.size; - removeFromOrder(it->second.orderIt); - cache_.erase(it); - stats_.evictions++; - return true; - } - - return false; - } - - void removeFromOrder(typename std::list::iterator it) { - order_.erase(it); - } - - mutable std::shared_mutex mutex_; - std::unordered_map cache_; - std::list order_; // For LRU/FIFO ordering - - size_t maxSize_; - size_t maxMemory_ = 0; - size_t memoryUsage_ = 0; - std::chrono::milliseconds defaultTtl_; - EvictionPolicy policy_; - - mutable CacheStats stats_; -}; - -// Type aliases for common cache types -using StringCache = LruCache; -using HttpCache = LruCache; -using TrackCache = LruCache; - -// Cache manager for multiple cache types -class CacheManager { -public: - static CacheManager& instance(); - - void initialize(); - void shutdown(); - - // Get specific caches - [[nodiscard]] HttpCache& httpCache() { return httpCache_; } - [[nodiscard]] TrackCache& trackCache() { return trackCache_; } - [[nodiscard]] StringCache& metadataCache() { return metadataCache_; } - - // Purge all expired entries - void purgeAllExpired(); - - // Clear all caches - void clearAll(); - - // Get combined stats - [[nodiscard]] std::unordered_map getAllStats() const; - -private: - CacheManager() = default; - - HttpCache httpCache_{100, std::chrono::minutes(5)}; - TrackCache trackCache_{500, std::chrono::hours(1)}; - StringCache metadataCache_{1000, std::chrono::minutes(30)}; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/ConfigManager.hpp b/include/echoion/api/ConfigManager.hpp deleted file mode 100644 index 518cac7..0000000 --- a/include/echoion/api/ConfigManager.hpp +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -#include "ConfigTypes.hpp" -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -/** - * @brief DEPRECATED: Global configuration manager - * - * This singleton pattern does NOT work across shared library boundaries. - * Each shared library (Plugin and Core) gets its own instance. - * - * NEW ARCHITECTURE: - * - Plugin loads config using ConfigLoader - - Plugin passes config to Core via CoreLoader::setConfig() -> Core::initialize() - * - Core stores config locally, updates via Core::updateConfig() - * - Config reload: Core calls plugin->reloadConfig() -> Core::updateConfig() - * - * This header is kept for backward compatibility but should not be used. - */ -class ConfigManager { -public: - using ConfigChangedCallback = std::function; - - // Get singleton instance - static ConfigManager& instance(); - - // Delete copy/move - ConfigManager(const ConfigManager&) = delete; - ConfigManager& operator=(const ConfigManager&) = delete; - - // Initialize with config file path (call once at startup) - [[nodiscard]] bool initialize(const std::filesystem::path& configPath); - - // Initialize with default path (~/.config/echoion/config.json) - [[nodiscard]] bool initialize(); - - // Get current config (thread-safe) - [[nodiscard]] AppConfig getConfig() const; - - // Get config by reference (faster, but hold lock briefly) - template - auto withConfig(Func&& func) const -> decltype(func(std::declval())) { - std::shared_lock lock(mutex_); - return func(config_); - } - - // Reload configuration from file - [[nodiscard]] bool reload(); - - // Save current configuration to file - [[nodiscard]] bool save(); - - // Update config (and optionally save) - void updateConfig(const AppConfig& config, bool saveToFile = true); - - // Check if initialized - [[nodiscard]] bool isInitialized() const; - - // Get config file path - [[nodiscard]] std::filesystem::path getConfigPath() const; - - // Get default config path (~/.config/echoion/config.json) - [[nodiscard]] static std::filesystem::path getDefaultConfigPath(); - - // Subscribe to config changes - void onConfigChanged(ConfigChangedCallback callback); - - // Create default config file if it doesn't exist - [[nodiscard]] bool createDefaultConfigIfNeeded(); - -private: - ConfigManager() = default; - ~ConfigManager() = default; - - mutable std::shared_mutex mutex_; - AppConfig config_; - std::filesystem::path configPath_; - std::atomic initialized_{false}; - std::vector callbacks_; - mutable std::mutex callbackMutex_; - - void notifyCallbacks(); - [[nodiscard]] bool loadFromFileInternal(); - [[nodiscard]] bool saveToFileInternal(); -}; - -} // namespace Echoion::Api - -// Convenience macro for accessing config -#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig()) diff --git a/include/echoion/api/ConfigTypes.hpp b/include/echoion/api/ConfigTypes.hpp deleted file mode 100644 index b90205a..0000000 --- a/include/echoion/api/ConfigTypes.hpp +++ /dev/null @@ -1,104 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "NetworkTypes.hpp" -#include "echoion/api/AudioTypes.hpp" -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -using ConfigValue = std::variant< - std::monostate, - bool, - int64_t, - double, - std::string, - std::vector ->; - -struct ConfigEntry { - std::string key; - ConfigValue value; - std::string description; - bool isSecret; - std::optional defaultValue; - std::optional category; -}; - -struct BotConfig { - std::string botName = "Echoion"; - std::string commandPrefix = "!"; - float defaultVolume = 0.5f; - bool autoReconnect = true; - std::chrono::milliseconds reconnectDelay = 5000ms; - uint32_t maxReconnectAttempts = 5; - std::optional proxy; - std::optional youtubeApiKey; - AudioQuality preferredQuality = AudioQuality::High; - bool allowPlaylistImports = true; - uint32_t maxQueueSize = 100; - std::chrono::milliseconds trackTimeout = 30000ms; - uint16_t rpcPort = 8765; // WebSocket RPC server port for Desktop/API clients - - // YouTube cookie file path for yt-dlp authentication - // See: https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies - std::optional youtubeCookiesPath; - - // Alternative: use cookies from browser directly - // e.g., "chrome", "firefox", "safari", "edge" - std::optional cookiesFromBrowser; - - // yt-dlp concurrent resolution settings - // Number of concurrent yt-dlp processes for playlist track resolution (1-8, default: 4) - size_t ytDlpMaxConcurrent = 4; - - // Enable async yt-dlp execution for better performance - bool ytDlpAsyncEnabled = true; - - // URL shortening settings - bool enableUrlShortening = true; // Enable faumaray.ru link shortening - std::optional urlShortenerApiUrl; // Custom URL shortener API endpoint -}; - -struct ServerConfig { - std::string address; - uint16_t port; - std::string serverPassword; - std::string nickname; - std::optional defaultChannelId; - std::optional channelPassword; - std::vector adminGroups; - std::vector djGroups; - std::vector bannedGroups; -}; - -struct AdminCredentials { - std::string username; - std::string passwordHash; - std::optional salt; - std::vector permissions; - std::chrono::system_clock::time_point createdAt; - std::optional lastLogin; - bool isActive; -}; - -struct SecurityConfig { - bool requireAuthForAdmin = true; - uint32_t maxLoginAttempts = 5; - std::chrono::milliseconds lockoutDuration = 300000ms; - std::chrono::milliseconds sessionTimeout = 3600000ms; - bool enableAuditLog = true; -}; - -struct AppConfig { - BotConfig bot; - ServerConfig server; - SecurityConfig security; - std::map custom; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/CoreInterface.hpp b/include/echoion/api/CoreInterface.hpp deleted file mode 100644 index bebcfcb..0000000 --- a/include/echoion/api/CoreInterface.hpp +++ /dev/null @@ -1,164 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "TrackTypes.hpp" -#include "PluginTypes.hpp" -#include "ConfigTypes.hpp" -#include "RpcTypes.hpp" -#include "NetworkTypes.hpp" -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -// Forward declarations -class IAudioDecoder; -class IMusicManager; -class ICommandManager; -class IPluginInterface; -class ICoreInterface; - -// Network client interface -class INetworkClient { -public: - virtual ~INetworkClient() = default; - - // Initialize with optional proxy - virtual Result initialize(const std::optional& proxy = std::nullopt) = 0; - virtual void shutdown() = 0; - - // Synchronous requests - [[nodiscard]] virtual Result get(std::string_view url, - const std::vector& headers = {}) = 0; - [[nodiscard]] virtual Result post(std::string_view url, - std::string_view body, const std::vector& headers = {}) = 0; - [[nodiscard]] virtual Result request(const HttpRequest& req) = 0; - - // Asynchronous requests - [[nodiscard]] virtual std::future> getAsync(std::string_view url, - const std::vector& headers = {}) = 0; - [[nodiscard]] virtual std::future> postAsync(std::string_view url, - std::string_view body, const std::vector& headers = {}) = 0; - [[nodiscard]] virtual std::future> requestAsync(const HttpRequest& req) = 0; - - // Proxy configuration - virtual void setProxy(const std::optional& proxy) = 0; - [[nodiscard]] virtual std::optional getProxy() const = 0; - virtual void clearProxy() = 0; - - // Retry configuration - virtual void setRetryConfig(const RetryConfig& config) = 0; - [[nodiscard]] virtual RetryConfig getRetryConfig() const = 0; -}; - -// Plugin interface that the core will use -class IPluginInterface { -public: - virtual ~IPluginInterface() = default; - - // Lifecycle - virtual Result initialize() = 0; - virtual Result shutdown() = 0; - - // Client operations - [[nodiscard]] virtual Result> getClients() = 0; - [[nodiscard]] virtual Result> - getClient(uint64_t clientId) = 0; - virtual Result moveClient(uint64_t clientId, uint64_t channelId) = 0; - virtual Result kickClient(uint64_t clientId, const std::string& reason) = 0; - - // Channel operations - [[nodiscard]] virtual Result> getChannels() const = 0; - [[nodiscard]] virtual Result> getChannel(uint64_t channelId) const = 0; - - // Messaging - virtual Result sendTextMessage(uint64_t targetId, const std::string& message) = 0; - virtual Result sendChannelMessage(uint64_t channelId, const std::string& message) = 0; - virtual Result sendServerMessage(const std::string& message) = 0; - - // Audio - virtual Result sendAudioData(const std::span& data) = 0; - virtual Result setWhisperList(const std::vector& clientIds) = 0; - - // Server connection - virtual Result connectToServer(const ServerConfig& config) = 0; - virtual Result disconnectFromServer() = 0; - [[nodiscard]] virtual bool isConnected() const = 0; - virtual Result reconnect() = 0; - - // Event subscription - virtual void registerEventCallback(const EventCallback& callback) = 0; - virtual void unregisterEventCallback(const EventCallback& callback) = 0; -}; - -using PluginInterfacePtr = std::shared_ptr; - -// Core interface that the plugin will use to communicate with the core -class ICoreInterface { -public: - virtual ~ICoreInterface() = default; - - // Lifecycle - // Plugin passes config file path, Core loads config internally (no AppConfig dependency in Plugin) - virtual Result initialize(const std::filesystem::path& configPath) = 0; - virtual Result shutdown() = 0; - virtual bool isInitialized() const noexcept = 0; - - // Playback control - virtual Result play(const TrackInfo& track) = 0; - virtual Result pause() = 0; - virtual Result resume() = 0; - virtual Result stop() = 0; - virtual Result skip(uint32_t count = 1) = 0; - virtual Result seek(std::chrono::milliseconds position) = 0; - virtual Result setVolume(float volume) = 0; - - // Queue management - virtual Result queueTrack(const TrackInfo& track, uint64_t clientId) = 0; - virtual Result removeFromQueue(uint64_t queueId) = 0; - virtual Result clearQueue() = 0; - [[nodiscard]] virtual Result> getQueue() const = 0; - virtual Result moveInQueue(uint64_t queueId, uint32_t newPosition) = 0; - - // Track info - [[nodiscard]] virtual Result> getCurrentTrack() const = 0; - [[nodiscard]] virtual Result getPlaybackState() const = 0; - - // Playlist - virtual Result loadPlaylist(const std::string& playlistId, uint64_t clientId) = 0; - virtual Result> getPlaylists() const = 0; - - // Configuration - virtual Result updateConfig(const AppConfig& config) = 0; - [[nodiscard]] virtual Result getConfig() const = 0; - - // Hot reload - virtual Result prepareForHotReload() = 0; - virtual Result restoreAfterHotReload(const HotReloadState& state) = 0; - - // Event handling - virtual void registerEventCallback(const EventCallback& callback) = 0; - virtual void unregisterEventCallback(const EventCallback& callback) = 0; - - // Plugin event processing - virtual Result onPluginEvent(const PluginEvent& event) = 0; - - // Status - [[nodiscard]] virtual std::string getVersion() const = 0; - [[nodiscard]] virtual std::chrono::system_clock::time_point getUptime() const = 0; - - // Plugin interface - virtual void setPluginInterface(PluginInterfacePtr pluginInterface) = 0; - - // Trigger auto-connect (call after setPluginInterface) - virtual void triggerAutoConnect() = 0; -}; - -using CoreInterfacePtr = std::shared_ptr; -using CoreCreateFunc = std::function; -using CoreDestroyFunc = std::function; - -} // namespace Echoion::Api diff --git a/include/echoion/api/Database.hpp b/include/echoion/api/Database.hpp deleted file mode 100644 index f544280..0000000 --- a/include/echoion/api/Database.hpp +++ /dev/null @@ -1,225 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "TrackTypes.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -// Forward declaration -class DatabaseImpl; - -// Database configuration -struct DatabaseConfig { - std::string path = "echoion.db"; - bool walMode = true; // Write-Ahead Logging for better concurrency - int maxConnections = 4; - std::chrono::seconds busyTimeout{5000}; -}; - -// Playlist with tracks -struct Playlist { - uint64_t id; - std::string name; - std::string description; - uint64_t createdBy; - std::chrono::system_clock::time_point createdAt; - std::chrono::system_clock::time_point updatedAt; - std::vector tracks; - bool isPublic = false; -}; - -// Playback history entry -struct PlaybackHistoryEntry { - uint64_t id; - TrackInfo track; - uint64_t playedBy; - std::chrono::system_clock::time_point playedAt; - std::chrono::milliseconds duration; // How long it played - bool completed = false; // Did it play to the end -}; - -// User favorites -struct FavoriteTrack { - TrackInfo track; - uint64_t userId; - std::chrono::system_clock::time_point addedAt; -}; - -// Statistics -struct PlaybackStatistics { - uint64_t totalPlays = 0; - uint64_t totalTracks = 0; - uint64_t totalPlaytimeMs = 0; - std::optional mostPlayedTrack; - uint64_t mostPlayedCount = 0; -}; - -// Main database interface -class Database { -public: - Database(); - ~Database(); - - // Non-copyable - Database(const Database&) = delete; - Database& operator=(const Database&) = delete; - - // Initialization - Api::Result initialize(const DatabaseConfig& config = {}); - void shutdown(); - [[nodiscard]] bool isInitialized() const; - - // Migrations - Api::Result migrate(); // Run pending migrations - [[nodiscard]] int getCurrentVersion() const; - - // ===== Playlists ===== - - // Create a new playlist - [[nodiscard]] Api::Result createPlaylist( - const std::string& name, - const std::string& description, - uint64_t createdBy, - bool isPublic = false); - - // Get playlist by ID - [[nodiscard]] Api::Result> getPlaylist(uint64_t id); - - // Get all playlists for a user - [[nodiscard]] Api::Result> getUserPlaylists(uint64_t userId); - - // Update playlist - Api::Result updatePlaylist(uint64_t id, - const std::optional& name = std::nullopt, - const std::optional& description = std::nullopt, - const std::optional& isPublic = std::nullopt); - - // Delete playlist - Api::Result deletePlaylist(uint64_t id); - - // Add track to playlist - Api::Result addTrackToPlaylist(uint64_t playlistId, - const TrackInfo& track, uint32_t position = 0); - - // Remove track from playlist - Api::Result removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId); - - // Reorder playlist tracks - Api::Result reorderPlaylistTrack(uint64_t playlistId, - uint64_t trackId, uint32_t newPosition); - - // ===== Playback History ===== - - // Record a playback - Api::Result recordPlayback(const TrackInfo& track, - uint64_t playedBy, - std::chrono::milliseconds duration, - bool completed); - - // Get playback history for a user - [[nodiscard]] Api::Result> getPlaybackHistory( - uint64_t userId, - size_t limit = 100, - size_t offset = 0); - - // Get recently played tracks - [[nodiscard]] Api::Result> getRecentlyPlayed( - uint64_t userId, - size_t limit = 20); - - // ===== Favorites ===== - - // Add track to favorites - Api::Result addFavorite(uint64_t userId, const TrackInfo& track); - - // Remove track from favorites - Api::Result removeFavorite(uint64_t userId, const std::string& trackUrl); - - // Check if track is favorited - [[nodiscard]] Api::Result isFavorite(uint64_t userId, const std::string& trackUrl); - - // Get all favorites for a user - [[nodiscard]] Api::Result> getFavorites(uint64_t userId); - - // ===== Statistics ===== - - // Get playback statistics - [[nodiscard]] Api::Result getStatistics( - uint64_t userId, - std::optional since = std::nullopt); - - // Get most played tracks - [[nodiscard]] Api::Result>> getMostPlayed( - uint64_t userId, - size_t limit = 10); - - // ===== Subscriptions ===== - - // Subscriber info - struct SubscriberInfo { - std::string uid; - std::string nickname; - std::chrono::system_clock::time_point subscribedAt; - }; - - // Add a subscriber (by UID) - Api::Result addSubscriber(const std::string& uid, const std::string& nickname); - - // Remove a subscriber (by UID) - Api::Result removeSubscriber(const std::string& uid); - - // Check if client is subscribed (by UID) - [[nodiscard]] Api::Result isSubscriber(const std::string& uid); - - // Get all subscribers - [[nodiscard]] Api::Result> getAllSubscribers(); - - // Get subscriber count - [[nodiscard]] Api::Result getSubscriberCount(); - - // Clear all subscribers - Api::Result clearAllSubscribers(); - - // ===== Cache Management ===== - - // Clear old history (keep last N entries) - Api::Result trimHistory(size_t keepCount = 10000); - - // Clear all data for a user - Api::Result clearUserData(uint64_t userId); - - // Vacuum database (reclaim space) - Api::Result vacuum(); - - // ===== Raw Query (for advanced use) ===== - - using RowCallback = std::function>&)>; - Api::Result executeQuery(const std::string& sql, RowCallback callback = nullptr); - -private: - std::unique_ptr impl_; - mutable std::shared_mutex mutex_; // Shared mutex for read/write concurrency - std::atomic shutdown_{false}; // Flag to prevent operations after shutdown -}; - -// Database manager (singleton) -class DatabaseManager { -public: - static Database& instance(); - - static Api::Result initialize(const DatabaseConfig& config = {}); - static void shutdown(); - -private: - DatabaseManager() = default; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/EventBus.hpp b/include/echoion/api/EventBus.hpp deleted file mode 100644 index d20273b..0000000 --- a/include/echoion/api/EventBus.hpp +++ /dev/null @@ -1,269 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "echoion/api/ConfigTypes.hpp" -#include "echoion/api/PluginTypes.hpp" -#include "echoion/api/TrackTypes.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -// Base event interface -struct IEvent { - virtual ~IEvent() = default; - virtual std::type_index getType() const = 0; - std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now(); -}; - -// Typed event wrapper -template -struct Event : IEvent { - T data; - - explicit Event(T d) : data(std::move(d)) {} - - std::type_index getType() const override { - return std::type_index(typeid(T)); - } -}; - -// Event handler type -template -using EventHandler = std::function; - -// Subscription token for unsubscribing -class SubscriptionToken { -public: - using Id = uint64_t; - - SubscriptionToken() = default; - explicit SubscriptionToken(Id id, std::type_index type, - std::weak_ptr&)>> handler) - : id_(id), type_(type), handler_(std::move(handler)) {} - - [[nodiscard]] bool isValid() const { return id_ != 0; } - [[nodiscard]] Id getId() const { return id_; } - [[nodiscard]] std::type_index getType() const { return type_; } - -private: - Id id_ = 0; - std::type_index type_ = std::type_index(typeid(void)); - std::weak_ptr&)>> handler_; - - friend class EventBus; -}; - -// Event bus for decoupled communication -class EventBus { -public: - EventBus(); - ~EventBus(); - - // Delete copy/move - EventBus(const EventBus&) = delete; - EventBus& operator=(const EventBus&) = delete; - EventBus(EventBus&&) = delete; - EventBus& operator=(EventBus&&) = delete; - - // Start processing events - void start(); - void stop(); - - // Publish an event (thread-safe) - template - void publish(T event) { - auto evt = std::make_shared>(std::move(event)); - { - std::lock_guard lock(queueMutex_); - eventQueue_.push(evt); - } - queueCv_.notify_one(); - } - - // Subscribe to events (thread-safe) - template - [[nodiscard]] SubscriptionToken subscribe(EventHandler handler) { - auto wrappedHandler = std::make_shared&)>>( - [h = std::move(handler)](const std::shared_ptr& evt) { - if (auto typedEvt = std::dynamic_pointer_cast>(evt)) { - h(typedEvt->data); - } - } - ); - - std::type_index type(typeid(T)); - auto id = nextId_++; - - { - std::unique_lock lock(handlersMutex_); - handlers_[type][id] = wrappedHandler; - } - - return SubscriptionToken(id, type, wrappedHandler); - } - - // Unsubscribe from events - void unsubscribe(const SubscriptionToken& token); - - // Process a single event immediately (for synchronous processing) - void processOne(); - - // Wait for and process one event (blocking) - bool waitAndProcessOne(std::chrono::milliseconds timeout); - - // Clear all pending events - void clearQueue(); - - // Get number of pending events - [[nodiscard]] size_t getPendingEventCount() const; - -private: - void processEvents(); - - mutable std::shared_mutex handlersMutex_; - std::unordered_map&)>>>> handlers_; - - mutable std::mutex queueMutex_; - std::queue> eventQueue_; - std::condition_variable queueCv_; - - std::atomic running_{false}; - std::atomic stopRequested_{false}; - std::jthread eventThread_; - - std::atomic nextId_{1}; -}; - -// Global event bus singleton -class GlobalEventBus { -public: - [[nodiscard]] static EventBus& instance(); - -private: - GlobalEventBus() = default; -}; - -// Common event types for Echoion -namespace Events { - -// Playback events -struct PlaybackStarted { - TrackInfo track; - uint64_t clientId; -}; - -struct PlaybackPaused { - std::chrono::milliseconds position; -}; - -struct PlaybackResumed { - std::chrono::milliseconds position; -}; - -struct PlaybackStopped {}; - -struct TrackFinished { - TrackInfo track; - bool autoSkipped; -}; - -struct VolumeChanged { - float oldVolume; - float newVolume; - uint64_t changedByClientId; -}; - -// Queue events -struct TrackQueued { - TrackInfo track; - uint64_t queueId; - uint64_t addedByClientId; - uint32_t position; -}; - -struct TrackRemoved { - uint64_t queueId; - uint64_t removedByClientId; -}; - -struct QueueCleared { - uint64_t clearedByClientId; -}; - -struct QueueShuffled { - uint64_t triggeredByClientId; -}; - -// Connection events -struct ClientConnected { - ClientInfo client; -}; - -struct ClientDisconnected { - uint64_t clientId; - std::string reason; -}; - -struct ChannelChanged { - uint64_t clientId; - uint64_t oldChannelId; - uint64_t newChannelId; -}; - -// Error events -struct PlaybackError { - ErrorCode code; - std::string message; - std::optional track; -}; - -struct NetworkError { - std::string url; - ErrorCode code; - std::string message; -}; - -// Configuration events -struct ConfigReloaded { - BotConfig newConfig; -}; - -struct ConfigChanged { - std::string key; - std::string oldValue; - std::string newValue; -}; - -// Cache events -struct CacheHit { - std::string key; - std::string type; -}; - -struct CacheMiss { - std::string key; - std::string type; -}; - -struct CacheEvicted { - std::string key; - std::string reason; -}; - -} // namespace Events - -// Helper macros for event publishing/subscribing -#define ECHOION_PUBLISH(event) Echoion::Api::GlobalEventBus::instance().publish(event) -#define ECHOION_SUBSCRIBE(type, handler) Echoion::Api::GlobalEventBus::instance().subscribe(handler) - -} // namespace Echoion::Api diff --git a/include/echoion/api/Export.hpp b/include/echoion/api/Export.hpp deleted file mode 100644 index da99dd2..0000000 --- a/include/echoion/api/Export.hpp +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once - -#include "CoreInterface.hpp" - -// Platform-specific export macros -#ifdef _WIN32 - #ifdef ECHOION_API_EXPORT - #define ECHOION_API __declspec(dllexport) - #else - #define ECHOION_API __declspec(dllimport) - #endif -#else - #define ECHOION_API __attribute__((visibility("default"))) -#endif - -namespace Echoion::Api { - -// Version information -constexpr uint32_t VERSION_MAJOR = 1; -constexpr uint32_t VERSION_MINOR = 0; -constexpr uint32_t VERSION_PATCH = 0; -constexpr const char* VERSION_STRING = "1.0.0"; - -// API export functions -extern "C" { - // Create a new core instance - ECHOION_API CoreInterfacePtr CreateCore(); - - // Destroy a core instance - ECHOION_API void DestroyCore(ICoreInterface* core); - - // Get API version - ECHOION_API const char* GetApiVersion(); - - // Check if API is compatible - ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor); -} - -} // namespace Echoion::Api diff --git a/include/echoion/api/LoggerInterface.hpp b/include/echoion/api/LoggerInterface.hpp deleted file mode 100644 index 9c61679..0000000 --- a/include/echoion/api/LoggerInterface.hpp +++ /dev/null @@ -1,104 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include -#include -#include -#include - -namespace Echoion::Api { - -// Logger interface for the user's custom logger implementation -class ILogger { -public: - virtual ~ILogger() = default; - - // Core logging method - virtual void log(LogLevel level, std::string_view message, - std::source_location location = std::source_location::current()) = 0; - - // Convenience methods - virtual void debug(std::string_view message, - std::source_location location = std::source_location::current()) { - log(LogLevel::Debug, message, location); - } - - virtual void info(std::string_view message, - std::source_location location = std::source_location::current()) { - log(LogLevel::Info, message, location); - } - - virtual void warning(std::string_view message, - std::source_location location = std::source_location::current()) { - log(LogLevel::Warning, message, location); - } - - virtual void error(std::string_view message, - std::source_location location = std::source_location::current()) { - log(LogLevel::Error, message, location); - } - - virtual void critical(std::string_view message, - std::source_location location = std::source_location::current()) { - log(LogLevel::Critical, message, location); - } - - // Template method for formatted logging - template - void logf(LogLevel level, std::format_string fmt, Args&&... args, - std::source_location location = std::source_location::current()) { - log(level, std::format(fmt, std::forward(args)...), location); - } - - // Set minimum log level - virtual void setMinLevel(LogLevel level) = 0; - [[nodiscard]] virtual LogLevel getMinLevel() const = 0; - - // Register log callback - using LogCallback = std::function; - virtual void registerCallback(const LogCallback& callback) = 0; - virtual void unregisterCallback(const LogCallback& callback) = 0; -}; - -using LoggerPtr = std::shared_ptr; - -// Global logger accessor -class LoggerRegistry { -public: - static LoggerRegistry& instance() { - static LoggerRegistry instance; - return instance; - } - - void setLogger(LoggerPtr logger) { logger_ = std::move(logger); } - [[nodiscard]] LoggerPtr getLogger() const { return logger_; } - - [[nodiscard]] bool hasLogger() const noexcept { return static_cast(logger_); } - -private: - LoggerRegistry() = default; - LoggerPtr logger_; -}; - -// Convenience macros -#define ECHOION_LOG_DEBUG(msg) \ - do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \ - logger->debug(msg); } while(0) - -#define ECHOION_LOG_INFO(msg) \ - do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \ - logger->info(msg); } while(0) - -#define ECHOION_LOG_WARNING(msg) \ - do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \ - logger->warning(msg); } while(0) - -#define ECHOION_LOG_ERROR(msg) \ - do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \ - logger->error(msg); } while(0) - -#define ECHOION_LOG_CRITICAL(msg) \ - do { if (auto logger = Echoion::Api::LoggerRegistry::instance().getLogger()) \ - logger->critical(msg); } while(0) - -} // namespace Echoion::Api diff --git a/include/echoion/api/MemoryPool.hpp b/include/echoion/api/MemoryPool.hpp deleted file mode 100644 index 707582a..0000000 --- a/include/echoion/api/MemoryPool.hpp +++ /dev/null @@ -1,292 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -// Custom allocator for audio buffers -template -class MemoryPool { -public: - explicit MemoryPool(size_t blockSize, size_t initialBlocks = 64) - : blockSize_(blockSize) - , capacity_(initialBlocks) { - - // Pre-allocate memory - storage_.resize(blockSize_ * capacity_); - - // Initialize free list - for (size_t i = 0; i < capacity_; ++i) { - freeList_.push(&storage_[i * blockSize_]); - } - - available_.store(capacity_, std::memory_order_relaxed); - } - - ~MemoryPool() = default; - - // Non-copyable, non-movable - MemoryPool(const MemoryPool&) = delete; - MemoryPool& operator=(const MemoryPool&) = delete; - MemoryPool(MemoryPool&&) = delete; - MemoryPool& operator=(MemoryPool&&) = delete; - - // Allocate a block - [[nodiscard]] T* acquire() { - std::lock_guard lock(mutex_); - - if (freeList_.empty()) { - // Grow pool if needed - grow(); - } - - if (freeList_.empty()) { - return nullptr; // Out of memory - } - - T* block = freeList_.front(); - freeList_.pop(); - available_.fetch_sub(1, std::memory_order_relaxed); - - return block; - } - - // Release a block back to pool - void release(T* block) { - if (!block) return; - - // Verify block belongs to this pool - if (!contains(block)) { - return; // Or assert/panic - } - - std::lock_guard lock(mutex_); - freeList_.push(block); - available_.fetch_add(1, std::memory_order_relaxed); - } - - // Get available blocks count - [[nodiscard]] size_t available() const { - return available_.load(std::memory_order_relaxed); - } - - // Get total capacity - [[nodiscard]] size_t capacity() const { - std::lock_guard lock(mutex_); - return capacity_; - } - - // Get block size - [[nodiscard]] size_t blockSize() const { - return blockSize_; - } - - // Reserve additional blocks - void reserve(size_t additionalBlocks) { - std::lock_guard lock(mutex_); - - size_t oldCapacity = capacity_; - size_t newCapacity = capacity_ + additionalBlocks; - - storage_.resize(blockSize_ * newCapacity); - - // Add new blocks to free list - for (size_t i = oldCapacity; i < newCapacity; ++i) { - freeList_.push(&storage_[i * blockSize_]); - } - - capacity_ = newCapacity; - available_.fetch_add(additionalBlocks, std::memory_order_relaxed); - } - -private: - [[nodiscard]] bool contains(const T* block) const { - return block >= &storage_[0] && - block <= &storage_[(capacity_ - 1) * blockSize_]; - } - - void grow() { - // Double the capacity - size_t additionalBlocks = capacity_; - reserve(additionalBlocks); - } - - size_t blockSize_; - size_t capacity_; - std::vector storage_; - std::queue freeList_; - mutable std::mutex mutex_; - std::atomic available_; -}; - -// Smart pointer for pooled memory -template -class PooledPtr { -public: - PooledPtr() = default; - - PooledPtr(T* ptr, MemoryPool* pool) - : ptr_(ptr), pool_(pool) {} - - ~PooledPtr() { - reset(); - } - - // Move semantics only - PooledPtr(PooledPtr&& other) noexcept - : ptr_(other.ptr_), pool_(other.pool_) { - other.ptr_ = nullptr; - other.pool_ = nullptr; - } - - PooledPtr& operator=(PooledPtr&& other) noexcept { - if (this != &other) { - reset(); - ptr_ = other.ptr_; - pool_ = other.pool_; - other.ptr_ = nullptr; - other.pool_ = nullptr; - } - return *this; - } - - // Delete copy - PooledPtr(const PooledPtr&) = delete; - PooledPtr& operator=(const PooledPtr&) = delete; - - [[nodiscard]] T* get() const { return ptr_; } - [[nodiscard]] T& operator*() const { return *ptr_; } - [[nodiscard]] T* operator->() const { return ptr_; } - [[nodiscard]] explicit operator bool() const { return ptr_ != nullptr; } - - [[nodiscard]] T* release() { - T* tmp = ptr_; - ptr_ = nullptr; - pool_ = nullptr; - return tmp; - } - - void reset() { - if (ptr_ && pool_) { - pool_->release(ptr_); - } - ptr_ = nullptr; - pool_ = nullptr; - } - -private: - T* ptr_ = nullptr; - MemoryPool* pool_ = nullptr; -}; - -// Specialized audio buffer pool for int16 (direct TeamSpeak compatibility) -class AudioBufferPool { -public: - static constexpr size_t DEFAULT_BUFFER_SIZE = 1920; // 48000Hz * 2ch * 20ms - static constexpr size_t DEFAULT_POOL_SIZE = 256; // ~1MB for int16 buffers - - static AudioBufferPool& instance(); - - void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE, - size_t poolSize = DEFAULT_POOL_SIZE); - void shutdown(); - - // Get a buffer (returns nullptr if pool exhausted) - [[nodiscard]] PooledPtr acquireBuffer(); - - // Get buffer size - [[nodiscard]] size_t getBufferSize() const { return bufferSize_; } - - // Get stats - [[nodiscard]] size_t getAvailableBuffers() const; - [[nodiscard]] size_t getTotalBuffers() const; - -private: - AudioBufferPool() = default; - - std::unique_ptr> pool_; - size_t bufferSize_ = DEFAULT_BUFFER_SIZE; -}; - -// Zero-copy audio buffer view -template -class AudioBufferView { -public: - AudioBufferView() = default; - - AudioBufferView(T* data, size_t size, size_t channels = 2) - : data_(data), size_(size), channels_(channels) {} - - [[nodiscard]] T* data() { return data_; } - [[nodiscard]] const T* data() const { return data_; } - [[nodiscard]] size_t size() const { return size_; } - [[nodiscard]] size_t channels() const { return channels_; } - [[nodiscard]] size_t samplesPerChannel() const { return size_ / channels_; } - - [[nodiscard]] T* channel(size_t ch) { - return data_ + ch; - } - - [[nodiscard]] T& sample(size_t frame, size_t ch) { - return data_[frame * channels_ + ch]; - } - - [[nodiscard]] const T& sample(size_t frame, size_t ch) const { - return data_[frame * channels_ + ch]; - } - - // Span for single channel - [[nodiscard]] std::span getChannelSpan(size_t ch) { - return std::span(data_ + ch, size_, channels_); - } - - // Span for all data - [[nodiscard]] std::span getSpan() { - return std::span(data_, size_); - } - - [[nodiscard]] bool empty() const { return data_ == nullptr || size_ == 0; } - - void clear() { - if (data_) { - std::memset(data_, 0, size_ * sizeof(T)); - } - } - - // Apply gain in-place - void applyGain(float gain) { - if (!data_) return; - for (size_t i = 0; i < size_; ++i) { - data_[i] *= gain; - } - } - - // Mix another buffer into this one - void mix(const AudioBufferView& other, float gain = 1.0f) { - if (!data_ || !other.data_) return; - size_t mixSize = std::min(size_, other.size_); - for (size_t i = 0; i < mixSize; ++i) { - data_[i] += other.data_[i] * gain; - } - } - -private: - T* data_ = nullptr; - size_t size_ = 0; - size_t channels_ = 2; -}; - -// Audio buffer view types - using int16 (short) for direct TeamSpeak compatibility -using Int16AudioView = AudioBufferView; - -// Deprecated: Float audio view is no longer used, all audio is int16 -using FloatAudioView = AudioBufferView; - -} // namespace Echoion::Api diff --git a/include/echoion/api/NetworkTypes.hpp b/include/echoion/api/NetworkTypes.hpp deleted file mode 100644 index bc7831c..0000000 --- a/include/echoion/api/NetworkTypes.hpp +++ /dev/null @@ -1,145 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -enum class HttpMethod : uint8_t { - GET = 0, - POST, - PUT, - DELETE, - PATCH, - HEAD, - OPTIONS -}; - -enum class ProxyType : uint8_t { - HTTP = 0, - SOCKS5 -}; - -struct ProxyConfig { - ProxyType type = ProxyType::HTTP; - std::string host; - uint16_t port; - std::optional username; - std::optional password; - std::optional timeout; - - [[nodiscard]] bool isValid() const noexcept { - return !host.empty() && port > 0; - } - - [[nodiscard]] bool requiresAuth() const noexcept { - return username.has_value() && password.has_value(); - } - - [[nodiscard]] bool isSocks5() const noexcept { - return type == ProxyType::SOCKS5; - } - - [[nodiscard]] bool operator==(const ProxyConfig& other) const = default; - [[nodiscard]] bool operator!=(const ProxyConfig& other) const = default; -}; - -struct HttpHeader { - std::string name; - std::string value; -}; - -struct HttpRequest { - std::string url; - HttpMethod method = HttpMethod::GET; - std::vector headers; - std::optional> body; - std::optional proxy; - std::chrono::milliseconds timeout = 30000ms; - bool followRedirects = true; - uint32_t maxRedirects = 10; -}; - -struct HttpResponse { - int32_t statusCode; - // Using vector to support multiple headers with same name (e.g., Set-Cookie) - std::vector> headers; - std::string body; - std::chrono::milliseconds responseTime; - std::optional contentType; - bool fromCache = false; - - [[nodiscard]] bool isSuccess() const noexcept { - return statusCode >= 200 && statusCode < 300; - } - - [[nodiscard]] bool isRedirect() const noexcept { - return statusCode >= 300 && statusCode < 400; - } - - [[nodiscard]] bool isError() const noexcept { - return statusCode >= 400 || statusCode == 0; - } - - [[nodiscard]] std::string bodyAsString() const { - return std::string(body.begin(), body.end()); - } - - // Helper to get first header value by name (case-insensitive) - [[nodiscard]] std::optional getHeader(std::string_view name) const { - for (const auto& [key, value] : headers) { - if (key.size() == name.size()) { - bool match = true; - for (size_t i = 0; i < key.size(); ++i) { - if (std::tolower(static_cast(key[i])) != - std::tolower(static_cast(name[i]))) { - match = false; - break; - } - } - if (match) return value; - } - } - return std::nullopt; - } - - // Helper to get all header values by name (case-insensitive) - useful for Set-Cookie - [[nodiscard]] std::vector getHeaders(std::string_view name) const { - std::vector result; - for (const auto& [key, value] : headers) { - if (key.size() == name.size()) { - bool match = true; - for (size_t i = 0; i < key.size(); ++i) { - if (std::tolower(static_cast(key[i])) != - std::tolower(static_cast(name[i]))) { - match = false; - break; - } - } - if (match) result.push_back(value); - } - } - return result; - } -}; - -struct RateLimitInfo { - uint32_t limit; - uint32_t remaining; - std::optional resetTime; -}; - -struct RetryConfig { - uint32_t maxRetries = 3; - std::chrono::milliseconds initialDelay = 1000ms; - std::chrono::milliseconds maxDelay = 30000ms; - float backoffMultiplier = 2.0f; - std::vector retryableStatusCodes = {408, 429, 500, 502, 503, 504}; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/PluginTypes.hpp b/include/echoion/api/PluginTypes.hpp deleted file mode 100644 index f16421a..0000000 --- a/include/echoion/api/PluginTypes.hpp +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "TrackTypes.hpp" -#include -#include -#include -#include - -namespace Echoion::Api { - -enum class PluginEventType : uint8_t { - // Connection events - ClientConnected = 0, - ClientDisconnected, - ClientMoved, - - // Chat events - TextMessageReceived, - - // Audio events - VoiceDataReceived, - - // Bot control events - PlayRequested, - PauseRequested, - SkipRequested, - StopRequested, - - // Queue events - TrackQueued, - TrackRemoved, - QueueCleared, - QueueUpdated, - - // State events - PlaybackStarted, - PlaybackPaused, - PlaybackResumed, - PlaybackStopped, - TrackFinished, - TrackSkipped, - VolumeChanged, - SeekPosition, - - // System events - HotReloadRequested, - HotReloadCompleted, - ConfigurationChanged -}; - -struct PluginEvent { - PluginEventType type; - std::optional clientName; - uint64_t clientId; - std::optional targetChannelId; - std::optional message; - std::optional trackInfo; - std::optional volume; - std::optional queuePosition; - std::chrono::system_clock::time_point timestamp; -}; - -struct ClientInfo { - uint64_t id; - std::string nickname; - std::optional uniqueIdentifier; - uint64_t channelId; - bool isTalking; - bool isMuted; - bool isDeafened; - std::vector serverGroups; -}; - -struct ChannelInfo { - uint64_t id; - std::string name; - std::optional parentId; - uint64_t order; - bool isDefault; - bool hasPassword; - uint32_t maxClients; - uint32_t currentClients; -}; - -struct ServerInfo { - uint64_t id; - std::string name; - std::string welcomeMessage; - uint32_t maxClients; - uint32_t currentClients; - uint64_t defaultChannelId; -}; - -using EventCallback = std::function; -using CommandHandler = std::function& args)>; - -struct CommandInfo { - std::string name; - std::string description; - std::vector aliases; - std::optional usage; - bool requiresAdmin; - CommandHandler handler; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/RpcTypes.hpp b/include/echoion/api/RpcTypes.hpp deleted file mode 100644 index 5f56439..0000000 --- a/include/echoion/api/RpcTypes.hpp +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "TrackTypes.hpp" -#include "PluginTypes.hpp" -#include "ConfigTypes.hpp" -#include -#include -#include -#include - -namespace Echoion::Api { - -enum class RpcMethod : uint8_t { - // Playback control - Play = 0, - Pause, - Resume, - Stop, - Skip, - Seek, - SetVolume, - - // Queue management - QueueTrack, - RemoveFromQueue, - ClearQueue, - GetQueue, - MoveInQueue, - - // Track info - GetCurrentTrack, - GetTrackInfo, - SearchTracks, - - // Playlist - LoadPlaylist, - SavePlaylist, - GetPlaylists, - DeletePlaylist, - - // Configuration - GetConfig, - SetConfig, - ReloadConfig, - - // Plugin/Core management - GetStatus, - HotReload, - Shutdown, - - // Admin - Authenticate, - Logout, - GetAuditLog, - ManageUsers -}; - -struct RpcRequest { - uint64_t id; - RpcMethod method; - std::optional params; - std::optional authToken; - std::chrono::system_clock::time_point timestamp; -}; - -struct RpcResponse { - uint64_t requestId; - bool success; - std::optional result; - std::optional error; // JSON string: {"code":N,"message":"...","source":"..."} - std::chrono::system_clock::time_point timestamp; -}; - -struct RpcNotification { - std::string event; - std::optional data; - std::chrono::system_clock::time_point timestamp; -}; - -using RpcHandler = std::function; - -struct RpcEndpoint { - RpcMethod method; - std::string name; - std::string description; - bool requiresAuth; - RpcHandler handler; -}; - -// Hot reload state preservation -struct HotReloadState { - PlaybackState playback; - std::vector queue; - std::optional currentStreamUrl; - std::chrono::milliseconds playbackPosition; - BotConfig config; - std::map sessionData; - - [[nodiscard]] bool shouldPreservePlayback() const noexcept { - return playback.isPlaying && playback.currentTrack.has_value(); - } -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/TrackTypes.hpp b/include/echoion/api/TrackTypes.hpp deleted file mode 100644 index ce71690..0000000 --- a/include/echoion/api/TrackTypes.hpp +++ /dev/null @@ -1,100 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "AudioTypes.hpp" -#include -#include -#include -#include - -namespace Echoion::Api { - -enum class TrackSource : uint8_t { - Unknown = 0, - YouTube, - SoundCloud, - Spotify, - LocalFile, - URL -}; - -struct TrackInfo { - std::string id; - std::string title; - std::string artist; - std::string album; - std::optional thumbnailUrl; - std::optional duration; - TrackSource source; - std::string originalUrl; - std::optional shortenedUrl; // faumaray.ru shortened link - std::optional streamUrl; - std::optional audioInfo; - std::chrono::system_clock::time_point addedAt; - std::string requestedBy; - - // Format track as markdown link: [Title](shortenedUrl) - // Only uses shortened URL (faumaray), returns empty string if not available - [[nodiscard]] std::string formatWithLink() const { - if (shortenedUrl.has_value() && !shortenedUrl->empty()) { - return std::format("[{}]({})", title, *shortenedUrl); - } - return std::format("[{}]", title); // No link if no shortened URL - } - - // Format track with artist and link - // Only uses shortened URL (faumaray), returns text only if not available - [[nodiscard]] std::string formatWithArtistAndLink() const { - std::string displayTitle = title; - if (!artist.empty()) { - displayTitle = std::format("{} by {}", title, artist); - } - if (shortenedUrl.has_value() && !shortenedUrl->empty()) { - return std::format("[{}]({})", displayTitle, *shortenedUrl); - } - return displayTitle; // No link if no shortened URL - } -}; - -struct PlaylistInfo { - std::string id; - std::string name; - std::string description; - std::optional thumbnailUrl; - std::string owner; - std::vector tracks; - std::chrono::system_clock::time_point createdAt; - std::chrono::system_clock::time_point updatedAt; -}; - -struct QueueEntry { - uint64_t queueId; - TrackInfo track; - std::chrono::system_clock::time_point addedAt; - std::string addedBy; - bool isPlaying; - std::optional position; -}; - -struct PlaybackState { - std::optional currentTrack; - std::vector queue; - bool isPlaying; - bool isPaused; - std::chrono::milliseconds position; - std::chrono::milliseconds buffered; - float volume; - bool repeat; - bool shuffle; - std::chrono::system_clock::time_point lastUpdate; -}; - -struct SearchResult { - std::vector tracks; - std::vector playlists; - std::string query; - std::optional nextPageToken; - uint32_t totalResults; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/Types.hpp b/include/echoion/api/Types.hpp deleted file mode 100644 index 03759d7..0000000 --- a/include/echoion/api/Types.hpp +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Api { - -using namespace std::chrono_literals; - -enum class ErrorCode : uint32_t { - Success = 0, - InvalidArgument, - NotFound, - AlreadyExists, - NetworkError, - ParseError, - AudioError, - PluginError, - InvalidUrl, - NotAuthenticated, - Unauthorized, - PermissionDenied, - ServiceUnavailable, - DatabaseError, - NotSupported, - NotInitialized, - UnknownError -}; - -struct Error { - ErrorCode code; - std::string message; - std::string source; - std::chrono::system_clock::time_point timestamp; - - Error() = default; - Error(ErrorCode c, std::string_view msg, std::string_view src = "") - : code(c), message(msg), source(src), timestamp(std::chrono::system_clock::now()) {} - - [[nodiscard]] std::string toString() const { - return std::format("[{}] {} (from: {})", - static_cast(code), message, source); - } -}; - -template -using Result = std::expected; - -enum class LogLevel : uint8_t { - Debug = 0, - Info, - Warning, - Error, - Critical -}; - -struct LogEntry { - LogLevel level; - std::string message; - std::string source; - std::string sourceFile; - uint32_t sourceLine = 0; - std::string function; - std::thread::id threadId; - std::chrono::system_clock::time_point timestamp; -}; - -} // namespace Echoion::Api diff --git a/include/echoion/api/YouTubeTypes.hpp b/include/echoion/api/YouTubeTypes.hpp deleted file mode 100644 index f9480ad..0000000 --- a/include/echoion/api/YouTubeTypes.hpp +++ /dev/null @@ -1,134 +0,0 @@ -#pragma once - -#include "Types.hpp" -#include "TrackTypes.hpp" -#include -#include -#include -#include - -namespace Echoion::Api { - -// YouTube-specific types for the extracted client algorithm - -struct YouTubeFormat { - std::string itag; - std::string mimeType; - std::optional url; - std::optional signatureCipher; - int32_t bitrate; - int32_t width; - int32_t height; - std::optional qualityLabel; - std::optional audioQuality; - int32_t audioSampleRate; - int32_t audioChannels; - bool hasVideo; - bool hasAudio; -}; - -struct YouTubeVideoDetails { - std::string videoId; - std::string title; - std::string author; - std::optional lengthSeconds; - std::vector formats; - std::vector adaptiveFormats; - std::optional playerJsUrl; - std::optional streamingData; -}; - -struct YouTubeSearchResult { - std::string videoId; - std::string title; - std::string channelTitle; - std::optional duration; - std::optional thumbnailUrl; - std::string publishedAt; - uint64_t viewCount; -}; - -struct YouTubePlaylistItem { - std::string videoId; - std::string title; - std::optional duration; - std::optional thumbnailUrl; -}; - -struct YouTubePlaylist { - std::string playlistId; - std::string title; - std::string author; - std::vector videos; - std::optional continuationToken; -}; - -struct YouTubePlayerConfig { - std::string innertubeApiKey; - std::string innertubeClientName; - std::string innertubeClientVersion; - std::string contextClientName; - std::string contextClientVersion; - std::string visitorData; - std::optional poToken; -}; - -struct YouTubeClientContext { - std::string hl = "en"; - std::string gl = "US"; - std::string clientName = "WEB"; - std::string clientVersion; - std::optional visitorData; - std::optional userAgent; -}; - -// Convert YouTube types to generic TrackInfo -[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeVideoDetails& details) { - TrackInfo info; - info.id = details.videoId; - info.title = details.title; - info.artist = details.author; - if (details.lengthSeconds.has_value()) { - info.duration = std::chrono::milliseconds(*details.lengthSeconds * 1000); - } - info.source = TrackSource::YouTube; - info.originalUrl = "https://youtube.com/watch?v=" + details.videoId; - return info; -} - -[[nodiscard]] inline TrackInfo ConvertToTrackInfo(const YouTubeSearchResult& result) { - TrackInfo info; - info.id = result.videoId; - info.title = result.title; - info.artist = result.channelTitle; - if (result.duration.has_value()) { - info.duration = std::chrono::milliseconds(*result.duration * 1000); - } - info.thumbnailUrl = result.thumbnailUrl; - info.source = TrackSource::YouTube; - info.originalUrl = "https://youtube.com/watch?v=" + result.videoId; - return info; -} - -[[nodiscard]] inline PlaylistInfo ConvertToPlaylistInfo(const YouTubePlaylist& playlist) { - PlaylistInfo info; - info.id = playlist.playlistId; - info.name = playlist.title; - info.owner = playlist.author; - // Convert playlist items to tracks - for (const auto& item : playlist.videos) { - TrackInfo track; - track.id = item.videoId; - track.title = item.title; - track.source = TrackSource::YouTube; - track.originalUrl = "https://youtube.com/watch?v=" + item.videoId; - if (item.duration.has_value()) { - track.duration = std::chrono::milliseconds(*item.duration * 1000); - } - track.thumbnailUrl = item.thumbnailUrl; - info.tracks.push_back(std::move(track)); - } - return info; -} - -} // namespace Echoion::Api diff --git a/include/echoion/api/audio/AudioTypes.hpp b/include/echoion/api/audio/AudioTypes.hpp new file mode 100644 index 0000000..6436ff2 --- /dev/null +++ b/include/echoion/api/audio/AudioTypes.hpp @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +namespace Echoion::Api +{ + + enum class AudioFormat : uint8_t { + Unknown = 0, + MP3, + AAC, + Opus, + Vorbis, + FLAC, + WAV + }; + + enum class AudioQuality : uint8_t { + Low = 0, // 64-96 kbps + Medium, // 128-160 kbps + High, // 192-256 kbps + VeryHigh, // 320 kbps + Lossless // FLAC or equivalent + }; + + // Hardware acceleration types + enum class HwAccelType : uint8_t { + None = 0, + CUDA, // NVIDIA CUDA + VAAPI, // Video Acceleration API (Linux) + DXVA2, // DirectX Video Acceleration 2 (Windows) + D3D11VA, // Direct3D 11 Video Acceleration + VideoToolbox, // Apple VideoToolbox + Vulkan // Vulkan Video + }; + + struct AudioFrame { + std::vector data; + std::chrono::milliseconds pts; + std::chrono::milliseconds duration; + bool isKeyFrame; + }; + + struct AudioStreamInfo { + AudioFormat format; + uint32_t sampleRate; + uint32_t channels; + uint32_t bitrate; + std::chrono::milliseconds duration; + std::optional quality; + bool hwAccelerated = false; + HwAccelType hwAccelType = HwAccelType::None; + }; + + // Zero-copy decoded audio using pooled memory (int16 for direct playback) + struct DecodedAudio { + // Use pooled buffer instead of std::vector for zero-copy + // Now using int16_t for direct TeamSpeak compatibility (no float + // conversion) + std::vector samples; + + // Non-owning view into the data + Int16AudioView view; + + uint32_t sampleRate; + uint32_t channels; + std::chrono::milliseconds timestamp; + + // Backwards compatibility - returns the samples + [[nodiscard]] std::vector getSamples() const + { + return samples; + } + + // Check if valid + [[nodiscard]] bool isValid() const { return !samples.empty(); } + + // Apply volume in-place (int16 version) + void applyVolume(float volume) + { + if (samples.empty()) { + return; + } + int32_t volInt = static_cast(volume * 32768); + for (auto& sample : samples) { + int32_t scaled = + (static_cast(sample) * volInt) / 32768; + sample = + static_cast(std::clamp(scaled, -32768, 32767)); + } + // Update view to point to new data + view = Int16AudioView(samples.data(), samples.size(), channels); + } + }; + + // Hardware acceleration configuration + struct HwAccelConfig { + HwAccelType type = HwAccelType::None; + int deviceIndex = -1; // -1 for auto-select + std::optional deviceName; + + [[nodiscard]] bool isEnabled() const + { + return type != HwAccelType::None; + } + }; + + // Audio processing options + struct AudioProcessOptions { + float volume = 1.0f; + bool normalize = false; + bool highPassFilter = false; // Remove DC offset + float highPassFreq = 20.0f; // Hz + bool limiter = false; // Prevent clipping + float limiterThreshold = 0.95f; + }; + + using AudioBuffer = std::vector; + using AudioFramePtr = std::shared_ptr; + +} // namespace Echoion::Api diff --git a/include/echoion/api/base/StateBlob.hpp b/include/echoion/api/base/StateBlob.hpp new file mode 100644 index 0000000..42d294c --- /dev/null +++ b/include/echoion/api/base/StateBlob.hpp @@ -0,0 +1,34 @@ +#pragma once +#include +#include +#include + +namespace Echoion::Api +{ + + // Opaque state blob - contents are internal to Core + // Plugin should NEVER inspect or modify the data field + struct StateBlob { + std::vector + data; // Serialized state data (JSON using glaze) + uint32_t version = 0; // Format version (for logging/debugging only) + std::string timestamp; // ISO 8601 timestamp when saved + + bool empty() const { return data.empty(); } + size_t size() const { return data.size(); } + + // Clear the state + void clear() + { + data.clear(); + version = 0; + timestamp.clear(); + } + }; + + // Constants for state management + constexpr uint32_t MAX_SUPPORTED_STATE_VERSION_AGE = + 10; // Support 10 versions back + constexpr uint32_t STATE_VERSION_NONE = 0; + +} // namespace Echoion::Api diff --git a/include/echoion/api/base/Types.hpp b/include/echoion/api/base/Types.hpp new file mode 100644 index 0000000..5577a8f --- /dev/null +++ b/include/echoion/api/base/Types.hpp @@ -0,0 +1,140 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Version constants + inline constexpr uint32_t VERSION_MAJOR = 1; + inline constexpr uint32_t VERSION_MINOR = 0; + inline constexpr uint32_t VERSION_PATCH = 0; + inline constexpr const char* VERSION_STRING = "1.0.0"; + + using namespace std::chrono_literals; + + enum class ErrorCode : uint32_t { + Success = 0, + InvalidArgument, + NotFound, + AlreadyExists, + NetworkError, + ParseError, + AudioError, + PluginError, + InvalidUrl, + NotAuthenticated, + Unauthorized, + PermissionDenied, + ServiceUnavailable, + DatabaseError, + NotSupported, + NotInitialized, + IncompatibleVersion, // State version incompatible + UnknownError + }; + + struct Error { + ErrorCode code = ErrorCode::UnknownError; + std::string message; + std::string source; + std::chrono::system_clock::time_point timestamp; + // Optional underlying cause (set via with_context), forming a chain. + std::shared_ptr cause; + + Error() = default; + Error(ErrorCode c, std::string_view msg, std::string_view src = "") + : code(c), message(msg), source(src), + timestamp(std::chrono::system_clock::now()) + { + } + + // Void::Result context API: wrap this error as the cause of a new + // contextual layer, preserving the original ErrorCode and source. + [[nodiscard]] Error with_context(std::string ctx) const& + { + Error e(code, ctx, source); + e.cause = std::make_shared(*this); + return e; + } + [[nodiscard]] Error with_context(std::string ctx) && + { + Error e(code, ctx, source); + e.cause = std::make_shared(std::move(*this)); + return e; + } + + [[nodiscard]] std::string toString() const + { + std::string out = + std::format("[{}] {} (from: {})", + static_cast(code), message, source); + for (const Error* c = cause.get(); c; c = c->cause.get()) { + out += std::format("\n caused by: {}", c->message); + } + return out; + } + }; + + // Result aliases Void::Result with Echoion's domain Error (which keeps + // the ErrorCode used across RPC and error handling). Void::Result::Result + // is itself std::expected, so existing call sites are unaffected and + // Void::Result::ok/fail/with_context all work with Api::Error. + template + using Result = Void::Result::Result; + + enum class LogLevel : uint8_t { Debug = 0, Info, Warning, Error, Critical }; + + inline constexpr std::string LogLevelToString(const LogLevel level) noexcept + { + switch (level) { + + case LogLevel::Debug: + return "Debug"; + case LogLevel::Info: + return "Info"; + case LogLevel::Warning: + return "Warning"; + case LogLevel::Error: + return "Error"; + case LogLevel::Critical: + return "Critical"; + } + } + inline constexpr LogLevel StringToLogLevel(const std::string level) noexcept + { + if (level == "Info") { + return LogLevel::Info; + } else if (level == "Warning") { + return LogLevel::Warning; + + } else if (level == "Error") { + return LogLevel::Error; + + } else if (level == "Critical") { + return LogLevel::Critical; + } + return LogLevel::Debug; + } + + struct LogEntry { + LogLevel level; + std::string message; + std::string source; + std::string sourceFile; + uint32_t sourceLine = 0; + std::string function; + std::thread::id threadId; + std::chrono::system_clock::time_point timestamp; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/config/ConfigManager.hpp b/include/echoion/api/config/ConfigManager.hpp new file mode 100644 index 0000000..010650b --- /dev/null +++ b/include/echoion/api/config/ConfigManager.hpp @@ -0,0 +1,111 @@ +#pragma once +#ifndef PLUGIN +#include "ConfigTypes.hpp" +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + class ConfigManager + { + public: + + using ConfigChangedCallback = std::function; + + // Get singleton instance + static ConfigManager& instance(); + + // Delete copy/move + ConfigManager(const ConfigManager&) = delete; + ConfigManager& operator=(const ConfigManager&) = delete; + + // Initialize with config file path (call once at startup) + [[nodiscard]] bool + initialize(const std::filesystem::path& configPath); + + // Initialize with default path (~/.config/echoion/config.json) + [[nodiscard]] bool initialize(); + + // Get current config (thread-safe) + [[nodiscard]] AppConfig getConfig() const; + + // Get config by reference (faster, but hold lock briefly) + template + auto withConfig(Func&& func) const + -> decltype(func(std::declval())) + { + std::shared_lock lock(mutex_); + return func(config_); + } + + // Direct accessors for config sections (convenience methods) + [[nodiscard]] const BotConfig& getBot() const; + [[nodiscard]] const YouTubeConfig& getYouTube() const; + [[nodiscard]] const NetworkConfig& getNetwork() const; + [[nodiscard]] const TeamSpeakConfig& getTeamSpeak() const; + [[nodiscard]] const SecurityConfig& getSecurity() const; + [[nodiscard]] const FeaturesConfig& getFeatures() const; + [[nodiscard]] const AdvancedConfig& getAdvanced() const; + + // Reload configuration from file + [[nodiscard]] bool reload(); + + // Save current configuration to file + [[nodiscard]] bool save(); + + // Update config (and optionally save) + void updateConfig(const AppConfig& config, bool saveToFile = true); + + // Check if initialized + [[nodiscard]] bool isInitialized() const; + + // Get config file path + [[nodiscard]] std::filesystem::path getConfigPath() const; + + // Get default config path (~/.config/echoion/config.json) + [[nodiscard]] static std::filesystem::path getDefaultConfigPath(); + + // Subscribe to config changes + void onConfigChanged(ConfigChangedCallback callback); + + // Create default config file if it doesn't exist + [[nodiscard]] bool createDefaultConfigIfNeeded(); + + private: + + ConfigManager() = default; + ~ConfigManager() = default; + + mutable std::shared_mutex mutex_; + AppConfig config_; + std::filesystem::path configPath_; + std::atomic initialized_{false}; + std::vector callbacks_; + mutable std::shared_mutex callbackMutex_; + + void notifyCallbacks(); + [[nodiscard]] bool loadFromFileInternal(); + [[nodiscard]] bool saveToFileInternal(); + }; + +} // namespace Echoion::Api + +// Convenience macros for accessing config +#define ECHOION_CONFIG (::Echoion::Api::ConfigManager::instance().getConfig()) +#define ECHOION_BOT (::Echoion::Api::ConfigManager::instance().getBot()) +#define ECHOION_YOUTUBE (::Echoion::Api::ConfigManager::instance().getYouTube()) +#define ECHOION_NETWORK (::Echoion::Api::ConfigManager::instance().getNetwork()) +#define ECHOION_TEAMSPEAK \ + (::Echoion::Api::ConfigManager::instance().getTeamSpeak()) +#define ECHOION_SECURITY \ + (::Echoion::Api::ConfigManager::instance().getSecurity()) +#define ECHOION_FEATURES \ + (::Echoion::Api::ConfigManager::instance().getFeatures()) +#define ECHOION_ADVANCED \ + (::Echoion::Api::ConfigManager::instance().getAdvanced()) +#endif diff --git a/include/echoion/api/config/ConfigTypes.hpp b/include/echoion/api/config/ConfigTypes.hpp new file mode 100644 index 0000000..1f9f681 --- /dev/null +++ b/include/echoion/api/config/ConfigTypes.hpp @@ -0,0 +1,165 @@ +#pragma once +#ifndef PLUGIN +#include "AudioTypes.hpp" +#include "NetworkTypes.hpp" +#include "Types.hpp" +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + using ConfigValue = std::variant>; + + struct ConfigEntry { + std::string key; + ConfigValue value; + std::string description; + bool isSecret; + std::optional defaultValue; + std::optional category; + }; + + // Core Bot Settings + struct BotConfig { + std::string botName = "Echoion"; + std::string commandPrefix = "!"; + float defaultVolume = 0.5f; + uint32_t maxQueueSize = 100; + std::chrono::milliseconds trackTimeout = + std::chrono::milliseconds(30000); + + // Reconnection settings + bool autoReconnect = true; + std::chrono::milliseconds reconnectDelay = + std::chrono::milliseconds(5000); + uint32_t maxReconnectAttempts = 5; + + // Audio quality settings + AudioQuality preferredQuality = AudioQuality::High; + bool allowPlaylistImports = true; + }; + + // YouTube Integration Settings + struct YouTubeConfig { + std::optional youtubeApiKey; + std::optional youtubeCookiesPath; + std::optional cookiesFromBrowser; + size_t ytDlpMaxConcurrent = 4; + bool ytDlpAsyncEnabled = true; + bool enableUrlShortening = true; + }; + + // Network & Proxy Settings + struct NetworkConfig { + std::optional proxy; + bool rpcEnabled = true; + uint16_t rpcPort = 8765; + std::string rpcBindAddress = "127.0.0.1"; + }; + + // TeamSpeak Server Connection + struct TeamSpeakConfig { + 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; + }; + + // Security & Authentication + struct SecurityConfig { + bool requireAuthForAdmin = true; + uint32_t maxLoginAttempts = 5; + std::chrono::milliseconds lockoutDuration = + std::chrono::milliseconds(300000); + std::chrono::milliseconds sessionTimeout = + std::chrono::milliseconds(3600000); + bool enableAuditLog = true; + std::optional apiKey; + bool allowCors = false; + std::vector corsOrigins; + }; + + // Feature Toggles + struct FeaturesConfig { + bool enableHotReload = true; + bool enableAutoReload = false; + bool enableAutoUpdateCheck = true; + + // Playback behavior + bool autoStartOnSubscribe = true; + bool pauseOnEmptySubscribers = true; + bool resumeOnSubscriberReturn = true; + + // Queue management + std::string shuffleMode = "random"; + std::string repeatMode = "off"; + uint32_t maxHistorySize = 50; + }; + + // Advanced Settings + struct AdvancedConfig { + // Audio configuration + uint32_t sampleRate = 192000; + uint32_t channels = 2; + uint32_t bufferSize = 7680; + + // Thread pool configuration + uint32_t commandThreadPoolSize = 4; + uint32_t networkThreadPoolSize = 4; + uint32_t decoderThreads = 2; + + // Cache settings + bool cacheEnabled = true; + std::string cacheMaxSize = "1GB"; + uint32_t cacheTTL = 86400; + uint32_t tempCleanupInterval = 3600; + }; + + // ServerConfig for Plugin interface (mirrors PluginTypes.hpp version) + struct ServerConfig { + std::string address; + uint16_t port = 0; + std::string serverPassword; + std::string nickname; + std::optional defaultChannelId; + std::optional channelPassword; + std::vector adminGroups; + std::vector djGroups; + std::vector bannedGroups; + }; + + struct AdminCredentials { + std::string username; + std::string passwordHash; + std::optional salt; + std::vector permissions; + std::chrono::system_clock::time_point createdAt; + std::optional lastLogin; + bool isActive; + }; + + struct AppConfig { + BotConfig bot; + YouTubeConfig youtube; + NetworkConfig network; + TeamSpeakConfig teamspeak; + SecurityConfig security; + FeaturesConfig features; + AdvancedConfig advanced; + AdminCredentials admin; + std::map custom; + }; + +} // namespace Echoion::Api +#endif diff --git a/include/echoion/api/database/Database.hpp b/include/echoion/api/database/Database.hpp new file mode 100644 index 0000000..5a19261 --- /dev/null +++ b/include/echoion/api/database/Database.hpp @@ -0,0 +1,299 @@ +#pragma once + +#include "TrackTypes.hpp" +#include "Types.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Forward declaration + class DatabaseImpl; + + // Database configuration + struct DatabaseConfig { + std::string path = "echoion.db"; + bool walMode = true; // Write-Ahead Logging for better concurrency + int maxConnections = 4; + std::chrono::seconds busyTimeout{5000}; + }; + + // Playlist with tracks + struct Playlist { + uint64_t id; + std::string name; + std::string description; + uint64_t createdBy; + std::chrono::system_clock::time_point createdAt; + std::chrono::system_clock::time_point updatedAt; + std::vector tracks; + bool isPublic = false; + std::string externalId; // YouTube playlist ID, etc. + }; + + // Playback history entry + struct PlaybackHistoryEntry { + uint64_t id; + TrackInfo track; + uint64_t playedBy; + std::chrono::system_clock::time_point playedAt; + std::chrono::milliseconds duration; // How long it played + bool completed = false; // Did it play to the end + }; + + // User favorites + struct FavoriteTrack { + TrackInfo track; + uint64_t userId; + std::chrono::system_clock::time_point addedAt; + }; + + // Statistics + struct PlaybackStatistics { + uint64_t totalPlays = 0; + uint64_t totalTracks = 0; + uint64_t totalPlaytimeMs = 0; + std::optional mostPlayedTrack; + uint64_t mostPlayedCount = 0; + }; + + // Main database interface + class Database + { + public: + + Database(); + ~Database(); + + // Non-copyable + Database(const Database&) = delete; + Database& operator=(const Database&) = delete; + + // Initialization + Api::Result initialize(const DatabaseConfig& config = {}); + void shutdown(); + [[nodiscard]] bool isInitialized() const; + + // Migrations + Api::Result migrate(); // Run pending migrations + [[nodiscard]] int getCurrentVersion() const; + + // ===== Playlists ===== + + // Create a new playlist + [[nodiscard]] Api::Result + createPlaylist(const std::string& name, + const std::string& description, + uint64_t createdBy, + bool isPublic = false, + const std::string& externalId = ""); + + // Get or create playlist by external ID (e.g., YouTube playlist ID) + // Returns existing playlist ID if found, creates new one otherwise + [[nodiscard]] Api::Result + getOrCreatePlaylistByExternalId(const std::string& externalId, + const std::string& name, + const std::string& description, + uint64_t createdBy, + bool isPublic = false); + + // Get playlist by ID + [[nodiscard]] Api::Result> + getPlaylist(uint64_t id); + + // Get all playlists for a user + [[nodiscard]] Api::Result> + getUserPlaylists(uint64_t userId); + + // Update playlist + Api::Result updatePlaylist( + uint64_t id, + const std::optional& name = std::nullopt, + const std::optional& description = std::nullopt, + const std::optional& isPublic = std::nullopt); + + // Delete playlist + Api::Result deletePlaylist(uint64_t id); + + // Add track to playlist + Api::Result addTrackToPlaylist(uint64_t playlistId, + const TrackInfo& track, + uint32_t position = 0); + + // Remove track from playlist + Api::Result removeTrackFromPlaylist(uint64_t playlistId, + uint64_t trackId); + + // Reorder playlist tracks + Api::Result reorderPlaylistTrack(uint64_t playlistId, + uint64_t trackId, + uint32_t newPosition); + + // ===== Playback History ===== + + // Record a playback + Api::Result recordPlayback(const TrackInfo& track, + uint64_t playedBy, + std::chrono::milliseconds duration, + bool completed); + + // Get playback history for a user + [[nodiscard]] Api::Result> + getPlaybackHistory(uint64_t userId, + size_t limit = 100, + size_t offset = 0); + + // Get recently played tracks + [[nodiscard]] Api::Result> + getRecentlyPlayed(uint64_t userId, size_t limit = 20); + + // ===== Favorites ===== + + // Add track to favorites + Api::Result addFavorite(uint64_t userId, + const TrackInfo& track); + + // Remove track from favorites + Api::Result removeFavorite(uint64_t userId, + const std::string& trackUrl); + + // Check if track is favorited + [[nodiscard]] Api::Result + isFavorite(uint64_t userId, const std::string& trackUrl); + + // Get all favorites for a user + [[nodiscard]] Api::Result> + getFavorites(uint64_t userId); + + // ===== Statistics ===== + + // Get playback statistics + [[nodiscard]] Api::Result getStatistics( + uint64_t userId, + std::optional since = + std::nullopt); + + // Get most played tracks + [[nodiscard]] Api::Result< + std::vector>> + getMostPlayed(uint64_t userId, size_t limit = 10); + + // ===== Subscriptions ===== + + // Subscriber info + struct SubscriberInfo { + std::string uid; + std::string nickname; + std::chrono::system_clock::time_point subscribedAt; + }; + + // Add a subscriber (by UID) + Api::Result addSubscriber(const std::string& uid, + const std::string& nickname); + + // Remove a subscriber (by UID) + Api::Result removeSubscriber(const std::string& uid); + + // Check if client is subscribed (by UID) + [[nodiscard]] Api::Result + isSubscriber(const std::string& uid); + + // Get all subscribers + [[nodiscard]] Api::Result> + getAllSubscribers(); + + // Get subscriber count + [[nodiscard]] Api::Result getSubscriberCount(); + + // Clear all subscribers + Api::Result clearAllSubscribers(); + + // ===== RPC Authentication ===== + + // RPC token info + struct RpcTokenInfo { + std::string uid; + std::string token; + std::chrono::system_clock::time_point createdAt; + std::chrono::system_clock::time_point lastUsedAt; + bool isActive = true; + }; + + // Generate new RPC token for subscriber + [[nodiscard]] Api::Result + generateRpcToken(const std::string& uid); + + // Get existing RPC token for subscriber (if any) + [[nodiscard]] Api::Result> + getExistingRpcToken(const std::string& uid); + + // Validate RPC token + [[nodiscard]] Api::Result + validateRpcToken(const std::string& token); + + // Get UID from RPC token + [[nodiscard]] Api::Result> + getUidFromRpcToken(const std::string& token); + + // Revoke RPC token + Api::Result revokeRpcToken(const std::string& token); + + // Get subscriber UID by nickname (case-insensitive) + [[nodiscard]] Api::Result> + getSubscriberByNickname(const std::string& nickname); + + // Get all subscriber UIDs + [[nodiscard]] Api::Result> + getAllSubscriberUids(); + + // ===== Cache Management ===== + + // Clear old history (keep last N entries) + Api::Result trimHistory(size_t keepCount = 10000); + + // Clear all data for a user + Api::Result clearUserData(uint64_t userId); + + // Vacuum database (reclaim space) + Api::Result vacuum(); + + // ===== Raw Query (for advanced use) ===== + + using RowCallback = std::function>&)>; + Api::Result executeQuery(const std::string& sql, + RowCallback callback = nullptr); + + private: + + std::unique_ptr impl_; + mutable std::shared_mutex + mutex_; // Shared mutex for read/write concurrency + std::atomic shutdown_{ + false}; // Flag to prevent operations after shutdown + }; + + // Database manager (singleton) + class DatabaseManager + { + public: + + static Database& instance(); + + static Api::Result + initialize(const DatabaseConfig& config = {}); + static void shutdown(); + + private: + + DatabaseManager() = default; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/eventbus/EventBus.hpp b/include/echoion/api/eventbus/EventBus.hpp new file mode 100644 index 0000000..ea04ddc --- /dev/null +++ b/include/echoion/api/eventbus/EventBus.hpp @@ -0,0 +1,292 @@ +#pragma once + +#include "ConfigTypes.hpp" +#include "PluginTypes.hpp" +#include "TrackTypes.hpp" +#include "Types.hpp" +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Event handler type + template using EventHandler = std::function; + + // Subscription handle. Wraps the underlying Void::EventBus handler id so + // existing call sites that hold a token keep compiling; pass it back to + // EventBus::unsubscribe() to detach. + class SubscriptionToken + { + public: + + using Id = Void::EventBus::EventBus::HandlerId; + + SubscriptionToken() = default; + explicit SubscriptionToken(Id id) : id_(id), valid_(true) {} + + [[nodiscard]] bool isValid() const { return valid_; } + [[nodiscard]] Id getId() const { return id_; } + + private: + + Id id_ = 0; + bool valid_ = false; + }; + + // Type-keyed publish/subscribe bus. Delegates to Void::EventBus in + // asynchronous mode: publish() snapshots handlers and dispatches them on a + // background worker, so handlers that do I/O (RPC broadcast, DB writes) + // never block the publishing thread. + class EventBus + { + public: + + EventBus() = default; + + EventBus(const EventBus&) = delete; + EventBus& operator=(const EventBus&) = delete; + EventBus(EventBus&&) = delete; + EventBus& operator=(EventBus&&) = delete; + + // The Void async worker runs from construction; kept for API + // compatibility. stop() drains any in-flight dispatch. + void start() {} + void stop() { bus_.flush(); } + + template void publish(T event) + { + bus_.publish(event); + } + + template + SubscriptionToken subscribe(EventHandler handler) + { + return SubscriptionToken{bus_.subscribe(std::move(handler))}; + } + + void unsubscribe(const SubscriptionToken& token) + { + if (token.isValid()) { + bus_.unsubscribe(token.getId()); + } + } + + // Block until every event published before this call is delivered. + void flush() { bus_.flush(); } + + private: + + Void::EventBus::EventBus bus_{Void::EventBus::Mode::Async}; + }; + + // Global event bus singleton + class GlobalEventBus + { + public: + + [[nodiscard]] static EventBus& instance(); + + private: + + GlobalEventBus() = default; + }; + + // Common event types for Echoion + namespace Events + { + + // Playback events + struct PlaybackStarted { + TrackInfo track; + uint64_t clientId; + std::chrono::milliseconds position; + }; + + struct PlaybackPaused { + TrackInfo track; + std::chrono::milliseconds position; + }; + + struct PlaybackResumed { + TrackInfo track; + std::chrono::milliseconds position; + }; + + struct PlaybackStopped { + std::optional lastTrack; + std::chrono::milliseconds finalPosition; + }; + + struct PlaybackPositionChanged { + TrackInfo track; + std::chrono::milliseconds position; + std::chrono::milliseconds duration; + float progressPercent; // 0.0 - 100.0 + }; + + struct TrackFinished { + TrackInfo track; + bool autoSkipped; + std::chrono::milliseconds finalPosition; + }; + + struct VolumeChanged { + float oldVolume; + float newVolume; + uint64_t changedByClientId; + }; + + struct ShuffleChanged { + bool enabled; + uint64_t changedByClientId; + }; + + struct RepeatChanged { + bool enabled; + uint64_t changedByClientId; + }; + + // Queue events + struct TrackQueued { + TrackInfo track; + uint64_t queueId; + uint64_t addedByClientId; + uint32_t position; + uint32_t queueLength; + }; + + struct TrackRemoved { + TrackInfo track; + uint64_t queueId; + uint64_t removedByClientId; + uint32_t queueLength; + }; + + struct QueueCleared { + uint64_t clearedByClientId; + uint32_t previousLength; + }; + + struct QueueShuffled { + uint64_t triggeredByClientId; + }; + + struct QueueReordered { + uint64_t queueId; + uint32_t oldPosition; + uint32_t newPosition; + uint64_t changedByClientId; + }; + + // Playlist events + struct PlaylistLoadStarted { + std::string playlistId; + uint64_t requestedByClientId; + uint64_t databasePlaylistId; + }; + + struct PlaylistTrackLoaded { + std::string playlistId; + TrackInfo track; + uint32_t loadedCount; + uint32_t totalCount; + uint64_t databasePlaylistId; + }; + + struct PlaylistLoadCompleted { + std::string playlistId; + uint32_t totalTracksLoaded; + bool success; + std::optional error; + }; + + // Subscription events + struct UserSubscribed { + std::string uid; + std::string nickname; + uint64_t clientId; + }; + + struct UserUnsubscribed { + std::string uid; + std::string nickname; + uint64_t clientId; + }; + + // Connection events + struct ClientConnected { + ClientInfo client; + }; + + struct ClientDisconnected { + uint64_t clientId; + std::string reason; + }; + + struct ChannelChanged { + uint64_t clientId; + uint64_t oldChannelId; + uint64_t newChannelId; + }; + + // Error events + struct PlaybackError { + ErrorCode code; + std::string message; + std::optional track; + }; + + struct NetworkError { + std::string url; + ErrorCode code; + std::string message; + }; + + // Configuration events + struct ConfigReloaded { + BotConfig newConfig; + }; + + struct ConfigChanged { + std::string key; + std::string oldValue; + std::string newValue; + }; + + // Cache events + struct CacheHit { + std::string key; + std::string type; + }; + + struct CacheMiss { + std::string key; + std::string type; + }; + + struct CacheEvicted { + std::string key; + std::string reason; + }; + + // Database persistence events (for audit/logging) + struct DatabasePersisted { + std::string + entityType; // "queue", "playback", "subscription", etc. + std::string operation; // "insert", "update", "delete" + bool success; + std::optional error; + }; + + } // namespace Events + +// Helper macros for event publishing/subscribing +#define ECHOION_PUBLISH(event) \ + Echoion::Api::GlobalEventBus::instance().publish(event) +#define ECHOION_SUBSCRIBE(type, handler) \ + Echoion::Api::GlobalEventBus::instance().subscribe(handler) + +} // namespace Echoion::Api diff --git a/include/echoion/api/interfaces/CoreInterface.hpp b/include/echoion/api/interfaces/CoreInterface.hpp new file mode 100644 index 0000000..5f02f15 --- /dev/null +++ b/include/echoion/api/interfaces/CoreInterface.hpp @@ -0,0 +1,158 @@ +#pragma once + +#include "OpaqueHandle.hpp" +#include "PluginTypes.hpp" +#include "StateBlob.hpp" +#include "Types.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Forward declarations - Core provides implementations + struct TrackInfo; + struct QueueEntry; + struct PlaylistInfo; + + // Minimal PlaybackState for Plugin + struct PlaybackSummary { + std::optional currentTrack; + bool isPlaying = false; + bool isPaused = false; + std::chrono::milliseconds position{0}; + float volume = 0.5f; + bool repeat = false; + bool shuffle = false; + }; + + // Callback types for async operations + using TrackCallback = std::function; + using StateCallback = std::function; + + // Forward declarations + class ICoreInterface; + using CoreInterfacePtr = std::shared_ptr; + using CoreCreateFunc = std::function; + using CoreDestroyFunc = std::function; + + // Core interface that the Plugin will use to communicate with the Core + // MINIMAL VERSION - breaks dependencies on Core-specific types + class ICoreInterface + { + public: + + virtual ~ICoreInterface() = default; + + // Lifecycle + // Plugin passes config file path, Core loads config internally + virtual Result + initialize(const std::filesystem::path& configPath) = 0; + virtual Result shutdown() = 0; + virtual bool isInitialized() const noexcept = 0; + + // Playback control - using string identifiers instead of TrackInfo + virtual Result play(const std::string& trackId) = 0; + virtual Result pause() = 0; + virtual Result resume() = 0; + virtual Result stop() = 0; + virtual Result skip(uint32_t count = 1) = 0; + virtual Result seek(std::chrono::milliseconds position) = 0; + virtual Result setVolume(float volume) = 0; + + // Queue management - using string identifiers + virtual Result queueTrack(const std::string& trackId, + uint64_t clientId) = 0; + virtual Result removeFromQueue(uint64_t queueId) = 0; + virtual Result clearQueue() = 0; + + // Get queue as summaries (minimal data) + [[nodiscard]] virtual Result> + getQueueSummaries() const = 0; + + virtual Result moveInQueue(uint64_t queueId, + uint32_t newPosition) = 0; + + // Track info - return summaries instead of full TrackInfo + [[nodiscard]] virtual Result> + getCurrentTrackSummary() const = 0; + [[nodiscard]] virtual Result + getPlaybackSummary() const = 0; + + // Playlist - using string identifiers + virtual Result loadPlaylist(const std::string& playlistId, + uint64_t clientId) = 0; + [[nodiscard]] virtual Result> + getPlaylistIds() const = 0; + + // Configuration - using serialization instead of AppConfig + // Plugin sends JSON string, Core parses internally + virtual Result + updateConfigJson(const std::string& configJson) = 0; + [[nodiscard]] virtual Result getConfigJson() const = 0; + + // Hot reload - using serialization instead of HotReloadState + // Returns opaque handle that Plugin just passes back + [[nodiscard]] virtual Result prepareForHotReload() = 0; + virtual Result + restoreAfterHotReload(const std::string& state) = 0; + + // Decoupled state management - Plugin never knows state internals + // Core handles all serialization/deserialization internally + // State format can change without Plugin rebuild + [[nodiscard]] virtual StateBlob saveState() = 0; + virtual Result restoreState(const StateBlob& state) = 0; + + // Version info for state compatibility checking + [[nodiscard]] virtual uint32_t getStateFormatVersion() const = 0; + [[nodiscard]] virtual bool + canRestoreStateVersion(uint32_t version) const = 0; + + // Event handling + virtual void + registerEventCallback(const EventCallback& callback) = 0; + virtual void + unregisterEventCallback(const EventCallback& callback) = 0; + + // Plugin event processing + virtual Result onPluginEvent(const PluginEvent& event) = 0; + + // Status + [[nodiscard]] virtual std::string getVersion() const = 0; + [[nodiscard]] virtual std::chrono::system_clock::time_point + getUptime() const = 0; + + // Plugin interface + virtual void + setPluginInterface(PluginInterfacePtr pluginInterface) = 0; + + // Trigger auto-connect (call after setPluginInterface) + virtual void triggerAutoConnect() = 0; + + // === Advanced methods for Core-to-Core communication (not for + // Plugin) === These are only called by Core implementations, not + // Plugin They use OpaqueHandle for type safety without exposing + // types + + // Full TrackInfo access (for internal use) + [[nodiscard]] virtual Result> + getCurrentTrackHandle() const = 0; + + // Full QueueEntry access (for internal use) + [[nodiscard]] virtual Result>> + getQueueHandles() const = 0; + + // Raw config access (for internal use) + [[nodiscard]] virtual Result + getConfigHandle() const = 0; + virtual Result + updateConfigFromHandle(AppConfigHandle config) = 0; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/interfaces/Export.hpp b/include/echoion/api/interfaces/Export.hpp new file mode 100644 index 0000000..da92ae1 --- /dev/null +++ b/include/echoion/api/interfaces/Export.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include "CoreInterface.hpp" + +// Platform-specific export macros +#ifdef _WIN32 +#ifdef ECHOION_API_EXPORT +#define ECHOION_API __declspec(dllexport) +#else +#define ECHOION_API __declspec(dllimport) +#endif +#else +#define ECHOION_API __attribute__((visibility("default"))) +#endif + +namespace Echoion::Api +{ + + // API export functions + extern "C" { + // Create a new core instance + ECHOION_API CoreInterfacePtr CreateCore(); + + // Destroy a core instance + ECHOION_API void DestroyCore(ICoreInterface* core); + + // Get API version + ECHOION_API const char* GetApiVersion(); + + // Check if API is compatible + ECHOION_API bool IsApiCompatible(uint32_t major, uint32_t minor); + } + +} // namespace Echoion::Api diff --git a/include/echoion/api/interfaces/OpaqueHandle.hpp b/include/echoion/api/interfaces/OpaqueHandle.hpp new file mode 100644 index 0000000..5206834 --- /dev/null +++ b/include/echoion/api/interfaces/OpaqueHandle.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include +#include + +namespace Echoion::Api +{ + + // Opaque handle types to avoid including full headers + // These are used in interfaces to break dependencies + + // Forward declarations for Core types (Plugin never needs full definition) + struct AppConfig; + struct HotReloadState; + struct PlaybackState; + struct TrackInfo; + struct QueueEntry; + + // Opaque handle wrapper - type-safe void pointer replacement + template class OpaqueHandle + { + public: + + OpaqueHandle() = default; + explicit OpaqueHandle(std::shared_ptr ptr) : ptr_(std::move(ptr)) + { + } + + [[nodiscard]] bool isValid() const { return ptr_ != nullptr; } + [[nodiscard]] T* get() const { return ptr_.get(); } + [[nodiscard]] T& operator*() const { return *ptr_; } + [[nodiscard]] T* operator->() const { return ptr_.get(); } + + void reset() { ptr_.reset(); } + void reset(T* ptr) { ptr_.reset(ptr); } + + [[nodiscard]] std::shared_ptr toSharedPtr() const + { + return ptr_; + } + + private: + + std::shared_ptr ptr_; + }; + + // Specific handle types + using AppConfigHandle = OpaqueHandle; + using HotReloadStateHandle = OpaqueHandle; + using PlaybackStateHandle = OpaqueHandle; + using TrackInfoHandle = OpaqueHandle; + using QueueEntryHandle = OpaqueHandle; + + // Serialization helpers for cross-boundary communication + using SerializedConfig = std::string; // JSON string + using SerializedState = std::string; // JSON string + +} // namespace Echoion::Api diff --git a/include/echoion/api/interfaces/PluginInterface.hpp b/include/echoion/api/interfaces/PluginInterface.hpp new file mode 100644 index 0000000..10533e4 --- /dev/null +++ b/include/echoion/api/interfaces/PluginInterface.hpp @@ -0,0 +1,81 @@ +#pragma once + +#include "PluginTypes.hpp" +#include "Types.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Forward declarations + class IPluginInterface; + using PluginInterfacePtr = std::shared_ptr; + + // Plugin interface that the Core will use + // MINIMAL VERSION - only depends on Types.hpp and PluginTypes.hpp + // NO dependencies on TrackTypes, ConfigTypes, RpcTypes, etc. + class IPluginInterface + { + public: + + virtual ~IPluginInterface() = default; + + // Lifecycle + virtual Result initialize() = 0; + virtual Result shutdown() = 0; + + // Client operations + [[nodiscard]] virtual Result> + getClients() = 0; + [[nodiscard]] virtual Result> + getClient(uint64_t clientId) = 0; + virtual Result moveClient(uint64_t clientId, + uint64_t channelId) = 0; + virtual Result kickClient(uint64_t clientId, + const std::string& reason) = 0; + + // Channel operations + [[nodiscard]] virtual Result> + getChannels() const = 0; + [[nodiscard]] virtual Result> + getChannel(uint64_t channelId) const = 0; + + // Messaging + virtual Result + sendTextMessage(uint64_t targetId, + const std::string& message) = 0; + virtual Result + sendChannelMessage(uint64_t channelId, + const std::string& message) = 0; + virtual Result + sendServerMessage(const std::string& message) = 0; + + // Audio + virtual Result + sendAudioData(const std::span& data) = 0; + virtual Result + setWhisperList(const std::vector& clientIds) = 0; + + // Server connection + // ServerConfig is defined in PluginTypes.hpp (self-contained) + virtual Result + connectToServer(const ServerConfig& config) = 0; + virtual Result disconnectFromServer() = 0; + [[nodiscard]] virtual bool isConnected() const = 0; + virtual Result reconnect() = 0; + + // Event subscription + virtual void + registerEventCallback(const EventCallback& callback) = 0; + virtual void + unregisterEventCallback(const EventCallback& callback) = 0; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/logger/LoggerInterface.hpp b/include/echoion/api/logger/LoggerInterface.hpp new file mode 100644 index 0000000..3ea100e --- /dev/null +++ b/include/echoion/api/logger/LoggerInterface.hpp @@ -0,0 +1,166 @@ +#pragma once + +#include "Types.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Logger interface for the user's custom logger implementation + class ILogger + { + public: + + virtual ~ILogger() = default; + + // Core logging method + virtual void log(LogLevel level, std::string_view message, + std::source_location location = + std::source_location::current()) = 0; + + // Convenience methods + virtual void debug( + std::string_view message, + std::source_location location = std::source_location::current()) + { + log(LogLevel::Debug, message, location); + } + + virtual void info( + std::string_view message, + std::source_location location = std::source_location::current()) + { + log(LogLevel::Info, message, location); + } + + virtual void warning( + std::string_view message, + std::source_location location = std::source_location::current()) + { + log(LogLevel::Warning, message, location); + } + + virtual void error( + std::string_view message, + std::source_location location = std::source_location::current()) + { + log(LogLevel::Error, message, location); + } + + virtual void critical( + std::string_view message, + std::source_location location = std::source_location::current()) + { + log(LogLevel::Critical, message, location); + } + + // Template method for formatted logging + template + void logf( + LogLevel level, std::format_string fmt, Args&&... args, + std::source_location location = std::source_location::current()) + { + log(level, std::format(fmt, std::forward(args)...), + location); + } + + // Set minimum log level + virtual void setMinLevel(LogLevel level) = 0; + [[nodiscard]] virtual LogLevel getMinLevel() const = 0; + + // Register log callback + using LogCallback = std::function; + virtual void registerCallback(const LogCallback& callback) = 0; + virtual void unregisterCallback(const LogCallback& callback) = 0; + }; + + using LoggerPtr = std::shared_ptr; + + // Global logger accessor + class LoggerRegistry + { + public: + + static LoggerRegistry& instance() + { + static LoggerRegistry instance; + return instance; + } + + void setLogger(LoggerPtr logger) { logger_ = std::move(logger); } + [[nodiscard]] LoggerPtr getLogger() const { return logger_; } + + [[nodiscard]] bool hasLogger() const noexcept + { + return static_cast(logger_); + } + + private: + + LoggerRegistry() = default; + LoggerPtr logger_; + }; + +// Convenience macros +#define ECHOION_LOG_DEBUG(msg) \ + do { \ + if (auto logger = \ + Echoion::Api::LoggerRegistry::instance().getLogger(); \ + logger) { \ + logger->debug(msg); \ + } else { \ + std::cout << "[DEBUG] Echoion: " << std::string(msg) << std::endl; \ + } \ + } while (0) + +#define ECHOION_LOG_INFO(msg) \ + do { \ + if (auto logger = \ + Echoion::Api::LoggerRegistry::instance().getLogger(); \ + logger) { \ + logger->info(msg); \ + } else { \ + std::cout << "[INFO] Echoion: " << std::string(msg) << std::endl; \ + } \ + } while (0) + +#define ECHOION_LOG_WARNING(msg) \ + do { \ + if (auto logger = \ + Echoion::Api::LoggerRegistry::instance().getLogger(); \ + logger) { \ + logger->warning(msg); \ + } else { \ + std::cout << "[WARNING] Echoion: " << std::string(msg) \ + << std::endl; \ + } \ + } while (0) + +#define ECHOION_LOG_ERROR(msg) \ + do { \ + if (auto logger = \ + Echoion::Api::LoggerRegistry::instance().getLogger(); \ + logger) { \ + logger->error(msg); \ + } else { \ + std::cerr << "[ERROR] Echoion: " << std::string(msg) << std::endl; \ + } \ + } while (0) + +#define ECHOION_LOG_CRITICAL(msg) \ + do { \ + if (auto logger = \ + Echoion::Api::LoggerRegistry::instance().getLogger(); \ + logger) { \ + logger->critical(msg); \ + } else { \ + std::cerr << "[CRITICAL] Echoion: " << std::string(msg) \ + << std::endl; \ + } \ + } while (0) + +} // namespace Echoion::Api diff --git a/include/echoion/api/network/NetworkInterface.hpp b/include/echoion/api/network/NetworkInterface.hpp new file mode 100644 index 0000000..2f8f67e --- /dev/null +++ b/include/echoion/api/network/NetworkInterface.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "NetworkTypes.hpp" +#include "Types.hpp" +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Network client interface + class INetworkClient + { + public: + + virtual ~INetworkClient() = default; + + // Initialize with optional proxy + virtual Result initialize( + const std::optional& proxy = std::nullopt) = 0; + virtual void shutdown() = 0; + + // Synchronous requests + [[nodiscard]] virtual Result + get(std::string_view url, + const std::vector& headers = {}) = 0; + [[nodiscard]] virtual Result + post(std::string_view url, std::string_view body, + const std::vector& headers = {}) = 0; + [[nodiscard]] virtual Result + request(const HttpRequest& req) = 0; + + // Asynchronous requests + [[nodiscard]] virtual std::future> + getAsync(std::string_view url, + const std::vector& headers = {}) = 0; + [[nodiscard]] virtual std::future> + postAsync(std::string_view url, std::string_view body, + const std::vector& headers = {}) = 0; + [[nodiscard]] virtual std::future> + requestAsync(const HttpRequest& req) = 0; + + // Proxy configuration + virtual void setProxy(const std::optional& proxy) = 0; + [[nodiscard]] virtual std::optional + getProxy() const = 0; + virtual void clearProxy() = 0; + + // Retry configuration + virtual void setRetryConfig(const RetryConfig& config) = 0; + [[nodiscard]] virtual RetryConfig getRetryConfig() const = 0; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/network/NetworkTypes.hpp b/include/echoion/api/network/NetworkTypes.hpp new file mode 100644 index 0000000..1336a69 --- /dev/null +++ b/include/echoion/api/network/NetworkTypes.hpp @@ -0,0 +1,167 @@ +#pragma once + +#include "Types.hpp" +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + enum class HttpMethod : uint8_t { + GET = 0, + POST, + PUT, + DELETE, + PATCH, + HEAD, + OPTIONS + }; + + enum class ProxyType : uint8_t { HTTP = 0, SOCKS5 }; + + struct ProxyConfig { + ProxyType type = ProxyType::HTTP; + std::string host; + uint16_t port; + std::optional username; + std::optional password; + std::optional timeout; + + [[nodiscard]] bool isValid() const noexcept + { + return !host.empty() && port > 0; + } + + [[nodiscard]] bool requiresAuth() const noexcept + { + return username.has_value() && password.has_value(); + } + + [[nodiscard]] bool isSocks5() const noexcept + { + return type == ProxyType::SOCKS5; + } + + [[nodiscard]] bool + operator==(const ProxyConfig& other) const = default; + [[nodiscard]] bool + operator!=(const ProxyConfig& other) const = default; + }; + + struct HttpHeader { + std::string name; + std::string value; + }; + + struct HttpRequest { + std::string url; + HttpMethod method = HttpMethod::GET; + std::vector headers; + std::optional> body; + std::optional proxy; + std::chrono::milliseconds timeout = 30000ms; + bool followRedirects = true; + uint32_t maxRedirects = 10; + }; + + struct HttpResponse { + int32_t statusCode; + // Using vector to support multiple headers with same name (e.g., + // Set-Cookie) + std::vector> headers; + std::string body; + std::chrono::milliseconds responseTime; + std::optional contentType; + bool fromCache = false; + + [[nodiscard]] bool isSuccess() const noexcept + { + return statusCode >= 200 && statusCode < 300; + } + + [[nodiscard]] bool isRedirect() const noexcept + { + return statusCode >= 300 && statusCode < 400; + } + + [[nodiscard]] bool isError() const noexcept + { + return statusCode >= 400 || statusCode == 0; + } + + [[nodiscard]] std::string bodyAsString() const + { + return std::string(body.begin(), body.end()); + } + + // Helper to get first header value by name (case-insensitive) + [[nodiscard]] std::optional + getHeader(std::string_view name) const + { + for (const auto& [key, value] : headers) { + if (key.size() == name.size()) { + bool match = true; + for (size_t i = 0; i < key.size(); ++i) { + if (std::tolower( + static_cast(key[i])) != + std::tolower( + static_cast(name[i]))) { + match = false; + break; + } + } + if (match) { + return value; + } + } + } + return std::nullopt; + } + + // Helper to get all header values by name (case-insensitive) - + // useful for Set-Cookie + [[nodiscard]] std::vector + getHeaders(std::string_view name) const + { + std::vector result; + for (const auto& [key, value] : headers) { + if (key.size() == name.size()) { + bool match = true; + for (size_t i = 0; i < key.size(); ++i) { + if (std::tolower( + static_cast(key[i])) != + std::tolower( + static_cast(name[i]))) { + match = false; + break; + } + } + if (match) { + result.push_back(value); + } + } + } + return result; + } + }; + + struct RateLimitInfo { + uint32_t limit; + uint32_t remaining; + std::optional resetTime; + }; + + struct RetryConfig { + uint32_t maxRetries = 3; + std::chrono::milliseconds initialDelay = 1000ms; + std::chrono::milliseconds maxDelay = 30000ms; + float backoffMultiplier = 2.0f; + std::vector retryableStatusCodes = {408, 429, 500, + 502, 503, 504}; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/plugin/PluginTypes.hpp b/include/echoion/api/plugin/PluginTypes.hpp new file mode 100644 index 0000000..46d25f3 --- /dev/null +++ b/include/echoion/api/plugin/PluginTypes.hpp @@ -0,0 +1,129 @@ +#pragma once +#ifndef PLUGIN +#include +#endif +#include +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // ===== Plugin Event Types ===== + + enum class PluginEventType : uint8_t { + ClientConnected = 0, + ClientDisconnected, + ClientMoved, + TextMessageReceived, + VoiceDataReceived, + PlayRequested, + PauseRequested, + SkipRequested, + StopRequested, + TrackQueued, + TrackRemoved, + QueueCleared, + QueueUpdated, + PlaybackStarted, + PlaybackPaused, + PlaybackResumed, + PlaybackStopped, + TrackFinished, + TrackSkipped, + VolumeChanged, + SeekPosition, + HotReloadRequested, + HotReloadCompleted, + ConfigurationChanged + }; + + // Minimal track info for Plugin (no internal types) + struct TrackSummary { + std::string id; + std::string title; + std::string artist; + std::optional duration; + }; + + struct PluginEvent { + PluginEventType type; + std::optional clientName; + std::optional + trackSummary; // Opaque summary instead of full TrackInfo + uint64_t clientId = 0; + std::optional targetChannelId; + std::optional message; + std::optional volume; + std::optional queuePosition; + std::chrono::system_clock::time_point timestamp; + }; + + // ===== Connection Types ===== + + struct ClientInfo { + uint64_t id = 0; + std::string nickname; + std::optional uniqueIdentifier; + uint64_t channelId = 0; + bool isTalking = false; + bool isMuted = false; + bool isDeafened = false; + std::vector serverGroups; + }; + + struct ChannelInfo { + uint64_t id = 0; + std::string name; + std::optional parentId; + uint64_t order = 0; + bool isDefault = false; + bool hasPassword = false; + uint32_t maxClients = 0; + uint32_t currentClients = 0; + }; + + struct ServerInfo { + uint64_t id = 0; + std::string name; + std::string welcomeMessage; + uint32_t maxClients = 0; + uint32_t currentClients = 0; + uint64_t defaultChannelId = 0; + }; + +// ServerConfig is needed for Plugin's connectToServer() +// This is a minimal version without dependencies on AudioTypes, etc. +// Available to both Core and Plugin +#ifdef PLUGIN + struct ServerConfig { + std::string address; + uint16_t port = 0; + std::string serverPassword; + std::string nickname; + std::optional defaultChannelId; + std::optional channelPassword; + std::vector adminGroups; + std::vector djGroups; + std::vector bannedGroups; + }; +#endif + // ===== Callback Types ===== + + using EventCallback = std::function; + using CommandHandler = std::function& args)>; + + struct CommandInfo { + std::string name; + std::string description; + std::vector aliases; + std::optional usage; + bool requiresAdmin = false; + CommandHandler handler; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/rpc/RpcTypes.hpp b/include/echoion/api/rpc/RpcTypes.hpp new file mode 100644 index 0000000..1952ba5 --- /dev/null +++ b/include/echoion/api/rpc/RpcTypes.hpp @@ -0,0 +1,112 @@ +#pragma once + +#include "ConfigTypes.hpp" +#include "TrackTypes.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + enum class RpcMethod : uint8_t { + // Playback control + Play = 0, + Pause, + Resume, + Stop, + Skip, + Seek, + SetVolume, + + // Queue management + QueueTrack, + RemoveFromQueue, + ClearQueue, + GetQueue, + MoveInQueue, + + // Track info + GetCurrentTrack, + GetTrackInfo, + SearchTracks, + + // Playlist + LoadPlaylist, + SavePlaylist, + GetPlaylists, + DeletePlaylist, + + // Configuration + GetConfig, + SetConfig, + ReloadConfig, + + // Plugin/Core management + GetStatus, + HotReload, + Shutdown, + + // Admin + Authenticate, + Logout, + GetAuditLog, + ManageUsers, + + // Server info + GetServerInfo, + RequestLoginToken, + ValidateLoginToken + }; + + struct RpcRequest { + uint64_t id; + RpcMethod method; + std::optional params; + std::optional authToken; + std::chrono::system_clock::time_point timestamp; + }; + + struct RpcResponse { + uint64_t requestId; + bool success; + std::optional result; + std::optional + error; // JSON string: {"code":N,"message":"...","source":"..."} + std::chrono::system_clock::time_point timestamp; + }; + + struct RpcNotification { + std::string event; + std::optional data; + std::chrono::system_clock::time_point timestamp; + }; + + using RpcHandler = std::function; + + struct RpcEndpoint { + RpcMethod method; + std::string name; + std::string description; + bool requiresAuth; + RpcHandler handler; + }; + + // Hot reload state preservation + struct HotReloadState { + PlaybackState playback; + std::vector queue; + std::optional currentStreamUrl; + std::chrono::milliseconds playbackPosition; + BotConfig config; + std::map sessionData; + + [[nodiscard]] bool shouldPreservePlayback() const noexcept + { + return playback.isPlaying && playback.currentTrack.has_value(); + } + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/track/TrackTypes.hpp b/include/echoion/api/track/TrackTypes.hpp new file mode 100644 index 0000000..112260a --- /dev/null +++ b/include/echoion/api/track/TrackTypes.hpp @@ -0,0 +1,196 @@ +#pragma once + +#include "AudioTypes.hpp" +#include "Types.hpp" +#include // Void::Json::Value + ReflectError +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + enum class TrackSource : uint8_t { + Unknown = 0, + YouTube, + SoundCloud, + Spotify, + LocalFile, + URL + }; + + struct TrackInfo { + std::string id; + std::string title; + std::string artist; + std::string album; + std::optional thumbnailUrl; + std::optional duration; + TrackSource source; + std::string originalUrl; + std::optional + shortenedUrl; // faumaray.ru shortened link + std::optional streamUrl; + std::optional audioInfo; + std::chrono::system_clock::time_point addedAt; + std::string requestedBy; + + // Format track as markdown link: [Title](shortenedUrl) + // Only uses shortened URL (faumaray), returns empty string if not + // available + [[nodiscard]] std::string formatWithLink() const + { + if (shortenedUrl.has_value() && !shortenedUrl->empty()) { + return std::format("[{}]({})", title, *shortenedUrl); + } + return std::format("[{}]", + title); // No link if no shortened URL + } + + // Format track with artist and link + // Only uses shortened URL (faumaray), returns text only if not + // available + [[nodiscard]] std::string formatWithArtistAndLink() const + { + std::string displayTitle = title; + if (!artist.empty()) { + displayTitle = std::format("{} by {}", title, artist); + } + if (shortenedUrl.has_value() && !shortenedUrl->empty()) { + return std::format("[{}]({})", displayTitle, *shortenedUrl); + } + return displayTitle; // No link if no shortened URL + } + + // ── Void::Json customization ────────────────────────────────── + // TrackInfo holds chrono and an optional nested AudioStreamInfo, + // neither of which Void::Json reflection covers, so it provides an + // explicit serializer. chrono is stored as integer milliseconds and + // the enum as its underlying value (stable round-trips). The + // transient audioInfo (re-derived on playback) is intentionally not + // persisted. + [[nodiscard]] Void::Json::Value to_json() const + { + using Void::Json::Value; + Value out = Void::Json::object(); + auto& o = out.as_object(); + o.emplace_back("id", Value{id}); + o.emplace_back("title", Value{title}); + o.emplace_back("artist", Value{artist}); + o.emplace_back("album", Value{album}); + o.emplace_back("thumbnailUrl", thumbnailUrl + ? Value{*thumbnailUrl} + : Value{nullptr}); + o.emplace_back( + "durationMs", + duration ? Value{static_cast(duration->count())} + : Value{nullptr}); + o.emplace_back("source", + Value{static_cast( + static_cast(source))}); + o.emplace_back("originalUrl", Value{originalUrl}); + o.emplace_back("shortenedUrl", shortenedUrl ? Value{*shortenedUrl} + : Value{nullptr}); + o.emplace_back("streamUrl", + streamUrl ? Value{*streamUrl} : Value{nullptr}); + o.emplace_back( + "addedAtMs", + Value{static_cast( + std::chrono::duration_cast( + addedAt.time_since_epoch()) + .count())}); + o.emplace_back("requestedBy", Value{requestedBy}); + return out; + } + + [[nodiscard]] static std::expected + from_json(const Void::Json::Value& j) + { + TrackInfo t; + const auto str = [&](const char* k) -> std::string { + const auto* v = j.find(k); + return (v && v->is_string()) ? v->as_string() + : std::string{}; + }; + const auto optStr = + [&](const char* k) -> std::optional { + const auto* v = j.find(k); + if (v && v->is_string()) { + return v->as_string(); + } + return std::nullopt; + }; + t.id = str("id"); + t.title = str("title"); + t.artist = str("artist"); + t.album = str("album"); + t.thumbnailUrl = optStr("thumbnailUrl"); + if (const auto* d = j.find("durationMs"); + d && d->is_number()) { + t.duration = std::chrono::milliseconds( + static_cast(d->as_number())); + } + if (const auto* s = j.find("source"); s && s->is_number()) { + t.source = static_cast( + static_cast(s->as_number())); + } else { + t.source = TrackSource::Unknown; + } + t.originalUrl = str("originalUrl"); + t.shortenedUrl = optStr("shortenedUrl"); + t.streamUrl = optStr("streamUrl"); + if (const auto* a = j.find("addedAtMs"); + a && a->is_number()) { + t.addedAt = std::chrono::system_clock::time_point( + std::chrono::milliseconds( + static_cast(a->as_number()))); + } + t.requestedBy = str("requestedBy"); + return t; + } + }; + + struct PlaylistInfo { + std::string id; + std::string name; + std::string description; + std::optional thumbnailUrl; + std::string owner; + std::vector tracks; + std::chrono::system_clock::time_point createdAt; + std::chrono::system_clock::time_point updatedAt; + }; + + struct QueueEntry { + uint64_t queueId; + TrackInfo track; + std::chrono::system_clock::time_point addedAt; + std::string addedBy; + bool isPlaying; + std::optional position; + }; + + struct PlaybackState { + std::optional currentTrack; + std::vector queue; + bool isPlaying; + bool isPaused; + std::chrono::milliseconds position; + std::chrono::milliseconds buffered; + float volume; + bool repeat; + bool shuffle; + std::chrono::system_clock::time_point lastUpdate; + }; + + struct SearchResult { + std::vector tracks; + std::vector playlists; + std::string query; + std::optional nextPageToken; + uint32_t totalResults; + }; + +} // namespace Echoion::Api diff --git a/include/echoion/api/utils/MemoryPool.hpp b/include/echoion/api/utils/MemoryPool.hpp new file mode 100644 index 0000000..c50cc55 --- /dev/null +++ b/include/echoion/api/utils/MemoryPool.hpp @@ -0,0 +1,147 @@ +#pragma once + +#include "Types.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // Reusable int16 audio sample buffer, recycled by the pool on drop. + using AudioSampleBuffer = Void::BufferPool::BufferPool::Buffer; + + // Specialized audio buffer pool for int16 (direct TeamSpeak compatibility). + // Backed by Void::BufferPool, which pools by power-of-two size class and + // reuses storage across acquisitions (grow-on-demand, no fixed capacity). + class AudioBufferPool + { + public: + + static constexpr size_t DEFAULT_BUFFER_SIZE = + 1920; // 48000Hz * 2ch * 20ms + static constexpr size_t DEFAULT_POOL_SIZE = + 256; // pre-warm hint (buffers) + + static AudioBufferPool& instance(); + + void initialize(size_t bufferSize = DEFAULT_BUFFER_SIZE, + size_t poolSize = DEFAULT_POOL_SIZE); + void shutdown(); + + // Borrow an int16 buffer of the configured size. An empty Buffer is + // returned if the pool has not been initialized. + [[nodiscard]] AudioSampleBuffer acquireBuffer(); + + // Get buffer size + [[nodiscard]] size_t getBufferSize() const { return bufferSize_; } + + // Get stats + [[nodiscard]] size_t getAvailableBuffers() const; + [[nodiscard]] size_t getTotalBuffers() const; + + private: + + AudioBufferPool() = default; + + std::unique_ptr> pool_; + size_t bufferSize_ = DEFAULT_BUFFER_SIZE; + }; + + // Zero-copy audio buffer view + template class AudioBufferView + { + public: + + AudioBufferView() = default; + + AudioBufferView(T* data, size_t size, size_t channels = 2) + : data_(data), size_(size), channels_(channels) + { + } + + [[nodiscard]] T* data() { return data_; } + [[nodiscard]] const T* data() const { return data_; } + [[nodiscard]] size_t size() const { return size_; } + [[nodiscard]] size_t channels() const { return channels_; } + [[nodiscard]] size_t samplesPerChannel() const + { + return size_ / channels_; + } + + [[nodiscard]] T* channel(size_t ch) { return data_ + ch; } + + [[nodiscard]] T& sample(size_t frame, size_t ch) + { + return data_[frame * channels_ + ch]; + } + + [[nodiscard]] const T& sample(size_t frame, size_t ch) const + { + return data_[frame * channels_ + ch]; + } + + // Span for single channel + [[nodiscard]] std::span getChannelSpan(size_t ch) + { + return std::span(data_ + ch, size_, channels_); + } + + // Span for all data + [[nodiscard]] std::span getSpan() + { + return std::span(data_, size_); + } + + [[nodiscard]] bool empty() const + { + return data_ == nullptr || size_ == 0; + } + + void clear() + { + if (data_) { + std::memset(data_, 0, size_ * sizeof(T)); + } + } + + // Apply gain in-place + void applyGain(float gain) + { + if (!data_) { + return; + } + for (size_t i = 0; i < size_; ++i) { + data_[i] *= gain; + } + } + + // Mix another buffer into this one + void mix(const AudioBufferView& other, float gain = 1.0f) + { + if (!data_ || !other.data_) { + return; + } + size_t mixSize = std::min(size_, other.size_); + for (size_t i = 0; i < mixSize; ++i) { + data_[i] += other.data_[i] * gain; + } + } + + private: + + T* data_ = nullptr; + size_t size_ = 0; + size_t channels_ = 2; + }; + + // Audio buffer view types - using int16 (short) for direct TeamSpeak + // compatibility + using Int16AudioView = AudioBufferView; + + // Deprecated: Float audio view is no longer used, all audio is int16 + using FloatAudioView = AudioBufferView; + +} // namespace Echoion::Api diff --git a/include/echoion/api/youtube/YouTubeTypes.hpp b/include/echoion/api/youtube/YouTubeTypes.hpp new file mode 100644 index 0000000..ea26004 --- /dev/null +++ b/include/echoion/api/youtube/YouTubeTypes.hpp @@ -0,0 +1,143 @@ +#pragma once + +#include "TrackTypes.hpp" +#include "Types.hpp" +#include +#include +#include +#include + +namespace Echoion::Api +{ + + // YouTube-specific types for the extracted client algorithm + + struct YouTubeFormat { + std::string itag; + std::string mimeType; + std::optional url; + std::optional signatureCipher; + int32_t bitrate; + int32_t width; + int32_t height; + std::optional qualityLabel; + std::optional audioQuality; + int32_t audioSampleRate; + int32_t audioChannels; + bool hasVideo; + bool hasAudio; + }; + + struct YouTubeVideoDetails { + std::string videoId; + std::string title; + std::string author; + std::optional lengthSeconds; + std::vector formats; + std::vector adaptiveFormats; + std::optional playerJsUrl; + std::optional streamingData; + }; + + struct YouTubeSearchResult { + std::string videoId; + std::string title; + std::string channelTitle; + std::optional duration; + std::optional thumbnailUrl; + std::string publishedAt; + uint64_t viewCount; + }; + + struct YouTubePlaylistItem { + std::string videoId; + std::string title; + std::optional duration; + std::optional thumbnailUrl; + }; + + struct YouTubePlaylist { + std::string playlistId; + std::string title; + std::string author; + std::vector videos; + std::optional continuationToken; + }; + + struct YouTubePlayerConfig { + std::string innertubeApiKey; + std::string innertubeClientName; + std::string innertubeClientVersion; + std::string contextClientName; + std::string contextClientVersion; + std::string visitorData; + std::optional poToken; + }; + + struct YouTubeClientContext { + std::string hl = "en"; + std::string gl = "US"; + std::string clientName = "WEB"; + std::string clientVersion; + std::optional visitorData; + std::optional userAgent; + }; + + // Convert YouTube types to generic TrackInfo + [[nodiscard]] inline TrackInfo + ConvertToTrackInfo(const YouTubeVideoDetails& details) + { + TrackInfo info; + info.id = details.videoId; + info.title = details.title; + info.artist = details.author; + if (details.lengthSeconds.has_value()) { + info.duration = + std::chrono::milliseconds(*details.lengthSeconds * 1000); + } + info.source = TrackSource::YouTube; + info.originalUrl = "https://youtube.com/watch?v=" + details.videoId; + return info; + } + + [[nodiscard]] inline TrackInfo + ConvertToTrackInfo(const YouTubeSearchResult& result) + { + TrackInfo info; + info.id = result.videoId; + info.title = result.title; + info.artist = result.channelTitle; + if (result.duration.has_value()) { + info.duration = std::chrono::milliseconds(*result.duration * 1000); + } + info.thumbnailUrl = result.thumbnailUrl; + info.source = TrackSource::YouTube; + info.originalUrl = "https://youtube.com/watch?v=" + result.videoId; + return info; + } + + [[nodiscard]] inline PlaylistInfo + ConvertToPlaylistInfo(const YouTubePlaylist& playlist) + { + PlaylistInfo info; + info.id = playlist.playlistId; + info.name = playlist.title; + info.owner = playlist.author; + // Convert playlist items to tracks + for (const auto& item : playlist.videos) { + TrackInfo track; + track.id = item.videoId; + track.title = item.title; + track.source = TrackSource::YouTube; + track.originalUrl = "https://youtube.com/watch?v=" + item.videoId; + if (item.duration.has_value()) { + track.duration = + std::chrono::milliseconds(*item.duration * 1000); + } + track.thumbnailUrl = item.thumbnailUrl; + info.tracks.push_back(std::move(track)); + } + return info; + } + +} // namespace Echoion::Api