#include "echoion/core/YouTubeClient.hpp" #include #include #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::getStreamUrlForPage(std::string_view pageUrl, bool useProxy) { if (!initialized_ || !ytDlpManager_->isAvailable()) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } if (pageUrl.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Page URL is empty"); } std::vector args{std::string(pageUrl), "-f", "bestaudio/best", "-g", "--no-playlist", "--no-warnings"}; if (!useProxy) { // yt-dlp uses the LAST --proxy: an empty value overrides the // manager-prepended proxy and forces a direct connection. args.push_back("--proxy"); args.push_back(""); } auto future = ytDlpManager_->executeAsync(args); if (future.wait_for(std::chrono::seconds(30)) == std::future_status::timeout) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp stream URL extraction timed out"); } auto result = future.get(); if (!result.success) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp stream URL extraction failed"); } std::string url = result.output; // -g may print multiple lines (video+audio); take the first. if (auto nl = url.find('\n'); nl != std::string::npos) { url.resize(nl); } if (url.starts_with("http")) { return url; } return Api::fail(Api::ErrorCode::NotFound, "yt-dlp produced no stream URL"); } Api::Result YouTubeClient::downloadAudioToFile(std::string_view videoIdOrUrl, const std::string& outDir) { if (!initialized_ || !ytDlpManager_->isAvailable()) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } if (videoIdOrUrl.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, "Video ID/URL is empty"); } std::error_code ec; std::filesystem::create_directories(outDir, ec); const std::string id(videoIdOrUrl); const std::string outTemplate = outDir + "/%(id)s.%(ext)s"; auto startTime = std::chrono::steady_clock::now(); Void::Log::info("YouTubeClient", "{}", std::format("Downloading audio via yt-dlp: {}", id)); // yt-dlp downloads through the configured proxy + cookies and writes to // disk; --print after_move:filepath emits the final path on stdout. auto future = ytDlpManager_->executeAsync( {id, "-f", "bestaudio/251/140", "-o", outTemplate, "--no-playlist", "--no-warnings", "--print", "after_move:filepath"}); auto waitStatus = future.wait_for(std::chrono::seconds(180)); if (waitStatus == std::future_status::timeout) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp audio download timed out"); } auto ytdlpResult = future.get(); if (!ytdlpResult.success) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp audio download failed"); } // The emitted path is the last non-empty stdout line. std::string path; { std::istringstream stream(ytdlpResult.output); for (std::string line; std::getline(stream, line);) { while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) { line.pop_back(); } if (!line.empty()) { path = line; } } } if (path.empty() || !std::filesystem::exists(path)) { return Api::fail(Api::ErrorCode::NotFound, "yt-dlp reported no downloaded file"); } auto elapsed = std::chrono::duration_cast( std::chrono::steady_clock::now() - startTime) .count(); Void::Log::info( "YouTubeClient", "{}", std::format("Downloaded audio to {} in {} ms", path, elapsed)); return path; } 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); // Fall back to yt-dlp if the API path failed (bad/expired key, // quota exceeded, network error, etc.). if (!result) { Void::Log::warn( "YouTubeClient", "{}", std::format("YouTube API search failed ({}), falling back " "to yt-dlp", result.error().message)); result = searchWithYtDlp(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..."); // Run the blocking network GET on the shared thread pool. The pool's // destructor joins in-flight tasks, so abandoning a timed-out future is // safe — no detached thread racing this object's lifetime. std::future> responseFuture = pool_.submit([this, url = std::string(url)]() { return networkClient_->get(url); }); // Wait with timeout auto waitStatus = responseFuture.wait_for(std::chrono::seconds(20)); if (waitStatus == std::future_status::timeout) { Void::Log::warn("YouTubeClient", "{}", "YouTube API search timed out after 10s"); // Task keeps running on the pool; its result is discarded. return Api::fail(Api::ErrorCode::NetworkError, "YouTube API search timed out"); } // 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. Run on the shared // pool — the pool destructor joins in-flight tasks, so abandoning a // timed-out future is safe (no detached thread outliving this object). std::future> responseFuture = pool_.submit([this, url = std::string(url)]() { return networkClient_->get(url); }); 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"); // Task keeps running on the pool; its result is discarded. return; } 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::radioMix(const std::string& videoId, size_t limit) { if (!ytDlpManager_->isAvailable()) { return Api::fail(Api::ErrorCode::ServiceUnavailable, "yt-dlp not available"); } // YouTube's auto-generated "mix" playlist for a video is RD. // --flat-playlist lists it cheaply; each entry becomes a seed-free // related track. Runs through the proxy like every yt-dlp call. const std::string mixUrl = std::format( "https://www.youtube.com/watch?v={}&list=RD{}", videoId, videoId); auto future = ytDlpManager_->executeAsync( {mixUrl, "-J", "--flat-playlist", "--no-warnings", "--playlist-end", std::to_string(limit + 5)}); auto waitStatus = future.wait_for(std::chrono::seconds(30)); if (waitStatus == std::future_status::timeout) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp radio mix timed out"); } auto ytdlpResult = future.get(); if (!ytdlpResult.success || ytdlpResult.output.empty()) { return Api::fail(Api::ErrorCode::NetworkError, "yt-dlp radio mix failed"); } try { auto parsed = Void::Json::parse(ytdlpResult.output); if (!parsed) { return Api::fail(Api::ErrorCode::ParseError, "Failed to parse yt-dlp radio mix output"); } const JValue& json = *parsed; std::vector tracks; if (const JValue* entries = (json).child_array("entries")) { for (const JValue& entry : entries->as_array()) { if (tracks.size() >= limit) { break; } if (!(entry).has("id")) { continue; } Api::TrackInfo track; track.id = (entry).get_str("id"); // Skip the seed itself — the mix always leads with it. if (track.id == videoId) { continue; } 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"); } track.requestedBy = "radio\\autoplay"; track.addedAt = std::chrono::system_clock::now(); track.originalUrl = std::format( "https://www.youtube.com/watch?v={}", track.id); track.source = Api::TrackSource::YouTube; tracks.push_back(std::move(track)); } } populateShortenedUrls(tracks); return tracks; } catch (const std::exception& e) { return Api::fail( Api::ErrorCode::ParseError, std::format("Exception parsing yt-dlp radio mix: {}", 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")); } void YouTubeClient::setAutoUpdateEnabled(bool enabled) { if (ytDlpManager_) { ytDlpManager_->setAutoUpdateEnabled(enabled); } } 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 on the shared pool with a timeout. Best-effort: if // it times out we keep the track unshortened. The future is only read // on the ready path (which establishes happens-before), and on timeout // the task keeps running on the pool with its result discarded — no // detached thread and no busy-wait poll. auto trackId = track.id; auto future = pool_.submit([this, trackId]() -> std::optional { try { auto result = urlShortener_->shortenYouTubeUrl(trackId); if (result) { return *result; } } catch (...) { // Ignore exceptions - this is best-effort } return std::nullopt; }); if (future.wait_for(std::chrono::seconds(3)) == std::future_status::ready) { if (auto shortened = future.get()) { track.shortenedUrl = *shortened; Void::Log::debug("YouTubeClient", "{}", std::format("URL shortened for {}: {}", track.title, track.shortenedUrl.value())); } } else { Void::Log::warn("YouTubeClient", "{}", "URL shortening timed out after 3s"); } } 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 on the shared pool. Each task writes its // result into a shared optional (kept alive by the captured // shared_ptr), so a task that outlives the overall timeout writes only // to that shared slot — never to the caller's `tracks` vector. Results // are applied on this thread, and only for tasks whose future is ready // (which gives the needed happens-before for reading the slot). // Replaces the previous nested std::async + std::thread + busy-wait + // detach design. struct Slot { Api::TrackInfo* track; std::shared_ptr> out; std::future future; }; std::vector slots; slots.reserve(tracks.size()); for (auto& track : tracks) { if (track.id.empty()) { continue; } auto trackId = track.id; auto out = std::make_shared>(); auto future = pool_.submit([this, trackId, out]() { try { auto result = urlShortener_->shortenYouTubeUrl(trackId); if (result) { *out = *result; } } catch (...) { // Ignore exceptions - best-effort } }); slots.push_back({&track, std::move(out), std::move(future)}); } // Wait for all with an overall 5-second timeout. auto start = std::chrono::steady_clock::now(); for (auto& slot : slots) { auto remaining = std::chrono::seconds(5) - (std::chrono::steady_clock::now() - start); if (remaining <= std::chrono::seconds::zero()) { break; } slot.future.wait_for(remaining); } // Apply results for tasks that finished in time. for (auto& slot : slots) { if (slot.future.wait_for(std::chrono::seconds::zero()) == std::future_status::ready && slot.out->has_value()) { slot.track->shortenedUrl = **slot.out; } } } } // namespace Echoion::Core