Initial commit

This commit is contained in:
faumaray committed 2026-02-01 23:04:49 +03:00
commit a583c17916
56 files changed
+11025

No files matched your search

+902
View File
@@ -0,0 +1,902 @@
#include "echoion/core/Core.hpp"
#include "echoion/core/Logger.hpp"
#include <echoion/api/Database.hpp>
#include <format>
#include <algorithm>
namespace Echoion::Core {
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"));
}
// 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;
}
ECHOION_LOG_INFO(std::format("Core loaded config - Server: {}:{}, Nickname: {}",
config_.server.address, config_.server.port, config_.server.nickname));
// Initialize logger
auto logger = std::make_shared<Logger>();
logger->setMinLevel(Api::LogLevel::Debug);
Api::LoggerRegistry::instance().setLogger(logger);
ECHOION_LOG_INFO("Initializing Echoion Core...");
// Initialize network client
networkClient_ = std::make_shared<NetworkClient>();
auto netResult = networkClient_->initialize(config_.bot.proxy);
if (!netResult) {
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 music manager
musicManager_ = std::make_shared<MusicManager>();
auto musicResult = musicManager_->initialize(config_.bot, 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 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
});
// 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();
// 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("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));
auto connectResult = pluginInterface_->connectToServer(config_.server);
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 (musicManager_) {
musicManager_->shutdown();
}
if (networkClient_) {
networkClient_->shutdown();
}
if (rpcServer_) {
rpcServer_->stop();
rpcServer_.reset();
}
if (database_) {
database_->shutdown();
database_.reset();
}
// Clear callbacks
{
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.clear();
}
initialized_ = false;
ECHOION_LOG_INFO("Echoion Core shutdown complete");
return {};
}
bool Core::isInitialized() const noexcept {
return initialized_.load();
}
Api::Result<void> Core::play(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,
.clientId = 0,
.trackInfo = track,
.timestamp = std::chrono::system_clock::now()
});
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::queueTrack(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,
.clientId = clientId,
.trackInfo = track,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
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<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<Api::PlaybackState> Core::getPlaybackState() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getPlaybackState();
}
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<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.bot.proxy != networkClient_->getProxy()) {
networkClient_->setProxy(config.bot.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::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::prepareForHotReload() {
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::restoreAfterHotReload(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 {};
}
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) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
switch (event.type) {
case Api::PluginEventType::TextMessageReceived:
if (event.message) {
// Check if it's a command
if (event.message->starts_with(config_.bot.commandPrefix)) {
// 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", event.clientId));
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);
}
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_.server.address.empty()) {
ECHOION_LOG_INFO("Auto-connect skipped: No server address configured");
return;
}
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
config_.server.address, config_.server.port));
auto connectResult = pluginInterface_->connectToServer(config_.server);
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.trackInfo) {
eventData = std::format("{{\"id\":\"{}\",\"title\":\"{}\",\"artist\":\"{}\",\"album\":\"{}\"}}",
event.trackInfo->id,
event.trackInfo->title,
event.trackInfo->artist,
event.trackInfo->album);
}
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_) {
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));
}
}
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
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Authenticate)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
rpcServer_->addAuthenticatedClient(clientId);
return std::string("{\"success\":true,\"token\":\"authenticated\"}");
});
// 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");
}
} // namespace Echoion::Core