Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-11 21:41:30 +03:00
1 parent 6dddf513b3
commit a7ffe73a6c
14 files changed
+700 -114

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
#include <Void/TeamSpeak/Client.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <echoion/protocol/TsClient.hpp>
#include <echoion/protocol/Command.hpp>
#include <exception>
#include <charconv>
#include <system_error>
#include <utility>
namespace Void::TeamSpeak
{
class Client::Impl {
public:
Echoion::Protocol::TsClient client;
Events events;
};
namespace
{
Error protocolError(std::string message)
{
return Error{Error::Code::Protocol, std::move(message)};
}
ConnectionState convert(Echoion::Protocol::ClientState state)
{
using Old = Echoion::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 Echoion::Protocol::CommandParams& record,
std::string_view key)
{
const auto iterator = record.find(std::string{key});
if (iterator == record.end()) return 0;
std::uint64_t value = 0;
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;
}
std::string text(const Echoion::Protocol::CommandParams& record,
std::string_view key)
{
const auto iterator = record.find(std::string{key});
return iterator == record.end() ? std::string{} : iterator->second;
}
}
Client::Client() : impl_(std::make_unique<Impl>()) {}
Client::~Client() = default;
Client::Client(Client&&) noexcept = default;
Client& Client::operator=(Client&&) noexcept = default;
void Client::setEvents(Events events)
{
impl_->events = std::move(events);
auto* impl = impl_.get();
Echoion::Protocol::TsClientCallbacks callbacks;
callbacks.onConnected = [impl] { if (impl->events.connected) impl->events.connected(); };
callbacks.onDisconnected = [impl] { if (impl->events.disconnected) impl->events.disconnected(); };
callbacks.onError = [impl](const std::string& message) {
if (impl->events.error) impl->events.error(protocolError(message));
};
callbacks.onDebug = [impl](const std::string& message) {
if (impl->events.debug) impl->events.debug(message);
};
callbacks.onCommand = [impl](const Echoion::Protocol::ParsedCommand& command) {
if (impl->events.command) impl->events.command(command.name, command.params);
};
callbacks.onVoice = [impl](std::span<const std::uint8_t> voice) {
if (impl->events.voice) impl->events.voice(voice);
};
impl_->client.setCallbacks(std::move(callbacks));
}
Void::Result::Result<void, Error> Client::connect(const ConnectOptions& options)
{
if (options.host.empty() || !options.identity) {
return Void::Result::fail(Error{Error::Code::InvalidArgument,
"host and identity are required"});
}
Echoion::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::Result::Result<CommandResponse, Error>
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<std::vector<RemoteClient>, Error>
Client::clients(std::chrono::milliseconds timeout)
{
auto response = request("clientlist -uid", timeout);
if (!response) return Void::Result::fail(response.error());
std::vector<RemoteClient> result;
result.reserve(response->records.size());
for (const auto& record : response->records) {
result.push_back(RemoteClient{
.id = ClientId{static_cast<std::uint16_t>(number(record, "clid"))},
.channel = ChannelId{number(record, "cid")},
.nickname = text(record, "client_nickname"),
.uniqueId = text(record, "client_unique_identifier")});
}
return result;
}
Void::Result::Result<std::vector<Channel>, Error>
Client::channels(std::chrono::milliseconds timeout)
{
auto response = request("channellist -flags", timeout);
if (!response) return Void::Result::fail(response.error());
std::vector<Channel> 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});
}
return result;
}
Void::Result::Result<std::vector<ServerGroup>, Error>
Client::serverGroups(std::chrono::milliseconds timeout)
{
auto response = request("servergrouplist", timeout);
if (!response) return Void::Result::fail(response.error());
std::vector<ServerGroup> result;
result.reserve(response->records.size());
for (const auto& record : response->records) {
result.push_back(ServerGroup{
.id = ServerGroupId{number(record, "sgid")},
.name = text(record, "name"),
.type = static_cast<int>(number(record, "type"))});
}
return result;
}
Void::Result::Result<void, Error>
Client::addToServerGroup(ServerGroupId group, ClientDatabaseId client)
{
Echoion::Protocol::CommandParams params{
{"sgid", std::to_string(group.value)},
{"cldbid", std::to_string(client.value)}};
auto response = request(Echoion::Protocol::buildCommand(
"servergroupaddclient", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::removeFromServerGroup(ServerGroupId group, ClientDatabaseId client)
{
Echoion::Protocol::CommandParams params{
{"sgid", std::to_string(group.value)},
{"cldbid", std::to_string(client.value)}};
auto response = request(Echoion::Protocol::buildCommand(
"servergroupdelclient", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::sendText(TextTarget target, std::string_view message)
{
Echoion::Protocol::CommandParams params;
params["targetmode"] = std::to_string(static_cast<int>(target.kind));
if (target.kind != TextTargetKind::Server)
params["target"] = std::to_string(target.id);
params["msg"] = std::string{message};
auto response = request(Echoion::Protocol::buildCommand(
"sendtextmessage", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::move(ClientId client, ChannelId channel)
{
Echoion::Protocol::CommandParams params{
{"clid", std::to_string(client.value)},
{"cid", std::to_string(channel.value)}};
auto response = request(Echoion::Protocol::buildCommand("clientmove", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<void, Error>
Client::kick(ClientId client, std::string_view reason)
{
Echoion::Protocol::CommandParams params{
{"clid", std::to_string(client.value)}, {"reasonid", "5"},
{"reasonmsg", std::string{reason}}};
auto response = request(Echoion::Protocol::buildCommand("clientkick", params));
if (!response) return Void::Result::fail(response.error());
return {};
}
Void::Result::Result<std::filesystem::path, Error>
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<void, Error>
Client::sendVoice(std::span<const std::uint8_t> frame)
{
if (state() != ConnectionState::Connected)
return Void::Result::fail(Error{Error::Code::NotConnected, "not connected"});
impl_->client.sendVoice(frame);
return {};
}
Void::Result::Result<void, Error>
Client::sendWhisper(std::span<const std::uint8_t> frame,
const WhisperTargets& targets)
{
if (state() != ConnectionState::Connected)
return Void::Result::fail(Error{Error::Code::NotConnected, "not connected"});
std::vector<std::uint64_t> channels;
std::vector<std::uint16_t> 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(); }
}
+13 -41
View File
@@ -9,7 +9,6 @@
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
@@ -136,30 +135,11 @@ namespace Echoion::Protocol
}
opts_ = opts;
// Resolve host and open a connected UDP socket.
addrinfo hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
addrinfo* res = nullptr;
std::string portStr = std::to_string(opts.port);
if (getaddrinfo(opts.host.c_str(), portStr.c_str(), &hints, &res) != 0 ||
!res) {
throw std::runtime_error("TsClient: cannot resolve host " +
opts.host);
auto connected = Void::Net::UdpSocket::connect(opts.host, opts.port);
if (!connected) {
throw std::runtime_error("TsClient: " + connected.error().message());
}
sock_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock_ < 0) {
freeaddrinfo(res);
throw std::runtime_error("TsClient: socket() failed");
}
if (::connect(sock_, res->ai_addr, res->ai_addrlen) != 0) {
freeaddrinfo(res);
::close(sock_);
sock_ = -1;
throw std::runtime_error("TsClient: connect() failed");
}
freeaddrinfo(res);
socket_ = std::move(*connected);
// Reset all per-connection state.
state_ = ClientState::Init;
@@ -192,29 +172,23 @@ namespace Echoion::Protocol
void TsClient::loopThread()
{
while (running_.load()) {
pollfd pfd{};
pfd.fd = sock_;
pfd.events = POLLIN;
int rc = ::poll(&pfd, 1, 100);
auto readable = socket_.wait_readable(std::chrono::milliseconds{100});
if (!running_.load()) {
break;
}
std::lock_guard<std::recursive_mutex> lock(mu_);
if (rc > 0 && (pfd.revents & POLLIN)) {
if (readable && *readable) {
uint8_t buf[2048];
ssize_t n = ::recv(sock_, buf, sizeof(buf), 0);
if (n > 0) {
auto received = socket_.receive(buf);
if (received && *received > 0) {
handleIncomingPacket(
std::span<const uint8_t>(buf, static_cast<size_t>(n)));
std::span<const uint8_t>(buf, *received));
}
}
resendTick();
}
std::lock_guard<std::recursive_mutex> lock(mu_);
if (sock_ >= 0) {
::close(sock_);
sock_ = -1;
}
socket_.close();
}
// ---- Outgoing ----------------------------------------------------------
@@ -333,10 +307,10 @@ namespace Echoion::Protocol
void TsClient::sendRawLocked(const std::vector<uint8_t>& raw)
{
if (sock_ < 0) {
if (!socket_.valid()) {
return;
}
::send(sock_, raw.data(), raw.size(), 0);
std::ignore = socket_.send(raw);
}
void TsClient::sendCommand(const std::string& cmd)
@@ -1175,9 +1149,7 @@ namespace Echoion::Protocol
}
state_ = ClientState::Disconnected;
running_ = false;
if (sock_ >= 0) {
::shutdown(sock_, SHUT_RDWR);
}
socket_.shutdown();
cancelPendingRequests("connection closed");
}