From 0779fdcf20a608b8a6b14a3ee60905198f7904c2 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 24 Jun 2026 00:20:13 +0300 Subject: [PATCH] Serialize RPC responses + event payloads via Void::Json (RpcDtos) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the ~37 hand-built JSON strings in setupRpcHandlers and setupEventBusSubscriptions (and broadcastEvent) with reflectable DTOs in a new RpcDtos.hpp, serialized through Void::Json. This fixes a real correctness bug — track titles/artists, nicknames, playlist IDs, and play messages containing " or \ produced invalid JSON before; they are now correctly escaped (verified: `My "Song" \o/` -> `My \"Song\" \\o/`). Shapes preserved (same keys/order); the only change is absent optionals now serialize as null instead of being omitted. Build green. Co-Authored-By: Claude Opus 4.8 --- include/echoion/core/RpcDtos.hpp | 163 +++++++++++++++++++ src/Core.cpp | 263 ++++++++++++++----------------- 2 files changed, 282 insertions(+), 144 deletions(-) create mode 100644 include/echoion/core/RpcDtos.hpp diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp new file mode 100644 index 0000000..a08b114 --- /dev/null +++ b/include/echoion/core/RpcDtos.hpp @@ -0,0 +1,163 @@ +#pragma once + +#include +#include +#include +#include +#include + +// 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 handler responses ─────────────────────────────────────────────── + + struct Track { + std::string id; + std::string title; + std::string artist; + std::string album; + std::optional duration; // milliseconds + int source = 0; + }; + + [[nodiscard]] inline Track toTrack(const Api::TrackInfo& t) + { + return Track{.id = t.id, + .title = t.title, + .artist = t.artist, + .album = t.album, + .duration = t.duration + ? std::optional( + t.duration->count()) + : std::nullopt, + .source = static_cast(t.source)}; + } + + struct QueueItem { + std::uint64_t queueId = 0; + Track track; + bool isPlaying = false; + }; + + struct QueueResponse { + std::vector queue; + }; + + struct CurrentTrackResponse { + std::optional track; + }; + + struct Status { + bool isPlaying = false; + bool isPaused = false; + float volume = 0.0f; + bool repeat = false; + bool shuffle = false; + }; + + struct Success { + bool success = true; + }; + + struct SuccessMessage { + bool success = true; + std::string message; + }; + + struct SuccessVolume { + bool success = true; + float volume = 0.0f; + }; + + // ── Event-broadcast payloads ──────────────────────────────────────────── + + struct TrackBrief { + std::string id; + std::string title; + std::string artist; + }; + + struct PlaybackStarted { + TrackBrief track; + std::int64_t position = 0; + }; + + struct Position { + std::int64_t position = 0; + }; + + struct PositionProgress { + std::int64_t position = 0; + std::int64_t duration = 0; + float progress = 0.0f; + }; + + struct Volume { + float volume = 0.0f; + }; + + struct Shuffle { + bool shuffle = false; + }; + + struct Repeat { + bool repeat = false; + }; + + struct TrackQueued { + std::uint64_t queueId = 0; + std::string title; + std::string artist; + std::uint32_t position = 0; + std::uint32_t queueLength = 0; + }; + + struct TrackRemoved { + std::uint64_t queueId = 0; + std::uint32_t queueLength = 0; + }; + + struct QueueReordered { + std::uint64_t queueId = 0; + std::uint32_t oldPosition = 0; + std::uint32_t newPosition = 0; + }; + + struct PlaylistId { + std::string playlistId; + }; + + struct PlaylistTrackLoaded { + std::string playlistId; + std::uint32_t loaded = 0; + std::uint32_t total = 0; + }; + + struct PlaylistLoadCompleted { + std::string playlistId; + std::uint32_t totalTracks = 0; + bool success = false; + }; + + struct User { + std::string uid; + std::string nickname; + }; + + struct ClientId { + std::uint64_t clientId = 0; + }; + + // Plugin-event track payload (duration in seconds, matching the legacy + // broadcastEvent shape). + struct EventTrack { + std::string id; + std::string title; + std::string artist; + std::int64_t duration = 0; + }; + +} // namespace Echoion::Core::Dto diff --git a/src/Core.cpp b/src/Core.cpp index dbb0702..fa21074 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -1,5 +1,6 @@ #include "echoion/core/ConfigLoader.hpp" #include "echoion/core/Core.hpp" +#include "echoion/core/RpcDtos.hpp" #include "echoion/core/state/StateSerializer.hpp" #include "echoion/core/state/StateVersions.hpp" #include @@ -25,6 +26,13 @@ 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. @@ -1445,25 +1453,23 @@ namespace Echoion::Core // Serialize event data to JSON with proper escaping std::string eventData = "{}"; if (event.trackSummary) { - eventData = std::format( - "{{\"id\":\"{}\",\"title\":\"{}\",\"artist\":\"{}" - "\",\"duration\":{}}}", - event.trackSummary->id, - event.trackSummary->title, - event.trackSummary->artist, - event.trackSummary->duration - ? event.trackSummary->duration->count() / 1000 - : 0); + eventData = toJson(Dto::EventTrack{ + .id = event.trackSummary->id, + .title = event.trackSummary->title, + .artist = event.trackSummary->artist, + .duration = event.trackSummary->duration + ? event.trackSummary->duration->count() / 1000 + : 0}); } if (event.volume.has_value()) { - eventData = std::format("{{\"volume\":{:.2f}}}", *event.volume); + eventData = toJson(Dto::Volume{.volume = *event.volume}); } if (event.queuePosition.has_value()) { - eventData = - std::format("{{\"position\":{}}}", *event.queuePosition); + eventData = toJson(Dto::Position{ + .position = static_cast(*event.queuePosition)}); } if (event.clientId > 0) { - eventData = std::format("{{\"clientId\":{}}}", event.clientId); + eventData = toJson(Dto::ClientId{.clientId = event.clientId}); } rpcServer_->broadcastEvent(eventName, eventData); @@ -1514,23 +1520,6 @@ namespace Echoion::Core return; } - // Helper to serialize track info - auto serializeTrack = [](const Api::TrackInfo& track) -> std::string { - std::string json = "{"; - json += std::format("\"id\":\"{}\",", track.id); - json += std::format("\"title\":\"{}\",", track.title); - json += std::format("\"artist\":\"{}\",", track.artist); - json += std::format("\"album\":\"{}\",", track.album); - if (track.duration.has_value()) { - json += - std::format("\"duration\":{},", track.duration->count()); - } - json += - std::format("\"source\":{}", static_cast(track.source)); - json += "}"; - return json; - }; - // Authentication - expects JSON with either "nickname" (for initial // request) or "token" (for validation) rpcServer_->registerHandler( @@ -1559,9 +1548,8 @@ namespace Echoion::Core } if (*validResult) { rpcServer_->addAuthenticatedClient(clientId); - return std::string( - "{\"success\":true,\"message\":\"Authentication " - "successful\"}"); + return toJson(Dto::SuccessMessage{ + .message = "Authentication successful"}); } else { return Api::fail( Api::ErrorCode::PermissionDenied, "Invalid token"); @@ -1641,9 +1629,9 @@ namespace Echoion::Core } } - return std::string( - "{\"success\":true,\"message\":\"Token sent via " - "TeamSpeak PM. Please check your private messages.\"}"); + return toJson(Dto::SuccessMessage{ + .message = "Token sent via TeamSpeak PM. Please check " + "your private messages."}); } return Api::fail(Api::ErrorCode::InvalidArgument, @@ -1667,8 +1655,7 @@ namespace Echoion::Core if (!result) { return std::unexpected(result.error()); } - return std::format("{{\"success\":true,\"message\":\"{}\"}}", - *result); + return toJson(Dto::SuccessMessage{.message = *result}); }); rpcServer_->registerHandler( @@ -1679,7 +1666,7 @@ namespace Echoion::Core if (!result) { return std::unexpected(result.error()); } - return std::string("{\"success\":true}"); + return toJson(Dto::Success{}); }); rpcServer_->registerHandler( @@ -1690,7 +1677,7 @@ namespace Echoion::Core if (!result) { return std::unexpected(result.error()); } - return std::string("{\"success\":true}"); + return toJson(Dto::Success{}); }); rpcServer_->registerHandler( @@ -1701,7 +1688,7 @@ namespace Echoion::Core if (!result) { return std::unexpected(result.error()); } - return std::string("{\"success\":true}"); + return toJson(Dto::Success{}); }); rpcServer_->registerHandler( @@ -1712,7 +1699,7 @@ namespace Echoion::Core if (!result) { return std::unexpected(result.error()); } - return std::string("{\"success\":true}"); + return toJson(Dto::Success{}); }); rpcServer_->registerHandler( @@ -1731,53 +1718,44 @@ namespace Echoion::Core if (!result) { return std::unexpected(result.error()); } - return std::format("{{\"success\":true,\"volume\":{}}}", - volume); + return toJson(Dto::SuccessVolume{.volume = volume}); }); // Queue management rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetQueue)), - [this, serializeTrack](const std::string& params, uint64_t clientId) + [this](const std::string& params, uint64_t clientId) -> Api::Result { auto queue = getQueue(); if (!queue) { return std::unexpected(queue.error()); } - std::string json = "{\"queue\":["; - for (size_t i = 0; i < queue->size(); ++i) { - if (i > 0) { - json += ","; - } - json += "{"; - json += std::format("\"queueId\":{},", (*queue)[i].queueId); - json += std::format("\"track\":{},", - serializeTrack((*queue)[i].track)); - json += - std::format("\"isPlaying\":{}", - (*queue)[i].isPlaying ? "true" : "false"); - json += "}"; + 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}); } - json += "]}"; - return json; + return toJson(resp); }); rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetCurrentTrack)), - [this, serializeTrack](const std::string& params, uint64_t clientId) + [this](const std::string& params, uint64_t clientId) -> Api::Result { auto track = getCurrentTrack(); if (!track) { return std::unexpected(track.error()); } - if (!track->has_value()) { - return std::string("{\"track\":null}"); + Dto::CurrentTrackResponse resp; + if (track->has_value()) { + resp.track = Dto::toTrack(track->value().track); } - - return std::format("{{\"track\":{}}}", - serializeTrack(track->value().track)); + return toJson(resp); }); rpcServer_->registerHandler( @@ -1789,18 +1767,11 @@ namespace Echoion::Core return std::unexpected(state.error()); } - std::string json = "{"; - json += std::format("\"isPlaying\":{},", - state->isPlaying ? "true" : "false"); - json += std::format("\"isPaused\":{},", - state->isPaused ? "true" : "false"); - json += std::format("\"volume\":{},", state->volume); - json += std::format("\"repeat\":{},", - state->repeat ? "true" : "false"); - json += std::format("\"shuffle\":{}", - state->shuffle ? "true" : "false"); - json += "}"; - return json; + 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"); @@ -1816,12 +1787,13 @@ namespace Echoion::Core [this](const PlaybackStarted& evt) mutable { // Broadcast to RPC/WebSocket clients if (rpcServer_) { - std::string data = std::format( - "{{\"track\":{{\"id\":\"{}\",\"title\":\"{}\"," - "\"artist\":\"{}\"}},\"position\":{}}}", - evt.track.id, evt.track.title, evt.track.artist, - evt.position.count()); - rpcServer_->broadcastEvent("playback.started", data); + 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 @@ -1835,18 +1807,18 @@ namespace Echoion::Core eventBus_.subscribe( [this](const PlaybackPaused& evt) mutable { if (rpcServer_) { - std::string data = std::format("{{\"position\":{}}}", - evt.position.count()); - rpcServer_->broadcastEvent("playback.paused", data); + rpcServer_->broadcastEvent( + "playback.paused", + toJson(Dto::Position{.position = evt.position.count()})); } }); eventBus_.subscribe( [this](const PlaybackResumed& evt) mutable { if (rpcServer_) { - std::string data = std::format("{{\"position\":{}}}", - evt.position.count()); - rpcServer_->broadcastEvent("playback.resumed", data); + rpcServer_->broadcastEvent( + "playback.resumed", + toJson(Dto::Position{.position = evt.position.count()})); } }); @@ -1860,12 +1832,12 @@ namespace Echoion::Core eventBus_.subscribe( [this](const PlaybackPositionChanged& evt) mutable { if (rpcServer_) { - std::string data = - std::format("{{\"position\":{},\"duration\":{}," - "\"progress\":{:.2f}}}", - evt.position.count(), evt.duration.count(), - evt.progressPercent); - rpcServer_->broadcastEvent("playback.position", data); + rpcServer_->broadcastEvent( + "playback.position", + toJson(Dto::PositionProgress{ + .position = evt.position.count(), + .duration = evt.duration.count(), + .progress = evt.progressPercent})); } }); @@ -1886,27 +1858,27 @@ namespace Echoion::Core eventBus_.subscribe( [this](const VolumeChanged& evt) mutable { if (rpcServer_) { - std::string data = - std::format("{{\"volume\":{:.2f}}}", evt.newVolume); - rpcServer_->broadcastEvent("playback.volumeChanged", data); + rpcServer_->broadcastEvent( + "playback.volumeChanged", + toJson(Dto::Volume{.volume = evt.newVolume})); } }); eventBus_.subscribe( [this](const ShuffleChanged& evt) mutable { if (rpcServer_) { - std::string data = std::format( - "{{\"shuffle\":{}}}", evt.enabled ? "true" : "false"); - rpcServer_->broadcastEvent("playback.shuffleChanged", data); + rpcServer_->broadcastEvent( + "playback.shuffleChanged", + toJson(Dto::Shuffle{.shuffle = evt.enabled})); } }); eventBus_.subscribe( [this](const RepeatChanged& evt) mutable { if (rpcServer_) { - std::string data = std::format( - "{{\"repeat\":{}}}", evt.enabled ? "true" : "false"); - rpcServer_->broadcastEvent("playback.repeatChanged", data); + rpcServer_->broadcastEvent( + "playback.repeatChanged", + toJson(Dto::Repeat{.repeat = evt.enabled})); } }); @@ -1914,22 +1886,25 @@ namespace Echoion::Core eventBus_.subscribe( [this](const TrackQueued& evt) mutable { if (rpcServer_) { - std::string data = std::format( - "{{\"queueId\":{},\"title\":\"{}\",\"artist\":" - "\"{}\",\"position\":{},\"queueLength\":{}}}", - evt.queueId, evt.track.title, evt.track.artist, - evt.position, evt.queueLength); - rpcServer_->broadcastEvent("queue.trackAdded", data); + 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_) { - std::string data = - std::format("{{\"queueId\":{},\"queueLength\":{}}}", - evt.queueId, evt.queueLength); - rpcServer_->broadcastEvent("queue.trackRemoved", data); + rpcServer_->broadcastEvent( + "queue.trackRemoved", + toJson(Dto::TrackRemoved{ + .queueId = evt.queueId, + .queueLength = evt.queueLength})); } }); @@ -1943,11 +1918,12 @@ namespace Echoion::Core eventBus_.subscribe( [this](const QueueReordered& evt) mutable { if (rpcServer_) { - std::string data = std::format( - "{{\"queueId\":{},\"oldPosition\":{},\"newPosition\":{}" - "}}", - evt.queueId, evt.oldPosition, evt.newPosition); - rpcServer_->broadcastEvent("queue.reordered", data); + rpcServer_->broadcastEvent( + "queue.reordered", + toJson(Dto::QueueReordered{ + .queueId = evt.queueId, + .oldPosition = evt.oldPosition, + .newPosition = evt.newPosition})); } }); @@ -1955,9 +1931,9 @@ namespace Echoion::Core eventBus_.subscribe( [this](const PlaylistLoadStarted& evt) mutable { if (rpcServer_) { - std::string data = std::string("{\"playlistId\":\"") + - evt.playlistId + "\"}"; - rpcServer_->broadcastEvent("playlist.loadStarted", data); + rpcServer_->broadcastEvent( + "playlist.loadStarted", + toJson(Dto::PlaylistId{.playlistId = evt.playlistId})); } if (database_) { @@ -1970,11 +1946,12 @@ namespace Echoion::Core eventBus_.subscribe( [this](const PlaylistTrackLoaded& evt) mutable { if (rpcServer_) { - std::string data = - std::string("{\"playlistId\":\"") + evt.playlistId + - "\",\"loaded\":" + std::to_string(evt.loadedCount) + - ",\"total\":" + std::to_string(evt.totalCount) + "}"; - rpcServer_->broadcastEvent("playlist.trackLoaded", data); + 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 @@ -1992,13 +1969,12 @@ namespace Echoion::Core eventBus_.subscribe( [this](const PlaylistLoadCompleted& evt) mutable { if (rpcServer_) { - std::string data = - std::string("{\"playlistId\":\"") + evt.playlistId + - "\",\"totalTracks\":" + - std::to_string(evt.totalTracksLoaded) + - ",\"success\":" + (evt.success ? "true" : "false") + - "}"; - rpcServer_->broadcastEvent("playlist.loadCompleted", data); + rpcServer_->broadcastEvent( + "playlist.loadCompleted", + toJson(Dto::PlaylistLoadCompleted{ + .playlistId = evt.playlistId, + .totalTracks = evt.totalTracksLoaded, + .success = evt.success})); } }); @@ -2006,21 +1982,20 @@ namespace Echoion::Core eventBus_.subscribe( [this](const UserSubscribed& evt) mutable { if (rpcServer_) { - std::string data = - std::format("{{\"uid\":\"{}\",\"nickname\":\"{}\"}}", - evt.uid, evt.nickname); - rpcServer_->broadcastEvent("subscription.subscribed", data); + rpcServer_->broadcastEvent( + "subscription.subscribed", + toJson(Dto::User{.uid = evt.uid, + .nickname = evt.nickname})); } }); eventBus_.subscribe( [this](const UserUnsubscribed& evt) mutable { if (rpcServer_) { - std::string data = - std::format("{{\"uid\":\"{}\",\"nickname\":\"{}\"}}", - evt.uid, evt.nickname); - rpcServer_->broadcastEvent("subscription.unsubscribed", - data); + rpcServer_->broadcastEvent( + "subscription.unsubscribed", + toJson(Dto::User{.uid = evt.uid, + .nickname = evt.nickname})); } });