Initial commit

This commit is contained in:
faumaray committed 2026-02-01 23:04:49 +03:00
commit a583c17916
56 files changed
+11025

No files matched your search

+456
View File
@@ -0,0 +1,456 @@
#include "echoion/core/YtDlpManager.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
#include <fstream>
#include <cstdlib>
#include <array>
#include <chrono>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Echoion::Core {
YtDlpManager::YtDlpManager(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)) {
}
YtDlpManager::~YtDlpManager() = default;
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<void> YtDlpManager::initialize() {
{
std::lock_guard<std::mutex> 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, checking for updates...");
// Try to update, but don't fail if update fails
auto result = update();
if (!result) {
ECHOION_LOG_WARNING(std::format("yt-dlp update failed: {}", result.error().toString()));
}
}
} // 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));
std::lock_guard<std::mutex> lock(mutex_);
initialized_ = true;
return {};
}
Api::Result<void> 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<Api::HttpHeader> 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<void> 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<std::chrono::hours>(now - last).count();
// Update if older than 7 days
return diff > (7 * 24);
} catch (...) {
return true;
}
}
Api::Result<void> YtDlpManager::update() {
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
cookiesFromBrowser_ = browser;
ECHOION_LOG_INFO(std::format("yt-dlp will use cookies from browser: {}", browser));
}
std::vector<std::string> YtDlpManager::getCookieArgs() const {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::string> 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<std::string>& args) const {
if (!std::filesystem::exists(executablePath_)) {
return "";
}
std::string cmd = executablePath_.string();
// Add cookie arguments first
auto cookieArgs = getCookieArgs();
for (const auto& arg : cookieArgs) {
cmd += " ";
// Simple escaping
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
for (const auto& arg : args) {
cmd += " ";
// Simple escaping - wrap in quotes if contains spaces or special chars
if (arg.find(' ') != std::string::npos ||
arg.find('"') != std::string::npos ||
arg.find('\\') != std::string::npos) {
// Escape existing quotes and wrap
std::string escaped;
for (char c : arg) {
if (c == '"') escaped += "\\";
escaped += c;
}
cmd += "\"" + escaped + "\"";
} else {
cmd += arg;
}
}
// Suppress stderr
#ifdef _WIN32
cmd += " 2>nul";
#else
cmd += " 2>/dev/null";
#endif
// Add timeout to prevent hanging (10 seconds for version check, 60 for download)
bool isVersionCheck = (args.size() == 1 && args[0] == "--version");
int timeoutSec = isVersionCheck ? 10 : 60;
#ifdef __linux__
cmd = std::format("timeout {} {}", timeoutSec, cmd);
#elif defined(__APPLE__)
cmd = std::format("gtimeout {} {} 2>/dev/null || {}", timeoutSec, cmd, cmd);
#endif
ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd));
std::array<char, 8192> buffer;
std::string result;
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution");
return "";
}
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result += buffer.data();
}
pclose(pipe);
return result;
}
} // namespace Echoion::Core