#include #include "echoion/core/YouTubeClient.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { // 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; } // 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 {}; } Void::Log::info("YouTubeClient", "{}", "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; Void::Log::info("YouTubeClient", "{}", "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->enabled()) { Void::Log::info("YouTubeClient", "{}", 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; Void::Log::info("YouTubeClient", "{}", "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(); Void::Log::info("YouTubeClient", "{}", std::format("Getting audio stream URL for video: {}", videoId)); // Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm) // 140 = AAC 128kbps (m4a), 251 = Opus 160kbps (webm) // Pass just the video ID to yt-dlp std::string videoIdStr(videoId); Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp audio URL extraction..."); auto future = ytDlpManager_->executeAsync( {videoIdStr, "-f", "bestaudio/251/140", "-g", "--no-warnings"}); // Wait with timeout (30 seconds) Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp audio URL (30s timeout)..."); auto waitStatus = future.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { Void::Log::warn("YouTubeClient", "{}", "yt-dlp audio URL extraction timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp audio URL extraction timed out"); } auto ytdlpResult = future.get(); if (!ytdlpResult.success) { Void::Log::warn("YouTubeClient", "{}", "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) { Void::Log::info("YouTubeClient", "{}", std::format( "Successfully got audio URL from yt-dlp in {} ms", elapsed)); return result; } Void::Log::warn("YouTubeClient", "{}", std::format( "Failed to get audio URL from yt-dlp after {} ms", elapsed)); return Api::fail( Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp"); } 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"); } Void::Log::debug("YouTubeClient", "{}", 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) Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp video info (30s timeout)..."); auto waitStatus = result.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { Void::Log::warn("YouTubeClient", "{}", "yt-dlp video info timed out after 30s"); return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp video info timed out"); } auto ytdlpResult = result.get(); Void::Log::debug("YouTubeClient", "{}", 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 = (json).get_str("id"); if ((json).has("title")) { info.title = Void::Text::html_unescape((json).get_str("title")); } info.artist = (json).get_str("uploader"); if ((json).has("duration")) { info.duration = std::chrono::seconds( static_cast((json).get_num("duration"))); } info.thumbnailUrl = (json).get_str("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 pool_.submit([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()) { Void::Log::info("YouTubeClient", "{}", std::format("Searching YouTube via API: '{}'", query)); result = searchWithApi(query, pageToken); } else { // Fallback to yt-dlp if no API key Void::Log::warn("YouTubeClient", "{}", "No YouTube API key configured, falling back " "to yt-dlp for search"); result = searchWithYtDlp(query, pageToken); } Void::Log::info("YouTubeClient", "{}", 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) Void::Log::debug("YouTubeClient", "{}", "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]() { Void::Log::debug("YouTubeClient", "{}", "API request thread started"); try { auto result = networkClient_->get(url); responsePromise->set_value(std::move(result)); } catch (...) { responsePromise->set_exception(std::current_exception()); } Void::Log::debug("YouTubeClient", "{}", "API request thread completed"); }); // Wait with timeout auto waitStatus = responseFuture.wait_for(std::chrono::seconds(10)); if (waitStatus == std::future_status::timeout) { Void::Log::warn("YouTubeClient", "{}", "YouTube API search timed out after 10s"); apiThread.detach(); // Thread owns shared_ptr, safe to detach return Api::fail(Api::ErrorCode::NetworkError, "YouTube API search timed out"); } Void::Log::debug("YouTubeClient", "{}", "Joining API request thread..."); apiThread.join(); Void::Log::debug("YouTubeClient", "{}", "API request thread joined"); // Get the response Api::Result response; try { response = responseFuture.get(); } catch (const std::exception& e) { Void::Log::error("YouTubeClient", "{}", std::format("API request threw exception: {}", e.what())); return Api::fail(Api::ErrorCode::NetworkError, std::format("API request failed: {}", e.what())); } // Log response status if (response) { Void::Log::debug("YouTubeClient", "{}", std::format("API response status: {}", response->status)); } else { Void::Log::warn("YouTubeClient", "{}", std::format("API request failed: {}", response.error().message)); } if (!response || !response->ok()) { return Api::fail( Api::ErrorCode::NetworkError, std::format("YouTube API search failed: {}", response ? std::to_string(response->status) : "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 = (json).child_object("pageInfo")) { if ((*pageInfo).has("totalResults")) { result.totalResults = static_cast( (*pageInfo).get_num("totalResults")); } } // Store next page token if available if ((json).has("nextPageToken")) { result.nextPageToken = (json).get_str("nextPageToken"); } // Extract search results if (const JValue* items = (json).child_array("items")) { std::vector videoIds; for (const JValue& item : items->as_array()) { const JValue* id = (item).child_object("id"); if (!id || !(*id).has("videoId")) { continue; } std::string videoId = (*id).get_str("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 = (item).child_object("snippet")) { if ((*snippet).has("title")) { track.title = Void::Text::html_unescape((*snippet).get_str("title")); } if ((*snippet).has("channelTitle")) { track.artist = Void::Text::html_unescape( (*snippet).get_str("channelTitle")); } if (const JValue* thumbnails = (*snippet).child_object("thumbnails")) { // Get the highest quality thumbnail available if (const JValue* t = (*thumbnails).child_object("high")) { track.thumbnailUrl = (*t).get_str("url"); } else if (const JValue* m = (*thumbnails).child_object("medium")) { track.thumbnailUrl = (*m).get_str("url"); } else if (const JValue* d = (*thumbnails).child_object("default")) { track.thumbnailUrl = (*d).get_str("url"); } } } result.tracks.push_back(std::move(track)); } // Fetch duration for each video using videos endpoint (batch // request) if (!videoIds.empty()) { Void::Log::debug("YouTubeClient", "{}", "Fetching video durations..."); fetchVideoDurations(result.tracks, videoIds); Void::Log::debug("YouTubeClient", "{}", "Video durations fetched"); } } Void::Log::info("YouTubeClient", "{}", std::format("YouTube API search returned {} results", result.tracks.size())); // Populate shortened URLs for all tracks (already non-blocking with // timeout) Void::Log::debug("YouTubeClient", "{}", "Populating shortened URLs..."); populateShortenedUrls(result.tracks); Void::Log::debug("YouTubeClient", "{}", "Shortened URLs populated"); Void::Log::debug("YouTubeClient", "{}", "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) { Void::Log::warn("YouTubeClient", "{}", "Video duration fetch timed out after 5s"); durationThread.detach(); return; } durationThread.join(); Api::Result response; try { response = responseFuture.get(); } catch (const std::exception& e) { Void::Log::warn("YouTubeClient", "{}", std::format("Video duration request failed: {}", e.what())); return; } if (!response || !response->ok()) { Void::Log::warn("YouTubeClient", "{}", "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 = (json).child_array("items")) { for (const JValue& item : items->as_array()) { const JValue* contentDetails = (item).child_object("contentDetails"); if (!(item).has("id") || !contentDetails) { continue; } std::string videoId = (item).get_str("id"); if ((*contentDetails).has("duration")) { std::string durationStr = (*contentDetails).get_str("duration"); auto duration = Void::Time::parse_iso8601_interval(durationStr).value_or(std::chrono::seconds{0}); if (duration.count() > 0) { Void::Log::debug("YouTubeClient", "{}", 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) { Void::Log::warn("YouTubeClient", "{}", 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"); } Void::Log::debug("YouTubeClient", "{}", "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) Void::Log::debug("YouTubeClient", "{}", "Waiting for yt-dlp search result (30s timeout)..."); auto waitStatus = result.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { Void::Log::warn("YouTubeClient", "{}", "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(); Void::Log::debug("YouTubeClient", "{}", 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 = (json).child_array("entries")) { for (const JValue& entry : entries->as_array()) { if (!(entry).has("id")) { continue; } Api::TrackInfo track; track.id = (entry).get_str("id"); if ((entry).has("title")) { track.title = Void::Text::html_unescape((entry).get_str("title")); } if ((entry).has("uploader")) { track.artist = Void::Text::html_unescape((entry).get_str("uploader")); } if ((entry).has("duration")) { track.duration = std::chrono::seconds(static_cast( (entry).get_num("duration"))); } if ((entry).has("thumbnail")) { track.thumbnailUrl = (entry).get_str("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"); } Void::Log::info("YouTubeClient", "{}", 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; } Void::Log::info("YouTubeClient", "{}", 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( pool_.submit([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 { Void::Log::warn("YouTubeClient", "{}", std::format( "Failed to resolve track: {}", result.error().message)); } } Void::Log::debug("YouTubeClient", "{}", 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()); } Void::Log::info("YouTubeClient", "{}", 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 pool_.submit([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; } Void::Log::info("YouTubeClient", "{}", std::format("Streaming playlist: {}", playlistId)); // Fetch playlist items first (quick operation) auto itemsResult = fetchPlaylistItems(playlistId); if (!itemsResult || itemsResult->empty()) { Void::Log::warn("YouTubeClient", "{}", "No items found in playlist or fetch failed"); if (onComplete) { onComplete(); } return; } const auto& items = *itemsResult; Void::Log::info("YouTubeClient", "{}", 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( pool_.submit([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 { Void::Log::warn("YouTubeClient", "{}", std::format( "Failed to resolve track: {}", result.error().message)); } } Void::Log::debug("YouTubeClient", "{}", std::format("Processed batch {}/{}", (i / batchSize) + 1, (items.size() + batchSize - 1) / batchSize)); } Void::Log::info("YouTubeClient", "{}", "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()) { Void::Log::info("YouTubeClient", "{}", "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->ok()) { Void::Log::warn("YouTubeClient", "{}", "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) { Void::Log::warn("YouTubeClient", "{}", "Failed to parse YouTube API response, " "falling back to yt-dlp"); break; } const JValue& json = *parsed; if (const JValue* itemsArr = (json).child_array("items")) { for (const JValue& item : itemsArr->as_array()) { const JValue* snippet = (item).child_object("snippet"); const JValue* contentDetails = (item).child_object("contentDetails"); if (!snippet || !contentDetails) { continue; } Api::YouTubePlaylistItem playlistItem; if ((*contentDetails).has("videoId")) { playlistItem.videoId = (*contentDetails).get_str("videoId"); } if ((*snippet).has("title")) { playlistItem.title = (*snippet).get_str("title"); } if (const JValue* thumbnails = (*snippet).child_object("thumbnails")) { // Get the highest quality thumbnail available if (const JValue* t = (*thumbnails).child_object("high")) { playlistItem.thumbnailUrl = (*t).get_str("url"); } else if (const JValue* m = (*thumbnails).child_object("medium")) { playlistItem.thumbnailUrl = (*m).get_str("url"); } else if (const JValue* d = (*thumbnails).child_object("default")) { playlistItem.thumbnailUrl = (*d).get_str("url"); } } items.push_back(std::move(playlistItem)); } } // Check for next page if ((json).has("nextPageToken")) { pageToken = (json).get_str("nextPageToken"); } else { pageToken = std::nullopt; } } catch (const std::exception& e) { Void::Log::warn("YouTubeClient", "{}", std::format( "Error parsing YouTube API response: {}", e.what())); break; // Fall back to yt-dlp } } while (pageToken.has_value()); if (!items.empty()) { Void::Log::info("YouTubeClient", "{}", std::format( "Fetched {} tracks via YouTube API", items.size())); return items; } } // Fallback: Use yt-dlp to fetch playlist items Void::Log::info("YouTubeClient", "{}", "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 = (json).child_array("entries")) { for (const JValue& entry : entries->as_array()) { if (!(entry).has("id")) { continue; } Api::YouTubePlaylistItem item; item.videoId = (entry).get_str("id"); if ((entry).has("title")) { item.title = Void::Text::html_unescape((entry).get_str("title")); } 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 = (arr.back()).get_str("url"); } } items.push_back(std::move(item)); } } Void::Log::info("YouTubeClient", "{}", 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 = (json).get_str("id"); if ((json).has("title")) { track.title = Void::Text::html_unescape((json).get_str("title")); } if ((json).has("uploader")) { track.artist = Void::Text::html_unescape((json).get_str("uploader")); } if ((json).has("duration")) { track.duration = std::chrono::seconds( static_cast((json).get_num("duration"))); } if ((json).has("thumbnail")) { track.thumbnailUrl = (json).get_str("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_) { Void::Log::debug("YouTubeClient", "{}", 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->status >= 300 && response->status < 400) { auto location = response->header("location"); if (location.has_value()) { Void::Log::debug("YouTubeClient", "{}", std::format("Redirected to: {}", *location)); url_str = std::string(*location); } } else if (response->ok()) { // 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->header( "x-final-url"); // Some clients add this if (finalUrl.has_value()) { url_str = std::string(*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; Void::Log::info("YouTubeClient", "{}", 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; Void::Log::debug("YouTubeClient", "{}", std::format("URL shortened for {}: {}", track.title, track.shortenedUrl.value())); } } else { // Timeout - thread owns shared_ptr, safe to detach Void::Log::warn("YouTubeClient", "{}", "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; } // Best-effort wide-parallel shortening under a tight timeout — kept // on std::async so each track gets its own thread rather than // queueing behind the bounded resolution pool. 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