Compare commits

...
3 Commits
Author SHA1 Message Date
faumarayandClaude Opus 4.8 6c7e6a170f Use Void::Json typed accessors instead of local jHelpers
Replace YouTubeClient's local jHas/jStr/jNum/jObj/jArr free-function helpers
(and their ~77 call sites) with the new Void::Json::Value member accessors
has/get_str/get_num/child_object/child_array. Same safe semantics
(missing/wrong-type → default/nullptr), now shared across the project.

Requires the VoidLibrary re-pin that adds the accessors.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:15:36 +03:00
faumarayandClaude Opus 4.8 23759899bb 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>
2026-06-22 22:07:18 +03:00
faumarayandClaude Opus 4.8 f8757d6040 Inline 4 trivial Void delegation shims
Remove YouTubeClient::urlEncode/decodeHtmlEntities/parseIso8601Duration and
StateSerializer::getCurrentTimestampISO8601 — each just forwarded to one Void
call — and have the ~12 call sites call Void directly
(Void::Encoding::Url::encode, Void::Text::html_unescape,
Void::Time::parse_iso8601_interval(...).value_or(0), Void::Time::utc_now_iso8601).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 22:04:43 +03:00
16 changed files with 429 additions and 590 deletions

No files matched your search

+4 -4
View File
@@ -98,18 +98,18 @@ namespace Echoion::Core
{
auto parsed = Void::Json::parse(body);
if (!parsed) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("JSON parse error ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)));
parsed.error().message));
}
auto value = Void::Json::from_json<T>(*parsed);
if (!value) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("JSON decode error: field '{}': {}",
value.error().field, value.error().message)));
value.error().field, value.error().message));
}
return std::move(*value);
}
-9
View File
@@ -135,15 +135,6 @@ namespace Echoion::Core
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
const std::vector<std::string>& videoIds);
// Parse ISO 8601 duration string
[[nodiscard]] static std::chrono::seconds
parseIso8601Duration(const std::string& duration);
// URL encode/decode helpers
[[nodiscard]] static std::string urlEncode(std::string_view value);
[[nodiscard]] static std::string
decodeHtmlEntities(std::string_view value);
// Internal methods for playlist resolution
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
fetchPlaylistItems(std::string_view playlistId);
@@ -33,9 +33,6 @@ namespace Echoion::Core
// Extract version from JSON blob
static uint32_t extractVersion(const std::string& jsonStr);
// Helper to get current timestamp
static std::string getCurrentTimestampISO8601();
// Make it accessible to StateMigration
friend class StateMigration;
};
+33 -46
View File
@@ -75,16 +75,15 @@ namespace Echoion::Core
hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
break;
default:
return std::unexpected(
Api::Error(Api::ErrorCode::InvalidArgument,
"Unsupported hardware acceleration type"));
return Api::fail(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(
return Api::fail(
Api::ErrorCode::NotSupported,
"Hardware acceleration not available on this system"));
"Hardware acceleration not available on this system");
}
hwAccelType_ = config.type;
@@ -122,8 +121,8 @@ namespace Echoion::Core
Api::Result<void> AudioDecoder::openSource(const std::string& url)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Decoder not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Decoder not initialized");
}
std::lock_guard<std::mutex> lock(mutex_);
@@ -192,9 +191,8 @@ namespace Echoion::Core
// 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"));
return Api::fail(Api::ErrorCode::AudioError,
"Failed to allocate format context");
}
// Set up interrupt callback to allow graceful shutdown during blocking
@@ -218,11 +216,11 @@ namespace Echoion::Core
av_strerror(ret, errbuf, sizeof(errbuf));
ECHOION_LOG_ERROR(std::format(
"FFmpeg failed to open input (error {}): {}", ret, errbuf));
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::AudioError,
std::format(
"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");
@@ -234,9 +232,9 @@ namespace Echoion::Core
std::format("FFmpeg failed to find stream info (error {}): {}",
ret, errbuf));
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::AudioError,
std::format("Failed to find stream info: {}", errbuf)));
std::format("Failed to find stream info: {}", errbuf));
}
const AVCodec* decoder = nullptr;
audioStreamIndex_ = -1;
@@ -246,16 +244,15 @@ namespace Echoion::Core
if (audioStreamIndex_ == -1) {
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(Api::ErrorCode::AudioError,
"No audio stream found"));
return Api::fail(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"));
return Api::fail(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;
@@ -265,16 +262,15 @@ namespace Echoion::Core
if (ret < 0) {
avcodec_free_context(&codecContext_);
avformat_close_input(&formatContext_);
return std::unexpected(Api::Error(
Api::ErrorCode::AudioError, "Failed to copy codec parameters"));
return Api::fail(
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"));
return Api::fail(Api::ErrorCode::AudioError, "Failed to open codec");
}
frame_ = av_frame_alloc();
@@ -282,8 +278,8 @@ namespace Echoion::Core
if (!frame_ || !packet_) {
cleanupFfmpeg();
return std::unexpected(Api::Error(
Api::ErrorCode::AudioError, "Failed to allocate frame/packet"));
return Api::fail(
Api::ErrorCode::AudioError, "Failed to allocate frame/packet");
}
streamInfo_.sampleRate = codecContext_->sample_rate;
@@ -338,8 +334,8 @@ namespace Echoion::Core
}
if (ret < 0 || swr_init(swrContext_) < 0) {
cleanupFfmpeg();
return std::unexpected(Api::Error(
Api::ErrorCode::AudioError, "Failed to initialize resampler"));
return Api::fail(
Api::ErrorCode::AudioError, "Failed to initialize resampler");
}
// Allocate output buffer for S16 samples (like reference)
@@ -401,12 +397,10 @@ namespace Echoion::Core
}
if (eof_) {
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "End of stream"));
return Api::fail(Api::ErrorCode::AudioError, "End of stream");
}
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "Decoder stopped"));
return Api::fail(Api::ErrorCode::AudioError, "Decoder stopped");
}
static int callCount = 0;
@@ -443,8 +437,7 @@ namespace Echoion::Core
Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position)
{
if (!formatContext_ || audioStreamIndex_ < 0) {
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "No source open"));
return Api::fail(Api::ErrorCode::AudioError, "No source open");
}
std::lock_guard<std::mutex> lock(mutex_);
@@ -454,8 +447,7 @@ namespace Echoion::Core
av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
if (ret < 0) {
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "Seek failed"));
return Api::fail(Api::ErrorCode::AudioError, "Seek failed");
}
avcodec_flush_buffers(codecContext_);
@@ -472,8 +464,7 @@ namespace Echoion::Core
Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const
{
if (!initialized_ || !formatContext_) {
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "No source open"));
return Api::fail(Api::ErrorCode::AudioError, "No source open");
}
return streamInfo_;
}
@@ -629,18 +620,15 @@ namespace Echoion::Core
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"));
return Api::fail(Api::ErrorCode::AudioError, "End of file");
}
if (ret == AVERROR_EXIT) {
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "Interrupted"));
return Api::fail(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)));
return Api::fail(Api::ErrorCode::AudioError,
std::format("Error reading frame: {}", errbuf));
}
if (packet_->stream_index != audioStreamIndex_) {
@@ -698,8 +686,7 @@ namespace Echoion::Core
int converted = swr_convert(swrContext_, &outData, outSamples, inData,
frame_->nb_samples);
if (converted < 0) {
return std::unexpected(
Api::Error(Api::ErrorCode::AudioError, "Resampling failed"));
return Api::fail(Api::ErrorCode::AudioError, "Resampling failed");
}
outputBuffer.resize(converted * outputChannels_);
+10 -13
View File
@@ -20,18 +20,16 @@ namespace Echoion::Core
ConfigLoader::loadFromFile(const std::filesystem::path& path)
{
if (!std::filesystem::exists(path)) {
return std::unexpected(
Api::Error(Api::ErrorCode::NotFound,
return Api::fail(Api::ErrorCode::NotFound,
std::format("Configuration file not found: {}",
path.string())));
path.string()));
}
std::ifstream file(path);
if (!file.is_open()) {
return std::unexpected(
Api::Error(Api::ErrorCode::PermissionDenied,
return Api::fail(Api::ErrorCode::PermissionDenied,
std::format("Failed to open configuration file: {}",
path.string())));
path.string()));
}
std::string content((std::istreambuf_iterator<char>(file)),
@@ -40,11 +38,11 @@ namespace Echoion::Core
auto parsed = Void::Json::parse(content);
if (!parsed) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse configuration ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)));
parsed.error().message));
}
// 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}).
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
if (!jsonResult) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse configuration: field '{}': {}",
jsonResult.error().field,
jsonResult.error().message)));
jsonResult.error().message));
}
AppConfigJson jsonConfig = std::move(*jsonResult);
@@ -294,10 +292,9 @@ namespace Echoion::Core
Void::Json::to_json(jsonConfig), {.pretty = true});
std::ofstream file(path);
if (!file.is_open()) {
return std::unexpected(
Api::Error(Api::ErrorCode::PermissionDenied,
return Api::fail(Api::ErrorCode::PermissionDenied,
std::format("Failed to write configuration file: {}",
path.string())));
path.string()));
}
file << json;
+87 -91
View File
@@ -41,8 +41,8 @@ namespace Echoion::Core
Api::Result<void> Core::initialize(const std::filesystem::path& configPath)
{
if (initialized_) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
"Core already initialized"));
return Api::fail(Api::ErrorCode::AlreadyExists,
"Core already initialized");
}
auto logger = std::make_shared<Logger>();
logger->setMinLevel(Api::LogLevel::Debug);
@@ -412,8 +412,8 @@ namespace Echoion::Core
Api::Result<void> Core::playTrack(const Api::TrackInfo& track)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->queueTrack(track, 0);
@@ -445,8 +445,8 @@ namespace Echoion::Core
Api::Result<void> Core::play(const std::string& trackId)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
// Resolve track ID to TrackInfo via MusicManager
@@ -461,8 +461,8 @@ namespace Echoion::Core
Api::Result<void> Core::pause()
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->pause();
@@ -478,8 +478,8 @@ namespace Echoion::Core
Api::Result<void> Core::resume()
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->resume();
@@ -495,8 +495,8 @@ namespace Echoion::Core
Api::Result<void> Core::stop()
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->stop();
@@ -512,8 +512,8 @@ namespace Echoion::Core
Api::Result<void> Core::skip(uint32_t count)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->skip(count);
@@ -529,8 +529,8 @@ namespace Echoion::Core
Api::Result<void> Core::seek(std::chrono::milliseconds position)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
return musicManager_->seek(position);
@@ -539,8 +539,8 @@ namespace Echoion::Core
Api::Result<void> Core::setVolume(float volume)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
return musicManager_->setVolume(volume);
@@ -550,8 +550,8 @@ namespace Echoion::Core
uint64_t clientId)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->queueTrack(track, clientId);
@@ -572,8 +572,8 @@ namespace Echoion::Core
uint64_t clientId)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
// Use MusicManager::play to resolve trackId and get TrackInfo
@@ -592,8 +592,8 @@ namespace Echoion::Core
Api::Result<void> Core::removeFromQueue(uint64_t queueId)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
// Find position by queueId
@@ -608,15 +608,14 @@ namespace Echoion::Core
}
}
return std::unexpected(
Api::Error(Api::ErrorCode::NotFound, "Track not found in queue"));
return Api::fail(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"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->clearQueue();
@@ -632,8 +631,8 @@ namespace Echoion::Core
Api::Result<std::vector<Api::QueueEntry>> Core::getQueue() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
return musicManager_->getQueue();
@@ -642,8 +641,8 @@ namespace Echoion::Core
Api::Result<std::vector<Api::TrackSummary>> Core::getQueueSummaries() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto queue = musicManager_->getQueue();
@@ -666,8 +665,8 @@ namespace Echoion::Core
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
// Find current position
@@ -687,8 +686,8 @@ namespace Echoion::Core
}
if (!found) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
"Track not found in queue"));
return Api::fail(Api::ErrorCode::NotFound,
"Track not found in queue");
}
return musicManager_->moveInQueue(fromPosition, newPosition);
@@ -697,8 +696,8 @@ namespace Echoion::Core
Api::Result<std::optional<Api::QueueEntry>> Core::getCurrentTrack() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
return musicManager_->getCurrentTrack();
@@ -708,8 +707,8 @@ namespace Echoion::Core
Core::getCurrentTrackSummary() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto current = musicManager_->getCurrentTrack();
@@ -731,8 +730,8 @@ namespace Echoion::Core
Api::Result<Api::PlaybackState> Core::getPlaybackState() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
return musicManager_->getPlaybackState();
@@ -741,8 +740,8 @@ namespace Echoion::Core
Api::Result<Api::PlaybackSummary> Core::getPlaybackSummary() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto state = musicManager_->getPlaybackState();
@@ -773,8 +772,8 @@ namespace Echoion::Core
uint64_t clientId)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto result = musicManager_->loadPlaylist(playlistId, clientId);
@@ -787,8 +786,8 @@ namespace Echoion::Core
Api::Result<std::vector<Api::PlaylistInfo>> Core::getPlaylists() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
return musicManager_->getPlaylists();
@@ -797,8 +796,8 @@ namespace Echoion::Core
Api::Result<std::vector<std::string>> Core::getPlaylistIds() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto playlists = musicManager_->getPlaylists();
@@ -845,19 +844,19 @@ namespace Echoion::Core
// Parse JSON config using Void::Json reflection
auto parsed = Void::Json::parse(configJson);
if (!parsed) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)));
parsed.error().message));
}
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
if (!jsonResult.has_value()) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON: field '{}': {}",
jsonResult.error().field,
jsonResult.error().message)));
jsonResult.error().message));
}
// Convert to AppConfig
@@ -976,13 +975,13 @@ namespace Echoion::Core
Api::Result<void> Core::reloadConfig()
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
if (configPath_.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Config path not set"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Config path not set");
}
// Reload config from disk
@@ -1007,8 +1006,8 @@ namespace Echoion::Core
Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull()
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Preparing for hot reload...");
@@ -1025,8 +1024,8 @@ namespace Echoion::Core
Core::restoreAfterHotReloadFull(const Api::HotReloadState& state)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Restoring after hot reload...");
@@ -1048,8 +1047,8 @@ namespace Echoion::Core
Api::Result<std::string> Core::prepareForHotReload()
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Preparing for hot reload (decoupled)...");
@@ -1068,8 +1067,8 @@ namespace Echoion::Core
Api::Result<void> Core::restoreAfterHotReload(const std::string& state)
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
ECHOION_LOG_INFO("Restoring after hot reload (decoupled)...");
@@ -1077,20 +1076,20 @@ namespace Echoion::Core
// Deserialize state from JSON
auto parsed = Void::Json::parse(state);
if (!parsed) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse hot reload state ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)));
parsed.error().message));
}
auto stateResult = Void::Json::from_json<Api::HotReloadState>(*parsed);
if (!stateResult.has_value()) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to deserialize hot reload state: "
"field '{}': {}",
stateResult.error().field,
stateResult.error().message)));
stateResult.error().message));
}
auto result = musicManager_->restoreFromHotReload(stateResult.value());
@@ -1223,8 +1222,8 @@ namespace Echoion::Core
Core::getCurrentTrackHandle() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto current = musicManager_->getCurrentTrack();
@@ -1246,8 +1245,8 @@ namespace Echoion::Core
Core::getQueueHandles() const
{
if (!initialized_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
auto queue = musicManager_->getQueue();
@@ -1274,8 +1273,8 @@ namespace Echoion::Core
Api::Result<void> Core::updateConfigFromHandle(Api::AppConfigHandle config)
{
if (!config.isValid()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Invalid config handle"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid config handle");
}
// Update from the handle
@@ -1307,8 +1306,8 @@ namespace Echoion::Core
"(this={}), ignoring event type={}",
reinterpret_cast<uintptr_t>(this),
static_cast<int>(event.type)));
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Core not initialized"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Core not initialized");
}
// Debug logging for command events
@@ -1628,16 +1627,14 @@ namespace Echoion::Core
// Parse JSON params
auto parsedParams = Void::Json::parse(params);
if (!parsedParams) {
return std::unexpected(
Api::Error(Api::ErrorCode::InvalidArgument,
"Invalid authentication request format"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid authentication request format");
}
auto reqResult =
Void::Json::from_json<RpcAuthRequest>(*parsedParams);
if (!reqResult) {
return std::unexpected(
Api::Error(Api::ErrorCode::InvalidArgument,
"Invalid authentication request format"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid authentication request format");
}
const RpcAuthRequest& req = *reqResult;
@@ -1653,8 +1650,8 @@ namespace Echoion::Core
"{\"success\":true,\"message\":\"Authentication "
"successful\"}");
} else {
return std::unexpected(Api::Error(
Api::ErrorCode::PermissionDenied, "Invalid token"));
return Api::fail(
Api::ErrorCode::PermissionDenied, "Invalid token");
}
}
@@ -1668,10 +1665,10 @@ namespace Echoion::Core
}
if (!uidResult->has_value()) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::NotFound,
"Subscriber not found. Please subscribe to the bot "
"first using !subscribe command."));
"first using !subscribe command.");
}
const std::string& uid = **uidResult;
@@ -1736,10 +1733,9 @@ namespace Echoion::Core
"TeamSpeak PM. Please check your private messages.\"}");
}
return std::unexpected(
Api::Error(Api::ErrorCode::InvalidArgument,
return Api::fail(Api::ErrorCode::InvalidArgument,
"Authentication request must include either "
"'nickname' or 'token'"));
"'nickname' or 'token'");
});
// Playback control
+35 -65
View File
@@ -51,10 +51,9 @@ namespace Echoion::Api
auto opened = Void::Sqlite::Database::open(
config.path, Void::Sqlite::OpenMode::ReadWriteCreate);
if (!opened) {
return std::unexpected(
Error(ErrorCode::DatabaseError,
return fail(ErrorCode::DatabaseError,
std::format("Failed to open database: {}",
opened.error().message())));
opened.error().message()));
}
impl_->voidDb = std::move(*opened);
impl_->db = impl_->voidDb.handle();
@@ -120,7 +119,7 @@ namespace Echoion::Api
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
return fail(ErrorCode::DatabaseError, error);
}
// Get current version
@@ -200,7 +199,7 @@ namespace Echoion::Api
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
return fail(ErrorCode::DatabaseError, error);
}
sqlite3_exec(impl_->db,
@@ -228,7 +227,7 @@ namespace Echoion::Api
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
return fail(ErrorCode::DatabaseError, error);
}
sqlite3_exec(impl_->db,
@@ -290,7 +289,7 @@ namespace Echoion::Api
if (errMsg) {
std::string error = errMsg;
sqlite3_free(errMsg);
return std::unexpected(Error(ErrorCode::DatabaseError, error));
return fail(ErrorCode::DatabaseError, error);
}
sqlite3_exec(impl_->db,
@@ -327,8 +326,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
@@ -341,8 +339,7 @@ namespace Echoion::Api
if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt);
return std::unexpected(
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
uint64_t id =
@@ -398,8 +395,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
@@ -473,8 +469,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -502,8 +497,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(id));
@@ -528,8 +522,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(playlistId));
@@ -573,8 +566,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, track.originalUrl.c_str(), -1,
@@ -610,8 +602,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -651,8 +642,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -677,8 +667,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -700,8 +689,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -728,8 +716,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(userId));
@@ -766,8 +753,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(keepCount));
@@ -821,8 +807,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -841,8 +826,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -860,8 +844,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -882,8 +865,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
while (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -917,8 +899,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
size_t count = 0;
@@ -1020,16 +1001,14 @@ namespace Echoion::Api
if (sqlite3_prepare_v2(impl_->db,
"SELECT 1 FROM subscriptions WHERE uid = ?", -1,
&checkStmt, nullptr) != SQLITE_OK) {
return std::unexpected(
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(checkStmt, 1, uid.c_str(), -1, SQLITE_STATIC);
bool exists = sqlite3_step(checkStmt) == SQLITE_ROW;
sqlite3_finalize(checkStmt);
if (!exists) {
return std::unexpected(
Error(ErrorCode::NotFound, "Subscriber not found"));
return fail(ErrorCode::NotFound, "Subscriber not found");
}
// Generate a random 32-character alphanumeric token (Void::Random is
@@ -1045,8 +1024,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
@@ -1054,8 +1032,7 @@ namespace Echoion::Api
if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt);
return std::unexpected(
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_finalize(stmt);
@@ -1074,8 +1051,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
@@ -1104,8 +1080,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
@@ -1143,8 +1118,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
@@ -1174,8 +1148,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, nickname.c_str(), -1, SQLITE_STATIC);
@@ -1204,16 +1177,14 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_bind_text(stmt, 1, token.c_str(), -1, SQLITE_STATIC);
if (sqlite3_step(stmt) != SQLITE_DONE) {
sqlite3_finalize(stmt);
return std::unexpected(
Error(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
sqlite3_finalize(stmt);
@@ -1231,8 +1202,7 @@ namespace Echoion::Api
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)));
return fail(ErrorCode::DatabaseError, sqlite3_errmsg(impl_->db));
}
std::vector<std::string> uids;
+57 -73
View File
@@ -317,8 +317,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_ || isPaused_) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Nothing is playing"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
// Capture current position before pausing
@@ -334,8 +334,7 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_ || !isPaused_) {
return std::unexpected(
Api::Error(Api::ErrorCode::InvalidArgument, "Not paused"));
return Api::fail(Api::ErrorCode::InvalidArgument, "Not paused");
}
// Reset time tracking from current position
@@ -410,8 +409,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_);
if (!isPlaying_) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Nothing is playing"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
for (uint32_t i = 0; i < count; ++i) {
@@ -458,8 +457,8 @@ namespace Echoion::Core
Api::Result<void> MusicManager::seek(std::chrono::milliseconds position)
{
if (!isPlaying_) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Nothing is playing"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Nothing is playing");
}
auto result = audioDecoder_->seek(position);
@@ -485,8 +484,8 @@ namespace Echoion::Core
Api::Result<void> MusicManager::setVolume(float volume)
{
if (volume < 0.0f || volume > 1.0f) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Volume must be 0.0-1.0"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Volume must be 0.0-1.0");
}
float oldVolume = volume_;
@@ -516,10 +515,9 @@ namespace Echoion::Core
ECHOION_LOG_WARNING(std::format(
"Track validation failed for '{} - {}': {}", track.title,
track.artist, streamUrl.error().message));
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
return Api::fail(Api::ErrorCode::ServiceUnavailable,
std::format("Cannot play this track: {}",
streamUrl.error().message)));
streamUrl.error().message));
}
uint64_t queueId;
@@ -538,8 +536,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_);
if (queue_.size() >= config_.maxQueueSize) {
return std::unexpected(Api::Error(
Api::ErrorCode::InvalidArgument, "Queue is full"));
return Api::fail(
Api::ErrorCode::InvalidArgument, "Queue is full");
}
queueId = nextQueueId_++;
@@ -632,8 +630,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_);
if (position >= queue_.size()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Invalid position"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid position");
}
auto removedTrack = queue_[position];
@@ -706,8 +704,8 @@ namespace Echoion::Core
std::shared_lock<std::shared_mutex> lock(mutex_);
if (from >= queue_.size() || to >= queue_.size()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Invalid position"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Invalid position");
}
auto entry = queue_[from];
@@ -828,16 +826,14 @@ namespace Echoion::Core
uint64_t clientId)
{
if (!youTubeClient_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTube client not available"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTube client not available");
}
// Check if already loading a playlist
if (playlistLoading_.load()) {
return std::unexpected(
Api::Error(Api::ErrorCode::AlreadyExists,
"Already loading a playlist, please wait"));
return Api::fail(Api::ErrorCode::AlreadyExists,
"Already loading a playlist, please wait");
}
// Extract playlist ID if a full URL was provided
@@ -850,9 +846,8 @@ namespace Echoion::Core
ECHOION_LOG_DEBUG(std::format(
"Extracted playlist ID '{}' from URL", playlistId));
} else {
return std::unexpected(
Api::Error(Api::ErrorCode::InvalidArgument,
"Could not extract playlist ID from URL"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Could not extract playlist ID from URL");
}
}
@@ -1042,9 +1037,8 @@ namespace Echoion::Core
MusicManager::search(const std::string& query)
{
if (!youTubeClient_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTube client not available"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTube client not available");
}
return youTubeClient_->search(query);
@@ -1078,23 +1072,22 @@ namespace Echoion::Core
{
if (index == 0) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Index must be 1 or greater"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Index must be 1 or greater");
}
auto pending = getPendingSearch(clientId);
if (!pending) {
return std::unexpected(
Api::Error(Api::ErrorCode::NotFound,
return Api::fail(Api::ErrorCode::NotFound,
"No pending search results. Use search or play "
"commands first."));
"commands first.");
}
if (index > pending->size()) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::NotFound,
std::format("Invalid selection. Only {} results available.",
pending->size())));
pending->size()));
}
auto selected =
@@ -1689,8 +1682,7 @@ namespace Echoion::Core
}
if (searchResult->tracks.empty()) {
return std::unexpected(
Api::Error(Api::ErrorCode::NotFound, "No results found"));
return Api::fail(Api::ErrorCode::NotFound, "No results found");
}
return searchResult->tracks[0];
@@ -1722,8 +1714,7 @@ namespace Echoion::Core
ECHOION_LOG_WARNING("Could not extract video ID from URL");
}
return std::unexpected(
Api::Error(Api::ErrorCode::NotFound, "Could not get stream URL"));
return Api::fail(Api::ErrorCode::NotFound, "Could not get stream URL");
}
void MusicManager::onTrackFinished()
@@ -1896,21 +1887,20 @@ Subscriptions are persistent across server reconnects.)";
Api::Result<std::string> MusicManager::subscribe(uint64_t clientId)
{
if (!subscriptionManager_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
// Get client info (UID and nickname) from the callback
if (!clientInfoCallback_) {
return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized,
"Client info callback not set"));
return Api::fail(Api::ErrorCode::NotInitialized,
"Client info callback not set");
}
auto clientInfo = clientInfoCallback_(clientId);
if (!clientInfo) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
"Could not get client info"));
return Api::fail(Api::ErrorCode::NotFound,
"Could not get client info");
}
const auto& [uid, nickname] = *clientInfo;
@@ -1951,21 +1941,20 @@ Subscriptions are persistent across server reconnects.)";
Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId)
{
if (!subscriptionManager_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
// Get client UID from the callback
if (!clientInfoCallback_) {
return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized,
"Client info callback not set"));
return Api::fail(Api::ErrorCode::NotInitialized,
"Client info callback not set");
}
auto clientInfo = clientInfoCallback_(clientId);
if (!clientInfo) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
"Could not get client info"));
return Api::fail(Api::ErrorCode::NotFound,
"Could not get client info");
}
const auto& [uid, nickname] = *clientInfo;
@@ -2000,9 +1989,8 @@ Subscriptions are persistent across server reconnects.)";
MusicManager::unsubscribeByUid(const std::string& uid)
{
if (!subscriptionManager_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
bool removed = subscriptionManager_->unsubscribe(uid);
@@ -2031,9 +2019,8 @@ Subscriptions are persistent across server reconnects.)";
Api::Result<std::string> MusicManager::clearAllSubscriptions()
{
if (!subscriptionManager_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Subscription manager not initialized");
}
bool cleared = subscriptionManager_->clearAll();
@@ -2251,9 +2238,8 @@ Subscriptions are persistent across server reconnects.)";
MusicManager::downloadAudioForPlayback(const std::string& url)
{
if (!networkClient_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"NetworkClient not available"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"NetworkClient not available");
}
// Create temp file path
@@ -2272,25 +2258,23 @@ Subscriptions are persistent across server reconnects.)";
auto response = networkClient_->get(url);
if (!response) {
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Failed to download audio: {}",
response.error().message)));
response.error().message));
}
if (response->statusCode != 200) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::NetworkError,
std::format("HTTP error {}: {}", response->statusCode,
response->body.substr(0, 100))));
response->body.substr(0, 100)));
}
// Write to temp file
std::ofstream file(tempPath, std::ios::binary);
if (!file) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Failed to create temp file"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Failed to create temp file");
}
file.write(response->body.data(), response->body.size());
+2 -2
View File
@@ -90,8 +90,8 @@ namespace Echoion::Core
auto result = client.send(vreq);
if (!result) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
result.error().message()));
return Api::fail(Api::ErrorCode::NetworkError,
result.error().message());
}
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)
{
if (running_.exchange(true)) {
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
"RPC server already running"));
return Api::fail(Api::ErrorCode::AlreadyExists,
"RPC server already running");
}
port_ = port;
@@ -36,9 +36,9 @@ namespace Echoion::Core
return {};
} catch (const std::exception& e) {
running_ = false;
return std::unexpected(Api::Error(
return Api::fail(
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);
if (!database_) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "Database not available"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "Database not available");
}
// Load existing subscriptions from database
+12 -15
View File
@@ -42,9 +42,8 @@ namespace Echoion::Core
}
if (!networkClient_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Network client not available");
}
// faumaray.ru API endpoint for URL shortening
@@ -68,17 +67,16 @@ namespace Echoion::Core
if (!response) {
ECHOION_LOG_WARNING(std::format("URL shortening failed: {}",
response.error().message));
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"Failed to shorten URL"));
return Api::fail(Api::ErrorCode::NetworkError,
"Failed to shorten URL");
}
if (!response->isSuccess()) {
ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}",
response->statusCode));
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}",
response->statusCode)));
response->statusCode));
}
try {
@@ -87,9 +85,8 @@ namespace Echoion::Core
auto parsed = Void::Json::parse(response->body);
if (!parsed) {
ECHOION_LOG_WARNING("Failed to parse URL shortening response");
return std::unexpected(
Api::Error(Api::ErrorCode::ParseError,
"Failed to parse shortening response"));
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse shortening response");
}
std::string shortenedUrl;
@@ -98,8 +95,8 @@ namespace Echoion::Core
shortenedUrl = shortUrl->as_string();
} else {
ECHOION_LOG_WARNING("No shortUrl field in response");
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
"No shortUrl in response"));
return Api::fail(Api::ErrorCode::ParseError,
"No shortUrl in response");
}
// Cache the result
@@ -117,8 +114,8 @@ namespace Echoion::Core
} catch (const std::exception& e) {
ECHOION_LOG_WARNING(std::format(
"Exception parsing shortening response: {}", e.what()));
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError, "Exception during URL shortening"));
return Api::fail(
Api::ErrorCode::ParseError, "Exception during URL shortening");
}
}
+144 -213
View File
@@ -18,58 +18,14 @@
namespace
{
// Safe Void::Json::Value accessors for navigating dynamic API responses
// (the former glz::generic helpers). Missing or wrong-typed fields yield a
// default value / nullptr instead of throwing.
// Local alias for navigating dynamic API responses; the safe typed getters
// (has/get_str/get_num/child_object/child_array) live on Void::Json::Value.
using JValue = Void::Json::Value;
[[nodiscard]] bool jHas(const JValue& v, std::string_view key)
{
return v.find(key) != nullptr;
}
[[nodiscard]] std::string jStr(const JValue& v, std::string_view key)
{
const JValue* c = v.find(key);
return (c && c->is_string()) ? c->as_string() : std::string{};
}
[[nodiscard]] double jNum(const JValue& v, std::string_view key)
{
const JValue* c = v.find(key);
return (c && c->is_number()) ? c->as_number() : 0.0;
}
// Returns a child only when it exists and is an object.
[[nodiscard]] const JValue* jObj(const JValue& v, std::string_view key)
{
const JValue* c = v.find(key);
return (c && c->is_object()) ? c : nullptr;
}
// Returns a child only when it exists and is an array.
[[nodiscard]] const JValue* jArr(const JValue& v, std::string_view key)
{
const JValue* c = v.find(key);
return (c && c->is_array()) ? c : nullptr;
}
} // namespace
namespace Echoion::Core
{
// URL encode helper function
std::string YouTubeClient::urlEncode(std::string_view value)
{
return Void::Encoding::Url::encode(value);
}
// HTML entity decode helper function
std::string YouTubeClient::decodeHtmlEntities(std::string_view value)
{
return Void::Text::html_unescape(value);
}
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)),
ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)),
@@ -193,9 +149,8 @@ namespace Echoion::Core
Api::Result<void> YouTubeClient::updateYtDlp()
{
if (!ytDlpManager_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp manager not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"yt-dlp manager not initialized");
}
return ytDlpManager_->update();
}
@@ -204,19 +159,18 @@ namespace Echoion::Core
YouTubeClient::getAudioStreamUrl(std::string_view videoId)
{
if (!initialized_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized");
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
}
if (videoId.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Video ID is empty"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Video ID is empty");
}
auto startTime = std::chrono::steady_clock::now();
@@ -239,18 +193,16 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING(
"yt-dlp audio URL extraction timed out after 30s");
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp audio URL extraction timed out"));
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp audio URL extraction timed out");
}
auto ytdlpResult = future.get();
if (!ytdlpResult.success) {
ECHOION_LOG_WARNING("yt-dlp audio URL extraction failed");
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp audio URL extraction failed"));
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp audio URL extraction failed");
}
std::string result = ytdlpResult.output;
@@ -271,8 +223,8 @@ namespace Echoion::Core
ECHOION_LOG_WARNING(std::format(
"Failed to get audio URL from yt-dlp after {} ms", elapsed));
return std::unexpected(Api::Error(
Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp"));
return Api::fail(
Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp");
}
Api::Result<std::string>
@@ -285,20 +237,19 @@ namespace Echoion::Core
YouTubeClient::getVideoInfo(std::string_view videoId)
{
if (!initialized_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized");
}
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
}
// Validate video ID
if (videoId.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument,
"Video ID is empty"));
return Api::fail(Api::ErrorCode::InvalidArgument,
"Video ID is empty");
}
ECHOION_LOG_DEBUG(
@@ -316,8 +267,8 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("yt-dlp video info timed out after 30s");
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp video info timed out"));
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp video info timed out");
}
auto ytdlpResult = result.get();
@@ -329,31 +280,29 @@ namespace Echoion::Core
.count()));
if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp failed to get video info"));
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp failed to get video info");
}
try {
auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) {
return std::unexpected(
Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp output"));
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp output");
}
const JValue& json = *parsed;
Api::TrackInfo info;
info.id = jStr(json, "id");
if (jHas(json, "title")) {
info.title = decodeHtmlEntities(jStr(json, "title"));
info.id = (json).get_str("id");
if ((json).has("title")) {
info.title = Void::Text::html_unescape((json).get_str("title"));
}
info.artist = jStr(json, "uploader");
if (jHas(json, "duration")) {
info.artist = (json).get_str("uploader");
if ((json).has("duration")) {
info.duration = std::chrono::seconds(
static_cast<int64_t>(jNum(json, "duration")));
static_cast<int64_t>((json).get_num("duration")));
}
info.thumbnailUrl = jStr(json, "thumbnail");
info.thumbnailUrl = (json).get_str("thumbnail");
// Set originalUrl so we can extract video ID later for streaming
info.originalUrl =
@@ -366,9 +315,9 @@ namespace Echoion::Core
return info;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp output: {}", e.what())));
std::format("Exception parsing yt-dlp output: {}", e.what()));
}
}
@@ -409,9 +358,8 @@ namespace Echoion::Core
{
if (!initialized_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized");
}
auto startTime = std::chrono::steady_clock::now();
@@ -445,9 +393,8 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(configMutex_);
if (!apiKey_.has_value() || apiKey_->empty()) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTube API key not configured"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTube API key not configured");
}
apiKey = *apiKey_;
}
@@ -456,7 +403,7 @@ namespace Echoion::Core
std::string url = std::format(
"https://www.googleapis.com/youtube/v3/"
"search?part=snippet&type=video&maxResults=10&q={}&key={}",
urlEncode(query), apiKey);
Void::Encoding::Url::encode(query), apiKey);
if (pageToken.has_value()) {
url += std::format("&pageToken={}", *pageToken);
@@ -489,8 +436,8 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("YouTube API search timed out after 10s");
apiThread.detach(); // Thread owns shared_ptr, safe to detach
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"YouTube API search timed out"));
return Api::fail(Api::ErrorCode::NetworkError,
"YouTube API search timed out");
}
ECHOION_LOG_DEBUG("Joining API request thread...");
@@ -504,9 +451,8 @@ namespace Echoion::Core
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("API request threw exception: {}", e.what()));
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
std::format("API request failed: {}", e.what())));
return Api::fail(Api::ErrorCode::NetworkError,
std::format("API request failed: {}", e.what()));
}
// Log response status
@@ -519,19 +465,18 @@ namespace Echoion::Core
}
if (!response || !response->isSuccess()) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::NetworkError,
std::format("YouTube API search failed: {}",
response ? std::to_string(response->statusCode)
: "no response")));
: "no response"));
}
try {
auto parsed = Void::Json::parse(response->body);
if (!parsed) {
return std::unexpected(
Api::Error(Api::ErrorCode::ParseError,
"Failed to parse YouTube API search response"));
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse YouTube API search response");
}
const JValue& json = *parsed;
@@ -539,29 +484,29 @@ namespace Echoion::Core
result.query = std::string(query);
// Extract total results
if (const JValue* pageInfo = jObj(json, "pageInfo")) {
if (jHas(*pageInfo, "totalResults")) {
if (const JValue* pageInfo = (json).child_object("pageInfo")) {
if ((*pageInfo).has("totalResults")) {
result.totalResults = static_cast<uint32_t>(
jNum(*pageInfo, "totalResults"));
(*pageInfo).get_num("totalResults"));
}
}
// Store next page token if available
if (jHas(json, "nextPageToken")) {
result.nextPageToken = jStr(json, "nextPageToken");
if ((json).has("nextPageToken")) {
result.nextPageToken = (json).get_str("nextPageToken");
}
// Extract search results
if (const JValue* items = jArr(json, "items")) {
if (const JValue* items = (json).child_array("items")) {
std::vector<std::string> videoIds;
for (const JValue& item : items->as_array()) {
const JValue* id = jObj(item, "id");
if (!id || !jHas(*id, "videoId")) {
const JValue* id = (item).child_object("id");
if (!id || !(*id).has("videoId")) {
continue;
}
std::string videoId = jStr(*id, "videoId");
std::string videoId = (*id).get_str("videoId");
videoIds.push_back(videoId);
Api::TrackInfo track;
@@ -570,26 +515,26 @@ namespace Echoion::Core
track.originalUrl = std::format(
"https://www.youtube.com/watch?v={}", videoId);
if (const JValue* snippet = jObj(item, "snippet")) {
if (jHas(*snippet, "title")) {
if (const JValue* snippet = (item).child_object("snippet")) {
if ((*snippet).has("title")) {
track.title =
decodeHtmlEntities(jStr(*snippet, "title"));
Void::Text::html_unescape((*snippet).get_str("title"));
}
if (jHas(*snippet, "channelTitle")) {
track.artist = decodeHtmlEntities(
jStr(*snippet, "channelTitle"));
if ((*snippet).has("channelTitle")) {
track.artist = Void::Text::html_unescape(
(*snippet).get_str("channelTitle"));
}
if (const JValue* thumbnails =
jObj(*snippet, "thumbnails")) {
(*snippet).child_object("thumbnails")) {
// Get the highest quality thumbnail available
if (const JValue* t = jObj(*thumbnails, "high")) {
track.thumbnailUrl = jStr(*t, "url");
if (const JValue* t = (*thumbnails).child_object("high")) {
track.thumbnailUrl = (*t).get_str("url");
} else if (const JValue* m =
jObj(*thumbnails, "medium")) {
track.thumbnailUrl = jStr(*m, "url");
(*thumbnails).child_object("medium")) {
track.thumbnailUrl = (*m).get_str("url");
} else if (const JValue* d =
jObj(*thumbnails, "default")) {
track.thumbnailUrl = jStr(*d, "url");
(*thumbnails).child_object("default")) {
track.thumbnailUrl = (*d).get_str("url");
}
}
}
@@ -620,10 +565,10 @@ namespace Echoion::Core
return result;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Exception parsing YouTube API search: {}",
e.what())));
e.what()));
}
}
@@ -705,20 +650,20 @@ namespace Echoion::Core
// Create a map of video ID to duration
std::unordered_map<std::string, std::chrono::seconds> durationMap;
if (const JValue* items = jArr(json, "items")) {
if (const JValue* items = (json).child_array("items")) {
for (const JValue& item : items->as_array()) {
const JValue* contentDetails =
jObj(item, "contentDetails");
if (!jHas(item, "id") || !contentDetails) {
(item).child_object("contentDetails");
if (!(item).has("id") || !contentDetails) {
continue;
}
std::string videoId = jStr(item, "id");
std::string videoId = (item).get_str("id");
if (jHas(*contentDetails, "duration")) {
if ((*contentDetails).has("duration")) {
std::string durationStr =
jStr(*contentDetails, "duration");
auto duration = parseIso8601Duration(durationStr);
(*contentDetails).get_str("duration");
auto duration = Void::Time::parse_iso8601_interval(durationStr).value_or(std::chrono::seconds{0});
if (duration.count() > 0) {
ECHOION_LOG_DEBUG(
std::format("Got duration: {}, parse as: {}",
@@ -745,23 +690,13 @@ namespace Echoion::Core
}
}
std::chrono::seconds
YouTubeClient::parseIso8601Duration(const std::string& duration)
{
// Delegate to Void; an unparseable value yields zero (prior behaviour).
if (auto d = Void::Time::parse_iso8601_interval(duration)) {
return *d;
}
return std::chrono::seconds{0};
}
Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlp(
std::string_view query, const std::optional<std::string>& pageToken)
{
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
}
ECHOION_LOG_DEBUG("Starting yt-dlp search...");
@@ -779,8 +714,8 @@ namespace Echoion::Core
if (waitStatus == std::future_status::timeout) {
ECHOION_LOG_WARNING("yt-dlp search timed out after 30s");
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp search timed out"));
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp search timed out");
}
auto ytdlpResult = result.get();
@@ -792,45 +727,44 @@ namespace Echoion::Core
std::format("yt-dlp search completed in {} ms", elapsed));
if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
"yt-dlp search failed"));
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp search failed");
}
try {
auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) {
return std::unexpected(
Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp search output"));
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp search output");
}
const JValue& json = *parsed;
Api::SearchResult searchResult;
searchResult.query = std::string(query);
if (const JValue* entries = jArr(json, "entries")) {
if (const JValue* entries = (json).child_array("entries")) {
for (const JValue& entry : entries->as_array()) {
if (!jHas(entry, "id")) {
if (!(entry).has("id")) {
continue;
}
Api::TrackInfo track;
track.id = jStr(entry, "id");
if (jHas(entry, "title")) {
track.id = (entry).get_str("id");
if ((entry).has("title")) {
track.title =
decodeHtmlEntities(jStr(entry, "title"));
Void::Text::html_unescape((entry).get_str("title"));
}
if (jHas(entry, "uploader")) {
if ((entry).has("uploader")) {
track.artist =
decodeHtmlEntities(jStr(entry, "uploader"));
Void::Text::html_unescape((entry).get_str("uploader"));
}
if (jHas(entry, "duration")) {
if ((entry).has("duration")) {
track.duration =
std::chrono::seconds(static_cast<int64_t>(
jNum(entry, "duration")));
(entry).get_num("duration")));
}
if (jHas(entry, "thumbnail")) {
track.thumbnailUrl = jStr(entry, "thumbnail");
if ((entry).has("thumbnail")) {
track.thumbnailUrl = (entry).get_str("thumbnail");
}
// Set originalUrl so we can extract video ID later for
// streaming
@@ -851,9 +785,9 @@ namespace Echoion::Core
return searchResult;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp search: {}", e.what())));
std::format("Exception parsing yt-dlp search: {}", e.what()));
}
}
@@ -861,9 +795,8 @@ namespace Echoion::Core
YouTubeClient::getPlaylist(std::string_view playlistId)
{
if (!initialized_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTubeClient not initialized");
}
ECHOION_LOG_INFO(std::format("Fetching playlist: {}", playlistId));
@@ -1071,38 +1004,38 @@ namespace Echoion::Core
}
const JValue& json = *parsed;
if (const JValue* itemsArr = jArr(json, "items")) {
if (const JValue* itemsArr = (json).child_array("items")) {
for (const JValue& item : itemsArr->as_array()) {
const JValue* snippet = jObj(item, "snippet");
const JValue* snippet = (item).child_object("snippet");
const JValue* contentDetails =
jObj(item, "contentDetails");
(item).child_object("contentDetails");
if (!snippet || !contentDetails) {
continue;
}
Api::YouTubePlaylistItem playlistItem;
if (jHas(*contentDetails, "videoId")) {
if ((*contentDetails).has("videoId")) {
playlistItem.videoId =
jStr(*contentDetails, "videoId");
(*contentDetails).get_str("videoId");
}
if (jHas(*snippet, "title")) {
playlistItem.title = jStr(*snippet, "title");
if ((*snippet).has("title")) {
playlistItem.title = (*snippet).get_str("title");
}
if (const JValue* thumbnails =
jObj(*snippet, "thumbnails")) {
(*snippet).child_object("thumbnails")) {
// Get the highest quality thumbnail available
if (const JValue* t =
jObj(*thumbnails, "high")) {
playlistItem.thumbnailUrl = jStr(*t, "url");
(*thumbnails).child_object("high")) {
playlistItem.thumbnailUrl = (*t).get_str("url");
} else if (const JValue* m =
jObj(*thumbnails, "medium")) {
playlistItem.thumbnailUrl = jStr(*m, "url");
(*thumbnails).child_object("medium")) {
playlistItem.thumbnailUrl = (*m).get_str("url");
} else if (const JValue* d =
jObj(*thumbnails, "default")) {
playlistItem.thumbnailUrl = jStr(*d, "url");
(*thumbnails).child_object("default")) {
playlistItem.thumbnailUrl = (*d).get_str("url");
}
}
@@ -1111,8 +1044,8 @@ namespace Echoion::Core
}
// Check for next page
if (jHas(json, "nextPageToken")) {
pageToken = jStr(json, "nextPageToken");
if ((json).has("nextPageToken")) {
pageToken = (json).get_str("nextPageToken");
} else {
pageToken = std::nullopt;
}
@@ -1135,8 +1068,8 @@ namespace Echoion::Core
ECHOION_LOG_INFO("Using yt-dlp for playlist fetch");
if (!ytDlpManager_->isAvailable()) {
return std::unexpected(Api::Error(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"));
return Api::fail(
Api::ErrorCode::ServiceUnavailable, "yt-dlp not available");
}
std::string url =
@@ -1148,36 +1081,34 @@ namespace Echoion::Core
auto ytdlpResult = result.get();
if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
"Failed to fetch playlist via yt-dlp"));
return Api::fail(Api::ErrorCode::NetworkError,
"Failed to fetch playlist via yt-dlp");
}
try {
auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) {
return std::unexpected(
Api::Error(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp playlist output"));
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse yt-dlp playlist output");
}
const JValue& json = *parsed;
if (const JValue* entries = jArr(json, "entries")) {
if (const JValue* entries = (json).child_array("entries")) {
for (const JValue& entry : entries->as_array()) {
if (!jHas(entry, "id")) {
if (!(entry).has("id")) {
continue;
}
Api::YouTubePlaylistItem item;
item.videoId = jStr(entry, "id");
if (jHas(entry, "title")) {
item.title = decodeHtmlEntities(jStr(entry, "title"));
item.videoId = (entry).get_str("id");
if ((entry).has("title")) {
item.title = Void::Text::html_unescape((entry).get_str("title"));
}
if (const JValue* thumbs = jArr(entry, "thumbnails")) {
if (const JValue* thumbs = (entry).child_array("thumbnails")) {
const auto& arr = thumbs->as_array();
if (!arr.empty() && arr.back().is_object() &&
arr.back().find("url")) {
item.thumbnailUrl = jStr(arr.back(), "url");
item.thumbnailUrl = (arr.back()).get_str("url");
}
}
@@ -1190,9 +1121,9 @@ namespace Echoion::Core
return items;
} catch (const std::exception& e) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Exception parsing playlist: {}", e.what())));
std::format("Exception parsing playlist: {}", e.what()));
}
}
@@ -1245,19 +1176,19 @@ namespace Echoion::Core
const JValue& json = *parsed;
Api::TrackInfo track;
track.id = jStr(json, "id");
if (jHas(json, "title")) {
track.title = decodeHtmlEntities(jStr(json, "title"));
track.id = (json).get_str("id");
if ((json).has("title")) {
track.title = Void::Text::html_unescape((json).get_str("title"));
}
if (jHas(json, "uploader")) {
track.artist = decodeHtmlEntities(jStr(json, "uploader"));
if ((json).has("uploader")) {
track.artist = Void::Text::html_unescape((json).get_str("uploader"));
}
if (jHas(json, "duration")) {
if ((json).has("duration")) {
track.duration = std::chrono::seconds(
static_cast<int64_t>(jNum(json, "duration")));
static_cast<int64_t>((json).get_num("duration")));
}
if (jHas(json, "thumbnail")) {
track.thumbnailUrl = jStr(json, "thumbnail");
if ((json).has("thumbnail")) {
track.thumbnailUrl = (json).get_str("thumbnail");
}
track.originalUrl = url;
+20 -27
View File
@@ -112,11 +112,11 @@ namespace Echoion::Core
try {
std::filesystem::create_directories(storageDir);
} catch (const std::exception& e) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format(
"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...");
std::string version = getVersion();
if (version.empty()) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"yt-dlp executable not working"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"yt-dlp executable not working");
}
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
@@ -315,9 +314,8 @@ namespace Echoion::Core
Api::Result<void> YtDlpManager::downloadYtDlp()
{
if (!networkClient_) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Network client not available"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Network client not available");
}
std::string downloadUrl = getDownloadUrl();
@@ -336,10 +334,9 @@ namespace Echoion::Core
while (redirectCount < maxRedirects) {
auto result = networkClient_->get(downloadUrl, headers);
if (!result) {
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: {}",
result.error().message)));
result.error().message));
}
response = std::move(*result);
@@ -348,9 +345,9 @@ namespace Echoion::Core
if (response.statusCode >= 300 && response.statusCode < 400) {
auto location = response.getHeader("location");
if (!location.has_value()) {
return std::unexpected(Api::Error(
return Api::fail(
Api::ErrorCode::NetworkError,
"Redirect response missing Location header"));
"Redirect response missing Location header");
}
// Handle relative URLs
@@ -379,10 +376,9 @@ namespace Echoion::Core
}
if (!response.isSuccess()) {
return std::unexpected(
Api::Error(Api::ErrorCode::NetworkError,
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: HTTP {}",
response.statusCode)));
response.statusCode));
}
ECHOION_LOG_INFO(
@@ -392,16 +388,15 @@ namespace Echoion::Core
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"));
return Api::fail(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(
return Api::fail(
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
@@ -434,9 +429,8 @@ namespace Echoion::Core
#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 Api::fail(Api::ErrorCode::ServiceUnavailable,
"Failed to make yt-dlp executable");
}
return {};
#endif
@@ -513,9 +507,8 @@ namespace Echoion::Core
// Verify new version works
std::string version = getVersion();
if (version.empty()) {
return std::unexpected(
Api::Error(Api::ErrorCode::ServiceUnavailable,
"Updated yt-dlp not working"));
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Updated yt-dlp not working");
}
ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version));
+8 -7
View File
@@ -2,6 +2,7 @@
#include "echoion/core/state/StateSerializer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <Void/Time/Format.hpp>
#include <format>
namespace Echoion::Core
@@ -17,13 +18,13 @@ namespace Echoion::Core
if (fromVersion == 0) {
auto parsed = Void::Json::parse(jsonData);
if (!parsed) {
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
"Failed to parse V0 state"});
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse V0 state");
}
auto v0 = Void::Json::from_json<StateV0>(*parsed);
if (!v0) {
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
"Failed to parse V0 state"});
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse V0 state");
}
return fromV0(*v0);
}
@@ -31,9 +32,9 @@ namespace Echoion::Core
// Add more migrations here as versions evolve
// if (fromVersion == 1) { return fromV1(...); }
return std::unexpected(Api::Error{
return Api::fail(
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)
@@ -59,7 +60,7 @@ namespace Echoion::Core
}
v1.version = 1;
v1.savedAt = StateSerializer::getCurrentTimestampISO8601();
v1.savedAt = Void::Time::utc_now_iso8601();
return v1;
}
+11 -16
View File
@@ -20,15 +20,15 @@ namespace Echoion::Core
return Api::StateBlob{.data = std::move(data),
.version = CURRENT_VERSION,
.timestamp = getCurrentTimestampISO8601()};
.timestamp = Void::Time::utc_now_iso8601()};
}
Api::Result<StateV1>
StateSerializer::deserialize(const Api::StateBlob& blob)
{
if (blob.data.empty()) {
return std::unexpected(Api::Error{Api::ErrorCode::InvalidArgument,
"Empty state blob"});
return Api::fail(Api::ErrorCode::InvalidArgument,
"Empty state blob");
}
// Convert blob to string
@@ -40,18 +40,18 @@ namespace Echoion::Core
// Check if version is supported
if (!isVersionSupported(dataVersion)) {
if (dataVersion > CURRENT_VERSION) {
return std::unexpected(Api::Error{
return Api::fail(
Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is from a newer Core. "
"Please update/restart to load this state.",
dataVersion)});
dataVersion));
} else {
return std::unexpected(Api::Error{
return Api::fail(
Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is too old. "
"Maximum supported age is {} versions.",
dataVersion,
Api::MAX_SUPPORTED_STATE_VERSION_AGE)});
Api::MAX_SUPPORTED_STATE_VERSION_AGE));
}
}
@@ -59,18 +59,18 @@ namespace Echoion::Core
if (dataVersion == CURRENT_VERSION) {
auto parsed = Void::Json::parse(jsonStr);
if (!parsed) {
return std::unexpected(Api::Error{
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse state ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)});
parsed.error().message));
}
auto state = Void::Json::from_json<StateV1>(*parsed);
if (!state) {
return std::unexpected(Api::Error{
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to decode state: field '{}': {}",
state.error().field, state.error().message)});
state.error().field, state.error().message));
}
return *state;
}
@@ -130,9 +130,4 @@ namespace Echoion::Core
return 0;
}
std::string StateSerializer::getCurrentTimestampISO8601()
{
return Void::Time::utc_now_iso8601();
}
} // namespace Echoion::Core