From 499143050b445aff5d7d2e47191de1d100b54925 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 24 Jun 2026 21:11:20 +0300 Subject: [PATCH] Implement reload commands; fix SOCKS5 playback; API->yt-dlp search fallback F1 (reload commands): Core registers itself as Api::ICoreInterface in the service registry; !reloadconfig and !reload resolve it via ctx.service and call Core::reloadConfig() (which reloads config.json from disk), replacing the old placeholder replies. F2 (SOCKS5 playback): ffmpeg can't use a SOCKS5 proxy, so it connected directly to the IP-locked googlevideo URL and timed out; the fallback then buffered the whole (705 MB) body in memory and tripped Void::Net's body limit. New YouTubeClient::downloadAudioToFile() re-downloads the audio with yt-dlp (which handles SOCKS5 + writes to disk) by video id and ffmpeg opens the local file. MusicManager::downloadAudioForPlayback now uses it, and the play-open path short-circuits straight to the download when the proxy is SOCKS5 (skipping the doomed ~15 s ffmpeg attempt); HTTP/no-proxy keeps stream-first-then-download. F3 (API fallback): YouTubeClient::search() now falls back to yt-dlp when the Data API path errors (bad/expired key, quota, network), mirroring what fetchPlaylistItems already did. Build green; runtime behaviour to be verified on the live bot. Co-Authored-By: Claude Opus 4.8 --- include/echoion/core/Core.hpp | 2 +- include/echoion/core/MusicManager.hpp | 2 +- include/echoion/core/YouTubeClient.hpp | 8 ++ .../echoion/core/commands/ReloadCommand.hpp | 24 +++- .../core/commands/ReloadConfigCommand.hpp | 22 ++-- src/Core.cpp | 4 + src/MusicManager.cpp | 124 +++++++++--------- src/YouTubeClient.cpp | 85 +++++++++++- 8 files changed, 190 insertions(+), 81 deletions(-) diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index b271a3f..0a44eef 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -125,7 +125,7 @@ namespace Echoion::Core // Additional methods for internal use (not in interface) void setAudioDataCallback( const MusicManager::AudioDataCallback& callback); - Api::Result reloadConfig(); + Api::Result reloadConfig() override; // Internal implementations using full types Api::Result playTrack(const Api::TrackInfo& track); diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 79ca1d4..ce0c62d 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -201,7 +201,7 @@ namespace Echoion::Core // Download audio through proxy for playback [[nodiscard]] Api::Result - downloadAudioForPlayback(const std::string& url); + downloadAudioForPlayback(const Api::TrackInfo& track); void cleanupTempFile(const std::string& filepath); // Prefetch next track for seamless transitions diff --git a/include/echoion/core/YouTubeClient.hpp b/include/echoion/core/YouTubeClient.hpp index 64afbd4..33a140d 100644 --- a/include/echoion/core/YouTubeClient.hpp +++ b/include/echoion/core/YouTubeClient.hpp @@ -101,6 +101,14 @@ namespace Echoion::Core [[nodiscard]] Api::Result getAudioStreamUrl(std::string_view videoId); + // 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 + 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); diff --git a/include/echoion/core/commands/ReloadCommand.hpp b/include/echoion/core/commands/ReloadCommand.hpp index 41a167d..50186d9 100644 --- a/include/echoion/core/commands/ReloadCommand.hpp +++ b/include/echoion/core/commands/ReloadCommand.hpp @@ -1,6 +1,7 @@ #pragma once #include "Command.hpp" +#include #include #include @@ -13,11 +14,24 @@ namespace Echoion::Core void execute(const CommandContext& ctx) override { - // This is a placeholder - actual reload is handled by the - // plugin - Void::Log::info("ReloadCommand", "{}", "Reload requested by user"); - ctx.reply("Reload is handled automatically by the plugin. Use " - "the TS3 plugin menu to reload the core."); + Void::Log::info("ReloadCommand", "{}", + "Reload requested by user"); + + // Reload configuration from disk. A full core/plugin reload is + // driven from the TS plugin menu (that lives in the plugin). + if (auto core = ctx.service()) { + auto result = core->reloadConfig(); + if (result) { + ctx.reply("✅ Configuration reloaded. For a full core " + "reload, use the TS plugin menu."); + } else { + ctx.reply(std::string("❌ Config reload failed: ") + + result.error().message); + } + } else { + ctx.reply("Reload is handled by the plugin. Use the TS " + "plugin menu to reload the core."); + } } std::string_view getDescription() const override diff --git a/include/echoion/core/commands/ReloadConfigCommand.hpp b/include/echoion/core/commands/ReloadConfigCommand.hpp index 4f0321f..38c15f5 100644 --- a/include/echoion/core/commands/ReloadConfigCommand.hpp +++ b/include/echoion/core/commands/ReloadConfigCommand.hpp @@ -1,8 +1,8 @@ #pragma once #include "Command.hpp" +#include #include -#include "echoion/core/Core.hpp" // For Core::reloadConfig #include namespace Echoion::Core @@ -15,15 +15,19 @@ namespace Echoion::Core void execute(const CommandContext& ctx) override { try { - // Note: ctx.core is not directly accessible, we need to use - // the MusicManager's core reference For now, reply with - // instructions - ctx.reply( - "Config reload: Please use !reload command or restart " - "the bot for config changes to take effect."); + auto core = ctx.service(); + if (!core) { + ctx.reply("Config reload is unavailable right now."); + return; + } - // TODO: Add core reference to CommandContext so commands - // can call Core methods + auto result = core->reloadConfig(); + if (result) { + ctx.reply("✅ Configuration reloaded from disk."); + } else { + ctx.reply(std::string("❌ Failed to reload config: ") + + result.error().message); + } } catch (const std::exception& e) { Void::Log::error("ReloadConfigCommand", "{}", std::format( "ReloadConfig command exception: {}", e.what())); diff --git a/src/Core.cpp b/src/Core.cpp index 355465e..0dd45ce 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -353,6 +353,10 @@ namespace Echoion::Core registry_.provide( alias(&configManager_)); registry_.provide(alias(&eventBus_)); + // Expose Core itself so commands can reach Core operations + // (e.g. reloadConfig) through the registry. + registry_.provide( + alias(static_cast(this))); if (networkClient_) { registry_.provide(networkClient_); } diff --git a/src/MusicManager.cpp b/src/MusicManager.cpp index 6f34386..04b28e9 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -233,30 +233,54 @@ namespace Echoion::Core } Void::Log::debug("MusicManager", "{}", "Opening audio source..."); - auto openResult = audioDecoder_->openSource(*streamUrl); - // If direct open fails and we have a proxy, try downloading through - // proxy const auto& networkConfig = configManager_->getNetwork(); - if (!openResult && networkConfig.proxy.has_value() && - networkConfig.proxy->enabled()) { - Void::Log::info("MusicManager", "{}", - "Direct open failed, trying download through proxy..."); - auto downloadedPath = downloadAudioForPlayback(*streamUrl); - if (downloadedPath) { - Void::Log::info("MusicManager", "{}", std::format("Downloaded audio to: {}", - *downloadedPath)); - openResult = audioDecoder_->openSource(*downloadedPath); - if (openResult) { - // Track temp file for cleanup - std::unique_lock lock( - tempFilesMutex_); - tempFiles_.insert(*downloadedPath); - } - } else { - Void::Log::warn("MusicManager", "{}", - std::format("Failed to download through proxy: {}", + const bool socks5Proxy = + networkConfig.proxy.has_value() && + networkConfig.proxy->enabled() && + networkConfig.proxy->kind == + Void::Net::ProxyConfig::Kind::Socks5; + + // Download the audio via yt-dlp and open the resulting local file. + auto downloadAndOpen = [&]() -> Api::Result { + auto downloadedPath = + downloadAudioForPlayback(currentTrack_->track); + if (!downloadedPath) { + Void::Log::warn( + "MusicManager", "{}", + std::format("Failed to download audio: {}", downloadedPath.error().message)); + return std::unexpected(downloadedPath.error()); + } + Void::Log::info("MusicManager", "{}", + std::format("Downloaded audio to: {}", + *downloadedPath)); + auto opened = audioDecoder_->openSource(*downloadedPath); + if (opened) { + std::unique_lock lock(tempFilesMutex_); + tempFiles_.insert(*downloadedPath); + } + return opened; + }; + + Api::Result openResult; + if (socks5Proxy) { + // ffmpeg can't use a SOCKS5 proxy for the IP-locked stream URL; + // go straight to the yt-dlp download (which can). + Void::Log::info( + "MusicManager", "{}", + "SOCKS5 proxy configured: downloading audio via yt-dlp..."); + openResult = downloadAndOpen(); + } else { + openResult = audioDecoder_->openSource(*streamUrl); + // HTTP/no proxy: if a direct open fails but a proxy is set, + // fall back to a yt-dlp download through it. + if (!openResult && networkConfig.proxy.has_value() && + networkConfig.proxy->enabled()) { + Void::Log::info("MusicManager", "{}", + "Direct open failed, trying download via " + "yt-dlp through proxy..."); + openResult = downloadAndOpen(); } } @@ -2128,55 +2152,27 @@ Subscriptions are persistent across server reconnects.)"; } Api::Result - MusicManager::downloadAudioForPlayback(const std::string& url) + MusicManager::downloadAudioForPlayback(const Api::TrackInfo& track) { - if (!networkClient_) { + if (!youTubeClient_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "NetworkClient not available"); + "YouTube client not available"); } - // Create temp file path - auto cacheDir = - std::filesystem::temp_directory_path() / "echoion_audio"; - std::error_code ec; - std::filesystem::create_directories(cacheDir, ec); - - auto timestamp = - std::chrono::system_clock::now().time_since_epoch().count(); - auto tempPath = cacheDir / std::format("audio_{}.tmp", timestamp); - - // Download the file - Void::Log::info("MusicManager", "{}", - std::format("Downloading audio from: {}...", url.substr(0, 60))); - - auto response = networkClient_->get(url); - if (!response) { - return Api::fail(Api::ErrorCode::NetworkError, - std::format("Failed to download audio: {}", - response.error().message)); + // yt-dlp re-downloads through the configured proxy (it handles SOCKS5, + // which ffmpeg cannot) and writes the audio to disk, sidestepping both + // the IP-locked stream URL and any in-memory body limit. Re-download by + // the original video id/URL, not the (IP-locked) CDN stream URL. + const std::string idOrUrl = + !track.originalUrl.empty() ? track.originalUrl : track.id; + if (idOrUrl.empty()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Track has no id/URL to download"); } - if (response->status != 200) { - return Api::fail( - Api::ErrorCode::NetworkError, - std::format("HTTP error {}: {}", response->status, - response->body.substr(0, 100))); - } - - // Write to temp file - std::ofstream file(tempPath, std::ios::binary); - if (!file) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Failed to create temp file"); - } - - file.write(response->body.data(), response->body.size()); - file.close(); - - Void::Log::info("MusicManager", "{}", std::format("Downloaded {} bytes to {}", - response->body.size(), tempPath.string())); - - return tempPath.string(); + const auto cacheDir = + (std::filesystem::temp_directory_path() / "echoion_audio").string(); + return youTubeClient_->downloadAudioToFile(idOrUrl, cacheDir); } void MusicManager::cleanupTempFile(const std::string& filepath) diff --git a/src/YouTubeClient.cpp b/src/YouTubeClient.cpp index a9e50ab..a737ac4 100644 --- a/src/YouTubeClient.cpp +++ b/src/YouTubeClient.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -226,6 +227,77 @@ namespace Echoion::Core Api::ErrorCode::NotFound, "Failed to get audio URL from yt-dlp"); } + 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) { @@ -365,9 +437,20 @@ namespace Echoion::Core // Use YouTube Data API v3 if key is available if (hasApiKey()) { - Void::Log::info("YouTubeClient", "{}", + 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 "