From 01362d2e513bdbdb993a0ec5701ebc1fdc1ffb8c Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 12 Jul 2026 02:56:29 +0300 Subject: [PATCH] Update Signed-off-by: faumaray --- CMakeLists.txt | 10 + include/echoion/core/Core.hpp | 3 + include/echoion/core/ListeningRoomManager.hpp | 106 ++++ include/echoion/core/ListeningRoomName.hpp | 37 ++ include/echoion/core/RpcDtos.hpp | 35 ++ include/echoion/core/commands/Commands.hpp | 1 + include/echoion/core/commands/RoomCommand.hpp | 218 +++++++++ include/echoion/core/state/StateVersions.hpp | 14 + src/CommandManager.cpp | 1 + src/Core.cpp | 152 ++++-- src/CoreRpcHandlers.cpp | 214 ++++++++ src/Export.cpp | 86 +++- src/ListeningRoomManager.cpp | 457 ++++++++++++++++++ tests/test_listening_room_state.cpp | 41 ++ 14 files changed, 1324 insertions(+), 51 deletions(-) create mode 100644 include/echoion/core/ListeningRoomManager.hpp create mode 100644 include/echoion/core/ListeningRoomName.hpp create mode 100644 include/echoion/core/commands/RoomCommand.hpp create mode 100644 src/ListeningRoomManager.cpp create mode 100644 tests/test_listening_room_state.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c45b630..de20f57 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -219,6 +219,16 @@ install(FILES DESTINATION lib/cmake/EchoionCore ) +if(BUILD_TESTS) + add_executable(echoion_core_room_state_tests + tests/test_listening_room_state.cpp) + target_include_directories(echoion_core_room_state_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(echoion_core_room_state_tests PRIVATE EchoionCore) + add_test(NAME echoion_core_room_state_tests + COMMAND echoion_core_room_state_tests) +endif() + option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF) if(BUNDLE_FFMPEG) include(cmake/BundleFFmpeg.cmake) diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index 73d89b2..feb36ec 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -35,6 +35,7 @@ namespace Void::Logging namespace Echoion::Core { + class ListeningRoomManager; // Main Core implementation of ICoreInterface class Core : public Api::ICoreInterface @@ -191,6 +192,8 @@ namespace Echoion::Core std::shared_ptr networkClient_; std::shared_ptr lyricsService_; std::shared_ptr musicManager_; + std::shared_ptr listeningRooms_; + std::string pendingListeningRoomState_; std::unique_ptr commandManager_; Api::PluginInterfacePtr pluginInterface_; diff --git a/include/echoion/core/ListeningRoomManager.hpp b/include/echoion/core/ListeningRoomManager.hpp new file mode 100644 index 0000000..ea6c767 --- /dev/null +++ b/include/echoion/core/ListeningRoomManager.hpp @@ -0,0 +1,106 @@ +#pragma once + +#include "echoion/core/MusicManager.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + class NetworkClient; + + class ListeningRoomManager final + { + public: + struct RoomSummary { + std::string name; + uint64_t ownerId{}; + std::vector members; + bool isPlaying{}; + bool isPaused{}; + std::size_t queueSize{}; + }; + struct PersistedRoom { + std::string name; + uint64_t ownerId{}; + std::vector members; + Api::HotReloadState state; + }; + + ListeningRoomManager(std::shared_ptr network, + Api::ConfigManager& config, Void::EventBus::EventBus& events); + ~ListeningRoomManager(); + ListeningRoomManager(const ListeningRoomManager&) = delete; + ListeningRoomManager& operator=(const ListeningRoomManager&) = delete; + + void setPluginInterface(Api::PluginInterfacePtr plugin); + void setChangeCallback(std::function callback); + [[nodiscard]] Api::Result + create(std::string name, uint64_t ownerId); + [[nodiscard]] Api::Result remove(const std::string& name, + uint64_t requesterId); + [[nodiscard]] Api::Result join(const std::string& name, + uint64_t clientId); + [[nodiscard]] Api::Result leave(uint64_t clientId); + [[nodiscard]] Api::Result play(const std::string& name, + std::string query, uint64_t clientId); + [[nodiscard]] Api::Result pause(const std::string& name, + uint64_t requesterId); + [[nodiscard]] Api::Result resume(const std::string& name, + uint64_t requesterId); + [[nodiscard]] Api::Result stop(const std::string& name, + uint64_t requesterId); + [[nodiscard]] Api::Result skip(const std::string& name, + uint64_t requesterId); + [[nodiscard]] Api::Result removeQueueEntry(const std::string& name, + uint64_t queueId, uint64_t requesterId); + [[nodiscard]] Api::Result moveQueueEntry(const std::string& name, + uint64_t queueId, uint32_t newPosition, uint64_t requesterId); + [[nodiscard]] Api::Result clearQueue(const std::string& name, + uint64_t requesterId); + [[nodiscard]] Api::Result> + queue(const std::string& name) const; + [[nodiscard]] std::vector list() const; + [[nodiscard]] std::optional + roomForClient(uint64_t clientId) const; + [[nodiscard]] std::vector snapshot() const; + [[nodiscard]] Api::Result + restore(const std::vector& rooms); + void shutdown(); + + private: + struct Room { + std::string name; + uint64_t ownerId{}; + Api::IPluginInterface::AudioStreamId streamId{}; + std::set members; + std::unique_ptr music; + }; + + [[nodiscard]] Api::ServerConfig serverConfigFor( + const std::string& roomName) const; + [[nodiscard]] Api::Result refreshRecipients(Room& room); + [[nodiscard]] Room* findLocked(const std::string& name); + [[nodiscard]] const Room* findLocked(const std::string& name) const; + + std::shared_ptr network_; + Api::ConfigManager& config_; + Void::EventBus::EventBus& events_; + Api::PluginInterfacePtr plugin_; + std::map> rooms_; + std::map membership_; + mutable std::mutex mutex_; + std::function changeCallback_; + void notifyChanged() const; + }; +} diff --git a/include/echoion/core/ListeningRoomName.hpp b/include/echoion/core/ListeningRoomName.hpp new file mode 100644 index 0000000..2c1ee1d --- /dev/null +++ b/include/echoion/core/ListeningRoomName.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Echoion::Core +{ + [[nodiscard]] inline Api::Result + validateListeningRoomName(std::string name) + { + const auto first = name.find_first_not_of(" \t\r\n"); + if (first == std::string::npos) return Api::fail( + Api::ErrorCode::InvalidArgument, "room name is required"); + const auto last = name.find_last_not_of(" \t\r\n"); + name = name.substr(first, last - first + 1); + if (name.size() > 48 || std::ranges::any_of(name, + [](unsigned char value) { return std::iscntrl(value) != 0; })) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "room name must be 1-48 printable characters"); + } + return name; + } + + [[nodiscard]] inline std::string + canonicalListeningRoomName(std::string_view name) + { + std::string key{name}; + std::ranges::transform(key, key.begin(), [](unsigned char value) { + return static_cast(std::tolower(value)); + }); + return key; + } +} diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp index 110307d..452cedb 100644 --- a/include/echoion/core/RpcDtos.hpp +++ b/include/echoion/core/RpcDtos.hpp @@ -85,6 +85,26 @@ namespace Echoion::Core::Dto std::string text; }; + struct ListeningRoomRequest { + std::string room; + }; + + struct ListeningRoomPlayRequest { + std::string room; + std::string query; + }; + + struct ListeningRoomQueueRequest { + std::string room; + std::uint64_t queueId = 0; + }; + + struct ListeningRoomMoveRequest { + std::string room; + std::uint64_t queueId = 0; + std::uint32_t newPosition = 0; + }; + // ── RPC handler responses ─────────────────────────────────────────────── struct Track { @@ -181,6 +201,21 @@ namespace Echoion::Core::Dto float volume = 0.0f; }; + struct ListeningRoom { + std::string name; + std::uint64_t ownerId = 0; + std::vector members; + bool isPlaying = false; + bool isPaused = false; + std::uint64_t queueSize = 0; + bool isOwner = false; + }; + + struct ListeningRoomList { + std::vector rooms; + std::optional currentRoom; + }; + struct Autoplay { bool autoplay = false; }; diff --git a/include/echoion/core/commands/Commands.hpp b/include/echoion/core/commands/Commands.hpp index 6b5ad25..6ee5e6e 100644 --- a/include/echoion/core/commands/Commands.hpp +++ b/include/echoion/core/commands/Commands.hpp @@ -19,6 +19,7 @@ #include "ReloadConfigCommand.hpp" #include "RemoveCommand.hpp" #include "RepeatCommand.hpp" +#include "RoomCommand.hpp" #include "ResumeCommand.hpp" #include "RpcInfoCommand.hpp" #include "SearchCommand.hpp" diff --git a/include/echoion/core/commands/RoomCommand.hpp b/include/echoion/core/commands/RoomCommand.hpp new file mode 100644 index 0000000..9c5a09d --- /dev/null +++ b/include/echoion/core/commands/RoomCommand.hpp @@ -0,0 +1,218 @@ +#pragma once + +#include "Command.hpp" +#include "echoion/core/ListeningRoomManager.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + class RoomCommand final : public Command + { + public: + void execute(const CommandContext& ctx) override + { + auto rooms = ctx.service(); + if (!rooms) { + ctx.reply(ctx.tr("Listening rooms are currently unavailable.")); + return; + } + + auto [action, argument] = split(ctx.args); + if (action.empty() || action == "list") { + list(ctx, *rooms); + return; + } + if (action == "help") { + help(ctx); + return; + } + + if (action == "create") { + reply(ctx, rooms->create(argument, ctx.clientId), + ctx.trf("Created and joined room '{}'.", argument)); + return; + } + if (action == "join") { + reply(ctx, rooms->join(argument, ctx.clientId), + ctx.trf("Joined room '{}'.", argument)); + return; + } + if (action == "leave") { + reply(ctx, rooms->leave(ctx.clientId), + ctx.tr("Left the listening room.")); + return; + } + + const auto current = rooms->roomForClient(ctx.clientId); + if (!current) { + ctx.reply(ctx.trf( + "Join a room first with {}room join .", ctx.prefix)); + return; + } + if (action == "delete") { + reply(ctx, rooms->remove(*current, ctx.clientId), + ctx.trf("Deleted room '{}'.", *current)); + } else if (action == "play") { + if (argument.empty()) { + help(ctx); + return; + } + auto result = rooms->play(*current, argument, ctx.clientId); + if (!result) { + ctx.reply(ctx.trf("Room action failed: {}", + result.error().message)); + } else { + ctx.reply(ctx.trf("Added to '{}': {}", *current, *result)); + } + } else if (action == "pause") { + reply(ctx, rooms->pause(*current, ctx.clientId), + ctx.trf("Paused room '{}'.", *current)); + } else if (action == "resume") { + reply(ctx, rooms->resume(*current, ctx.clientId), + ctx.trf("Resumed room '{}'.", *current)); + } else if (action == "stop") { + reply(ctx, rooms->stop(*current, ctx.clientId), + ctx.trf("Stopped room '{}'.", *current)); + } else if (action == "skip") { + reply(ctx, rooms->skip(*current, ctx.clientId), + ctx.trf("Skipped in room '{}'.", *current)); + } else if (action == "clear") { + reply(ctx, rooms->clearQueue(*current, ctx.clientId), + ctx.trf("Cleared queue for '{}'.", *current)); + } else if (action == "remove") { + const auto queueId = number(argument); + if (!queueId) { + help(ctx); + return; + } + reply(ctx, rooms->removeQueueEntry( + *current, *queueId, ctx.clientId), + ctx.trf("Removed queue entry {}.", *queueId)); + } else if (action == "move") { + auto [queueIdText, positionText] = split(argument); + const auto queueId = number(queueIdText); + const auto position = number(positionText); + if (!queueId || !position || *position == 0) { + help(ctx); + return; + } + reply(ctx, rooms->moveQueueEntry(*current, *queueId, + static_cast(*position - 1), ctx.clientId), + ctx.trf("Moved queue entry {} to position {}.", + *queueId, *position)); + } else if (action == "queue") { + queue(ctx, *rooms, *current); + } else { + help(ctx); + } + } + + [[nodiscard]] std::string_view getDescription() const override + { + return "Creates, joins and controls independent listening rooms."; + } + [[nodiscard]] std::string_view getUsage() const override + { + return ""; + } + [[nodiscard]] CommandCategory getCategory() const override + { + return CommandCategory::Music; + } + + private: + static std::pair split(std::string_view input) + { + const auto first = input.find_first_not_of(" \t"); + if (first == std::string_view::npos) return {}; + const auto separator = input.find_first_of(" \t", first); + std::string action(input.substr(first, separator - first)); + std::ranges::transform(action, action.begin(), + [](unsigned char value) { return std::tolower(value); }); + if (separator == std::string_view::npos) return {action, {}}; + const auto argumentStart = input.find_first_not_of(" \t", separator); + return {action, argumentStart == std::string_view::npos + ? std::string{} : std::string(input.substr(argumentStart))}; + } + + static std::optional number(std::string_view text) + { + uint64_t value = 0; + const auto [end, error] = std::from_chars( + text.data(), text.data() + text.size(), value); + return error == std::errc{} && end == text.data() + text.size() + ? std::optional{value} : std::nullopt; + } + + static void list(const CommandContext& ctx, ListeningRoomManager& rooms) + { + const auto all = rooms.list(); + if (all.empty()) { + ctx.reply(ctx.trf("No listening rooms. Create one with {}room create .", + ctx.prefix)); + return; + } + const auto current = rooms.roomForClient(ctx.clientId); + std::stringstream output; + output << ctx.tr("Listening rooms:") << '\n'; + for (const auto& room : all) { + const bool selected = current == room.name; + output << (selected ? "**> " : "- ") + << escapeMarkdown(room.name) << (selected ? "** " : " ") + << ctx.trf("({} listeners, {} queued{})", room.members.size(), + room.queueSize, room.isPlaying ? ", playing" : "") << '\n'; + } + ctx.reply(output.str()); + } + + static void queue(const CommandContext& ctx, ListeningRoomManager& rooms, + const std::string& name) + { + auto entries = rooms.queue(name); + if (!entries) { + ctx.reply(ctx.trf("Room action failed: {}", entries.error().message)); + return; + } + std::stringstream output; + output << ctx.trf("Queue for '{}' ({} tracks):", name, entries->size()); + for (std::size_t index = 0; index < entries->size(); ++index) { + output << '\n' << index + 1 << ". " + << trackLink((*entries)[index].track) << " `#" + << (*entries)[index].queueId << '`'; + } + ctx.reply(output.str()); + } + + static void reply(const CommandContext& ctx, const Api::Result& result, + std::string_view success) + { + if (result) { + ctx.reply(success); + } else { + ctx.reply(ctx.trf("Room action failed: {}", result.error().message)); + } + } + + static void help(const CommandContext& ctx) + { + ctx.reply(ctx.trf( + "Room commands:\n" + "`{}room list`\n`{}room create `\n" + "`{}room join `\n`{}room leave`\n" + "`{}room play `\n`{}room pause|resume|stop|skip`\n" + "`{}room queue`\n`{}room remove `\n" + "`{}room move `\n" + "`{}room clear`\n`{}room delete`", + ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix, + ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix, ctx.prefix, + ctx.prefix)); + } + }; +} diff --git a/include/echoion/core/state/StateVersions.hpp b/include/echoion/core/state/StateVersions.hpp index 10d540d..e5e688a 100644 --- a/include/echoion/core/state/StateVersions.hpp +++ b/include/echoion/core/state/StateVersions.hpp @@ -1,5 +1,6 @@ #pragma once #include "TrackTypes.hpp" +#include "RpcTypes.hpp" #include #include #include @@ -45,6 +46,18 @@ namespace Echoion::Core std::string lastActivity; // ISO 8601 }; + struct ListeningRoomState { + std::string name; + uint64_t ownerId = 0; + std::vector members; + Echoion::Api::PlaybackState playback; + std::vector queue; + std::optional currentStreamUrl; + int64_t playbackPositionMs = 0; + BotConfig config; + bool autoplay = false; + }; + // Main state PlaybackState playback; bool hasPlayback = @@ -52,6 +65,7 @@ namespace Echoion::Core bool autoplay = false; // Radio mode on/off (persisted for restart) std::vector queue; std::vector sessions; + std::vector listeningRooms; // Version info uint32_t version = 1; diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index 45a804c..c35b6e9 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -640,6 +640,7 @@ namespace Echoion::Core registerCommand("shuffle"); registerCommand("autoplay"); registerCommand("repeat"); + registerCommand("room"); registerCommand("playlist"); registerCommand("np"); registerCommand("lyrics"); diff --git a/src/Core.cpp b/src/Core.cpp index c0e4c36..0a5ffb7 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -1,5 +1,7 @@ +#include "PluginTypes.hpp" #include "echoion/core/ConfigLoader.hpp" #include "echoion/core/Core.hpp" +#include "echoion/core/ListeningRoomManager.hpp" #include "echoion/core/RpcDtos.hpp" #include "echoion/core/i18n/Localization.hpp" #include "echoion/core/state/StateSerializer.hpp" @@ -33,11 +35,21 @@ namespace Echoion::Core std::string decodeBase64(const std::string& in) { static constexpr auto val = [](char c) -> int { - if (c >= 'A' && c <= 'Z') return c - 'A'; - if (c >= 'a' && c <= 'z') return c - 'a' + 26; - if (c >= '0' && c <= '9') return c - '0' + 52; - if (c == '+') return 62; - if (c == '/') return 63; + if (c >= 'A' && c <= 'Z') { + return c - 'A'; + } + if (c >= 'a' && c <= 'z') { + return c - 'a' + 26; + } + if (c >= '0' && c <= '9') { + return c - '0' + 52; + } + if (c == '+') { + return 62; + } + if (c == '/') { + return 63; + } return -1; }; std::string out; @@ -63,18 +75,20 @@ namespace Echoion::Core } // Encode raw bytes to base64 (used to persist TeamSpeak avatar images - // in the database so they survive the client going offline/out-of-view). + // in the database so they survive the client going + // offline/out-of-view). std::string encodeBase64(std::string_view in) { - static constexpr char tbl[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + static constexpr char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij" + "klmnopqrstuvwxyz0123456789+/"; std::string out; out.reserve((in.size() + 2) / 3 * 4); std::size_t i = 0; while (i + 3 <= in.size()) { - const unsigned n = (static_cast(in[i]) << 16) | - (static_cast(in[i + 1]) << 8) | - static_cast(in[i + 2]); + const unsigned n = + (static_cast(in[i]) << 16) | + (static_cast(in[i + 1]) << 8) | + static_cast(in[i + 2]); out.push_back(tbl[(n >> 18) & 0x3F]); out.push_back(tbl[(n >> 12) & 0x3F]); out.push_back(tbl[(n >> 6) & 0x3F]); @@ -99,7 +113,8 @@ namespace Echoion::Core // Best content type for avatar bytes: honour a valid image/* hint // (e.g. an HTTP Content-Type), else sniff the magic number. - std::string sniffImageMime(std::string_view bytes, std::string_view hint) + std::string sniffImageMime(std::string_view bytes, + std::string_view hint) { if (hint.starts_with("image/")) { return std::string(hint); @@ -164,7 +179,7 @@ namespace Echoion::Core void Core::installLogging() { logSink_ = buildLogSink(); - Void::Log::set_sink(Void::Log::make_sink(*logSink_)); + Void::Log::set_sink(Void::Log::make_sink(logSink_)); Void::Log::set_min_level(Void::Log::Level::Debug); } @@ -273,6 +288,8 @@ namespace Echoion::Core if (!musicResult) { return std::unexpected(musicResult.error()); } + listeningRooms_ = std::make_shared( + networkClient_, configManager_, eventBus_); // Initialize command manager commandManager_ = std::make_unique(); @@ -467,6 +484,11 @@ namespace Echoion::Core std::format("RPC server started on port {}", rpcPort)); setupRpcHandlers(); setupEventBusSubscriptions(); + if (listeningRooms_) { + listeningRooms_->setChangeCallback([server = rpcServer_] { + server->broadcastEvent("listening_rooms.updated", "{}"); + }); + } } #ifdef ECHOION_WITH_WEB @@ -530,8 +552,7 @@ namespace Echoion::Core if (database_) { [[maybe_unused]] auto put = database_->putCachedAvatar( - u, type, - encodeBase64(resp->body)); + u, type, encodeBase64(resp->body)); } return Web::HttpServer::AvatarImage{ .contentType = std::move(type), @@ -549,7 +570,7 @@ namespace Echoion::Core continue; } if (auto r = - fetchClientAvatarBytes(uid, c.id)) { + fetchClientAvatarBytes(uid, c.id)) { return Web::HttpServer::AvatarImage{ .contentType = std::move(r->first), .bytes = std::move(r->second)}; @@ -599,8 +620,8 @@ namespace Echoion::Core // Proactively cache avatars for every online client so they stay // available (from the DB / stored myTS URL) once the user goes offline. - // A short-cycle poll keeps up with clients whose avatar variables sync a - // moment after they come into view. + // A short-cycle poll keeps up with clients whose avatar variables sync + // a moment after they come into view. avatarWarmer_ = std::jthread([this](std::stop_token st) { while (!st.stop_requested()) { for (int i = 0; i < 30 && !st.stop_requested(); ++i) { @@ -642,6 +663,9 @@ namespace Echoion::Core if (musicManager_) { registry_.provide(musicManager_); } + if (listeningRooms_) { + registry_.provide(listeningRooms_); + } if (rpcServer_) { registry_.provide(rpcServer_); } @@ -687,6 +711,11 @@ namespace Echoion::Core musicManager_->shutdown(); } + if (listeningRooms_) { + listeningRooms_->shutdown(); + listeningRooms_.reset(); + } + if (networkClient_) { networkClient_->shutdown(); } @@ -1354,6 +1383,21 @@ namespace Echoion::Core state.playback.shuffle = ps->shuffle; state.playback.repeat = ps->repeat; } + if (listeningRooms_) { + for (auto& saved : listeningRooms_->snapshot()) { + StateV1::ListeningRoomState room; + room.name = std::move(saved.name); + room.ownerId = saved.ownerId; + room.members = std::move(saved.members); + room.playback = std::move(saved.state.playback); + room.queue = std::move(saved.state.queue); + room.currentStreamUrl = std::move(saved.state.currentStreamUrl); + room.playbackPositionMs = saved.state.playbackPosition.count(); + room.config = std::move(saved.state.config); + room.autoplay = saved.state.autoplay; + state.listeningRooms.push_back(std::move(room)); + } + } // Serialize using StateSerializer auto blob = StateSerializer::serialize(state); @@ -1381,6 +1425,8 @@ namespace Echoion::Core } const StateV1& stateData = *result; + pendingListeningRoomState_ = Void::Json::serialize( + Void::Json::to_json(stateData.listeningRooms)); // MusicManager already reloads its persisted session (queue + modes) // from the database at startup. Only fall back to re-adding from this @@ -1509,11 +1555,14 @@ namespace Echoion::Core Api::Result Core::onPluginEvent(const Api::PluginEvent& event) { - Void::Log::debug( - "Core", "{}", - std::format("Core::onPluginEvent called (this={}, initialized={})", - reinterpret_cast(this), - initialized_.load())); + if (event.type != Api::PluginEventType::VoiceDataReceived) { + Void::Log::debug("Core", "{}", + std::format("Core::onPluginEvent called (this={}, " + "initialized={}, event={})", + reinterpret_cast(this), + initialized_.load(), + static_cast(event.type))); + } if (!initialized_) { Void::Log::warn( "Core", "{}", @@ -1628,6 +1677,9 @@ namespace Echoion::Core if (musicManager_) { musicManager_->onClientDisconnected(event.clientId); } + if (listeningRooms_) { + std::ignore = listeningRooms_->leave(event.clientId); + } break; default: @@ -1649,6 +1701,44 @@ namespace Echoion::Core void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface) { pluginInterface_ = std::move(pluginInterface); + if (listeningRooms_) { + listeningRooms_->setPluginInterface(pluginInterface_); + if (!pendingListeningRoomState_.empty()) { + auto json = Void::Json::parse(pendingListeningRoomState_); + if (json) { + auto saved = Void::Json::from_json< + std::vector>(*json); + if (saved) { + std::vector rooms; + rooms.reserve(saved->size()); + for (auto& source : *saved) { + Api::HotReloadState state; + state.playback = std::move(source.playback); + state.queue = std::move(source.queue); + state.currentStreamUrl = + std::move(source.currentStreamUrl); + state.playbackPosition = std::chrono::milliseconds( + source.playbackPositionMs); + state.config = std::move(source.config); + state.autoplay = source.autoplay; + rooms.push_back( + {.name = std::move(source.name), + .ownerId = source.ownerId, + .members = std::move(source.members), + .state = std::move(state)}); + } + if (auto restored = listeningRooms_->restore(rooms); + !restored) { + Void::Log::error( + "Core", + "Failed to restore listening rooms: {}", + restored.error().message); + } + } + } + pendingListeningRoomState_.clear(); + } + } Void::Log::info("Core", "{}", std::format("Plugin interface set (this={})", reinterpret_cast(this))); @@ -1904,10 +1994,10 @@ namespace Echoion::Core if (c.uniqueIdentifier != identity.uid) { continue; } - identity.isAdmin = inAnyGroup( - config_.teamspeak.adminGroups, c.serverGroups); - identity.isDj = inAnyGroup(config_.teamspeak.djGroups, - c.serverGroups); + identity.isAdmin = inAnyGroup(config_.teamspeak.adminGroups, + c.serverGroups); + identity.isDj = + inAnyGroup(config_.teamspeak.djGroups, c.serverGroups); if (identity.nickname.empty()) { identity.nickname = c.nickname; } @@ -1934,8 +2024,8 @@ namespace Echoion::Core } { std::lock_guard lock(rpcIdentityMutex_); - rpcIdentities_[clientId] = RpcIdentity{ - .uid = identity.uid, .nickname = identity.nickname}; + rpcIdentities_[clientId] = + RpcIdentity{.uid = identity.uid, .nickname = identity.nickname}; } } @@ -1952,8 +2042,8 @@ namespace Echoion::Core } std::string type = sniffImageMime(bytes, hint); if (database_) { - [[maybe_unused]] auto put = database_->putCachedAvatar( - uid, type, encodeBase64(bytes)); + [[maybe_unused]] auto put = + database_->putCachedAvatar(uid, type, encodeBase64(bytes)); } return std::pair{std::move(type), std::move(bytes)}; }; diff --git a/src/CoreRpcHandlers.cpp b/src/CoreRpcHandlers.cpp index f4f10cb..c2adc9f 100644 --- a/src/CoreRpcHandlers.cpp +++ b/src/CoreRpcHandlers.cpp @@ -1,4 +1,5 @@ #include "echoion/core/Core.hpp" +#include "echoion/core/ListeningRoomManager.hpp" #include "echoion/core/RpcDtos.hpp" #include #include @@ -36,6 +37,21 @@ namespace Echoion::Core if (!rpcServer_) { return; } + auto resolveTeamSpeakClient = [this](uint64_t rpcClientId) + -> Api::Result { + auto identity = rpcIdentity(rpcClientId); + if (!identity) return Api::fail(Api::ErrorCode::NotAuthenticated, + "authenticate before using listening rooms"); + if (!pluginInterface_) return Api::fail( + Api::ErrorCode::ServiceUnavailable, "TeamSpeak host unavailable"); + auto clients = pluginInterface_->getClients(); + if (!clients) return std::unexpected(clients.error()); + for (const auto& client : *clients) { + if (client.uniqueIdentifier == identity->uid) return client.id; + } + return Api::fail(Api::ErrorCode::NotFound, + "authenticated TeamSpeak client is not online"); + }; // Authentication - expects JSON with either "nickname" (for initial // request) or "token" (for validation). The same handler backs @@ -593,6 +609,204 @@ namespace Echoion::Core return toJson(resp); }); + // Named listening rooms: every room owns an independent playback engine, + // Opus encoder and TeamSpeak whisper connection. + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::ListListeningRooms)), + [this, resolveTeamSpeakClient](const std::string&, uint64_t rpcId) + -> Api::Result { + if (!listeningRooms_) return Api::fail( + Api::ErrorCode::ServiceUnavailable, "listening rooms unavailable"); + Dto::ListeningRoomList response; + const auto client = resolveTeamSpeakClient(rpcId); + if (client) { + response.currentRoom = listeningRooms_->roomForClient(*client); + } + for (const auto& room : listeningRooms_->list()) { + response.rooms.push_back(Dto::ListeningRoom{ + .name = room.name, .ownerId = room.ownerId, + .members = room.members, .isPlaying = room.isPlaying, + .isPaused = room.isPaused, + .queueSize = static_cast(room.queueSize), + .isOwner = client && room.ownerId == *client}); + } + return toJson(response); + }); + + auto roomRequest = [](const std::string& params) + -> Api::Result { + auto json = Void::Json::parse(params); + if (!json) return Api::fail(Api::ErrorCode::InvalidArgument, + "invalid listening-room request"); + auto request = Void::Json::from_json(*json); + if (!request || request->room.empty()) return Api::fail( + Api::ErrorCode::InvalidArgument, "room name is required"); + return *request; + }; + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::CreateListeningRoom)), + [this, resolveTeamSpeakClient, roomRequest](const std::string& params, + uint64_t rpcId) -> Api::Result { + auto request = roomRequest(params); + if (!request) return std::unexpected(request.error()); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->create(request->room, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::DeleteListeningRoom)), + [this, resolveTeamSpeakClient, roomRequest](const std::string& params, + uint64_t rpcId) -> Api::Result { + auto request = roomRequest(params); + if (!request) return std::unexpected(request.error()); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->remove(request->room, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::JoinListeningRoom)), + [this, resolveTeamSpeakClient, roomRequest](const std::string& params, + uint64_t rpcId) -> Api::Result { + auto request = roomRequest(params); + if (!request) return std::unexpected(request.error()); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->join(request->room, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::LeaveListeningRoom)), + [this, resolveTeamSpeakClient](const std::string&, uint64_t rpcId) + -> Api::Result { + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->leave(*client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::PlayInListeningRoom)), + [this, resolveTeamSpeakClient](const std::string& params, uint64_t rpcId) + -> Api::Result { + auto json = Void::Json::parse(params); + if (!json) return Api::fail(Api::ErrorCode::InvalidArgument, + "invalid room play request"); + auto request = Void::Json::from_json(*json); + if (!request || request->room.empty() || request->query.empty()) + return Api::fail(Api::ErrorCode::InvalidArgument, + "room and query are required"); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->play( + request->room, request->query, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::SuccessMessage{.message = *result}); + }); + + const auto registerRoomControl = + [this, roomRequest, resolveTeamSpeakClient](Api::RpcMethod method, + auto operation) { + rpcServer_->registerHandler( + std::to_string(static_cast(method)), + [roomRequest, operation, resolveTeamSpeakClient]( + const std::string& params, uint64_t rpcId) + -> Api::Result { + auto request = roomRequest(params); + if (!request) return std::unexpected(request.error()); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = operation(request->room, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + }; + registerRoomControl(Api::RpcMethod::PauseListeningRoom, + [this](const std::string& room, uint64_t client) { + return listeningRooms_->pause(room, client); + }); + registerRoomControl(Api::RpcMethod::ResumeListeningRoom, + [this](const std::string& room, uint64_t client) { + return listeningRooms_->resume(room, client); + }); + registerRoomControl(Api::RpcMethod::StopListeningRoom, + [this](const std::string& room, uint64_t client) { + return listeningRooms_->stop(room, client); + }); + registerRoomControl(Api::RpcMethod::SkipListeningRoom, + [this](const std::string& room, uint64_t client) { + return listeningRooms_->skip(room, client); + }); + registerRoomControl(Api::RpcMethod::ClearListeningRoomQueue, + [this](const std::string& room, uint64_t client) { + return listeningRooms_->clearQueue(room, client); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::GetListeningRoomQueue)), + [this, roomRequest](const std::string& params, uint64_t) + -> Api::Result { + auto request = roomRequest(params); + if (!request) return std::unexpected(request.error()); + auto queue = listeningRooms_->queue(request->room); + if (!queue) return std::unexpected(queue.error()); + Dto::QueueResponse response; + for (const auto& entry : *queue) response.queue.push_back( + Dto::QueueItem{.queueId = entry.queueId, + .track = Dto::toTrack(entry.track), + .isPlaying = entry.isPlaying}); + return toJson(response); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast( + Api::RpcMethod::RemoveFromListeningRoomQueue)), + [this, resolveTeamSpeakClient](const std::string& params, uint64_t rpcId) + -> Api::Result { + auto json = Void::Json::parse(params); + if (!json) return Api::fail(Api::ErrorCode::InvalidArgument, + "invalid room queue request"); + auto request = Void::Json::from_json(*json); + if (!request || request->room.empty() || request->queueId == 0) + return Api::fail(Api::ErrorCode::InvalidArgument, + "room and queueId are required"); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->removeQueueEntry( + request->room, request->queueId, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast( + Api::RpcMethod::MoveInListeningRoomQueue)), + [this, resolveTeamSpeakClient](const std::string& params, uint64_t rpcId) + -> Api::Result { + auto json = Void::Json::parse(params); + if (!json) return Api::fail(Api::ErrorCode::InvalidArgument, + "invalid room queue move request"); + auto request = Void::Json::from_json(*json); + if (!request || request->room.empty() || request->queueId == 0) + return Api::fail(Api::ErrorCode::InvalidArgument, + "room and queueId are required"); + auto client = resolveTeamSpeakClient(rpcId); + if (!client) return std::unexpected(client.error()); + auto result = listeningRooms_->moveQueueEntry(request->room, + request->queueId, request->newPosition, *client); + if (!result) return std::unexpected(result.error()); + return toJson(Dto::Success{}); + }); + rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetCurrentTrack)), [this](const std::string& /*params*/, uint64_t /*clientId*/) diff --git a/src/Export.cpp b/src/Export.cpp index 49a6afd..1731ac2 100644 --- a/src/Export.cpp +++ b/src/Export.cpp @@ -3,8 +3,11 @@ #include #include #include +#include #include +#include #include +#include namespace Echoion::Api { @@ -37,16 +40,52 @@ namespace Echoion::Core return "Echoion"; } - // Void::Plugin::PluginLoader calls on_load() once after create - // (first load and after a reload swap). Self-initialize from the - // default config path so the plugin is ready without host-provided - // wiring; idempotent via isInitialized(). + void configure(std::filesystem::path path) + { + configPath_ = std::move(path); + } + + void stageState(std::string state) + { + pendingState_ = std::move(state); + } + + [[nodiscard]] bool ready() const noexcept { return ready_; } + + // Configuration and state are supplied before on_load(). Keep all + // fallible activation work here so void_plugin_ready can make the + // manager's eventual swap transactional. void on_load() override { - if (!isInitialized()) { - (void)initialize(ConfigLoader::getDefaultConfigPath()); + ready_ = false; + const auto path = configPath_.empty() + ? ConfigLoader::getDefaultConfigPath() + : configPath_; + if (auto result = initialize(path); !result) { + return; + } + if (pendingState_.has_value()) { + if (auto result = restoreAfterHotReload(*pendingState_); !result) { + (void)shutdown(); + return; + } + pendingState_.reset(); + } + ready_ = true; + } + + void on_unload() override + { + ready_ = false; + if (isInitialized()) { + (void)shutdown(); } } + + private: + std::filesystem::path configPath_; + std::optional pendingState_; + bool ready_{false}; }; } // namespace Echoion::Core @@ -80,6 +119,23 @@ extern "C" .description = "Echoion TeamSpeak music bot core"}; } + void void_plugin_configure(void* instance, const char* config) + { + auto* plugin = dynamic_cast( + static_cast(instance)); + if (plugin != nullptr) { + plugin->configure(config != nullptr ? std::filesystem::path{config} + : std::filesystem::path{}); + } + } + + int void_plugin_ready(void* instance) + { + auto* plugin = dynamic_cast( + static_cast(instance)); + return plugin != nullptr && plugin->ready() ? 0 : -1; + } + // v2 state protocol — survives layout changes across plugin versions. std::uint32_t void_plugin_state_version() { @@ -109,22 +165,12 @@ extern "C" int void_plugin_deserialize_state(void* instance, const char* json, std::uint32_t /*from_version*/) { - auto* core = dynamic_cast( + auto* plugin = dynamic_cast( static_cast(instance)); - if (!core || !json) { + if (!plugin || !json) { return -1; } - // reload() transfers state before on_load(), so the freshly-created - // instance is not yet initialized — bring it up first, then restore. - // Idempotent: a no-op once initialized. - if (!core->isInitialized()) { - auto initResult = - core->initialize(Echoion::Core::ConfigLoader::getDefaultConfigPath()); - if (!initResult) { - return -1; - } - } - auto result = core->restoreAfterHotReload(std::string(json)); - return result ? 0 : -1; + plugin->stageState(json); + return 0; } } diff --git a/src/ListeningRoomManager.cpp b/src/ListeningRoomManager.cpp new file mode 100644 index 0000000..c3fea23 --- /dev/null +++ b/src/ListeningRoomManager.cpp @@ -0,0 +1,457 @@ +#include "echoion/core/ListeningRoomManager.hpp" +#include "echoion/core/ListeningRoomName.hpp" + +#include "echoion/core/NetworkClient.hpp" + +#include + +#include +#include + +namespace Echoion::Core +{ + ListeningRoomManager::ListeningRoomManager( + std::shared_ptr network, Api::ConfigManager& config, + Void::EventBus::EventBus& events) + : network_(std::move(network)), config_(config), events_(events) + { + } + + ListeningRoomManager::~ListeningRoomManager() { shutdown(); } + + void ListeningRoomManager::setPluginInterface( + Api::PluginInterfacePtr plugin) + { + std::lock_guard lock(mutex_); + plugin_ = std::move(plugin); + } + + void ListeningRoomManager::setChangeCallback(std::function callback) + { + std::lock_guard lock(mutex_); + changeCallback_ = std::move(callback); + } + + void ListeningRoomManager::notifyChanged() const + { + if (changeCallback_) changeCallback_(); + } + + Api::ServerConfig ListeningRoomManager::serverConfigFor( + const std::string& roomName) const + { + const auto& source = config_.getTeamSpeak(); + Api::ServerConfig result; + result.address = source.address; + result.port = source.port; + result.serverPassword = source.serverPassword; + result.nickname = source.nickname.empty() ? "Echoion" : source.nickname; + result.nickname += "/" + roomName; + result.defaultChannelId = source.defaultChannelId; + result.channelPassword = source.channelPassword; + result.adminGroups = source.adminGroups; + result.djGroups = source.djGroups; + result.bannedGroups = source.bannedGroups; + return result; + } + + Api::Result ListeningRoomManager::create( + std::string name, uint64_t ownerId) + { + auto validName = validateListeningRoomName(std::move(name)); + if (!validName || ownerId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + validName ? "room owner is required" : validName.error().message); + } + name = std::move(*validName); + const auto key = canonicalListeningRoomName(name); + std::lock_guard lock(mutex_); + if (!plugin_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "TeamSpeak host is not available"); + } + if (rooms_.contains(key)) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "listening room already exists"); + } + if (membership_.contains(ownerId)) { + return Api::fail(Api::ErrorCode::AlreadyExists, + "owner already belongs to another listening room"); + } + + Api::IPluginInterface::AudioStreamOptions streamOptions; + streamOptions.name = name; + streamOptions.server = serverConfigFor(name); + streamOptions.recipients = {ownerId}; + auto stream = plugin_->createAudioStream(streamOptions); + if (!stream) return std::unexpected(stream.error()); + + auto room = std::make_unique(); + room->name = name; + room->ownerId = ownerId; + room->streamId = *stream; + room->members.insert(ownerId); + room->music = std::make_unique(); + room->music->setConfigManager(&config_); + room->music->setEventBus(&events_); + room->music->setAudioDataCallback( + [plugin = plugin_, streamId = *stream](std::span data) { + if (!data.empty()) { + std::ignore = plugin->sendAudioDataToStream(streamId, data); + } + }); + room->music->setClientInfoCallback( + [plugin = plugin_](uint64_t clientId) + -> std::optional> { + auto client = plugin->getClient(clientId); + if (!client || !client->has_value() || + !client->value().uniqueIdentifier) return std::nullopt; + return std::pair{*client->value().uniqueIdentifier, + client->value().nickname}; + }); + if (auto initialized = room->music->initialize(network_, nullptr); + !initialized) { + std::ignore = plugin_->destroyAudioStream(*stream); + return std::unexpected(initialized.error()); + } + membership_[ownerId] = key; + rooms_.emplace(key, std::move(room)); + Void::Log::info("ListeningRooms", "Created room '{}' for client {}", + name, ownerId); + notifyChanged(); + return {}; + } + + Api::Result ListeningRoomManager::remove( + const std::string& name, uint64_t requesterId) + { + std::unique_ptr room; + Api::PluginInterfacePtr plugin; + { + std::lock_guard lock(mutex_); + auto iterator = rooms_.find(canonicalListeningRoomName(name)); + if (iterator == rooms_.end()) + return Api::fail(Api::ErrorCode::NotFound, "listening room not found"); + if (iterator->second->ownerId != requesterId) + return Api::fail(Api::ErrorCode::PermissionDenied, + "only the room owner may delete it"); + for (auto member : iterator->second->members) membership_.erase(member); + room = std::move(iterator->second); + rooms_.erase(iterator); + plugin = plugin_; + } + room->music->shutdown(); + notifyChanged(); + if (plugin) return plugin->destroyAudioStream(room->streamId); + return {}; + } + + Api::Result ListeningRoomManager::refreshRecipients(Room& room) + { + if (!plugin_) return Api::fail(Api::ErrorCode::ServiceUnavailable, + "TeamSpeak host is not available"); + return plugin_->setAudioStreamRecipients(room.streamId, + {room.members.begin(), room.members.end()}); + } + + Api::Result ListeningRoomManager::join( + const std::string& name, uint64_t clientId) + { + { + std::lock_guard lock(mutex_); + const auto* destination = findLocked(name); + if (!destination) return Api::fail(Api::ErrorCode::NotFound, + "listening room not found"); + const auto current = membership_.find(clientId); + if (current != membership_.end()) { + const auto currentRoom = rooms_.find(current->second); + if (currentRoom != rooms_.end() && + currentRoom->second.get() == destination) return {}; + } + } + if (auto left = leave(clientId); !left) return left; + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, + "listening room not found"); + room->members.insert(clientId); + for (const auto& [key, candidate] : rooms_) { + if (candidate.get() == room) { + membership_[clientId] = key; + break; + } + } + auto refreshed = refreshRecipients(*room); + notifyChanged(); + return refreshed; + } + + Api::Result ListeningRoomManager::leave(uint64_t clientId) + { + std::unique_ptr emptyRoom; + Api::PluginInterfacePtr plugin; + { + std::lock_guard lock(mutex_); + auto membership = membership_.find(clientId); + if (membership == membership_.end()) return {}; + const auto key = membership->second; + auto iterator = rooms_.find(key); + membership_.erase(membership); + if (iterator == rooms_.end()) return {}; + auto& room = *iterator->second; + room.members.erase(clientId); + if (room.ownerId == clientId && !room.members.empty()) { + room.ownerId = *room.members.begin(); + Void::Log::info("ListeningRooms", + "Transferred room '{}' ownership to client {}", + room.name, room.ownerId); + } + if (room.members.empty()) { + emptyRoom = std::move(iterator->second); + rooms_.erase(iterator); + plugin = plugin_; + } else { + auto refreshed = refreshRecipients(room); + notifyChanged(); + return refreshed; + } + } + emptyRoom->music->shutdown(); + Void::Log::info("ListeningRooms", "Removed empty room '{}'", + emptyRoom->name); + notifyChanged(); + return plugin ? plugin->destroyAudioStream(emptyRoom->streamId) + : Api::Result{}; + } + + Api::Result ListeningRoomManager::play( + const std::string& name, std::string query, uint64_t clientId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, + "listening room not found"); + if (!room->members.contains(clientId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto result = room->music->play(query, clientId); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::pause( + const std::string& name, uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto result = room->music->pause(); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::resume( + const std::string& name, uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto result = room->music->resume(); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::stop( + const std::string& name, uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto result = room->music->stop(); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::skip( + const std::string& name, uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto result = room->music->skip(); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::removeQueueEntry( + const std::string& name, uint64_t queueId, uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto queue = room->music->getQueue(); + if (!queue) return std::unexpected(queue.error()); + const auto iterator = std::ranges::find(*queue, queueId, &Api::QueueEntry::queueId); + if (iterator == queue->end()) return Api::fail( + Api::ErrorCode::NotFound, "room queue entry not found"); + auto result = room->music->removeFromQueue( + static_cast(std::distance(queue->begin(), iterator))); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::moveQueueEntry( + const std::string& name, uint64_t queueId, uint32_t newPosition, + uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto queue = room->music->getQueue(); + if (!queue) return std::unexpected(queue.error()); + const auto iterator = std::ranges::find(*queue, queueId, &Api::QueueEntry::queueId); + if (iterator == queue->end()) return Api::fail( + Api::ErrorCode::NotFound, "room queue entry not found"); + auto result = room->music->moveInQueue( + static_cast(std::distance(queue->begin(), iterator)), newPosition); + if (result) notifyChanged(); + return result; + } + + Api::Result ListeningRoomManager::clearQueue( + const std::string& name, uint64_t requesterId) + { + std::lock_guard lock(mutex_); + auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + if (!room->members.contains(requesterId)) return Api::fail( + Api::ErrorCode::PermissionDenied, "join the room before controlling it"); + auto result = room->music->clearQueue(); + if (result) notifyChanged(); + return result; + } + + Api::Result> + ListeningRoomManager::queue(const std::string& name) const + { + std::lock_guard lock(mutex_); + const auto* room = findLocked(name); + if (!room) return Api::fail(Api::ErrorCode::NotFound, "room not found"); + return room->music->getQueue(); + } + + std::vector + ListeningRoomManager::list() const + { + std::lock_guard lock(mutex_); + std::vector result; + result.reserve(rooms_.size()); + for (const auto& [key, room] : rooms_) { + std::ignore = key; + auto state = room->music->getPlaybackState(); + auto queue = room->music->getQueue(); + result.push_back(RoomSummary{.name = room->name, + .ownerId = room->ownerId, + .members = {room->members.begin(), room->members.end()}, + .isPlaying = state && state->isPlaying, + .isPaused = state && state->isPaused, + .queueSize = queue ? queue->size() : 0}); + } + return result; + } + + std::optional ListeningRoomManager::roomForClient( + uint64_t clientId) const + { + std::lock_guard lock(mutex_); + const auto iterator = membership_.find(clientId); + if (iterator == membership_.end()) { + return std::nullopt; + } + const auto room = rooms_.find(iterator->second); + return room == rooms_.end() ? std::nullopt + : std::optional{room->second->name}; + } + + std::vector + ListeningRoomManager::snapshot() const + { + std::lock_guard lock(mutex_); + std::vector result; + result.reserve(rooms_.size()); + for (const auto& [key, room] : rooms_) { + std::ignore = key; + result.push_back(PersistedRoom{ + .name = room->name, .ownerId = room->ownerId, + .members = {room->members.begin(), room->members.end()}, + .state = room->music->getStateForHotReload()}); + } + return result; + } + + Api::Result ListeningRoomManager::restore( + const std::vector& rooms) + { + for (const auto& saved : rooms) { + if (auto created = create(saved.name, saved.ownerId); !created) { + return std::unexpected(created.error()); + } + for (auto member : saved.members) { + if (member != saved.ownerId) { + if (auto joined = join(saved.name, member); !joined) + return std::unexpected(joined.error()); + } + } + std::lock_guard lock(mutex_); + auto* room = findLocked(saved.name); + if (!room) return Api::fail(Api::ErrorCode::UnknownError, + "restored room disappeared"); + if (auto restored = room->music->restoreFromHotReload(saved.state); + !restored) return std::unexpected(restored.error()); + } + return {}; + } + + ListeningRoomManager::Room* ListeningRoomManager::findLocked( + const std::string& name) + { + auto iterator = rooms_.find(canonicalListeningRoomName(name)); + return iterator == rooms_.end() ? nullptr : iterator->second.get(); + } + + const ListeningRoomManager::Room* ListeningRoomManager::findLocked( + const std::string& name) const + { + auto iterator = rooms_.find(canonicalListeningRoomName(name)); + return iterator == rooms_.end() ? nullptr : iterator->second.get(); + } + + + void ListeningRoomManager::shutdown() + { + std::map> rooms; + Api::PluginInterfacePtr plugin; + { + std::lock_guard lock(mutex_); + rooms.swap(rooms_); + membership_.clear(); + plugin = plugin_; + } + for (auto& [name, room] : rooms) { + std::ignore = name; + room->music->shutdown(); + if (plugin) std::ignore = plugin->destroyAudioStream(room->streamId); + } + } +} diff --git a/tests/test_listening_room_state.cpp b/tests/test_listening_room_state.cpp new file mode 100644 index 0000000..59329f9 --- /dev/null +++ b/tests/test_listening_room_state.cpp @@ -0,0 +1,41 @@ +#include "echoion/core/state/StateSerializer.hpp" +#include "echoion/core/ListeningRoomName.hpp" + +#include + +int main() +{ + const auto normalized = Echoion::Core::validateListeningRoomName(" Focus Room "); + if (!normalized || *normalized != "Focus Room" || + Echoion::Core::canonicalListeningRoomName(*normalized) != "focus room" || + Echoion::Core::validateListeningRoomName("\n\t") || + Echoion::Core::validateListeningRoomName(std::string(49, 'x'))) { + std::cerr << "listening-room name validation failed\n"; + return 1; + } + Echoion::Core::StateV1 state; + Echoion::Core::StateV1::ListeningRoomState room; + room.name = "focus"; + room.ownerId = 17; + room.members = {17, 23}; + room.playback.isPlaying = true; + room.playback.position = std::chrono::milliseconds{42000}; + room.playbackPositionMs = 42000; + room.autoplay = true; + state.listeningRooms.push_back(std::move(room)); + + const auto blob = Echoion::Core::StateSerializer::serialize(state); + const auto restored = Echoion::Core::StateSerializer::deserialize(blob); + if (!restored || restored->listeningRooms.size() != 1) { + std::cerr << "listening-room state did not round-trip\n"; + return 1; + } + const auto& actual = restored->listeningRooms.front(); + if (actual.name != "focus" || actual.ownerId != 17 || + actual.members != std::vector({17, 23}) || + actual.playbackPositionMs != 42000 || !actual.autoplay) { + std::cerr << "restored listening-room fields differ\n"; + return 1; + } + return 0; +}