From 30884ad0b56a793474cb2a52eaea9b443b7894bb Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 24 Jun 2026 00:26:26 +0300 Subject: [PATCH] Decompose Core: split RPC/event setup into files + dedupe init guards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move Core::setupRpcHandlers (→ CoreRpcHandlers.cpp) and Core::setupEventBusSubscriptions (→ CoreEventRelay.cpp) out of the 2100-line Core.cpp (now ~1535). They stay Core member functions — definitions live in dedicated translation units — which gives the file-decomposition without a risky 500-line this→core rewrite into separate classes. The RpcAuthRequest struct moves to RpcDtos.hpp as Dto::AuthRequest; the toJson helper also moves there so both units share it. Add Core::requireInitialized() and collapse the 28 identical `if (!initialized_) return fail(ServiceUnavailable,…)` guards into `if (auto r = requireInitialized(); !r) return std::unexpected(r.error());`. Build green. Co-Authored-By: Claude Opus 4.8 --- include/echoion/core/Core.hpp | 3 + include/echoion/core/RpcDtos.hpp | 18 + src/Core.cpp | 650 ++++--------------------------- src/CoreEventRelay.cpp | 240 ++++++++++++ src/CoreRpcHandlers.cpp | 278 +++++++++++++ 5 files changed, 604 insertions(+), 585 deletions(-) create mode 100644 src/CoreEventRelay.cpp create mode 100644 src/CoreRpcHandlers.cpp diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index 3989e26..b271a3f 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -162,6 +162,9 @@ namespace Echoion::Core // the global Void::Log sink (logSink_ must outlive logging). void installLogging(); + // Guard helper: ok if initialized, else a ServiceUnavailable error. + [[nodiscard]] Api::Result requireInitialized() const noexcept; + // Components std::shared_ptr networkClient_; std::shared_ptr musicManager_; diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp index a08b114..2b7ee53 100644 --- a/include/echoion/core/RpcDtos.hpp +++ b/include/echoion/core/RpcDtos.hpp @@ -1,17 +1,35 @@ #pragma once #include +#include +#include #include #include #include #include +namespace Echoion::Core +{ + // Serialize any reflectable DTO to a JSON string (correct escaping). + template [[nodiscard]] std::string toJson(const T& dto) + { + return Void::Json::serialize(Void::Json::to_json(dto)); + } +} // namespace Echoion::Core + // Reflectable DTOs for the RPC responses and event-broadcast payloads. These // are serialized with Void::Json (reflection) instead of hand-built strings, // so member names are the JSON keys and values are always correctly escaped. namespace Echoion::Core::Dto { + // ── RPC request payloads (parsed) ─────────────────────────────────────── + + struct AuthRequest { + std::optional nickname; + std::optional token; + }; + // ── RPC handler responses ─────────────────────────────────────────────── struct Track { diff --git a/src/Core.cpp b/src/Core.cpp index fa21074..355465e 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -26,13 +26,6 @@ namespace Echoion::Core { namespace { - // Serialize any reflectable DTO to a JSON string (correct escaping). - template - [[nodiscard]] std::string toJson(const T& dto) - { - return Void::Json::serialize(Void::Json::to_json(dto)); - } - // Build the console + split-file logging stack and install it as the // process-wide Void::Log sink. Replaces the old ILogger/LoggerRegistry // indirection; every ECHOION_LOG_* macro is now a Void::Log:: call. @@ -83,6 +76,15 @@ namespace Echoion::Core Void::Log::set_min_level(Void::Log::Level::Debug); } + Api::Result Core::requireInitialized() const noexcept + { + if (!initialized_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Core not initialized"); + } + return {}; + } + Core::~Core() { if (initialized_) { @@ -457,9 +459,8 @@ namespace Echoion::Core Api::Result Core::playTrack(const Api::TrackInfo& track) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->queueTrack(track, 0); @@ -490,9 +491,8 @@ namespace Echoion::Core Api::Result Core::play(const std::string& trackId) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } // Resolve track ID to TrackInfo via MusicManager @@ -506,9 +506,8 @@ namespace Echoion::Core Api::Result Core::pause() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->pause(); @@ -523,9 +522,8 @@ namespace Echoion::Core Api::Result Core::resume() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->resume(); @@ -540,9 +538,8 @@ namespace Echoion::Core Api::Result Core::stop() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->stop(); @@ -557,9 +554,8 @@ namespace Echoion::Core Api::Result Core::skip(uint32_t count) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->skip(count); @@ -574,9 +570,8 @@ namespace Echoion::Core Api::Result Core::seek(std::chrono::milliseconds position) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } return musicManager_->seek(position); @@ -584,9 +579,8 @@ namespace Echoion::Core Api::Result Core::setVolume(float volume) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } return musicManager_->setVolume(volume); @@ -595,9 +589,8 @@ namespace Echoion::Core Api::Result Core::queueTrackFull(const Api::TrackInfo& track, uint64_t clientId) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->queueTrack(track, clientId); @@ -617,9 +610,8 @@ namespace Echoion::Core Api::Result Core::queueTrack(const std::string& trackId, uint64_t clientId) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } // Use MusicManager::play to resolve trackId and get TrackInfo @@ -637,9 +629,8 @@ namespace Echoion::Core Api::Result Core::removeFromQueue(uint64_t queueId) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } // Find position by queueId @@ -659,9 +650,8 @@ namespace Echoion::Core Api::Result Core::clearQueue() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->clearQueue(); @@ -676,9 +666,8 @@ namespace Echoion::Core Api::Result> Core::getQueue() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } return musicManager_->getQueue(); @@ -686,9 +675,8 @@ namespace Echoion::Core Api::Result Core::moveInQueue(uint64_t queueId, uint32_t newPosition) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } // Find current position @@ -717,9 +705,8 @@ namespace Echoion::Core Api::Result> Core::getCurrentTrack() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } return musicManager_->getCurrentTrack(); @@ -728,9 +715,8 @@ namespace Echoion::Core Api::Result> Core::getCurrentTrackSummary() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto current = musicManager_->getCurrentTrack(); @@ -751,9 +737,8 @@ namespace Echoion::Core Api::Result Core::getPlaybackState() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } return musicManager_->getPlaybackState(); @@ -761,9 +746,8 @@ namespace Echoion::Core Api::Result Core::getPlaybackSummary() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto state = musicManager_->getPlaybackState(); @@ -793,9 +777,8 @@ namespace Echoion::Core Api::Result Core::loadPlaylist(const std::string& playlistId, uint64_t clientId) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto result = musicManager_->loadPlaylist(playlistId, clientId); @@ -807,9 +790,8 @@ namespace Echoion::Core Api::Result> Core::getPlaylists() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } return musicManager_->getPlaylists(); @@ -817,9 +799,8 @@ namespace Echoion::Core Api::Result> Core::getPlaylistIds() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto playlists = musicManager_->getPlaylists(); @@ -895,9 +876,8 @@ namespace Echoion::Core Api::Result Core::reloadConfig() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } if (configPath_.empty()) { @@ -926,9 +906,8 @@ namespace Echoion::Core Api::Result Core::prepareForHotReloadFull() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } Void::Log::info("Core", "{}", "Preparing for hot reload..."); @@ -944,9 +923,8 @@ namespace Echoion::Core Api::Result Core::restoreAfterHotReloadFull(const Api::HotReloadState& state) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } Void::Log::info("Core", "{}", "Restoring after hot reload..."); @@ -967,9 +945,8 @@ namespace Echoion::Core Api::Result Core::prepareForHotReload() { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } Void::Log::info("Core", "{}", "Preparing for hot reload (decoupled)..."); @@ -987,9 +964,8 @@ namespace Echoion::Core Api::Result Core::restoreAfterHotReload(const std::string& state) { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } Void::Log::info("Core", "{}", "Restoring after hot reload (decoupled)..."); @@ -1142,9 +1118,8 @@ namespace Echoion::Core Api::Result> Core::getCurrentTrackHandle() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto current = musicManager_->getCurrentTrack(); @@ -1165,9 +1140,8 @@ namespace Echoion::Core Api::Result>> Core::getQueueHandles() const { - if (!initialized_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + if (auto r = requireInitialized(); !r) { + return std::unexpected(r.error()); } auto queue = musicManager_->getQueue(); @@ -1508,500 +1482,6 @@ namespace Echoion::Core } } - // Auth request structure for RPC authentication - struct RpcAuthRequest { - std::optional nickname; - std::optional token; - }; - - void Core::setupRpcHandlers() - { - if (!rpcServer_) { - return; - } - - // Authentication - expects JSON with either "nickname" (for initial - // request) or "token" (for validation) - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::Authenticate)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - // Parse JSON params - auto parsedParams = Void::Json::parse(params); - if (!parsedParams) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid authentication request format"); - } - auto reqResult = - Void::Json::from_json(*parsedParams); - if (!reqResult) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid authentication request format"); - } - const RpcAuthRequest& req = *reqResult; - - // If token provided, validate it - if (req.token.has_value()) { - auto validResult = database_->validateRpcToken(*req.token); - if (!validResult) { - return std::unexpected(validResult.error()); - } - if (*validResult) { - rpcServer_->addAuthenticatedClient(clientId); - return toJson(Dto::SuccessMessage{ - .message = "Authentication successful"}); - } else { - return Api::fail( - Api::ErrorCode::PermissionDenied, "Invalid token"); - } - } - - // If nickname provided, search for subscriber and send token - // via PM - if (req.nickname.has_value()) { - auto uidResult = - database_->getSubscriberByNickname(*req.nickname); - if (!uidResult) { - return std::unexpected(uidResult.error()); - } - - if (!uidResult->has_value()) { - return Api::fail( - Api::ErrorCode::NotFound, - "Subscriber not found. Please subscribe to the bot " - "first using !subscribe command."); - } - - const std::string& uid = **uidResult; - - // Get or create token - auto tokenResult = database_->getExistingRpcToken(uid); - if (!tokenResult) { - return std::unexpected(tokenResult.error()); - } - - std::string token; - if (tokenResult->has_value()) { - token = **tokenResult; - } else { - // Generate new token - auto genResult = database_->generateRpcToken(uid); - if (!genResult) { - return std::unexpected(genResult.error()); - } - token = *genResult; - } - - // Get client ID from UID to send PM - if (pluginInterface_) { - // Get all clients and find the one with matching UID - auto clientsResult = pluginInterface_->getClients(); - if (clientsResult) { - for (const auto& client : *clientsResult) { - if (client.uniqueIdentifier == uid) { - uint64_t tsClientId = client.id; - - // Send PM with token using plain text - // format (compatible with both TS3 BBCode - // and TS6 Markdown) - std::string pmMessage = std::format( - "**Echoion RPC Authentication**\n\n" - "Your authentication token:\n" - "```\n{}\n```\n\n" - "Use this token to authenticate with " - "the RPC server.\n" - "Keep this token secure and do not " - "share it with others.", - token); - - auto pmResult = - pluginInterface_->sendTextMessage( - tsClientId, pmMessage); - - if (!pmResult) { - Void::Log::warn("Core", "{}", std::format( - "Failed to send PM with token: {}", - pmResult.error().message)); - } - break; - } - } - } - } - - return toJson(Dto::SuccessMessage{ - .message = "Token sent via TeamSpeak PM. Please check " - "your private messages."}); - } - - return Api::fail(Api::ErrorCode::InvalidArgument, - "Authentication request must include either " - "'nickname' or 'token'"); - }); - - // Playback control - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::Play)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - // Parse query from params (simple implementation) - std::string query = params; - // Remove quotes if present - if (query.size() >= 2 && query.front() == '"' && - query.back() == '"') { - query = query.substr(1, query.size() - 2); - } - auto result = musicManager_->play(query, clientId); - if (!result) { - return std::unexpected(result.error()); - } - return toJson(Dto::SuccessMessage{.message = *result}); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::Pause)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - auto result = pause(); - if (!result) { - return std::unexpected(result.error()); - } - return toJson(Dto::Success{}); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::Resume)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - auto result = resume(); - if (!result) { - return std::unexpected(result.error()); - } - return toJson(Dto::Success{}); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::Stop)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - auto result = stop(); - if (!result) { - return std::unexpected(result.error()); - } - return toJson(Dto::Success{}); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::Skip)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - auto result = skip(1); - if (!result) { - return std::unexpected(result.error()); - } - return toJson(Dto::Success{}); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::SetVolume)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - // Parse volume from params - expect {"volume":0.5} - float volume = 0.5f; - if (params.find("volume") != std::string::npos) { - size_t pos = params.find(':'); - if (pos != std::string::npos) { - volume = std::stof(params.substr(pos + 1)); - } - } - auto result = setVolume(volume); - if (!result) { - return std::unexpected(result.error()); - } - return toJson(Dto::SuccessVolume{.volume = volume}); - }); - - // Queue management - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::GetQueue)), - [this](const std::string& params, uint64_t clientId) - -> Api::Result { - auto queue = getQueue(); - if (!queue) { - return std::unexpected(queue.error()); - } - - Dto::QueueResponse resp; - resp.queue.reserve(queue->size()); - for (const auto& entry : *queue) { - resp.queue.push_back( - Dto::QueueItem{.queueId = entry.queueId, - .track = Dto::toTrack(entry.track), - .isPlaying = entry.isPlaying}); - } - return toJson(resp); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::GetCurrentTrack)), - [this](const std::string& params, uint64_t clientId) - -> Api::Result { - auto track = getCurrentTrack(); - if (!track) { - return std::unexpected(track.error()); - } - - Dto::CurrentTrackResponse resp; - if (track->has_value()) { - resp.track = Dto::toTrack(track->value().track); - } - return toJson(resp); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::GetStatus)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - auto state = getPlaybackState(); - if (!state) { - return std::unexpected(state.error()); - } - - return toJson(Dto::Status{.isPlaying = state->isPlaying, - .isPaused = state->isPaused, - .volume = state->volume, - .repeat = state->repeat, - .shuffle = state->shuffle}); - }); - - Void::Log::info("Core", "{}", "RPC handlers registered"); - } - - void Core::setupEventBusSubscriptions() noexcept - { - using namespace Api::Events; - - // Subscribe to playback events for RPC broadcasting and database - // persistence - eventBus_.subscribe( - [this](const PlaybackStarted& evt) mutable { - // Broadcast to RPC/WebSocket clients - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.started", - toJson(Dto::PlaybackStarted{ - .track = {.id = evt.track.id, - .title = evt.track.title, - .artist = evt.track.artist}, - .position = evt.position.count()})); - } - - // Record playback start in database - if (database_) { - database_->recordPlayback(evt.track, evt.clientId, - std::chrono::milliseconds(0), - false); - } - }); - - eventBus_.subscribe( - [this](const PlaybackPaused& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.paused", - toJson(Dto::Position{.position = evt.position.count()})); - } - }); - - eventBus_.subscribe( - [this](const PlaybackResumed& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.resumed", - toJson(Dto::Position{.position = evt.position.count()})); - } - }); - - eventBus_.subscribe( - [this](const PlaybackStopped& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent("playback.stopped", "{}"); - } - }); - - eventBus_.subscribe( - [this](const PlaybackPositionChanged& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.position", - toJson(Dto::PositionProgress{ - .position = evt.position.count(), - .duration = evt.duration.count(), - .progress = evt.progressPercent})); - } - }); - - eventBus_.subscribe( - [this](const TrackFinished& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent("playback.finished", "{}"); - } - - // Update playback record as completed - if (database_) { - database_->recordPlayback(evt.track, 0, evt.finalPosition, - true); - } - }); - - // Volume and playback mode changes - eventBus_.subscribe( - [this](const VolumeChanged& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.volumeChanged", - toJson(Dto::Volume{.volume = evt.newVolume})); - } - }); - - eventBus_.subscribe( - [this](const ShuffleChanged& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.shuffleChanged", - toJson(Dto::Shuffle{.shuffle = evt.enabled})); - } - }); - - eventBus_.subscribe( - [this](const RepeatChanged& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playback.repeatChanged", - toJson(Dto::Repeat{.repeat = evt.enabled})); - } - }); - - // Queue events - eventBus_.subscribe( - [this](const TrackQueued& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "queue.trackAdded", - toJson(Dto::TrackQueued{ - .queueId = evt.queueId, - .title = evt.track.title, - .artist = evt.track.artist, - .position = evt.position, - .queueLength = evt.queueLength})); - } - }); - - eventBus_.subscribe( - [this](const TrackRemoved& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "queue.trackRemoved", - toJson(Dto::TrackRemoved{ - .queueId = evt.queueId, - .queueLength = evt.queueLength})); - } - }); - - eventBus_.subscribe( - [this](const QueueCleared& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent("queue.cleared", "{}"); - } - }); - - eventBus_.subscribe( - [this](const QueueReordered& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "queue.reordered", - toJson(Dto::QueueReordered{ - .queueId = evt.queueId, - .oldPosition = evt.oldPosition, - .newPosition = evt.newPosition})); - } - }); - - // Playlist events - save to database via event bus using external ID - eventBus_.subscribe( - [this](const PlaylistLoadStarted& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playlist.loadStarted", - toJson(Dto::PlaylistId{.playlistId = evt.playlistId})); - } - - if (database_) { - auto result = database_->getOrCreatePlaylistByExternalId( - evt.playlistId, evt.playlistId, "Loaded from YouTube", - evt.requestedByClientId, true); - } - }); - - eventBus_.subscribe( - [this](const PlaylistTrackLoaded& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playlist.trackLoaded", - toJson(Dto::PlaylistTrackLoaded{ - .playlistId = evt.playlistId, - .loaded = evt.loadedCount, - .total = evt.totalCount})); - } - - // Add track to playlist in database - lookup by external ID - if (database_) { - auto result = database_->getOrCreatePlaylistByExternalId( - evt.playlistId, evt.playlistId, "Loaded from YouTube", - 0, true); - if (result) { - database_->addTrackToPlaylist(result.value(), evt.track, - evt.loadedCount - 1); - } - } - }); - - eventBus_.subscribe( - [this](const PlaylistLoadCompleted& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "playlist.loadCompleted", - toJson(Dto::PlaylistLoadCompleted{ - .playlistId = evt.playlistId, - .totalTracks = evt.totalTracksLoaded, - .success = evt.success})); - } - }); - - // Subscription events - eventBus_.subscribe( - [this](const UserSubscribed& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "subscription.subscribed", - toJson(Dto::User{.uid = evt.uid, - .nickname = evt.nickname})); - } - }); - - eventBus_.subscribe( - [this](const UserUnsubscribed& evt) mutable { - if (rpcServer_) { - rpcServer_->broadcastEvent( - "subscription.unsubscribed", - toJson(Dto::User{.uid = evt.uid, - .nickname = evt.nickname})); - } - }); - - Void::Log::info("Core", "{}", "EventBus subscriptions set up"); - } - void Core::generateRpcTokensForSubscribers() { if (!database_) { diff --git a/src/CoreEventRelay.cpp b/src/CoreEventRelay.cpp new file mode 100644 index 0000000..de525d5 --- /dev/null +++ b/src/CoreEventRelay.cpp @@ -0,0 +1,240 @@ +#include "echoion/core/Core.hpp" +#include "echoion/core/RpcDtos.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + + void Core::setupEventBusSubscriptions() noexcept + { + using namespace Api::Events; + + // Subscribe to playback events for RPC broadcasting and database + // persistence + eventBus_.subscribe( + [this](const PlaybackStarted& evt) mutable { + // Broadcast to RPC/WebSocket clients + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.started", + toJson(Dto::PlaybackStarted{ + .track = {.id = evt.track.id, + .title = evt.track.title, + .artist = evt.track.artist}, + .position = evt.position.count()})); + } + + // Record playback start in database + if (database_) { + database_->recordPlayback(evt.track, evt.clientId, + std::chrono::milliseconds(0), + false); + } + }); + + eventBus_.subscribe( + [this](const PlaybackPaused& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.paused", + toJson(Dto::Position{.position = evt.position.count()})); + } + }); + + eventBus_.subscribe( + [this](const PlaybackResumed& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.resumed", + toJson(Dto::Position{.position = evt.position.count()})); + } + }); + + eventBus_.subscribe( + [this](const PlaybackStopped& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent("playback.stopped", "{}"); + } + }); + + eventBus_.subscribe( + [this](const PlaybackPositionChanged& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.position", + toJson(Dto::PositionProgress{ + .position = evt.position.count(), + .duration = evt.duration.count(), + .progress = evt.progressPercent})); + } + }); + + eventBus_.subscribe( + [this](const TrackFinished& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent("playback.finished", "{}"); + } + + // Update playback record as completed + if (database_) { + database_->recordPlayback(evt.track, 0, evt.finalPosition, + true); + } + }); + + // Volume and playback mode changes + eventBus_.subscribe( + [this](const VolumeChanged& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.volumeChanged", + toJson(Dto::Volume{.volume = evt.newVolume})); + } + }); + + eventBus_.subscribe( + [this](const ShuffleChanged& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.shuffleChanged", + toJson(Dto::Shuffle{.shuffle = evt.enabled})); + } + }); + + eventBus_.subscribe( + [this](const RepeatChanged& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playback.repeatChanged", + toJson(Dto::Repeat{.repeat = evt.enabled})); + } + }); + + // Queue events + eventBus_.subscribe( + [this](const TrackQueued& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "queue.trackAdded", + toJson(Dto::TrackQueued{ + .queueId = evt.queueId, + .title = evt.track.title, + .artist = evt.track.artist, + .position = evt.position, + .queueLength = evt.queueLength})); + } + }); + + eventBus_.subscribe( + [this](const TrackRemoved& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "queue.trackRemoved", + toJson(Dto::TrackRemoved{ + .queueId = evt.queueId, + .queueLength = evt.queueLength})); + } + }); + + eventBus_.subscribe( + [this](const QueueCleared& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent("queue.cleared", "{}"); + } + }); + + eventBus_.subscribe( + [this](const QueueReordered& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "queue.reordered", + toJson(Dto::QueueReordered{ + .queueId = evt.queueId, + .oldPosition = evt.oldPosition, + .newPosition = evt.newPosition})); + } + }); + + // Playlist events - save to database via event bus using external ID + eventBus_.subscribe( + [this](const PlaylistLoadStarted& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playlist.loadStarted", + toJson(Dto::PlaylistId{.playlistId = evt.playlistId})); + } + + if (database_) { + auto result = database_->getOrCreatePlaylistByExternalId( + evt.playlistId, evt.playlistId, "Loaded from YouTube", + evt.requestedByClientId, true); + } + }); + + eventBus_.subscribe( + [this](const PlaylistTrackLoaded& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playlist.trackLoaded", + toJson(Dto::PlaylistTrackLoaded{ + .playlistId = evt.playlistId, + .loaded = evt.loadedCount, + .total = evt.totalCount})); + } + + // Add track to playlist in database - lookup by external ID + if (database_) { + auto result = database_->getOrCreatePlaylistByExternalId( + evt.playlistId, evt.playlistId, "Loaded from YouTube", + 0, true); + if (result) { + database_->addTrackToPlaylist(result.value(), evt.track, + evt.loadedCount - 1); + } + } + }); + + eventBus_.subscribe( + [this](const PlaylistLoadCompleted& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "playlist.loadCompleted", + toJson(Dto::PlaylistLoadCompleted{ + .playlistId = evt.playlistId, + .totalTracks = evt.totalTracksLoaded, + .success = evt.success})); + } + }); + + // Subscription events + eventBus_.subscribe( + [this](const UserSubscribed& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "subscription.subscribed", + toJson(Dto::User{.uid = evt.uid, + .nickname = evt.nickname})); + } + }); + + eventBus_.subscribe( + [this](const UserUnsubscribed& evt) mutable { + if (rpcServer_) { + rpcServer_->broadcastEvent( + "subscription.unsubscribed", + toJson(Dto::User{.uid = evt.uid, + .nickname = evt.nickname})); + } + }); + + Void::Log::info("Core", "{}", "EventBus subscriptions set up"); + } + +} // namespace Echoion::Core diff --git a/src/CoreRpcHandlers.cpp b/src/CoreRpcHandlers.cpp new file mode 100644 index 0000000..83ff45a --- /dev/null +++ b/src/CoreRpcHandlers.cpp @@ -0,0 +1,278 @@ +#include "echoion/core/Core.hpp" +#include "echoion/core/RpcDtos.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + + void Core::setupRpcHandlers() + { + if (!rpcServer_) { + return; + } + + // Authentication - expects JSON with either "nickname" (for initial + // request) or "token" (for validation) + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::Authenticate)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + // Parse JSON params + auto parsedParams = Void::Json::parse(params); + if (!parsedParams) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid authentication request format"); + } + auto reqResult = + Void::Json::from_json(*parsedParams); + if (!reqResult) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid authentication request format"); + } + const Dto::AuthRequest& req = *reqResult; + + // If token provided, validate it + if (req.token.has_value()) { + auto validResult = database_->validateRpcToken(*req.token); + if (!validResult) { + return std::unexpected(validResult.error()); + } + if (*validResult) { + rpcServer_->addAuthenticatedClient(clientId); + return toJson(Dto::SuccessMessage{ + .message = "Authentication successful"}); + } else { + return Api::fail( + Api::ErrorCode::PermissionDenied, "Invalid token"); + } + } + + // If nickname provided, search for subscriber and send token + // via PM + if (req.nickname.has_value()) { + auto uidResult = + database_->getSubscriberByNickname(*req.nickname); + if (!uidResult) { + return std::unexpected(uidResult.error()); + } + + if (!uidResult->has_value()) { + return Api::fail( + Api::ErrorCode::NotFound, + "Subscriber not found. Please subscribe to the bot " + "first using !subscribe command."); + } + + const std::string& uid = **uidResult; + + // Get or create token + auto tokenResult = database_->getExistingRpcToken(uid); + if (!tokenResult) { + return std::unexpected(tokenResult.error()); + } + + std::string token; + if (tokenResult->has_value()) { + token = **tokenResult; + } else { + // Generate new token + auto genResult = database_->generateRpcToken(uid); + if (!genResult) { + return std::unexpected(genResult.error()); + } + token = *genResult; + } + + // Get client ID from UID to send PM + if (pluginInterface_) { + // Get all clients and find the one with matching UID + auto clientsResult = pluginInterface_->getClients(); + if (clientsResult) { + for (const auto& client : *clientsResult) { + if (client.uniqueIdentifier == uid) { + uint64_t tsClientId = client.id; + + // Send PM with token using plain text + // format (compatible with both TS3 BBCode + // and TS6 Markdown) + std::string pmMessage = std::format( + "**Echoion RPC Authentication**\n\n" + "Your authentication token:\n" + "```\n{}\n```\n\n" + "Use this token to authenticate with " + "the RPC server.\n" + "Keep this token secure and do not " + "share it with others.", + token); + + auto pmResult = + pluginInterface_->sendTextMessage( + tsClientId, pmMessage); + + if (!pmResult) { + Void::Log::warn("Core", "{}", std::format( + "Failed to send PM with token: {}", + pmResult.error().message)); + } + break; + } + } + } + } + + return toJson(Dto::SuccessMessage{ + .message = "Token sent via TeamSpeak PM. Please check " + "your private messages."}); + } + + return Api::fail(Api::ErrorCode::InvalidArgument, + "Authentication request must include either " + "'nickname' or 'token'"); + }); + + // Playback control + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::Play)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + // Parse query from params (simple implementation) + std::string query = params; + // Remove quotes if present + if (query.size() >= 2 && query.front() == '"' && + query.back() == '"') { + query = query.substr(1, query.size() - 2); + } + auto result = musicManager_->play(query, clientId); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::SuccessMessage{.message = *result}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::Pause)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + auto result = pause(); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::Resume)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + auto result = resume(); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::Stop)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + auto result = stop(); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::Skip)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + auto result = skip(1); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::SetVolume)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + // Parse volume from params - expect {"volume":0.5} + float volume = 0.5f; + if (params.find("volume") != std::string::npos) { + size_t pos = params.find(':'); + if (pos != std::string::npos) { + volume = std::stof(params.substr(pos + 1)); + } + } + auto result = setVolume(volume); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::SuccessVolume{.volume = volume}); + }); + + // Queue management + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::GetQueue)), + [this](const std::string& params, uint64_t clientId) + -> Api::Result { + auto queue = getQueue(); + if (!queue) { + return std::unexpected(queue.error()); + } + + Dto::QueueResponse resp; + resp.queue.reserve(queue->size()); + for (const auto& entry : *queue) { + resp.queue.push_back( + Dto::QueueItem{.queueId = entry.queueId, + .track = Dto::toTrack(entry.track), + .isPlaying = entry.isPlaying}); + } + return toJson(resp); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::GetCurrentTrack)), + [this](const std::string& params, uint64_t clientId) + -> Api::Result { + auto track = getCurrentTrack(); + if (!track) { + return std::unexpected(track.error()); + } + + Dto::CurrentTrackResponse resp; + if (track->has_value()) { + resp.track = Dto::toTrack(track->value().track); + } + return toJson(resp); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::GetStatus)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + auto state = getPlaybackState(); + if (!state) { + return std::unexpected(state.error()); + } + + return toJson(Dto::Status{.isPlaying = state->isPlaying, + .isPaused = state->isPaused, + .volume = state->volume, + .repeat = state->repeat, + .shuffle = state->shuffle}); + }); + + Void::Log::info("Core", "{}", "RPC handlers registered"); + } + +} // namespace Echoion::Core