#include "echoion/core/Logger.hpp" #include "echoion/core/YtDlpManager.hpp" #include #include #include #include #include #include #include #ifdef _WIN32 #include #else #include #include #endif namespace Echoion::Core { YtDlpManager::YtDlpManager(std::shared_ptr networkClient) : networkClient_(std::move(networkClient)) { } YtDlpManager::~YtDlpManager() { stopThreadPool(); } std::filesystem::path YtDlpManager::getStorageDir() const { // Store in ~/.local/share/echoion/yt-dlp on Linux // or %APPDATA%/echoion/yt-dlp on Windows // or ~/Library/Application Support/echoion/yt-dlp on macOS std::filesystem::path homeDir; #ifdef _WIN32 const char* appData = std::getenv("APPDATA"); if (appData) { homeDir = appData; } else { homeDir = std::filesystem::temp_directory_path(); } return homeDir / "echoion" / "yt-dlp"; #else const char* home = std::getenv("HOME"); if (home) { homeDir = home; } else { homeDir = std::filesystem::temp_directory_path(); } #ifdef __APPLE__ return homeDir / "Library" / "Application Support" / "echoion" / "yt-dlp"; #else return homeDir / ".local" / "share" / "echoion" / "yt-dlp"; #endif #endif } std::string YtDlpManager::getExecutableName() const { #ifdef _WIN32 return "yt-dlp.exe"; #else return "yt-dlp"; #endif } std::string YtDlpManager::getDownloadUrl() const { #ifdef _WIN32 return std::string(YTDLP_DOWNLOAD_WINDOWS); #elif defined(__APPLE__) return std::string(YTDLP_DOWNLOAD_MACOS); #else return std::string(YTDLP_DOWNLOAD_LINUX); #endif } std::filesystem::path YtDlpManager::getExecutablePath() const { if (!executablePath_.empty()) { return executablePath_; } return getStorageDir() / getExecutableName(); } bool YtDlpManager::isAvailable() const { return std::filesystem::exists(getExecutablePath()); } Api::Result YtDlpManager::initialize() { { std::lock_guard lock(mutex_); if (initialized_) { return {}; } ECHOION_LOG_INFO("Initializing yt-dlp manager..."); // Create storage directory if needed std::filesystem::path storageDir = getStorageDir(); ECHOION_LOG_DEBUG( std::format("yt-dlp storage dir: {}", storageDir.string())); if (!std::filesystem::exists(storageDir)) { ECHOION_LOG_INFO("Creating yt-dlp storage directory..."); try { std::filesystem::create_directories(storageDir); } catch (const std::exception& e) { return std::unexpected(Api::Error( Api::ErrorCode::ServiceUnavailable, std::format( "Failed to create yt-dlp storage directory: {}", e.what()))); } } executablePath_ = storageDir / getExecutableName(); ECHOION_LOG_DEBUG(std::format("yt-dlp executable path: {}", executablePath_.string())); // Check if yt-dlp exists bool exists = std::filesystem::exists(executablePath_); ECHOION_LOG_DEBUG(std::format("yt-dlp exists: {}", exists)); if (!exists) { ECHOION_LOG_INFO("yt-dlp not found, downloading..."); auto result = downloadYtDlp(); if (!result) { return result; } } else if (shouldUpdate()) { ECHOION_LOG_INFO( "yt-dlp may be outdated, updating in background..."); // Start async update to avoid blocking initialization std::thread([this]() { auto result = update(); if (!result) { ECHOION_LOG_WARNING( std::format("yt-dlp update failed: {}", result.error().toString())); } }).detach(); } } // Release lock before calling getVersion() to avoid deadlock with // getCookieArgs() // Verify it works (outside lock to prevent deadlock with // execute()->getCookieArgs()) ECHOION_LOG_INFO("Checking yt-dlp version..."); std::string version = getVersion(); if (version.empty()) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "yt-dlp executable not working")); } ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version)); // Start thread pool for async operations startThreadPool(); std::lock_guard lock(mutex_); initialized_ = true; return {}; } void YtDlpManager::startThreadPool() { stopThreadPool(); // Clear any existing threads first // Auto-adjust thread pool size based on hardware unsigned int hardwareThreads = std::thread::hardware_concurrency(); if (hardwareThreads > 0 && threadPoolSize_ > hardwareThreads / 2) { threadPoolSize_ = std::max(1u, hardwareThreads / 2); ECHOION_LOG_INFO(std::format( "Auto-adjusted yt-dlp thread pool to {} threads (hardware: {})", threadPoolSize_, hardwareThreads)); } ECHOION_LOG_INFO(std::format( "Starting yt-dlp thread pool with {} threads", threadPoolSize_)); for (size_t i = 0; i < threadPoolSize_; ++i) { threadPool_.emplace_back([this] { workerThread(); }); } } void YtDlpManager::stopThreadPool() { stopThreads_ = true; taskCv_.notify_all(); for (auto& thread : threadPool_) { if (thread.joinable()) { thread.join(); } } threadPool_.clear(); stopThreads_ = false; } void YtDlpManager::workerThread() { while (!stopThreads_.load()) { std::packaged_task task; { std::unique_lock lock(taskMutex_); taskCv_.wait(lock, [this] { return !taskQueue_.empty() || stopThreads_.load(); }); if (stopThreads_.load()) { return; } if (!taskQueue_.empty()) { task = std::move(taskQueue_.front()); taskQueue_.pop(); } } if (task.valid()) { task(); } } } void YtDlpManager::setThreadPoolSize(size_t size) { if (size == 0) { size = 1; } if (size > 16) { size = 16; // Cap at 16 threads } std::lock_guard lock(mutex_); if (threadPoolSize_ != size) { threadPoolSize_ = size; if (initialized_) { // Restart thread pool with new size stopThreadPool(); startThreadPool(); } } } size_t YtDlpManager::getThreadPoolSize() const { std::lock_guard lock(mutex_); return threadPoolSize_; } void YtDlpManager::setProxyConfig( const std::optional& proxy) { std::lock_guard lock(proxyMutex_); proxyConfig_ = proxy; if (proxy.has_value() && proxy->isValid()) { ECHOION_LOG_INFO(std::format("yt-dlp proxy configured: {}:{}", proxy->host, proxy->port)); } else { ECHOION_LOG_INFO("yt-dlp proxy cleared"); } } std::optional YtDlpManager::getProxyConfig() const { std::lock_guard lock(proxyMutex_); return proxyConfig_; } std::vector YtDlpManager::getProxyArgs() const { std::lock_guard lock(proxyMutex_); std::vector proxyArgs; if (!proxyConfig_.has_value() || !proxyConfig_->isValid()) { return proxyArgs; } const auto& proxy = *proxyConfig_; std::string proxyUrl; if (proxy.isSocks5()) { if (proxy.requiresAuth()) { proxyUrl = std::format("socks5://{}:{}@{}:{}", *proxy.username, *proxy.password, proxy.host, proxy.port); } else { proxyUrl = std::format("socks5://{}:{}", proxy.host, proxy.port); } } else { if (proxy.requiresAuth()) { proxyUrl = std::format("http://{}:{}@{}:{}", *proxy.username, *proxy.password, proxy.host, proxy.port); } else { proxyUrl = std::format("http://{}:{}", proxy.host, proxy.port); } } proxyArgs.push_back("--proxy"); proxyArgs.push_back(proxyUrl); return proxyArgs; } Api::Result YtDlpManager::downloadYtDlp() { if (!networkClient_) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Network client not available")); } std::string downloadUrl = getDownloadUrl(); ECHOION_LOG_INFO( std::format("Downloading yt-dlp from: {}", downloadUrl)); std::vector headers = { {"User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}}; // Follow redirects manually (GitHub releases use 302 redirects) Api::HttpResponse response; int redirectCount = 0; constexpr int maxRedirects = 5; while (redirectCount < maxRedirects) { auto result = networkClient_->get(downloadUrl, headers); if (!result) { return std::unexpected( Api::Error(Api::ErrorCode::NetworkError, std::format("Failed to download yt-dlp: {}", result.error().message))); } response = std::move(*result); // Check for redirect (3xx status codes) if (response.statusCode >= 300 && response.statusCode < 400) { auto location = response.getHeader("location"); if (!location.has_value()) { return std::unexpected(Api::Error( Api::ErrorCode::NetworkError, "Redirect response missing Location header")); } // Handle relative URLs std::string newUrl = *location; if (newUrl.starts_with("/")) { // Relative to host - extract host from current URL auto pos = downloadUrl.find("://"); if (pos != std::string::npos) { auto pathStart = downloadUrl.find("/", pos + 3); std::string base = (pathStart != std::string::npos) ? downloadUrl.substr(0, pathStart) : downloadUrl; newUrl = base + newUrl; } } ECHOION_LOG_INFO(std::format("Following redirect (HTTP {}): {}", response.statusCode, newUrl)); downloadUrl = newUrl; redirectCount++; continue; } break; } if (!response.isSuccess()) { return std::unexpected( Api::Error(Api::ErrorCode::NetworkError, std::format("Failed to download yt-dlp: HTTP {}", response.statusCode))); } ECHOION_LOG_INFO( std::format("Downloaded {} bytes", response.body.size())); // Write to file try { std::ofstream file(executablePath_, std::ios::binary); if (!file) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Failed to open yt-dlp file for writing")); } file.write(response.body.data(), response.body.size()); file.close(); } catch (const std::exception& e) { return std::unexpected(Api::Error( Api::ErrorCode::ServiceUnavailable, std::format("Failed to write yt-dlp file: {}", e.what()))); } // Make executable on Unix #ifndef _WIN32 auto execResult = makeExecutable(); if (!execResult) { return execResult; } #endif // Write timestamp file for update checking try { std::ofstream tsFile(getStorageDir() / ".last_update"); if (tsFile) { auto now = std::chrono::system_clock::now(); auto timestamp = std::chrono::system_clock::to_time_t(now); tsFile << timestamp; } } catch (...) { } ECHOION_LOG_INFO("yt-dlp downloaded successfully"); return {}; } Api::Result YtDlpManager::makeExecutable() { #ifdef _WIN32 return {}; // Windows doesn't need this #else if (chmod(executablePath_.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Failed to make yt-dlp executable")); } return {}; #endif } bool YtDlpManager::shouldUpdate() const { try { std::filesystem::path tsPath = getStorageDir() / ".last_update"; if (!std::filesystem::exists(tsPath)) { return true; } std::ifstream tsFile(tsPath); if (!tsFile) { return true; } std::time_t lastUpdate; tsFile >> lastUpdate; auto now = std::chrono::system_clock::now(); auto last = std::chrono::system_clock::from_time_t(lastUpdate); auto diff = std::chrono::duration_cast(now - last) .count(); // Update if older than 7 days return diff > (7 * 24); } catch (...) { return true; } } Api::Result YtDlpManager::update() { std::lock_guard lock(mutex_); ECHOION_LOG_INFO("Updating yt-dlp..."); // Backup current version std::filesystem::path backupPath = executablePath_.string() + ".backup"; try { if (std::filesystem::exists(executablePath_)) { std::filesystem::copy_file( executablePath_, backupPath, std::filesystem::copy_options::overwrite_existing); } } catch (...) { } // Download new version auto result = downloadYtDlp(); if (!result) { // Restore backup if available try { if (std::filesystem::exists(backupPath)) { std::filesystem::copy_file( backupPath, executablePath_, std::filesystem::copy_options::overwrite_existing); } } catch (...) { } return result; } // Remove backup try { std::filesystem::remove(backupPath); } catch (...) { } // Verify new version works std::string version = getVersion(); if (version.empty()) { return std::unexpected( Api::Error(Api::ErrorCode::ServiceUnavailable, "Updated yt-dlp not working")); } ECHOION_LOG_INFO(std::format("yt-dlp updated to: {}", version)); return {}; } std::string YtDlpManager::getVersion() const { if (!std::filesystem::exists(executablePath_)) { ECHOION_LOG_WARNING( "yt-dlp executable not found for version check"); return ""; } ECHOION_LOG_DEBUG("Executing yt-dlp --version..."); std::string result = execute({"--version"}); ECHOION_LOG_DEBUG(std::format("yt-dlp --version output: '{}'", result)); // Remove trailing newline if (!result.empty() && result.back() == '\n') { result.pop_back(); } return result; } void YtDlpManager::setCookiesPath(const std::string& path) { std::lock_guard lock(mutex_); cookiesPath_ = path; ECHOION_LOG_INFO(std::format("yt-dlp cookies path set to: {}", path)); } void YtDlpManager::setCookiesFromBrowser(const std::string& browser) { std::lock_guard lock(mutex_); cookiesFromBrowser_ = browser; ECHOION_LOG_INFO( std::format("yt-dlp will use cookies from browser: {}", browser)); } std::vector YtDlpManager::getCookieArgs() const { std::lock_guard lock(mutex_); std::vector cookieArgs; if (cookiesFromBrowser_.has_value()) { cookieArgs.push_back("--cookies-from-browser"); cookieArgs.push_back(*cookiesFromBrowser_); } else if (cookiesPath_.has_value()) { cookieArgs.push_back("--cookies"); cookieArgs.push_back(*cookiesPath_); } return cookieArgs; } std::string YtDlpManager::execute(const std::vector& args) const { return executeInternal(args).output; } YtDlpResult YtDlpManager::executeInternal( const std::vector& args) const { YtDlpResult result; result.success = false; result.exitCode = -1; if (!std::filesystem::exists(executablePath_)) { return result; } auto startTime = std::chrono::steady_clock::now(); // Assemble argv: proxy args, then cookie args, then caller args. // Void::Process::run executes the binary directly (no shell), so no // manual quoting/escaping is required and arguments are passed verbatim. std::vector processArgs; const auto proxyArgs = getProxyArgs(); processArgs.insert(processArgs.end(), proxyArgs.begin(), proxyArgs.end()); const auto cookieArgs = getCookieArgs(); processArgs.insert(processArgs.end(), cookieArgs.begin(), cookieArgs.end()); processArgs.insert(processArgs.end(), args.begin(), args.end()); // Timeout: 10s for the lightweight --version probe, 60s otherwise. const bool isVersionCheck = (args.size() == 1 && args[0] == "--version"); const auto timeout = std::chrono::seconds(isVersionCheck ? 10 : 60); ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {} ({} args)", executablePath_.string(), processArgs.size())); auto procResult = Void::Process::run(executablePath_, processArgs, {}, timeout); auto endTime = std::chrono::steady_clock::now(); result.executionTime = std::chrono::duration_cast(endTime - startTime); if (!procResult) { ECHOION_LOG_WARNING(std::format("Failed to execute yt-dlp: {}", procResult.error().message())); return result; } result.exitCode = procResult->exit_code; result.output = std::move(procResult->out); result.success = (result.exitCode == 0); return result; } std::future YtDlpManager::executeAsync(const std::vector& args) { std::packaged_task task( [this, args]() { return executeInternal(args); }); auto future = task.get_future(); { std::lock_guard lock(taskMutex_); taskQueue_.push(std::move(task)); } taskCv_.notify_one(); return future; } std::vector YtDlpManager::executeBatch( const std::vector>& argsList) { std::vector> futures; futures.reserve(argsList.size()); // Launch all tasks for (const auto& args : argsList) { futures.push_back(executeAsync(args)); } // Collect results std::vector results; results.reserve(argsList.size()); for (auto& future : futures) { results.push_back(future.get()); } return results; } } // namespace Echoion::Core