Compare commits

...
6 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
faumarayandClaude Opus 4.8 ac88cd6eb1 Plugin: log sendTextMessage size + chunk count (debug)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 02:39:10 +03:00
faumarayandClaude Opus 4.8 a356251c83 Plugin: chunk long text replies so search/queue results arrive
requestSendPrivateTextMsg rejects over-long messages, and sendTextMessage
ignored its error return — so long replies (e.g. a 5-result search list) were
silently dropped while short ones (!help, error messages) worked. Split
messages into UTF-8-safe <=900-byte chunks on line boundaries and send each;
log the TeamSpeak error code on failure instead of swallowing it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 21:49:52 +03:00
faumarayandClaude Opus 4.8 9a61e01fda Route plugin logging through the Void::Log facade
Rewrite the ~80 ECHOION_LOG_* sites in PluginInterface/CoreLoader to
Void::Log::<level>("<Subsystem>", "{}", <expr>); add <iostream> where the
deleted LoggerInterface.hpp previously pulled it in. The plugin shares the
process-wide Void::Log sink installed by Core.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 14:10:06 +03:00
7 changed files with 661 additions and 190 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,
+54 -31
View File
@@ -1,4 +1,4 @@
#include "LoggerInterface.hpp"
#include <Void/Log/Log.hpp>
#include "dylib.hpp"
#include "echoion/plugin/CoreLoader.hpp"
#include <chrono>
@@ -21,7 +21,7 @@ namespace Echoion::Plugin
std::lock_guard<std::mutex> lock(mutex_);
if (!currentLibraryPath_.empty() &&
std::filesystem::exists(currentLibraryPath_)) {
ECHOION_LOG_INFO(std::format("Enabling auto-reload for: {}",
Void::Log::info("CoreLoader", "{}", std::format("Enabling auto-reload for: {}",
currentLibraryPath_.string()));
fileWatcher_.startWatching(currentLibraryPath_,
@@ -33,7 +33,7 @@ namespace Echoion::Plugin
{
autoReloadEnabled_ = false;
fileWatcher_.stopWatching();
ECHOION_LOG_INFO("Auto-reload disabled");
Void::Log::info("CoreLoader", "{}", "Auto-reload disabled");
}
bool CoreLoader::isAutoReloadEnabled() const noexcept
@@ -47,7 +47,7 @@ namespace Echoion::Plugin
return;
}
ECHOION_LOG_INFO(
Void::Log::info("CoreLoader", "{}",
"Core file changed, scheduling hot reload after current track...");
// Small delay to ensure file write is complete
@@ -69,7 +69,7 @@ namespace Echoion::Plugin
}
}
ECHOION_LOG_INFO(
Void::Log::info("CoreLoader", "{}",
std::format("Playback active (track: {}), deferring reload "
"until track finishes",
currentTrackId));
@@ -85,10 +85,10 @@ namespace Echoion::Plugin
// No playback, reload immediately
auto result = hotReload(currentLibraryPath_);
if (!result) {
ECHOION_LOG_ERROR(std::format("Auto hot-reload failed: {}",
Void::Log::error("CoreLoader", "{}", std::format("Auto hot-reload failed: {}",
result.error().message));
} else {
ECHOION_LOG_INFO("Auto hot-reload completed successfully");
Void::Log::info("CoreLoader", "{}", "Auto hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
@@ -129,17 +129,30 @@ namespace Echoion::Plugin
void CoreLoader::waitForTrackAndReload(
const std::filesystem::path& targetPath, const std::string& trackId)
{
ECHOION_LOG_INFO(std::format(
Void::Log::info("CoreLoader", "{}", std::format(
"Waiting for track {} to finish before reload...", trackId));
// 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;
}
}
ECHOION_LOG_INFO("Track finished, starting hot reload");
if (stopDeferredReload_.load()) {
return;
}
Void::Log::info("CoreLoader", "{}", "Track finished, starting hot reload");
// Clear pending flag
{
@@ -151,10 +164,10 @@ namespace Echoion::Plugin
// Now do the reload
auto result = hotReload(targetPath);
if (!result) {
ECHOION_LOG_ERROR(std::format("Deferred hot-reload failed: {}",
Void::Log::error("CoreLoader", "{}", std::format("Deferred hot-reload failed: {}",
result.error().message));
} else {
ECHOION_LOG_INFO("Deferred hot-reload completed successfully");
Void::Log::info("CoreLoader", "{}", "Deferred hot-reload completed successfully");
// Notify Plugin to re-register callbacks
if (hotReloadCallback_) {
hotReloadCallback_();
@@ -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();
}
@@ -238,13 +256,13 @@ namespace Echoion::Plugin
hotReloading_ = true;
ECHOION_LOG_INFO("Starting hot reload with temp file...");
Void::Log::info("CoreLoader", "{}", "Starting hot reload with temp file...");
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
Api::StateBlob stateBlob;
if (core_) {
stateBlob = core_->saveState();
ECHOION_LOG_INFO(
Void::Log::info("CoreLoader", "{}",
std::format("Saved state: version={}, size={} bytes",
stateBlob.version, stateBlob.size()));
}
@@ -300,13 +318,13 @@ namespace Echoion::Plugin
auto coreVersion = core_->getStateFormatVersion();
auto stateVersion = stateBlob.version;
ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}",
Void::Log::info("CoreLoader", "{}", std::format("Restoring state v{} to Core v{}",
stateVersion, coreVersion));
if (core_->canRestoreStateVersion(stateVersion)) {
auto restoreResult = core_->restoreState(stateBlob);
if (!restoreResult) {
ECHOION_LOG_ERROR(
Void::Log::error("CoreLoader", "{}",
std::format("Failed to restore state: {}",
restoreResult.error().message));
@@ -314,17 +332,17 @@ namespace Echoion::Plugin
if (restoreResult.error().code ==
Api::ErrorCode::IncompatibleVersion) {
// Signal user to update/restart
ECHOION_LOG_WARNING("State version incompatible. "
Void::Log::warn("CoreLoader", "{}", "State version incompatible. "
"User needs to update/restart.");
// Optionally: notify through plugin interface
}
// Continue with empty state - graceful degradation
} else {
ECHOION_LOG_INFO("State restored successfully");
Void::Log::info("CoreLoader", "{}", "State restored successfully");
}
} else {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("CoreLoader", "{}", std::format(
"Cannot restore state v{} in Core v{}. "
"Version age exceeds maximum supported ({} versions).",
stateVersion, coreVersion,
@@ -336,7 +354,7 @@ namespace Echoion::Plugin
currentLibraryPath_ = targetPath;
hotReloading_ = false;
ECHOION_LOG_INFO("Hot reload complete");
Void::Log::info("CoreLoader", "{}", "Hot reload complete");
return {};
}
@@ -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>(
@@ -411,7 +429,7 @@ namespace Echoion::Plugin
loaded_ = true;
ECHOION_LOG_INFO(std::format(
Void::Log::info("CoreLoader", "{}", std::format(
"Core library loaded (API version: {})", versionFunc()));
return {};
@@ -434,17 +452,22 @@ namespace Echoion::Plugin
return {};
}
ECHOION_LOG_INFO("Unloading core library...");
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;
}
+384 -87
View File
@@ -1,19 +1,128 @@
#include <iostream>
#include <echoion/plugin/PluginInterface.hpp>
#include "LoggerInterface.hpp"
#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
{
namespace
{
// 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,
std::size_t limit)
{
std::vector<std::string> chunks;
if (message.size() <= limit) {
chunks.push_back(message);
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()) {
if (!isBlank(current)) {
chunks.push_back(current);
}
current.clear();
}
};
std::size_t pos = 0;
while (pos < message.size()) {
const std::size_t nl = message.find('\n', pos);
std::string line = (nl == std::string::npos)
? message.substr(pos)
: message.substr(pos, nl - pos + 1);
pos = (nl == std::string::npos) ? message.size() : nl + 1;
// ":::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();
}
}
// 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;
}
} // namespace
PluginInterface::PluginInterface() = default;
PluginInterface::~PluginInterface()
{
if (initialized_) {
shutdown();
if (auto result = shutdown(); !result) {
Void::Log::warn(
"PluginInterface", "{}",
std::format("Shutdown from destructor failed: {}",
result.error().message));
}
}
}
@@ -55,7 +164,7 @@ namespace Echoion::Plugin
if (res != ERROR_ok) {
char* errorMsg = nullptr;
ts3Functions_->getErrorMessage(res, &errorMsg);
ECHOION_LOG_ERROR(std::format(
Void::Log::error("PluginInterface", "{}", std::format(
"Unable to register custom device: {}",
errorMsg));
ts3Functions_->freeMemory(errorMsg);
@@ -66,7 +175,7 @@ namespace Echoion::Plugin
});
initialized_ = true;
ECHOION_LOG_INFO("PluginInterface initialized with TeamSpeak functions "
Void::Log::info("PluginInterface", "{}", "PluginInterface initialized with TeamSpeak functions "
"(audio deferred)");
return {};
}
@@ -98,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
@@ -118,7 +228,7 @@ namespace Echoion::Plugin
ts3Functions_ = nullptr;
initialized_ = false;
ECHOION_LOG_INFO("PluginInterface shutdown");
Void::Log::info("PluginInterface", "{}", "PluginInterface shutdown");
return {};
}
@@ -233,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)
{
@@ -356,14 +630,27 @@ namespace Echoion::Plugin
"Plugin interface not initialized");
}
unsigned int error = ts3Functions_->requestSendPrivateTextMsg(
serverConnectionHandlerId_, message.c_str(),
static_cast<anyID>(targetId), nullptr);
const auto chunks = chunkMessage(message, kMaxMessageBytes);
Void::Log::debug(
"PluginInterface", "{}",
std::format("sendTextMessage: {} bytes to client {} in {} chunk(s)",
message.size(), targetId, chunks.size()));
if (error != ERROR_ok) {
return Api::fail(
Api::ErrorCode::NetworkError,
std::format("Failed to send text message: {}", error));
for (const auto& chunk : chunks) {
unsigned int error = ts3Functions_->requestSendPrivateTextMsg(
serverConnectionHandlerId_, chunk.c_str(),
static_cast<anyID>(targetId), nullptr);
if (error != ERROR_ok) {
Void::Log::warn(
"PluginInterface", "{}",
std::format("requestSendPrivateTextMsg failed (error {}) "
"for a {}-byte chunk",
error, chunk.size()));
return Api::fail(
Api::ErrorCode::NetworkError,
std::format("Failed to send text message: {}", error));
}
}
return {};
@@ -414,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
@@ -428,8 +714,7 @@ namespace Echoion::Plugin
maxSample =
std::max(maxSample, std::abs(static_cast<int>(data[i])));
}
nonZeroTotal += nonZero;
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("PluginInterface", "{}", std::format(
"sendAudioData {}: {} samples, nonZero={}/100, maxSample={}, "
"queueSize={}",
callCount, data.size(), nonZero, maxSample,
@@ -438,7 +723,7 @@ namespace Echoion::Plugin
if (!initialized_ || !ts3Functions_) {
if (callCount <= 10) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("PluginInterface", "{}", std::format(
"sendAudioData {}: not initialized", callCount));
}
return Api::fail(Api::ErrorCode::ServiceUnavailable,
@@ -447,7 +732,7 @@ namespace Echoion::Plugin
if (!audioDeviceOpen_) {
if (callCount <= 10) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("PluginInterface", "{}", std::format(
"sendAudioData {}: audio device not open", callCount));
}
return Api::fail(
@@ -506,7 +791,7 @@ namespace Echoion::Plugin
{
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.push_back(callback);
ECHOION_LOG_INFO(
Void::Log::info("PluginInterface", "{}",
std::format("Event callback registered, total callbacks: {}",
eventCallbacks_.size()));
}
@@ -523,11 +808,24 @@ namespace Echoion::Plugin
void PluginInterface::clearEventCallbacks()
{
std::lock_guard<std::mutex> lock(eventMutex_);
ECHOION_LOG_INFO(
Void::Log::info("PluginInterface", "{}",
std::format("Clearing {} event callbacks", eventCallbacks_.size()));
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)
{
@@ -570,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_) {
@@ -586,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;
@@ -607,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(
@@ -626,7 +922,7 @@ namespace Echoion::Plugin
serverConnectionHandlerId_ = 0;
char* msg;
ts3Functions_->getErrorMessage(error, &msg);
ECHOION_LOG_ERROR(std::format("GUI Connect failed: {}", msg));
Void::Log::error("PluginInterface", "{}", std::format("GUI Connect failed: {}", msg));
ts3Functions_->freeMemory(msg);
return Api::fail(
Api::ErrorCode::NetworkError,
@@ -636,11 +932,11 @@ namespace Echoion::Plugin
// Open audio device
auto audioResult = openAudioDevice();
if (!audioResult) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
"Failed to open audio device, continuing without audio");
}
ECHOION_LOG_INFO(std::format("Connecting to server {}:{} as {}",
Void::Log::info("PluginInterface", "{}", std::format("Connecting to server {}:{} as {}",
config.address, config.port,
config.nickname));
@@ -658,13 +954,13 @@ 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");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Error stopping connection: {}", error));
}
@@ -672,12 +968,12 @@ namespace Echoion::Plugin
error = ts3Functions_->destroyServerConnectionHandler(
serverConnectionHandlerId_);
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Error destroying connection handler: {}", error));
}
serverConnectionHandlerId_ = 0;
ECHOION_LOG_INFO("Disconnected from server");
Void::Log::info("PluginInterface", "{}", "Disconnected from server");
return {};
}
@@ -715,22 +1011,22 @@ namespace Echoion::Plugin
Api::Result<void> PluginInterface::registerAudioDevice()
{
ECHOION_LOG_DEBUG("registerAudioDevice called");
Void::Log::debug("PluginInterface", "{}", "registerAudioDevice called");
if (!ts3Functions_) {
ECHOION_LOG_ERROR("registerAudioDevice: ts3Functions_ is null");
Void::Log::error("PluginInterface", "{}", "registerAudioDevice: ts3Functions_ is null");
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"TS3 functions not available");
}
if (audioDeviceRegistered_) {
ECHOION_LOG_DEBUG("registerAudioDevice: already registered");
Void::Log::debug("PluginInterface", "{}", "registerAudioDevice: already registered");
return {};
}
// Check if registerCustomDevice is available (null pointer check)
if (!ts3Functions_->registerCustomDevice) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
"registerCustomDevice not available in this TeamSpeak version");
return Api::fail(Api::ErrorCode::NotSupported,
"Custom audio devices not supported by this "
@@ -738,7 +1034,7 @@ namespace Echoion::Plugin
}
// Register custom device for both capture and playback
ECHOION_LOG_DEBUG(std::format("Registering device: {} at {}Hz, {}ch",
Void::Log::debug("PluginInterface", "{}", std::format("Registering device: {} at {}Hz, {}ch",
AudioDeviceConfig::DEVICE_ID,
AudioDeviceConfig::SAMPLE_RATE,
AudioDeviceConfig::CHANNELS));
@@ -752,7 +1048,7 @@ namespace Echoion::Plugin
AudioDeviceConfig::CHANNELS);
if (error != ERROR_ok) {
ECHOION_LOG_ERROR(
Void::Log::error("PluginInterface", "{}",
std::format("registerCustomDevice failed: {}", error));
return Api::fail(
Api::ErrorCode::PluginError,
@@ -761,7 +1057,7 @@ namespace Echoion::Plugin
}
audioDeviceRegistered_ = true;
ECHOION_LOG_INFO("Audio device registered successfully");
Void::Log::info("PluginInterface", "{}", "Audio device registered successfully");
return {};
}
@@ -775,14 +1071,14 @@ namespace Echoion::Plugin
return {};
}
closeAudioDevice();
std::ignore = closeAudioDevice();
// Check if unregisterCustomDevice is available
if (!ts3Functions_->unregisterCustomDevice) {
ECHOION_LOG_WARNING("");
Void::Log::warn("PluginInterface", "{}", "");
std::cerr << std::format(
"[WARNING] unregisterCustomDevice not available")
<< std::endl;
<< '\n';
audioDeviceRegistered_ = false;
return {};
}
@@ -793,58 +1089,58 @@ 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 {};
}
Api::Result<void> PluginInterface::openAudioDevice()
{
if (auto res = closeAudioDevice(); !res.has_value()) {
ECHOION_LOG_ERROR(
Void::Log::error("PluginInterface", "{}",
std::format("Not closed devices: {}", res.error().toString()));
}
ECHOION_LOG_DEBUG("openAudioDevice called");
Void::Log::debug("PluginInterface", "{}", "openAudioDevice called");
if (!ts3Functions_) {
ECHOION_LOG_ERROR("openAudioDevice: ts3Functions_ is null");
Void::Log::error("PluginInterface", "{}", "openAudioDevice: ts3Functions_ is null");
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"TS3 functions not available");
}
if (!audioDeviceRegistered_) {
ECHOION_LOG_ERROR("openAudioDevice: device not registered");
Void::Log::error("PluginInterface", "{}", "openAudioDevice: device not registered");
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Audio device not registered");
}
if (audioDeviceOpen_) {
ECHOION_LOG_DEBUG("openAudioDevice: already open");
Void::Log::debug("PluginInterface", "{}", "openAudioDevice: already open");
return {};
}
if (serverConnectionHandlerId_ == 0) {
ECHOION_LOG_ERROR("openAudioDevice: not connected (handler=0)");
Void::Log::error("PluginInterface", "{}", "openAudioDevice: not connected (handler=0)");
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Not connected to server");
}
// Close any existing device first (in case it was left open)
ECHOION_LOG_DEBUG("Closing any existing device first...");
Void::Log::debug("PluginInterface", "{}", "Closing any existing device first...");
ts3Functions_->closePlaybackDevice(serverConnectionHandlerId_);
ts3Functions_->closeCaptureDevice(serverConnectionHandlerId_);
ECHOION_LOG_DEBUG("Opening playback device...");
Void::Log::debug("PluginInterface", "{}", "Opening playback device...");
unsigned int err = ts3Functions_->openPlaybackDevice(
serverConnectionHandlerId_, "custom", AudioDeviceConfig::DEVICE_ID);
if (err == ERROR_sound_device_already_registerred) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
"Playback device already registered, treating as open");
audioDeviceOpen_ = true;
return {};
@@ -855,14 +1151,14 @@ namespace Echoion::Plugin
ts3Functions_->getErrorMessage(err, &msg);
std::string errStr = msg;
ts3Functions_->freeMemory(msg);
ECHOION_LOG_ERROR(
Void::Log::error("PluginInterface", "{}",
std::format("openPlaybackDevice failed: {}", errStr));
return Api::fail(
Api::ErrorCode::PluginError,
std::format("Failed to open playback device: {}", errStr));
}
ECHOION_LOG_DEBUG("Opening capture device...");
Void::Log::debug("PluginInterface", "{}", "Opening capture device...");
err = ts3Functions_->openCaptureDevice(
serverConnectionHandlerId_, "custom", AudioDeviceConfig::DEVICE_ID);
@@ -871,17 +1167,17 @@ namespace Echoion::Plugin
ts3Functions_->getErrorMessage(err, &msg);
std::string errStr = msg;
ts3Functions_->freeMemory(msg);
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to open capture device: {}", errStr));
}
audioDeviceOpen_ = true;
ECHOION_LOG_INFO("Audio device opened successfully");
Void::Log::info("PluginInterface", "{}", "Audio device opened successfully");
// Configure audio profile for optimal music playback
auto profileResult = configureAudioProfile();
if (!profileResult) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to configure audio profile: {}",
profileResult.error().message));
// Continue anyway - audio will still work with default settings
@@ -903,18 +1199,18 @@ namespace Echoion::Plugin
unsigned int error =
ts3Functions_->closePlaybackDevice(serverConnectionHandlerId_);
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Error closing playback device: {}", error));
}
error = ts3Functions_->closeCaptureDevice(serverConnectionHandlerId_);
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Error closing capture device: {}", error));
}
audioDeviceOpen_ = false;
ECHOION_LOG_INFO("Audio device closed");
Void::Log::info("PluginInterface", "{}", "Audio device closed");
return {};
}
@@ -938,19 +1234,19 @@ namespace Echoion::Plugin
{
std::lock_guard<std::mutex> lock(eventMutex_);
if (eventCallbacks_.empty()) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
"No event callbacks registered, event will be dropped!");
return;
}
ECHOION_LOG_DEBUG(std::format("Broadcasting event to {} callbacks",
Void::Log::debug("PluginInterface", "{}", std::format("Broadcasting event to {} callbacks",
eventCallbacks_.size()));
for (size_t i = 0; i < eventCallbacks_.size(); ++i) {
try {
ECHOION_LOG_DEBUG(std::format("Calling callback {}...", i));
Void::Log::debug("PluginInterface", "{}", std::format("Calling callback {}...", i));
eventCallbacks_[i](event);
ECHOION_LOG_DEBUG(std::format("Callback {} completed", i));
Void::Log::debug("PluginInterface", "{}", std::format("Callback {} completed", i));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("PluginInterface", "{}",
std::format("Event callback {} error: {}", i, e.what()));
}
}
@@ -1063,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_) {
@@ -1082,7 +1379,7 @@ namespace Echoion::Plugin
Api::ErrorCode::ServiceUnavailable, "Not connected to server");
}
ECHOION_LOG_INFO("Configuring audio profile for music bot...");
Void::Log::info("PluginInterface", "{}", "Configuring audio profile for music bot...");
// Configure preprocessor settings (noise reduction, echo cancellation,
// etc.) These settings optimize the audio for music playback rather
@@ -1093,7 +1390,7 @@ namespace Echoion::Plugin
unsigned int error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "denoise", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to disable denoiser: {}", error));
}
@@ -1101,7 +1398,7 @@ namespace Echoion::Plugin
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "agc", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to disable AGC: {}", error));
}
@@ -1110,7 +1407,7 @@ namespace Echoion::Plugin
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "vad", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to disable VAD: {}", error));
}
@@ -1118,7 +1415,7 @@ namespace Echoion::Plugin
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "echocancel", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to disable echo cancellation: {}", error));
}
@@ -1126,7 +1423,7 @@ namespace Echoion::Plugin
error = ts3Functions_->setPreProcessorConfigValue(
serverConnectionHandlerId_, "echo_reduction", "false");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to disable echo reduction: {}", error));
}
@@ -1135,7 +1432,7 @@ namespace Echoion::Plugin
error = ts3Functions_->setPlaybackConfigValue(
serverConnectionHandlerId_, "typing_attenuation", "0");
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
std::format("Failed to disable typing attenuation: {}", error));
}
@@ -1144,7 +1441,7 @@ namespace Echoion::Plugin
error = ts3Functions_->setClientSelfVariableAsInt(
serverConnectionHandlerId_, CLIENT_INPUT_DEACTIVATED, 0);
if (error != ERROR_ok) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("PluginInterface", "{}", std::format(
"Failed to enable continuous transmission: {}", error));
}
const char* returnCode = nullptr;
@@ -1152,7 +1449,7 @@ namespace Echoion::Plugin
ts3Functions_->flushClientSelfUpdates(serverConnectionHandlerId_,
returnCode);
ECHOION_LOG_INFO("Audio profile configured successfully");
Void::Log::info("PluginInterface", "{}", "Audio profile configured successfully");
return {};
}
@@ -1163,7 +1460,7 @@ namespace Echoion::Plugin
"TS3 functions not available");
}
ECHOION_LOG_INFO("Checking for first-run setup...");
Void::Log::info("PluginInterface", "{}", "Checking for first-run setup...");
// Check if we have a valid client identity
// TeamSpeak requires accepting TOS on first run, which is handled by
@@ -1173,13 +1470,13 @@ namespace Echoion::Plugin
char* identity = nullptr;
unsigned int error = ts3Functions_->getClientLibVersion(&identity);
if (error != ERROR_ok || !identity) {
ECHOION_LOG_WARNING(
Void::Log::warn("PluginInterface", "{}",
"TeamSpeak client library not properly initialized");
ECHOION_LOG_INFO(
Void::Log::info("PluginInterface", "{}",
"Please ensure TeamSpeak client is properly configured:");
ECHOION_LOG_INFO(" 1. Accept the Terms of Service");
ECHOION_LOG_INFO(" 2. Create/obtain your identity");
ECHOION_LOG_INFO(" 3. Complete the initial setup wizard");
Void::Log::info("PluginInterface", "{}", " 1. Accept the Terms of Service");
Void::Log::info("PluginInterface", "{}", " 2. Create/obtain your identity");
Void::Log::info("PluginInterface", "{}", " 3. Complete the initial setup wizard");
if (identity) {
ts3Functions_->freeMemory(identity);
@@ -1193,7 +1490,7 @@ namespace Echoion::Plugin
ts3Functions_->freeMemory(identity);
}
ECHOION_LOG_INFO("TeamSpeak client is properly initialized");
Void::Log::info("PluginInterface", "{}", "TeamSpeak client is properly initialized");
return {};
}