Initial commit
This commit is contained in:
commit
a583c17916
56 files changed
+11025
No files matched your search
@@ -0,0 +1,373 @@
|
||||
#include "echoion/core/YouTubeClient.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <format>
|
||||
#include <algorithm>
|
||||
#include <regex>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
|
||||
: networkClient_(std::move(networkClient))
|
||||
, ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)) {
|
||||
}
|
||||
|
||||
YouTubeClient::~YouTubeClient() {
|
||||
shutdown();
|
||||
}
|
||||
|
||||
Api::Result<void> 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;
|
||||
}
|
||||
|
||||
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::shutdown() {
|
||||
initialized_ = false;
|
||||
}
|
||||
|
||||
bool YouTubeClient::isAvailable() const {
|
||||
return ytDlpManager_ && ytDlpManager_->isAvailable();
|
||||
}
|
||||
|
||||
std::string YouTubeClient::getYtDlpVersion() const {
|
||||
if (!ytDlpManager_) return "";
|
||||
return ytDlpManager_->getVersion();
|
||||
}
|
||||
|
||||
Api::Result<void> YouTubeClient::updateYtDlp() {
|
||||
if (!ytDlpManager_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"yt-dlp manager not initialized"));
|
||||
}
|
||||
return ytDlpManager_->update();
|
||||
}
|
||||
|
||||
Api::Result<std::string> YouTubeClient::getAudioStreamUrl(std::string_view videoId) {
|
||||
if (!initialized_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"YouTubeClient not initialized"));
|
||||
}
|
||||
|
||||
if (!ytDlpManager_->isAvailable()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"yt-dlp not available"));
|
||||
}
|
||||
|
||||
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)
|
||||
std::string url = std::format("https://www.youtube.com/watch?v={}", videoId);
|
||||
// Fallback: try any audio format
|
||||
ECHOION_LOG_INFO("Trying any audio format...");
|
||||
|
||||
std::string result = ytDlpManager_->execute({
|
||||
url,
|
||||
"-f", "bestaudio/251/140",
|
||||
"-g",
|
||||
"--no-warnings"
|
||||
});
|
||||
|
||||
if (!result.empty() && result.back() == '\n') {
|
||||
result.pop_back();
|
||||
}
|
||||
|
||||
if (!result.empty() && result.find("http") == 0) {
|
||||
ECHOION_LOG_INFO("Successfully got audio URL from yt-dlp (fallback)");
|
||||
return result;
|
||||
}
|
||||
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
"Failed to get audio URL from yt-dlp"));
|
||||
}
|
||||
|
||||
Api::Result<std::string> YouTubeClient::getStreamUrl(std::string_view videoId) {
|
||||
return getAudioStreamUrl(videoId);
|
||||
}
|
||||
|
||||
Api::Result<Api::TrackInfo> YouTubeClient::getVideoInfo(std::string_view videoId) {
|
||||
if (!initialized_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"YouTubeClient not initialized"));
|
||||
}
|
||||
|
||||
if (!ytDlpManager_->isAvailable()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"yt-dlp not available"));
|
||||
}
|
||||
|
||||
std::string url = std::format("https://www.youtube.com/watch?v={}", videoId);
|
||||
std::string jsonStr = ytDlpManager_->execute({
|
||||
url,
|
||||
"-J",
|
||||
"--no-warnings"
|
||||
});
|
||||
|
||||
if (jsonStr.empty()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
||||
"yt-dlp failed to get video info"));
|
||||
}
|
||||
|
||||
try {
|
||||
glz::generic json;
|
||||
if (glz::read_json(json, jsonStr)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
"Failed to parse yt-dlp output"));
|
||||
}
|
||||
|
||||
Api::TrackInfo info;
|
||||
if (json.contains("id")) info.id = json["id"].get<std::string>();
|
||||
if (json.contains("title")) info.title = json["title"].get<std::string>();
|
||||
if (json.contains("uploader")) info.artist = json["uploader"].get<std::string>();
|
||||
if (json.contains("duration")) {
|
||||
info.duration = std::chrono::seconds(static_cast<int64_t>(json["duration"].get<double>()));
|
||||
}
|
||||
if (json.contains("thumbnail")) info.thumbnailUrl = json["thumbnail"].get<std::string>();
|
||||
|
||||
// Set originalUrl so we can extract video ID later for streaming
|
||||
info.originalUrl = url;
|
||||
info.source = Api::TrackSource::YouTube;
|
||||
return info;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("Exception parsing yt-dlp output: {}", e.what())));
|
||||
}
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult> YouTubeClient::search(std::string_view query,
|
||||
std::optional<std::string> pageToken) {
|
||||
|
||||
if (!initialized_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"YouTubeClient not initialized"));
|
||||
}
|
||||
|
||||
if (!ytDlpManager_->isAvailable()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"yt-dlp not available"));
|
||||
}
|
||||
|
||||
// yt-dlp search format: ytsearch5:query
|
||||
std::string searchQuery = std::format("ytsearch5:{}", query);
|
||||
|
||||
std::string jsonStr = ytDlpManager_->execute({
|
||||
searchQuery,
|
||||
"-J",
|
||||
"--flat-playlist",
|
||||
"--no-warnings"
|
||||
});
|
||||
|
||||
if (jsonStr.empty()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
||||
"yt-dlp search failed"));
|
||||
}
|
||||
|
||||
try {
|
||||
glz::generic json;
|
||||
if (glz::read_json(json, jsonStr)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
"Failed to parse yt-dlp search output"));
|
||||
}
|
||||
|
||||
Api::SearchResult result;
|
||||
result.query = std::string(query);
|
||||
|
||||
if (json.contains("entries") && json["entries"].is_array()) {
|
||||
for (const auto& entry : json["entries"].get<std::vector<glz::generic>>()) {
|
||||
if (!entry.contains("id")) continue;
|
||||
|
||||
Api::TrackInfo track;
|
||||
track.id = entry["id"].get<std::string>();
|
||||
if (entry.contains("title")) track.title = entry["title"].get<std::string>();
|
||||
if (entry.contains("uploader")) track.artist = entry["uploader"].get<std::string>();
|
||||
if (entry.contains("duration")) {
|
||||
track.duration = std::chrono::seconds(static_cast<int64_t>(entry["duration"].get<double>()));
|
||||
}
|
||||
if (entry.contains("thumbnail")) track.thumbnailUrl = entry["thumbnail"].get<std::string>();
|
||||
// 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;
|
||||
|
||||
result.tracks.push_back(track);
|
||||
}
|
||||
}
|
||||
|
||||
result.totalResults = result.tracks.size();
|
||||
return result;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("Exception parsing yt-dlp search: {}", e.what())));
|
||||
}
|
||||
}
|
||||
|
||||
Api::Result<Api::PlaylistInfo> YouTubeClient::getPlaylist(std::string_view playlistId) {
|
||||
if (!initialized_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"YouTubeClient not initialized"));
|
||||
}
|
||||
|
||||
if (!ytDlpManager_->isAvailable()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"yt-dlp not available"));
|
||||
}
|
||||
|
||||
std::string url = std::format("https://www.youtube.com/playlist?list={}", playlistId);
|
||||
|
||||
std::string jsonStr = ytDlpManager_->execute({
|
||||
url,
|
||||
"-J",
|
||||
"--flat-playlist",
|
||||
"--no-warnings"
|
||||
});
|
||||
|
||||
if (jsonStr.empty()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NetworkError,
|
||||
"yt-dlp playlist fetch failed"));
|
||||
}
|
||||
|
||||
try {
|
||||
glz::generic json;
|
||||
if (glz::read_json(json, jsonStr)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
"Failed to parse yt-dlp playlist output"));
|
||||
}
|
||||
|
||||
Api::PlaylistInfo info;
|
||||
if (json.contains("title")) info.name = json["title"].get<std::string>();
|
||||
if (json.contains("id")) info.id = json["id"].get<std::string>();
|
||||
|
||||
if (json.contains("entries") && json["entries"].is_array()) {
|
||||
for (const auto& entry : json["entries"].get<std::vector<glz::generic>>()) {
|
||||
if (!entry.contains("id")) continue;
|
||||
|
||||
Api::TrackInfo track;
|
||||
track.id = entry["id"].get<std::string>();
|
||||
if (entry.contains("title")) track.title = entry["title"].get<std::string>();
|
||||
if (entry.contains("uploader")) track.artist = entry["uploader"].get<std::string>();
|
||||
if (entry.contains("duration")) {
|
||||
track.duration = std::chrono::seconds(static_cast<int64_t>(entry["duration"].get<double>()));
|
||||
}
|
||||
// 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;
|
||||
|
||||
info.tracks.push_back(track);
|
||||
}
|
||||
}
|
||||
|
||||
return info;
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("Exception parsing yt-dlp playlist: {}", e.what())));
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::string> 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<Api::HttpHeader> 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<std::string> 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("youtube.com") != std::string::npos || url.find("youtu.be") != std::string::npos;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Reference in new issue
Block a user