Files
EchoionCore/src/Core.cpp
T
faumaray d146f11f02 Release 1.0.0
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-04 01:49:28 +03:00

1593 lines
46 KiB
C++

#include "echoion/core/ConfigLoader.hpp"
#include "echoion/core/Core.hpp"
#include "echoion/core/RpcDtos.hpp"
#include "echoion/core/state/StateSerializer.hpp"
#include "echoion/core/state/StateVersions.hpp"
#include <ConfigManager.hpp>
#include <Database.hpp>
#include <Events.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/LoggingAdapter.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <algorithm>
#include <ctime>
#include <format>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <thread>
namespace Echoion::Core
{
namespace
{
// Build the console + split-file logging stack and install it as the
// process-wide Void::Log sink. Replaces the old ILogger/LoggerRegistry
// indirection; every ECHOION_LOG_* macro is now a Void::Log:: call.
[[nodiscard]] std::shared_ptr<Void::Logging::MultiLogger>
buildLogSink()
{
namespace VL = Void::Logging;
auto multi = std::make_shared<VL::MultiLogger>();
auto formatter = std::make_shared<const VL::PatternFormatter>(
"[{time}] [{level}] [{thread}] {file} - {message}");
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
console->set_formatter(formatter);
multi->add(std::move(console));
VL::SplitFileOptions opts;
opts.combined = true;
opts.max_bytes = 10 * 1024 * 1024;
opts.max_files = 5;
if (auto fileSink = VL::SplitFileLogger::open("logs", opts)) {
(*fileSink)->set_formatter(formatter);
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
}
return multi;
}
} // namespace
} // namespace Echoion::Core
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;
void Core::installLogging()
{
logSink_ = buildLogSink();
Void::Log::set_sink(Void::Log::make_sink(*logSink_));
Void::Log::set_min_level(Void::Log::Level::Debug);
}
Api::Result<void> Core::requireInitialized() const noexcept
{
if (!initialized_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Core not initialized");
}
return {};
}
Core::~Core()
{
if (initialized_) {
shutdown();
}
}
Api::Result<void> Core::initialize(const std::filesystem::path& configPath)
{
if (initialized_) {
return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already initialized");
}
installLogging();
// 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
Void::Log::warn("Core", "{}",
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
configManager_.updateConfig(config_, false);
Void::Log::info("Core", "{}", "Global ConfigManager initialized");
Void::Log::info("Core", "{}",
std::format("Core loaded config - Server: {}:{}, Nickname: {}",
config_.teamspeak.address, config_.teamspeak.port,
config_.teamspeak.nickname));
// Initialize logger
Void::Log::info("Core", "{}", "Initializing Echoion Core...");
// The async event bus runs from construction; nothing to start.
Void::Log::info("Core", "{}", "EventBus ready");
// 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) {
Void::Log::warn("Core", "{}", std::format("Failed to initialize database: {}",
dbResult.error().message));
// Not fatal - continue without database
database_ = nullptr;
} else {
Void::Log::info("Core", "{}", "Database initialized successfully");
// Generate RPC tokens for existing subscribers
this->generateRpcTokensForSubscribers();
}
// Initialize music manager
musicManager_ = std::make_shared<MusicManager>();
musicManager_->setEventBus(&eventBus_);
musicManager_->setConfigManager(&configManager_);
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_);
// Let commands resolve shared services (e.g. the network client) by
// interface from the registry composed below — the pointer is stable
// and entries are populated before any command dispatches.
commandManager_->setServices(&registry_);
// 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()) {
Void::Log::warn("Core", "{}",
"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) {
Void::Log::debug("Core", "{}", std::format(
"Audio callback: {} calls, {} samples, result: {}",
callCount, data.size(),
result.has_value() ? "ok" : "error"));
lastLog = now;
}
}
});
// Proactive private-message send path (announcements).
musicManager_->setMessageCallback(
[this](uint64_t clientId, const std::string& text) {
if (pluginInterface_) {
[[maybe_unused]] auto r =
pluginInterface_->sendTextMessage(clientId, text);
}
});
// 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_) {
Void::Log::warn("Core", "{}",
"ClientInfoCallback: pluginInterface is null");
return std::nullopt;
}
auto clientInfoResult = pluginInterface_->getClient(clientId);
if (!clientInfoResult || !clientInfoResult->has_value()) {
Void::Log::warn("Core", "{}", std::format(
"ClientInfoCallback: getClient failed for client {}",
clientId));
return std::nullopt;
}
auto clientInfo = clientInfoResult->value();
if (!clientInfo.uniqueIdentifier) {
Void::Log::warn("Core", "{}", std::format(
"ClientInfoCallback: client {} has no uniqueIdentifier",
clientId));
return std::nullopt;
}
Void::Log::debug("Core", "{}",
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) {
Void::Log::warn("Core", "{}", std::format("Failed to start RPC server: {}",
rpcResult.error().message));
// Not fatal - continue without RPC
rpcServer_.reset();
} else {
Void::Log::info("Core", "{}",
std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
setupEventBusSubscriptions();
}
// ── Compose the service registry ─────────────────────────────────
// Register every Core service by interface so code can resolve them
// via registry_.require<I>() instead of reaching for global singletons.
// Config and event bus are wrapped in non-owning aliasing shared_ptrs
// so the registry can hand them out without owning them.
{
const auto alias = [](auto* p) {
using T = std::remove_reference_t<decltype(*p)>;
return std::shared_ptr<T>(p, [](T*) {});
};
registry_.provide<Api::ConfigManager>(
alias(&configManager_));
registry_.provide<Void::EventBus::EventBus>(alias(&eventBus_));
// Expose Core itself so commands can reach Core operations
// (e.g. reloadConfig) through the registry.
registry_.provide<Api::ICoreInterface>(
alias(static_cast<Api::ICoreInterface*>(this)));
if (networkClient_) {
registry_.provide<Api::INetworkClient>(networkClient_);
}
if (database_) {
registry_.provide<Api::Database>(database_);
}
if (musicManager_) {
registry_.provide<MusicManager>(musicManager_);
}
if (rpcServer_) {
registry_.provide<RpcServer>(rpcServer_);
}
Void::Log::info("Core", "{}", "Service registry composed");
}
startTime_ = std::chrono::system_clock::now();
initialized_ = true;
Void::Log::info("Core", "{}", std::format("Core initialized (this={})",
reinterpret_cast<uintptr_t>(this)));
unsigned int hwThreads = std::thread::hardware_concurrency();
Void::Log::info("Core", "{}",
std::format("Hardware concurrency: {} threads", hwThreads));
Void::Log::info("Core", "{}", "Echoion Core initialized successfully");
// Auto-connect to server if configured
if (!config_.teamspeak.address.empty() && pluginInterface_) {
Void::Log::info("Core", "{}", 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) {
Void::Log::error("Core", "{}", std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
Void::Log::info("Core", "{}", "Auto-connect initiated");
}
}
return {};
}
Api::Result<void> Core::shutdown()
{
if (!initialized_) {
return {};
}
Void::Log::info("Core", "{}", "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();
}
// Drain any in-flight event dispatch.
eventBus_.flush();
Void::Log::info("Core", "{}", "EventBus stopped");
// Clear callbacks
{
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.clear();
}
initialized_ = false;
Void::Log::info("Core", "{}", 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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
// 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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
return musicManager_->seek(position);
}
Api::Result<void> Core::setVolume(float volume)
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
return musicManager_->setVolume(volume);
}
Api::Result<uint64_t> Core::queueTrackFull(const Api::TrackInfo& track,
uint64_t clientId)
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
// 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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
// 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 Api::fail(Api::ErrorCode::NotFound, "Track not found in queue");
}
Api::Result<void> Core::clearQueue()
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
return musicManager_->getQueue();
}
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition)
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
// 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 Api::fail(Api::ErrorCode::NotFound,
"Track not found in queue");
}
return musicManager_->moveInQueue(fromPosition, newPosition);
}
Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
return musicManager_->getCurrentTrack();
}
Api::Result<std::optional<Api::TrackSummary>>
Core::getCurrentTrackSummary() const
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
return musicManager_->getPlaybackState();
}
Api::Result<Api::PlaybackSummary> Core::getPlaybackSummary() const
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
auto result = musicManager_->loadPlaylist(playlistId, clientId);
if (!result) {
return std::unexpected(result.error());
}
return {};
}
Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
return musicManager_->getPlaylists();
}
Api::Result<std::vector<std::string>> Core::getPlaylistIds() const
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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);
}
// Re-apply network settings to every outbound client (NetworkClient,
// yt-dlp, ffmpeg), not just the HTTP client.
if (musicManager_) {
musicManager_->applyBotConfig(config.bot);
musicManager_->applyFeaturesConfig(config.features);
musicManager_->applyNetworkConfig(config.network);
musicManager_->applyYouTubeConfig(config.youtube);
musicManager_->applySourcesConfig(config.sources);
} else if (networkClient_) {
networkClient_->setProxy(config.network.proxy);
}
broadcastEvent(
Api::PluginEvent{.type = Api::PluginEventType::ConfigurationChanged,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()});
eventBus_.publish(
Api::Events::ConfigReloaded{.newConfig = config.bot});
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 Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message));
}
// Deserialize the full Api::AppConfig document directly via reflection.
auto jsonResult = Void::Json::from_json<Api::AppConfig>(*parsed);
if (!jsonResult.has_value()) {
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON: field '{}': {}",
jsonResult.error().field,
jsonResult.error().message));
}
Api::AppConfig config = std::move(jsonResult.value());
ConfigLoader::normalize(config);
return updateConfig(config);
}
Api::Result<std::string> Core::getConfigJson() const
{
// Serialize the current config directly via reflection.
return Void::Json::serialize(Void::Json::to_json(config_),
{.pretty = true});
}
Api::Result<void> Core::reloadConfig()
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
if (configPath_.empty()) {
return Api::fail(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;
// Keep the shared ConfigManager in sync so components that read through
// it (cookies, API key, etc.) see the reloaded values.
configManager_.updateConfig(config_, false);
// Update components with new config
if (commandManager_) {
commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config_);
}
// Re-apply network settings so a proxy edit actually reaches every
// outbound client (HTTP NetworkClient, yt-dlp, ffmpeg) — not just the
// config copy. Without this the YouTube API kept using the old/no proxy.
if (musicManager_) {
musicManager_->applyBotConfig(config_.bot);
musicManager_->applyFeaturesConfig(config_.features);
musicManager_->applyNetworkConfig(config_.network);
musicManager_->applyYouTubeConfig(config_.youtube);
musicManager_->applySourcesConfig(config_.sources);
} else if (networkClient_) {
networkClient_->setProxy(config_.network.proxy);
}
eventBus_.publish(
Api::Events::ConfigReloaded{.newConfig = config_.bot});
Void::Log::info("Core", "{}", "Configuration reloaded from disk");
return {};
}
Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull()
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
Void::Log::info("Core", "{}", "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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
Void::Log::info("Core", "{}", "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()});
Void::Log::info("Core", "{}", "Hot reload restore complete");
return {};
}
Api::Result<std::string> Core::prepareForHotReload()
{
if (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
Void::Log::info("Core", "{}", "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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
Void::Log::info("Core", "{}", "Restoring after hot reload (decoupled)...");
// Deserialize state from JSON
auto parsed = Void::Json::parse(state);
if (!parsed) {
return Api::fail(
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 Api::fail(
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()});
Void::Log::info("Core", "{}", "Hot reload restore complete (decoupled)");
return {};
}
// ============================================================================
// Decoupled State Management - Plugin never knows state internals
// ============================================================================
Api::StateBlob Core::saveState()
{
Void::Log::info("Core", "{}", "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);
Void::Log::info("Core", "{}", std::format("State saved: version={}, size={} bytes",
blob.version, blob.size()));
return blob;
}
Api::Result<void> Core::restoreState(const Api::StateBlob& state)
{
Void::Log::info("Core", "{}",
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) {
Void::Log::warn("Core", "{}", 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
Void::Log::info("Core", "{}", 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) {
Void::Log::info("Core", "{}",
std::format("Restored queue entry: {} (ID: {})",
entry.track.title, *result));
} else {
Void::Log::warn("Core", "{}",
std::format("Failed to restore queue entry '{}': {}",
entry.track.title, result.error().message));
}
}
Void::Log::info("Core", "{}", "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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 (auto r = requireInitialized(); !r) {
return std::unexpected(r.error());
}
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 Api::fail(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)
{
Void::Log::debug("Core", "{}", std::format(
"Core::onPluginEvent called (this={}, initialized={})",
reinterpret_cast<uintptr_t>(this), initialized_.load()));
if (!initialized_) {
Void::Log::warn("Core", "{}",
std::format("Core::onPluginEvent: Core not initialized "
"(this={}), ignoring event type={}",
reinterpret_cast<uintptr_t>(this),
static_cast<int>(event.type)));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
// Debug logging for command events
if (event.type == Api::PluginEventType::TextMessageReceived &&
event.message) {
Void::Log::debug("Core", "{}",
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)) {
Void::Log::debug("Core", "{}",
std::format("Processing command: {} from client {}",
*event.message, event.clientId));
// Create reply callback
auto replyFunc = [this](uint64_t clientId,
std::string_view message) {
Void::Log::debug(
"Core", "{}",
std::format("Reply -> client {} ({} bytes)",
clientId, message.size()));
if (pluginInterface_) {
auto sent = pluginInterface_->sendTextMessage(
clientId, std::string(message));
if (!sent) {
Void::Log::warn(
"Core", "{}",
std::format("Reply send failed: {}",
sent.error().message));
}
} else {
Void::Log::warn("Core", "{}",
"Reply dropped: no plugin "
"interface");
}
};
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:
Void::Log::info("Core", "{}",
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:
Void::Log::info("Core", "{}",
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::Log::info("Core", "{}", 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()) {
Void::Log::info("Core", "{}",
"Plugin interface available, triggering auto-connect...");
triggerAutoConnect();
}
}
void Core::triggerAutoConnect()
{
if (!initialized_) {
Void::Log::warn("Core", "{}", "Cannot auto-connect: Core not initialized");
return;
}
if (!pluginInterface_) {
Void::Log::warn("Core", "{}",
"Cannot auto-connect: Plugin interface not set");
return;
}
if (config_.teamspeak.address.empty()) {
Void::Log::info("Core", "{}",
"Auto-connect skipped: No server address configured");
return;
}
Void::Log::info("Core", "{}", 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) {
Void::Log::error("Core", "{}", std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
Void::Log::info("Core", "{}", "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) {
Void::Log::error("Core", "{}",
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 = toJson(Dto::EventTrack{
.id = event.trackSummary->id,
.title = event.trackSummary->title,
.artist = event.trackSummary->artist,
.duration = event.trackSummary->duration
? event.trackSummary->duration->count() / 1000
: 0});
}
if (event.volume.has_value()) {
eventData = toJson(Dto::Volume{.volume = *event.volume});
}
if (event.queuePosition.has_value()) {
eventData = toJson(Dto::Position{
.position = static_cast<std::int64_t>(*event.queuePosition)});
}
if (event.clientId > 0) {
eventData = toJson(Dto::ClientId{.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_) {
Void::Log::warn("Core", "{}",
"updateWhisperList: pluginInterface or musicManager is null");
return;
}
auto subscribers = musicManager_->getSubscribedClients();
std::vector<uint64_t> subscriberVec(subscribers.begin(),
subscribers.end());
Void::Log::info("Core", "{}",
std::format("Updating whisper list with {} online subscribers",
subscriberVec.size()));
auto result = pluginInterface_->setWhisperList(subscriberVec);
if (!result) {
Void::Log::warn("Core", "{}", std::format("Failed to update whisper list: {}",
result.error().message));
} else {
Void::Log::info("Core", "{}", "Whisper list updated successfully");
}
}
void Core::generateRpcTokensForSubscribers()
{
if (!database_) {
return;
}
Void::Log::info("Core", "{}", "Generating RPC tokens for existing subscribers...");
// Get all subscriber UIDs
auto uidsResult = database_->getAllSubscriberUids();
if (!uidsResult) {
Void::Log::warn("Core", "{}", 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) {
Void::Log::warn("Core", "{}",
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) {
Void::Log::warn("Core", "{}",
std::format("Failed to generate token for UID {}: {}", uid,
tokenResult.error().message));
} else {
generatedCount++;
}
}
Void::Log::info("Core", "{}", std::format("RPC token generation complete: {} new "
"tokens generated, {} already existed",
generatedCount, existingCount));
}
} // namespace Echoion::Core