From 39aff68d8d79d3e5d5c92e0c10f20d7fc4c6a4e0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 15 Jul 2026 19:49:57 +0300 Subject: [PATCH] Update Signed-off-by: faumaray --- CMakeLists.txt | 23 +- include/echoion/core/CommandManager.hpp | 5 + include/echoion/core/Core.hpp | 42 +- include/echoion/core/ListeningRoomManager.hpp | 106 -- include/echoion/core/ListeningRoomName.hpp | 37 - include/echoion/core/MusicManager.hpp | 10 +- include/echoion/core/PluginHost.hpp | 59 + include/echoion/core/RpcDtos.hpp | 63 +- .../core/TeamSpeakDirectoryService.hpp | 54 + include/echoion/core/YouTubeClient.hpp | 1 - include/echoion/core/commands/Commands.hpp | 1 - include/echoion/core/commands/RoomCommand.hpp | 218 --- include/echoion/core/detail/RpcValidation.hpp | 31 + include/echoion/core/sources/SourceRouter.hpp | 5 +- include/echoion/core/state/StateVersions.hpp | 14 +- src/CommandManager.cpp | 30 +- src/Core.cpp | 265 ++-- src/CoreRpcHandlers.cpp | 1300 +++++++++-------- src/Database.cpp | 99 +- src/ListeningRoomManager.cpp | 457 ------ src/MusicManager.cpp | 9 +- src/PluginHost.cpp | 400 +++++ src/RpcServer.cpp | 15 +- src/TeamSpeakDirectoryService.cpp | 265 ++++ src/sources/SourceRouter.cpp | 74 +- src/state/StateSerializer.cpp | 33 +- tests/test_extension_state.cpp | 34 + tests/test_listening_room_state.cpp | 41 - tests/test_teamspeak_directory.cpp | 188 +++ 29 files changed, 2061 insertions(+), 1818 deletions(-) delete mode 100644 include/echoion/core/ListeningRoomManager.hpp delete mode 100644 include/echoion/core/ListeningRoomName.hpp create mode 100644 include/echoion/core/PluginHost.hpp create mode 100644 include/echoion/core/TeamSpeakDirectoryService.hpp delete mode 100644 include/echoion/core/commands/RoomCommand.hpp create mode 100644 include/echoion/core/detail/RpcValidation.hpp delete mode 100644 src/ListeningRoomManager.cpp create mode 100644 src/PluginHost.cpp create mode 100644 src/TeamSpeakDirectoryService.cpp create mode 100644 tests/test_extension_state.cpp delete mode 100644 tests/test_listening_room_state.cpp create mode 100644 tests/test_teamspeak_directory.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index de20f57..531fdef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -220,13 +220,22 @@ install(FILES ) 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) + add_executable(echoion_core_extension_state_tests + tests/test_extension_state.cpp) + target_include_directories(echoion_core_extension_state_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(echoion_core_extension_state_tests PRIVATE EchoionCore) + add_test(NAME echoion_core_extension_state_tests + COMMAND echoion_core_extension_state_tests) + + add_executable(echoion_core_teamspeak_directory_tests + tests/test_teamspeak_directory.cpp + src/TeamSpeakDirectoryService.cpp) + target_include_directories(echoion_core_teamspeak_directory_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore) + add_test(NAME echoion_core_teamspeak_directory_tests + COMMAND echoion_core_teamspeak_directory_tests) endif() option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF) diff --git a/include/echoion/core/CommandManager.hpp b/include/echoion/core/CommandManager.hpp index 2b462af..81de1a1 100644 --- a/include/echoion/core/CommandManager.hpp +++ b/include/echoion/core/CommandManager.hpp @@ -120,6 +120,9 @@ namespace Echoion::Core getCommand(std::string_view name) const; [[nodiscard]] std::vector> getAllCommands() const; + [[nodiscard]] bool registerExternalCommand( + std::string owner, std::string primaryName, CommandPtr command); + void unregisterExternalCommands(std::string_view owner); // Get commands visible to a specific client (for help) [[nodiscard]] std::vector> @@ -202,6 +205,8 @@ namespace Echoion::Core // List for generating help: {"play", PlayCommand} std::vector uniqueCommands_; + std::map, std::less<>> + externalCommands_; mutable std::mutex mutex_; diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index feb36ec..8ac2b39 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -12,12 +12,12 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include #include @@ -35,7 +35,8 @@ namespace Void::Logging namespace Echoion::Core { - class ListeningRoomManager; + class PluginHost; + class TeamSpeakDirectoryService; // Main Core implementation of ICoreInterface class Core : public Api::ICoreInterface @@ -169,10 +170,10 @@ namespace Echoion::Core void setupEventBusSubscriptions() noexcept; // Fetch an online client's avatar bytes (TS local cache, then the - // myTeamSpeak URL, then a legacy file-transfer download) and persist - // them — and the myTS URL — to the database keyed by uid. Returns - // {contentType, bytes} on success. Web-agnostic; used by both the - // avatar HTTP provider and the background warmer. + // myTeamSpeak URL, then a legacy file-transfer download) and + // persist them — and the myTS URL — to the database keyed by uid. + // Returns {contentType, bytes} on success. Web-agnostic; used by + // both the avatar HTTP provider and the background warmer. [[nodiscard]] std::optional> fetchClientAvatarBytes(const std::string& uid, uint64_t clientId); @@ -192,9 +193,9 @@ 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_; + std::shared_ptr extensionPlugins_; + std::shared_ptr directoryService_; Api::PluginInterfacePtr pluginInterface_; // State @@ -210,12 +211,6 @@ namespace Echoion::Core std::vector eventCallbacks_; mutable std::mutex eventMutex_; - // Admin / DJ tracking (RPC clients whose TeamSpeak identity is in - // a configured teamspeak.adminGroups / djGroups server group). - std::vector adminClients_; - std::vector djClients_; - mutable std::mutex adminMutex_; - // Authenticated RPC client -> stable TS uid + nickname, resolved // at token auth. Keys per-user features (favorites, vote-skip). struct RpcIdentity { @@ -226,10 +221,12 @@ namespace Echoion::Core mutable std::mutex rpcIdentityMutex_; [[nodiscard]] std::optional rpcIdentity(uint64_t clientId) const; + [[nodiscard]] bool hasLiveTeamSpeakRole( + uint64_t clientId, + const std::vector& configuredGroups) const; // Full identity behind an RPC token: uid, display nickname and - // admin standing. Shared by token auth, IP autologin and the - // watch-together identity resolver. + // admin standing. Shared by token auth and IP autologin. struct TokenIdentity { std::string uid; std::string nickname; @@ -238,8 +235,9 @@ namespace Echoion::Core }; [[nodiscard]] std::optional identityForToken(const std::string& token); - // Mark an RPC connection authenticated as `identity` (auth set, - // admin list, per-client identity map). + // Mark an RPC connection authenticated as `identity` and retain its + // stable TeamSpeak identity. Roles are checked live for each + // request. void registerRpcAuth(uint64_t clientId, const TokenIdentity& identity); // Guards RestartWebInterface against overlapping restarts. @@ -249,7 +247,8 @@ namespace Echoion::Core std::shared_ptr database_; // Background avatar cache warmer + the uids already cached this - // session (so we don't re-download an unchanged avatar every cycle). + // session (so we don't re-download an unchanged avatar every + // cycle). std::jthread avatarWarmer_; std::unordered_set warmedUids_; @@ -257,9 +256,8 @@ namespace Echoion::Core std::shared_ptr rpcServer_; #ifdef ECHOION_WITH_WEB - // Browser web interface: serves the static UI and hosts the - // independent sync-watch WebSocket. Bot control from the browser - // goes straight to the RPC server, so this holds no bot handles. + // Browser web interface: serves the static dashboard and same-origin + // RPC bridge. Bot control still terminates at the RPC server. std::shared_ptr webServer_; #endif diff --git a/include/echoion/core/ListeningRoomManager.hpp b/include/echoion/core/ListeningRoomManager.hpp deleted file mode 100644 index ea6c767..0000000 --- a/include/echoion/core/ListeningRoomManager.hpp +++ /dev/null @@ -1,106 +0,0 @@ -#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 deleted file mode 100644 index 2c1ee1d..0000000 --- a/include/echoion/core/ListeningRoomName.hpp +++ /dev/null @@ -1,37 +0,0 @@ -#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/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 19ee323..03d7be7 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -80,7 +80,15 @@ namespace Echoion::Core // Re-apply the source-chain settings (order, cooldown, instance // lists) after a config reload. void applySourcesConfig(const Api::SourcesConfig& sources); - + void addTrackSource(std::shared_ptr source); + void setSharedYouTubeClient(std::shared_ptr client) + { + youTubeClient_ = std::move(client); + } + [[nodiscard]] std::shared_ptr sharedYouTubeClient() const + { + return youTubeClient_; + } // Re-apply bot settings (queue size, track timeout, playlist // import gate) after a config reload. Does not touch the live // volume. diff --git a/include/echoion/core/PluginHost.hpp b/include/echoion/core/PluginHost.hpp new file mode 100644 index 0000000..86d6360 --- /dev/null +++ b/include/echoion/core/PluginHost.hpp @@ -0,0 +1,59 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + class CommandManager; + class MusicManager; + class ITrackSource; + + class PluginHost final : public std::enable_shared_from_this + { + public: + PluginHost(CommandManager& commands, std::shared_ptr music, + std::function isAdmin, + std::function)> mediaSink = {}); + ~PluginHost(); + + void loadDirectory(const std::filesystem::path& directory); + void setChangeCallback(std::function callback); + void dispatch(const Api::PluginEvent& event) const; + [[nodiscard]] Api::Result call( + std::string_view plugin, std::string_view method, + std::string params, uint64_t clientId) const; + [[nodiscard]] std::vector webAssets() const; + [[nodiscard]] std::vector names() const; + struct State { + std::string name; + std::string json; + std::uint32_t version{}; + }; + [[nodiscard]] std::vector snapshotStates() const; + void restoreStates(const std::vector& states); + + private: + void publish(std::string_view name); + void unpublish(std::string_view name); + void notifyChanged() const; + + CommandManager& commands_; + std::shared_ptr music_; + std::function isAdmin_; + std::function)> mediaSink_; + Void::Plugin::PluginManager plugins_; + Void::Plugin::ReloadCallbackId reloadCallback_{}; + mutable std::mutex mutex_; + std::vector> sources_; + std::function changeCallback_; + }; +} diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp index 452cedb..9732f9b 100644 --- a/include/echoion/core/RpcDtos.hpp +++ b/include/echoion/core/RpcDtos.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -85,26 +86,6 @@ 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 { @@ -201,19 +182,19 @@ 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 Capabilities { + bool plugins = false; + bool webExtensions = false; }; - struct ListeningRoomList { - std::vector rooms; - std::optional currentRoom; + struct PluginCallRequest { + std::string plugin; + std::string method; + std::string params; + }; + + struct PluginExtensions { + std::vector assets; }; struct Autoplay { @@ -227,26 +208,6 @@ namespace Echoion::Core::Dto std::string language; }; - // Custom emoji metadata (name + mime); the image itself is served at - // GET /emoji/, not inlined here. - struct CustomEmojiDto { - std::string name; - std::string mime; - std::string addedBy; - }; - struct CustomEmojiList { - std::vector emojis; - }; - // AddCustomEmoji request: name + mime + base64-encoded image bytes. - struct AddEmojiRequest { - std::string name; - std::string mime; - std::string dataBase64; - }; - struct EmojiNameRequest { - std::string name; - }; - struct QueuedResponse { bool success = true; std::uint64_t queueId = 0; diff --git a/include/echoion/core/TeamSpeakDirectoryService.hpp b/include/echoion/core/TeamSpeakDirectoryService.hpp new file mode 100644 index 0000000..8918ec4 --- /dev/null +++ b/include/echoion/core/TeamSpeakDirectoryService.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + // One authoritative, event-refreshed TeamSpeak topology cache. The public + // serializer is deliberately structural: it has no fields for UIDs, groups, + // database IDs, addresses, or query clients, so private data cannot leak by + // accidentally toggling a flag at the HTTP boundary. + class TeamSpeakDirectoryService + { + public: + + struct Snapshot { + Api::ServerInfo server; + std::vector channels; + std::vector clients; + bool connected = false; + std::uint64_t revision = 0; + }; + + void setPluginInterface(Api::PluginInterfacePtr plugin); + [[nodiscard]] Api::Result refresh(); + void handleEvent(Api::PluginEventType type); + + [[nodiscard]] Snapshot snapshot() const; + [[nodiscard]] Void::Json::Value publicJson() const; + [[nodiscard]] Void::Json::Value adminJson() const; + + // TeamSpeak stores a sibling's predecessor id in channel_order. + // This helper turns that linked-list representation into display + // order and deterministically appends malformed/orphaned entries. + [[nodiscard]] static std::vector + orderChannels(std::vector channels); + + private: + + mutable std::mutex mutex_; + Api::PluginInterfacePtr plugin_; + Snapshot snapshot_; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/YouTubeClient.hpp b/include/echoion/core/YouTubeClient.hpp index 4efcb84..febc1e0 100644 --- a/include/echoion/core/YouTubeClient.hpp +++ b/include/echoion/core/YouTubeClient.hpp @@ -119,7 +119,6 @@ namespace Echoion::Core // Get best audio stream URL using yt-dlp [[nodiscard]] Api::Result getAudioStreamUrl(std::string_view videoId); - // Resolve a stream URL for any yt-dlp-supported page URL // (SoundCloud, Bandcamp, VK, radio pages, ...). When useProxy is // false the configured proxy is explicitly bypassed with a diff --git a/include/echoion/core/commands/Commands.hpp b/include/echoion/core/commands/Commands.hpp index 6ee5e6e..6b5ad25 100644 --- a/include/echoion/core/commands/Commands.hpp +++ b/include/echoion/core/commands/Commands.hpp @@ -19,7 +19,6 @@ #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 deleted file mode 100644 index 9c5a09d..0000000 --- a/include/echoion/core/commands/RoomCommand.hpp +++ /dev/null @@ -1,218 +0,0 @@ -#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/detail/RpcValidation.hpp b/include/echoion/core/detail/RpcValidation.hpp new file mode 100644 index 0000000..cc5c648 --- /dev/null +++ b/include/echoion/core/detail/RpcValidation.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Echoion::Core::Detail +{ + [[nodiscard]] inline std::optional + uintField(const Void::Json::Value& object, std::string_view key) + { + const auto* value = object.find(key); + if (!value || !value->is_number()) { + return std::nullopt; + } + + const auto number = value->as_number(); + // A double equal to 2^64 is what uint64_t::max() rounds to, so use + // an exclusive 2^64 bound before converting. Floating-to-integer + // conversion outside the destination range is undefined behavior. + constexpr double kUint64Limit = 18446744073709551616.0; + if (!std::isfinite(number) || number < 0.0 || + std::trunc(number) != number || number >= kUint64Limit) { + return std::nullopt; + } + return static_cast(number); + } +} // namespace Echoion::Core::Detail diff --git a/include/echoion/core/sources/SourceRouter.hpp b/include/echoion/core/sources/SourceRouter.hpp index 843e39b..c56c321 100644 --- a/include/echoion/core/sources/SourceRouter.hpp +++ b/include/echoion/core/sources/SourceRouter.hpp @@ -21,6 +21,7 @@ namespace Echoion::Core public: void setSources(std::vector> sources); + void addSource(std::shared_ptr source); // Reorder/enable per config; names not found are ignored, sources // not named are dropped from the chain. @@ -59,9 +60,9 @@ namespace Echoion::Core std::chrono::steady_clock::time_point cooldownUntil{}; }; - [[nodiscard]] std::vector + [[nodiscard]] std::vector> candidatesFor(const std::string& query, bool needSearch); - void reportFailure(SourceState& state); + void reportFailure(const std::shared_ptr& source); mutable std::mutex mutex_; std::vector> allSources_; diff --git a/include/echoion/core/state/StateVersions.hpp b/include/echoion/core/state/StateVersions.hpp index e5e688a..3c04098 100644 --- a/include/echoion/core/state/StateVersions.hpp +++ b/include/echoion/core/state/StateVersions.hpp @@ -46,16 +46,10 @@ namespace Echoion::Core std::string lastActivity; // ISO 8601 }; - struct ListeningRoomState { + struct ExtensionPluginState { 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; + std::string json; + std::uint32_t version = 0; }; // Main state @@ -65,7 +59,7 @@ namespace Echoion::Core bool autoplay = false; // Radio mode on/off (persisted for restart) std::vector queue; std::vector sessions; - std::vector listeningRooms; + std::vector extensionPlugins; // Version info uint32_t version = 1; diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index c35b6e9..bc710c8 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -614,6 +614,35 @@ namespace Echoion::Core permissionCheck_ = std::move(func); } + bool CommandManager::registerExternalCommand( + std::string owner, std::string primaryName, CommandPtr command) + { + if (owner.empty() || primaryName.empty() || !command) return false; + std::lock_guard lock(mutex_); + if (commands_.contains(primaryName)) return false; + commands_[primaryName] = command; + uniqueCommands_.push_back({std::move(primaryName), command}); + for (auto alias : command->getAliases()) { + if (!commands_.contains(alias)) commands_[std::string(alias)] = command; + } + externalCommands_[std::move(owner)].push_back(std::move(command)); + return true; + } + + void CommandManager::unregisterExternalCommands(std::string_view owner) + { + std::lock_guard lock(mutex_); + auto found = externalCommands_.find(owner); + if (found == externalCommands_.end()) return; + const auto owns = [&](const CommandPtr& command) { + return std::ranges::find(found->second, command) != found->second.end(); + }; + std::erase_if(commands_, [&](const auto& entry) { return owns(entry.second); }); + std::erase_if(uniqueCommands_, + [&](const CommandEntry& entry) { return owns(entry.instance); }); + externalCommands_.erase(found); + } + void CommandManager::setServerConfig(const Api::AppConfig& config) { std::lock_guard lock(mutex_); @@ -640,7 +669,6 @@ 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 0a5ffb7..58485d7 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -1,8 +1,9 @@ #include "PluginTypes.hpp" #include "echoion/core/ConfigLoader.hpp" #include "echoion/core/Core.hpp" -#include "echoion/core/ListeningRoomManager.hpp" +#include "echoion/core/PluginHost.hpp" #include "echoion/core/RpcDtos.hpp" +#include "echoion/core/TeamSpeakDirectoryService.hpp" #include "echoion/core/i18n/Localization.hpp" #include "echoion/core/state/StateSerializer.hpp" #include "echoion/core/state/StateVersions.hpp" @@ -30,8 +31,9 @@ namespace Echoion::Core { namespace { - // Decode a base64 string to raw bytes (used for custom emoji images - // served over HTTP). Returns empty on malformed input. + // Decode cached avatar bytes before serving them over HTTP. Returns + // empty on malformed input. +#ifdef ECHOION_WITH_WEB std::string decodeBase64(const std::string& in) { static constexpr auto val = [](char c) -> int { @@ -73,6 +75,7 @@ namespace Echoion::Core } return out; } +#endif // Encode raw bytes to base64 (used to persist TeamSpeak avatar images // in the database so they survive the client going @@ -288,8 +291,7 @@ namespace Echoion::Core if (!musicResult) { return std::unexpected(musicResult.error()); } - listeningRooms_ = std::make_shared( - networkClient_, configManager_, eventBus_); + directoryService_ = std::make_shared(); // Initialize command manager commandManager_ = std::make_unique(); @@ -484,31 +486,73 @@ namespace Echoion::Core std::format("RPC server started on port {}", rpcPort)); setupRpcHandlers(); setupEventBusSubscriptions(); - if (listeningRooms_) { - listeningRooms_->setChangeCallback([server = rpcServer_] { - server->broadcastEvent("listening_rooms.updated", "{}"); - }); - } } + extensionPlugins_ = std::make_shared( + *commandManager_, musicManager_, + [this](uint64_t clientId) { return isAdmin(clientId); }); + if (rpcServer_) { + extensionPlugins_->setChangeCallback([server = rpcServer_] { + server->broadcastEvent("plugins.updated", "{}"); + }); + } + extensionPlugins_->loadDirectory(configPath.parent_path() / "plugins"); + #ifdef ECHOION_WITH_WEB // Browser web interface (independent of the RPC transport above). if (config_.web.enabled) { webServer_ = std::make_shared(); - // Watch-together control requires a signed-in user; the web - // server validates tokens through Core (it has no DB handle). - webServer_->setIdentityResolver( - [this](const std::string& token) - -> std::optional { - auto identity = identityForToken(token); - if (!identity) { - return std::nullopt; + webServer_->setDashboardProvider([this] { + using Void::Json::Value; + auto dashboard = directoryService_->publicJson(); + auto playback = Void::Json::object({{"isPlaying", Value{false}}, + {"isPaused", Value{false}}, + {"positionMs", Value{0LL}}, + {"volume", Value{0.0}}, + {"track", Value{nullptr}}}); + if (musicManager_) { + if (auto state = musicManager_->getPlaybackState(); state) { + auto& out = playback.as_object(); + out.clear(); + out.emplace_back("isPlaying", Value{state->isPlaying}); + out.emplace_back("isPaused", Value{state->isPaused}); + out.emplace_back("positionMs", + Value{static_cast( + state->position.count())}); + out.emplace_back( + "volume", + Value{static_cast(state->volume)}); + if (state->currentTrack) { + const auto& track = state->currentTrack->track; + out.emplace_back( + "track", + Void::Json::object( + {{"id", Value{track.id}}, + {"title", Value{track.title}}, + {"artist", Value{track.artist}}, + {"album", Value{track.album}}, + {"thumbnailUrl", + track.thumbnailUrl + ? Value{*track.thumbnailUrl} + : Value{nullptr}}, + {"durationMs", + track.duration + ? Value{static_cast( + track.duration->count())} + : Value{nullptr}}})); + } else { + out.emplace_back("track", Value{nullptr}); + } } - return Web::WatchSessionManager::Identity{ - .uid = identity->uid, - .nickname = identity->nickname, - .isAdmin = identity->isAdmin}; - }); + } + dashboard.as_object().emplace_back("playback", + std::move(playback)); + std::string body = Void::Json::serialize(dashboard); + return Web::HttpServer::DashboardSnapshot{ + .body = body, + .etag = std::format("\"{:x}\"", + std::hash{}(body))}; + }); // Avatar images for GET /avatar/: resolve the uid to an online // client and serve its TeamSpeak avatar. Sources, in order: the TS // client's own cache (in-view clients), an active file-transfer @@ -582,31 +626,12 @@ namespace Echoion::Core // Offline or live miss: persisted bytes / stored-url. return fromStore(uid); }); - // Custom emoji images for GET /emoji/: decode the stored - // base64 payload to raw bytes with its mime type. - webServer_->setEmojiProvider( - [this](const std::string& name) - -> std::optional { - if (!database_) { - return std::nullopt; - } - auto emoji = database_->getCustomEmoji(name); - if (!emoji || !emoji->has_value()) { - return std::nullopt; - } - auto bytes = decodeBase64((*emoji)->dataBase64); - if (bytes.empty()) { - return std::nullopt; - } - return Web::HttpServer::AvatarImage{ - .contentType = (*emoji)->mime, - .bytes = std::move(bytes)}; - }); Web::HttpServer::Config webCfg; webCfg.port = config_.web.port; webCfg.bindAddress = config_.web.bindAddress; webCfg.webRoot = config_.web.webRoot; webCfg.rpcUrl = config_.web.rpcUrl; + webCfg.watchUrl = config_.web.watchUrl; webCfg.nowPlayingVideo = config_.web.nowPlayingVideo; webCfg.rpcPort = config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765; @@ -663,9 +688,6 @@ namespace Echoion::Core if (musicManager_) { registry_.provide(musicManager_); } - if (listeningRooms_) { - registry_.provide(listeningRooms_); - } if (rpcServer_) { registry_.provide(rpcServer_); } @@ -711,27 +733,26 @@ namespace Echoion::Core musicManager_->shutdown(); } - if (listeningRooms_) { - listeningRooms_->shutdown(); - listeningRooms_.reset(); - } - - if (networkClient_) { - networkClient_->shutdown(); - } - - if (rpcServer_) { - rpcServer_->stop(); - rpcServer_.reset(); - } + extensionPlugins_.reset(); #ifdef ECHOION_WITH_WEB + // Providers and the RPC bridge capture Core services, so drain all HTTP + // workers before destroying any of those dependencies. if (webServer_) { webServer_->stop(); webServer_.reset(); } #endif + if (networkClient_) { + networkClient_->shutdown(); + } + directoryService_.reset(); + + if (rpcServer_) { + rpcServer_->stop(); + rpcServer_.reset(); + } if (database_) { database_->shutdown(); database_.reset(); @@ -1119,7 +1140,6 @@ namespace Echoion::Core { // Update local config copy config_ = config; - if (commandManager_) { commandManager_->setPrefix(config.bot.commandPrefix); commandManager_->setServerConfig(config); @@ -1201,7 +1221,6 @@ namespace Echoion::Core // Update local config config_ = *configResult; - // Keep the shared ConfigManager in sync so components that read through // it (cookies, API key, etc.) see the reloaded values. configManager_.updateConfig(config_, false); @@ -1383,19 +1402,12 @@ 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)); + if (extensionPlugins_) { + for (auto& plugin : extensionPlugins_->snapshotStates()) { + state.extensionPlugins.push_back( + {.name = std::move(plugin.name), + .json = std::move(plugin.json), + .version = plugin.version}); } } @@ -1425,8 +1437,16 @@ namespace Echoion::Core } const StateV1& stateData = *result; - pendingListeningRoomState_ = Void::Json::serialize( - Void::Json::to_json(stateData.listeningRooms)); + if (extensionPlugins_) { + std::vector states; + states.reserve(stateData.extensionPlugins.size()); + for (const auto& plugin : stateData.extensionPlugins) { + states.push_back({.name = plugin.name, + .json = plugin.json, + .version = plugin.version}); + } + extensionPlugins_->restoreStates(states); + } // MusicManager already reloads its persisted session (queue + modes) // from the database at startup. Only fall back to re-adding from this @@ -1573,6 +1593,12 @@ namespace Echoion::Core return Api::fail(Api::ErrorCode::ServiceUnavailable, "Core not initialized"); } + if (extensionPlugins_) { + extensionPlugins_->dispatch(event); + } + if (directoryService_) { + directoryService_->handleEvent(event.type); + } // Debug logging for command events if (event.type == Api::PluginEventType::TextMessageReceived && @@ -1677,9 +1703,6 @@ namespace Echoion::Core if (musicManager_) { musicManager_->onClientDisconnected(event.clientId); } - if (listeningRooms_) { - std::ignore = listeningRooms_->leave(event.clientId); - } break; default: @@ -1701,43 +1724,8 @@ 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(); - } + if (directoryService_) { + directoryService_->setPluginInterface(pluginInterface_); } Void::Log::info("Core", "{}", std::format("Plugin interface set (this={})", @@ -1925,16 +1913,12 @@ namespace Echoion::Core bool Core::isAdmin(uint64_t clientId) const { - std::lock_guard lock(adminMutex_); - return std::find(adminClients_.begin(), adminClients_.end(), - clientId) != adminClients_.end(); + return hasLiveTeamSpeakRole(clientId, config_.teamspeak.adminGroups); } bool Core::isDj(uint64_t clientId) const { - std::lock_guard lock(adminMutex_); - return std::find(djClients_.begin(), djClients_.end(), clientId) != - djClients_.end(); + return hasLiveTeamSpeakRole(clientId, config_.teamspeak.djGroups); } std::optional Core::rpcIdentity(uint64_t clientId) const @@ -1947,6 +1931,34 @@ namespace Echoion::Core return std::nullopt; } + bool Core::hasLiveTeamSpeakRole( + uint64_t clientId, const std::vector& configuredGroups) const + { + const auto identity = rpcIdentity(clientId); + if (!identity || configuredGroups.empty() || !pluginInterface_) { + return false; + } + + const auto clients = pluginInterface_->getClients(); + if (!clients) { + return false; + } + + for (const auto& client : *clients) { + if (client.uniqueIdentifier != identity->uid) { + continue; + } + for (const auto group : client.serverGroups) { + if (std::find(configuredGroups.begin(), configuredGroups.end(), + group) != configuredGroups.end()) { + return true; + } + } + return false; + } + return false; + } + std::optional Core::identityForToken(const std::string& token) { @@ -2013,15 +2025,6 @@ namespace Echoion::Core if (rpcServer_) { rpcServer_->addAuthenticatedClient(clientId); } - if (identity.isAdmin || identity.isDj) { - std::lock_guard lock(adminMutex_); - if (identity.isAdmin) { - adminClients_.push_back(clientId); - } - if (identity.isDj) { - djClients_.push_back(clientId); - } - } { std::lock_guard lock(rpcIdentityMutex_); rpcIdentities_[clientId] = diff --git a/src/CoreRpcHandlers.cpp b/src/CoreRpcHandlers.cpp index c2adc9f..38e8367 100644 --- a/src/CoreRpcHandlers.cpp +++ b/src/CoreRpcHandlers.cpp @@ -1,6 +1,8 @@ #include "echoion/core/Core.hpp" -#include "echoion/core/ListeningRoomManager.hpp" +#include "echoion/core/PluginHost.hpp" #include "echoion/core/RpcDtos.hpp" +#include "echoion/core/TeamSpeakDirectoryService.hpp" +#include "echoion/core/detail/RpcValidation.hpp" #include #include #include @@ -10,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +22,8 @@ namespace Echoion::Core namespace { + using Detail::uintField; + // Stable 64-bit key for a TS uid string (FNV-1a): the favorites // tables key users by integer id, while RPC auth yields string uids. [[nodiscard]] uint64_t uidHash(const std::string& uid) @@ -30,6 +35,47 @@ namespace Echoion::Core } return hash; } + + [[nodiscard]] Api::Result + parseObject(const std::string& params) + { + auto parsed = Void::Json::parse(params); + if (!parsed || !parsed->is_object()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Request must be a JSON object"); + } + return std::move(*parsed); + } + + [[nodiscard]] std::optional + stringField(const Void::Json::Value& object, std::string_view key) + { + const auto* value = object.find(key); + if (!value || !value->is_string()) { + return std::nullopt; + } + return value->as_string(); + } + + [[nodiscard]] std::optional + boolField(const Void::Json::Value& object, std::string_view key) + { + const auto* value = object.find(key); + return value && value->is_bool() + ? std::optional{value->as_bool()} + : std::nullopt; + } + + [[nodiscard]] Api::Result + validatedMessage(const Void::Json::Value& request) + { + auto message = stringField(request, "message"); + if (!message || message->empty() || message->size() > 4096) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Message must contain 1 to 4096 bytes"); + } + return std::move(*message); + } } // namespace void Core::setupRpcHandlers() @@ -37,150 +83,178 @@ 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"); - }; - + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::GetCapabilities)), + [](const std::string&, uint64_t) -> Api::Result { + Dto::Capabilities capabilities; + capabilities.plugins = true; + capabilities.webExtensions = true; + return Void::Json::serialize(Void::Json::to_json(capabilities)); + }); + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::GetPluginExtensions)), + [this](const std::string&, uint64_t) -> Api::Result { + return toJson(Dto::PluginExtensions{ + .assets = extensionPlugins_ + ? extensionPlugins_->webAssets() + : std::vector{}}); + }); + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::PluginCall)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result { + if (!extensionPlugins_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin host unavailable"); + } + auto json = Void::Json::parse(params); + if (!json) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "invalid plugin call"); + } + auto request = + Void::Json::from_json(*json); + if (!request || request->plugin.empty() || + request->method.empty()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "plugin and method are required"); + } + return extensionPlugins_->call(request->plugin, request->method, + std::move(request->params), + clientId); + }); // Authentication - expects JSON with either "nickname" (for initial // request) or "token" (for validation). The same handler backs // Authenticate, RequestLoginToken and ValidateLoginToken. auto authHandler = [this](const std::string& params, uint64_t clientId) -> Api::Result { - // Parse JSON params - auto parsedParams = Void::Json::parse(params); - if (!parsedParams) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid authentication request format"); - } - auto reqResult = - Void::Json::from_json(*parsedParams); - if (!reqResult) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid authentication request format"); - } - const Dto::AuthRequest& req = *reqResult; + // Parse JSON params + auto parsedParams = Void::Json::parse(params); + if (!parsedParams) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid authentication request format"); + } + auto reqResult = + Void::Json::from_json(*parsedParams); + if (!reqResult) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid authentication request format"); + } + const Dto::AuthRequest& req = *reqResult; - // If token provided, validate it - if (req.token.has_value()) { - auto identity = identityForToken(*req.token); - if (!identity) { - return Api::fail( - Api::ErrorCode::PermissionDenied, "Invalid token"); - } - registerRpcAuth(clientId, *identity); - return toJson(Dto::AuthSuccess{ - .message = "Authentication successful", - .isAdmin = identity->isAdmin, - .isDj = identity->isDj, - .uid = identity->uid, - .nickname = identity->nickname}); + // If token provided, validate it + if (req.token.has_value()) { + auto identity = identityForToken(*req.token); + if (!identity) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Invalid token"); + } + registerRpcAuth(clientId, *identity); + return toJson( + Dto::AuthSuccess{.message = "Authentication successful", + .isAdmin = identity->isAdmin, + .isDj = identity->isDj, + .uid = identity->uid, + .nickname = identity->nickname, + .token = {}}); + } + + // If nickname provided, search for subscriber and send token + // via PM + if (req.nickname.has_value()) { + auto uidResult = + database_->getSubscriberByNickname(*req.nickname); + if (!uidResult) { + return std::unexpected(uidResult.error()); } - // If nickname provided, search for subscriber and send token - // via PM - if (req.nickname.has_value()) { - auto uidResult = - database_->getSubscriberByNickname(*req.nickname); - if (!uidResult) { - return std::unexpected(uidResult.error()); + if (!uidResult->has_value()) { + return Api::fail( + Api::ErrorCode::NotFound, + "Subscriber not found. Please subscribe to the bot " + "first using !subscribe command."); + } + + const std::string& uid = **uidResult; + + // Get or create token + auto tokenResult = database_->getExistingRpcToken(uid); + if (!tokenResult) { + return std::unexpected(tokenResult.error()); + } + + std::string token; + if (tokenResult->has_value()) { + token = **tokenResult; + } else { + // Generate new token + auto genResult = database_->generateRpcToken(uid); + if (!genResult) { + return std::unexpected(genResult.error()); } + token = *genResult; + } - if (!uidResult->has_value()) { - return Api::fail( - Api::ErrorCode::NotFound, - "Subscriber not found. Please subscribe to the bot " - "first using !subscribe command."); - } + // Get client ID from UID to send PM + if (pluginInterface_) { + // Get all clients and find the one with matching UID + auto clientsResult = pluginInterface_->getClients(); + if (clientsResult) { + for (const auto& client : *clientsResult) { + if (client.uniqueIdentifier == uid) { + uint64_t tsClientId = client.id; - const std::string& uid = **uidResult; + // Send PM with token using plain text + // format (compatible with both TS3 BBCode + // and TS6 Markdown) + std::string pmMessage = std::format( + "**Echoion RPC Authentication**\n\n" + "Your authentication token:\n" + "```\n{}\n```\n\n" + "Use this token to authenticate with " + "the RPC server.\n" + "Keep this token secure and do not " + "share it with others.", + token); - // Get or create token - auto tokenResult = database_->getExistingRpcToken(uid); - if (!tokenResult) { - return std::unexpected(tokenResult.error()); - } + auto pmResult = + pluginInterface_->sendTextMessage( + tsClientId, pmMessage); - std::string token; - if (tokenResult->has_value()) { - token = **tokenResult; - } else { - // Generate new token - auto genResult = database_->generateRpcToken(uid); - if (!genResult) { - return std::unexpected(genResult.error()); - } - token = *genResult; - } - - // Get client ID from UID to send PM - if (pluginInterface_) { - // Get all clients and find the one with matching UID - auto clientsResult = pluginInterface_->getClients(); - if (clientsResult) { - for (const auto& client : *clientsResult) { - if (client.uniqueIdentifier == uid) { - uint64_t tsClientId = client.id; - - // Send PM with token using plain text - // format (compatible with both TS3 BBCode - // and TS6 Markdown) - std::string pmMessage = std::format( - "**Echoion RPC Authentication**\n\n" - "Your authentication token:\n" - "```\n{}\n```\n\n" - "Use this token to authenticate with " - "the RPC server.\n" - "Keep this token secure and do not " - "share it with others.", - token); - - auto pmResult = - pluginInterface_->sendTextMessage( - tsClientId, pmMessage); - - if (!pmResult) { - Void::Log::warn("Core", "{}", std::format( + if (!pmResult) { + Void::Log::warn( + "Core", + "{}", + std::format( "Failed to send PM with token: {}", pmResult.error().message)); - } - break; } + break; } } } - - return toJson(Dto::SuccessMessage{ - .message = "Token sent via TeamSpeak PM. Please check " - "your private messages."}); } - return Api::fail(Api::ErrorCode::InvalidArgument, - "Authentication request must include either " - "'nickname' or 'token'"); - }; + return toJson(Dto::SuccessMessage{ + .message = "Token sent via TeamSpeak PM. Please check " + "your private messages."}); + } + + return Api::fail(Api::ErrorCode::InvalidArgument, + "Authentication request must include either " + "'nickname' or 'token'"); + }; rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::Authenticate)), authHandler); rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::RequestLoginToken)), authHandler); - rpcServer_->registerHandler( - std::to_string( - static_cast(Api::RpcMethod::ValidateLoginToken)), - authHandler); + rpcServer_->registerHandler(std::to_string(static_cast( + Api::RpcMethod::ValidateLoginToken)), + authHandler); // Address-based autologin: if the caller's network address matches an // online subscriber's TeamSpeak address, sign them in without a typed @@ -193,12 +267,12 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!database_ || !musicManager_ || !pluginInterface_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Autologin unavailable"); + "Autologin unavailable"); } auto address = rpcServer_->getClientAddress(clientId); if (!address) { return Api::fail(Api::ErrorCode::NotFound, - "Caller address unknown"); + "Caller address unknown"); } const auto onlineUids = musicManager_->getOnlineSubscriberUids(); @@ -243,15 +317,14 @@ namespace Echoion::Core .token = token}); } return Api::fail(Api::ErrorCode::NotFound, - "No online subscriber matches this address"); + "No online subscriber matches this address"); }); #ifdef ECHOION_WITH_WEB // Restart the web interface in place (config edits to web.* take // effect after ReloadConfig + this). The browser reaches the RPC // through the web server's own /rpc bridge, so respond first and - // restart on a delayed background thread; watch rooms live in the - // HttpServer object and survive the stop()/start(). + // restart on a delayed background thread. rpcServer_->registerHandler( std::to_string( static_cast(Api::RpcMethod::RestartWebInterface)), @@ -259,38 +332,38 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } if (!webServer_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Web interface is not running"); + "Web interface is not running"); } if (webRestartPending_.exchange(true)) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Restart already in progress"); + "Restart already in progress"); } Web::HttpServer::Config webCfg; webCfg.port = config_.web.port; webCfg.bindAddress = config_.web.bindAddress; webCfg.webRoot = config_.web.webRoot; webCfg.rpcUrl = config_.web.rpcUrl; + webCfg.watchUrl = config_.web.watchUrl; webCfg.nowPlayingVideo = config_.web.nowPlayingVideo; webCfg.rpcPort = config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765; const bool enabled = config_.web.enabled; std::thread([this, webCfg, enabled]() { - std::this_thread::sleep_for( - std::chrono::milliseconds(500)); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); webServer_->stop(); if (enabled && !webServer_->start(webCfg)) { Void::Log::error("Core", "{}", - "Web interface failed to restart"); + "Web interface failed to restart"); } webRestartPending_ = false; }).detach(); - return toJson(Dto::SuccessMessage{ - .message = "Web interface restarting"}); + return toJson( + Dto::SuccessMessage{.message = "Web interface restarting"}); }); #endif @@ -304,7 +377,7 @@ namespace Echoion::Core auto identity = rpcIdentity(clientId); if (!identity || !database_) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Authentication required"); + "Authentication required"); } Dto::UserPrefs prefs; if (auto lang = database_->getKv("lang:" + identity->uid); @@ -321,22 +394,22 @@ namespace Echoion::Core auto identity = rpcIdentity(clientId); if (!identity || !database_) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Authentication required"); + "Authentication required"); } auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid parameters"); + "Invalid parameters"); } auto prefs = Void::Json::from_json(*parsed); if (!prefs) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid parameters"); + "Invalid parameters"); } if (!prefs->language.empty()) { if (prefs->language != "en" && prefs->language != "ru") { return Api::fail(Api::ErrorCode::InvalidArgument, - "Unsupported language"); + "Unsupported language"); } auto res = database_->setKv("lang:" + identity->uid, prefs->language); @@ -347,118 +420,6 @@ namespace Echoion::Core return toJson(*prefs); }); - // ── Custom emojis (web watch chat/reactions) ──────────────────────── - // Listing is open to any authenticated user; adding/removing is - // admin-only. Images are served at GET /emoji/. - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::GetCustomEmojis)), - [this](const std::string&, - uint64_t) -> Api::Result { - if (!database_) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); - } - auto emojis = database_->getCustomEmojis(); - if (!emojis) { - return std::unexpected(emojis.error()); - } - Dto::CustomEmojiList list; - for (const auto& e : *emojis) { - list.emojis.push_back(Dto::CustomEmojiDto{ - .name = e.name, - .mime = e.mime, - .addedBy = e.addedBy}); - } - return toJson(list); - }); - - rpcServer_->registerHandler( - std::to_string(static_cast(Api::RpcMethod::AddCustomEmoji)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - if (!isAdmin(clientId)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); - } - if (!database_) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); - } - auto parsed = Void::Json::parse(params); - if (!parsed) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid parameters"); - } - auto req = - Void::Json::from_json(*parsed); - if (!req) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid parameters"); - } - // Shortcode-safe name: [a-z0-9_], 1..32 chars. - const std::string& name = req->name; - const bool nameOk = - !name.empty() && name.size() <= 32 && - std::all_of(name.begin(), name.end(), [](char c) { - return (c >= 'a' && c <= 'z') || - (c >= '0' && c <= '9') || c == '_'; - }); - if (!nameOk) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "Emoji name must be 1-32 chars of a-z, 0-9, _"); - } - // Cap the payload (~64KB image → ~88KB base64). - if (req->dataBase64.size() > 90000) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Emoji image too large (max ~64KB)"); - } - if (req->mime != "image/png" && req->mime != "image/gif" && - req->mime != "image/webp" && req->mime != "image/jpeg") { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Unsupported image type"); - } - auto res = database_->addCustomEmoji( - name, req->mime, req->dataBase64, - std::to_string(clientId)); - if (!res) { - return std::unexpected(res.error()); - } - return toJson(Dto::CustomEmojiDto{.name = name, - .mime = req->mime}); - }); - - rpcServer_->registerHandler( - std::to_string( - static_cast(Api::RpcMethod::RemoveCustomEmoji)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result { - if (!isAdmin(clientId)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); - } - if (!database_) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); - } - auto parsed = Void::Json::parse(params); - if (!parsed) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid parameters"); - } - auto req = - Void::Json::from_json(*parsed); - if (!req || req->name.empty()) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid parameters"); - } - auto res = database_->removeCustomEmoji(req->name); - if (!res) { - return std::unexpected(res.error()); - } - return toJson(Dto::Success{}); - }); - // Radio (autoplay) toggle — same switch as the !autoplay command. rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::ToggleAutoplay)), @@ -466,11 +427,11 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } if (!musicManager_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Music manager unavailable"); + "Music manager unavailable"); } const bool enabled = !musicManager_->autoplayEnabled(); musicManager_->setAutoplay(enabled); @@ -548,8 +509,8 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId) && !isDj(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "DJ or admin privileges required — use " - "vote skip instead"); + "DJ or admin privileges required — use " + "vote skip instead"); } uint32_t count = 1; if (auto parsed = Void::Json::parse(params)) { @@ -573,12 +534,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid volume request"); + "Invalid volume request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid volume request"); + "Invalid volume request"); } float volume = std::clamp(req->volume, 0.0f, 1.0f); auto result = setVolume(volume); @@ -591,8 +552,8 @@ namespace Echoion::Core // Queue management rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetQueue)), - [this](const std::string& /*params*/, uint64_t /*clientId*/) - -> Api::Result { + [this](const std::string& /*params*/, + uint64_t /*clientId*/) -> Api::Result { auto queue = getQueue(); if (!queue) { return std::unexpected(queue.error()); @@ -609,208 +570,10 @@ 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*/) - -> Api::Result { + [this](const std::string& /*params*/, + uint64_t /*clientId*/) -> Api::Result { auto track = getCurrentTrack(); if (!track) { return std::unexpected(track.error()); @@ -836,10 +599,9 @@ namespace Echoion::Core return toJson(resp); } const auto& info = track->value().track; - long long durationSec = - info.duration.has_value() - ? info.duration->count() / 1000 - : 0; + long long durationSec = info.duration.has_value() + ? info.duration->count() / 1000 + : 0; auto lyrics = lyricsService_->fetch(info.title, info.artist, info.album, durationSec); resp.found = lyrics.found; @@ -870,18 +632,17 @@ namespace Echoion::Core voteSkip = musicManager_->voteSkipStatus( identity ? identity->uid : ""); } - return toJson( - Dto::Status{.isPlaying = state->isPlaying, - .isPaused = state->isPaused, - .volume = state->volume, - .repeat = state->repeat, - .shuffle = state->shuffle, - .autoplay = musicManager_ - ? musicManager_->autoplayEnabled() - : false, - .skipVotes = voteSkip.votes, - .skipVotesNeeded = voteSkip.needed, - .skipVoted = voteSkip.voted}); + return toJson(Dto::Status{ + .isPlaying = state->isPlaying, + .isPaused = state->isPaused, + .volume = state->volume, + .repeat = state->repeat, + .shuffle = state->shuffle, + .autoplay = musicManager_ ? musicManager_->autoplayEnabled() + : false, + .skipVotes = voteSkip.votes, + .skipVotesNeeded = voteSkip.needed, + .skipVoted = voteSkip.voted}); }); rpcServer_->registerHandler( @@ -891,12 +652,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid seek request"); + "Invalid seek request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid seek request"); + "Invalid seek request"); } auto result = seek(std::chrono::milliseconds(req->position)); if (!result) { @@ -912,13 +673,13 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid queue request"); + "Invalid queue request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid queue request"); + "Invalid queue request"); } auto result = queueTrack(req->query, clientId); if (!result) { @@ -934,12 +695,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid remove request"); + "Invalid remove request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid remove request"); + "Invalid remove request"); } auto result = removeFromQueue(req->queueId); if (!result) { @@ -950,8 +711,7 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::ClearQueue)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { auto result = clearQueue(); if (!result) { return std::unexpected(result.error()); @@ -966,12 +726,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid move request"); + "Invalid move request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid move request"); + "Invalid move request"); } auto result = moveInQueue(req->queueId, req->newPosition); if (!result) { @@ -987,12 +747,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid search request"); + "Invalid search request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid search request"); + "Invalid search request"); } auto result = musicManager_->search(req->query); if (!result) { @@ -1013,12 +773,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid track info request"); + "Invalid track info request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid track info request"); + "Invalid track info request"); } // No arbitrary-id lookup exists; resolve via search top result. auto result = musicManager_->search(req->id); @@ -1027,15 +787,14 @@ namespace Echoion::Core } if (result->tracks.empty()) { return Api::fail(Api::ErrorCode::NotFound, - "Track not found"); + "Track not found"); } return toJson(Dto::toTrack(result->tracks.front())); }); rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::ToggleShuffle)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { auto result = musicManager_->toggleShuffle(); if (!result) { return std::unexpected(result.error()); @@ -1045,8 +804,7 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::ToggleRepeat)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { auto result = musicManager_->toggleRepeat(); if (!result) { return std::unexpected(result.error()); @@ -1056,8 +814,7 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::ShuffleQueue)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { auto result = musicManager_->shuffleQueue(); if (!result) { return std::unexpected(result.error()); @@ -1073,13 +830,13 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid playlist request"); + "Invalid playlist request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid playlist request"); + "Invalid playlist request"); } auto result = loadPlaylist(req->playlistId, clientId); if (!result) { @@ -1090,11 +847,10 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetPlaylists)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto playlists = database_->getAllPlaylists(); if (!playlists) { @@ -1119,25 +875,25 @@ namespace Echoion::Core uint64_t) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid playlist request"); + "Invalid playlist request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid playlist request"); + "Invalid playlist request"); } uint64_t playlistId = 0; try { playlistId = std::stoull(req->playlistId); } catch (const std::exception&) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Playlist id must be numeric"); + "Playlist id must be numeric"); } auto playlist = database_->getPlaylist(playlistId); if (!playlist) { @@ -1145,7 +901,7 @@ namespace Echoion::Core } if (!playlist->has_value()) { return Api::fail(Api::ErrorCode::NotFound, - "Playlist not found"); + "Playlist not found"); } Dto::PlaylistContents resp; resp.id = std::to_string((*playlist)->id); @@ -1164,13 +920,14 @@ namespace Echoion::Core uint64_t) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } uint32_t limit = 20; if (!params.empty()) { if (auto parsed = Void::Json::parse(params)) { - if (auto req = Void::Json::from_json< - Dto::HistoryRequest>(*parsed)) { + if (auto req = + Void::Json::from_json( + *parsed)) { limit = std::clamp(req->limit, 1u, 100u); } } @@ -1189,11 +946,10 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetStats)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto stats = database_->getStatistics(0); if (!stats) { @@ -1216,18 +972,18 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid save-playlist request"); + "Invalid save-playlist request"); } auto req = Void::Json::from_json(*parsed); if (!req || req->name.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Playlist name is required"); + "Playlist name is required"); } // Persist the current queue as a new playlist. Ownership is // recorded as the RPC client id (no TS-uid→user mapping yet). @@ -1253,25 +1009,25 @@ namespace Echoion::Core uint64_t) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid delete-playlist request"); + "Invalid delete-playlist request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid delete-playlist request"); + "Invalid delete-playlist request"); } std::uint64_t id = 0; try { id = std::stoull(req->playlistId); } catch (const std::exception&) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid playlist id"); + "Invalid playlist id"); } auto result = database_->deletePlaylist(id); if (!result) { @@ -1288,7 +1044,7 @@ namespace Echoion::Core // Config may contain secrets — admin only. if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } // Returns the config as a JSON string (already serialized). return getConfigJson(); @@ -1300,7 +1056,7 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } auto result = updateConfigJson(params); if (!result) { @@ -1312,7 +1068,11 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::ReloadConfig)), [this](const std::string&, - uint64_t) -> Api::Result { + uint64_t clientId) -> Api::Result { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } auto result = reloadConfig(); if (!result) { return std::unexpected(result.error()); @@ -1327,11 +1087,6 @@ namespace Echoion::Core [this](const std::string&, uint64_t clientId) -> Api::Result { rpcServer_->removeAuthenticatedClient(clientId); - { - std::lock_guard lock(adminMutex_); - std::erase(adminClients_, clientId); - std::erase(djClients_, clientId); - } { std::lock_guard lock(rpcIdentityMutex_); rpcIdentities_.erase(clientId); @@ -1341,17 +1096,15 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast(Api::RpcMethod::GetServerInfo)), - [this](const std::string&, - uint64_t) -> Api::Result { + [this](const std::string&, uint64_t) -> Api::Result { Dto::ServerInfo info; info.version = Api::VERSION_STRING; info.uptimeSeconds = rpcServer_->getUptime().count(); - info.connectedClients = static_cast( - rpcServer_->getClientCount()); + info.connectedClients = + static_cast(rpcServer_->getClientCount()); if (database_) { if (auto count = database_->getSubscriberCount()) { - info.subscribers = - static_cast(*count); + info.subscribers = static_cast(*count); } } if (auto queue = getQueue()) { @@ -1386,17 +1139,17 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } Dto::AuditLogResponse resp; for (const auto& e : rpcServer_->getAuditLog()) { resp.entries.push_back(Dto::AuditEntryDto{ .clientId = e.clientId, .method = e.method, - .timestamp = std::chrono::duration_cast< - std::chrono::seconds>( - e.timestamp.time_since_epoch()) - .count()}); + .timestamp = + std::chrono::duration_cast( + e.timestamp.time_since_epoch()) + .count()}); } return toJson(resp); }); @@ -1407,27 +1160,27 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid manage-users request"); + "Invalid manage-users request"); } auto req = Void::Json::from_json(*parsed); if (!req) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid manage-users request"); + "Invalid manage-users request"); } if (req->action == "remove") { if (!req->uid || req->uid->empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "uid required for remove"); + "uid required for remove"); } // Through MusicManager so runtime state (whisper list, // pause-on-empty) stays consistent with the database. @@ -1468,10 +1221,10 @@ namespace Echoion::Core Dto::UsersResponse resp; resp.users.reserve(subs->size()); for (const auto& s : *subs) { - resp.users.push_back(Dto::SubscriberDto{ - .uid = s.uid, - .nickname = s.nickname, - .online = online.contains(s.uid)}); + resp.users.push_back( + Dto::SubscriberDto{.uid = s.uid, + .nickname = s.nickname, + .online = online.contains(s.uid)}); } return toJson(resp); }); @@ -1482,7 +1235,7 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } auto result = prepareForHotReload(); if (!result) { @@ -1497,17 +1250,15 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } // Defer the actual shutdown so this success response is // delivered before the server tears down. std::thread([this]() { - std::this_thread::sleep_for( - std::chrono::milliseconds(250)); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); (void)shutdown(); }).detach(); - return toJson(Dto::SuccessMessage{ - .message = "Shutting down"}); + return toJson(Dto::SuccessMessage{.message = "Shutting down"}); }); // ── Web UI additions ──────────────────────────────────────────────── @@ -1519,7 +1270,7 @@ namespace Echoion::Core auto identity = rpcIdentity(clientId); if (!identity || identity->uid.empty()) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Token authentication required"); + "Token authentication required"); } return identity->uid; }; @@ -1530,7 +1281,7 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto uid = requireUid(clientId); if (!uid) { @@ -1554,7 +1305,7 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto uid = requireUid(clientId); if (!uid) { @@ -1563,13 +1314,13 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid add-favorite request"); + "Invalid add-favorite request"); } auto req = Void::Json::from_json(*parsed); if (!req || (!req->track.url && req->track.title.empty())) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Track is required"); + "Track is required"); } auto result = database_->addFavorite( uidHash(*uid), Dto::fromTrack(req->track)); @@ -1585,7 +1336,7 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto uid = requireUid(clientId); if (!uid) { @@ -1594,12 +1345,12 @@ namespace Echoion::Core auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid remove-favorite request"); + "Invalid remove-favorite request"); } auto req = Void::Json::from_json(*parsed); if (!req || req->url.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Track url is required"); + "Track url is required"); } auto result = database_->removeFavorite(uidHash(*uid), req->url); @@ -1615,7 +1366,7 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!musicManager_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Music manager unavailable"); + "Music manager unavailable"); } auto uid = requireUid(clientId); if (!uid) { @@ -1625,11 +1376,10 @@ namespace Echoion::Core if (!status) { return std::unexpected(status.error()); } - const Dto::VoteSkipResponse resp{ - .votes = status->votes, - .needed = status->needed, - .voted = status->voted, - .skipped = status->skipped}; + const Dto::VoteSkipResponse resp{.votes = status->votes, + .needed = status->needed, + .voted = status->voted, + .skipped = status->skipped}; rpcServer_->broadcastEvent("voteskip.updated", toJson(resp)); return toJson(resp); }); @@ -1640,21 +1390,21 @@ namespace Echoion::Core uint64_t clientId) -> Api::Result { if (!isAdmin(clientId)) { return Api::fail(Api::ErrorCode::PermissionDenied, - "Admin privileges required"); + "Admin privileges required"); } if (!musicManager_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Music manager unavailable"); + "Music manager unavailable"); } auto parsed = Void::Json::parse(params); if (!parsed) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid announce request"); + "Invalid announce request"); } auto req = Void::Json::from_json(*parsed); if (!req || req->text.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Announcement text is required"); + "Announcement text is required"); } const size_t reached = musicManager_->setAnnouncement(req->text); @@ -1665,13 +1415,11 @@ namespace Echoion::Core }); rpcServer_->registerHandler( - std::to_string( - static_cast(Api::RpcMethod::GetAggregateStats)), - [this](const std::string&, - uint64_t) -> Api::Result { + std::to_string(static_cast(Api::RpcMethod::GetAggregateStats)), + [this](const std::string&, uint64_t) -> Api::Result { if (!database_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Database unavailable"); + "Database unavailable"); } auto stats = database_->getAggregateStats(); if (!stats) { @@ -1697,6 +1445,414 @@ namespace Echoion::Core return toJson(resp); }); + // ── TeamSpeak directory and administration ───────────────────────── + // Every operation goes through the same host interface/identity that + // the bot already uses. The RPC layer never creates a second TeamSpeak + // client. + auto requireTeamSpeakAdmin = + [this](uint64_t clientId) -> Api::Result { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!pluginInterface_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "TeamSpeak interface unavailable"); + } + return {}; + }; + auto finishTeamSpeakMutation = + [this](Api::Result result) -> Api::Result { + if (!result) { + return std::unexpected(result.error()); + } + if (directoryService_) { + (void)directoryService_->refresh(); + } + return toJson(Dto::Success{}); + }; + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::GetTeamSpeakDirectory)), + [this, requireTeamSpeakAdmin](const std::string&, uint64_t clientId) + -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + if (!directoryService_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "TeamSpeak directory unavailable"); + } + return Void::Json::serialize(directoryService_->adminJson()); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::MoveTeamSpeakClient)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto target = + request ? uintField(*request, "clientId") : std::nullopt; + const auto channel = + request ? uintField(*request, "channelId") : std::nullopt; + if (!target || !channel || *target == 0 || *channel == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "clientId and channelId are required"); + } + return finishTeamSpeakMutation( + pluginInterface_->moveClient(*target, *channel)); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::KickTeamSpeakClient)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto target = + request ? uintField(*request, "clientId") : std::nullopt; + if (!target || *target == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "clientId is required"); + } + const auto reason = + stringField(*request, "reason").value_or(""); + const bool fromServer = + boolField(*request, "fromServer").value_or(true); + return finishTeamSpeakMutation( + fromServer ? pluginInterface_->kickClient(*target, reason) + : pluginInterface_->kickClientFromChannel( + *target, reason)); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::BanTeamSpeakClient)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto target = + request ? uintField(*request, "clientId") : std::nullopt; + if (!target || *target == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "clientId is required"); + } + const auto duration = + uintField(*request, "durationSeconds").value_or(0); + const auto reason = + stringField(*request, "reason").value_or(""); + return finishTeamSpeakMutation( + pluginInterface_->banClient(*target, duration, reason)); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast(Api::RpcMethod::GetTeamSpeakBans)), + [this, requireTeamSpeakAdmin](const std::string&, uint64_t clientId) + -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto bans = pluginInterface_->getBans(); + if (!bans) { + return std::unexpected(bans.error()); + } + Void::Json::Value::Array_t values; + values.reserve(bans->size()); + for (const auto& ban : *bans) { + values.push_back(Void::Json::object( + {{"id", + Void::Json::Value{static_cast(ban.id)}}, + {"uid", ban.uniqueIdentifier + ? Void::Json::Value{*ban.uniqueIdentifier} + : Void::Json::Value{nullptr}}, + {"nickname", ban.nickname + ? Void::Json::Value{*ban.nickname} + : Void::Json::Value{nullptr}}, + {"reason", Void::Json::Value{ban.reason}}, + {"createdAt", Void::Json::Value{static_cast( + ban.createdAt)}}, + {"durationSeconds", + Void::Json::Value{ + static_cast(ban.durationSeconds)}}})); + } + return Void::Json::serialize(Void::Json::object( + {{"bans", Void::Json::array(std::move(values))}})); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::UnbanTeamSpeakClient)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto banId = + request ? uintField(*request, "banId") : std::nullopt; + if (!banId || *banId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "banId is required"); + } + return finishTeamSpeakMutation(pluginInterface_->unban(*banId)); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::CreateTeamSpeakChannel)), + [this, requireTeamSpeakAdmin]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + auto name = + request ? stringField(*request, "name") : std::nullopt; + if (!name || name->empty() || name->size() > 100) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "Channel name must contain 1 to 100 bytes"); + } + Api::ChannelCreateOptions options; + options.name = std::move(*name); + options.parentId = uintField(*request, "parentId"); + options.orderAfterId = uintField(*request, "orderAfterId"); + options.topic = stringField(*request, "topic"); + options.description = stringField(*request, "description"); + options.password = stringField(*request, "password"); + if (const auto max = uintField(*request, "maxClients"); max) { + if (*max > std::numeric_limits::max()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "maxClients is out of range"); + } + options.maxClients = static_cast(*max); + } + options.permanent = + boolField(*request, "permanent").value_or(true); + auto created = pluginInterface_->createChannel(options); + if (!created) { + return std::unexpected(created.error()); + } + if (directoryService_) { + (void)directoryService_->refresh(); + } + return Void::Json::serialize(Void::Json::object( + {{"id", + Void::Json::Value{static_cast(*created)}}})); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::EditTeamSpeakChannel)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto channelId = + request ? uintField(*request, "channelId") : std::nullopt; + if (!channelId || *channelId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "channelId is required"); + } + Api::ChannelEditOptions options; + options.name = stringField(*request, "name"); + options.topic = stringField(*request, "topic"); + options.description = stringField(*request, "description"); + options.password = stringField(*request, "password"); + if (const auto max = uintField(*request, "maxClients"); max) { + if (*max > std::numeric_limits::max()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "maxClients is out of range"); + } + options.maxClients = static_cast(*max); + } + options.permanent = boolField(*request, "permanent"); + if (!options.name && !options.topic && !options.description && + !options.password && !options.maxClients && + !options.permanent) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "At least one channel field is required"); + } + if (options.name && + (options.name->empty() || options.name->size() > 100)) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "Channel name must contain 1 to 100 bytes"); + } + return finishTeamSpeakMutation( + pluginInterface_->editChannel(*channelId, options)); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::ReorderTeamSpeakChannel)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto channelId = + request ? uintField(*request, "channelId") : std::nullopt; + const auto parentId = + request ? uintField(*request, "parentId") : std::nullopt; + const auto afterId = request + ? uintField(*request, "orderAfterId") + : std::nullopt; + if (!channelId || *channelId == 0 || !parentId || !afterId) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "channelId, parentId and orderAfterId are required"); + } + return finishTeamSpeakMutation(pluginInterface_->reorderChannel( + *channelId, *parentId, *afterId)); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::DeleteTeamSpeakChannel)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto channelId = + request ? uintField(*request, "channelId") : std::nullopt; + if (!channelId || *channelId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "channelId is required"); + } + return finishTeamSpeakMutation(pluginInterface_->deleteChannel( + *channelId, boolField(*request, "force").value_or(false))); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast(Api::RpcMethod::GetTeamSpeakServerGroups)), + [this, requireTeamSpeakAdmin](const std::string&, uint64_t clientId) + -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); !allowed) { + return std::unexpected(allowed.error()); + } + auto groups = pluginInterface_->getServerGroups(); + if (!groups) { + return std::unexpected(groups.error()); + } + Void::Json::Value::Array_t values; + values.reserve(groups->size()); + for (const auto& group : *groups) { + values.push_back(Void::Json::object( + {{"id", + Void::Json::Value{static_cast(group.id)}}, + {"name", Void::Json::Value{group.name}}, + {"default", Void::Json::Value{group.isDefault}}})); + } + return Void::Json::serialize(Void::Json::object( + {{"groups", Void::Json::array(std::move(values))}})); + }); + + auto registerGroupMutation = [this, + requireTeamSpeakAdmin, + finishTeamSpeakMutation]( + Api::RpcMethod method, bool add) { + rpcServer_->registerHandler( + std::to_string(static_cast(method)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation, add]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); + !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + const auto groupId = + request ? uintField(*request, "groupId") : std::nullopt; + const auto databaseId = + request ? uintField(*request, "clientDatabaseId") + : std::nullopt; + if (!groupId || *groupId == 0 || !databaseId || + *databaseId == 0) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "groupId and clientDatabaseId are required"); + } + return finishTeamSpeakMutation( + add ? pluginInterface_->addClientToServerGroup( + *groupId, *databaseId) + : pluginInterface_->removeClientFromServerGroup( + *groupId, *databaseId)); + }); + }; + registerGroupMutation(Api::RpcMethod::AddTeamSpeakServerGroupMember, + true); + registerGroupMutation(Api::RpcMethod::RemoveTeamSpeakServerGroupMember, + false); + + auto registerMessage = [this, + requireTeamSpeakAdmin, + finishTeamSpeakMutation](Api::RpcMethod method, + int scope) { + rpcServer_->registerHandler( + std::to_string(static_cast(method)), + [this, requireTeamSpeakAdmin, finishTeamSpeakMutation, scope]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (auto allowed = requireTeamSpeakAdmin(clientId); + !allowed) { + return std::unexpected(allowed.error()); + } + auto request = parseObject(params); + if (!request) { + return std::unexpected(request.error()); + } + auto message = validatedMessage(*request); + if (!message) { + return std::unexpected(message.error()); + } + if (scope == 2) { + return finishTeamSpeakMutation( + pluginInterface_->sendServerMessage(*message)); + } + const auto target = uintField( + *request, scope == 0 ? "clientId" : "channelId"); + if (!target || *target == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + scope == 0 ? "clientId is required" + : "channelId is required"); + } + return finishTeamSpeakMutation( + scope == 0 ? pluginInterface_->sendTextMessage(*target, + *message) + : pluginInterface_->sendChannelMessage( + *target, *message)); + }); + }; + registerMessage(Api::RpcMethod::SendTeamSpeakPrivateMessage, 0); + registerMessage(Api::RpcMethod::SendTeamSpeakChannelMessage, 1); + registerMessage(Api::RpcMethod::SendTeamSpeakServerMessage, 2); + Void::Log::info("Core", "{}", "RPC handlers registered"); } diff --git a/src/Database.cpp b/src/Database.cpp index a1470fb..e2b14b2 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -359,28 +359,14 @@ namespace Echoion::Api "Database migration 8 applied: track_thumbnail columns added"); } - // Migration 9: custom emojis for the web UI (admin-managed image - // emotes, referenced by :name: shortcodes in watch chat/reactions). + // Migration 9 belonged to a retired embedded browser feature. Preserve + // its version slot so existing databases and later migrations remain + // compatible, but new Echoion databases no longer create its tables. if (currentVersion < 9) { - const char* migration9 = R"( - CREATE TABLE IF NOT EXISTS custom_emojis ( - name TEXT PRIMARY KEY, - mime TEXT NOT NULL, - data TEXT NOT NULL, -- base64-encoded image bytes - added_by TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ); - )"; - - if (auto r = impl_->voidDb.exec(migration9); !r) { - return fail(ErrorCode::DatabaseError, r.error().message()); - } - [[maybe_unused]] auto ins = impl_->voidDb.exec( "INSERT INTO schema_migrations (version) VALUES (9)"); - Void::Log::info("Database", "{}", - "Database migration 9 applied: custom_emojis table added"); + Void::Log::info("Database", "{}", "Database migration 9 retired"); } // Migration 10: cached TeamSpeak avatars for the web UI, keyed by uid, @@ -1451,83 +1437,6 @@ namespace Echoion::Api return {}; } - Result> Database::getCustomEmojis() - { - std::shared_lock lock(mutex_); - auto stmtRes = impl_->voidDb.prepare( - "SELECT name, mime, data, added_by FROM custom_emojis " - "ORDER BY name;"); - if (!stmtRes) { - return fail(ErrorCode::DatabaseError, stmtRes.error().message()); - } - auto& stmt = *stmtRes; - std::vector out; - while (stmt.step().value_or(false)) { - out.push_back(CustomEmoji{.name = stmt.column_text(0), - .mime = stmt.column_text(1), - .dataBase64 = stmt.column_text(2), - .addedBy = stmt.column_text(3)}); - } - return out; - } - - Result> - Database::getCustomEmoji(const std::string& name) - { - std::shared_lock lock(mutex_); - auto stmtRes = impl_->voidDb.prepare( - "SELECT name, mime, data, added_by FROM custom_emojis " - "WHERE name = ?;"); - if (!stmtRes) { - return fail(ErrorCode::DatabaseError, stmtRes.error().message()); - } - auto& stmt = *stmtRes; - stmt.bind(1, name); - if (stmt.step().value_or(false)) { - return std::optional{ - CustomEmoji{.name = stmt.column_text(0), - .mime = stmt.column_text(1), - .dataBase64 = stmt.column_text(2), - .addedBy = stmt.column_text(3)}}; - } - return std::optional{}; - } - - Result Database::addCustomEmoji(const std::string& name, - const std::string& mime, - const std::string& dataBase64, - const std::string& addedBy) - { - std::unique_lock lock(mutex_); - auto stmtRes = impl_->voidDb.prepare(R"( - INSERT OR REPLACE INTO custom_emojis (name, mime, data, added_by) - VALUES (?, ?, ?, ?); - )"); - if (!stmtRes) { - return fail(ErrorCode::DatabaseError, stmtRes.error().message()); - } - auto& stmt = *stmtRes; - stmt.bind(1, name).bind(2, mime).bind(3, dataBase64).bind(4, addedBy); - if (auto stepRes = stmt.step(); !stepRes) { - return fail(ErrorCode::DatabaseError, stepRes.error().message()); - } - return {}; - } - - Result Database::removeCustomEmoji(const std::string& name) - { - std::unique_lock lock(mutex_); - auto stmtRes = - impl_->voidDb.prepare("DELETE FROM custom_emojis WHERE name = ?;"); - if (!stmtRes) { - return fail(ErrorCode::DatabaseError, stmtRes.error().message()); - } - auto& stmt = *stmtRes; - stmt.bind(1, name); - [[maybe_unused]] auto stepRes = stmt.step(); - return {}; - } - Result> Database::getCachedAvatar(const std::string& uid) { diff --git a/src/ListeningRoomManager.cpp b/src/ListeningRoomManager.cpp deleted file mode 100644 index c3fea23..0000000 --- a/src/ListeningRoomManager.cpp +++ /dev/null @@ -1,457 +0,0 @@ -#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/src/MusicManager.cpp b/src/MusicManager.cpp index 34d8fe0..c45688d 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -60,7 +60,9 @@ namespace Echoion::Core networkConfig.proxy->port)); } - youTubeClient_ = std::make_shared(networkClient_); + if (!youTubeClient_) { + youTubeClient_ = std::make_shared(networkClient_); + } // Playlist loading runs off the audio path: it enqueues resolved // tracks via queueTrack and pokes the playback loop on the first one. @@ -459,6 +461,11 @@ namespace Echoion::Core Void::Log::info("MusicManager", "{}", "Sources config applied"); } + void MusicManager::addTrackSource(std::shared_ptr source) + { + if (router_) router_->addSource(std::move(source)); + } + void MusicManager::shutdown() { // Background fetch threads touch queue_/engine_/sources; join them diff --git a/src/PluginHost.cpp b/src/PluginHost.cpp new file mode 100644 index 0000000..fe909a5 --- /dev/null +++ b/src/PluginHost.cpp @@ -0,0 +1,400 @@ +#include "echoion/core/PluginHost.hpp" + +#include "echoion/core/CommandManager.hpp" +#include "echoion/core/MusicManager.hpp" +#include "echoion/core/sources/TrackSource.hpp" + +#include +#include + +#include +#include + +namespace Echoion::Core +{ + namespace + { + class ExtensionCommandAdapter final : public Command + { + public: + ExtensionCommandAdapter(Void::Plugin::PluginManager& plugins, + std::string plugin, Api::ExtensionCommand command) + : plugins_(plugins), plugin_(std::move(plugin)), + command_(std::move(command)) + { + } + + void execute(const CommandContext& context) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) { + context.reply("Plugin is temporarily unavailable."); + return; + } + auto result = extension->executeCommand({ + .command = command_.name, + .arguments = context.args, + .clientId = context.clientId, + .invokerName = std::string(context.invokerName)}); + context.reply(result ? *result : result.error().message); + } catch (const std::exception& error) { + Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw: {}", + plugin_, command_.name, error.what()); + context.reply("Plugin command failed."); + } catch (...) { + Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw", + plugin_, command_.name); + context.reply("Plugin command failed."); + } + } + + std::string_view getDescription() const override + { + return command_.description; + } + std::string_view getUsage() const override { return command_.usage; } + CommandCategory getCategory() const override + { + return static_cast( + std::min(command_.category, + static_cast(CommandCategory::Admin))); + } + std::vector getAliases() const override + { + std::vector aliases; + aliases.reserve(command_.aliases.size()); + for (const auto& alias : command_.aliases) aliases.push_back(alias); + return aliases; + } + bool requiresAdmin() const override { return command_.adminOnly; } + + private: + Void::Plugin::PluginManager& plugins_; + std::string plugin_; + Api::ExtensionCommand command_; + }; + } + + class PluginTrackSource final : public ITrackSource + { + public: + PluginTrackSource(std::weak_ptr host, + Void::Plugin::PluginManager& plugins, std::string plugin, + Api::ExtensionMediaSource source) + : host_(std::move(host)), plugins_(plugins), plugin_(std::move(plugin)), + source_(std::move(source)) + { + } + std::string_view name() const override { return source_.name; } + bool canHandle(const std::string& query) const override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + return extension && declaredBy(*extension) && + extension->canHandleMedia(source_.name, query); + } catch (...) { + return false; + } + } + bool isAvailable() const override + { + try { + if (host_.expired()) return false; + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + return extension && declaredBy(*extension); + } catch (...) { + return false; + } + } + bool supportsSearch() const override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) return false; + auto descriptors = extension->mediaSources(); + auto descriptor = std::ranges::find( + descriptors, source_.name, &Api::ExtensionMediaSource::name); + return descriptor != descriptors.end() && descriptor->supportsSearch; + } catch (...) { + return false; + } + } + [[nodiscard]] bool represents(std::string_view plugin, + std::string_view source) const + { + return plugin_ == plugin && source_.name == source; + } + Api::Result search(std::string_view query) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin media source unavailable"); + return extension->searchMedia(source_.name, query); + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, error.what()); + } catch (...) { + return Api::fail(Api::ErrorCode::UnknownError, + "plugin media search threw an exception"); + } + } + Api::Result resolve(const std::string& query) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin media source unavailable"); + return extension->resolveMedia(source_.name, query); + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, error.what()); + } catch (...) { + return Api::fail(Api::ErrorCode::UnknownError, + "plugin media resolve threw an exception"); + } + } + Api::Result getStream(const Api::TrackInfo& track) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin media source unavailable"); + auto result = extension->streamMedia(source_.name, track); + if (!result) return std::unexpected(result.error()); + return StreamHandle{.url = std::move(result->url), + .isLocalFile = result->localFile, .sourceName = source_.name}; + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, error.what()); + } catch (...) { + return Api::fail(Api::ErrorCode::UnknownError, + "plugin media stream threw an exception"); + } + } + + private: + [[nodiscard]] bool declaredBy(Api::IExtensionPlugin& extension) const + { + auto descriptors = extension.mediaSources(); + return std::ranges::find(descriptors, source_.name, + &Api::ExtensionMediaSource::name) != descriptors.end(); + } + + std::weak_ptr host_; + Void::Plugin::PluginManager& plugins_; + std::string plugin_; + Api::ExtensionMediaSource source_; + }; + + PluginHost::PluginHost(CommandManager& commands, + std::shared_ptr music, std::function isAdmin, + std::function)> mediaSink) + : commands_(commands), music_(std::move(music)), + isAdmin_(std::move(isAdmin)), mediaSink_(std::move(mediaSink)), + plugins_(Void::Plugin::PluginManager::Options{ + .dlclose_on_swap = false, + .copy_on_load = true, + .config_provider = {}, + .instance_validator = [](Void::Plugin::IPlugin& plugin, + const Void::Plugin::PluginInfo&) { + return dynamic_cast(&plugin) != nullptr; + }}) + { + reloadCallback_ = plugins_.on_reloaded( + [this](std::string_view name) { publish(name); }); + } + + PluginHost::~PluginHost() + { + plugins_.remove_on_reloaded(reloadCallback_); + for (const auto& name : plugins_.names()) unpublish(name); + } + + void PluginHost::loadDirectory(const std::filesystem::path& directory) + { + for (auto& [path, result] : plugins_.load_directory(directory)) { + if (!result) { + Void::Log::warn("PluginHost", "Failed to load '{}': {}", + path.string(), Void::Plugin::to_string(result.error())); + continue; + } + publish(*result); + plugins_.watch(*result); + } + } + + void PluginHost::setChangeCallback(std::function callback) + { + std::lock_guard lock(mutex_); + changeCallback_ = std::move(callback); + } + + void PluginHost::notifyChanged() const + { + std::function callback; + { + std::lock_guard lock(mutex_); + callback = changeCallback_; + } + if (callback) callback(); + } + + void PluginHost::publish(std::string_view name) + { + unpublish(name); + auto pin = plugins_.acquire(name); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) return; + std::vector commands; + std::vector mediaSources; + try { + commands = extension->commands(); + mediaSources = extension->mediaSources(); + } catch (const std::exception& error) { + Void::Log::error("PluginHost", "Plugin '{}' descriptors threw: {}", + name, error.what()); + return; + } catch (...) { + Void::Log::error("PluginHost", "Plugin '{}' descriptors threw", name); + return; + } + for (const auto& descriptor : commands) { + auto command = std::make_shared( + plugins_, std::string(name), descriptor); + if (!commands_.registerExternalCommand( + std::string(name), descriptor.name, std::move(command))) { + Void::Log::warn("PluginHost", "Command '{}' from '{}' conflicts", + descriptor.name, name); + } + } + for (auto source : mediaSources) { + { + std::lock_guard lock(mutex_); + if (std::ranges::any_of(sources_, [&](const auto& existing) { + return existing->represents(name, source.name); + })) continue; + } + auto proxy = std::make_shared( + weak_from_this(), plugins_, std::string(name), std::move(source)); + music_->addTrackSource(proxy); + if (mediaSink_) mediaSink_(proxy); + std::lock_guard lock(mutex_); + sources_.push_back(std::move(proxy)); + } + Void::Log::info("PluginHost", "Published Echoion plugin '{}'", name); + notifyChanged(); + } + + void PluginHost::unpublish(std::string_view name) + { + commands_.unregisterExternalCommands(name); + } + + void PluginHost::dispatch(const Api::PluginEvent& event) const + { + for (const auto& name : plugins_.names()) { + try { + auto pin = plugins_.acquire(name); + if (auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr) { + extension->onEvent(event); + } + } catch (const std::exception& error) { + Void::Log::error("PluginHost", "Plugin '{}' event handler threw: {}", + name, error.what()); + } catch (...) { + Void::Log::error("PluginHost", "Plugin '{}' event handler threw", name); + } + } + } + + Api::Result PluginHost::call( + std::string_view plugin, std::string_view method, std::string params, + uint64_t clientId) const + { + try { + auto pin = plugins_.acquire(plugin); + auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr; + if (!extension) return Api::fail(Api::ErrorCode::NotFound, + "plugin not found"); + auto rpc = extension->rpcMethods(); + auto descriptor = std::ranges::find(rpc, method, &Api::ExtensionRpc::name); + if (descriptor == rpc.end()) return Api::fail(Api::ErrorCode::NotFound, + "plugin RPC method not found"); + if (descriptor->adminOnly && (!isAdmin_ || !isAdmin_(clientId))) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "admin privileges required"); + } + return extension->callRpc({.method = std::string(method), + .params = std::move(params), .clientId = clientId}); + } catch (const std::exception& error) { + Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw: {}", + plugin, method, error.what()); + return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed"); + } catch (...) { + Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw", plugin, method); + return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed"); + } + } + + std::vector PluginHost::webAssets() const + { + std::vector assets; + for (const auto& name : plugins_.names()) { + try { + auto pin = plugins_.acquire(name); + if (auto* extension = pin + ? dynamic_cast(pin.get()) : nullptr) { + auto current = extension->webAssets(); + assets.insert(assets.end(), std::make_move_iterator(current.begin()), + std::make_move_iterator(current.end())); + } + } catch (const std::exception& error) { + Void::Log::error("PluginHost", "Plugin '{}' web assets threw: {}", + name, error.what()); + } catch (...) { + Void::Log::error("PluginHost", "Plugin '{}' web assets threw", name); + } + } + return assets; + } + + std::vector PluginHost::names() const { return plugins_.names(); } + + std::vector PluginHost::snapshotStates() const + { + std::vector states; + for (const auto& name : plugins_.names()) { + if (auto state = plugins_.serialize_state(name)) { + states.push_back({.name = name, .json = std::move(state->json), + .version = state->version}); + } + } + return states; + } + + void PluginHost::restoreStates(const std::vector& states) + { + for (const auto& state : states) { + if (!plugins_.deserialize_state(state.name, state.json, state.version)) { + Void::Log::warn("PluginHost", "Plugin '{}' rejected restored state", + state.name); + } + } + } +} diff --git a/src/RpcServer.cpp b/src/RpcServer.cpp index 0e6b4a1..b548182 100644 --- a/src/RpcServer.cpp +++ b/src/RpcServer.cpp @@ -373,11 +373,16 @@ namespace Echoion::Core response.result = *result; } else { response.success = false; - response.error = std::format( - "{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}", - static_cast(result.error().code), - result.error().message, - result.error().source); + // Error text can include quoted TeamSpeak permission names + // or other protocol detail. Serialize it as JSON instead of + // interpolating it into JSON syntax so the browser always + // receives a decodable error. + response.error = Void::Json::serialize(Void::Json::object( + {{"code", Void::Json::Value{static_cast( + result.error().code)}}, + {"message", Void::Json::Value{result.error().message}}, + {"source", + Void::Json::Value{result.error().source}}})); } } else { response.success = false; diff --git a/src/TeamSpeakDirectoryService.cpp b/src/TeamSpeakDirectoryService.cpp new file mode 100644 index 0000000..93e0f91 --- /dev/null +++ b/src/TeamSpeakDirectoryService.cpp @@ -0,0 +1,265 @@ +#include "echoion/core/TeamSpeakDirectoryService.hpp" + +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + namespace + { + using Void::Json::Value; + + Value optionalId(const std::optional& id) + { + return id ? Value{static_cast(*id)} : Value{nullptr}; + } + + Value publicClient(const Api::ClientInfo& client) + { + return Void::Json::object({{"nickname", Value{client.nickname}}, + {"talking", Value{client.isTalking}}, + {"muted", Value{client.isMuted}}, + {"deafened", Value{client.isDeafened}}, + {"away", Value{client.isAway}}}); + } + + Value adminClient(const Api::ClientInfo& client) + { + Value::Array_t groups; + groups.reserve(client.serverGroups.size()); + for (const auto group : client.serverGroups) { + groups.emplace_back(static_cast(group)); + } + return Void::Json::object( + {{"id", Value{static_cast(client.id)}}, + {"databaseId", optionalId(client.databaseId)}, + {"uid", client.uniqueIdentifier + ? Value{*client.uniqueIdentifier} + : Value{nullptr}}, + {"nickname", Value{client.nickname}}, + {"channelId", Value{static_cast(client.channelId)}}, + {"talking", Value{client.isTalking}}, + {"muted", Value{client.isMuted}}, + {"deafened", Value{client.isDeafened}}, + {"away", Value{client.isAway}}, + {"groups", Void::Json::array(std::move(groups))}}); + } + + Value channelMetadata(const Api::ChannelInfo& channel) + { + return Void::Json::object( + {{"id", Value{static_cast(channel.id)}}, + {"name", Value{channel.name}}, + {"parentId", optionalId(channel.parentId)}, + {"order", Value{static_cast(channel.order)}}, + {"default", Value{channel.isDefault}}, + {"permanent", Value{channel.isPermanent}}, + {"semiPermanent", Value{channel.isSemiPermanent}}, + {"password", Value{channel.hasPassword}}, + {"maxClients", + Value{static_cast(channel.maxClients)}}, + {"currentClients", + Value{static_cast(channel.currentClients)}}}); + } + + Value buildChannelTree(const std::vector& channels, + const std::vector& clients, + const std::optional + parent, + bool admin) + { + Value::Array_t result; + for (const auto& channel : channels) { + if (channel.parentId != parent) { + continue; + } + auto node = channelMetadata(channel); + Value::Array_t members; + for (const auto& client : clients) { + if (client.channelId != channel.id || client.isQuery) { + continue; + } + members.push_back(admin ? adminClient(client) + : publicClient(client)); + } + node.as_object().emplace_back( + "clients", Void::Json::array(std::move(members))); + node.as_object().emplace_back( + "channels", + buildChannelTree(channels, clients, channel.id, admin)); + result.push_back(std::move(node)); + } + return Void::Json::array(std::move(result)); + } + + Value serverJson(const TeamSpeakDirectoryService::Snapshot& snapshot) + { + const auto visibleClients = + std::ranges::count_if(snapshot.clients, [](const auto& client) { + return !client.isQuery; + }); + return Void::Json::object( + {{"name", Value{snapshot.server.name}}, + {"connected", Value{snapshot.connected}}, + {"clientCount", Value{static_cast(visibleClients)}}, + {"maxClients", + Value{static_cast(snapshot.server.maxClients)}}, + {"channelCount", + Value{static_cast(snapshot.channels.size())}}, + {"revision", + Value{static_cast(snapshot.revision)}}}); + } + } // namespace + + void TeamSpeakDirectoryService::setPluginInterface( + Api::PluginInterfacePtr plugin) + { + { + std::lock_guard lock{mutex_}; + plugin_ = std::move(plugin); + } + (void)refresh(); + } + + Api::Result TeamSpeakDirectoryService::refresh() + { + Api::PluginInterfacePtr plugin; + { + std::lock_guard lock{mutex_}; + plugin = plugin_; + } + if (!plugin) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "TeamSpeak interface is unavailable"); + } + + // Host calls may block or invoke callbacks. Never hold the cache lock + // while crossing that boundary. + auto channelsResult = plugin->getChannels(); + if (!channelsResult) { + return std::unexpected(channelsResult.error()); + } + auto clientsResult = plugin->getClients(); + if (!clientsResult) { + return std::unexpected(clientsResult.error()); + } + + Snapshot next; + next.connected = plugin->isConnected(); + next.channels = orderChannels(std::move(*channelsResult)); + for (auto& channel : next.channels) { + // TeamSpeak uses 0 as the root parent while the API model uses an + // absent value. Normalize once so both serializers build one tree. + if (channel.parentId == 0) { + channel.parentId.reset(); + } + } + next.clients = std::move(*clientsResult); + if (auto server = plugin->getTeamSpeakServerInfo(); server) { + next.server = std::move(*server); + } + + // Counts derived from the same snapshot cannot disagree with the tree, + // even when a host does not expose TeamSpeak's aggregate properties. + for (auto& channel : next.channels) { + channel.currentClients = static_cast( + std::ranges::count_if(next.clients, [&](const auto& client) { + return !client.isQuery && client.channelId == channel.id; + })); + } + next.server.currentClients = static_cast( + std::ranges::count_if(next.clients, [](const auto& client) { + return !client.isQuery; + })); + + { + std::lock_guard lock{mutex_}; + next.revision = snapshot_.revision + 1; + snapshot_ = std::move(next); + } + return {}; + } + + void TeamSpeakDirectoryService::handleEvent(Api::PluginEventType type) + { + switch (type) { + case Api::PluginEventType::ConnectionEstablished: + case Api::PluginEventType::ClientConnected: + case Api::PluginEventType::ClientDisconnected: + case Api::PluginEventType::ClientMoved: + case Api::PluginEventType::ClientUpdated: + case Api::PluginEventType::ChannelUpdated: + (void)refresh(); + break; + default: + break; + } + } + + TeamSpeakDirectoryService::Snapshot + TeamSpeakDirectoryService::snapshot() const + { + std::lock_guard lock{mutex_}; + return snapshot_; + } + + Value TeamSpeakDirectoryService::publicJson() const + { + const auto current = snapshot(); + return Void::Json::object( + {{"server", serverJson(current)}, + {"channels", buildChannelTree(current.channels, current.clients, + std::nullopt, false)}}); + } + + Value TeamSpeakDirectoryService::adminJson() const + { + const auto current = snapshot(); + return Void::Json::object( + {{"server", serverJson(current)}, + {"channels", buildChannelTree(current.channels, current.clients, + std::nullopt, true)}}); + } + + std::vector TeamSpeakDirectoryService::orderChannels( + std::vector channels) + { + std::map, std::vector> + byParent; + for (auto& channel : channels) { + byParent[channel.parentId].push_back(std::move(channel)); + } + + std::vector ordered; + ordered.reserve(channels.size()); + for (auto& [parent, siblings] : byParent) { + (void)parent; + std::set emitted; + std::uint64_t predecessor = 0; + for (;;) { + auto next = + std::ranges::find_if(siblings, [&](const auto& channel) { + return channel.order == predecessor && + !emitted.contains(channel.id); + }); + if (next == siblings.end()) { + break; + } + predecessor = next->id; + emitted.insert(next->id); + ordered.push_back(*next); + } + std::ranges::sort(siblings, {}, &Api::ChannelInfo::id); + for (const auto& orphan : siblings) { + if (!emitted.contains(orphan.id)) { + ordered.push_back(orphan); + } + } + } + return ordered; + } + +} // namespace Echoion::Core diff --git a/src/sources/SourceRouter.cpp b/src/sources/SourceRouter.cpp index 273e460..add76b6 100644 --- a/src/sources/SourceRouter.cpp +++ b/src/sources/SourceRouter.cpp @@ -38,6 +38,14 @@ namespace Echoion::Core } } + void SourceRouter::addSource(std::shared_ptr source) + { + if (!source) return; + std::lock_guard lock(mutex_); + allSources_.push_back(source); + chain_.push_back(SourceState{.source = std::move(source)}); + } + void SourceRouter::setOrder(const std::vector& order) { std::lock_guard lock(mutex_); @@ -73,13 +81,13 @@ namespace Echoion::Core hedgeDelay_ = std::max(delay, std::chrono::milliseconds(0)); } - std::vector - SourceRouter::candidatesFor(const std::string& query, bool needSearch) + std::vector> + SourceRouter::candidatesFor(const std::string& query, bool needSearch) { // Callers hold mutex_. const auto now = std::chrono::steady_clock::now(); - std::vector eligible; - std::vector coolingDown; + std::vector> eligible; + std::vector> coolingDown; for (auto& state : chain_) { if (needSearch && !state.source->supportsSearch()) { @@ -89,10 +97,10 @@ namespace Echoion::Core continue; } if (state.cooldownUntil > now) { - coolingDown.push_back(&state); + coolingDown.push_back(state.source); continue; } - eligible.push_back(&state); + eligible.push_back(state.source); } // A source on cooldown is still tried when nothing else matched — // better a likely-failing attempt than an immediate error. @@ -102,13 +110,17 @@ namespace Echoion::Core return eligible; } - void SourceRouter::reportFailure(SourceState& state) + void SourceRouter::reportFailure(const std::shared_ptr& source) { - state.cooldownUntil = std::chrono::steady_clock::now() + cooldown_; + auto state = std::ranges::find_if(chain_, [&](const SourceState& candidate) { + return candidate.source == source; + }); + if (state == chain_.end()) return; + state->cooldownUntil = std::chrono::steady_clock::now() + cooldown_; Void::Log::info( "SourceRouter", "{}", std::format("Source '{}' on cooldown for {}s", - state.source->name(), cooldown_.count() / 1000)); + source->name(), cooldown_.count() / 1000)); } Api::Result SourceRouter::search(std::string_view query) @@ -119,17 +131,17 @@ namespace Echoion::Core Api::Error lastError{Api::ErrorCode::ServiceUnavailable, "No source can search"}; - for (auto* state : candidates) { - if (!state->source->isAvailable()) { + for (const auto& source : candidates) { + if (!source->isAvailable()) { continue; } - auto result = state->source->search(query); + auto result = source->search(query); if (result) { return result; } lastError = result.error(); std::lock_guard relock(mutex_); - reportFailure(*state); + reportFailure(source); } return std::unexpected(lastError); } @@ -142,21 +154,21 @@ namespace Echoion::Core Api::Error lastError{Api::ErrorCode::NotFound, "No source can resolve this query"}; - for (auto* state : candidates) { - if (!state->source->isAvailable()) { + for (const auto& source : candidates) { + if (!source->isAvailable()) { continue; } Void::Log::debug( "SourceRouter", "{}", std::format("Resolving '{}' via {}", query, - state->source->name())); - auto result = state->source->resolve(query); + source->name())); + auto result = source->resolve(query); if (result) { return result; } lastError = result.error(); std::lock_guard relock(mutex_); - reportFailure(*state); + reportFailure(source); } return std::unexpected(lastError); } @@ -191,10 +203,10 @@ namespace Echoion::Core const auto hedgeDelay = hedgeDelay_; lock.unlock(); - std::vector eligible; - for (auto* state : candidates) { - if (state->source->isAvailable()) { - eligible.push_back(state); + std::vector> eligible; + for (const auto& source : candidates) { + if (source->isAvailable()) { + eligible.push_back(source); } } @@ -253,7 +265,7 @@ namespace Echoion::Core }).detach(); }; - launch(eligible[0]->source, 0); + launch(eligible[0], 0); int launched = 1; std::optional> winner; std::array failed{false, false}; @@ -267,7 +279,7 @@ namespace Echoion::Core if (!state->winner) { // A is slow or already failed: bring in B. lk.unlock(); - launch(eligible[1]->source, 1); + launch(eligible[1], 1); launched = 2; lk.lock(); state->cv.wait(lk, [&] { @@ -291,11 +303,9 @@ namespace Echoion::Core "SourceRouter", "{}", std::format( "Source '{}' failed stream for '{}': {}", - eligible[static_cast(slot)] - ->source->name(), + eligible[static_cast(slot)]->name(), cacheKey, lastError.message)); - reportFailure( - *eligible[static_cast(slot)]); + reportFailure(eligible[static_cast(slot)]); } } } @@ -308,8 +318,8 @@ namespace Echoion::Core // Sequential pass over the remaining candidates (or all of them // when hedging is disabled). for (; index < eligible.size(); ++index) { - auto* state = eligible[index]; - auto handle = state->source->getStream(track); + const auto& source = eligible[index]; + auto handle = source->getStream(track); if (handle) { return finish(std::move(handle)); } @@ -317,10 +327,10 @@ namespace Echoion::Core Void::Log::warn( "SourceRouter", "{}", std::format("Source '{}' failed stream for '{}': {}", - state->source->name(), cacheKey, + source->name(), cacheKey, handle.error().message)); std::lock_guard relock(mutex_); - reportFailure(*state); + reportFailure(source); } return std::unexpected(lastError); } diff --git a/src/state/StateSerializer.cpp b/src/state/StateSerializer.cpp index 2510bbd..276afef 100644 --- a/src/state/StateSerializer.cpp +++ b/src/state/StateSerializer.cpp @@ -101,33 +101,12 @@ namespace Echoion::Core uint32_t StateSerializer::extractVersion(const std::string& jsonStr) { - // Quick extraction without full parse - // Look for "version": N pattern - size_t pos = jsonStr.find("\"version\""); - if (pos != std::string::npos) { - pos = jsonStr.find(':', pos); - if (pos != std::string::npos) { - // Skip whitespace - pos++; - while (pos < jsonStr.size() && - std::isspace(static_cast(jsonStr[pos]))) { - pos++; - } - // Parse number - if (pos < jsonStr.size() && - std::isdigit(static_cast(jsonStr[pos]))) { - try { - return static_cast( - std::stoul(jsonStr.substr(pos))); - } catch (const std::exception&) { - return 0; - } - } - } - } - - // Default to 0 (unknown/legacy) - return 0; + // Read only the root field. A textual search can accidentally select a + // nested schema version (for example an extension plugin's state). + auto parsed = Void::Json::parse(jsonStr); + if (!parsed || !parsed->is_object()) return 0; + const auto version = parsed->get_num("version", 0); + return version > 0 ? static_cast(version) : 0; } } // namespace Echoion::Core diff --git a/tests/test_extension_state.cpp b/tests/test_extension_state.cpp new file mode 100644 index 0000000..71f40e4 --- /dev/null +++ b/tests/test_extension_state.cpp @@ -0,0 +1,34 @@ +#include "echoion/core/state/StateSerializer.hpp" + +#include +#include + +int main() +{ + Echoion::Core::StateV1 state; + state.extensionPlugins.push_back({.name = "example", .json = "{\"v\":1}", + .version = 3}); + + auto blob = Echoion::Core::StateSerializer::serialize(state); + std::string json{blob.data.begin(), blob.data.end()}; + // State written by the removed experimental rooms build must remain safe to + // load during a hot reload. Void reflection intentionally ignores unknown + // root fields, so the obsolete payload is discarded rather than rejected. + json.insert(json.rfind('}'), + R"(,"listeningRooms":[{"name":"legacy","subscribers":["uid"]}])"); + blob.data.assign(json.begin(), json.end()); + + const auto restored = Echoion::Core::StateSerializer::deserialize(blob); + if (!restored) { + std::cerr << "extension state did not deserialize: " + << restored.error().message << '\n'; + return 1; + } + if (restored->extensionPlugins.size() != 1 || + restored->extensionPlugins.front().name != "example" || + restored->extensionPlugins.front().version != 3) { + std::cerr << "extension plugin state did not round-trip\n"; + return 1; + } + return 0; +} diff --git a/tests/test_listening_room_state.cpp b/tests/test_listening_room_state.cpp deleted file mode 100644 index 59329f9..0000000 --- a/tests/test_listening_room_state.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#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; -} diff --git a/tests/test_teamspeak_directory.cpp b/tests/test_teamspeak_directory.cpp new file mode 100644 index 0000000..65cfeb8 --- /dev/null +++ b/tests/test_teamspeak_directory.cpp @@ -0,0 +1,188 @@ +#include "echoion/core/TeamSpeakDirectoryService.hpp" +#include "echoion/core/detail/RpcValidation.hpp" + +#include + +#include +#include +#include +#include +#include + +namespace +{ + class FakePlugin final : public Echoion::Api::IPluginInterface + { + public: + + Echoion::Api::Result initialize() override { return {}; } + Echoion::Api::Result shutdown() override { return {}; } + Echoion::Api::Result> + getClients() override + { + return clients; + } + Echoion::Api::Result> + getClient(uint64_t id) override + { + for (const auto& client : clients) { + if (client.id == id) { + return client; + } + } + return std::optional{}; + } + Echoion::Api::Result moveClient(uint64_t, uint64_t) override + { + return {}; + } + Echoion::Api::Result kickClient(uint64_t, + const std::string&) override + { + return {}; + } + Echoion::Api::Result> + getChannels() const override + { + return channels; + } + Echoion::Api::Result> + getChannel(uint64_t id) const override + { + for (const auto& channel : channels) { + if (channel.id == id) { + return channel; + } + } + return std::optional{}; + } + Echoion::Api::Result + sendTextMessage(uint64_t, const std::string&) override + { + return {}; + } + Echoion::Api::Result + sendChannelMessage(uint64_t, const std::string&) override + { + return {}; + } + Echoion::Api::Result + sendServerMessage(const std::string&) override + { + return {}; + } + Echoion::Api::Result + sendAudioData(const std::span&) override + { + return {}; + } + Echoion::Api::Result + setWhisperList(const std::vector&) override + { + return {}; + } + Echoion::Api::Result + connectToServer(const Echoion::Api::ServerConfig&) override + { + return {}; + } + Echoion::Api::Result disconnectFromServer() override + { + return {}; + } + bool isConnected() const override { return connected; } + Echoion::Api::Result reconnect() override { return {}; } + void registerEventCallback( + const Echoion::Api::EventCallback&) override + { + } + void unregisterEventCallback( + const Echoion::Api::EventCallback&) override + { + } + Echoion::Api::Result + getTeamSpeakServerInfo() override + { + return Echoion::Api::ServerInfo{ + .name = "Fixture", .welcomeMessage = "", .maxClients = 64}; + } + + std::vector clients; + std::vector channels; + bool connected = true; + }; +} // namespace + +int main() +{ + using Echoion::Api::ChannelInfo; + using Echoion::Api::ClientInfo; + using Echoion::Core::TeamSpeakDirectoryService; + + const auto validId = Void::Json::parse(R"({"id":42})"); + const auto fractionalId = Void::Json::parse(R"({"id":1.5})"); + const auto negativeId = Void::Json::parse(R"({"id":-1})"); + const auto overflowingId = + Void::Json::parse(R"({"id":18446744073709551616})"); + const auto enormousId = Void::Json::parse(R"({"id":1e100})"); + assert(validId && Echoion::Core::Detail::uintField(*validId, "id") == 42); + assert(fractionalId && + !Echoion::Core::Detail::uintField(*fractionalId, "id")); + assert(negativeId && !Echoion::Core::Detail::uintField(*negativeId, "id")); + assert(overflowingId && + !Echoion::Core::Detail::uintField(*overflowingId, "id")); + assert(enormousId && !Echoion::Core::Detail::uintField(*enormousId, "id")); + + auto plugin = std::make_shared(); + plugin->channels = { + ChannelInfo{.id = 2, .name = "Second", .parentId = 0, .order = 1}, + ChannelInfo{.id = 1, .name = "First", .parentId = 0, .order = 0}, + ChannelInfo{.id = 3, .name = "Child", .parentId = 1, .order = 0}}; + plugin->clients = {ClientInfo{.id = 10, + .databaseId = 110, + .nickname = "Visible", + .uniqueIdentifier = "secret-uid", + .channelId = 1, + .isTalking = true, + .serverGroups = {7}}, + ClientInfo{.id = 11, + .databaseId = std::nullopt, + .nickname = "Query Client", + .uniqueIdentifier = "query-secret", + .channelId = 1, + .isQuery = true, + .serverGroups = {}}}; + + TeamSpeakDirectoryService service; + service.setPluginInterface(plugin); + const auto publicJson = Void::Json::serialize(service.publicJson()); + assert(publicJson.contains("Visible")); + assert(publicJson.find("First") < publicJson.find("Second")); + assert(!publicJson.contains("Query Client")); + assert(!publicJson.contains("secret-uid")); + assert(!publicJson.contains("databaseId")); + assert(!publicJson.contains("groups")); + + const auto adminJson = Void::Json::serialize(service.adminJson()); + assert(adminJson.contains("secret-uid")); + assert(adminJson.contains("databaseId")); + assert(!adminJson.contains("Query Client")); + + const auto ordered = TeamSpeakDirectoryService::orderChannels( + {ChannelInfo{.id = 2, .name = "", .parentId = std::nullopt, .order = 1}, + ChannelInfo{.id = 1, .name = "", .parentId = std::nullopt, .order = 0}, + ChannelInfo{ + .id = 9, .name = "", .parentId = std::nullopt, .order = 99}}); + assert(ordered.size() == 3); + assert(ordered[0].id == 1); + assert(ordered[1].id == 2); + assert(ordered[2].id == 9); + + plugin->connected = false; + plugin->clients.clear(); + plugin->channels.clear(); + service.handleEvent(Echoion::Api::PluginEventType::ChannelUpdated); + const auto disconnected = Void::Json::serialize(service.publicJson()); + assert(disconnected.contains("\"connected\":false")); + assert(!disconnected.contains("Visible")); +}