Use Api::fail() for error returns (241 sites)

Mechanically convert std::unexpected(Api::Error(ErrorCode::X, msg[, src]))
to Api::fail(ErrorCode::X, msg[, src]) across Core. Pure syntax; forwards of
existing errors (std::unexpected(x.error())) are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 22:07:18 +03:00
1 parent f8757d6040
commit 23759899bb
14 files changed
+344 -435

No files matched your search

+4 -4
View File
@@ -98,18 +98,18 @@ namespace Echoion::Core
{ {
auto parsed = Void::Json::parse(body); auto parsed = Void::Json::parse(body);
if (!parsed) { if (!parsed) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("JSON parse error ({}:{}): {}", std::format("JSON parse error ({}:{}): {}",
parsed.error().line, parsed.error().col, parsed.error().line, parsed.error().col,
parsed.error().message))); parsed.error().message));
} }
auto value = Void::Json::from_json<T>(*parsed); auto value = Void::Json::from_json<T>(*parsed);
if (!value) { if (!value) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("JSON decode error: field '{}': {}", std::format("JSON decode error: field '{}': {}",
value.error().field, value.error().message))); value.error().field, value.error().message));
} }
return std::move(*value); return std::move(*value);
} }
+33 -46
View File
@@ -75,16 +75,15 @@ namespace Echoion::Core
hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX; hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
break; break;
default: default:
return std::unexpected( return Api::fail(Api::ErrorCode::InvalidArgument,
Api::Error(Api::ErrorCode::InvalidArgument, "Unsupported hardware acceleration type");
"Unsupported hardware acceleration type"));
} }
if (av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(hwType)) == if (av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(hwType)) ==
AV_HWDEVICE_TYPE_NONE) { AV_HWDEVICE_TYPE_NONE) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NotSupported, Api::ErrorCode::NotSupported,
"Hardware acceleration not available on this system")); "Hardware acceleration not available on this system");
} }
hwAccelType_ = config.type; hwAccelType_ = config.type;
@@ -122,8 +121,8 @@ namespace Echoion::Core
Api::Result<void> AudioDecoder::openSource(const std::string& url) Api::Result<void> AudioDecoder::openSource(const std::string& url)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Decoder not initialized")); Api::ErrorCode::ServiceUnavailable, "Decoder not initialized");
} }
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@@ -192,9 +191,8 @@ namespace Echoion::Core
// Allocate format context first (needed for interrupt callback) // Allocate format context first (needed for interrupt callback)
formatContext_ = avformat_alloc_context(); formatContext_ = avformat_alloc_context();
if (!formatContext_) { if (!formatContext_) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError,
Api::Error(Api::ErrorCode::AudioError, "Failed to allocate format context");
"Failed to allocate format context"));
} }
// Set up interrupt callback to allow graceful shutdown during blocking // Set up interrupt callback to allow graceful shutdown during blocking
@@ -218,11 +216,11 @@ namespace Echoion::Core
av_strerror(ret, errbuf, sizeof(errbuf)); av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format( ECHOION_LOG_ERROR(std::format(
"FFmpeg failed to open input (error {}): {}", ret, errbuf)); "FFmpeg failed to open input (error {}): {}", ret, errbuf));
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::AudioError, Api::ErrorCode::AudioError,
std::format( std::format(
"Failed to open audio source: {} (FFmpeg error {}: {})", "Failed to open audio source: {} (FFmpeg error {}: {})",
url.substr(0, 80), ret, errbuf))); url.substr(0, 80), ret, errbuf));
} }
ECHOION_LOG_DEBUG("avformat_open_input succeeded"); ECHOION_LOG_DEBUG("avformat_open_input succeeded");
@@ -234,9 +232,9 @@ namespace Echoion::Core
std::format("FFmpeg failed to find stream info (error {}): {}", std::format("FFmpeg failed to find stream info (error {}): {}",
ret, errbuf)); ret, errbuf));
avformat_close_input(&formatContext_); avformat_close_input(&formatContext_);
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::AudioError, Api::ErrorCode::AudioError,
std::format("Failed to find stream info: {}", errbuf))); std::format("Failed to find stream info: {}", errbuf));
} }
const AVCodec* decoder = nullptr; const AVCodec* decoder = nullptr;
audioStreamIndex_ = -1; audioStreamIndex_ = -1;
@@ -246,16 +244,15 @@ namespace Echoion::Core
if (audioStreamIndex_ == -1) { if (audioStreamIndex_ == -1) {
avformat_close_input(&formatContext_); avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError, return Api::fail(Api::ErrorCode::AudioError,
"No audio stream found")); "No audio stream found");
} }
codecContext_ = avcodec_alloc_context3(decoder); codecContext_ = avcodec_alloc_context3(decoder);
if (!codecContext_) { if (!codecContext_) {
avformat_close_input(&formatContext_); avformat_close_input(&formatContext_);
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError,
Api::Error(Api::ErrorCode::AudioError, "Failed to allocate codec context");
"Failed to allocate codec context"));
} }
codecContext_->thread_count = 0; // Auto-detect CPU cores codecContext_->thread_count = 0; // Auto-detect CPU cores
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE; codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
@@ -265,16 +262,15 @@ namespace Echoion::Core
if (ret < 0) { if (ret < 0) {
avcodec_free_context(&codecContext_); avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_); avformat_close_input(&formatContext_);
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::AudioError, "Failed to copy codec parameters")); Api::ErrorCode::AudioError, "Failed to copy codec parameters");
} }
ret = avcodec_open2(codecContext_, decoder, nullptr); ret = avcodec_open2(codecContext_, decoder, nullptr);
if (ret < 0) { if (ret < 0) {
avcodec_free_context(&codecContext_); avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_); avformat_close_input(&formatContext_);
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "Failed to open codec");
Api::Error(Api::ErrorCode::AudioError, "Failed to open codec"));
} }
frame_ = av_frame_alloc(); frame_ = av_frame_alloc();
@@ -282,8 +278,8 @@ namespace Echoion::Core
if (!frame_ || !packet_) { if (!frame_ || !packet_) {
cleanupFfmpeg(); cleanupFfmpeg();
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::AudioError, "Failed to allocate frame/packet")); Api::ErrorCode::AudioError, "Failed to allocate frame/packet");
} }
streamInfo_.sampleRate = codecContext_->sample_rate; streamInfo_.sampleRate = codecContext_->sample_rate;
@@ -338,8 +334,8 @@ namespace Echoion::Core
} }
if (ret < 0 || swr_init(swrContext_) < 0) { if (ret < 0 || swr_init(swrContext_) < 0) {
cleanupFfmpeg(); cleanupFfmpeg();
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::AudioError, "Failed to initialize resampler")); Api::ErrorCode::AudioError, "Failed to initialize resampler");
} }
// Allocate output buffer for S16 samples (like reference) // Allocate output buffer for S16 samples (like reference)
@@ -401,12 +397,10 @@ namespace Echoion::Core
} }
if (eof_) { if (eof_) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "End of stream");
Api::Error(Api::ErrorCode::AudioError, "End of stream"));
} }
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "Decoder stopped");
Api::Error(Api::ErrorCode::AudioError, "Decoder stopped"));
} }
static int callCount = 0; static int callCount = 0;
@@ -443,8 +437,7 @@ namespace Echoion::Core
Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position) Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position)
{ {
if (!formatContext_ || audioStreamIndex_ < 0) { if (!formatContext_ || audioStreamIndex_ < 0) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "No source open");
Api::Error(Api::ErrorCode::AudioError, "No source open"));
} }
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@@ -454,8 +447,7 @@ namespace Echoion::Core
av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD); av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
if (ret < 0) { if (ret < 0) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "Seek failed");
Api::Error(Api::ErrorCode::AudioError, "Seek failed"));
} }
avcodec_flush_buffers(codecContext_); avcodec_flush_buffers(codecContext_);
@@ -472,8 +464,7 @@ namespace Echoion::Core
Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const
{ {
if (!initialized_ || !formatContext_) { if (!initialized_ || !formatContext_) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "No source open");
Api::Error(Api::ErrorCode::AudioError, "No source open"));
} }
return streamInfo_; return streamInfo_;
} }
@@ -629,18 +620,15 @@ namespace Echoion::Core
int ret = av_read_frame(formatContext_, packet_); int ret = av_read_frame(formatContext_, packet_);
if (ret < 0) { if (ret < 0) {
if (ret == AVERROR_EOF) { if (ret == AVERROR_EOF) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "End of file");
Api::Error(Api::ErrorCode::AudioError, "End of file"));
} }
if (ret == AVERROR_EXIT) { if (ret == AVERROR_EXIT) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "Interrupted");
Api::Error(Api::ErrorCode::AudioError, "Interrupted"));
} }
char errbuf[256]; char errbuf[256];
av_strerror(ret, errbuf, sizeof(errbuf)); av_strerror(ret, errbuf, sizeof(errbuf));
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError,
Api::Error(Api::ErrorCode::AudioError, std::format("Error reading frame: {}", errbuf));
std::format("Error reading frame: {}", errbuf)));
} }
if (packet_->stream_index != audioStreamIndex_) { if (packet_->stream_index != audioStreamIndex_) {
@@ -698,8 +686,7 @@ namespace Echoion::Core
int converted = swr_convert(swrContext_, &outData, outSamples, inData, int converted = swr_convert(swrContext_, &outData, outSamples, inData,
frame_->nb_samples); frame_->nb_samples);
if (converted < 0) { if (converted < 0) {
return std::unexpected( return Api::fail(Api::ErrorCode::AudioError, "Resampling failed");
Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
} }
outputBuffer.resize(converted * outputChannels_); outputBuffer.resize(converted * outputChannels_);
+10 -13
View File
@@ -20,18 +20,16 @@ namespace Echoion::Core
ConfigLoader::loadFromFile(const std::filesystem::path& path) ConfigLoader::loadFromFile(const std::filesystem::path& path)
{ {
if (!std::filesystem::exists(path)) { if (!std::filesystem::exists(path)) {
return std::unexpected( return Api::fail(Api::ErrorCode::NotFound,
Api::Error(Api::ErrorCode::NotFound,
std::format("Configuration file not found: {}", std::format("Configuration file not found: {}",
path.string()))); path.string()));
} }
std::ifstream file(path); std::ifstream file(path);
if (!file.is_open()) { if (!file.is_open()) {
return std::unexpected( return Api::fail(Api::ErrorCode::PermissionDenied,
Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to open configuration file: {}", std::format("Failed to open configuration file: {}",
path.string()))); path.string()));
} }
std::string content((std::istreambuf_iterator<char>(file)), std::string content((std::istreambuf_iterator<char>(file)),
@@ -40,11 +38,11 @@ namespace Echoion::Core
auto parsed = Void::Json::parse(content); auto parsed = Void::Json::parse(content);
if (!parsed) { if (!parsed) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to parse configuration ({}:{}): {}", std::format("Failed to parse configuration ({}:{}): {}",
parsed.error().line, parsed.error().col, parsed.error().line, parsed.error().col,
parsed.error().message))); parsed.error().message));
} }
// Tolerant deserialization: unknown JSON fields are ignored and missing // Tolerant deserialization: unknown JSON fields are ignored and missing
@@ -52,11 +50,11 @@ namespace Echoion::Core
// glz::opts{error_on_unknown_keys=false, error_on_missing_keys=false}). // glz::opts{error_on_unknown_keys=false, error_on_missing_keys=false}).
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed); auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
if (!jsonResult) { if (!jsonResult) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to parse configuration: field '{}': {}", std::format("Failed to parse configuration: field '{}': {}",
jsonResult.error().field, jsonResult.error().field,
jsonResult.error().message))); jsonResult.error().message));
} }
AppConfigJson jsonConfig = std::move(*jsonResult); AppConfigJson jsonConfig = std::move(*jsonResult);
@@ -294,10 +292,9 @@ namespace Echoion::Core
Void::Json::to_json(jsonConfig), {.pretty = true}); Void::Json::to_json(jsonConfig), {.pretty = true});
std::ofstream file(path); std::ofstream file(path);
if (!file.is_open()) { if (!file.is_open()) {
return std::unexpected( return Api::fail(Api::ErrorCode::PermissionDenied,
Api::Error(Api::ErrorCode::PermissionDenied,
std::format("Failed to write configuration file: {}", std::format("Failed to write configuration file: {}",
path.string()))); path.string()));
} }
file << json; file << json;
+87 -91
View File
@@ -41,8 +41,8 @@ namespace Echoion::Core
Api::Result<void> Core::initialize(const std::filesystem::path& configPath) Api::Result<void> Core::initialize(const std::filesystem::path& configPath)
{ {
if (initialized_) { if (initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already initialized")); "Core already initialized");
} }
auto logger = std::make_shared<Logger>(); auto logger = std::make_shared<Logger>();
logger->setMinLevel(Api::LogLevel::Debug); logger->setMinLevel(Api::LogLevel::Debug);
@@ -412,8 +412,8 @@ namespace Echoion::Core
Api::Result<void> Core::playTrack(const Api::TrackInfo& track) Api::Result<void> Core::playTrack(const Api::TrackInfo& track)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->queueTrack(track, 0); auto result = musicManager_->queueTrack(track, 0);
@@ -445,8 +445,8 @@ namespace Echoion::Core
Api::Result<void> Core::play(const std::string& trackId) Api::Result<void> Core::play(const std::string& trackId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
// Resolve track ID to TrackInfo via MusicManager // Resolve track ID to TrackInfo via MusicManager
@@ -461,8 +461,8 @@ namespace Echoion::Core
Api::Result<void> Core::pause() Api::Result<void> Core::pause()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->pause(); auto result = musicManager_->pause();
@@ -478,8 +478,8 @@ namespace Echoion::Core
Api::Result<void> Core::resume() Api::Result<void> Core::resume()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->resume(); auto result = musicManager_->resume();
@@ -495,8 +495,8 @@ namespace Echoion::Core
Api::Result<void> Core::stop() Api::Result<void> Core::stop()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->stop(); auto result = musicManager_->stop();
@@ -512,8 +512,8 @@ namespace Echoion::Core
Api::Result<void> Core::skip(uint32_t count) Api::Result<void> Core::skip(uint32_t count)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->skip(count); auto result = musicManager_->skip(count);
@@ -529,8 +529,8 @@ namespace Echoion::Core
Api::Result<void> Core::seek(std::chrono::milliseconds position) Api::Result<void> Core::seek(std::chrono::milliseconds position)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
return musicManager_->seek(position); return musicManager_->seek(position);
@@ -539,8 +539,8 @@ namespace Echoion::Core
Api::Result<void> Core::setVolume(float volume) Api::Result<void> Core::setVolume(float volume)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
return musicManager_->setVolume(volume); return musicManager_->setVolume(volume);
@@ -550,8 +550,8 @@ namespace Echoion::Core
uint64_t clientId) uint64_t clientId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->queueTrack(track, clientId); auto result = musicManager_->queueTrack(track, clientId);
@@ -572,8 +572,8 @@ namespace Echoion::Core
uint64_t clientId) uint64_t clientId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
// Use MusicManager::play to resolve trackId and get TrackInfo // Use MusicManager::play to resolve trackId and get TrackInfo
@@ -592,8 +592,8 @@ namespace Echoion::Core
Api::Result<void> Core::removeFromQueue(uint64_t queueId) Api::Result<void> Core::removeFromQueue(uint64_t queueId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
// Find position by queueId // Find position by queueId
@@ -608,15 +608,14 @@ namespace Echoion::Core
} }
} }
return std::unexpected( return Api::fail(Api::ErrorCode::NotFound, "Track not found in queue");
Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
} }
Api::Result<void> Core::clearQueue() Api::Result<void> Core::clearQueue()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->clearQueue(); auto result = musicManager_->clearQueue();
@@ -632,8 +631,8 @@ namespace Echoion::Core
Api::Result<std::vector<Api::QueueEntry>> Core::getQueue() const Api::Result<std::vector<Api::QueueEntry>> Core::getQueue() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
return musicManager_->getQueue(); return musicManager_->getQueue();
@@ -642,8 +641,8 @@ namespace Echoion::Core
Api::Result<std::vector<Api::TrackSummary>> Core::getQueueSummaries() const Api::Result<std::vector<Api::TrackSummary>> Core::getQueueSummaries() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto queue = musicManager_->getQueue(); auto queue = musicManager_->getQueue();
@@ -666,8 +665,8 @@ namespace Echoion::Core
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition) Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
// Find current position // Find current position
@@ -687,8 +686,8 @@ namespace Echoion::Core
} }
if (!found) { if (!found) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, return Api::fail(Api::ErrorCode::NotFound,
"Track not found in queue")); "Track not found in queue");
} }
return musicManager_->moveInQueue(fromPosition, newPosition); return musicManager_->moveInQueue(fromPosition, newPosition);
@@ -697,8 +696,8 @@ namespace Echoion::Core
Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
return musicManager_->getCurrentTrack(); return musicManager_->getCurrentTrack();
@@ -708,8 +707,8 @@ namespace Echoion::Core
Core::getCurrentTrackSummary() const Core::getCurrentTrackSummary() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto current = musicManager_->getCurrentTrack(); auto current = musicManager_->getCurrentTrack();
@@ -731,8 +730,8 @@ namespace Echoion::Core
Api::Result<Api::PlaybackState> Core::getPlaybackState() const Api::Result<Api::PlaybackState> Core::getPlaybackState() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
return musicManager_->getPlaybackState(); return musicManager_->getPlaybackState();
@@ -741,8 +740,8 @@ namespace Echoion::Core
Api::Result<Api::PlaybackSummary> Core::getPlaybackSummary() const Api::Result<Api::PlaybackSummary> Core::getPlaybackSummary() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto state = musicManager_->getPlaybackState(); auto state = musicManager_->getPlaybackState();
@@ -773,8 +772,8 @@ namespace Echoion::Core
uint64_t clientId) uint64_t clientId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto result = musicManager_->loadPlaylist(playlistId, clientId); auto result = musicManager_->loadPlaylist(playlistId, clientId);
@@ -787,8 +786,8 @@ namespace Echoion::Core
Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
return musicManager_->getPlaylists(); return musicManager_->getPlaylists();
@@ -797,8 +796,8 @@ namespace Echoion::Core
Api::Result<std::vector<std::string>> Core::getPlaylistIds() const Api::Result<std::vector<std::string>> Core::getPlaylistIds() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto playlists = musicManager_->getPlaylists(); auto playlists = musicManager_->getPlaylists();
@@ -845,19 +844,19 @@ namespace Echoion::Core
// Parse JSON config using Void::Json reflection // Parse JSON config using Void::Json reflection
auto parsed = Void::Json::parse(configJson); auto parsed = Void::Json::parse(configJson);
if (!parsed) { if (!parsed) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON ({}:{}): {}", std::format("Failed to parse config JSON ({}:{}): {}",
parsed.error().line, parsed.error().col, parsed.error().line, parsed.error().col,
parsed.error().message))); parsed.error().message));
} }
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed); auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
if (!jsonResult.has_value()) { if (!jsonResult.has_value()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON: field '{}': {}", std::format("Failed to parse config JSON: field '{}': {}",
jsonResult.error().field, jsonResult.error().field,
jsonResult.error().message))); jsonResult.error().message));
} }
// Convert to AppConfig // Convert to AppConfig
@@ -976,13 +975,13 @@ namespace Echoion::Core
Api::Result<void> Core::reloadConfig() Api::Result<void> Core::reloadConfig()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
if (configPath_.empty()) { if (configPath_.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Config path not set")); "Config path not set");
} }
// Reload config from disk // Reload config from disk
@@ -1007,8 +1006,8 @@ namespace Echoion::Core
Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull() Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
ECHOION_LOG_INFO("Preparing for hot reload..."); ECHOION_LOG_INFO("Preparing for hot reload...");
@@ -1025,8 +1024,8 @@ namespace Echoion::Core
Core::restoreAfterHotReloadFull(const Api::HotReloadState& state) Core::restoreAfterHotReloadFull(const Api::HotReloadState& state)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
ECHOION_LOG_INFO("Restoring after hot reload..."); ECHOION_LOG_INFO("Restoring after hot reload...");
@@ -1048,8 +1047,8 @@ namespace Echoion::Core
Api::Result<std::string> Core::prepareForHotReload() Api::Result<std::string> Core::prepareForHotReload()
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
ECHOION_LOG_INFO("Preparing for hot reload (decoupled)..."); ECHOION_LOG_INFO("Preparing for hot reload (decoupled)...");
@@ -1068,8 +1067,8 @@ namespace Echoion::Core
Api::Result<void> Core::restoreAfterHotReload(const std::string& state) Api::Result<void> Core::restoreAfterHotReload(const std::string& state)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
ECHOION_LOG_INFO("Restoring after hot reload (decoupled)..."); ECHOION_LOG_INFO("Restoring after hot reload (decoupled)...");
@@ -1077,20 +1076,20 @@ namespace Echoion::Core
// Deserialize state from JSON // Deserialize state from JSON
auto parsed = Void::Json::parse(state); auto parsed = Void::Json::parse(state);
if (!parsed) { if (!parsed) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to parse hot reload state ({}:{}): {}", std::format("Failed to parse hot reload state ({}:{}): {}",
parsed.error().line, parsed.error().col, parsed.error().line, parsed.error().col,
parsed.error().message))); parsed.error().message));
} }
auto stateResult = Void::Json::from_json<Api::HotReloadState>(*parsed); auto stateResult = Void::Json::from_json<Api::HotReloadState>(*parsed);
if (!stateResult.has_value()) { if (!stateResult.has_value()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to deserialize hot reload state: " std::format("Failed to deserialize hot reload state: "
"field '{}': {}", "field '{}': {}",
stateResult.error().field, stateResult.error().field,
stateResult.error().message))); stateResult.error().message));
} }
auto result = musicManager_->restoreFromHotReload(stateResult.value()); auto result = musicManager_->restoreFromHotReload(stateResult.value());
@@ -1223,8 +1222,8 @@ namespace Echoion::Core
Core::getCurrentTrackHandle() const Core::getCurrentTrackHandle() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto current = musicManager_->getCurrentTrack(); auto current = musicManager_->getCurrentTrack();
@@ -1246,8 +1245,8 @@ namespace Echoion::Core
Core::getQueueHandles() const Core::getQueueHandles() const
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
auto queue = musicManager_->getQueue(); auto queue = musicManager_->getQueue();
@@ -1274,8 +1273,8 @@ namespace Echoion::Core
Api::Result<void> Core::updateConfigFromHandle(Api::AppConfigHandle config) Api::Result<void> Core::updateConfigFromHandle(Api::AppConfigHandle config)
{ {
if (!config.isValid()) { if (!config.isValid()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid config handle")); "Invalid config handle");
} }
// Update from the handle // Update from the handle
@@ -1307,8 +1306,8 @@ namespace Echoion::Core
"(this={}), ignoring event type={}", "(this={}), ignoring event type={}",
reinterpret_cast<uintptr_t>(this), reinterpret_cast<uintptr_t>(this),
static_cast<int>(event.type))); static_cast<int>(event.type)));
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized")); Api::ErrorCode::ServiceUnavailable, "Core not initialized");
} }
// Debug logging for command events // Debug logging for command events
@@ -1628,16 +1627,14 @@ namespace Echoion::Core
// Parse JSON params // Parse JSON params
auto parsedParams = Void::Json::parse(params); auto parsedParams = Void::Json::parse(params);
if (!parsedParams) { if (!parsedParams) {
return std::unexpected( return Api::fail(Api::ErrorCode::InvalidArgument,
Api::Error(Api::ErrorCode::InvalidArgument, "Invalid authentication request format");
"Invalid authentication request format"));
} }
auto reqResult = auto reqResult =
Void::Json::from_json<RpcAuthRequest>(*parsedParams); Void::Json::from_json<RpcAuthRequest>(*parsedParams);
if (!reqResult) { if (!reqResult) {
return std::unexpected( return Api::fail(Api::ErrorCode::InvalidArgument,
Api::Error(Api::ErrorCode::InvalidArgument, "Invalid authentication request format");
"Invalid authentication request format"));
} }
const RpcAuthRequest& req = *reqResult; const RpcAuthRequest& req = *reqResult;
@@ -1653,8 +1650,8 @@ namespace Echoion::Core
"{\"success\":true,\"message\":\"Authentication " "{\"success\":true,\"message\":\"Authentication "
"successful\"}"); "successful\"}");
} else { } else {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::PermissionDenied, "Invalid token")); Api::ErrorCode::PermissionDenied, "Invalid token");
} }
} }
@@ -1668,10 +1665,10 @@ namespace Echoion::Core
} }
if (!uidResult->has_value()) { if (!uidResult->has_value()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NotFound, Api::ErrorCode::NotFound,
"Subscriber not found. Please subscribe to the bot " "Subscriber not found. Please subscribe to the bot "
"first using !subscribe command.")); "first using !subscribe command.");
} }
const std::string& uid = **uidResult; const std::string& uid = **uidResult;
@@ -1736,10 +1733,9 @@ namespace Echoion::Core
"TeamSpeak PM. Please check your private messages.\"}"); "TeamSpeak PM. Please check your private messages.\"}");
} }
return std::unexpected( return Api::fail(Api::ErrorCode::InvalidArgument,
Api::Error(Api::ErrorCode::InvalidArgument,
"Authentication request must include either " "Authentication request must include either "
"'nickname' or 'token'")); "'nickname' or 'token'");
}); });
// Playback control // Playback control
+35 -65
View File
@@ -51,10 +51,9 @@ namespace Echoion::Api
auto opened = Void::Sqlite::Database::open( auto opened = Void::Sqlite::Database::open(
config.path, Void::Sqlite::OpenMode::ReadWriteCreate); config.path, Void::Sqlite::OpenMode::ReadWriteCreate);
if (!opened) { if (!opened) {
return std::unexpected( return fail(ErrorCode::DatabaseError,
Error(ErrorCode::DatabaseError,
std::format("Failed to open database: {}", std::format("Failed to open database: {}",
opened.error().message()))); opened.error().message()));
} }
impl_->voidDb = std::move(*opened); impl_->voidDb = std::move(*opened);
impl_->db = impl_->voidDb.handle(); impl_->db = impl_->voidDb.handle();
@@ -120,7 +119,7 @@ namespace Echoion::Api
if (errMsg) { if (errMsg) {
std::string error = errMsg; std::string error = errMsg;
sqlite3_free(errMsg); sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error)); return fail(ErrorCode::DatabaseError, error);
} }
// Get current version // Get current version
@@ -200,7 +199,7 @@ namespace Echoion::Api
if (errMsg) { if (errMsg) {
std::string error = errMsg; std::string error = errMsg;
sqlite3_free(errMsg); sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error)); return fail(ErrorCode::DatabaseError, error);
} }
sqlite3_exec(impl_->db, sqlite3_exec(impl_->db,
@@ -228,7 +227,7 @@ namespace Echoion::Api
if (errMsg) { if (errMsg) {
std::string error = errMsg; std::string error = errMsg;
sqlite3_free(errMsg); sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error)); return fail(ErrorCode::DatabaseError, error);
} }
sqlite3_exec(impl_->db, sqlite3_exec(impl_->db,
@@ -290,7 +289,7 @@ namespace Echoion::Api
if (errMsg) { if (errMsg) {
std::string error = errMsg; std::string error = errMsg;
sqlite3_free(errMsg); sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error)); return fail(ErrorCode::DatabaseError, error);
} }
sqlite3_exec(impl_->db, sqlite3_exec(impl_->db,
@@ -327,8 +326,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
@@ -341,8 +339,7 @@ namespace Echoion::Api
if (sqlite3_step(stmt) != SQLITE_DONE) { if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
uint64_t id = uint64_t id =
@@ -398,8 +395,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
@@ -473,8 +469,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -502,8 +497,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
@@ -528,8 +522,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(playlistId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(playlistId));
@@ -573,8 +566,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, track.originalUrl.c_str(), -1, sqlite3_bind_text(stmt, 1, track.originalUrl.c_str(), -1,
@@ -610,8 +602,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -651,8 +642,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -677,8 +667,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -700,8 +689,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -728,8 +716,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -766,8 +753,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(keepCount)); sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(keepCount));
@@ -821,8 +807,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -841,8 +826,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -860,8 +844,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -882,8 +865,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
while (sqlite3_step(stmt) == SQLITE_ROW) { while (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -917,8 +899,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
size_t count = 0; size_t count = 0;
@@ -1020,16 +1001,14 @@ namespace Echoion::Api
if (sqlite3_prepare_v2(impl_->db, if (sqlite3_prepare_v2(impl_->db,
"SELECT 1 FROM subscriptions WHERE uid = ?", -1, "SELECT 1 FROM subscriptions WHERE uid = ?", -1,
&checkStmt, nullptr) != SQLITE_OK) { &checkStmt, nullptr) != SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(checkStmt, 1, uid.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(checkStmt, 1, uid.c_str(), -1, SQLITE_STATIC);
bool exists = sqlite3_step(checkStmt) == SQLITE_ROW; bool exists = sqlite3_step(checkStmt) == SQLITE_ROW;
sqlite3_finalize(checkStmt); sqlite3_finalize(checkStmt);
if (!exists) { if (!exists) {
return std::unexpected( return fail(ErrorCode::NotFound, "Subscriber not found");
Error(ErrorCode::NotFound, "Subscriber not found"));
} }
// Generate a random 32-character alphanumeric token (Void::Random is // Generate a random 32-character alphanumeric token (Void::Random is
@@ -1045,8 +1024,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
@@ -1054,8 +1032,7 @@ namespace Echoion::Api
if (sqlite3_step(stmt) != SQLITE_DONE) { if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
@@ -1074,8 +1051,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -1104,8 +1080,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
@@ -1143,8 +1118,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
@@ -1174,8 +1148,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, nickname.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, nickname.c_str(), -1, SQLITE_STATIC);
@@ -1204,16 +1177,14 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
if (sqlite3_step(stmt) != SQLITE_DONE) { if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
@@ -1231,8 +1202,7 @@ namespace Echoion::Api
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) !=
SQLITE_OK) { SQLITE_OK) {
return std::unexpected( return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
} }
std::vector<std::string> uids; std::vector<std::string> uids;
+57 -73
View File
@@ -317,8 +317,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_ || isPaused_) { if (!isPlaying_ || isPaused_) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing")); "Nothing is playing");
} }
// Capture current position before pausing // Capture current position before pausing
@@ -334,8 +334,7 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_ || !isPaused_) { if (!isPlaying_ || !isPaused_) {
return std::unexpected( return Api::fail(Api::ErrorCode::InvalidArgument, "Not paused");
Api::Error(Api::ErrorCode::InvalidArgument, "Not paused"));
} }
// Reset time tracking from current position // Reset time tracking from current position
@@ -410,8 +409,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_) { if (!isPlaying_) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing")); "Nothing is playing");
} }
for (uint32_t i = 0; i < count; ++i) { for (uint32_t i = 0; i < count; ++i) {
@@ -458,8 +457,8 @@ namespace Echoion::Core
Api::Result<void> MusicManager::seek(std::chrono::milliseconds position) Api::Result<void> MusicManager::seek(std::chrono::milliseconds position)
{ {
if (!isPlaying_) { if (!isPlaying_) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing")); "Nothing is playing");
} }
auto result = audioDecoder_->seek(position); auto result = audioDecoder_->seek(position);
@@ -485,8 +484,8 @@ namespace Echoion::Core
Api::Result<void> MusicManager::setVolume(float volume) Api::Result<void> MusicManager::setVolume(float volume)
{ {
if (volume < 0.0f || volume > 1.0f) { if (volume < 0.0f || volume > 1.0f) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Volume must be 0.0-1.0")); "Volume must be 0.0-1.0");
} }
float oldVolume = volume_; float oldVolume = volume_;
@@ -516,10 +515,9 @@ namespace Echoion::Core
ECHOION_LOG_WARNING(std::format( ECHOION_LOG_WARNING(std::format(
"Track validation failed for '{} - {}': {}", track.title, "Track validation failed for '{} - {}': {}", track.title,
track.artist, streamUrl.error().message)); track.artist, streamUrl.error().message));
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable,
std::format("Cannot play this track: {}", std::format("Cannot play this track: {}",
streamUrl.error().message))); streamUrl.error().message));
} }
uint64_t queueId; uint64_t queueId;
@@ -538,8 +536,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (queue_.size() >= config_.maxQueueSize) { if (queue_.size() >= config_.maxQueueSize) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::InvalidArgument, "Queue is full")); Api::ErrorCode::InvalidArgument, "Queue is full");
} }
queueId = nextQueueId_++; queueId = nextQueueId_++;
@@ -632,8 +630,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (position >= queue_.size()) { if (position >= queue_.size()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid position")); "Invalid position");
} }
auto removedTrack = queue_[position]; auto removedTrack = queue_[position];
@@ -706,8 +704,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_); std::shared_lock<std::shared_mutex> lock(mutex_);
if (from >= queue_.size() || to >= queue_.size()) { if (from >= queue_.size() || to >= queue_.size()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid position")); "Invalid position");
} }
auto entry = queue_[from]; auto entry = queue_[from];
@@ -828,16 +826,14 @@ namespace Echoion::Core
uint64_t clientId) uint64_t clientId)
{ {
if (!youTubeClient_) { if (!youTubeClient_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTube client not available");
"YouTube client not available"));
} }
// Check if already loading a playlist // Check if already loading a playlist
if (playlistLoading_.load()) { if (playlistLoading_.load()) {
return std::unexpected( return Api::fail(Api::ErrorCode::AlreadyExists,
Api::Error(Api::ErrorCode::AlreadyExists, "Already loading a playlist, please wait");
"Already loading a playlist, please wait"));
} }
// Extract playlist ID if a full URL was provided // Extract playlist ID if a full URL was provided
@@ -850,9 +846,8 @@ namespace Echoion::Core
ECHOION_LOG_DEBUG(std::format( ECHOION_LOG_DEBUG(std::format(
"Extracted playlist ID '{}' from URL", playlistId)); "Extracted playlist ID '{}' from URL", playlistId));
} else { } else {
return std::unexpected( return Api::fail(Api::ErrorCode::InvalidArgument,
Api::Error(Api::ErrorCode::InvalidArgument, "Could not extract playlist ID from URL");
"Could not extract playlist ID from URL"));
} }
} }
@@ -1042,9 +1037,8 @@ namespace Echoion::Core
MusicManager::search(const std::string& query) MusicManager::search(const std::string& query)
{ {
if (!youTubeClient_) { if (!youTubeClient_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTube client not available");
"YouTube client not available"));
} }
return youTubeClient_->search(query); return youTubeClient_->search(query);
@@ -1078,23 +1072,22 @@ namespace Echoion::Core
{ {
if (index == 0) { if (index == 0) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Index must be 1 or greater")); "Index must be 1 or greater");
} }
auto pending = getPendingSearch(clientId); auto pending = getPendingSearch(clientId);
if (!pending) { if (!pending) {
return std::unexpected( return Api::fail(Api::ErrorCode::NotFound,
Api::Error(Api::ErrorCode::NotFound,
"No pending search results. Use search or play " "No pending search results. Use search or play "
"commands first.")); "commands first.");
} }
if (index > pending->size()) { if (index > pending->size()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NotFound, Api::ErrorCode::NotFound,
std::format("Invalid selection. Only {} results available.", std::format("Invalid selection. Only {} results available.",
pending->size()))); pending->size()));
} }
auto selected = auto selected =
@@ -1689,8 +1682,7 @@ namespace Echoion::Core
} }
if (searchResult->tracks.empty()) { if (searchResult->tracks.empty()) {
return std::unexpected( return Api::fail(Api::ErrorCode::NotFound, "No results found");
Api::Error(Api::ErrorCode::NotFound, "No results found"));
} }
return searchResult->tracks[0]; return searchResult->tracks[0];
@@ -1722,8 +1714,7 @@ namespace Echoion::Core
ECHOION_LOG_WARNING("Could not extract video ID from URL"); ECHOION_LOG_WARNING("Could not extract video ID from URL");
} }
return std::unexpected( return Api::fail(Api::ErrorCode::NotFound, "Could not get stream URL");
Api::Error(Api::ErrorCode::NotFound, "Could not get stream URL"));
} }
void MusicManager::onTrackFinished() void MusicManager::onTrackFinished()
@@ -1896,21 +1887,20 @@ Subscriptions are persistent across server reconnects.)";
Api::Result<std::string> MusicManager::subscribe(uint64_t clientId) Api::Result<std::string> MusicManager::subscribe(uint64_t clientId)
{ {
if (!subscriptionManager_) { if (!subscriptionManager_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized");
"Subscription manager not initialized"));
} }
// Get client info (UID and nickname) from the callback // Get client info (UID and nickname) from the callback
if (!clientInfoCallback_) { if (!clientInfoCallback_) {
return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized, return Api::fail(Api::ErrorCode::NotInitialized,
"Client info callback not set")); "Client info callback not set");
} }
auto clientInfo = clientInfoCallback_(clientId); auto clientInfo = clientInfoCallback_(clientId);
if (!clientInfo) { if (!clientInfo) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, return Api::fail(Api::ErrorCode::NotFound,
"Could not get client info")); "Could not get client info");
} }
const auto& [uid, nickname] = *clientInfo; const auto& [uid, nickname] = *clientInfo;
@@ -1951,21 +1941,20 @@ Subscriptions are persistent across server reconnects.)";
Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId) Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId)
{ {
if (!subscriptionManager_) { if (!subscriptionManager_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized");
"Subscription manager not initialized"));
} }
// Get client UID from the callback // Get client UID from the callback
if (!clientInfoCallback_) { if (!clientInfoCallback_) {
return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized, return Api::fail(Api::ErrorCode::NotInitialized,
"Client info callback not set")); "Client info callback not set");
} }
auto clientInfo = clientInfoCallback_(clientId); auto clientInfo = clientInfoCallback_(clientId);
if (!clientInfo) { if (!clientInfo) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound, return Api::fail(Api::ErrorCode::NotFound,
"Could not get client info")); "Could not get client info");
} }
const auto& [uid, nickname] = *clientInfo; const auto& [uid, nickname] = *clientInfo;
@@ -2000,9 +1989,8 @@ Subscriptions are persistent across server reconnects.)";
MusicManager::unsubscribeByUid(const std::string& uid) MusicManager::unsubscribeByUid(const std::string& uid)
{ {
if (!subscriptionManager_) { if (!subscriptionManager_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized");
"Subscription manager not initialized"));
} }
bool removed = subscriptionManager_->unsubscribe(uid); bool removed = subscriptionManager_->unsubscribe(uid);
@@ -2031,9 +2019,8 @@ Subscriptions are persistent across server reconnects.)";
Api::Result<std::string> MusicManager::clearAllSubscriptions() Api::Result<std::string> MusicManager::clearAllSubscriptions()
{ {
if (!subscriptionManager_) { if (!subscriptionManager_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized");
"Subscription manager not initialized"));
} }
bool cleared = subscriptionManager_->clearAll(); bool cleared = subscriptionManager_->clearAll();
@@ -2251,9 +2238,8 @@ Subscriptions are persistent across server reconnects.)";
MusicManager::downloadAudioForPlayback(const std::string& url) MusicManager::downloadAudioForPlayback(const std::string& url)
{ {
if (!networkClient_) { if (!networkClient_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "NetworkClient not available");
"NetworkClient not available"));
} }
// Create temp file path // Create temp file path
@@ -2272,25 +2258,23 @@ Subscriptions are persistent across server reconnects.)";
auto response = networkClient_->get(url); auto response = networkClient_->get(url);
if (!response) { if (!response) {
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download audio: {}", std::format("Failed to download audio: {}",
response.error().message))); response.error().message));
} }
if (response->statusCode != 200) { if (response->statusCode != 200) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NetworkError, Api::ErrorCode::NetworkError,
std::format("HTTP error {}: {}", response->statusCode, std::format("HTTP error {}: {}", response->statusCode,
response->body.substr(0, 100)))); response->body.substr(0, 100)));
} }
// Write to temp file // Write to temp file
std::ofstream file(tempPath, std::ios::binary); std::ofstream file(tempPath, std::ios::binary);
if (!file) { if (!file) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Failed to create temp file");
"Failed to create temp file"));
} }
file.write(response->body.data(), response->body.size()); file.write(response->body.data(), response->body.size());
+2 -2
View File
@@ -90,8 +90,8 @@ namespace Echoion::Core
auto result = client.send(vreq); auto result = client.send(vreq);
if (!result) { if (!result) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, return Api::fail(Api::ErrorCode::NetworkError,
result.error().message())); result.error().message());
} }
return to_api_response(std::move(*result)); return to_api_response(std::move(*result));
} }
+4 -4
View File
@@ -15,8 +15,8 @@ namespace Echoion::Core
Api::Result<void> RpcServer::start(uint16_t port) Api::Result<void> RpcServer::start(uint16_t port)
{ {
if (running_.exchange(true)) { if (running_.exchange(true)) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, return Api::fail(Api::ErrorCode::AlreadyExists,
"RPC server already running")); "RPC server already running");
} }
port_ = port; port_ = port;
@@ -36,9 +36,9 @@ namespace Echoion::Core
return {}; return {};
} catch (const std::exception& e) { } catch (const std::exception& e) {
running_ = false; running_ = false;
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, Api::ErrorCode::ServiceUnavailable,
std::format("Failed to start RPC server: {}", e.what()))); std::format("Failed to start RPC server: {}", e.what()));
} }
} }
+2 -2
View File
@@ -19,8 +19,8 @@ namespace Echoion::Core
database_ = std::move(database); database_ = std::move(database);
if (!database_) { if (!database_) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Database not available")); Api::ErrorCode::ServiceUnavailable, "Database not available");
} }
// Load existing subscriptions from database // Load existing subscriptions from database
+12 -15
View File
@@ -42,9 +42,8 @@ namespace Echoion::Core
} }
if (!networkClient_) { if (!networkClient_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Network client not available");
"Network client not available"));
} }
// faumaray.ru API endpoint for URL shortening // faumaray.ru API endpoint for URL shortening
@@ -68,17 +67,16 @@ namespace Echoion::Core
if (!response) { if (!response) {
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}", ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
response.error().message)); response.error().message));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, return Api::fail(Api::ErrorCode::NetworkError,
"Failed to shorten URL")); "Failed to shorten URL");
} }
if (!response->isSuccess()) { if (!response->isSuccess()) {
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}", ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
response->statusCode)); response->statusCode));
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}", std::format("Shortening service returned HTTP {}",
response->statusCode))); response->statusCode));
} }
try { try {
@@ -87,9 +85,8 @@ namespace Echoion::Core
auto parsed = Void::Json::parse(response->body); auto parsed = Void::Json::parse(response->body);
if (!parsed) { if (!parsed) {
ECHOION_LOG_WARNING("Failed to parse URL shortening response"); ECHOION_LOG_WARNING("Failed to parse URL shortening response");
return std::unexpected( return Api::fail(Api::ErrorCode::ParseError,
Api::Error(Api::ErrorCode::ParseError, "Failed to parse shortening response");
"Failed to parse shortening response"));
} }
std::string shortenedUrl; std::string shortenedUrl;
@@ -98,8 +95,8 @@ namespace Echoion::Core
shortenedUrl = shortUrl->as_string(); shortenedUrl = shortUrl->as_string();
} else { } else {
ECHOION_LOG_WARNING("No shortUrl field in response"); ECHOION_LOG_WARNING("No shortUrl field in response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError, return Api::fail(Api::ErrorCode::ParseError,
"No shortUrl in response")); "No shortUrl in response");
} }
// Cache the result // Cache the result
@@ -117,8 +114,8 @@ namespace Echoion::Core
} catch (const std::exception& e) { } catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format( ECHOION_LOG_WARNING(std::format(
"Exception parsing shortening response: {}", e.what())); "Exception parsing shortening response: {}", e.what()));
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, "Exception during URL shortening")); Api::ErrorCode::ParseError, "Exception during URL shortening");
} }
} }
+62 -77
View File
@@ -181,9 +181,8 @@ namespace Echoion::Core
Api::Result<void> YouTubeClient::updateYtDlp() Api::Result<void> YouTubeClient::updateYtDlp()
{ {
if (!ytDlpManager_) { if (!ytDlpManager_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "yt-dlp manager not initialized");
"yt-dlp manager not initialized"));
} }
return ytDlpManager_->update(); return ytDlpManager_->update();
} }
@@ -192,19 +191,18 @@ namespace Echoion::Core
YouTubeClient::getAudioStreamUrl(std::string_view videoId) YouTubeClient::getAudioStreamUrl(std::string_view videoId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized");
"YouTubeClient not initialized"));
} }
if (!ytDlpManager_->isAvailable()) { if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available")); Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
} }
if (videoId.empty()) { if (videoId.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Video ID is empty")); "Video ID is empty");
} }
auto startTime = std::chrono::steady_clock::now(); auto startTime = std::chrono::steady_clock::now();
@@ -227,18 +225,16 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) { if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING( ECHOION_LOG_WARNING(
"yt-dlp audio URL extraction timed out after 30s"); "yt-dlp audio URL extraction timed out after 30s");
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError, "yt-dlp audio URL extraction timed out");
"yt-dlp audio URL extraction timed out"));
} }
auto ytdlpResult = future.get(); auto ytdlpResult = future.get();
if (!ytdlpResult.success) { if (!ytdlpResult.success) {
ECHOION_LOG_WARNING("yt-dlp audio URL extraction failed"); ECHOION_LOG_WARNING("yt-dlp audio URL extraction failed");
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError, "yt-dlp audio URL extraction failed");
"yt-dlp audio URL extraction failed"));
} }
std::string result = ytdlpResult.output; std::string result = ytdlpResult.output;
@@ -259,8 +255,8 @@ namespace Echoion::Core
ECHOION_LOG_WARNING(std::format( ECHOION_LOG_WARNING(std::format(
"Failed to get audio URL from yt-dlp after {} ms", elapsed)); "Failed to get audio URL from yt-dlp after {} ms", elapsed));
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp")); Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp");
} }
Api::Result<std::string> Api::Result<std::string>
@@ -273,20 +269,19 @@ namespace Echoion::Core
YouTubeClient::getVideoInfo(std::string_view videoId) YouTubeClient::getVideoInfo(std::string_view videoId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized");
"YouTubeClient not initialized"));
} }
if (!ytDlpManager_->isAvailable()) { if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available")); Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
} }
// Validate video ID // Validate video ID
if (videoId.empty()) { if (videoId.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Video ID is empty")); "Video ID is empty");
} }
ECHOION_LOG_DEBUG( ECHOION_LOG_DEBUG(
@@ -304,8 +299,8 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) { if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("yt-dlp video info timed out after 30s"); ECHOION_LOG_WARNING("yt-dlp video info timed out after 30s");
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp video info timed out")); "yt-dlp video info timed out");
} }
auto ytdlpResult = result.get(); auto ytdlpResult = result.get();
@@ -317,17 +312,15 @@ namespace Echoion::Core
.count())); .count()));
if (!ytdlpResult.success || ytdlpResult.output.empty()) { if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError, "yt-dlp failed to get video info");
"yt-dlp failed to get video info"));
} }
try { try {
auto parsed = Void::Json::parse(ytdlpResult.output); auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) { if (!parsed) {
return std::unexpected( return Api::fail(Api::ErrorCode::ParseError,
Api::Error(Api::ErrorCode::ParseError, "Failed to parse yt-dlp output");
"Failed to parse yt-dlp output"));
} }
const JValue& json = *parsed; const JValue& json = *parsed;
@@ -354,9 +347,9 @@ namespace Echoion::Core
return info; return info;
} catch (const std::exception& e) { } catch (const std::exception& e) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp output: {}", e.what()))); std::format("Exception parsing yt-dlp output: {}", e.what()));
} }
} }
@@ -397,9 +390,8 @@ namespace Echoion::Core
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized");
"YouTubeClient not initialized"));
} }
auto startTime = std::chrono::steady_clock::now(); auto startTime = std::chrono::steady_clock::now();
@@ -433,9 +425,8 @@ namespace Echoion::Core
{ {
std::lock_guard<std::mutex> lock(configMutex_); std::lock_guard<std::mutex> lock(configMutex_);
if (!apiKey_.has_value() || apiKey_->empty()) { if (!apiKey_.has_value() || apiKey_->empty()) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTube API key not configured");
"YouTube API key not configured"));
} }
apiKey = *apiKey_; apiKey = *apiKey_;
} }
@@ -477,8 +468,8 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) { if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("YouTube API search timed out after 10s"); ECHOION_LOG_WARNING("YouTube API search timed out after 10s");
apiThread.detach(); // Thread owns shared_ptr, safe to detach apiThread.detach(); // Thread owns shared_ptr, safe to detach
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, return Api::fail(Api::ErrorCode::NetworkError,
"YouTube API search timed out")); "YouTube API search timed out");
} }
ECHOION_LOG_DEBUG("Joining API request thread..."); ECHOION_LOG_DEBUG("Joining API request thread...");
@@ -492,9 +483,8 @@ namespace Echoion::Core
} catch (const std::exception& e) { } catch (const std::exception& e) {
ECHOION_LOG_ERROR( ECHOION_LOG_ERROR(
std::format("API request threw exception: {}", e.what())); std::format("API request threw exception: {}", e.what()));
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError, std::format("API request failed: {}", e.what()));
std::format("API request failed: {}", e.what())));
} }
// Log response status // Log response status
@@ -507,19 +497,18 @@ namespace Echoion::Core
} }
if (!response || !response->isSuccess()) { if (!response || !response->isSuccess()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NetworkError, Api::ErrorCode::NetworkError,
std::format("YouTube API search failed: {}", std::format("YouTube API search failed: {}",
response ? std::to_string(response->statusCode) response ? std::to_string(response->statusCode)
: "no response"))); : "no response"));
} }
try { try {
auto parsed = Void::Json::parse(response->body); auto parsed = Void::Json::parse(response->body);
if (!parsed) { if (!parsed) {
return std::unexpected( return Api::fail(Api::ErrorCode::ParseError,
Api::Error(Api::ErrorCode::ParseError, "Failed to parse YouTube API search response");
"Failed to parse YouTube API search response"));
} }
const JValue& json = *parsed; const JValue& json = *parsed;
@@ -608,10 +597,10 @@ namespace Echoion::Core
return result; return result;
} catch (const std::exception& e) { } catch (const std::exception& e) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Exception parsing YouTube API search: {}", std::format("Exception parsing YouTube API search: {}",
e.what()))); e.what()));
} }
} }
@@ -738,8 +727,8 @@ namespace Echoion::Core
{ {
if (!ytDlpManager_->isAvailable()) { if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available")); Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
} }
ECHOION_LOG_DEBUG("Starting yt-dlp search..."); ECHOION_LOG_DEBUG("Starting yt-dlp search...");
@@ -757,8 +746,8 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) { if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("yt-dlp search timed out after 30s"); ECHOION_LOG_WARNING("yt-dlp search timed out after 30s");
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp search timed out")); "yt-dlp search timed out");
} }
auto ytdlpResult = result.get(); auto ytdlpResult = result.get();
@@ -770,16 +759,15 @@ namespace Echoion::Core
std::format("yt-dlp search completed in {} ms", elapsed)); std::format("yt-dlp search completed in {} ms", elapsed));
if (!ytdlpResult.success || ytdlpResult.output.empty()) { if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp search failed")); "yt-dlp search failed");
} }
try { try {
auto parsed = Void::Json::parse(ytdlpResult.output); auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) { if (!parsed) {
return std::unexpected( return Api::fail(Api::ErrorCode::ParseError,
Api::Error(Api::ErrorCode::ParseError, "Failed to parse yt-dlp search output");
"Failed to parse yt-dlp search output"));
} }
const JValue& json = *parsed; const JValue& json = *parsed;
@@ -829,9 +817,9 @@ namespace Echoion::Core
return searchResult; return searchResult;
} catch (const std::exception& e) { } catch (const std::exception& e) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp search: {}", e.what()))); std::format("Exception parsing yt-dlp search: {}", e.what()));
} }
} }
@@ -839,9 +827,8 @@ namespace Echoion::Core
YouTubeClient::getPlaylist(std::string_view playlistId) YouTubeClient::getPlaylist(std::string_view playlistId)
{ {
if (!initialized_) { if (!initialized_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized");
"YouTubeClient not initialized"));
} }
ECHOION_LOG_INFO(std::format("Fetching playlist: {}", playlistId)); ECHOION_LOG_INFO(std::format("Fetching playlist: {}", playlistId));
@@ -1113,8 +1100,8 @@ namespace Echoion::Core
ECHOION_LOG_INFO("Using yt-dlp for playlist fetch"); ECHOION_LOG_INFO("Using yt-dlp for playlist fetch");
if (!ytDlpManager_->isAvailable()) { if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available")); Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
} }
std::string url = std::string url =
@@ -1126,17 +1113,15 @@ namespace Echoion::Core
auto ytdlpResult = result.get(); auto ytdlpResult = result.get();
if (!ytdlpResult.success || ytdlpResult.output.empty()) { if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError, "Failed to fetch playlist via yt-dlp");
"Failed to fetch playlist via yt-dlp"));
} }
try { try {
auto parsed = Void::Json::parse(ytdlpResult.output); auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) { if (!parsed) {
return std::unexpected( return Api::fail(Api::ErrorCode::ParseError,
Api::Error(Api::ErrorCode::ParseError, "Failed to parse yt-dlp playlist output");
"Failed to parse yt-dlp playlist output"));
} }
const JValue& json = *parsed; const JValue& json = *parsed;
@@ -1168,9 +1153,9 @@ namespace Echoion::Core
return items; return items;
} catch (const std::exception& e) { } catch (const std::exception& e) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Exception parsing playlist: {}", e.what()))); std::format("Exception parsing playlist: {}", e.what()));
} }
} }
+20 -27
View File
@@ -112,11 +112,11 @@ namespace Echoion::Core
try { try {
std::filesystem::create_directories(storageDir); std::filesystem::create_directories(storageDir);
} catch (const std::exception& e) { } catch (const std::exception& e) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, Api::ErrorCode::ServiceUnavailable,
std::format( std::format(
"Failed to create yt-dlp storage directory: {}", "Failed to create yt-dlp storage directory: {}",
e.what()))); e.what()));
} }
} }
@@ -155,9 +155,8 @@ namespace Echoion::Core
ECHOION_LOG_INFO("Checking yt-dlp version..."); ECHOION_LOG_INFO("Checking yt-dlp version...");
std::string version = getVersion(); std::string version = getVersion();
if (version.empty()) { if (version.empty()) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "yt-dlp executable not working");
"yt-dlp executable not working"));
} }
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version)); ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
@@ -315,9 +314,8 @@ namespace Echoion::Core
Api::Result<void> YtDlpManager::downloadYtDlp() Api::Result<void> YtDlpManager::downloadYtDlp()
{ {
if (!networkClient_) { if (!networkClient_) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Network client not available");
"Network client not available"));
} }
std::string downloadUrl = getDownloadUrl(); std::string downloadUrl = getDownloadUrl();
@@ -336,10 +334,9 @@ namespace Echoion::Core
while (redirectCount < maxRedirects) { while (redirectCount < maxRedirects) {
auto result = networkClient_->get(downloadUrl, headers); auto result = networkClient_->get(downloadUrl, headers);
if (!result) { if (!result) {
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: {}", std::format("Failed to download yt-dlp: {}",
result.error().message))); result.error().message));
} }
response = std::move(*result); response = std::move(*result);
@@ -348,9 +345,9 @@ namespace Echoion::Core
if (response.statusCode >= 300 && response.statusCode < 400) { if (response.statusCode >= 300 && response.statusCode < 400) {
auto location = response.getHeader("location"); auto location = response.getHeader("location");
if (!location.has_value()) { if (!location.has_value()) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::NetworkError, Api::ErrorCode::NetworkError,
"Redirect response missing Location header")); "Redirect response missing Location header");
} }
// Handle relative URLs // Handle relative URLs
@@ -379,10 +376,9 @@ namespace Echoion::Core
} }
if (!response.isSuccess()) { if (!response.isSuccess()) {
return std::unexpected( return Api::fail(Api::ErrorCode::NetworkError,
Api::Error(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: HTTP {}", std::format("Failed to download yt-dlp: HTTP {}",
response.statusCode))); response.statusCode));
} }
ECHOION_LOG_INFO( ECHOION_LOG_INFO(
@@ -392,16 +388,15 @@ namespace Echoion::Core
try { try {
std::ofstream file(executablePath_, std::ios::binary); std::ofstream file(executablePath_, std::ios::binary);
if (!file) { if (!file) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Failed to open yt-dlp file for writing");
"Failed to open yt-dlp file for writing"));
} }
file.write(response.body.data(), response.body.size()); file.write(response.body.data(), response.body.size());
file.close(); file.close();
} catch (const std::exception& e) { } catch (const std::exception& e) {
return std::unexpected(Api::Error( return Api::fail(
Api::ErrorCode::ServiceUnavailable, Api::ErrorCode::ServiceUnavailable,
std::format("Failed to write yt-dlp file: {}", e.what()))); std::format("Failed to write yt-dlp file: {}", e.what()));
} }
// Make executable on Unix // Make executable on Unix
@@ -434,9 +429,8 @@ namespace Echoion::Core
#else #else
if (chmod(executablePath_.c_str(), if (chmod(executablePath_.c_str(),
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Failed to make yt-dlp executable");
"Failed to make yt-dlp executable"));
} }
return {}; return {};
#endif #endif
@@ -513,9 +507,8 @@ namespace Echoion::Core
// Verify new version works // Verify new version works
std::string version = getVersion(); std::string version = getVersion();
if (version.empty()) { if (version.empty()) {
return std::unexpected( return Api::fail(Api::ErrorCode::ServiceUnavailable,
Api::Error(Api::ErrorCode::ServiceUnavailable, "Updated yt-dlp not working");
"Updated yt-dlp not working"));
} }
ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version)); ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version));
+6 -6
View File
@@ -18,13 +18,13 @@ namespace Echoion::Core
if (fromVersion == 0) { if (fromVersion == 0) {
auto parsed = Void::Json::parse(jsonData); auto parsed = Void::Json::parse(jsonData);
if (!parsed) { if (!parsed) {
return std::unexpected(Api::Error{Api::ErrorCode::ParseError, return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse V0 state"}); "Failed to parse V0 state");
} }
auto v0 = Void::Json::from_json<StateV0>(*parsed); auto v0 = Void::Json::from_json<StateV0>(*parsed);
if (!v0) { if (!v0) {
return std::unexpected(Api::Error{Api::ErrorCode::ParseError, return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse V0 state"}); "Failed to parse V0 state");
} }
return fromV0(*v0); return fromV0(*v0);
} }
@@ -32,9 +32,9 @@ namespace Echoion::Core
// Add more migrations here as versions evolve // Add more migrations here as versions evolve
// if (fromVersion == 1) { return fromV1(...); } // if (fromVersion == 1) { return fromV1(...); }
return std::unexpected(Api::Error{ return Api::fail(
Api::ErrorCode::IncompatibleVersion, Api::ErrorCode::IncompatibleVersion,
std::format("No migration path from version {}", fromVersion)}); std::format("No migration path from version {}", fromVersion));
} }
StateV1 StateMigration::fromV0(const StateV0& v0) StateV1 StateMigration::fromV0(const StateV0& v0)
+10 -10
View File
@@ -27,8 +27,8 @@ namespace Echoion::Core
StateSerializer::deserialize(const Api::StateBlob& blob) StateSerializer::deserialize(const Api::StateBlob& blob)
{ {
if (blob.data.empty()) { if (blob.data.empty()) {
return std::unexpected(Api::Error{Api::ErrorCode::InvalidArgument, return Api::fail(Api::ErrorCode::InvalidArgument,
"Empty state blob"}); "Empty state blob");
} }
// Convert blob to string // Convert blob to string
@@ -40,18 +40,18 @@ namespace Echoion::Core
// Check if version is supported // Check if version is supported
if (!isVersionSupported(dataVersion)) { if (!isVersionSupported(dataVersion)) {
if (dataVersion > CURRENT_VERSION) { if (dataVersion > CURRENT_VERSION) {
return std::unexpected(Api::Error{ return Api::fail(
Api::ErrorCode::IncompatibleVersion, Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is from a newer Core. " std::format("State version {} is from a newer Core. "
"Please update/restart to load this state.", "Please update/restart to load this state.",
dataVersion)}); dataVersion));
} else { } else {
return std::unexpected(Api::Error{ return Api::fail(
Api::ErrorCode::IncompatibleVersion, Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is too old. " std::format("State version {} is too old. "
"Maximum supported age is {} versions.", "Maximum supported age is {} versions.",
dataVersion, dataVersion,
Api::MAX_SUPPORTED_STATE_VERSION_AGE)}); Api::MAX_SUPPORTED_STATE_VERSION_AGE));
} }
} }
@@ -59,18 +59,18 @@ namespace Echoion::Core
if (dataVersion == CURRENT_VERSION) { if (dataVersion == CURRENT_VERSION) {
auto parsed = Void::Json::parse(jsonStr); auto parsed = Void::Json::parse(jsonStr);
if (!parsed) { if (!parsed) {
return std::unexpected(Api::Error{ return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to parse state ({}:{}): {}", std::format("Failed to parse state ({}:{}): {}",
parsed.error().line, parsed.error().col, parsed.error().line, parsed.error().col,
parsed.error().message)}); parsed.error().message));
} }
auto state = Void::Json::from_json<StateV1>(*parsed); auto state = Void::Json::from_json<StateV1>(*parsed);
if (!state) { if (!state) {
return std::unexpected(Api::Error{ return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
std::format("Failed to decode state: field '{}': {}", std::format("Failed to decode state: field '{}': {}",
state.error().field, state.error().message)}); state.error().field, state.error().message));
} }
return *state; return *state;
} }