Route all logging through the Void::Log facade

Delete the echoion Logger adapter (Logger.{hpp,cpp}) and the
ILogger/LoggerRegistry indirection. Core::installLogging() builds the
console + split-file Void::Logging::MultiLogger and installs it as the
process-wide Void::Log sink via Void::Log::make_sink (logSink_ owns it for
the process lifetime). The ~450 ECHOION_LOG_* call sites across EchoionCore
are rewritten to Void::Log::<level>("<Subsystem>", "{}", <expr>) with
per-file module tags (warning->warn, critical->fatal); the pre-formatted
message is passed as the single "{}" argument. Build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-23 14:10:06 +03:00
1 parent 0e08ccaefa
commit 2d7651c308
42 files changed
+550 -792

No files matched your search

+14
View File
@@ -16,9 +16,15 @@
#include <Types.hpp>
#include <Void/Service/Registry.hpp>
#include <atomic>
#include <memory>
#include <mutex>
#include <thread>
namespace Void::Logging
{
class MultiLogger;
}
namespace Echoion::Core
{
@@ -154,6 +160,10 @@ namespace Echoion::Core
void setupRpcHandlers();
void setupEventBusSubscriptions() noexcept;
// Build the console + split-file logging stack and install it as
// the global Void::Log sink (logSink_ must outlive logging).
void installLogging();
// Components
std::shared_ptr<NetworkClient> networkClient_;
std::shared_ptr<MusicManager> musicManager_;
@@ -197,6 +207,10 @@ namespace Echoion::Core
// (replaces the former ConfigManager singleton).
Api::ConfigManager configManager_;
// Owns the logging stack installed as the global Void::Log sink;
// must outlive any logging (i.e. the whole process).
std::shared_ptr<Void::Logging::MultiLogger> logSink_;
public:
// Access the service registry (composition root).
-77
View File
@@ -1,77 +0,0 @@
#pragma once
#include <LoggerInterface.hpp>
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace Void::Logging
{
class MultiLogger;
} // namespace Void::Logging
namespace Echoion::Core
{
// ILogger implementation backed by the Void::Logging framework.
//
// Output is produced by a Void MultiLogger fanning out to:
// * a ConsoleLogger (stdout),
// * a SplitFileLogger writing per-level files (<dir>/<level>.log) plus a
// combined <dir>/all.log, each rolling independently by size, and
// * a CallbackLogger bridging back to the registered ILogger callbacks.
// The ILogger surface (levels, callbacks, console/file toggles, rotation
// knobs) is preserved so existing call sites and the ECHOION_LOG_* macros
// keep working unchanged.
class Logger : public Api::ILogger
{
public:
explicit Logger(std::string_view logDir = "logs",
std::string_view baseName = "echoion");
~Logger() override;
void log(Api::LogLevel level, std::string_view message,
std::source_location location) override;
void setMinLevel(Api::LogLevel level) override;
[[nodiscard]] Api::LogLevel getMinLevel() const override;
void registerCallback(const LogCallback& callback) override;
void unregisterCallback(const LogCallback& callback) override;
void flush();
void setConsoleOutput(bool enabled);
void setFileOutput(bool enabled);
void setMaxFileSize(uint64_t bytes);
void setMaxFiles(uint32_t count);
private:
// (Re)assemble the Void sink tree from the current toggles/limits.
void rebuildSinks();
// Fan a Void log entry out to the registered ILogger callbacks.
void dispatchToCallbacks(Api::LogLevel level,
const std::string& message,
const std::string& file, uint32_t line,
const std::string& function);
std::filesystem::path logDir_;
std::string baseName_;
std::shared_ptr<Void::Logging::MultiLogger> sink_;
std::mutex sinkMutex_;
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
std::atomic<bool> consoleOutput_{true};
std::atomic<bool> fileOutput_{true};
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB
std::atomic<uint32_t> maxFiles_{5};
std::vector<LogCallback> callbacks_;
std::mutex callbackMutex_;
};
} // namespace Echoion::Core
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->clearQueue();
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("ClearCommand", "{}",
std::format("Clear command failed: {}",
result.error().message));
ctx.reply(
@@ -33,7 +33,7 @@ namespace Echoion::Core
ctx.reply("Queue cleared!");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("ClearCommand", "{}",
std::format("Clear command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <charconv>
#include <format>
@@ -54,7 +54,7 @@ namespace Echoion::Core
auto moveResult = manager->moveInQueue(
from - 1, to - 1); // Convert to 0-based
if (!moveResult) {
ECHOION_LOG_ERROR(
Void::Log::error("MoveCommand", "{}",
std::format("Move command failed: {}",
moveResult.error().message));
@@ -72,7 +72,7 @@ namespace Echoion::Core
ctx.reply(std::format(
"Moved track from position {} to {}.", from, to));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("MoveCommand", "{}",
std::format("Move command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto current = manager->getCurrentTrack();
if (!current) {
ECHOION_LOG_ERROR(
Void::Log::error("NowPlayingCommand", "{}",
std::format("NowPlaying command failed: {}",
current.error().message));
ctx.reply("Couldn't get current track information.");
@@ -75,7 +75,7 @@ namespace Echoion::Core
ctx.reply(msg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("NowPlayingCommand", "{}", std::format(
"NowPlaying command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->pause();
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("PauseCommand", "{}",
std::format("Pause command failed: {}",
result.error().message));
@@ -39,7 +39,7 @@ namespace Echoion::Core
ctx.reply("Playback paused.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("PauseCommand", "{}",
std::format("Pause command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -31,7 +31,7 @@ namespace Echoion::Core
if (ctx.args.find("http") == 0) {
auto result = manager->play(ctx.args, ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("PlayCommand", "{}",
std::format("Play URL failed '{}': {}",
ctx.args, result.error().message));
@@ -60,7 +60,7 @@ namespace Echoion::Core
// Otherwise, treat as search query
auto searchResult = manager->search(ctx.args);
if (!searchResult) {
ECHOION_LOG_ERROR(
Void::Log::error("PlayCommand", "{}",
std::format("Search failed for '{}': {}", ctx.args,
searchResult.error().message));
@@ -85,7 +85,7 @@ namespace Echoion::Core
auto playResult =
manager->queueTrack(track, ctx.clientId);
if (!playResult) {
ECHOION_LOG_ERROR(
Void::Log::error("PlayCommand", "{}",
std::format("Queue failed: {}",
playResult.error().message));
ctx.reply(
@@ -141,7 +141,7 @@ namespace Echoion::Core
ctx.reply(msg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("PlayCommand", "{}",
std::format("Play command exception: {}", e.what()));
ctx.reply("Something went wrong while trying to play. "
"Please try again.");
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
#include <sstream>
@@ -26,7 +26,7 @@ namespace Echoion::Core
// List playlists
auto playlists = manager->getPlaylists();
if (!playlists) {
ECHOION_LOG_ERROR(
Void::Log::error("PlaylistCommand", "{}",
std::format("Playlist list failed: {}",
playlists.error().message));
ctx.reply("Couldn't retrieve playlists.");
@@ -51,7 +51,7 @@ namespace Echoion::Core
auto result = manager->loadPlaylist(
std::string(ctx.args), ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("PlaylistCommand", "{}",
std::format("Playlist load failed: {}",
result.error().message));
@@ -71,7 +71,7 @@ namespace Echoion::Core
ctx.args));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("PlaylistCommand", "{}", std::format(
"Playlist command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
#include <sstream>
@@ -27,7 +27,7 @@ namespace Echoion::Core
auto state = manager->getPlaybackState();
if (!queue) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("QueueCommand", "{}", std::format(
"Queue command failed: {}", queue.error().message));
ctx.reply("Couldn't get queue information.");
return;
@@ -161,7 +161,7 @@ namespace Echoion::Core
ctx.reply(msg.str());
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("QueueCommand", "{}",
std::format("Queue command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -15,7 +15,7 @@ namespace Echoion::Core
{
// This is a placeholder - actual reload is handled by the
// plugin
ECHOION_LOG_INFO("Reload requested by user");
Void::Log::info("ReloadCommand", "{}", "Reload requested by user");
ctx.reply("Reload is handled automatically by the plugin. Use "
"the TS3 plugin menu to reload the core.");
}
@@ -1,8 +1,8 @@
#pragma once
#include "Command.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/Core.hpp" // For Core::reloadConfig
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core
@@ -25,7 +25,7 @@ namespace Echoion::Core
// TODO: Add core reference to CommandContext so commands
// can call Core methods
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("ReloadConfigCommand", "{}", std::format(
"ReloadConfig command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <charconv>
#include <format>
@@ -44,7 +44,7 @@ namespace Echoion::Core
auto remResult = manager->removeFromQueue(
position - 1); // Convert to 0-based
if (!remResult) {
ECHOION_LOG_ERROR(
Void::Log::error("RemoveCommand", "{}",
std::format("Remove command failed: {}",
remResult.error().message));
@@ -62,7 +62,7 @@ namespace Echoion::Core
ctx.reply(
std::format("Removed track at position {}.", position));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RemoveCommand", "{}",
std::format("Remove command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->toggleRepeat();
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("RepeatCommand", "{}",
std::format("Repeat command failed: {}",
result.error().message));
ctx.reply("Couldn't toggle repeat. Please try again.");
@@ -33,7 +33,7 @@ namespace Echoion::Core
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON."
: "Repeat is now OFF.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RepeatCommand", "{}",
std::format("Repeat command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->resume();
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("ResumeCommand", "{}",
std::format("Resume command failed: {}",
result.error().message));
@@ -39,7 +39,7 @@ namespace Echoion::Core
ctx.reply("Playback resumed.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("ResumeCommand", "{}",
std::format("Resume command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
#include <sstream>
@@ -30,7 +30,7 @@ namespace Echoion::Core
auto result = manager->search(ctx.args);
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("SearchCommand", "{}",
std::format("Search failed for '{}': {}", ctx.args,
result.error().message));
@@ -87,7 +87,7 @@ namespace Echoion::Core
ctx.reply(msg.str());
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("SearchCommand", "{}",
std::format("Search command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <charconv>
#include <chrono>
#include <format>
@@ -94,7 +94,7 @@ namespace Echoion::Core
auto result = manager->seek(targetPosition);
if (!result) {
ECHOION_LOG_ERROR(std::format("Seek command failed: {}",
Void::Log::error("SeekCommand", "{}", std::format("Seek command failed: {}",
result.error().message));
if (result.error().code ==
@@ -117,7 +117,7 @@ namespace Echoion::Core
std::format("Seeked to position {}.", positionStr));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("SeekCommand", "{}",
std::format("Seek command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <charconv>
#include <format>
@@ -45,7 +45,7 @@ namespace Echoion::Core
ctx.clientId, index, invokerName);
if (!selectResult) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SelectCommand", "{}", std::format(
"Select failed for client {} index {}: {}",
ctx.clientId, index, selectResult.error().message));
@@ -65,7 +65,7 @@ namespace Echoion::Core
ctx.reply(*selectResult);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("SelectCommand", "{}",
std::format("Select command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -26,7 +26,7 @@ namespace Echoion::Core
ctx.reply("\xf0\x9f\x94\x80 Queue shuffled!");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("ShuffleCommand", "{}",
std::format("Shuffle command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <charconv>
#include <format>
@@ -37,7 +37,7 @@ namespace Echoion::Core
auto result = manager->skip(count);
if (!result) {
ECHOION_LOG_ERROR(std::format("Skip command failed: {}",
Void::Log::error("SkipCommand", "{}", std::format("Skip command failed: {}",
result.error().message));
if (result.error().code == Api::ErrorCode::NotFound) {
@@ -55,7 +55,7 @@ namespace Echoion::Core
ctx.reply(std::format("Skipped {} tracks.", count));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("SkipCommand", "{}",
std::format("Skip command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->stop();
if (!result) {
ECHOION_LOG_ERROR(std::format("Stop command failed: {}",
Void::Log::error("StopCommand", "{}", std::format("Stop command failed: {}",
result.error().message));
ctx.reply("Couldn't stop playback. Please try again.");
return;
@@ -31,7 +31,7 @@ namespace Echoion::Core
ctx.reply("Playback stopped and queue cleared.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("StopCommand", "{}",
std::format("Stop command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->subscribe(ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}",
Void::Log::error("SubscribeCommand", "{}", std::format("Subscribe failed: {}",
result.error().message));
ctx.reply("Couldn't subscribe you. Please try again.");
return;
@@ -31,7 +31,7 @@ namespace Echoion::Core
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SubscribeCommand", "{}", std::format(
"Subscribe command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/MusicManager.hpp"
#include <algorithm>
#include <format>
@@ -82,7 +82,7 @@ namespace Echoion::Core
ctx.reply(msg.str());
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SubscribersCommand", "{}", std::format(
"Subscribers command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/MusicManager.hpp"
#include <format>
@@ -25,7 +25,7 @@ namespace Echoion::Core
auto result = manager->clearAllSubscriptions();
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("UnsubscribeAllCommand", "{}",
std::format("Unsubscribe all failed: {}",
result.error().message));
ctx.reply(
@@ -35,7 +35,7 @@ namespace Echoion::Core
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("UnsubscribeAllCommand", "{}", std::format(
"Unsubscribeall command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <format>
namespace Echoion::Core
@@ -23,7 +23,7 @@ namespace Echoion::Core
auto result = manager->unsubscribe(ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}",
Void::Log::error("UnsubscribeCommand", "{}", std::format("Unsubscribe failed: {}",
result.error().message));
ctx.reply(
"Couldn't unsubscribe you. Please try again.");
@@ -32,7 +32,7 @@ namespace Echoion::Core
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("UnsubscribeCommand", "{}", std::format(
"Unsubscribe command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/MusicManager.hpp"
#include <format>
@@ -32,7 +32,7 @@ namespace Echoion::Core
auto result = manager->unsubscribeByUid(uid);
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("UnsubscribeIdCommand", "{}",
std::format("Unsubscribe by ID failed: {}",
result.error().message));
ctx.reply(
@@ -42,7 +42,7 @@ namespace Echoion::Core
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("UnsubscribeIdCommand", "{}", std::format(
"Unsubscribeid command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
@@ -1,7 +1,7 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <charconv>
#include <format>
@@ -54,7 +54,7 @@ namespace Echoion::Core
float volume = volumePercent / 100.0f;
auto volResult = manager->setVolume(volume);
if (!volResult) {
ECHOION_LOG_ERROR(
Void::Log::error("VolumeCommand", "{}",
std::format("Volume command failed: {}",
volResult.error().message));
ctx.reply("Couldn't change volume. Please try again.");
@@ -74,7 +74,7 @@ namespace Echoion::Core
ctx.reply(std::format(
"Volume: {}% {}", volumePercent, indicator));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("VolumeCommand", "{}",
std::format("Volume command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
+15 -15
View File
@@ -1,4 +1,4 @@
#include "LoggerInterface.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/AudioDecoder.hpp"
extern "C" {
#include <libavcodec/avcodec.h>
@@ -41,7 +41,7 @@ namespace Echoion::Core
if (hwConfig.isEnabled()) {
auto result = initializeHardwareAccel(hwConfig);
if (!result) {
ECHOION_LOG_WARNING(
Void::Log::warn("AudioDecoder", "{}",
std::format("Hardware acceleration init failed: {}, "
"falling back to software",
result.error().message));
@@ -49,7 +49,7 @@ namespace Echoion::Core
}
av_log_set_level(AV_LOG_DEBUG);
initialized_ = true;
ECHOION_LOG_INFO("AudioDecoder initialized");
Void::Log::info("AudioDecoder", "{}", "AudioDecoder initialized");
return {};
}
@@ -87,7 +87,7 @@ namespace Echoion::Core
}
hwAccelType_ = config.type;
ECHOION_LOG_INFO(std::format("Hardware acceleration configured: {}",
Void::Log::info("AudioDecoder", "{}", std::format("Hardware acceleration configured: {}",
av_hwdevice_get_type_name(hwType)));
return {};
@@ -180,12 +180,12 @@ namespace Echoion::Core
}
av_dict_set(&options, "proxy", proxyUrl.c_str(), 0);
ECHOION_LOG_INFO(std::format("Using proxy for ffmpeg: {}:{}",
Void::Log::info("AudioDecoder", "{}", std::format("Using proxy for ffmpeg: {}:{}",
proxyConfig_->host,
proxyConfig_->port));
}
ECHOION_LOG_DEBUG(
Void::Log::debug("AudioDecoder", "{}",
std::format("Opening audio source: {}", url.substr(0, 80)));
// Allocate format context first (needed for interrupt callback)
@@ -214,7 +214,7 @@ namespace Echoion::Core
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format(
Void::Log::error("AudioDecoder", "{}", std::format(
"FFmpeg failed to open input (error {}): {}", ret, errbuf));
return Api::fail(
Api::ErrorCode::AudioError,
@@ -222,13 +222,13 @@ namespace Echoion::Core
"Failed to open audio source: {} (FFmpeg error {}: {})",
url.substr(0, 80), ret, errbuf));
}
ECHOION_LOG_DEBUG("avformat_open_input succeeded");
Void::Log::debug("AudioDecoder", "{}", "avformat_open_input succeeded");
ret = avformat_find_stream_info(formatContext_, nullptr);
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(
Void::Log::error("AudioDecoder", "{}",
std::format("FFmpeg failed to find stream info (error {}): {}",
ret, errbuf));
avformat_close_input(&formatContext_);
@@ -348,7 +348,7 @@ namespace Echoion::Core
shouldExit_ = false;
decodeThread_ = std::jthread(&AudioDecoder::decodeThread, this);
ECHOION_LOG_INFO(std::format(
Void::Log::info("AudioDecoder", "{}", std::format(
"Audio source opened: {} -> {} Hz, {} ch, in={} out=S16", url,
outputSampleRate_, outputChannels_,
av_get_sample_fmt_name(codecContext_->sample_fmt)));
@@ -389,7 +389,7 @@ namespace Echoion::Core
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
ECHOION_LOG_DEBUG(std::format("Frame consumed: {} samples, {} ms",
Void::Log::debug("AudioDecoder", "{}", std::format("Frame consumed: {} samples, {} ms",
audio.view.samplesPerChannel() * 2,
audio.timestamp.count()));
@@ -424,7 +424,7 @@ namespace Echoion::Core
cv_.notify_one();
if (callCount <= 10 || callCount % 1000 == 0) {
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("AudioDecoder", "{}", std::format(
"getNextChunk {}: returned {} samples, queue left: {}",
callCount, outChunk.size(), int16Queue_.size()));
}
@@ -504,7 +504,7 @@ namespace Echoion::Core
void AudioDecoder::decodeThread()
{
ECHOION_LOG_DEBUG("Decode thread started");
Void::Log::debug("AudioDecoder", "{}", "Decode thread started");
constexpr int maxSamples = 4096;
int packetsRead = 0;
int framesProduced = 0;
@@ -571,7 +571,7 @@ namespace Echoion::Core
framesProduced++;
if (framesProduced <= 5) {
ECHOION_LOG_DEBUG(
Void::Log::debug("AudioDecoder", "{}",
std::format("Decode produced frame {}: {} samples",
framesProduced, chunk.size()));
}
@@ -611,7 +611,7 @@ namespace Echoion::Core
eof_ = true;
cv_.notify_all();
ECHOION_LOG_INFO(std::format("Decode finished. Packets: {}, Frames: {}",
Void::Log::info("AudioDecoder", "{}", std::format("Decode finished. Packets: {}, Frames: {}",
packetsRead, framesProduced));
}
+5 -5
View File
@@ -1,5 +1,5 @@
#include "echoion/core/CommandManager.hpp"
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/commands/Command.hpp"
#include <ConfigTypes.hpp>
@@ -82,7 +82,7 @@ namespace Echoion::Core
ctx.reply(helpMsg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("CommandManager", "{}",
std::format("Help command exception: {}", e.what()));
ctx.reply("Couldn't generate help. Please try again.");
}
@@ -128,7 +128,7 @@ namespace Echoion::Core
{
pool_ =
std::make_unique<Void::Concurrency::ThreadPool>(THREAD_POOL_SIZE);
ECHOION_LOG_INFO(
Void::Log::info("CommandManager", "{}",
std::format("CommandManager thread pool started with {} workers",
THREAD_POOL_SIZE));
}
@@ -197,7 +197,7 @@ namespace Echoion::Core
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("CommandManager", "{}",
std::format("Async command execution error: {}", e.what()));
try {
task.replyFunc(
@@ -338,7 +338,7 @@ namespace Echoion::Core
try {
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("CommandManager", "{}", std::format(
"Command execution error [{}]: {}", cmdKey, e.what()));
ctx.reply(
"An unexpected error occurred. Our team has been notified.");
+3 -2
View File
@@ -1,4 +1,4 @@
#include "LoggerInterface.hpp"
#include <Void/Log/Log.hpp>
#include "Types.hpp"
#include "echoion/core/ConfigLoader.hpp"
#include <AudioTypes.hpp>
@@ -6,6 +6,7 @@
#include <Void/Data/Reflect.hpp>
#include <format>
#include <fstream>
#include <iostream>
#include <string>
namespace Echoion::Core
@@ -83,7 +84,7 @@ namespace Echoion::Core
file << json;
file.close();
ECHOION_LOG_INFO(
Void::Log::info("ConfigLoader", "{}",
std::format("Configuration saved to {}", path.string()));
return {};
}
+116 -82
View File
@@ -1,7 +1,5 @@
#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>
@@ -9,13 +7,52 @@
#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
{
@@ -31,6 +68,13 @@ namespace Echoion::Core
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);
}
Core::~Core()
{
if (initialized_) {
@@ -44,9 +88,7 @@ namespace Echoion::Core
return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already initialized");
}
auto logger = std::make_shared<Logger>();
logger->setMinLevel(Api::LogLevel::Debug);
Api::LoggerRegistry::instance().setLogger(logger);
installLogging();
// Store config path for later reload
configPath_ = configPath;
@@ -55,7 +97,7 @@ namespace Echoion::Core
auto configResult = ConfigLoader::loadFromFile(configPath);
if (!configResult) {
// Try to create default config
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
std::format("Failed to load config: {}, creating default",
configResult.error().message));
config_ = ConfigLoader::createDefaultConfig();
@@ -66,22 +108,19 @@ namespace Echoion::Core
// Initialize global ConfigManager with loaded config
configManager_.updateConfig(config_, false);
ECHOION_LOG_INFO("Global ConfigManager initialized");
Void::Log::info("Core", "{}", "Global ConfigManager initialized");
// Note: logLevel was removed from BotConfig, using Debug as default
Api::LoggerRegistry::instance().getLogger()->setMinLevel(
Api::LogLevel::Debug);
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
std::format("Core loaded config - Server: {}:{}, Nickname: {}",
config_.teamspeak.address, config_.teamspeak.port,
config_.teamspeak.nickname));
// Initialize logger
ECHOION_LOG_INFO("Initializing Echoion Core...");
Void::Log::info("Core", "{}", "Initializing Echoion Core...");
// The async event bus runs from construction; nothing to start.
ECHOION_LOG_INFO("EventBus ready");
Void::Log::info("Core", "{}", "EventBus ready");
// Initialize network client
networkClient_ = std::make_shared<NetworkClient>();
@@ -96,12 +135,12 @@ namespace Echoion::Core
dbConfig.path = configPath.parent_path() / "echoion.db";
auto dbResult = database_->initialize(dbConfig);
if (!dbResult) {
ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}",
Void::Log::warn("Core", "{}", std::format("Failed to initialize database: {}",
dbResult.error().message));
// Not fatal - continue without database
database_ = nullptr;
} else {
ECHOION_LOG_INFO("Database initialized successfully");
Void::Log::info("Core", "{}", "Database initialized successfully");
// Generate RPC tokens for existing subscribers
this->generateRpcTokensForSubscribers();
@@ -150,7 +189,7 @@ namespace Echoion::Core
// Check if server groups are available
if (clientInfo.serverGroups.empty()) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
"Cannot check admin permissions: server "
"groups not available for client " +
std::to_string(clientId));
@@ -190,7 +229,7 @@ namespace Echoion::Core
if (std::chrono::duration_cast<std::chrono::seconds>(
now - lastLog)
.count() >= 5) {
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("Core", "{}", std::format(
"Audio callback: {} calls, {} samples, result: {}",
callCount, data.size(),
result.has_value() ? "ok" : "error"));
@@ -213,25 +252,25 @@ namespace Echoion::Core
[this](uint64_t clientId)
-> std::optional<std::pair<std::string, std::string>> {
if (!pluginInterface_) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
"ClientInfoCallback: pluginInterface is null");
return std::nullopt;
}
auto clientInfoResult = pluginInterface_->getClient(clientId);
if (!clientInfoResult || !clientInfoResult->has_value()) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("Core", "{}", std::format(
"ClientInfoCallback: getClient failed for client {}",
clientId));
return std::nullopt;
}
auto clientInfo = clientInfoResult->value();
if (!clientInfo.uniqueIdentifier) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("Core", "{}", std::format(
"ClientInfoCallback: client {} has no uniqueIdentifier",
clientId));
return std::nullopt;
}
ECHOION_LOG_DEBUG(
Void::Log::debug("Core", "{}",
std::format("ClientInfoCallback: Got UID for client {}: {}",
clientId, *clientInfo.uniqueIdentifier));
return std::make_pair(*clientInfo.uniqueIdentifier,
@@ -280,12 +319,12 @@ namespace Echoion::Core
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: {}",
Void::Log::warn("Core", "{}", std::format("Failed to start RPC server: {}",
rpcResult.error().message));
// Not fatal - continue without RPC
rpcServer_.reset();
} else {
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
setupEventBusSubscriptions();
@@ -294,18 +333,13 @@ namespace Echoion::Core
// ── 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.
// The three former singletons (logger, config, event bus) are wrapped
// in non-owning aliasing shared_ptrs — they remain valid statics behind
// the ECHOION_LOG_*/PUBLISH/SUBSCRIBE macros, the registry just makes
// them discoverable as services too.
// 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*) {});
};
if (auto logger = Api::LoggerRegistry::instance().getLogger()) {
registry_.provide<Api::ILogger>(logger);
}
registry_.provide<Api::ConfigManager>(
alias(&configManager_));
registry_.provide<Void::EventBus::EventBus>(alias(&eventBus_));
@@ -321,22 +355,22 @@ namespace Echoion::Core
if (rpcServer_) {
registry_.provide<RpcServer>(rpcServer_);
}
ECHOION_LOG_INFO("Service registry composed");
Void::Log::info("Core", "{}", "Service registry composed");
}
startTime_ = std::chrono::system_clock::now();
initialized_ = true;
ECHOION_LOG_INFO(std::format("Core initialized (this={})",
Void::Log::info("Core", "{}", std::format("Core initialized (this={})",
reinterpret_cast<uintptr_t>(this)));
unsigned int hwThreads = std::thread::hardware_concurrency();
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
std::format("Hardware concurrency: {} threads", hwThreads));
ECHOION_LOG_INFO("Echoion Core initialized successfully");
Void::Log::info("Core", "{}", "Echoion Core initialized successfully");
// Auto-connect to server if configured
if (!config_.teamspeak.address.empty() && pluginInterface_) {
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
Void::Log::info("Core", "{}", std::format("Auto-connecting to {}:{}...",
config_.teamspeak.address,
config_.teamspeak.port));
@@ -355,10 +389,10 @@ namespace Echoion::Core
auto connectResult =
pluginInterface_->connectToServer(serverConfig);
if (!connectResult) {
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
Void::Log::error("Core", "{}", std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
ECHOION_LOG_INFO("Auto-connect initiated");
Void::Log::info("Core", "{}", "Auto-connect initiated");
}
}
@@ -371,7 +405,7 @@ namespace Echoion::Core
return {};
}
ECHOION_LOG_INFO("Shutting down Echoion Core...");
Void::Log::info("Core", "{}", "Shutting down Echoion Core...");
if (commandManager_) {
commandManager_->shutdown();
@@ -397,7 +431,7 @@ namespace Echoion::Core
// Drain any in-flight event dispatch.
eventBus_.flush();
ECHOION_LOG_INFO("EventBus stopped");
Void::Log::info("Core", "{}", "EventBus stopped");
// Clear callbacks
{
@@ -406,7 +440,7 @@ namespace Echoion::Core
}
initialized_ = false;
ECHOION_LOG_INFO(std::format("Echoion Core shutdown complete (this={})",
Void::Log::info("Core", "{}", std::format("Echoion Core shutdown complete (this={})",
reinterpret_cast<uintptr_t>(this)));
return {};
}
@@ -902,7 +936,7 @@ namespace Echoion::Core
commandManager_->setServerConfig(config_);
}
ECHOION_LOG_INFO("Configuration reloaded from disk");
Void::Log::info("Core", "{}", "Configuration reloaded from disk");
return {};
}
@@ -913,7 +947,7 @@ namespace Echoion::Core
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Preparing for hot reload...");
Void::Log::info("Core", "{}", "Preparing for hot reload...");
broadcastEvent(
Api::PluginEvent{.type = Api::PluginEventType::HotReloadRequested,
@@ -931,7 +965,7 @@ namespace Echoion::Core
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Restoring after hot reload...");
Void::Log::info("Core", "{}", "Restoring after hot reload...");
auto result = musicManager_->restoreFromHotReload(state);
if (!result) {
@@ -943,7 +977,7 @@ namespace Echoion::Core
.clientId = 0,
.timestamp = std::chrono::system_clock::now()});
ECHOION_LOG_INFO("Hot reload restore complete");
Void::Log::info("Core", "{}", "Hot reload restore complete");
return {};
}
@@ -954,7 +988,7 @@ namespace Echoion::Core
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Preparing for hot reload (decoupled)...");
Void::Log::info("Core", "{}", "Preparing for hot reload (decoupled)...");
broadcastEvent(
Api::PluginEvent{.type = Api::PluginEventType::HotReloadRequested,
@@ -974,7 +1008,7 @@ namespace Echoion::Core
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Restoring after hot reload (decoupled)...");
Void::Log::info("Core", "{}", "Restoring after hot reload (decoupled)...");
// Deserialize state from JSON
auto parsed = Void::Json::parse(state);
@@ -1005,7 +1039,7 @@ namespace Echoion::Core
.clientId = 0,
.timestamp = std::chrono::system_clock::now()});
ECHOION_LOG_INFO("Hot reload restore complete (decoupled)");
Void::Log::info("Core", "{}", "Hot reload restore complete (decoupled)");
return {};
}
@@ -1015,7 +1049,7 @@ namespace Echoion::Core
Api::StateBlob Core::saveState()
{
ECHOION_LOG_INFO("Saving Core state...");
Void::Log::info("Core", "{}", "Saving Core state...");
StateV1 state;
@@ -1055,7 +1089,7 @@ namespace Echoion::Core
// Serialize using StateSerializer
auto blob = StateSerializer::serialize(state);
ECHOION_LOG_INFO(std::format("State saved: version={}, size={} bytes",
Void::Log::info("Core", "{}", std::format("State saved: version={}, size={} bytes",
blob.version, blob.size()));
return blob;
@@ -1063,14 +1097,14 @@ namespace Echoion::Core
Api::Result<void> Core::restoreState(const Api::StateBlob& state)
{
ECHOION_LOG_INFO(
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) {
ECHOION_LOG_WARNING(result.error().message);
Void::Log::warn("Core", "{}", result.error().message);
}
return std::unexpected(result.error());
}
@@ -1083,7 +1117,7 @@ namespace Echoion::Core
// 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: {} - {}",
Void::Log::info("Core", "{}", std::format("Restoring playback: {} - {}",
playback.currentTrack.title,
playback.currentTrack.artist));
}
@@ -1093,17 +1127,17 @@ namespace Echoion::Core
// Add to music manager queue
auto result = musicManager_->queueTrack(entry.track, 0);
if (result) {
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
std::format("Restored queue entry: {} (ID: {})",
entry.track.title, *result));
} else {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
std::format("Failed to restore queue entry '{}': {}",
entry.track.title, result.error().message));
}
}
ECHOION_LOG_INFO("State restored successfully");
Void::Log::info("Core", "{}", "State restored successfully");
return {};
}
@@ -1200,11 +1234,11 @@ namespace Echoion::Core
Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event)
{
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("Core", "{}", std::format(
"Core::onPluginEvent called (this={}, initialized={})",
reinterpret_cast<uintptr_t>(this), initialized_.load()));
if (!initialized_) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
std::format("Core::onPluginEvent: Core not initialized "
"(this={}), ignoring event type={}",
reinterpret_cast<uintptr_t>(this),
@@ -1216,7 +1250,7 @@ namespace Echoion::Core
// Debug logging for command events
if (event.type == Api::PluginEventType::TextMessageReceived &&
event.message) {
ECHOION_LOG_DEBUG(
Void::Log::debug("Core", "{}",
std::format("Core received message: {} from client {}",
*event.message, event.clientId));
}
@@ -1226,7 +1260,7 @@ namespace Echoion::Core
if (event.message) {
// Check if it's a command
if (event.message->starts_with(config_.bot.commandPrefix)) {
ECHOION_LOG_DEBUG(
Void::Log::debug("Core", "{}",
std::format("Processing command: {} from client {}",
*event.message, event.clientId));
// Create reply callback
@@ -1262,7 +1296,7 @@ namespace Echoion::Core
break;
case Api::PluginEventType::ClientConnected:
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
std::format("Client {} connected, updating whisper list",
event.clientId));
if (musicManager_) {
@@ -1273,7 +1307,7 @@ namespace Echoion::Core
break;
case Api::PluginEventType::ClientDisconnected:
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
std::format("Client {} disconnected", event.clientId));
if (musicManager_) {
musicManager_->onClientDisconnected(event.clientId);
@@ -1301,7 +1335,7 @@ namespace Echoion::Core
void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface)
{
pluginInterface_ = std::move(pluginInterface);
ECHOION_LOG_INFO(std::format("Plugin interface set (this={})",
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
@@ -1311,7 +1345,7 @@ namespace Echoion::Core
// Trigger auto-connect now that plugin interface is available
if (initialized_ && !config_.teamspeak.address.empty()) {
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
"Plugin interface available, triggering auto-connect...");
triggerAutoConnect();
}
@@ -1320,23 +1354,23 @@ namespace Echoion::Core
void Core::triggerAutoConnect()
{
if (!initialized_) {
ECHOION_LOG_WARNING("Cannot auto-connect: Core not initialized");
Void::Log::warn("Core", "{}", "Cannot auto-connect: Core not initialized");
return;
}
if (!pluginInterface_) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
"Cannot auto-connect: Plugin interface not set");
return;
}
if (config_.teamspeak.address.empty()) {
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
"Auto-connect skipped: No server address configured");
return;
}
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
Void::Log::info("Core", "{}", std::format("Auto-connecting to {}:{}...",
config_.teamspeak.address,
config_.teamspeak.port));
@@ -1354,10 +1388,10 @@ namespace Echoion::Core
auto connectResult = pluginInterface_->connectToServer(serverConfig);
if (!connectResult) {
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
Void::Log::error("Core", "{}", std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
ECHOION_LOG_INFO("Auto-connect initiated");
Void::Log::info("Core", "{}", "Auto-connect initiated");
}
}
@@ -1378,7 +1412,7 @@ namespace Echoion::Core
try {
callback(event);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("Core", "{}",
std::format("Event callback error: {}", e.what()));
}
}
@@ -1470,7 +1504,7 @@ namespace Echoion::Core
void Core::updateWhisperList()
{
if (!pluginInterface_ || !musicManager_) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
"updateWhisperList: pluginInterface or musicManager is null");
return;
}
@@ -1479,16 +1513,16 @@ namespace Echoion::Core
std::vector<uint64_t> subscriberVec(subscribers.begin(),
subscribers.end());
ECHOION_LOG_INFO(
Void::Log::info("Core", "{}",
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: {}",
Void::Log::warn("Core", "{}", std::format("Failed to update whisper list: {}",
result.error().message));
} else {
ECHOION_LOG_INFO("Whisper list updated successfully");
Void::Log::info("Core", "{}", "Whisper list updated successfully");
}
}
@@ -1621,7 +1655,7 @@ namespace Echoion::Core
tsClientId, pmMessage);
if (!pmResult) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("Core", "{}", std::format(
"Failed to send PM with token: {}",
pmResult.error().message));
}
@@ -1793,7 +1827,7 @@ namespace Echoion::Core
return json;
});
ECHOION_LOG_INFO("RPC handlers registered");
Void::Log::info("Core", "{}", "RPC handlers registered");
}
void Core::setupEventBusSubscriptions() noexcept
@@ -2014,7 +2048,7 @@ namespace Echoion::Core
}
});
ECHOION_LOG_INFO("EventBus subscriptions set up");
Void::Log::info("Core", "{}", "EventBus subscriptions set up");
}
void Core::generateRpcTokensForSubscribers()
@@ -2023,12 +2057,12 @@ namespace Echoion::Core
return;
}
ECHOION_LOG_INFO("Generating RPC tokens for existing subscribers...");
Void::Log::info("Core", "{}", "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: {}",
Void::Log::warn("Core", "{}", std::format("Failed to get subscriber UIDs: {}",
uidsResult.error().message));
return;
}
@@ -2040,7 +2074,7 @@ namespace Echoion::Core
// Check if token already exists
auto existingToken = database_->getExistingRpcToken(uid);
if (!existingToken) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
std::format("Failed to check existing token for UID {}: {}",
uid, existingToken.error().message));
continue;
@@ -2054,7 +2088,7 @@ namespace Echoion::Core
// Generate new token
auto tokenResult = database_->generateRpcToken(uid);
if (!tokenResult) {
ECHOION_LOG_WARNING(
Void::Log::warn("Core", "{}",
std::format("Failed to generate token for UID {}: {}", uid,
tokenResult.error().message));
} else {
@@ -2062,7 +2096,7 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO(std::format("RPC token generation complete: {} new "
Void::Log::info("Core", "{}", std::format("RPC token generation complete: {} new "
"tokens generated, {} already existed",
generatedCount, existingCount));
}
+6 -6
View File
@@ -1,5 +1,5 @@
#include <Database.hpp>
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <Void/Math/Random.hpp>
#include <Void/Sqlite/Sqlite.hpp>
#include <cstring>
@@ -73,7 +73,7 @@ namespace Echoion::Api
}
impl_->initialized = true;
ECHOION_LOG_INFO(std::format("Database initialized: {}", config.path));
Void::Log::info("Database", "{}", std::format("Database initialized: {}", config.path));
return {};
}
@@ -206,7 +206,7 @@ namespace Echoion::Api
"INSERT INTO schema_migrations (version) VALUES (1)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO("Database migration 1 applied");
Void::Log::info("Database", "{}", "Database migration 1 applied");
}
// Migration 2: Fix subscriptions table to use UID
@@ -234,7 +234,7 @@ namespace Echoion::Api
"INSERT INTO schema_migrations (version) VALUES (2)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO(
Void::Log::info("Database", "{}",
"Database migration 2 applied: subscriptions now use UID");
}
@@ -267,7 +267,7 @@ namespace Echoion::Api
"INSERT INTO schema_migrations (version) VALUES (3)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO("Database migration 3 applied: playlists now "
Void::Log::info("Database", "{}", "Database migration 3 applied: playlists now "
"support external_id");
}
@@ -296,7 +296,7 @@ namespace Echoion::Api
"INSERT INTO schema_migrations (version) VALUES (4)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO(
Void::Log::info("Database", "{}",
"Database migration 4 applied: RPC tokens table added");
}
-213
View File
@@ -1,213 +0,0 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/Entry.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Level.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <algorithm>
#include <iostream>
namespace
{
[[nodiscard]] Void::Logging::Level toVoidLevel(Echoion::Api::LogLevel level)
{
using A = Echoion::Api::LogLevel;
using V = Void::Logging::Level;
switch (level) {
case A::Debug:
return V::Debug;
case A::Info:
return V::Info;
case A::Warning:
return V::Warning;
case A::Error:
return V::Error;
case A::Critical:
return V::Fatal;
}
return V::Info;
}
[[nodiscard]] Echoion::Api::LogLevel fromVoidLevel(Void::Logging::Level level)
{
using A = Echoion::Api::LogLevel;
using V = Void::Logging::Level;
switch (level) {
case V::Trace:
case V::Debug:
return A::Debug;
case V::Info:
return A::Info;
case V::Warning:
return A::Warning;
case V::Error:
return A::Error;
case V::Fatal:
return A::Critical;
case V::Disabled:
return A::Debug;
}
return A::Info;
}
} // namespace
namespace Echoion::Core
{
Logger::Logger(std::string_view logDir, std::string_view baseName)
: logDir_(logDir), baseName_(baseName)
{
std::error_code ec;
std::filesystem::create_directories(logDir_, ec);
rebuildSinks();
}
Logger::~Logger()
{
std::lock_guard<std::mutex> lock(sinkMutex_);
if (sink_) {
sink_->flush();
sink_.reset();
}
}
void Logger::rebuildSinks()
{
namespace VL = Void::Logging;
auto multi = std::make_shared<VL::MultiLogger>();
// Shared layout approximating the previous Logger output:
// [2024-01-01 12:00:00.123] [INFO] [thread] file.cpp - message
auto formatter = std::make_shared<const VL::PatternFormatter>(
"[{time}] [{level}] [{thread}] {file} - {message}");
if (consoleOutput_.load()) {
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
console->set_formatter(formatter);
multi->add(std::move(console));
}
if (fileOutput_.load()) {
VL::SplitFileOptions opts;
opts.combined = true; // also write <dir>/all.log
opts.max_bytes = static_cast<std::size_t>(maxFileSize_.load());
opts.max_files = static_cast<std::size_t>(maxFiles_.load());
if (auto fileSink = VL::SplitFileLogger::open(logDir_, opts)) {
(*fileSink)->set_formatter(formatter);
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
}
}
// Bridge Void entries back to the registered ILogger callbacks so
// existing log subscribers (e.g. RPC log streaming) keep receiving
// Api::LogEntry records, asynchronously as before.
multi->add(std::make_shared<VL::CallbackLogger>(
[this](const VL::Entry& entry) {
dispatchToCallbacks(fromVoidLevel(entry.level), entry.message,
entry.location.file_name(),
entry.location.line(),
entry.location.function_name());
}));
std::lock_guard<std::mutex> lock(sinkMutex_);
sink_ = std::move(multi);
}
void Logger::dispatchToCallbacks(Api::LogLevel level,
const std::string& message,
const std::string& file, uint32_t line,
const std::string& function)
{
std::lock_guard<std::mutex> lock(callbackMutex_);
if (callbacks_.empty()) {
return;
}
Api::LogEntry entry;
entry.level = level;
entry.message = message;
entry.sourceFile = file;
entry.sourceLine = line;
entry.function = function;
entry.threadId = std::this_thread::get_id();
entry.timestamp = std::chrono::system_clock::now();
for (const auto& callback : callbacks_) {
callback(entry);
}
}
void Logger::log(Api::LogLevel level, std::string_view message,
std::source_location location)
{
if (level < minLevel_.load()) {
return;
}
std::shared_ptr<Void::Logging::MultiLogger> sink;
{
std::lock_guard<std::mutex> lock(sinkMutex_);
sink = sink_;
}
if (sink) {
sink->log(toVoidLevel(level), message, location);
}
}
void Logger::setMinLevel(Api::LogLevel level) { minLevel_.store(level); }
Api::LogLevel Logger::getMinLevel() const { return minLevel_.load(); }
void Logger::registerCallback(const LogCallback& callback)
{
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.push_back(callback);
}
void Logger::unregisterCallback(const LogCallback& callback)
{
std::lock_guard<std::mutex> lock(callbackMutex_);
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
[&callback](const auto& cb) {
return &cb == &callback;
}),
callbacks_.end());
}
void Logger::flush()
{
std::lock_guard<std::mutex> lock(sinkMutex_);
if (sink_) {
sink_->flush();
}
}
void Logger::setConsoleOutput(bool enabled)
{
consoleOutput_.store(enabled);
rebuildSinks();
}
void Logger::setFileOutput(bool enabled)
{
fileOutput_.store(enabled);
rebuildSinks();
}
void Logger::setMaxFileSize(uint64_t bytes)
{
maxFileSize_.store(bytes);
rebuildSinks();
}
void Logger::setMaxFiles(uint32_t count)
{
maxFiles_.store(count);
rebuildSinks();
}
} // namespace Echoion::Core
+3 -3
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include <MemoryPool.hpp>
#include <format>
#include <vector>
@@ -27,7 +27,7 @@ namespace Echoion::Api
}
} // buffers returned to the pool here
ECHOION_LOG_INFO(std::format(
Void::Log::info("MemoryPool", "{}", std::format(
"AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
poolSize, bufferSize,
(bufferSize * poolSize * sizeof(int16_t)) / 1024));
@@ -36,7 +36,7 @@ namespace Echoion::Api
void AudioBufferPool::shutdown()
{
pool_.reset();
ECHOION_LOG_INFO("AudioBufferPool shutdown");
Void::Log::info("MemoryPool", "{}", "AudioBufferPool shutdown");
}
AudioSampleBuffer AudioBufferPool::acquireBuffer()
+128 -128
View File
@@ -1,5 +1,5 @@
#include "ConfigManager.hpp"
#include "LoggerInterface.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/MusicManager.hpp"
#include <Events.hpp>
#include <algorithm>
@@ -34,7 +34,7 @@ namespace Echoion::Core
// needed
if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) {
networkClient_->setProxy(networkConfig.proxy);
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"NetworkClient using {} proxy: {}:{}",
(networkConfig.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" : "HTTP",
networkConfig.proxy->host, networkConfig.proxy->port));
@@ -45,12 +45,12 @@ namespace Echoion::Core
// Configure YouTube cookies if provided
if (youtubeConfig.youtubeCookiesPath.has_value()) {
youTubeClient_->setCookiesPath(*youtubeConfig.youtubeCookiesPath);
ECHOION_LOG_INFO(std::format("Using YouTube cookies from file: {}",
Void::Log::info("MusicManager", "{}", std::format("Using YouTube cookies from file: {}",
*youtubeConfig.youtubeCookiesPath));
} else if (youtubeConfig.cookiesFromBrowser.has_value()) {
youTubeClient_->setCookiesFromBrowser(
*youtubeConfig.cookiesFromBrowser);
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Using YouTube cookies from browser: {}",
*youtubeConfig.cookiesFromBrowser));
}
@@ -78,7 +78,7 @@ namespace Echoion::Core
auto ytResult = youTubeClient_->initialize();
if (!ytResult) {
ECHOION_LOG_WARNING(
Void::Log::warn("MusicManager", "{}",
std::format("Failed to initialize YouTube client: {}",
ytResult.error().message));
}
@@ -95,7 +95,7 @@ namespace Echoion::Core
// Set proxy config from NetworkConfig if enabled
if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) {
audioDecoder_->setProxyConfig(networkConfig.proxy);
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("AudioDecoder using {} proxy: {}:{}",
(networkConfig.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" : "HTTP",
networkConfig.proxy->host,
@@ -106,7 +106,7 @@ namespace Echoion::Core
subscriptionManager_ = std::make_unique<SubscriptionManager>();
auto subResult = subscriptionManager_->initialize(database);
if (!subResult) {
ECHOION_LOG_WARNING(
Void::Log::warn("MusicManager", "{}",
std::format("Failed to initialize subscription manager: {}",
subResult.error().message));
// Not fatal - continue without subscriptions
@@ -114,7 +114,7 @@ namespace Echoion::Core
volume_ = botConfig.defaultVolume;
ECHOION_LOG_INFO("MusicManager initialized");
Void::Log::info("MusicManager", "{}", "MusicManager initialized");
return {};
}
@@ -147,7 +147,7 @@ namespace Echoion::Core
std::error_code ec;
std::filesystem::remove(filepath, ec);
if (!ec) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Cleaned up temp file: {}", filepath));
}
}
@@ -164,13 +164,13 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO("MusicManager shutdown");
Void::Log::info("MusicManager", "{}", "MusicManager shutdown");
}
Api::Result<std::string> MusicManager::play(const std::string& query,
uint64_t clientId)
{
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Play request: '{}' from client {}", query, clientId));
auto startTime = std::chrono::steady_clock::now();
@@ -184,18 +184,18 @@ namespace Echoion::Core
auto track = resolveQuery(query);
auto afterResolve = std::chrono::steady_clock::now();
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("resolveQuery took {} ms",
std::chrono::duration_cast<std::chrono::milliseconds>(
afterResolve - startTime)
.count()));
if (!track) {
ECHOION_LOG_ERROR(std::format("Failed to resolve query '{}': {}",
Void::Log::error("MusicManager", "{}", std::format("Failed to resolve query '{}': {}",
query, track.error().message));
return std::unexpected(track.error());
}
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"Resolved track: {} - {} ({}:{}", track->title, track->artist,
track->source == Api::TrackSource::YouTube ? "YouTube" : "Unknown",
track->streamUrl.has_value() ? "direct" : "needs extraction"));
@@ -209,22 +209,22 @@ namespace Echoion::Core
.isPlaying = true,
.position = std::chrono::milliseconds(0)};
ECHOION_LOG_DEBUG("Getting stream URL...");
Void::Log::debug("MusicManager", "{}", "Getting stream URL...");
auto streamStart = std::chrono::steady_clock::now();
auto streamUrl = getStreamUrl(*track);
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"getStreamUrl took {} ms",
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - streamStart)
.count()));
if (!streamUrl) {
ECHOION_LOG_ERROR(std::format("Failed to get stream URL: {}",
Void::Log::error("MusicManager", "{}", std::format("Failed to get stream URL: {}",
streamUrl.error().message));
currentTrack_.reset();
return std::unexpected(streamUrl.error());
}
ECHOION_LOG_DEBUG("Opening audio source...");
Void::Log::debug("MusicManager", "{}", "Opening audio source...");
auto openResult = audioDecoder_->openSource(*streamUrl);
// If direct open fails and we have a proxy, try downloading through
@@ -232,11 +232,11 @@ namespace Echoion::Core
const auto& networkConfig = configManager_->getNetwork();
if (!openResult && networkConfig.proxy.has_value() &&
networkConfig.proxy->enabled()) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Direct open failed, trying download through proxy...");
auto downloadedPath = downloadAudioForPlayback(*streamUrl);
if (downloadedPath) {
ECHOION_LOG_INFO(std::format("Downloaded audio to: {}",
Void::Log::info("MusicManager", "{}", std::format("Downloaded audio to: {}",
*downloadedPath));
openResult = audioDecoder_->openSource(*downloadedPath);
if (openResult) {
@@ -246,14 +246,14 @@ namespace Echoion::Core
tempFiles_.insert(*downloadedPath);
}
} else {
ECHOION_LOG_WARNING(
Void::Log::warn("MusicManager", "{}",
std::format("Failed to download through proxy: {}",
downloadedPath.error().message));
}
}
if (!openResult) {
ECHOION_LOG_ERROR(std::format("Failed to open audio source: {}",
Void::Log::error("MusicManager", "{}", std::format("Failed to open audio source: {}",
openResult.error().message));
currentTrack_.reset();
return std::unexpected(openResult.error());
@@ -286,23 +286,23 @@ namespace Echoion::Core
if (!playbackThread_.joinable() || !playbackThreadRunning_) {
// Join old thread if it exists but isn't running
if (playbackThread_.joinable()) {
ECHOION_LOG_INFO("Joining old playback thread before "
Void::Log::info("MusicManager", "{}", "Joining old playback thread before "
"starting new one...");
playbackThread_.join();
}
playbackThread_ =
std::jthread(&MusicManager::playbackThread, this);
ECHOION_LOG_INFO("Playback thread started");
Void::Log::info("MusicManager", "{}", "Playback thread started");
}
cv_.notify_one();
ECHOION_LOG_INFO(std::format("Now playing: {} - {}", track->title,
Void::Log::info("MusicManager", "{}", std::format("Now playing: {} - {}", track->title,
track->artist));
return std::format("{} - {}", track->title, track->artist);
}
ECHOION_LOG_DEBUG("Already playing, adding to queue");
Void::Log::debug("MusicManager", "{}", "Already playing, adding to queue");
auto queueId = queueTrack(*track, clientId);
if (!queueId) {
return std::unexpected(queueId.error());
@@ -324,7 +324,7 @@ namespace Echoion::Core
// Capture current position before pausing
playbackPosition_ = getPlaybackPosition();
isPaused_ = true;
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Playback paused at {}ms", playbackPosition_.count()));
return {};
}
@@ -343,10 +343,10 @@ namespace Echoion::Core
isPaused_ = false;
bool needToStartThread = false;
if (playbackThread_.joinable() && !playbackThreadRunning_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Joining finished playback thread before starting new one...");
playbackThread_.join();
ECHOION_LOG_INFO("Old thread joined");
Void::Log::info("MusicManager", "{}", "Old thread joined");
needToStartThread = true;
}
@@ -368,13 +368,13 @@ namespace Echoion::Core
}
playbackThread_ = std::jthread(&MusicManager::playbackThread, this);
ECHOION_LOG_INFO("Started playback thread");
Void::Log::info("MusicManager", "{}", "Started playback thread");
}
// Notify the thread to process
cv_.notify_one();
ECHOION_LOG_INFO(std::format("Playback resumed from {}ms",
Void::Log::info("MusicManager", "{}", std::format("Playback resumed from {}ms",
playbackPosition_.count()));
return {};
}
@@ -393,7 +393,7 @@ namespace Echoion::Core
}
cv_.notify_one();
ECHOION_LOG_INFO("Playback stopped");
Void::Log::info("MusicManager", "{}", "Playback stopped");
// Publish playback stopped event
emit(Api::Events::PlaybackStopped{
@@ -443,14 +443,14 @@ namespace Echoion::Core
audioDecoder_->closeSource();
auto openResult = audioDecoder_->openSource(*streamUrl);
if (!openResult) {
ECHOION_LOG_ERROR(std::format("Failed to open stream: {}",
Void::Log::error("MusicManager", "{}", std::format("Failed to open stream: {}",
openResult.error().message));
}
}
}
cv_.notify_one();
ECHOION_LOG_INFO(std::format("Skipped {} track(s)", count));
Void::Log::info("MusicManager", "{}", std::format("Skipped {} track(s)", count));
return {};
}
@@ -477,7 +477,7 @@ namespace Echoion::Core
currentTrack_->position = position;
}
ECHOION_LOG_INFO(std::format("Seeked to {} ms", position.count()));
Void::Log::info("MusicManager", "{}", std::format("Seeked to {} ms", position.count()));
return {};
}
@@ -490,7 +490,7 @@ namespace Echoion::Core
float oldVolume = volume_;
volume_ = volume;
ECHOION_LOG_INFO(std::format("Volume set to {}", volume));
Void::Log::info("MusicManager", "{}", std::format("Volume set to {}", volume));
// Publish volume changed event
emit(Api::Events::VolumeChanged{
@@ -507,12 +507,12 @@ namespace Echoion::Core
{
// Validate track before adding to queue - check if we can get a stream
// URL
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Validating track before queueing: {} - {}",
track.title, track.artist));
auto streamUrl = getStreamUrl(track);
if (!streamUrl) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("MusicManager", "{}", std::format(
"Track validation failed for '{} - {}': {}", track.title,
track.artist, streamUrl.error().message));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
@@ -564,7 +564,7 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Queued: {} - {}", track.title, track.artist));
// Check if we should auto-start playback
@@ -576,7 +576,7 @@ namespace Echoion::Core
needToStartThread =
!playbackThread_.joinable() && !playbackThreadRunning_;
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"queueTrack debug: shouldStart={}, "
"needToStartThread={}, isPlaying_={}, "
"thread_joinable={}, thread_running={}, queue_size={}",
@@ -586,15 +586,15 @@ namespace Echoion::Core
}
if (shouldStart) {
ECHOION_LOG_INFO("Auto-starting playback for first track in queue");
Void::Log::info("MusicManager", "{}", "Auto-starting playback for first track in queue");
// Check if we need to handle an old thread that's done but still
// joinable
if (playbackThread_.joinable() && !playbackThreadRunning_) {
ECHOION_LOG_INFO("Joining finished playback thread before "
Void::Log::info("MusicManager", "{}", "Joining finished playback thread before "
"starting new one...");
playbackThread_.join();
ECHOION_LOG_INFO("Old thread joined");
Void::Log::info("MusicManager", "{}", "Old thread joined");
needToStartThread = true;
}
@@ -615,7 +615,7 @@ namespace Echoion::Core
playbackThread_ =
std::jthread(&MusicManager::playbackThread, this);
ECHOION_LOG_INFO("Started playback thread for auto-play");
Void::Log::info("MusicManager", "{}", "Started playback thread for auto-play");
}
// Notify the thread to process
@@ -660,7 +660,7 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO(std::format("Removed track at position {}", position));
Void::Log::info("MusicManager", "{}", std::format("Removed track at position {}", position));
// Publish track removed event
emit(Api::Events::TrackRemoved{
@@ -684,7 +684,7 @@ namespace Echoion::Core
shuffleIndex_ = 0;
}
ECHOION_LOG_INFO("Queue cleared");
Void::Log::info("MusicManager", "{}", "Queue cleared");
// Publish queue cleared event
emit(Api::Events::QueueCleared{
@@ -735,7 +735,7 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO(std::format("Moved track from {} to {}", from, to));
Void::Log::info("MusicManager", "{}", std::format("Moved track from {} to {}", from, to));
// Publish queue reordered event
emit(
@@ -757,14 +757,14 @@ namespace Echoion::Core
// Build shuffled indices for current queue
rebuildShuffledIndices();
shuffleIndex_ = 0;
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Shuffle enabled - queue shuffled with {} tracks",
shuffledIndices_.size()));
} else {
// Clear shuffle state
shuffledIndices_.clear();
shuffleIndex_ = 0;
ECHOION_LOG_INFO("Shuffle disabled");
Void::Log::info("MusicManager", "{}", "Shuffle disabled");
}
// Publish shuffle changed event
@@ -788,7 +788,7 @@ namespace Echoion::Core
std::shuffle(shuffledIndices_.begin(), shuffledIndices_.end(), rng_);
shuffleIndex_ = 0;
ECHOION_LOG_DEBUG(std::format("Rebuilt shuffled indices: {} tracks",
Void::Log::debug("MusicManager", "{}", std::format("Rebuilt shuffled indices: {} tracks",
shuffledIndices_.size()));
}
@@ -805,14 +805,14 @@ namespace Echoion::Core
std::shuffle(shuffledIndices_.begin() + shuffleIndex_,
shuffledIndices_.end(), rng_);
ECHOION_LOG_DEBUG(std::format("Reshuffled remaining {} tracks",
Void::Log::debug("MusicManager", "{}", std::format("Reshuffled remaining {} tracks",
shuffledIndices_.size() - shuffleIndex_));
}
Api::Result<bool> MusicManager::toggleRepeat()
{
repeat_ = !repeat_;
ECHOION_LOG_INFO(repeat_ ? "Repeat enabled" : "Repeat disabled");
Void::Log::info("MusicManager", "{}", repeat_ ? "Repeat enabled" : "Repeat disabled");
// Publish repeat changed event
emit(Api::Events::RepeatChanged{
@@ -843,7 +843,7 @@ namespace Echoion::Core
youTubeClient_->extractPlaylistId(playlistIdOrUrl);
if (extractedId) {
playlistId = *extractedId;
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"Extracted playlist ID '{}' from URL", playlistId));
} else {
return Api::fail(Api::ErrorCode::InvalidArgument,
@@ -861,7 +861,7 @@ namespace Echoion::Core
playlistLoadedCount_ = 0;
playlistTotalCount_ = 0;
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Starting async playlist load: {}", playlistId));
// Publish playlist load started event
@@ -910,7 +910,7 @@ namespace Echoion::Core
// Start playback immediately on first track
if (isFirst) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("First track resolved: {} - {}. "
"Starting playback...",
track.title, track.artist));
@@ -931,7 +931,7 @@ namespace Echoion::Core
if (!isPlaying_ && !queue_.empty()) {
// Trigger playback start
cv_.notify_one();
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Playback started from playlist");
}
});
@@ -942,13 +942,13 @@ namespace Echoion::Core
// known
[this, playlistId](size_t totalTracks) {
playlistTotalCount_ = totalTracks;
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Playlist '{}' has {} tracks, resolving...",
playlistId, totalTracks));
},
// On complete callback
[this, &added, playlistId]() {
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"Playlist streaming complete. Added {} tracks",
added.load()));
playlistLoading_ = false;
@@ -994,7 +994,7 @@ namespace Echoion::Core
// Safety check: if playbackStartTime_ is not initialized, return base
// position
if (playbackStartTime_.time_since_epoch().count() == 0) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
"getPlaybackPosition: playbackStartTime_ not initialized");
return playbackBasePosition_;
}
@@ -1006,7 +1006,7 @@ namespace Echoion::Core
// Sanity check: position shouldn't be negative or more than 24 hours
if (position.count() < 0 || position.count() > 86400000) {
ECHOION_LOG_WARNING(
Void::Log::warn("MusicManager", "{}",
std::format("getPlaybackPosition: Invalid position: {}ms",
position.count()));
return std::chrono::milliseconds(0);
@@ -1049,7 +1049,7 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(pendingSearchMutex_);
pendingSearches_[clientId] = results;
ECHOION_LOG_DEBUG(std::format("Stored {} search results for client {}",
Void::Log::debug("MusicManager", "{}", std::format("Stored {} search results for client {}",
results.size(), clientId));
}
@@ -1162,7 +1162,7 @@ namespace Echoion::Core
rebuildShuffledIndices();
}
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("restoreFromHotReload: shouldPreservePlayback={}, "
"hasStreamUrl={}, isPlaying={}, hasCurrentTrack={}",
state.shouldPreservePlayback(),
@@ -1171,7 +1171,7 @@ namespace Echoion::Core
state.playback.currentTrack.has_value()));
if (state.shouldPreservePlayback() && state.currentStreamUrl) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Restoring playback from position {}ms",
state.playbackPosition.count()));
auto openResult =
@@ -1202,19 +1202,19 @@ namespace Echoion::Core
}
cv_.notify_one();
ECHOION_LOG_INFO("Playback restored successfully");
Void::Log::info("MusicManager", "{}", "Playback restored successfully");
} else {
ECHOION_LOG_ERROR(
Void::Log::error("MusicManager", "{}",
std::format("Failed to seek to position {}ms: {}",
state.playbackPosition.count(),
seekResult.error().message));
}
} else {
ECHOION_LOG_ERROR(std::format("Failed to open stream URL: {}",
Void::Log::error("MusicManager", "{}", std::format("Failed to open stream URL: {}",
openResult.error().message));
}
} else {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Playback not restored: conditions not met "
"(isPlaying={}, hasTrack={}, hasUrl={})",
state.playback.isPlaying,
@@ -1223,7 +1223,7 @@ namespace Echoion::Core
}
if (!currentTrack_.has_value() && !queue_.empty() &&
hasOnlineSubscribers()) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Playback not restored but queue has items, starting "
"thread for auto-start");
if (playbackThread_.joinable()) {
@@ -1255,7 +1255,7 @@ namespace Echoion::Core
currentTrack_.reset();
}
ECHOION_LOG_INFO("State restored from hot reload");
Void::Log::info("MusicManager", "{}", "State restored from hot reload");
return {};
}
@@ -1294,7 +1294,7 @@ namespace Echoion::Core
void MusicManager::playbackThread()
{
ECHOION_LOG_DEBUG("Playback thread started");
Void::Log::debug("MusicManager", "{}", "Playback thread started");
playbackThreadRunning_ = true;
// Constants for 192kHz 20ms chunks (like reference)
@@ -1357,7 +1357,7 @@ namespace Echoion::Core
auto openResult = audioDecoder_->openSource(*streamUrl);
if (!openResult) {
ECHOION_LOG_ERROR(
Void::Log::error("MusicManager", "{}",
std::format("Failed to open first track: {}",
openResult.error().message));
lock.lock();
@@ -1367,7 +1367,7 @@ namespace Echoion::Core
}
lock.lock();
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"Auto-started playback: {} - {}",
firstTrack.track.title, firstTrack.track.artist));
}
@@ -1390,7 +1390,7 @@ namespace Echoion::Core
incomingChunk.begin(),
incomingChunk.end());
if (chunksSent == 0) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("First chunk received: {} samples",
incomingChunk.size()));
}
@@ -1460,7 +1460,7 @@ namespace Echoion::Core
maxSample,
std::abs(static_cast<int>(localAudioBuffer[i])));
}
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"Audio debug: volume={:.3f}, volMult={:.3f}, "
"nonZero={}/100, maxSample={}",
volume_.load(), volMult, nonZeroCount, maxSample));
@@ -1485,13 +1485,13 @@ namespace Echoion::Core
chunksSent++;
if (chunksSent == 1 || chunksSent % 100 == 0) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Sent {} chunks, buffer: {}",
chunksSent,
localAudioBuffer.size()));
}
} else if (chunksSent == 0) {
ECHOION_LOG_WARNING("No audio callback set!");
Void::Log::warn("MusicManager", "{}", "No audio callback set!");
}
// Precision timing (like reference)
@@ -1500,7 +1500,7 @@ namespace Echoion::Core
} else {
// Buffer underrun - wait for more data
if (chunksSent == 0) {
ECHOION_LOG_DEBUG(std::format("Waiting for data: {} < {}",
Void::Log::debug("MusicManager", "{}", std::format("Waiting for data: {} < {}",
localAudioBuffer.size(),
SHORTS_PER_CHUNK));
}
@@ -1556,12 +1556,12 @@ namespace Echoion::Core
}
if (totalFlushed > 0) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Playback finished with last flush, "
"sent {} chunks, flushed {} samples",
chunksSent, totalFlushed));
} else {
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"Playback finished, sent {} chunks", chunksSent));
}
@@ -1569,7 +1569,7 @@ namespace Echoion::Core
// Send low-level white noise during track transition to
// prevent audio glitch and keep microphone active
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
"Sending transition noise during track transition...");
auto transitionStart = std::chrono::steady_clock::now();
constexpr auto MAX_TRANSITION_TIME =
@@ -1590,7 +1590,7 @@ namespace Echoion::Core
localAudioBuffer.insert(localAudioBuffer.end(),
incoming.begin(),
incoming.end());
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
"Next track ready, resuming playback");
break;
}
@@ -1615,7 +1615,7 @@ namespace Echoion::Core
{
std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Playback stopped during transition");
break;
}
@@ -1625,13 +1625,13 @@ namespace Echoion::Core
// Check if playback should continue (more tracks available)
{
std::shared_lock<std::shared_mutex> lock(mutex_);
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"Playback thread: isPlaying_={}, queue_size={}, "
"currentTrack.has_value={}",
isPlaying_.load(), queue_.size(),
currentTrack_.has_value()));
if (!isPlaying_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Playback thread exiting: isPlaying_ is false");
break; // Exit thread if no more tracks
}
@@ -1640,13 +1640,13 @@ namespace Echoion::Core
// Reset for next track
chunksSent = 0;
next = std::chrono::steady_clock::now();
ECHOION_LOG_DEBUG("Continuing to next track...");
Void::Log::debug("MusicManager", "{}", "Continuing to next track...");
continue;
}
}
}
ECHOION_LOG_DEBUG("Playback thread exiting");
Void::Log::debug("MusicManager", "{}", "Playback thread exiting");
playbackThreadRunning_ = false;
}
@@ -1654,20 +1654,20 @@ namespace Echoion::Core
MusicManager::resolveQuery(const std::string& query)
{
if (YouTubeClient::isYouTubeUrl(query)) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Extracting video ID from URL: {}", query));
auto videoId = youTubeClient_->extractVideoId(query);
if (videoId) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Extracted video ID: '{}'", *videoId));
return youTubeClient_->getVideoInfo(*videoId);
} else {
ECHOION_LOG_WARNING("Failed to extract video ID from URL");
Void::Log::warn("MusicManager", "{}", "Failed to extract video ID from URL");
}
auto playlistId = youTubeClient_->extractPlaylistId(query);
if (playlistId) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Extracted playlist ID: '{}'", *playlistId));
auto playlist = youTubeClient_->getPlaylist(*playlistId);
if (playlist && !playlist->tracks.empty()) {
@@ -1692,26 +1692,26 @@ namespace Echoion::Core
MusicManager::getStreamUrl(const Api::TrackInfo& track)
{
if (track.streamUrl) {
ECHOION_LOG_DEBUG("Using pre-resolved stream URL");
Void::Log::debug("MusicManager", "{}", "Using pre-resolved stream URL");
return *track.streamUrl;
}
if (track.source == Api::TrackSource::YouTube) {
auto videoId = youTubeClient_->extractVideoId(track.originalUrl);
if (videoId) {
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"Extracting stream URL for YouTube video: {}", *videoId));
auto url = youTubeClient_->getStreamUrl(*videoId);
if (url) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Got stream URL: {}", url->c_str()));
} else {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("MusicManager", "{}", std::format(
"Failed to get stream URL: {}", url.error().message));
}
return url;
}
ECHOION_LOG_WARNING("Could not extract video ID from URL");
Void::Log::warn("MusicManager", "{}", "Could not extract video ID from URL");
}
return Api::fail(Api::ErrorCode::NotFound, "Could not get stream URL");
@@ -1747,13 +1747,13 @@ namespace Echoion::Core
isPlaying_ = false;
currentTrack_.reset();
audioDecoder_->closeSource();
ECHOION_LOG_INFO("Queue empty, playback stopped");
Void::Log::info("MusicManager", "{}", "Queue empty, playback stopped");
return;
}
// Play next track from queue
auto nextTrack = getNextTrack();
ECHOION_LOG_INFO(std::format("Playing next track: {} - {}",
Void::Log::info("MusicManager", "{}", std::format("Playing next track: {} - {}",
nextTrack.title, nextTrack.artist));
currentTrack_ =
@@ -1777,7 +1777,7 @@ namespace Echoion::Core
if (status == std::future_status::ready) {
auto result = prefetchState_.streamUrlFuture.get();
if (result) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Using prefetched stream URL for seamless transition");
streamUrl = *result;
}
@@ -1787,7 +1787,7 @@ namespace Echoion::Core
// If prefetch not ready or failed, fetch synchronously
if (!streamUrl) {
if (prefetchState_.isPrefetching) {
ECHOION_LOG_INFO("Waiting for prefetch to complete...");
Void::Log::info("MusicManager", "{}", "Waiting for prefetch to complete...");
auto result = prefetchState_.streamUrlFuture.get();
if (result) {
streamUrl = *result;
@@ -1795,7 +1795,7 @@ namespace Echoion::Core
}
if (!streamUrl) {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
"No prefetched URL available, fetching synchronously");
auto result = getStreamUrl(nextTrack);
if (result) {
@@ -1808,14 +1808,14 @@ namespace Echoion::Core
audioDecoder_->closeSource();
auto result = audioDecoder_->openSource(*streamUrl);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to open next track: {}",
Void::Log::error("MusicManager", "{}", std::format("Failed to open next track: {}",
result.error().message));
// Remove the failed track and try next
queue_.erase(queue_.begin());
onTrackFinished();
}
} else {
ECHOION_LOG_ERROR("Failed to get stream URL for next track");
Void::Log::error("MusicManager", "{}", "Failed to get stream URL for next track");
queue_.erase(queue_.begin());
onTrackFinished();
}
@@ -1906,7 +1906,7 @@ Subscriptions are persistent across server reconnects.)";
const auto& [uid, nickname] = *clientInfo;
bool added = subscriptionManager_->subscribe(uid, nickname);
ECHOION_LOG_INFO(std::format("Subscribe: client {} ({}), added={}",
Void::Log::info("MusicManager", "{}", std::format("Subscribe: client {} ({}), added={}",
clientId, nickname, added));
// If we have subscribers now and were paused due to no subscribers,
@@ -1922,7 +1922,7 @@ Subscriptions are persistent across server reconnects.)";
// update whisper list This ensures offline->online transitions update
// the whisper list
if (subscriptionChangeCallback_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Subscribe: triggering subscriptionChangeCallback");
subscriptionChangeCallback_();
}
@@ -1962,7 +1962,7 @@ Subscriptions are persistent across server reconnects.)";
// If no online subscribers left and we're playing, pause
if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) {
ECHOION_LOG_INFO("No online subscribers left, pausing playback");
Void::Log::info("MusicManager", "{}", "No online subscribers left, pausing playback");
auto result = pause();
if (result) {
wasPausedForNoSubscribers_ = true;
@@ -1997,7 +1997,7 @@ Subscriptions are persistent across server reconnects.)";
// If no online subscribers left and we're playing, pause
if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) {
ECHOION_LOG_INFO("No online subscribers left, pausing playback");
Void::Log::info("MusicManager", "{}", "No online subscribers left, pausing playback");
auto result = pause();
if (result) {
wasPausedForNoSubscribers_ = true;
@@ -2027,7 +2027,7 @@ Subscriptions are persistent across server reconnects.)";
// Pause playback if no subscribers
if (cleared && isPlaying_ && !isPaused_) {
ECHOION_LOG_INFO("All subscriptions cleared, pausing playback");
Void::Log::info("MusicManager", "{}", "All subscriptions cleared, pausing playback");
auto result = pause();
if (result) {
wasPausedForNoSubscribers_ = true;
@@ -2131,10 +2131,10 @@ Subscriptions are persistent across server reconnects.)";
void MusicManager::onClientConnected(uint64_t clientId)
{
ECHOION_LOG_INFO(std::format("onClientConnected: client {}", clientId));
Void::Log::info("MusicManager", "{}", std::format("onClientConnected: client {}", clientId));
if (!subscriptionManager_ || !clientInfoCallback_) {
ECHOION_LOG_WARNING("onClientConnected: subscriptionManager or "
Void::Log::warn("MusicManager", "{}", "onClientConnected: subscriptionManager or "
"clientInfoCallback not set");
return;
}
@@ -2142,7 +2142,7 @@ Subscriptions are persistent across server reconnects.)";
// Get the client's UID
auto clientInfo = clientInfoCallback_(clientId);
if (!clientInfo) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("MusicManager", "{}", std::format(
"onClientConnected: could not get client info for {}",
clientId));
return;
@@ -2150,13 +2150,13 @@ Subscriptions are persistent across server reconnects.)";
const auto& [uid, nickname] = *clientInfo;
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"onClientConnected: client {} ({}), uid={}, isSubscribed={}",
clientId, nickname, uid, subscriptionManager_->isSubscribed(uid)));
// Check if this user is subscribed (in offline subscribers)
if (subscriptionManager_->isSubscribed(uid)) {
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"Subscribed user {} ({}) connected, moving to online", nickname,
uid));
@@ -2165,14 +2165,14 @@ Subscriptions are persistent across server reconnects.)";
// Update whisper list to include them
if (subscriptionChangeCallback_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"onClientConnected: triggering subscriptionChangeCallback");
subscriptionChangeCallback_();
}
// If we were paused due to no online subscribers, resume playback
if (wasPausedForNoSubscribers_ && isPlaying_ && isPaused_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"Online subscriber returned, resuming playback");
auto result = resume();
if (result) {
@@ -2182,7 +2182,7 @@ Subscriptions are persistent across server reconnects.)";
// If we're not playing but have tracks in queue, auto-start
else if (!isPlaying_ && !currentTrack_.has_value() &&
!queue_.empty()) {
ECHOION_LOG_INFO("Online subscriber connected with tracks in "
Void::Log::info("MusicManager", "{}", "Online subscriber connected with tracks in "
"queue, auto-starting");
// Notify playback thread to start
cv_.notify_one();
@@ -2213,7 +2213,7 @@ Subscriptions are persistent across server reconnects.)";
// If this was a subscribed user, update whisper list
if (subscriptionManager_->isSubscribed(uid)) {
ECHOION_LOG_INFO(std::format(
Void::Log::info("MusicManager", "{}", std::format(
"Subscribed user {} ({}) disconnected, moving to offline",
nickname, uid));
@@ -2224,7 +2224,7 @@ Subscriptions are persistent across server reconnects.)";
// If no more online subscribers and we're playing, pause
if (!hasOnlineSubscribers() && isPlaying_ && !isPaused_) {
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
"No online subscribers left, pausing playback");
auto result = pause();
if (result) {
@@ -2253,7 +2253,7 @@ Subscriptions are persistent across server reconnects.)";
auto tempPath = cacheDir / std::format("audio_{}.tmp", timestamp);
// Download the file
ECHOION_LOG_INFO(
Void::Log::info("MusicManager", "{}",
std::format("Downloading audio from: {}...", url.substr(0, 60)));
auto response = networkClient_->get(url);
@@ -2280,7 +2280,7 @@ Subscriptions are persistent across server reconnects.)";
file.write(response->body.data(), response->body.size());
file.close();
ECHOION_LOG_INFO(std::format("Downloaded {} bytes to {}",
Void::Log::info("MusicManager", "{}", std::format("Downloaded {} bytes to {}",
response->body.size(), tempPath.string()));
return tempPath.string();
@@ -2294,10 +2294,10 @@ Subscriptions are persistent across server reconnects.)";
std::error_code ec;
std::filesystem::remove(filepath, ec);
if (ec) {
ECHOION_LOG_WARNING(std::format("Failed to remove temp file {}: {}",
Void::Log::warn("MusicManager", "{}", std::format("Failed to remove temp file {}: {}",
filepath, ec.message()));
} else {
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Cleaned up temp file: {}", filepath));
}
}
@@ -2322,7 +2322,7 @@ Subscriptions are persistent across server reconnects.)";
auto streamInfo = audioDecoder_->getStreamInfo();
if (!streamInfo) {
ECHOION_LOG_DEBUG("Prefetch: No stream info available");
Void::Log::debug("MusicManager", "{}", "Prefetch: No stream info available");
return false;
}
@@ -2332,7 +2332,7 @@ Subscriptions are persistent across server reconnects.)";
if (streamInfo->duration <= PREFETCH_THRESHOLD) {
bool shouldPrefetch = position >= std::chrono::seconds(2);
if (shouldPrefetch) {
ECHOION_LOG_DEBUG(std::format("Prefetch: Short track ({}s), "
Void::Log::debug("MusicManager", "{}", std::format("Prefetch: Short track ({}s), "
"position {}s - should prefetch",
streamInfo->duration.count(),
position.count()));
@@ -2348,7 +2348,7 @@ Subscriptions are persistent across server reconnects.)";
// Log when we're getting close to prefetch threshold
if (timeRemaining <= std::chrono::seconds(20) &&
timeRemaining > std::chrono::seconds(0)) {
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("MusicManager", "{}", std::format(
"Prefetch: Time remaining {}s, threshold {}s - {}",
std::chrono::duration_cast<std::chrono::seconds>(timeRemaining)
.count(),
@@ -2368,7 +2368,7 @@ Subscriptions are persistent across server reconnects.)";
return; // Already prefetching
}
ECHOION_LOG_INFO("Starting prefetch of next track stream URL");
Void::Log::info("MusicManager", "{}", "Starting prefetch of next track stream URL");
// Get next track info (copy to avoid holding lock during async
// operation)
@@ -2394,9 +2394,9 @@ Subscriptions are persistent across server reconnects.)";
[this, nextTrack]() -> Api::Result<std::string> {
auto result = getStreamUrl(nextTrack);
if (result) {
ECHOION_LOG_INFO("Prefetch completed successfully");
Void::Log::info("MusicManager", "{}", "Prefetch completed successfully");
} else {
ECHOION_LOG_WARNING(std::format("Prefetch failed: {}",
Void::Log::warn("MusicManager", "{}", std::format("Prefetch failed: {}",
result.error().message));
}
return result;
@@ -2421,7 +2421,7 @@ Subscriptions are persistent across server reconnects.)";
auto chunksNeeded = duration.count() / CHUNK_MS;
std::vector<short> silenceChunk(SHORTS_PER_CHUNK, 0);
ECHOION_LOG_DEBUG(
Void::Log::debug("MusicManager", "{}",
std::format("Generating {}ms of transition silence ({} chunks)",
duration.count(), chunksNeeded));
+4 -4
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/NetworkClient.hpp"
#include <Void/Functional/Retry.hpp>
#include <Void/Net/Http.hpp>
@@ -15,7 +15,7 @@ namespace Echoion::Core
{
proxy_ = proxy;
initialized_ = true;
ECHOION_LOG_INFO(std::format("NetworkClient initialized (proxy: {})",
Void::Log::info("NetworkClient", "{}", std::format("NetworkClient initialized (proxy: {})",
proxy.has_value() ? "enabled" : "disabled"));
return {};
}
@@ -46,7 +46,7 @@ namespace Echoion::Core
retryPolicy_, [&] { return executeRequest(req); },
[this](const Api::Result<Void::Net::Response>& result) {
if (!result) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("NetworkClient", "{}", std::format(
"Request error: {}, retrying", result.error().message));
return true;
}
@@ -54,7 +54,7 @@ namespace Echoion::Core
const auto& codes = retryableStatusCodes_;
if (std::find(codes.begin(), codes.end(), result->status) !=
codes.end()) {
ECHOION_LOG_WARNING(
Void::Log::warn("NetworkClient", "{}",
std::format("Request failed with status {}, retrying",
result->status));
return true;
+18 -18
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/RpcServer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
@@ -33,7 +33,7 @@ namespace Echoion::Core
CLIENT_POOL_SIZE);
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
ECHOION_LOG_INFO(
Void::Log::info("RpcServer", "{}",
std::format("RPC server started on port {}", port));
return {};
} catch (const std::exception& e) {
@@ -95,20 +95,20 @@ namespace Echoion::Core
acceptor_->close(ec);
}
ECHOION_LOG_INFO("RPC server stopped");
Void::Log::info("RpcServer", "{}", "RPC server stopped");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("Error stopping RPC server: {}", e.what()));
}
}
void RpcServer::acceptLoop()
{
ECHOION_LOG_INFO("RPC server accept loop started");
Void::Log::info("RpcServer", "{}", "RPC server accept loop started");
while (running_.load()) {
try {
asio::ip::tcp::socket socket(ioContext_);
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
Void::Log::debug("RpcServer", "{}", "RPC server waiting for connection...");
// Use async accept with cancellation support
std::atomic<bool> acceptComplete{false};
@@ -136,7 +136,7 @@ namespace Echoion::Core
throw std::runtime_error(acceptEc.message());
}
ECHOION_LOG_DEBUG(
Void::Log::debug("RpcServer", "{}",
std::format("RPC server accepted TCP connection from {}:{}",
socket.remote_endpoint().address().to_string(),
socket.remote_endpoint().port()));
@@ -149,7 +149,7 @@ namespace Echoion::Core
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
std::move(socket));
ws->accept();
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed");
uint64_t clientId = nextClientId_++;
{
@@ -157,7 +157,7 @@ namespace Echoion::Core
clients_[clientId] = ws;
}
ECHOION_LOG_DEBUG(
Void::Log::debug("RpcServer", "{}",
std::format("RPC client {} connected", clientId));
// Handle the client on the worker pool (drained/joined by
@@ -175,7 +175,7 @@ namespace Echoion::Core
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("RpcServer", "{}", std::format(
"RPC client {} disconnected", clientId));
});
}
@@ -185,11 +185,11 @@ namespace Echoion::Core
if (!running_.load()) {
break;
}
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("RPC accept error: {}", e.what()));
}
}
ECHOION_LOG_INFO("RPC server accept loop stopped");
Void::Log::info("RpcServer", "{}", "RPC server accept loop stopped");
}
void RpcServer::handleClient(
@@ -206,7 +206,7 @@ namespace Echoion::Core
break;
}
if (ec) {
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("WebSocket read error: {}", ec.message()));
break;
}
@@ -231,7 +231,7 @@ namespace Echoion::Core
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("Client handling error: {}", e.what()));
break;
}
@@ -314,7 +314,7 @@ namespace Echoion::Core
sendResponse(clientId, response);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("Message processing error: {}", e.what()));
}
}
@@ -333,7 +333,7 @@ namespace Echoion::Core
Void::Json::serialize(Void::Json::to_json(response));
it->second->write(asio::buffer(json));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
Void::Log::error("RpcServer", "{}", std::format("Send response error: {}", e.what()));
}
}
@@ -351,7 +351,7 @@ namespace Echoion::Core
Void::Json::serialize(Void::Json::to_json(notification));
it->second->write(asio::buffer(json));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("Send notification error: {}", e.what()));
}
}
@@ -372,7 +372,7 @@ namespace Echoion::Core
Void::Json::to_json(notification));
ws->write(asio::buffer(json));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("RpcServer", "{}",
std::format("Broadcast error: {}", e.what()));
}
}
+6 -6
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/SessionManager.hpp"
#include <format>
#include <iomanip>
@@ -15,7 +15,7 @@ namespace Echoion::Core
bool SessionManager::initialize()
{
running_ = true;
ECHOION_LOG_INFO(std::format(
Void::Log::info("SessionManager", "{}", std::format(
"SessionManager initialized: max {} sessions, timeout {}s",
config_.maxSessions, config_.sessionTimeout.count()));
return true;
@@ -26,7 +26,7 @@ namespace Echoion::Core
running_ = false;
std::lock_guard<std::mutex> lock(mutex_);
sessions_.clear();
ECHOION_LOG_INFO("SessionManager shut down");
Void::Log::info("SessionManager", "{}", "SessionManager shut down");
}
std::string SessionManager::createSession(uint64_t clientId)
@@ -35,7 +35,7 @@ namespace Echoion::Core
// Check capacity
if (sessions_.size() >= config_.maxSessions) {
ECHOION_LOG_WARNING(
Void::Log::warn("SessionManager", "{}",
"Session capacity reached, rejecting new session");
return "";
}
@@ -52,7 +52,7 @@ namespace Echoion::Core
sessions_[token] = std::move(session);
ECHOION_LOG_INFO(
Void::Log::info("SessionManager", "{}",
std::format("Created session for client {}", clientId));
return token;
}
@@ -172,7 +172,7 @@ namespace Echoion::Core
}
if (cleaned > 0) {
ECHOION_LOG_INFO(
Void::Log::info("SessionManager", "{}",
std::format("Cleaned up {} expired sessions", cleaned));
}
+47 -47
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/SignatureCipher.hpp"
#include <Void/Data/Json.hpp>
#include <algorithm>
@@ -83,13 +83,13 @@ namespace Echoion::Core
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
ECHOION_LOG_ERROR(
Void::Log::error("SignatureCipher", "{}",
"Cipher not initialized. Call initialize() first.");
return false;
}
if (!solverInitialized_) {
ECHOION_LOG_WARNING(
Void::Log::warn("SignatureCipher", "{}",
"Solver not initialized - cannot process player JS");
return false;
}
@@ -98,12 +98,12 @@ namespace Echoion::Core
hasPlayerJs_ = false;
preprocessedPlayer_.clear();
if (playerJsCode_.empty()) {
ECHOION_LOG_WARNING("Empty player JS code provided");
Void::Log::warn("SignatureCipher", "{}", "Empty player JS code provided");
return false;
}
if (!context_) {
ECHOION_LOG_ERROR("QuickJS context not available");
Void::Log::error("SignatureCipher", "{}", "QuickJS context not available");
return false;
}
@@ -121,10 +121,10 @@ namespace Echoion::Core
std::string_view inputPreview(inputStr);
if (inputPreview.size() > 500) {
inputPreview = inputPreview.substr(0, 500);
ECHOION_LOG_DEBUG(
Void::Log::debug("SignatureCipher", "{}",
std::format("Solver input (truncated): {}...", inputPreview));
} else {
ECHOION_LOG_DEBUG(std::format("Solver input: {}", inputPreview));
Void::Log::debug("SignatureCipher", "{}", std::format("Solver input: {}", inputPreview));
}
// Get global object and jsc function
@@ -132,7 +132,7 @@ namespace Echoion::Core
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
ECHOION_LOG_ERROR("jsc function not found in QuickJS context");
Void::Log::error("SignatureCipher", "{}", "jsc function not found in QuickJS context");
JS_FreeValue(context_, global);
return false;
}
@@ -142,7 +142,7 @@ namespace Echoion::Core
JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
ECHOION_LOG_ERROR("Failed to parse input JSON");
Void::Log::error("SignatureCipher", "{}", "Failed to parse input JSON");
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
@@ -171,7 +171,7 @@ namespace Echoion::Core
"<wrapper>", JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(wrapper)) {
ECHOION_LOG_ERROR("Failed to compile error handling wrapper");
Void::Log::error("SignatureCipher", "{}", "Failed to compile error handling wrapper");
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
@@ -186,7 +186,7 @@ namespace Echoion::Core
if (!JS_IsException(result)) {
// Check if result is null or undefined
if (JS_IsNull(result) || JS_IsUndefined(result)) {
ECHOION_LOG_ERROR("jsc returned null/undefined - solver may "
Void::Log::error("SignatureCipher", "{}", "jsc returned null/undefined - solver may "
"have failed silently");
} else {
const char* resultStr = JS_ToCString(context_, result);
@@ -196,7 +196,7 @@ namespace Echoion::Core
if (resultView.size() > 500) {
resultView = resultView.substr(0, 500);
}
ECHOION_LOG_DEBUG(
Void::Log::debug("SignatureCipher", "{}",
std::format("jsc result: {}", resultView));
try {
@@ -209,38 +209,38 @@ namespace Echoion::Core
if (pp && pp->is_string()) {
preprocessedPlayer_ = pp->as_string();
hasPlayerJs_ = true;
ECHOION_LOG_INFO(
Void::Log::info("SignatureCipher", "{}",
"Player JS preprocessed successfully");
} else if (err && err->is_string()) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SignatureCipher", "{}", std::format(
"Solver error: {}", err->as_string()));
} else {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SignatureCipher", "{}", std::format(
"Unexpected solver output: {}", resultStr));
}
} else {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SignatureCipher", "{}", std::format(
"Failed to parse solver JSON output: {}",
resultStr));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SignatureCipher", "{}", std::format(
"Failed to parse solver output: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
} else {
ECHOION_LOG_ERROR("jsc returned non-convertible value");
Void::Log::error("SignatureCipher", "{}", "jsc returned non-convertible value");
}
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
if (errorStr) {
ECHOION_LOG_ERROR(
Void::Log::error("SignatureCipher", "{}",
std::format("QuickJS execution error: {}", errorStr));
} else {
// Try to get exception details differently
ECHOION_LOG_ERROR("QuickJS execution failed (exception value "
Void::Log::error("SignatureCipher", "{}", "QuickJS execution failed (exception value "
"not convertible to string)");
}
JS_FreeCString(context_, errorStr);
@@ -422,7 +422,7 @@ namespace Echoion::Core
}
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SignatureCipher", "{}", std::format(
"Failed to parse challenge response: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
@@ -430,7 +430,7 @@ namespace Echoion::Core
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Challenge solving error: {}",
Void::Log::error("SignatureCipher", "{}", std::format("Challenge solving error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
@@ -497,11 +497,11 @@ namespace Echoion::Core
std::string cmd =
std::format("curl -sLf -m 30 '{}' 2>&1", std::string(url));
ECHOION_LOG_DEBUG(std::format("Downloading: {}", url));
Void::Log::debug("SignatureCipher", "{}", std::format("Downloading: {}", url));
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING(std::format("Failed to run curl for {}", url));
Void::Log::warn("SignatureCipher", "{}", std::format("Failed to run curl for {}", url));
return std::nullopt;
}
@@ -513,13 +513,13 @@ namespace Echoion::Core
int status = pclose(pipe);
if (status != 0) {
ECHOION_LOG_WARNING(
Void::Log::warn("SignatureCipher", "{}",
std::format("curl failed with status {} for {}", status, url));
return std::nullopt;
}
if (result.empty()) {
ECHOION_LOG_WARNING(
Void::Log::warn("SignatureCipher", "{}",
std::format("Downloaded empty file from {}", url));
return std::nullopt;
}
@@ -536,7 +536,7 @@ namespace Echoion::Core
// Create QuickJS runtime
runtime_ = JS_NewRuntime();
if (!runtime_) {
ECHOION_LOG_ERROR("Failed to create QuickJS runtime");
Void::Log::error("SignatureCipher", "{}", "Failed to create QuickJS runtime");
return;
}
@@ -549,7 +549,7 @@ namespace Echoion::Core
// Create context
context_ = JS_NewContext(runtime_);
if (!context_) {
ECHOION_LOG_ERROR("Failed to create QuickJS context");
Void::Log::error("SignatureCipher", "{}", "Failed to create QuickJS context");
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
return;
@@ -577,14 +577,14 @@ namespace Echoion::Core
std::istreambuf_iterator<char>());
libCode = std::string((std::istreambuf_iterator<char>(libFile)),
std::istreambuf_iterator<char>());
ECHOION_LOG_INFO(
Void::Log::info("SignatureCipher", "{}",
std::format("Loaded solver libraries from cache (core: {} "
"bytes, lib: {} bytes)",
coreCode.size(), libCode.size()));
// Validate content
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_WARNING("Cached solver files are empty");
Void::Log::warn("SignatureCipher", "{}", "Cached solver files are empty");
coreCode.clear();
libCode.clear();
}
@@ -593,7 +593,7 @@ namespace Echoion::Core
// Download if not in cache or empty
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_INFO(
Void::Log::info("SignatureCipher", "{}",
"Downloading solver libraries from GitHub releases...");
// Download core
@@ -609,7 +609,7 @@ namespace Echoion::Core
coreCode = *coreOpt;
libCode = *libOpt;
ECHOION_LOG_DEBUG(
Void::Log::debug("SignatureCipher", "{}",
std::format("Downloaded core: {} bytes, lib: {} bytes",
coreCode.size(), libCode.size()));
@@ -618,19 +618,19 @@ namespace Echoion::Core
std::string_view preview(
coreCode.c_str(),
std::min(size_t(200), coreCode.size()));
ECHOION_LOG_DEBUG(std::format("Core preview: {}", preview));
Void::Log::debug("SignatureCipher", "{}", std::format("Core preview: {}", preview));
}
// Validate downloaded content looks like JS
if (coreCode.find("function") == std::string::npos &&
coreCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING("Downloaded core.js doesn't look like "
Void::Log::warn("SignatureCipher", "{}", "Downloaded core.js doesn't look like "
"valid JavaScript");
coreCode.clear();
}
if (libCode.find("function") == std::string::npos &&
libCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING(
Void::Log::warn("SignatureCipher", "{}",
"Downloaded lib.js doesn't look like valid JavaScript");
libCode.clear();
}
@@ -645,12 +645,12 @@ namespace Echoion::Core
libOut << libCode;
coreOut.close();
libOut.close();
ECHOION_LOG_INFO(
Void::Log::info("SignatureCipher", "{}",
"Solver libraries cached successfully");
}
}
} else {
ECHOION_LOG_WARNING("Failed to download solver libraries");
Void::Log::warn("SignatureCipher", "{}", "Failed to download solver libraries");
}
}
@@ -668,11 +668,11 @@ namespace Echoion::Core
JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(libResult)) {
libLoaded = true;
ECHOION_LOG_DEBUG("Solver lib.js loaded successfully");
Void::Log::debug("SignatureCipher", "{}", "Solver lib.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_WARNING(
Void::Log::warn("SignatureCipher", "{}",
std::format("Failed to load lib solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
@@ -690,11 +690,11 @@ namespace Echoion::Core
"bridge", JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(bridgeResult)) {
bridgeLoaded = true;
ECHOION_LOG_DEBUG("Solver bridge created successfully");
Void::Log::debug("SignatureCipher", "{}", "Solver bridge created successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Failed to load bridge: {}",
Void::Log::error("SignatureCipher", "{}", std::format("Failed to load bridge: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
@@ -710,11 +710,11 @@ namespace Echoion::Core
JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(coreResult)) {
coreLoaded = true;
ECHOION_LOG_DEBUG("Solver core.js loaded successfully");
Void::Log::debug("SignatureCipher", "{}", "Solver core.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Failed to load core solver: {}",
Void::Log::error("SignatureCipher", "{}", std::format("Failed to load core solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
@@ -724,7 +724,7 @@ namespace Echoion::Core
// If core failed to load, we can't solve cipher signatures
if (!coreLoaded) {
ECHOION_LOG_WARNING(
Void::Log::warn("SignatureCipher", "{}",
"Loading fallback solver stub - ciphered videos won't work");
JSValue fallbackResult = JS_Eval(
context_, FALLBACK_CORE_JS.data(), FALLBACK_CORE_JS.size(),
@@ -742,14 +742,14 @@ namespace Echoion::Core
JS_FreeValue(context_, global);
if (!hasJsc) {
ECHOION_LOG_ERROR("jsc function not found after loading solver - "
Void::Log::error("SignatureCipher", "{}", "jsc function not found after loading solver - "
"ciphered videos won't work");
cleanupQuickJS();
return;
}
solverInitialized_ = true;
ECHOION_LOG_INFO(
Void::Log::info("SignatureCipher", "{}",
"QuickJS solver initialized successfully (jsc function verified)");
}
@@ -767,7 +767,7 @@ namespace Echoion::Core
if (JS_IsException(result)) {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("JS execution error: {}",
Void::Log::error("SignatureCipher", "{}", std::format("JS execution error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
+11 -11
View File
@@ -1,4 +1,4 @@
#include "LoggerInterface.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/SubscriptionManager.hpp"
namespace Echoion::Core
@@ -26,7 +26,7 @@ namespace Echoion::Core
// Load existing subscriptions from database
auto result = database_->getAllSubscribers();
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}",
Void::Log::warn("SubscriptionManager", "{}", std::format("Failed to load subscriptions: {}",
result.error().message));
// Not fatal - start with empty subscriptions
} else {
@@ -36,7 +36,7 @@ namespace Echoion::Core
}
initialized_ = true;
ECHOION_LOG_INFO(
Void::Log::info("SubscriptionManager", "{}",
std::format("SubscriptionManager initialized ({} subscribers)",
subscribedUids_.size()));
return {};
@@ -53,7 +53,7 @@ namespace Echoion::Core
initialized_ = false;
database_.reset();
subscribedUids_.clear();
ECHOION_LOG_INFO("SubscriptionManager shutdown");
Void::Log::info("SubscriptionManager", "{}", "SubscriptionManager shutdown");
}
bool SubscriptionManager::subscribe(const std::string& uid,
@@ -74,7 +74,7 @@ namespace Echoion::Core
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("SubscriptionManager", "{}",
std::format("Failed to add subscriber {} to database: {}",
uid, result.error().message));
return false;
@@ -82,7 +82,7 @@ namespace Echoion::Core
}
subscribedUids_.insert(uid);
ECHOION_LOG_INFO(
Void::Log::info("SubscriptionManager", "{}",
std::format("Client {} ({}) subscribed", nickname, uid));
return true;
}
@@ -97,12 +97,12 @@ namespace Echoion::Core
if (database_) {
auto result = database_->removeSubscriber(uid);
if (!result) {
ECHOION_LOG_ERROR(std::format(
Void::Log::error("SubscriptionManager", "{}", std::format(
"Failed to remove subscriber {} from database: {}", uid,
result.error().message));
}
}
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
Void::Log::info("SubscriptionManager", "{}", std::format("Client {} unsubscribed", uid));
}
return removed;
}
@@ -173,7 +173,7 @@ namespace Echoion::Core
if (database_) {
auto result = database_->addSubscriber(uid, nickname);
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("SubscriptionManager", "{}",
std::format("Failed to update nickname for {}: {}", uid,
result.error().message));
return false;
@@ -201,7 +201,7 @@ namespace Echoion::Core
if (database_) {
auto result = database_->clearAllSubscribers();
if (!result) {
ECHOION_LOG_ERROR(
Void::Log::error("SubscriptionManager", "{}",
std::format("Failed to clear all subscribers: {}",
result.error().message));
return false;
@@ -209,7 +209,7 @@ namespace Echoion::Core
}
subscribedUids_.clear();
ECHOION_LOG_INFO("All subscriptions cleared");
Void::Log::info("SubscriptionManager", "{}", "All subscriptions cleared");
return true;
}
+9 -9
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/UrlShortener.hpp"
#include <Void/Data/Json.hpp>
#include <format>
@@ -31,7 +31,7 @@ namespace Echoion::Core
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}",
Void::Log::debug("UrlShortener", "{}", std::format("URL cache hit: {} -> {}",
originalUrl,
it->second.shortenedUrl));
return it->second.shortenedUrl;
@@ -59,20 +59,20 @@ namespace Echoion::Core
{"Content-Type", "application/json"},
{"User-Agent", "EchoionBot/1.0"}};
ECHOION_LOG_DEBUG(
Void::Log::debug("UrlShortener", "{}",
std::format("Shortening URL via faumaray.ru: {}", originalUrl));
auto response = networkClient_->post(apiUrl, jsonBody, headers);
if (!response) {
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
Void::Log::warn("UrlShortener", "{}", std::format("URL shortening failed: {}",
response.error().message));
return Api::fail(Api::ErrorCode::NetworkError,
"Failed to shorten URL");
}
if (!response->ok()) {
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
Void::Log::warn("UrlShortener", "{}", std::format("URL shortening returned HTTP {}",
response->status));
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}",
@@ -84,7 +84,7 @@ namespace Echoion::Core
// "https://faumaray.ru/xxxxx"}
auto parsed = Void::Json::parse(response->body);
if (!parsed) {
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
Void::Log::warn("UrlShortener", "{}", "Failed to parse URL shortening response");
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse shortening response");
}
@@ -94,7 +94,7 @@ namespace Echoion::Core
if (shortUrl && shortUrl->is_string()) {
shortenedUrl = shortUrl->as_string();
} else {
ECHOION_LOG_WARNING("No shortUrl field in response");
Void::Log::warn("UrlShortener", "{}", "No shortUrl field in response");
return Api::fail(Api::ErrorCode::ParseError,
"No shortUrl in response");
}
@@ -107,12 +107,12 @@ namespace Echoion::Core
.timestamp = std::chrono::system_clock::now()};
}
ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}",
Void::Log::debug("UrlShortener", "{}", std::format("URL shortened: {} -> {}",
originalUrl, shortenedUrl));
return shortenedUrl;
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("UrlShortener", "{}", std::format(
"Exception parsing shortening response: {}", e.what()));
return Api::fail(
Api::ErrorCode::ParseError, "Exception during URL shortening");
+66 -67
View File
@@ -1,6 +1,5 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/YouTubeClient.hpp"
#include <LoggerInterface.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Text/Html.hpp>
#include <Void/Text/Url.hpp>
@@ -41,7 +40,7 @@ namespace Echoion::Core
return {};
}
ECHOION_LOG_INFO("Initializing YouTube client...");
Void::Log::info("YouTubeClient", "{}", "Initializing YouTube client...");
// Initialize yt-dlp manager (downloads if needed)
auto result = ytDlpManager_->initialize();
@@ -53,7 +52,7 @@ namespace Echoion::Core
ytDlpManager_->setThreadPoolSize(maxConcurrentResolutions_);
initialized_ = true;
ECHOION_LOG_INFO("YouTube client initialized successfully");
Void::Log::info("YouTubeClient", "{}", "YouTube client initialized successfully");
return {};
}
@@ -80,7 +79,7 @@ namespace Echoion::Core
std::lock_guard<std::mutex> lock(configMutex_);
if (proxy.has_value() && proxy->enabled()) {
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("YouTubeClient proxy configured: {}:{}",
proxy->host, proxy->port));
}
@@ -98,7 +97,7 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(configMutex_);
apiKey_ = apiKey;
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
"YouTube API key configured for enhanced playlist resolution");
}
@@ -174,7 +173,7 @@ namespace Echoion::Core
}
auto startTime = std::chrono::steady_clock::now();
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("Getting audio stream URL for video: {}", videoId));
// Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm)
@@ -182,16 +181,16 @@ namespace Echoion::Core
// Pass just the video ID to yt-dlp
std::string videoIdStr(videoId);
ECHOION_LOG_DEBUG("Starting yt-dlp audio URL extraction...");
Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp audio URL extraction...");
auto future = ytDlpManager_->executeAsync(
{videoIdStr, "-f", "bestaudio/251/140", "-g", "--no-warnings"});
// Wait with timeout (30 seconds)
ECHOION_LOG_DEBUG("Waiting for yt-dlp audio URL (30s timeout)...");
Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp audio URL (30s timeout)...");
auto waitStatus = future.wait_for(std::chrono::seconds(30));
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
"yt-dlp audio URL extraction timed out after 30s");
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp audio URL extraction timed out");
@@ -200,7 +199,7 @@ namespace Echoion::Core
auto ytdlpResult = future.get();
if (!ytdlpResult.success) {
ECHOION_LOG_WARNING("yt-dlp audio URL extraction failed");
Void::Log::warn("YouTubeClient", "{}", "yt-dlp audio URL extraction failed");
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp audio URL extraction failed");
}
@@ -216,12 +215,12 @@ namespace Echoion::Core
.count();
if (!result.empty() && result.find("http") == 0) {
ECHOION_LOG_INFO(std::format(
Void::Log::info("YouTubeClient", "{}", std::format(
"Successfully got audio URL from yt-dlp in {} ms", elapsed));
return result;
}
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("YouTubeClient", "{}", std::format(
"Failed to get audio URL from yt-dlp after {} ms", elapsed));
return Api::fail(
Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp");
@@ -252,7 +251,7 @@ namespace Echoion::Core
"Video ID is empty");
}
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("Getting video info for ID: '{}'", videoId));
auto infoStart = std::chrono::steady_clock::now();
@@ -262,18 +261,18 @@ namespace Echoion::Core
ytDlpManager_->executeAsync({videoIdStr, "-J", "--no-warnings"});
// Wait with timeout (30 seconds)
ECHOION_LOG_DEBUG("Waiting for yt-dlp video info (30s timeout)...");
Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp video info (30s timeout)...");
auto waitStatus = result.wait_for(std::chrono::seconds(30));
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("yt-dlp video info timed out after 30s");
Void::Log::warn("YouTubeClient", "{}", "yt-dlp video info timed out after 30s");
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp video info timed out");
}
auto ytdlpResult = result.get();
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("yt-dlp video info completed in {} ms",
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - infoStart)
@@ -366,17 +365,17 @@ namespace Echoion::Core
// Use YouTube Data API v3 if key is available
if (hasApiKey()) {
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("Searching YouTube via API: '{}'", query));
result = searchWithApi(query, pageToken);
} else {
// Fallback to yt-dlp if no API key
ECHOION_LOG_WARNING("No YouTube API key configured, falling back "
Void::Log::warn("YouTubeClient", "{}", "No YouTube API key configured, falling back "
"to yt-dlp for search");
result = searchWithYtDlp(query, pageToken);
}
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("YouTube search took {} ms",
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - startTime)
@@ -409,7 +408,7 @@ namespace Echoion::Core
}
// Execute with timeout (10 seconds for API search)
ECHOION_LOG_DEBUG("Executing YouTube API search with 10s timeout...");
Void::Log::debug("YouTubeClient", "{}", "Executing YouTube API search with 10s timeout...");
// Use shared promise so detached thread can safely complete
auto responsePromise =
@@ -419,36 +418,36 @@ namespace Echoion::Core
std::thread apiThread(
[this, url = std::string(url), responsePromise]() {
ECHOION_LOG_DEBUG("API request thread started");
Void::Log::debug("YouTubeClient", "{}", "API request thread started");
try {
auto result = networkClient_->get(url);
responsePromise->set_value(std::move(result));
} catch (...) {
responsePromise->set_exception(std::current_exception());
}
ECHOION_LOG_DEBUG("API request thread completed");
Void::Log::debug("YouTubeClient", "{}", "API request thread completed");
});
// Wait with timeout
auto waitStatus = responseFuture.wait_for(std::chrono::seconds(10));
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("YouTube API search timed out after 10s");
Void::Log::warn("YouTubeClient", "{}", "YouTube API search timed out after 10s");
apiThread.detach(); // Thread owns shared_ptr, safe to detach
return Api::fail(Api::ErrorCode::NetworkError,
"YouTube API search timed out");
}
ECHOION_LOG_DEBUG("Joining API request thread...");
Void::Log::debug("YouTubeClient", "{}", "Joining API request thread...");
apiThread.join();
ECHOION_LOG_DEBUG("API request thread joined");
Void::Log::debug("YouTubeClient", "{}", "API request thread joined");
// Get the response
Api::Result<Void::Net::Response> response;
try {
response = responseFuture.get();
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
Void::Log::error("YouTubeClient", "{}",
std::format("API request threw exception: {}", e.what()));
return Api::fail(Api::ErrorCode::NetworkError,
std::format("API request failed: {}", e.what()));
@@ -456,10 +455,10 @@ namespace Echoion::Core
// Log response status
if (response) {
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("API response status: {}", response->status));
} else {
ECHOION_LOG_WARNING(std::format("API request failed: {}",
Void::Log::warn("YouTubeClient", "{}", std::format("API request failed: {}",
response.error().message));
}
@@ -544,23 +543,23 @@ namespace Echoion::Core
// Fetch duration for each video using videos endpoint (batch
// request)
if (!videoIds.empty()) {
ECHOION_LOG_DEBUG("Fetching video durations...");
Void::Log::debug("YouTubeClient", "{}", "Fetching video durations...");
fetchVideoDurations(result.tracks, videoIds);
ECHOION_LOG_DEBUG("Video durations fetched");
Void::Log::debug("YouTubeClient", "{}", "Video durations fetched");
}
}
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("YouTube API search returned {} results",
result.tracks.size()));
// Populate shortened URLs for all tracks (already non-blocking with
// timeout)
ECHOION_LOG_DEBUG("Populating shortened URLs...");
Void::Log::debug("YouTubeClient", "{}", "Populating shortened URLs...");
populateShortenedUrls(result.tracks);
ECHOION_LOG_DEBUG("Shortened URLs populated");
Void::Log::debug("YouTubeClient", "{}", "Shortened URLs populated");
ECHOION_LOG_DEBUG("Returning search result");
Void::Log::debug("YouTubeClient", "{}", "Returning search result");
return result;
} catch (const std::exception& e) {
@@ -617,7 +616,7 @@ namespace Echoion::Core
auto waitStatus = responseFuture.wait_for(std::chrono::seconds(5));
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("Video duration fetch timed out after 5s");
Void::Log::warn("YouTubeClient", "{}", "Video duration fetch timed out after 5s");
durationThread.detach();
return;
}
@@ -628,13 +627,13 @@ namespace Echoion::Core
try {
response = responseFuture.get();
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
std::format("Video duration request failed: {}", e.what()));
return;
}
if (!response || !response->ok()) {
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
"Failed to fetch video durations from YouTube API");
return;
}
@@ -664,7 +663,7 @@ namespace Echoion::Core
(*contentDetails).get_str("duration");
auto duration = Void::Time::parse_iso8601_interval(durationStr).value_or(std::chrono::seconds{0});
if (duration.count() > 0) {
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("Got duration: {}, parse as: {}",
durationStr, duration));
durationMap[videoId] = duration;
@@ -684,7 +683,7 @@ namespace Echoion::Core
}
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
std::format("Failed to parse video durations: {}", e.what()));
}
}
@@ -698,7 +697,7 @@ namespace Echoion::Core
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
}
ECHOION_LOG_DEBUG("Starting yt-dlp search...");
Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp search...");
auto searchStart = std::chrono::steady_clock::now();
// yt-dlp search format: ytsearch5:query
@@ -708,11 +707,11 @@ namespace Echoion::Core
{searchQuery, "-J", "--flat-playlist", "--no-warnings"});
// Wait with timeout (30 seconds for yt-dlp search)
ECHOION_LOG_DEBUG("Waiting for yt-dlp search result (30s timeout)...");
Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp search result (30s timeout)...");
auto waitStatus = result.wait_for(std::chrono::seconds(30));
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("yt-dlp search timed out after 30s");
Void::Log::warn("YouTubeClient", "{}", "yt-dlp search timed out after 30s");
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp search timed out");
}
@@ -722,7 +721,7 @@ namespace Echoion::Core
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - searchStart)
.count();
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("yt-dlp search completed in {} ms", elapsed));
if (!ytdlpResult.success || ytdlpResult.output.empty()) {
@@ -798,7 +797,7 @@ namespace Echoion::Core
"YouTubeClient not initialized");
}
ECHOION_LOG_INFO(std::format("Fetching playlist: {}", playlistId));
Void::Log::info("YouTubeClient", "{}", std::format("Fetching playlist: {}", playlistId));
// Step 1: Fetch playlist items (via API v2 if key available, else
// yt-dlp)
@@ -815,7 +814,7 @@ namespace Echoion::Core
return emptyInfo;
}
ECHOION_LOG_INFO(std::format(
Void::Log::info("YouTubeClient", "{}", std::format(
"Found {} tracks in playlist, resolving individually...",
items.size()));
@@ -850,12 +849,12 @@ namespace Echoion::Core
if (result) {
resolvedTracks.push_back(std::move(*result));
} else {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("YouTubeClient", "{}", std::format(
"Failed to resolve track: {}", result.error().message));
}
}
ECHOION_LOG_DEBUG(std::format(
Void::Log::debug("YouTubeClient", "{}", std::format(
"Resolved batch {}/{} ({} tracks so far)", (i / batchSize) + 1,
(items.size() + batchSize - 1) / batchSize,
resolvedTracks.size()));
@@ -870,7 +869,7 @@ namespace Echoion::Core
info.name = std::format("Playlist ({} tracks)", info.tracks.size());
}
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("Successfully resolved {}/{} tracks from playlist",
info.tracks.size(), items.size()));
@@ -904,12 +903,12 @@ namespace Echoion::Core
return;
}
ECHOION_LOG_INFO(std::format("Streaming playlist: {}", playlistId));
Void::Log::info("YouTubeClient", "{}", std::format("Streaming playlist: {}", playlistId));
// Fetch playlist items first (quick operation)
auto itemsResult = fetchPlaylistItems(playlistId);
if (!itemsResult || itemsResult->empty()) {
ECHOION_LOG_WARNING("No items found in playlist or fetch failed");
Void::Log::warn("YouTubeClient", "{}", "No items found in playlist or fetch failed");
if (onComplete) {
onComplete();
}
@@ -917,7 +916,7 @@ namespace Echoion::Core
}
const auto& items = *itemsResult;
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("Streaming {} tracks from playlist", items.size()));
// Notify about total tracks
@@ -955,17 +954,17 @@ namespace Echoion::Core
// start
trackCallback(std::move(*result));
} else {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("YouTubeClient", "{}", std::format(
"Failed to resolve track: {}", result.error().message));
}
}
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("Processed batch {}/{}", (i / batchSize) + 1,
(items.size() + batchSize - 1) / batchSize));
}
ECHOION_LOG_INFO("Playlist streaming complete");
Void::Log::info("YouTubeClient", "{}", "Playlist streaming complete");
if (onComplete) {
onComplete();
}
@@ -979,7 +978,7 @@ namespace Echoion::Core
// Try using YouTube Data API v3 if key is available
if (hasApiKey()) {
ECHOION_LOG_INFO("Using YouTube Data API v3 for playlist fetch");
Void::Log::info("YouTubeClient", "{}", "Using YouTube Data API v3 for playlist fetch");
std::optional<std::string> pageToken;
do {
@@ -987,7 +986,7 @@ namespace Echoion::Core
auto response = networkClient_->get(apiUrl);
if (!response || !response->ok()) {
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
"YouTube API request failed, falling back to yt-dlp");
break; // Fall back to yt-dlp
}
@@ -995,7 +994,7 @@ namespace Echoion::Core
try {
auto parsed = Void::Json::parse(response->body);
if (!parsed) {
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
"Failed to parse YouTube API response, "
"falling back to yt-dlp");
break;
@@ -1049,21 +1048,21 @@ namespace Echoion::Core
}
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format(
Void::Log::warn("YouTubeClient", "{}", std::format(
"Error parsing YouTube API response: {}", e.what()));
break; // Fall back to yt-dlp
}
} while (pageToken.has_value());
if (!items.empty()) {
ECHOION_LOG_INFO(std::format(
Void::Log::info("YouTubeClient", "{}", std::format(
"Fetched {} tracks via YouTube API", items.size()));
return items;
}
}
// Fallback: Use yt-dlp to fetch playlist items
ECHOION_LOG_INFO("Using yt-dlp for playlist fetch");
Void::Log::info("YouTubeClient", "{}", "Using yt-dlp for playlist fetch");
if (!ytDlpManager_->isAvailable()) {
return Api::fail(
@@ -1114,7 +1113,7 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("Fetched {} tracks via yt-dlp", items.size()));
return items;
@@ -1232,7 +1231,7 @@ namespace Echoion::Core
// Handle faumaray.ru redirects using NetworkClient
if (url_str.find("faumaray.ru") != std::string::npos &&
networkClient_) {
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("Following redirect for: {}", url_str));
std::vector<Void::Net::Header> headers = {
@@ -1248,7 +1247,7 @@ namespace Echoion::Core
if (response->status >= 300 && response->status < 400) {
auto location = response->header("location");
if (location.has_value()) {
ECHOION_LOG_DEBUG(
Void::Log::debug("YouTubeClient", "{}",
std::format("Redirected to: {}", *location));
url_str = std::string(*location);
}
@@ -1323,7 +1322,7 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(configMutex_);
urlShorteningEnabled_ = enabled;
ECHOION_LOG_INFO(
Void::Log::info("YouTubeClient", "{}",
std::format("URL shortening {}", enabled ? "enabled" : "disabled"));
}
@@ -1378,13 +1377,13 @@ namespace Echoion::Core
}
if (shortenedUrl->has_value()) {
track.shortenedUrl = *shortenedUrl;
ECHOION_LOG_DEBUG(std::format("URL shortened for {}: {}",
Void::Log::debug("YouTubeClient", "{}", std::format("URL shortened for {}: {}",
track.title,
track.shortenedUrl.value()));
}
} else {
// Timeout - thread owns shared_ptr, safe to detach
ECHOION_LOG_WARNING(
Void::Log::warn("YouTubeClient", "{}",
"URL shortening timed out after 3s, detaching thread");
shortenThread.detach();
}
+28 -28
View File
@@ -1,4 +1,4 @@
#include "echoion/core/Logger.hpp"
#include <Void/Log/Log.hpp>
#include "echoion/core/YtDlpManager.hpp"
#include <Void/System/Process.hpp>
#include <array>
@@ -100,15 +100,15 @@ namespace Echoion::Core
return {};
}
ECHOION_LOG_INFO("Initializing yt-dlp manager...");
Void::Log::info("YtDlpManager", "{}", "Initializing yt-dlp manager...");
// Create storage directory if needed
std::filesystem::path storageDir = getStorageDir();
ECHOION_LOG_DEBUG(
Void::Log::debug("YtDlpManager", "{}",
std::format("yt-dlp storage dir: {}", storageDir.string()));
if (!std::filesystem::exists(storageDir)) {
ECHOION_LOG_INFO("Creating yt-dlp storage directory...");
Void::Log::info("YtDlpManager", "{}", "Creating yt-dlp storage directory...");
try {
std::filesystem::create_directories(storageDir);
} catch (const std::exception& e) {
@@ -121,27 +121,27 @@ namespace Echoion::Core
}
executablePath_ = storageDir / getExecutableName();
ECHOION_LOG_DEBUG(std::format("yt-dlp executable path: {}",
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp executable path: {}",
executablePath_.string()));
// Check if yt-dlp exists
bool exists = std::filesystem::exists(executablePath_);
ECHOION_LOG_DEBUG(std::format("yt-dlp exists: {}", exists));
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp exists: {}", exists));
if (!exists) {
ECHOION_LOG_INFO("yt-dlp not found, downloading...");
Void::Log::info("YtDlpManager", "{}", "yt-dlp not found, downloading...");
auto result = downloadYtDlp();
if (!result) {
return result;
}
} else if (shouldUpdate()) {
ECHOION_LOG_INFO(
Void::Log::info("YtDlpManager", "{}",
"yt-dlp may be outdated, updating in background...");
// Start async update to avoid blocking initialization
std::thread([this]() {
auto result = update();
if (!result) {
ECHOION_LOG_WARNING(
Void::Log::warn("YtDlpManager", "{}",
std::format("yt-dlp update failed: {}",
result.error().toString()));
}
@@ -152,14 +152,14 @@ namespace Echoion::Core
// Verify it works (outside lock to prevent deadlock with
// execute()->getCookieArgs())
ECHOION_LOG_INFO("Checking yt-dlp version...");
Void::Log::info("YtDlpManager", "{}", "Checking yt-dlp version...");
std::string version = getVersion();
if (version.empty()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"yt-dlp executable not working");
}
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp ready: {}", version));
// Start thread pool for async operations
startThreadPool();
@@ -177,12 +177,12 @@ namespace Echoion::Core
unsigned int hardwareThreads = std::thread::hardware_concurrency();
if (hardwareThreads > 0 && threadPoolSize_ > hardwareThreads / 2) {
threadPoolSize_ = std::max(1u, hardwareThreads / 2);
ECHOION_LOG_INFO(std::format(
Void::Log::info("YtDlpManager", "{}", std::format(
"Auto-adjusted yt-dlp thread pool to {} threads (hardware: {})",
threadPoolSize_, hardwareThreads));
}
ECHOION_LOG_INFO(std::format(
Void::Log::info("YtDlpManager", "{}", std::format(
"Starting yt-dlp thread pool with {} threads", threadPoolSize_));
pool_ = std::make_unique<Void::Concurrency::ThreadPool>(threadPoolSize_);
@@ -226,10 +226,10 @@ namespace Echoion::Core
std::lock_guard<std::mutex> lock(proxyMutex_);
proxyConfig_ = proxy;
if (proxy.has_value() && proxy->enabled()) {
ECHOION_LOG_INFO(std::format("yt-dlp proxy configured: {}:{}",
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp proxy configured: {}:{}",
proxy->host, proxy->port));
} else {
ECHOION_LOG_INFO("yt-dlp proxy cleared");
Void::Log::info("YtDlpManager", "{}", "yt-dlp proxy cleared");
}
}
@@ -282,7 +282,7 @@ namespace Echoion::Core
}
std::string downloadUrl = getDownloadUrl();
ECHOION_LOG_INFO(
Void::Log::info("YtDlpManager", "{}",
std::format("Downloading yt-dlp from: {}", downloadUrl));
std::vector<Void::Net::Header> headers = {
@@ -328,7 +328,7 @@ namespace Echoion::Core
}
}
ECHOION_LOG_INFO(std::format("Following redirect (HTTP {}): {}",
Void::Log::info("YtDlpManager", "{}", std::format("Following redirect (HTTP {}): {}",
response.status, newUrl));
downloadUrl = newUrl;
redirectCount++;
@@ -344,7 +344,7 @@ namespace Echoion::Core
response.status));
}
ECHOION_LOG_INFO(
Void::Log::info("YtDlpManager", "{}",
std::format("Downloaded {} bytes", response.body.size()));
// Write to file
@@ -381,7 +381,7 @@ namespace Echoion::Core
} catch (...) {
}
ECHOION_LOG_INFO("yt-dlp downloaded successfully");
Void::Log::info("YtDlpManager", "{}", "yt-dlp downloaded successfully");
return {};
}
@@ -433,7 +433,7 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(mutex_);
ECHOION_LOG_INFO("Updating yt-dlp...");
Void::Log::info("YtDlpManager", "{}", "Updating yt-dlp...");
// Backup current version
std::filesystem::path backupPath = executablePath_.string() + ".backup";
@@ -474,21 +474,21 @@ namespace Echoion::Core
"Updated yt-dlp not working");
}
ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version));
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp updated to: {}", version));
return {};
}
std::string YtDlpManager::getVersion() const
{
if (!std::filesystem::exists(executablePath_)) {
ECHOION_LOG_WARNING(
Void::Log::warn("YtDlpManager", "{}",
"yt-dlp executable not found for version check");
return "";
}
ECHOION_LOG_DEBUG("Executing yt-dlp --version...");
Void::Log::debug("YtDlpManager", "{}", "Executing yt-dlp --version...");
std::string result = execute({"--version"});
ECHOION_LOG_DEBUG(std::format("yt-dlp --version output: '{}'", result));
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp --version output: '{}'", result));
// Remove trailing newline
if (!result.empty() && result.back() == '\n') {
@@ -502,14 +502,14 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(mutex_);
cookiesPath_ = path;
ECHOION_LOG_INFO(std::format("yt-dlp cookies path set to: {}", path));
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp cookies path set to: {}", path));
}
void YtDlpManager::setCookiesFromBrowser(const std::string& browser)
{
std::lock_guard<std::mutex> lock(mutex_);
cookiesFromBrowser_ = browser;
ECHOION_LOG_INFO(
Void::Log::info("YtDlpManager", "{}",
std::format("yt-dlp will use cookies from browser: {}", browser));
}
@@ -565,7 +565,7 @@ namespace Echoion::Core
(args.size() == 1 && args[0] == "--version");
const auto timeout = std::chrono::seconds(isVersionCheck ? 10 : 60);
ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {} ({} args)",
Void::Log::debug("YtDlpManager", "{}", std::format("Executing yt-dlp: {} ({} args)",
executablePath_.string(),
processArgs.size()));
@@ -578,7 +578,7 @@ namespace Echoion::Core
startTime);
if (!procResult) {
ECHOION_LOG_WARNING(std::format("Failed to execute yt-dlp: {}",
Void::Log::warn("YtDlpManager", "{}", std::format("Failed to execute yt-dlp: {}",
procResult.error().message()));
return result;
}