Files
EchoionCore/include/echoion/core/YouTubeClient.hpp
T
faumaray 5c036d91fb making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:45:17 +03:00

218 lines
7.8 KiB
C++

#pragma once
#include "NetworkClient.hpp"
#include "UrlShortener.hpp"
#include "YtDlpManager.hpp"
#include <NetworkTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <YouTubeTypes.hpp>
#include <chrono>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <regex>
#include <string>
#include <unordered_map>
#include <vector>
namespace Echoion::Core
{
class YouTubeClient
{
public:
explicit YouTubeClient(
std::shared_ptr<NetworkClient> networkClient);
~YouTubeClient();
// Initialize the client - downloads yt-dlp if needed
Api::Result<void> initialize();
void shutdown();
// Check if yt-dlp is available
[[nodiscard]] bool isAvailable() const;
// Get yt-dlp version
[[nodiscard]] std::string getYtDlpVersion() const;
// Force update yt-dlp
Api::Result<void> updateYtDlp();
// Search for videos using YouTube Data API v3 (or yt-dlp as
// fallback)
[[nodiscard]] Api::Result<Api::SearchResult>
search(std::string_view query,
std::optional<std::string> pageToken = std::nullopt);
// Search SoundCloud via yt-dlp (scsearch). Returns SoundCloud
// tracks whose originalUrl is the permalink, streamable through the
// ytdlp-direct source.
[[nodiscard]] Api::Result<Api::SearchResult>
searchSoundCloud(std::string_view query);
// Related tracks for radio autoplay: lists the YouTube "mix"
// playlist (RD<videoId>) via yt-dlp --flat-playlist. Runs through
// the proxy like every yt-dlp call, so it works under SOCKS5.
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
radioMix(const std::string& videoId, size_t limit = 10);
// Fetch music-video candidates for a random search query. Used as a
// radio fallback when no unplayed related track can be found (or
// there is no seed). Goes through yt-dlp/proxy like radioMix; the
// returned list is shuffled so the caller can pick/filter freely.
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
randomMusicVideo(size_t limit = 10);
// Get video details including stream URLs using yt-dlp
[[nodiscard]] Api::Result<Api::TrackInfo>
getVideoInfo(std::string_view videoId);
// Get video details asynchronously
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
getVideoInfoAsync(std::string_view videoId);
// Get multiple video details concurrently
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
getVideoInfoBatch(const std::vector<std::string>& videoIds);
// Get playlist videos - uses YouTube API v2 if key available,
// otherwise yt-dlp Then resolves each track individually via yt-dlp
// for full metadata
[[nodiscard]] Api::Result<Api::PlaylistInfo>
getPlaylist(std::string_view playlistId);
// Get playlist videos asynchronously with concurrent track
// resolution
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
getPlaylistAsync(std::string_view playlistId);
// Stream playlist tracks with callback - calls trackCallback for
// each track as it is resolved, enabling immediate playback of
// first track
void getPlaylistStreaming(
std::string_view playlistId,
std::function<void(Api::TrackInfo&&)>
trackCallback,
std::function<void(size_t totalTracks)> onPlaylistInfo =
nullptr,
std::function<void()> onComplete = nullptr);
// Extract video ID from various YouTube URL formats (handles
// redirects for short URLs)
[[nodiscard]] std::optional<std::string>
extractVideoId(std::string_view url);
[[nodiscard]] static std::optional<std::string>
extractPlaylistId(std::string_view url);
// Check if URL is a YouTube URL
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
// Get stream URL for a video (used by MusicManager)
[[nodiscard]] Api::Result<std::string>
getStreamUrl(std::string_view videoId);
// Get best audio stream URL using yt-dlp
[[nodiscard]] Api::Result<std::string>
getAudioStreamUrl(std::string_view videoId);
// Resolve a stream URL for any yt-dlp-supported page URL
// (SoundCloud, Bandcamp, VK, radio pages, ...). When useProxy is
// false the configured proxy is explicitly bypassed with a
// trailing --proxy "" (yt-dlp honours the last occurrence).
[[nodiscard]] Api::Result<std::string>
getStreamUrlForPage(std::string_view pageUrl, bool useProxy);
// Download the best audio to a file via yt-dlp (used when the
// stream URL can't be opened directly — e.g. behind a SOCKS5 proxy
// that ffmpeg can't use). yt-dlp applies the proxy + cookies and
// writes to disk; returns the resulting file path.
[[nodiscard]] Api::Result<std::string>
downloadAudioToFile(std::string_view videoIdOrUrl,
const std::string& outDir);
// Configure cookie options for yt-dlp
void setCookiesPath(const std::string& path);
void setCookiesFromBrowser(const std::string& browser);
// Configure proxy for yt-dlp
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Void::Net::ProxyConfig>
getProxyConfig() const;
// Set YouTube API key for enhanced playlist resolution (optional)
void setApiKey(const std::string& apiKey);
[[nodiscard]] bool hasApiKey() const;
// Configure concurrent resolution settings
void setMaxConcurrentResolutions(size_t max);
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
// Enable/disable URL shortening for track links
void setUrlShorteningEnabled(bool enabled);
// Gate yt-dlp's periodic background self-update
// (features.enableAutoUpdateCheck). Set before initialize().
void setAutoUpdateEnabled(bool enabled);
[[nodiscard]] bool isUrlShorteningEnabled() const;
private:
// Internal search implementations
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithApi(std::string_view query,
const std::optional<std::string>& pageToken);
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithYtDlp(std::string_view query,
const std::optional<std::string>& pageToken);
// Shared yt-dlp search backend. `searchPrefix` is the yt-dlp search
// selector (e.g. "ytsearch5", "scsearch5"); `source` tags the
// resulting tracks and decides how originalUrl is built.
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithYtDlpProvider(std::string_view query,
std::string_view searchPrefix,
Api::TrackSource source);
// Fetch video durations for search results (batch API call)
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
const std::vector<std::string>& videoIds);
// Internal methods for playlist resolution
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
fetchPlaylistItems(std::string_view playlistId);
[[nodiscard]] Api::Result<Api::TrackInfo>
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
// Build YouTube API v3 URL for playlist items
[[nodiscard]] std::string buildPlaylistApiUrl(
std::string_view playlistId,
const std::optional<std::string>& pageToken =
std::nullopt) const;
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YtDlpManager> ytDlpManager_;
std::unique_ptr<UrlShortener> urlShortener_;
// Worker pool backing the parallel API/resolution fan-outs. Bounds
// thread reuse instead of spawning an OS thread per std::async call.
Void::Concurrency::ThreadPool pool_;
std::atomic<bool> initialized_{false};
mutable std::mutex mutex_;
// Configuration
std::optional<std::string> apiKey_;
mutable std::mutex configMutex_;
size_t maxConcurrentResolutions_ = 4;
bool urlShorteningEnabled_ = true;
// Populate shortened URLs for tracks
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
void populateShortenedUrl(Api::TrackInfo& track);
};
} // namespace Echoion::Core