#include "echoion/core/Logger.hpp" #include "echoion/core/YouTubeClient.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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. 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 { YouTubeClient::YouTubeClient(std::shared_ptr networkClient) : networkClient_(std::move(networkClient)), ytDlpManager_(std::make_unique(networkClient_)), urlShortener_(std::make_unique(networkClient_)) { } YouTubeClient::~YouTubeClient() { shutdown(); } Api::Result YouTubeClient::initialize() { if (initialized_) { return {}; } ECHOION_LOG_INFO("Initializing YouTube client..."); // Initialize yt-dlp manager (downloads if needed) auto result = ytDlpManager_->initialize(); if (!result) { return result; } // Set thread pool size based on configuration ytDlpManager_->setThreadPoolSize(maxConcurrentResolutions_); initialized_ = true; ECHOION_LOG_INFO("YouTube client initialized successfully"); return {}; } void YouTubeClient::setCookiesPath(const std::string& path) { if (ytDlpManager_) { ytDlpManager_->setCookiesPath(path); } } void YouTubeClient::setCookiesFromBrowser(const std::string& browser) { if (ytDlpManager_) { ytDlpManager_->setCookiesFromBrowser(browser); } } void YouTubeClient::setProxyConfig( const std::optional& proxy) { if (ytDlpManager_) { ytDlpManager_->setProxyConfig(proxy); } std::lock_guard lock(configMutex_); if (proxy.has_value() && proxy->isValid()) { ECHOION_LOG_INFO( std::format("YouTubeClient proxy configured: {}:{}", proxy->host, proxy->port)); } } std::optional YouTubeClient::getProxyConfig() const { if (ytDlpManager_) { return ytDlpManager_->getProxyConfig(); } return std::nullopt; } void YouTubeClient::setApiKey(const std::string& apiKey) { std::lock_guard lock(configMutex_); apiKey_ = apiKey; ECHOION_LOG_INFO( "YouTube API key configured for enhanced playlist resolution"); } bool YouTubeClient::hasApiKey() const { std::lock_guard lock(configMutex_); return apiKey_.has_value() && !apiKey_->empty(); } void YouTubeClient::setMaxConcurrentResolutions(size_t max) { if (max == 0) { max = 1; } if (max > 8) { max = 8; // Cap at 8 concurrent resolutions } std::lock_guard lock(configMutex_); maxConcurrentResolutions_ = max; if (ytDlpManager_) { ytDlpManager_->setThreadPoolSize(max); } } size_t YouTubeClient::getMaxConcurrentResolutions() const { std::lock_guard lock(configMutex_); return maxConcurrentResolutions_; } void YouTubeClient::shutdown() { initialized_ = false; } bool YouTubeClient::isAvailable() const { return ytDlpManager_ && ytDlpManager_->isAvailable(); } std::string YouTubeClient::getYtDlpVersion() const { if (!ytDlpManager_) { return ""; } return ytDlpManager_->getVersion(); } Api::Result YouTubeClient::updateYtDlp() { if (!ytDlpManager_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "yt-dlp manager not initialized"); } return ytDlpManager_->update(); } Api::Result YouTubeClient::getAudioStreamUrl(std::string_view videoId) { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized"); } if (!ytDlpManager_->isAvailable()) { return Api::fail( Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } if (videoId.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Video ID is empty"); } auto startTime = std::chrono::steady_clock::now(); ECHOION_LOG_INFO( std::format("Getting audio stream URL for video: {}", videoId)); // Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm) // 140 = AAC 128kbps (m4a), 251 = Opus 160kbps (webm) // Pass just the video ID to yt-dlp std::string videoIdStr(videoId); ECHOION_LOG_DEBUG("Starting yt-dlp audio URL extraction..."); auto future = ytDlpManager_->executeAsync( {videoIdStr, "-f", "bestaudio/251/140", "-g", "--no-warnings"}); // Wait with timeout (30 seconds) ECHOION_LOG_DEBUG("Waiting for yt-dlp audio URL (30s timeout)..."); auto waitStatus = future.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { ECHOION_LOG_WARNING( "yt-dlp audio URL extraction timed out after 30s"); 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 Api::fail(Api::ErrorCode::NetworkError, "yt-dlp audio URL extraction failed"); } std::string result = ytdlpResult.output; if (!result.empty() && result.back() == '\n') { result.pop_back(); } auto elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - startTime) .count(); if (!result.empty() && result.find("http") == 0) { ECHOION_LOG_INFO(std::format( "Successfully got audio URL from yt-dlp in {} ms", elapsed)); return result; } ECHOION_LOG_WARNING(std::format( "Failed to get audio URL from yt-dlp after {} ms", elapsed)); return Api::fail( Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp"); } Api::Result YouTubeClient::getStreamUrl(std::string_view videoId) { return getAudioStreamUrl(videoId); } Api::Result YouTubeClient::getVideoInfo(std::string_view videoId) { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized"); } if (!ytDlpManager_->isAvailable()) { return Api::fail( Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } // Validate video ID if (videoId.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Video ID is empty"); } ECHOION_LOG_DEBUG( std::format("Getting video info for ID: '{}'", videoId)); auto infoStart = std::chrono::steady_clock::now(); // Pass just the video ID to yt-dlp (it can handle both ID and URL) std::string videoIdStr(videoId); auto result = ytDlpManager_->executeAsync({videoIdStr, "-J", "--no-warnings"}); // Wait with timeout (30 seconds) ECHOION_LOG_DEBUG("Waiting for yt-dlp video info (30s timeout)..."); auto waitStatus = result.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { ECHOION_LOG_WARNING("yt-dlp video info timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp video info timed out"); } auto ytdlpResult = result.get(); ECHOION_LOG_DEBUG( std::format("yt-dlp video info completed in {} ms", std::chrono::duration_cast( std::chrono::steady_clock::now() - infoStart) .count())); if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp failed to get video info"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { 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 = Void::Text::html_unescape(jStr(json, "title")); } info.artist = jStr(json, "uploader"); if (jHas(json, "duration")) { info.duration = std::chrono::seconds( static_cast(jNum(json, "duration"))); } info.thumbnailUrl = jStr(json, "thumbnail"); // Set originalUrl so we can extract video ID later for streaming info.originalUrl = std::format("https://www.youtube.com/watch?v={}", info.id); info.source = Api::TrackSource::YouTube; // Populate shortened URL populateShortenedUrl(info); return info; } catch (const std::exception& e) { return Api::fail( Api::ErrorCode::ParseError, std::format("Exception parsing yt-dlp output: {}", e.what())); } } std::future> YouTubeClient::getVideoInfoAsync(std::string_view videoId) { return std::async(std::launch::async, [this, videoIdStr = std::string(videoId)]() { return getVideoInfo(videoIdStr); }); } std::vector> YouTubeClient::getVideoInfoBatch( const std::vector& videoIds) { std::vector>> futures; futures.reserve(videoIds.size()); // Launch all requests concurrently for (const auto& videoId : videoIds) { futures.push_back(getVideoInfoAsync(videoId)); } // Collect results std::vector> results; results.reserve(videoIds.size()); for (auto& future : futures) { results.push_back(future.get()); } return results; } Api::Result YouTubeClient::search( std::string_view query, std::optional pageToken) { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized"); } auto startTime = std::chrono::steady_clock::now(); Api::Result result; // Use YouTube Data API v3 if key is available if (hasApiKey()) { ECHOION_LOG_INFO( std::format("Searching YouTube via API: '{}'", query)); result = searchWithApi(query, pageToken); } else { // Fallback to yt-dlp if no API key ECHOION_LOG_WARNING("No YouTube API key configured, falling back " "to yt-dlp for search"); result = searchWithYtDlp(query, pageToken); } ECHOION_LOG_INFO( std::format("YouTube search took {} ms", std::chrono::duration_cast( std::chrono::steady_clock::now() - startTime) .count())); return result; } Api::Result YouTubeClient::searchWithApi( std::string_view query, const std::optional& pageToken) { std::string apiKey; { std::lock_guard lock(configMutex_); if (!apiKey_.has_value() || apiKey_->empty()) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "YouTube API key not configured"); } apiKey = *apiKey_; } // Build YouTube Data API v3 search URL std::string url = std::format( "https://www.googleapis.com/youtube/v3/" "search?part=snippet&type=video&maxResults=10&q={}&key={}", Void::Encoding::Url::encode(query), apiKey); if (pageToken.has_value()) { url += std::format("&pageToken={}", *pageToken); } // Execute with timeout (10 seconds for API search) ECHOION_LOG_DEBUG("Executing YouTube API search with 10s timeout..."); // Use shared promise so detached thread can safely complete auto responsePromise = std::make_shared>>(); std::future> responseFuture = responsePromise->get_future(); std::thread apiThread( [this, url = std::string(url), responsePromise]() { ECHOION_LOG_DEBUG("API request thread started"); try { auto result = networkClient_->get(url); responsePromise->set_value(std::move(result)); } catch (...) { responsePromise->set_exception(std::current_exception()); } ECHOION_LOG_DEBUG("API request thread completed"); }); // Wait with timeout auto waitStatus = responseFuture.wait_for(std::chrono::seconds(10)); if (waitStatus == std::future_status::timeout) { ECHOION_LOG_WARNING("YouTube API search timed out after 10s"); apiThread.detach(); // Thread owns shared_ptr, safe to detach return Api::fail(Api::ErrorCode::NetworkError, "YouTube API search timed out"); } ECHOION_LOG_DEBUG("Joining API request thread..."); apiThread.join(); ECHOION_LOG_DEBUG("API request thread joined"); // Get the response Api::Result response; try { response = responseFuture.get(); } catch (const std::exception& e) { ECHOION_LOG_ERROR( std::format("API request threw exception: {}", e.what())); return Api::fail(Api::ErrorCode::NetworkError, std::format("API request failed: {}", e.what())); } // Log response status if (response) { ECHOION_LOG_DEBUG( std::format("API response status: {}", response->statusCode)); } else { ECHOION_LOG_WARNING(std::format("API request failed: {}", response.error().message)); } if (!response || !response->isSuccess()) { return Api::fail( Api::ErrorCode::NetworkError, std::format("YouTube API search failed: {}", response ? std::to_string(response->statusCode) : "no response")); } try { auto parsed = Void::Json::parse(response->body); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, "Failed to parse YouTube API search response"); } const JValue& json = *parsed; Api::SearchResult result; result.query = std::string(query); // Extract total results if (const JValue* pageInfo = jObj(json, "pageInfo")) { if (jHas(*pageInfo, "totalResults")) { result.totalResults = static_cast( jNum(*pageInfo, "totalResults")); } } // Store next page token if available if (jHas(json, "nextPageToken")) { result.nextPageToken = jStr(json, "nextPageToken"); } // Extract search results if (const JValue* items = jArr(json, "items")) { std::vector videoIds; for (const JValue& item : items->as_array()) { const JValue* id = jObj(item, "id"); if (!id || !jHas(*id, "videoId")) { continue; } std::string videoId = jStr(*id, "videoId"); videoIds.push_back(videoId); Api::TrackInfo track; track.id = videoId; track.source = Api::TrackSource::YouTube; track.originalUrl = std::format( "https://www.youtube.com/watch?v={}", videoId); if (const JValue* snippet = jObj(item, "snippet")) { if (jHas(*snippet, "title")) { track.title = Void::Text::html_unescape(jStr(*snippet, "title")); } if (jHas(*snippet, "channelTitle")) { track.artist = Void::Text::html_unescape( jStr(*snippet, "channelTitle")); } if (const JValue* thumbnails = jObj(*snippet, "thumbnails")) { // Get the highest quality thumbnail available if (const JValue* t = jObj(*thumbnails, "high")) { track.thumbnailUrl = jStr(*t, "url"); } else if (const JValue* m = jObj(*thumbnails, "medium")) { track.thumbnailUrl = jStr(*m, "url"); } else if (const JValue* d = jObj(*thumbnails, "default")) { track.thumbnailUrl = jStr(*d, "url"); } } } result.tracks.push_back(std::move(track)); } // Fetch duration for each video using videos endpoint (batch // request) if (!videoIds.empty()) { ECHOION_LOG_DEBUG("Fetching video durations..."); fetchVideoDurations(result.tracks, videoIds); ECHOION_LOG_DEBUG("Video durations fetched"); } } ECHOION_LOG_INFO( std::format("YouTube API search returned {} results", result.tracks.size())); // Populate shortened URLs for all tracks (already non-blocking with // timeout) ECHOION_LOG_DEBUG("Populating shortened URLs..."); populateShortenedUrls(result.tracks); ECHOION_LOG_DEBUG("Shortened URLs populated"); ECHOION_LOG_DEBUG("Returning search result"); return result; } catch (const std::exception& e) { return Api::fail( Api::ErrorCode::ParseError, std::format("Exception parsing YouTube API search: {}", e.what())); } } void YouTubeClient::fetchVideoDurations( std::vector& tracks, const std::vector& videoIds) { if (!hasApiKey() || videoIds.empty()) { return; } // Build comma-separated video IDs std::string idList; for (size_t i = 0; i < videoIds.size(); ++i) { if (i > 0) { idList += ","; } idList += videoIds[i]; } std::string url; { std::lock_guard lock(configMutex_); url = std::format("https://www.googleapis.com/youtube/v3/" "videos?part=contentDetails&id={}&key={}", idList, *apiKey_); } // Execute with timeout (5 seconds) to avoid blocking // Use shared promise so detached thread can safely complete auto responsePromise = std::make_shared>>(); std::future> responseFuture = responsePromise->get_future(); std::thread durationThread( [this, url = std::string(url), responsePromise]() { try { auto result = networkClient_->get(url); responsePromise->set_value(std::move(result)); } catch (...) { responsePromise->set_exception(std::current_exception()); } }); auto waitStatus = responseFuture.wait_for(std::chrono::seconds(5)); if (waitStatus == std::future_status::timeout) { ECHOION_LOG_WARNING("Video duration fetch timed out after 5s"); durationThread.detach(); return; } durationThread.join(); Api::Result response; try { response = responseFuture.get(); } catch (const std::exception& e) { ECHOION_LOG_WARNING( std::format("Video duration request failed: {}", e.what())); return; } if (!response || !response->isSuccess()) { ECHOION_LOG_WARNING( "Failed to fetch video durations from YouTube API"); return; } try { auto parsed = Void::Json::parse(response->body); if (!parsed) { return; } const JValue& json = *parsed; // Create a map of video ID to duration std::unordered_map durationMap; if (const JValue* items = jArr(json, "items")) { for (const JValue& item : items->as_array()) { const JValue* contentDetails = jObj(item, "contentDetails"); if (!jHas(item, "id") || !contentDetails) { continue; } std::string videoId = jStr(item, "id"); if (jHas(*contentDetails, "duration")) { std::string durationStr = jStr(*contentDetails, "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: {}", durationStr, duration)); durationMap[videoId] = duration; } } } } // Apply durations to tracks for (auto& track : tracks) { auto it = durationMap.find(track.id); if (it != durationMap.end()) { track.duration = std::chrono::duration_cast( it->second); } } } catch (const std::exception& e) { ECHOION_LOG_WARNING( std::format("Failed to parse video durations: {}", e.what())); } } Api::Result YouTubeClient::searchWithYtDlp( std::string_view query, const std::optional& pageToken) { if (!ytDlpManager_->isAvailable()) { return Api::fail( Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } ECHOION_LOG_DEBUG("Starting yt-dlp search..."); auto searchStart = std::chrono::steady_clock::now(); // yt-dlp search format: ytsearch5:query std::string searchQuery = std::format("ytsearch5:{}", query); auto result = ytDlpManager_->executeAsync( {searchQuery, "-J", "--flat-playlist", "--no-warnings"}); // Wait with timeout (30 seconds for yt-dlp search) ECHOION_LOG_DEBUG("Waiting for yt-dlp search result (30s timeout)..."); auto waitStatus = result.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { ECHOION_LOG_WARNING("yt-dlp search timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp search timed out"); } auto ytdlpResult = result.get(); auto elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - searchStart) .count(); ECHOION_LOG_DEBUG( std::format("yt-dlp search completed in {} ms", elapsed)); if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp search failed"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { 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")) { for (const JValue& entry : entries->as_array()) { if (!jHas(entry, "id")) { continue; } Api::TrackInfo track; track.id = jStr(entry, "id"); if (jHas(entry, "title")) { track.title = Void::Text::html_unescape(jStr(entry, "title")); } if (jHas(entry, "uploader")) { track.artist = Void::Text::html_unescape(jStr(entry, "uploader")); } if (jHas(entry, "duration")) { track.duration = std::chrono::seconds(static_cast( jNum(entry, "duration"))); } if (jHas(entry, "thumbnail")) { track.thumbnailUrl = jStr(entry, "thumbnail"); } // Set originalUrl so we can extract video ID later for // streaming track.originalUrl = std::format( "https://www.youtube.com/watch?v={}", track.id); track.source = Api::TrackSource::YouTube; searchResult.tracks.push_back(track); } } searchResult.totalResults = static_cast(searchResult.tracks.size()); // Populate shortened URLs for all tracks populateShortenedUrls(searchResult.tracks); return searchResult; } catch (const std::exception& e) { return Api::fail( Api::ErrorCode::ParseError, std::format("Exception parsing yt-dlp search: {}", e.what())); } } Api::Result YouTubeClient::getPlaylist(std::string_view playlistId) { if (!initialized_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized"); } ECHOION_LOG_INFO(std::format("Fetching playlist: {}", playlistId)); // Step 1: Fetch playlist items (via API v2 if key available, else // yt-dlp) auto itemsResult = fetchPlaylistItems(playlistId); if (!itemsResult) { return std::unexpected(itemsResult.error()); } const auto& items = *itemsResult; if (items.empty()) { Api::PlaylistInfo emptyInfo; emptyInfo.id = std::string(playlistId); emptyInfo.name = "Empty Playlist"; return emptyInfo; } ECHOION_LOG_INFO(std::format( "Found {} tracks in playlist, resolving individually...", items.size())); // Step 2: Resolve each track individually via yt-dlp (concurrently) Api::PlaylistInfo info; info.id = std::string(playlistId); // Process tracks in batches to avoid overwhelming the system size_t batchSize; { std::lock_guard lock(configMutex_); batchSize = maxConcurrentResolutions_; } std::vector resolvedTracks; resolvedTracks.reserve(items.size()); for (size_t i = 0; i < items.size(); i += batchSize) { size_t end = std::min(i + batchSize, items.size()); std::vector>> futures; // Launch concurrent resolutions for this batch for (size_t j = i; j < end; ++j) { futures.push_back( std::async(std::launch::async, [this, &items, j]() { return resolveTrackWithYtDlp(items[j]); })); } // Collect results for (auto& future : futures) { auto result = future.get(); if (result) { resolvedTracks.push_back(std::move(*result)); } else { ECHOION_LOG_WARNING(std::format( "Failed to resolve track: {}", result.error().message)); } } ECHOION_LOG_DEBUG(std::format( "Resolved batch {}/{} ({} tracks so far)", (i / batchSize) + 1, (items.size() + batchSize - 1) / batchSize, resolvedTracks.size())); } info.tracks = std::move(resolvedTracks); // Set playlist name from first track if available if (!info.tracks.empty() && !items.empty()) { // Try to get playlist title from yt-dlp if we used it // Otherwise use a default name info.name = std::format("Playlist ({} tracks)", info.tracks.size()); } ECHOION_LOG_INFO( std::format("Successfully resolved {}/{} tracks from playlist", info.tracks.size(), items.size())); // Populate shortened URLs for all tracks populateShortenedUrls(info.tracks); return info; } std::future> YouTubeClient::getPlaylistAsync(std::string_view playlistId) { return std::async(std::launch::async, [this, playlistIdStr = std::string(playlistId)]() { return getPlaylist(playlistIdStr); }); } void YouTubeClient::getPlaylistStreaming( std::string_view playlistId, std::function trackCallback, std::function onPlaylistInfo, std::function onComplete) { if (!initialized_ || !trackCallback) { if (onComplete) { onComplete(); } return; } ECHOION_LOG_INFO(std::format("Streaming playlist: {}", playlistId)); // Fetch playlist items first (quick operation) auto itemsResult = fetchPlaylistItems(playlistId); if (!itemsResult || itemsResult->empty()) { ECHOION_LOG_WARNING("No items found in playlist or fetch failed"); if (onComplete) { onComplete(); } return; } const auto& items = *itemsResult; ECHOION_LOG_INFO( std::format("Streaming {} tracks from playlist", items.size())); // Notify about total tracks if (onPlaylistInfo) { onPlaylistInfo(items.size()); } // Resolve tracks in batches and call callback immediately for each // resolved track size_t batchSize; { std::lock_guard lock(configMutex_); batchSize = maxConcurrentResolutions_; } for (size_t i = 0; i < items.size(); i += batchSize) { size_t end = std::min(i + batchSize, items.size()); std::vector>> futures; // Launch concurrent resolutions for this batch for (size_t j = i; j < end; ++j) { futures.push_back( std::async(std::launch::async, [this, &items, j]() { return resolveTrackWithYtDlp(items[j]); })); } // Collect results and immediately call callback for each for (auto& future : futures) { auto result = future.get(); if (result) { // Populate shortened URL for this track populateShortenedUrl(*result); // Immediately notify callback - enables quick playback // start trackCallback(std::move(*result)); } else { ECHOION_LOG_WARNING(std::format( "Failed to resolve track: {}", result.error().message)); } } ECHOION_LOG_DEBUG( std::format("Processed batch {}/{}", (i / batchSize) + 1, (items.size() + batchSize - 1) / batchSize)); } ECHOION_LOG_INFO("Playlist streaming complete"); if (onComplete) { onComplete(); } } Api::Result> YouTubeClient::fetchPlaylistItems(std::string_view playlistId) { std::vector items; // Try using YouTube Data API v3 if key is available if (hasApiKey()) { ECHOION_LOG_INFO("Using YouTube Data API v3 for playlist fetch"); std::optional pageToken; do { std::string apiUrl = buildPlaylistApiUrl(playlistId, pageToken); auto response = networkClient_->get(apiUrl); if (!response || !response->isSuccess()) { ECHOION_LOG_WARNING( "YouTube API request failed, falling back to yt-dlp"); break; // Fall back to yt-dlp } try { auto parsed = Void::Json::parse(response->body); if (!parsed) { ECHOION_LOG_WARNING( "Failed to parse YouTube API response, " "falling back to yt-dlp"); break; } const JValue& json = *parsed; if (const JValue* itemsArr = jArr(json, "items")) { for (const JValue& item : itemsArr->as_array()) { const JValue* snippet = jObj(item, "snippet"); const JValue* contentDetails = jObj(item, "contentDetails"); if (!snippet || !contentDetails) { continue; } Api::YouTubePlaylistItem playlistItem; if (jHas(*contentDetails, "videoId")) { playlistItem.videoId = jStr(*contentDetails, "videoId"); } if (jHas(*snippet, "title")) { playlistItem.title = jStr(*snippet, "title"); } if (const JValue* thumbnails = jObj(*snippet, "thumbnails")) { // Get the highest quality thumbnail available if (const JValue* t = jObj(*thumbnails, "high")) { playlistItem.thumbnailUrl = jStr(*t, "url"); } else if (const JValue* m = jObj(*thumbnails, "medium")) { playlistItem.thumbnailUrl = jStr(*m, "url"); } else if (const JValue* d = jObj(*thumbnails, "default")) { playlistItem.thumbnailUrl = jStr(*d, "url"); } } items.push_back(std::move(playlistItem)); } } // Check for next page if (jHas(json, "nextPageToken")) { pageToken = jStr(json, "nextPageToken"); } else { pageToken = std::nullopt; } } catch (const std::exception& e) { ECHOION_LOG_WARNING(std::format( "Error parsing YouTube API response: {}", e.what())); break; // Fall back to yt-dlp } } while (pageToken.has_value()); if (!items.empty()) { ECHOION_LOG_INFO(std::format( "Fetched {} tracks via YouTube API", items.size())); return items; } } // Fallback: Use yt-dlp to fetch playlist items ECHOION_LOG_INFO("Using yt-dlp for playlist fetch"); if (!ytDlpManager_->isAvailable()) { return Api::fail( Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } std::string url = std::format("https://www.youtube.com/playlist?list={}", playlistId); auto result = ytDlpManager_->executeAsync( {url, "-J", "--flat-playlist", "--no-warnings"}); auto ytdlpResult = result.get(); if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, "Failed to fetch playlist via yt-dlp"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, "Failed to parse yt-dlp playlist output"); } const JValue& json = *parsed; if (const JValue* entries = jArr(json, "entries")) { for (const JValue& entry : entries->as_array()) { if (!jHas(entry, "id")) { continue; } Api::YouTubePlaylistItem item; item.videoId = jStr(entry, "id"); if (jHas(entry, "title")) { item.title = Void::Text::html_unescape(jStr(entry, "title")); } if (const JValue* thumbs = jArr(entry, "thumbnails")) { const auto& arr = thumbs->as_array(); if (!arr.empty() && arr.back().is_object() && arr.back().find("url")) { item.thumbnailUrl = jStr(arr.back(), "url"); } } items.push_back(std::move(item)); } } ECHOION_LOG_INFO( std::format("Fetched {} tracks via yt-dlp", items.size())); return items; } catch (const std::exception& e) { return Api::fail( Api::ErrorCode::ParseError, std::format("Exception parsing playlist: {}", e.what())); } } Api::Result YouTubeClient::resolveTrackWithYtDlp( const Api::YouTubePlaylistItem& item) { if (!ytDlpManager_->isAvailable()) { // Return basic info without yt-dlp resolution Api::TrackInfo track; track.id = item.videoId; track.title = item.title; track.thumbnailUrl = item.thumbnailUrl; track.source = Api::TrackSource::YouTube; track.originalUrl = std::format("https://www.youtube.com/watch?v={}", item.videoId); return track; } std::string url = std::format("https://www.youtube.com/watch?v={}", item.videoId); auto result = ytDlpManager_->executeAsync({url, "-J", "--no-warnings"}); auto ytdlpResult = result.get(); if (!ytdlpResult.success || ytdlpResult.output.empty()) { // Return basic info on failure Api::TrackInfo track; track.id = item.videoId; track.title = item.title; track.thumbnailUrl = item.thumbnailUrl; track.source = Api::TrackSource::YouTube; track.originalUrl = url; return track; } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { // Return basic info on parse failure Api::TrackInfo track; track.id = item.videoId; track.title = item.title; track.thumbnailUrl = item.thumbnailUrl; track.source = Api::TrackSource::YouTube; track.originalUrl = url; return track; } const JValue& json = *parsed; Api::TrackInfo track; track.id = jStr(json, "id"); if (jHas(json, "title")) { track.title = Void::Text::html_unescape(jStr(json, "title")); } if (jHas(json, "uploader")) { track.artist = Void::Text::html_unescape(jStr(json, "uploader")); } if (jHas(json, "duration")) { track.duration = std::chrono::seconds( static_cast(jNum(json, "duration"))); } if (jHas(json, "thumbnail")) { track.thumbnailUrl = jStr(json, "thumbnail"); } track.originalUrl = url; track.source = Api::TrackSource::YouTube; return track; } catch (const std::exception& e) { // Return basic info on exception Api::TrackInfo track; track.id = item.videoId; track.title = item.title; track.thumbnailUrl = item.thumbnailUrl; track.source = Api::TrackSource::YouTube; track.originalUrl = url; return track; } } std::string YouTubeClient::buildPlaylistApiUrl( std::string_view playlistId, const std::optional& pageToken) const { std::lock_guard lock(configMutex_); std::string url = std::format("https://www.googleapis.com/youtube/v3/" "playlistItems?part=snippet,contentDetails&" "playlistId={}&maxResults=50&key={}", playlistId, *apiKey_); if (pageToken.has_value()) { url += std::format("&pageToken={}", *pageToken); } return url; } std::optional YouTubeClient::extractVideoId(std::string_view url) { std::string url_str(url); // Handle faumaray.ru redirects using NetworkClient if (url_str.find("faumaray.ru") != std::string::npos && networkClient_) { ECHOION_LOG_DEBUG( std::format("Following redirect for: {}", url_str)); std::vector headers = { {"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36"}}; // Make request without following redirects to get the Location // header auto response = networkClient_->get(url_str, headers); if (response) { // Check if we got a redirect if (response->isRedirect()) { auto location = response->getHeader("location"); if (location.has_value()) { ECHOION_LOG_DEBUG( std::format("Redirected to: {}", *location)); url_str = *location; } } else if (response->isSuccess()) { // Some shorteners might return the target in the body or we // might need to look at the URL after any automatic // redirect following Try to extract from current URL or // response auto finalUrl = response->getHeader( "x-final-url"); // Some clients add this if (finalUrl.has_value()) { url_str = *finalUrl; } } } } // More comprehensive regex patterns for YouTube URLs static const std::regex watch_pattern( R"((?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?)", std::regex::icase); static const std::regex short_pattern( R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)", std::regex::icase); static const std::regex embed_pattern( R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)", std::regex::icase); static const std::regex shorts_pattern( R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)", std::regex::icase); // Also match just the video ID (11 characters) static const std::regex id_only_pattern(R"(^([a-zA-Z0-9_-]{11})$)", std::regex::icase); std::smatch match; if (std::regex_search(url_str, match, watch_pattern) || std::regex_search(url_str, match, short_pattern) || std::regex_search(url_str, match, embed_pattern) || std::regex_search(url_str, match, shorts_pattern) || std::regex_search(url_str, match, id_only_pattern)) { return match[1].str(); } return std::nullopt; } std::optional YouTubeClient::extractPlaylistId(std::string_view url) { std::string urlStr(url); std::smatch match; if (std::regex_search(urlStr, match, std::regex(R"(list=([a-zA-Z0-9_-]+))"))) { return match[1].str(); } return std::nullopt; } bool YouTubeClient::isYouTubeUrl(std::string_view url) { return url.find("faumaray.ru") != std::string::npos || url.find("youtube.com") != std::string::npos || url.find("youtu.be") != std::string::npos; } void YouTubeClient::setUrlShorteningEnabled(bool enabled) { std::lock_guard lock(configMutex_); urlShorteningEnabled_ = enabled; ECHOION_LOG_INFO( std::format("URL shortening {}", enabled ? "enabled" : "disabled")); } bool YouTubeClient::isUrlShorteningEnabled() const { std::lock_guard lock(configMutex_); return urlShorteningEnabled_; } void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track) { bool enabled; { std::lock_guard lock(configMutex_); enabled = urlShorteningEnabled_; } if (!enabled || !urlShortener_ || track.id.empty()) { return; } // Run URL shortening asynchronously with timeout to avoid blocking // This is a best-effort feature - if it fails or times out, we still // have the track. Use shared_ptr to ensure data lives for detached // thread. auto trackId = track.id; auto shortenedUrl = std::make_shared>(); auto completed = std::make_shared>(false); std::thread shortenThread([this, trackId, shortenedUrl, completed]() { try { auto result = urlShortener_->shortenYouTubeUrl(trackId); if (result) { *shortenedUrl = *result; } } catch (...) { // Ignore exceptions - this is best-effort } *completed = true; }); // Wait up to 3 seconds for URL shortening auto start = std::chrono::steady_clock::now(); while (!*completed && std::chrono::steady_clock::now() - start < std::chrono::seconds(3)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } if (*completed) { // Thread completed, join it and apply result if (shortenThread.joinable()) { shortenThread.join(); } if (shortenedUrl->has_value()) { track.shortenedUrl = *shortenedUrl; ECHOION_LOG_DEBUG(std::format("URL shortened for {}: {}", track.title, track.shortenedUrl.value())); } } else { // Timeout - thread owns shared_ptr, safe to detach ECHOION_LOG_WARNING( "URL shortening timed out after 3s, detaching thread"); shortenThread.detach(); } } void YouTubeClient::populateShortenedUrls( std::vector& tracks) { bool enabled; { std::lock_guard lock(configMutex_); enabled = urlShorteningEnabled_; } if (!enabled || !urlShortener_ || tracks.empty()) { return; } // Shorten URLs in parallel using async with timeout std::vector> futures; futures.reserve(tracks.size()); for (auto& track : tracks) { if (track.id.empty()) { continue; } futures.push_back(std::async(std::launch::async, [this, &track]() { // Each URL shortening has its own 3-second timeout // Use shared_ptr for safe detached thread execution auto trackId = track.id; auto shortenedUrl = std::make_shared>(); auto completed = std::make_shared>(false); std::thread t([this, trackId, shortenedUrl, completed]() { try { auto result = urlShortener_->shortenYouTubeUrl(trackId); if (result) { *shortenedUrl = *result; } } catch (...) { // Ignore exceptions } *completed = true; }); // Wait for completion or timeout auto start = std::chrono::steady_clock::now(); while (!*completed && std::chrono::steady_clock::now() - start < std::chrono::seconds(3)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } if (*completed) { // Thread completed, join and apply result if (t.joinable()) { t.join(); } if (shortenedUrl->has_value()) { track.shortenedUrl = *shortenedUrl; } } else { // Timeout - thread owns shared_ptr, safe to detach t.detach(); } })); } // Wait for all with overall 5-second timeout auto start = std::chrono::steady_clock::now(); for (auto& f : futures) { auto remaining = std::chrono::seconds(5) - std::chrono::duration_cast( std::chrono::steady_clock::now() - start); if (remaining.count() <= 0) { break; } f.wait_for(remaining); } } } // namespace Echoion::Core