many different fixes

This commit is contained in:
faumaray committed 2026-02-03 05:07:15 +03:00
1 parent a583c17916
commit 53801f2b53
36 files changed
+5149 -1291

No files matched your search

+231 -118
View File
@@ -3,6 +3,7 @@
#include <echoion/api/Database.hpp>
#include <format>
#include <algorithm>
#include <thread>
namespace Echoion::Core {
@@ -50,22 +51,25 @@ Api::Result<void> Core::initialize(const std::filesystem::path& configPath) {
return std::unexpected(netResult.error());
}
// Initialize database
database_ = std::make_shared<Api::Database>();
auto dbResult = database_->initialize();
if (!dbResult) {
ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}",
dbResult.error().message));
// Not fatal - continue without database
database_ = nullptr;
} else {
ECHOION_LOG_INFO("Database initialized successfully");
}
// Initialize database alongside config file
database_ = std::make_shared<Api::Database>();
Api::DatabaseConfig dbConfig;
dbConfig.path = configPath.parent_path() / "echoion.db";
auto dbResult = database_->initialize(dbConfig);
if (!dbResult) {
ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}",
dbResult.error().message));
// Not fatal - continue without database
database_ = nullptr;
} else {
ECHOION_LOG_INFO("Database initialized successfully");
}
// Initialize music manager
musicManager_ = std::make_shared<MusicManager>();
auto musicResult = musicManager_->initialize(config_.bot, networkClient_, database_);
if (!musicResult) {
// Initialize music manager
musicManager_ = std::make_shared<MusicManager>();
auto musicResult =
musicManager_->initialize(config_.bot, networkClient_, database_);
if (!musicResult) {
return std::unexpected(musicResult.error());
}
@@ -80,89 +84,162 @@ Api::Result<void> Core::initialize(const std::filesystem::path& configPath) {
if (!pluginInterface_) return false;
// Get client info from plugin
auto clientInfo = pluginInterface_->getClient(clientId);
if (!clientInfo || !clientInfo->has_value()) {
return false;
}
// Admin category requires admin group membership
if (category == CommandCategory::Admin) {
// Check if any admin groups are configured
if (config_.server.adminGroups.empty()) {
return false; // No admin groups configured = no admin access
}
// Check if client is in any admin group
// This would need to be implemented with proper group checking
// For now, we'll rely on the TS3 plugin to provide this info
// through a future interface
return false; // Default deny until proper group check is implemented
}
return true; // Non-admin categories are allowed
auto clientInfoResult = pluginInterface_->getClient(clientId);
if (!clientInfoResult || !clientInfoResult->has_value()) {
return false;
}
auto clientInfo = clientInfoResult->value();
// Admin category requires admin group membership
if (category == CommandCategory::Admin) {
// Check if any admin groups are configured
if (config_.server.adminGroups.empty()) {
return false; // No admin groups configured = no admin access
}
// Check if server groups are available
if (clientInfo.serverGroups.empty()) {
ECHOION_LOG_WARNING("Cannot check admin permissions: server "
"groups not available for client " +
std::to_string(clientId));
return false; // Server groups not available, deny admin access
}
// Check if client is in any admin group
for (uint64_t adminGroupId : config_.server.adminGroups) {
for (uint64_t clientGroupId : clientInfo.serverGroups) {
if (adminGroupId == clientGroupId) {
return true; // Client is in an admin group
}
}
}
return false; // Client is not in any admin group
}
return true; // Non-admin categories are allowed
});
// Set up audio data callback
// Receives float audio from MusicManager (-1.0 to 1.0), converts to bytes for plugin
musicManager_->setAudioDataCallback([this](const std::span<const float> data) {
static int callCount = 0;
static auto lastLog = std::chrono::steady_clock::now();
if (pluginInterface_ && !data.empty()) {
// Convert float (-1.0 to 1.0) to int16 for TeamSpeak
// Use 32768.0f scaling but ensure we don't overflow
std::vector<int16_t> int16Data(data.size());
for (size_t i = 0; i < data.size(); ++i) {
float sample = data[i];
// Soft clipping to prevent hard distortion
if (sample > 0.95f) sample = 0.95f + (sample - 0.95f) * 0.5f;
if (sample < -0.95f) sample = -0.95f + (sample + 0.95f) * 0.5f;
int16Data[i] = static_cast<int16_t>(sample * 32767.0f);
}
// Send to plugin
auto result = pluginInterface_->sendAudioData(std::span<const uint8_t>(
reinterpret_cast<const uint8_t*>(int16Data.data()),
int16Data.size() * sizeof(int16_t)));
callCount++;
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - lastLog).count() >= 5) {
ECHOION_LOG_DEBUG(std::format("Audio callback: {} calls, {} samples, result: {}",
callCount, data.size(), result.has_value() ? "ok" : "error"));
lastLog = now;
}
}
});
// Set up subscription change callback to update whisper list
musicManager_->setSubscriptionChangeCallback([this]() {
updateWhisperList();
});
// Set initial whisper list from loaded subscriptions
updateWhisperList();
// Set up audio data callback
// Receives int16 audio from MusicManager, sends directly to plugin
musicManager_->setAudioDataCallback([this](
const std::span<const short> data) {
static int callCount = 0;
static auto lastLog = std::chrono::steady_clock::now();
// Start RPC server for Desktop/API clients
rpcServer_ = std::make_shared<RpcServer>();
uint16_t rpcPort = config_.bot.rpcPort > 0 ? config_.bot.rpcPort : 8765;
auto rpcResult = rpcServer_->start(rpcPort);
if (!rpcResult) {
ECHOION_LOG_WARNING(std::format("Failed to start RPC server: {}",
rpcResult.error().message));
// Not fatal - continue without RPC
rpcServer_.reset();
} else {
ECHOION_LOG_INFO(std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
}
if (pluginInterface_ && !data.empty()) {
// Send int16 data directly to plugin (no conversion needed)
auto result = pluginInterface_->sendAudioData(data);
startTime_ = std::chrono::system_clock::now();
initialized_ = true;
callCount++;
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - lastLog)
.count() >= 5) {
ECHOION_LOG_DEBUG(std::format(
"Audio callback: {} calls, {} samples, result: {}",
callCount, data.size(),
result.has_value() ? "ok" : "error"));
lastLog = now;
}
}
});
ECHOION_LOG_INFO("Echoion Core initialized successfully");
// Auto-connect to server if configured
// Set up subscription change callback to update whisper list
musicManager_->setSubscriptionChangeCallback(
[this]() { updateWhisperList(); });
// Set up playback start callback to update whisper list before playing
musicManager_->setPlaybackStartCallback([this]() { updateWhisperList(); });
// Set up client info callback to resolve UID and nickname from client ID
musicManager_->setClientInfoCallback(
[this](uint64_t clientId)
-> std::optional<std::pair<std::string, std::string>> {
if (!pluginInterface_) {
ECHOION_LOG_WARNING(
"ClientInfoCallback: pluginInterface is null");
return std::nullopt;
}
auto clientInfoResult = pluginInterface_->getClient(clientId);
if (!clientInfoResult || !clientInfoResult->has_value()) {
ECHOION_LOG_WARNING(std::format(
"ClientInfoCallback: getClient failed for client {}",
clientId));
return std::nullopt;
}
auto clientInfo = clientInfoResult->value();
if (!clientInfo.uniqueIdentifier) {
ECHOION_LOG_WARNING(std::format(
"ClientInfoCallback: client {} has no uniqueIdentifier",
clientId));
return std::nullopt;
}
ECHOION_LOG_DEBUG(
std::format("ClientInfoCallback: Got UID for client {}: {}",
clientId, *clientInfo.uniqueIdentifier));
return std::make_pair(*clientInfo.uniqueIdentifier,
clientInfo.nickname);
});
// Set up UID to client ID callback
musicManager_->setUidToClientIdCallback(
[this](const std::string& uid) -> std::optional<uint64_t> {
if (!pluginInterface_) {
return std::nullopt;
}
auto clients = pluginInterface_->getClients();
if (!clients) {
return std::nullopt;
}
for (const auto& client : *clients) {
if (client.uniqueIdentifier &&
*client.uniqueIdentifier == uid) {
return client.id;
}
}
return std::nullopt;
});
// Set up nickname callback
musicManager_->setNicknameCallback(
[this](uint64_t clientId) -> std::optional<std::string> {
if (!pluginInterface_) {
return std::nullopt;
}
auto clientInfoResult = pluginInterface_->getClient(clientId);
if (!clientInfoResult || !clientInfoResult->has_value()) {
return std::nullopt;
}
return clientInfoResult->value().nickname;
});
// Don't call updateWhisperList here - pluginInterface is not set yet
// It will be called when setPluginInterface is called, or when
// subscriptions change
// Start RPC server for Desktop/API clients
rpcServer_ = std::make_shared<RpcServer>();
uint16_t rpcPort = config_.bot.rpcPort > 0 ? config_.bot.rpcPort : 8765;
auto rpcResult = rpcServer_->start(rpcPort);
if (!rpcResult) {
ECHOION_LOG_WARNING(std::format("Failed to start RPC server: {}",
rpcResult.error().message));
// Not fatal - continue without RPC
rpcServer_.reset();
} else {
ECHOION_LOG_INFO(std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
}
startTime_ = std::chrono::system_clock::now();
initialized_ = true;
ECHOION_LOG_INFO(std::format("Core initialized (this={})", reinterpret_cast<uintptr_t>(this)));
unsigned int hwThreads = std::thread::hardware_concurrency();
ECHOION_LOG_INFO(std::format("Hardware concurrency: {} threads", hwThreads));
ECHOION_LOG_INFO("Echoion Core initialized successfully");
// Auto-connect to server if configured
if (!config_.server.address.empty() && pluginInterface_) {
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
config_.server.address, config_.server.port));
@@ -186,6 +263,10 @@ Api::Result<void> Core::shutdown() {
ECHOION_LOG_INFO("Shutting down Echoion Core...");
if (commandManager_) {
commandManager_->shutdown();
}
if (musicManager_) {
musicManager_->shutdown();
}
@@ -211,7 +292,7 @@ Api::Result<void> Core::shutdown() {
}
initialized_ = false;
ECHOION_LOG_INFO("Echoion Core shutdown complete");
ECHOION_LOG_INFO(std::format("Echoion Core shutdown complete (this={})", reinterpret_cast<uintptr_t>(this)));
return {};
}
@@ -559,15 +640,27 @@ void Core::unregisterEventCallback(const Api::EventCallback& callback) {
}
Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event) {
ECHOION_LOG_DEBUG(std::format("Core::onPluginEvent called (this={}, initialized={})",
reinterpret_cast<uintptr_t>(this), initialized_.load()));
if (!initialized_) {
ECHOION_LOG_WARNING(std::format("Core::onPluginEvent: Core not initialized (this={}), ignoring event type={}",
reinterpret_cast<uintptr_t>(this), static_cast<int>(event.type)));
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
// Debug logging for command events
if (event.type == Api::PluginEventType::TextMessageReceived && event.message) {
ECHOION_LOG_DEBUG(std::format("Core received message: {} from client {}",
*event.message, event.clientId));
}
switch (event.type) {
case Api::PluginEventType::TextMessageReceived:
if (event.message) {
// Check if it's a command
if (event.message->starts_with(config_.bot.commandPrefix)) {
ECHOION_LOG_DEBUG(std::format("Processing command: {} from client {}",
*event.message, event.clientId));
// Create reply callback
auto replyFunc = [this](uint64_t clientId, std::string_view message) {
if (pluginInterface_) {
@@ -596,20 +689,27 @@ Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event) {
break;
case Api::PluginEventType::ClientConnected:
ECHOION_LOG_INFO(std::format("Client {} connected", event.clientId));
break;
ECHOION_LOG_INFO(std::format(
"Client {} connected, updating whisper list", event.clientId));
if (musicManager_) {
musicManager_->onClientConnected(event.clientId);
}
// Update whisper list after client connect
updateWhisperList();
break;
case Api::PluginEventType::ClientDisconnected:
ECHOION_LOG_INFO(std::format("Client {} disconnected", event.clientId));
if (musicManager_) {
musicManager_->onClientDisconnected(event.clientId);
}
// Update whisper list after client disconnect
updateWhisperList();
break;
case Api::PluginEventType::ClientDisconnected:
ECHOION_LOG_INFO(
std::format("Client {} disconnected", event.clientId));
if (musicManager_) {
musicManager_->onClientDisconnected(event.clientId);
}
// Update whisper list after client disconnect
updateWhisperList();
break;
default:
// Forward other events to subscribers
default:
// Forward other events to subscribers
broadcastEvent(event);
break;
}
@@ -627,6 +727,12 @@ std::chrono::system_clock::time_point Core::getUptime() const {
void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface) {
pluginInterface_ = std::move(pluginInterface);
ECHOION_LOG_INFO(std::format("Plugin interface set (this={})", reinterpret_cast<uintptr_t>(this)));
// Now that we have the plugin interface, update the whisper list
// This is needed because subscriptions may have been loaded from database
// before the plugin interface was available
updateWhisperList();
}
void Core::triggerAutoConnect() {
@@ -754,18 +860,25 @@ bool Core::isAdmin(uint64_t clientId) const {
void Core::updateWhisperList() {
if (!pluginInterface_ || !musicManager_) {
return;
}
auto subscribers = musicManager_->getSubscribedClients();
std::vector<uint64_t> subscriberVec(subscribers.begin(), subscribers.end());
ECHOION_LOG_DEBUG(std::format("Updating whisper list with {} subscribers", subscriberVec.size()));
auto result = pluginInterface_->setWhisperList(subscriberVec);
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to update whisper list: {}", result.error().message));
}
ECHOION_LOG_WARNING(
"updateWhisperList: pluginInterface or musicManager is null");
return;
}
auto subscribers = musicManager_->getSubscribedClients();
std::vector<uint64_t> subscriberVec(subscribers.begin(), subscribers.end());
ECHOION_LOG_INFO(
std::format("Updating whisper list with {} online subscribers",
subscriberVec.size()));
auto result = pluginInterface_->setWhisperList(subscriberVec);
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to update whisper list: {}",
result.error().message));
} else {
ECHOION_LOG_INFO("Whisper list updated successfully");
}
}
void Core::setupRpcHandlers() {