From 4a92d09e6315a67140383a334d7ec24ed4fa06d4 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 11 Jul 2026 16:30:05 +0300 Subject: [PATCH] New arch Signed-off-by: faumaray --- CMakeLists.txt | 40 +- include/echoion/standalone/MessageChunker.hpp | 13 + .../standalone/StandaloneClientInterface.hpp | 20 + src/MessageChunker.cpp | 86 +++++ src/StandaloneClientInterface.cpp | 361 ++++++++++++++++-- src/main.cpp | 74 +++- tests/test_message_chunker.cpp | 41 ++ 7 files changed, 571 insertions(+), 64 deletions(-) create mode 100644 include/echoion/standalone/MessageChunker.hpp create mode 100644 src/MessageChunker.cpp create mode 100644 tests/test_message_chunker.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5733ceb..d0d01c9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,9 +1,7 @@ # EchoionStandalone — the daemon that runs Core without a TeamSpeak client. # -# It reuses the plugin's (TeamSpeak-independent) CoreLoader/FileWatcher to load -# and hot-reload Core, but implements IPluginInterface with EchoionProtocol's -# native UDP client. Built with PLUGIN=1 so it shares the plugin's minimal-API -# ABI contract with Core (self-contained ServerConfig, no ConfigTypes). +# It uses the host-common CoreLoader/FileWatcher to load and hot-reload Core, +# and implements IPluginInterface with EchoionProtocol's native UDP client. cmake_minimum_required(VERSION 4.0.0) project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX) @@ -12,41 +10,25 @@ set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -# dylib for the Core hot-reload loader (same version the plugin uses). -CPMAddPackage( - NAME dylib - GITHUB_REPOSITORY martin-olivier/dylib - GIT_TAG "v3.0.1" -) - find_package(PkgConfig REQUIRED) pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil) pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) find_package(Threads REQUIRED) -set(PLUGIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../EchoionPlugin") - add_executable(EchoionStandalone src/main.cpp src/StandaloneClientInterface.cpp src/AudioEncoder.cpp - # Reused, TeamSpeak-independent loader from the plugin (transition shim; - # a shared EchoionHostCommon lib can extract these later). - "${PLUGIN_DIR}/src/CoreLoader.cpp" - "${PLUGIN_DIR}/src/FileWatcher.cpp" + src/MessageChunker.cpp ) -# PLUGIN=1 gives the self-contained ServerConfig + minimal API, matching the -# ABI Core was built against for the plugin path. -target_compile_definitions(EchoionStandalone PRIVATE PLUGIN=1) - target_include_directories(EchoionStandalone PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include" - "${PLUGIN_DIR}/include" ) target_link_libraries(EchoionStandalone PRIVATE Echoion::Protocol + Echoion::Host Echoion::ApiBase Echoion::ApiPlugin Echoion::ApiOpaque @@ -56,7 +38,6 @@ target_link_libraries(EchoionStandalone PRIVATE Void::Data Void::Log Void::Stacktrace - dylib Threads::Threads PkgConfig::SWRESAMPLE PkgConfig::OPUS @@ -68,3 +49,16 @@ set_target_properties(EchoionStandalone PROPERTIES ) install(TARGETS EchoionStandalone RUNTIME DESTINATION bin) + +if(BUILD_TESTS) + add_executable(echoion_standalone_message_tests + tests/test_message_chunker.cpp + src/MessageChunker.cpp + ) + target_include_directories(echoion_standalone_message_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + ) + target_compile_features(echoion_standalone_message_tests PRIVATE cxx_std_20) + add_test(NAME echoion_standalone_message_tests + COMMAND echoion_standalone_message_tests) +endif() diff --git a/include/echoion/standalone/MessageChunker.hpp b/include/echoion/standalone/MessageChunker.hpp new file mode 100644 index 0000000..4b224b2 --- /dev/null +++ b/include/echoion/standalone/MessageChunker.hpp @@ -0,0 +1,13 @@ +#pragma once + +#include +#include +#include + +namespace Echoion::Standalone +{ + // Split TeamSpeak messages on UTF-8/line boundaries while preserving each + // complete markdown-it `:::details ... :::` container in one message. + [[nodiscard]] std::vector + chunkMessage(const std::string& message, std::size_t limit = 900); +} diff --git a/include/echoion/standalone/StandaloneClientInterface.hpp b/include/echoion/standalone/StandaloneClientInterface.hpp index 8910b06..b22c08a 100644 --- a/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/include/echoion/standalone/StandaloneClientInterface.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #include namespace Echoion::Standalone @@ -28,6 +29,7 @@ namespace Echoion::Standalone // required. struct StandaloneSettings { std::string identityPath; // where to load/persist the TS identity + std::string avatarCachePath; int securityLevel = 8; int opusBitrate = 96000; }; @@ -48,6 +50,15 @@ namespace Echoion::Standalone getClients() override; [[nodiscard]] Api::Result> getClient(uint64_t clientId) override; + [[nodiscard]] Api::Result> + getClientIp(uint64_t clientId) override; + [[nodiscard]] Api::Result> + getClientAvatarPath(uint64_t clientId) override; + [[nodiscard]] Api::Result> + getClientAvatarUrl(uint64_t clientId) override; + [[nodiscard]] Api::Result> + requestClientAvatar(uint64_t clientId, + const std::string& destDir) override; Api::Result moveClient(uint64_t clientId, uint64_t channelId) override; Api::Result kickClient(uint64_t clientId, @@ -96,6 +107,10 @@ namespace Echoion::Standalone void broadcast(const Api::PluginEvent& event); void upsertClientGroup(const Protocol::CommandParams& p, bool emitConnected); + void refreshClient(const Protocol::CommandParams& params); + void loadInitialSnapshot(); + [[nodiscard]] Api::Result + commandResult(const Protocol::CommandResult& result) const; StandaloneSettings settings_; std::unique_ptr identity_; @@ -108,7 +123,12 @@ namespace Echoion::Standalone mutable std::mutex mirrorMutex_; std::map clients_; std::map channels_; + std::map clientIps_; + std::map avatarHashes_; + std::map avatarUrls_; + std::map avatarPaths_; std::vector whisperList_; + std::jthread snapshotThread_; std::mutex cbMutex_; std::vector callbacks_; diff --git a/src/MessageChunker.cpp b/src/MessageChunker.cpp new file mode 100644 index 0000000..00c65cd --- /dev/null +++ b/src/MessageChunker.cpp @@ -0,0 +1,86 @@ +#include "echoion/standalone/MessageChunker.hpp" + +#include + +namespace Echoion::Standalone +{ + std::vector chunkMessage(const std::string& message, + std::size_t limit) + { + if (limit == 0 || message.empty()) { + return message.empty() ? std::vector{} + : std::vector{message}; + } + if (message.size() <= limit) { + return {message}; + } + + const auto isBlank = [](const std::string& value) { + return value.find_first_not_of(" \t\r\n") == std::string::npos; + }; + std::vector chunks; + std::string current; + int detailsDepth = 0; + const auto flush = [&] { + if (!current.empty() && !isBlank(current)) { + chunks.push_back(current); + } + current.clear(); + }; + + std::size_t position = 0; + while (position < message.size()) { + const auto newline = message.find('\n', position); + std::string line = newline == std::string::npos + ? message.substr(position) + : message.substr(position, newline - position + 1); + position = newline == std::string::npos ? message.size() : newline + 1; + + const bool opens = line.starts_with(":::details"); + std::string_view trimmed = line; + while (!trimmed.empty() && + (trimmed.back() == '\n' || trimmed.back() == '\r' || + trimmed.back() == ' ' || trimmed.back() == '\t')) { + trimmed.remove_suffix(1); + } + const bool closes = trimmed == ":::"; + + if (detailsDepth == 0 && !current.empty() && + (opens || current.size() + line.size() > limit)) { + flush(); + } + + // A details block must remain syntactically complete even if it is + // longer than the preferred message limit. Normal lines are split at + // a UTF-8 code-point boundary. + if (detailsDepth == 0 && !opens) { + while (line.size() > limit) { + std::size_t cut = limit; + while (cut > 0 && + (static_cast(line[cut]) & 0xc0) == 0x80) { + --cut; + } + if (cut == 0) { + cut = limit; + } + flush(); + auto piece = line.substr(0, cut); + if (!isBlank(piece)) { + chunks.push_back(std::move(piece)); + } + line.erase(0, cut); + } + } + + current += line; + if (opens) { + ++detailsDepth; + } + if (closes && detailsDepth > 0) { + --detailsDepth; + } + } + flush(); + return chunks; + } +} diff --git a/src/StandaloneClientInterface.cpp b/src/StandaloneClientInterface.cpp index 5104807..8f1598e 100644 --- a/src/StandaloneClientInterface.cpp +++ b/src/StandaloneClientInterface.cpp @@ -1,12 +1,16 @@ #include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/AudioEncoder.hpp" +#include "echoion/standalone/MessageChunker.hpp" #include "echoion/protocol/Command.hpp" #include +#include #include #include +#include +#include namespace Echoion::Standalone { @@ -28,6 +32,26 @@ namespace Echoion::Standalone 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); + } + } + return result; + } + } // namespace StandaloneClientInterface::StandaloneClientInterface( @@ -59,6 +83,12 @@ namespace Echoion::Standalone } if (client_) { client_->forceClose(); + } + if (snapshotThread_.joinable()) { + snapshotThread_.request_stop(); + snapshotThread_.join(); + } + if (client_) { client_.reset(); } encoder_.reset(); @@ -129,15 +159,20 @@ namespace Echoion::Standalone { Protocol::TsClientCallbacks cb; cb.onConnected = [this] { - // Ask the server to reveal all clients so the presence mirror fills. - client_->sendCommand("channelsubscribeall"); - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ConnectionEstablished; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); + if (snapshotThread_.joinable()) { + snapshotThread_.request_stop(); + snapshotThread_.join(); + } + snapshotThread_ = std::jthread([this] { loadInitialSnapshot(); }); }; cb.onDisconnected = [this] { Void::Log::warn(LOG, "Disconnected from server"); + std::lock_guard lock(mirrorMutex_); + clients_.clear(); + channels_.clear(); + clientIps_.clear(); + avatarHashes_.clear(); + avatarUrls_.clear(); }; cb.onError = [](const std::string& msg) { Void::Log::error(LOG, "Protocol error: {}", msg); @@ -151,9 +186,60 @@ namespace Echoion::Standalone cb.onDebug = [](const std::string& msg) { Void::Log::debug(LOG, "{}", msg); }; + cb.onVoice = [this](std::span) { + Api::PluginEvent event; + event.type = Api::PluginEventType::VoiceDataReceived; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + }; client_->setCallbacks(std::move(cb)); } + Api::Result StandaloneClientInterface::commandResult( + const Protocol::CommandResult& result) const + { + if (result.ok()) { + return {}; + } + return Api::fail(Api::ErrorCode::NetworkError, + "TeamSpeak error " + std::to_string(result.errorId) + ": " + + result.errorMessage); + } + + void StandaloneClientInterface::loadInitialSnapshot() + { + if (!client_) { + return; + } + auto clients = client_->requestCommand( + "clientlist -uid -groups -voice -away -times -info -country -ip"); + if (clients.ok()) { + for (const auto& record : clients.records) { + refreshClient(record); + } + } else { + Void::Log::warn(LOG, "Initial client snapshot failed: {}", + clients.errorMessage); + } + auto channels = client_->requestCommand( + "channellist -topic -flags -voice -limits"); + if (channels.ok()) { + onCommand(Protocol::ParsedCommand{.name = "channellist", + .params = channels.records.empty() + ? Protocol::CommandParams{} + : channels.records.front(), + .groups = channels.records}); + } else { + Void::Log::warn(LOG, "Initial channel snapshot failed: {}", + channels.errorMessage); + } + client_->sendCommand("channelsubscribeall"); + Api::PluginEvent event; + event.type = Api::PluginEventType::ConnectionEstablished; + event.timestamp = std::chrono::system_clock::now(); + broadcast(event); + } + Api::Result StandaloneClientInterface::disconnectFromServer() { if (client_) { @@ -187,19 +273,11 @@ namespace Echoion::Standalone { std::lock_guard lock(mirrorMutex_); info = clients_[clid]; - info.id = clid; - if (auto n = get(p, "client_nickname"); !n.empty()) { - info.nickname = n; - } - if (auto u = get(p, "client_unique_identifier"); !u.empty()) { - info.uniqueIdentifier = u; - } - if (auto c = get(p, "ctid"); !c.empty()) { - info.channelId = toU64(c); - } else if (auto cid = get(p, "cid"); !cid.empty()) { - info.channelId = toU64(cid); - } - clients_[clid] = info; + } + refreshClient(p); + { + std::lock_guard lock(mirrorMutex_); + info = clients_[clid]; } if (emitConnected) { Api::PluginEvent ev; @@ -211,6 +289,63 @@ namespace Echoion::Standalone } } + void StandaloneClientInterface::refreshClient( + const Protocol::CommandParams& 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(const Protocol::ParsedCommand& p) { const auto& groups = @@ -218,9 +353,11 @@ namespace Echoion::Standalone ? std::vector{p.params} : p.groups; - if (p.name == "notifycliententerview") { + if (p.name == "notifycliententerview" || p.name == "clientlist" || + p.name == "clientinfo" || p.name == "notifyclientupdated" || + p.name == "notifytalkstatuschange") { for (const auto& g : groups) { - upsertClientGroup(g, true); + upsertClientGroup(g, p.name == "notifycliententerview"); } } else if (p.name == "notifyclientleftview") { for (const auto& g : groups) { @@ -263,7 +400,15 @@ namespace Echoion::Standalone ev.timestamp = std::chrono::system_clock::now(); broadcast(ev); } - } else if (p.name == "channellist" || p.name == "notifychannellist") { + } else if (p.name == "notifychanneldeleted") { + std::lock_guard lock(mirrorMutex_); + for (const auto& group : groups) { + channels_.erase(toU64(get(group, "cid"))); + } + } else if (p.name == "channellist" || p.name == "notifychannellist" || + p.name == "notifychannelcreated" || + p.name == "notifychanneledited" || + p.name == "notifychannelmoved") { std::lock_guard lock(mirrorMutex_); for (const auto& g : groups) { uint64_t cid = toU64(get(g, "cid")); @@ -276,8 +421,17 @@ namespace Echoion::Standalone ch.name = n; } if (auto pid = get(g, "pid"); !pid.empty()) { - ch.parentId = toU64(pid); + 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; } } @@ -339,6 +493,124 @@ namespace Echoion::Standalone return std::optional{it->second}; } + Api::Result> + StandaloneClientInterface::getClientIp(uint64_t clientId) + { + if (!client_ || !isConnected()) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected"); + } + Protocol::CommandParams parameters; + parameters["clid"] = std::to_string(clientId); + auto result = client_->requestCommand( + Protocol::buildCommand("clientconnectioninfo", parameters)); + if (!result.ok()) { + result = client_->requestCommand( + Protocol::buildCommand("clientinfo", parameters)); + } + if (!result.ok()) { + return Api::fail(Api::ErrorCode::NetworkError, result.errorMessage); + } + for (const auto& record : result.records) { + refreshClient(record); + } + std::lock_guard lock(mirrorMutex_); + const auto entry = clientIps_.find(clientId); + return entry == clientIps_.end() + ? std::optional{} + : std::optional{entry->second}; + } + + Api::Result> + StandaloneClientInterface::getClientAvatarPath(uint64_t clientId) + { + std::lock_guard lock(mirrorMutex_); + const auto entry = avatarPaths_.find(clientId); + if (entry == avatarPaths_.end() || + !std::filesystem::exists(entry->second)) { + return std::optional{}; + } + return std::optional{entry->second}; + } + + Api::Result> + StandaloneClientInterface::getClientAvatarUrl(uint64_t clientId) + { + if (client_ && isConnected()) { + Protocol::CommandParams parameters; + parameters["clid"] = std::to_string(clientId); + const auto result = client_->requestCommand( + Protocol::buildCommand("clientinfo", parameters)); + if (result.ok()) { + for (const auto& record : result.records) { + refreshClient(record); + } + } + } + std::lock_guard lock(mirrorMutex_); + const auto entry = avatarUrls_.find(clientId); + return entry == avatarUrls_.end() + ? std::optional{} + : std::optional{entry->second}; + } + + Api::Result> + StandaloneClientInterface::requestClientAvatar(uint64_t clientId, + const std::string& destDir) + { + if (!client_ || !isConnected()) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected"); + } + Protocol::CommandParams parameters; + parameters["clid"] = std::to_string(clientId); + const auto info = + client_->requestCommand(Protocol::buildCommand("clientinfo", parameters)); + if (!info.ok()) { + return Api::fail(Api::ErrorCode::NetworkError, info.errorMessage); + } + for (const auto& record : info.records) { + refreshClient(record); + } + std::string hash; + { + std::lock_guard lock(mirrorMutex_); + if (const auto entry = avatarHashes_.find(clientId); + entry != avatarHashes_.end()) { + hash = entry->second; + } + } + if (hash.empty()) { + return std::optional{}; + } + if (hash.find_first_not_of( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") != + std::string::npos) { + return Api::fail(Api::ErrorCode::ParseError, + "server returned an unsafe avatar hash"); + } + const auto directory = destDir.empty() ? settings_.avatarCachePath : destDir; + std::error_code directoryError; + std::filesystem::create_directories(directory, directoryError); + if (directoryError) { + return Api::fail(Api::ErrorCode::PluginError, + "cannot create avatar cache directory"); + } + const auto destination = + (std::filesystem::path(directory) / ("avatar_" + hash)).string(); + if (!std::filesystem::exists(destination)) { + const auto result = + client_->downloadFile("/avatar_" + hash, destination); + if (!result.ok()) { + return Api::fail(Api::ErrorCode::NetworkError, + result.errorMessage); + } + } + { + std::lock_guard lock(mirrorMutex_); + avatarPaths_[clientId] = destination; + } + return std::optional{destination}; + } + Api::Result> StandaloneClientInterface::getChannels() const { @@ -371,8 +643,8 @@ namespace Echoion::Standalone Protocol::CommandParams p; p["clid"] = std::to_string(clientId); p["cid"] = std::to_string(channelId); - client_->sendCommand(Protocol::buildCommand("clientmove", p)); - return {}; + return commandResult( + client_->requestCommand(Protocol::buildCommand("clientmove", p))); } Api::Result @@ -386,8 +658,8 @@ namespace Echoion::Standalone p["clid"] = std::to_string(clientId); p["reasonid"] = "5"; // kick from server p["reasonmsg"] = reason; - client_->sendCommand(Protocol::buildCommand("clientkick", p)); - return {}; + return commandResult( + client_->requestCommand(Protocol::buildCommand("clientkick", p))); } // ---- Messaging --------------------------------------------------------- @@ -399,11 +671,20 @@ namespace Echoion::Standalone if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - Protocol::CommandParams p; - p["targetmode"] = "1"; // client - p["target"] = std::to_string(targetId); - p["msg"] = message; - client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); + for (const auto& chunk : chunkMessage(message)) { + Protocol::CommandParams p; + p["targetmode"] = "1"; // client + p["target"] = std::to_string(targetId); + p["msg"] = chunk; + if (auto result = commandResult(client_->requestCommand( + Protocol::buildCommand("sendtextmessage", p))); + !result) { + Void::Log::warn(LOG, + "Failed to send help/reply chunk ({} bytes): {}", + chunk.size(), result.error().message); + return result; + } + } return {}; } @@ -418,8 +699,8 @@ namespace Echoion::Standalone p["targetmode"] = "2"; // channel p["target"] = std::to_string(channelId); p["msg"] = message; - client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); - return {}; + return commandResult(client_->requestCommand( + Protocol::buildCommand("sendtextmessage", p))); } Api::Result @@ -431,8 +712,8 @@ namespace Echoion::Standalone Protocol::CommandParams p; p["targetmode"] = "3"; // server p["msg"] = message; - client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); - return {}; + return commandResult(client_->requestCommand( + Protocol::buildCommand("sendtextmessage", p))); } // ---- Audio ------------------------------------------------------------- @@ -442,7 +723,7 @@ namespace Echoion::Standalone { if (!client_ || !encoder_ || client_->state() != Protocol::ClientState::Connected) { - return {}; + return Api::fail(Api::ErrorCode::ServiceUnavailable, "not connected"); } std::vector whisper; { @@ -468,6 +749,12 @@ namespace Echoion::Standalone Api::Result StandaloneClientInterface::setWhisperList( const std::vector& clientIds) { + if (std::ranges::any_of(clientIds, [](uint64_t clientId) { + return clientId > std::numeric_limits::max(); + })) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "whisper client ID exceeds protocol range"); + } std::lock_guard lock(mirrorMutex_); whisperList_ = clientIds; return {}; diff --git a/src/main.cpp b/src/main.cpp index f40cff7..ee96500 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,7 +6,8 @@ // TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no // TeamSpeak client, no Weston/RDP, no plugin directory. -#include "echoion/plugin/CoreLoader.hpp" +#include "echoion/host/CoreLoader.hpp" +#include "echoion/protocol/Identity.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp" #include @@ -22,7 +23,9 @@ #include #include #include +#include #include +#include namespace { @@ -80,6 +83,62 @@ namespace } return "./Echoion.ts"; } + + int importIdentity(int argc, char** argv, + const std::filesystem::path& defaultIdentityPath) + { + std::optional source; + auto destination = defaultIdentityPath; + bool force = false; + bool importRequested = false; + 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"; + return 0; + } + if (argument == "--import-identity") { + importRequested = true; + if (i + 1 < argc && + !std::string_view{argv[i + 1]}.starts_with("--")) { + source = argv[++i]; + } + } else if (argument == "--identity-path" && i + 1 < argc) { + destination = argv[++i]; + } else if (argument == "--force") { + force = true; + } + } + if (!importRequested) { + return -1; + } + if (!source) { + std::cerr << "--import-identity requires an exported INI path.\n"; + return 2; + } + try { + if (std::filesystem::exists(destination) && !force) { + std::cerr << "Identity already exists at " << destination + << "; pass --force to replace it.\n"; + return 2; + } + const auto identity = + Echoion::Protocol::Identity::importTeamSpeakIni(source->string()); + if (const auto parent = destination.parent_path(); !parent.empty()) { + std::filesystem::create_directories(parent); + } + identity.save(destination.string()); + std::cout << "Imported TeamSpeak identity " << identity.uid() + << " to " << destination << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << "Identity import failed: " << error.what() << '\n'; + return 2; + } + } } // namespace int main(int argc, char** argv) @@ -92,6 +151,12 @@ int main(int argc, char** argv) std::filesystem::path cfgDir = configDir(); std::filesystem::path cfgPath = cfgDir / "config.json"; + 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; + } // Optional CLI: --config for (int i = 1; i + 1 < argc; ++i) { if (std::string(argv[i]) == "--config") { @@ -100,8 +165,8 @@ int main(int argc, char** argv) } Echoion::Standalone::StandaloneSettings settings; - settings.identityPath = - envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()); + settings.identityPath = identityPath.string(); + settings.avatarCachePath = (cfgDir / "avatars").string(); settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); @@ -113,7 +178,7 @@ int main(int argc, char** argv) return 1; } - Echoion::Plugin::CoreLoader loader; + Echoion::Host::CoreLoader loader; loader.setConfigPath(cfgPath); auto corePathResolved = corePath(); @@ -137,6 +202,7 @@ int main(int argc, char** argv) loader.setHotReloadCallback([&loader, interface] { if (auto c = loader.getCore()) { c->setPluginInterface(interface); + interface->unregisterEventCallback({}); interface->registerEventCallback( [c](const Echoion::Api::PluginEvent& ev) { std::ignore = c->onPluginEvent(ev); diff --git a/tests/test_message_chunker.cpp b/tests/test_message_chunker.cpp new file mode 100644 index 0000000..c880af1 --- /dev/null +++ b/tests/test_message_chunker.cpp @@ -0,0 +1,41 @@ +#include "echoion/standalone/MessageChunker.hpp" + +#include +#include + +namespace +{ + bool check(bool condition, const char* message) + { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + } + return condition; + } +} + +int main() +{ + using Echoion::Standalone::chunkMessage; + bool passed = true; + + const std::string header = "# Help\n\n> [!TIP] Prefix is `!`\n\n"; + const std::string details = + ":::details ▶ Play — commands\n\n" + std::string(1100, 'x') + + "\n\n`!play` query\n> description\n:::\n\n"; + const auto helpChunks = chunkMessage(header + details, 900); + passed &= check(helpChunks.size() == 2, + "help header and details block should be separate messages"); + passed &= check(helpChunks.size() > 1 && + helpChunks[1] == details.substr(0, details.size() - 1), + "details container must remain complete even above the limit"); + + const std::string utf8Line = std::string(899, 'a') + "я" + "tail"; + const auto utf8Chunks = chunkMessage(utf8Line, 900); + passed &= check(utf8Chunks.size() == 2, + "long ordinary line should be split"); + passed &= check(!utf8Chunks.empty() && utf8Chunks.front().size() == 899, + "UTF-8 sequence should not be split in the middle"); + + return passed ? 0 : 1; +}