diff --git a/SDK_PARITY.md b/SDK_PARITY.md index 5ef4f51..cb4884d 100644 --- a/SDK_PARITY.md +++ b/SDK_PARITY.md @@ -9,15 +9,18 @@ does not reproduce the proprietary C ABI. | Identity generation/import/security level | Implemented | `Identity` | | Connect/disconnect/state/client ID | Implemented | `Client` | | Raw requests and typed responses | Implemented | `Client::request` | -| Client and channel lists | Implemented | `clients`, `channels` | -| Text messaging | Implemented | `sendText` | -| Client move and kick | Implemented | `move`, `kick` | -| Server groups | Implemented | `serverGroups`, add/remove client | +| Client, channel, and server directory | Implemented | rich `clients`, sensitive `clientDetails`, `channels`, `serverInfo` records | +| Channel event subscription | Implemented | `subscribeAllChannels` plus typed callbacks | +| Text messaging | Implemented | `sendText`, plus private/channel/server typed scopes | +| Client move and kick | Implemented | `move`, typed channel/server `kick` | +| Ban administration | Implemented | permanent/timed `ban`, `bans`, `unban` | +| Channel administration | Implemented | `createChannel`, `editChannel`, `reorderChannel`, `deleteChannel` | +| Server groups | Implemented | `serverGroups`, typed membership add/remove | | Voice and whisper transmission | Implemented | `sendVoice`, `sendWhisper` | | Independent voice timelines | Implemented | one `Client` per timeline | | Voice receive callback | Implemented | `Events::voice` | | File download | Implemented | `download` | -| Typed server/channel/client notifications | Implemented | client lifecycle/update/talk, channel, server, group, text, file-transfer events; batched fallback | +| Typed server/channel/client notifications | Implemented | client lifecycle/update/talk, sparse-safe `ChannelPatch`, server, group, text, file-transfer events; batched fallback | | Permissions and channel groups | Implemented | typed lists and channel-group assignment | | File upload/delete | Implemented | `upload`, `deleteFile` | | Audio preprocessing/device GUI | Not applicable | client-local SDK behavior | diff --git a/include/Void/TeamSpeak/Client.hpp b/include/Void/TeamSpeak/Client.hpp index 27093f7..5382b2e 100644 --- a/include/Void/TeamSpeak/Client.hpp +++ b/include/Void/TeamSpeak/Client.hpp @@ -1,8 +1,8 @@ #pragma once #include -#include #include +#include #include #include @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -17,121 +18,169 @@ namespace Void::TeamSpeak { - struct ConnectOptions { - std::string host; - std::uint16_t port{9987}; - std::shared_ptr identity; - std::string nickname{"VoidTeamspeak"}; - std::string serverPassword; - std::string defaultChannel; - std::string channelPassword; - }; - - struct CommandResponse { - using Record = CommandFields; - std::vector records; - }; - - struct CommandEvent { - std::string name; - std::vector records; + struct ConnectOptions { + std::string host; + std::uint16_t port{9987}; + std::shared_ptr identity; + std::string nickname{"VoidTeamspeak"}; + std::string serverPassword; + std::string defaultChannel; + std::string channelPassword; }; - struct Events { - std::function connected; - std::function disconnected; - std::function error; - std::function debug; - std::function&)> command; - std::function commandBatch; - std::function clientEntered; - std::function clientLeft; - std::function clientMoved; - std::function clientUpdated; - std::function talkStatusChanged; - std::function textMessage; - std::function channelChanged; - std::function serverUpdated; - std::function - serverGroupMembershipChanged; - std::function - channelGroupMembershipChanged; - std::function fileTransferStatus; - std::function)> voice; - }; + struct CommandResponse { + using Record = CommandFields; + std::vector records; + }; - class Client final - { - public: - Client(); - ~Client(); - Client(Client&&) noexcept; - Client& operator=(Client&&) noexcept; - Client(const Client&) = delete; - Client& operator=(const Client&) = delete; + struct CommandEvent { + std::string name; + std::vector records; + }; - void setEvents(Events events); - [[nodiscard]] Void::Result::Result - connect(const ConnectOptions& options); - void disconnect() noexcept; - void close() noexcept; - [[nodiscard]] ConnectionState state() const noexcept; - [[nodiscard]] ClientId id() const noexcept; + struct Events { + std::function connected; + std::function disconnected; + std::function error; + std::function debug; + std::function &)> + command; + std::function commandBatch; + std::function clientEntered; + std::function clientLeft; + std::function clientMoved; + std::function clientUpdated; + std::function talkStatusChanged; + std::function textMessage; + std::function channelChanged; + std::function serverUpdated; + std::function + serverGroupMembershipChanged; + std::function + channelGroupMembershipChanged; + std::function fileTransferStatus; + std::function)> voice; + }; - [[nodiscard]] Void::Result::Result - request(std::string_view command, - std::chrono::milliseconds timeout = std::chrono::seconds{3}); - [[nodiscard]] Void::Result::Result, Error> - clients(std::chrono::milliseconds timeout = std::chrono::seconds{3}); - [[nodiscard]] Void::Result::Result, Error> - channels(std::chrono::milliseconds timeout = std::chrono::seconds{3}); - [[nodiscard]] Void::Result::Result, Error> - serverGroups( + class Client final + { + public: + + Client(); + ~Client(); + Client(Client &&) noexcept; + Client &operator=(Client &&) noexcept; + Client(const Client &) = delete; + Client &operator=(const Client &) = delete; + + void setEvents(Events events); + [[nodiscard]] Void::Result::Result + connect(const ConnectOptions &options); + void disconnect() noexcept; + void close() noexcept; + [[nodiscard]] ConnectionState state() const noexcept; + [[nodiscard]] ClientId id() const noexcept; + + [[nodiscard]] Void::Result::Result request( + std::string_view command, std::chrono::milliseconds timeout = std::chrono::seconds{3}); - [[nodiscard]] Void::Result::Result, Error> - channelGroups( + [[nodiscard]] Void::Result::Result, Error> + clients(std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result + clientDetails(ClientId client, + std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result, Error> + channels(std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result + subscribeAllChannels(std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result, Error> + serverGroups(std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result, Error> + channelGroups(std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result, Error> + permissions(std::chrono::milliseconds timeout = + std::chrono::seconds{3}); + [[nodiscard]] Void::Result::Result serverInfo( std::chrono::milliseconds timeout = std::chrono::seconds{3}); - [[nodiscard]] Void::Result::Result, Error> - permissions( + [[nodiscard]] Void::Result::Result, Error> bans( std::chrono::milliseconds timeout = std::chrono::seconds{3}); - [[nodiscard]] Void::Result::Result - addToServerGroup(ServerGroupId group, ClientDatabaseId client); - [[nodiscard]] Void::Result::Result - removeFromServerGroup(ServerGroupId group, ClientDatabaseId client); - [[nodiscard]] Void::Result::Result - setChannelGroup(ChannelGroupId group, ChannelId channel, - ClientDatabaseId client); - [[nodiscard]] Void::Result::Result - sendText(TextTarget target, std::string_view message); - [[nodiscard]] Void::Result::Result - move(ClientId client, ChannelId channel); - [[nodiscard]] Void::Result::Result - kick(ClientId client, std::string_view reason); - [[nodiscard]] Void::Result::Result - download(std::string_view remotePath, - const std::filesystem::path& destination, - ChannelId channel = {}, - std::string_view channelPassword = {}, - std::chrono::milliseconds timeout = std::chrono::seconds{10}); - [[nodiscard]] Void::Result::Result - upload(const std::filesystem::path& source, + [[nodiscard]] Void::Result::Result + ban(ClientId client, const BanOptions &options = {}); + [[nodiscard]] Void::Result::Result unban(BanId ban); + + [[nodiscard]] Void::Result::Result + createChannel(const ChannelCreateOptions &options); + [[nodiscard]] Void::Result::Result + editChannel(ChannelId channel, + const ChannelEditOptions &options); + [[nodiscard]] Void::Result::Result reorderChannel( + ChannelId channel, std::optional parent, + std::optional orderAfter = std::nullopt); + [[nodiscard]] Void::Result::Result + deleteChannel(ChannelId channel, bool force = false); + + [[nodiscard]] Void::Result::Result + addServerGroupMember(ServerGroupId group, + ClientDatabaseId client); + [[nodiscard]] Void::Result::Result + removeServerGroupMember(ServerGroupId group, + ClientDatabaseId client); + // Compatibility names retained for existing consumers. + [[nodiscard]] Void::Result::Result + addToServerGroup(ServerGroupId group, ClientDatabaseId client); + [[nodiscard]] Void::Result::Result + removeFromServerGroup(ServerGroupId group, + ClientDatabaseId client); + [[nodiscard]] Void::Result::Result + setChannelGroup(ChannelGroupId group, ChannelId channel, + ClientDatabaseId client); + [[nodiscard]] Void::Result::Result + sendText(TextTarget target, std::string_view message); + [[nodiscard]] Void::Result::Result + sendPrivateMessage(ClientId client, std::string_view message); + [[nodiscard]] Void::Result::Result + sendChannelMessage(ChannelId channel, std::string_view message); + [[nodiscard]] Void::Result::Result + sendServerMessage(std::string_view message); + [[nodiscard]] Void::Result::Result + move(ClientId client, ChannelId channel); + [[nodiscard]] Void::Result::Result + kick(ClientId client, KickScope scope, std::string_view reason); + [[nodiscard]] Void::Result::Result + kick(ClientId client, std::string_view reason); + [[nodiscard]] Void::Result::Result + download(std::string_view remotePath, + const std::filesystem::path &destination, + ChannelId channel = {}, + std::string_view channelPassword = {}, + std::chrono::milliseconds timeout = + std::chrono::seconds{10}); + [[nodiscard]] Void::Result::Result upload( + const std::filesystem::path &source, std::string_view remotePath, ChannelId channel = {}, std::string_view channelPassword = {}, bool overwrite = false, std::chrono::milliseconds timeout = std::chrono::seconds{10}); - [[nodiscard]] Void::Result::Result - deleteFile(std::string_view remotePath, ChannelId channel = {}, - std::string_view channelPassword = {}); + [[nodiscard]] Void::Result::Result + deleteFile(std::string_view remotePath, ChannelId channel = {}, + std::string_view channelPassword = {}); - [[nodiscard]] Void::Result::Result - sendVoice(std::span opusFrame); - [[nodiscard]] Void::Result::Result - sendWhisper(std::span opusFrame, - const WhisperTargets& targets); - void stopVoice() noexcept; + [[nodiscard]] Void::Result::Result + sendVoice(std::span opusFrame); + [[nodiscard]] Void::Result::Result + sendWhisper(std::span opusFrame, + const WhisperTargets &targets); + void stopVoice() noexcept; - private: - class Impl; - std::unique_ptr impl_; - }; -} + private: + + class Impl; + std::unique_ptr impl_; + }; +} // namespace Void::TeamSpeak diff --git a/include/Void/TeamSpeak/Types.hpp b/include/Void/TeamSpeak/Types.hpp index bea4320..5442b0d 100644 --- a/include/Void/TeamSpeak/Types.hpp +++ b/include/Void/TeamSpeak/Types.hpp @@ -1,160 +1,416 @@ #pragma once +#include +#include #include #include -#include #include +#include #include namespace Void::TeamSpeak { - template - struct Id { - Value value{}; - explicit constexpr operator bool() const noexcept { return value != 0; } - auto operator<=>(const Id&) const = default; - }; + template struct Id { + Value value{}; + explicit constexpr operator bool() const noexcept + { + return value != 0; + } + auto operator<=>(const Id &) const = default; + }; - using ClientId = Id; + using ClientId = Id; using ClientDatabaseId = Id; - using ChannelId = Id; - using ServerConnectionId = Id; + using ChannelId = Id; + using ServerConnectionId = Id; using ServerGroupId = Id; using ChannelGroupId = Id; using PermissionId = Id; + using BanId = Id; - enum class ConnectionState { - Disconnected, - Initializing, - Handshaking, - Connected, - Disconnecting, - }; + enum class ConnectionState { + Disconnected, + Initializing, + Handshaking, + Connected, + Disconnecting, + }; - struct WhisperTargets { - std::vector channels; - std::vector clients; - [[nodiscard]] bool empty() const noexcept - { - return channels.empty() && clients.empty(); - } - }; + struct WhisperTargets { + std::vector channels; + std::vector clients; + [[nodiscard]] bool empty() const noexcept + { + return channels.empty() && clients.empty(); + } + }; struct RemoteClient { - ClientId id; - ChannelId channel; - std::string nickname; - std::string uniqueId; + ClientId id; + ClientDatabaseId databaseId; + ChannelId channel; + std::string nickname; + std::string uniqueId; + std::vector serverGroups; + int type{}; + int talkPower{}; + bool inputMuted{false}; + bool outputMuted{false}; + bool inputHardware{true}; + bool outputHardware{true}; + bool away{false}; + bool talking{false}; + bool recording{false}; + bool channelCommander{false}; + bool prioritySpeaker{false}; + std::string awayMessage; + std::string country; + + [[nodiscard]] bool isQuery() const noexcept { return type != 0; } + [[nodiscard]] bool muted() const noexcept + { + return inputMuted || !inputHardware; + } + [[nodiscard]] bool deafened() const noexcept + { + return outputMuted || !outputHardware; + } + }; + + struct ClientDetails { + RemoteClient client; + // Sensitive connection data is intentionally kept out of + // RemoteClient so directory snapshots cannot expose it + // accidentally. + std::optional connectionIp; + std::optional avatarHash; + std::optional avatarUrl; }; struct ClientLeft { - ClientId id; - int reasonId{}; - std::string reasonMessage; + ClientId id; + int reasonId{}; + std::string reasonMessage; }; struct ClientMoved { - ClientId id; - ChannelId channel; + ClientId id; + ChannelId channel; }; struct ClientUpdated { - ClientId id; - std::optional nickname; - std::optional uniqueId; - std::optional inputMuted; - std::optional outputMuted; - std::optional away; - std::optional recording; - std::map properties; + ClientId id; + std::optional nickname; + std::optional uniqueId; + std::optional inputMuted; + std::optional outputMuted; + std::optional inputHardware; + std::optional outputHardware; + std::optional away; + std::optional talking; + std::optional recording; + std::optional channelCommander; + std::optional prioritySpeaker; + std::optional avatarHash; + std::optional avatarUrl; + std::map properties; }; struct TalkStatusChanged { - ClientId id; - bool talking{false}; - bool whisper{false}; + ClientId id; + bool talking{false}; + bool whisper{false}; }; struct Channel { - ChannelId id; - std::optional parent; - std::string name; - bool passwordProtected{false}; + ChannelId id; + std::optional parent; + ChannelId orderAfter; + std::string name; + std::string topic; + std::string description; + int codec{}; + int codecQuality{}; + int maxClients{}; + int maxFamilyClients{}; + int neededTalkPower{}; + std::uint64_t iconId{}; + bool passwordProtected{false}; + bool permanent{false}; + bool semiPermanent{false}; + bool defaultChannel{false}; + bool unlimitedClients{false}; + bool unlimitedFamilyClients{false}; + }; + + // TeamSpeak channel notifications are sparse: only fields that changed are + // guaranteed to be present. Keeping that distinction in the public type + // prevents an omitted value from resetting a cached channel to its default. + struct ChannelPatch { + // The outer optional means "present in the notification". The + // inner optional is empty when the channel was explicitly moved to + // the root. + std::optional> parent; + std::optional orderAfter; + std::optional name; + std::optional topic; + std::optional description; + std::optional codec; + std::optional codecQuality; + std::optional maxClients; + std::optional maxFamilyClients; + std::optional neededTalkPower; + std::optional iconId; + std::optional passwordProtected; + std::optional permanent; + std::optional semiPermanent; + std::optional defaultChannel; + std::optional unlimitedClients; + std::optional unlimitedFamilyClients; + std::map properties; + + [[nodiscard]] bool empty() const noexcept + { + return !parent && !orderAfter && !name && !topic && + !description && !codec && !codecQuality && !maxClients && + !maxFamilyClients && !neededTalkPower && !iconId && + !passwordProtected && !permanent && !semiPermanent && + !defaultChannel && !unlimitedClients && + !unlimitedFamilyClients; + } + + void applyTo(Channel &channel) const + { + if (parent) { + channel.parent = *parent; + } + if (orderAfter) { + channel.orderAfter = *orderAfter; + } + if (name) { + channel.name = *name; + } + if (topic) { + channel.topic = *topic; + } + if (description) { + channel.description = *description; + } + if (codec) { + channel.codec = *codec; + } + if (codecQuality) { + channel.codecQuality = *codecQuality; + } + if (maxClients) { + channel.maxClients = *maxClients; + } + if (maxFamilyClients) { + channel.maxFamilyClients = *maxFamilyClients; + } + if (neededTalkPower) { + channel.neededTalkPower = *neededTalkPower; + } + if (iconId) { + channel.iconId = *iconId; + } + if (passwordProtected) { + channel.passwordProtected = *passwordProtected; + } + if (permanent) { + channel.permanent = *permanent; + } + if (semiPermanent) { + channel.semiPermanent = *semiPermanent; + } + if (defaultChannel) { + channel.defaultChannel = *defaultChannel; + } + if (unlimitedClients) { + channel.unlimitedClients = *unlimitedClients; + } + if (unlimitedFamilyClients) { + channel.unlimitedFamilyClients = *unlimitedFamilyClients; + } + } + }; + + enum class ChannelLifetime { Temporary, SemiPermanent, Permanent }; + + struct ChannelCreateOptions { + std::string name; + std::optional parent; + std::optional orderAfter; + std::string topic; + std::string description; + std::string password; + std::optional codec; + std::optional codecQuality; + std::optional maxClients; + std::optional maxFamilyClients; + std::optional neededTalkPower; + ChannelLifetime lifetime{ChannelLifetime::Permanent}; + bool defaultChannel{false}; + bool unlimitedClients{false}; + bool unlimitedFamilyClients{false}; + }; + + struct ChannelEditOptions { + std::optional name; + std::optional topic; + std::optional description; + std::optional password; + std::optional codec; + std::optional codecQuality; + std::optional maxClients; + std::optional maxFamilyClients; + std::optional neededTalkPower; + std::optional lifetime; + std::optional defaultChannel; + std::optional unlimitedClients; + std::optional unlimitedFamilyClients; + + [[nodiscard]] bool empty() const noexcept + { + return !name && !topic && !description && !password && !codec && + !codecQuality && !maxClients && !maxFamilyClients && + !neededTalkPower && !lifetime && !defaultChannel && + !unlimitedClients && !unlimitedFamilyClients; + } }; struct ServerGroup { - ServerGroupId id; - std::string name; - int type{}; + ServerGroupId id; + std::string name; + int type{}; + int nameMode{}; + int sortId{}; + int modifyPower{}; + int memberAddPower{}; + int memberRemovePower{}; + std::uint64_t iconId{}; + bool savedToDatabase{false}; }; struct ChannelGroup { - ChannelGroupId id; - std::string name; - int type{}; + ChannelGroupId id; + std::string name; + int type{}; }; struct Permission { - PermissionId id; - std::string name; - std::string description; + PermissionId id; + std::string name; + std::string description; }; + struct ServerInfo { + ServerConnectionId id; + std::string uniqueIdentifier; + std::string name; + std::string welcomeMessage; + std::string platform; + std::string version; + std::string hostMessage; + int hostMessageMode{}; + std::uint64_t uptimeSeconds{}; + std::uint64_t maxClients{}; + std::uint64_t clientCount{}; + std::uint64_t queryClientCount{}; + std::uint64_t channelCount{}; + std::uint64_t reservedSlots{}; + ServerGroupId defaultServerGroup; + ChannelGroupId defaultChannelGroup; + ChannelGroupId defaultChannelAdminGroup; + bool passwordProtected{false}; + }; + + struct Ban { + BanId id; + std::string ip; + std::string name; + std::string uniqueId; + std::string lastNickname; + std::uint64_t createdAtUnixSeconds{}; + std::chrono::seconds duration{}; + ClientDatabaseId invokerDatabaseId; + std::string invokerName; + std::string invokerUniqueId; + std::string reason; + std::uint64_t enforcements{}; + + [[nodiscard]] bool permanent() const noexcept + { + return duration == std::chrono::seconds::zero(); + } + }; + + struct BanOptions { + // No duration means a permanent ban. Timed bans must be positive. + std::optional duration; + std::string reason; + }; + + enum class KickScope { Channel = 4, Server = 5 }; + enum class TextTargetKind { Client = 1, Channel = 2, Server = 3 }; struct TextTarget { - TextTargetKind kind{TextTargetKind::Client}; - std::uint64_t id{}; + TextTargetKind kind{TextTargetKind::Client}; + std::uint64_t id{}; }; struct TextMessage { - TextTarget target; - ClientId invoker; - std::string invokerName; - std::string message; + TextTarget target; + ClientId invoker; + std::string invokerName; + std::string message; }; enum class ChannelChangeKind { Created, Updated, Moved, Deleted }; struct ChannelChanged { - ChannelChangeKind kind{ChannelChangeKind::Updated}; - Channel channel; + ChannelChangeKind kind{ChannelChangeKind::Updated}; + ChannelId id; + ChannelPatch patch; + ClientId invoker; + int reasonId{}; }; struct ServerUpdated { - std::optional name; - std::optional welcomeMessage; - ClientId invoker; - std::map properties; + std::optional name; + std::optional welcomeMessage; + ClientId invoker; + std::map properties; }; struct ServerGroupMembershipChanged { - bool added{false}; - ServerGroupId group; - ClientDatabaseId client; - ClientId invoker; + bool added{false}; + ServerGroupId group; + ClientDatabaseId client; + ClientId invoker; }; struct ChannelGroupMembershipChanged { - ChannelGroupId group; - ChannelId channel; - ClientDatabaseId client; - ClientId invoker; + ChannelGroupId group; + ChannelId channel; + ClientDatabaseId client; + ClientId invoker; }; struct FileTransferStatus { - std::uint64_t id{}; - int status{}; - std::string message; + std::uint64_t id{}; + int status{}; + std::string message; }; - struct Error { - enum class Code { - InvalidArgument, - NotConnected, - Timeout, - Protocol, - Io, - NotSupported, - } code{Code::Protocol}; - std::string message; - }; -} + struct Error { + enum class Code { + InvalidArgument, + NotConnected, + Timeout, + Protocol, + Io, + NotSupported, + } code{Code::Protocol}; + std::string message; + }; +} // namespace Void::TeamSpeak diff --git a/src/Client.cpp b/src/Client.cpp index 0fe9ed2..5d59f50 100644 --- a/src/Client.cpp +++ b/src/Client.cpp @@ -1,494 +1,1327 @@ #include #include +#include "EventParser.hpp" + +#include #include -#include -#include #include #include +#include +#include +#include #include #include namespace Void::TeamSpeak { - std::string buildCommand(std::string_view name, const CommandFields& fields) + std::string buildCommand(std::string_view name, const CommandFields &fields) { - return Void::TeamSpeak::Protocol::buildCommand(std::string{name}, fields); + return Void::TeamSpeak::Protocol::buildCommand(std::string{name}, + fields); } - class Client::Impl { - public: - std::atomic> events{ - std::make_shared()}; - std::atomic callbacksInstalled{false}; - Void::TeamSpeak::Protocol::TsClient client; - }; + class Client::Impl + { + public: - namespace - { - Error protocolError(std::string message) - { - return Error{Error::Code::Protocol, std::move(message)}; - } + std::atomic> events{ + std::make_shared()}; + std::atomic callbacksInstalled{false}; + Void::TeamSpeak::Protocol::TsClient client; + }; + + namespace + { + Error protocolError(std::string message) + { + return Error{Error::Code::Protocol, std::move(message)}; + } + + Error invalidArgument(std::string message) + { + return Error{Error::Code::InvalidArgument, std::move(message)}; + } ConnectionState convert(Void::TeamSpeak::Protocol::ClientState state) - { - using Old = Void::TeamSpeak::Protocol::ClientState; - switch (state) { - case Old::Disconnected: return ConnectionState::Disconnected; - case Old::Init: return ConnectionState::Initializing; - case Old::Handshake: return ConnectionState::Handshaking; - case Old::Connected: return ConnectionState::Connected; - case Old::Disconnecting: return ConnectionState::Disconnecting; + { + using Old = Void::TeamSpeak::Protocol::ClientState; + switch (state) { + case Old::Disconnected: + return ConnectionState::Disconnected; + case Old::Init: + return ConnectionState::Initializing; + case Old::Handshake: + return ConnectionState::Handshaking; + case Old::Connected: + return ConnectionState::Connected; + case Old::Disconnecting: + return ConnectionState::Disconnecting; } return ConnectionState::Disconnected; } - std::uint64_t number(const Void::TeamSpeak::Protocol::CommandParams& record, + std::optional optionalNumber( + const Void::TeamSpeak::Protocol::CommandParams &record, std::string_view key) { const auto iterator = record.find(std::string{key}); - if (iterator == record.end()) return 0; + if (iterator == record.end()) { + return std::nullopt; + } std::uint64_t value = 0; - auto [end, error] = std::from_chars(iterator->second.data(), + const auto [end, error] = std::from_chars( + iterator->second.data(), iterator->second.data() + iterator->second.size(), value); - return error == std::errc{} && end == iterator->second.data() + - iterator->second.size() ? value : 0; + if (error != std::errc{} || + end != iterator->second.data() + iterator->second.size()) { + return std::nullopt; + } + return value; } - std::string text(const Void::TeamSpeak::Protocol::CommandParams& record, + std::uint64_t + number(const Void::TeamSpeak::Protocol::CommandParams &record, + std::string_view key) + { + return optionalNumber(record, key).value_or(0); + } + + std::optional optionalInteger( + const Void::TeamSpeak::Protocol::CommandParams &record, std::string_view key) + { + const auto iterator = record.find(std::string{key}); + if (iterator == record.end()) { + return std::nullopt; + } + std::int64_t value = 0; + const auto [end, error] = std::from_chars( + iterator->second.data(), + iterator->second.data() + iterator->second.size(), value); + if (error != std::errc{} || + end != iterator->second.data() + iterator->second.size()) { + return std::nullopt; + } + return value; + } + + std::int64_t + integer(const Void::TeamSpeak::Protocol::CommandParams &record, + std::string_view key) + { + return optionalInteger(record, key).value_or(0); + } + + std::optional + optionalInt(const Void::TeamSpeak::Protocol::CommandParams &record, + std::string_view key) + { + const auto value = optionalInteger(record, key); + if (!value || *value < std::numeric_limits::min() || + *value > std::numeric_limits::max()) { + return std::nullopt; + } + return static_cast(*value); + } + + std::string text(const Void::TeamSpeak::Protocol::CommandParams &record, + std::string_view key) { const auto iterator = record.find(std::string{key}); return iterator == record.end() ? std::string{} : iterator->second; } - std::optional optionalText( - const Void::TeamSpeak::Protocol::CommandParams& record, - std::string_view key) + std::optional + optionalText(const Void::TeamSpeak::Protocol::CommandParams &record, + std::string_view key) { const auto iterator = record.find(std::string{key}); - if (iterator == record.end()) return std::nullopt; + if (iterator == record.end()) { + return std::nullopt; + } return iterator->second; } - std::optional optionalBool( - const Void::TeamSpeak::Protocol::CommandParams& record, + std::optional optionalNonEmptyText( + const Void::TeamSpeak::Protocol::CommandParams &record, std::string_view key) { - if (!record.contains(std::string{key})) return std::nullopt; - return number(record, key) != 0; + auto value = optionalText(record, key); + return value && !value->empty() ? std::move(value) : std::nullopt; } - } - Client::Client() : impl_(std::make_unique()) { setEvents({}); } - Client::~Client() = default; - Client::Client(Client&&) noexcept = default; - Client& Client::operator=(Client&&) noexcept = default; + std::optional + optionalBool(const Void::TeamSpeak::Protocol::CommandParams &record, + std::string_view key) + { + const auto value = optionalNumber(record, key); + if (!value) { + return std::nullopt; + } + return *value != 0; + } - void Client::setEvents(Events handlers) - { + std::optional + avatarHash(const Void::TeamSpeak::Protocol::CommandParams &record) + { + auto value = optionalNonEmptyText(record, "client_flag_avatar"); + if (!value || value->find_first_not_of( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv" + "wxyz0123456789_-") != std::string::npos) { + return std::nullopt; + } + return value; + } + + std::optional + avatarUrl(const Void::TeamSpeak::Protocol::CommandParams &record) + { + auto raw = + optionalNonEmptyText(record, "client_myteamspeak_avatar"); + if (!raw) { + raw = optionalNonEmptyText(record, "client_myts_avatar"); + } + if (!raw) { + return std::nullopt; + } + const auto separator = raw->find(','); + if (separator == std::string::npos) { + return std::nullopt; + } + auto url = raw->substr(separator + 1); + if (!url.starts_with("https://") && !url.starts_with("http://")) { + return std::nullopt; + } + return url; + } + + std::vector serverGroupIds( + const Void::TeamSpeak::Protocol::CommandParams &record) + { + const auto raw = text(record, "client_servergroups"); + std::vector groups; + std::string_view remaining{raw}; + while (!remaining.empty()) { + const auto separator = remaining.find(','); + const auto token = remaining.substr(0, separator); + std::uint64_t value = 0; + const auto [end, error] = std::from_chars( + token.data(), token.data() + token.size(), value); + if (error == std::errc{} && + end == token.data() + token.size() && value != 0) { + groups.push_back(ServerGroupId{value}); + } + if (separator == std::string_view::npos) { + break; + } + remaining.remove_prefix(separator + 1); + } + return groups; + } + + RemoteClient + remoteClient(const Void::TeamSpeak::Protocol::CommandParams &record) + { + const auto clientId = number(record, "clid") != 0 + ? number(record, "clid") + : number(record, "client_id"); + return RemoteClient{ + .id = ClientId{static_cast(clientId)}, + .databaseId = + ClientDatabaseId{number(record, "client_database_id")}, + .channel = ChannelId{number(record, "cid") != 0 + ? number(record, "cid") + : number(record, "ctid")}, + .nickname = text(record, "client_nickname"), + .uniqueId = text(record, "client_unique_identifier"), + .serverGroups = serverGroupIds(record), + .type = static_cast(integer(record, "client_type")), + .talkPower = + static_cast(integer(record, "client_talk_power")), + .inputMuted = number(record, "client_input_muted") != 0, + .outputMuted = number(record, "client_output_muted") != 0, + .inputHardware = optionalBool(record, "client_input_hardware") + .value_or(true), + .outputHardware = optionalBool(record, "client_output_hardware") + .value_or(true), + .away = number(record, "client_away") != 0, + .talking = number(record, "client_flag_talking") != 0, + .recording = number(record, "client_is_recording") != 0, + .channelCommander = + number(record, "client_is_channel_commander") != 0, + .prioritySpeaker = + number(record, "client_is_priority_speaker") != 0, + .awayMessage = text(record, "client_away_message"), + .country = text(record, "client_country")}; + } + + Channel channel(const Void::TeamSpeak::Protocol::CommandParams &record) + { + const auto parent = number(record, "pid"); + return Channel{ + .id = ChannelId{number(record, "cid")}, + .parent = parent == 0 ? std::nullopt + : std::optional{ChannelId{parent}}, + .orderAfter = ChannelId{number(record, "channel_order")}, + .name = text(record, "channel_name"), + .topic = text(record, "channel_topic"), + .description = text(record, "channel_description"), + .codec = static_cast(integer(record, "channel_codec")), + .codecQuality = + static_cast(integer(record, "channel_codec_quality")), + .maxClients = + static_cast(integer(record, "channel_maxclients")), + .maxFamilyClients = static_cast( + integer(record, "channel_maxfamilyclients")), + .neededTalkPower = static_cast( + integer(record, "channel_needed_talk_power")), + .iconId = number(record, "channel_icon_id"), + .passwordProtected = + number(record, "channel_flag_password") != 0, + .permanent = number(record, "channel_flag_permanent") != 0, + .semiPermanent = + number(record, "channel_flag_semi_permanent") != 0, + .defaultChannel = number(record, "channel_flag_default") != 0, + .unlimitedClients = + number(record, "channel_flag_maxclients_unlimited") != 0, + .unlimitedFamilyClients = + number(record, "channel_flag_maxfamilyclients_unlimited") != + 0}; + } + + ChannelPatch + channelPatch(const Void::TeamSpeak::Protocol::CommandParams &record) + { + ChannelPatch patch{ + .parent = std::nullopt, + .orderAfter = optionalNumber(record, "channel_order") + .transform([](const std::uint64_t value) { + return ChannelId{value}; + }), + .name = optionalText(record, "channel_name"), + .topic = optionalText(record, "channel_topic"), + .description = optionalText(record, "channel_description"), + .codec = optionalInt(record, "channel_codec"), + .codecQuality = optionalInt(record, "channel_codec_quality"), + .maxClients = optionalInt(record, "channel_maxclients"), + .maxFamilyClients = + optionalInt(record, "channel_maxfamilyclients"), + .neededTalkPower = + optionalInt(record, "channel_needed_talk_power"), + .iconId = optionalNumber(record, "channel_icon_id"), + .passwordProtected = + optionalBool(record, "channel_flag_password"), + .permanent = optionalBool(record, "channel_flag_permanent"), + .semiPermanent = + optionalBool(record, "channel_flag_semi_permanent"), + .defaultChannel = optionalBool(record, "channel_flag_default"), + .unlimitedClients = + optionalBool(record, "channel_flag_maxclients_unlimited"), + .unlimitedFamilyClients = optionalBool( + record, "channel_flag_maxfamilyclients_unlimited"), + .properties = record}; + + auto parent = optionalNumber(record, "pid"); + if (!parent) { + parent = optionalNumber(record, "cpid"); + } + if (parent) { + patch.parent = *parent == 0 ? std::optional{} + : std::optional{ChannelId{*parent}}; + } + if (!patch.orderAfter) { + patch.orderAfter = + optionalNumber(record, "order") + .transform([](const std::uint64_t value) { + return ChannelId{value}; + }); + } + return patch; + } + + void addLifetime(CommandFields &fields, ChannelLifetime lifetime) + { + fields["channel_flag_permanent"] = + lifetime == ChannelLifetime::Permanent ? "1" : "0"; + fields["channel_flag_semi_permanent"] = + lifetime == ChannelLifetime::SemiPermanent ? "1" : "0"; + } + + template + void addOptionalNumber(CommandFields &fields, std::string_view name, + const std::optional &value) + { + if (value) { + fields[std::string{name}] = std::to_string(*value); + } + } + + void addOptionalBool(CommandFields &fields, std::string_view name, + const std::optional &value) + { + if (value) { + fields[std::string{name}] = *value ? "1" : "0"; + } + } + + bool hasInvalidChannelNumbers(const ChannelCreateOptions &options) + { + return (options.codec && + (*options.codec < 0 || *options.codec > 5)) || + (options.codecQuality && (*options.codecQuality < 0 || + *options.codecQuality > 10)) || + (options.maxClients && *options.maxClients < 0) || + (options.maxFamilyClients && + *options.maxFamilyClients < 0) || + (options.neededTalkPower && *options.neededTalkPower < 0); + } + + bool hasInvalidChannelNumbers(const ChannelEditOptions &options) + { + return (options.codec && + (*options.codec < 0 || *options.codec > 5)) || + (options.codecQuality && (*options.codecQuality < 0 || + *options.codecQuality > 10)) || + (options.maxClients && *options.maxClients < 0) || + (options.maxFamilyClients && + *options.maxFamilyClients < 0) || + (options.neededTalkPower && *options.neededTalkPower < 0); + } + } // namespace + + namespace Detail + { + std::optional parseChannelChanged( + std::string_view eventName, const CommandFields &record) + { + const auto kind = [&]() -> std::optional { + if (eventName == "notifychannelcreated") { + return ChannelChangeKind::Created; + } + if (eventName == "notifychanneledited") { + return ChannelChangeKind::Updated; + } + if (eventName == "notifychannelmoved") { + return ChannelChangeKind::Moved; + } + if (eventName == "notifychanneldeleted") { + return ChannelChangeKind::Deleted; + } + return std::nullopt; + }(); + const auto id = optionalNumber(record, "cid"); + if (!kind || !id || *id == 0) { + return std::nullopt; + } + + ClientId invoker; + const auto invokerValue = optionalNumber(record, "invokerid"); + if (invokerValue && + *invokerValue <= std::numeric_limits::max()) { + invoker.value = static_cast(*invokerValue); + } + return ChannelChanged{ + .kind = *kind, + .id = ChannelId{*id}, + .patch = channelPatch(record), + .invoker = invoker, + .reasonId = optionalInt(record, "reasonid").value_or(0)}; + } + } // namespace Detail + + Client::Client() : impl_(std::make_unique()) { setEvents({}); } + Client::~Client() = default; + Client::Client(Client &&) noexcept = default; + Client &Client::operator=(Client &&) noexcept = default; + + void Client::setEvents(Events handlers) + { impl_->events.store(std::make_shared(std::move(handlers)), - std::memory_order_release); - if (impl_->callbacksInstalled.exchange(true, std::memory_order_acq_rel)) { + std::memory_order_release); + if (impl_->callbacksInstalled.exchange(true, + std::memory_order_acq_rel)) { return; } - auto* impl = impl_.get(); - Void::TeamSpeak::Protocol::TsClientCallbacks callbacks; - callbacks.onConnected = [impl] { + auto *impl = impl_.get(); + Void::TeamSpeak::Protocol::TsClientCallbacks callbacks; + callbacks.onConnected = [impl] { auto events = impl->events.load(std::memory_order_acquire); - if (events->connected) events->connected(); + if (events->connected) { + events->connected(); + } }; - callbacks.onDisconnected = [impl] { + callbacks.onDisconnected = [impl] { auto events = impl->events.load(std::memory_order_acquire); - if (events->disconnected) events->disconnected(); + if (events->disconnected) { + events->disconnected(); + } }; - callbacks.onError = [impl](const std::string& message) { + callbacks.onError = [impl](const std::string &message) { auto events = impl->events.load(std::memory_order_acquire); - if (events->error) events->error(protocolError(message)); - }; - callbacks.onDebug = [impl](const std::string& message) { + if (events->error) { + events->error(protocolError(message)); + } + }; + callbacks.onDebug = [impl](const std::string &message) { auto events = impl->events.load(std::memory_order_acquire); - if (events->debug) events->debug(message); - }; - callbacks.onCommand = [impl](const Void::TeamSpeak::Protocol::ParsedCommand& command) { + if (events->debug) { + events->debug(message); + } + }; + callbacks.onCommand = [impl]( + const Void::TeamSpeak::Protocol::ParsedCommand + &command) { auto events = impl->events.load(std::memory_order_acquire); - if (events->command) events->command(command.name, command.params); + if (events->command) { + events->command(command.name, command.params); + } if (events->commandBatch) { events->commandBatch(CommandEvent{ .name = command.name, - .records = command.groups.empty() - ? std::vector{command.params} - : command.groups}); + .records = + command.groups.empty() + ? std::vector{command + .params} + : command.groups}); } - const auto& records = command.groups.empty() - ? std::vector{command.params} - : command.groups; - for (const auto& record : records) { + const auto &records = + command.groups.empty() + ? std::vector{command.params} + : command.groups; + for (const auto &record : records) { if (command.name == "notifycliententerview" && events->clientEntered) { - events->clientEntered(RemoteClient{ - .id = ClientId{static_cast(number(record, "clid"))}, - .channel = ChannelId{number(record, "ctid")}, - .nickname = text(record, "client_nickname"), - .uniqueId = text(record, "client_unique_identifier")}); + events->clientEntered(remoteClient(record)); } else if (command.name == "notifyclientleftview" && - events->clientLeft) { + events->clientLeft) { events->clientLeft(ClientLeft{ - .id = ClientId{static_cast(number(record, "clid"))}, - .reasonId = static_cast(number(record, "reasonid")), + .id = ClientId{static_cast( + number(record, "clid"))}, + .reasonId = + static_cast(number(record, "reasonid")), .reasonMessage = text(record, "reasonmsg")}); } else if (command.name == "notifyclientmoved" && - events->clientMoved) { + events->clientMoved) { events->clientMoved(ClientMoved{ - .id = ClientId{static_cast(number(record, "clid"))}, + .id = ClientId{static_cast( + number(record, "clid"))}, .channel = ChannelId{number(record, "ctid")}}); } else if (command.name == "notifyclientupdated" && - events->clientUpdated) { + events->clientUpdated) { events->clientUpdated(ClientUpdated{ - .id = ClientId{static_cast(number(record, "clid"))}, + .id = ClientId{static_cast( + number(record, "clid"))}, .nickname = optionalText(record, "client_nickname"), - .uniqueId = optionalText(record, "client_unique_identifier"), - .inputMuted = optionalBool(record, "client_input_muted"), - .outputMuted = optionalBool(record, "client_output_muted"), + .uniqueId = + optionalText(record, "client_unique_identifier"), + .inputMuted = + optionalBool(record, "client_input_muted"), + .outputMuted = + optionalBool(record, "client_output_muted"), + .inputHardware = + optionalBool(record, "client_input_hardware"), + .outputHardware = + optionalBool(record, "client_output_hardware"), .away = optionalBool(record, "client_away"), - .recording = optionalBool(record, "client_is_recording"), + .talking = optionalBool(record, "client_flag_talking"), + .recording = + optionalBool(record, "client_is_recording"), + .channelCommander = + optionalBool(record, "client_is_channel_commander"), + .prioritySpeaker = + optionalBool(record, "client_is_priority_speaker"), + .avatarHash = avatarHash(record), + .avatarUrl = avatarUrl(record), .properties = record}); } else if (command.name == "notifytalkstatuschange" && - events->talkStatusChanged) { + events->talkStatusChanged) { events->talkStatusChanged(TalkStatusChanged{ - .id = ClientId{static_cast(number(record, "clid"))}, + .id = ClientId{static_cast( + number(record, "clid"))}, .talking = number(record, "status") != 0, .whisper = number(record, "isreceivedwhisper") != 0}); } else if (command.name == "notifytextmessage" && - events->textMessage) { + events->textMessage) { events->textMessage(TextMessage{ - .target = TextTarget{ - .kind = static_cast(number(record, "targetmode")), - .id = number(record, "target")}, - .invoker = ClientId{static_cast(number(record, "invokerid"))}, + .target = + TextTarget{.kind = static_cast( + number(record, "targetmode")), + .id = number(record, "target")}, + .invoker = ClientId{static_cast( + number(record, "invokerid"))}, .invokerName = text(record, "invokername"), .message = text(record, "msg")}); } else if ((command.name == "notifyserveredited" || - command.name == "notifyserverupdated") && - events->serverUpdated) { + command.name == "notifyserverupdated") && + events->serverUpdated) { events->serverUpdated(ServerUpdated{ .name = optionalText(record, "virtualserver_name"), - .welcomeMessage = optionalText(record, - "virtualserver_welcomemessage"), - .invoker = ClientId{static_cast(number(record, - "invokerid"))}, + .welcomeMessage = optionalText( + record, "virtualserver_welcomemessage"), + .invoker = ClientId{static_cast( + number(record, "invokerid"))}, .properties = record}); } else if ((command.name == "notifyservergroupclientadded" || - command.name == "notifyservergroupclientdeleted") && - events->serverGroupMembershipChanged) { + command.name == "notifyservergroupclientdeleted") && + events->serverGroupMembershipChanged) { events->serverGroupMembershipChanged( ServerGroupMembershipChanged{ - .added = command.name == "notifyservergroupclientadded", + .added = + command.name == "notifyservergroupclientadded", .group = ServerGroupId{number(record, "sgid")}, - .client = ClientDatabaseId{number(record, "cldbid")}, - .invoker = ClientId{static_cast(number(record, - "invokerid"))}}); + .client = + ClientDatabaseId{number(record, "cldbid")}, + .invoker = ClientId{static_cast( + number(record, "invokerid"))}}); } else if (command.name == "notifyclientchannelgroupchanged" && - events->channelGroupMembershipChanged) { + events->channelGroupMembershipChanged) { events->channelGroupMembershipChanged( ChannelGroupMembershipChanged{ .group = ChannelGroupId{number(record, "cgid")}, .channel = ChannelId{number(record, "cid")}, - .client = ClientDatabaseId{number(record, "cldbid")}, - .invoker = ClientId{static_cast(number(record, - "invokerid"))}}); + .client = + ClientDatabaseId{number(record, "cldbid")}, + .invoker = ClientId{static_cast( + number(record, "invokerid"))}}); } else if (command.name == "notifyfiletransferstatus" && - events->fileTransferStatus) { + events->fileTransferStatus) { events->fileTransferStatus(FileTransferStatus{ .id = number(record, "ftid"), .status = static_cast(number(record, "status")), .message = text(record, "msg")}); } else if (events->channelChanged) { - std::optional kind; - if (command.name == "notifychannelcreated") kind = ChannelChangeKind::Created; - else if (command.name == "notifychanneledited") kind = ChannelChangeKind::Updated; - else if (command.name == "notifychannelmoved") kind = ChannelChangeKind::Moved; - else if (command.name == "notifychanneldeleted") kind = ChannelChangeKind::Deleted; - if (kind) { - const auto parent = number(record, "pid"); - events->channelChanged(ChannelChanged{ - .kind = *kind, - .channel = Channel{ - .id = ChannelId{number(record, "cid")}, - .parent = parent == 0 ? std::nullopt - : std::optional{ChannelId{parent}}, - .name = text(record, "channel_name"), - .passwordProtected = number(record, - "channel_flag_password") != 0}}); + if (const auto change = Detail::parseChannelChanged( + command.name, record)) { + events->channelChanged(*change); } } } - }; - callbacks.onVoice = [impl](std::span voice) { + }; + callbacks.onVoice = [impl](std::span voice) { auto events = impl->events.load(std::memory_order_acquire); - if (events->voice) events->voice(voice); - }; - impl_->client.setCallbacks(std::move(callbacks)); - } + if (events->voice) { + events->voice(voice); + } + }; + impl_->client.setCallbacks(std::move(callbacks)); + } - Void::Result::Result Client::connect(const ConnectOptions& options) - { - if (options.host.empty() || !options.identity) { - return Void::Result::fail(Error{Error::Code::InvalidArgument, - "host and identity are required"}); - } - Void::TeamSpeak::Protocol::TsClientOptions old; - old.host = options.host; - old.port = options.port; - old.identity = options.identity.get(); - old.nickname = options.nickname; - old.serverPassword = options.serverPassword; - old.defaultChannel = options.defaultChannel; - old.channelPassword = options.channelPassword; - try { - impl_->client.connect(old); - return {}; - } catch (const std::exception& exception) { - return Void::Result::fail(Error{Error::Code::Io, exception.what()}); - } - } + Void::Result::Result + Client::connect(const ConnectOptions &options) + { + if (options.host.empty() || !options.identity) { + return Void::Result::fail(Error{Error::Code::InvalidArgument, + "host and identity are required"}); + } + Void::TeamSpeak::Protocol::TsClientOptions old; + old.host = options.host; + old.port = options.port; + old.identity = options.identity.get(); + old.nickname = options.nickname; + old.serverPassword = options.serverPassword; + old.defaultChannel = options.defaultChannel; + old.channelPassword = options.channelPassword; + try { + impl_->client.connect(old); + return {}; + } catch (const std::exception &exception) { + return Void::Result::fail(Error{Error::Code::Io, exception.what()}); + } + } - void Client::disconnect() noexcept { impl_->client.disconnect(); } - void Client::close() noexcept { impl_->client.forceClose(); } - ConnectionState Client::state() const noexcept { return convert(impl_->client.state()); } - ClientId Client::id() const noexcept { return ClientId{impl_->client.clientId()}; } + void Client::disconnect() noexcept { impl_->client.disconnect(); } + void Client::close() noexcept { impl_->client.forceClose(); } + ConnectionState Client::state() const noexcept + { + return convert(impl_->client.state()); + } + ClientId Client::id() const noexcept + { + return ClientId{impl_->client.clientId()}; + } - Void::Result::Result - Client::request(std::string_view command, std::chrono::milliseconds timeout) - { - auto result = impl_->client.requestCommand(std::string{command}, timeout); - if (!result.ok()) { - return Void::Result::fail(protocolError(result.errorMessage)); - } - return CommandResponse{std::move(result.records)}; - } + Void::Result::Result + Client::request(std::string_view command, + std::chrono::milliseconds timeout) + { + auto result = + impl_->client.requestCommand(std::string{command}, timeout); + if (!result.ok()) { + return Void::Result::fail(protocolError(result.errorMessage)); + } + return CommandResponse{std::move(result.records)}; + } Void::Result::Result, Error> - Client::clients(std::chrono::milliseconds timeout) + Client::clients(std::chrono::milliseconds timeout) { - auto response = request("clientlist -uid", timeout); - if (!response) return Void::Result::fail(response.error()); + auto response = request( + "clientlist -uid -away -voice -groups -info -country", timeout); + if (!response) { + return Void::Result::fail(response.error()); + } std::vector result; result.reserve(response->records.size()); - for (const auto& record : response->records) { - result.push_back(RemoteClient{ - .id = ClientId{static_cast(number(record, "clid"))}, - .channel = ChannelId{number(record, "cid")}, - .nickname = text(record, "client_nickname"), - .uniqueId = text(record, "client_unique_identifier")}); + for (const auto &record : response->records) { + result.push_back(remoteClient(record)); } return result; } + Void::Result::Result + Client::clientDetails(ClientId clientId, + std::chrono::milliseconds timeout) + { + if (!clientId) { + return Void::Result::fail(invalidArgument("client id is required")); + } + const auto command = buildCommand( + "clientinfo", {{"clid", std::to_string(clientId.value)}}); + auto response = request(command, timeout); + if (!response) { + return Void::Result::fail(response.error()); + } + if (response->records.empty()) { + return Void::Result::fail( + protocolError("clientinfo returned no record")); + } + const auto &record = response->records.front(); + auto client = remoteClient(record); + if (!client.id) { + client.id = clientId; + } + ClientDetails details{.client = std::move(client), + .connectionIp = optionalNonEmptyText( + record, "connection_client_ip"), + .avatarHash = avatarHash(record), + .avatarUrl = avatarUrl(record)}; + + // connection_client_ip is permission-gated and normally comes from a + // separate command. Details remain useful when that optional query + // fails. + auto connection = + request(buildCommand("clientconnectioninfo", + {{"clid", std::to_string(clientId.value)}}), + timeout); + if (connection && !connection->records.empty()) { + if (auto address = optionalNonEmptyText(connection->records.front(), + "connection_client_ip")) { + details.connectionIp = std::move(address); + } + } + return details; + } + Void::Result::Result, Error> - Client::channels(std::chrono::milliseconds timeout) + Client::channels(std::chrono::milliseconds timeout) { - auto response = request("channellist -flags", timeout); - if (!response) return Void::Result::fail(response.error()); + auto response = + request("channellist -topic -flags -voice -limits -icon", timeout); + if (!response) { + return Void::Result::fail(response.error()); + } std::vector result; result.reserve(response->records.size()); - for (const auto& record : response->records) { - const auto parent = number(record, "pid"); - result.push_back(Channel{ - .id = ChannelId{number(record, "cid")}, - .parent = parent == 0 ? std::nullopt - : std::optional{ChannelId{parent}}, - .name = text(record, "channel_name"), - .passwordProtected = number(record, "channel_flag_password") != 0}); + for (const auto &record : response->records) { + result.push_back(channel(record)); } return result; } + Void::Result::Result + Client::subscribeAllChannels(std::chrono::milliseconds timeout) + { + auto response = request("channelsubscribeall", timeout); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + Void::Result::Result, Error> - Client::serverGroups(std::chrono::milliseconds timeout) + Client::serverGroups(std::chrono::milliseconds timeout) { auto response = request("servergrouplist", timeout); - if (!response) return Void::Result::fail(response.error()); + if (!response) { + return Void::Result::fail(response.error()); + } std::vector result; result.reserve(response->records.size()); - for (const auto& record : response->records) { + for (const auto &record : response->records) { result.push_back(ServerGroup{ .id = ServerGroupId{number(record, "sgid")}, .name = text(record, "name"), - .type = static_cast(number(record, "type"))}); + .type = static_cast(integer(record, "type")), + .nameMode = static_cast(integer(record, "namemode")), + .sortId = static_cast(integer(record, "sortid")), + .modifyPower = static_cast(integer(record, "n_modifyp")), + .memberAddPower = + static_cast(integer(record, "n_member_addp")), + .memberRemovePower = + static_cast(integer(record, "n_member_removep")), + .iconId = number(record, "iconid"), + .savedToDatabase = number(record, "savedb") != 0}); } return result; } Void::Result::Result, Error> - Client::channelGroups(std::chrono::milliseconds timeout) + Client::channelGroups(std::chrono::milliseconds timeout) { auto response = request("channelgrouplist", timeout); - if (!response) return Void::Result::fail(response.error()); + if (!response) { + return Void::Result::fail(response.error()); + } std::vector result; result.reserve(response->records.size()); - for (const auto& record : response->records) { - result.push_back(ChannelGroup{ - .id = ChannelGroupId{number(record, "cgid")}, - .name = text(record, "name"), - .type = static_cast(number(record, "type"))}); + for (const auto &record : response->records) { + result.push_back( + ChannelGroup{.id = ChannelGroupId{number(record, "cgid")}, + .name = text(record, "name"), + .type = static_cast(number(record, "type"))}); } return result; } Void::Result::Result, Error> - Client::permissions(std::chrono::milliseconds timeout) + Client::permissions(std::chrono::milliseconds timeout) { auto response = request("permissionlist", timeout); - if (!response) return Void::Result::fail(response.error()); + if (!response) { + return Void::Result::fail(response.error()); + } std::vector result; result.reserve(response->records.size()); - for (const auto& record : response->records) { - result.push_back(Permission{ - .id = PermissionId{static_cast( - number(record, "permid"))}, - .name = text(record, "permname"), - .description = text(record, "permdesc")}); + for (const auto &record : response->records) { + result.push_back( + Permission{.id = PermissionId{static_cast( + number(record, "permid"))}, + .name = text(record, "permname"), + .description = text(record, "permdesc")}); } return result; } - Void::Result::Result -Client::addToServerGroup(ServerGroupId group, ClientDatabaseId client) + Void::Result::Result + Client::serverInfo(std::chrono::milliseconds timeout) { - Void::TeamSpeak::Protocol::CommandParams params{ - {"sgid", std::to_string(group.value)}, - {"cldbid", std::to_string(client.value)}}; - auto response = request(Void::TeamSpeak::Protocol::buildCommand( - "servergroupaddclient", params)); - if (!response) return Void::Result::fail(response.error()); - return {}; + auto response = request("serverinfo", timeout); + if (!response) { + return Void::Result::fail(response.error()); + } + if (response->records.empty()) { + return Void::Result::fail( + protocolError("serverinfo returned no record")); + } + const auto &record = response->records.front(); + return ServerInfo{ + .id = ServerConnectionId{number(record, "virtualserver_id")}, + .uniqueIdentifier = text(record, "virtualserver_unique_identifier"), + .name = text(record, "virtualserver_name"), + .welcomeMessage = text(record, "virtualserver_welcomemessage"), + .platform = text(record, "virtualserver_platform"), + .version = text(record, "virtualserver_version"), + .hostMessage = text(record, "virtualserver_hostmessage"), + .hostMessageMode = static_cast( + integer(record, "virtualserver_hostmessage_mode")), + .uptimeSeconds = number(record, "virtualserver_uptime"), + .maxClients = number(record, "virtualserver_maxclients"), + .clientCount = number(record, "virtualserver_clientsonline"), + .queryClientCount = + number(record, "virtualserver_queryclientsonline"), + .channelCount = number(record, "virtualserver_channelsonline"), + .reservedSlots = number(record, "virtualserver_reserved_slots"), + .defaultServerGroup = ServerGroupId{number( + record, "virtualserver_default_server_group")}, + .defaultChannelGroup = ChannelGroupId{number( + record, "virtualserver_default_channel_group")}, + .defaultChannelAdminGroup = ChannelGroupId{number( + record, "virtualserver_default_channel_admin_group")}, + .passwordProtected = + number(record, "virtualserver_flag_password") != 0}; } - Void::Result::Result -Client::removeFromServerGroup(ServerGroupId group, ClientDatabaseId client) + Void::Result::Result, Error> + Client::bans(std::chrono::milliseconds timeout) { - Void::TeamSpeak::Protocol::CommandParams params{ - {"sgid", std::to_string(group.value)}, - {"cldbid", std::to_string(client.value)}}; - auto response = request(Void::TeamSpeak::Protocol::buildCommand( - "servergroupdelclient", params)); - if (!response) return Void::Result::fail(response.error()); - return {}; + auto response = request("banlist", timeout); + if (!response) { + return Void::Result::fail(response.error()); + } + std::vector result; + result.reserve(response->records.size()); + for (const auto &record : response->records) { + result.push_back(Ban{ + .id = BanId{number(record, "banid")}, + .ip = text(record, "ip"), + .name = text(record, "name"), + .uniqueId = text(record, "uid"), + .lastNickname = text(record, "lastnickname"), + .createdAtUnixSeconds = number(record, "created"), + .duration = std::chrono::seconds{integer(record, "duration")}, + .invokerDatabaseId = + ClientDatabaseId{number(record, "invokercldbid")}, + .invokerName = text(record, "invokername"), + .invokerUniqueId = text(record, "invokeruid"), + .reason = text(record, "reason"), + .enforcements = number(record, "enforcements")}); + } + return result; } - Void::Result::Result Client::setChannelGroup( - ChannelGroupId group, ChannelId channel, ClientDatabaseId client) + Void::Result::Result Client::ban(ClientId client, + const BanOptions &options) { - CommandFields fields{{"cgid", std::to_string(group.value)}, - {"cid", std::to_string(channel.value)}, - {"cldbid", std::to_string(client.value)}}; - auto response = request(buildCommand("setclientchannelgroup", fields)); - if (!response) return Void::Result::fail(response.error()); - return {}; - } - - Void::Result::Result - Client::sendText(TextTarget target, std::string_view message) - { - Void::TeamSpeak::Protocol::CommandParams params; - params["targetmode"] = std::to_string(static_cast(target.kind)); - if (target.kind != TextTargetKind::Server) - params["target"] = std::to_string(target.id); - params["msg"] = std::string{message}; - auto response = request(Void::TeamSpeak::Protocol::buildCommand( - "sendtextmessage", params)); - if (!response) return Void::Result::fail(response.error()); - return {}; - } - - Void::Result::Result - Client::move(ClientId client, ChannelId channel) - { - Void::TeamSpeak::Protocol::CommandParams params{ + if (!client) { + return Void::Result::fail(invalidArgument("client id is required")); + } + if (options.duration && + *options.duration <= std::chrono::seconds::zero()) { + return Void::Result::fail( + invalidArgument("timed ban duration must be positive")); + } + CommandFields fields{ {"clid", std::to_string(client.value)}, - {"cid", std::to_string(channel.value)}}; - auto response = request(Void::TeamSpeak::Protocol::buildCommand("clientmove", params)); - if (!response) return Void::Result::fail(response.error()); + {"time", + std::to_string(options.duration ? options.duration->count() : 0)}, + {"banreason", options.reason}}; + auto response = request(buildCommand("banclient", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + if (response->records.empty()) { + return Void::Result::fail( + protocolError("banclient returned no ban id")); + } + const auto id = BanId{number(response->records.front(), "banid")}; + if (!id) { + return Void::Result::fail( + protocolError("banclient returned an invalid ban id")); + } + return id; + } + + Void::Result::Result Client::unban(BanId ban) + { + if (!ban) { + return Void::Result::fail(invalidArgument("ban id is required")); + } + auto response = request( + buildCommand("bandel", {{"banid", std::to_string(ban.value)}})); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result + Client::createChannel(const ChannelCreateOptions &options) + { + if (options.name.empty()) { + return Void::Result::fail( + invalidArgument("channel name is required")); + } + if (hasInvalidChannelNumbers(options)) { + return Void::Result::fail(invalidArgument( + "channel codec must be between 0 and 5, codec quality between " + "0 " + "and 10, and limits and talk power must be non-negative")); + } + CommandFields fields{ + {"channel_name", options.name}, + {"channel_flag_default", options.defaultChannel ? "1" : "0"}, + {"channel_flag_maxclients_unlimited", + options.unlimitedClients ? "1" : "0"}, + {"channel_flag_maxfamilyclients_unlimited", + options.unlimitedFamilyClients ? "1" : "0"}}; + if (options.parent) { + fields["cpid"] = std::to_string(options.parent->value); + } + if (options.orderAfter) { + fields["channel_order"] = std::to_string(options.orderAfter->value); + } + if (!options.topic.empty()) { + fields["channel_topic"] = options.topic; + } + if (!options.description.empty()) { + fields["channel_description"] = options.description; + } + if (!options.password.empty()) { + fields["channel_password"] = options.password; + } + addOptionalNumber(fields, "channel_codec", options.codec); + addOptionalNumber(fields, "channel_codec_quality", + options.codecQuality); + addOptionalNumber(fields, "channel_maxclients", options.maxClients); + addOptionalNumber(fields, "channel_maxfamilyclients", + options.maxFamilyClients); + addOptionalNumber(fields, "channel_needed_talk_power", + options.neededTalkPower); + addLifetime(fields, options.lifetime); + + auto response = request(buildCommand("channelcreate", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + if (response->records.empty()) { + return Void::Result::fail( + protocolError("channelcreate returned no channel id")); + } + const auto id = ChannelId{number(response->records.front(), "cid")}; + if (!id) { + return Void::Result::fail( + protocolError("channelcreate returned an invalid channel id")); + } + return id; + } + + Void::Result::Result + Client::editChannel(ChannelId channelId, + const ChannelEditOptions &options) + { + if (!channelId) { + return Void::Result::fail( + invalidArgument("channel id is required")); + } + if (options.empty()) { + return Void::Result::fail( + invalidArgument("at least one channel property is required")); + } + if ((options.name && options.name->empty()) || + hasInvalidChannelNumbers(options)) { + return Void::Result::fail(invalidArgument( + "channel name cannot be empty; codec must be between 0 and 5, " + "codec quality between 0 and 10, and limits and talk power " + "must " + "be non-negative")); + } + CommandFields fields{{"cid", std::to_string(channelId.value)}}; + if (options.name) { + fields["channel_name"] = *options.name; + } + if (options.topic) { + fields["channel_topic"] = *options.topic; + } + if (options.description) { + fields["channel_description"] = *options.description; + } + if (options.password) { + fields["channel_password"] = *options.password; + } + addOptionalNumber(fields, "channel_codec", options.codec); + addOptionalNumber(fields, "channel_codec_quality", + options.codecQuality); + addOptionalNumber(fields, "channel_maxclients", options.maxClients); + addOptionalNumber(fields, "channel_maxfamilyclients", + options.maxFamilyClients); + addOptionalNumber(fields, "channel_needed_talk_power", + options.neededTalkPower); + addOptionalBool(fields, "channel_flag_default", options.defaultChannel); + addOptionalBool(fields, "channel_flag_maxclients_unlimited", + options.unlimitedClients); + addOptionalBool(fields, "channel_flag_maxfamilyclients_unlimited", + options.unlimitedFamilyClients); + if (options.lifetime) { + addLifetime(fields, *options.lifetime); + } + auto response = request(buildCommand("channeledit", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } return {}; } Void::Result::Result - Client::kick(ClientId client, std::string_view reason) + Client::reorderChannel(ChannelId channelId, + std::optional + parent, + std::optional + orderAfter) { - Void::TeamSpeak::Protocol::CommandParams params{ - {"clid", std::to_string(client.value)}, {"reasonid", "5"}, - {"reasonmsg", std::string{reason}}}; - auto response = request(Void::TeamSpeak::Protocol::buildCommand("clientkick", params)); - if (!response) return Void::Result::fail(response.error()); + if (!channelId || (parent && *parent == channelId) || + (orderAfter && *orderAfter == channelId)) { + return Void::Result::fail( + invalidArgument("channel id is required and cannot be its own " + "parent or order")); + } + CommandFields fields{ + {"cid", std::to_string(channelId.value)}, + {"cpid", std::to_string(parent ? parent->value : 0)}}; + if (orderAfter) { + fields["order"] = std::to_string(orderAfter->value); + } + auto response = request(buildCommand("channelmove", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } return {}; } - Void::Result::Result - Client::download(std::string_view remotePath, - const std::filesystem::path& destination, ChannelId channel, - std::string_view password, std::chrono::milliseconds timeout) - { - auto result = impl_->client.downloadFile(std::string{remotePath}, destination.string(), - channel.value, std::string{password}, timeout); - if (!result.ok()) return Void::Result::fail(protocolError(result.errorMessage)); - return destination; - } + Void::Result::Result Client::deleteChannel(ChannelId channelId, + bool force) + { + if (!channelId) { + return Void::Result::fail( + invalidArgument("channel id is required")); + } + auto response = request(buildCommand( + "channeldelete", {{"cid", std::to_string(channelId.value)}, + {"force", force ? "1" : "0"}})); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } - Void::Result::Result Client::upload( - const std::filesystem::path& source, std::string_view remotePath, - ChannelId channel, std::string_view password, bool overwrite, - std::chrono::milliseconds timeout) + Void::Result::Result + Client::addServerGroupMember(ServerGroupId group, + ClientDatabaseId client) + { + if (!group || !client) { + return Void::Result::fail(invalidArgument( + "server group and client database ids are required")); + } + CommandFields fields{{"sgid", std::to_string(group.value)}, + {"cldbid", std::to_string(client.value)}}; + auto response = request(buildCommand("servergroupaddclient", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result + Client::removeServerGroupMember(ServerGroupId group, + ClientDatabaseId client) + { + if (!group || !client) { + return Void::Result::fail(invalidArgument( + "server group and client database ids are required")); + } + CommandFields fields{{"sgid", std::to_string(group.value)}, + {"cldbid", std::to_string(client.value)}}; + auto response = request(buildCommand("servergroupdelclient", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result + Client::addToServerGroup(ServerGroupId group, ClientDatabaseId client) + { + return addServerGroupMember(group, client); + } + + Void::Result::Result + Client::removeFromServerGroup(ServerGroupId group, + ClientDatabaseId client) + { + return removeServerGroupMember(group, client); + } + + Void::Result::Result + Client::setChannelGroup(ChannelGroupId group, ChannelId channel, + ClientDatabaseId client) + { + if (!group || !channel || !client) { + return Void::Result::fail( + invalidArgument("channel group, channel, and client database " + "ids are required")); + } + CommandFields fields{{"cgid", std::to_string(group.value)}, + {"cid", std::to_string(channel.value)}, + {"cldbid", std::to_string(client.value)}}; + auto response = request(buildCommand("setclientchannelgroup", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result Client::sendText(TextTarget target, + std::string_view message) + { + if (message.empty()) { + return Void::Result::fail(invalidArgument("message is required")); + } + switch (target.kind) { + case TextTargetKind::Client: + case TextTargetKind::Channel: + if (target.id == 0) { + return Void::Result::fail(invalidArgument( + "client or channel target id is required")); + } + break; + case TextTargetKind::Server: + break; + default: + return Void::Result::fail( + invalidArgument("invalid text target")); + } + CommandFields fields{ + {"targetmode", std::to_string(static_cast(target.kind))}, + {"msg", std::string{message}}}; + if (target.kind != TextTargetKind::Server) { + fields["target"] = std::to_string(target.id); + } + auto response = request(buildCommand("sendtextmessage", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result + Client::sendPrivateMessage(ClientId client, std::string_view message) + { + return sendText(TextTarget{TextTargetKind::Client, client.value}, + message); + } + + Void::Result::Result + Client::sendChannelMessage(ChannelId channelId, + std::string_view message) + { + return sendText(TextTarget{TextTargetKind::Channel, channelId.value}, + message); + } + + Void::Result::Result + Client::sendServerMessage(std::string_view message) + { + return sendText(TextTarget{TextTargetKind::Server, 0}, message); + } + + Void::Result::Result Client::move(ClientId client, + ChannelId channel) + { + if (!client || !channel) { + return Void::Result::fail( + invalidArgument("client and channel ids are required")); + } + CommandFields fields{{"clid", std::to_string(client.value)}, + {"cid", std::to_string(channel.value)}}; + auto response = request(buildCommand("clientmove", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result + Client::kick(ClientId client, KickScope scope, std::string_view reason) + { + if (!client) { + return Void::Result::fail(invalidArgument("client id is required")); + } + if (scope != KickScope::Channel && scope != KickScope::Server) { + return Void::Result::fail(invalidArgument("invalid kick scope")); + } + CommandFields fields{ + {"clid", std::to_string(client.value)}, + {"reasonid", std::to_string(static_cast(scope))}, + {"reasonmsg", std::string{reason}}}; + auto response = request(buildCommand("clientkick", fields)); + if (!response) { + return Void::Result::fail(response.error()); + } + return {}; + } + + Void::Result::Result Client::kick(ClientId client, + std::string_view reason) + { + return kick(client, KickScope::Server, reason); + } + + Void::Result::Result + Client::download(std::string_view remotePath, + const std::filesystem::path &destination, + ChannelId channel, std::string_view password, + std::chrono::milliseconds timeout) + { + auto result = impl_->client.downloadFile( + std::string{remotePath}, destination.string(), channel.value, + std::string{password}, timeout); + if (!result.ok()) { + return Void::Result::fail(protocolError(result.errorMessage)); + } + return destination; + } + + Void::Result::Result + Client::upload(const std::filesystem::path &source, + std::string_view remotePath, ChannelId channel, + std::string_view password, bool overwrite, + std::chrono::milliseconds timeout) { if (remotePath.empty() || !std::filesystem::is_regular_file(source)) { - return Void::Result::fail(Error{Error::Code::InvalidArgument, - "upload source and remote path are required"}); + return Void::Result::fail( + Error{Error::Code::InvalidArgument, + "upload source and remote path are required"}); + } + auto result = impl_->client.uploadFile( + source.string(), std::string{remotePath}, channel.value, + std::string{password}, overwrite, timeout); + if (!result.ok()) { + return Void::Result::fail(protocolError(result.errorMessage)); } - auto result = impl_->client.uploadFile(source.string(), - std::string{remotePath}, channel.value, std::string{password}, - overwrite, timeout); - if (!result.ok()) return Void::Result::fail(protocolError(result.errorMessage)); return {}; } - Void::Result::Result Client::deleteFile( - std::string_view remotePath, ChannelId channel, std::string_view password) + Void::Result::Result + Client::deleteFile(std::string_view remotePath, ChannelId channel, + std::string_view password) { - if (remotePath.empty()) return Void::Result::fail( - Error{Error::Code::InvalidArgument, "remote path is required"}); + if (remotePath.empty()) { + return Void::Result::fail( + Error{Error::Code::InvalidArgument, "remote path is required"}); + } CommandFields fields{{"cid", std::to_string(channel.value)}, - {"cpw", std::string{password}}, {"name", std::string{remotePath}}}; + {"cpw", std::string{password}}, + {"name", std::string{remotePath}}}; auto response = request(buildCommand("ftdeletefile", fields)); - if (!response) return Void::Result::fail(response.error()); + if (!response) { + return Void::Result::fail(response.error()); + } return {}; } - Void::Result::Result - Client::sendVoice(std::span frame) - { - if (state() != ConnectionState::Connected) - return Void::Result::fail(Error{Error::Code::NotConnected, "not connected"}); - impl_->client.sendVoice(frame); - return {}; - } + Void::Result::Result + Client::sendVoice(std::span frame) + { + if (state() != ConnectionState::Connected) { + return Void::Result::fail( + Error{Error::Code::NotConnected, "not connected"}); + } + impl_->client.sendVoice(frame); + return {}; + } - Void::Result::Result - Client::sendWhisper(std::span frame, - const WhisperTargets& targets) - { - if (state() != ConnectionState::Connected) - return Void::Result::fail(Error{Error::Code::NotConnected, "not connected"}); - std::vector channels; - std::vector clients; - channels.reserve(targets.channels.size()); - clients.reserve(targets.clients.size()); - for (auto value : targets.channels) channels.push_back(value.value); - for (auto value : targets.clients) clients.push_back(value.value); - impl_->client.sendWhisper(frame, channels, clients); - return {}; - } + Void::Result::Result + Client::sendWhisper(std::span frame, + const WhisperTargets &targets) + { + if (state() != ConnectionState::Connected) { + return Void::Result::fail( + Error{Error::Code::NotConnected, "not connected"}); + } + std::vector channels; + std::vector clients; + channels.reserve(targets.channels.size()); + clients.reserve(targets.clients.size()); + for (auto value : targets.channels) { + channels.push_back(value.value); + } + for (auto value : targets.clients) { + clients.push_back(value.value); + } + impl_->client.sendWhisper(frame, channels, clients); + return {}; + } - void Client::stopVoice() noexcept { impl_->client.sendVoiceStop(); } -} + void Client::stopVoice() noexcept { impl_->client.sendVoiceStop(); } +} // namespace Void::TeamSpeak diff --git a/src/EventParser.hpp b/src/EventParser.hpp new file mode 100644 index 0000000..1e4f29e --- /dev/null +++ b/src/EventParser.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +#include +#include + +namespace Void::TeamSpeak::Detail +{ + [[nodiscard]] std::optional + parseChannelChanged(std::string_view eventName, + const CommandFields &record); +} // namespace Void::TeamSpeak::Detail diff --git a/tests/test_modern_api.cpp b/tests/test_modern_api.cpp index bdb4fd2..127cdd2 100644 --- a/tests/test_modern_api.cpp +++ b/tests/test_modern_api.cpp @@ -2,6 +2,9 @@ #include +#include "../src/EventParser.hpp" + +#include #include #include @@ -12,23 +15,47 @@ static_assert(std::is_move_constructible_v); static_assert(std::is_same_v); static_assert(std::is_same_v); static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert( + std::is_same_v); +static_assert( + std::is_same_v); static_assert(std::is_same_v>); + std::function>); static_assert(std::is_same_v>); + std::function>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); static_assert(std::is_same_v>); + std::function>); static_assert(std::is_same_v>); -static_assert(std::is_same_v().deleteFile("x")), - Void::Result::Result>); + std::function>); +static_assert(std::is_same_v().deleteFile("x")), + Void::Result::Result>); +static_assert( + std::is_same_v().ban(ClientId{1})), + Void::Result::Result>); +static_assert(std::is_same_v().createChannel( + std::declval())), + Void::Result::Result>); +static_assert(std::is_same_v().serverInfo()), + Void::Result::Result>); +static_assert(std::is_same_v().bans()), + Void::Result::Result, Error>>); +static_assert(std::is_same_v< + decltype(std::declval().clientDetails(ClientId{1})), + Void::Result::Result>); +static_assert( + std::is_same_v().subscribeAllChannels()), + Void::Result::Result>); TEST_CASE(modern_build_command_escapes_fields) { - const auto command = buildCommand("sendtextmessage", { - {"msg", "hello world|all"}, {"target", "7"}}); + const auto command = buildCommand( + "sendtextmessage", {{"msg", "hello world|all"}, {"target", "7"}}); CHECK_EQ(command, - std::string("sendtextmessage msg=hello\\sworld\\pall target=7")); + std::string("sendtextmessage msg=hello\\sworld\\pall target=7")); } TEST_CASE(strong_ids_do_not_implicitly_convert) @@ -48,3 +75,213 @@ TEST_CASE(whisper_targets_report_empty_state) targets.clients.push_back(ClientId{7}); CHECK(!targets.empty()); } + +TEST_CASE(channel_edit_options_preserve_explicit_false) +{ + ChannelEditOptions options; + CHECK(options.empty()); + options.defaultChannel = false; + CHECK(!options.empty()); +} + +TEST_CASE(channel_patch_preserves_fields_omitted_by_sparse_events) +{ + Channel cached{.id = ChannelId{7}, + .parent = ChannelId{2}, + .orderAfter = ChannelId{6}, + .name = "Original", + .topic = "Keep topic", + .description = "Keep description", + .codec = 4, + .codecQuality = 8, + .maxClients = 32, + .maxFamilyClients = 64, + .neededTalkPower = 25, + .iconId = 99, + .passwordProtected = true, + .permanent = true, + .defaultChannel = true, + .unlimitedClients = true}; + + const ChannelPatch patch{.name = "Renamed"}; + patch.applyTo(cached); + + CHECK_EQ(cached.name, std::string{"Renamed"}); + CHECK_EQ(cached.topic, std::string{"Keep topic"}); + CHECK_EQ(cached.description, std::string{"Keep description"}); + CHECK(cached.parent == std::optional{ChannelId{2}}); + CHECK(cached.orderAfter == ChannelId{6}); + CHECK(cached.codec == 4); + CHECK(cached.codecQuality == 8); + CHECK(cached.maxClients == 32); + CHECK(cached.maxFamilyClients == 64); + CHECK(cached.neededTalkPower == 25); + CHECK(cached.iconId == 99); + CHECK(cached.passwordProtected); + CHECK(cached.permanent); + CHECK(cached.defaultChannel); + CHECK(cached.unlimitedClients); +} + +TEST_CASE(channel_patch_applies_explicit_empty_zero_false_and_root_values) +{ + Channel cached{.id = ChannelId{7}, + .parent = ChannelId{2}, + .orderAfter = ChannelId{6}, + .topic = "Topic", + .description = "Description", + .maxClients = 32, + .iconId = 99, + .passwordProtected = true, + .defaultChannel = true}; + const ChannelPatch patch{.parent = std::optional{}, + .orderAfter = ChannelId{}, + .topic = "", + .description = "", + .maxClients = 0, + .iconId = 0, + .passwordProtected = false, + .defaultChannel = false}; + + CHECK(!patch.empty()); + patch.applyTo(cached); + + CHECK(!cached.parent); + CHECK(!static_cast(cached.orderAfter)); + CHECK(cached.topic.empty()); + CHECK(cached.description.empty()); + CHECK(cached.maxClients == 0); + CHECK(cached.iconId == 0); + CHECK(!cached.passwordProtected); + CHECK(!cached.defaultChannel); +} + +TEST_CASE(channel_events_decode_only_fields_present_in_the_notification) +{ + const CommandFields record{{"cid", "42"}, + {"channel_name", "Renamed"}, + {"channel_flag_default", "0"}, + {"reasonid", "10"}, + {"invokerid", "7"}}; + const auto event = + Detail::parseChannelChanged("notifychanneledited", record); + + CHECK(event.has_value()); + CHECK(event->kind == ChannelChangeKind::Updated); + CHECK(event->id == ChannelId{42}); + CHECK(event->invoker == ClientId{7}); + CHECK(event->reasonId == 10); + CHECK(event->patch.name == std::optional{"Renamed"}); + CHECK(event->patch.defaultChannel == std::optional{false}); + CHECK(!event->patch.topic); + CHECK(!event->patch.description); + CHECK(!event->patch.codec); + CHECK(!event->patch.parent); + CHECK(!event->patch.orderAfter); +} + +TEST_CASE(channel_move_events_preserve_explicit_root_and_zero_order) +{ + const CommandFields record{{"cid", "42"}, {"cpid", "0"}, {"order", "0"}}; + const auto event = + Detail::parseChannelChanged("notifychannelmoved", record); + + CHECK(event.has_value()); + CHECK(event->patch.parent.has_value()); + CHECK(!*event->patch.parent); + CHECK(event->patch.orderAfter == std::optional{ChannelId{}}); + + Channel cached{.id = ChannelId{42}, + .parent = ChannelId{2}, + .orderAfter = ChannelId{6}, + .name = "Keep"}; + event->patch.applyTo(cached); + CHECK(!cached.parent); + CHECK(!static_cast(cached.orderAfter)); + CHECK_EQ(cached.name, std::string{"Keep"}); +} + +TEST_CASE(channel_events_reject_invalid_identity_and_ignore_invalid_fields) +{ + CHECK(!Detail::parseChannelChanged("notifychannelmoved", {{"cpid", "2"}})); + CHECK(!Detail::parseChannelChanged("unrelated", {{"cid", "42"}})); + + const auto event = Detail::parseChannelChanged( + "notifychanneledited", + {{"cid", "42"}, {"channel_codec", "not-a-number"}}); + CHECK(event.has_value()); + CHECK(!event->patch.codec); +} + +TEST_CASE(ban_models_permanent_and_timed_duration) +{ + const Ban permanent{.duration = std::chrono::seconds::zero()}; + const Ban timed{.duration = std::chrono::minutes{10}}; + CHECK(permanent.permanent()); + CHECK(!timed.permanent()); +} + +TEST_CASE(remote_client_derives_public_status_flags) +{ + const RemoteClient query{ + .type = 1, .inputHardware = false, .outputHardware = false}; + CHECK(query.isQuery()); + CHECK(query.muted()); + CHECK(query.deafened()); + + const RemoteClient voice; + CHECK(!voice.isQuery()); + CHECK(!voice.muted()); + CHECK(!voice.deafened()); +} + +TEST_CASE(administration_operations_reject_invalid_identifiers) +{ + Client client; + const auto ban = client.ban(ClientId{}); + const auto unban = client.unban(BanId{}); + const auto edit = + client.editChannel(ChannelId{}, ChannelEditOptions{.name = "name"}); + const auto reorder = client.reorderChannel(ChannelId{}, std::nullopt); + const auto remove = client.deleteChannel(ChannelId{}); + const auto addGroup = + client.addServerGroupMember(ServerGroupId{}, ClientDatabaseId{1}); + const auto move = client.move(ClientId{1}, ChannelId{}); + const auto kick = client.kick(ClientId{}, KickScope::Channel, "reason"); + const auto details = client.clientDetails(ClientId{}); + + CHECK(!ban && ban.error().code == Error::Code::InvalidArgument); + CHECK(!unban && unban.error().code == Error::Code::InvalidArgument); + CHECK(!edit && edit.error().code == Error::Code::InvalidArgument); + CHECK(!reorder && reorder.error().code == Error::Code::InvalidArgument); + CHECK(!remove && remove.error().code == Error::Code::InvalidArgument); + CHECK(!addGroup && addGroup.error().code == Error::Code::InvalidArgument); + CHECK(!move && move.error().code == Error::Code::InvalidArgument); + CHECK(!kick && kick.error().code == Error::Code::InvalidArgument); + CHECK(!details && details.error().code == Error::Code::InvalidArgument); +} + +TEST_CASE(administration_operations_validate_payloads_before_transport) +{ + Client client; + const auto missingName = client.createChannel(ChannelCreateOptions{}); + const auto emptyEdit = client.editChannel(ChannelId{1}, {}); + const auto invalidQuality = client.createChannel( + ChannelCreateOptions{.name = "Talk", .codecQuality = 11}); + const auto invalidDuration = client.ban( + ClientId{1}, BanOptions{.duration = std::chrono::seconds::zero()}); + const auto emptyMessage = client.sendServerMessage(""); + const auto missingTarget = client.sendPrivateMessage(ClientId{}, "hello"); + + CHECK(!missingName && + missingName.error().code == Error::Code::InvalidArgument); + CHECK(!emptyEdit && emptyEdit.error().code == Error::Code::InvalidArgument); + CHECK(!invalidQuality && + invalidQuality.error().code == Error::Code::InvalidArgument); + CHECK(!invalidDuration && + invalidDuration.error().code == Error::Code::InvalidArgument); + CHECK(!emptyMessage && + emptyMessage.error().code == Error::Code::InvalidArgument); + CHECK(!missingTarget && + missingTarget.error().code == Error::Code::InvalidArgument); +}