Initial commit

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

No files matched your search

+630
View File
@@ -0,0 +1,630 @@
#include "echoion/core/AudioDecoder.hpp"
#include "echoion/core/NetworkClient.hpp"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
#include <libavutil/dict.h>
#include <libavutil/hwcontext.h>
#include <libavutil/samplefmt.h>
#include <libswresample/swresample.h>
}
#include <format>
#include <cstring>
#include <fstream>
#include <filesystem>
#include <thread>
namespace Echoion::Core {
AudioDecoder::AudioDecoder() = default;
AudioDecoder::~AudioDecoder() {
shutdown();
cleanupFfmpeg();
cleanupHardwareAccel();
}
Api::Result<void> AudioDecoder::initialize(const Api::HwAccelConfig& hwConfig) {
if (initialized_) {
return {};
}
if (zeroCopyEnabled_) {
Api::AudioBufferPool::instance().initialize(
outputSampleRate_ / 50 * outputChannels_,
256
);
}
if (hwConfig.isEnabled()) {
auto result = initializeHardwareAccel(hwConfig);
if (!result) {
ECHOION_LOG_WARNING(std::format("Hardware acceleration init failed: {}, falling back to software",
result.error().message));
}
}
av_log_set_level(AV_LOG_DEBUG);
initialized_ = true;
ECHOION_LOG_INFO("AudioDecoder initialized");
return {};
}
Api::Result<void> AudioDecoder::initializeHardwareAccel(const Api::HwAccelConfig& config) {
enum AVHWDeviceType hwType = AV_HWDEVICE_TYPE_NONE;
switch (config.type) {
case Api::HwAccelType::CUDA: hwType = AV_HWDEVICE_TYPE_CUDA; break;
case Api::HwAccelType::VAAPI: hwType = AV_HWDEVICE_TYPE_VAAPI; break;
case Api::HwAccelType::DXVA2: hwType = AV_HWDEVICE_TYPE_DXVA2; break;
case Api::HwAccelType::D3D11VA: hwType = AV_HWDEVICE_TYPE_D3D11VA; break;
case Api::HwAccelType::VideoToolbox: hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX; break;
default: return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Unsupported hardware acceleration type"));
}
if (av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(hwType)) == AV_HWDEVICE_TYPE_NONE) {
return std::unexpected(Api::Error(Api::ErrorCode::NotSupported, "Hardware acceleration not available on this system"));
}
hwAccelType_ = config.type;
ECHOION_LOG_INFO(std::format("Hardware acceleration configured: {}", av_hwdevice_get_type_name(hwType)));
return {};
}
void AudioDecoder::shutdown() {
decoding_ = false;
shouldExit_ = true; // Signal FFmpeg to abort blocking I/O
cv_.notify_all();
if (decodeThread_.joinable()) {
decodeThread_.join();
}
closeSource();
initialized_ = false;
}
void AudioDecoder::cleanupHardwareAccel() {
if (hwFramesContext_) av_buffer_unref(&hwFramesContext_);
if (hwDeviceContext_) av_buffer_unref(&hwDeviceContext_);
hwAccelEnabled_ = false;
}
Api::Result<void> AudioDecoder::openSource(const std::string& url) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Decoder not initialized"));
}
std::lock_guard<std::mutex> lock(mutex_);
closeSource();
currentUrl_ = url;
AVDictionary* options = nullptr;
av_dict_set(&options, "protocol_whitelist", "file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5,socks5h", 0);
// CRITICAL: Use iOS User Agent to match the client that generated the URL.
// Mismatch between URL client (c=IOS) and User-Agent (Chrome) causes 403 Forbidden.
av_dict_set(&options, "user_agent",
"Mozilla/5.0 (Linux; Android 12; Quest 2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Mobile VR Safari/537.36", 0);
av_dict_set(&options, "timeout", "15000000", 0);
av_dict_set(&options, "reconnect", "1", 0);
av_dict_set(&options, "reconnect_streamed", "1", 0);
av_dict_set(&options, "reconnect_delay_max", "5", 0);
av_dict_set(&options, "analyzeduration", "20000000", 0);
av_dict_set(&options, "probesize", "10240000", 0);
if (proxyConfig_.has_value() && proxyConfig_->isValid()) {
std::string proxyUrl;
if (proxyConfig_->isSocks5()) {
// Use standard socks5:// scheme. FFmpeg http protocol handles this correctly.
// socks5h:// is often rejected by the http protocol handler, causing proxy bypass.
if (proxyConfig_->requiresAuth()) {
proxyUrl = std::format("socks5://{}:{}@{}:{}",
*proxyConfig_->username, *proxyConfig_->password,
proxyConfig_->host, proxyConfig_->port);
} else {
proxyUrl = std::format("socks5://{}:{}",
proxyConfig_->host, proxyConfig_->port);
}
} else {
if (proxyConfig_->requiresAuth()) {
proxyUrl = std::format("http://{}:{}@{}:{}",
*proxyConfig_->username, *proxyConfig_->password,
proxyConfig_->host, proxyConfig_->port);
} else {
proxyUrl = std::format("http://{}:{}",
proxyConfig_->host, proxyConfig_->port);
}
}
av_dict_set(&options, "proxy", proxyUrl.c_str(), 0);
ECHOION_LOG_INFO(std::format("Using proxy for ffmpeg: {}:{}", proxyConfig_->host, proxyConfig_->port));
}
ECHOION_LOG_DEBUG(std::format("Opening audio source: {}", url.substr(0, 80)));
// Allocate format context first (needed for interrupt callback)
formatContext_ = avformat_alloc_context();
if (!formatContext_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
"Failed to allocate format context"));
}
// Set up interrupt callback to allow graceful shutdown during blocking I/O
shouldExit_ = false;
formatContext_->interrupt_callback.callback = [](void* ctx) -> int {
auto* decoder = static_cast<AudioDecoder*>(ctx);
return decoder->shouldExit_.load() ? 1 : 0;
};
formatContext_->interrupt_callback.opaque = this;
int ret = avformat_open_input(&formatContext_, url.c_str(), nullptr, &options);
if (options) {
av_dict_free(&options);
}
if (ret < 0) {
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format("FFmpeg failed to open input (error {}): {}", ret, errbuf));
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Failed to open audio source: {} (FFmpeg error {}: {})",
url.substr(0, 80), ret, errbuf)));
}
ECHOION_LOG_DEBUG("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(std::format("FFmpeg failed to find stream info (error {}): {}", ret, errbuf));
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Failed to find stream info: {}", errbuf)));
}
const AVCodec *decoder = nullptr;
audioStreamIndex_ = -1;
audioStreamIndex_ = av_find_best_stream(formatContext_, AVMEDIA_TYPE_AUDIO, -1,
-1, &decoder, 0);
if (audioStreamIndex_ == -1) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No audio stream found"));
}
codecContext_ = avcodec_alloc_context3(decoder);
if (!codecContext_) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to allocate codec context"));
}
codecContext_->thread_count = 0; // Auto-detect CPU cores
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
ret = avcodec_parameters_to_context(codecContext_,
formatContext_->streams[audioStreamIndex_]->codecpar);
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to copy codec parameters"));
}
ret = avcodec_open2(codecContext_, decoder, nullptr);
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to open codec"));
}
frame_ = av_frame_alloc();
packet_ = av_packet_alloc();
if (!frame_ || !packet_) {
cleanupFfmpeg();
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to allocate frame/packet"));
}
streamInfo_.sampleRate = codecContext_->sample_rate;
streamInfo_.channels = codecContext_->ch_layout.nb_channels;
streamInfo_.bitrate = static_cast<uint32_t>(codecContext_->bit_rate);
streamInfo_.hwAccelerated = hwAccelEnabled_;
streamInfo_.hwAccelType = hwAccelType_;
if (formatContext_->duration != AV_NOPTS_VALUE) {
streamInfo_.duration = std::chrono::milliseconds(
formatContext_->duration * 1000 / AV_TIME_BASE);
}
switch (codecContext_->codec_id) {
case AV_CODEC_ID_MP3: streamInfo_.format = Api::AudioFormat::MP3; break;
case AV_CODEC_ID_AAC: streamInfo_.format = Api::AudioFormat::AAC; break;
case AV_CODEC_ID_OPUS: streamInfo_.format = Api::AudioFormat::Opus; break;
case AV_CODEC_ID_VORBIS: streamInfo_.format = Api::AudioFormat::Vorbis; break;
case AV_CODEC_ID_FLAC: streamInfo_.format = Api::AudioFormat::FLAC; break;
default: streamInfo_.format = Api::AudioFormat::Unknown; break;
}
// Setup resampler to output S16 (int16) like reference - avoids float->int conversion
AVChannelLayout outLayout;
av_channel_layout_default(&outLayout, static_cast<int>(outputChannels_));
ret = swr_alloc_set_opts2(&swrContext_,
&outLayout, AV_SAMPLE_FMT_S16, static_cast<int>(outputSampleRate_),
&codecContext_->ch_layout, codecContext_->sample_fmt, codecContext_->sample_rate,
0, nullptr);
if (codecContext_->sample_rate != outputSampleRate_) {
av_opt_set_int(swrContext_, "linear_interp", 1, 0);
av_opt_set_int(swrContext_, "filter_size", 256, 0);
}
if (ret < 0 || swr_init(swrContext_) < 0) {
cleanupFfmpeg();
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Failed to initialize resampler"));
}
// Allocate output buffer for S16 samples (like reference)
constexpr int maxSamples = 4096;
av_samples_alloc(&outputBuffer_, nullptr, static_cast<int>(outputChannels_), maxSamples,
AV_SAMPLE_FMT_S16, 0);
decoding_ = true;
shouldExit_ = false;
decodeThread_ = std::jthread(&AudioDecoder::decodeThread, this);
ECHOION_LOG_INFO(std::format("Audio source opened: {} -> {} Hz, {} ch, in={} out=S16",
url, outputSampleRate_, outputChannels_,
av_get_sample_fmt_name(codecContext_->sample_fmt)));
return {};
}
void AudioDecoder::closeSource() {
decoding_ = false;
shouldExit_ = true; // Signal FFmpeg to abort blocking I/O
cv_.notify_all();
if (decodeThread_.joinable()) {
decodeThread_.join();
}
cleanupFfmpeg();
currentUrl_.clear();
currentPosition_ = std::chrono::milliseconds(0);
eof_ = false;
shouldExit_ = false; // Reset for next use
}
Api::Result<Api::DecodedAudio> AudioDecoder::decodeFrame() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] {
return !decodedQueue_.empty() || eof_ || !decoding_;
});
if (!decodedQueue_.empty()) {
auto audio = std::move(decodedQueue_.front());
decodedQueue_.pop();
cv_.notify_one();
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
ECHOION_LOG_DEBUG(std::format("Frame consumed: {} samples, {} ms",
audio.view.samplesPerChannel() * 2, audio.timestamp.count()));
return audio;
}
if (eof_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "End of stream"));
}
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Decoder stopped"));
}
static int callCount = 0;
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk, bool blocking) {
callCount++;
std::unique_lock<std::mutex> lock(mutex_);
if (blocking) {
cv_.wait(lock, [this] { return !int16Queue_.empty() || eof_.load(); });
}
if (int16Queue_.empty()) {
return false;
}
outChunk = std::move(int16Queue_.front());
int16Queue_.pop_front();
cv_.notify_one();
if (callCount <= 10 || callCount % 1000 == 0) {
ECHOION_LOG_DEBUG(std::format("getNextChunk {}: returned {} samples, queue left: {}",
callCount, outChunk.size(), int16Queue_.size()));
}
std::lock_guard<std::mutex> statsLock(statsMutex_);
stats_.framesDecoded++;
return true;
}
Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position) {
if (!formatContext_ || audioStreamIndex_ < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No source open"));
}
std::lock_guard<std::mutex> lock(mutex_);
int64_t targetPts = position.count() * AV_TIME_BASE / 1000;
int ret = av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
if (ret < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Seek failed"));
}
avcodec_flush_buffers(codecContext_);
currentPosition_ = position;
std::queue<Api::DecodedAudio> empty;
std::swap(decodedQueue_, empty);
return {};
}
Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const {
if (!initialized_ || !formatContext_) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "No source open"));
}
return streamInfo_;
}
std::chrono::milliseconds AudioDecoder::getPosition() const {
return currentPosition_;
}
bool AudioDecoder::hasMoreData() const {
std::lock_guard<std::mutex> lock(mutex_);
return !decodedQueue_.empty() || (!eof_ && decoding_);
}
void AudioDecoder::setOutputFormat(uint32_t sampleRate, uint32_t channels) {
outputSampleRate_ = sampleRate;
outputChannels_ = channels;
}
void AudioDecoder::setProxyConfig(const std::optional<Api::ProxyConfig>& proxy) {
proxyConfig_ = proxy;
}
AudioDecoder::Stats AudioDecoder::getStats() const {
std::lock_guard<std::mutex> lock(statsMutex_);
return stats_;
}
void AudioDecoder::decodeThread() {
ECHOION_LOG_DEBUG("Decode thread started");
constexpr int maxSamples = 4096;
int packetsRead = 0;
int framesProduced = 0;
while (decoding_.load()) {
// Check queue size limit
{
std::unique_lock<std::mutex> lock(mutex_);
if (int16Queue_.size() >= MAX_INT16_QUEUE_SIZE) {
cv_.wait(lock, [this] { return int16Queue_.size() < MAX_INT16_QUEUE_SIZE || !decoding_; });
if (!decoding_) break;
}
}
int ret = av_read_frame(formatContext_, packet_);
if (ret == AVERROR_EOF) {
break; // End of file - go to flush
}
if (ret < 0) {
continue; // Read error - try next packet
}
packetsRead++;
if (packet_->stream_index != audioStreamIndex_) {
av_packet_unref(packet_);
continue;
}
// Send packet to decoder - ignore errors like reference
avcodec_send_packet(codecContext_, packet_);
av_packet_unref(packet_);
// Receive all available frames
while (decoding_.load()) {
ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR(EAGAIN)) {
break; // Need more packets
}
if (ret < 0) {
break; // Error - continue to next packet
}
// Convert to S16 and queue (like reference)
int outSamples = swr_convert(swrContext_, &outputBuffer_, maxSamples,
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
if (outSamples > 0) {
std::vector<int16_t> chunk(outSamples * outputChannels_);
std::memcpy(chunk.data(), outputBuffer_,
outSamples * outputChannels_ * sizeof(int16_t));
{
std::lock_guard<std::mutex> lock(mutex_);
int16Queue_.push_back(std::move(chunk));
}
cv_.notify_one();
framesProduced++;
if (framesProduced <= 5) {
ECHOION_LOG_DEBUG(std::format("Decode produced frame {}: {} samples",
framesProduced, chunk.size()));
}
}
}
}
// Final flush (CRITICAL - like reference)
avcodec_send_packet(codecContext_, nullptr);
while (decoding_.load()) {
int ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN)) {
break;
}
if (ret < 0) break;
int outSamples = swr_convert(swrContext_, &outputBuffer_, 4096,
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
if (outSamples > 0) {
std::vector<int16_t> chunk(outSamples * outputChannels_);
std::memcpy(chunk.data(), outputBuffer_,
outSamples * outputChannels_ * sizeof(int16_t));
{
std::lock_guard<std::mutex> lock(mutex_);
int16Queue_.push_back(std::move(chunk));
}
cv_.notify_one();
framesProduced++;
}
}
eof_ = true;
cv_.notify_all();
ECHOION_LOG_INFO(std::format("Decode finished. Packets: {}, Frames: {}",
packetsRead, framesProduced));
}
Api::Result<void> AudioDecoder::readPacket() {
int ret = av_read_frame(formatContext_, packet_);
if (ret < 0) {
if (ret == AVERROR_EOF) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "End of file"));
}
if (ret == AVERROR_EXIT) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Interrupted"));
}
char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf));
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
std::format("Error reading frame: {}", errbuf)));
}
if (packet_->stream_index != audioStreamIndex_) {
av_packet_unref(packet_);
return {};
}
// Send packet to decoder - don't check error, just like reference code
// Some packets may be corrupt but we continue to next
avcodec_send_packet(codecContext_, packet_);
av_packet_unref(packet_);
// Receive all available frames from the decoder
while (true) {
ret = avcodec_receive_frame(codecContext_, frame_);
if (ret == AVERROR(EAGAIN)) {
// Need more packets to produce a frame
break;
}
if (ret < 0) {
// Error receiving frame - log but continue to next packet
// Don't treat as fatal - Opus may have bad packets that are safe to skip
break;
}
Api::Result<Api::DecodedAudio> audio;
if (zeroCopyEnabled_) {
audio = convertFramePooled();
} else {
audio = convertFrame();
}
if (audio) {
std::lock_guard<std::mutex> lock(mutex_);
decodedQueue_.push(std::move(*audio));
cv_.notify_one();
}
}
return {};
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
std::vector<float> outputBuffer(outSamples * outputChannels_);
uint8_t* outData = reinterpret_cast<uint8_t*>(outputBuffer.data());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) {
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
}
outputBuffer.resize(converted * outputChannels_);
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.view = Api::FloatAudioView(outputBuffer.data(), outputBuffer.size(), outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
}
Api::Result<Api::DecodedAudio> AudioDecoder::convertFramePooled() {
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
auto pooledBuffer = Api::AudioBufferPool::instance().acquireBuffer();
if (!pooledBuffer) return convertFrame();
uint8_t* outData = reinterpret_cast<uint8_t*>(pooledBuffer.get());
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples);
if (converted < 0) return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base;
currentPosition_ = std::chrono::milliseconds(
frame_->pts * 1000 * timeBase.num / timeBase.den);
}
Api::DecodedAudio audio;
audio.pooledSamples = std::move(pooledBuffer);
audio.view = Api::FloatAudioView(audio.pooledSamples.get(), converted * outputChannels_, outputChannels_);
audio.sampleRate = outputSampleRate_;
audio.channels = outputChannels_;
audio.timestamp = currentPosition_;
return audio;
}
void AudioDecoder::cleanupFfmpeg() {
if (swrContext_) swr_free(&swrContext_);
if (frame_) av_frame_free(&frame_);
if (packet_) av_packet_free(&packet_);
if (codecContext_) avcodec_free_context(&codecContext_);
if (formatContext_) avformat_close_input(&formatContext_);
if (outputBuffer_) av_freep(&outputBuffer_);
audioStreamIndex_ = -1;
}
} // namespace Echoion::Core
+46
View File
@@ -0,0 +1,46 @@
#include "echoion/api/Cache.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Api {
CacheManager& CacheManager::instance() {
static CacheManager instance;
return instance;
}
void CacheManager::initialize() {
ECHOION_LOG_INFO("CacheManager initialized");
}
void CacheManager::shutdown() {
clearAll();
ECHOION_LOG_INFO("CacheManager shutdown");
}
void CacheManager::purgeAllExpired() {
size_t totalPurged = 0;
totalPurged += httpCache_.purgeExpired();
totalPurged += trackCache_.purgeExpired();
totalPurged += metadataCache_.purgeExpired();
if (totalPurged > 0) {
ECHOION_LOG_INFO(std::format("Purged {} expired cache entries", totalPurged));
}
}
void CacheManager::clearAll() {
httpCache_.clear();
trackCache_.clear();
metadataCache_.clear();
ECHOION_LOG_INFO("All caches cleared");
}
std::unordered_map<std::string, CacheStats> CacheManager::getAllStats() const {
return {
{"http", httpCache_.getStats()},
{"track", trackCache_.getStats()},
{"metadata", metadataCache_.getStats()}
};
}
} // namespace Echoion::Api
+278
View File
@@ -0,0 +1,278 @@
#include "echoion/core/CommandManager.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/Logger.hpp"
#include <echoion/core/commands/Commands.hpp>
#include <algorithm>
#include <sstream>
#include <format>
namespace Echoion::Core {
// --- Internal Help Command ---
class CommandManager::HelpCommand : public Command {
CommandManager& manager_;
public:
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
void execute(const CommandContext& ctx) override {
try {
auto prefix = manager_.getPrefix();
std::string helpMsg = std::format("\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
// Get commands visible to this client
auto visibleCommands = manager_.getVisibleCommands(ctx.clientId);
// Group commands by category
std::map<CommandCategory, std::vector<std::pair<std::string, CommandPtr>>> grouped;
for (const auto& [name, cmd] : visibleCommands) {
grouped[cmd->getCategory()].push_back({name, cmd});
}
for (const auto& [cat, cmds] : grouped) {
helpMsg += std::format("**{} Commands**\n", toString(cat));
for (const auto& [name, cmd] : cmds) {
// Format: prefix!command usage
if (!cmd->getUsage().empty()) {
helpMsg += std::format("`{}{}` {}\n", prefix, name, cmd->getUsage());
} else {
helpMsg += std::format("`{}{}`\n", prefix, name);
}
// Description
helpMsg += std::format("> {}\n", cmd->getDescription());
// Aliases
auto aliases = cmd->getAliases();
if (!aliases.empty()) {
helpMsg += "> Aliases: ";
for (size_t i = 0; i < aliases.size(); ++i) {
helpMsg += std::format("`{}{}`", prefix, aliases[i]);
if (i < aliases.size() - 1) {
helpMsg += ", ";
}
}
helpMsg += "\n";
}
helpMsg += "\n";
}
}
ctx.reply(helpMsg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Help command exception: {}", e.what()));
ctx.reply("Couldn't generate help. Please try again.");
}
}
std::string_view getDescription() const override {
return "Shows this help message with all available commands.";
}
std::string_view getUsage() const override { return "[command]"; }
CommandCategory getCategory() const override { return CommandCategory::Utility; }
std::vector<std::string_view> getAliases() const override {
return {"h", "?", "commands"};
}
};
// --- Manager Implementation ---
CommandManager::CommandManager() {
registerBuiltinCommands();
registerHelpCommand();
}
bool CommandManager::dispatch(
uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName) {
if (!message.starts_with(prefix_)) {
return false;
}
// Skip prefix and trim leading whitespace
std::string_view input = message.substr(prefix_.length());
size_t start = input.find_first_not_of(" \t");
if (start == std::string_view::npos) {
return false;
}
input = input.substr(start);
// Split command and arguments
size_t spacePos = input.find_first_of(" \t");
std::string_view cmdName = (spacePos == std::string_view::npos)
? input
: input.substr(0, spacePos);
std::string argsStr;
if (spacePos != std::string_view::npos) {
size_t argStart = input.find_first_not_of(" \t", spacePos);
if (argStart != std::string_view::npos) {
argsStr = std::string(input.substr(argStart));
}
}
// Convert to lowercase for lookup
std::string cmdKey(cmdName);
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
CommandPtr command;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(cmdKey);
if (it == commands_.end()) {
return false;
}
command = it->second;
}
// Check permissions
if (!canExecuteCommand(clientId, command)) {
replyFunc("You don't have permission to use this command.");
return true; // Command was found but not allowed
}
CommandContext ctx{
.clientId = clientId,
.args = std::move(argsStr),
.invokerName = invokerName,
.musicManager = musicManager,
.replyCallback = std::move(replyFunc)
};
try {
command->execute(ctx);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Command execution error [{}]: {}", cmdKey, e.what()));
ctx.reply("An unexpected error occurred. Our team has been notified.");
}
return true;
}
bool CommandManager::hasCommand(std::string_view name) const {
std::lock_guard<std::mutex> lock(mutex_);
return commands_.contains(std::string(name));
}
std::optional<CommandPtr> CommandManager::getCommand(std::string_view name) const {
std::lock_guard<std::mutex> lock(mutex_);
auto it = commands_.find(std::string(name));
if (it != commands_.end()) {
return it->second;
}
return std::nullopt;
}
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getAllCommands() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::pair<std::string, CommandPtr>> result;
result.reserve(uniqueCommands_.size());
for (const auto& entry : uniqueCommands_) {
result.emplace_back(entry.primaryName, entry.instance);
}
return result;
}
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getVisibleCommands(uint64_t clientId) const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::pair<std::string, CommandPtr>> result;
for (const auto& entry : uniqueCommands_) {
// Only include if client can execute it
if (canExecuteCommand(clientId, entry.instance)) {
result.emplace_back(entry.primaryName, entry.instance);
}
}
return result;
}
bool CommandManager::canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const {
if (!cmd->requiresAdmin()) {
return true; // Non-admin commands are always allowed
}
// If no server config is set, deny admin commands
if (!serverConfig_.has_value()) {
return false;
}
// If no admin groups configured, deny everyone
if (serverConfig_->server.adminGroups.empty()) {
return false;
}
// Check permission via callback if set
if (permissionCheck_) {
return permissionCheck_(clientId, cmd->getCategory());
}
// Default: deny admin commands if no checker configured
return false;
}
void CommandManager::setPrefix(std::string_view prefix) {
prefix_ = prefix;
}
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func) {
std::lock_guard<std::mutex> lock(mutex_);
permissionCheck_ = std::move(func);
}
void CommandManager::setServerConfig(const Api::AppConfig& config) {
std::lock_guard<std::mutex> lock(mutex_);
serverConfig_ = config;
}
void CommandManager::registerBuiltinCommands() {
registerCommand<PlayCommand>("play");
registerCommand<SelectCommand>("select");
registerCommand<PauseCommand>("pause");
registerCommand<ResumeCommand>("resume");
registerCommand<StopCommand>("stop");
registerCommand<SkipCommand>("skip");
registerCommand<SeekCommand>("seek");
registerCommand<VolumeCommand>("volume");
registerCommand<QueueCommand>("queue");
registerCommand<RemoveCommand>("remove");
registerCommand<ClearCommand>("clear");
registerCommand<MoveCommand>("move");
registerCommand<ShuffleCommand>("shuffle");
registerCommand<RepeatCommand>("repeat");
registerCommand<PlaylistCommand>("playlist");
registerCommand<NowPlayingCommand>("np");
registerCommand<SearchCommand>("search");
registerCommand<ReloadCommand>("reload");
registerCommand<ReloadConfigCommand>("reloadconfig");
registerCommand<SubscribeCommand>("subscribe");
registerCommand<UnsubscribeCommand>("unsubscribe");
}
void CommandManager::registerHelpCommand() {
auto helpCmd = std::make_shared<HelpCommand>(*this);
std::lock_guard<std::mutex> lock(mutex_);
commands_["help"] = helpCmd;
uniqueCommands_.push_back({"help", helpCmd});
for (auto alias : helpCmd->getAliases()) {
commands_[std::string(alias)] = helpCmd;
}
}
} // namespace Echoion::Core
+355
View File
@@ -0,0 +1,355 @@
#include "echoion/core/ConfigLoader.hpp"
#include "echoion/api/AudioTypes.hpp"
#include <glaze/glaze.hpp>
#include <fstream>
#include <format>
namespace Echoion::Core {
// JSON structures for configuration
struct BotConfigJson {
std::string botName = "Echoion";
std::string commandPrefix = "!";
float defaultVolume = 0.5f;
bool autoReconnect = true;
uint32_t reconnectDelay = 5000;
uint32_t maxReconnectAttempts = 5;
std::optional<std::string> proxyHost;
std::optional<uint16_t> proxyPort;
std::optional<std::string> proxyUsername;
std::optional<std::string> proxyPassword;
std::optional<std::string> proxyType;
std::optional<std::string> youtubeApiKey;
std::string preferredQuality = "High";
bool allowPlaylistImports = true;
uint32_t maxQueueSize = 100;
uint32_t trackTimeout = 30000;
std::optional<std::string> youtubeCookiesPath;
std::optional<std::string> cookiesFromBrowser;
};
struct ServerConfigJson {
std::string address;
uint16_t port = 9987;
std::string serverPassword = "";
std::string nickname = "EchoionBot";
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
struct SecurityConfigJson {
bool requireAuthForAdmin = true;
uint32_t maxLoginAttempts = 5;
uint32_t lockoutDuration = 300000;
uint32_t sessionTimeout = 3600000;
bool enableAuditLog = true;
};
struct AppConfigJson {
BotConfigJson bot;
ServerConfigJson server;
SecurityConfigJson security;
};
} // namespace Echoion::Core
// Glaze metadata for JSON serialization
template<> struct glz::meta<Echoion::Core::BotConfigJson> {
using T = Echoion::Core::BotConfigJson;
static constexpr auto value = object(
"botName", &T::botName,
"commandPrefix", &T::commandPrefix,
"defaultVolume", &T::defaultVolume,
"autoReconnect", &T::autoReconnect,
"reconnectDelay", &T::reconnectDelay,
"maxReconnectAttempts", &T::maxReconnectAttempts,
"proxyHost", &T::proxyHost,
"proxyPort", &T::proxyPort,
"proxyUsername", &T::proxyUsername,
"proxyPassword", &T::proxyPassword,
"proxyType", &T::proxyType,
"youtubeApiKey", &T::youtubeApiKey,
"preferredQuality", &T::preferredQuality,
"allowPlaylistImports", &T::allowPlaylistImports,
"maxQueueSize", &T::maxQueueSize,
"trackTimeout", &T::trackTimeout,
"youtubeCookiesPath", &T::youtubeCookiesPath,
"cookiesFromBrowser", &T::cookiesFromBrowser
);
};
template<> struct glz::meta<Echoion::Core::ServerConfigJson> {
using T = Echoion::Core::ServerConfigJson;
static constexpr auto value = object(
"address", &T::address,
"port", &T::port,
"serverPassword", &T::serverPassword,
"nickname", &T::nickname,
"defaultChannelId", &T::defaultChannelId,
"channelPassword", &T::channelPassword,
"adminGroups", &T::adminGroups,
"djGroups", &T::djGroups,
"bannedGroups", &T::bannedGroups
);
};
template<> struct glz::meta<Echoion::Core::SecurityConfigJson> {
using T = Echoion::Core::SecurityConfigJson;
static constexpr auto value = object(
"requireAuthForAdmin", &T::requireAuthForAdmin,
"maxLoginAttempts", &T::maxLoginAttempts,
"lockoutDuration", &T::lockoutDuration,
"sessionTimeout", &T::sessionTimeout,
"enableAuditLog", &T::enableAuditLog
);
};
template<> struct glz::meta<Echoion::Core::AppConfigJson> {
using T = Echoion::Core::AppConfigJson;
static constexpr auto value = object(
"bot", &T::bot,
"server", &T::server,
"security", &T::security
);
};
namespace Echoion::Core {
Api::Result<Api::AppConfig> ConfigLoader::loadFromFile(const std::filesystem::path& path) {
if (!std::filesystem::exists(path)) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
std::format("Configuration file not found: {}", path.string())));
}
std::ifstream file(path);
if (!file.is_open()) {
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to open configuration file: {}", path.string())));
}
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
AppConfigJson jsonConfig;
auto ec = glz::read_json(jsonConfig, content);
if (ec) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Failed to parse configuration: {}", glz::format_error(ec, content))));
}
// Convert to API config
Api::AppConfig config;
// Bot config
config.bot.botName = jsonConfig.bot.botName;
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
config.bot.reconnectDelay = std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
config.bot.preferredQuality = parseQuality(jsonConfig.bot.preferredQuality);
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
config.bot.trackTimeout = std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
// Proxy config
if (jsonConfig.bot.proxyHost.has_value() && jsonConfig.bot.proxyPort.has_value()) {
Api::ProxyConfig proxy;
proxy.host = *jsonConfig.bot.proxyHost;
proxy.port = *jsonConfig.bot.proxyPort;
proxy.username = jsonConfig.bot.proxyUsername;
proxy.password = jsonConfig.bot.proxyPassword;
// Parse proxy type (default to HTTP)
if (jsonConfig.bot.proxyType.has_value()) {
const auto& typeStr = *jsonConfig.bot.proxyType;
if (typeStr == "SOCKS5" || typeStr == "socks5") {
proxy.type = Api::ProxyType::SOCKS5;
} else {
proxy.type = Api::ProxyType::HTTP;
}
} else {
proxy.type = Api::ProxyType::HTTP;
}
config.bot.proxy = proxy;
}
// YouTube API key
if (jsonConfig.bot.youtubeApiKey.has_value()) {
config.bot.youtubeApiKey = jsonConfig.bot.youtubeApiKey;
}
// YouTube cookies
if (jsonConfig.bot.youtubeCookiesPath.has_value()) {
config.bot.youtubeCookiesPath = jsonConfig.bot.youtubeCookiesPath;
}
if (jsonConfig.bot.cookiesFromBrowser.has_value()) {
config.bot.cookiesFromBrowser = jsonConfig.bot.cookiesFromBrowser;
}
// Server config
config.server.address = jsonConfig.server.address;
config.server.port = jsonConfig.server.port;
config.server.serverPassword = jsonConfig.server.serverPassword;
config.server.nickname = jsonConfig.server.nickname;
config.server.defaultChannelId = jsonConfig.server.defaultChannelId;
config.server.channelPassword = jsonConfig.server.channelPassword;
config.server.adminGroups = jsonConfig.server.adminGroups;
config.server.djGroups = jsonConfig.server.djGroups;
config.server.bannedGroups = jsonConfig.server.bannedGroups;
// Security config
config.security.requireAuthForAdmin = jsonConfig.security.requireAuthForAdmin;
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
config.security.lockoutDuration = std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
config.security.sessionTimeout = std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
ECHOION_LOG_INFO(std::format("Configuration loaded from {}", path.string()));
return config;
}
Api::Result<void> ConfigLoader::saveToFile(const std::filesystem::path& path, const Api::AppConfig& config) {
AppConfigJson jsonConfig;
// Bot config
jsonConfig.bot.botName = config.bot.botName;
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
jsonConfig.bot.reconnectDelay = static_cast<uint32_t>(config.bot.reconnectDelay.count());
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
jsonConfig.bot.preferredQuality = qualityToString(config.bot.preferredQuality);
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
jsonConfig.bot.trackTimeout = static_cast<uint32_t>(config.bot.trackTimeout.count());
// Proxy config
if (config.bot.proxy.has_value()) {
jsonConfig.bot.proxyHost = config.bot.proxy->host;
jsonConfig.bot.proxyPort = config.bot.proxy->port;
jsonConfig.bot.proxyUsername = config.bot.proxy->username;
jsonConfig.bot.proxyPassword = config.bot.proxy->password;
jsonConfig.bot.proxyType = config.bot.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5" : "HTTP";
}
// YouTube API key
if (config.bot.youtubeApiKey.has_value()) {
jsonConfig.bot.youtubeApiKey = *config.bot.youtubeApiKey;
}
// YouTube cookies
if (config.bot.youtubeCookiesPath.has_value()) {
jsonConfig.bot.youtubeCookiesPath = *config.bot.youtubeCookiesPath;
}
if (config.bot.cookiesFromBrowser.has_value()) {
jsonConfig.bot.cookiesFromBrowser = *config.bot.cookiesFromBrowser;
}
// Server config
jsonConfig.server.address = config.server.address;
jsonConfig.server.port = config.server.port;
jsonConfig.server.serverPassword = config.server.serverPassword;
jsonConfig.server.nickname = config.server.nickname;
jsonConfig.server.defaultChannelId = config.server.defaultChannelId;
jsonConfig.server.channelPassword = config.server.channelPassword;
jsonConfig.server.adminGroups = config.server.adminGroups;
jsonConfig.server.djGroups = config.server.djGroups;
jsonConfig.server.bannedGroups = config.server.bannedGroups;
// Security config
jsonConfig.security.requireAuthForAdmin = config.security.requireAuthForAdmin;
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
jsonConfig.security.lockoutDuration = static_cast<uint32_t>(config.security.lockoutDuration.count());
jsonConfig.security.sessionTimeout = static_cast<uint32_t>(config.security.sessionTimeout.count());
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
auto json = glz::write_json(jsonConfig);
if (!json.has_value())
{
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Failed to serialize: {}", json.error().custom_error_message)));
}
std::ofstream file(path);
if (!file.is_open()) {
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to write configuration file: {}", path.string())));
}
file << json.value();
file.close();
ECHOION_LOG_INFO(std::format("Configuration saved to {}", path.string()));
return {};
}
std::filesystem::path ConfigLoader::getDefaultConfigPath() {
// Try to get config path from environment or use default
const char* configHome = std::getenv("XDG_CONFIG_HOME");
if (configHome) {
return std::filesystem::path(configHome) / "echoion" / "config.json";
}
const char* home = std::getenv("HOME");
if (home) {
return std::filesystem::path(home) / ".config" / "echoion" / "config.json";
}
// Fallback to current directory
return "echoion_config.json";
}
Api::AppConfig ConfigLoader::createDefaultConfig() {
Api::AppConfig config;
// Default bot config
config.bot.botName = "Echoion";
config.bot.commandPrefix = "!";
config.bot.defaultVolume = 0.5f;
config.bot.autoReconnect = true;
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
config.bot.maxReconnectAttempts = 5;
config.bot.preferredQuality = Api::AudioQuality::High;
config.bot.allowPlaylistImports = true;
config.bot.maxQueueSize = 100;
config.bot.trackTimeout = std::chrono::milliseconds(30000);
// Default server config
config.server.address = "localhost";
config.server.port = 9987;
config.server.nickname = "EchoionBot";
// Default security config
config.security.requireAuthForAdmin = true;
config.security.maxLoginAttempts = 5;
config.security.lockoutDuration = std::chrono::milliseconds(300000);
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
config.security.enableAuditLog = true;
return config;
}
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str) {
if (str == "Low") return Api::AudioQuality::Low;
if (str == "Medium") return Api::AudioQuality::Medium;
if (str == "High") return Api::AudioQuality::High;
if (str == "VeryHigh") return Api::AudioQuality::VeryHigh;
if (str == "Lossless") return Api::AudioQuality::Lossless;
return Api::AudioQuality::High; // Default
}
std::string ConfigLoader::qualityToString(Api::AudioQuality quality) {
switch (quality) {
case Api::AudioQuality::Low: return "Low";
case Api::AudioQuality::Medium: return "Medium";
case Api::AudioQuality::High: return "High";
case Api::AudioQuality::VeryHigh: return "VeryHigh";
case Api::AudioQuality::Lossless: return "Lossless";
default: return "High";
}
}
} // namespace Echoion::Core
+902
View File
@@ -0,0 +1,902 @@
#include "echoion/core/Core.hpp"
#include "echoion/core/Logger.hpp"
#include <echoion/api/Database.hpp>
#include <format>
#include <algorithm>
namespace Echoion::Core {
Core::Core() = default;
Core::~Core() {
if (initialized_) {
shutdown();
}
}
Api::Result<void> Core::initialize(const std::filesystem::path& configPath) {
if (initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "Core already initialized"));
}
// Store config path for later reload
configPath_ = configPath;
// Load config from file (Core-internal, Plugin doesn't need to know about AppConfig structure)
auto configResult = ConfigLoader::loadFromFile(configPath);
if (!configResult) {
// Try to create default config
ECHOION_LOG_WARNING(std::format("Failed to load config: {}, creating default", configResult.error().message));
config_ = ConfigLoader::createDefaultConfig();
ConfigLoader::saveToFile(configPath, config_);
} else {
config_ = *configResult;
}
ECHOION_LOG_INFO(std::format("Core loaded config - Server: {}:{}, Nickname: {}",
config_.server.address, config_.server.port, config_.server.nickname));
// Initialize logger
auto logger = std::make_shared<Logger>();
logger->setMinLevel(Api::LogLevel::Debug);
Api::LoggerRegistry::instance().setLogger(logger);
ECHOION_LOG_INFO("Initializing Echoion Core...");
// Initialize network client
networkClient_ = std::make_shared<NetworkClient>();
auto netResult = networkClient_->initialize(config_.bot.proxy);
if (!netResult) {
return std::unexpected(netResult.error());
}
// Initialize database
database_ = std::make_shared<Api::Database>();
auto dbResult = database_->initialize();
if (!dbResult) {
ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}",
dbResult.error().message));
// Not fatal - continue without database
database_ = nullptr;
} else {
ECHOION_LOG_INFO("Database initialized successfully");
}
// Initialize music manager
musicManager_ = std::make_shared<MusicManager>();
auto musicResult = musicManager_->initialize(config_.bot, networkClient_, database_);
if (!musicResult) {
return std::unexpected(musicResult.error());
}
// Initialize command manager
commandManager_ = std::make_unique<CommandManager>();
commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config_);
// Set up permission check function
commandManager_->setPermissionCheckFunc([this](uint64_t clientId, CommandCategory category) -> bool {
// Check if client is in admin groups
if (!pluginInterface_) return false;
// Get client info from plugin
auto clientInfo = pluginInterface_->getClient(clientId);
if (!clientInfo || !clientInfo->has_value()) {
return false;
}
// Admin category requires admin group membership
if (category == CommandCategory::Admin) {
// Check if any admin groups are configured
if (config_.server.adminGroups.empty()) {
return false; // No admin groups configured = no admin access
}
// Check if client is in any admin group
// This would need to be implemented with proper group checking
// For now, we'll rely on the TS3 plugin to provide this info
// through a future interface
return false; // Default deny until proper group check is implemented
}
return true; // Non-admin categories are allowed
});
// Set up audio data callback
// Receives float audio from MusicManager (-1.0 to 1.0), converts to bytes for plugin
musicManager_->setAudioDataCallback([this](const std::span<const float> data) {
static int callCount = 0;
static auto lastLog = std::chrono::steady_clock::now();
if (pluginInterface_ && !data.empty()) {
// Convert float (-1.0 to 1.0) to int16 for TeamSpeak
// Use 32768.0f scaling but ensure we don't overflow
std::vector<int16_t> int16Data(data.size());
for (size_t i = 0; i < data.size(); ++i) {
float sample = data[i];
// Soft clipping to prevent hard distortion
if (sample > 0.95f) sample = 0.95f + (sample - 0.95f) * 0.5f;
if (sample < -0.95f) sample = -0.95f + (sample + 0.95f) * 0.5f;
int16Data[i] = static_cast<int16_t>(sample * 32767.0f);
}
// Send to plugin
auto result = pluginInterface_->sendAudioData(std::span<const uint8_t>(
reinterpret_cast<const uint8_t*>(int16Data.data()),
int16Data.size() * sizeof(int16_t)));
callCount++;
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - lastLog).count() >= 5) {
ECHOION_LOG_DEBUG(std::format("Audio callback: {} calls, {} samples, result: {}",
callCount, data.size(), result.has_value() ? "ok" : "error"));
lastLog = now;
}
}
});
// Set up subscription change callback to update whisper list
musicManager_->setSubscriptionChangeCallback([this]() {
updateWhisperList();
});
// Set initial whisper list from loaded subscriptions
updateWhisperList();
// Start RPC server for Desktop/API clients
rpcServer_ = std::make_shared<RpcServer>();
uint16_t rpcPort = config_.bot.rpcPort > 0 ? config_.bot.rpcPort : 8765;
auto rpcResult = rpcServer_->start(rpcPort);
if (!rpcResult) {
ECHOION_LOG_WARNING(std::format("Failed to start RPC server: {}",
rpcResult.error().message));
// Not fatal - continue without RPC
rpcServer_.reset();
} else {
ECHOION_LOG_INFO(std::format("RPC server started on port {}", rpcPort));
setupRpcHandlers();
}
startTime_ = std::chrono::system_clock::now();
initialized_ = true;
ECHOION_LOG_INFO("Echoion Core initialized successfully");
// Auto-connect to server if configured
if (!config_.server.address.empty() && pluginInterface_) {
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
config_.server.address, config_.server.port));
auto connectResult = pluginInterface_->connectToServer(config_.server);
if (!connectResult) {
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
ECHOION_LOG_INFO("Auto-connect initiated");
}
}
return {};
}
Api::Result<void> Core::shutdown() {
if (!initialized_) {
return {};
}
ECHOION_LOG_INFO("Shutting down Echoion Core...");
if (musicManager_) {
musicManager_->shutdown();
}
if (networkClient_) {
networkClient_->shutdown();
}
if (rpcServer_) {
rpcServer_->stop();
rpcServer_.reset();
}
if (database_) {
database_->shutdown();
database_.reset();
}
// Clear callbacks
{
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.clear();
}
initialized_ = false;
ECHOION_LOG_INFO("Echoion Core shutdown complete");
return {};
}
bool Core::isInitialized() const noexcept {
return initialized_.load();
}
Api::Result<void> Core::play(const Api::TrackInfo& track) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->queueTrack(track, 0);
if (!result) {
return std::unexpected(result.error());
}
// If not playing, start playback
auto state = musicManager_->getPlaybackState();
if (state && !state->isPlaying) {
auto playResult = musicManager_->skip(0); // Start first track
if (!playResult) {
return std::unexpected(playResult.error());
}
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlayRequested,
.clientId = 0,
.trackInfo = track,
.timestamp = std::chrono::system_clock::now()
});
return {};
}
Api::Result<void> Core::pause() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->pause();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlaybackPaused,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::resume() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->resume();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlaybackStarted,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::stop() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->stop();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::PlaybackStopped,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::skip(uint32_t count) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->skip(count);
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::SkipRequested,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::seek(std::chrono::milliseconds position) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->seek(position);
}
Api::Result<void> Core::setVolume(float volume) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->setVolume(volume);
}
Api::Result<uint64_t> Core::queueTrack(const Api::TrackInfo& track, uint64_t clientId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->queueTrack(track, clientId);
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::TrackQueued,
.clientId = clientId,
.trackInfo = track,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<void> Core::removeFromQueue(uint64_t queueId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
// Find position by queueId
auto queue = musicManager_->getQueue();
if (!queue) {
return std::unexpected(queue.error());
}
for (size_t i = 0; i < queue->size(); ++i) {
if ((*queue)[i].queueId == queueId) {
return musicManager_->removeFromQueue(static_cast<uint32_t>(i));
}
}
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
}
Api::Result<void> Core::clearQueue() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->clearQueue();
if (result) {
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::QueueCleared,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
}
return result;
}
Api::Result<std::vector<Api::QueueEntry>> Core::getQueue() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getQueue();
}
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
// Find current position
auto queue = musicManager_->getQueue();
if (!queue) {
return std::unexpected(queue.error());
}
uint32_t fromPosition = 0;
bool found = false;
for (size_t i = 0; i < queue->size(); ++i) {
if ((*queue)[i].queueId == queueId) {
fromPosition = static_cast<uint32_t>(i);
found = true;
break;
}
}
if (!found) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
}
return musicManager_->moveInQueue(fromPosition, newPosition);
}
Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getCurrentTrack();
}
Api::Result<Api::PlaybackState> Core::getPlaybackState() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getPlaybackState();
}
Api::Result<void> Core::loadPlaylist(const std::string& playlistId, uint64_t clientId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
auto result = musicManager_->loadPlaylist(playlistId, clientId);
if (!result) {
return std::unexpected(result.error());
}
return {};
}
Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
return musicManager_->getPlaylists();
}
Api::Result<void> Core::updateConfig(const Api::AppConfig& config) {
// Update local config copy
config_ = config;
if (commandManager_) {
commandManager_->setPrefix(config.bot.commandPrefix);
commandManager_->setServerConfig(config);
}
// Update network proxy if changed
if (networkClient_ && config.bot.proxy != networkClient_->getProxy()) {
networkClient_->setProxy(config.bot.proxy);
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::ConfigurationChanged,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
return {};
}
Api::Result<Api::AppConfig> Core::getConfig() const {
return config_;
}
Api::Result<void> Core::reloadConfig() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
if (configPath_.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Config path not set"));
}
// Reload config from disk
auto configResult = ConfigLoader::loadFromFile(configPath_);
if (!configResult) {
return std::unexpected(configResult.error());
}
// Update local config
config_ = *configResult;
// Update components with new config
if (commandManager_) {
commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config_);
}
ECHOION_LOG_INFO("Configuration reloaded from disk");
return {};
}
Api::Result<Api::HotReloadState> Core::prepareForHotReload() {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
ECHOION_LOG_INFO("Preparing for hot reload...");
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::HotReloadRequested,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
return musicManager_->getStateForHotReload();
}
Api::Result<void> Core::restoreAfterHotReload(const Api::HotReloadState& state) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
ECHOION_LOG_INFO("Restoring after hot reload...");
auto result = musicManager_->restoreFromHotReload(state);
if (!result) {
return result;
}
broadcastEvent(Api::PluginEvent{
.type = Api::PluginEventType::HotReloadCompleted,
.clientId = 0,
.timestamp = std::chrono::system_clock::now()
});
ECHOION_LOG_INFO("Hot reload restore complete");
return {};
}
void Core::registerEventCallback(const Api::EventCallback& callback) {
std::lock_guard<std::mutex> lock(eventMutex_);
eventCallbacks_.push_back(callback);
}
void Core::unregisterEventCallback(const Api::EventCallback& callback) {
std::lock_guard<std::mutex> lock(eventMutex_);
std::erase_if(eventCallbacks_, [&callback](const auto& cb) {
return cb.target_type() == callback.target_type();
});
}
Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
}
switch (event.type) {
case Api::PluginEventType::TextMessageReceived:
if (event.message) {
// Check if it's a command
if (event.message->starts_with(config_.bot.commandPrefix)) {
// Create reply callback
auto replyFunc = [this](uint64_t clientId, std::string_view message) {
if (pluginInterface_) {
pluginInterface_->sendTextMessage(clientId, std::string(message));
}
};
bool handled = commandManager_->dispatch(
event.clientId,
*event.message,
musicManager_,
[replyFunc, clientId = event.clientId](std::string_view msg) {
replyFunc(clientId, msg);
},
event.clientName.value_or("")
);
if (!handled) {
if (pluginInterface_) {
pluginInterface_->sendTextMessage(event.clientId,
std::format("Unknown command. Type {}help for available commands.", config_.bot.commandPrefix));
}
}
}
}
break;
case Api::PluginEventType::ClientConnected:
ECHOION_LOG_INFO(std::format("Client {} connected", event.clientId));
break;
case Api::PluginEventType::ClientDisconnected:
ECHOION_LOG_INFO(std::format("Client {} disconnected", event.clientId));
if (musicManager_) {
musicManager_->onClientDisconnected(event.clientId);
}
// Update whisper list after client disconnect
updateWhisperList();
break;
default:
// Forward other events to subscribers
broadcastEvent(event);
break;
}
return {};
}
std::string Core::getVersion() const {
return Api::VERSION_STRING;
}
std::chrono::system_clock::time_point Core::getUptime() const {
return startTime_;
}
void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface) {
pluginInterface_ = std::move(pluginInterface);
}
void Core::triggerAutoConnect() {
if (!initialized_) {
ECHOION_LOG_WARNING("Cannot auto-connect: Core not initialized");
return;
}
if (!pluginInterface_) {
ECHOION_LOG_WARNING("Cannot auto-connect: Plugin interface not set");
return;
}
if (config_.server.address.empty()) {
ECHOION_LOG_INFO("Auto-connect skipped: No server address configured");
return;
}
ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...",
config_.server.address, config_.server.port));
auto connectResult = pluginInterface_->connectToServer(config_.server);
if (!connectResult) {
ECHOION_LOG_ERROR(std::format("Auto-connect failed: {}",
connectResult.error().message));
} else {
ECHOION_LOG_INFO("Auto-connect initiated");
}
}
void Core::setAudioDataCallback(const MusicManager::AudioDataCallback& callback) {
if (musicManager_) {
musicManager_->setAudioDataCallback(callback);
}
}
void Core::broadcastEvent(const Api::PluginEvent& event) {
// Send to plugin event callbacks
{
std::lock_guard<std::mutex> lock(eventMutex_);
for (const auto& callback : eventCallbacks_) {
try {
callback(event);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event callback error: {}", e.what()));
}
}
}
// Broadcast to WebSocket/RPC clients
if (rpcServer_) {
std::string eventName;
switch (event.type) {
case Api::PluginEventType::PlaybackStarted:
eventName = "playback.started";
break;
case Api::PluginEventType::PlaybackPaused:
eventName = "playback.paused";
break;
case Api::PluginEventType::PlaybackResumed:
eventName = "playback.resumed";
break;
case Api::PluginEventType::PlaybackStopped:
eventName = "playback.stopped";
break;
case Api::PluginEventType::TrackFinished:
eventName = "playback.trackFinished";
break;
case Api::PluginEventType::TrackSkipped:
eventName = "playback.trackSkipped";
break;
case Api::PluginEventType::QueueUpdated:
eventName = "queue.updated";
break;
case Api::PluginEventType::VolumeChanged:
eventName = "playback.volumeChanged";
break;
case Api::PluginEventType::TrackQueued:
eventName = "queue.trackAdded";
break;
case Api::PluginEventType::TrackRemoved:
eventName = "queue.trackRemoved";
break;
case Api::PluginEventType::SeekPosition:
eventName = "playback.seeked";
break;
case Api::PluginEventType::HotReloadRequested:
eventName = "system.hotReloadRequested";
break;
case Api::PluginEventType::HotReloadCompleted:
eventName = "system.hotReloadCompleted";
break;
default:
eventName = "unknown";
break;
}
// Serialize event data to JSON with proper escaping
std::string eventData = "{}";
if (event.trackInfo) {
eventData = std::format("{{\"id\":\"{}\",\"title\":\"{}\",\"artist\":\"{}\",\"album\":\"{}\"}}",
event.trackInfo->id,
event.trackInfo->title,
event.trackInfo->artist,
event.trackInfo->album);
}
if (event.volume.has_value()) {
eventData = std::format("{{\"volume\":{:.2f}}}", *event.volume);
}
if (event.queuePosition.has_value()) {
eventData = std::format("{{\"position\":{}}}", *event.queuePosition);
}
if (event.clientId > 0) {
eventData = std::format("{{\"clientId\":{}}}", event.clientId);
}
rpcServer_->broadcastEvent(eventName, eventData);
}
}
bool Core::isAdmin(uint64_t clientId) const {
std::lock_guard<std::mutex> lock(adminMutex_);
return std::find(adminClients_.begin(), adminClients_.end(), clientId) != adminClients_.end();
}
void Core::updateWhisperList() {
if (!pluginInterface_ || !musicManager_) {
return;
}
auto subscribers = musicManager_->getSubscribedClients();
std::vector<uint64_t> subscriberVec(subscribers.begin(), subscribers.end());
ECHOION_LOG_DEBUG(std::format("Updating whisper list with {} subscribers", subscriberVec.size()));
auto result = pluginInterface_->setWhisperList(subscriberVec);
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to update whisper list: {}", result.error().message));
}
}
void Core::setupRpcHandlers() {
if (!rpcServer_) return;
// Helper to serialize track info
auto serializeTrack = [](const Api::TrackInfo& track) -> std::string {
std::string json = "{";
json += std::format("\"id\":\"{}\",", track.id);
json += std::format("\"title\":\"{}\",", track.title);
json += std::format("\"artist\":\"{}\",", track.artist);
json += std::format("\"album\":\"{}\",", track.album);
if (track.duration.has_value()) {
json += std::format("\"duration\":{},", track.duration->count());
}
json += std::format("\"source\":{}", static_cast<int>(track.source));
json += "}";
return json;
};
// Authentication
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Authenticate)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
rpcServer_->addAuthenticatedClient(clientId);
return std::string("{\"success\":true,\"token\":\"authenticated\"}");
});
// Playback control
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Play)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
// Parse query from params (simple implementation)
std::string query = params;
// Remove quotes if present
if (query.size() >= 2 && query.front() == '"' && query.back() == '"') {
query = query.substr(1, query.size() - 2);
}
auto result = musicManager_->play(query, clientId);
if (!result) return std::unexpected(result.error());
return std::format("{{\"success\":true,\"message\":\"{}\"}}", *result);
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Pause)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = pause();
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Resume)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = resume();
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Stop)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = stop();
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::Skip)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto result = skip(1);
if (!result) return std::unexpected(result.error());
return std::string("{\"success\":true}");
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::SetVolume)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
// Parse volume from params - expect {"volume":0.5}
float volume = 0.5f;
if (params.find("volume") != std::string::npos) {
size_t pos = params.find(':');
if (pos != std::string::npos) {
volume = std::stof(params.substr(pos + 1));
}
}
auto result = setVolume(volume);
if (!result) return std::unexpected(result.error());
return std::format("{{\"success\":true,\"volume\":{}}}", volume);
});
// Queue management
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::GetQueue)),
[this, serializeTrack](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto queue = getQueue();
if (!queue) return std::unexpected(queue.error());
std::string json = "{\"queue\":[";
for (size_t i = 0; i < queue->size(); ++i) {
if (i > 0) json += ",";
json += "{";
json += std::format("\"queueId\":{},", (*queue)[i].queueId);
json += std::format("\"track\":{},", serializeTrack((*queue)[i].track));
json += std::format("\"isPlaying\":{}", (*queue)[i].isPlaying ? "true" : "false");
json += "}";
}
json += "]}";
return json;
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)),
[this, serializeTrack](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto track = getCurrentTrack();
if (!track) return std::unexpected(track.error());
if (!track->has_value()) {
return std::string("{\"track\":null}");
}
return std::format("{{\"track\":{}}}", serializeTrack(track->value().track));
});
rpcServer_->registerHandler(std::to_string(static_cast<int>(Api::RpcMethod::GetStatus)),
[this](const std::string& params, uint64_t clientId) -> Api::Result<std::string> {
auto state = getPlaybackState();
if (!state) return std::unexpected(state.error());
std::string json = "{";
json += std::format("\"isPlaying\":{},", state->isPlaying ? "true" : "false");
json += std::format("\"isPaused\":{},", state->isPaused ? "true" : "false");
json += std::format("\"volume\":{},", state->volume);
json += std::format("\"repeat\":{},", state->repeat ? "true" : "false");
json += std::format("\"shuffle\":{}", state->shuffle ? "true" : "false");
json += "}";
return json;
});
ECHOION_LOG_INFO("RPC handlers registered");
}
} // namespace Echoion::Core
+714
View File
@@ -0,0 +1,714 @@
#include "echoion/api/Database.hpp"
#include "echoion/core/Logger.hpp"
#include <sqlite3.h>
#include <format>
#include <cstring>
namespace Echoion::Api {
// Internal implementation
class DatabaseImpl {
public:
sqlite3* db = nullptr;
DatabaseConfig config;
bool initialized = false;
int version = 0;
};
Database::Database() : impl_(std::make_unique<DatabaseImpl>()) {}
Database::~Database() {
shutdown();
}
Result<void> Database::initialize(const DatabaseConfig& config) {
impl_->config = config;
int rc = sqlite3_open(config.path.c_str(), &impl_->db);
if (rc != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
std::format("Failed to open database: {}", sqlite3_errmsg(impl_->db))));
}
// Enable WAL mode
if (config.walMode) {
char* errMsg = nullptr;
sqlite3_exec(impl_->db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, &errMsg);
if (errMsg) sqlite3_free(errMsg);
}
// Set busy timeout
sqlite3_busy_timeout(impl_->db,
static_cast<int>(config.busyTimeout.count()));
// Run migrations
auto result = migrate();
if (!result) {
return result;
}
impl_->initialized = true;
ECHOION_LOG_INFO(std::format("Database initialized: {}", config.path));
return {};
}
void Database::shutdown() {
if (impl_->db) {
sqlite3_close(impl_->db);
impl_->db = nullptr;
}
impl_->initialized = false;
}
bool Database::isInitialized() const {
return impl_->initialized;
}
Result<void> Database::migrate() {
// Create migrations table
const char* createMigrationsTable = R"(
CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
)";
char* errMsg = nullptr;
sqlite3_exec(impl_->db, createMigrationsTable, nullptr, nullptr, &errMsg);
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
}
// Get current version
sqlite3_stmt* stmt;
int currentVersion = 0;
if (sqlite3_prepare_v2(impl_->db,
"SELECT MAX(version) FROM schema_migrations", -1, &stmt, nullptr) == SQLITE_OK) {
if (sqlite3_step(stmt) == SQLITE_ROW) {
currentVersion = sqlite3_column_int(stmt, 0);
}
sqlite3_finalize(stmt);
}
// Migration 1: Initial schema
if (currentVersion < 1) {
const char* migration1 = R"(
CREATE TABLE IF NOT EXISTS playlists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT,
created_by INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_public INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS playlist_tracks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
playlist_id INTEGER NOT NULL,
track_url TEXT NOT NULL,
track_title TEXT NOT NULL,
track_artist TEXT,
track_thumbnail TEXT,
position INTEGER NOT NULL,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS playback_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
track_url TEXT NOT NULL,
track_title TEXT NOT NULL,
track_artist TEXT,
played_by INTEGER NOT NULL,
played_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
duration_ms INTEGER DEFAULT 0,
completed INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS user_favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
track_url TEXT NOT NULL,
track_title TEXT NOT NULL,
track_artist TEXT,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, track_url)
);
CREATE TABLE IF NOT EXISTS subscriptions (
client_id INTEGER PRIMARY KEY,
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_history_user ON playback_history(played_by);
CREATE INDEX IF NOT EXISTS idx_history_date ON playback_history(played_at);
CREATE INDEX IF NOT EXISTS idx_favorites_user ON user_favorites(user_id);
CREATE INDEX IF NOT EXISTS idx_playlist_tracks ON playlist_tracks(playlist_id);
CREATE TABLE IF NOT EXISTS subscriptions (
client_id INTEGER PRIMARY KEY,
subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_subscriptions_client ON subscriptions(client_id);
)";
sqlite3_exec(impl_->db, migration1, nullptr, nullptr, &errMsg);
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
}
// Record migration
sqlite3_exec(impl_->db,
"INSERT INTO schema_migrations (version) VALUES (1)",
nullptr, nullptr, nullptr);
ECHOION_LOG_INFO("Database migration 1 applied");
}
impl_->version = 1;
return {};
}
int Database::getCurrentVersion() const {
return impl_->version;
}
// Playlist operations
Result<uint64_t> Database::createPlaylist(const std::string& name,
const std::string& description, uint64_t createdBy, bool isPublic) {
const char* sql = R"(
INSERT INTO playlists (name, description, created_by, is_public)
VALUES (?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, description.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int64(stmt, 3, static_cast<sqlite3_int64>(createdBy));
sqlite3_bind_int(stmt, 4, isPublic ? 1 : 0);
if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt);
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
uint64_t id = static_cast<uint64_t>(sqlite3_last_insert_rowid(impl_->db));
sqlite3_finalize(stmt);
return id;
}
Result<std::optional<Playlist>> Database::getPlaylist(uint64_t id) {
const char* sql = R"(
SELECT id, name, description, created_by, created_at, updated_at, is_public
FROM playlists WHERE id = ?;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
Playlist playlist;
bool found = false;
if (sqlite3_step(stmt) == SQLITE_ROW) {
found = true;
playlist.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
playlist.name = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
playlist.description = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
playlist.createdBy = static_cast<uint64_t>(sqlite3_column_int64(stmt, 3));
playlist.isPublic = sqlite3_column_int(stmt, 6) != 0;
}
sqlite3_finalize(stmt);
if (!found) {
return std::optional<Playlist>{};
}
// Load tracks
const char* tracksSql = R"(
SELECT track_url, track_title, track_artist, track_thumbnail
FROM playlist_tracks
WHERE playlist_id = ?
ORDER BY position;
)";
if (sqlite3_prepare_v2(impl_->db, tracksSql, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
while (sqlite3_step(stmt) == SQLITE_ROW) {
TrackInfo track;
track.originalUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
track.title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
track.artist = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
if (sqlite3_column_text(stmt, 3)) {
track.thumbnailUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3));
}
playlist.tracks.push_back(track);
}
sqlite3_finalize(stmt);
}
return playlist;
}
Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId) {
std::vector<Playlist> playlists;
const char* sql = R"(
SELECT id, name, description, created_at, is_public
FROM playlists
WHERE created_by = ? OR is_public = 1
ORDER BY updated_at DESC;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
while (sqlite3_step(stmt) == SQLITE_ROW) {
Playlist playlist;
playlist.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
playlist.name = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
playlist.description = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
playlist.isPublic = sqlite3_column_int(stmt, 4) != 0;
playlists.push_back(playlist);
}
sqlite3_finalize(stmt);
return playlists;
}
Result<void> Database::deletePlaylist(uint64_t id) {
const char* sql = "DELETE FROM playlists WHERE id = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
const TrackInfo& track, uint32_t position) {
const char* sql = R"(
INSERT INTO playlist_tracks
(playlist_id, track_url, track_title, track_artist, track_thumbnail, position)
VALUES (?, ?, ?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(playlistId));
sqlite3_bind_text(stmt, 2, track.originalUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, track.title.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, track.artist.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 5,
track.thumbnailUrl ? track.thumbnailUrl->c_str() : "", -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 6, position);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
// Update playlist timestamp
sqlite3_exec(impl_->db,
std::format("UPDATE playlists SET updated_at = CURRENT_TIMESTAMP WHERE id = {}",
playlistId).c_str(), nullptr, nullptr, nullptr);
return {};
}
// Playback history
Result<void> Database::recordPlayback(const TrackInfo& track,
uint64_t playedBy, std::chrono::milliseconds duration, bool completed) {
const char* sql = R"(
INSERT INTO playback_history
(track_url, track_title, track_artist, played_by, duration_ms, completed)
VALUES (?, ?, ?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_text(stmt, 1, track.originalUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, track.title.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, track.artist.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_int64(stmt, 4, static_cast<sqlite3_int64>(playedBy));
sqlite3_bind_int64(stmt, 5, duration.count());
sqlite3_bind_int(stmt, 6, completed ? 1 : 0);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<std::vector<PlaybackHistoryEntry>> Database::getPlaybackHistory(
uint64_t userId, size_t limit, size_t offset) {
std::vector<PlaybackHistoryEntry> history;
const char* sql = R"(
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed
FROM playback_history
WHERE played_by = ?
ORDER BY played_at DESC
LIMIT ? OFFSET ?;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_int64(stmt, 2, static_cast<sqlite3_int64>(limit));
sqlite3_bind_int64(stmt, 3, static_cast<sqlite3_int64>(offset));
while (sqlite3_step(stmt) == SQLITE_ROW) {
PlaybackHistoryEntry entry;
entry.id = static_cast<uint64_t>(sqlite3_column_int64(stmt, 0));
entry.track.originalUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
entry.track.title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
entry.track.artist = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 3));
entry.playedBy = userId;
entry.duration = std::chrono::milliseconds(sqlite3_column_int64(stmt, 5));
entry.completed = sqlite3_column_int(stmt, 6) != 0;
history.push_back(entry);
}
sqlite3_finalize(stmt);
return history;
}
// Favorites
Result<void> Database::addFavorite(uint64_t userId, const TrackInfo& track) {
const char* sql = R"(
INSERT OR REPLACE INTO user_favorites
(user_id, track_url, track_title, track_artist)
VALUES (?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_text(stmt, 2, track.originalUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, track.title.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 4, track.artist.c_str(), -1, SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::removeFavorite(uint64_t userId, const std::string& trackUrl) {
const char* sql = "DELETE FROM user_favorites WHERE user_id = ? AND track_url = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_text(stmt, 2, trackUrl.c_str(), -1, SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<bool> Database::isFavorite(uint64_t userId, const std::string& trackUrl) {
const char* sql =
"SELECT 1 FROM user_favorites WHERE user_id = ? AND track_url = ? LIMIT 1;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_bind_text(stmt, 2, trackUrl.c_str(), -1, SQLITE_STATIC);
bool found = sqlite3_step(stmt) == SQLITE_ROW;
sqlite3_finalize(stmt);
return found;
}
Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId) {
std::vector<FavoriteTrack> favorites;
const char* sql = R"(
SELECT track_url, track_title, track_artist, added_at
FROM user_favorites
WHERE user_id = ?
ORDER BY added_at DESC;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
while (sqlite3_step(stmt) == SQLITE_ROW) {
FavoriteTrack fav;
fav.track.originalUrl = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
fav.track.title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1));
fav.track.artist = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2));
fav.userId = userId;
favorites.push_back(fav);
}
sqlite3_finalize(stmt);
return favorites;
}
// Maintenance
Result<void> Database::trimHistory(size_t keepCount) {
const char* sql = R"(
DELETE FROM playback_history
WHERE id NOT IN (
SELECT id FROM playback_history
ORDER BY played_at DESC
LIMIT ?
);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(keepCount));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
// Vacuum to reclaim space
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
return {};
}
Result<void> Database::clearUserData(uint64_t userId) {
const char* sql1 = "DELETE FROM user_favorites WHERE user_id = ?;";
const char* sql2 = "DELETE FROM playback_history WHERE played_by = ?;";
const char* sql3 = "DELETE FROM playlists WHERE created_by = ?;";
sqlite3_stmt* stmt;
for (const char* sql : {sql1, sql2, sql3}) {
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) == SQLITE_OK) {
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
}
}
return {};
}
Result<void> Database::vacuum() {
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
return {};
}
// Subscriptions
Result<void> Database::addSubscriber(uint64_t clientId) {
const char* sql = R"(
INSERT OR REPLACE INTO subscriptions (client_id)
VALUES (?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<void> Database::removeSubscriber(uint64_t clientId) {
const char* sql = "DELETE FROM subscriptions WHERE client_id = ?;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return {};
}
Result<bool> Database::isSubscriber(uint64_t clientId) {
const char* sql =
"SELECT 1 FROM subscriptions WHERE client_id = ? LIMIT 1;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
bool found = sqlite3_step(stmt) == SQLITE_ROW;
sqlite3_finalize(stmt);
return found;
}
Result<std::vector<uint64_t>> Database::getAllSubscribers() {
std::vector<uint64_t> subscribers;
const char* sql = "SELECT client_id FROM subscriptions;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
while (sqlite3_step(stmt) == SQLITE_ROW) {
subscribers.push_back(static_cast<uint64_t>(sqlite3_column_int64(stmt, 0)));
}
sqlite3_finalize(stmt);
return subscribers;
}
Result<size_t> Database::getSubscriberCount() {
const char* sql = "SELECT COUNT(*) FROM subscriptions;";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
return std::unexpected(Error(ErrorCode::DatabaseError,
sqlite3_errmsg(impl_->db)));
}
size_t count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
count = static_cast<size_t>(sqlite3_column_int64(stmt, 0));
}
sqlite3_finalize(stmt);
return count;
}
// Stub implementations for missing methods
Result<void> Database::updatePlaylist(uint64_t id,
const std::optional<std::string>& name,
const std::optional<std::string>& description,
const std::optional<bool>& isPublic) {
(void)id; (void)name; (void)description; (void)isPublic;
return {};
}
Result<void> Database::removeTrackFromPlaylist(uint64_t playlistId, uint64_t trackId) {
(void)playlistId; (void)trackId;
return {};
}
Result<void> Database::reorderPlaylistTrack(uint64_t playlistId,
uint64_t trackId, uint32_t newPosition) {
(void)playlistId; (void)trackId; (void)newPosition;
return {};
}
Result<std::vector<TrackInfo>> Database::getRecentlyPlayed(
uint64_t userId, size_t limit) {
(void)userId; (void)limit;
return std::vector<TrackInfo>{};
}
Result<PlaybackStatistics> Database::getStatistics(
uint64_t userId,
std::optional<std::chrono::system_clock::time_point> since) {
(void)userId; (void)since;
return PlaybackStatistics{};
}
Result<std::vector<std::pair<TrackInfo, uint64_t>>> Database::getMostPlayed(
uint64_t userId, size_t limit) {
(void)userId; (void)limit;
return std::vector<std::pair<TrackInfo, uint64_t>>{};
}
Result<void> Database::executeQuery(const std::string& sql, RowCallback callback) {
(void)sql; (void)callback;
return {};
}
// Database manager
Database& DatabaseManager::instance() {
static Database db;
return db;
}
Result<void> DatabaseManager::initialize(const DatabaseConfig& config) {
return instance().initialize(config);
}
void DatabaseManager::shutdown() {
instance().shutdown();
}
} // namespace Echoion::Api
+185
View File
@@ -0,0 +1,185 @@
#include "echoion/api/EventBus.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Api {
// Global event bus instance
EventBus& GlobalEventBus::instance() {
static EventBus instance;
return instance;
}
EventBus::EventBus() = default;
EventBus::~EventBus() {
stop();
}
void EventBus::start() {
if (running_.exchange(true)) {
return; // Already running
}
stopRequested_ = false;
eventThread_ = std::jthread([this] { processEvents(); });
ECHOION_LOG_INFO("EventBus started");
}
void EventBus::stop() {
if (!running_.exchange(false)) {
return; // Not running
}
stopRequested_ = true;
queueCv_.notify_all();
if (eventThread_.joinable()) {
eventThread_.join();
}
ECHOION_LOG_INFO("EventBus stopped");
}
void EventBus::unsubscribe(const SubscriptionToken& token) {
if (!token.isValid()) {
return;
}
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(token.getType());
if (it != handlers_.end()) {
it->second.erase(token.getId());
if (it->second.empty()) {
handlers_.erase(it);
}
}
}
void EventBus::processOne() {
std::shared_ptr<IEvent> evt;
{
std::lock_guard<std::mutex> lock(queueMutex_);
if (eventQueue_.empty()) {
return;
}
evt = std::move(eventQueue_.front());
eventQueue_.pop();
}
// Get handlers for this event type
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(evt->getType());
if (it != handlers_.end()) {
// Copy handlers to avoid holding lock during callback
auto handlers = it->second;
lock.unlock();
for (const auto& [id, handler] : handlers) {
try {
if (handler) {
(*handler)(evt);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
}
}
}
}
bool EventBus::waitAndProcessOne(std::chrono::milliseconds timeout) {
std::shared_ptr<IEvent> evt;
{
std::unique_lock<std::mutex> lock(queueMutex_);
if (!queueCv_.wait_for(lock, timeout, [this] {
return !eventQueue_.empty() || stopRequested_.load();
})) {
return false; // Timeout
}
if (stopRequested_ || eventQueue_.empty()) {
return false;
}
evt = std::move(eventQueue_.front());
eventQueue_.pop();
}
// Get handlers for this event type
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(evt->getType());
if (it != handlers_.end()) {
auto handlers = it->second;
lock.unlock();
for (const auto& [id, handler] : handlers) {
try {
if (handler) {
(*handler)(evt);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
}
}
}
return true;
}
void EventBus::clearQueue() {
std::lock_guard<std::mutex> lock(queueMutex_);
std::queue<std::shared_ptr<IEvent>> empty;
std::swap(eventQueue_, empty);
}
size_t EventBus::getPendingEventCount() const {
std::lock_guard<std::mutex> lock(queueMutex_);
return eventQueue_.size();
}
void EventBus::processEvents() {
while (!stopRequested_) {
std::shared_ptr<IEvent> evt;
{
std::unique_lock<std::mutex> lock(queueMutex_);
queueCv_.wait(lock, [this] {
return !eventQueue_.empty() || stopRequested_.load();
});
if (stopRequested_) {
break;
}
if (eventQueue_.empty()) {
continue;
}
evt = std::move(eventQueue_.front());
eventQueue_.pop();
}
// Get handlers for this event type
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
auto it = handlers_.find(evt->getType());
if (it != handlers_.end()) {
// Copy handlers to avoid holding lock during callback
auto handlers = it->second;
lock.unlock();
for (const auto& [id, handler] : handlers) {
try {
if (handler) {
(*handler)(evt);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
}
}
}
}
}
} // namespace Echoion::Api
+23
View File
@@ -0,0 +1,23 @@
#include "echoion/api/Export.hpp"
#include "echoion/core/Core.hpp"
#include <memory>
namespace Echoion::Api {
CoreInterfacePtr CreateCore() {
return std::make_shared<Core::Core>();
}
void DestroyCore(ICoreInterface* core) {
delete core;
}
const char* GetApiVersion() {
return VERSION_STRING;
}
bool IsApiCompatible(uint32_t major, uint32_t minor) {
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
}
} // namespace Echoion::Api
+295
View File
@@ -0,0 +1,295 @@
#include "echoion/core/Logger.hpp"
#include <iostream>
#include <format>
#include <algorithm>
namespace Echoion::Core {
Logger::Logger(std::string_view logDir, std::string_view baseName)
: logDir_(logDir)
, baseName_(baseName) {
// Ensure log directory exists
std::error_code ec;
std::filesystem::create_directories(logDir_, ec);
// Open log files for each level
openLogFiles();
// Start worker thread
workerThread_ = std::thread(&Logger::logWorker, this);
}
Logger::~Logger() {
running_ = false;
cv_.notify_all();
if (workerThread_.joinable()) {
workerThread_.join();
}
// Close all file streams
std::lock_guard<std::mutex> lock(fileMutex_);
for (auto& [level, info] : levelFiles_) {
if (info.stream.is_open()) {
info.stream.close();
}
}
if (combinedFile_.stream.is_open()) {
combinedFile_.stream.close();
}
}
void Logger::openLogFiles() {
std::lock_guard<std::mutex> lock(fileMutex_);
// Open file for each log level
for (auto level : {Api::LogLevel::Debug, Api::LogLevel::Info,
Api::LogLevel::Warning, Api::LogLevel::Error, Api::LogLevel::Critical}) {
auto path = generateLogFilePath(level);
LogFileInfo info;
info.path = path;
info.stream.open(path, std::ios::app);
info.createdAt = std::chrono::system_clock::now();
// Get current file size
if (std::filesystem::exists(path)) {
info.size = std::filesystem::file_size(path);
}
levelFiles_[level] = std::move(info);
}
// Open combined log file
auto combinedPath = logDir_ / std::format("{}_all.log", baseName_);
combinedFile_.path = combinedPath;
combinedFile_.stream.open(combinedPath, std::ios::app);
combinedFile_.createdAt = std::chrono::system_clock::now();
if (std::filesystem::exists(combinedPath)) {
combinedFile_.size = std::filesystem::file_size(combinedPath);
}
}
std::filesystem::path Logger::generateLogFilePath(Api::LogLevel level) {
std::string levelStr;
switch (level) {
case Api::LogLevel::Debug: levelStr = "debug"; break;
case Api::LogLevel::Info: levelStr = "info"; break;
case Api::LogLevel::Warning: levelStr = "warning"; break;
case Api::LogLevel::Error: levelStr = "error"; break;
case Api::LogLevel::Critical: levelStr = "critical"; break;
default: levelStr = "unknown"; break;
}
return logDir_ / std::format("{}_{}.log", baseName_, levelStr);
}
void Logger::log(Api::LogLevel level, std::string_view message, std::source_location location) {
if (level < minLevel_.load()) {
return;
}
Api::LogEntry entry;
entry.timestamp = std::chrono::system_clock::now();
entry.level = level;
entry.message = std::string(message);
entry.sourceFile = location.file_name();
entry.sourceLine = location.line();
entry.function = location.function_name();
entry.threadId = std::this_thread::get_id();
{
std::lock_guard<std::mutex> lock(queueMutex_);
logQueue_.push(std::move(entry));
}
cv_.notify_one();
}
void Logger::logWorker() {
while (running_.load()) {
std::unique_lock<std::mutex> lock(queueMutex_);
cv_.wait(lock, [this] { return !logQueue_.empty() || !running_.load(); });
while (!logQueue_.empty()) {
auto entry = std::move(logQueue_.front());
logQueue_.pop();
lock.unlock();
// Format the log entry
std::string formatted = formatLogEntry(entry);
// Console output
if (consoleOutput_.load()) {
if (entry.level >= Api::LogLevel::Error) {
std::cerr << formatted << std::endl;
} else {
std::cout << formatted << std::endl;
}
}
// File output
if (fileOutput_.load()) {
rotateIfNeeded(entry.level);
writeToFile(entry.level, formatted);
}
// Callbacks
{
std::lock_guard<std::mutex> cbLock(callbackMutex_);
for (const auto& callback : callbacks_) {
callback(entry);
}
}
lock.lock();
}
}
}
void Logger::writeToFile(Api::LogLevel level, const std::string& formattedEntry) {
std::lock_guard<std::mutex> lock(fileMutex_);
// Write to level-specific file
auto it = levelFiles_.find(level);
if (it != levelFiles_.end() && it->second.stream.is_open()) {
it->second.stream << formattedEntry << std::endl;
it->second.size += formattedEntry.size() + 1;
}
// Write to combined file
if (combinedFile_.stream.is_open()) {
combinedFile_.stream << formattedEntry << std::endl;
combinedFile_.size += formattedEntry.size() + 1;
}
}
void Logger::rotateIfNeeded(Api::LogLevel level) {
std::lock_guard<std::mutex> lock(fileMutex_);
auto maxSize = maxFileSize_.load();
// Check level-specific file
auto it = levelFiles_.find(level);
if (it != levelFiles_.end() && it->second.size >= maxSize) {
it->second.stream.close();
// Rotate: move current to .1, .1 to .2, etc.
auto basePath = it->second.path;
for (int i = maxFiles_.load() - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}" , basePath.string(), i);
auto newPath = std::format("{}.{}" , basePath.string(), i + 1);
if (std::filesystem::exists(oldPath)) {
std::filesystem::rename(oldPath, newPath);
}
}
if (std::filesystem::exists(basePath)) {
std::filesystem::rename(basePath, std::format("{}.1" , basePath.string()));
}
// Reopen
it->second.stream.open(basePath, std::ios::app);
it->second.size = 0;
it->second.createdAt = std::chrono::system_clock::now();
}
// Check combined file
if (combinedFile_.size >= maxSize) {
combinedFile_.stream.close();
auto basePath = combinedFile_.path;
for (int i = maxFiles_.load() - 1; i > 0; --i) {
auto oldPath = std::format("{}.{}" , basePath.string(), i);
auto newPath = std::format("{}.{}" , basePath.string(), i + 1);
if (std::filesystem::exists(oldPath)) {
std::filesystem::rename(oldPath, newPath);
}
}
if (std::filesystem::exists(basePath)) {
std::filesystem::rename(basePath, std::format("{}.1" , basePath.string()));
}
combinedFile_.stream.open(basePath, std::ios::app);
combinedFile_.size = 0;
combinedFile_.createdAt = std::chrono::system_clock::now();
}
}
std::string Logger::formatLogEntry(const Api::LogEntry& entry) {
return std::format("[{}] [{}] [{}] {} - {}",
formatTimestamp(entry.timestamp),
levelToString(entry.level),
entry.threadId,
entry.sourceFile.substr(entry.sourceFile.find_last_of("/\\") + 1),
entry.message);
}
std::string Logger::levelToString(Api::LogLevel level) {
switch (level) {
case Api::LogLevel::Debug: return "DEBUG";
case Api::LogLevel::Info: return "INFO";
case Api::LogLevel::Warning: return "WARN";
case Api::LogLevel::Error: return "ERROR";
case Api::LogLevel::Critical: return "CRITICAL";
default: return "UNKNOWN";
}
}
std::string Logger::formatTimestamp(const std::chrono::system_clock::time_point& tp) {
auto time_t = std::chrono::system_clock::to_time_t(tp);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch()) % 1000;
std::tm tm;
localtime_r(&time_t, &tm);
return std::format("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:03d}",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
}
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(fileMutex_);
for (auto& [level, info] : levelFiles_) {
if (info.stream.is_open()) {
info.stream.flush();
}
}
if (combinedFile_.stream.is_open()) {
combinedFile_.stream.flush();
}
}
void Logger::setConsoleOutput(bool enabled) {
consoleOutput_.store(enabled);
}
void Logger::setFileOutput(bool enabled) {
fileOutput_.store(enabled);
}
void Logger::setMaxFileSize(uint64_t bytes) {
maxFileSize_.store(bytes);
}
void Logger::setMaxFiles(uint32_t count) {
maxFiles_.store(count);
}
} // namespace Echoion::Core
+47
View File
@@ -0,0 +1,47 @@
#include "echoion/api/MemoryPool.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Api {
AudioBufferPool& AudioBufferPool::instance() {
static AudioBufferPool instance;
return instance;
}
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
bufferSize_ = bufferSize;
pool_ = std::make_unique<MemoryPool<float>>(bufferSize, poolSize);
ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} MB)",
poolSize, bufferSize, (bufferSize * poolSize * sizeof(float)) / (1024 * 1024)));
}
void AudioBufferPool::shutdown() {
pool_.reset();
ECHOION_LOG_INFO("AudioBufferPool shutdown");
}
PooledPtr<float> AudioBufferPool::acquireBuffer() {
if (!pool_) {
return PooledPtr<float>();
}
float* ptr = pool_->acquire();
if (!ptr) {
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
return PooledPtr<float>();
}
return PooledPtr<float>(ptr, pool_.get());
}
size_t AudioBufferPool::getAvailableBuffers() const {
if (!pool_) return 0;
return pool_->available();
}
size_t AudioBufferPool::getTotalBuffers() const {
if (!pool_) return 0;
return pool_->capacity();
}
} // namespace Echoion::Api
+1081
View File
File diff suppressed because it is too large. Load diff
+813
View File
@@ -0,0 +1,813 @@
#include "echoion/core/NetworkClient.hpp"
#include "boost/beast/core/buffers_to_string.hpp"
#include "echoion/core/Logger.hpp"
#include <boost/beast/http/field.hpp>
#include <format>
#include <algorithm>
#include <glaze/glaze.hpp>
// Boost.Beast for HTTP with proxy support
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/url.hpp>
namespace Echoion::Core {
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace http = boost::beast::http;
namespace ssl = boost::asio::ssl;
namespace urls = boost::urls;
// Simple base64 encoding for proxy authentication
namespace base64 {
static const std::string chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string encode(const std::string& input) {
std::string encoded;
encoded.reserve(((input.size() + 2) / 3) * 4);
int val = 0, valb = -6;
for (unsigned char c : input) {
val = (val << 8) + c;
valb += 8;
while (valb >= 0) {
encoded.push_back(chars[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6) {
encoded.push_back(chars[((val << 8) >> (valb + 8)) & 0x3F]);
}
while (encoded.size() % 4) {
encoded.push_back('=');
}
return encoded;
}
}
// Helper to perform URL encoding
std::string urlEncode(std::string_view value) {
std::string encoded;
encoded.reserve(value.size() * 3);
for (unsigned char c : value) {
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
} else {
encoded += std::format("%{:02X}", c);
}
}
return encoded;
}
// Helper to parse URL into components
struct UrlComponents {
std::string protocol;
std::string host;
std::string port;
std::string path;
std::string query;
bool isHttps;
};
std::optional<UrlComponents> parseUrl(std::string_view url) {
try {
auto result = urls::parse_uri(url);
if (!result) {
return std::nullopt;
}
const auto& uri = *result;
UrlComponents comp;
comp.protocol = std::string(uri.scheme());
comp.host = std::string(uri.host());
comp.isHttps = (comp.protocol == "https");
// Set default port
if (uri.port().empty()) {
comp.port = comp.isHttps ? "443" : "80";
} else {
comp.port = std::string(uri.port());
}
// Build path (use encoded path to preserve percent-encoding)
comp.path = std::string(uri.encoded_path());
if (comp.path.empty()) {
comp.path = "/";
}
// Add query if present (use encoded query to preserve percent-encoding)
if (!uri.query().empty()) {
comp.query = std::string(uri.encoded_query());
comp.path += "?" + comp.query;
}
return comp;
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("URL parse error: {}", e.what()));
return std::nullopt;
}
}
NetworkClient::NetworkClient() = default;
NetworkClient::~NetworkClient() {
shutdown();
}
Api::Result<void> NetworkClient::initialize(const std::optional<Api::ProxyConfig>& proxy) {
proxy_ = proxy;
initialized_ = true;
// Initialize thread pool
for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) {
threadPool_.emplace_back([this] {
while (!stopThreads_.load()) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task;
{
std::unique_lock<std::mutex> lock(taskMutex_);
taskCv_.wait(lock, [this] { return !taskQueue_.empty() || stopThreads_.load(); });
if (stopThreads_.load() && taskQueue_.empty()) {
return;
}
task = std::move(taskQueue_.front());
taskQueue_.pop();
}
task();
}
});
}
ECHOION_LOG_INFO(std::format("NetworkClient initialized (proxy: {})",
proxy.has_value() ? "enabled" : "disabled"));
return {};
}
void NetworkClient::shutdown() {
stopThreads_ = true;
taskCv_.notify_all();
for (auto& thread : threadPool_) {
if (thread.joinable()) {
thread.join();
}
}
threadPool_.clear();
initialized_ = false;
ECHOION_LOG_INFO("NetworkClient shutdown");
}
Api::Result<Api::HttpResponse> NetworkClient::get(std::string_view url,
const std::vector<Api::HttpHeader>& headers) {
Api::HttpRequest req;
req.url = std::string(url);
req.method = Api::HttpMethod::GET;
req.headers = addDefaultHeaders(headers);
req.proxy = proxy_;
return request(req);
}
Api::Result<Api::HttpResponse> NetworkClient::post(std::string_view url, std::string_view body,
const std::vector<Api::HttpHeader>& headers) {
Api::HttpRequest req;
req.url = std::string(url);
req.method = Api::HttpMethod::POST;
req.headers = addDefaultHeaders(headers);
req.body = std::vector<uint8_t>(body.begin(), body.end());
req.proxy = proxy_;
return request(req);
}
Api::Result<Api::HttpResponse> NetworkClient::request(const Api::HttpRequest& req) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"NetworkClient not initialized"));
}
return executeWithRetry(req);
}
std::future<Api::Result<Api::HttpResponse>> NetworkClient::getAsync(std::string_view url,
const std::vector<Api::HttpHeader>& headers) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, urlStr = std::string(url), headers] {
return get(urlStr, headers);
});
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::future<Api::Result<Api::HttpResponse>> NetworkClient::postAsync(std::string_view url,
std::string_view body, const std::vector<Api::HttpHeader>& headers) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, urlStr = std::string(url),
bodyStr = std::string(body), headers] {
return post(urlStr, bodyStr, headers);
});
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::future<Api::Result<Api::HttpResponse>> NetworkClient::requestAsync(const Api::HttpRequest& req) {
std::packaged_task<Api::Result<Api::HttpResponse>()> task([this, req] {
return request(req);
});
auto future = task.get_future();
{
std::lock_guard<std::mutex> lock(taskMutex_);
taskQueue_.push(std::move(task));
}
taskCv_.notify_one();
return future;
}
std::vector<Api::Result<Api::HttpResponse>> NetworkClient::requestBatch(
const std::vector<Api::HttpRequest>& requests) {
std::vector<std::future<Api::Result<Api::HttpResponse>>> futures;
futures.reserve(requests.size());
for (const auto& req : requests) {
futures.push_back(requestAsync(req));
}
std::vector<Api::Result<Api::HttpResponse>> results;
results.reserve(requests.size());
for (auto& future : futures) {
results.push_back(future.get());
}
return results;
}
void NetworkClient::setProxy(const std::optional<Api::ProxyConfig>& proxy) {
std::lock_guard<std::mutex> lock(mutex_);
proxy_ = proxy;
ECHOION_LOG_INFO(std::format("Proxy {}", proxy.has_value() ? "configured" : "cleared"));
}
std::optional<Api::ProxyConfig> NetworkClient::getProxy() const {
std::lock_guard<std::mutex> lock(mutex_);
return proxy_;
}
void NetworkClient::clearProxy() {
std::lock_guard<std::mutex> lock(mutex_);
proxy_.reset();
ECHOION_LOG_INFO("Proxy cleared");
}
void NetworkClient::setRetryConfig(const Api::RetryConfig& config) {
std::lock_guard<std::mutex> lock(mutex_);
retryConfig_ = config;
}
Api::RetryConfig NetworkClient::getRetryConfig() const {
std::lock_guard<std::mutex> lock(mutex_);
return retryConfig_;
}
Api::Result<Api::HttpResponse> NetworkClient::executeWithRetry(const Api::HttpRequest& req) {
auto delay = retryConfig_.initialDelay;
for (uint32_t attempt = 0; attempt <= retryConfig_.maxRetries; ++attempt) {
auto result = executeRequest(req);
if (result) {
// Check if we should retry based on status code
if (result->isError() && attempt < retryConfig_.maxRetries) {
auto it = std::find(retryConfig_.retryableStatusCodes.begin(),
retryConfig_.retryableStatusCodes.end(),
result->statusCode);
if (it != retryConfig_.retryableStatusCodes.end()) {
ECHOION_LOG_WARNING(std::format("Request failed with status {}, retrying (attempt {}/{})",
result->statusCode, attempt + 1, retryConfig_.maxRetries));
std::this_thread::sleep_for(delay);
delay = std::min(std::chrono::milliseconds(static_cast<uint32_t>(
delay.count() * retryConfig_.backoffMultiplier)), retryConfig_.maxDelay);
continue;
}
}
return result;
} else if (attempt < retryConfig_.maxRetries) {
ECHOION_LOG_WARNING(std::format("Request error: {}, retrying (attempt {}/{})",
result.error().message, attempt + 1, retryConfig_.maxRetries));
std::this_thread::sleep_for(delay);
delay = std::min(std::chrono::milliseconds(static_cast<uint32_t>(
delay.count() * retryConfig_.backoffMultiplier)), retryConfig_.maxDelay);
} else {
return result;
}
}
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Max retries exceeded"));
}
// Execute HTTP request using Boost.Beast with proxy support
Api::Result<Api::HttpResponse> NetworkClient::executeRequest(const Api::HttpRequest& req) {
try {
auto start = std::chrono::steady_clock::now();
// Parse target URL
auto urlComp = parseUrl(req.url);
if (!urlComp) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidUrl,
"Failed to parse URL"));
}
// Determine which proxy to use (request-specific or global)
std::optional<Api::ProxyConfig> activeProxy = req.proxy.has_value() ? req.proxy : proxy_;
bool useProxy = activeProxy.has_value() && activeProxy->isValid();
// Setup IO context
asio::io_context ioc;
ssl::context ctx(ssl::context::tlsv12_client);
ctx.set_default_verify_paths();
// Resolve timeout
auto timeout = std::chrono::seconds(req.timeout.count());
Api::HttpResponse response;
if (useProxy) {
// Route to appropriate proxy handler based on proxy type
const auto& proxy = *activeProxy;
if (proxy.isSocks5()) {
response = executeWithSocks5Proxy(ioc, ctx, *urlComp, req, proxy, timeout);
} else {
response = executeWithHttpProxy(ioc, ctx, *urlComp, req, proxy, timeout);
}
} else {
// Direct connection
response = executeDirect(ioc, ctx, *urlComp, req, timeout);
}
auto end = std::chrono::steady_clock::now();
response.responseTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
return response;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("HTTP request failed: {}", e.what())));
}
}
// Execute request through HTTP proxy using CONNECT tunneling
Api::HttpResponse NetworkClient::executeWithProxy(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout) {
// Dispatch to appropriate proxy handler
if (proxy.isSocks5()) {
return executeWithSocks5Proxy(ioc, ctx, urlComp, req, proxy, timeout);
} else {
return executeWithHttpProxy(ioc, ctx, urlComp, req, proxy, timeout);
}
}
// Execute request through HTTP proxy using CONNECT tunneling
Api::HttpResponse NetworkClient::executeWithHttpProxy(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout) {
// Create TCP socket for proxy connection
asio::ip::tcp::socket socket(ioc);
// Resolve proxy address
asio::ip::tcp::resolver resolver(ioc);
auto proxyResults = resolver.resolve(proxy.host, std::to_string(proxy.port));
// Connect to proxy
asio::connect(socket, proxyResults);
std::string target = urlComp.host + ":" + urlComp.port;
if (urlComp.isHttps) {
// For HTTPS: Send CONNECT request to establish tunnel
http::request<http::string_body> connect_req(http::verb::connect, target, 11);
connect_req.set(http::field::host, target);
// Add proxy authentication if needed
if (proxy.requiresAuth()) {
std::string auth = std::format("{}:{}", *proxy.username, *proxy.password);
std::string encoded = base64::encode(auth);
connect_req.set(http::field::proxy_authorization, "Basic " + encoded);
}
// Send CONNECT request
http::write(socket, connect_req);
// Read CONNECT response
beast::flat_buffer buffer;
http::response<http::empty_body> connect_res;
http::read(socket, buffer, connect_res);
if (connect_res.result() != http::status::ok) {
throw std::runtime_error(std::format("Proxy CONNECT failed: {}",
static_cast<int>(connect_res.result())));
}
// Upgrade socket to SSL
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
stream.set_verify_mode(ssl::verify_peer);
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
// Perform SSL handshake
stream.handshake(ssl::stream_base::client);
// Send actual HTTPS request through tunnel
return sendHttpsRequest(stream, urlComp, req);
} else {
// For HTTP: Proxy forwards the request
// Some proxies require absolute URL in the request line
return sendHttpRequestThroughProxy(socket, urlComp, req, proxy);
}
}
// Execute request through SOCKS5 proxy
Api::HttpResponse NetworkClient::executeWithSocks5Proxy(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout) {
// Create TCP socket for proxy connection
asio::ip::tcp::socket socket(ioc);
// Resolve proxy address
asio::ip::tcp::resolver resolver(ioc);
auto proxyResults = resolver.resolve(proxy.host, std::to_string(proxy.port));
// Connect to SOCKS5 proxy
asio::connect(socket, proxyResults);
// SOCKS5 handshake
// Step 1: Send greeting
std::vector<uint8_t> greeting;
greeting.push_back(0x05); // SOCKS version 5
if (proxy.requiresAuth()) {
greeting.push_back(0x02); // 2 auth methods
greeting.push_back(0x00); // No auth
greeting.push_back(0x02); // Username/password auth
} else {
greeting.push_back(0x01); // 1 auth method
greeting.push_back(0x00); // No auth
}
asio::write(socket, asio::buffer(greeting));
// Step 2: Receive server response
std::vector<uint8_t> response(2);
asio::read(socket, asio::buffer(response));
if (response[0] != 0x05) {
throw std::runtime_error("SOCKS5 proxy: Invalid version");
}
// Step 3: Handle authentication if required
if (response[1] == 0x02) {
// Username/password authentication
if (!proxy.requiresAuth()) {
throw std::runtime_error("SOCKS5 proxy: Auth required but no credentials provided");
}
// Build auth request
std::vector<uint8_t> authRequest;
authRequest.push_back(0x01); // Auth version
authRequest.push_back(static_cast<uint8_t>(proxy.username->size()));
authRequest.insert(authRequest.end(), proxy.username->begin(), proxy.username->end());
authRequest.push_back(static_cast<uint8_t>(proxy.password->size()));
authRequest.insert(authRequest.end(), proxy.password->begin(), proxy.password->end());
asio::write(socket, asio::buffer(authRequest));
// Read auth response
std::vector<uint8_t> authResponse(2);
asio::read(socket, asio::buffer(authResponse));
if (authResponse[0] != 0x01 || authResponse[1] != 0x00) {
throw std::runtime_error("SOCKS5 proxy: Authentication failed");
}
} else if (response[1] != 0x00) {
throw std::runtime_error(std::format("SOCKS5 proxy: Auth method {} not accepted",
static_cast<int>(response[1])));
}
// Step 4: Send connection request
std::vector<uint8_t> connectRequest;
connectRequest.push_back(0x05); // SOCKS version 5
connectRequest.push_back(0x01); // CONNECT command
connectRequest.push_back(0x00); // Reserved
// Check if target is IP address or domain name
asio::ip::address ipAddr;
bool isIp = false;
try {
ipAddr = asio::ip::make_address(urlComp.host);
isIp = true;
} catch (...) {
isIp = false;
}
uint16_t targetPort = static_cast<uint16_t>(std::stoi(urlComp.port));
if (isIp) {
if (ipAddr.is_v4()) {
connectRequest.push_back(0x01); // IPv4
auto bytes = ipAddr.to_v4().to_bytes();
connectRequest.insert(connectRequest.end(), bytes.begin(), bytes.end());
} else {
connectRequest.push_back(0x04); // IPv6
auto bytes = ipAddr.to_v6().to_bytes();
connectRequest.insert(connectRequest.end(), bytes.begin(), bytes.end());
}
} else {
connectRequest.push_back(0x03); // Domain name
connectRequest.push_back(static_cast<uint8_t>(urlComp.host.size()));
connectRequest.insert(connectRequest.end(), urlComp.host.begin(), urlComp.host.end());
}
// Port in network byte order
connectRequest.push_back(static_cast<uint8_t>((targetPort >> 8) & 0xFF));
connectRequest.push_back(static_cast<uint8_t>(targetPort & 0xFF));
asio::write(socket, asio::buffer(connectRequest));
// Step 5: Receive connection response
std::vector<uint8_t> connectResponse(4);
asio::read(socket, asio::buffer(connectResponse));
if (connectResponse[0] != 0x05) {
throw std::runtime_error("SOCKS5 proxy: Invalid version in connect response");
}
if (connectResponse[1] != 0x00) {
std::string errorMsg;
switch (connectResponse[1]) {
case 0x01: errorMsg = "General SOCKS server failure"; break;
case 0x02: errorMsg = "Connection not allowed by ruleset"; break;
case 0x03: errorMsg = "Network unreachable"; break;
case 0x04: errorMsg = "Host unreachable"; break;
case 0x05: errorMsg = "Connection refused"; break;
case 0x06: errorMsg = "TTL expired"; break;
case 0x07: errorMsg = "Command not supported"; break;
case 0x08: errorMsg = "Address type not supported"; break;
default: errorMsg = std::format("Unknown error code {}", static_cast<int>(connectResponse[1]));
}
throw std::runtime_error(std::format("SOCKS5 proxy connection failed: {}", errorMsg));
}
// Read the bind address from response (variable length)
uint8_t addrType = connectResponse[3];
std::vector<uint8_t> bindAddr;
if (addrType == 0x01) {
// IPv4: 4 bytes + 2 bytes port
bindAddr.resize(6);
asio::read(socket, asio::buffer(bindAddr));
} else if (addrType == 0x03) {
// Domain name: 1 byte length + domain + 2 bytes port
std::vector<uint8_t> domainLen(1);
asio::read(socket, asio::buffer(domainLen));
bindAddr.resize(domainLen[0] + 2);
asio::read(socket, asio::buffer(bindAddr));
} else if (addrType == 0x04) {
// IPv6: 16 bytes + 2 bytes port
bindAddr.resize(18);
asio::read(socket, asio::buffer(bindAddr));
}
// SOCKS5 tunnel established, now send HTTP request
if (urlComp.isHttps) {
// Upgrade socket to SSL for HTTPS
ssl::stream<asio::ip::tcp::socket> stream(std::move(socket), ctx);
stream.set_verify_mode(ssl::verify_peer);
stream.set_verify_callback(ssl::host_name_verification(urlComp.host));
// Perform SSL handshake
stream.handshake(ssl::stream_base::client);
// Send HTTPS request through tunnel
return sendHttpsRequest(stream, urlComp, req);
} else {
// Send HTTP request through tunnel
return sendHttpRequest(socket, urlComp, req);
}
}
// Execute direct request without proxy
Api::HttpResponse NetworkClient::executeDirect(
asio::io_context& ioc,
ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
std::chrono::seconds timeout) {
if (urlComp.isHttps) {
// HTTPS direct connection
ssl::stream<asio::ip::tcp::socket> stream(ioc, ctx);
// Set SNI hostname
if (!SSL_set_tlsext_host_name(stream.native_handle(), urlComp.host.c_str())) {
throw std::runtime_error("Failed to set SNI hostname");
}
// Resolve and connect
asio::ip::tcp::resolver resolver(ioc);
auto results = resolver.resolve(urlComp.host, urlComp.port);
asio::connect(stream.next_layer(), results);
// SSL handshake
stream.handshake(ssl::stream_base::client);
return sendHttpsRequest(stream, urlComp, req);
} else {
// HTTP direct connection
asio::ip::tcp::socket socket(ioc);
asio::ip::tcp::resolver resolver(ioc);
auto results = resolver.resolve(urlComp.host, urlComp.port);
asio::connect(socket, results);
return sendHttpRequest(socket, urlComp, req);
}
}
// Send HTTP request through socket
Api::HttpResponse NetworkClient::sendHttpRequest(
asio::ip::tcp::socket& socket,
const UrlComponents& urlComp,
const Api::HttpRequest& req) {
http::request<http::string_body> request = buildBeastRequest(urlComp, req);
http::write(socket, request);
beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(socket, buffer, response);
return convertBeastResponse(response);
}
// Send HTTP request through proxy (for non-HTTPS)
Api::HttpResponse NetworkClient::sendHttpRequestThroughProxy(
asio::ip::tcp::socket& socket,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy) {
// Build request with absolute URL
std::string absoluteUrl = std::format("{}://{}{}",
urlComp.protocol, urlComp.host, urlComp.path);
http::verb method = http::verb::get;
switch (req.method) {
case Api::HttpMethod::GET: method = http::verb::get; break;
case Api::HttpMethod::POST: method = http::verb::post; break;
case Api::HttpMethod::PUT: method = http::verb::put; break;
case Api::HttpMethod::DELETE: method = http::verb::delete_; break;
case Api::HttpMethod::PATCH: method = http::verb::patch; break;
case Api::HttpMethod::HEAD: method = http::verb::head; break;
case Api::HttpMethod::OPTIONS: method = http::verb::options; break;
}
http::request<http::string_body> request(method, absoluteUrl, 11);
request.set(http::field::host, urlComp.host);
request.set(http::field::user_agent, "EchoionBot/1.0");
// Add headers
for (const auto& header : req.headers) {
request.set(header.name, header.value);
}
// Add proxy auth
if (proxy.requiresAuth()) {
std::string auth = std::format("{}:{}", *proxy.username, *proxy.password);
std::string encoded = base64::encode(auth);
request.set(http::field::proxy_authorization, "Basic " + encoded);
}
// Add body
if (req.body.has_value()) {
request.body() = std::string(req.body->begin(), req.body->end());
request.prepare_payload();
}
http::write(socket, request);
beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(socket, buffer, response);
return convertBeastResponse(response);
}
// Build Beast HTTP request
http::request<http::string_body> NetworkClient::buildBeastRequest(
const UrlComponents& urlComp,
const Api::HttpRequest& req) {
http::verb method = http::verb::get;
switch (req.method) {
case Api::HttpMethod::GET: method = http::verb::get; break;
case Api::HttpMethod::POST: method = http::verb::post; break;
case Api::HttpMethod::PUT: method = http::verb::put; break;
case Api::HttpMethod::DELETE: method = http::verb::delete_; break;
case Api::HttpMethod::PATCH: method = http::verb::patch; break;
case Api::HttpMethod::HEAD: method = http::verb::head; break;
case Api::HttpMethod::OPTIONS: method = http::verb::options; break;
}
http::request<http::string_body> request(method, urlComp.path, 11);
request.set(http::field::host, urlComp.host);
request.set(http::field::user_agent, "EchoionBot/1.0");
// Add custom headers
for (const auto& header : req.headers) {
request.set(header.name, header.value);
}
// Add body if present
if (req.body.has_value()) {
request.body() = std::string(req.body->begin(), req.body->end());
request.prepare_payload();
}
return request;
}
// Convert Beast response to Api::HttpResponse
Api::HttpResponse NetworkClient::convertBeastResponse(
const http::response<http::dynamic_body>& beastResponse) {
Api::HttpResponse response;
response.statusCode = static_cast<uint16_t>(beastResponse.result_int());
// Extract body
response.body = boost::beast::buffers_to_string(beastResponse.body().data());
// Extract headers (use push_back to preserve multiple headers with same name)
for (const auto& field : beastResponse.base()) {
response.headers.push_back({
std::string(field.name_string()),
std::string(field.value())
});
}
return response;
}
std::vector<Api::HttpHeader> NetworkClient::addDefaultHeaders(const std::vector<Api::HttpHeader>& headers) {
std::vector<Api::HttpHeader> result = headers;
// Check if User-Agent is already present
bool hasUserAgent = std::any_of(headers.begin(), headers.end(),
[](const auto& h) { return h.name == "User-Agent"; });
if (!hasUserAgent) {
result.push_back({"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"});
}
// Check if Accept is already present
bool hasAccept = std::any_of(headers.begin(), headers.end(),
[](const auto& h) { return h.name == "Accept"; });
if (!hasAccept) {
result.push_back({"Accept", "application/json, */*"});
}
return result;
}
} // namespace Echoion::Core
+400
View File
@@ -0,0 +1,400 @@
#include "echoion/core/RpcServer.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <algorithm>
namespace Echoion::Core {
RpcServer::RpcServer() = default;
RpcServer::~RpcServer() {
stop();
}
Api::Result<void> RpcServer::start(uint16_t port) {
if (running_.exchange(true)) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running"));
}
port_ = port;
try {
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
acceptor_.emplace(ioContext_);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen();
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
ECHOION_LOG_INFO(std::format("RPC server started on port {}", port));
return {};
} catch (const std::exception& e) {
running_ = false;
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to start RPC server: {}", e.what())));
}
}
void RpcServer::stop() {
if (!running_.exchange(false)) {
return;
}
try {
// Cancel any pending async operations
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->cancel(ec);
}
ioContext_.stop();
// Close all client connections
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (auto& [id, ws] : clients_) {
if (ws->is_open()) {
beast::error_code ec;
ws->close(websocket::close_code::normal, ec);
}
}
clients_.clear();
}
// Wait for all client threads to finish (with timeout)
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
for (auto& thread : clientThreads_) {
if (thread.joinable()) {
thread.detach(); // Don't wait, just detach
}
}
clientThreads_.clear();
}
// Wait for server thread with timeout
if (serverThread_.joinable()) {
// Give it a moment to clean up
auto start = std::chrono::steady_clock::now();
while (serverThread_.joinable() &&
std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
if (serverThread_.joinable()) {
serverThread_.detach(); // Force detach if still running
}
}
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->close(ec);
}
ECHOION_LOG_INFO("RPC server stopped");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what()));
}
}
void RpcServer::acceptLoop() {
ECHOION_LOG_INFO("RPC server accept loop started");
while (running_.load()) {
try {
asio::ip::tcp::socket socket(ioContext_);
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
// Use async accept with cancellation support
std::atomic<bool> acceptComplete{false};
boost::system::error_code acceptEc;
acceptor_->async_accept(socket, [&](const boost::system::error_code& ec) {
acceptEc = ec;
acceptComplete = true;
});
// Poll until accept completes or we're stopped
while (!acceptComplete.load() && running_.load()) {
ioContext_.poll_one();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Cancel pending operation if we're stopping
if (!running_.load()) {
acceptor_->cancel();
break;
}
if (acceptEc) {
throw std::runtime_error(acceptEc.message());
}
ECHOION_LOG_DEBUG(std::format("RPC server accepted TCP connection from {}:{}",
socket.remote_endpoint().address().to_string(),
socket.remote_endpoint().port()));
if (!running_.load()) break;
auto ws = std::make_shared<websocket::stream<asio::ip::tcp::socket>>(std::move(socket));
ws->accept();
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
uint64_t clientId = nextClientId_++;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_[clientId] = ws;
}
ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId));
// Handle client in separate thread
std::thread clientThread([this, clientId, ws]() {
handleClient(ws);
// Cleanup
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_.erase(clientId);
}
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
ECHOION_LOG_DEBUG(std::format("RPC client {} disconnected", clientId));
});
// Track the thread for proper cleanup
{
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
// Clean up any finished threads first
clientThreads_.erase(
std::remove_if(clientThreads_.begin(), clientThreads_.end(),
[](std::thread& t) {
if (!t.joinable()) return true;
return false;
}),
clientThreads_.end()
);
clientThreads_.push_back(std::move(clientThread));
}
} catch (const std::exception& e) {
// If we're shutting down, exit gracefully
if (!running_.load()) {
break;
}
ECHOION_LOG_ERROR(std::format("RPC accept error: {}", e.what()));
}
}
ECHOION_LOG_INFO("RPC server accept loop stopped");
}
void RpcServer::handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws) {
beast::flat_buffer buffer;
while (running_.load() && ws->is_open()) {
try {
beast::error_code ec;
ws->read(buffer, ec);
if (ec == websocket::error::closed) {
break;
}
if (ec) {
ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message()));
break;
}
std::string message = beast::buffers_to_string(buffer.data());
buffer.consume(buffer.size());
// Find client ID
uint64_t clientId = 0;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [id, clientWs] : clients_) {
if (clientWs.get() == ws.get()) {
clientId = id;
break;
}
}
}
if (clientId != 0) {
processMessage(clientId, message);
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what()));
break;
}
}
}
void RpcServer::processMessage(uint64_t clientId, const std::string& message) {
try {
Api::RpcRequest request;
auto ec = glz::read_json(request, message);
if (ec) {
Api::RpcResponse response;
response.requestId = 0;
response.success = false;
response.error = "{\"code\":5,\"message\":\"Invalid JSON\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
// Check authentication (except for Authenticate method)
if (request.method != Api::RpcMethod::Authenticate) {
if (!isClientAuthenticated(clientId)) {
Api::RpcResponse response;
response.requestId = request.id;
response.success = false;
response.error = "{\"code\":10,\"message\":\"Not authenticated\",\"source\":\"RpcServer\"}";
response.success = false;
sendResponse(clientId, response);
return;
}
}
// Find handler
std::string methodName = std::to_string(static_cast<int>(request.method));
CommandHandler handler;
{
std::lock_guard<std::mutex> lock(handlersMutex_);
auto it = handlers_.find(methodName);
if (it != handlers_.end()) {
handler = it->second;
}
}
Api::RpcResponse response;
response.requestId = request.id;
response.timestamp = std::chrono::system_clock::now();
if (handler) {
auto result = handler(request.params.value_or(""), clientId);
if (result) {
response.success = true;
response.result = *result;
} else {
response.success = false;
response.error = std::format("{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
static_cast<uint32_t>(result.error().code),
result.error().message,
result.error().source);
}
} else {
response.success = false;
response.error = "{\"code\":2,\"message\":\"Unknown method\",\"source\":\"RpcServer\"}";
}
sendResponse(clientId, response);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what()));
}
}
void RpcServer::sendResponse(uint64_t clientId, const Api::RpcResponse& response) {
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
try {
auto json = glz::write_json(response);
if (json) {
it->second->write(asio::buffer(*json));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
}
}
void RpcServer::sendNotification(uint64_t clientId, const Api::RpcNotification& notification) {
std::lock_guard<std::mutex> lock(clientsMutex_);
auto it = clients_.find(clientId);
if (it == clients_.end() || !it->second->is_open()) {
return;
}
try {
auto json = glz::write_json(notification);
if (json) {
it->second->write(asio::buffer(*json));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Send notification error: {}", e.what()));
}
}
void RpcServer::broadcastEvent(const std::string& event, const std::string& data) {
Api::RpcNotification notification;
notification.event = event;
notification.data = data;
notification.timestamp = std::chrono::system_clock::now();
std::lock_guard<std::mutex> lock(clientsMutex_);
for (const auto& [clientId, ws] : clients_) {
if (ws->is_open() && isClientAuthenticated(clientId)) {
try {
auto json = glz::write_json(notification);
if (json) {
ws->write(asio::buffer(*json));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Broadcast error: {}", e.what()));
}
}
}
}
void RpcServer::sendEvent(uint64_t clientId, const std::string& event, const std::string& data) {
Api::RpcNotification notification;
notification.event = event;
notification.data = data;
notification.timestamp = std::chrono::system_clock::now();
sendNotification(clientId, notification);
}
void RpcServer::registerHandler(const std::string& method, CommandHandler handler) {
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_[method] = std::move(handler);
}
void RpcServer::unregisterHandler(const std::string& method) {
std::lock_guard<std::mutex> lock(handlersMutex_);
handlers_.erase(method);
}
void RpcServer::setAuthToken(const std::string& token) {
std::lock_guard<std::mutex> lock(authMutex_);
authToken_ = token;
}
bool RpcServer::authenticate(const std::string& token) {
std::lock_guard<std::mutex> lock(authMutex_);
return authToken_.empty() || token == authToken_;
}
void RpcServer::addAuthenticatedClient(uint64_t clientId) {
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.insert(clientId);
}
void RpcServer::removeAuthenticatedClient(uint64_t clientId) {
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
bool RpcServer::isClientAuthenticated(uint64_t clientId) {
std::lock_guard<std::mutex> lock(authMutex_);
return authenticatedClients_.contains(clientId);
}
} // namespace Echoion::Core
+721
View File
@@ -0,0 +1,721 @@
#include "echoion/core/SignatureCipher.hpp"
#include "echoion/core/Logger.hpp"
#include <regex>
#include <format>
#include <algorithm>
#include <cctype>
#include <glaze/glaze.hpp>
#include <fstream>
#include <filesystem>
// Minimal embedded fallback - a stub that logs errors
// The real solver is downloaded from GitHub releases
namespace {
constexpr std::string_view FALLBACK_CORE_JS = R"(
var globalThis = globalThis || this;
var jsc = function(input) {
return JSON.stringify({
error: "Solver libraries not available. Please check internet connection.",
responses: []
});
};
)";
}
namespace Echoion::Core {
SignatureCipher::SignatureCipher() = default;
SignatureCipher::~SignatureCipher() {
clear();
}
SignatureCipher::SignatureCipher(SignatureCipher&& other) noexcept
: runtime_(other.runtime_)
, context_(other.context_)
, playerJsCode_(std::move(other.playerJsCode_))
, preprocessedPlayer_(std::move(other.preprocessedPlayer_))
, initialized_(other.initialized_)
, solverInitialized_(other.solverInitialized_)
, hasPlayerJs_(other.hasPlayerJs_) {
other.runtime_ = nullptr;
other.context_ = nullptr;
other.initialized_ = false;
other.solverInitialized_ = false;
other.hasPlayerJs_ = false;
}
SignatureCipher& SignatureCipher::operator=(SignatureCipher&& other) noexcept {
if (this != &other) {
clear();
runtime_ = other.runtime_;
context_ = other.context_;
playerJsCode_ = std::move(other.playerJsCode_);
preprocessedPlayer_ = std::move(other.preprocessedPlayer_);
initialized_ = other.initialized_;
solverInitialized_ = other.solverInitialized_;
hasPlayerJs_ = other.hasPlayerJs_;
other.runtime_ = nullptr;
other.context_ = nullptr;
other.initialized_ = false;
other.solverInitialized_ = false;
other.hasPlayerJs_ = false;
}
return *this;
}
void SignatureCipher::initialize() {
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return;
}
initSolver();
initialized_ = true;
}
bool SignatureCipher::setPlayerJs(std::string_view playerJsCode) {
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
ECHOION_LOG_ERROR("Cipher not initialized. Call initialize() first.");
return false;
}
if (!solverInitialized_) {
ECHOION_LOG_WARNING("Solver not initialized - cannot process player JS");
return false;
}
playerJsCode_ = std::string(playerJsCode);
hasPlayerJs_ = false;
preprocessedPlayer_.clear();
if (playerJsCode_.empty()) {
ECHOION_LOG_WARNING("Empty player JS code provided");
return false;
}
if (!context_) {
ECHOION_LOG_ERROR("QuickJS context not available");
return false;
}
// Create input for the solver
glz::generic input;
input["type"] = "player";
input["player"] = playerJsCode_;
input["output_preprocessed"] = true;
input["requests"] = glz::generic::array_t{};
std::string inputStr = glz::write_json(input).value();
// Log input for debugging (truncate if too large)
std::string_view inputPreview(inputStr);
if (inputPreview.size() > 500) {
inputPreview = inputPreview.substr(0, 500);
ECHOION_LOG_DEBUG(std::format("Solver input (truncated): {}...", inputPreview));
} else {
ECHOION_LOG_DEBUG(std::format("Solver input: {}", inputPreview));
}
// Get global object and jsc function
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
ECHOION_LOG_ERROR("jsc function not found in QuickJS context");
JS_FreeValue(context_, global);
return false;
}
// Parse input JSON
JSValue inputVal = JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
ECHOION_LOG_ERROR("Failed to parse input JSON");
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
}
// Call jsc function with error handling wrapper
// The solver can throw on malformed player JS, so we wrap in try/catch
// Also JSON.stringify the result since jsc returns a JS object, not a string
const char* wrapperJS = R"(
(function(jscFunc, input) {
try {
var result = jscFunc(input);
return JSON.stringify(result);
} catch (e) {
return JSON.stringify({
error: e.message || String(e),
stack: e.stack || '',
responses: []
});
}
})
)";
JSValue wrapper = JS_Eval(context_, wrapperJS, strlen(wrapperJS), "<wrapper>",
JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(wrapper)) {
ECHOION_LOG_ERROR("Failed to compile error handling wrapper");
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
}
// Call the wrapper with jsc and input as arguments
JSValue args[] = { jsc, inputVal };
JSValue result = JS_Call(context_, wrapper, global, 2, args);
JS_FreeValue(context_, wrapper);
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 have failed silently");
} else {
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
// Log first 500 chars of result for debugging
std::string_view resultView(resultStr);
if (resultView.size() > 500) resultView = resultView.substr(0, 500);
ECHOION_LOG_DEBUG(std::format("jsc result: {}", resultView));
try {
glz::generic output;
auto ec = glz::read_json(output, resultStr);
if (!ec) {
if (output.contains("preprocessed_player")) {
preprocessedPlayer_ = output["preprocessed_player"].get<std::string>();
hasPlayerJs_ = true;
ECHOION_LOG_INFO("Player JS preprocessed successfully");
} else if (output.contains("error")) {
ECHOION_LOG_ERROR(std::format("Solver error: {}",
output["error"].get<std::string>()));
} else {
ECHOION_LOG_ERROR(std::format("Unexpected solver output: {}", resultStr));
}
} else {
ECHOION_LOG_ERROR(std::format("Failed to parse solver JSON output: {}", resultStr));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Failed to parse solver output: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
} else {
ECHOION_LOG_ERROR("jsc returned non-convertible value");
}
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
if (errorStr) {
ECHOION_LOG_ERROR(std::format("QuickJS execution error: {}", errorStr));
} else {
// Try to get exception details differently
ECHOION_LOG_ERROR("QuickJS execution failed (exception value not convertible to string)");
}
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
return hasPlayerJs_;
}
bool SignatureCipher::isReady() const {
std::lock_guard<std::mutex> lock(mutex_);
return initialized_ && solverInitialized_ && hasPlayerJs_;
}
bool SignatureCipher::isInitialized() const {
std::lock_guard<std::mutex> lock(mutex_);
return initialized_;
}
std::string SignatureCipher::decipher(std::string_view signatureCipher) {
if (!isReady() || signatureCipher.empty()) {
return std::string(signatureCipher);
}
// Parse the signature cipher parameters
// Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
std::string url, signature, sigParam = "signature";
// Parse query string
auto parseQuery = [](std::string_view query) {
std::map<std::string, std::string> result;
std::regex re("([^&=]+)=([^&]*)");
std::string queryStr(query);
for (std::sregex_iterator it(queryStr.begin(), queryStr.end(), re), end;
it != end; ++it) {
std::string key = (*it)[1].str();
std::string value = (*it)[2].str();
// URL decode
auto decodeUrl = [](std::string_view input) -> std::string {
std::string out;
for (size_t i = 0; i < input.size(); ++i) {
if (input[i] == '%' && i + 2 < input.size()) {
int hex = std::stoi(std::string(input.substr(i + 1, 2)), nullptr, 16);
out += static_cast<char>(hex);
i += 2;
} else if (input[i] == '+') {
out += ' ';
} else {
out += input[i];
}
}
return out;
};
result[key] = decodeUrl(value);
}
return result;
};
auto params = parseQuery(signatureCipher);
if (params.count("s")) {
signature = params["s"];
}
if (params.count("sp")) {
sigParam = params["sp"];
}
if (params.count("url")) {
url = params["url"];
}
if (signature.empty()) {
return std::string(signatureCipher);
}
// Solve the signature challenge
std::string deciphered = solveChallenge(signature, "sig");
if (deciphered.empty()) {
return std::string(signatureCipher);
}
// Build final URL
if (!url.empty()) {
url += "&" + sigParam + "=" + deciphered;
return url;
}
return deciphered;
}
std::string SignatureCipher::solveChallenge(const std::string& challenge, const std::string& type) {
std::lock_guard<std::mutex> lock(mutex_);
if (!solverInitialized_ || preprocessedPlayer_.empty()) {
return "";
}
if (!context_) {
return "";
}
// Create input for challenge solving
glz::generic input;
input["type"] = "preprocessed";
input["preprocessed_player"] = preprocessedPlayer_;
glz::generic request;
request["type"] = type;
request["challenges"] = glz::array(challenge);
input["requests"] = glz::array(request);
std::string inputStr = glz::write_json(input).value();
// Get global object and jsc function
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
JS_FreeValue(context_, global);
return "";
}
// Parse input JSON
JSValue inputVal = JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return "";
}
// Call jsc function
JSValue args[] = { inputVal };
JSValue result = JS_Call(context_, jsc, global, 1, args);
std::string output;
if (!JS_IsException(result)) {
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
try {
glz::generic jsonResult;
auto ec = glz::read_json(jsonResult, resultStr);
if (!ec && jsonResult.contains("responses")) {
auto& responses = jsonResult["responses"];
if (responses.is_array() && !responses.empty()) {
auto& firstResponse = responses[0];
if (firstResponse.contains("type") &&
firstResponse["type"].get<std::string>() == "result" &&
firstResponse.contains("data")) {
auto& data = firstResponse["data"];
if (data.contains(challenge)) {
output = data[challenge].get<std::string>();
}
}
}
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Failed to parse challenge response: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Challenge solving error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, result);
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return output;
}
std::string SignatureCipher::decipherNParam(std::string_view nParam) {
if (!isReady() || nParam.empty()) {
return std::string(nParam);
}
return solveChallenge(std::string(nParam), "n");
}
void SignatureCipher::clear() {
std::lock_guard<std::mutex> lock(mutex_);
cleanupQuickJS();
playerJsCode_.clear();
preprocessedPlayer_.clear();
initialized_ = false;
solverInitialized_ = false;
hasPlayerJs_ = false;
}
std::filesystem::path SignatureCipher::getCacheDir() {
std::filesystem::path cacheDir;
// Use XDG_CACHE_HOME or fallback to ~/.cache
const char* xdgCache = std::getenv("XDG_CACHE_HOME");
if (xdgCache && *xdgCache) {
cacheDir = std::filesystem::path(xdgCache) / "echoion";
} else {
const char* home = std::getenv("HOME");
if (home && *home) {
cacheDir = std::filesystem::path(home) / ".cache" / "echoion";
} else {
// Fallback to current directory
cacheDir = std::filesystem::path(".echoion_cache");
}
}
std::error_code ec;
std::filesystem::create_directories(cacheDir, ec);
return cacheDir;
}
std::optional<std::string> SignatureCipher::downloadSolverLibrary(std::string_view url) {
// Simple curl-based download with redirect following
// -s: silent, -L: follow redirects, -f: fail on HTTP error, -m 30: timeout 30s
std::string cmd = std::format("curl -sLf -m 30 '{}' 2>&1", std::string(url));
ECHOION_LOG_DEBUG(std::format("Downloading: {}", url));
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING(std::format("Failed to run curl for {}", url));
return std::nullopt;
}
std::string result;
char buffer[4096];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
int status = pclose(pipe);
if (status != 0) {
ECHOION_LOG_WARNING(std::format("curl failed with status {} for {}", status, url));
return std::nullopt;
}
if (result.empty()) {
ECHOION_LOG_WARNING(std::format("Downloaded empty file from {}", url));
return std::nullopt;
}
return result;
}
void SignatureCipher::initSolver() {
if (runtime_ && context_) {
return; // Already initialized
}
// Create QuickJS runtime
runtime_ = JS_NewRuntime();
if (!runtime_) {
ECHOION_LOG_ERROR("Failed to create QuickJS runtime");
return;
}
// Set memory limit (256 MB - player JS processing needs more memory)
JS_SetMemoryLimit(runtime_, 256 * 1024 * 1024);
// Set max stack size (8 MB to handle deep AST recursion)
JS_SetMaxStackSize(runtime_, 8 * 1024 * 1024);
// Create context
context_ = JS_NewContext(runtime_);
if (!context_) {
ECHOION_LOG_ERROR("Failed to create QuickJS context");
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
return;
}
// Get cache directory for storing solver libraries
auto cacheDir = getCacheDir();
auto corePath = cacheDir / "yt.solver.core.js";
auto libPath = cacheDir / "yt.solver.lib.js";
std::string coreCode;
std::string libCode;
// Try to load from cache first
std::error_code ec;
if (std::filesystem::exists(corePath, ec) && std::filesystem::exists(libPath, ec)) {
// Load from cache
std::ifstream coreFile(corePath);
std::ifstream libFile(libPath);
if (coreFile && libFile) {
coreCode = std::string((std::istreambuf_iterator<char>(coreFile)),
std::istreambuf_iterator<char>());
libCode = std::string((std::istreambuf_iterator<char>(libFile)),
std::istreambuf_iterator<char>());
ECHOION_LOG_INFO(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");
coreCode.clear();
libCode.clear();
}
}
}
// Download if not in cache or empty
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_INFO("Downloading solver libraries from GitHub releases...");
// Download core
auto coreOpt = downloadSolverLibrary(
"https://github.com/yt-dlp/ejs/releases/latest/download/yt.solver.core.js");
// Download lib
auto libOpt = downloadSolverLibrary(
"https://github.com/yt-dlp/ejs/releases/latest/download/yt.solver.lib.js");
if (coreOpt && libOpt && !coreOpt->empty() && !libOpt->empty()) {
coreCode = *coreOpt;
libCode = *libOpt;
ECHOION_LOG_DEBUG(std::format("Downloaded core: {} bytes, lib: {} bytes",
coreCode.size(), libCode.size()));
// Log first 200 chars of core to verify it's valid
if (!coreCode.empty()) {
std::string_view preview(coreCode.c_str(), std::min(size_t(200), coreCode.size()));
ECHOION_LOG_DEBUG(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 valid JavaScript");
coreCode.clear();
}
if (libCode.find("function") == std::string::npos &&
libCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING("Downloaded lib.js doesn't look like valid JavaScript");
libCode.clear();
}
// Save to cache
if (!coreCode.empty() && !libCode.empty()) {
std::ofstream coreOut(corePath);
std::ofstream libOut(libPath);
if (coreOut && libOut) {
coreOut << coreCode;
libOut << libCode;
coreOut.close();
libOut.close();
ECHOION_LOG_INFO("Solver libraries cached successfully");
}
}
} else {
ECHOION_LOG_WARNING("Failed to download solver libraries");
}
}
// Load libraries into QuickJS
// Order matters: lib.js creates 'lib' object, then bridge, then core.js uses meriyah/astring
bool coreLoaded = false;
bool libLoaded = false;
bool bridgeLoaded = false;
// Step 1: Load lib.js (contains meriyah and astring)
if (!libCode.empty()) {
JSValue libResult = JS_Eval(context_, libCode.c_str(), libCode.size(),
"lib.js", JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(libResult)) {
libLoaded = true;
ECHOION_LOG_DEBUG("Solver lib.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_WARNING(std::format("Failed to load lib solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, libResult);
}
// Step 2: Create bridge to expose meriyah and astring as global variables
if (libLoaded) {
const char* bridge = "var meriyah=lib.meriyah; var astring=lib.astring;";
JSValue bridgeResult = JS_Eval(context_, bridge, strlen(bridge), "bridge",
JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(bridgeResult)) {
bridgeLoaded = true;
ECHOION_LOG_DEBUG("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: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, bridgeResult);
}
// Step 3: Load core.js (uses meriyah and astring, creates jsc global function)
if (!coreCode.empty() && bridgeLoaded && libLoaded) {
JSValue coreResult = JS_Eval(context_, coreCode.c_str(), coreCode.size(),
"core.js", JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(coreResult)) {
coreLoaded = true;
ECHOION_LOG_DEBUG("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: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, coreResult);
}
// If core failed to load, we can't solve cipher signatures
if (!coreLoaded) {
ECHOION_LOG_WARNING("Loading fallback solver stub - ciphered videos won't work");
JSValue fallbackResult = JS_Eval(context_, FALLBACK_CORE_JS.data(),
FALLBACK_CORE_JS.size(), "fallback.js",
JS_EVAL_TYPE_GLOBAL);
JS_FreeValue(context_, fallbackResult);
cleanupQuickJS();
return;
}
// Verify jsc function exists in global scope
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
bool hasJsc = !JS_IsUndefined(jsc);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
if (!hasJsc) {
ECHOION_LOG_ERROR("jsc function not found after loading solver - ciphered videos won't work");
cleanupQuickJS();
return;
}
solverInitialized_ = true;
ECHOION_LOG_INFO("QuickJS solver initialized successfully (jsc function verified)");
}
std::optional<std::string> SignatureCipher::executeJS(std::string_view code, std::string_view filename) {
if (!context_) {
return std::nullopt;
}
JSValue result = JS_Eval(context_, code.data(), code.size(),
filename.data(), JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(result)) {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("JS execution error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
JS_FreeValue(context_, result);
return std::nullopt;
}
std::string output;
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
output = resultStr;
JS_FreeCString(context_, resultStr);
}
JS_FreeValue(context_, result);
return output;
}
void SignatureCipher::cleanupQuickJS() {
if (context_) {
JS_FreeContext(context_);
context_ = nullptr;
}
if (runtime_) {
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
}
solverInitialized_ = false;
}
} // namespace Echoion::Core
+115
View File
@@ -0,0 +1,115 @@
#include "echoion/core/SubscriptionManager.hpp"
#include "echoion/core/Logger.hpp"
namespace Echoion::Core {
SubscriptionManager::SubscriptionManager() = default;
SubscriptionManager::~SubscriptionManager() {
shutdown();
}
Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database> database) {
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return {};
}
database_ = std::move(database);
if (!database_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Database not available"));
}
// Load existing subscriptions from database
auto result = database_->getAllSubscribers();
if (!result) {
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}", result.error().message));
// Not fatal - start with empty subscriptions
} else {
for (auto clientId : *result) {
subscribedClients_.insert(clientId);
}
}
initialized_ = true;
ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)",
subscribedClients_.size()));
return {};
}
void SubscriptionManager::shutdown() {
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
return;
}
initialized_ = false;
database_.reset();
ECHOION_LOG_INFO("SubscriptionManager shutdown");
}
bool SubscriptionManager::subscribe(uint64_t clientId) {
std::lock_guard<std::mutex> lock(mutex_);
// Check if already subscribed (ensures uniqueness)
if (subscribedClients_.contains(clientId)) {
return false; // Already subscribed
}
// Add to database first
if (database_) {
auto result = database_->addSubscriber(clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}",
clientId, result.error().message));
return false;
}
}
subscribedClients_.insert(clientId);
ECHOION_LOG_INFO(std::format("Client {} subscribed", clientId));
return true;
}
bool SubscriptionManager::unsubscribe(uint64_t clientId) {
std::lock_guard<std::mutex> lock(mutex_);
bool removed = subscribedClients_.erase(clientId) > 0;
if (removed) {
// Remove from database
if (database_) {
auto result = database_->removeSubscriber(clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}",
clientId, result.error().message));
}
}
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", clientId));
}
return removed;
}
bool SubscriptionManager::isSubscribed(uint64_t clientId) const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_.contains(clientId);
}
std::set<uint64_t> SubscriptionManager::getSubscribedClients() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_;
}
bool SubscriptionManager::hasSubscribers() const {
std::lock_guard<std::mutex> lock(mutex_);
return !subscribedClients_.empty();
}
size_t SubscriptionManager::getSubscriberCount() const {
std::lock_guard<std::mutex> lock(mutex_);
return subscribedClients_.size();
}
} // namespace Echoion::Core
+373
View File
@@ -0,0 +1,373 @@
#include "echoion/core/YouTubeClient.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <algorithm>
#include <regex>
namespace Echoion::Core {
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient))
, ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)) {
}
YouTubeClient::~YouTubeClient() {
shutdown();
}
Api::Result<void> YouTubeClient::initialize() {
if (initialized_) return {};
ECHOION_LOG_INFO("Initializing YouTube client...");
// Initialize yt-dlp manager (downloads if needed)
auto result = ytDlpManager_->initialize();
if (!result) {
return result;
}
initialized_ = true;
ECHOION_LOG_INFO("YouTube client initialized successfully");
return {};
}
void YouTubeClient::setCookiesPath(const std::string& path) {
if (ytDlpManager_) {
ytDlpManager_->setCookiesPath(path);
}
}
void YouTubeClient::setCookiesFromBrowser(const std::string& browser) {
if (ytDlpManager_) {
ytDlpManager_->setCookiesFromBrowser(browser);
}
}
void YouTubeClient::shutdown() {
initialized_ = false;
}
bool YouTubeClient::isAvailable() const {
return ytDlpManager_ && ytDlpManager_->isAvailable();
}
std::string YouTubeClient::getYtDlpVersion() const {
if (!ytDlpManager_) return "";
return ytDlpManager_->getVersion();
}
Api::Result<void> YouTubeClient::updateYtDlp() {
if (!ytDlpManager_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp manager not initialized"));
}
return ytDlpManager_->update();
}
Api::Result<std::string> YouTubeClient::getAudioStreamUrl(std::string_view videoId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
ECHOION_LOG_INFO(std::format("Getting audio stream URL for video: {}", videoId));
// Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm)
// 140 = AAC 128kbps (m4a), 251 = Opus 160kbps (webm)
std::string url = std::format("https://www.youtube.com/watch?v={}", videoId);
// Fallback: try any audio format
ECHOION_LOG_INFO("Trying any audio format...");
std::string result = ytDlpManager_->execute({
url,
"-f", "bestaudio/251/140",
"-g",
"--no-warnings"
});
if (!result.empty() && result.back() == '\n') {
result.pop_back();
}
if (!result.empty() && result.find("http") == 0) {
ECHOION_LOG_INFO("Successfully got audio URL from yt-dlp (fallback)");
return result;
}
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
"Failed to get audio URL from yt-dlp"));
}
Api::Result<std::string> YouTubeClient::getStreamUrl(std::string_view videoId) {
return getAudioStreamUrl(videoId);
}
Api::Result<Api::TrackInfo> YouTubeClient::getVideoInfo(std::string_view videoId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
std::string url = std::format("https://www.youtube.com/watch?v={}", videoId);
std::string jsonStr = ytDlpManager_->execute({
url,
"-J",
"--no-warnings"
});
if (jsonStr.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp failed to get video info"));
}
try {
glz::generic json;
if (glz::read_json(json, jsonStr)) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp output"));
}
Api::TrackInfo info;
if (json.contains("id")) info.id = json["id"].get<std::string>();
if (json.contains("title")) info.title = json["title"].get<std::string>();
if (json.contains("uploader")) info.artist = json["uploader"].get<std::string>();
if (json.contains("duration")) {
info.duration = std::chrono::seconds(static_cast<int64_t>(json["duration"].get<double>()));
}
if (json.contains("thumbnail")) info.thumbnailUrl = json["thumbnail"].get<std::string>();
// Set originalUrl so we can extract video ID later for streaming
info.originalUrl = url;
info.source = Api::TrackSource::YouTube;
return info;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp output: {}", e.what())));
}
}
Api::Result<Api::SearchResult> YouTubeClient::search(std::string_view query,
std::optional<std::string> pageToken) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
// yt-dlp search format: ytsearch5:query
std::string searchQuery = std::format("ytsearch5:{}", query);
std::string jsonStr = ytDlpManager_->execute({
searchQuery,
"-J",
"--flat-playlist",
"--no-warnings"
});
if (jsonStr.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp search failed"));
}
try {
glz::generic json;
if (glz::read_json(json, jsonStr)) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp search output"));
}
Api::SearchResult result;
result.query = std::string(query);
if (json.contains("entries") && json["entries"].is_array()) {
for (const auto& entry : json["entries"].get<std::vector<glz::generic>>()) {
if (!entry.contains("id")) continue;
Api::TrackInfo track;
track.id = entry["id"].get<std::string>();
if (entry.contains("title")) track.title = entry["title"].get<std::string>();
if (entry.contains("uploader")) track.artist = entry["uploader"].get<std::string>();
if (entry.contains("duration")) {
track.duration = std::chrono::seconds(static_cast<int64_t>(entry["duration"].get<double>()));
}
if (entry.contains("thumbnail")) track.thumbnailUrl = entry["thumbnail"].get<std::string>();
// Set originalUrl so we can extract video ID later for streaming
track.originalUrl = std::format("https://www.youtube.com/watch?v={}", track.id);
track.source = Api::TrackSource::YouTube;
result.tracks.push_back(track);
}
}
result.totalResults = result.tracks.size();
return result;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp search: {}", e.what())));
}
}
Api::Result<Api::PlaylistInfo> YouTubeClient::getPlaylist(std::string_view playlistId) {
if (!initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available"));
}
std::string url = std::format("https://www.youtube.com/playlist?list={}", playlistId);
std::string jsonStr = ytDlpManager_->execute({
url,
"-J",
"--flat-playlist",
"--no-warnings"
});
if (jsonStr.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp playlist fetch failed"));
}
try {
glz::generic json;
if (glz::read_json(json, jsonStr)) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp playlist output"));
}
Api::PlaylistInfo info;
if (json.contains("title")) info.name = json["title"].get<std::string>();
if (json.contains("id")) info.id = json["id"].get<std::string>();
if (json.contains("entries") && json["entries"].is_array()) {
for (const auto& entry : json["entries"].get<std::vector<glz::generic>>()) {
if (!entry.contains("id")) continue;
Api::TrackInfo track;
track.id = entry["id"].get<std::string>();
if (entry.contains("title")) track.title = entry["title"].get<std::string>();
if (entry.contains("uploader")) track.artist = entry["uploader"].get<std::string>();
if (entry.contains("duration")) {
track.duration = std::chrono::seconds(static_cast<int64_t>(entry["duration"].get<double>()));
}
// Set originalUrl so we can extract video ID later for streaming
track.originalUrl = std::format("https://www.youtube.com/watch?v={}", track.id);
track.source = Api::TrackSource::YouTube;
info.tracks.push_back(track);
}
}
return info;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp playlist: {}", e.what())));
}
}
std::optional<std::string> YouTubeClient::extractVideoId(std::string_view url) {
std::string url_str(url);
// Handle faumaray.ru redirects using NetworkClient
if (url_str.find("faumaray.ru") != std::string::npos && networkClient_) {
ECHOION_LOG_DEBUG(std::format("Following redirect for: {}", url_str));
std::vector<Api::HttpHeader> headers = {
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
};
// Make request without following redirects to get the Location header
auto response = networkClient_->get(url_str, headers);
if (response) {
// Check if we got a redirect
if (response->isRedirect()) {
auto location = response->getHeader("location");
if (location.has_value()) {
ECHOION_LOG_DEBUG(std::format("Redirected to: {}", *location));
url_str = *location;
}
} else if (response->isSuccess()) {
// Some shorteners might return the target in the body or we might need
// to look at the URL after any automatic redirect following
// Try to extract from current URL or response
auto finalUrl = response->getHeader("x-final-url"); // Some clients add this
if (finalUrl.has_value()) {
url_str = *finalUrl;
}
}
}
}
// More comprehensive regex patterns for YouTube URLs
static const std::regex watch_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?)",
std::regex::icase);
static const std::regex short_pattern(
R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
std::regex::icase);
static const std::regex embed_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
std::regex::icase);
static const std::regex shorts_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
std::regex::icase);
// Also match just the video ID (11 characters)
static const std::regex id_only_pattern(
R"(^([a-zA-Z0-9_-]{11})$)",
std::regex::icase);
std::smatch match;
if (std::regex_search(url_str, match, watch_pattern) ||
std::regex_search(url_str, match, short_pattern) ||
std::regex_search(url_str, match, embed_pattern) ||
std::regex_search(url_str, match, shorts_pattern) ||
std::regex_search(url_str, match, id_only_pattern)) {
return match[1].str();
}
return std::nullopt;
}
std::optional<std::string> YouTubeClient::extractPlaylistId(std::string_view url) {
std::string urlStr(url);
std::smatch match;
if (std::regex_search(urlStr, match, std::regex(R"(list=([a-zA-Z0-9_-]+))"))) {
return match[1].str();
}
return std::nullopt;
}
bool YouTubeClient::isYouTubeUrl(std::string_view url) {
return url.find("youtube.com") != std::string::npos || url.find("youtu.be") != std::string::npos;
}
} // namespace Echoion::Core
+456
View File
@@ -0,0 +1,456 @@
#include "echoion/core/YtDlpManager.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <fstream>
#include <cstdlib>
#include <array>
#include <chrono>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Echoion::Core {
YtDlpManager::YtDlpManager(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)) {
}
YtDlpManager::~YtDlpManager() = default;
std::filesystem::path YtDlpManager::getStorageDir() const {
// Store in ~/.local/share/echoion/yt-dlp on Linux
// or %APPDATA%/echoion/yt-dlp on Windows
// or ~/Library/Application Support/echoion/yt-dlp on macOS
std::filesystem::path homeDir;
#ifdef _WIN32
const char* appData = std::getenv("APPDATA");
if (appData) {
homeDir = appData;
} else {
homeDir = std::filesystem::temp_directory_path();
}
return homeDir / "echoion" / "yt-dlp";
#else
const char* home = std::getenv("HOME");
if (home) {
homeDir = home;
} else {
homeDir = std::filesystem::temp_directory_path();
}
#ifdef __APPLE__
return homeDir / "Library" / "Application Support" / "echoion" / "yt-dlp";
#else
return homeDir / ".local" / "share" / "echoion" / "yt-dlp";
#endif
#endif
}
std::string YtDlpManager::getExecutableName() const {
#ifdef _WIN32
return "yt-dlp.exe";
#else
return "yt-dlp";
#endif
}
std::string YtDlpManager::getDownloadUrl() const {
#ifdef _WIN32
return std::string(YTDLP_DOWNLOAD_WINDOWS);
#elif defined(__APPLE__)
return std::string(YTDLP_DOWNLOAD_MACOS);
#else
return std::string(YTDLP_DOWNLOAD_LINUX);
#endif
}
std::filesystem::path YtDlpManager::getExecutablePath() const {
if (!executablePath_.empty()) {
return executablePath_;
}
return getStorageDir() / getExecutableName();
}
bool YtDlpManager::isAvailable() const {
return std::filesystem::exists(getExecutablePath());
}
Api::Result<void> YtDlpManager::initialize() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return {};
}
ECHOION_LOG_INFO("Initializing yt-dlp manager...");
// Create storage directory if needed
std::filesystem::path storageDir = getStorageDir();
ECHOION_LOG_DEBUG(std::format("yt-dlp storage dir: {}", storageDir.string()));
if (!std::filesystem::exists(storageDir)) {
ECHOION_LOG_INFO("Creating yt-dlp storage directory...");
try {
std::filesystem::create_directories(storageDir);
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to create yt-dlp storage directory: {}", e.what())));
}
}
executablePath_ = storageDir / getExecutableName();
ECHOION_LOG_DEBUG(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));
if (!exists) {
ECHOION_LOG_INFO("yt-dlp not found, downloading...");
auto result = downloadYtDlp();
if (!result) {
return result;
}
} else if (shouldUpdate()) {
ECHOION_LOG_INFO("yt-dlp may be outdated, checking for updates...");
// Try to update, but don't fail if update fails
auto result = update();
if (!result) {
ECHOION_LOG_WARNING(std::format("yt-dlp update failed: {}", result.error().toString()));
}
}
} // Release lock before calling getVersion() to avoid deadlock with getCookieArgs()
// Verify it works (outside lock to prevent deadlock with execute()->getCookieArgs())
ECHOION_LOG_INFO("Checking yt-dlp version...");
std::string version = getVersion();
if (version.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp executable not working"));
}
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
std::lock_guard<std::mutex> lock(mutex_);
initialized_ = true;
return {};
}
Api::Result<void> YtDlpManager::downloadYtDlp() {
if (!networkClient_) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
}
std::string downloadUrl = getDownloadUrl();
ECHOION_LOG_INFO(std::format("Downloading yt-dlp from: {}", downloadUrl));
std::vector<Api::HttpHeader> headers = {
{"User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}
};
// Follow redirects manually (GitHub releases use 302 redirects)
Api::HttpResponse response;
int redirectCount = 0;
constexpr int maxRedirects = 5;
while (redirectCount < maxRedirects) {
auto result = networkClient_->get(downloadUrl, headers);
if (!result) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: {}", result.error().message)));
}
response = std::move(*result);
// Check for redirect (3xx status codes)
if (response.statusCode >= 300 && response.statusCode < 400) {
auto location = response.getHeader("location");
if (!location.has_value()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Redirect response missing Location header"));
}
// Handle relative URLs
std::string newUrl = *location;
if (newUrl.starts_with("/")) {
// Relative to host - extract host from current URL
auto pos = downloadUrl.find("://");
if (pos != std::string::npos) {
auto pathStart = downloadUrl.find("/", pos + 3);
std::string base = (pathStart != std::string::npos)
? downloadUrl.substr(0, pathStart)
: downloadUrl;
newUrl = base + newUrl;
}
}
ECHOION_LOG_INFO(std::format("Following redirect (HTTP {}): {}",
response.statusCode, newUrl));
downloadUrl = newUrl;
redirectCount++;
continue;
}
break;
}
if (!response.isSuccess()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: HTTP {}", response.statusCode)));
}
ECHOION_LOG_INFO(std::format("Downloaded {} bytes", response.body.size()));
// Write to file
try {
std::ofstream file(executablePath_, std::ios::binary);
if (!file) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Failed to open yt-dlp file for writing"));
}
file.write(response.body.data(), response.body.size());
file.close();
} catch (const std::exception& e) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Failed to write yt-dlp file: {}", e.what())));
}
// Make executable on Unix
#ifndef _WIN32
auto execResult = makeExecutable();
if (!execResult) {
return execResult;
}
#endif
// Write timestamp file for update checking
try {
std::ofstream tsFile(getStorageDir() / ".last_update");
if (tsFile) {
auto now = std::chrono::system_clock::now();
auto timestamp = std::chrono::system_clock::to_time_t(now);
tsFile << timestamp;
}
} catch (...) {}
ECHOION_LOG_INFO("yt-dlp downloaded successfully");
return {};
}
Api::Result<void> YtDlpManager::makeExecutable() {
#ifdef _WIN32
return {}; // Windows doesn't need this
#else
if (chmod(executablePath_.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Failed to make yt-dlp executable"));
}
return {};
#endif
}
bool YtDlpManager::shouldUpdate() const {
try {
std::filesystem::path tsPath = getStorageDir() / ".last_update";
if (!std::filesystem::exists(tsPath)) {
return true;
}
std::ifstream tsFile(tsPath);
if (!tsFile) {
return true;
}
std::time_t lastUpdate;
tsFile >> lastUpdate;
auto now = std::chrono::system_clock::now();
auto last = std::chrono::system_clock::from_time_t(lastUpdate);
auto diff = std::chrono::duration_cast<std::chrono::hours>(now - last).count();
// Update if older than 7 days
return diff > (7 * 24);
} catch (...) {
return true;
}
}
Api::Result<void> YtDlpManager::update() {
std::lock_guard<std::mutex> lock(mutex_);
ECHOION_LOG_INFO("Updating yt-dlp...");
// Backup current version
std::filesystem::path backupPath = executablePath_.string() + ".backup";
try {
if (std::filesystem::exists(executablePath_)) {
std::filesystem::copy_file(executablePath_, backupPath,
std::filesystem::copy_options::overwrite_existing);
}
} catch (...) {}
// Download new version
auto result = downloadYtDlp();
if (!result) {
// Restore backup if available
try {
if (std::filesystem::exists(backupPath)) {
std::filesystem::copy_file(backupPath, executablePath_,
std::filesystem::copy_options::overwrite_existing);
}
} catch (...) {}
return result;
}
// Remove backup
try {
std::filesystem::remove(backupPath);
} catch (...) {}
// Verify new version works
std::string version = getVersion();
if (version.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
"Updated yt-dlp not working"));
}
ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version));
return {};
}
std::string YtDlpManager::getVersion() const {
if (!std::filesystem::exists(executablePath_)) {
ECHOION_LOG_WARNING("yt-dlp executable not found for version check");
return "";
}
ECHOION_LOG_DEBUG("Executing yt-dlp --version...");
std::string result = execute({"--version"});
ECHOION_LOG_DEBUG(std::format("yt-dlp --version output: '{}'", result));
// Remove trailing newline
if (!result.empty() && result.back() == '\n') {
result.pop_back();
}
return result;
}
void YtDlpManager::setCookiesPath(const std::string& path) {
std::lock_guard<std::mutex> lock(mutex_);
cookiesPath_ = path;
ECHOION_LOG_INFO(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(std::format("yt-dlp will use cookies from browser: {}", browser));
}
std::vector<std::string> YtDlpManager::getCookieArgs() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::string> cookieArgs;
if (cookiesFromBrowser_.has_value()) {
cookieArgs.push_back("--cookies-from-browser");
cookieArgs.push_back(*cookiesFromBrowser_);
} else if (cookiesPath_.has_value()) {
cookieArgs.push_back("--cookies");
cookieArgs.push_back(*cookiesPath_);
}
return cookieArgs;
}
std::string YtDlpManager::execute(const std::vector<std::string>& args) const {
if (!std::filesystem::exists(executablePath_)) {
return "";
}
std::string cmd = executablePath_.string();
// Add cookie arguments first
auto cookieArgs = getCookieArgs();
for (const auto& arg : cookieArgs) {
cmd += " ";
// Simple escaping
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
for (const auto& arg : args) {
cmd += " ";
// Simple escaping - wrap in quotes if contains spaces or special chars
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
// Escape existing quotes and wrap
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
// Suppress stderr
#ifdef _WIN32
cmd += " 2>nul";
#else
cmd += " 2>/dev/null";
#endif
// Add timeout to prevent hanging (10 seconds for version check, 60 for download)
bool isVersionCheck = (args.size() == 1 && args[0] == "--version");
int timeoutSec = isVersionCheck ? 10 : 60;
#ifdef __linux__
cmd = std::format("timeout {} {}", timeoutSec, cmd);
#elif defined(__APPLE__)
cmd = std::format("gtimeout {} {} 2>/dev/null || {}", timeoutSec, cmd, cmd);
#endif
ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd));
std::array<char, 8192> buffer;
std::string result;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution");
return "";
}
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result += buffer.data();
}
pclose(pipe);
return result;
}
} // namespace Echoion::Core