Serialize RPC responses + event payloads via Void::Json (RpcDtos)

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 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-24 00:20:13 +03:00
1 parent 75ee32a24b
commit 0779fdcf20
2 files changed
+282 -144

No files matched your search

+163
View File
@@ -0,0 +1,163 @@
#pragma once
#include <TrackTypes.hpp>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
// 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<std::int64_t> 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<std::int64_t>(
t.duration->count())
: std::nullopt,
.source = static_cast<int>(t.source)};
}
struct QueueItem {
std::uint64_t queueId = 0;
Track track;
bool isPlaying = false;
};
struct QueueResponse {
std::vector<QueueItem> queue;
};
struct CurrentTrackResponse {
std::optional<Track> 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
+119 -144
View File
@@ -1,5 +1,6 @@
#include "echoion/core/ConfigLoader.hpp" #include "echoion/core/ConfigLoader.hpp"
#include "echoion/core/Core.hpp" #include "echoion/core/Core.hpp"
#include "echoion/core/RpcDtos.hpp"
#include "echoion/core/state/StateSerializer.hpp" #include "echoion/core/state/StateSerializer.hpp"
#include "echoion/core/state/StateVersions.hpp" #include "echoion/core/state/StateVersions.hpp"
#include <ConfigManager.hpp> #include <ConfigManager.hpp>
@@ -25,6 +26,13 @@ namespace Echoion::Core
{ {
namespace namespace
{ {
// Serialize any reflectable DTO to a JSON string (correct escaping).
template <typename T>
[[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 // Build the console + split-file logging stack and install it as the
// process-wide Void::Log sink. Replaces the old ILogger/LoggerRegistry // process-wide Void::Log sink. Replaces the old ILogger/LoggerRegistry
// indirection; every ECHOION_LOG_* macro is now a Void::Log:: call. // 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 // Serialize event data to JSON with proper escaping
std::string eventData = "{}"; std::string eventData = "{}";
if (event.trackSummary) { if (event.trackSummary) {
eventData = std::format( eventData = toJson(Dto::EventTrack{
"{{\"id\":\"{}\",\"title\":\"{}\",\"artist\":\"{}" .id = event.trackSummary->id,
"\",\"duration\":{}}}", .title = event.trackSummary->title,
event.trackSummary->id, .artist = event.trackSummary->artist,
event.trackSummary->title, .duration = event.trackSummary->duration
event.trackSummary->artist, ? event.trackSummary->duration->count() / 1000
event.trackSummary->duration : 0});
? event.trackSummary->duration->count() / 1000
: 0);
} }
if (event.volume.has_value()) { if (event.volume.has_value()) {
eventData = std::format("{{\"volume\":{:.2f}}}", *event.volume); eventData = toJson(Dto::Volume{.volume = *event.volume});
} }
if (event.queuePosition.has_value()) { if (event.queuePosition.has_value()) {
eventData = eventData = toJson(Dto::Position{
std::format("{{\"position\":{}}}", *event.queuePosition); .position = static_cast<std::int64_t>(*event.queuePosition)});
} }
if (event.clientId > 0) { if (event.clientId > 0) {
eventData = std::format("{{\"clientId\":{}}}", event.clientId); eventData = toJson(Dto::ClientId{.clientId = event.clientId});
} }
rpcServer_->broadcastEvent(eventName, eventData); rpcServer_->broadcastEvent(eventName, eventData);
@@ -1514,23 +1520,6 @@ namespace Echoion::Core
return; 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<int>(track.source));
json += "}";
return json;
};
// Authentication - expects JSON with either "nickname" (for initial // Authentication - expects JSON with either "nickname" (for initial
// request) or "token" (for validation) // request) or "token" (for validation)
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1559,9 +1548,8 @@ namespace Echoion::Core
} }
if (*validResult) { if (*validResult) {
rpcServer_->addAuthenticatedClient(clientId); rpcServer_->addAuthenticatedClient(clientId);
return std::string( return toJson(Dto::SuccessMessage{
"{\"success\":true,\"message\":\"Authentication " .message = "Authentication successful"});
"successful\"}");
} else { } else {
return Api::fail( return Api::fail(
Api::ErrorCode::PermissionDenied, "Invalid token"); Api::ErrorCode::PermissionDenied, "Invalid token");
@@ -1641,9 +1629,9 @@ namespace Echoion::Core
} }
} }
return std::string( return toJson(Dto::SuccessMessage{
"{\"success\":true,\"message\":\"Token sent via " .message = "Token sent via TeamSpeak PM. Please check "
"TeamSpeak PM. Please check your private messages.\"}"); "your private messages."});
} }
return Api::fail(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
@@ -1667,8 +1655,7 @@ namespace Echoion::Core
if (!result) { if (!result) {
return std::unexpected(result.error()); return std::unexpected(result.error());
} }
return std::format("{{\"success\":true,\"message\":\"{}\"}}", return toJson(Dto::SuccessMessage{.message = *result});
*result);
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1679,7 +1666,7 @@ namespace Echoion::Core
if (!result) { if (!result) {
return std::unexpected(result.error()); return std::unexpected(result.error());
} }
return std::string("{\"success\":true}"); return toJson(Dto::Success{});
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1690,7 +1677,7 @@ namespace Echoion::Core
if (!result) { if (!result) {
return std::unexpected(result.error()); return std::unexpected(result.error());
} }
return std::string("{\"success\":true}"); return toJson(Dto::Success{});
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1701,7 +1688,7 @@ namespace Echoion::Core
if (!result) { if (!result) {
return std::unexpected(result.error()); return std::unexpected(result.error());
} }
return std::string("{\"success\":true}"); return toJson(Dto::Success{});
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1712,7 +1699,7 @@ namespace Echoion::Core
if (!result) { if (!result) {
return std::unexpected(result.error()); return std::unexpected(result.error());
} }
return std::string("{\"success\":true}"); return toJson(Dto::Success{});
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1731,53 +1718,44 @@ namespace Echoion::Core
if (!result) { if (!result) {
return std::unexpected(result.error()); return std::unexpected(result.error());
} }
return std::format("{{\"success\":true,\"volume\":{}}}", return toJson(Dto::SuccessVolume{.volume = volume});
volume);
}); });
// Queue management // Queue management
rpcServer_->registerHandler( rpcServer_->registerHandler(
std::to_string(static_cast<int>(Api::RpcMethod::GetQueue)), std::to_string(static_cast<int>(Api::RpcMethod::GetQueue)),
[this, serializeTrack](const std::string& params, uint64_t clientId) [this](const std::string& params, uint64_t clientId)
-> Api::Result<std::string> { -> Api::Result<std::string> {
auto queue = getQueue(); auto queue = getQueue();
if (!queue) { if (!queue) {
return std::unexpected(queue.error()); return std::unexpected(queue.error());
} }
std::string json = "{\"queue\":["; Dto::QueueResponse resp;
for (size_t i = 0; i < queue->size(); ++i) { resp.queue.reserve(queue->size());
if (i > 0) { for (const auto& entry : *queue) {
json += ","; resp.queue.push_back(
} Dto::QueueItem{.queueId = entry.queueId,
json += "{"; .track = Dto::toTrack(entry.track),
json += std::format("\"queueId\":{},", (*queue)[i].queueId); .isPlaying = entry.isPlaying});
json += std::format("\"track\":{},",
serializeTrack((*queue)[i].track));
json +=
std::format("\"isPlaying\":{}",
(*queue)[i].isPlaying ? "true" : "false");
json += "}";
} }
json += "]}"; return toJson(resp);
return json;
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)), std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)),
[this, serializeTrack](const std::string& params, uint64_t clientId) [this](const std::string& params, uint64_t clientId)
-> Api::Result<std::string> { -> Api::Result<std::string> {
auto track = getCurrentTrack(); auto track = getCurrentTrack();
if (!track) { if (!track) {
return std::unexpected(track.error()); return std::unexpected(track.error());
} }
if (!track->has_value()) { Dto::CurrentTrackResponse resp;
return std::string("{\"track\":null}"); if (track->has_value()) {
resp.track = Dto::toTrack(track->value().track);
} }
return toJson(resp);
return std::format("{{\"track\":{}}}",
serializeTrack(track->value().track));
}); });
rpcServer_->registerHandler( rpcServer_->registerHandler(
@@ -1789,18 +1767,11 @@ namespace Echoion::Core
return std::unexpected(state.error()); return std::unexpected(state.error());
} }
std::string json = "{"; return toJson(Dto::Status{.isPlaying = state->isPlaying,
json += std::format("\"isPlaying\":{},", .isPaused = state->isPaused,
state->isPlaying ? "true" : "false"); .volume = state->volume,
json += std::format("\"isPaused\":{},", .repeat = state->repeat,
state->isPaused ? "true" : "false"); .shuffle = state->shuffle});
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;
}); });
Void::Log::info("Core", "{}", "RPC handlers registered"); Void::Log::info("Core", "{}", "RPC handlers registered");
@@ -1816,12 +1787,13 @@ namespace Echoion::Core
[this](const PlaybackStarted& evt) mutable { [this](const PlaybackStarted& evt) mutable {
// Broadcast to RPC/WebSocket clients // Broadcast to RPC/WebSocket clients
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format( rpcServer_->broadcastEvent(
"{{\"track\":{{\"id\":\"{}\",\"title\":\"{}\"," "playback.started",
"\"artist\":\"{}\"}},\"position\":{}}}", toJson(Dto::PlaybackStarted{
evt.track.id, evt.track.title, evt.track.artist, .track = {.id = evt.track.id,
evt.position.count()); .title = evt.track.title,
rpcServer_->broadcastEvent("playback.started", data); .artist = evt.track.artist},
.position = evt.position.count()}));
} }
// Record playback start in database // Record playback start in database
@@ -1835,18 +1807,18 @@ namespace Echoion::Core
eventBus_.subscribe<PlaybackPaused>( eventBus_.subscribe<PlaybackPaused>(
[this](const PlaybackPaused& evt) mutable { [this](const PlaybackPaused& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format("{{\"position\":{}}}", rpcServer_->broadcastEvent(
evt.position.count()); "playback.paused",
rpcServer_->broadcastEvent("playback.paused", data); toJson(Dto::Position{.position = evt.position.count()}));
} }
}); });
eventBus_.subscribe<PlaybackResumed>( eventBus_.subscribe<PlaybackResumed>(
[this](const PlaybackResumed& evt) mutable { [this](const PlaybackResumed& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format("{{\"position\":{}}}", rpcServer_->broadcastEvent(
evt.position.count()); "playback.resumed",
rpcServer_->broadcastEvent("playback.resumed", data); toJson(Dto::Position{.position = evt.position.count()}));
} }
}); });
@@ -1860,12 +1832,12 @@ namespace Echoion::Core
eventBus_.subscribe<PlaybackPositionChanged>( eventBus_.subscribe<PlaybackPositionChanged>(
[this](const PlaybackPositionChanged& evt) mutable { [this](const PlaybackPositionChanged& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::format("{{\"position\":{},\"duration\":{}," "playback.position",
"\"progress\":{:.2f}}}", toJson(Dto::PositionProgress{
evt.position.count(), evt.duration.count(), .position = evt.position.count(),
evt.progressPercent); .duration = evt.duration.count(),
rpcServer_->broadcastEvent("playback.position", data); .progress = evt.progressPercent}));
} }
}); });
@@ -1886,27 +1858,27 @@ namespace Echoion::Core
eventBus_.subscribe<VolumeChanged>( eventBus_.subscribe<VolumeChanged>(
[this](const VolumeChanged& evt) mutable { [this](const VolumeChanged& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::format("{{\"volume\":{:.2f}}}", evt.newVolume); "playback.volumeChanged",
rpcServer_->broadcastEvent("playback.volumeChanged", data); toJson(Dto::Volume{.volume = evt.newVolume}));
} }
}); });
eventBus_.subscribe<ShuffleChanged>( eventBus_.subscribe<ShuffleChanged>(
[this](const ShuffleChanged& evt) mutable { [this](const ShuffleChanged& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format( rpcServer_->broadcastEvent(
"{{\"shuffle\":{}}}", evt.enabled ? "true" : "false"); "playback.shuffleChanged",
rpcServer_->broadcastEvent("playback.shuffleChanged", data); toJson(Dto::Shuffle{.shuffle = evt.enabled}));
} }
}); });
eventBus_.subscribe<RepeatChanged>( eventBus_.subscribe<RepeatChanged>(
[this](const RepeatChanged& evt) mutable { [this](const RepeatChanged& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format( rpcServer_->broadcastEvent(
"{{\"repeat\":{}}}", evt.enabled ? "true" : "false"); "playback.repeatChanged",
rpcServer_->broadcastEvent("playback.repeatChanged", data); toJson(Dto::Repeat{.repeat = evt.enabled}));
} }
}); });
@@ -1914,22 +1886,25 @@ namespace Echoion::Core
eventBus_.subscribe<TrackQueued>( eventBus_.subscribe<TrackQueued>(
[this](const TrackQueued& evt) mutable { [this](const TrackQueued& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format( rpcServer_->broadcastEvent(
"{{\"queueId\":{},\"title\":\"{}\",\"artist\":" "queue.trackAdded",
"\"{}\",\"position\":{},\"queueLength\":{}}}", toJson(Dto::TrackQueued{
evt.queueId, evt.track.title, evt.track.artist, .queueId = evt.queueId,
evt.position, evt.queueLength); .title = evt.track.title,
rpcServer_->broadcastEvent("queue.trackAdded", data); .artist = evt.track.artist,
.position = evt.position,
.queueLength = evt.queueLength}));
} }
}); });
eventBus_.subscribe<TrackRemoved>( eventBus_.subscribe<TrackRemoved>(
[this](const TrackRemoved& evt) mutable { [this](const TrackRemoved& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::format("{{\"queueId\":{},\"queueLength\":{}}}", "queue.trackRemoved",
evt.queueId, evt.queueLength); toJson(Dto::TrackRemoved{
rpcServer_->broadcastEvent("queue.trackRemoved", data); .queueId = evt.queueId,
.queueLength = evt.queueLength}));
} }
}); });
@@ -1943,11 +1918,12 @@ namespace Echoion::Core
eventBus_.subscribe<QueueReordered>( eventBus_.subscribe<QueueReordered>(
[this](const QueueReordered& evt) mutable { [this](const QueueReordered& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::format( rpcServer_->broadcastEvent(
"{{\"queueId\":{},\"oldPosition\":{},\"newPosition\":{}" "queue.reordered",
"}}", toJson(Dto::QueueReordered{
evt.queueId, evt.oldPosition, evt.newPosition); .queueId = evt.queueId,
rpcServer_->broadcastEvent("queue.reordered", data); .oldPosition = evt.oldPosition,
.newPosition = evt.newPosition}));
} }
}); });
@@ -1955,9 +1931,9 @@ namespace Echoion::Core
eventBus_.subscribe<PlaylistLoadStarted>( eventBus_.subscribe<PlaylistLoadStarted>(
[this](const PlaylistLoadStarted& evt) mutable { [this](const PlaylistLoadStarted& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = std::string("{\"playlistId\":\"") + rpcServer_->broadcastEvent(
evt.playlistId + "\"}"; "playlist.loadStarted",
rpcServer_->broadcastEvent("playlist.loadStarted", data); toJson(Dto::PlaylistId{.playlistId = evt.playlistId}));
} }
if (database_) { if (database_) {
@@ -1970,11 +1946,12 @@ namespace Echoion::Core
eventBus_.subscribe<PlaylistTrackLoaded>( eventBus_.subscribe<PlaylistTrackLoaded>(
[this](const PlaylistTrackLoaded& evt) mutable { [this](const PlaylistTrackLoaded& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::string("{\"playlistId\":\"") + evt.playlistId + "playlist.trackLoaded",
"\",\"loaded\":" + std::to_string(evt.loadedCount) + toJson(Dto::PlaylistTrackLoaded{
",\"total\":" + std::to_string(evt.totalCount) + "}"; .playlistId = evt.playlistId,
rpcServer_->broadcastEvent("playlist.trackLoaded", data); .loaded = evt.loadedCount,
.total = evt.totalCount}));
} }
// Add track to playlist in database - lookup by external ID // Add track to playlist in database - lookup by external ID
@@ -1992,13 +1969,12 @@ namespace Echoion::Core
eventBus_.subscribe<PlaylistLoadCompleted>( eventBus_.subscribe<PlaylistLoadCompleted>(
[this](const PlaylistLoadCompleted& evt) mutable { [this](const PlaylistLoadCompleted& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::string("{\"playlistId\":\"") + evt.playlistId + "playlist.loadCompleted",
"\",\"totalTracks\":" + toJson(Dto::PlaylistLoadCompleted{
std::to_string(evt.totalTracksLoaded) + .playlistId = evt.playlistId,
",\"success\":" + (evt.success ? "true" : "false") + .totalTracks = evt.totalTracksLoaded,
"}"; .success = evt.success}));
rpcServer_->broadcastEvent("playlist.loadCompleted", data);
} }
}); });
@@ -2006,21 +1982,20 @@ namespace Echoion::Core
eventBus_.subscribe<UserSubscribed>( eventBus_.subscribe<UserSubscribed>(
[this](const UserSubscribed& evt) mutable { [this](const UserSubscribed& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::format("{{\"uid\":\"{}\",\"nickname\":\"{}\"}}", "subscription.subscribed",
evt.uid, evt.nickname); toJson(Dto::User{.uid = evt.uid,
rpcServer_->broadcastEvent("subscription.subscribed", data); .nickname = evt.nickname}));
} }
}); });
eventBus_.subscribe<UserUnsubscribed>( eventBus_.subscribe<UserUnsubscribed>(
[this](const UserUnsubscribed& evt) mutable { [this](const UserUnsubscribed& evt) mutable {
if (rpcServer_) { if (rpcServer_) {
std::string data = rpcServer_->broadcastEvent(
std::format("{{\"uid\":\"{}\",\"nickname\":\"{}\"}}", "subscription.unsubscribed",
evt.uid, evt.nickname); toJson(Dto::User{.uid = evt.uid,
rpcServer_->broadcastEvent("subscription.unsubscribed", .nickname = evt.nickname}));
data);
} }
}); });