From 8aa968eb9f449cf9b92f75e3f897fef02a4b7b0e Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 15 Jul 2026 19:50:44 +0300 Subject: [PATCH] Update Signed-off-by: faumaray --- .../standalone/StandaloneClientInterface.hpp | 77 +- src/StandaloneClientInterface.cpp | 1333 ++++++++++------- src/main.cpp | 128 +- 3 files changed, 922 insertions(+), 616 deletions(-) diff --git a/include/echoion/standalone/StandaloneClientInterface.hpp b/include/echoion/standalone/StandaloneClientInterface.hpp index 479f6ea..ec1353c 100644 --- a/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/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/src/StandaloneClientInterface.cpp b/src/StandaloneClientInterface.cpp index d54746a..8a3b809 100644 --- a/src/StandaloneClientInterface.cpp +++ b/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/src/main.cpp b/src/main.cpp index f9603f1..2acb628 100644 --- a/src/main.cpp +++ b/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; } }