2138 lines
63 KiB
C++
2138 lines
63 KiB
C++
#include "LoggerInterface.hpp"
|
|
#include "echoion/core/ConfigLoader.hpp"
|
|
#include "echoion/core/Core.hpp"
|
|
#include "echoion/core/Logger.hpp"
|
|
#include "echoion/core/state/StateSerializer.hpp"
|
|
#include "echoion/core/state/StateVersions.hpp"
|
|
#include <ConfigManager.hpp>
|
|
#include <Database.hpp>
|
|
#include <EventBus.hpp>
|
|
#include <Void/Data/Json.hpp>
|
|
#include <Void/Data/Reflect.hpp>
|
|
#include <algorithm>
|
|
#include <ctime>
|
|
#include <format>
|
|
#include <iomanip>
|
|
#include <sstream>
|
|
#include <thread>
|
|
|
|
namespace Echoion::Core
|
|
{
|
|
|
|
// Helper function to format timestamp to ISO 8601
|
|
static std::string
|
|
formatTimestampISO8601(std::chrono::system_clock::time_point tp)
|
|
{
|
|
auto time_t_now = std::chrono::system_clock::to_time_t(tp);
|
|
std::stringstream ss;
|
|
ss << std::put_time(std::gmtime(&time_t_now), "%Y-%m-%dT%H:%M:%SZ");
|
|
return ss.str();
|
|
}
|
|
|
|
Core::Core() = default;
|
|
|
|
Core::~Core()
|
|
{
|
|
if (initialized_) {
|
|
shutdown();
|
|
}
|
|
}
|
|
|
|
Api::Result<void> Core::initialize(const std::filesystem::path& configPath)
|
|
{
|
|
if (initialized_) {
|
|
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
|
|
"Core already initialized"));
|
|
}
|
|
auto logger = std::make_shared<Logger>();
|
|
logger->setMinLevel(Api::LogLevel::Debug);
|
|
Api::LoggerRegistry::instance().setLogger(logger);
|
|
// Store config path for later reload
|
|
configPath_ = configPath;
|
|
|
|
// Load config from file (Core-internal, Plugin doesn't need to know
|
|
// about AppConfig structure)
|
|
auto configResult = ConfigLoader::loadFromFile(configPath);
|
|
if (!configResult) {
|
|
// Try to create default config
|
|
ECHOION_LOG_WARNING(
|
|
std::format("Failed to load config: {}, creating default",
|
|
configResult.error().message));
|
|
config_ = ConfigLoader::createDefaultConfig();
|
|
ConfigLoader::saveToFile(configPath, config_);
|
|
} else {
|
|
config_ = *configResult;
|
|
}
|
|
|
|
// Initialize global ConfigManager with loaded config
|
|
Api::ConfigManager::instance().updateConfig(config_, false);
|
|
ECHOION_LOG_INFO("Global ConfigManager initialized");
|
|
|
|
// Note: logLevel was removed from BotConfig, using Debug as default
|
|
Api::LoggerRegistry::instance().getLogger()->setMinLevel(
|
|
Api::LogLevel::Debug);
|
|
ECHOION_LOG_INFO(
|
|
std::format("Core loaded config - Server: {}:{}, Nickname: {}",
|
|
config_.teamspeak.address, config_.teamspeak.port,
|
|
config_.teamspeak.nickname));
|
|
|
|
// Initialize logger
|
|
|
|
ECHOION_LOG_INFO("Initializing Echoion Core...");
|
|
|
|
// Start EventBus processing thread
|
|
Api::GlobalEventBus::instance().start();
|
|
ECHOION_LOG_INFO("EventBus started");
|
|
|
|
// Initialize network client
|
|
networkClient_ = std::make_shared<NetworkClient>();
|
|
auto netResult = networkClient_->initialize(config_.network.proxy);
|
|
if (!netResult) {
|
|
return std::unexpected(netResult.error());
|
|
}
|
|
|
|
// 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");
|
|
|
|
// Generate RPC tokens for existing subscribers
|
|
this->generateRpcTokensForSubscribers();
|
|
}
|
|
|
|
// Initialize music manager
|
|
musicManager_ = std::make_shared<MusicManager>();
|
|
auto musicResult = musicManager_->initialize(networkClient_, database_);
|
|
if (!musicResult) {
|
|
return std::unexpected(musicResult.error());
|
|
}
|
|
|
|
// Initialize command manager
|
|
commandManager_ = std::make_unique<CommandManager>();
|
|
commandManager_->setPrefix(config_.bot.commandPrefix);
|
|
commandManager_->setServerConfig(config_);
|
|
|
|
// Set up permission check function
|
|
commandManager_->setPermissionCheckFunc(
|
|
[this](uint64_t clientId, CommandCategory category) -> bool {
|
|
// Check if client is in admin groups
|
|
if (!pluginInterface_) {
|
|
return false;
|
|
}
|
|
|
|
// Get client info from plugin
|
|
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_.teamspeak.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_.teamspeak.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 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();
|
|
|
|
if (pluginInterface_ && !data.empty()) {
|
|
// Send int16 data directly to plugin (no conversion needed)
|
|
auto result = pluginInterface_->sendAudioData(data);
|
|
|
|
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 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_.network.rpcPort > 0 ? config_.network.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();
|
|
setupEventBusSubscriptions();
|
|
}
|
|
|
|
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_.teamspeak.address.empty() && pluginInterface_) {
|
|
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
|
|
config_.teamspeak.address,
|
|
config_.teamspeak.port));
|
|
|
|
// Convert TeamSpeakConfig to ServerConfig for the plugin interface
|
|
Api::ServerConfig serverConfig;
|
|
serverConfig.address = config_.teamspeak.address;
|
|
serverConfig.port = config_.teamspeak.port;
|
|
serverConfig.serverPassword = config_.teamspeak.serverPassword;
|
|
serverConfig.nickname = config_.teamspeak.nickname;
|
|
serverConfig.defaultChannelId = config_.teamspeak.defaultChannelId;
|
|
serverConfig.channelPassword = config_.teamspeak.channelPassword;
|
|
serverConfig.adminGroups = config_.teamspeak.adminGroups;
|
|
serverConfig.djGroups = config_.teamspeak.djGroups;
|
|
serverConfig.bannedGroups = config_.teamspeak.bannedGroups;
|
|
|
|
auto connectResult =
|
|
pluginInterface_->connectToServer(serverConfig);
|
|
if (!connectResult) {
|
|
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
|
|
connectResult.error().message));
|
|
} else {
|
|
ECHOION_LOG_INFO("Auto-connect initiated");
|
|
}
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> Core::shutdown()
|
|
{
|
|
if (!initialized_) {
|
|
return {};
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Shutting down Echoion Core...");
|
|
|
|
if (commandManager_) {
|
|
commandManager_->shutdown();
|
|
}
|
|
|
|
if (musicManager_) {
|
|
musicManager_->shutdown();
|
|
}
|
|
|
|
if (networkClient_) {
|
|
networkClient_->shutdown();
|
|
}
|
|
|
|
if (rpcServer_) {
|
|
rpcServer_->stop();
|
|
rpcServer_.reset();
|
|
}
|
|
|
|
if (database_) {
|
|
database_->shutdown();
|
|
database_.reset();
|
|
}
|
|
|
|
// Stop EventBus
|
|
Api::GlobalEventBus::instance().stop();
|
|
ECHOION_LOG_INFO("EventBus stopped");
|
|
|
|
// Clear callbacks
|
|
{
|
|
std::lock_guard<std::mutex> lock(eventMutex_);
|
|
eventCallbacks_.clear();
|
|
}
|
|
|
|
initialized_ = false;
|
|
ECHOION_LOG_INFO(std::format("Echoion Core shutdown complete (this={})",
|
|
reinterpret_cast<uintptr_t>(this)));
|
|
return {};
|
|
}
|
|
|
|
bool Core::isInitialized() const noexcept { return initialized_.load(); }
|
|
|
|
Api::Result<void> Core::playTrack(const Api::TrackInfo& track)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->queueTrack(track, 0);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
|
|
// If not playing, start playback
|
|
auto state = musicManager_->getPlaybackState();
|
|
if (state && !state->isPlaying) {
|
|
auto playResult = musicManager_->skip(0); // Start first track
|
|
if (!playResult) {
|
|
return std::unexpected(playResult.error());
|
|
}
|
|
}
|
|
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::PlayRequested,
|
|
.trackSummary = Api::TrackSummary{.id = track.id,
|
|
.title = track.title,
|
|
.artist = track.artist,
|
|
.duration = track.duration},
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> Core::play(const std::string& trackId)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
// Resolve track ID to TrackInfo via MusicManager
|
|
auto result = musicManager_->play(trackId, 0);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<void> Core::pause()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->pause();
|
|
if (result) {
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::PlaybackPaused,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Api::Result<void> Core::resume()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->resume();
|
|
if (result) {
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::PlaybackStarted,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Api::Result<void> Core::stop()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->stop();
|
|
if (result) {
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::PlaybackStopped,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Api::Result<void> Core::skip(uint32_t count)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->skip(count);
|
|
if (result) {
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::SkipRequested,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Api::Result<void> Core::seek(std::chrono::milliseconds position)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
return musicManager_->seek(position);
|
|
}
|
|
|
|
Api::Result<void> Core::setVolume(float volume)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
return musicManager_->setVolume(volume);
|
|
}
|
|
|
|
Api::Result<uint64_t> Core::queueTrackFull(const Api::TrackInfo& track,
|
|
uint64_t clientId)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->queueTrack(track, clientId);
|
|
if (result) {
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::TrackQueued,
|
|
.trackSummary = Api::TrackSummary{.id = track.id,
|
|
.title = track.title,
|
|
.artist = track.artist,
|
|
.duration = track.duration},
|
|
.clientId = clientId,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Api::Result<uint64_t> Core::queueTrack(const std::string& trackId,
|
|
uint64_t clientId)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
// Use MusicManager::play to resolve trackId and get TrackInfo
|
|
auto resolveResult = musicManager_->play(trackId, clientId);
|
|
if (!resolveResult) {
|
|
return std::unexpected(resolveResult.error());
|
|
}
|
|
|
|
// Return a generated queue ID (MusicManager handles actual queue ID
|
|
// generation) The play method already queues the track, so we return 0
|
|
// as success indicator The actual queue ID would need to be retrieved
|
|
// from getQueue if needed
|
|
return 0;
|
|
}
|
|
|
|
Api::Result<void> Core::removeFromQueue(uint64_t queueId)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
// Find position by queueId
|
|
auto queue = musicManager_->getQueue();
|
|
if (!queue) {
|
|
return std::unexpected(queue.error());
|
|
}
|
|
|
|
for (size_t i = 0; i < queue->size(); ++i) {
|
|
if ((*queue)[i].queueId == queueId) {
|
|
return musicManager_->removeFromQueue(static_cast<uint32_t>(i));
|
|
}
|
|
}
|
|
|
|
return std::unexpected(
|
|
Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
|
|
}
|
|
|
|
Api::Result<void> Core::clearQueue()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->clearQueue();
|
|
if (result) {
|
|
broadcastEvent(Api::PluginEvent{
|
|
.type = Api::PluginEventType::QueueCleared,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Api::Result<std::vector<Api::QueueEntry>> Core::getQueue() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
return musicManager_->getQueue();
|
|
}
|
|
|
|
Api::Result<std::vector<Api::TrackSummary>> Core::getQueueSummaries() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto queue = musicManager_->getQueue();
|
|
if (!queue) {
|
|
return std::unexpected(queue.error());
|
|
}
|
|
|
|
std::vector<Api::TrackSummary> summaries;
|
|
summaries.reserve(queue->size());
|
|
for (const auto& entry : *queue) {
|
|
summaries.push_back(
|
|
Api::TrackSummary{.id = entry.track.id,
|
|
.title = entry.track.title,
|
|
.artist = entry.track.artist,
|
|
.duration = entry.track.duration});
|
|
}
|
|
return summaries;
|
|
}
|
|
|
|
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
// Find current position
|
|
auto queue = musicManager_->getQueue();
|
|
if (!queue) {
|
|
return std::unexpected(queue.error());
|
|
}
|
|
|
|
uint32_t fromPosition = 0;
|
|
bool found = false;
|
|
for (size_t i = 0; i < queue->size(); ++i) {
|
|
if ((*queue)[i].queueId == queueId) {
|
|
fromPosition = static_cast<uint32_t>(i);
|
|
found = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!found) {
|
|
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
|
"Track not found in queue"));
|
|
}
|
|
|
|
return musicManager_->moveInQueue(fromPosition, newPosition);
|
|
}
|
|
|
|
Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
return musicManager_->getCurrentTrack();
|
|
}
|
|
|
|
Api::Result<std::optional<Api::TrackSummary>>
|
|
Core::getCurrentTrackSummary() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto current = musicManager_->getCurrentTrack();
|
|
if (!current) {
|
|
return std::unexpected(current.error());
|
|
}
|
|
|
|
if (!current->has_value()) {
|
|
return std::optional<Api::TrackSummary>{};
|
|
}
|
|
|
|
return std::optional<Api::TrackSummary>{
|
|
Api::TrackSummary{.id = current->value().track.id,
|
|
.title = current->value().track.title,
|
|
.artist = current->value().track.artist,
|
|
.duration = current->value().track.duration}};
|
|
}
|
|
|
|
Api::Result<Api::PlaybackState> Core::getPlaybackState() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
return musicManager_->getPlaybackState();
|
|
}
|
|
|
|
Api::Result<Api::PlaybackSummary> Core::getPlaybackSummary() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto state = musicManager_->getPlaybackState();
|
|
if (!state) {
|
|
return std::unexpected(state.error());
|
|
}
|
|
|
|
Api::PlaybackSummary summary;
|
|
summary.isPlaying = state->isPlaying;
|
|
summary.isPaused = state->isPaused;
|
|
summary.position = state->position;
|
|
summary.volume = state->volume;
|
|
summary.repeat = state->repeat;
|
|
summary.shuffle = state->shuffle;
|
|
|
|
if (state->currentTrack.has_value()) {
|
|
summary.currentTrack = Api::TrackSummary{
|
|
.id = state->currentTrack->track.id,
|
|
.title = state->currentTrack->track.title,
|
|
.artist = state->currentTrack->track.artist,
|
|
.duration = state->currentTrack->track.duration};
|
|
}
|
|
|
|
return summary;
|
|
}
|
|
|
|
Api::Result<void> Core::loadPlaylist(const std::string& playlistId,
|
|
uint64_t clientId)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto result = musicManager_->loadPlaylist(playlistId, clientId);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
return musicManager_->getPlaylists();
|
|
}
|
|
|
|
Api::Result<std::vector<std::string>> Core::getPlaylistIds() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto playlists = musicManager_->getPlaylists();
|
|
if (!playlists) {
|
|
return std::unexpected(playlists.error());
|
|
}
|
|
|
|
std::vector<std::string> ids;
|
|
ids.reserve(playlists->size());
|
|
for (const auto& playlist : *playlists) {
|
|
ids.push_back(playlist.id);
|
|
}
|
|
return ids;
|
|
}
|
|
|
|
Api::Result<void> Core::updateConfig(const Api::AppConfig& config)
|
|
{
|
|
// Update local config copy
|
|
config_ = config;
|
|
|
|
if (commandManager_) {
|
|
commandManager_->setPrefix(config.bot.commandPrefix);
|
|
commandManager_->setServerConfig(config);
|
|
}
|
|
|
|
// Update network proxy if changed
|
|
if (networkClient_ &&
|
|
config.network.proxy != networkClient_->getProxy()) {
|
|
networkClient_->setProxy(config.network.proxy);
|
|
}
|
|
|
|
broadcastEvent(
|
|
Api::PluginEvent{.type = Api::PluginEventType::ConfigurationChanged,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
|
|
return {};
|
|
}
|
|
|
|
Api::Result<Api::AppConfig> Core::getConfig() const { return config_; }
|
|
|
|
Api::Result<void> Core::updateConfigJson(const std::string& configJson)
|
|
{
|
|
// Parse JSON config using Void::Json reflection
|
|
auto parsed = Void::Json::parse(configJson);
|
|
if (!parsed) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ParseError,
|
|
std::format("Failed to parse config JSON ({}:{}): {}",
|
|
parsed.error().line, parsed.error().col,
|
|
parsed.error().message)));
|
|
}
|
|
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
|
|
if (!jsonResult.has_value()) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ParseError,
|
|
std::format("Failed to parse config JSON: field '{}': {}",
|
|
jsonResult.error().field,
|
|
jsonResult.error().message)));
|
|
}
|
|
|
|
// Convert to AppConfig
|
|
Api::AppConfig config;
|
|
const auto& json = jsonResult.value();
|
|
|
|
// Bot config
|
|
config.bot.botName = json.bot.botName;
|
|
config.bot.commandPrefix = json.bot.commandPrefix;
|
|
config.bot.defaultVolume = json.bot.defaultVolume;
|
|
config.bot.autoReconnect = json.bot.autoReconnect;
|
|
config.bot.reconnectDelay =
|
|
std::chrono::milliseconds(json.bot.reconnectDelay);
|
|
config.bot.maxReconnectAttempts = json.bot.maxReconnectAttempts;
|
|
config.bot.preferredQuality =
|
|
ConfigLoader::parseQuality(json.bot.preferredQuality);
|
|
config.bot.allowPlaylistImports = json.bot.allowPlaylistImports;
|
|
config.bot.maxQueueSize = json.bot.maxQueueSize;
|
|
config.bot.trackTimeout =
|
|
std::chrono::milliseconds(json.bot.trackTimeout);
|
|
|
|
// Proxy config
|
|
if (json.network.proxyHost.has_value() &&
|
|
json.network.proxyPort.has_value()) {
|
|
Api::ProxyConfig proxy;
|
|
proxy.host = *json.network.proxyHost;
|
|
proxy.port = *json.network.proxyPort;
|
|
proxy.username = json.network.proxyUsername;
|
|
proxy.password = json.network.proxyPassword;
|
|
proxy.type = (json.network.proxyType == "SOCKS5")
|
|
? Api::ProxyType::SOCKS5
|
|
: Api::ProxyType::HTTP;
|
|
config.network.proxy = proxy;
|
|
}
|
|
|
|
// Server config
|
|
config.teamspeak.address = json.teamspeak.address;
|
|
config.teamspeak.port = json.teamspeak.port;
|
|
config.teamspeak.serverPassword = json.teamspeak.serverPassword;
|
|
config.teamspeak.nickname = json.teamspeak.nickname;
|
|
config.teamspeak.defaultChannelId = json.teamspeak.defaultChannelId;
|
|
config.teamspeak.channelPassword = json.teamspeak.channelPassword;
|
|
config.teamspeak.adminGroups = json.teamspeak.adminGroups;
|
|
config.teamspeak.djGroups = json.teamspeak.djGroups;
|
|
config.teamspeak.bannedGroups = json.teamspeak.bannedGroups;
|
|
|
|
// Security config
|
|
config.security.requireAuthForAdmin = json.security.requireAuthForAdmin;
|
|
config.security.maxLoginAttempts = json.security.maxLoginAttempts;
|
|
config.security.lockoutDuration =
|
|
std::chrono::milliseconds(json.security.lockoutDuration);
|
|
config.security.sessionTimeout =
|
|
std::chrono::milliseconds(json.security.sessionTimeout);
|
|
config.security.enableAuditLog = json.security.enableAuditLog;
|
|
|
|
// Update the config
|
|
return updateConfig(config);
|
|
}
|
|
|
|
Api::Result<std::string> Core::getConfigJson() const
|
|
{
|
|
// Convert current config to JSON
|
|
AppConfigJson json;
|
|
|
|
// Bot config
|
|
json.bot.botName = config_.bot.botName;
|
|
json.bot.commandPrefix = config_.bot.commandPrefix;
|
|
json.bot.defaultVolume = config_.bot.defaultVolume;
|
|
json.bot.autoReconnect = config_.bot.autoReconnect;
|
|
json.bot.reconnectDelay =
|
|
static_cast<uint32_t>(config_.bot.reconnectDelay.count());
|
|
json.bot.maxReconnectAttempts = config_.bot.maxReconnectAttempts;
|
|
json.bot.preferredQuality =
|
|
ConfigLoader::qualityToString(config_.bot.preferredQuality);
|
|
json.bot.allowPlaylistImports = config_.bot.allowPlaylistImports;
|
|
json.bot.maxQueueSize = config_.bot.maxQueueSize;
|
|
json.bot.trackTimeout =
|
|
static_cast<uint32_t>(config_.bot.trackTimeout.count());
|
|
|
|
// Proxy config
|
|
if (config_.network.proxy.has_value()) {
|
|
json.network.proxyHost = config_.network.proxy->host;
|
|
json.network.proxyPort = config_.network.proxy->port;
|
|
json.network.proxyUsername = config_.network.proxy->username;
|
|
json.network.proxyPassword = config_.network.proxy->password;
|
|
json.network.proxyType =
|
|
config_.network.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5"
|
|
: "HTTP";
|
|
}
|
|
|
|
// Server config
|
|
json.teamspeak.address = config_.teamspeak.address;
|
|
json.teamspeak.port = config_.teamspeak.port;
|
|
json.teamspeak.serverPassword = config_.teamspeak.serverPassword;
|
|
json.teamspeak.nickname = config_.teamspeak.nickname;
|
|
json.teamspeak.defaultChannelId = config_.teamspeak.defaultChannelId;
|
|
json.teamspeak.channelPassword = config_.teamspeak.channelPassword;
|
|
json.teamspeak.adminGroups = config_.teamspeak.adminGroups;
|
|
json.teamspeak.djGroups = config_.teamspeak.djGroups;
|
|
json.teamspeak.bannedGroups = config_.teamspeak.bannedGroups;
|
|
|
|
// Security config
|
|
json.security.requireAuthForAdmin =
|
|
config_.security.requireAuthForAdmin;
|
|
json.security.maxLoginAttempts = config_.security.maxLoginAttempts;
|
|
json.security.lockoutDuration =
|
|
static_cast<uint32_t>(config_.security.lockoutDuration.count());
|
|
json.security.sessionTimeout =
|
|
static_cast<uint32_t>(config_.security.sessionTimeout.count());
|
|
json.security.enableAuditLog = config_.security.enableAuditLog;
|
|
|
|
return Void::Json::serialize(Void::Json::to_json(json),
|
|
{.pretty = true});
|
|
}
|
|
|
|
Api::Result<void> Core::reloadConfig()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
if (configPath_.empty()) {
|
|
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
|
|
"Config path not set"));
|
|
}
|
|
|
|
// Reload config from disk
|
|
auto configResult = ConfigLoader::loadFromFile(configPath_);
|
|
if (!configResult) {
|
|
return std::unexpected(configResult.error());
|
|
}
|
|
|
|
// Update local config
|
|
config_ = *configResult;
|
|
|
|
// Update components with new config
|
|
if (commandManager_) {
|
|
commandManager_->setPrefix(config_.bot.commandPrefix);
|
|
commandManager_->setServerConfig(config_);
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Configuration reloaded from disk");
|
|
return {};
|
|
}
|
|
|
|
Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Preparing for hot reload...");
|
|
|
|
broadcastEvent(
|
|
Api::PluginEvent{.type = Api::PluginEventType::HotReloadRequested,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
|
|
return musicManager_->getStateForHotReload();
|
|
}
|
|
|
|
Api::Result<void>
|
|
Core::restoreAfterHotReloadFull(const Api::HotReloadState& state)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Restoring after hot reload...");
|
|
|
|
auto result = musicManager_->restoreFromHotReload(state);
|
|
if (!result) {
|
|
return result;
|
|
}
|
|
|
|
broadcastEvent(
|
|
Api::PluginEvent{.type = Api::PluginEventType::HotReloadCompleted,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
|
|
ECHOION_LOG_INFO("Hot reload restore complete");
|
|
return {};
|
|
}
|
|
|
|
Api::Result<std::string> Core::prepareForHotReload()
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Preparing for hot reload (decoupled)...");
|
|
|
|
broadcastEvent(
|
|
Api::PluginEvent{.type = Api::PluginEventType::HotReloadRequested,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
|
|
auto state = musicManager_->getStateForHotReload();
|
|
|
|
// Serialize state to JSON using Void::Json reflection
|
|
return Void::Json::serialize(Void::Json::to_json(state));
|
|
}
|
|
|
|
Api::Result<void> Core::restoreAfterHotReload(const std::string& state)
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Restoring after hot reload (decoupled)...");
|
|
|
|
// Deserialize state from JSON
|
|
auto parsed = Void::Json::parse(state);
|
|
if (!parsed) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ParseError,
|
|
std::format("Failed to parse hot reload state ({}:{}): {}",
|
|
parsed.error().line, parsed.error().col,
|
|
parsed.error().message)));
|
|
}
|
|
auto stateResult = Void::Json::from_json<Api::HotReloadState>(*parsed);
|
|
if (!stateResult.has_value()) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ParseError,
|
|
std::format("Failed to deserialize hot reload state: "
|
|
"field '{}': {}",
|
|
stateResult.error().field,
|
|
stateResult.error().message)));
|
|
}
|
|
|
|
auto result = musicManager_->restoreFromHotReload(stateResult.value());
|
|
if (!result) {
|
|
return result;
|
|
}
|
|
|
|
broadcastEvent(
|
|
Api::PluginEvent{.type = Api::PluginEventType::HotReloadCompleted,
|
|
.clientId = 0,
|
|
.timestamp = std::chrono::system_clock::now()});
|
|
|
|
ECHOION_LOG_INFO("Hot reload restore complete (decoupled)");
|
|
return {};
|
|
}
|
|
|
|
// ============================================================================
|
|
// Decoupled State Management - Plugin never knows state internals
|
|
// ============================================================================
|
|
|
|
Api::StateBlob Core::saveState()
|
|
{
|
|
ECHOION_LOG_INFO("Saving Core state...");
|
|
|
|
StateV1 state;
|
|
|
|
// Capture current playback state
|
|
auto currentTrackResult = musicManager_->getCurrentTrack();
|
|
if (currentTrackResult && currentTrackResult->has_value()) {
|
|
const auto& current = currentTrackResult->value();
|
|
StateV1::PlaybackState playback;
|
|
playback.currentTrack = current.track;
|
|
if (current.position.has_value()) {
|
|
playback.positionMs = current.position->count();
|
|
}
|
|
// Get volume from playback summary
|
|
auto playbackSummary = getPlaybackSummary();
|
|
if (playbackSummary) {
|
|
playback.volume = playbackSummary->volume;
|
|
}
|
|
// Note: isPlaying, isPaused, shuffle, repeat would need to be
|
|
// captured from MusicManager For now, we'll capture what we can
|
|
state.playback = std::move(playback);
|
|
state.hasPlayback = true;
|
|
}
|
|
|
|
// Capture queue
|
|
auto queueResult = musicManager_->getQueue();
|
|
if (queueResult) {
|
|
for (const auto& entry : *queueResult) {
|
|
StateV1::QueueEntryState entryState;
|
|
entryState.track = entry.track;
|
|
entryState.queueId = entry.queueId;
|
|
entryState.addedBy = entry.addedBy;
|
|
entryState.addedAt = formatTimestampISO8601(entry.addedAt);
|
|
state.queue.push_back(std::move(entryState));
|
|
}
|
|
}
|
|
|
|
// Serialize using StateSerializer
|
|
auto blob = StateSerializer::serialize(state);
|
|
|
|
ECHOION_LOG_INFO(std::format("State saved: version={}, size={} bytes",
|
|
blob.version, blob.size()));
|
|
|
|
return blob;
|
|
}
|
|
|
|
Api::Result<void> Core::restoreState(const Api::StateBlob& state)
|
|
{
|
|
ECHOION_LOG_INFO(
|
|
std::format("Restoring Core state: version={}", state.version));
|
|
|
|
auto result = StateSerializer::deserialize(state);
|
|
if (!result) {
|
|
// Check if it's a version issue and provide helpful message
|
|
if (result.error().code == Api::ErrorCode::IncompatibleVersion) {
|
|
ECHOION_LOG_WARNING(result.error().message);
|
|
}
|
|
return std::unexpected(result.error());
|
|
}
|
|
|
|
const StateV1& stateData = *result;
|
|
|
|
// Restore playback state
|
|
if (stateData.hasPlayback) {
|
|
const auto& playback = stateData.playback;
|
|
// Restore track, position, volume, etc.
|
|
// This would involve calling MusicManager methods
|
|
// For now, we'll just log it
|
|
ECHOION_LOG_INFO(std::format("Restoring playback: {} - {}",
|
|
playback.currentTrack.title,
|
|
playback.currentTrack.artist));
|
|
}
|
|
|
|
// Restore queue
|
|
for (const auto& entry : stateData.queue) {
|
|
// Add to music manager queue
|
|
auto result = musicManager_->queueTrack(entry.track, 0);
|
|
if (result) {
|
|
ECHOION_LOG_INFO(
|
|
std::format("Restored queue entry: {} (ID: {})",
|
|
entry.track.title, *result));
|
|
} else {
|
|
ECHOION_LOG_WARNING(
|
|
std::format("Failed to restore queue entry '{}': {}",
|
|
entry.track.title, result.error().message));
|
|
}
|
|
}
|
|
|
|
ECHOION_LOG_INFO("State restored successfully");
|
|
return {};
|
|
}
|
|
|
|
uint32_t Core::getStateFormatVersion() const
|
|
{
|
|
return StateSerializer::getCurrentVersion();
|
|
}
|
|
|
|
bool Core::canRestoreStateVersion(uint32_t version) const
|
|
{
|
|
return StateSerializer::isVersionSupported(version);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Advanced Methods (for internal Core-to-Core use)
|
|
// ============================================================================
|
|
|
|
Api::Result<Api::OpaqueHandle<Api::TrackInfo>>
|
|
Core::getCurrentTrackHandle() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto current = musicManager_->getCurrentTrack();
|
|
if (!current) {
|
|
return std::unexpected(current.error());
|
|
}
|
|
|
|
if (!current->has_value()) {
|
|
return Api::OpaqueHandle<Api::TrackInfo>{}; // Empty handle
|
|
}
|
|
|
|
// Create a copy of the TrackInfo and return as handle
|
|
auto trackCopy =
|
|
std::make_shared<Api::TrackInfo>(current->value().track);
|
|
return Api::OpaqueHandle<Api::TrackInfo>(trackCopy);
|
|
}
|
|
|
|
Api::Result<std::vector<Api::OpaqueHandle<Api::QueueEntry>>>
|
|
Core::getQueueHandles() const
|
|
{
|
|
if (!initialized_) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
|
|
}
|
|
|
|
auto queue = musicManager_->getQueue();
|
|
if (!queue) {
|
|
return std::unexpected(queue.error());
|
|
}
|
|
|
|
std::vector<Api::OpaqueHandle<Api::QueueEntry>> handles;
|
|
handles.reserve(queue->size());
|
|
for (const auto& entry : *queue) {
|
|
auto entryCopy = std::make_shared<Api::QueueEntry>(entry);
|
|
handles.emplace_back(entryCopy);
|
|
}
|
|
return handles;
|
|
}
|
|
|
|
Api::Result<Api::AppConfigHandle> Core::getConfigHandle() const
|
|
{
|
|
// Return a copy of the current config wrapped in a handle
|
|
auto configCopy = std::make_shared<Api::AppConfig>(config_);
|
|
return Api::AppConfigHandle(configCopy);
|
|
}
|
|
|
|
Api::Result<void> Core::updateConfigFromHandle(Api::AppConfigHandle config)
|
|
{
|
|
if (!config.isValid()) {
|
|
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
|
|
"Invalid config handle"));
|
|
}
|
|
|
|
// Update from the handle
|
|
return updateConfig(*config);
|
|
}
|
|
|
|
void Core::registerEventCallback(const Api::EventCallback& callback)
|
|
{
|
|
std::lock_guard<std::mutex> lock(eventMutex_);
|
|
eventCallbacks_.push_back(callback);
|
|
}
|
|
|
|
void Core::unregisterEventCallback(const Api::EventCallback& callback)
|
|
{
|
|
std::lock_guard<std::mutex> lock(eventMutex_);
|
|
std::erase_if(eventCallbacks_, [&callback](const auto& cb) {
|
|
return cb.target_type() == callback.target_type();
|
|
});
|
|
}
|
|
|
|
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_) {
|
|
pluginInterface_->sendTextMessage(
|
|
clientId, std::string(message));
|
|
}
|
|
};
|
|
|
|
bool handled = commandManager_->dispatch(
|
|
event.clientId,
|
|
*event.message,
|
|
musicManager_,
|
|
[replyFunc,
|
|
clientId = event.clientId](std::string_view msg) {
|
|
replyFunc(clientId, msg);
|
|
},
|
|
event.clientName.value_or(""));
|
|
|
|
if (!handled) {
|
|
if (pluginInterface_) {
|
|
pluginInterface_->sendTextMessage(
|
|
event.clientId,
|
|
std::format("Unknown command. Type {}help "
|
|
"for available commands.",
|
|
config_.bot.commandPrefix));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
|
|
case Api::PluginEventType::ClientConnected:
|
|
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;
|
|
|
|
default:
|
|
// Forward other events to subscribers
|
|
broadcastEvent(event);
|
|
break;
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
std::string Core::getVersion() const { return Api::VERSION_STRING; }
|
|
|
|
std::chrono::system_clock::time_point Core::getUptime() const
|
|
{
|
|
return startTime_;
|
|
}
|
|
|
|
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();
|
|
|
|
// Trigger auto-connect now that plugin interface is available
|
|
if (initialized_ && !config_.teamspeak.address.empty()) {
|
|
ECHOION_LOG_INFO(
|
|
"Plugin interface available, triggering auto-connect...");
|
|
triggerAutoConnect();
|
|
}
|
|
}
|
|
|
|
void Core::triggerAutoConnect()
|
|
{
|
|
if (!initialized_) {
|
|
ECHOION_LOG_WARNING("Cannot auto-connect: Core not initialized");
|
|
return;
|
|
}
|
|
|
|
if (!pluginInterface_) {
|
|
ECHOION_LOG_WARNING(
|
|
"Cannot auto-connect: Plugin interface not set");
|
|
return;
|
|
}
|
|
|
|
if (config_.teamspeak.address.empty()) {
|
|
ECHOION_LOG_INFO(
|
|
"Auto-connect skipped: No server address configured");
|
|
return;
|
|
}
|
|
|
|
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
|
|
config_.teamspeak.address,
|
|
config_.teamspeak.port));
|
|
|
|
// Convert TeamSpeakConfig to ServerConfig for the plugin interface
|
|
Api::ServerConfig serverConfig;
|
|
serverConfig.address = config_.teamspeak.address;
|
|
serverConfig.port = config_.teamspeak.port;
|
|
serverConfig.serverPassword = config_.teamspeak.serverPassword;
|
|
serverConfig.nickname = config_.teamspeak.nickname;
|
|
serverConfig.defaultChannelId = config_.teamspeak.defaultChannelId;
|
|
serverConfig.channelPassword = config_.teamspeak.channelPassword;
|
|
serverConfig.adminGroups = config_.teamspeak.adminGroups;
|
|
serverConfig.djGroups = config_.teamspeak.djGroups;
|
|
serverConfig.bannedGroups = config_.teamspeak.bannedGroups;
|
|
|
|
auto connectResult = pluginInterface_->connectToServer(serverConfig);
|
|
if (!connectResult) {
|
|
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
|
|
connectResult.error().message));
|
|
} else {
|
|
ECHOION_LOG_INFO("Auto-connect initiated");
|
|
}
|
|
}
|
|
|
|
void Core::setAudioDataCallback(
|
|
const MusicManager::AudioDataCallback& callback)
|
|
{
|
|
if (musicManager_) {
|
|
musicManager_->setAudioDataCallback(callback);
|
|
}
|
|
}
|
|
|
|
void Core::broadcastEvent(const Api::PluginEvent& event)
|
|
{
|
|
// Send to plugin event callbacks
|
|
{
|
|
std::lock_guard<std::mutex> lock(eventMutex_);
|
|
for (const auto& callback : eventCallbacks_) {
|
|
try {
|
|
callback(event);
|
|
} catch (const std::exception& e) {
|
|
ECHOION_LOG_ERROR(
|
|
std::format("Event callback error: {}", e.what()));
|
|
}
|
|
}
|
|
}
|
|
|
|
// Broadcast to WebSocket/RPC clients
|
|
if (rpcServer_) {
|
|
std::string eventName;
|
|
switch (event.type) {
|
|
case Api::PluginEventType::PlaybackStarted:
|
|
eventName = "playback.started";
|
|
break;
|
|
case Api::PluginEventType::PlaybackPaused:
|
|
eventName = "playback.paused";
|
|
break;
|
|
case Api::PluginEventType::PlaybackResumed:
|
|
eventName = "playback.resumed";
|
|
break;
|
|
case Api::PluginEventType::PlaybackStopped:
|
|
eventName = "playback.stopped";
|
|
break;
|
|
case Api::PluginEventType::TrackFinished:
|
|
eventName = "playback.trackFinished";
|
|
break;
|
|
case Api::PluginEventType::TrackSkipped:
|
|
eventName = "playback.trackSkipped";
|
|
break;
|
|
case Api::PluginEventType::QueueUpdated:
|
|
eventName = "queue.updated";
|
|
break;
|
|
case Api::PluginEventType::VolumeChanged:
|
|
eventName = "playback.volumeChanged";
|
|
break;
|
|
case Api::PluginEventType::TrackQueued:
|
|
eventName = "queue.trackAdded";
|
|
break;
|
|
case Api::PluginEventType::TrackRemoved:
|
|
eventName = "queue.trackRemoved";
|
|
break;
|
|
case Api::PluginEventType::SeekPosition:
|
|
eventName = "playback.seeked";
|
|
break;
|
|
case Api::PluginEventType::HotReloadRequested:
|
|
eventName = "system.hotReloadRequested";
|
|
break;
|
|
case Api::PluginEventType::HotReloadCompleted:
|
|
eventName = "system.hotReloadCompleted";
|
|
break;
|
|
default:
|
|
eventName = "unknown";
|
|
break;
|
|
}
|
|
|
|
// Serialize event data to JSON with proper escaping
|
|
std::string eventData = "{}";
|
|
if (event.trackSummary) {
|
|
eventData = std::format(
|
|
"{{\"id\":\"{}\",\"title\":\"{}\",\"artist\":\"{}"
|
|
"\",\"duration\":{}}}",
|
|
event.trackSummary->id,
|
|
event.trackSummary->title,
|
|
event.trackSummary->artist,
|
|
event.trackSummary->duration
|
|
? event.trackSummary->duration->count() / 1000
|
|
: 0);
|
|
}
|
|
if (event.volume.has_value()) {
|
|
eventData = std::format("{{\"volume\":{:.2f}}}", *event.volume);
|
|
}
|
|
if (event.queuePosition.has_value()) {
|
|
eventData =
|
|
std::format("{{\"position\":{}}}", *event.queuePosition);
|
|
}
|
|
if (event.clientId > 0) {
|
|
eventData = std::format("{{\"clientId\":{}}}", event.clientId);
|
|
}
|
|
|
|
rpcServer_->broadcastEvent(eventName, eventData);
|
|
}
|
|
}
|
|
|
|
bool Core::isAdmin(uint64_t clientId) const
|
|
{
|
|
std::lock_guard<std::mutex> lock(adminMutex_);
|
|
return std::find(adminClients_.begin(), adminClients_.end(),
|
|
clientId) != adminClients_.end();
|
|
}
|
|
|
|
void Core::updateWhisperList()
|
|
{
|
|
if (!pluginInterface_ || !musicManager_) {
|
|
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");
|
|
}
|
|
}
|
|
|
|
// Auth request structure for RPC authentication
|
|
struct RpcAuthRequest {
|
|
std::optional<std::string> nickname;
|
|
std::optional<std::string> token;
|
|
};
|
|
|
|
void Core::setupRpcHandlers()
|
|
{
|
|
if (!rpcServer_) {
|
|
return;
|
|
}
|
|
|
|
// Helper to serialize track info
|
|
auto serializeTrack = [](const Api::TrackInfo& track) -> std::string {
|
|
std::string json = "{";
|
|
json += std::format("\"id\":\"{}\",", track.id);
|
|
json += std::format("\"title\":\"{}\",", track.title);
|
|
json += std::format("\"artist\":\"{}\",", track.artist);
|
|
json += std::format("\"album\":\"{}\",", track.album);
|
|
if (track.duration.has_value()) {
|
|
json +=
|
|
std::format("\"duration\":{},", track.duration->count());
|
|
}
|
|
json +=
|
|
std::format("\"source\":{}", static_cast<int>(track.source));
|
|
json += "}";
|
|
return json;
|
|
};
|
|
|
|
// Authentication - expects JSON with either "nickname" (for initial
|
|
// request) or "token" (for validation)
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::Authenticate)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
// Parse JSON params
|
|
auto parsedParams = Void::Json::parse(params);
|
|
if (!parsedParams) {
|
|
return std::unexpected(
|
|
Api::Error(Api::ErrorCode::InvalidArgument,
|
|
"Invalid authentication request format"));
|
|
}
|
|
auto reqResult =
|
|
Void::Json::from_json<RpcAuthRequest>(*parsedParams);
|
|
if (!reqResult) {
|
|
return std::unexpected(
|
|
Api::Error(Api::ErrorCode::InvalidArgument,
|
|
"Invalid authentication request format"));
|
|
}
|
|
const RpcAuthRequest& req = *reqResult;
|
|
|
|
// If token provided, validate it
|
|
if (req.token.has_value()) {
|
|
auto validResult = database_->validateRpcToken(*req.token);
|
|
if (!validResult) {
|
|
return std::unexpected(validResult.error());
|
|
}
|
|
if (*validResult) {
|
|
rpcServer_->addAuthenticatedClient(clientId);
|
|
return std::string(
|
|
"{\"success\":true,\"message\":\"Authentication "
|
|
"successful\"}");
|
|
} else {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::PermissionDenied, "Invalid token"));
|
|
}
|
|
}
|
|
|
|
// If nickname provided, search for subscriber and send token
|
|
// via PM
|
|
if (req.nickname.has_value()) {
|
|
auto uidResult =
|
|
database_->getSubscriberByNickname(*req.nickname);
|
|
if (!uidResult) {
|
|
return std::unexpected(uidResult.error());
|
|
}
|
|
|
|
if (!uidResult->has_value()) {
|
|
return std::unexpected(Api::Error(
|
|
Api::ErrorCode::NotFound,
|
|
"Subscriber not found. Please subscribe to the bot "
|
|
"first using !subscribe command."));
|
|
}
|
|
|
|
const std::string& uid = **uidResult;
|
|
|
|
// Get or create token
|
|
auto tokenResult = database_->getExistingRpcToken(uid);
|
|
if (!tokenResult) {
|
|
return std::unexpected(tokenResult.error());
|
|
}
|
|
|
|
std::string token;
|
|
if (tokenResult->has_value()) {
|
|
token = **tokenResult;
|
|
} else {
|
|
// Generate new token
|
|
auto genResult = database_->generateRpcToken(uid);
|
|
if (!genResult) {
|
|
return std::unexpected(genResult.error());
|
|
}
|
|
token = *genResult;
|
|
}
|
|
|
|
// Get client ID from UID to send PM
|
|
if (pluginInterface_) {
|
|
// Get all clients and find the one with matching UID
|
|
auto clientsResult = pluginInterface_->getClients();
|
|
if (clientsResult) {
|
|
for (const auto& client : *clientsResult) {
|
|
if (client.uniqueIdentifier == uid) {
|
|
uint64_t tsClientId = client.id;
|
|
|
|
// Send PM with token using plain text
|
|
// format (compatible with both TS3 BBCode
|
|
// and TS6 Markdown)
|
|
std::string pmMessage = std::format(
|
|
"**Echoion RPC Authentication**\n\n"
|
|
"Your authentication token:\n"
|
|
"```\n{}\n```\n\n"
|
|
"Use this token to authenticate with "
|
|
"the RPC server.\n"
|
|
"Keep this token secure and do not "
|
|
"share it with others.",
|
|
token);
|
|
|
|
auto pmResult =
|
|
pluginInterface_->sendTextMessage(
|
|
tsClientId, pmMessage);
|
|
|
|
if (!pmResult) {
|
|
ECHOION_LOG_WARNING(std::format(
|
|
"Failed to send PM with token: {}",
|
|
pmResult.error().message));
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return std::string(
|
|
"{\"success\":true,\"message\":\"Token sent via "
|
|
"TeamSpeak PM. Please check your private messages.\"}");
|
|
}
|
|
|
|
return std::unexpected(
|
|
Api::Error(Api::ErrorCode::InvalidArgument,
|
|
"Authentication request must include either "
|
|
"'nickname' or 'token'"));
|
|
});
|
|
|
|
// Playback control
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::Play)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
// Parse query from params (simple implementation)
|
|
std::string query = params;
|
|
// Remove quotes if present
|
|
if (query.size() >= 2 && query.front() == '"' &&
|
|
query.back() == '"') {
|
|
query = query.substr(1, query.size() - 2);
|
|
}
|
|
auto result = musicManager_->play(query, clientId);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return std::format("{{\"success\":true,\"message\":\"{}\"}}",
|
|
*result);
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::Pause)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
auto result = pause();
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return std::string("{\"success\":true}");
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::Resume)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
auto result = resume();
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return std::string("{\"success\":true}");
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::Stop)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
auto result = stop();
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return std::string("{\"success\":true}");
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::Skip)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
auto result = skip(1);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return std::string("{\"success\":true}");
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::SetVolume)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
// Parse volume from params - expect {"volume":0.5}
|
|
float volume = 0.5f;
|
|
if (params.find("volume") != std::string::npos) {
|
|
size_t pos = params.find(':');
|
|
if (pos != std::string::npos) {
|
|
volume = std::stof(params.substr(pos + 1));
|
|
}
|
|
}
|
|
auto result = setVolume(volume);
|
|
if (!result) {
|
|
return std::unexpected(result.error());
|
|
}
|
|
return std::format("{{\"success\":true,\"volume\":{}}}",
|
|
volume);
|
|
});
|
|
|
|
// Queue management
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::GetQueue)),
|
|
[this, serializeTrack](const std::string& params, uint64_t clientId)
|
|
-> Api::Result<std::string> {
|
|
auto queue = getQueue();
|
|
if (!queue) {
|
|
return std::unexpected(queue.error());
|
|
}
|
|
|
|
std::string json = "{\"queue\":[";
|
|
for (size_t i = 0; i < queue->size(); ++i) {
|
|
if (i > 0) {
|
|
json += ",";
|
|
}
|
|
json += "{";
|
|
json += std::format("\"queueId\":{},", (*queue)[i].queueId);
|
|
json += std::format("\"track\":{},",
|
|
serializeTrack((*queue)[i].track));
|
|
json +=
|
|
std::format("\"isPlaying\":{}",
|
|
(*queue)[i].isPlaying ? "true" : "false");
|
|
json += "}";
|
|
}
|
|
json += "]}";
|
|
return json;
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)),
|
|
[this, serializeTrack](const std::string& params, uint64_t clientId)
|
|
-> Api::Result<std::string> {
|
|
auto track = getCurrentTrack();
|
|
if (!track) {
|
|
return std::unexpected(track.error());
|
|
}
|
|
|
|
if (!track->has_value()) {
|
|
return std::string("{\"track\":null}");
|
|
}
|
|
|
|
return std::format("{{\"track\":{}}}",
|
|
serializeTrack(track->value().track));
|
|
});
|
|
|
|
rpcServer_->registerHandler(
|
|
std::to_string(static_cast<int>(Api::RpcMethod::GetStatus)),
|
|
[this](const std::string& params,
|
|
uint64_t clientId) -> Api::Result<std::string> {
|
|
auto state = getPlaybackState();
|
|
if (!state) {
|
|
return std::unexpected(state.error());
|
|
}
|
|
|
|
std::string json = "{";
|
|
json += std::format("\"isPlaying\":{},",
|
|
state->isPlaying ? "true" : "false");
|
|
json += std::format("\"isPaused\":{},",
|
|
state->isPaused ? "true" : "false");
|
|
json += std::format("\"volume\":{},", state->volume);
|
|
json += std::format("\"repeat\":{},",
|
|
state->repeat ? "true" : "false");
|
|
json += std::format("\"shuffle\":{}",
|
|
state->shuffle ? "true" : "false");
|
|
json += "}";
|
|
return json;
|
|
});
|
|
|
|
ECHOION_LOG_INFO("RPC handlers registered");
|
|
}
|
|
|
|
void Core::setupEventBusSubscriptions() const noexcept
|
|
{
|
|
using namespace Api::Events;
|
|
|
|
// Subscribe to playback events for RPC broadcasting and database
|
|
// persistence
|
|
Api::GlobalEventBus::instance().subscribe<PlaybackStarted>(
|
|
[this](const PlaybackStarted& evt) mutable {
|
|
// Broadcast to RPC/WebSocket clients
|
|
if (rpcServer_) {
|
|
std::string data = std::format(
|
|
"{{\"track\":{{\"id\":\"{}\",\"title\":\"{}\","
|
|
"\"artist\":\"{}\"}},\"position\":{}}}",
|
|
evt.track.id, evt.track.title, evt.track.artist,
|
|
evt.position.count());
|
|
rpcServer_->broadcastEvent("playback.started", data);
|
|
}
|
|
|
|
// Record playback start in database
|
|
if (database_) {
|
|
database_->recordPlayback(evt.track, evt.clientId,
|
|
std::chrono::milliseconds(0),
|
|
false);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<PlaybackPaused>(
|
|
[this](const PlaybackPaused& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::format("{{\"position\":{}}}",
|
|
evt.position.count());
|
|
rpcServer_->broadcastEvent("playback.paused", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<PlaybackResumed>(
|
|
[this](const PlaybackResumed& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::format("{{\"position\":{}}}",
|
|
evt.position.count());
|
|
rpcServer_->broadcastEvent("playback.resumed", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<PlaybackStopped>(
|
|
[this](const PlaybackStopped& evt) mutable {
|
|
if (rpcServer_) {
|
|
rpcServer_->broadcastEvent("playback.stopped", "{}");
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<PlaybackPositionChanged>(
|
|
[this](const PlaybackPositionChanged& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::format("{{\"position\":{},\"duration\":{},"
|
|
"\"progress\":{:.2f}}}",
|
|
evt.position.count(), evt.duration.count(),
|
|
evt.progressPercent);
|
|
rpcServer_->broadcastEvent("playback.position", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<TrackFinished>(
|
|
[this](const TrackFinished& evt) mutable {
|
|
if (rpcServer_) {
|
|
rpcServer_->broadcastEvent("playback.finished", "{}");
|
|
}
|
|
|
|
// Update playback record as completed
|
|
if (database_) {
|
|
database_->recordPlayback(evt.track, 0, evt.finalPosition,
|
|
true);
|
|
}
|
|
});
|
|
|
|
// Volume and playback mode changes
|
|
Api::GlobalEventBus::instance().subscribe<VolumeChanged>(
|
|
[this](const VolumeChanged& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::format("{{\"volume\":{:.2f}}}", evt.newVolume);
|
|
rpcServer_->broadcastEvent("playback.volumeChanged", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<ShuffleChanged>(
|
|
[this](const ShuffleChanged& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::format(
|
|
"{{\"shuffle\":{}}}", evt.enabled ? "true" : "false");
|
|
rpcServer_->broadcastEvent("playback.shuffleChanged", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<RepeatChanged>(
|
|
[this](const RepeatChanged& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::format(
|
|
"{{\"repeat\":{}}}", evt.enabled ? "true" : "false");
|
|
rpcServer_->broadcastEvent("playback.repeatChanged", data);
|
|
}
|
|
});
|
|
|
|
// Queue events
|
|
Api::GlobalEventBus::instance().subscribe<TrackQueued>(
|
|
[this](const TrackQueued& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::format(
|
|
"{{\"queueId\":{},\"title\":\"{}\",\"artist\":"
|
|
"\"{}\",\"position\":{},\"queueLength\":{}}}",
|
|
evt.queueId, evt.track.title, evt.track.artist,
|
|
evt.position, evt.queueLength);
|
|
rpcServer_->broadcastEvent("queue.trackAdded", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<TrackRemoved>(
|
|
[this](const TrackRemoved& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::format("{{\"queueId\":{},\"queueLength\":{}}}",
|
|
evt.queueId, evt.queueLength);
|
|
rpcServer_->broadcastEvent("queue.trackRemoved", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<QueueCleared>(
|
|
[this](const QueueCleared& evt) mutable {
|
|
if (rpcServer_) {
|
|
rpcServer_->broadcastEvent("queue.cleared", "{}");
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<QueueReordered>(
|
|
[this](const QueueReordered& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::format(
|
|
"{{\"queueId\":{},\"oldPosition\":{},\"newPosition\":{}"
|
|
"}}",
|
|
evt.queueId, evt.oldPosition, evt.newPosition);
|
|
rpcServer_->broadcastEvent("queue.reordered", data);
|
|
}
|
|
});
|
|
|
|
// Playlist events - save to database via event bus using external ID
|
|
Api::GlobalEventBus::instance().subscribe<PlaylistLoadStarted>(
|
|
[this](const PlaylistLoadStarted& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data = std::string("{\"playlistId\":\"") +
|
|
evt.playlistId + "\"}";
|
|
rpcServer_->broadcastEvent("playlist.loadStarted", data);
|
|
}
|
|
|
|
if (database_) {
|
|
auto result = database_->getOrCreatePlaylistByExternalId(
|
|
evt.playlistId, evt.playlistId, "Loaded from YouTube",
|
|
evt.requestedByClientId, true);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<PlaylistTrackLoaded>(
|
|
[this](const PlaylistTrackLoaded& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::string("{\"playlistId\":\"") + evt.playlistId +
|
|
"\",\"loaded\":" + std::to_string(evt.loadedCount) +
|
|
",\"total\":" + std::to_string(evt.totalCount) + "}";
|
|
rpcServer_->broadcastEvent("playlist.trackLoaded", data);
|
|
}
|
|
|
|
// Add track to playlist in database - lookup by external ID
|
|
if (database_) {
|
|
auto result = database_->getOrCreatePlaylistByExternalId(
|
|
evt.playlistId, evt.playlistId, "Loaded from YouTube",
|
|
0, true);
|
|
if (result) {
|
|
database_->addTrackToPlaylist(result.value(), evt.track,
|
|
evt.loadedCount - 1);
|
|
}
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<PlaylistLoadCompleted>(
|
|
[this](const PlaylistLoadCompleted& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::string("{\"playlistId\":\"") + evt.playlistId +
|
|
"\",\"totalTracks\":" +
|
|
std::to_string(evt.totalTracksLoaded) +
|
|
",\"success\":" + (evt.success ? "true" : "false") +
|
|
"}";
|
|
rpcServer_->broadcastEvent("playlist.loadCompleted", data);
|
|
}
|
|
});
|
|
|
|
// Subscription events
|
|
Api::GlobalEventBus::instance().subscribe<UserSubscribed>(
|
|
[this](const UserSubscribed& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::format("{{\"uid\":\"{}\",\"nickname\":\"{}\"}}",
|
|
evt.uid, evt.nickname);
|
|
rpcServer_->broadcastEvent("subscription.subscribed", data);
|
|
}
|
|
});
|
|
|
|
Api::GlobalEventBus::instance().subscribe<UserUnsubscribed>(
|
|
[this](const UserUnsubscribed& evt) mutable {
|
|
if (rpcServer_) {
|
|
std::string data =
|
|
std::format("{{\"uid\":\"{}\",\"nickname\":\"{}\"}}",
|
|
evt.uid, evt.nickname);
|
|
rpcServer_->broadcastEvent("subscription.unsubscribed",
|
|
data);
|
|
}
|
|
});
|
|
|
|
ECHOION_LOG_INFO("EventBus subscriptions set up");
|
|
}
|
|
|
|
void Core::generateRpcTokensForSubscribers()
|
|
{
|
|
if (!database_) {
|
|
return;
|
|
}
|
|
|
|
ECHOION_LOG_INFO("Generating RPC tokens for existing subscribers...");
|
|
|
|
// Get all subscriber UIDs
|
|
auto uidsResult = database_->getAllSubscriberUids();
|
|
if (!uidsResult) {
|
|
ECHOION_LOG_WARNING(std::format("Failed to get subscriber UIDs: {}",
|
|
uidsResult.error().message));
|
|
return;
|
|
}
|
|
|
|
int generatedCount = 0;
|
|
int existingCount = 0;
|
|
|
|
for (const auto& uid : *uidsResult) {
|
|
// Check if token already exists
|
|
auto existingToken = database_->getExistingRpcToken(uid);
|
|
if (!existingToken) {
|
|
ECHOION_LOG_WARNING(
|
|
std::format("Failed to check existing token for UID {}: {}",
|
|
uid, existingToken.error().message));
|
|
continue;
|
|
}
|
|
|
|
if (existingToken->has_value()) {
|
|
existingCount++;
|
|
continue; // Token already exists
|
|
}
|
|
|
|
// Generate new token
|
|
auto tokenResult = database_->generateRpcToken(uid);
|
|
if (!tokenResult) {
|
|
ECHOION_LOG_WARNING(
|
|
std::format("Failed to generate token for UID {}: {}", uid,
|
|
tokenResult.error().message));
|
|
} else {
|
|
generatedCount++;
|
|
}
|
|
}
|
|
|
|
ECHOION_LOG_INFO(std::format("RPC token generation complete: {} new "
|
|
"tokens generated, {} already existed",
|
|
generatedCount, existingCount));
|
|
}
|
|
|
|
} // namespace Echoion::Core
|