Compare commits

...
3 Commits
Author SHA1 Message Date
faumaray 470ab507e1 making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:46:06 +03:00
faumaray 06379fbd5c Release 1.0.0
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-04 01:49:55 +03:00
faumarayandClaude Opus 4.8 446416c723 Plugin: keep <details> blocks intact when chunking replies
A reply is split into <=900-byte TeamSpeak messages; never split inside a
<details>…</details> block (each top-level block starts a fresh message and is
kept whole), otherwise a collapsible section spanning two messages would not
render.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 03:15:40 +03:00
7 changed files with 516 additions and 117 deletions

No files matched your search

+1
View File
@@ -38,6 +38,7 @@ target_link_libraries(EchoionPlugin PRIVATE
Echoion::ApiPluginInterface
Echoion::ApiLogger
Echoion::ApiCoreInterface
Void::Data
Void::Stacktrace
)
+2
View File
@@ -74,6 +74,8 @@ namespace Echoion::Plugin
// Deferred reload - waits for current track to finish
std::thread deferredReloadThread_;
std::atomic<bool> hasPendingReload_{false};
std::atomic<bool> stopDeferredReload_{false};
std::condition_variable deferredReloadCv_;
std::filesystem::path pendingReloadPath_;
std::string pendingTrackId_; // Track ID that was playing when
// reload scheduled
@@ -55,6 +55,15 @@ namespace Echoion::Plugin
getClients() override;
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
getClient(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientIp(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarPath(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
getClientAvatarUrl(uint64_t clientId) override;
[[nodiscard]] Api::Result<std::optional<std::string>>
requestClientAvatar(uint64_t clientId,
const std::string& destDir) override;
Api::Result<void> moveClient(uint64_t clientId,
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
@@ -90,6 +99,7 @@ namespace Echoion::Plugin
void clearEventCallbacks();
// TeamSpeak event handlers (called by TeamSpeak SDK)
void onConnectionEstablished(uint64_t serverConnectionHandlerId);
void onClientConnected(uint64_t serverConnectionHandlerId,
uint64_t clientId);
void onClientDisconnected(uint64_t serverConnectionHandlerId,
+33 -10
View File
@@ -134,9 +134,22 @@ namespace Echoion::Plugin
// Poll every 500ms to check if the specific track finished
// (playback may continue with next track, but we only care about THIS
// track)
// track). The wait is interruptible so the destructor can join this
// thread instead of detaching it (detaching risks use-after-free when
// the plugin unloads mid-wait).
while (isSameTrackPlaying(trackId)) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::unique_lock<std::mutex> lock(pendingReloadMutex_);
if (deferredReloadCv_.wait_for(
lock, std::chrono::milliseconds(500),
[this] { return stopDeferredReload_.load(); })) {
Void::Log::info("CoreLoader", "{}",
"Deferred hot-reload cancelled (loader shutting down)");
return;
}
}
if (stopDeferredReload_.load()) {
return;
}
Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload");
@@ -164,13 +177,18 @@ namespace Echoion::Plugin
CoreLoader::~CoreLoader()
{
// Stop any deferred reload thread
// Signal the deferred reload thread to stop and wait for it. It must
// never outlive this object: it dereferences core_ and this.
stopDeferredReload_ = true;
deferredReloadCv_.notify_all();
if (deferredReloadThread_.joinable()) {
// We can't really stop it gracefully, but we can detach it
// to avoid hanging on shutdown
deferredReloadThread_.detach();
deferredReloadThread_.join();
}
if (auto result = unload(); !result) {
Void::Log::warn("CoreLoader", "{}",
std::format("Unload from destructor failed: {}",
result.error().message));
}
unload();
cleanupTempFiles();
}
@@ -372,7 +390,7 @@ namespace Echoion::Plugin
std::cout << std::format("[Echoion] Loading core library: {}",
path.string())
<< std::endl;
<< '\n';
// Use no decorations - the path already has the correct extension
// (.ts)
library_ = std::make_unique<dylib::library>(
@@ -437,14 +455,19 @@ namespace Echoion::Plugin
Void::Log::info("CoreLoader", "{}", "Unloading core library...");
if (core_) {
core_->shutdown();
if (auto result = core_->shutdown(); !result) {
Void::Log::warn(
"CoreLoader", "{}",
std::format("Core shutdown reported failure: {}",
result.error().message));
}
core_.reset();
}
library_.reset();
loaded_ = false;
std::cout << "[Echoion] Core library unloaded" << std::endl;
std::cout << "[Echoion] Core library unloaded" << '\n';
return {};
}
+1 -1
View File
@@ -85,7 +85,7 @@ namespace Echoion::Plugin
std::cerr
<< std::format("FileWatcher callback error: {}",
e.what())
<< std::endl;
<< '\n';
}
}
}
+209 -71
View File
@@ -3,8 +3,10 @@
#include "echoion/plugin/PluginInterface.hpp"
#include "teamspeak/public_errors.h"
#include <CoreInterface.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <PluginTypes.hpp>
#include <cstdio>
#include <Types.hpp>
#include <atomic>
#include <chrono>
@@ -17,6 +19,7 @@
#include <mutex>
#include <plugin_definitions.h>
#include <thread>
#include <tuple>
#include <ts3_functions.h>
namespace Echoion::Plugin
@@ -94,10 +97,10 @@ namespace Echoion::Plugin
if (g_ts3Functions && g_ts3Functions->getConfigPath &&
g_ts3Functions->getPluginPath) {
g_ts3FunctionsReady.store(true);
std::cout << "[Echoion] TS3 function pointers set" << std::endl;
std::cout << "[Echoion] TS3 function pointers set" << '\n';
} else {
std::cerr << "[Echoion] TS3 function pointers incomplete"
<< std::endl;
<< '\n';
}
}
@@ -113,7 +116,7 @@ namespace Echoion::Plugin
pluginID = std::make_unique<char[]>(sz);
_strcpy(pluginID.get(), sz, id);
std::cout << std::format("[Echoion] Plugin ID: {}", pluginID.get())
<< std::endl;
<< '\n';
}
// Forward declarations for helper functions
@@ -134,7 +137,7 @@ namespace Echoion::Plugin
g_coreLoader->setHotReloadCallback([]() {
std::cout << "[Echoion] Auto-reload callback triggered, "
"re-registering interface..."
<< std::endl;
<< '\n';
reregisterPluginInterface();
});
}
@@ -143,16 +146,16 @@ namespace Echoion::Plugin
g_coreLoader->setConfigPath(getConfigPath());
std::cout << std::format("[Echoion] Config path: {}",
getConfigPath().string())
<< std::endl;
<< '\n';
std::cout << std::format("[Echoion] Loading Core from: {}",
getCorePath().string())
<< std::endl;
<< '\n';
auto loadResult = g_coreLoader->load(getCorePath());
if (!loadResult) {
std::cerr << std::format("[Echoion] Failed to load core: {}",
loadResult.error().message)
<< std::endl;
<< '\n';
return false;
}
@@ -161,21 +164,20 @@ namespace Echoion::Plugin
if (core && g_pluginInterface) {
core->setPluginInterface(g_pluginInterface);
// Register for plugin events from Core
// Register for plugin events from Core. Auto-connect is
// already triggered inside setPluginInterface() above.
g_pluginInterface->registerEventCallback(
[core](const Api::PluginEvent& event) {
core->onPluginEvent(event);
// Core logs dispatch failures itself.
std::ignore = core->onPluginEvent(event);
});
// Trigger auto-connect now that plugin interface is set
core->triggerAutoConnect();
}
return true;
} catch (const std::exception& e) {
std::cerr << std::format("[Echoion] Exception loading core: {}",
e.what())
<< std::endl;
<< '\n';
return false;
}
}
@@ -196,13 +198,13 @@ namespace Echoion::Plugin
if (!g_ts3FunctionsReady.load()) {
std::cerr << "[Echoion] TS3 functions not ready, aborting init"
<< std::endl;
<< '\n';
g_deferredInitRunning = false;
return;
}
std::cout << "[Echoion] Starting deferred initialization..."
<< std::endl;
<< '\n';
try {
// Create plugin interface
@@ -214,7 +216,7 @@ namespace Echoion::Plugin
std::cerr << std::format("[Echoion] Failed to initialize "
"plugin interface: {}",
result.error().message)
<< std::endl;
<< '\n';
g_deferredInitRunning = false;
return;
}
@@ -224,29 +226,29 @@ namespace Echoion::Plugin
if (!deviceResult) {
std::cout << std::format("[Echoion] Audio device skipped: {}",
deviceResult.error().message)
<< std::endl;
<< '\n';
} else {
std::cout << "[Echoion] Audio device registered" << std::endl;
std::cout << "[Echoion] Audio device registered" << '\n';
}
// Load Core library (Core will handle config loading and
// auto-connect)
if (ensureCoreLoaded()) {
std::cout << "[Echoion] Core loaded successfully" << std::endl;
std::cout << "[Echoion] Core loaded successfully" << '\n';
if (g_coreLoader) {
g_coreLoader->enableAutoReload();
}
} else {
std::cout << "[Echoion] Core failed to load" << std::endl;
std::cout << "[Echoion] Core failed to load" << '\n';
}
std::cout << "[Echoion] Initialization complete" << std::endl;
std::cout << "[Echoion] Initialization complete" << '\n';
g_deferredInitComplete = true;
} catch (const std::exception& e) {
std::cerr << std::format("[Echoion] Deferred init failed: {}",
e.what())
<< std::endl;
<< '\n';
}
g_deferredInitRunning = false;
@@ -254,7 +256,7 @@ namespace Echoion::Plugin
TS3_PLUGIN_API int ts3plugin_init()
{
std::cout << "[Echoion] Plugin init started" << std::endl;
std::cout << "[Echoion] Plugin init started" << '\n';
// Install a terminate handler that dumps a symbolized stack trace
// (with source snippets) before the process dies — invaluable for
@@ -265,7 +267,7 @@ namespace Echoion::Plugin
std::cerr << "[Echoion] FATAL: std::terminate — stack trace:\n";
const auto frames = Void::Stacktrace::capture_stacktrace();
std::cerr << Void::Stacktrace::format_stacktrace(frames)
<< std::endl;
<< '\n';
std::abort();
});
});
@@ -276,7 +278,7 @@ namespace Echoion::Plugin
TS3_PLUGIN_API void ts3plugin_shutdown()
{
std::cout << "[Echoion] Shutting down..." << std::endl;
std::cout << "[Echoion] Shutting down..." << '\n';
g_deferredInitRunning = false;
@@ -297,32 +299,35 @@ namespace Echoion::Plugin
}
}
// Teardown is best-effort: failures here can't be acted on and the
// individual calls log their own errors.
if (g_pluginInterface) {
g_pluginInterface->disconnectFromServer();
std::ignore = g_pluginInterface->disconnectFromServer();
}
if (g_coreLoader) {
g_coreLoader->disableAutoReload();
g_coreLoader->unload();
std::ignore = g_coreLoader->unload();
g_coreLoader.reset();
}
if (g_pluginInterface) {
g_pluginInterface->shutdown();
std::ignore = g_pluginInterface->shutdown();
g_pluginInterface = nullptr;
}
g_ts3Functions = nullptr;
g_ts3FunctionsReady = false;
std::cout << "[Echoion] Shutdown complete" << std::endl;
std::cout << "[Echoion] Shutdown complete" << '\n';
}
// Handle incoming text messages
TS3_PLUGIN_API void ts3plugin_onTextMessageEvent(
uint64 serverConnectionHandlerId, anyID targetMode, anyID toID,
anyID fromID, const char* fromName, const char* fromUniqueIdentifier,
const char* message, int ffIgnored)
uint64 serverConnectionHandlerId, anyID targetMode, anyID /*toID*/,
anyID fromID, const char* /*fromName*/,
const char* /*fromUniqueIdentifier*/, const char* message,
int /*ffIgnored*/)
{
anyID myID = 0;
@@ -343,7 +348,7 @@ namespace Echoion::Plugin
// Handle client connect/disconnect
TS3_PLUGIN_API void ts3plugin_onClientMoveEvent(
uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility, const char* moveMessage)
uint64 newChannelID, int /*visibility*/, const char* /*moveMessage*/)
{
if (!g_pluginInterface) {
@@ -362,9 +367,32 @@ namespace Echoion::Plugin
}
}
TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent(
// Clients that become visible without moving — e.g. everyone already
// online when the bot itself connects, or channel-subscription changes.
// Without this, subscribers present before a restart never produce a
// ClientConnected event and restored playback stays paused.
TS3_PLUGIN_API void ts3plugin_onClientMoveSubscriptionEvent(
uint64 serverConnectionHandlerId, anyID clientID, uint64 oldChannelID,
uint64 newChannelID, int visibility, const char* timeoutMessage)
uint64 newChannelID, int /*visibility*/)
{
if (!g_pluginInterface) {
return;
}
if (oldChannelID == 0) {
g_pluginInterface->onClientConnected(serverConnectionHandlerId,
clientID);
} else if (newChannelID == 0) {
g_pluginInterface->onClientDisconnected(serverConnectionHandlerId,
clientID);
}
}
TS3_PLUGIN_API void ts3plugin_onClientMoveTimeoutEvent(
uint64 serverConnectionHandlerId, anyID clientID,
uint64 /*oldChannelID*/, uint64 /*newChannelID*/, int /*visibility*/,
const char* /*timeoutMessage*/)
{
if (g_pluginInterface) {
@@ -380,52 +408,55 @@ namespace Echoion::Plugin
if (!g_coreLoader) {
std::cerr
<< "[Echoion] Cannot re-register: CoreLoader not available"
<< std::endl;
<< '\n';
return false;
}
std::cout
<< "[Echoion] Re-registering plugin interface after hot reload..."
<< std::endl;
<< '\n';
// Get the new core instance
auto core = g_coreLoader->getCore();
if (!core) {
std::cerr << "[Echoion] ERROR: Core is null!" << std::endl;
std::cerr << "[Echoion] ERROR: Core is null!" << '\n';
return false;
}
if (!g_pluginInterface) {
std::cerr << "[Echoion] ERROR: PluginInterface is null!"
<< std::endl;
<< '\n';
return false;
}
std::cout << std::format("[Echoion] New Core pointer: {}",
reinterpret_cast<uintptr_t>(core.get()))
<< std::endl;
<< '\n';
// Set the plugin interface first (before registering callbacks)
core->setPluginInterface(g_pluginInterface);
std::cout << "[Echoion] Plugin interface set on new Core" << std::endl;
std::cout << "[Echoion] Plugin interface set on new Core" << '\n';
// Clear old callbacks (they point to destroyed Core) and register new
// one
std::cout << "[Echoion] About to clear callbacks..." << std::endl;
std::cout << "[Echoion] About to clear callbacks..." << '\n';
g_pluginInterface->clearEventCallbacks();
std::cout << "[Echoion] Old event callbacks cleared" << std::endl;
std::cout << "[Echoion] Old event callbacks cleared" << '\n';
std::cout << "[Echoion] About to register new callback..." << std::endl;
std::cout << "[Echoion] About to register new callback..." << '\n';
g_pluginInterface->registerEventCallback(
[core](const Api::PluginEvent& event) {
core->onPluginEvent(event);
// Core logs dispatch failures itself.
std::ignore = core->onPluginEvent(event);
});
std::cout << "[Echoion] New event callback registered" << std::endl;
core->skip(0);
core->resume();
std::cout << "[Echoion] New event callback registered" << '\n';
// Best-effort nudge so playback resumes after the reload; failures
// only mean nothing was playing.
std::ignore = core->skip(0);
std::ignore = core->resume();
std::cout << "[Echoion] Re-registration complete - bot should respond "
"to commands"
<< std::endl;
<< '\n';
return true;
}
@@ -435,17 +466,17 @@ namespace Echoion::Plugin
{
if (!g_coreLoader) {
std::cerr << "[Echoion] Cannot reload: CoreLoader not available"
<< std::endl;
<< '\n';
return false;
}
std::cout << "[Echoion] Starting hot reload (Plugin)..." << std::endl;
std::cout << "[Echoion] Starting hot reload (Plugin)..." << '\n';
auto result = g_coreLoader->hotReload(getCorePath());
if (!result) {
std::cerr << std::format("[Echoion] Hot reload failed: {}",
result.error().message)
<< std::endl;
<< '\n';
return false;
}
@@ -455,8 +486,8 @@ namespace Echoion::Plugin
// Handle plugin commands from TS3
TS3_PLUGIN_API void
ts3plugin_onPluginCommandEvent(uint64 serverConnectionHandlerId,
const char* pluginName,
ts3plugin_onPluginCommandEvent(uint64 /*serverConnectionHandlerId*/,
const char* /*pluginName*/,
const char* command)
{
@@ -467,11 +498,48 @@ namespace Echoion::Plugin
}
}
// Global plugin menu. Item ids match the existing
// ts3plugin_onMenuItemEvent handler below (1..5).
TS3_PLUGIN_API void ts3plugin_initMenus(struct PluginMenuItem*** menuItems,
char** menuIcon)
{
struct Entry {
int id;
const char* text;
};
static constexpr Entry entries[] = {
{1, "Play / Pause"}, {2, "Skip Track"},
{3, "Stop Playback"}, {4, "Hot Reload Core"},
{5, "Connect / Disconnect"},
};
constexpr size_t count = std::size(entries);
// The client frees each item, the array and the icon string via
// ts3plugin_freeMemory, so everything must come from malloc.
auto** items = static_cast<PluginMenuItem**>(
std::malloc((count + 1) * sizeof(PluginMenuItem*)));
for (size_t i = 0; i < count; ++i) {
auto* item = static_cast<PluginMenuItem*>(
std::malloc(sizeof(PluginMenuItem)));
item->type = PLUGIN_MENU_TYPE_GLOBAL;
item->id = entries[i].id;
std::snprintf(item->text, PLUGIN_MENU_BUFSZ, "%s",
entries[i].text);
item->icon[0] = '\0';
items[i] = item;
}
items[count] = nullptr;
*menuItems = items;
*menuIcon = nullptr;
}
TS3_PLUGIN_API void ts3plugin_freeMemory(void* data) { std::free(data); }
// Menu item callbacks
TS3_PLUGIN_API void
ts3plugin_onMenuItemEvent(uint64 serverConnectionHandlerId,
enum PluginMenuType type, int menuItemID,
uint64 selectedItemID)
ts3plugin_onMenuItemEvent(uint64 /*serverConnectionHandlerId*/,
enum PluginMenuType /*type*/, int menuItemID,
uint64 /*selectedItemID*/)
{
if (!ensureCoreLoaded()) {
@@ -483,24 +551,26 @@ namespace Echoion::Plugin
return;
}
// Menu actions are fire-and-forget: Core logs failures and there is
// no channel to report them back through the TS3 menu.
switch (menuItemID) {
case 1:
{ // Play/Pause
auto state = core->getPlaybackSummary();
if (state) {
if (state->isPlaying && !state->isPaused) {
core->pause();
std::ignore = core->pause();
} else if (state->isPaused) {
core->resume();
std::ignore = core->resume();
}
}
break;
}
case 2: // Skip
core->skip(1);
std::ignore = core->skip(1);
break;
case 3: // Stop
core->stop();
std::ignore = core->stop();
break;
case 4: // Hot Reload Core
reloadCoreWithInterface();
@@ -508,7 +578,8 @@ namespace Echoion::Plugin
case 5: // Connect/Disconnect
if (g_pluginInterface) {
if (g_pluginInterface->isConnected()) {
g_pluginInterface->disconnectFromServer();
std::ignore =
g_pluginInterface->disconnectFromServer();
} else {
// Core handles connection, just trigger reconnect
if (auto result = g_pluginInterface->reconnect();
@@ -516,7 +587,7 @@ namespace Echoion::Plugin
std::cerr
<< std::format("[Echoion] Reconnect failed: {}",
result.error().message)
<< std::endl;
<< '\n';
}
}
}
@@ -524,11 +595,70 @@ namespace Echoion::Plugin
}
}
// Move the bot into teamspeak.defaultChannelId (config) once fully
// connected. No-op when the option is absent/non-numeric or the bot is
// already there.
static void joinDefaultChannel(uint64 serverConnectionHandlerId)
{
if (!g_ts3Functions || !ensureCoreLoaded()) {
return;
}
auto core = g_coreLoader->getCore();
if (!core) {
return;
}
auto configJson = core->getConfigJson();
if (!configJson) {
return;
}
auto parsed = Void::Json::parse(*configJson);
if (!parsed) {
return;
}
const auto* teamspeak = parsed->find("teamspeak");
const auto* channel =
teamspeak ? teamspeak->find("defaultChannelId") : nullptr;
if (!channel || !channel->is_string()) {
return;
}
uint64 targetChannel = 0;
try {
targetChannel = std::stoull(channel->as_string());
} catch (const std::exception&) {
std::cerr << "[Echoion] defaultChannelId is not numeric, "
"skipping auto-join"
<< '\n';
return;
}
if (targetChannel == 0) {
return;
}
anyID myId = 0;
if (g_ts3Functions->getClientID(serverConnectionHandlerId, &myId) !=
ERROR_ok) {
return;
}
uint64 currentChannel = 0;
if (g_ts3Functions->getChannelOfClient(serverConnectionHandlerId,
myId, &currentChannel) ==
ERROR_ok &&
currentChannel == targetChannel) {
return; // already there
}
std::cout << std::format("[Echoion] Auto-joining channel {}",
targetChannel)
<< '\n';
g_ts3Functions->requestClientMove(serverConnectionHandlerId, myId,
targetChannel, "", nullptr);
}
// Connection status changes
TS3_PLUGIN_API void
ts3plugin_onConnectStatusChangeEvent(uint64 serverConnectionHandlerId,
int newStatus,
unsigned int errorNumber)
unsigned int /*errorNumber*/)
{
if (g_pluginInterface) {
@@ -538,22 +668,30 @@ namespace Echoion::Plugin
switch (newStatus) {
case STATUS_CONNECTING:
std::cout << "[Echoion] Connecting..." << std::endl;
std::cout << "[Echoion] Connecting..." << '\n';
break;
case STATUS_CONNECTED:
std::cout << "[Echoion] Connected" << std::endl;
std::cout << "[Echoion] Connected" << '\n';
if (g_pluginInterface) {
g_pluginInterface->closeAudioDevice();
g_pluginInterface->openAudioDevice();
// Cycle the device best-effort; both calls log errors.
std::ignore = g_pluginInterface->closeAudioDevice();
std::ignore = g_pluginInterface->openAudioDevice();
}
break;
case STATUS_CONNECTION_ESTABLISHED:
std::cout << "[Echoion] Connection established" << std::endl;
std::cout << "[Echoion] Connection established" << '\n';
joinDefaultChannel(serverConnectionHandlerId);
// Tell the core the client list is now available so it can
// resolve online subscribers and resume a restored session.
if (g_pluginInterface) {
g_pluginInterface->onConnectionEstablished(
serverConnectionHandlerId);
}
break;
case STATUS_DISCONNECTED:
std::cout << "[Echoion] Disconnected" << std::endl;
std::cout << "[Echoion] Disconnected" << '\n';
if (g_pluginInterface) {
g_pluginInterface->closeAudioDevice();
std::ignore = g_pluginInterface->closeAudioDevice();
}
break;
}
+260 -35
View File
@@ -3,9 +3,14 @@
#include <Void/Log/Log.hpp>
#include "teamspeak/public_definitions.h"
#include "teamspeak/public_rare_definitions.h"
#include <chrono>
#include <cstring>
#include <filesystem>
#include <format>
#include <system_error>
#include <teamspeak/public_errors.h>
#include <thread>
#include <tuple>
#include <vector>
namespace Echoion::Plugin
{
@@ -14,6 +19,8 @@ namespace Echoion::Plugin
// TeamSpeak rejects over-long text messages (long replies such as
// search results or the queue silently never arrive). Split into
// UTF-8-safe chunks on line boundaries so every line is delivered.
// A ":::details … :::" collapsible block is kept whole in its own
// message — splitting it across messages would break the fold.
constexpr std::size_t kMaxMessageBytes = 900;
std::vector<std::string> chunkMessage(const std::string& message,
@@ -25,10 +32,20 @@ namespace Echoion::Plugin
return chunks;
}
// A chunk that is only whitespace (the blank lines left between two
// collapsible blocks after a split) would be sent as a blank,
// content-free message. Never emit those.
auto isBlank = [](const std::string& s) {
return s.find_first_not_of(" \t\r\n") == std::string::npos;
};
std::string current;
int detailsDepth = 0;
auto flush = [&] {
if (!current.empty()) {
chunks.push_back(current);
if (!isBlank(current)) {
chunks.push_back(current);
}
current.clear();
}
};
@@ -41,26 +58,54 @@ namespace Echoion::Plugin
: message.substr(pos, nl - pos + 1);
pos = (nl == std::string::npos) ? message.size() : nl + 1;
// Hard-split a single over-long line on a UTF-8 boundary.
while (line.size() > limit) {
std::size_t cut = limit;
while (cut > 0 &&
(static_cast<unsigned char>(line[cut]) & 0xC0) ==
0x80) {
--cut;
// ":::details …" opens a collapsible block; a line that is
// just ":::" closes it.
const bool opens = line.starts_with(":::details");
std::string_view trimmed = line;
while (!trimmed.empty() &&
(trimmed.back() == '\n' || trimmed.back() == '\r' ||
trimmed.back() == ' ' || trimmed.back() == '\t')) {
trimmed.remove_suffix(1);
}
const bool closes = (trimmed == ":::");
if (detailsDepth == 0 && !current.empty()) {
// Start each top-level <details> block in a fresh message,
// and otherwise split when adding the line would overflow.
if (opens || current.size() + line.size() > limit) {
flush();
}
if (cut == 0) {
cut = limit; // pathological line; avoid an infinite loop
}
flush();
chunks.push_back(line.substr(0, cut));
line.erase(0, cut);
}
if (current.size() + line.size() > limit) {
flush();
// Hard-split an over-long line on a UTF-8 boundary, but never
// inside a <details> block (it stays whole even if oversized).
if (detailsDepth == 0 && !opens) {
while (line.size() > limit) {
std::size_t cut = limit;
while (cut > 0 && (static_cast<unsigned char>(
line[cut]) &
0xC0) == 0x80) {
--cut;
}
if (cut == 0) {
cut = limit; // pathological line; avoid infinite loop
}
flush();
auto piece = line.substr(0, cut);
if (!isBlank(piece)) {
chunks.push_back(piece);
}
line.erase(0, cut);
}
}
current += line;
if (opens) {
++detailsDepth;
}
if (closes && detailsDepth > 0) {
--detailsDepth;
}
}
flush();
return chunks;
@@ -72,7 +117,12 @@ namespace Echoion::Plugin
PluginInterface::~PluginInterface()
{
if (initialized_) {
shutdown();
if (auto result = shutdown(); !result) {
Void::Log::warn(
"PluginInterface", "{}",
std::format("Shutdown from destructor failed: {}",
result.error().message));
}
}
}
@@ -157,15 +207,16 @@ namespace Echoion::Plugin
}
}
// Teardown steps are best-effort; each call logs its own failure.
// Close audio device
closeAudioDevice();
std::ignore = closeAudioDevice();
// Unregister audio device
unregisterAudioDevice();
std::ignore = unregisterAudioDevice();
// Disconnect from server
if (isConnected()) {
disconnectFromServer();
std::ignore = disconnectFromServer();
}
// Clear callbacks
@@ -292,6 +343,170 @@ namespace Echoion::Plugin
return info;
}
Api::Result<std::optional<std::string>>
PluginInterface::getClientIp(uint64_t clientId)
{
if (!initialized_ || !ts3Functions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized");
}
// CONNECTION_CLIENT_IP is only populated after connection info has
// been requested from the server, and only when the bot holds the
// b_client_remoteaddress_view permission. The answer arrives
// asynchronously, so request once and poll briefly.
for (int attempt = 0; attempt < 4; ++attempt) {
char* ip = nullptr;
if (ts3Functions_->getConnectionVariableAsString(
serverConnectionHandlerId_, static_cast<anyID>(clientId),
CONNECTION_CLIENT_IP, &ip) == ERROR_ok &&
ip) {
std::string address = ip;
ts3Functions_->freeMemory(ip);
if (!address.empty()) {
return std::optional<std::string>{std::move(address)};
}
}
if (attempt == 0) {
ts3Functions_->requestConnectionInfo(
serverConnectionHandlerId_, static_cast<anyID>(clientId),
nullptr);
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
return std::optional<std::string>{};
}
Api::Result<std::optional<std::string>>
PluginInterface::getClientAvatarPath(uint64_t clientId)
{
if (!initialized_ || !ts3Functions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Plugin interface not initialized");
}
if (!ts3Functions_->getAvatar) {
return std::optional<std::string>{};
}
// getAvatar answers from the TS client's local avatar cache: a file
// path once the avatar is downloaded, an empty string while a
// download is in flight, and an error when the client has no
// avatar. The cache is populated automatically for clients in view.
char path[512] = {};
const unsigned int error = ts3Functions_->getAvatar(
serverConnectionHandlerId_, static_cast<anyID>(clientId), path,
sizeof(path));
if (error != ERROR_ok || path[0] == '\0') {
return std::optional<std::string>{};
}
return std::optional<std::string>{std::string(path)};
}
Api::Result<std::optional<std::string>>
PluginInterface::getClientAvatarUrl(uint64_t clientId)
{
if (!initialized_ || !ts3Functions_ ||
!ts3Functions_->getClientVariableAsString) {
return std::optional<std::string>{};
}
char* v = nullptr;
if (ts3Functions_->getClientVariableAsString(
serverConnectionHandlerId_, static_cast<anyID>(clientId),
CLIENT_MYTS_AVATAR, &v) != ERROR_ok ||
!v) {
return std::optional<std::string>{};
}
std::string raw(v);
ts3Functions_->freeMemory(v);
// Format is "<version>,<url>" (e.g. "2,https://storage.googleapis.com/
// ts-sys-myts-avatars/<uuid>"). Take everything after the first comma.
const auto comma = raw.find(',');
if (comma == std::string::npos) {
return std::optional<std::string>{};
}
std::string url = raw.substr(comma + 1);
if (!url.starts_with("http")) {
return std::optional<std::string>{};
}
return std::optional<std::string>{std::move(url)};
}
Api::Result<std::optional<std::string>>
PluginInterface::requestClientAvatar(uint64_t clientId,
const std::string& destDir)
{
// NOTE: the plugin's Void::Log sink is separate from Core's, so plugin
// logs don't reach the journal. Until that's unified, surface the
// diagnosis through the return value — Core logs Api::fail messages as
// "requestClientAvatar -> error: <msg>".
if (!initialized_ || !ts3Functions_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"avatar: plugin not initialized");
}
if (!ts3Functions_->getClientVariableAsString ||
!ts3Functions_->requestFile) {
return Api::fail(Api::ErrorCode::NotSupported,
"avatar: SDK getClientVariableAsString/requestFile "
"unavailable");
}
// Read a client string variable into a std::string ("" on any error).
auto readVar = [&](std::size_t prop) -> std::string {
char* v = nullptr;
if (ts3Functions_->getClientVariableAsString(
serverConnectionHandlerId_, static_cast<anyID>(clientId),
prop, &v) == ERROR_ok &&
v) {
std::string s(v);
ts3Functions_->freeMemory(v);
return s;
}
return {};
};
// Legacy file-based avatar hash. Modern clients set their avatar via
// myTeamSpeak instead (CLIENT_MYTS_AVATAR), which leaves this empty —
// so read both and report what we actually have.
std::string hash = readVar(CLIENT_FLAG_AVATAR);
std::string mytsAvatar = readVar(CLIENT_MYTS_AVATAR);
if (hash.empty()) {
return Api::fail(
Api::ErrorCode::NotFound,
std::format(
"avatar: CLIENT_FLAG_AVATAR empty; CLIENT_MYTS_AVATAR "
"len={} value(≤80)='{}'",
mytsAvatar.size(), mytsAvatar.substr(0, 80)));
}
// Avatars are files in the virtual server's file repository (channel 0)
// named "/avatar_<hash>". requestFile downloads into destDir, where the
// file lands as "avatar_<hash>".
const std::string remote = "/avatar_" + hash;
const std::filesystem::path localPath =
std::filesystem::path(destDir) / ("avatar_" + hash);
std::error_code ec;
std::filesystem::create_directories(destDir, ec);
// Already downloaded (this or an earlier request finished): serve it.
if (std::filesystem::exists(localPath, ec)) {
return std::optional<std::string>{localPath.string()};
}
// Kick off the async download; the file appears in destDir when the
// transfer completes, so a later call returns the path. overwrite=1 so
// a stale partial is replaced, resume=0.
anyID transferId = 0;
const unsigned int error = ts3Functions_->requestFile(
serverConnectionHandlerId_, 0, "", remote.c_str(), 1, 0,
destDir.c_str(), &transferId, nullptr);
return Api::fail(
Api::ErrorCode::PluginError,
std::format("avatar: download started hash={} result={:#x} "
"transferId={}",
hash, error, transferId));
}
Api::Result<void> PluginInterface::moveClient(uint64_t clientId,
uint64_t channelId)
{
@@ -486,7 +701,6 @@ namespace Echoion::Plugin
PluginInterface::sendAudioData(const std::span<const short>& data)
{
static int callCount = 0;
static int nonZeroTotal = 0;
callCount++;
// Debug: Check audio data on first few calls
@@ -500,7 +714,6 @@ namespace Echoion::Plugin
maxSample =
std::max(maxSample, std::abs(static_cast<int>(data[i])));
}
nonZeroTotal += nonZero;
Void::Log::debug("PluginInterface", "{}", std::format(
"sendAudioData {}: {} samples, nonZero={}/100, maxSample={}, "
"queueSize={}",
@@ -600,6 +813,19 @@ namespace Echoion::Plugin
eventCallbacks_.clear();
}
void PluginInterface::onConnectionEstablished(
uint64_t serverConnectionHandlerId)
{
if (serverConnectionHandlerId != serverConnectionHandlerId_) {
return;
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::ConnectionEstablished,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()});
}
void PluginInterface::onClientConnected(uint64_t serverConnectionHandlerId,
uint64_t clientId)
{
@@ -642,7 +868,7 @@ namespace Echoion::Plugin
}
void PluginInterface::onTextMessageReceived(
uint64_t serverConnectionHandlerId, uint64_t targetMode,
uint64_t serverConnectionHandlerId, uint64_t /*targetMode*/,
uint64_t fromId, const std::string& message)
{
if (serverConnectionHandlerId != serverConnectionHandlerId_) {
@@ -658,7 +884,7 @@ namespace Echoion::Plugin
void PluginInterface::onVoiceDataReceived(
uint64_t serverConnectionHandlerId, uint64_t clientId,
const std::span<const uint8_t>& data)
const std::span<const uint8_t>& /*data*/)
{
if (serverConnectionHandlerId != serverConnectionHandlerId_) {
return;
@@ -679,12 +905,10 @@ namespace Echoion::Plugin
}
currentServerConfig_ = config;
// Prepare default channel array
const char* defaultChannelArray[2] = {nullptr, nullptr};
// Default channel (guiConnect takes it as a plain string)
std::string defaultChannelStr;
if (config.defaultChannelId.has_value()) {
defaultChannelStr = config.defaultChannelId.value();
defaultChannelArray[0] = defaultChannelStr.c_str();
}
unsigned int error = ts3Functions_->guiConnect(
@@ -730,8 +954,8 @@ namespace Echoion::Plugin
return {};
}
// Close audio device first
closeAudioDevice();
// Close audio device first (best-effort; it logs failures).
std::ignore = closeAudioDevice();
// Stop connection
unsigned int error = ts3Functions_->stopConnection(
serverConnectionHandlerId_, "Echoion Bot disconnecting");
@@ -847,14 +1071,14 @@ namespace Echoion::Plugin
return {};
}
closeAudioDevice();
std::ignore = closeAudioDevice();
// Check if unregisterCustomDevice is available
if (!ts3Functions_->unregisterCustomDevice) {
Void::Log::warn("PluginInterface", "{}", "");
std::cerr << std::format(
"[WARNING] unregisterCustomDevice not available")
<< std::endl;
<< '\n';
audioDeviceRegistered_ = false;
return {};
}
@@ -865,12 +1089,12 @@ namespace Echoion::Plugin
std::cerr << std::format(
"[WARNING] Failed to unregister audio device: {}",
error)
<< std::endl;
<< '\n';
}
audioDeviceRegistered_ = false;
std::cout << std::format("[INFO] Audio device unregistered")
<< std::endl;
<< '\n';
return {};
}
@@ -1135,8 +1359,9 @@ namespace Echoion::Plugin
}
void PluginInterface::onServerGroupByClientID(
uint64_t serverConnectionHandlerId, uint64_t clientDatabaseId,
const char* groupName, uint64_t serverGroupId, uint64_t clientId)
uint64_t serverConnectionHandlerId, uint64_t /*clientDatabaseId*/,
const char* /*groupName*/, uint64_t /*serverGroupId*/,
uint64_t /*clientId*/)
{
if (serverConnectionHandlerId != serverConnectionHandlerId_) {