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

+20 -30
View File
@@ -234,6 +234,8 @@ Api::Result<void> AudioDecoder::openSource(const std::string& url) {
streamInfo_.hwAccelerated = hwAccelEnabled_;
streamInfo_.hwAccelType = hwAccelType_;
streamSampleRate_ = static_cast<uint32_t>(codecContext_->sample_rate > 0 ? codecContext_->sample_rate : 48000);
if (formatContext_->duration != AV_NOPTS_VALUE) {
streamInfo_.duration = std::chrono::milliseconds(
formatContext_->duration * 1000 / AV_TIME_BASE);
@@ -326,10 +328,11 @@ Api::Result<Api::DecodedAudio> AudioDecoder::decodeFrame() {
}
static int callCount = 0;
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk, bool blocking) {
callCount++;
std::unique_lock<std::mutex> lock(mutex_);
bool AudioDecoder::getNextChunk(std::vector<short>& outChunk, bool blocking)
{
callCount++;
std::unique_lock<std::mutex> lock(mutex_);
if (blocking) {
cv_.wait(lock, [this] { return !int16Queue_.empty() || eof_.load(); });
@@ -369,7 +372,9 @@ Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position) {
avcodec_flush_buffers(codecContext_);
currentPosition_ = position;
// Clear pending audio data
int16Queue_.clear();
std::queue<Api::DecodedAudio> empty;
std::swap(decodedQueue_, empty);
@@ -384,6 +389,9 @@ Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const {
}
std::chrono::milliseconds AudioDecoder::getPosition() const {
// Return last known position from FFmpeg decoding
// Note: This is updated when frames are decoded, not when played
// For accurate playback position, use MusicManager::getPlaybackPosition()
return currentPosition_;
}
@@ -565,7 +573,8 @@ Api::Result<void> AudioDecoder::readPacket() {
Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
std::vector<float> outputBuffer(outSamples * outputChannels_);
// Use int16_t for direct output (no float conversion)
std::vector<int16_t> outputBuffer(outSamples * outputChannels_);
uint8_t* outData = reinterpret_cast<uint8_t*>(outputBuffer.data());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
@@ -584,7 +593,8 @@ Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
}
Api::DecodedAudio audio;
audio.view = Api::FloatAudioView(outputBuffer.data(), outputBuffer.size(), outputChannels_);
audio.samples = std::move(outputBuffer);
audio.view = Api::Int16AudioView(audio.samples.data(), audio.samples.size(), outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
@@ -592,29 +602,9 @@ Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFramePooled() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
auto pooledBuffer = Api::AudioBufferPool::instance().acquireBuffer();
if (!pooledBuffer) return convertFrame();
uint8_t* outData = reinterpret_cast<uint8_t*>(pooledBuffer.get());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.pooledSamples = std::move(pooledBuffer);
audio.view = Api::FloatAudioView(audio.pooledSamples.get(), converted * outputChannels_, outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
// Using int16_t (short) for direct TeamSpeak compatibility
// Both pooled and non-pooled versions now use the same int16 format
return convertFrame();
}
void AudioDecoder::cleanupFfmpeg() {
+205 -15
View File
@@ -1,11 +1,12 @@
#include "echoion/core/CommandManager.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/CommandManager.hpp"
#include "echoion/core/Logger.hpp"
#include <echoion/core/commands/Commands.hpp>
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/commands/Command.hpp"
#include <algorithm>
#include <sstream>
#include <echoion/core/commands/Commands.hpp>
#include <format>
#include <sstream>
namespace Echoion::Core {
@@ -89,6 +90,122 @@ public:
CommandManager::CommandManager() {
registerBuiltinCommands();
registerHelpCommand();
startThreadPool();
}
CommandManager::~CommandManager() {
shutdown();
}
void CommandManager::shutdown() {
{
std::lock_guard<std::mutex> lock(queueMutex_);
shutdown_ = true;
}
queueCv_.notify_all();
for (auto& thread : workerThreads_) {
if (thread.joinable()) {
thread.join();
}
}
workerThreads_.clear();
}
void CommandManager::startThreadPool() {
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
workerThreads_.emplace_back([this]() {
processCommandQueue();
});
}
ECHOION_LOG_INFO(std::format("CommandManager thread pool started with {} workers", THREAD_POOL_SIZE));
}
void CommandManager::processCommandQueue() {
while (true) {
CommandTask task;
{
std::unique_lock<std::mutex> lock(queueMutex_);
queueCv_.wait(lock, [this] { return shutdown_ || !commandQueue_.empty(); });
if (shutdown_ && commandQueue_.empty()) {
return;
}
task = std::move(commandQueue_.front());
commandQueue_.pop();
}
// Execute the command
executeCommandAsync(std::move(task));
}
}
void CommandManager::executeCommandAsync(CommandTask task) {
try {
// Re-parse the command (same logic as dispatch)
std::string_view message = task.message;
if (!message.starts_with(prefix_)) {
return;
}
// Skip prefix and trim
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) return;
input = input.substr(start);
// Split command and args
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
std::string argsStr;
if (spacePos != std::string_view::npos) {
size_t argStart = input.find_first_not_of(" \t", spacePos);
if (argStart != std::string_view::npos) {
argsStr = std::string(input.substr(argStart));
}
}
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return;
}
command = it->second;
}
// Check permissions
if (!canExecuteCommand(task.clientId, command)) {
task.replyFunc("You don't have permission to use this command.");
return;
}
// Execute command
CommandContext ctx{
.clientId = task.clientId,
.prefix = prefix_,
.args = std::move(argsStr),
.invokerName = task.invokerName,
.musicManager = task.musicManager,
.replyCallback = std::move(task.replyFunc)
};
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Async command execution error: {}", e.what()));
try {
task.replyFunc("An error occurred while executing the command.");
} catch (...) {}
}
}
bool CommandManager::dispatch(
@@ -110,6 +227,73 @@ bool CommandManager::dispatch(
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
// Convert to lowercase for lookup
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
// Check if command exists
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return false;
}
command = it->second;
}
// Check permissions synchronously (fast check)
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true; // Command was found but not allowed
}
// Queue the command for async execution
CommandTask task{
.clientId = clientId,
.message = std::string(message),
.musicManager = musicManager,
.replyFunc = std::move(replyFunc),
.invokerName = std::string(invokerName)
};
{
std::lock_guard<std::mutex> lock(queueMutex_);
if (shutdown_) {
return false;
}
commandQueue_.push(std::move(task));
}
queueCv_.notify_one();
return true;
}
bool CommandManager::dispatchSync(
uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName) {
if (!message.starts_with(prefix_)) {
return false;
}
// Skip prefix and trim leading whitespace
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
@@ -141,11 +325,12 @@ bool CommandManager::dispatch(
// Check permissions
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true; // Command was found but not allowed
return true;
}
CommandContext ctx{
.clientId = clientId,
.prefix = prefix_,
.args = std::move(argsStr),
.invokerName = invokerName,
.musicManager = musicManager,
@@ -155,7 +340,8 @@ bool CommandManager::dispatch(
try {
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Command execution error [{}]: {}", cmdKey, e.what()));
ECHOION_LOG_ERROR(
std::format("Command execution error [{}]: {}", cmdKey, e.what()));
ctx.reply("An unexpected error occurred. Our team has been notified.");
}
@@ -216,12 +402,13 @@ bool CommandManager::canExecuteCommand(uint64_t clientId, const CommandPtr& cmd)
}
// Check permission via callback if set
if (permissionCheck_) {
return permissionCheck_(clientId, cmd->getCategory());
}
// Default: deny admin commands if no checker configured
return false;
if (permissionCheck_ && (cmd->requiresAdmin() ||
cmd->getCategory() == CommandCategory::Admin)) {
return permissionCheck_(clientId, cmd->getCategory());
}
// Default: deny admin commands if no checker configured
return false;
}
void CommandManager::setPrefix(std::string_view prefix) {
@@ -245,9 +432,9 @@ void CommandManager::registerBuiltinCommands() {
registerCommand<ResumeCommand>("resume");
registerCommand<StopCommand>("stop");
registerCommand<SkipCommand>("skip");
registerCommand<SeekCommand>("seek");
registerCommand<VolumeCommand>("volume");
registerCommand<QueueCommand>("queue");
// registerCommand<SeekCommand>("seek");
registerCommand<VolumeCommand>("volume");
registerCommand<QueueCommand>("queue");
registerCommand<RemoveCommand>("remove");
registerCommand<ClearCommand>("clear");
registerCommand<MoveCommand>("move");
@@ -260,6 +447,9 @@ void CommandManager::registerBuiltinCommands() {
registerCommand<ReloadConfigCommand>("reloadconfig");
registerCommand<SubscribeCommand>("subscribe");
registerCommand<UnsubscribeCommand>("unsubscribe");
registerCommand<SubscribersCommand>("subscribers");
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
}
void CommandManager::registerHelpCommand() {
+24 -1
View File
@@ -26,6 +26,9 @@ struct BotConfigJson {
uint32_t trackTimeout = 30000;
std::optional<std::string> youtubeCookiesPath;
std::optional<std::string> cookiesFromBrowser;
uint32_t ytDlpMaxConcurrent = 4;
bool ytDlpAsyncEnabled = true;
bool enableUrlShortening = true;
};
struct ServerConfigJson {
@@ -77,7 +80,10 @@ template<> struct glz::meta<Echoion::Core::BotConfigJson> {
"maxQueueSize", &T::maxQueueSize,
"trackTimeout", &T::trackTimeout,
"youtubeCookiesPath", &T::youtubeCookiesPath,
"cookiesFromBrowser", &T::cookiesFromBrowser
"cookiesFromBrowser", &T::cookiesFromBrowser,
"ytDlpMaxConcurrent", &T::ytDlpMaxConcurrent,
"ytDlpAsyncEnabled", &T::ytDlpAsyncEnabled,
"enableUrlShortening", &T::enableUrlShortening
);
};
@@ -189,6 +195,13 @@ Api::Result<Api::AppConfig> ConfigLoader::loadFromFile(const std::filesystem::pa
if (jsonConfig.bot.cookiesFromBrowser.has_value()) {
config.bot.cookiesFromBrowser = jsonConfig.bot.cookiesFromBrowser;
}
// yt-dlp settings
config.bot.ytDlpMaxConcurrent = std::min(static_cast<size_t>(jsonConfig.bot.ytDlpMaxConcurrent), size_t(8));
config.bot.ytDlpAsyncEnabled = jsonConfig.bot.ytDlpAsyncEnabled;
// URL shortening settings
config.bot.enableUrlShortening = jsonConfig.bot.enableUrlShortening;
// Server config
config.server.address = jsonConfig.server.address;
@@ -248,6 +261,13 @@ Api::Result<void> ConfigLoader::saveToFile(const std::filesystem::path& path, co
if (config.bot.cookiesFromBrowser.has_value()) {
jsonConfig.bot.cookiesFromBrowser = *config.bot.cookiesFromBrowser;
}
// yt-dlp settings
jsonConfig.bot.ytDlpMaxConcurrent = static_cast<uint32_t>(config.bot.ytDlpMaxConcurrent);
jsonConfig.bot.ytDlpAsyncEnabled = config.bot.ytDlpAsyncEnabled;
// URL shortening settings
jsonConfig.bot.enableUrlShortening = config.bot.enableUrlShortening;
// Server config
jsonConfig.server.address = config.server.address;
@@ -316,6 +336,9 @@ Api::AppConfig ConfigLoader::createDefaultConfig() {
config.bot.allowPlaylistImports = true;
config.bot.maxQueueSize = 100;
config.bot.trackTimeout = std::chrono::milliseconds(30000);
config.bot.ytDlpMaxConcurrent = 4;
config.bot.ytDlpAsyncEnabled = true;
config.bot.enableUrlShortening = true;
// Default server config
config.server.address = "localhost";
+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() {
+104 -20
View File
@@ -3,6 +3,7 @@
#include <sqlite3.h>
#include <format>
#include <cstring>
#include <shared_mutex>
namespace Echoion::Api {
@@ -18,10 +19,15 @@ public:
Database::Database() : impl_(std::make_unique<DatabaseImpl>()) {}
Database::~Database() {
shutdown();
// Only shutdown if not already shut down
if (!shutdown_.load()) {
shutdown();
}
}
Result<void> Database::initialize(const DatabaseConfig& config) {
std::unique_lock<std::shared_mutex> lock(mutex_);
impl_->config = config;
int rc = sqlite3_open(config.path.c_str(), &impl_->db);
@@ -30,7 +36,7 @@ Result<void> Database::initialize(const DatabaseConfig& config) {
std::format("Failed to open database: {}", sqlite3_errmsg(impl_->db))));
}
// Enable WAL mode
// Enable WAL mode for better concurrency
if (config.walMode) {
char* errMsg = nullptr;
sqlite3_exec(impl_->db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, &errMsg);
@@ -41,8 +47,11 @@ Result<void> Database::initialize(const DatabaseConfig& config) {
sqlite3_busy_timeout(impl_->db,
static_cast<int>(config.busyTimeout.count()));
// Run migrations
// Run migrations (without lock to avoid deadlock, since migrate() will acquire lock)
lock.unlock();
auto result = migrate();
lock.lock();
if (!result) {
return result;
}
@@ -53,6 +62,13 @@ Result<void> Database::initialize(const DatabaseConfig& config) {
}
void Database::shutdown() {
// Check if already shut down to avoid mutex operations after destruction
if (shutdown_.exchange(true)) {
return; // Already shut down
}
std::unique_lock<std::shared_mutex> lock(mutex_);
if (impl_->db) {
sqlite3_close(impl_->db);
impl_->db = nullptr;
@@ -61,6 +77,10 @@ void Database::shutdown() {
}
bool Database::isInitialized() const {
if (shutdown_.load()) {
return false;
}
std::shared_lock<std::shared_mutex> lock(mutex_);
return impl_->initialized;
}
@@ -171,7 +191,35 @@ Result<void> Database::migrate() {
ECHOION_LOG_INFO("Database migration 1 applied");
}
impl_->version = 1;
// Migration 2: Fix subscriptions table to use UID instead of client_id
if (currentVersion < 2) {
const char* migration2 = R"(
DROP TABLE IF EXISTS subscriptions;
CREATE TABLE subscriptions (
uid TEXT PRIMARY KEY,
nickname TEXT,
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_subscriptions_uid ON subscriptions(uid);
)";
sqlite3_exec(impl_->db, migration2, nullptr, nullptr, &errMsg);
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
}
sqlite3_exec(impl_->db,
"INSERT INTO schema_migrations (version) VALUES (2)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO("Database migration 2 applied: subscriptions now use UID");
}
impl_->version = 2;
return {};
}
@@ -182,6 +230,7 @@ int Database::getCurrentVersion() const {
// Playlist operations
Result<uint64_t> Database::createPlaylist(const std::string& name,
const std::string& description, uint64_t createdBy, bool isPublic) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT INTO playlists (name, description, created_by, is_public)
@@ -212,6 +261,8 @@ Result<uint64_t> Database::createPlaylist(const std::string& name,
}
Result<std::optional<Playlist>> Database::getPlaylist(uint64_t id) {
std::shared_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
SELECT id, name, description, created_by, created_at, updated_at, is_public
FROM playlists WHERE id = ?;
@@ -272,6 +323,7 @@ Result<std::optional<Playlist>> Database::getPlaylist(uint64_t id) {
}
Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId) {
std::shared_lock<std::shared_mutex> lock(mutex_);
std::vector<Playlist> playlists;
const char* sql = R"(
@@ -303,6 +355,7 @@ Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId) {
}
Result<void> Database::deletePlaylist(uint64_t id) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = "DELETE FROM playlists WHERE id = ?;";
sqlite3_stmt* stmt;
@@ -320,6 +373,7 @@ Result<void> Database::deletePlaylist(uint64_t id) {
Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
const TrackInfo& track, uint32_t position) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT INTO playlist_tracks
@@ -354,7 +408,10 @@ Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
// Playback history
Result<void> Database::recordPlayback(const TrackInfo& track,
uint64_t playedBy, std::chrono::milliseconds duration, bool completed) {
uint64_t playedBy,
std::chrono::milliseconds duration,
bool completed) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT INTO playback_history
@@ -382,7 +439,10 @@ Result<void> Database::recordPlayback(const TrackInfo& track,
}
Result<std::vector<PlaybackHistoryEntry>> Database::getPlaybackHistory(
uint64_t userId, size_t limit, size_t offset) {
uint64_t userId,
size_t limit,
size_t offset) {
std::shared_lock<std::shared_mutex> lock(mutex_);
std::vector<PlaybackHistoryEntry> history;
@@ -422,6 +482,7 @@ Result<std::vector<PlaybackHistoryEntry>> Database::getPlaybackHistory(
// Favorites
Result<void> Database::addFavorite(uint64_t userId, const TrackInfo& track) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT OR REPLACE INTO user_favorites
(user_id, track_url, track_title, track_artist)
@@ -446,6 +507,7 @@ Result<void> Database::addFavorite(uint64_t userId, const TrackInfo& track) {
}
Result<void> Database::removeFavorite(uint64_t userId, const std::string& trackUrl) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = "DELETE FROM user_favorites WHERE user_id = ? AND track_url = ?;";
sqlite3_stmt* stmt;
@@ -464,6 +526,7 @@ Result<void> Database::removeFavorite(uint64_t userId, const std::string& trackU
}
Result<bool> Database::isFavorite(uint64_t userId, const std::string& trackUrl) {
std::shared_lock<std::shared_mutex> lock(mutex_);
const char* sql =
"SELECT 1 FROM user_favorites WHERE user_id = ? AND track_url = ? LIMIT 1;";
@@ -483,6 +546,7 @@ Result<bool> Database::isFavorite(uint64_t userId, const std::string& trackUrl)
}
Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId) {
std::shared_lock<std::shared_mutex> lock(mutex_);
std::vector<FavoriteTrack> favorites;
const char* sql = R"(
@@ -515,6 +579,7 @@ Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId) {
// Maintenance
Result<void> Database::trimHistory(size_t keepCount) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
DELETE FROM playback_history
WHERE id NOT IN (
@@ -541,6 +606,7 @@ Result<void> Database::trimHistory(size_t keepCount) {
}
Result<void> Database::clearUserData(uint64_t userId) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql1 = "DELETE FROM user_favorites WHERE user_id = ?;";
const char* sql2 = "DELETE FROM playback_history WHERE played_by = ?;";
const char* sql3 = "DELETE FROM playlists WHERE created_by = ?;";
@@ -559,15 +625,17 @@ Result<void> Database::clearUserData(uint64_t userId) {
}
Result<void> Database::vacuum() {
std::unique_lock<std::shared_mutex> lock(mutex_);
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
return {};
}
// Subscriptions
Result<void> Database::addSubscriber(uint64_t clientId) {
Result<void> Database::addSubscriber(const std::string& uid, const std::string& nickname) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT OR REPLACE INTO subscriptions (client_id)
VALUES (?);
INSERT OR REPLACE INTO subscriptions (uid, nickname, subscribed_at)
VALUES (?, ?, CURRENT_TIMESTAMP);
)";
sqlite3_stmt* stmt;
@@ -576,15 +644,17 @@ Result<void> Database::addSubscriber(uint64_t clientId) {
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, nickname.c_str(), -1, SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::removeSubscriber(uint64_t clientId) {
const char* sql = "DELETE FROM subscriptions WHERE client_id = ?;";
Result<void> Database::removeSubscriber(const std::string& uid) {
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = "DELETE FROM subscriptions WHERE uid = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
@@ -592,16 +662,17 @@ Result<void> Database::removeSubscriber(uint64_t clientId) {
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<bool> Database::isSubscriber(uint64_t clientId) {
Result<bool> Database::isSubscriber(const std::string& uid) {
std::shared_lock<std::shared_mutex> lock(mutex_);
const char* sql =
"SELECT 1 FROM subscriptions WHERE client_id = ? LIMIT 1;";
"SELECT 1 FROM subscriptions WHERE uid = ? LIMIT 1;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
@@ -609,17 +680,18 @@ Result<bool> Database::isSubscriber(uint64_t clientId) {
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
bool found = sqlite3_step(stmt) == SQLITE_ROW;
sqlite3_finalize(stmt);
return found;
}
Result<std::vector<uint64_t>> Database::getAllSubscribers() {
std::vector<uint64_t> subscribers;
Result<std::vector<Database::SubscriberInfo>> Database::getAllSubscribers() {
std::shared_lock<std::shared_mutex> lock(mutex_);
std::vector<SubscriberInfo> subscribers;
const char* sql = "SELECT client_id FROM subscriptions;";
const char* sql = "SELECT uid, nickname, subscribed_at FROM subscriptions;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
@@ -628,14 +700,26 @@ Result<std::vector<uint64_t>> Database::getAllSubscribers() {
}
while (sqlite3_step(stmt) == SQLITE_ROW) {
subscribers.push_back(static_cast<uint64_t>(sqlite3_column_int64(stmt, 0)));
SubscriberInfo info;
info.uid = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
info.nickname = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
info.subscribedAt = std::chrono::system_clock::from_time_t(
sqlite3_column_int64(stmt, 2));
subscribers.push_back(std::move(info));
}
sqlite3_finalize(stmt);
return subscribers;
}
Result<void> Database::clearAllSubscribers() {
std::unique_lock<std::shared_mutex> lock(mutex_);
sqlite3_exec(impl_->db, "DELETE FROM subscriptions;", nullptr, nullptr, nullptr);
return {};
}
Result<size_t> Database::getSubscriberCount() {
std::shared_lock<std::shared_mutex> lock(mutex_);
const char* sql = "SELECT COUNT(*) FROM subscriptions;";
sqlite3_stmt* stmt;
+95 -9
View File
@@ -13,6 +13,9 @@ Logger::Logger(std::string_view logDir, std::string_view baseName)
std::error_code ec;
std::filesystem::create_directories(logDir_, ec);
// Ensure history directory exists
ensureHistoryDirExists();
// Open log files for each level
openLogFiles();
@@ -39,6 +42,12 @@ Logger::~Logger() {
}
}
void Logger::ensureHistoryDirExists() {
std::error_code ec;
auto historyDir = logDir_ / "history";
std::filesystem::create_directories(historyDir, ec);
}
void Logger::openLogFiles() {
std::lock_guard<std::mutex> lock(fileMutex_);
@@ -161,27 +170,94 @@ void Logger::writeToFile(Api::LogLevel level, const std::string& formattedEntry)
}
}
void Logger::moveToHistory(const std::filesystem::path& filePath) {
ensureHistoryDirExists();
auto historyDir = logDir_ / "history";
auto fileName = filePath.filename().string();
// Generate timestamp for unique filename
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::tm tm;
localtime_r(&time_t, &tm);
std::string timestamp = std::format("{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
auto historyPath = historyDir / std::format("{}.{}", fileName, timestamp);
std::error_code ec;
std::filesystem::rename(filePath, historyPath, ec);
if (!ec) {
// Clean up old history files (keep last 30)
cleanupOldLogs();
}
}
void Logger::cleanupOldLogs() {
ensureHistoryDirExists();
auto historyDir = logDir_ / "history";
if (!std::filesystem::exists(historyDir)) {
return;
}
// Get all files in history directory
std::vector<std::pair<std::filesystem::path, std::filesystem::file_time_type>> files;
for (const auto& entry : std::filesystem::directory_iterator(historyDir)) {
if (entry.is_regular_file()) {
files.emplace_back(entry.path(), entry.last_write_time());
}
}
// Sort by modification time (oldest first)
std::sort(files.begin(), files.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
// Keep only the most recent 30 files
const size_t maxHistoryFiles = 30;
if (files.size() > maxHistoryFiles) {
std::error_code ec;
for (size_t i = 0; i < files.size() - maxHistoryFiles; ++i) {
std::filesystem::remove(files[i].first, ec);
}
}
}
void Logger::rotateIfNeeded(Api::LogLevel level) {
std::lock_guard<std::mutex> lock(fileMutex_);
auto maxSize = maxFileSize_.load();
auto maxFiles = maxFiles_.load();
// Check level-specific file
auto it = levelFiles_.find(level);
if (it != levelFiles_.end() && it->second.size >= maxSize) {
it->second.stream.close();
// Rotate: move current to .1, .1 to .2, etc.
auto basePath = it->second.path;
for (int i = maxFiles_.load() - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}" , basePath.string(), i);
auto newPath = std::format("{}.{}" , basePath.string(), i + 1);
// Move oldest to history if at max files
auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles);
if (std::filesystem::exists(oldestPath)) {
moveToHistory(oldestPath);
}
// Rotate: move .4 to .5, .3 to .4, etc.
for (int i = maxFiles - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}", basePath.string(), i);
auto newPath = std::format("{}.{}", basePath.string(), i + 1);
if (std::filesystem::exists(oldPath)) {
std::filesystem::rename(oldPath, newPath);
}
}
// Move current to .1
if (std::filesystem::exists(basePath)) {
std::filesystem::rename(basePath, std::format("{}.1" , basePath.string()));
std::filesystem::rename(basePath, std::format("{}.1", basePath.string()));
}
// Reopen
@@ -195,15 +271,25 @@ void Logger::rotateIfNeeded(Api::LogLevel level) {
combinedFile_.stream.close();
auto basePath = combinedFile_.path;
for (int i = maxFiles_.load() - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}" , basePath.string(), i);
auto newPath = std::format("{}.{}" , basePath.string(), i + 1);
// Move oldest to history if at max files
auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles);
if (std::filesystem::exists(oldestPath)) {
moveToHistory(oldestPath);
}
// Rotate: move .4 to .5, .3 to .4, etc.
for (int i = maxFiles - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}", basePath.string(), i);
auto newPath = std::format("{}.{}", basePath.string(), i + 1);
if (std::filesystem::exists(oldPath)) {
std::filesystem::rename(oldPath, newPath);
}
}
// Move current to .1
if (std::filesystem::exists(basePath)) {
std::filesystem::rename(basePath, std::format("{}.1" , basePath.string()));
std::filesystem::rename(basePath, std::format("{}.1", basePath.string()));
}
combinedFile_.stream.open(basePath, std::ios::app);
+8 -8
View File
@@ -10,9 +10,9 @@ AudioBufferPool& AudioBufferPool::instance() {
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
bufferSize_ = bufferSize;
pool_ = std::make_unique<MemoryPool<float>>(bufferSize, poolSize);
ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} MB)",
poolSize, bufferSize, (bufferSize * poolSize * sizeof(float)) / (1024 * 1024)));
pool_ = std::make_unique<MemoryPool<int16_t>>(bufferSize, poolSize);
ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
poolSize, bufferSize, (bufferSize * poolSize * sizeof(int16_t)) / 1024));
}
void AudioBufferPool::shutdown() {
@@ -20,18 +20,18 @@ void AudioBufferPool::shutdown() {
ECHOION_LOG_INFO("AudioBufferPool shutdown");
}
PooledPtr<float> AudioBufferPool::acquireBuffer() {
PooledPtr<int16_t> AudioBufferPool::acquireBuffer() {
if (!pool_) {
return PooledPtr<float>();
return PooledPtr<int16_t>();
}
float* ptr = pool_->acquire();
int16_t* ptr = pool_->acquire();
if (!ptr) {
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
return PooledPtr<float>();
return PooledPtr<int16_t>();
}
return PooledPtr<float>(ptr, pool_.get());
return PooledPtr<int16_t>(ptr, pool_.get());
}
size_t AudioBufferPool::getAvailableBuffers() const {
+1377 -569
View File
File diff suppressed because it is too large. Load diff
+4 -6
View File
@@ -339,8 +339,8 @@ Api::Result<Api::HttpResponse> NetworkClient::executeRequest(const Api::HttpRequ
asio::io_context ioc;
ssl::context ctx(ssl::context::tlsv12_client);
ctx.set_default_verify_paths();
// Resolve timeout
ctx.set_verify_mode(ssl::verify_none);
// Resolve timeout
auto timeout = std::chrono::seconds(req.timeout.count());
Api::HttpResponse response;
@@ -433,8 +433,7 @@ Api::HttpResponse NetworkClient::executeWithHttpProxy(
// Upgrade socket to SSL
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
stream.set_verify_mode(ssl::verify_peer);
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
// SSL verification mode is already set in ctx (verify_none)
// Perform SSL handshake
stream.handshake(ssl::stream_base::client);
@@ -609,8 +608,7 @@ Api::HttpResponse NetworkClient::executeWithSocks5Proxy(
if (urlComp.isHttps) {
// Upgrade socket to SSL for HTTPS
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
stream.set_verify_mode(ssl::verify_peer);
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
// SSL verification mode is already set in ctx (verify_none)
// Perform SSL handshake
stream.handshake(ssl::stream_base::client);
+97 -20
View File
@@ -28,14 +28,14 @@ Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database>
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}", result.error().message));
// Not fatal - start with empty subscriptions
} else {
for (auto clientId : *result) {
subscribedClients_.insert(clientId);
for (const auto& subscriber : *result) {
subscribedUids_.insert(subscriber.uid);
}
}
initialized_ = true;
ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)",
subscribedClients_.size()));
subscribedUids_.size()));
return {};
}
@@ -48,68 +48,145 @@ void SubscriptionManager::shutdown() {
initialized_ = false;
database_.reset();
subscribedUids_.clear();
ECHOION_LOG_INFO("SubscriptionManager shutdown");
}
bool SubscriptionManager::subscribe(uint64_t clientId) {
bool SubscriptionManager::subscribe(const std::string& uid, const std::string& nickname) {
std::lock_guard<std::mutex> lock(mutex_);
// Check if already subscribed (ensures uniqueness)
if (subscribedClients_.contains(clientId)) {
if (subscribedUids_.contains(uid)) {
// Update nickname even if already subscribed
if (database_) {
database_->addSubscriber(uid, nickname);
}
return false; // Already subscribed
}
// Add to database first
if (database_) {
auto result = database_->addSubscriber(clientId);
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}",
clientId, result.error().message));
uid, result.error().message));
return false;
}
}
subscribedClients_.insert(clientId);
ECHOION_LOG_INFO(std::format("Client {} subscribed", clientId));
subscribedUids_.insert(uid);
ECHOION_LOG_INFO(std::format("Client {} ({}) subscribed", nickname, uid));
return true;
}
bool SubscriptionManager::unsubscribe(uint64_t clientId) {
bool SubscriptionManager::unsubscribe(const std::string& uid) {
std::lock_guard<std::mutex> lock(mutex_);
bool removed = subscribedClients_.erase(clientId) > 0;
bool removed = subscribedUids_.erase(uid) > 0;
if (removed) {
// Remove from database
if (database_) {
auto result = database_->removeSubscriber(clientId);
auto result = database_->removeSubscriber(uid);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}",
clientId, result.error().message));
uid, result.error().message));
}
}
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", clientId));
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
}
return removed;
}
bool SubscriptionManager::isSubscribed(uint64_t clientId) const {
bool SubscriptionManager::isSubscribed(const std::string& uid) const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_.contains(clientId);
return subscribedUids_.contains(uid);
}
std::set<uint64_t> SubscriptionManager::getSubscribedClients() const {
std::vector<std::string> SubscriptionManager::getSubscribedUids() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_;
return std::vector<std::string>(subscribedUids_.begin(), subscribedUids_.end());
}
std::vector<SubscriptionManager::Subscriber> SubscriptionManager::getSubscribers() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<Subscriber> result;
if (!database_) {
return result;
}
auto dbSubscribers = database_->getAllSubscribers();
if (dbSubscribers) {
for (const auto& info : *dbSubscribers) {
if (subscribedUids_.contains(info.uid)) {
result.push_back({info.uid, info.nickname});
}
}
}
return result;
}
std::optional<std::string> SubscriptionManager::getSubscriberNickname(const std::string& uid) const {
std::lock_guard<std::mutex> lock(mutex_);
if (!subscribedUids_.contains(uid) || !database_) {
return std::nullopt;
}
auto subscribers = database_->getAllSubscribers();
if (subscribers) {
for (const auto& info : *subscribers) {
if (info.uid == uid) {
return info.nickname;
}
}
}
return std::nullopt;
}
bool SubscriptionManager::updateNickname(const std::string& uid, const std::string& nickname) {
std::lock_guard<std::mutex> lock(mutex_);
if (!subscribedUids_.contains(uid)) {
return false;
}
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to update nickname for {}: {}",
uid, result.error().message));
return false;
}
}
return true;
}
bool SubscriptionManager::hasSubscribers() const {
std::lock_guard<std::mutex> lock(mutex_);
return !subscribedClients_.empty();
return !subscribedUids_.empty();
}
size_t SubscriptionManager::getSubscriberCount() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_.size();
return subscribedUids_.size();
}
bool SubscriptionManager::clearAll() {
std::lock_guard<std::mutex> lock(mutex_);
if (database_) {
auto result = database_->clearAllSubscribers();
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to clear all subscribers: {}",
result.error().message));
return false;
}
}
subscribedUids_.clear();
ECHOION_LOG_INFO("All subscriptions cleared");
return true;
}
} // namespace Echoion::Core
+144
View File
@@ -0,0 +1,144 @@
#include "echoion/core/UrlShortener.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <glaze/glaze.hpp>
namespace Echoion::Core {
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)) {
}
UrlShortener::~UrlShortener() = default;
Api::Result<std::string> UrlShortener::shortenYouTubeUrl(std::string_view videoId) {
std::string originalUrl = std::format("https://www.youtube.com/watch?v={}", videoId);
return shortenUrl(originalUrl);
}
Api::Result<std::string> UrlShortener::shortenUrl(std::string_view originalUrl) {
// Check cache first
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}",
originalUrl, it->second.shortenedUrl));
return it->second.shortenedUrl;
}
// Expired, remove from cache
cache_.erase(it);
}
}
if (!networkClient_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
}
// faumaray.ru API endpoint for URL shortening
// POST /shorten with JSON body {"longUrl": "https://..."}
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
std::string apiUrl = "https://faumaray.ru/shorten";
// Build JSON request body - API expects "longUrl" field
std::string jsonBody = std::format(R"({{"longUrl":"{}"}})", originalUrl);
std::vector<Api::HttpHeader> headers = {
{"Content-Type", "application/json"},
{"User-Agent", "EchoionBot/1.0"}
};
ECHOION_LOG_DEBUG(std::format("Shortening URL via faumaray.ru: {}", originalUrl));
auto response = networkClient_->post(apiUrl, jsonBody, headers);
if (!response) {
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
response.error().message));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Failed to shorten URL"));
}
if (!response->isSuccess()) {
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
response->statusCode));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}", response->statusCode)));
}
try {
// Parse response - expecting {"shortUrl": "https://faumaray.ru/xxxxx"}
glz::generic json;
if (glz::read_json(json, response->body)) {
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse shortening response"));
}
std::string shortenedUrl;
if (json.contains("shortUrl")) {
shortenedUrl = json["shortUrl"].get<std::string>();
} else {
ECHOION_LOG_WARNING("No shortUrl field in response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"No shortUrl in response"));
}
// Cache the result
{
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_[std::string(originalUrl)] = {
.shortenedUrl = shortenedUrl,
.timestamp = std::chrono::system_clock::now()
};
}
ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}", originalUrl, shortenedUrl));
return shortenedUrl;
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format("Exception parsing shortening response: {}",
e.what()));
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Exception during URL shortening"));
}
}
std::optional<std::string> UrlShortener::getCachedUrl(std::string_view originalUrl) const {
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
return it->second.shortenedUrl;
}
}
return std::nullopt;
}
void UrlShortener::clearCache() {
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_.clear();
}
void UrlShortener::setCacheTtl(std::chrono::hours ttl) {
cacheTtl_ = ttl;
}
void UrlShortener::cleanExpiredCache() {
std::lock_guard<std::mutex> lock(cacheMutex_);
auto now = std::chrono::system_clock::now();
for (auto it = cache_.begin(); it != cache_.end();) {
if (now - it->second.timestamp >= cacheTtl_) {
it = cache_.erase(it);
} else {
++it;
}
}
}
} // namespace Echoion::Core
+1435 -185
View File
File diff suppressed because it is too large. Load diff
+301 -72
View File
@@ -1,11 +1,12 @@
#include "echoion/core/YtDlpManager.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <fstream>
#include <cstdlib>
#include "echoion/core/YtDlpManager.hpp"
#include <array>
#include <chrono>
#include <cstdlib>
#include <format>
#include <fstream>
#include <future>
#include <glaze/glaze.hpp>
#ifdef _WIN32
#include <windows.h>
@@ -20,7 +21,7 @@ YtDlpManager::YtDlpManager(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)) {
}
YtDlpManager::~YtDlpManager() = default;
YtDlpManager::~YtDlpManager() { stopThreadPool(); }
std::filesystem::path YtDlpManager::getStorageDir() const {
// Store in ~/.local/share/echoion/yt-dlp on Linux
@@ -138,10 +139,153 @@ Api::Result<void> YtDlpManager::initialize() {
}
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
std::lock_guard<std::mutex> lock(mutex_);
initialized_ = true;
return {};
// Start thread pool for async operations
startThreadPool();
std::lock_guard<std::mutex> lock(mutex_);
initialized_ = true;
return {};
}
void YtDlpManager::startThreadPool()
{
stopThreadPool(); // Clear any existing threads first
// Auto-adjust thread pool size based on hardware
unsigned int hardwareThreads = std::thread::hardware_concurrency();
if (hardwareThreads > 0 && threadPoolSize_ > hardwareThreads / 2) {
threadPoolSize_ = std::max(1u, hardwareThreads / 2);
ECHOION_LOG_INFO(std::format(
"Auto-adjusted yt-dlp thread pool to {} threads (hardware: {})",
threadPoolSize_, hardwareThreads));
}
ECHOION_LOG_INFO(std::format("Starting yt-dlp thread pool with {} threads",
threadPoolSize_));
for (size_t i = 0; i < threadPoolSize_; ++i) {
threadPool_.emplace_back([this] { workerThread(); });
}
}
void YtDlpManager::stopThreadPool()
{
stopThreads_ = true;
taskCv_.notify_all();
for (auto& thread : threadPool_) {
if (thread.joinable()) {
thread.join();
}
}
threadPool_.clear();
stopThreads_ = false;
}
void YtDlpManager::workerThread()
{
while (!stopThreads_.load()) {
std::packaged_task<YtDlpResult()> task;
{
std::unique_lock<std::mutex> lock(taskMutex_);
taskCv_.wait(lock, [this] {
return !taskQueue_.empty() || stopThreads_.load();
});
if (stopThreads_.load()) {
return;
}
if (!taskQueue_.empty()) {
task = std::move(taskQueue_.front());
taskQueue_.pop();
}
}
if (task.valid()) {
task();
}
}
}
void YtDlpManager::setThreadPoolSize(size_t size)
{
if (size == 0) {
size = 1;
}
if (size > 16) {
size = 16; // Cap at 16 threads
}
std::lock_guard<std::mutex> lock(mutex_);
if (threadPoolSize_ != size) {
threadPoolSize_ = size;
if (initialized_) {
// Restart thread pool with new size
stopThreadPool();
startThreadPool();
}
}
}
size_t YtDlpManager::getThreadPoolSize() const
{
std::lock_guard<std::mutex> lock(mutex_);
return threadPoolSize_;
}
void YtDlpManager::setProxyConfig(const std::optional<Api::ProxyConfig>& proxy)
{
std::lock_guard<std::mutex> lock(proxyMutex_);
proxyConfig_ = proxy;
if (proxy.has_value() && proxy->isValid()) {
ECHOION_LOG_INFO(std::format("yt-dlp proxy configured: {}:{}",
proxy->host, proxy->port));
} else {
ECHOION_LOG_INFO("yt-dlp proxy cleared");
}
}
std::optional<Api::ProxyConfig> YtDlpManager::getProxyConfig() const
{
std::lock_guard<std::mutex> lock(proxyMutex_);
return proxyConfig_;
}
std::vector<std::string> YtDlpManager::getProxyArgs() const
{
std::lock_guard<std::mutex> lock(proxyMutex_);
std::vector<std::string> proxyArgs;
if (!proxyConfig_.has_value() || !proxyConfig_->isValid()) {
return proxyArgs;
}
const auto& proxy = *proxyConfig_;
std::string proxyUrl;
if (proxy.isSocks5()) {
if (proxy.requiresAuth()) {
proxyUrl = std::format("socks5://{}:{}@{}:{}", *proxy.username,
*proxy.password, proxy.host, proxy.port);
} else {
proxyUrl = std::format("socks5://{}:{}", proxy.host, proxy.port);
}
} else {
if (proxy.requiresAuth()) {
proxyUrl = std::format("http://{}:{}@{}:{}", *proxy.username,
*proxy.password, proxy.host, proxy.port);
} else {
proxyUrl = std::format("http://{}:{}", proxy.host, proxy.port);
}
}
proxyArgs.push_back("--proxy");
proxyArgs.push_back(proxyUrl);
return proxyArgs;
}
Api::Result<void> YtDlpManager::downloadYtDlp() {
@@ -374,50 +518,86 @@ std::vector<std::string> YtDlpManager::getCookieArgs() const {
}
std::string YtDlpManager::execute(const std::vector<std::string>& args) const {
if (!std::filesystem::exists(executablePath_)) {
return "";
}
std::string cmd = executablePath_.string();
// Add cookie arguments first
auto cookieArgs = getCookieArgs();
for (const auto& arg : cookieArgs) {
cmd += " ";
// Simple escaping
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
for (const auto& arg : args) {
cmd += " ";
// Simple escaping - wrap in quotes if contains spaces or special chars
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
// Escape existing quotes and wrap
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
// Suppress stderr
return executeInternal(args).output;
}
YtDlpResult
YtDlpManager::executeInternal(const std::vector<std::string>& args) const
{
YtDlpResult result;
result.success = false;
result.exitCode = -1;
if (!std::filesystem::exists(executablePath_)) {
return result;
}
auto startTime = std::chrono::steady_clock::now();
std::string cmd = buildCommand(args);
ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd.substr(0, 200)));
std::array<char, 8192> buffer;
std::string output;
#ifdef _WIN32
FILE* pipe = _popen(cmd.c_str(), "r");
#else
FILE* pipe = popen(cmd.c_str(), "r");
#endif
if (!pipe) {
ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution");
return result;
}
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
output += buffer.data();
}
#ifdef _WIN32
result.exitCode = _pclose(pipe);
#else
result.exitCode = pclose(pipe);
if (WIFEXITED(result.exitCode)) {
result.exitCode = WEXITSTATUS(result.exitCode);
}
#endif
auto endTime = std::chrono::steady_clock::now();
result.executionTime =
std::chrono::duration_cast<std::chrono::milliseconds>(endTime -
startTime);
result.output = std::move(output);
result.success = (result.exitCode == 0);
return result;
}
std::string
YtDlpManager::buildCommand(const std::vector<std::string>& args) const
{
std::string cmd = executablePath_.string();
// Add proxy arguments first (before cookies)
auto proxyArgs = getProxyArgs();
for (const auto& arg : proxyArgs) {
cmd += " ";
cmd += escapeArg(arg);
}
// Add cookie arguments
auto cookieArgs = getCookieArgs();
for (const auto& arg : cookieArgs) {
cmd += " ";
cmd += escapeArg(arg);
}
for (const auto& arg : args) {
cmd += " ";
cmd += escapeArg(arg);
}
// Suppress stderr
#ifdef _WIN32
cmd += " 2>nul";
#else
@@ -433,24 +613,73 @@ std::string YtDlpManager::execute(const std::vector<std::string>& args) const {
#elif defined(__APPLE__)
cmd = std::format("gtimeout {} {} 2>/dev/null || {}", timeoutSec, cmd, cmd);
#endif
ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd));
std::array<char, 8192> buffer;
std::string result;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution");
return "";
}
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result += buffer.data();
}
pclose(pipe);
return result;
return cmd;
}
std::string YtDlpManager::escapeArg(const std::string& arg)
{
// Simple escaping - wrap in quotes if contains spaces or special chars
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos ||
arg.find('>') != std::string::npos ||
arg.find('<') != std::string::npos ||
arg.find('|') != std::string::npos ||
arg.find('&') != std::string::npos ||
arg.find('$') != std::string::npos ||
arg.find('`') != std::string::npos) {
// Escape existing quotes and wrap
std::string escaped;
for (char c : arg) {
if (c == '"') {
escaped += "\\";
}
escaped += c;
}
return "\"" + escaped + "\"";
}
return arg;
}
std::future<YtDlpResult>
YtDlpManager::executeAsync(const std::vector<std::string>& args)
{
std::packaged_task<YtDlpResult()> task(
[this, args]() { return executeInternal(args); });
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::vector<YtDlpResult> YtDlpManager::executeBatch(
const std::vector<std::vector<std::string>>& argsList)
{
std::vector<std::future<YtDlpResult>> futures;
futures.reserve(argsList.size());
// Launch all tasks
for (const auto& args : argsList) {
futures.push_back(executeAsync(args));
}
// Collect results
std::vector<YtDlpResult> results;
results.reserve(argsList.size());
for (auto& future : futures) {
results.push_back(future.get());
}
return results;
}
} // namespace Echoion::Core