diff --git a/.gitignore b/.gitignore index 3a34447..6b24400 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ *build* +release +.claude .cache .idea AGENTS.md diff --git a/.gitmodules b/.gitmodules index de313f3..b9aca0d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,9 +4,6 @@ [submodule "EchoionCore"] path = EchoionCore url = ssh://gitea@git.faumaray.ru/void/echoioncore.git -[submodule "EchoionPlugin"] - path = EchoionPlugin - url = ssh://gitea@git.faumaray.ru/void/echoionplugin.git [submodule "EchoionDesktop"] path = EchoionDesktop url = ssh://gitea@git.faumaray.ru/void/echoiondesktop.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 221ccb7..ed18f3e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -127,10 +127,9 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON) # Options option(BUILD_API "Build EchoionApi" ON) option(BUILD_CORE "Build EchoionCore" ON) -option(BUILD_PLUGIN "Build archived EchoionPlugin compatibility target" OFF) option(BUILD_DESKTOP "Build EchoionDesktop" ON) -option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON) -option(BUILD_STANDALONE "Build EchoionStandalone (daemon; no TeamSpeak client)" ON) +option(BUILD_WEB "Build EchoionWeb browser dashboard" ON) +option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON) option(BUILD_TESTS "Build tests" OFF) if(BUILD_TESTS) @@ -145,7 +144,7 @@ if(BUILD_API) add_subdirectory(EchoionApi) endif() -if(BUILD_PLUGIN OR BUILD_STANDALONE) +if(BUILD_STANDALONE) add_subdirectory(EchoionHost) endif() @@ -164,12 +163,8 @@ if(BUILD_WEB AND BUILD_CORE) endif() endif() -if(BUILD_PLUGIN) - add_subdirectory(EchoionPlugin) -endif() - # VoidTeamspeak is resolved above as a regular reusable package. The legacy -# in-tree EchoionProtocol directory is intentionally no longer built. +# TeamSpeak client plugin and in-tree protocol directories are no longer built. # EchoionStandalone links the host-common loader and native protocol client. if(BUILD_STANDALONE) @@ -282,10 +277,6 @@ if(BUILD_CORE AND TARGET EchoionCore) install_with_dependencies(EchoionCore) endif() -if(BUILD_PLUGIN AND TARGET EchoionPlugin) - install_with_dependencies(EchoionPlugin) -endif() - # Print configuration summary message(STATUS "") message(STATUS "Echoion Configuration:") @@ -293,7 +284,6 @@ message(STATUS " Version: ${PROJECT_VERSION}") message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") message(STATUS " Build API: ${BUILD_API}") message(STATUS " Build Core: ${BUILD_CORE}") -message(STATUS " Build Plugin: ${BUILD_PLUGIN}") message(STATUS " Build Desktop: ${BUILD_DESKTOP}") message(STATUS " Build Tests: ${BUILD_TESTS}") message(STATUS " Static Link: ${ECHOION_STATIC_LINK}") diff --git a/EchoionApi b/EchoionApi index 295542a..24075fb 160000 --- a/EchoionApi +++ b/EchoionApi @@ -1 +1 @@ -Subproject commit 295542ab9e80c609de3babdc2540025ae094d8bb +Subproject commit 24075fbd52f006639ea606b9e9447a19a4135406 diff --git a/EchoionCore b/EchoionCore index 01362d2..39aff68 160000 --- a/EchoionCore +++ b/EchoionCore @@ -1 +1 @@ -Subproject commit 01362d2e513bdbdb993a0ec5701ebc1fdc1ffb8c +Subproject commit 39aff68d8d79d3e5d5c92e0c10f20d7fc4c6a4e0 diff --git a/EchoionPlugin b/EchoionPlugin deleted file mode 160000 index 470ab50..0000000 --- a/EchoionPlugin +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 470ab507e16fcdf4dfd8ab8bdc385258979032ef diff --git a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp index 479f6ea..ec1353c 100644 --- a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp @@ -1,10 +1,8 @@ #pragma once -// Implements Echoion's IPluginInterface against the native TeamSpeak UDP -// protocol through VoidTeamspeak instead of the TS3 Client Plugin SDK. This is the -// single seam that lets the whole Core run as a standalone application: Core -// only ever talks to IPluginInterface, so swapping this implementation in for -// the plugin drops the TeamSpeak-client dependency entirely. +// Implements Echoion's host interface by adapting VoidTeamspeak's typed client +// operations and events. TeamSpeak protocol details remain inside +// VoidTeamspeak; Core only sees the host-neutral Echoion API contract. #include @@ -63,12 +61,42 @@ namespace Echoion::Standalone uint64_t channelId) override; Api::Result kickClient(uint64_t clientId, const std::string& reason) override; + Api::Result + kickClientFromChannel(uint64_t clientId, + const std::string& reason) override; + Api::Result banClient(uint64_t clientId, + uint64_t durationSeconds, + const std::string& reason) override; + [[nodiscard]] Api::Result> + getBans() override; + Api::Result unban(uint64_t banId) override; // Channels [[nodiscard]] Api::Result> getChannels() const override; [[nodiscard]] Api::Result> getChannel(uint64_t channelId) const override; + Api::Result createChannel( + const Api::ChannelCreateOptions& options) override; + Api::Result + editChannel(uint64_t channelId, + const Api::ChannelEditOptions& options) override; + Api::Result reorderChannel(uint64_t channelId, + uint64_t parentId, + uint64_t orderAfterId) override; + Api::Result deleteChannel(uint64_t channelId, + bool force) override; + + [[nodiscard]] Api::Result> + getServerGroups() override; + Api::Result + addClientToServerGroup(uint64_t groupId, + uint64_t clientDatabaseId) override; + Api::Result + removeClientFromServerGroup(uint64_t groupId, + uint64_t clientDatabaseId) override; + [[nodiscard]] Api::Result + getTeamSpeakServerInfo() override; // Messaging Api::Result @@ -85,14 +113,6 @@ namespace Echoion::Standalone sendAudioData(const std::span& data) override; Api::Result setWhisperList(const std::vector& clientIds) override; - [[nodiscard]] Api::Result - createAudioStream(const AudioStreamOptions& options) override; - Api::Result destroyAudioStream(AudioStreamId id) override; - Api::Result sendAudioDataToStream( - AudioStreamId id, const std::span& data) override; - Api::Result setAudioStreamRecipients( - AudioStreamId id, - const std::vector& recipients) override; // Connection Api::Result @@ -102,28 +122,22 @@ namespace Echoion::Standalone Api::Result reconnect() override; // Events - void - registerEventCallback(const Api::EventCallback& cb) override; - void - unregisterEventCallback(const Api::EventCallback& cb) override; - // Prevent new event dispatches, release registered callbacks and wait - // until every callback already in flight has returned. The host must - // call this before unloading code that owns an event callback. + void registerEventCallback(const Api::EventCallback& cb) override; + void unregisterEventCallback(const Api::EventCallback& cb) override; + // Prevent new event dispatches, release registered callbacks and + // wait until every callback already in flight has returned. The + // host must call this before unloading code that owns an event + // callback. void quiesceEventCallbacks(); private: void wireCallbacks(); - void onCommand(std::string_view name, - const std::vector& records); - void onTextMessage(const Void::TeamSpeak::CommandFields& params); void broadcast(const Api::PluginEvent& event); - void upsertClientGroup(const Void::TeamSpeak::CommandFields& p, - bool emitConnected); - void refreshClient(const Void::TeamSpeak::CommandFields& params); void loadInitialSnapshot(); [[nodiscard]] Api::Result commandResult( - const Void::Result::Result& result) const; + const Void::Result::Result& + result) const; StandaloneSettings settings_; std::shared_ptr identity_; @@ -134,17 +148,14 @@ namespace Echoion::Standalone std::atomic initialized_{false}; mutable std::mutex mirrorMutex_; - std::map clients_; - std::map channels_; + std::map clients_; + std::map channels_; + std::optional serverInfo_; std::map clientIps_; std::map avatarHashes_; std::map avatarUrls_; std::map avatarPaths_; std::vector whisperList_; - struct AudioStreamRuntime; - std::map> audioStreams_; - std::atomic nextAudioStreamId_{1}; - mutable std::mutex audioStreamsMutex_; std::jthread snapshotThread_; EventCallbackGate eventCallbacks_; diff --git a/EchoionStandalone/src/StandaloneClientInterface.cpp b/EchoionStandalone/src/StandaloneClientInterface.cpp index d54746a..8a3b809 100644 --- a/EchoionStandalone/src/StandaloneClientInterface.cpp +++ b/EchoionStandalone/src/StandaloneClientInterface.cpp @@ -1,64 +1,103 @@ -#include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/AudioEncoder.hpp" #include "echoion/standalone/MessageChunker.hpp" +#include "echoion/standalone/StandaloneClientInterface.hpp" #include -#include #include #include #include #include -#include #include -#include +#include namespace Echoion::Standalone { - struct StandaloneClientInterface::AudioStreamRuntime { - std::mutex mutex; - std::shared_ptr identity; - std::unique_ptr client; - std::unique_ptr encoder; - std::vector recipients; - }; - namespace { constexpr const char* LOG = "Standalone"; - uint64_t toU64(const std::string& s) + Api::Error teamSpeakError(const Void::TeamSpeak::Error& error) { - try { - return std::stoull(s); - } catch (...) { - return 0; + using Code = Void::TeamSpeak::Error::Code; + Api::ErrorCode code = Api::ErrorCode::PluginError; + switch (error.code) { + case Code::InvalidArgument: + code = Api::ErrorCode::InvalidArgument; + break; + case Code::NotConnected: + code = Api::ErrorCode::ServiceUnavailable; + break; + case Code::Timeout: + case Code::Io: + code = Api::ErrorCode::NetworkError; + break; + case Code::NotSupported: + code = Api::ErrorCode::NotSupported; + break; + case Code::Protocol: + break; } + return {code, error.message, "VoidTeamspeak"}; } - std::string get(const Void::TeamSpeak::CommandFields& p, const char* k) + std::optional checkedClientId(uint64_t value) { - auto it = p.find(k); - return it == p.end() ? std::string{} : it->second; - } - - bool isTrue(const std::string& value) - { - return value == "1" || value == "true"; - } - - std::vector parseIds(const std::string& value) - { - std::vector result; - std::istringstream input(value); - std::string item; - while (std::getline(input, item, ',')) { - const auto id = toU64(item); - if (id != 0) { - result.push_back(id); - } + if (value == 0 || value > std::numeric_limits::max()) { + return std::nullopt; } - return result; + return Void::TeamSpeak::ClientId{static_cast(value)}; + } + + Api::ClientInfo apiClient(const Void::TeamSpeak::RemoteClient& client) + { + std::vector groups; + groups.reserve(client.serverGroups.size()); + for (const auto group : client.serverGroups) { + groups.push_back(group.value); + } + return { + .id = client.id.value, + .databaseId = + client.databaseId + ? std::optional{client.databaseId.value} + : std::nullopt, + .nickname = client.nickname, + .uniqueIdentifier = + client.uniqueId.empty() + ? std::nullopt + : std::optional{client.uniqueId}, + .channelId = client.channel.value, + .isTalking = client.talking, + .isMuted = client.muted(), + .isDeafened = client.deafened(), + .isAway = client.away, + .isQuery = client.isQuery(), + .serverGroups = std::move(groups), + }; + } + + Api::ChannelInfo apiChannel(const Void::TeamSpeak::Channel& channel, + uint32_t currentClients) + { + const auto maxClients = + channel.unlimitedClients || channel.maxClients <= 0 + ? 0U + : static_cast(channel.maxClients); + return { + .id = channel.id.value, + .name = channel.name, + .parentId = channel.parent + ? std::optional{channel.parent->value} + : std::nullopt, + .order = channel.orderAfter.value, + .isDefault = channel.defaultChannel, + .isPermanent = channel.permanent, + .isSemiPermanent = channel.semiPermanent, + .hasPassword = channel.passwordProtected, + .maxClients = maxClients, + .currentClients = currentClients, + }; } } // namespace @@ -90,17 +129,6 @@ namespace Echoion::Standalone if (!initialized_.exchange(false)) { return {}; } - std::vector> streams; - { - std::lock_guard lock(audioStreamsMutex_); - streams.reserve(audioStreams_.size()); - for (auto& entry : audioStreams_) streams.push_back(entry.second); - audioStreams_.clear(); - } - for (const auto& stream : streams) { - std::lock_guard lock(stream->mutex); - stream->client->close(); - } if (client_) { client_->close(); } @@ -117,8 +145,8 @@ namespace Echoion::Standalone // ---- Connection -------------------------------------------------------- - Api::Result - StandaloneClientInterface::connectToServer(const Api::ServerConfig& config) + Api::Result StandaloneClientInterface::connectToServer( + const Api::ServerConfig& config) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, @@ -139,7 +167,8 @@ namespace Echoion::Standalone "Generating identity (security level {})...", settings_.securityLevel); identity_ = std::make_shared( - Void::TeamSpeak::Identity::generate(settings_.securityLevel)); + Void::TeamSpeak::Identity::generate( + settings_.securityLevel)); if (!idPath.empty()) { std::filesystem::create_directories(idPath.parent_path()); identity_->save(idPath.string()); @@ -158,15 +187,15 @@ namespace Echoion::Standalone opts.host = config.address; opts.port = config.port ? config.port : 9987; opts.identity = identity_; - opts.nickname = config.nickname.empty() ? "EchoionBot" : config.nickname; + opts.nickname = + config.nickname.empty() ? "EchoionBot" : config.nickname; opts.serverPassword = config.serverPassword; - opts.defaultChannel = - config.defaultChannelId.value_or(std::string{}); + opts.defaultChannel = config.defaultChannelId.value_or(std::string{}); opts.channelPassword = config.channelPassword.value_or(std::string{}); if (auto connected = client_->connect(opts); !connected) { return Api::fail(Api::ErrorCode::NetworkError, - "connect failed: " + connected.error().message); + "connect failed: " + connected.error().message); } Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port, opts.nickname); @@ -185,22 +214,230 @@ namespace Echoion::Standalone }; cb.disconnected = [this] { Void::Log::warn(LOG, "Disconnected from server"); - std::lock_guard lock(mirrorMutex_); - clients_.clear(); - channels_.clear(); - clientIps_.clear(); - avatarHashes_.clear(); - avatarUrls_.clear(); + { + std::lock_guard lock(mirrorMutex_); + clients_.clear(); + channels_.clear(); + serverInfo_.reset(); + clientIps_.clear(); + avatarHashes_.clear(); + avatarUrls_.clear(); + } + + // The directory service refreshes from topology events. Publish one + // after clearing the mirrors so a disconnect cannot leave the + // public dashboard reporting a connected server with stale clients. + Api::PluginEvent event; + event.type = Api::PluginEventType::ChannelUpdated; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); }; cb.error = [](const Void::TeamSpeak::Error& error) { Void::Log::error(LOG, "Protocol error: {}", error.message); }; - cb.commandBatch = [this](const Void::TeamSpeak::CommandEvent& command) { - onCommand(command.name, command.records); - if (command.name == "notifytextmessage") { - for (const auto& record : command.records) onTextMessage(record); + cb.clientEntered = [this](const Void::TeamSpeak::RemoteClient& client) { + { + std::lock_guard lock{mirrorMutex_}; + clients_[client.id.value] = client; } + Api::PluginEvent event; + event.type = Api::PluginEventType::ClientConnected; + event.clientId = client.id.value; + event.clientName = client.nickname; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); }; + cb.clientLeft = [this](const Void::TeamSpeak::ClientLeft& left) { + std::string nickname; + { + std::lock_guard lock{mirrorMutex_}; + if (const auto iterator = clients_.find(left.id.value); + iterator != clients_.end()) { + nickname = iterator->second.nickname; + clients_.erase(iterator); + } + clientIps_.erase(left.id.value); + avatarHashes_.erase(left.id.value); + avatarUrls_.erase(left.id.value); + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ClientDisconnected; + event.clientId = left.id.value; + event.clientName = std::move(nickname); + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.clientMoved = [this](const Void::TeamSpeak::ClientMoved& moved) { + { + std::lock_guard lock{mirrorMutex_}; + auto& client = clients_[moved.id.value]; + client.id = moved.id; + client.channel = moved.channel; + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ClientMoved; + event.clientId = moved.id.value; + event.targetChannelId = moved.channel.value; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.clientUpdated = + [this](const Void::TeamSpeak::ClientUpdated& update) { + { + std::lock_guard lock{mirrorMutex_}; + auto& client = clients_[update.id.value]; + client.id = update.id; + if (update.nickname) { + client.nickname = *update.nickname; + } + if (update.uniqueId) { + client.uniqueId = *update.uniqueId; + } + if (update.inputMuted) { + client.inputMuted = *update.inputMuted; + } + if (update.outputMuted) { + client.outputMuted = *update.outputMuted; + } + if (update.inputHardware) { + client.inputHardware = *update.inputHardware; + } + if (update.outputHardware) { + client.outputHardware = *update.outputHardware; + } + if (update.away) { + client.away = *update.away; + } + if (update.talking) { + client.talking = *update.talking; + } + if (update.recording) { + client.recording = *update.recording; + } + if (update.channelCommander) { + client.channelCommander = *update.channelCommander; + } + if (update.prioritySpeaker) { + client.prioritySpeaker = *update.prioritySpeaker; + } + if (update.avatarHash) { + if (update.avatarHash->empty()) { + avatarHashes_.erase(update.id.value); + } else { + avatarHashes_[update.id.value] = *update.avatarHash; + } + } + if (update.avatarUrl) { + if (update.avatarUrl->empty()) { + avatarUrls_.erase(update.id.value); + } else { + avatarUrls_[update.id.value] = *update.avatarUrl; + } + } + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ClientUpdated; + event.clientId = update.id.value; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.talkStatusChanged = + [this](const Void::TeamSpeak::TalkStatusChanged& status) { + { + std::lock_guard lock{mirrorMutex_}; + auto& client = clients_[status.id.value]; + client.id = status.id; + client.talking = status.talking; + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ClientUpdated; + event.clientId = status.id.value; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.textMessage = [this](const Void::TeamSpeak::TextMessage& message) { + if (client_ && message.invoker == client_->id()) { + return; + } + Api::PluginEvent event; + event.type = Api::PluginEventType::TextMessageReceived; + event.clientId = message.invoker.value; + event.clientName = message.invokerName; + event.message = message.message; + if (message.target.kind == + Void::TeamSpeak::TextTargetKind::Channel) { + event.targetChannelId = message.target.id; + } + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.channelChanged = + [this](const Void::TeamSpeak::ChannelChanged& change) { + { + std::lock_guard lock{mirrorMutex_}; + const auto id = change.id.value; + if (change.kind == + Void::TeamSpeak::ChannelChangeKind::Deleted) { + channels_.erase(id); + } else { + auto& channel = channels_[id]; + channel.id = change.id; + change.patch.applyTo(channel); + } + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ChannelUpdated; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.serverUpdated = + [this](const Void::TeamSpeak::ServerUpdated& update) { + { + std::lock_guard lock{mirrorMutex_}; + if (!serverInfo_) { + serverInfo_.emplace(); + } + if (update.name) { + serverInfo_->name = *update.name; + } + if (update.welcomeMessage) { + serverInfo_->welcomeMessage = *update.welcomeMessage; + } + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ChannelUpdated; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; + cb.serverGroupMembershipChanged = + [this](const Void::TeamSpeak::ServerGroupMembershipChanged& + membership) { + uint64_t changedClient = 0; + { + std::lock_guard lock{mirrorMutex_}; + for (auto& [id, client] : clients_) { + if (client.databaseId != membership.client) { + continue; + } + changedClient = id; + auto group = std::ranges::find(client.serverGroups, + membership.group); + if (membership.added && + group == client.serverGroups.end()) { + client.serverGroups.push_back(membership.group); + } else if (!membership.added && + group != client.serverGroups.end()) { + client.serverGroups.erase(group); + } + break; + } + } + Api::PluginEvent event; + event.type = Api::PluginEventType::ClientUpdated; + event.clientId = changedClient; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; cb.debug = [](std::string_view msg) { Void::Log::debug(LOG, "{}", msg); }; @@ -217,7 +454,7 @@ namespace Echoion::Standalone const Void::Result::Result& result) const { return result ? Api::Result{} - : Api::fail(Api::ErrorCode::NetworkError, result.error().message); + : std::unexpected(teamSpeakError(result.error())); } void StandaloneClientInterface::loadInitialSnapshot() @@ -225,28 +462,38 @@ namespace Echoion::Standalone if (!client_) { return; } - auto clients = client_->request( - "clientlist -uid -groups -voice -away -times -info -country -ip"); + auto clients = client_->clients(); if (clients) { - for (const auto& record : clients->records) { - refreshClient(record); + std::lock_guard lock{mirrorMutex_}; + clients_.clear(); + for (auto& remote : *clients) { + clients_.emplace(remote.id.value, std::move(remote)); } } else { Void::Log::warn(LOG, "Initial client snapshot failed: {}", clients.error().message); } - auto channels = client_->request( - "channellist -topic -flags -voice -limits"); + auto channels = client_->channels(); if (channels) { - onCommand("channellist", channels->records); + std::lock_guard lock{mirrorMutex_}; + channels_.clear(); + for (auto& channel : *channels) { + channels_.emplace(channel.id.value, std::move(channel)); + } } else { Void::Log::warn(LOG, "Initial channel snapshot failed: {}", channels.error().message); } - if (auto subscribed = client_->request("channelsubscribeall"); - !subscribed) { + if (auto server = client_->serverInfo(); server) { + std::lock_guard lock{mirrorMutex_}; + serverInfo_ = std::move(*server); + } else { + Void::Log::warn(LOG, "Initial server snapshot failed: {}", + server.error().message); + } + if (auto subscribed = client_->subscribeAllChannels(); !subscribed) { Void::Log::warn(LOG, "Channel subscription failed: {}", - subscribed.error().message); + subscribed.error().message); } Api::PluginEvent event; event.type = Api::PluginEventType::ConnectionEstablished; @@ -274,200 +521,8 @@ namespace Echoion::Standalone return connectToServer(currentConfig_); } - // ---- Event mirror ------------------------------------------------------ - - void StandaloneClientInterface::upsertClientGroup( - const Void::TeamSpeak::CommandFields& p, bool emitConnected) - { - uint64_t clid = toU64(get(p, "clid")); - if (clid == 0) { - return; - } - Api::ClientInfo info; - { - std::lock_guard lock(mirrorMutex_); - info = clients_[clid]; - } - refreshClient(p); - { - std::lock_guard lock(mirrorMutex_); - info = clients_[clid]; - } - if (emitConnected) { - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ClientConnected; - ev.clientId = clid; - ev.clientName = info.nickname; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - } - - void StandaloneClientInterface::refreshClient( - const Void::TeamSpeak::CommandFields& params) - { - const auto idText = !get(params, "clid").empty() - ? get(params, "clid") - : get(params, "client_id"); - const auto clientId = toU64(idText); - if (clientId == 0) { - return; - } - std::lock_guard lock(mirrorMutex_); - auto& info = clients_[clientId]; - info.id = clientId; - if (const auto value = get(params, "client_nickname"); !value.empty()) { - info.nickname = value; - } - if (const auto value = get(params, "client_unique_identifier"); - !value.empty()) { - info.uniqueIdentifier = value; - } - if (const auto value = get(params, "ctid"); !value.empty()) { - info.channelId = toU64(value); - } else if (const auto value = get(params, "cid"); !value.empty()) { - info.channelId = toU64(value); - } - if (const auto value = get(params, "client_servergroups"); - !value.empty()) { - info.serverGroups = parseIds(value); - } - if (const auto value = get(params, "client_input_muted"); !value.empty()) { - info.isMuted = isTrue(value); - } - if (const auto value = get(params, "client_output_muted"); !value.empty()) { - info.isDeafened = isTrue(value); - } - if (const auto value = get(params, "client_flag_talking"); !value.empty()) { - info.isTalking = isTrue(value); - } else if (const auto value = get(params, "status"); !value.empty()) { - info.isTalking = isTrue(value); - } - if (const auto value = get(params, "connection_client_ip"); !value.empty()) { - clientIps_[clientId] = value; - } - if (const auto value = get(params, "client_flag_avatar"); !value.empty()) { - avatarHashes_[clientId] = value; - } - const auto avatar = !get(params, "client_myteamspeak_avatar").empty() - ? get(params, "client_myteamspeak_avatar") - : get(params, "client_myts_avatar"); - if (const auto comma = avatar.find(','); comma != std::string::npos) { - const auto url = avatar.substr(comma + 1); - if (url.starts_with("https://") || url.starts_with("http://")) { - avatarUrls_[clientId] = url; - } - } - } - - void StandaloneClientInterface::onCommand(std::string_view name, - const std::vector& records) - { - const auto& groups = records; - - if (name == "notifycliententerview" || name == "clientlist" || - name == "clientinfo" || name == "notifyclientupdated" || - name == "notifytalkstatuschange") { - for (const auto& g : groups) { - upsertClientGroup(g, name == "notifycliententerview"); - } - } else if (name == "notifyclientleftview") { - for (const auto& g : groups) { - uint64_t clid = toU64(get(g, "clid")); - if (clid == 0) { - continue; - } - std::string name; - { - std::lock_guard lock(mirrorMutex_); - auto it = clients_.find(clid); - if (it != clients_.end()) { - name = it->second.nickname; - clients_.erase(it); - } - } - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ClientDisconnected; - ev.clientId = clid; - ev.clientName = name; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - } else if (name == "notifyclientmoved") { - for (const auto& g : groups) { - uint64_t clid = toU64(get(g, "clid")); - uint64_t ctid = toU64(get(g, "ctid")); - if (clid == 0) { - continue; - } - { - std::lock_guard lock(mirrorMutex_); - clients_[clid].id = clid; - clients_[clid].channelId = ctid; - } - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ClientMoved; - ev.clientId = clid; - ev.targetChannelId = ctid; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - } else if (name == "notifychanneldeleted") { - std::lock_guard lock(mirrorMutex_); - for (const auto& group : groups) { - channels_.erase(toU64(get(group, "cid"))); - } - } else if (name == "channellist" || name == "notifychannellist" || - name == "notifychannelcreated" || - name == "notifychanneledited" || - name == "notifychannelmoved") { - std::lock_guard lock(mirrorMutex_); - for (const auto& g : groups) { - uint64_t cid = toU64(get(g, "cid")); - if (cid == 0) { - continue; - } - Api::ChannelInfo ch = channels_[cid]; - ch.id = cid; - if (auto n = get(g, "channel_name"); !n.empty()) { - ch.name = n; - } - if (auto pid = get(g, "pid"); !pid.empty()) { - const auto parent = toU64(pid); - ch.parentId = parent == 0 ? std::optional{} - : std::optional{parent}; - } - ch.order = toU64(get(g, "channel_order")); - ch.isDefault = isTrue(get(g, "channel_flag_default")); - ch.hasPassword = isTrue(get(g, "channel_flag_password")); - ch.maxClients = static_cast( - toU64(get(g, "channel_maxclients"))); - ch.currentClients = static_cast( - toU64(get(g, "total_clients"))); - channels_[cid] = ch; - } - } - } - - void StandaloneClientInterface::onTextMessage( - const Void::TeamSpeak::CommandFields& params) - { - uint64_t invoker = toU64(get(params, "invokerid")); - if (client_ && invoker == client_->id().value) { - return; // ignore our own messages - } - Api::PluginEvent ev; - ev.type = Api::PluginEventType::TextMessageReceived; - ev.clientId = invoker; - ev.clientName = get(params, "invokername"); - ev.message = get(params, "msg"); - if (auto t = get(params, "target"); !t.empty()) { - ev.targetChannelId = toU64(t); - } - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - + // TeamSpeak command parsing and event normalization live in VoidTeamspeak. + // This adapter only mirrors its typed callbacks into Echoion events. void StandaloneClientInterface::broadcast(const Api::PluginEvent& event) { eventCallbacks_.dispatch(event); @@ -476,57 +531,59 @@ namespace Echoion::Standalone // ---- Clients / channels ------------------------------------------------ Api::Result> - StandaloneClientInterface::getClients() + StandaloneClientInterface::getClients() { std::lock_guard lock(mirrorMutex_); std::vector out; out.reserve(clients_.size()); for (const auto& [id, c] : clients_) { - out.push_back(c); + (void)id; + out.push_back(apiClient(c)); } return out; } Api::Result> - StandaloneClientInterface::getClient(uint64_t clientId) + StandaloneClientInterface::getClient(uint64_t clientId) { std::lock_guard lock(mirrorMutex_); auto it = clients_.find(clientId); if (it == clients_.end()) { return std::optional{}; } - return std::optional{it->second}; + return std::optional{apiClient(it->second)}; } Api::Result> - StandaloneClientInterface::getClientIp(uint64_t clientId) + StandaloneClientInterface::getClientIp(uint64_t clientId) { if (!client_ || !isConnected()) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "not connected"); } - Void::TeamSpeak::CommandFields parameters; - parameters["clid"] = std::to_string(clientId); - auto result = client_->request( - Void::TeamSpeak::buildCommand("clientconnectioninfo", parameters)); - if (!result) { - result = client_->request( - Void::TeamSpeak::buildCommand("clientinfo", parameters)); + const auto id = checkedClientId(clientId); + if (!id) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); } - if (!result) { - return Api::fail(Api::ErrorCode::NetworkError, result.error().message); + auto details = client_->clientDetails(*id); + if (!details) { + return std::unexpected(teamSpeakError(details.error())); } - for (const auto& record : result->records) { - refreshClient(record); + { + std::lock_guard lock{mirrorMutex_}; + clients_[clientId] = details->client; + if (details->connectionIp) { + clientIps_[clientId] = *details->connectionIp; + } else { + clientIps_.erase(clientId); + } } - std::lock_guard lock(mirrorMutex_); - const auto entry = clientIps_.find(clientId); - return entry == clientIps_.end() - ? std::optional{} - : std::optional{entry->second}; + return details->connectionIp; } Api::Result> - StandaloneClientInterface::getClientAvatarPath(uint64_t clientId) + StandaloneClientInterface::getClientAvatarPath(uint64_t clientId) { std::lock_guard lock(mirrorMutex_); const auto entry = avatarPaths_.find(clientId); @@ -538,61 +595,72 @@ namespace Echoion::Standalone } Api::Result> - StandaloneClientInterface::getClientAvatarUrl(uint64_t clientId) + StandaloneClientInterface::getClientAvatarUrl(uint64_t clientId) { - if (client_ && isConnected()) { - Void::TeamSpeak::CommandFields parameters; - parameters["clid"] = std::to_string(clientId); - const auto result = client_->request( - Void::TeamSpeak::buildCommand("clientinfo", parameters)); - if (result) { - for (const auto& record : result->records) { - refreshClient(record); - } + if (!client_ || !isConnected()) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "not connected"); + } + const auto id = checkedClientId(clientId); + if (!id) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); + } + auto details = client_->clientDetails(*id); + if (!details) { + return std::unexpected(teamSpeakError(details.error())); + } + { + std::lock_guard lock{mirrorMutex_}; + clients_[clientId] = details->client; + if (details->avatarUrl) { + avatarUrls_[clientId] = *details->avatarUrl; + } else { + avatarUrls_.erase(clientId); } } - std::lock_guard lock(mirrorMutex_); - const auto entry = avatarUrls_.find(clientId); - return entry == avatarUrls_.end() - ? std::optional{} - : std::optional{entry->second}; + return details->avatarUrl; } Api::Result> - StandaloneClientInterface::requestClientAvatar(uint64_t clientId, - const std::string& destDir) + StandaloneClientInterface::requestClientAvatar( + uint64_t clientId, const std::string& destDir) { if (!client_ || !isConnected()) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "not connected"); } - Void::TeamSpeak::CommandFields parameters; - parameters["clid"] = std::to_string(clientId); - const auto info = - client_->request(Void::TeamSpeak::buildCommand("clientinfo", parameters)); - if (!info) { - return Api::fail(Api::ErrorCode::NetworkError, info.error().message); + const auto id = checkedClientId(clientId); + if (!id) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); } - for (const auto& record : info->records) { - refreshClient(record); + auto details = client_->clientDetails(*id); + if (!details) { + return std::unexpected(teamSpeakError(details.error())); } - std::string hash; + const std::string hash = details->avatarHash.value_or(""); { - std::lock_guard lock(mirrorMutex_); - if (const auto entry = avatarHashes_.find(clientId); - entry != avatarHashes_.end()) { - hash = entry->second; + std::lock_guard lock{mirrorMutex_}; + clients_[clientId] = details->client; + if (!hash.empty()) { + avatarHashes_[clientId] = hash; + } + if (details->avatarUrl) { + avatarUrls_[clientId] = *details->avatarUrl; } } if (hash.empty()) { return std::optional{}; } - if (hash.find_first_not_of( - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") != + if (hash.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq" + "rstuvwxyz0123456789_-") != std::string::npos) { return Api::fail(Api::ErrorCode::ParseError, "server returned an unsafe avatar hash"); } - const auto directory = destDir.empty() ? settings_.avatarCachePath : destDir; + const auto directory = + destDir.empty() ? settings_.avatarCachePath : destDir; std::error_code directoryError; std::filesystem::create_directories(directory, directoryError); if (directoryError) { @@ -602,11 +670,10 @@ namespace Echoion::Standalone const auto destination = (std::filesystem::path(directory) / ("avatar_" + hash)).string(); if (!std::filesystem::exists(destination)) { - const auto result = client_->download( - "/avatar_" + hash, destination); + const auto result = + client_->download("/avatar_" + hash, destination); if (!result) { - return Api::fail(Api::ErrorCode::NetworkError, - result.error().message); + return std::unexpected(teamSpeakError(result.error())); } } { @@ -617,75 +684,448 @@ namespace Echoion::Standalone } Api::Result> - StandaloneClientInterface::getChannels() const + StandaloneClientInterface::getChannels() const { std::lock_guard lock(mirrorMutex_); std::vector out; out.reserve(channels_.size()); for (const auto& [id, c] : channels_) { - out.push_back(c); + const auto current = static_cast( + std::ranges::count_if(clients_, [&](const auto& entry) { + return !entry.second.isQuery() && + entry.second.channel.value == id; + })); + out.push_back(apiChannel(c, current)); } return out; } Api::Result> - StandaloneClientInterface::getChannel(uint64_t channelId) const + StandaloneClientInterface::getChannel(uint64_t channelId) const { std::lock_guard lock(mirrorMutex_); auto it = channels_.find(channelId); if (it == channels_.end()) { return std::optional{}; } - return std::optional{it->second}; + const auto current = static_cast( + std::ranges::count_if(clients_, [&](const auto& entry) { + return !entry.second.isQuery() && + entry.second.channel.value == channelId; + })); + return std::optional{apiChannel(it->second, current)}; } - Api::Result - StandaloneClientInterface::moveClient(uint64_t clientId, uint64_t channelId) + Api::Result StandaloneClientInterface::moveClient(uint64_t clientId, + uint64_t channelId) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - if (clientId == 0 || clientId > std::numeric_limits::max()) { + const auto id = checkedClientId(clientId); + if (!id || channelId == 0) { return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); + "valid client and channel IDs are required"); } - return commandResult(client_->move( - Void::TeamSpeak::ClientId{static_cast(clientId)}, - Void::TeamSpeak::ChannelId{channelId})); + auto moved = commandResult( + client_->move(*id, Void::TeamSpeak::ChannelId{channelId})); + if (moved) { + std::lock_guard lock{mirrorMutex_}; + if (auto client = clients_.find(clientId); + client != clients_.end()) { + client->second.channel = Void::TeamSpeak::ChannelId{channelId}; + } + } + return moved; } Api::Result - StandaloneClientInterface::kickClient(uint64_t clientId, - const std::string& reason) + StandaloneClientInterface::kickClient(uint64_t clientId, + const std::string& reason) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - if (clientId == 0 || clientId > std::numeric_limits::max()) { + const auto id = checkedClientId(clientId); + if (!id) { return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); + "client ID exceeds TeamSpeak protocol range"); } - return commandResult(client_->kick( - Void::TeamSpeak::ClientId{static_cast(clientId)}, reason)); + return commandResult( + client_->kick(*id, Void::TeamSpeak::KickScope::Server, reason)); + } + + Api::Result StandaloneClientInterface::kickClientFromChannel( + uint64_t clientId, const std::string& reason) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + const auto id = checkedClientId(clientId); + if (!id) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); + } + return commandResult( + client_->kick(*id, Void::TeamSpeak::KickScope::Channel, reason)); + } + + Api::Result StandaloneClientInterface::banClient( + uint64_t clientId, uint64_t durationSeconds, const std::string& reason) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + const auto id = checkedClientId(clientId); + if (!id || durationSeconds > static_cast( + std::numeric_limits::max())) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID or ban duration is out of range"); + } + Void::TeamSpeak::BanOptions options; + options.reason = reason; + if (durationSeconds != 0) { + options.duration = + std::chrono::seconds{static_cast(durationSeconds)}; + } + auto result = client_->ban(*id, options); + return result ? Api::Result{} + : std::unexpected(teamSpeakError(result.error())); + } + + Api::Result> StandaloneClientInterface::getBans() + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + auto result = client_->bans(); + if (!result) { + return std::unexpected(teamSpeakError(result.error())); + } + std::vector bans; + bans.reserve(result->size()); + for (const auto& ban : *result) { + bans.push_back({ + .id = ban.id.value, + .uniqueIdentifier = + ban.uniqueId.empty() + ? std::nullopt + : std::optional{ban.uniqueId}, + .nickname = ban.lastNickname.empty() + ? std::nullopt + : std::optional{ban.lastNickname}, + .reason = ban.reason, + .createdAt = ban.createdAtUnixSeconds, + .durationSeconds = static_cast(ban.duration.count()), + }); + } + return bans; + } + + Api::Result StandaloneClientInterface::unban(uint64_t banId) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + if (banId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "ban ID is required"); + } + return commandResult(client_->unban(Void::TeamSpeak::BanId{banId})); + } + + Api::Result StandaloneClientInterface::createChannel( + const Api::ChannelCreateOptions& options) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + if (options.maxClients > + static_cast(std::numeric_limits::max())) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "channel capacity is out of range"); + } + Void::TeamSpeak::ChannelCreateOptions native; + native.name = options.name; + native.topic = options.topic.value_or(""); + native.description = options.description.value_or(""); + native.password = options.password.value_or(""); + native.lifetime = options.permanent + ? Void::TeamSpeak::ChannelLifetime::Permanent + : Void::TeamSpeak::ChannelLifetime::Temporary; + native.unlimitedClients = options.maxClients == 0; + if (options.parentId && *options.parentId != 0) { + native.parent = Void::TeamSpeak::ChannelId{*options.parentId}; + } + if (options.orderAfterId && *options.orderAfterId != 0) { + native.orderAfter = + Void::TeamSpeak::ChannelId{*options.orderAfterId}; + } + if (options.maxClients != 0) { + native.maxClients = static_cast(options.maxClients); + } + auto result = client_->createChannel(native); + if (!result) { + return std::unexpected(teamSpeakError(result.error())); + } + { + std::lock_guard lock{mirrorMutex_}; + Void::TeamSpeak::Channel created; + created.id = *result; + created.parent = native.parent; + created.orderAfter = + native.orderAfter.value_or(Void::TeamSpeak::ChannelId{}); + created.name = native.name; + created.topic = native.topic; + created.description = native.description; + created.maxClients = native.maxClients.value_or(0); + created.passwordProtected = !native.password.empty(); + created.permanent = + native.lifetime == Void::TeamSpeak::ChannelLifetime::Permanent; + created.semiPermanent = + native.lifetime == + Void::TeamSpeak::ChannelLifetime::SemiPermanent; + created.unlimitedClients = native.unlimitedClients; + channels_[result->value] = std::move(created); + } + return result->value; + } + + Api::Result StandaloneClientInterface::editChannel( + uint64_t channelId, const Api::ChannelEditOptions& options) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + if (channelId == 0 || + (options.maxClients && + *options.maxClients > + static_cast(std::numeric_limits::max()))) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "channel ID or capacity is out of range"); + } + Void::TeamSpeak::ChannelEditOptions native; + native.name = options.name; + native.topic = options.topic; + native.description = options.description; + native.password = options.password; + if (options.maxClients) { + native.unlimitedClients = *options.maxClients == 0; + if (*options.maxClients != 0) { + native.maxClients = static_cast(*options.maxClients); + } + } + if (options.permanent) { + native.lifetime = *options.permanent + ? Void::TeamSpeak::ChannelLifetime::Permanent + : Void::TeamSpeak::ChannelLifetime::Temporary; + } + auto edited = commandResult(client_->editChannel( + Void::TeamSpeak::ChannelId{channelId}, native)); + if (edited) { + std::lock_guard lock{mirrorMutex_}; + if (auto channel = channels_.find(channelId); + channel != channels_.end()) { + if (options.name) { + channel->second.name = *options.name; + } + if (options.topic) { + channel->second.topic = *options.topic; + } + if (options.description) { + channel->second.description = *options.description; + } + if (options.password) { + channel->second.passwordProtected = + !options.password->empty(); + } + if (options.maxClients) { + channel->second.unlimitedClients = *options.maxClients == 0; + channel->second.maxClients = + static_cast(*options.maxClients); + } + if (options.permanent) { + channel->second.permanent = *options.permanent; + channel->second.semiPermanent = false; + } + } + } + return edited; + } + + Api::Result StandaloneClientInterface::reorderChannel( + uint64_t channelId, uint64_t parentId, uint64_t orderAfterId) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + if (channelId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "channel ID is required"); + } + const auto parent = + parentId == 0 ? std::nullopt + : std::optional{Void::TeamSpeak::ChannelId{parentId}}; + const auto after = + orderAfterId == 0 + ? std::nullopt + : std::optional{Void::TeamSpeak::ChannelId{orderAfterId}}; + auto reordered = commandResult(client_->reorderChannel( + Void::TeamSpeak::ChannelId{channelId}, parent, after)); + if (reordered) { + std::lock_guard lock{mirrorMutex_}; + if (auto channel = channels_.find(channelId); + channel != channels_.end()) { + channel->second.parent = parent; + channel->second.orderAfter = + after.value_or(Void::TeamSpeak::ChannelId{}); + } + } + return reordered; + } + + Api::Result + StandaloneClientInterface::deleteChannel(uint64_t channelId, bool force) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + if (channelId == 0) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "channel ID is required"); + } + auto removed = commandResult(client_->deleteChannel( + Void::TeamSpeak::ChannelId{channelId}, force)); + if (removed) { + std::lock_guard lock{mirrorMutex_}; + channels_.erase(channelId); + } + return removed; + } + + Api::Result> + StandaloneClientInterface::getServerGroups() + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + auto result = client_->serverGroups(); + if (!result) { + return std::unexpected(teamSpeakError(result.error())); + } + uint64_t defaultGroup = 0; + { + std::lock_guard lock{mirrorMutex_}; + if (serverInfo_) { + defaultGroup = serverInfo_->defaultServerGroup.value; + } + } + std::vector groups; + groups.reserve(result->size()); + for (const auto& group : *result) { + groups.push_back({.id = group.id.value, + .name = group.name, + .isDefault = group.id.value == defaultGroup}); + } + return groups; + } + + Api::Result StandaloneClientInterface::addClientToServerGroup( + uint64_t groupId, uint64_t clientDatabaseId) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + auto added = commandResult(client_->addServerGroupMember( + Void::TeamSpeak::ServerGroupId{groupId}, + Void::TeamSpeak::ClientDatabaseId{clientDatabaseId})); + if (added) { + std::lock_guard lock{mirrorMutex_}; + for (auto& [id, remote] : clients_) { + (void)id; + if (remote.databaseId.value != clientDatabaseId) { + continue; + } + const auto group = Void::TeamSpeak::ServerGroupId{groupId}; + if (std::ranges::find(remote.serverGroups, group) == + remote.serverGroups.end()) { + remote.serverGroups.push_back(group); + } + break; + } + } + return added; + } + + Api::Result StandaloneClientInterface::removeClientFromServerGroup( + uint64_t groupId, uint64_t clientDatabaseId) + { + if (!client_) { + return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); + } + auto removed = commandResult(client_->removeServerGroupMember( + Void::TeamSpeak::ServerGroupId{groupId}, + Void::TeamSpeak::ClientDatabaseId{clientDatabaseId})); + if (removed) { + std::lock_guard lock{mirrorMutex_}; + for (auto& [id, remote] : clients_) { + (void)id; + if (remote.databaseId.value != clientDatabaseId) { + continue; + } + const auto group = Void::TeamSpeak::ServerGroupId{groupId}; + if (const auto current = + std::ranges::find(remote.serverGroups, group); + current != remote.serverGroups.end()) { + remote.serverGroups.erase(current); + } + break; + } + } + return removed; + } + + Api::Result + StandaloneClientInterface::getTeamSpeakServerInfo() + { + std::lock_guard lock{mirrorMutex_}; + if (!serverInfo_) { + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + "TeamSpeak server information is not available yet"); + } + return Api::ServerInfo{ + .id = serverInfo_->id.value, + .name = serverInfo_->name, + .welcomeMessage = serverInfo_->welcomeMessage, + .maxClients = static_cast(std::min( + serverInfo_->maxClients, std::numeric_limits::max())), + .currentClients = static_cast( + std::min(serverInfo_->clientCount, + std::numeric_limits::max())), + }; } // ---- Messaging --------------------------------------------------------- Api::Result - StandaloneClientInterface::sendTextMessage(uint64_t targetId, - const std::string& message) + StandaloneClientInterface::sendTextMessage(uint64_t targetId, + const std::string& message) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } + const auto id = checkedClientId(targetId); + if (!id) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "client ID exceeds TeamSpeak protocol range"); + } for (const auto& chunk : chunkMessage(message)) { - if (auto result = commandResult(client_->sendText( - Void::TeamSpeak::TextTarget{ - .kind = Void::TeamSpeak::TextTargetKind::Client, - .id = targetId}, chunk)); + if (auto result = + commandResult(client_->sendPrivateMessage(*id, chunk)); !result) { - Void::Log::warn(LOG, - "Failed to send help/reply chunk ({} bytes): {}", + Void::Log::warn( + LOG, "Failed to send help/reply chunk ({} bytes): {}", chunk.size(), result.error().message); return result; } @@ -693,36 +1133,34 @@ namespace Echoion::Standalone return {}; } - Api::Result - StandaloneClientInterface::sendChannelMessage(uint64_t channelId, - const std::string& message) + Api::Result StandaloneClientInterface::sendChannelMessage( + uint64_t channelId, const std::string& message) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - return commandResult(client_->sendText(Void::TeamSpeak::TextTarget{ - .kind = Void::TeamSpeak::TextTargetKind::Channel, - .id = channelId}, message)); + return commandResult(client_->sendChannelMessage( + Void::TeamSpeak::ChannelId{channelId}, message)); } Api::Result - StandaloneClientInterface::sendServerMessage(const std::string& message) + StandaloneClientInterface::sendServerMessage(const std::string& message) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - return commandResult(client_->sendText(Void::TeamSpeak::TextTarget{ - .kind = Void::TeamSpeak::TextTargetKind::Server}, message)); + return commandResult(client_->sendServerMessage(message)); } // ---- Audio ------------------------------------------------------------- - Api::Result - StandaloneClientInterface::sendAudioData(const std::span& data) + Api::Result StandaloneClientInterface::sendAudioData( + const std::span& data) { if (!client_ || !encoder_ || client_->state() != Void::TeamSpeak::ConnectionState::Connected) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "not connected"); } std::vector whisper; { @@ -734,18 +1172,18 @@ namespace Echoion::Standalone if (whisper.empty()) { if (auto sent = client_->sendVoice(f); !sent) { return Api::fail(Api::ErrorCode::NetworkError, - sent.error().message); + sent.error().message); } } else { Void::TeamSpeak::WhisperTargets targets; targets.clients.reserve(whisper.size()); for (uint64_t c : whisper) { - targets.clients.push_back(Void::TeamSpeak::ClientId{ - static_cast(c)}); + targets.clients.push_back( + Void::TeamSpeak::ClientId{static_cast(c)}); } if (auto sent = client_->sendWhisper(f, targets); !sent) { return Api::fail(Api::ErrorCode::NetworkError, - sent.error().message); + sent.error().message); } } } @@ -766,155 +1204,6 @@ namespace Echoion::Standalone return {}; } - Api::Result - StandaloneClientInterface::createAudioStream( - const AudioStreamOptions& options) - { - if (!initialized_.load()) { - return Api::fail(Api::ErrorCode::NotInitialized, - "interface not initialized"); - } - if (options.name.empty() || options.server.address.empty()) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "stream name and server address are required"); - } - if (std::ranges::any_of(options.recipients, [](uint64_t id) { - return id == 0 || id > std::numeric_limits::max(); - })) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "stream recipient is outside the TeamSpeak client ID range"); - } - - const auto id = nextAudioStreamId_.fetch_add(1); - auto runtime = std::make_shared(); - const auto identityPath = std::filesystem::path(settings_.identityPath) - .parent_path() / "rooms" / - (std::format("{:016x}.identity", Void::Hash::fnv1a64(options.name))); - try { - if (std::filesystem::exists(identityPath)) { - runtime->identity = std::make_shared( - Void::TeamSpeak::Identity::load(identityPath.string())); - } else { - std::filesystem::create_directories(identityPath.parent_path()); - runtime->identity = std::make_shared( - Void::TeamSpeak::Identity::generate(settings_.securityLevel)); - runtime->identity->save(identityPath.string()); - } - runtime->encoder = std::make_unique(settings_.opusBitrate); - runtime->client = std::make_unique(); - runtime->recipients = options.recipients; - - Void::TeamSpeak::Events callbacks; - callbacks.error = [id](const Void::TeamSpeak::Error& error) { - Void::Log::error(LOG, "Audio stream {} protocol error: {}", id, - error.message); - }; - callbacks.disconnected = [id] { - Void::Log::warn(LOG, "Audio stream {} disconnected", id); - }; - runtime->client->setEvents(std::move(callbacks)); - - Void::TeamSpeak::ConnectOptions connect; - connect.host = options.server.address; - connect.port = options.server.port == 0 ? 9987 : options.server.port; - connect.identity = runtime->identity; - connect.nickname = options.server.nickname.empty() - ? "Echoion/" + options.name - : options.server.nickname + "/" + options.name; - connect.serverPassword = options.server.serverPassword; - connect.defaultChannel = - options.server.defaultChannelId.value_or(std::string{}); - connect.channelPassword = - options.server.channelPassword.value_or(std::string{}); - if (auto connected = runtime->client->connect(connect); !connected) { - return Api::fail(Api::ErrorCode::NetworkError, - connected.error().message); - } - } catch (const std::exception& exception) { - return Api::fail(Api::ErrorCode::NetworkError, exception.what()); - } - - std::lock_guard lock(audioStreamsMutex_); - audioStreams_.emplace(id, std::move(runtime)); - return id; - } - - Api::Result - StandaloneClientInterface::destroyAudioStream(AudioStreamId id) - { - std::shared_ptr stream; - { - std::lock_guard lock(audioStreamsMutex_); - auto iterator = audioStreams_.find(id); - if (iterator == audioStreams_.end()) { - return Api::fail(Api::ErrorCode::NotFound, - "audio stream not found"); - } - stream = iterator->second; - audioStreams_.erase(iterator); - } - std::lock_guard lock(stream->mutex); - stream->client->disconnect(); - return {}; - } - - Api::Result StandaloneClientInterface::sendAudioDataToStream( - AudioStreamId id, const std::span& data) - { - std::shared_ptr stream; - { - std::lock_guard lock(audioStreamsMutex_); - auto iterator = audioStreams_.find(id); - if (iterator == audioStreams_.end()) { - return Api::fail(Api::ErrorCode::NotFound, "audio stream not found"); - } - stream = iterator->second; - } - std::lock_guard streamLock(stream->mutex); - if (stream->client->state() != - Void::TeamSpeak::ConnectionState::Connected) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "audio stream is not connected"); - } - Void::TeamSpeak::WhisperTargets targets; - targets.clients.reserve(stream->recipients.size()); - for (auto recipient : stream->recipients) { - targets.clients.push_back(Void::TeamSpeak::ClientId{ - static_cast(recipient)}); - } - for (const auto& frame : stream->encoder->encode(data)) { - if (auto sent = stream->client->sendWhisper(frame, targets); !sent) { - return Api::fail(Api::ErrorCode::NetworkError, - sent.error().message); - } - } - return {}; - } - - Api::Result StandaloneClientInterface::setAudioStreamRecipients( - AudioStreamId id, const std::vector& recipients) - { - if (std::ranges::any_of(recipients, [](uint64_t clientId) { - return clientId == 0 || - clientId > std::numeric_limits::max(); - })) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "stream recipient is outside the TeamSpeak client ID range"); - } - std::shared_ptr stream; - { - std::lock_guard lock(audioStreamsMutex_); - auto iterator = audioStreams_.find(id); - if (iterator == audioStreams_.end()) { - return Api::fail(Api::ErrorCode::NotFound, "audio stream not found"); - } - stream = iterator->second; - } - std::lock_guard streamLock(stream->mutex); - stream->recipients = recipients; - return {}; - } - // ---- Events ------------------------------------------------------------ void StandaloneClientInterface::registerEventCallback( diff --git a/EchoionStandalone/src/main.cpp b/EchoionStandalone/src/main.cpp index f9603f1..2acb628 100644 --- a/EchoionStandalone/src/main.cpp +++ b/EchoionStandalone/src/main.cpp @@ -1,21 +1,16 @@ -// Standalone Echoion host. -// -// Replaces the TeamSpeak-client + plugin sandwich: loads the same hot-reloadable -// Core shared library via the (TeamSpeak-independent) CoreLoader, but backs -// IPluginInterface with a native TeamSpeak UDP protocol client instead of the -// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no -// TeamSpeak client, no Weston/RDP, no plugin directory. +// Standalone Echoion host. It loads the hot-reloadable Core through CoreLoader +// and adapts Echoion's host contract to VoidTeamspeak's typed client API. #include "echoion/host/CoreLoader.hpp" -#include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/ReleaseManifest.hpp" +#include "echoion/standalone/StandaloneClientInterface.hpp" #include #include #include #include -#include #include +#include #include #include @@ -50,8 +45,8 @@ namespace g_cv.notify_all(); } - std::optional argumentValue( - int argc, char** argv, std::string_view name) + std::optional argumentValue(int argc, char** argv, + std::string_view name) { for (int index = 1; index + 1 < argc; ++index) { if (std::string_view{argv[index]} == name) { @@ -76,14 +71,17 @@ namespace { const auto transaction = directory / "release-transaction"; if (!std::filesystem::exists(transaction) || - std::getenv("ECHOION_REEXEC_VERSION")) return; + std::getenv("ECHOION_REEXEC_VERSION")) { + return; + } auto version = Void::FileSystem::read_file(transaction); if (version && !version->empty()) { std::ignore = Void::FileSystem::atomic_write( directory / "failed-release", *version); Void::Log::error("main", - "Release {} failed its startup health check; stable service restored", - *version); + "Release {} failed its startup health check; " + "stable service restored", + *version); } std::ignore = Void::FileSystem::remove_path(transaction); } @@ -132,10 +130,9 @@ namespace for (int i = 1; i < argc; ++i) { const std::string_view argument{argv[i]}; if (argument == "--help") { - std::cout - << "Usage: echoiond [--config PATH]\n" - " echoiond --import-identity EXPORT.ini " - "[--identity-path PATH] [--force]\n"; + std::cout << "Usage: echoiond [--config PATH]\n" + " echoiond --import-identity EXPORT.ini " + "[--identity-path PATH] [--force]\n"; return 0; } if (argument == "--import-identity") { @@ -165,7 +162,8 @@ namespace } const auto identity = Void::TeamSpeak::Identity::importTeamSpeakIni(source->string()); - if (const auto parent = destination.parent_path(); !parent.empty()) { + if (const auto parent = destination.parent_path(); + !parent.empty()) { std::filesystem::create_directories(parent); } identity.save(destination.string()); @@ -186,9 +184,10 @@ int main(int argc, char** argv) std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n'; std::abort(); }); - if (const auto validationPath = argumentValue(argc, argv, - "--validate-release")) { - auto manifest = Echoion::Standalone::ReleaseManifest::load(*validationPath); + if (const auto validationPath = + argumentValue(argc, argv, "--validate-release")) { + auto manifest = + Echoion::Standalone::ReleaseManifest::load(*validationPath); if (!manifest) { std::cerr << manifest.error().message << '\n'; return 2; @@ -203,8 +202,8 @@ int main(int argc, char** argv) std::filesystem::path cfgDir = configDir(); recordInterruptedRelease(cfgDir); std::filesystem::path cfgPath = cfgDir / "config.json"; - const auto identityPath = std::filesystem::path(envOr( - "ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string())); + const auto identityPath = std::filesystem::path( + envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string())); if (const auto importResult = importIdentity(argc, argv, identityPath); importResult >= 0) { return importResult; @@ -222,8 +221,9 @@ int main(int argc, char** argv) settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); - auto interface = std::make_shared( - settings); + auto interface = + std::make_shared( + settings); if (auto r = interface->initialize(); !r) { Void::Log::error("main", "interface init failed: {}", r.error().message); @@ -242,7 +242,7 @@ int main(int argc, char** argv) if (const auto restorePath = argumentValue(argc, argv, "--restore-state")) { if (auto result = loader.restoreCheckpoint(*restorePath); !result) { Void::Log::error("main", "failed to restore restart checkpoint: {}", - result.error().message); + result.error().message); return 1; } } @@ -254,12 +254,12 @@ int main(int argc, char** argv) } core->setPluginInterface(interface); - interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) { - std::ignore = core->onPluginEvent(ev); - }); - loader.setHotReloadPrepareCallback([interface] { - interface->quiesceEventCallbacks(); - }); + interface->registerEventCallback( + [core](const Echoion::Api::PluginEvent& ev) { + std::ignore = core->onPluginEvent(ev); + }); + loader.setHotReloadPrepareCallback( + [interface] { interface->quiesceEventCallbacks(); }); // Re-register the Core callback after each hot reload (new Core instance). loader.setHotReloadCallback([&loader, interface] { if (auto c = loader.getCore()) { @@ -278,14 +278,15 @@ int main(int argc, char** argv) if (const char* manifest = std::getenv("ECHOION_RELEASE_MANIFEST")) { releaseManifestPath = manifest; releaseWatcher = std::make_unique(); - releaseWatcher->watch(*releaseManifestPath, + releaseWatcher->watch( + *releaseManifestPath, [](const Void::FileSystem::FileWatcher::Event& event) { if (event.exists) { requestUpdate(); } }); Void::Log::info("main", "Watching release manifest {}", - releaseManifestPath->string()); + releaseManifestPath->string()); } else { // Compatibility mode for development. Production release bundles use // transactional daemon re-exec instead of replacing Core in isolation. @@ -296,13 +297,14 @@ int main(int argc, char** argv) std::signal(SIGTERM, onSignal); Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) { - std::ignore = Void::FileSystem::atomic_write( - cfgDir / "release-health", version); - std::ignore = Void::FileSystem::remove_path( - cfgDir / "release-transaction"); + std::ignore = + Void::FileSystem::atomic_write(cfgDir / "release-health", version); + std::ignore = + Void::FileSystem::remove_path(cfgDir / "release-transaction"); std::ignore = Void::FileSystem::remove_path(cfgDir / "failed-release"); ::unsetenv("ECHOION_REEXEC_VERSION"); - Void::Log::info("main", "Release {} passed startup health check", version); + Void::Log::info("main", "Release {} passed startup health check", + version); } std::optional pendingRelease; @@ -310,49 +312,52 @@ int main(int argc, char** argv) while (!g_stop.load() && !pendingRelease) { { std::unique_lock lock(g_mu); - g_cv.wait(lock, [] { - return g_stop.load() || g_updateRequested.load(); - }); + g_cv.wait(lock, + [] { return g_stop.load() || g_updateRequested.load(); }); } if (g_stop.load() || !releaseManifestPath) { break; } g_updateRequested = false; - auto manifest = Echoion::Standalone::ReleaseManifest::load( - *releaseManifestPath); + auto manifest = + Echoion::Standalone::ReleaseManifest::load(*releaseManifestPath); if (!manifest) { Void::Log::error("main", "release rejected: {}", - manifest.error().message); + manifest.error().message); continue; } - if (auto failed = Void::FileSystem::read_file(cfgDir / "failed-release"); + if (auto failed = + Void::FileSystem::read_file(cfgDir / "failed-release"); failed && *failed == manifest->version) { Void::Log::error("main", - "Release {} was previously rolled back; publish a new version to retry", - manifest->version); + "Release {} was previously rolled back; publish a " + "new version to retry", + manifest->version); continue; } auto executable = std::filesystem::canonical("/proc/self/exe"); - auto validation = Void::Process::run(executable, - {"--validate-release", releaseManifestPath->string()}, {}, - std::chrono::seconds{30}); + auto validation = Void::Process::run( + executable, {"--validate-release", releaseManifestPath->string()}, + {}, std::chrono::seconds{30}); if (!validation || validation->exit_code != 0) { Void::Log::error("main", "release validation failed: {}", - validation ? validation->err : validation.error().message()); + validation ? validation->err + : validation.error().message()); continue; } checkpointPath = configDir() / "restart-state.bin"; if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) { Void::Log::error("main", "release checkpoint failed: {}", - checkpoint.error().message); + checkpoint.error().message); continue; } pendingRelease = std::move(*manifest); } releaseWatcher.reset(); - Void::Log::info("main", "{}", pendingRelease - ? "Applying validated release..." : "Shutting down..."); + Void::Log::info("main", "{}", + pendingRelease ? "Applying validated release..." + : "Shutting down..."); loader.disableAutoReload(); (void)interface->disconnectFromServer(); interface->quiesceEventCallbacks(); @@ -360,10 +365,10 @@ int main(int argc, char** argv) (void)interface->shutdown(); if (pendingRelease) { if (auto transaction = Void::FileSystem::atomic_write( - cfgDir / "release-transaction", pendingRelease->version); + cfgDir / "release-transaction", pendingRelease->version); !transaction) { Void::Log::error("main", "cannot record release transaction: {}", - transaction.error().message()); + transaction.error().message()); return 1; } ::setenv("ECHOION_CORE_PATH", pendingRelease->core.c_str(), 1); @@ -380,10 +385,11 @@ int main(int argc, char** argv) } arguments.emplace_back("--restore-state"); arguments.push_back(checkpointPath.string()); - if (auto result = Void::Process::reexec(pendingRelease->executable, - arguments); !result) { + if (auto result = + Void::Process::reexec(pendingRelease->executable, arguments); + !result) { Void::Log::error("main", "release re-exec failed: {}", - result.error().message()); + result.error().message()); return 1; } } diff --git a/EchoionWeb/CMakeLists.txt b/EchoionWeb/CMakeLists.txt index ff9a06b..e10aa9c 100644 --- a/EchoionWeb/CMakeLists.txt +++ b/EchoionWeb/CMakeLists.txt @@ -37,7 +37,6 @@ target_link_libraries(EchoionWeb Void::Data Void::Log Void::Async - Void::Net PRIVATE Threads::Threads Boost::beast @@ -56,7 +55,7 @@ endif() # That build output is what ships next to the runtime binary (default webRoot # "./web", relative to the working directory) and is installed. Opt out with # -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job). -option(ECHOION_BUILD_WEB "Build the React web frontend with npm/vite" ON) +option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON) set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend") set(_web_dist "${_web_frontend}/web-dist") diff --git a/EchoionWeb/frontend/public/manifest.webmanifest b/EchoionWeb/frontend/public/manifest.webmanifest index c8a0df9..ae42602 100644 --- a/EchoionWeb/frontend/public/manifest.webmanifest +++ b/EchoionWeb/frontend/public/manifest.webmanifest @@ -1,7 +1,7 @@ { "name": "Echoion Music Bot", "short_name": "Echoion", - "description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.", + "description": "Control the Echoion TeamSpeak music bot and view live server activity.", "start_url": "/", "scope": "/", "display": "standalone", diff --git a/EchoionWeb/frontend/public/sw.js b/EchoionWeb/frontend/public/sw.js index 531d95e..ee099dc 100644 --- a/EchoionWeb/frontend/public/sw.js +++ b/EchoionWeb/frontend/public/sw.js @@ -1,12 +1,12 @@ // Minimal, dependency-free service worker: makes the panel installable and // keeps the app shell available offline. It deliberately does NOT touch the -// live surfaces — /rpc and /ws (WebSockets aren't interceptable anyway), -// /config.json, /avatar/*, /emoji/* all fall through to the network so the UI -// never shows stale identity/config. +// live surfaces — /rpc (WebSockets aren't interceptable anyway), +// /config.json, /api/* and /avatar/* all fall through to the network so the +// UI never shows stale identity/config. // Bump when the player shell changes materially so installed/PWA clients do // not retain an index that references a removed hashed bundle. -const CACHE = 'echoion-shell-v2'; +const CACHE = 'echoion-shell-v4'; const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg']; self.addEventListener('install', (event) => { @@ -48,10 +48,9 @@ self.addEventListener('fetch', (event) => { // Never intercept the live control/config/media surfaces. if ( url.pathname === '/config.json' || + url.pathname.startsWith('/api/') || url.pathname.startsWith('/rpc') || - url.pathname.startsWith('/ws') || - url.pathname.startsWith('/avatar') || - url.pathname.startsWith('/emoji') + url.pathname.startsWith('/avatar') ) { return; } diff --git a/EchoionWeb/frontend/scripts/i18n-check.mjs b/EchoionWeb/frontend/scripts/i18n-check.mjs index f5051b0..d77942c 100644 --- a/EchoionWeb/frontend/scripts/i18n-check.mjs +++ b/EchoionWeb/frontend/scripts/i18n-check.mjs @@ -5,11 +5,8 @@ // - orphaned: present in ru.ts but never used as a literal key // // Dynamic keys can't be found by this scan and must be checked by hand: -// - watch.ts state strings rendered via t(w.playerEmpty) // - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label) // - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub) -// - server-sent watch.denied reasons (grep sendDenied in -// EchoionWeb/src/WatchSession.cpp) rendered via t(msg.reason) // Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC // list below suppresses the ones we know about. // @@ -25,17 +22,6 @@ const ruFile = join(srcDir, 'i18n', 'ru.ts'); // Keys reached through variables (see header); keep in sync by hand. const KNOWN_DYNAMIC = new Set([ - // watch.ts playerEmpty / state strings - 'Nothing loaded — paste a URL above', - 'Twitch embeds require HTTPS — open the site via its https:// domain', - // server-sent watch.denied reasons (grep sendDenied in WatchSession.cpp) - 'Sign in to control playback', - 'Only the host controls playback', - 'Watch queue is full', - 'Watch queue is empty', - 'Live stream — cannot seek', - 'That viewer is no longer here', - 'Only signed-in viewers can host', // connection state rendered via t(s.connection) in Sidebar.tsx 'connected', 'disconnected', @@ -48,8 +34,8 @@ const KNOWN_DYNAMIC = new Set([ 'Focus search', 'This help', // HEADS view titles/subtitles (App.tsx) - 'Now Playing', - 'What Echoion is streaming to the channel', + 'Dashboard', + 'Live playback and TeamSpeak server activity', 'Queue', 'Reorder and manage upcoming tracks', 'Search', @@ -58,8 +44,6 @@ const KNOWN_DYNAMIC = new Set([ 'Your favorites and saved playlists', 'History & Stats', 'Playback history and server insights', - 'Watch Together', - 'Synced viewing room — everyone in step', 'Server & Admin', 'Manage subscribers and broadcast', 'RPC / API', diff --git a/EchoionWeb/frontend/src/App.tsx b/EchoionWeb/frontend/src/App.tsx index 4ed3544..0d67666 100644 --- a/EchoionWeb/frontend/src/App.tsx +++ b/EchoionWeb/frontend/src/App.tsx @@ -1,6 +1,5 @@ import { useEffect } from 'react'; -import { appStore, boot, getStoredToken, toast } from './lib/app'; -import { initWatch } from './lib/watch'; +import { appStore, boot } from './lib/app'; import { initRouter } from './lib/router'; import { initShortcuts } from './lib/shortcuts'; import { initMediaSession } from './lib/mediaSession'; @@ -11,24 +10,20 @@ import { Sidebar } from './components/Sidebar'; import { MiniPlayer } from './components/MiniPlayer'; import { DialogHost } from './components/DialogHost'; import { ShortcutsHelp } from './components/ShortcutsHelp'; -import { NowView } from './views/NowView'; +import { DashboardView } from './views/DashboardView'; import { QueueView } from './views/QueueView'; import { SearchView } from './views/SearchView'; import { LibraryView } from './views/LibraryView'; import { StatsView } from './views/StatsView'; -import { WatchView } from './views/WatchView'; import { ServerView } from './views/ServerView'; import { RpcView } from './views/RpcView'; -import { RoomsView } from './views/RoomsView'; const HEADS: Record = { - now: ['Now Playing', 'What Echoion is streaming to the channel'], + dashboard: ['Dashboard', 'Live playback and TeamSpeak server activity'], queue: ['Queue', 'Reorder and manage upcoming tracks'], search: ['Search', 'Find tracks across YouTube and Yandex Music'], library: ['Library', 'Your favorites and saved playlists'], stats: ['History & Stats', 'Playback history and server insights'], - rooms: ['Listening Rooms', 'Independent music streams for different groups'], - watch: ['Watch Together', 'Synced viewing room — everyone in step'], server: ['Server & Admin', 'Manage subscribers and broadcast'], rpc: ['RPC / API', 'Connect to Echoion programmatically'], }; @@ -39,20 +34,12 @@ export function App() { useEffect(() => { boot(); - initWatch({ - getName: () => - (appStore.get().identity && - appStore.get().identity!.nickname) || - null, - getToken: getStoredToken, - toast, - }); initRouter(); initShortcuts(); initMediaSession(); }, []); - const [title, sub] = HEADS[s.view] || HEADS.now; + const [title, sub] = HEADS[s.view] || HEADS.dashboard; return (
@@ -84,7 +71,7 @@ export function App() {
- {s.onlineCount} {t('listening')} + {s.onlineCount} {t('online')} -
-
- {custom.map((c) => ( -
- {c.name} - :{c.name}: - -
- ))} -
-
- ); -} diff --git a/EchoionWeb/frontend/src/components/EmojiPicker.tsx b/EchoionWeb/frontend/src/components/EmojiPicker.tsx deleted file mode 100644 index 37d8a2c..0000000 --- a/EchoionWeb/frontend/src/components/EmojiPicker.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useStore } from '../lib/store'; -import { - EMOJI_CATEGORIES, - emojiStore, - rememberEmoji, -} from '../lib/emoji'; -import { t } from '../i18n'; - -// A popover emoji picker: recently-used, curated Unicode categories, and the -// server's custom image emojis. `onPick` receives either a unicode char or a -// :shortcode: for a custom emoji. -export function EmojiPicker(props: { - onPick: (token: string) => void; - onClose: () => void; -}) { - const { custom, recent } = useStore(emojiStore); - const ref = useRef(null); - - useEffect(() => { - const onDoc = (e: MouseEvent) => { - if (ref.current && !ref.current.contains(e.target as Node)) { - props.onClose(); - } - }; - // Defer so the opening click doesn't immediately close it. - const id = setTimeout( - () => document.addEventListener('mousedown', onDoc), - 0 - ); - return () => { - clearTimeout(id); - document.removeEventListener('mousedown', onDoc); - }; - }, [props]); - - const pick = (token: string) => { - rememberEmoji(token); - props.onPick(token); - }; - - return ( -
- {recent.length > 0 && ( -
-
{t('Recent')}
-
- {recent.map((token, i) => - token.startsWith(':') ? ( - - ) : ( - - ) - )} -
-
- )} - {custom.length > 0 && ( -
-
{t('Custom')}
-
- {custom.map((c) => ( - - ))} -
-
- )} - {EMOJI_CATEGORIES.map((cat) => ( -
-
{cat.label}
-
- {cat.emoji.map((e) => ( - - ))} -
-
- ))} -
- ); -} diff --git a/EchoionWeb/frontend/src/components/MiniPlayer.tsx b/EchoionWeb/frontend/src/components/MiniPlayer.tsx index cd635da..08a6e01 100644 --- a/EchoionWeb/frontend/src/components/MiniPlayer.tsx +++ b/EchoionWeb/frontend/src/components/MiniPlayer.tsx @@ -14,7 +14,7 @@ async function togglePlay() { // Mini player mirrors the current track on views other than Now Playing. export function MiniPlayer() { const s = useStore(appStore); - if (s.view === 'now' || !s.current) return null; + if (s.view === 'dashboard' || !s.current) return null; const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused); const canForceSkip = !!( s.identity && diff --git a/EchoionWeb/frontend/src/components/PlayerControls.tsx b/EchoionWeb/frontend/src/components/PlayerControls.tsx index df6591a..04e3564 100644 --- a/EchoionWeb/frontend/src/components/PlayerControls.tsx +++ b/EchoionWeb/frontend/src/components/PlayerControls.tsx @@ -11,11 +11,9 @@ import { } from './icons'; import { t } from '../i18n'; -// The one custom player control bar, shared by Watch Together (room /ws -// protocol) and Now Playing (bot RPC). Purely presentational: the two sync -// channels differ only in the callbacks the views pass in. Embedded players -// (YouTube/Twitch/HTML5) always run with native controls hidden; this bar is -// the only playback UI. +// Dashboard playback controls. This component is presentational; authenticated +// RPC callbacks are supplied by the dashboard while visitors receive a +// disabled, read-only transport surface. export function PlayerControls(props: { playing: boolean; positionMs: number; @@ -45,7 +43,7 @@ export function PlayerControls(props: { : 0; return (
-
+
- {open && ( -
- {local.length > 0 && ( -
-
{t('Local')}
- {local.map(renderControl)} -
- )} - {hasRoom && ( -
-
{t('Room')}
- {props.rateOptions && ( - - )} - {room.map(renderControl)} -
- )} -
- )} -
- ); -} diff --git a/EchoionWeb/frontend/src/components/Sidebar.tsx b/EchoionWeb/frontend/src/components/Sidebar.tsx index 0dcd65c..cb45f5a 100644 --- a/EchoionWeb/frontend/src/components/Sidebar.tsx +++ b/EchoionWeb/frontend/src/components/Sidebar.tsx @@ -18,7 +18,6 @@ import { HeartIcon, PlayIcon, QueueIcon, - RoomsIcon, SearchIcon, StatsIcon, WatchIcon, @@ -26,13 +25,11 @@ import { import { t, useLanguage } from '../i18n'; const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [ - { view: 'now', icon: , label: 'Now Playing' }, + { view: 'dashboard', icon: , label: 'Dashboard' }, { view: 'queue', icon: , label: 'Queue' }, { view: 'search', icon: , label: 'Search' }, { view: 'library', icon: , label: 'Library' }, { view: 'stats', icon: , label: 'History & Stats' }, - { view: 'rooms', icon: , label: 'Listening Rooms' }, - { view: 'watch', icon: , label: 'Watch Together' }, { view: 'server', icon: , label: 'Server & Admin' }, { view: 'rpc', icon: , label: 'RPC / API' }, ]; @@ -74,13 +71,14 @@ export function Sidebar() { ))} + {s.watchUrl && ( + + + + + {t('Watch Together')} + + + )}
diff --git a/EchoionWeb/frontend/src/components/TeamSpeakAdmin.tsx b/EchoionWeb/frontend/src/components/TeamSpeakAdmin.tsx new file mode 100644 index 0000000..ceeed3a --- /dev/null +++ b/EchoionWeb/frontend/src/components/TeamSpeakAdmin.tsx @@ -0,0 +1,472 @@ +import { useCallback, useEffect, useState } from 'react'; +import { safeCall, toast } from '../lib/app'; +import type { RpcMethodName } from '../lib/rpc'; +import { confirmDialog, promptDialog } from '../lib/dialog'; +import { EmptyRow } from './TrackRow'; +import { t, tf } from '../i18n'; + +interface AdminClient { + id: number; + databaseId: number | null; + uid: string | null; + nickname: string; + channelId: number; + talking: boolean; + muted: boolean; + deafened: boolean; + away: boolean; + groups: number[]; +} + +interface AdminChannel { + id: number; + name: string; + parentId: number | null; + default: boolean; + password: boolean; + maxClients: number; + currentClients: number; + clients: AdminClient[]; + channels: AdminChannel[]; +} + +interface DirectoryResponse { + server: { + name: string; + connected: boolean; + clientCount: number; + maxClients: number; + }; + channels: AdminChannel[]; +} + +interface Ban { + id: number; + uid: string | null; + nickname: string | null; + reason: string; + createdAt: number; + durationSeconds: number; +} + +interface ServerGroup { + id: number; + name: string; + default: boolean; +} + +export function TeamSpeakAdmin() { + const [directory, setDirectory] = useState(null); + const [bans, setBans] = useState([]); + const [groups, setGroups] = useState([]); + const [loading, setLoading] = useState(false); + + const refresh = useCallback(async () => { + setLoading(true); + const [nextDirectory, nextBans, nextGroups] = await Promise.all([ + safeCall('GetTeamSpeakDirectory'), + safeCall<{ bans?: Ban[] }>('GetTeamSpeakBans'), + safeCall<{ groups?: ServerGroup[] }>('GetTeamSpeakServerGroups'), + ]); + if (nextDirectory) setDirectory(nextDirectory); + if (nextBans) setBans(nextBans.bans || []); + if (nextGroups) setGroups(nextGroups.groups || []); + setLoading(false); + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const mutate = useCallback( + async ( + method: RpcMethodName, + params: Record, + message: string + ) => { + const result = await safeCall(method, params); + if (!result) return false; + toast(message); + await refresh(); + return true; + }, + [refresh] + ); + + async function sendServerMessage() { + const message = await promptDialog({ + title: t('Server message'), + message: t('Message sent to every connected TeamSpeak client:'), + confirmLabel: t('Send'), + }); + if (message) { + await mutate( + 'SendTeamSpeakServerMessage', + { message }, + t('Server message sent') + ); + } + } + + async function createChannel(parentId = 0) { + const name = await promptDialog({ + title: t('Create channel'), + message: t('Channel name:'), + confirmLabel: t('Create'), + }); + if (name) { + await mutate( + 'CreateTeamSpeakChannel', + { name, parentId, permanent: true }, + t('Channel created') + ); + } + } + + function ClientRow({ client }: { client: AdminClient }) { + return ( +
+
+ + {client.nickname} + #{client.id} + {client.away && {t('away')}} + {client.muted && {t('muted')}} + {client.deafened && {t('deafened')}} +
+
+ UID: {client.uid || '—'} + DB: {client.databaseId || '—'} + {t('Groups')}: {client.groups.join(', ') || '—'} +
+
+ + + {client.databaseId && ( + + )} + {client.databaseId && client.groups.length > 0 && ( + + )} + + +
+
+ ); + } + + function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) { + return ( +
+
+ {channel.name} + #{channel.id} + + {channel.currentClients}/{channel.maxClients || '∞'} + + + + + + {!channel.default && ( + + )} +
+ {channel.clients.map((client) => ( + + ))} + {channel.channels.map((child) => ( + + ))} +
+ ); + } + + return ( +
+
+
+
+

{directory?.server.name || t('TeamSpeak')}

+
+ {directory?.server.connected ? t('Connected') : t('Disconnected')} + {' · '} + {directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'} +
+
+
+ + + +
+
+
+ {directory?.channels.length ? ( + directory.channels.map((channel) => ( + + )) + ) : ( + + )} +
+
+ +
+
+

{t('Bans')}

+ {bans.length} +
+
+ {bans.length ? ( + bans.map((ban) => ( +
+
+ {ban.nickname || ban.uid || `#${ban.id}`} +
{ban.reason || t('No reason')}
+
+ + {ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')} + + +
+ )) + ) : ( + + )} +
+
+
+ ); +} diff --git a/EchoionWeb/frontend/src/components/WatchSearch.tsx b/EchoionWeb/frontend/src/components/WatchSearch.tsx deleted file mode 100644 index 6c27894..0000000 --- a/EchoionWeb/frontend/src/components/WatchSearch.tsx +++ /dev/null @@ -1,145 +0,0 @@ -import { useState } from 'react'; -import { rpc } from '../lib/rpc'; -import { send, watchStore } from '../lib/watch'; -import { toast } from '../lib/app'; -import { useStore } from '../lib/store'; -import { thumbFor } from '../lib/format'; -import type { Track } from '../lib/types'; -import { t, tf } from '../i18n'; - -// Normalize a Twitch channel entry: accept a bare login name, an @handle, or a -// full twitch.tv URL, and reduce it to the channel login the embed player -// expects. Numeric ids pass through (best effort — resolving them to a login -// would need the Helix API, which isn't wired up). -function normalizeTwitchChannel(input: string): string { - let s = input.trim(); - const m = s.match(/twitch\.tv\/([^/?#]+)/i); - if (m) s = m[1]; - s = s.replace(/^@/, ''); - return s.toLowerCase().replace(/[^a-z0-9_]/g, ''); -} - -// Add tracks to a watch room from inside it. YouTube uses the unauthenticated -// SearchTracks RPC (results added by title + thumbnail); Twitch has no search -// backend, so it offers an add-by-channel-name/id field instead. -export function WatchSearch({ disabled }: { disabled: boolean }) { - const w = useStore(watchStore); - const [query, setQuery] = useState(''); - const [channel, setChannel] = useState(''); - const [results, setResults] = useState([]); - const [open, setOpen] = useState(false); - - if (w.sourceChoice === 'twitch') { - return ( -
-
{ - e.preventDefault(); - const ch = normalizeTwitchChannel(channel); - if (!ch) return; - send({ - type: 'watch.queue.add', - source: 'twitch', - url: ch, - title: ch, - }); - toast(tf('Added “{0}” to queue', ch)); - setChannel(''); - }} - > - setChannel(e.target.value)} - placeholder={t( - 'Twitch channel name or id to queue…' - )} - autoComplete="off" - disabled={disabled} - /> - -
-
- ); - } - - return ( -
-
{ - e.preventDefault(); - const q = query.trim(); - if (!q) return; - try { - const res = await rpc.call<{ tracks?: Track[] }>( - 'SearchTracks', - { query: q } - ); - setResults((res && res.tracks) || []); - setOpen(true); - } catch (err) { - toast((err as { message?: string }).message || 'error'); - } - }} - > - setQuery(e.target.value)} - placeholder={t('Search YouTube to queue…')} - autoComplete="off" - disabled={disabled} - /> - -
- {open && results.length > 0 && ( -
- {results.slice(0, 8).map((tr, i) => ( - - ))} -
- )} -
- ); -} diff --git a/EchoionWeb/frontend/src/i18n/ru.ts b/EchoionWeb/frontend/src/i18n/ru.ts index 25b7d64..d9240fa 100644 --- a/EchoionWeb/frontend/src/i18n/ru.ts +++ b/EchoionWeb/frontend/src/i18n/ru.ts @@ -4,15 +4,12 @@ export const ru: Record = { // Sidebar / navigation - 'Now Playing': 'Сейчас играет', + 'Dashboard': 'Панель', 'Queue': 'Очередь', 'Search': 'Поиск', 'Library': 'Библиотека', 'History & Stats': 'История и статистика', 'Watch Together': 'Совместный просмотр', - 'Listening Rooms': 'Комнаты прослушивания', - 'Independent music streams for different groups': - 'Независимые музыкальные потоки для разных групп', 'Server & Admin': 'Сервер и админ', 'RPC / API': 'RPC / API', 'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3', @@ -26,15 +23,14 @@ export const ru: Record = { 'connected': 'подключено', 'disconnected': 'отключено', 'error': 'ошибка', - 'listening': 'слушают', // View headers - 'What Echoion is streaming to the channel': 'Что Echoion стримит в канал', + 'Live playback and TeamSpeak server activity': + 'Текущее воспроизведение и активность сервера TeamSpeak', 'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков', 'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке', 'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты', 'Playback history and server insights': 'История воспроизведения и статистика сервера', - 'Synced viewing room — everyone in step': 'Синхронный просмотр — все в ногу', 'Manage subscribers and broadcast': 'Управление подписчиками и объявления', 'Connect to Echoion programmatically': 'Подключение к Echoion из кода', @@ -125,75 +121,31 @@ export const ru: Record = { '{0}% skip rate': '{0}% пропусков', '{0} requests': '{0} запросов', - // Watch together - 'Nothing loaded — paste a URL above': 'Ничего не загружено — вставьте ссылку выше', - 'Twitch embeds require HTTPS — open the site via its https:// domain': - 'Встраивание Twitch требует HTTPS — откройте сайт по его https:// адресу', - 'YouTube URL to watch together': 'Ссылка YouTube для совместного просмотра', - 'Twitch channel or URL to watch together': 'Канал или ссылка Twitch для совместного просмотра', - 'Video URL': 'Видео по ссылке', - 'Embed': 'Встраивание', - 'Direct video or .m3u8 URL to watch together': - 'Прямая ссылка на видео или .m3u8 для совместного просмотра', - 'Embed URL (Kodik, etc.) to watch together': - 'Ссылка для встраивания (Kodik и др.) для совместного просмотра', + // Shared playback and action labels 'Load': 'Загрузить', - '+ Queue': '+ В очередь', - 'Add to the watch queue': 'Добавить в очередь просмотра', - 'Guest — sign in to control': 'Гость — войдите, чтобы управлять', - 'You are hosting': 'Вы ведущий', - 'Viewer': 'Зритель', - 'Synced': 'Синхронно', - 'Resync': 'Синхронизировать', - 'Resynced to room': 'Синхронизировано с комнатой', - 'Live stream — cannot seek': 'Прямой эфир — перемотка недоступна', - 'LIVE': 'ЭФИР', - 'In the room': 'В комнате', - 'Room chat': 'Чат комнаты', - 'Say something…': 'Скажите что-нибудь…', - 'Send': 'Отправить', - 'Host': 'Ведущий', - 'Host only': 'Только ведущий', 'Play next': 'Следующее', - '(you)': '(вы)', - 'Buffering…': 'Буферизация…', - 'In sync': 'Синхронно', - 'Nothing queued — paste a URL and hit “+ Queue”': 'Очередь пуста — вставьте ссылку и нажмите «+ В очередь»', - 'Remove from queue': 'Убрать из очереди', - 'added by {0}': 'добавил {0}', + 'LIVE': 'ЭФИР', + 'Send': 'Отправить', 'Fullscreen': 'Во весь экран', - 'Fullscreen unavailable': 'Полноэкранный режим недоступен', - 'Playback quality (best effort — YouTube may keep auto)': - 'Качество (по возможности — YouTube может оставить авто)', - 'Auto': 'Авто', - 'Not allowed': 'Недостаточно прав', - // Watch Together protocol extensions (items 3, 4, 5) - 'New room name…': 'Название новой комнаты…', - 'Create / join': 'Создать / войти', - 'Make host': 'Назначить ведущим', - 'That viewer is no longer here': 'Этого зрителя уже нет', - 'Only signed-in viewers can host': 'Вести может только вошедший зритель', - // Watch player & UX (items 7, 8, 16, 20) - 'Playback speed': 'Скорость воспроизведения', - 'Search YouTube to queue…': 'Найти на YouTube для очереди…', - 'Recent': 'Недавние', - 'Custom': 'Свои', - 'Custom emojis': 'Свои эмодзи', - 'Add emoji': 'Добавить эмодзи', - 'Emoji added': 'Эмодзи добавлено', - 'Emoji removed': 'Эмодзи удалено', - 'shortcode (a-z0-9_)': 'код (a-z0-9_)', - 'Choose an image file': 'Выберите файл изображения', - 'Emoji name must be 1-32 chars of a-z, 0-9, _': 'Имя: 1–32 символа a-z, 0-9, _', - 'Emoji image too large (max ~64KB)': 'Изображение слишком большое (макс ~64КБ)', // Server & admin + 'Administration': 'Администрирование', + 'Administrator authentication required': 'Требуется вход администратора', + 'Sign in with an account in a configured TeamSpeak admin group.': + 'Войдите под учётной записью, входящей в настроенную группу администраторов TeamSpeak.', + 'TeamSpeak': 'TeamSpeak', + 'Echoion service': 'Служба Echoion', + 'Bot messaging and runtime operations': + 'Сообщения бота и управление службой', 'Subscribers': 'Подписчики', + 'Emojis': 'Эмодзи', + 'Audit history': 'Журнал действий', + 'Room emojis moved to VoidWatch and are managed from its administration page.': + 'Эмодзи комнат перенесены в VoidWatch и управляются на его странице администрирования.', + 'Open VoidWatch admin ↗': 'Открыть панель VoidWatch ↗', 'Announce…': 'Объявление…', 'Reload config': 'Перезагрузить конфиг', 'Restart web UI': 'Перезапустить веб-интерфейс', - 'Stop and start the web server without touching the bot': - 'Остановить и запустить веб-сервер, не трогая бота', 'Unsub all': 'Отписать всех', 'No subscribers': 'Нет подписчиков', 'Nobody online right now': 'Сейчас никого нет в сети', @@ -201,7 +153,6 @@ export const ru: Record = { 'Offline': 'Не в сети', 'Unsub': 'Отписать', 'Unsubscribe {0}?': 'Отписать {0}?', - 'Unsubscribed {0}': '{0} отписан', 'Announcement to all subscribers:': 'Объявление всем подписчикам:', 'Announcement sent': 'Объявление отправлено', 'Configuration reloaded': 'Конфигурация перезагружена', @@ -213,11 +164,92 @@ export const ru: Record = { 'Удалить ВСЕ подписки? Это нельзя отменить.', 'All subscriptions removed': 'Все подписки удалены', 'Listening': 'Слушает', - 'Audit log': 'Журнал аудита', 'Refresh': 'Обновить', 'No audit entries yet': 'Записей аудита пока нет', 'client #{0}': 'клиент №{0}', + // Public TeamSpeak directory + 'TeamSpeak server': 'Сервер TeamSpeak', + 'Complete channel directory': 'Полное дерево каналов', + 'Connected': 'Подключено', + 'Disconnected': 'Отключено', + 'No channels available': 'Нет доступных каналов', + 'Password protected': 'Защищён паролем', + 'Talking': 'Говорит', + 'Away': 'Отошёл', + 'Muted': 'Микрофон выключен', + 'Deafened': 'Звук выключен', + 'clients': 'клиентов', + 'channels': 'каналов', + 'capacity': 'вместимость', + 'online': 'в сети', + 'default': 'по умолчанию', + 'locked': 'закрыт', + 'away': 'отошёл', + 'muted': 'микрофон выкл.', + 'deafened': 'звук выкл.', + + // TeamSpeak administration + 'No TeamSpeak topology available': 'Дерево TeamSpeak недоступно', + 'Message': 'Сообщение', + 'Message {0}': 'Сообщение для {0}', + 'Private message:': 'Личное сообщение:', + 'Channel message:': 'Сообщение в канал:', + 'Message sent': 'Сообщение отправлено', + 'Server message': 'Сообщение серверу', + 'Message sent to every connected TeamSpeak client:': + 'Сообщение всем подключённым клиентам TeamSpeak:', + 'Server message sent': 'Сообщение серверу отправлено', + 'Move': 'Переместить', + 'Move {0}': 'Переместить {0}', + 'Destination channel ID:': 'ID целевого канала:', + 'Client moved': 'Клиент перемещён', + 'Kick': 'Выгнать', + 'Kick {0}': 'Выгнать {0}', + 'Kick this client from the server?': 'Выгнать этого клиента с сервера?', + 'Client kicked': 'Клиент выгнан', + 'Ban': 'Заблокировать', + 'Ban {0}': 'Заблокировать {0}', + 'Duration in seconds (0 = permanent):': + 'Срок в секундах (0 = бессрочно):', + 'Apply this ban now?': 'Заблокировать этого клиента сейчас?', + 'Client banned': 'Клиент заблокирован', + 'Bans': 'Блокировки', + 'No bans': 'Блокировок нет', + 'No reason': 'Без причины', + 'Permanent': 'Бессрочно', + 'Remove ban': 'Снять блокировку', + 'Remove this TeamSpeak ban?': 'Снять эту блокировку TeamSpeak?', + 'Unban': 'Разблокировать', + 'Ban removed': 'Блокировка снята', + 'Groups': 'Группы', + 'Current groups': 'Текущие группы', + 'Server group ID:': 'ID серверной группы:', + 'Add server group': 'Добавление в серверную группу', + 'Add group': 'Добавить в группу', + 'Group added': 'Клиент добавлен в группу', + 'Remove server group': 'Удаление из серверной группы', + 'Remove group': 'Удалить из группы', + 'Group removed': 'Клиент удалён из группы', + 'Create channel': 'Создать канал', + 'Channel name:': 'Название канала:', + 'Create': 'Создать', + 'Channel created': 'Канал создан', + 'Add child': 'Добавить подканал', + 'Rename channel': 'Переименовать канал', + 'Edit': 'Изменить', + 'Channel updated': 'Канал обновлён', + 'Reorder': 'Переместить', + 'Reorder channel': 'Переместить канал', + 'Parent channel ID (0 = root):': 'ID родительского канала (0 = корень):', + 'Previous sibling channel ID (0 = first):': + 'ID предыдущего канала на этом уровне (0 = первый):', + 'Channel reordered': 'Канал перемещён', + 'Delete channel': 'Удалить канал', + 'Delete {0} and its contents?': 'Удалить {0} вместе с содержимым?', + 'Channel deleted': 'Канал удалён', + 'Continue': 'Продолжить', + // RPC view 'Connect programmatically': 'Программное подключение', 'Copy snippet': 'Скопировать пример', @@ -262,22 +294,7 @@ export const ru: Record = { 'Menu': 'Меню', 'Back 10 seconds': 'Назад на 10 секунд', 'Forward 10 seconds': 'Вперёд на 10 секунд', - 'Leave room': 'Покинуть комнату', - 'Leave this room': 'Покинуть эту комнату', - 'Room': 'Комната', - 'Watch together': 'Смотреть вместе', - 'Refresh rooms': 'Обновить список комнат', - 'Join a room to watch in sync, or create your own.': - 'Войдите в комнату для синхронного просмотра или создайте свою.', - 'No active rooms yet — create one below.': - 'Активных комнат пока нет — создайте свою ниже.', - '{0} watching': '{0} смотрят', - 'Tap to unmute': 'Нажмите, чтобы включить звук', - 'Add channel': 'Добавить канал', - 'Twitch channel name or id to queue…': 'Имя или ID Twitch-канала для очереди…', 'Clear queue': 'Очистить очередь', - 'Watch queue is full': 'Очередь просмотра заполнена', - 'Watch queue is empty': 'Очередь просмотра пуста', 'Confirm': 'Подтвердить', 'OK': 'ОК', 'Save': 'Сохранить', @@ -289,56 +306,5 @@ export const ru: Record = { 'Playlist name': 'Название плейлиста', 'Save playlist': 'Сохранить плейлист', - // Independent TeamSpeak listening rooms - 'MULTI-STREAM': 'МУЛЬТИПОТОК', - 'NOW TUNED': 'СЕЙЧАС В КОМНАТЕ', - 'Your channel, split into listening spaces': - 'Разделите канал на пространства для прослушивания', - 'Each room has its own queue and bot stream. Join one to hear and control it.': - 'У каждой комнаты своя очередь и поток бота. Войдите, чтобы слушать и управлять.', - 'Room name': 'Название комнаты', - 'Create room': 'Создать комнату', - 'Created room “{0}”': 'Комната «{0}» создана', - 'Live rooms': 'Активные комнаты', - 'No listening rooms yet': 'Комнат прослушивания пока нет', - '{0} listeners · {1} queued': '{0} слушателей · {1} в очереди', - 'JOINED': 'ВЫ В КОМНАТЕ', - 'PAUSED': 'ПАУЗА', - 'IDLE': 'ТИШИНА', - 'Choose a room': 'Выберите комнату', - 'Your TeamSpeak audio follows the room you join.': - 'Звук TeamSpeak переключается на комнату, в которую вы вошли.', - 'Leave': 'Выйти', - 'Delete room': 'Удалить комнату', - 'Delete “{0}” for everyone?': 'Удалить «{0}» для всех?', - 'Stop': 'Остановить', - 'Skip': 'Пропустить', - 'Move up': 'Переместить выше', - 'Move down': 'Переместить ниже', - 'Pause': 'Пауза', - 'Resume': 'Продолжить', - 'Paused': 'На паузе', - 'Streaming now': 'Сейчас транслируется', - 'Ready': 'Готово', - '{0} people are tuned in': 'Подключено: {0}', - 'Paste a URL or search for a track…': - 'Вставьте ссылку или найдите трек…', 'Add': 'Добавить', - 'Added to room queue': 'Добавлено в очередь комнаты', - 'Room queue': 'Очередь комнаты', - 'This room queue is empty': 'Очередь этой комнаты пуста', - - // Controllable embeds (Kodik / Playerjs) - 'Embed synced': 'Встраиваемый плеер синхронизирован', - 'Embed is view-only': 'Встраиваемый плеер — только просмотр', - 'Settings': 'Настройки', - 'Local': 'Локально', - 'Quality': 'Качество', - 'Speed': 'Скорость', - 'Voiceover': 'Озвучка', - 'Episode': 'Серия', - 'Subtitles': 'Субтитры', - 'Off': 'Выкл.', - 'Choose': 'Выбрать', - 'Only the host can change this': 'Изменять может только ведущий', }; diff --git a/EchoionWeb/frontend/src/lib/app.ts b/EchoionWeb/frontend/src/lib/app.ts index 9370410..deb8a3a 100644 --- a/EchoionWeb/frontend/src/lib/app.ts +++ b/EchoionWeb/frontend/src/lib/app.ts @@ -5,10 +5,9 @@ import { rpc, type RpcMethodName } from './rpc'; import { Store } from './store'; import { t, tf, setLanguage, getLanguage } from '../i18n'; -import { setWatchName } from './watch'; -import { loadCustomEmojis } from './emoji'; import type { Identity, + PublicDashboard, QueueEntry, ServerInfo, Status, @@ -17,13 +16,11 @@ import type { } from './types'; export type ViewName = - | 'now' + | 'dashboard' | 'queue' | 'search' | 'library' | 'stats' - | 'rooms' - | 'watch' | 'server' | 'rpc'; @@ -42,6 +39,8 @@ export interface AppState { durationMs: number; onlineCount: number; listeners: Subscriber[]; + publicDashboard: PublicDashboard | null; + watchUrl: string; toast: string | null; // Server-wide switch for the Now Playing video preview (item 11), from // /config.json; users can still disable it locally. @@ -51,10 +50,14 @@ export interface AppState { // Sidebar drawer on small screens (hamburger in the header); ignored by // CSS on desktop widths where the sidebar is always visible. sidebarOpen: boolean; + capabilities: { + plugins: boolean; + webExtensions: boolean; + }; } export const appStore = new Store({ - view: 'now', + view: 'dashboard', connection: 'disconnected', identity: null, status: null, @@ -68,10 +71,16 @@ export const appStore = new Store({ durationMs: 0, onlineCount: 0, listeners: [], + publicDashboard: null, + watchUrl: '', toast: null, nowPlayingVideoAllowed: true, shortcutsOpen: false, sidebarOpen: false, + capabilities: { + plugins: false, + webExtensions: false, + }, }); // ── toast ──────────────────────────────────────────────────────────────────── @@ -124,9 +133,7 @@ export async function changeLanguage(language: 'en' | 'ru') { export function applyIdentity(auth: Identity | null) { appStore.set({ identity: auth }); if (auth) { - setWatchName(auth.nickname || null); void loadUserPrefs(); - void loadCustomEmojis(); } } @@ -176,6 +183,7 @@ export async function connectWithToken(tokenInput: string) { const auth = (await rpc.authenticate(token)) as Identity; localStorage.setItem('echoion.token', token); applyIdentity(auth); + await loadCapabilities(); toast(tf('Welcome, {0}!', auth.nickname || t('friend'))); } refreshAll(); @@ -210,9 +218,6 @@ export function showView(view: ViewName) { // Navigation closes the mobile drawer. appStore.set({ view, sidebarOpen: false }); // Reflect the selection in the URL for back/forward + shareable links. - // The watch view owns its own #watch/ hash (see watch.ts), so a - // re-selection never clobbers an existing room deep link. - if (view === 'watch' && location.hash.startsWith('#watch')) return; const target = `#${view}`; if (location.hash !== target) location.hash = target; } @@ -275,6 +280,47 @@ export async function loadFavorites() { // ── boot ───────────────────────────────────────────────────────────────────── let booted = false; +let dashboardEtag = ''; + +export async function refreshPublicDashboard() { + try { + const response = await fetch('/api/public/dashboard', { + headers: dashboardEtag ? { 'If-None-Match': dashboardEtag } : {}, + cache: 'no-cache', + }); + if (response.status === 304) return; + if (!response.ok) return; + const dashboard = (await response.json()) as PublicDashboard; + dashboardEtag = response.headers.get('ETag') || ''; + const state = appStore.get(); + const publicTrack = dashboard.playback.track; + const sameTrack = + publicTrack && state.current && publicTrack.id === state.current.id; + const current = publicTrack + ? { + ...(sameTrack ? state.current! : {}), + ...publicTrack, + duration: + publicTrack.durationMs ?? publicTrack.duration ?? 0, + } + : null; + appStore.set({ + publicDashboard: dashboard, + current, + status: { + ...(state.status || {}), + isPlaying: dashboard.playback.isPlaying, + isPaused: dashboard.playback.isPaused, + volume: dashboard.playback.volume, + }, + positionMs: dashboard.playback.positionMs, + durationMs: current?.duration || 0, + onlineCount: dashboard.server.clientCount, + }); + } catch { + /* The RPC login remains usable if the public snapshot is unavailable. */ + } +} export function boot() { if (booted) return; @@ -283,24 +329,29 @@ export function boot() { // Apply the persisted language before anything renders text. setLanguage(getLanguage(), false); - // Server config: the Now Playing video preview can be disabled globally. + // Server config: the video preview policy and external VoidWatch link. fetch('/config.json') .then((r) => r.json()) .then((cfg) => { - if (cfg && cfg.nowPlayingVideo === false) { - appStore.set({ nowPlayingVideoAllowed: false }); - } + appStore.set({ + nowPlayingVideoAllowed: cfg?.nowPlayingVideo !== false, + watchUrl: + typeof cfg?.watchUrl === 'string' ? cfg.watchUrl : '', + }); }) .catch(() => { /* keep the default (allowed) */ }); rpc.onState = (s) => appStore.set({ connection: s }); + void refreshPublicDashboard(); + setInterval(() => void refreshPublicDashboard(), 5000); // After an automatic reconnect, restore the authenticated session from // the stored token (or autologin) and pull fresh state. rpc.onReconnected = async () => { await restoreSession(); + await loadCapabilities(); refreshAll(); toast(t('Reconnected')); }; @@ -335,6 +386,9 @@ export function boot() { }); } }); + rpc.on('plugins.updated', () => { + if (appStore.get().capabilities.webExtensions) void loadWebExtensions(); + }); // Local 1s ticker keeps the progress bar moving between server updates. setInterval(() => { @@ -361,6 +415,92 @@ export function boot() { // Session restore is independent of the connection: even if auth fails // we still refresh so guests see live state instead of a blank app. await restoreSession(); + await loadCapabilities(); refreshAll(); })(); } + +async function loadCapabilities() { + const capabilities = await safeCall( + 'GetCapabilities' + ); + if (capabilities) { + appStore.set({ capabilities }); + if (capabilities.webExtensions) await loadWebExtensions(); + } +} + +interface PluginWebAsset { + id: string; + javascript: string; + css: string; +} + +interface LoadedWebExtension { + signature: string; + cleanup?: () => void; +} + +const loadedWebExtensions = new Map(); + +function unloadWebExtension(id: string) { + const loaded = loadedWebExtensions.get(id); + if (!loaded) return; + try { + loaded.cleanup?.(); + } catch (error) { + console.error(`Echoion plugin web asset ${id} cleanup failed`, error); + } + document + .querySelectorAll(`style[data-echoion-plugin="${CSS.escape(id)}"]`) + .forEach((style) => style.remove()); + loadedWebExtensions.delete(id); +} + +async function loadWebExtensions() { + const response = await safeCall<{ assets?: PluginWebAsset[] }>( + 'GetPluginExtensions' + ); + if (!response) return; + const assets = response.assets || []; + const currentIds = new Set(assets.map((asset) => asset.id).filter(Boolean)); + for (const id of loadedWebExtensions.keys()) { + if (!currentIds.has(id)) unloadWebExtension(id); + } + for (const asset of assets) { + if (!asset.id) continue; + const signature = `${asset.javascript}\0${asset.css}`; + if (loadedWebExtensions.get(asset.id)?.signature === signature) continue; + unloadWebExtension(asset.id); + let style: HTMLStyleElement | undefined; + if (asset.css) { + style = document.createElement('style'); + style.dataset.echoionPlugin = asset.id; + style.textContent = asset.css; + document.head.appendChild(style); + } + try { + const host = { + call: async (plugin: string, method: string, params: unknown = {}) => + rpc.call('PluginCall', { + plugin, + method, + params: JSON.stringify(params), + }), + store: appStore, + toast, + }; + const cleanup = new Function( + 'Echoion', + `'use strict';\n${asset.javascript}` + )(host); + loadedWebExtensions.set(asset.id, { + signature, + cleanup: typeof cleanup === 'function' ? cleanup : undefined, + }); + } catch (error) { + style?.remove(); + console.error(`Echoion plugin web asset ${asset.id} failed`, error); + } + } +} diff --git a/EchoionWeb/frontend/src/lib/auditMethods.test.ts b/EchoionWeb/frontend/src/lib/auditMethods.test.ts index 3e407a7..fd96c87 100644 --- a/EchoionWeb/frontend/src/lib/auditMethods.test.ts +++ b/EchoionWeb/frontend/src/lib/auditMethods.test.ts @@ -2,10 +2,12 @@ import { describe, expect, it } from 'vitest'; import { auditMethodName } from './auditMethods'; describe('audit RPC method mapping', () => { - it('keeps listening-room methods append-only and aligned with RpcTypes.hpp', () => { - expect(auditMethodName(53)).toBe('ListListeningRooms'); - expect(auditMethodName(62)).toBe('GetListeningRoomQueue'); - expect(auditMethodName(63)).toBe('SkipListeningRoom'); - expect(auditMethodName(66)).toBe('ClearListeningRoomQueue'); + it('keeps removed room audit slots and newer methods aligned', () => { + expect(auditMethodName(53)).toBe('Reserved53'); + expect(auditMethodName(66)).toBe('Reserved66'); + expect(auditMethodName(67)).toBe('GetCapabilities'); + expect(auditMethodName(72)).toBe('Reserved72'); + expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory'); + expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage'); }); }); diff --git a/EchoionWeb/frontend/src/lib/auditMethods.ts b/EchoionWeb/frontend/src/lib/auditMethods.ts index 5143ef3..d822e27 100644 --- a/EchoionWeb/frontend/src/lib/auditMethods.ts +++ b/EchoionWeb/frontend/src/lib/auditMethods.ts @@ -54,24 +54,46 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [ 'ToggleAutoplay', 'GetUserPrefs', 'SetUserPrefs', - 'GetCustomEmojis', - 'AddCustomEmoji', // 50 - 'RemoveCustomEmoji', + 'Reserved49', + 'Reserved50', + 'Reserved51', 'GetLyrics', - 'ListListeningRooms', - 'CreateListeningRoom', - 'DeleteListeningRoom', - 'JoinListeningRoom', - 'LeaveListeningRoom', - 'PlayInListeningRoom', - 'PauseListeningRoom', - 'ResumeListeningRoom', - 'StopListeningRoom', - 'GetListeningRoomQueue', - 'SkipListeningRoom', - 'RemoveFromListeningRoomQueue', - 'MoveInListeningRoomQueue', - 'ClearListeningRoomQueue', + 'Reserved53', + 'Reserved54', + 'Reserved55', + 'Reserved56', + 'Reserved57', + 'Reserved58', + 'Reserved59', + 'Reserved60', + 'Reserved61', + 'Reserved62', + 'Reserved63', + 'Reserved64', + 'Reserved65', + 'Reserved66', + 'GetCapabilities', + 'GetPluginExtensions', + 'PluginCall', + 'Reserved70', + 'Reserved71', + 'Reserved72', + 'GetTeamSpeakDirectory', + 'MoveTeamSpeakClient', + 'KickTeamSpeakClient', + 'BanTeamSpeakClient', + 'GetTeamSpeakBans', + 'UnbanTeamSpeakClient', + 'CreateTeamSpeakChannel', + 'EditTeamSpeakChannel', + 'ReorderTeamSpeakChannel', + 'DeleteTeamSpeakChannel', + 'GetTeamSpeakServerGroups', + 'AddTeamSpeakServerGroupMember', + 'RemoveTeamSpeakServerGroupMember', + 'SendTeamSpeakPrivateMessage', + 'SendTeamSpeakChannelMessage', + 'SendTeamSpeakServerMessage', ]; export function auditMethodName(method: number): string { diff --git a/EchoionWeb/frontend/src/lib/embedProtocols.test.ts b/EchoionWeb/frontend/src/lib/embedProtocols.test.ts deleted file mode 100644 index a70c3f4..0000000 --- a/EchoionWeb/frontend/src/lib/embedProtocols.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols'; - -const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!; -const kodik = byName('kodik'); -const playerjs = byName('playerjs'); -const alloha = byName('alloha'); -const vimeo = byName('vimeo'); -const playerjsSpec = byName('player.js'); -const rutube = byName('rutube'); -const dailymotion = byName('dailymotion'); -const vk = byName('vk'); - -describe('kodik parse', () => { - it('parses JSON-string time updates', () => { - expect( - kodik.parse( - JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 }) - ) - ).toEqual({ kind: 'time', seconds: 42.5 }); - }); - - it('parses duration and play/pause/ended state', () => { - expect( - kodik.parse({ key: 'kodik_player_duration_update', value: 1440 }) - ).toEqual({ kind: 'duration', seconds: 1440 }); - expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' }); - expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({ - kind: 'pause', - }); - expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({ - kind: 'ended', - }); - }); - - it('rejects everything else', () => { - expect(kodik.parse('garbage')).toBeNull(); - expect(kodik.parse('{"broken json')).toBeNull(); - expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull(); - expect(kodik.parse(null)).toBeNull(); - expect(kodik.parse(42)).toBeNull(); - }); - - it('is hostname-pinned and seeks by reloading with start_from', () => { - expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe( - true - ); - expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true); - expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false); - // start_from is set (overwritten) while signed params are preserved. - const seeked = kodik.reloadSeek!( - 'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5', - 42.9 - ); - expect(seeked).toContain('start_from=42'); - expect(seeked).toContain('d_sign=abc'); - expect(seeked).not.toContain('start_from=5'); - }); -}); - -describe('playerjs.com parse', () => { - it('parses object and JSON-string events', () => { - expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({ - kind: 'time', - seconds: 12, - }); - expect( - playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 })) - ).toEqual({ kind: 'duration', seconds: 600 }); - expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' }); - }); - - it('does not lock on player.js-spec or unknown shapes', () => { - expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull(); - expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull(); - expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull(); - }); - - it('normalizes quality, voiceover and subtitle capabilities', () => { - expect( - playerjs.parse({ - event: 'qualities', - answer: [{ id: '720', name: '720p' }, '1080p'], - }) - ).toMatchObject({ - kind: 'extraList', - control: { id: 'quality', scope: 'local' }, - }); - expect( - playerjs.parse({ - event: 'audiotracks', - answer: { ru: 'Russian', en: 'English' }, - }) - ).toMatchObject({ - kind: 'extraList', - control: { id: 'audiotrack', scope: 'synced' }, - }); - expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({ - kind: 'extraCurrent', - id: 'subtitle', - value: '1', - }); - }); -}); - -describe('alloha detection', () => { - it('pins known Alloha player hosts', () => { - expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true); - expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true); - expect(alloha.matchUrl!('https://example.com/player')).toBe(false); - }); -}); - -describe('vimeo parse', () => { - it('parses timeupdate with bundled duration and the getDuration reply', () => { - expect( - vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } }) - ).toEqual({ kind: 'time', seconds: 10, duration: 200 }); - expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({ - kind: 'duration', - seconds: 200, - }); - expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' }); - }); - - it('does not lock on a playerjs.com message (has `answer`) or garbage', () => { - expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull(); - expect(vimeo.parse('garbage')).toBeNull(); - expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull(); - }); - - it('matchUrl selects vimeo hosts only', () => { - expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true); - expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true); - expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false); - }); - - it('prepareUrl hides native chrome', () => { - const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123'); - expect(p).toContain('controls=0'); - expect(p).toContain('title=0'); - }); -}); - -describe('player.js (embedly spec) parse', () => { - it('parses context-tagged events', () => { - expect( - playerjsSpec.parse({ - context: 'player.js', - event: 'timeupdate', - value: { seconds: 5, duration: 100 }, - }) - ).toEqual({ kind: 'time', seconds: 5, duration: 100 }); - expect( - playerjsSpec.parse({ context: 'player.js', event: 'pause' }) - ).toEqual({ kind: 'pause' }); - expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual( - { kind: 'hello' } - ); - }); - - it('rejects messages without the player.js context', () => { - expect(playerjsSpec.parse({ event: 'play' })).toBeNull(); - expect(playerjsSpec.parse('garbage')).toBeNull(); - }); -}); - -describe('rutube parse + matchUrl', () => { - it('parses player:* events', () => { - expect( - rutube.parse( - JSON.stringify({ type: 'player:currentTime', data: { time: 30 } }) - ) - ).toEqual({ kind: 'time', seconds: 30 }); - expect( - rutube.parse({ type: 'player:changeState', data: { state: 'playing' } }) - ).toEqual({ kind: 'play' }); - expect( - rutube.parse({ type: 'player:durationChange', data: { duration: 90 } }) - ).toEqual({ kind: 'duration', seconds: 90 }); - }); - - it('ignores foreign messages', () => { - expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull(); - expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull(); - expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true); - expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false); - }); -}); - -describe('dailymotion parse + prepareUrl', () => { - it('parses classic querystring events', () => { - expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual( - { kind: 'time', seconds: 12, duration: 240 } - ); - expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' }); - expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' }); - expect(dailymotion.parse({ event: 'play' })).toBeNull(); - }); - - it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => { - expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x')) - .toBe(true); - expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true); - const prepared = dailymotion.prepareUrl!( - 'https://www.dailymotion.com/embed/video/x?foo=1' - ); - expect(prepared).toContain('api=postMessage'); - expect(prepared).toContain('controls=0'); - expect(prepared).toContain('foo=1'); - // idempotent - expect(dailymotion.prepareUrl!(prepared)).toBe(prepared); - }); -}); - -describe('vk parse + prepareUrl', () => { - it('parses player_api events', () => { - expect( - vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 }) - ).toEqual({ kind: 'time', seconds: 8, duration: 60 }); - expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({ - kind: 'play', - }); - expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({ - kind: 'pause', - }); - }); - - it('ignores foreign messages and injects js_api=1', () => { - expect(vk.parse({ event: 'play', answer: 1 })).toBeNull(); - expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true); - expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true); - expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain( - 'js_api=1' - ); - }); -}); - -describe('registry order + prepareEmbedUrl', () => { - it('generic (content-detected) set is player.js then playerjs', () => { - expect( - EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name) - ).toEqual(['player.js', 'playerjs']); - }); - - it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => { - expect( - prepareEmbedUrl('https://www.dailymotion.com/embed/video/x') - ).toContain('api=postMessage'); - expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe( - 'https://kodik.info/seria/1/hash/720p' - ); - }); -}); diff --git a/EchoionWeb/frontend/src/lib/embedProtocols.ts b/EchoionWeb/frontend/src/lib/embedProtocols.ts deleted file mode 100644 index f0f4899..0000000 --- a/EchoionWeb/frontend/src/lib/embedProtocols.ts +++ /dev/null @@ -1,972 +0,0 @@ -// Adapters for postMessage-controllable embed players in the Watch view. -// -// A generic iframe can only be driven if the player inside exposes a -// postMessage API — everything else stays view-only by browser design. -// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS): -// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec}; -// commands {key:'kodik_player_api', value:{method}}. -// - vimeo: {method:'play'|...} strings; events {event:'timeupdate', -// data:{seconds,duration}}. Hostname-selected (player.vimeo.com). -// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL -// params (prepareUrl) and their command/event shapes are community- -// documented — flagged VERIFY, one-line fixes if a live embed differs. -// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co. -// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands, -// {event, answer} events. -// Shapes marked VERIFY are community-documented, not official; dev builds -// console.debug every unrecognized frame message to reverse-engineer them. -// -// Detection: for a hostname-matched player only that protocol is probed; -// otherwise the generic set is probed until one `parse` recognizes a message -// and locks the adapter. On timeout the embed is uncontrollable and the -// caller keeps today's host-driven view-only behavior. - -export interface EmbedAdapter { - protocol: string; - // True for players (Kodik) driven by reloading the iframe rather than - // postMessage commands: the caller should avoid drift-reconcile churn and - // not expect pause to work. - reloadBased: boolean; - play(): void; - pause(): void; - seekMs(ms: number): void; - setVolume(v01: number): void; // 0..1 - positionMs(): number; - durationMs(): number; - paused(): boolean; - extras(): PlayerExtraControl[]; - setExtra(id: string, value: string): void; - destroy(): void; -} - -export interface ExtraControlOption { - value: string; - label: string; -} - -export interface PlayerExtraControl { - id: string; - label: string; - kind: 'select' | 'button'; - options: ExtraControlOption[]; - current: string | null; - scope: 'local' | 'synced'; -} - -// Fired only for events NOT caused by our own commands (see suppression -// below) — i.e. gestures made inside the embed UI, which the host must relay -// to the room. -export interface EmbedCallbacks { - onPlay(positionMs: number): void; - onPause(positionMs: number): void; - onSeek(positionMs: number): void; - onDurationChange(durationMs: number): void; - onEnded(): void; - onExtraControls(controls: PlayerExtraControl[]): void; -} - -export type EmbedEvent = - // `duration` piggybacks on time events for players (Vimeo, player.js, DM, - // VK) that bundle it into their timeupdate payload. - | { kind: 'time'; seconds: number; duration?: number } - | { kind: 'duration'; seconds: number } - | { kind: 'play' } - | { kind: 'pause' } - | { kind: 'ended' } - | { kind: 'extraList'; control: PlayerExtraControl } - | { kind: 'extraCurrent'; id: string; value: string } - // Recognized the protocol but the event carries no state we track; enough - // to lock detection. - | { kind: 'hello' }; - -export interface ProtocolDef { - name: string; - // Hostname-based selection: when a URL matches, only this protocol is - // probed (skips content-based detection). Left undefined for generic - // protocols detected purely by the messages they emit (kodik, player.js). - matchUrl?(url: string): boolean; - // Inject opt-in query params the player needs before the iframe loads - // (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`). - prepareUrl?(url: string): string; - // Some players (Kodik) expose no postMessage command API — the only way to - // seek is to reload the iframe at a start offset. When present, the adapter - // seeks by setting frame.src to this URL instead of posting a command. - reloadSeek?(currentSrc: string, seconds: number): string; - probe(win: Window): void; - parse(data: unknown): EmbedEvent | null; - play(win: Window): void; - pause(win: Window): void; - seek(win: Window, seconds: number): void; - volume(win: Window, v01: number): void; - probeExtras?(win: Window): void; - setExtra?(win: Window, id: string, value: string): void; - staticExtras?(url: string): PlayerExtraControl[]; -} - -// Embeds are served from many mirror domains (esp. Kodik), so the target -// origin can't be pinned; we never trust incoming data beyond parsing known -// shapes into numbers. -function post(win: Window, msg: unknown) { - try { - win.postMessage(msg, '*'); - } catch { - /* frame navigating/gone */ - } -} - -const asNumber = (v: unknown): number => - typeof v === 'number' ? v : Number(v); - -// Embed URLs are absolute, so no base is needed; guard `location` so the -// helpers also work under the node test runner. -const baseHref = (): string | undefined => - typeof location !== 'undefined' ? location.href : undefined; - -function hostOf(url: string): string { - try { - return new URL(url, baseHref()).hostname.toLowerCase(); - } catch { - return ''; - } -} - -function isHostOrSubdomain(host: string, domain: string): boolean { - return host === domain || host.endsWith(`.${domain}`); -} - -function withParams(url: string, params: Record): string { - try { - const u = new URL(url, baseHref()); - for (const [k, v] of Object.entries(params)) { - if (!u.searchParams.has(k)) u.searchParams.set(k, v); - } - return u.toString(); - } catch { - return url; - } -} - -// Overwrite a single query param (preserves the rest, incl. Kodik's signed -// d_sign/ref_sign params). -function setParam(url: string, key: string, value: string): string { - try { - const u = new URL(url, baseHref()); - u.searchParams.set(key, value); - return u.toString(); - } catch { - return url; - } -} - -// Normalize an object-or-JSON-string payload into a plain object, or null. -function asObj(data: unknown): Record | null { - let obj: unknown = data; - if (typeof data === 'string') { - const s = data.trim(); - if (!s.startsWith('{') && !s.startsWith('[')) return null; - try { - obj = JSON.parse(s); - } catch { - return null; - } - } - return obj && typeof obj === 'object' - ? (obj as Record) - : null; -} - -function toOptions(value: unknown): ExtraControlOption[] { - const entries = Array.isArray(value) - ? value.map((item, index) => [String(index), item] as const) - : value && typeof value === 'object' - ? Object.entries(value as Record) - : []; - return entries.flatMap(([fallback, item]) => { - if (item && typeof item === 'object') { - const option = item as Record; - const raw = option.value ?? option.id ?? option.index ?? fallback; - const label = option.label ?? option.name ?? option.title ?? raw; - return [{ value: String(raw), label: String(label) }]; - } - return item == null - ? [] - : [{ value: fallback, label: String(item) }]; - }); -} - -function extraControl( - id: string, - label: string, - scope: PlayerExtraControl['scope'], - options: ExtraControlOption[], - current: string | null = null -): PlayerExtraControl { - return { id, label, scope, options, current, kind: 'select' }; -} - -const kodik: ProtocolDef = { - name: 'kodik', - // Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always - // locks as `kodik` and never falls back to view-only. - matchUrl: (url) => { - const host = hostOf(url); - return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com'] - .some((domain) => isHostOrSubdomain(host, domain)); - }, - // Kodik has NO postMessage command API — the only way to seek is to reload - // the iframe at a start offset (preserving its signed params). start_from - // auto-resumes playback from that second. - reloadSeek: (src, seconds) => - setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))), - probe(win) { - // Community-documented; harmless if ignored by the player. - post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } }); - post(win, { key: 'kodik_player_api', value: { method: 'get_time' } }); - }, - parse(data) { - let obj: unknown = data; - if (typeof data === 'string') { - if (!data.includes('kodik_player')) return null; - try { - obj = JSON.parse(data); - } catch { - return null; - } - } - const m = obj as { key?: unknown; value?: unknown } | null; - if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) { - return null; - } - const n = asNumber(m.value); - switch (m.key) { - case 'kodik_player_time_update': - case 'kodik_player_current_time': - return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' }; - case 'kodik_player_duration_update': - case 'kodik_player_duration': - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - case 'kodik_player_play': - return { kind: 'play' }; - case 'kodik_player_pause': - return { kind: 'pause' }; - case 'kodik_player_video_ended': - return { kind: 'ended' }; - default: - // Unmapped kodik_player_* event — still unambiguously Kodik. - return { kind: 'hello' }; - } - }, - play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }), - pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }), - seek: (win, seconds) => - post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }), - volume: (win, v01) => - post(win, { - key: 'kodik_player_api', - value: { method: 'change_volume', volume: v01 }, - }), -}; - -const playerjs: ProtocolDef = { - name: 'playerjs', - probe(win) { - post(win, { api: 'duration' }); - post(win, { api: 'time' }); - }, - probeExtras(win) { - for (const api of ['qualities', 'audiotracks', 'subtitles']) { - post(win, { api }); - } - }, - staticExtras() { - return [ - extraControl( - 'speed', - 'Speed', - 'synced', - [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({ - value: String(speed), - label: `${speed}×`, - })), - '1' - ), - ]; - }, - parse(data) { - let obj: unknown = data; - if (typeof data === 'string') { - if (!data.startsWith('{')) return null; - try { - obj = JSON.parse(data); - } catch { - return null; - } - } - const m = obj as - | { event?: unknown; answer?: unknown; context?: unknown } - | null; - if (!m || typeof m.event !== 'string') return null; - // A {context:'player.js'} message belongs to the embedly spec adapter, - // not this one. - if (m.context === 'player.js') return null; - const n = asNumber(m.answer); - // Only lock on events Playerjs actually emits — a bare {event:...} - // could belong to some other player's protocol. - switch (m.event) { - case 'qualities': - return { - kind: 'extraList', - control: extraControl( - 'quality', - 'Quality', - 'local', - toOptions(m.answer) - ), - }; - case 'audiotracks': - return { - kind: 'extraList', - control: extraControl( - 'audiotrack', - 'Voiceover', - 'synced', - toOptions(m.answer) - ), - }; - case 'subtitles': - return { - kind: 'extraList', - control: extraControl( - 'subtitle', - 'Subtitles', - 'local', - [ - { value: '-1', label: 'Off' }, - ...toOptions(m.answer), - ] - ), - }; - case 'episodes': - return { - kind: 'extraList', - control: extraControl( - 'episode', - 'Episode', - 'synced', - toOptions(m.answer) - ), - }; - case 'quality': - case 'audiotrack': - case 'subtitle': - case 'speed': - case 'episode': - return { - kind: 'extraCurrent', - id: m.event, - value: String(m.answer ?? ''), - }; - case 'time': - case 'updatetime': - return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' }; - case 'duration': - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - case 'play': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'end': - case 'ended': - return { kind: 'ended' }; - case 'init': - case 'inited': - case 'ready': - case 'volume': - return { kind: 'hello' }; - default: - return null; - } - }, - play: (win) => post(win, { api: 'play' }), - pause: (win) => post(win, { api: 'pause' }), - seek: (win, seconds) => post(win, { api: 'seek', set: seconds }), - volume: (win, v01) => post(win, { api: 'volume', set: v01 }), - setExtra: (win, id, value) => { - if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) { - return; - } - post(win, { api: id, set: value }); - }, -}; - -const alloha: ProtocolDef = { - ...playerjs, - name: 'alloha', - matchUrl: (url) => - ['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some( - (domain) => isHostOrSubdomain(hostOf(url), domain) - ), -}; - -// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated -// from playerjs.com by carrying `data`, not `answer`. -const vimeo: ProtocolDef = { - name: 'vimeo', - matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)), - // Our overlay bar is the only control surface, so hide Vimeo's native chrome. - prepareUrl: (url) => - withParams(url, { - controls: '0', - title: '0', - byline: '0', - portrait: '0', - }), - probe(win) { - for (const ev of ['timeupdate', 'play', 'pause', 'ended']) { - post(win, JSON.stringify({ method: 'addEventListener', value: ev })); - } - post(win, JSON.stringify({ method: 'getDuration' })); - }, - probeExtras(win) { - post(win, JSON.stringify({ method: 'getQualities' })); - }, - parse(data) { - const m = asObj(data); - if (!m) return null; - if (m.method === 'getDuration') { - const n = asNumber(m.value); - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - } - if (m.method === 'getQualities') { - return { - kind: 'extraList', - control: extraControl( - 'quality', - 'Quality', - 'local', - toOptions(m.value) - ), - }; - } - if (typeof m.event !== 'string') return null; - if ('answer' in m) return null; // that's a playerjs.com message - const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown }; - switch (m.event) { - case 'timeupdate': { - const sec = asNumber(d.seconds); - const dur = asNumber(d.duration); - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - } - case 'play': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'ended': - case 'finish': - return { kind: 'ended' }; - case 'ready': - case 'loaded': - return { kind: 'hello' }; - default: - return null; // bare {event} without vimeo markers → not ours - } - }, - play: (w) => post(w, JSON.stringify({ method: 'play' })), - pause: (w) => post(w, JSON.stringify({ method: 'pause' })), - seek: (w, s) => - post(w, JSON.stringify({ method: 'setCurrentTime', value: s })), - volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })), - setExtra: (w, id, value) => { - if (id === 'quality') { - post(w, JSON.stringify({ method: 'setQuality', value })); - } - }, -}; - -// embedly player.js SPEC (github.com/embedly/player.js): the `context` field -// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc. -const PJS = { context: 'player.js', version: '0.0.11' } as const; -const playerjsSpec: ProtocolDef = { - name: 'player.js', - probe(win) { - for (const ev of ['timeupdate', 'play', 'pause', 'ended']) { - post(win, { - ...PJS, - method: 'addEventListener', - listener: `ec_${ev}`, - value: ev, - }); - } - }, - parse(data) { - const m = asObj(data); - if (!m || m.context !== 'player.js' || typeof m.event !== 'string') { - return null; - } - const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown }; - switch (m.event) { - case 'timeupdate': { - const sec = asNumber(v.seconds); - const dur = asNumber(v.duration); - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - } - case 'play': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'ended': - return { kind: 'ended' }; - default: - return { kind: 'hello' }; // any context:'player.js' event is ours - } - }, - play: (w) => post(w, { ...PJS, method: 'play' }), - pause: (w) => post(w, { ...PJS, method: 'pause' }), - seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }), - volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }), -}; - -// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed. -const rutube: ProtocolDef = { - name: 'rutube', - matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)), - probe(win) { - // Rutube emits events only after an explicit subscribe. VERIFY payload. - post(win, JSON.stringify({ type: 'player:subscribe', data: {} })); - }, - parse(data) { - const m = asObj(data); - if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) { - return null; - } - const d = (m.data ?? {}) as { - time?: unknown; - duration?: unknown; - state?: unknown; - }; - switch (m.type) { - case 'player:currentTime': { - const n = asNumber(d.time); - return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' }; - } - case 'player:durationChange': { - const n = asNumber(d.duration); - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - } - case 'player:changeState': { - const st = String(d.state); - if (st === 'playing') return { kind: 'play' }; - if (st === 'paused' || st === 'stopped') return { kind: 'pause' }; - if (st === 'ended') return { kind: 'ended' }; - return { kind: 'hello' }; - } - default: - return { kind: 'hello' }; // player:* is unambiguously Rutube - } - }, - play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })), - pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })), - seek: (w, s) => - post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })), - volume: (w, v) => - post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })), -}; - -// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY; -// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed. -const dailymotion: ProtocolDef = { - name: 'dailymotion', - matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)), - // api=postMessage enables control; controls=0 + ui-* hide the native chrome - // (our overlay bar drives playback instead). - prepareUrl: (url) => - withParams(url, { - api: 'postMessage', - controls: '0', - 'ui-start-screen-info': 'false', - 'ui-logo': 'false', - }), - probe() { - /* classic embed auto-emits once api=postMessage is set */ - }, - parse(data) { - if (typeof data !== 'string' || !data.includes('event=')) return null; - const p = new URLSearchParams(data); - const ev = p.get('event'); - if (!ev) return null; - const sec = Number(p.get('time')); - const dur = Number(p.get('duration')); - switch (ev) { - case 'timeupdate': - case 'progress': - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - case 'durationchange': - return isFinite(dur) && dur > 0 - ? { kind: 'duration', seconds: dur } - : { kind: 'hello' }; - case 'play': - case 'playing': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'video_end': - case 'ended': - return { kind: 'ended' }; - default: - return { kind: 'hello' }; - } - }, - play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })), - pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })), - seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })), - volume: (w, v) => - post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })), -}; - -// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes. -const vk: ProtocolDef = { - name: 'vk', - matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)), - prepareUrl: (url) => withParams(url, { js_api: '1' }), - probe(win) { - post(win, JSON.stringify({ method: 'addEventListener', event: '*' })); - }, - parse(data) { - const m = asObj(data); - if (!m || m.type !== 'player_api' || typeof m.event !== 'string') { - return null; - } - const sec = asNumber(m.time ?? m.position); - const dur = asNumber(m.duration); - switch (m.event) { - case 'timeupdate': - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - case 'started': - case 'resumed': - return { kind: 'play' }; - case 'paused': - return { kind: 'pause' }; - case 'ended': - return { kind: 'ended' }; - default: - return { kind: 'hello' }; // type:'player_api' is unambiguously VK - } - }, - play: (w) => post(w, JSON.stringify({ method: 'play' })), - pause: (w) => post(w, JSON.stringify({ method: 'pause' })), - seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })), - volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })), -}; - -// Hostname-selected protocols first (they're picked by URL, never by content); -// then the generic set probed by the messages they emit — kodik first (its -// keys are unambiguous), the embedly spec before the looser playerjs.com. -// Exported for the parse unit tests. -export const EMBED_PROTOCOLS: ProtocolDef[] = [ - kodik, - alloha, - vimeo, - rutube, - dailymotion, - vk, - playerjsSpec, - playerjs, -]; - -// Inject any opt-in params a hostname-matched player needs, before iframe.src. -export function prepareEmbedUrl(url: string): string { - const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url)); - // Signed players such as Kodik depend on their own origin for scripts, - // AJAX, cookies and anti-abuse checks. Keep them on the provider origin; - // Echoion controls them only through their postMessage surface. - return p?.prepareUrl ? p.prepareUrl(url) : url; -} - -const PROBE_INTERVAL_MS = 750; -// Commands are echoed back as events by the player; ignore relay callbacks -// for this long after each command we send. -const SUPPRESS_MS = 800; -// A time event this far off the extrapolated position counts as a user seek. -const SEEK_JUMP_SEC = 2.5; -// Minimum gap between reload-based (Kodik) iframe reloads. -const RELOAD_DEBOUNCE_MS = 4000; - -export function detectEmbedAdapter( - frame: HTMLIFrameElement, - cb: EmbedCallbacks, - timeoutMs = 5000 -): Promise { - return new Promise((resolve) => { - let locked: ProtocolDef | null = null; - - // A hostname-matched player is probed alone; otherwise probe the - // generic (content-detected) set. frame.src is the prepared URL. - const matched = - EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null; - const probeSet = matched - ? [matched] - : EMBED_PROTOCOLS.filter((p) => !p.matchUrl); - - // Normalized player state. Embeds push time updates rather than expose - // getters, so position is the last event extrapolated by wall clock. - let lastTimeSec = 0; - let lastTimeAt = performance.now(); - let durationSec = 0; - let playing = false; - let suppressUntil = 0; - const extraControls = new Map(); - - const positionMs = () => - Math.floor( - (lastTimeSec + - (playing ? (performance.now() - lastTimeAt) / 1000 : 0)) * - 1000 - ); - const suppressed = () => performance.now() < suppressUntil; - - const applyEvent = (ev: EmbedEvent) => { - switch (ev.kind) { - case 'time': { - const jumped = - Math.abs(ev.seconds - positionMs() / 1000) > - SEEK_JUMP_SEC; - // Advancing time implies playing even when the protocol - // never sends an explicit play event. - const advancing = ev.seconds > lastTimeSec + 0.05; - lastTimeSec = ev.seconds; - lastTimeAt = performance.now(); - // Some protocols bundle duration into the time event. - if ( - ev.duration != null && - Math.abs(ev.duration - durationSec) > 0.5 - ) { - durationSec = ev.duration; - cb.onDurationChange(Math.floor(ev.duration * 1000)); - } - if (jumped && !suppressed()) { - cb.onSeek(Math.floor(ev.seconds * 1000)); - } - if (!playing && advancing) { - playing = true; - if (!suppressed()) cb.onPlay(positionMs()); - } - break; - } - case 'duration': - if (Math.abs(ev.seconds - durationSec) > 0.5) { - durationSec = ev.seconds; - cb.onDurationChange(Math.floor(ev.seconds * 1000)); - } - break; - case 'play': - if (!playing) { - playing = true; - lastTimeAt = performance.now(); - if (!suppressed()) cb.onPlay(positionMs()); - } - break; - case 'pause': - if (playing) { - lastTimeSec = positionMs() / 1000; - playing = false; - if (!suppressed()) cb.onPause(positionMs()); - } - break; - case 'ended': - playing = false; - cb.onEnded(); - break; - case 'extraList': - if (ev.control.options.length > 0) { - extraControls.set(ev.control.id, ev.control); - cb.onExtraControls([...extraControls.values()]); - } - break; - case 'extraCurrent': { - const control = extraControls.get(ev.id); - if (control && control.current !== ev.value) { - extraControls.set(ev.id, { ...control, current: ev.value }); - cb.onExtraControls([...extraControls.values()]); - } - break; - } - case 'hello': - break; - } - }; - - // contentWindow is read live on every use: it changes when the frame - // navigates, while ev.source comparison below stays valid because the - // browsing context object is stable for the life of the element. - const win = () => frame.contentWindow; - - const makeAdapter = (p: ProtocolDef): EmbedAdapter => { - for (const control of p.staticExtras?.(frame.src) ?? []) { - extraControls.set(control.id, control); - } - if (extraControls.size > 0) { - cb.onExtraControls([...extraControls.values()]); - } - const probeExtras = () => { - const current = win(); - if (current) p.probeExtras?.(current); - }; - probeExtras(); - const extraProbeTimers = [1500, 3000].map((delay) => - window.setTimeout(probeExtras, delay) - ); - // Reload-based (Kodik) seeking: replace frame.src at a start offset, - // debounced so drift-reconcile can't spam reloads (each reload - // re-buffers and may replay an ad). - let lastReloadAt = 0; - const reloadTo = (sec: number) => { - const now = performance.now(); - if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return; - lastReloadAt = now; - suppressUntil = now + SUPPRESS_MS; - lastTimeSec = Math.max(0, sec); - lastTimeAt = now; - playing = true; // start_from auto-resumes - frame.src = p.reloadSeek!(frame.src, sec); - }; - return { - protocol: p.name, - reloadBased: !!p.reloadSeek, - play() { - // Commands update state optimistically so positionMs()/paused() - // reflect intent immediately — otherwise the 3s sync heartbeat - // would fight the slow embed acknowledgement. - suppressUntil = performance.now() + SUPPRESS_MS; - playing = true; - lastTimeAt = performance.now(); - if (p.reloadSeek) { - // No play command — resume by reloading at the current spot. - reloadTo(lastTimeSec); - return; - } - const w = win(); - if (w) p.play(w); - }, - pause() { - suppressUntil = performance.now() + SUPPRESS_MS; - lastTimeSec = positionMs() / 1000; - playing = false; - // Reload-based players (Kodik) have no pause — best-effort no-op. - if (p.reloadSeek) return; - const w = win(); - if (w) p.pause(w); - }, - seekMs(ms: number) { - if (p.reloadSeek) { - reloadTo(ms / 1000); - return; - } - suppressUntil = performance.now() + SUPPRESS_MS; - lastTimeSec = ms / 1000; - lastTimeAt = performance.now(); - const w = win(); - if (w) p.seek(w, ms / 1000); - }, - setVolume(v01: number) { - const w = win(); - if (w) p.volume(w, Math.max(0, Math.min(1, v01))); - }, - extras: () => [...extraControls.values()], - setExtra(id, value) { - const control = extraControls.get(id); - if (!control || !p.setExtra) return; - suppressUntil = performance.now() + 1500; - extraControls.set(id, { ...control, current: value }); - cb.onExtraControls([...extraControls.values()]); - const current = win(); - if (current) p.setExtra(current, id, value); - }, - positionMs, - durationMs: () => Math.floor(durationSec * 1000), - paused: () => !playing, - destroy() { - window.removeEventListener('message', handler); - clearInterval(probeTimer); - clearTimeout(giveUp); - for (const timer of extraProbeTimers) clearTimeout(timer); - }, - }; - }; - - const handler = (ev: MessageEvent) => { - if (ev.source !== frame.contentWindow) return; - if (locked) { - const e = locked.parse(ev.data); - if (e) applyEvent(e); - else if (import.meta.env.DEV) { - console.debug('[embed] unrecognized message', ev.data); - } - return; - } - for (const p of probeSet) { - const e = p.parse(ev.data); - if (e) { - locked = p; - clearInterval(probeTimer); - clearTimeout(giveUp); - applyEvent(e); - resolve(makeAdapter(p)); - return; - } - } - if (import.meta.env.DEV) { - console.debug('[embed] unrecognized message', ev.data); - } - }; - window.addEventListener('message', handler); - - const sendProbes = () => { - const w = win(); - if (!w || locked) return; - for (const p of probeSet) p.probe(w); - }; - // The inner player may boot slowly; keep probing until lock or timeout. - const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS); - frame.addEventListener('load', sendProbes); - sendProbes(); - - const giveUp = setTimeout(() => { - if (locked) return; - window.removeEventListener('message', handler); - clearInterval(probeTimer); - resolve(null); - }, timeoutMs); - }); -} diff --git a/EchoionWeb/frontend/src/lib/emoji.ts b/EchoionWeb/frontend/src/lib/emoji.ts deleted file mode 100644 index 16ba575..0000000 --- a/EchoionWeb/frontend/src/lib/emoji.ts +++ /dev/null @@ -1,96 +0,0 @@ -// Emoji support for watch chat and reactions (item 16). A curated Unicode set -// across categories (dependency-free — no multi-MB emoji-data bundle), plus -// admin-managed custom image emojis served at /emoji/ and referenced by -// :name: shortcodes. Recently-used emoji are remembered locally. - -import { Store } from './store'; -import { rpc } from './rpc'; - -export interface CustomEmoji { - name: string; - mime: string; -} - -export const emojiStore = new Store<{ - custom: CustomEmoji[]; - recent: string[]; // unicode chars or :shortcode: -}>({ - custom: [], - recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'), -}); - -export async function loadCustomEmojis() { - try { - const res = await rpc.call<{ emojis?: CustomEmoji[] }>( - 'GetCustomEmojis' - ); - emojiStore.set({ custom: (res && res.emojis) || [] }); - } catch { - /* not connected / not authed — leave empty */ - } -} - -export function rememberEmoji(token: string) { - const recent = [ - token, - ...emojiStore.get().recent.filter((r) => r !== token), - ].slice(0, 24); - emojiStore.set({ recent }); - localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent)); -} - -// Curated categories of common Unicode emoji. -export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [ - { - label: 'Smileys', - emoji: [ - '😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰', - '😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞', - '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', - '😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒', - ], - }, - { - label: 'Gestures', - emoji: [ - '👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌', - '👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝', - ], - }, - { - label: 'Hearts', - emoji: [ - '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️', - '💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥', - ], - }, - { - label: 'Fun', - emoji: [ - '🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸', - '⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️', - ], - }, -]; - -// Render a chat message: plain text with :name: custom-emoji shortcodes -// replaced by tags. Returns React nodes (text is auto-escaped by React). -export function renderChatText(text: string): (string | EmojiToken)[] { - const out: (string | EmojiToken)[] = []; - const re = /:([a-z0-9_]{1,32}):/g; - const custom = new Set(emojiStore.get().custom.map((c) => c.name)); - let last = 0; - let m: RegExpExecArray | null; - while ((m = re.exec(text)) !== null) { - if (!custom.has(m[1])) continue; - if (m.index > last) out.push(text.slice(last, m.index)); - out.push({ emojiName: m[1] }); - last = m.index + m[0].length; - } - if (last < text.length) out.push(text.slice(last)); - return out; -} - -export interface EmojiToken { - emojiName: string; -} diff --git a/EchoionWeb/frontend/src/lib/router.test.ts b/EchoionWeb/frontend/src/lib/router.test.ts new file mode 100644 index 0000000..8c591e4 --- /dev/null +++ b/EchoionWeb/frontend/src/lib/router.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { viewFromHash } from './router'; + +describe('dashboard routing', () => { + it('uses dashboard as the default and redirects the retired now view', () => { + expect(viewFromHash('')).toBe('dashboard'); + expect(viewFromHash('#now')).toBe('dashboard'); + expect(viewFromHash('#dashboard')).toBe('dashboard'); + }); + + it('keeps the remaining flat views bookmarkable', () => { + expect(viewFromHash('#queue')).toBe('queue'); + expect(viewFromHash('#server')).toBe('server'); + }); +}); diff --git a/EchoionWeb/frontend/src/lib/router.ts b/EchoionWeb/frontend/src/lib/router.ts index 96b5208..2dae435 100644 --- a/EchoionWeb/frontend/src/lib/router.ts +++ b/EchoionWeb/frontend/src/lib/router.ts @@ -1,51 +1,40 @@ // Tiny hash router: keeps the active view in the URL so views are // bookmarkable and the browser back/forward buttons work. No dependency — -// the app has a single flat set of views. The Watch view owns its own -// `#watch/` hash (see watch.ts joinRoom/leaveRoom); this router only -// reads the room from it to auto-join a deep-linked room. +// the app has a single flat set of views. import { appStore, type ViewName } from './app'; -import { joinRoom, watchStore } from './watch'; const VIEWS: readonly ViewName[] = [ - 'now', + 'dashboard', 'queue', 'search', 'library', 'stats', - 'rooms', - 'watch', 'server', 'rpc', ]; -// The view named by the current hash, defaulting to `now`. Handles both -// `#queue` and the watch form `#watch/`. -export function viewFromHash(): ViewName { - const raw = location.hash.replace(/^#\/?/, ''); +// The view named by the current hash, defaulting to `dashboard`. Old `#now` +// bookmarks are intentionally canonicalized during router initialization. +export function viewFromHash(hash = location.hash): ViewName { + const raw = hash.replace(/^#\/?/, ''); const base = raw.split(/[/?]/)[0]; + if (base === 'now') return 'dashboard'; return (VIEWS as readonly string[]).includes(base) ? (base as ViewName) - : 'now'; -} - -function roomFromHash(): string | null { - const m = location.hash.match(/^#watch\/([\w-]{1,48})/); - return m ? m[1] : null; + : 'dashboard'; } export function initRouter() { // Initial view comes from the hash (refresh / shared link). - appStore.set({ view: viewFromHash() }); + const initial = viewFromHash(); + appStore.set({ view: initial }); + if (location.hash.replace(/^#\/?/, '').split(/[/?]/)[0] === 'now') { + history.replaceState(null, '', '#dashboard'); + } window.addEventListener('hashchange', () => { const view = viewFromHash(); appStore.set({ view }); - // Auto-join a room that appears in the hash (pasted link, or - // back/forward onto a different room). Leaving is always explicit. - if (view === 'watch') { - const room = roomFromHash(); - if (room && room !== watchStore.get().room) joinRoom(room); - } }); } diff --git a/EchoionWeb/frontend/src/lib/rpc.ts b/EchoionWeb/frontend/src/lib/rpc.ts index 284cf4a..191a5b6 100644 --- a/EchoionWeb/frontend/src/lib/rpc.ts +++ b/EchoionWeb/frontend/src/lib/rpc.ts @@ -62,23 +62,25 @@ export type RpcMethodName = | 'GetAuditLog' | 'GetUserPrefs' | 'SetUserPrefs' - | 'GetCustomEmojis' - | 'AddCustomEmoji' - | 'RemoveCustomEmoji' - | 'ListListeningRooms' - | 'CreateListeningRoom' - | 'DeleteListeningRoom' - | 'JoinListeningRoom' - | 'LeaveListeningRoom' - | 'PlayInListeningRoom' - | 'PauseListeningRoom' - | 'ResumeListeningRoom' - | 'StopListeningRoom' - | 'GetListeningRoomQueue' - | 'SkipListeningRoom' - | 'RemoveFromListeningRoomQueue' - | 'MoveInListeningRoomQueue' - | 'ClearListeningRoomQueue'; + | 'GetCapabilities' + | 'GetPluginExtensions' + | 'PluginCall' + | 'GetTeamSpeakDirectory' + | 'MoveTeamSpeakClient' + | 'KickTeamSpeakClient' + | 'BanTeamSpeakClient' + | 'GetTeamSpeakBans' + | 'UnbanTeamSpeakClient' + | 'CreateTeamSpeakChannel' + | 'EditTeamSpeakChannel' + | 'ReorderTeamSpeakChannel' + | 'DeleteTeamSpeakChannel' + | 'GetTeamSpeakServerGroups' + | 'AddTeamSpeakServerGroupMember' + | 'RemoveTeamSpeakServerGroupMember' + | 'SendTeamSpeakPrivateMessage' + | 'SendTeamSpeakChannelMessage' + | 'SendTeamSpeakServerMessage'; type Pending = { diff --git a/EchoionWeb/frontend/src/lib/types.ts b/EchoionWeb/frontend/src/lib/types.ts index 3c5b4e6..f8ef1a9 100644 --- a/EchoionWeb/frontend/src/lib/types.ts +++ b/EchoionWeb/frontend/src/lib/types.ts @@ -12,6 +12,48 @@ export interface Track { source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex } +export interface PublicDashboardClient { + nickname: string; + talking: boolean; + muted: boolean; + deafened: boolean; + away: boolean; +} + +export interface PublicDashboardChannel { + id: number; + name: string; + parentId: number | null; + order: number; + default: boolean; + permanent: boolean; + semiPermanent: boolean; + password: boolean; + maxClients: number; + currentClients: number; + clients: PublicDashboardClient[]; + channels: PublicDashboardChannel[]; +} + +export interface PublicDashboard { + server: { + name: string; + connected: boolean; + clientCount: number; + maxClients: number; + channelCount: number; + revision: number; + }; + channels: PublicDashboardChannel[]; + playback: { + isPlaying: boolean; + isPaused: boolean; + positionMs: number; + volume: number; + track: (Track & { durationMs?: number; album?: string }) | null; + }; +} + export interface QueueEntry { queueId: number; track: Track; @@ -19,21 +61,6 @@ export interface QueueEntry { addedBy?: string; } -export interface ListeningRoom { - name: string; - ownerId: number; - members: number[]; - isPlaying: boolean; - isPaused: boolean; - queueSize: number; - isOwner: boolean; -} - -export interface ListeningRoomList { - rooms: ListeningRoom[]; - currentRoom?: string; -} - export interface Status { isPlaying?: boolean; isPaused?: boolean; diff --git a/EchoionWeb/frontend/src/lib/useControlsAutoHide.ts b/EchoionWeb/frontend/src/lib/useControlsAutoHide.ts deleted file mode 100644 index b131790..0000000 --- a/EchoionWeb/frontend/src/lib/useControlsAutoHide.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { useEffect, useState, type RefObject } from 'react'; - -// Auto-hides the Watch player's overlay controls (and the mouse cursor) after -// `idleMs` of no input while a video is PLAYING, and reveals them instantly on -// any input — like a regular video player, in both windowed and fullscreen. -// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is -// open) is left to CSS (:hover / :focus-within); this hook only owns the idle -// timeout and the "always visible while paused" rule. Returns the hidden flag. -export function useControlsAutoHide( - shellRef: RefObject, - opts: { playing: boolean; enabled?: boolean; idleMs?: number } -): boolean { - const { playing, enabled = true, idleMs = 3000 } = opts; - const [hidden, setHidden] = useState(false); - - useEffect(() => { - const shell = shellRef.current; - // Paused, disabled, or no element: always show, no timer. - if (!shell || !enabled || !playing) { - setHidden(false); - return; - } - let timer: number | undefined; - const arm = () => { - if (timer) window.clearTimeout(timer); - timer = window.setTimeout(() => setHidden(true), idleMs); - }; - const reveal = () => { - setHidden(false); // React bails when already false → no churn - arm(); - }; - const events = [ - 'mousemove', - 'pointerdown', - 'touchstart', - 'keydown', - 'focusin', - ] as const; - for (const e of events) { - shell.addEventListener(e, reveal, { passive: true }); - } - // Entering/leaving fullscreen counts as activity. - document.addEventListener('fullscreenchange', reveal); - arm(); - return () => { - if (timer) window.clearTimeout(timer); - for (const e of events) shell.removeEventListener(e, reveal); - document.removeEventListener('fullscreenchange', reveal); - }; - }, [shellRef, playing, enabled, idleMs]); - - return hidden; -} diff --git a/EchoionWeb/frontend/src/lib/watch.ts b/EchoionWeb/frontend/src/lib/watch.ts deleted file mode 100644 index 7deb190..0000000 --- a/EchoionWeb/frontend/src/lib/watch.ts +++ /dev/null @@ -1,1293 +0,0 @@ -// Synchronized watching — an independent feature, unrelated to the music bot. -// TypeScript port of web/watch.js. The server (EchoionWeb /ws) is the timing -// authority for a room; every browser plays the video locally and reconciles -// to the server's position. -// -// Roles: the first authenticated joiner is the host; only the host may -// load/play/pause/seek (the server enforces this and answers watch.denied -// otherwise). Twitch rooms are live: everyone embeds the same channel and -// there is nothing to seek. - -import { Store } from './store'; -import { t } from '../i18n'; -import { - detectEmbedAdapter, - prepareEmbedUrl, - type EmbedAdapter, - type PlayerExtraControl, -} from './embedProtocols'; -import { - loadYouTubeApi, - YOUTUBE_EMBED_HOST, - youtubeEmbedVars, -} from './youtube'; - -export interface WatchQueueItem { - source: string; - url?: string; - videoId?: string; - title?: string; - thumbnailUrl?: string; - addedBy?: string; -} - -export interface RoomSummary { - name: string; - participants: number; - source: string; - videoId?: string; - nowTitle?: string; - hasHost: boolean; -} - -export interface Participant { - id: number; - name: string; - uid?: string; - host?: boolean; - buffering?: boolean; - offsetMs?: number | null; -} - -export interface ChatEntry { - name: string; - text: string; - at: number; // local receipt time -} - -// Watch sources. youtube/twitch use provider iframes; `direct` is a raw -// video/HLS URL played in an HTML5