diff --git a/CMakeLists.txt b/CMakeLists.txt index a0a2778..ec84278 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,7 +116,7 @@ target_link_libraries(EchoionCore PUBLIC PkgConfig::LIBAV TBB::tbb - SQLite3::SQLite3 + SQLite::SQLite3 # VoidLibrary modules (migration target — replacing in-house infra) Void::Data Void::Functional @@ -131,6 +131,7 @@ target_link_libraries(EchoionCore Void::Net Void::Sqlite Void::Service + Void::ShortUrl Void::Plugin PRIVATE Threads::Threads @@ -220,6 +221,14 @@ install(FILES ) if(BUILD_TESTS) + add_executable(echoion_core_config_loader_tests + tests/test_config_loader.cpp) + target_include_directories(echoion_core_config_loader_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(echoion_core_config_loader_tests PRIVATE EchoionCore) + add_test(NAME echoion_core_config_loader_tests + COMMAND echoion_core_config_loader_tests) + add_executable(echoion_core_extension_state_tests tests/test_extension_state.cpp) target_include_directories(echoion_core_extension_state_tests PRIVATE @@ -236,6 +245,14 @@ if(BUILD_TESTS) target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore) add_test(NAME echoion_core_teamspeak_directory_tests COMMAND echoion_core_teamspeak_directory_tests) + + add_executable(echoion_core_url_shortener_tests + tests/test_url_shortener.cpp) + target_include_directories(echoion_core_url_shortener_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include") + target_link_libraries(echoion_core_url_shortener_tests PRIVATE EchoionCore) + add_test(NAME echoion_core_url_shortener_tests + COMMAND echoion_core_url_shortener_tests) endif() option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF) diff --git a/include/echoion/core/ConfigLoader.hpp b/include/echoion/core/ConfigLoader.hpp index 65b4162..e0bcf36 100644 --- a/include/echoion/core/ConfigLoader.hpp +++ b/include/echoion/core/ConfigLoader.hpp @@ -4,6 +4,7 @@ #include #include #include +#include namespace Echoion::Core { @@ -22,6 +23,12 @@ namespace Echoion::Core [[nodiscard]] static Api::Result loadFromFile(const std::filesystem::path& path); + // Parse, migrate, and normalize a complete JSON configuration. This + // is shared by file loading and live configuration updates so + // legacy fields have identical behavior through both entry points. + [[nodiscard]] static Api::Result + loadFromJson(std::string_view json); + // Save configuration to JSON file [[nodiscard]] static Api::Result saveToFile(const std::filesystem::path& path, @@ -34,7 +41,8 @@ namespace Echoion::Core [[nodiscard]] static Api::AppConfig createDefaultConfig(); // Clamp/normalize values that carry hard limits after loading - // (e.g. the yt-dlp concurrency cap). Applied by loadFromFile. + // (e.g. the yt-dlp concurrency cap). Applied by all load/update + // paths. static void normalize(Api::AppConfig& config); }; diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index 13394b7..75db1ed 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -136,6 +136,8 @@ namespace Echoion::Core void setAudioDataCallback( const MusicManager::AudioDataCallback& callback); Api::Result reloadConfig() override; + [[nodiscard]] Api::Result + managePluginsJson(const std::string& requestJson) override; // Internal implementations using full types Api::Result playTrack(const Api::TrackInfo& track); @@ -168,6 +170,7 @@ namespace Echoion::Core void updateWhisperList(); void setupRpcHandlers(); void setupEventBusSubscriptions() noexcept; + void applyUrlShorteningConfig(); // Fetch an online client's avatar bytes (TS local cache, then the // myTeamSpeak URL, then a legacy file-transfer download) and @@ -256,8 +259,9 @@ namespace Echoion::Core std::shared_ptr rpcServer_; #ifdef ECHOION_WITH_WEB - // Browser web interface: serves the static dashboard and same-origin - // RPC bridge. Bot control still terminates at the RPC server. + // Browser web interface: serves the static dashboard and + // same-origin RPC bridge. Bot control still terminates at the RPC + // server. std::shared_ptr webServer_; #endif diff --git a/include/echoion/core/PluginHost.hpp b/include/echoion/core/PluginHost.hpp index 86d6360..dc14cba 100644 --- a/include/echoion/core/PluginHost.hpp +++ b/include/echoion/core/PluginHost.hpp @@ -1,14 +1,20 @@ #pragma once #include +#include #include +#include +#include +#include #include #include #include #include +#include #include #include +#include #include namespace Echoion::Core @@ -19,41 +25,84 @@ namespace Echoion::Core class PluginHost final : public std::enable_shared_from_this { - public: - PluginHost(CommandManager& commands, std::shared_ptr music, - std::function isAdmin, - std::function)> mediaSink = {}); - ~PluginHost(); + public: - void loadDirectory(const std::filesystem::path& directory); - void setChangeCallback(std::function callback); - void dispatch(const Api::PluginEvent& event) const; - [[nodiscard]] Api::Result call( - std::string_view plugin, std::string_view method, - std::string params, uint64_t clientId) const; - [[nodiscard]] std::vector webAssets() const; - [[nodiscard]] std::vector names() const; - struct State { - std::string name; - std::string json; - std::uint32_t version{}; - }; - [[nodiscard]] std::vector snapshotStates() const; - void restoreStates(const std::vector& states); + struct Configuration { + std::filesystem::path configDirectory; + std::filesystem::path stateDirectory; + std::string publicUrl; + std::optional proxy; + std::string shortenerProvider = "url-shortener-internal"; + }; - private: - void publish(std::string_view name); - void unpublish(std::string_view name); - void notifyChanged() const; + PluginHost(CommandManager& commands, + std::shared_ptr + music, + std::function + isAdmin, + std::function)> + mediaSink, + Configuration configuration); + ~PluginHost(); - CommandManager& commands_; - std::shared_ptr music_; - std::function isAdmin_; - std::function)> mediaSink_; - Void::Plugin::PluginManager plugins_; - Void::Plugin::ReloadCallbackId reloadCallback_{}; - mutable std::mutex mutex_; - std::vector> sources_; - std::function changeCallback_; + void loadDirectory(const std::filesystem::path& directory); + void loadManagedDirectory(const std::filesystem::path& directory); + [[nodiscard]] Api::Result + manage(const std::string& requestJson); + void setChangeCallback(std::function callback); + void dispatch(const Api::PluginEvent& event) const; + [[nodiscard]] Api::Result + call(std::string_view plugin, std::string_view method, + std::string params, uint64_t clientId) const; + [[nodiscard]] std::vector webAssets() const; + [[nodiscard]] std::vector names() const; + [[nodiscard]] bool reconfigure(Configuration configuration); + [[nodiscard]] std::shared_ptr + shortener() const; + [[nodiscard]] Void::ShortUrl::ResolveResult + resolveShortLink(std::string_view key) const; + struct State { + std::string name; + std::string json; + std::uint32_t version{}; + }; + [[nodiscard]] std::vector snapshotStates() const; + void restoreStates(const std::vector& states); + + private: + + void publish(std::string_view name); + void unpublish(std::string_view name); + void notifyChanged() const; + [[nodiscard]] std::string + pluginConfiguration(std::string_view name) const; + [[nodiscard]] bool bindShortenerServices(); + + CommandManager& commands_; + std::shared_ptr music_; + std::function isAdmin_; + std::function)> mediaSink_; + Void::Plugin::PluginManager plugins_; + Void::Service::ServiceRegistry shortenerRegistry_; + Void::Service::ServiceRegistry internalShortenerRegistry_; + std::unique_ptr< + Void::Service::PluginServiceBinding> + shortenerBinding_; + std::unique_ptr< + Void::Service::PluginServiceBinding> + internalShortenerBinding_; + Void::Plugin::ReloadCallbackId reloadCallback_{}; + mutable std::mutex reconfigureMutex_; + mutable std::mutex mutex_; + Configuration configuration_; + std::vector> sources_; + std::function changeCallback_; + struct ManagedPlugin { + std::string version; + std::filesystem::path path; + }; + std::filesystem::path managedDirectory_; + std::unordered_map managed_; + std::unordered_map loadedPaths_; }; -} +} // namespace Echoion::Core diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp index 9732f9b..2eec830 100644 --- a/include/echoion/core/RpcDtos.hpp +++ b/include/echoion/core/RpcDtos.hpp @@ -97,7 +97,7 @@ namespace Echoion::Core::Dto int source = 0; std::optional thumbnailUrl; std::optional url; // originalUrl (play-by-url) - // Shortened faumaray.ru link when available; the web UI prefers + // Provider-generated shortened link when available; the web UI prefers // it for "open original link" (falls back to url). std::optional shortenedUrl; }; diff --git a/include/echoion/core/UrlShortener.hpp b/include/echoion/core/UrlShortener.hpp index 700f01f..f61b27d 100644 --- a/include/echoion/core/UrlShortener.hpp +++ b/include/echoion/core/UrlShortener.hpp @@ -1,58 +1,45 @@ #pragma once -#include "NetworkClient.hpp" -#include +#include #include +#include + #include +#include +#include #include -#include #include -#include +#include +#include +#include namespace Echoion::Core { - - // URL shortener service for faumaray.ru + // Thin Core adapter around the universal Void ShortUrl service. It owns no + // provider and performs no HTTP itself: the getter returns a pinned service + // instance for each operation, making calls safe across plugin hot reloads. class UrlShortener { public: - explicit UrlShortener(std::shared_ptr networkClient); - ~UrlShortener(); + using ProviderGetter = std::function< + std::shared_ptr()>; + + void setProvider(ProviderGetter provider); + void setSources(const std::vector& sources); - // Shorten a YouTube URL via faumaray.ru - // Returns shortened URL in format: https://faumaray.ru/xxxxx [[nodiscard]] Api::Result - shortenYouTubeUrl(std::string_view videoId); - - // Shorten any URL via faumaray.ru - [[nodiscard]] Api::Result - shortenUrl(std::string_view originalUrl); - - // Get cached shortened URL if available - [[nodiscard]] std::optional - getCachedUrl(std::string_view originalUrl) const; - - // Clear the URL cache - void clearCache(); - - // Set cache TTL (default: 24 hours) - void setCacheTtl(std::chrono::hours ttl); + shortenUrl(std::string_view originalUrl, + Api::TrackSource source) const; private: - struct CacheEntry { - std::string shortenedUrl; - std::chrono::system_clock::time_point timestamp; - }; + [[nodiscard]] bool sourceAllowed(Api::TrackSource source) const; - std::shared_ptr networkClient_; - mutable std::mutex cacheMutex_; - std::unordered_map cache_; - std::chrono::hours cacheTtl_{24}; - - // Clean expired entries from cache - void cleanExpiredCache(); + mutable std::mutex mutex_; + ProviderGetter provider_; + std::unordered_set sources_ = { + Api::TrackSource::YouTube}; }; } // namespace Echoion::Core diff --git a/include/echoion/core/YouTubeClient.hpp b/include/echoion/core/YouTubeClient.hpp index febc1e0..e54819d 100644 --- a/include/echoion/core/YouTubeClient.hpp +++ b/include/echoion/core/YouTubeClient.hpp @@ -102,8 +102,7 @@ namespace Echoion::Core nullptr, std::function onComplete = nullptr); - // Extract video ID from various YouTube URL formats (handles - // redirects for short URLs) + // Extract a video ID from known YouTube URL formats or a bare ID. [[nodiscard]] std::optional extractVideoId(std::string_view url); [[nodiscard]] static std::optional @@ -153,6 +152,14 @@ namespace Echoion::Core // Enable/disable URL shortening for track links void setUrlShorteningEnabled(bool enabled); + void setUrlShortenerProvider(UrlShortener::ProviderGetter provider); + void setUrlShorteningSources( + const std::vector& sources); + void setUrlShorteningTimeout(std::chrono::milliseconds timeout); + // Apply the provider-neutral policy to resolved tracks from any + // source. Operations are best-effort and timeout-bounded. + void populateShortenedUrls(std::vector& tracks); + void populateShortenedUrl(Api::TrackInfo& track); // Gate yt-dlp's periodic background self-update // (features.enableAutoUpdateCheck). Set before initialize(). @@ -208,9 +215,7 @@ namespace Echoion::Core mutable std::mutex configMutex_; size_t maxConcurrentResolutions_ = 4; bool urlShorteningEnabled_ = true; + std::chrono::milliseconds urlShorteningTimeout_{3000}; - // Populate shortened URLs for tracks - void populateShortenedUrls(std::vector& tracks); - void populateShortenedUrl(Api::TrackInfo& track); }; } // namespace Echoion::Core diff --git a/include/echoion/core/commands/Command.hpp b/include/echoion/core/commands/Command.hpp index 8d877db..fc888fc 100644 --- a/include/echoion/core/commands/Command.hpp +++ b/include/echoion/core/commands/Command.hpp @@ -94,7 +94,7 @@ namespace Echoion::Core return escapeMarkdown(text); } - // The best public link for a track: the shortened faumaray link when + // The best public link for a track: the provider-generated short link when // available, otherwise the original source URL (e.g. the YouTube or // Yandex Music page). Used so every list — search, queue, history, // favorites, stats — links to the real track, never the CDN/stream URL. diff --git a/src/ConfigLoader.cpp b/src/ConfigLoader.cpp index 2b42854..5e11947 100644 --- a/src/ConfigLoader.cpp +++ b/src/ConfigLoader.cpp @@ -1,13 +1,17 @@ -#include #include "Types.hpp" #include "echoion/core/ConfigLoader.hpp" #include #include #include +#include +#include +#include #include #include #include +#include #include +#include namespace Echoion::Core { @@ -23,29 +27,97 @@ namespace Echoion::Core if (config.bot.language != "en" && config.bot.language != "ru") { config.bot.language = "en"; } + + // Keep partially specified updater sections usable. Security-sensitive + // URL/key validation happens in the host updater before the policy is + // persisted or used; normalization here only supplies structural + // defaults for older configuration files. + if (!config.updates.sources.contains("official")) { + config.updates.sources.emplace("official", + Api::UpdateSourceConfig{}); + } + auto normalizeComponent = [](Api::UpdateComponentConfig& component) { + if (component.source.empty()) { + component.source = "official"; + } + if (component.channel.empty()) { + component.channel = "stable"; + } + }; + normalizeComponent(config.updates.runtime); + normalizeComponent(config.updates.core); + if (config.updates.plugins.source.empty()) { + config.updates.plugins.source = "official"; + } + if (config.updates.plugins.channel.empty()) { + config.updates.plugins.channel = "stable"; + } + + if (config.urlShortening.provider.empty()) { + config.urlShortening.provider = "url-shortener-internal"; + } + if (config.urlShortening.enabled && + config.urlShortening.provider == "url-shortener-internal" && + config.web.publicUrl.empty()) { + config.urlShortening.enabled = false; + Void::Log::warn( + "ConfigLoader", "{}", + "Internal URL shortening was disabled because web.publicUrl is " + "empty; configure the bot's public URL before enabling " + "url-shortener-internal"); + } + config.urlShortening.timeout = std::clamp( + config.urlShortening.timeout, std::chrono::milliseconds(100), + std::chrono::milliseconds(30000)); + const auto validSource = [](std::string_view source) { + static constexpr std::array kSources = { + "youtube", "yandex", "url", "soundcloud", "spotify", "plugin"}; + return std::ranges::find(kSources, source) != kSources.end(); + }; + std::erase_if( + config.urlShortening.sources, + [&](const std::string& source) { return !validSource(source); }); + std::ranges::sort(config.urlShortening.sources); + auto unique = std::ranges::unique(config.urlShortening.sources); + config.urlShortening.sources.erase(unique.begin(), unique.end()); } Api::Result ConfigLoader::loadFromFile(const std::filesystem::path& path) { if (!std::filesystem::exists(path)) { - return Api::fail(Api::ErrorCode::NotFound, - std::format("Configuration file not found: {}", - path.string())); + return Api::fail( + Api::ErrorCode::NotFound, + std::format("Configuration file not found: {}", path.string())); } std::ifstream file(path); if (!file.is_open()) { - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("Failed to open configuration file: {}", - path.string())); + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("Failed to open configuration file: {}", + path.string())); } std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); - auto parsed = Void::Json::parse(content); + auto config = loadFromJson(content); + if (!config) { + return std::unexpected(config.error()); + } + + std::cout << std::format("[INFO] Configuration loaded from {}", + path.string()) + << '\n'; + return config; + } + + Api::Result + ConfigLoader::loadFromJson(std::string_view json) + { + auto parsed = Void::Json::parse(json); if (!parsed) { return Api::fail( Api::ErrorCode::ParseError, @@ -66,11 +138,15 @@ namespace Echoion::Core } Api::AppConfig config = std::move(*result); + // Legacy files only had youtube.enableUrlShortening. An explicitly + // present new section always wins, including enabled=false. + if (parsed->find("urlShortening") == nullptr) { + config.urlShortening.enabled = config.youtube.enableUrlShortening; + config.urlShortening.provider = "url-shortener-internal"; + config.urlShortening.sources = {"youtube"}; + } normalize(config); - std::cout << std::format("[INFO] Configuration loaded from {}", - path.string()) - << '\n'; return config; } @@ -82,15 +158,17 @@ namespace Echoion::Core Void::Json::to_json(config), {.pretty = true}); std::ofstream file(path); if (!file.is_open()) { - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("Failed to write configuration file: {}", - path.string())); + return Api::fail( + Api::ErrorCode::PermissionDenied, + std::format("Failed to write configuration file: {}", + path.string())); } file << json; file.close(); - Void::Log::info("ConfigLoader", "{}", + Void::Log::info( + "ConfigLoader", "{}", std::format("Configuration saved to {}", path.string())); return {}; } @@ -130,6 +208,10 @@ namespace Echoion::Core config.youtube.ytDlpMaxConcurrent = 4; config.youtube.ytDlpAsyncEnabled = true; config.youtube.enableUrlShortening = true; + config.urlShortening.enabled = false; + config.urlShortening.provider = "url-shortener-internal"; + config.urlShortening.sources = {"youtube"}; + config.urlShortening.timeout = std::chrono::milliseconds(3000); // Default network config config.network.rpcEnabled = true; diff --git a/src/Core.cpp b/src/Core.cpp index de81e65..a09e4c1 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -43,87 +44,28 @@ namespace Echoion::Core return configPath.parent_path(); } - // Decode cached avatar bytes before serving them over HTTP. Returns - // empty on malformed input. -#ifdef ECHOION_WITH_WEB - std::string decodeBase64(const std::string& in) + PluginHost::Configuration + pluginHostConfiguration(const Api::AppConfig& config, + const std::filesystem::path& configPath, + const std::filesystem::path& statePath) { - static constexpr auto val = [](char c) -> int { - if (c >= 'A' && c <= 'Z') { - return c - 'A'; - } - if (c >= 'a' && c <= 'z') { - return c - 'a' + 26; - } - if (c >= '0' && c <= '9') { - return c - '0' + 52; - } - if (c == '+') { - return 62; - } - if (c == '/') { - return 63; - } - return -1; + std::filesystem::path pluginConfig = config.plugins.configDirectory; + if (pluginConfig.empty()) { + pluginConfig = configPath.parent_path() / "plugins.d"; + } else if (pluginConfig.is_relative()) { + pluginConfig = configPath.parent_path() / pluginConfig; + } + std::error_code error; + std::filesystem::create_directories(pluginConfig, error); + return { + .configDirectory = std::move(pluginConfig), + .stateDirectory = statePath, + .publicUrl = config.web.publicUrl, + .proxy = config.network.proxy, + .shortenerProvider = config.urlShortening.enabled + ? config.urlShortening.provider + : std::string{}, }; - std::string out; - out.reserve(in.size() * 3 / 4); - int buf = 0; - int bits = 0; - for (char c : in) { - if (c == '=' || c == '\n' || c == '\r') { - continue; - } - const int v = val(c); - if (v < 0) { - return {}; // invalid character - } - buf = (buf << 6) | v; - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((buf >> bits) & 0xFF)); - } - } - return out; - } -#endif - - // Encode raw bytes to base64 (used to persist TeamSpeak avatar images - // in the database so they survive the client going - // offline/out-of-view). - std::string encodeBase64(std::string_view in) - { - static constexpr char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij" - "klmnopqrstuvwxyz0123456789+/"; - std::string out; - out.reserve((in.size() + 2) / 3 * 4); - std::size_t i = 0; - while (i + 3 <= in.size()) { - const unsigned n = - (static_cast(in[i]) << 16) | - (static_cast(in[i + 1]) << 8) | - static_cast(in[i + 2]); - out.push_back(tbl[(n >> 18) & 0x3F]); - out.push_back(tbl[(n >> 12) & 0x3F]); - out.push_back(tbl[(n >> 6) & 0x3F]); - out.push_back(tbl[n & 0x3F]); - i += 3; - } - if (const std::size_t rem = in.size() - i; rem == 1) { - const unsigned n = static_cast(in[i]) << 16; - out.push_back(tbl[(n >> 18) & 0x3F]); - out.push_back(tbl[(n >> 12) & 0x3F]); - out += "=="; - } else if (rem == 2) { - const unsigned n = (static_cast(in[i]) << 16) | - (static_cast(in[i + 1]) << 8); - out.push_back(tbl[(n >> 18) & 0x3F]); - out.push_back(tbl[(n >> 12) & 0x3F]); - out.push_back(tbl[(n >> 6) & 0x3F]); - out.push_back('='); - } - return out; } // Best content type for avatar bytes: honour a valid image/* hint @@ -516,18 +458,57 @@ namespace Echoion::Core extensionPlugins_ = std::make_shared( *commandManager_, musicManager_, - [this](uint64_t clientId) { return isAdmin(clientId); }); + [this](uint64_t clientId) { return isAdmin(clientId); }, + std::function)>{}, + pluginHostConfiguration(config_, configPath_, stateDir)); if (rpcServer_) { extensionPlugins_->setChangeCallback([server = rpcServer_] { server->broadcastEvent("plugins.updated", "{}"); }); } extensionPlugins_->loadDirectory(stateDir / "plugins"); + extensionPlugins_->loadManagedDirectory(stateDir / "plugins" / + ".managed"); + applyUrlShorteningConfig(); #ifdef ECHOION_WITH_WEB // Browser web interface (independent of the RPC transport above). if (config_.web.enabled) { webServer_ = std::make_shared(); + webServer_->setShortLinkResolver( + [host = std::weak_ptr{extensionPlugins_}]( + std::string_view key) { + using Status = Web::HttpServer::ShortLinkStatus; + auto pinnedHost = host.lock(); + if (!pinnedHost) { + return Web::HttpServer::ShortLinkResolution{ + .status = Status::unavailable, .location = {}}; + } + auto result = pinnedHost->resolveShortLink(key); + if (result.ok() && !result.target_url.empty()) { + return Web::HttpServer::ShortLinkResolution{ + .status = Status::found, + .location = std::move(result.target_url)}; + } + using enum Void::ShortUrl::ErrorCode; + switch (result.error.code) { + case expired: + case revoked: + return Web::HttpServer::ShortLinkResolution{ + .status = Status::gone, .location = {}}; + case rate_limited: + return Web::HttpServer::ShortLinkResolution{ + .status = Status::rateLimited, .location = {}}; + case unavailable: + case storage: + case internal_error: + return Web::HttpServer::ShortLinkResolution{ + .status = Status::unavailable, .location = {}}; + default: + return Web::HttpServer::ShortLinkResolution{ + .status = Status::notFound, .location = {}}; + } + }); webServer_->setDashboardProvider([this] { using Void::Json::Value; auto dashboard = directoryService_->publicJson(); @@ -602,7 +583,9 @@ namespace Echoion::Core return std::nullopt; } if (!(*stored)->dataBase64.empty()) { - auto bytes = decodeBase64((*stored)->dataBase64); + auto bytes = Void::Encoding::Base64::decode( + (*stored)->dataBase64) + .value_or(std::string{}); if (!bytes.empty()) { return Web::HttpServer::AvatarImage{ .contentType = (*stored)->mime, @@ -622,7 +605,9 @@ namespace Echoion::Core if (database_) { [[maybe_unused]] auto put = database_->putCachedAvatar( - u, type, encodeBase64(resp->body)); + u, type, + Void::Encoding::Base64::encode( + resp->body)); } return Web::HttpServer::AvatarImage{ .contentType = std::move(type), @@ -659,6 +644,7 @@ namespace Echoion::Core webCfg.rpcUrl = config_.web.rpcUrl; webCfg.watchUrl = config_.web.watchUrl; webCfg.nowPlayingVideo = config_.web.nowPlayingVideo; + webCfg.trustedProxyCidrs = config_.web.trustedProxyCidrs; webCfg.rpcPort = config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765; if (!webServer_->start(webCfg)) { @@ -759,8 +745,6 @@ namespace Echoion::Core musicManager_->shutdown(); } - extensionPlugins_.reset(); - #ifdef ECHOION_WITH_WEB // Providers and the RPC bridge capture Core services, so drain all HTTP // workers before destroying any of those dependencies. @@ -770,6 +754,8 @@ namespace Echoion::Core } #endif + extensionPlugins_.reset(); + if (networkClient_) { networkClient_->shutdown(); } @@ -1164,31 +1150,88 @@ namespace Echoion::Core Api::Result Core::updateConfig(const Api::AppConfig& config) { - // Update local config copy - config_ = config; + auto candidate = config; + ConfigLoader::normalize(candidate); +#ifdef ECHOION_WITH_WEB + if (webServer_) { + auto validated = Web::HttpServer::validateTrustedProxyCidrs( + candidate.web.trustedProxyCidrs); + if (!validated) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("invalid web.trustedProxyCidrs: {}", + validated.error())); + } + } +#endif + if (extensionPlugins_) { + const auto stateDir = stateDirectory(configPath_); + if (!extensionPlugins_->reconfigure(pluginHostConfiguration( + candidate, configPath_, stateDir))) { + return Api::fail( + Api::ErrorCode::PluginError, + "extension plugins rejected the updated configuration; the " + "previous configuration remains active"); + } + } + +#ifdef ECHOION_WITH_WEB + if (webServer_) { + auto updated = webServer_->setTrustedProxyCidrs( + candidate.web.trustedProxyCidrs); + if (!updated) { + bool pluginsRestored = true; + if (extensionPlugins_) { + const auto stateDir = stateDirectory(configPath_); + pluginsRestored = + extensionPlugins_->reconfigure(pluginHostConfiguration( + config_, configPath_, stateDir)); + } + if (!pluginsRestored) { + Void::Log::error( + "Core", "{}", + "Failed to restore extension plugins after the web " + "trusted-proxy update failed; restart is required"); + } + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format( + "failed to apply web.trustedProxyCidrs: {}{}", + updated.error(), + pluginsRestored + ? "; the previous configuration remains active" + : "; extension plugin rollback also failed")); + } + } +#endif + + // Publish the candidate only after provider and live web validation. + config_ = std::move(candidate); if (commandManager_) { - commandManager_->setPrefix(config.bot.commandPrefix); - commandManager_->setServerConfig(config); + commandManager_->setPrefix(config_.bot.commandPrefix); + commandManager_->setServerConfig(config_); } // Re-apply network settings to every outbound client (NetworkClient, // yt-dlp, ffmpeg), not just the HTTP client. if (musicManager_) { - musicManager_->applyBotConfig(config.bot); - musicManager_->applyFeaturesConfig(config.features); - musicManager_->applyNetworkConfig(config.network); - musicManager_->applyYouTubeConfig(config.youtube); - musicManager_->applySourcesConfig(config.sources); + musicManager_->applyBotConfig(config_.bot); + musicManager_->applyFeaturesConfig(config_.features); + musicManager_->applyNetworkConfig(config_.network); + musicManager_->applyYouTubeConfig(config_.youtube); + musicManager_->applySourcesConfig(config_.sources); } else if (networkClient_) { - networkClient_->setProxy(config.network.proxy); + networkClient_->setProxy(config_.network.proxy); } + applyUrlShorteningConfig(); broadcastEvent( Api::PluginEvent{.type = Api::PluginEventType::ConfigurationChanged, .clientId = 0, .timestamp = std::chrono::system_clock::now()}); - eventBus_.publish(Api::Events::ConfigReloaded{.newConfig = config.bot}); + eventBus_.publish( + Api::Events::ConfigReloaded{.newConfig = config_.bot}); return {}; } @@ -1197,28 +1240,11 @@ namespace Echoion::Core Api::Result Core::updateConfigJson(const std::string& configJson) { - // Parse JSON config using Void::Json reflection - auto parsed = Void::Json::parse(configJson); - if (!parsed) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("Failed to parse config JSON ({}:{}): {}", - parsed.error().line, parsed.error().col, - parsed.error().message)); + auto config = ConfigLoader::loadFromJson(configJson); + if (!config) { + return std::unexpected(config.error()); } - // Deserialize the full Api::AppConfig document directly via reflection. - auto jsonResult = Void::Json::from_json(*parsed); - if (!jsonResult.has_value()) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("Failed to parse config JSON: field '{}': {}", - jsonResult.error().field, - jsonResult.error().message)); - } - - Api::AppConfig config = std::move(jsonResult.value()); - ConfigLoader::normalize(config); - return updateConfig(config); + return updateConfig(*config); } Api::Result Core::getConfigJson() const @@ -1228,6 +1254,19 @@ namespace Echoion::Core {.pretty = true}); } + Api::Result + Core::managePluginsJson(const std::string& requestJson) + { + if (auto ready = requireInitialized(); !ready) { + return std::unexpected(ready.error()); + } + if (!extensionPlugins_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "extension plugin host is unavailable"); + } + return extensionPlugins_->manage(requestJson); + } + Api::Result Core::reloadConfig() { if (auto r = requireInitialized(); !r) { @@ -1245,8 +1284,62 @@ namespace Echoion::Core return std::unexpected(configResult.error()); } - // Update local config - config_ = *configResult; + auto candidate = *configResult; +#ifdef ECHOION_WITH_WEB + if (webServer_) { + auto validated = Web::HttpServer::validateTrustedProxyCidrs( + candidate.web.trustedProxyCidrs); + if (!validated) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + std::format("invalid web.trustedProxyCidrs: {}", + validated.error())); + } + } +#endif + if (extensionPlugins_) { + const auto stateDir = stateDirectory(configPath_); + if (!extensionPlugins_->reconfigure(pluginHostConfiguration( + candidate, configPath_, stateDir))) { + return Api::fail(Api::ErrorCode::PluginError, + "extension plugins rejected the reloaded " + "configuration; the " + "previous configuration remains active"); + } + } + +#ifdef ECHOION_WITH_WEB + if (webServer_) { + auto updated = webServer_->setTrustedProxyCidrs( + candidate.web.trustedProxyCidrs); + if (!updated) { + bool pluginsRestored = true; + if (extensionPlugins_) { + const auto stateDir = stateDirectory(configPath_); + pluginsRestored = + extensionPlugins_->reconfigure(pluginHostConfiguration( + config_, configPath_, stateDir)); + } + if (!pluginsRestored) { + Void::Log::error( + "Core", "{}", + "Failed to restore extension plugins after the web " + "trusted-proxy reload failed; restart is required"); + } + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format( + "failed to apply web.trustedProxyCidrs: {}{}", + updated.error(), + pluginsRestored + ? "; the previous configuration remains active" + : "; extension plugin rollback also failed")); + } + } +#endif + + // Update local config only after provider and live web validation. + config_ = std::move(candidate); // Keep the shared ConfigManager in sync so components that read through // it (cookies, API key, etc.) see the reloaded values. configManager_.updateConfig(config_, false); @@ -1270,6 +1363,7 @@ namespace Echoion::Core } else if (networkClient_) { networkClient_->setProxy(config_.network.proxy); } + applyUrlShorteningConfig(); eventBus_.publish( Api::Events::ConfigReloaded{.newConfig = config_.bot}); @@ -1278,6 +1372,27 @@ namespace Echoion::Core return {}; } + void Core::applyUrlShorteningConfig() + { + if (!musicManager_) { + return; + } + auto client = musicManager_->sharedYouTubeClient(); + if (!client) { + return; + } + client->setUrlShorteningEnabled(config_.urlShortening.enabled); + client->setUrlShorteningSources(config_.urlShortening.sources); + client->setUrlShorteningTimeout(config_.urlShortening.timeout); + client->setUrlShortenerProvider( + [host = std::weak_ptr{extensionPlugins_}] { + if (auto pinned = host.lock()) { + return pinned->shortener(); + } + return std::shared_ptr{}; + }); + } + Api::Result Core::prepareForHotReloadFull() { if (auto r = requireInitialized(); !r) { @@ -2071,8 +2186,8 @@ namespace Echoion::Core } std::string type = sniffImageMime(bytes, hint); if (database_) { - [[maybe_unused]] auto put = - database_->putCachedAvatar(uid, type, encodeBase64(bytes)); + [[maybe_unused]] auto put = database_->putCachedAvatar( + uid, type, Void::Encoding::Base64::encode(bytes)); } return std::pair{std::move(type), std::move(bytes)}; }; diff --git a/src/CoreRpcHandlers.cpp b/src/CoreRpcHandlers.cpp index 38e8367..50483e7 100644 --- a/src/CoreRpcHandlers.cpp +++ b/src/CoreRpcHandlers.cpp @@ -124,6 +124,41 @@ namespace Echoion::Core std::move(request->params), clientId); }); + + // Updater policy and activation belong to the host, which owns the + // executable and installed component paths. Core performs the existing + // RPC authentication/authorization and forwards an opaque JSON request + // through the single append-only host-control ABI operation. + auto registerUpdateHandler = [this](Api::RpcMethod rpcMethod, + std::string operation) { + rpcServer_->registerHandler( + std::to_string(static_cast(rpcMethod)), + [this, operation = std::move(operation)]( + const std::string& params, + uint64_t clientId) -> Api::Result { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!pluginInterface_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Host update control is unavailable"); + } + return pluginInterface_->hostControl(operation, params); + }); + }; + registerUpdateHandler(Api::RpcMethod::GetUpdateStatus, + "updates.getStatus"); + registerUpdateHandler(Api::RpcMethod::GetUpdateConfig, + "updates.getConfig"); + registerUpdateHandler(Api::RpcMethod::SetUpdateConfig, + "updates.setConfig"); + registerUpdateHandler(Api::RpcMethod::CheckForUpdates, "updates.check"); + registerUpdateHandler(Api::RpcMethod::ApplyUpdate, "updates.apply"); + registerUpdateHandler(Api::RpcMethod::RollbackUpdate, + "updates.rollback"); + registerUpdateHandler(Api::RpcMethod::ConfirmUnsignedUpdate, + "updates.confirmUnsigned"); // Authentication - expects JSON with either "nickname" (for initial // request) or "token" (for validation). The same handler backs // Authenticate, RequestLoginToken and ValidateLoginToken. diff --git a/src/LyricsService.cpp b/src/LyricsService.cpp index 13208d0..58b354b 100644 --- a/src/LyricsService.cpp +++ b/src/LyricsService.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -12,25 +13,6 @@ namespace Echoion::Core { namespace { - // Percent-encode a query-parameter value (RFC 3986 unreserved kept). - std::string urlEncode(std::string_view s) - { - static constexpr char hex[] = "0123456789ABCDEF"; - std::string out; - out.reserve(s.size() * 3); - for (unsigned char c : s) { - if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || - c == '~') { - out += static_cast(c); - } else { - out += '%'; - out += hex[c >> 4]; - out += hex[c & 0x0F]; - } - } - return out; - } - // Read an optional string field from a JSON object value. std::string strField(const Void::Json::Value& obj, std::string_view key) { @@ -131,9 +113,11 @@ namespace Echoion::Core std::string url = std::format( "https://lrclib.net/api/get?artist_name={}&track_name={}" "&duration={}", - urlEncode(artist), urlEncode(title), durationSec); + Void::Encoding::Url::encode(artist), + Void::Encoding::Url::encode(title), durationSec); if (!album.empty()) { - url += std::format("&album_name={}", urlEncode(album)); + url += std::format("&album_name={}", + Void::Encoding::Url::encode(album)); } if (auto resp = net_->get(url); resp && resp->status == 200 && !resp->body.empty()) { @@ -150,9 +134,10 @@ namespace Echoion::Core // 2) Search fallback — take the first result that carries lyrics. std::string searchUrl = std::format("https://lrclib.net/api/search?track_name={}", - urlEncode(title)); + Void::Encoding::Url::encode(title)); if (!artist.empty()) { - searchUrl += std::format("&artist_name={}", urlEncode(artist)); + searchUrl += std::format("&artist_name={}", + Void::Encoding::Url::encode(artist)); } if (auto resp = net_->get(searchUrl); resp && resp->status == 200 && !resp->body.empty()) { @@ -197,13 +182,14 @@ namespace Echoion::Core } std::string_view tag(raw.data() + pos + 1, close - pos - 1); // A timestamp starts with a digit; [ar:], [ti:] etc. don't. - if (!tag.empty() && std::isdigit(static_cast( - tag.front()))) { + if (!tag.empty() && + std::isdigit(static_cast(tag.front()))) { auto colon = tag.find(':'); if (colon != std::string_view::npos) { int minutes = 0; double seconds = 0.0; - std::from_chars(tag.data(), tag.data() + colon, minutes); + std::from_chars(tag.data(), tag.data() + colon, + minutes); // Parse the seconds part (may be fractional). std::string sec(tag.substr(colon + 1)); try { diff --git a/src/MusicManager.cpp b/src/MusicManager.cpp index c45688d..8bc0972 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -105,9 +105,7 @@ namespace Echoion::Core youtubeConfig.ytDlpMaxConcurrent); } - // Configure URL shortening - youTubeClient_->setUrlShorteningEnabled( - youtubeConfig.enableUrlShortening); + // URL shortening is configured by Core after extension services load. auto ytResult = youTubeClient_->initialize(); if (!ytResult) { @@ -267,8 +265,6 @@ namespace Echoion::Core youTubeClient_->setMaxConcurrentResolutions( youtube.ytDlpMaxConcurrent); } - youTubeClient_->setUrlShorteningEnabled(youtube.enableUrlShortening); - const bool hasKey = youtube.youtubeApiKey.has_value() && !youtube.youtubeApiKey->empty(); Void::Log::info("MusicManager", "{}", @@ -463,7 +459,9 @@ namespace Echoion::Core void MusicManager::addTrackSource(std::shared_ptr source) { - if (router_) router_->addSource(std::move(source)); + if (router_) { + router_->addSource(std::move(source)); + } } void MusicManager::shutdown() @@ -809,8 +807,8 @@ namespace Echoion::Core // Daily counters / top-requesters stats. clientId 0 is radio/system // (autoplay refill) — automatic adds don't count as user requests. if (database_ && clientId != 0) { - (void)database_->logQueueAddition( - clientUid(clientId).value_or(""), nicknameFor(clientId)); + (void)database_->logQueueAddition(clientUid(clientId).value_or(""), + nicknameFor(clientId)); } // Auto-start when idle with an online audience. @@ -953,6 +951,9 @@ namespace Echoion::Core importRunning_ = false; return; } + if (youTubeClient_) { + youTubeClient_->populateShortenedUrls(*tracks); + } size_t queued = 0; for (const auto& track : *tracks) { if (queueTrack(track, clientId)) { @@ -1057,26 +1058,33 @@ namespace Echoion::Core // YouTube search goes through the router (Invidious/Piped/ytdlp); // Yandex is called directly (its canHandle rejects text, so the // router never routes bare queries to it). + const auto applyShortening = + [this](Api::Result result) { + if (result && youTubeClient_) { + youTubeClient_->populateShortenedUrls(result->tracks); + } + return result; + }; const auto youtube = [&]() -> Api::Result { if (router_) { - return router_->search(query); + return applyShortening(router_->search(query)); } if (youTubeClient_) { - return youTubeClient_->search(query); + return applyShortening(youTubeClient_->search(query)); } return Api::fail(Api::ErrorCode::ServiceUnavailable, "YouTube search unavailable"); }; const auto yandex = [&]() -> Api::Result { if (yandexSource_ && yandexSource_->isAvailable()) { - return yandexSource_->search(query); + return applyShortening(yandexSource_->search(query)); } return Api::fail(Api::ErrorCode::ServiceUnavailable, "Yandex Music not configured"); }; const auto soundcloud = [&]() -> Api::Result { if (youTubeClient_) { - return youTubeClient_->searchSoundCloud(query); + return applyShortening(youTubeClient_->searchSoundCloud(query)); } return Api::fail(Api::ErrorCode::ServiceUnavailable, "SoundCloud search unavailable"); @@ -1167,6 +1175,9 @@ namespace Echoion::Core auto selected = (*pending)[index - 1]; // Convert to 0-based (copy to modify) selected.requestedBy = invokerName; + if (youTubeClient_) { + youTubeClient_->populateShortenedUrl(selected); + } auto result = queueTrack(selected, clientId); if (!result) { @@ -1569,9 +1580,8 @@ namespace Echoion::Core // Queue tracks that are both unplayed-recently and within the // radio duration cap. Stops once maxToQueue have been queued. - auto queueRadio = - [&](const std::vector& tracks, - size_t maxToQueue) -> size_t { + auto queueRadio = [&](const std::vector& tracks, + size_t maxToQueue) -> size_t { size_t queued = 0; for (const auto& track : tracks) { if (recentUrls.contains(track.originalUrl)) { @@ -1607,14 +1617,13 @@ namespace Echoion::Core related = youTubeClient_->radioMix(seed, 10); } if (related && !related->empty()) { - queued = queueRadio(*related, std::numeric_limits< - size_t>::max()); + queued = queueRadio(*related, + std::numeric_limits::max()); if (queued > 0) { Void::Log::info( "MusicManager", "{}", - std::format( - "Autoplay queued {} related track(s)", - queued)); + std::format("Autoplay queued {} related track(s)", + queued)); } } } @@ -1628,10 +1637,9 @@ namespace Echoion::Core random && !random->empty()) { queued = queueRadio(*random, 1); if (queued > 0) { - Void::Log::info( - "MusicManager", "{}", - "Autoplay queued a random music video " - "(no unplayed related track found)"); + Void::Log::info("MusicManager", "{}", + "Autoplay queued a random music video " + "(no unplayed related track found)"); } } } @@ -1641,9 +1649,8 @@ namespace Echoion::Core engine_->start(); } } else { - Void::Log::debug( - "MusicManager", "{}", - "Autoplay found no track to queue"); + Void::Log::debug("MusicManager", "{}", + "Autoplay found no track to queue"); } autoplayFetching_ = false; }); @@ -1706,6 +1713,12 @@ namespace Echoion::Core Api::Result MusicManager::resolveQuery(const std::string& query) { + const auto finalize = [this](Api::Result result) { + if (result && youTubeClient_) { + youTubeClient_->populateShortenedUrl(*result); + } + return result; + }; // Playlist URLs are still resolved through the YouTube client (the // router's sources resolve single tracks). if (config_.allowPlaylistImports && @@ -1717,13 +1730,13 @@ namespace Echoion::Core std::format("Extracted playlist ID: '{}'", *playlistId)); auto playlist = youTubeClient_->getPlaylist(*playlistId); if (playlist && !playlist->tracks.empty()) { - return playlist->tracks[0]; + return finalize(playlist->tracks[0]); } } } if (router_) { - return router_->resolve(query); + return finalize(router_->resolve(query)); } auto searchResult = youTubeClient_->search(query); @@ -1733,7 +1746,7 @@ namespace Echoion::Core if (searchResult->tracks.empty()) { return Api::fail(Api::ErrorCode::NotFound, "No results found"); } - return searchResult->tracks[0]; + return finalize(searchResult->tracks[0]); } Api::Result diff --git a/src/PluginHost.cpp b/src/PluginHost.cpp index fe909a5..e9862da 100644 --- a/src/PluginHost.cpp +++ b/src/PluginHost.cpp @@ -4,10 +4,16 @@ #include "echoion/core/MusicManager.hpp" #include "echoion/core/sources/TrackSource.hpp" +#include #include #include #include +#include +#include +#include +#include +#include #include namespace Echoion::Core @@ -16,202 +22,268 @@ namespace Echoion::Core { class ExtensionCommandAdapter final : public Command { - public: - ExtensionCommandAdapter(Void::Plugin::PluginManager& plugins, - std::string plugin, Api::ExtensionCommand command) - : plugins_(plugins), plugin_(std::move(plugin)), - command_(std::move(command)) - { - } + public: - void execute(const CommandContext& context) override - { - try { - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) { - context.reply("Plugin is temporarily unavailable."); - return; - } - auto result = extension->executeCommand({ - .command = command_.name, - .arguments = context.args, - .clientId = context.clientId, - .invokerName = std::string(context.invokerName)}); - context.reply(result ? *result : result.error().message); - } catch (const std::exception& error) { - Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw: {}", - plugin_, command_.name, error.what()); - context.reply("Plugin command failed."); - } catch (...) { - Void::Log::error("PluginHost", "Plugin '{}' command '{}' threw", - plugin_, command_.name); - context.reply("Plugin command failed."); + ExtensionCommandAdapter(Void::Plugin::PluginManager& plugins, + std::string plugin, + Api::ExtensionCommand command) + : plugins_(plugins), plugin_(std::move(plugin)), + command_(std::move(command)) + { } - } - std::string_view getDescription() const override - { - return command_.description; - } - std::string_view getUsage() const override { return command_.usage; } - CommandCategory getCategory() const override - { - return static_cast( - std::min(command_.category, + void execute(const CommandContext& context) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast( + pin.get()) + : nullptr; + if (!extension) { + context.reply("Plugin is temporarily unavailable."); + return; + } + auto result = extension->executeCommand( + {.command = command_.name, + .arguments = context.args, + .clientId = context.clientId, + .invokerName = std::string(context.invokerName)}); + context.reply(result ? *result + : result.error().message); + } catch (const std::exception& error) { + Void::Log::error("PluginHost", + "Plugin '{}' command '{}' threw: {}", + plugin_, command_.name, error.what()); + context.reply("Plugin command failed."); + } catch (...) { + Void::Log::error("PluginHost", + "Plugin '{}' command '{}' threw", + plugin_, command_.name); + context.reply("Plugin command failed."); + } + } + + std::string_view getDescription() const override + { + return command_.description; + } + std::string_view getUsage() const override + { + return command_.usage; + } + CommandCategory getCategory() const override + { + return static_cast(std::min( + command_.category, static_cast(CommandCategory::Admin))); - } - std::vector getAliases() const override - { - std::vector aliases; - aliases.reserve(command_.aliases.size()); - for (const auto& alias : command_.aliases) aliases.push_back(alias); - return aliases; - } - bool requiresAdmin() const override { return command_.adminOnly; } + } + std::vector getAliases() const override + { + std::vector aliases; + aliases.reserve(command_.aliases.size()); + for (const auto& alias : command_.aliases) { + aliases.push_back(alias); + } + return aliases; + } + bool requiresAdmin() const override + { + return command_.adminOnly; + } - private: - Void::Plugin::PluginManager& plugins_; - std::string plugin_; - Api::ExtensionCommand command_; + private: + + Void::Plugin::PluginManager& plugins_; + std::string plugin_; + Api::ExtensionCommand command_; }; - } + } // namespace class PluginTrackSource final : public ITrackSource { - public: - PluginTrackSource(std::weak_ptr host, - Void::Plugin::PluginManager& plugins, std::string plugin, - Api::ExtensionMediaSource source) - : host_(std::move(host)), plugins_(plugins), plugin_(std::move(plugin)), - source_(std::move(source)) - { - } - std::string_view name() const override { return source_.name; } - bool canHandle(const std::string& query) const override - { - try { - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - return extension && declaredBy(*extension) && - extension->canHandleMedia(source_.name, query); - } catch (...) { - return false; - } - } - bool isAvailable() const override - { - try { - if (host_.expired()) return false; - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - return extension && declaredBy(*extension); - } catch (...) { - return false; - } - } - bool supportsSearch() const override - { - try { - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) return false; - auto descriptors = extension->mediaSources(); - auto descriptor = std::ranges::find( - descriptors, source_.name, &Api::ExtensionMediaSource::name); - return descriptor != descriptors.end() && descriptor->supportsSearch; - } catch (...) { - return false; - } - } - [[nodiscard]] bool represents(std::string_view plugin, - std::string_view source) const - { - return plugin_ == plugin && source_.name == source; - } - Api::Result search(std::string_view query) override - { - try { - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable, - "plugin media source unavailable"); - return extension->searchMedia(source_.name, query); - } catch (const std::exception& error) { - return Api::fail(Api::ErrorCode::UnknownError, error.what()); - } catch (...) { - return Api::fail(Api::ErrorCode::UnknownError, - "plugin media search threw an exception"); - } - } - Api::Result resolve(const std::string& query) override - { - try { - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable, - "plugin media source unavailable"); - return extension->resolveMedia(source_.name, query); - } catch (const std::exception& error) { - return Api::fail(Api::ErrorCode::UnknownError, error.what()); - } catch (...) { - return Api::fail(Api::ErrorCode::UnknownError, - "plugin media resolve threw an exception"); - } - } - Api::Result getStream(const Api::TrackInfo& track) override - { - try { - auto pin = plugins_.acquire(plugin_); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) return Api::fail(Api::ErrorCode::ServiceUnavailable, - "plugin media source unavailable"); - auto result = extension->streamMedia(source_.name, track); - if (!result) return std::unexpected(result.error()); - return StreamHandle{.url = std::move(result->url), - .isLocalFile = result->localFile, .sourceName = source_.name}; - } catch (const std::exception& error) { - return Api::fail(Api::ErrorCode::UnknownError, error.what()); - } catch (...) { - return Api::fail(Api::ErrorCode::UnknownError, - "plugin media stream threw an exception"); - } - } + public: - private: - [[nodiscard]] bool declaredBy(Api::IExtensionPlugin& extension) const - { - auto descriptors = extension.mediaSources(); - return std::ranges::find(descriptors, source_.name, - &Api::ExtensionMediaSource::name) != descriptors.end(); - } + PluginTrackSource(std::weak_ptr host, + Void::Plugin::PluginManager& plugins, + std::string plugin, + Api::ExtensionMediaSource source) + : host_(std::move(host)), plugins_(plugins), + plugin_(std::move(plugin)), source_(std::move(source)) + { + } + std::string_view name() const override { return source_.name; } + bool canHandle(const std::string& query) const override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr; + return extension && declaredBy(*extension) && + extension->canHandleMedia(source_.name, query); + } catch (...) { + return false; + } + } + bool isAvailable() const override + { + try { + if (host_.expired()) { + return false; + } + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr; + return extension && declaredBy(*extension); + } catch (...) { + return false; + } + } + bool supportsSearch() const override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr; + if (!extension) { + return false; + } + auto descriptors = extension->mediaSources(); + auto descriptor = + std::ranges::find(descriptors, source_.name, + &Api::ExtensionMediaSource::name); + return descriptor != descriptors.end() && + descriptor->supportsSearch; + } catch (...) { + return false; + } + } + [[nodiscard]] bool represents(std::string_view plugin, + std::string_view source) const + { + return plugin_ == plugin && source_.name == source; + } + Api::Result + search(std::string_view query) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr; + if (!extension) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin media source unavailable"); + } + auto result = extension->searchMedia(source_.name, query); + if (result) { + for (auto& track : result->tracks) { + track.source = Api::TrackSource::Plugin; + } + } + return result; + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, + error.what()); + } catch (...) { + return Api::fail(Api::ErrorCode::UnknownError, + "plugin media search threw an exception"); + } + } + Api::Result + resolve(const std::string& query) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr; + if (!extension) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin media source unavailable"); + } + auto result = extension->resolveMedia(source_.name, query); + if (result) { + result->source = Api::TrackSource::Plugin; + } + return result; + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, + error.what()); + } catch (...) { + return Api::fail(Api::ErrorCode::UnknownError, + "plugin media resolve threw an exception"); + } + } + Api::Result + getStream(const Api::TrackInfo& track) override + { + try { + auto pin = plugins_.acquire(plugin_); + auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr; + if (!extension) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "plugin media source unavailable"); + } + auto result = extension->streamMedia(source_.name, track); + if (!result) { + return std::unexpected(result.error()); + } + return StreamHandle{.url = std::move(result->url), + .isLocalFile = result->localFile, + .sourceName = source_.name}; + } catch (const std::exception& error) { + return Api::fail(Api::ErrorCode::UnknownError, + error.what()); + } catch (...) { + return Api::fail(Api::ErrorCode::UnknownError, + "plugin media stream threw an exception"); + } + } - std::weak_ptr host_; - Void::Plugin::PluginManager& plugins_; - std::string plugin_; - Api::ExtensionMediaSource source_; + private: + + [[nodiscard]] bool + declaredBy(Api::IExtensionPlugin& extension) const + { + auto descriptors = extension.mediaSources(); + return std::ranges::find(descriptors, source_.name, + &Api::ExtensionMediaSource::name) != + descriptors.end(); + } + + std::weak_ptr host_; + Void::Plugin::PluginManager& plugins_; + std::string plugin_; + Api::ExtensionMediaSource source_; }; - PluginHost::PluginHost(CommandManager& commands, - std::shared_ptr music, std::function isAdmin, - std::function)> mediaSink) + PluginHost::PluginHost( + CommandManager& commands, std::shared_ptr music, + std::function isAdmin, + std::function)> mediaSink, + Configuration configuration) : commands_(commands), music_(std::move(music)), isAdmin_(std::move(isAdmin)), mediaSink_(std::move(mediaSink)), plugins_(Void::Plugin::PluginManager::Options{ .dlclose_on_swap = false, .copy_on_load = true, - .config_provider = {}, - .instance_validator = [](Void::Plugin::IPlugin& plugin, - const Void::Plugin::PluginInfo&) { - return dynamic_cast(&plugin) != nullptr; - }}) + .config_provider = + [this](std::string_view name) { + return pluginConfiguration(name); + }, + .instance_validator = + [](Void::Plugin::IPlugin& plugin, + const Void::Plugin::PluginInfo&) { + return dynamic_cast(&plugin) != + nullptr; + }}), + configuration_(std::move(configuration)) { reloadCallback_ = plugins_.on_reloaded( [this](std::string_view name) { publish(name); }); @@ -220,20 +292,642 @@ namespace Echoion::Core PluginHost::~PluginHost() { plugins_.remove_on_reloaded(reloadCallback_); - for (const auto& name : plugins_.names()) unpublish(name); + for (const auto& name : plugins_.names()) { + unpublish(name); + } } void PluginHost::loadDirectory(const std::filesystem::path& directory) { + std::scoped_lock operationLock{reconfigureMutex_}; for (auto& [path, result] : plugins_.load_directory(directory)) { if (!result) { Void::Log::warn("PluginHost", "Failed to load '{}': {}", - path.string(), Void::Plugin::to_string(result.error())); + path.string(), + Void::Plugin::to_string(result.error())); continue; } + { + std::error_code error; + auto loadedPath = + std::filesystem::weakly_canonical(path, error); + std::lock_guard lock(mutex_); + loadedPaths_[*result] = error ? path : std::move(loadedPath); + } publish(*result); plugins_.watch(*result); } + if (!bindShortenerServices()) { + Void::Log::warn("PluginHost", + "Loaded plugins do not provide the configured " + "short URL service"); + } + } + + void + PluginHost::loadManagedDirectory(const std::filesystem::path& directory) + { + std::scoped_lock operationLock{reconfigureMutex_}; + std::error_code error; + std::filesystem::create_directories(directory, error); + managedDirectory_ = std::filesystem::weakly_canonical(directory, error); + if (error) { + Void::Log::warn("PluginHost", + "Cannot prepare managed plugin root '{}': {}", + directory.string(), error.message()); + return; + } + for (const auto& entry : + std::filesystem::directory_iterator(managedDirectory_, error)) { + if (error || !entry.is_directory()) { + continue; + } + const auto id = entry.path().filename().string(); + if (id.empty() || id == "." || id == ".." || + !std::ranges::all_of(id, [](unsigned char character) { + return std::isalnum(character) || character == '.' || + character == '_' || character == '-'; + })) { + continue; + } + const auto current = + std::filesystem::canonical(entry.path() / "current", error); + const auto library = current / (id + ".so"); + if (error || !std::filesystem::is_regular_file(library)) { + continue; + } + auto loaded = plugins_.load(library); + if (!loaded || *loaded != id) { + Void::Log::warn( + "PluginHost", "Managed plugin '{}' failed to load: {}", id, + loaded + ? "reported a different name" + : std::string(Void::Plugin::to_string(loaded.error()))); + continue; + } + auto handle = plugins_.acquire(id); + const auto info = + handle ? handle.info() : Void::Plugin::PluginInfo{}; + { + std::lock_guard lock(mutex_); + managed_[id] = { + .version = info.plugin_version ? info.plugin_version : "", + .path = library}; + loadedPaths_[id] = library; + } + publish(id); + plugins_.watch(id); + } + if (!bindShortenerServices()) { + Void::Log::warn("PluginHost", + "Managed plugins do not provide the configured " + "short URL service"); + } + } + + std::string PluginHost::pluginConfiguration(std::string_view name) const + { + Configuration configuration; + { + std::lock_guard lock(mutex_); + configuration = configuration_; + } + + using Void::Json::Value; + Value settings = Void::Json::object(); + const auto configPath = + configuration.configDirectory / (std::string(name) + ".json"); + std::error_code error; + if (std::filesystem::is_regular_file(configPath, error)) { + std::ifstream file(configPath, std::ios::binary); + std::ostringstream content; + content << file.rdbuf(); + if (content.tellp() <= std::streampos{1024 * 1024}) { + if (auto parsed = Void::Json::parse(content.str()); + parsed && parsed->is_object()) { + settings = std::move(*parsed); + } else { + Void::Log::warn("PluginHost", + "Ignoring invalid plugin config '{}'", + configPath.string()); + } + } else { + Void::Log::warn("PluginHost", + "Ignoring plugin config larger than 1 MiB '{}'", + configPath.string()); + } + } + + Value envelope = Void::Json::object(); + auto& object = envelope.as_object(); + object.emplace_back("schemaVersion", Value{1}); + object.emplace_back("pluginId", Value{std::string(name)}); + Value host = Void::Json::object(); + auto& hostFields = host.as_object(); + hostFields.emplace_back("stateDirectory", + Value{configuration.stateDirectory.string()}); + hostFields.emplace_back("publicUrl", Value{configuration.publicUrl}); + std::string publicBaseUrl = configuration.publicUrl; + while (publicBaseUrl.ends_with('/')) { + publicBaseUrl.pop_back(); + } + if (!publicBaseUrl.empty()) { + publicBaseUrl += "/s"; + } + hostFields.emplace_back("publicBaseUrl", Value{publicBaseUrl}); + object.emplace_back("stateDirectory", + Value{configuration.stateDirectory.string()}); + object.emplace_back("configPath", Value{configPath.string()}); + object.emplace_back("publicUrl", Value{configuration.publicUrl}); + object.emplace_back("settings", std::move(settings)); + if (configuration.proxy) { + Value proxy = Void::Json::object(); + auto& fields = proxy.as_object(); + std::string kind = "none"; + if (configuration.proxy->kind == + Void::Net::ProxyConfig::Kind::Http) { + kind = "http"; + } else if (configuration.proxy->kind == + Void::Net::ProxyConfig::Kind::Socks5) { + kind = "socks5"; + } + fields.emplace_back("kind", Value{kind}); + fields.emplace_back("host", Value{configuration.proxy->host}); + fields.emplace_back("port", Value{static_cast( + configuration.proxy->port)}); + fields.emplace_back("username", + configuration.proxy->username + ? Value{*configuration.proxy->username} + : Value{nullptr}); + fields.emplace_back("password", + configuration.proxy->password + ? Value{*configuration.proxy->password} + : Value{nullptr}); + hostFields.emplace_back("proxy", proxy); + object.emplace_back("proxy", std::move(proxy)); + } else { + hostFields.emplace_back("proxy", Value{nullptr}); + object.emplace_back("proxy", Value{nullptr}); + } + object.emplace_back("_host", std::move(host)); + return Void::Json::serialize(envelope); + } + + bool PluginHost::bindShortenerServices() + { + using Binding = + Void::Service::PluginServiceBinding; + constexpr std::string_view kInternal = "url-shortener-internal"; + + std::string selected; + { + std::lock_guard lock(mutex_); + selected = configuration_.shortenerProvider; + } + const auto loaded = plugins_.names(); + const auto isLoaded = [&loaded](std::string_view name) { + return std::ranges::find(loaded, name) != loaded.end(); + }; + const auto validator = [](std::string expectedProvider, + bool requireResolver) -> Binding::Validator { + return [expectedProvider = std::move(expectedProvider), + requireResolver]( + const std::shared_ptr& + service) { + if (!service || + service->service_version() != + Void::ShortUrl::kServiceVersion || + service->provider_id() != expectedProvider || + (requireResolver && !service->supports_resolve())) { + return false; + } + const auto status = service->health().status; + return status == Void::ShortUrl::HealthStatus::healthy || + status == Void::ShortUrl::HealthStatus::degraded; + }; + }; + auto previousSelected = + shortenerRegistry_.get(); + auto previousInternal = + internalShortenerRegistry_.get(); + auto previousSelectedBinding = std::move(shortenerBinding_); + auto previousInternalBinding = std::move(internalShortenerBinding_); + const auto restorePrevious = [&]() noexcept { + // A later binding step may have published and enabled one + // replacement before another step failed. Quiesce those callbacks + // before restoring the prior registry values, otherwise a delayed + // replacement callback could overwrite the rollback. + if (shortenerBinding_) { + shortenerBinding_->disable_hot_reload(); + shortenerBinding_.reset(); + } + if (internalShortenerBinding_) { + internalShortenerBinding_->disable_hot_reload(); + internalShortenerBinding_.reset(); + } + try { + if (previousSelected) { + shortenerRegistry_.provide( + previousSelected); + } else { + (void) + shortenerRegistry_.remove(); + } + if (previousInternal) { + internalShortenerRegistry_ + .provide(previousInternal); + } else { + (void)internalShortenerRegistry_ + .remove(); + } + } catch (const std::exception& error) { + Void::Log::error( + "PluginHost", + "Restoring previous short URL services threw: {}", + error.what()); + } catch (...) { + Void::Log::error("PluginHost", + "Restoring previous short URL services threw"); + } + if (previousSelectedBinding) { + try { + previousSelectedBinding->enable_hot_reload(); + } catch (...) { + Void::Log::error("PluginHost", + "Failed to re-enable the previous short " + "URL provider binding"); + } + shortenerBinding_ = std::move(previousSelectedBinding); + } + if (previousInternalBinding) { + try { + previousInternalBinding->enable_hot_reload(); + } catch (...) { + Void::Log::error("PluginHost", + "Failed to re-enable the previous " + "internal resolver binding"); + } + internalShortenerBinding_ = std::move(previousInternalBinding); + } + }; + + try { + // Removing an observer is not enough after PluginManager has copied + // its callback list. disable_hot_reload() also waits for any + // callback already using the binding state, so no old provider can + // overwrite a newly-published service after this point. + if (previousSelectedBinding) { + previousSelectedBinding->disable_hot_reload(); + } + if (previousInternalBinding) { + previousInternalBinding->disable_hot_reload(); + } + + std::unique_ptr selectedBinding; + if (!selected.empty()) { + selectedBinding = std::make_unique( + plugins_, shortenerRegistry_, selected, + validator(selected, false)); + if (!selectedBinding->bind()) { + Void::Log::warn( + "PluginHost", + "Short URL provider '{}' failed service validation", + selected); + restorePrevious(); + return false; + } + } + + std::unique_ptr internalBinding; + const bool hasInternal = isLoaded(kInternal); + if (hasInternal) { + internalBinding = std::make_unique( + plugins_, internalShortenerRegistry_, + std::string{kInternal}, + validator(std::string{kInternal}, true)); + if (!internalBinding->bind()) { + Void::Log::warn("PluginHost", + "Internal short URL resolver failed " + "service validation"); + restorePrevious(); + return false; + } + } + + if (selectedBinding) { + selectedBinding->enable_hot_reload(); + shortenerBinding_ = std::move(selectedBinding); + } else { + shortenerBinding_.reset(); + (void)shortenerRegistry_.remove(); + } + if (internalBinding) { + internalBinding->enable_hot_reload(); + internalShortenerBinding_ = std::move(internalBinding); + } else { + internalShortenerBinding_.reset(); + (void)internalShortenerRegistry_ + .remove(); + } + return true; + } catch (const std::exception& error) { + Void::Log::warn("PluginHost", + "Binding short URL services threw: {}", + error.what()); + } catch (...) { + Void::Log::warn("PluginHost", "Binding short URL services threw"); + } + restorePrevious(); + return false; + } + + bool PluginHost::reconfigure(Configuration configuration) + { + std::scoped_lock operationLock{reconfigureMutex_}; + // Keep the previously validated service instances published while + // plugins are reconfigured. Reload callbacks must not expose a + // partially-applied provider before every plugin accepts the new + // configuration. + if (shortenerBinding_) { + shortenerBinding_->disable_hot_reload(); + } + if (internalShortenerBinding_) { + internalShortenerBinding_->disable_hot_reload(); + } + Configuration previous; + { + std::lock_guard lock(mutex_); + previous = configuration_; + configuration_ = std::move(configuration); + } + + const auto names = plugins_.names(); + std::vector reloaded; + reloaded.reserve(names.size()); + const auto rollback = [&] { + { + std::lock_guard lock(mutex_); + configuration_ = previous; + } + bool restored = true; + for (auto it = reloaded.rbegin(); it != reloaded.rend(); ++it) { + if (auto result = plugins_.reload(*it); !result) { + restored = false; + Void::Log::error( + "PluginHost", + "Plugin '{}' failed configuration rollback: {}", *it, + Void::Plugin::to_string(result.error())); + } + } + if (!bindShortenerServices()) { + restored = false; + Void::Log::error("PluginHost", + "Failed to restore short URL services after " + "configuration rollback"); + } + return restored; + }; + + for (const auto& name : names) { + if (auto result = plugins_.reload(name); !result) { + Void::Log::warn( + "PluginHost", + "Plugin '{}' rejected updated configuration: {}", + name, + Void::Plugin::to_string(result.error())); + (void)rollback(); + return false; + } + reloaded.push_back(name); + } + if (!bindShortenerServices()) { + Void::Log::warn( + "PluginHost", + "Updated configuration failed short URL service validation"); + (void)rollback(); + return false; + } + return true; + } + + std::shared_ptr PluginHost::shortener() const + { + return shortenerRegistry_.get(); + } + + Void::ShortUrl::ResolveResult + PluginHost::resolveShortLink(std::string_view key) const + { + const auto unavailable = [] { + return Void::ShortUrl::ResolveResult{ + .target_url = {}, + .expires_at_unix_seconds = 0, + .error = {.code = Void::ShortUrl::ErrorCode::unavailable, + .message = + "internal short URL resolver is unavailable"}}; + }; + auto service = + internalShortenerRegistry_.get(); + if (!service) { + return unavailable(); + } + try { + if (service->service_version() != Void::ShortUrl::kServiceVersion || + service->provider_id() != "url-shortener-internal" || + !service->supports_resolve()) { + return unavailable(); + } + const auto status = service->health().status; + if (status != Void::ShortUrl::HealthStatus::healthy && + status != Void::ShortUrl::HealthStatus::degraded) { + return unavailable(); + } + return service->resolve({.key = std::string(key)}); + } catch (const std::exception& error) { + Void::Log::warn("PluginHost", + "Internal short URL resolver threw: {}", + error.what()); + } catch (...) { + Void::Log::warn("PluginHost", "Internal short URL resolver threw"); + } + return unavailable(); + } + + Api::Result PluginHost::manage(const std::string& requestJson) + { + auto parsed = Void::Json::parse(requestJson); + if (!parsed || !parsed->is_object()) { + return Api::fail(Api::ErrorCode::ParseError, + "managed plugin request must be a JSON object"); + } + auto field = [&](std::string_view name) { + const auto* value = parsed->find(name); + return value && value->is_string() ? value->as_string() + : std::string{}; + }; + const auto action = field("action"); + if (action == "status") { + Void::Json::Value response = Void::Json::object(); + Void::Json::Value entries = Void::Json::array(); + for (const auto& name : plugins_.names()) { + auto handle = plugins_.acquire(name); + const auto info = + handle ? handle.info() : Void::Plugin::PluginInfo{}; + Void::Json::Value entry = Void::Json::object(); + auto& object = entry.as_object(); + object.emplace_back("id", Void::Json::Value{name}); + object.emplace_back( + "name", Void::Json::Value{ + info.name && *info.name ? info.name : name}); + object.emplace_back("version", + Void::Json::Value{info.plugin_version + ? info.plugin_version + : ""}); + { + std::lock_guard lock(mutex_); + object.emplace_back( + "managed", Void::Json::Value{managed_.contains(name)}); + if (const auto path = loadedPaths_.find(name); + path != loadedPaths_.end()) { + object.emplace_back( + "path", Void::Json::Value{path->second.string()}); + } + } + entries.as_array().push_back(std::move(entry)); + } + response.as_object().emplace_back("schemaVersion", + Void::Json::Value{1LL}); + response.as_object().emplace_back("plugins", std::move(entries)); + return Void::Json::serialize(response); + } + if (action != "replace") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "managed plugin action must be status or replace"); + } + std::scoped_lock operationLock{reconfigureMutex_}; + const auto pluginId = field("pluginId"); + const auto version = field("version"); + const std::filesystem::path requestedPath{field("path")}; + if (pluginId.empty() || version.empty() || requestedPath.empty() || + managedDirectory_.empty()) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "replace requires pluginId, version, path, and a managed root"); + } + std::error_code error; + const auto path = std::filesystem::canonical(requestedPath, error); + if (error) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "managed plugin path must be a regular file below " + "the managed root"); + } + const auto root = std::filesystem::canonical(managedDirectory_, error); + const auto rootEnd = + std::mismatch(root.begin(), root.end(), path.begin(), path.end()) + .first; + if (error || rootEnd != root.end() || + !std::filesystem::is_regular_file(path)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "managed plugin path must be a regular file below " + "the managed root"); + } + const auto loadedNames = plugins_.names(); + const bool exists = + std::ranges::find(loadedNames, pluginId) != loadedNames.end(); + std::optional previousPath; + if (exists) { + std::lock_guard lock(mutex_); + if (const auto current = loadedPaths_.find(pluginId); + current != loadedPaths_.end()) { + previousPath = current->second; + } + } + if (exists && !previousPath) { + return Api::fail(Api::ErrorCode::PluginError, + "current plugin path is unavailable; refusing a " + "non-rollbackable replacement"); + } + + // Do not let a reload callback publish a service from the candidate + // until its complete service contract has been validated below. + if (shortenerBinding_) { + shortenerBinding_->disable_hot_reload(); + } + if (internalShortenerBinding_) { + internalShortenerBinding_->disable_hot_reload(); + } + const auto resumeCurrentServices = [&] { + if (!bindShortenerServices()) { + Void::Log::error( + "PluginHost", + "Failed to resume short URL services after a rejected " + "plugin replacement"); + } + }; + if (exists) { + if (auto replaced = plugins_.replace(pluginId, path); !replaced) { + resumeCurrentServices(); + return Api::fail( + Api::ErrorCode::PluginError, + std::format("plugin replacement rejected: {}", + Void::Plugin::to_string(replaced.error()))); + } + } else { + auto loaded = plugins_.load(path); + if (!loaded || *loaded != pluginId) { + if (loaded) { + std::ignore = plugins_.unload(*loaded); + } + resumeCurrentServices(); + return Api::fail( + Api::ErrorCode::PluginError, + loaded + ? "plugin reported a different name" + : std::format("plugin load rejected: {}", + Void::Plugin::to_string(loaded.error()))); + } + } + if (!bindShortenerServices()) { + std::string rollbackError; + if (exists) { + if (auto restored = plugins_.replace(pluginId, *previousPath); + !restored) { + rollbackError = std::format( + "; restoring the previous plugin failed: {}", + Void::Plugin::to_string(restored.error())); + } + } else { + unpublish(pluginId); + if (auto unloaded = plugins_.unload(pluginId); !unloaded) { + rollbackError = std::format( + "; unloading the rejected plugin failed: {}", + Void::Plugin::to_string(unloaded.error())); + } + } + resumeCurrentServices(); + return Api::fail( + Api::ErrorCode::PluginError, + "plugin replacement failed short URL service validation" + + rollbackError); + } + if (!exists) { + plugins_.watch(pluginId); + } + { + std::lock_guard lock(mutex_); + managed_[pluginId] = {.version = version, .path = path}; + loadedPaths_[pluginId] = path; + } + publish(pluginId); + notifyChanged(); + Void::Json::Value response = Void::Json::object(); + response.as_object().emplace_back("pluginId", + Void::Json::Value{pluginId}); + response.as_object().emplace_back("version", + Void::Json::Value{version}); + response.as_object().emplace_back("state", + Void::Json::Value{"healthy"}); + return Void::Json::serialize(response); } void PluginHost::setChangeCallback(std::function callback) @@ -249,16 +943,20 @@ namespace Echoion::Core std::lock_guard lock(mutex_); callback = changeCallback_; } - if (callback) callback(); + if (callback) { + callback(); + } } void PluginHost::publish(std::string_view name) { unpublish(name); auto pin = plugins_.acquire(name); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) return; + auto* extension = + pin ? dynamic_cast(pin.get()) : nullptr; + if (!extension) { + return; + } std::vector commands; std::vector mediaSources; try { @@ -266,10 +964,11 @@ namespace Echoion::Core mediaSources = extension->mediaSources(); } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' descriptors threw: {}", - name, error.what()); + name, error.what()); return; } catch (...) { - Void::Log::error("PluginHost", "Plugin '{}' descriptors threw", name); + Void::Log::error("PluginHost", "Plugin '{}' descriptors threw", + name); return; } for (const auto& descriptor : commands) { @@ -277,8 +976,9 @@ namespace Echoion::Core plugins_, std::string(name), descriptor); if (!commands_.registerExternalCommand( std::string(name), descriptor.name, std::move(command))) { - Void::Log::warn("PluginHost", "Command '{}' from '{}' conflicts", - descriptor.name, name); + Void::Log::warn("PluginHost", + "Command '{}' from '{}' conflicts", + descriptor.name, name); } } for (auto source : mediaSources) { @@ -286,12 +986,17 @@ namespace Echoion::Core std::lock_guard lock(mutex_); if (std::ranges::any_of(sources_, [&](const auto& existing) { return existing->represents(name, source.name); - })) continue; + })) { + continue; + } } auto proxy = std::make_shared( - weak_from_this(), plugins_, std::string(name), std::move(source)); + weak_from_this(), plugins_, std::string(name), + std::move(source)); music_->addTrackSource(proxy); - if (mediaSink_) mediaSink_(proxy); + if (mediaSink_) { + mediaSink_(proxy); + } std::lock_guard lock(mutex_); sources_.push_back(std::move(proxy)); } @@ -309,45 +1014,55 @@ namespace Echoion::Core for (const auto& name : plugins_.names()) { try { auto pin = plugins_.acquire(name); - if (auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr) { + if (auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr) { extension->onEvent(event); } } catch (const std::exception& error) { - Void::Log::error("PluginHost", "Plugin '{}' event handler threw: {}", - name, error.what()); + Void::Log::error("PluginHost", + "Plugin '{}' event handler threw: {}", name, + error.what()); } catch (...) { - Void::Log::error("PluginHost", "Plugin '{}' event handler threw", name); + Void::Log::error("PluginHost", + "Plugin '{}' event handler threw", name); } } } - Api::Result PluginHost::call( - std::string_view plugin, std::string_view method, std::string params, - uint64_t clientId) const + Api::Result PluginHost::call(std::string_view plugin, + std::string_view method, + std::string params, + uint64_t clientId) const { try { auto pin = plugins_.acquire(plugin); - auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr; - if (!extension) return Api::fail(Api::ErrorCode::NotFound, - "plugin not found"); + auto* extension = + pin ? dynamic_cast(pin.get()) : nullptr; + if (!extension) { + return Api::fail(Api::ErrorCode::NotFound, "plugin not found"); + } auto rpc = extension->rpcMethods(); - auto descriptor = std::ranges::find(rpc, method, &Api::ExtensionRpc::name); - if (descriptor == rpc.end()) return Api::fail(Api::ErrorCode::NotFound, - "plugin RPC method not found"); + auto descriptor = + std::ranges::find(rpc, method, &Api::ExtensionRpc::name); + if (descriptor == rpc.end()) { + return Api::fail(Api::ErrorCode::NotFound, + "plugin RPC method not found"); + } if (descriptor->adminOnly && (!isAdmin_ || !isAdmin_(clientId))) { return Api::fail(Api::ErrorCode::PermissionDenied, - "admin privileges required"); + "admin privileges required"); } return extension->callRpc({.method = std::string(method), - .params = std::move(params), .clientId = clientId}); + .params = std::move(params), + .clientId = clientId}); } catch (const std::exception& error) { Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw: {}", - plugin, method, error.what()); + plugin, method, error.what()); return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed"); } catch (...) { - Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw", plugin, method); + Void::Log::error("PluginHost", "Plugin '{}' RPC '{}' threw", plugin, + method); return Api::fail(Api::ErrorCode::UnknownError, "plugin RPC failed"); } } @@ -358,31 +1073,39 @@ namespace Echoion::Core for (const auto& name : plugins_.names()) { try { auto pin = plugins_.acquire(name); - if (auto* extension = pin - ? dynamic_cast(pin.get()) : nullptr) { + if (auto* extension = + pin ? dynamic_cast(pin.get()) + : nullptr) { auto current = extension->webAssets(); - assets.insert(assets.end(), std::make_move_iterator(current.begin()), - std::make_move_iterator(current.end())); + assets.insert(assets.end(), + std::make_move_iterator(current.begin()), + std::make_move_iterator(current.end())); } } catch (const std::exception& error) { - Void::Log::error("PluginHost", "Plugin '{}' web assets threw: {}", - name, error.what()); + Void::Log::error("PluginHost", + "Plugin '{}' web assets threw: {}", name, + error.what()); } catch (...) { - Void::Log::error("PluginHost", "Plugin '{}' web assets threw", name); + Void::Log::error("PluginHost", "Plugin '{}' web assets threw", + name); } } return assets; } - std::vector PluginHost::names() const { return plugins_.names(); } + std::vector PluginHost::names() const + { + return plugins_.names(); + } std::vector PluginHost::snapshotStates() const { std::vector states; for (const auto& name : plugins_.names()) { if (auto state = plugins_.serialize_state(name)) { - states.push_back({.name = name, .json = std::move(state->json), - .version = state->version}); + states.push_back({.name = name, + .json = std::move(state->json), + .version = state->version}); } } return states; @@ -391,10 +1114,12 @@ namespace Echoion::Core void PluginHost::restoreStates(const std::vector& states) { for (const auto& state : states) { - if (!plugins_.deserialize_state(state.name, state.json, state.version)) { - Void::Log::warn("PluginHost", "Plugin '{}' rejected restored state", - state.name); + if (!plugins_.deserialize_state(state.name, state.json, + state.version)) { + Void::Log::warn("PluginHost", + "Plugin '{}' rejected restored state", + state.name); } } } -} +} // namespace Echoion::Core diff --git a/src/UrlShortener.cpp b/src/UrlShortener.cpp index 51c3c9a..9455577 100644 --- a/src/UrlShortener.cpp +++ b/src/UrlShortener.cpp @@ -1,158 +1,155 @@ -#include #include "echoion/core/UrlShortener.hpp" -#include -#include + +#include + +#include +#include +#include +#include +#include namespace Echoion::Core { - - UrlShortener::UrlShortener(std::shared_ptr networkClient) - : networkClient_(std::move(networkClient)) + namespace { - } - - UrlShortener::~UrlShortener() = default; - - Api::Result - UrlShortener::shortenYouTubeUrl(std::string_view videoId) - { - std::string originalUrl = - std::format("https://www.youtube.com/watch?v={}", videoId); - return shortenUrl(originalUrl); - } - - Api::Result - UrlShortener::shortenUrl(std::string_view originalUrl) - { - // Check cache first + std::string lower(std::string value) { - std::lock_guard lock(cacheMutex_); - auto it = cache_.find(std::string(originalUrl)); - if (it != cache_.end()) { - auto now = std::chrono::system_clock::now(); - if (now - it->second.timestamp < cacheTtl_) { - Void::Log::debug("UrlShortener", "{}", std::format("URL cache hit: {} -> {}", - originalUrl, - it->second.shortenedUrl)); - return it->second.shortenedUrl; - } - // Expired, remove from cache - cache_.erase(it); + std::ranges::transform(value, value.begin(), [](unsigned char ch) { + return static_cast(std::tolower(ch)); + }); + return value; + } + + std::optional sourceFromName(std::string name) + { + name = lower(std::move(name)); + if (name == "youtube") { + return Api::TrackSource::YouTube; + } + if (name == "yandex") { + return Api::TrackSource::Yandex; + } + if (name == "url") { + return Api::TrackSource::URL; + } + if (name == "soundcloud") { + return Api::TrackSource::SoundCloud; + } + if (name == "spotify") { + return Api::TrackSource::Spotify; + } + if (name == "plugin") { + return Api::TrackSource::Plugin; + } + return std::nullopt; + } + + Api::ErrorCode apiError(Void::ShortUrl::ErrorCode code) + { + using enum Void::ShortUrl::ErrorCode; + switch (code) { + case invalid_request: + return Api::ErrorCode::InvalidArgument; + case invalid_url: + return Api::ErrorCode::InvalidUrl; + case unsupported: + return Api::ErrorCode::NotSupported; + case not_found: + case expired: + case revoked: + return Api::ErrorCode::NotFound; + case conflict: + return Api::ErrorCode::AlreadyExists; + case unauthorized: + return Api::ErrorCode::Unauthorized; + case unavailable: + case timeout: + case rate_limited: + return Api::ErrorCode::ServiceUnavailable; + case provider_error: + case response_too_large: + return Api::ErrorCode::NetworkError; + case storage: + return Api::ErrorCode::DatabaseError; + default: + return Api::ErrorCode::UnknownError; } } + } // namespace - if (!networkClient_) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Network client not available"); + void UrlShortener::setProvider(ProviderGetter provider) + { + std::lock_guard lock(mutex_); + provider_ = std::move(provider); + } + + void UrlShortener::setSources(const std::vector& sources) + { + std::unordered_set parsed; + for (const auto& source : sources) { + if (auto value = sourceFromName(source)) { + parsed.insert(*value); + } + } + std::lock_guard lock(mutex_); + sources_ = std::move(parsed); + } + + bool UrlShortener::sourceAllowed(Api::TrackSource source) const + { + std::lock_guard lock(mutex_); + return source != Api::TrackSource::LocalFile && + sources_.contains(source); + } + + Api::Result + UrlShortener::shortenUrl(std::string_view originalUrl, + Api::TrackSource source) const + { + if (originalUrl.empty() || !sourceAllowed(source)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "URL source is not enabled for shortening"); } - // faumaray.ru API endpoint for URL shortening - // POST /shorten with JSON body {"longUrl": "https://..."} - // Response: {"shortUrl": "https://faumaray.ru/xxxxx"} - std::string apiUrl = "https://faumaray.ru/shorten"; - - // Build JSON request body - API expects "longUrl" field - std::string jsonBody = - std::format(R"({{"longUrl":"{}"}})", originalUrl); - - std::vector headers = { - {"Content-Type", "application/json"}, - {"User-Agent", "EchoionBot/1.0"}}; - - Void::Log::debug("UrlShortener", "{}", - std::format("Shortening URL via faumaray.ru: {}", originalUrl)); - - auto response = networkClient_->post(apiUrl, jsonBody, headers); - - if (!response) { - Void::Log::warn("UrlShortener", "{}", std::format("URL shortening failed: {}", - response.error().message)); - return Api::fail(Api::ErrorCode::NetworkError, - "Failed to shorten URL"); + ProviderGetter getter; + { + std::lock_guard lock(mutex_); + getter = provider_; } - - if (!response->ok()) { - Void::Log::warn("UrlShortener", "{}", std::format("URL shortening returned HTTP {}", - response->status)); - return Api::fail(Api::ErrorCode::NetworkError, - std::format("Shortening service returned HTTP {}", - response->status)); - } - try { - // Parse response - expecting {"shortUrl": - // "https://faumaray.ru/xxxxx"} - auto parsed = Void::Json::parse(response->body); - if (!parsed) { - Void::Log::warn("UrlShortener", "{}", "Failed to parse URL shortening response"); - return Api::fail(Api::ErrorCode::ParseError, - "Failed to parse shortening response"); + auto provider = getter ? getter() : nullptr; + if (!provider || provider->service_version() != + Void::ShortUrl::kServiceVersion) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "URL shortener provider is unavailable"); + } + const auto health = provider->health(); + if (health.status == Void::ShortUrl::HealthStatus::unhealthy) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + health.message.empty() + ? "URL shortener provider is unhealthy" + : health.message); } - std::string shortenedUrl; - const Void::Json::Value* shortUrl = parsed->find("shortUrl"); - if (shortUrl && shortUrl->is_string()) { - shortenedUrl = shortUrl->as_string(); - } else { - Void::Log::warn("UrlShortener", "{}", "No shortUrl field in response"); - return Api::fail(Api::ErrorCode::ParseError, - "No shortUrl in response"); - } - - // Cache the result - { - std::lock_guard lock(cacheMutex_); - cache_[std::string(originalUrl)] = { - .shortenedUrl = shortenedUrl, - .timestamp = std::chrono::system_clock::now()}; - } - - Void::Log::debug("UrlShortener", "{}", std::format("URL shortened: {} -> {}", - originalUrl, shortenedUrl)); - return shortenedUrl; - - } catch (const std::exception& e) { - Void::Log::warn("UrlShortener", "{}", std::format( - "Exception parsing shortening response: {}", e.what())); - return Api::fail( - Api::ErrorCode::ParseError, "Exception during URL shortening"); - } - } - - std::optional - UrlShortener::getCachedUrl(std::string_view originalUrl) const - { - std::lock_guard lock(cacheMutex_); - auto it = cache_.find(std::string(originalUrl)); - if (it != cache_.end()) { - auto now = std::chrono::system_clock::now(); - if (now - it->second.timestamp < cacheTtl_) { - return it->second.shortenedUrl; - } - } - return std::nullopt; - } - - void UrlShortener::clearCache() - { - std::lock_guard lock(cacheMutex_); - cache_.clear(); - } - - void UrlShortener::setCacheTtl(std::chrono::hours ttl) { cacheTtl_ = ttl; } - - void UrlShortener::cleanExpiredCache() - { - std::lock_guard lock(cacheMutex_); - auto now = std::chrono::system_clock::now(); - - for (auto it = cache_.begin(); it != cache_.end();) { - if (now - it->second.timestamp >= cacheTtl_) { - it = cache_.erase(it); - } else { - ++it; + auto result = + provider->shorten({.target_url = std::string(originalUrl), + .custom_key = {}, + .expires_at_unix_seconds = 0}); + if (!result.ok() || result.short_url.empty()) { + return Api::fail(apiError(result.error.code), + result.error.message.empty() + ? "URL shortening failed" + : result.error.message); } + return result.short_url; + } catch (const std::exception& error) { + Void::Log::warn("UrlShortener", "Provider call failed: {}", + error.what()); + } catch (...) { + Void::Log::warn("UrlShortener", "Provider call failed"); } + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "URL shortener provider failed"); } } // namespace Echoion::Core diff --git a/src/YouTubeClient.cpp b/src/YouTubeClient.cpp index 4c828ed..ba5599f 100644 --- a/src/YouTubeClient.cpp +++ b/src/YouTubeClient.cpp @@ -31,7 +31,7 @@ namespace Echoion::Core YouTubeClient::YouTubeClient(std::shared_ptr networkClient) : networkClient_(std::move(networkClient)), ytDlpManager_(std::make_unique(networkClient_)), - urlShortener_(std::make_unique(networkClient_)) + urlShortener_(std::make_unique()) { } @@ -492,9 +492,8 @@ namespace Echoion::Core return results; } - Api::Result - YouTubeClient::search(std::string_view query, - std::optional pageToken) + Api::Result YouTubeClient::search( + std::string_view query, std::optional pageToken) { if (!initialized_) { @@ -839,8 +838,7 @@ namespace Echoion::Core } Api::Result YouTubeClient::searchWithYtDlp( - std::string_view query, - const std::optional& /*pageToken*/) + std::string_view query, const std::optional& /*pageToken*/) { return searchWithYtDlpProvider(query, "ytsearch5", Api::TrackSource::YouTube); @@ -853,9 +851,10 @@ namespace Echoion::Core Api::TrackSource::SoundCloud); } - Api::Result YouTubeClient::searchWithYtDlpProvider( - std::string_view query, std::string_view searchPrefix, - Api::TrackSource source) + Api::Result + YouTubeClient::searchWithYtDlpProvider(std::string_view query, + std::string_view searchPrefix, + Api::TrackSource source) { if (!ytDlpManager_->isAvailable()) { @@ -1061,10 +1060,9 @@ namespace Echoion::Core // per call; combined with the shuffled results this gives the radio a // varied backstop when no related/unplayed track is available. static const std::array kQueries = { - "popular music", "top hits", "rock music", - "electronic music", "hip hop music", "lofi hip hop", - "pop music", "jazz music", "indie music", - "dance music"}; + "popular music", "top hits", "rock music", "electronic music", + "hip hop music", "lofi hip hop", "pop music", "jazz music", + "indie music", "dance music"}; static thread_local std::mt19937 rng(std::random_device{}()); std::uniform_int_distribution pick(0, kQueries.size() - 1); @@ -1610,60 +1608,21 @@ namespace Echoion::Core { std::string url_str(url); - // Handle faumaray.ru redirects using NetworkClient - if (url_str.find("faumaray.ru") != std::string::npos && - networkClient_) { - Void::Log::debug( - "YouTubeClient", "{}", - std::format("Following redirect for: {}", url_str)); - - std::vector 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->status >= 300 && response->status < 400) { - auto location = response->header("location"); - if (location.has_value()) { - Void::Log::debug( - "YouTubeClient", "{}", - std::format("Redirected to: {}", *location)); - url_str = std::string(*location); - } - } else if (response->ok()) { - // 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->header( - "x-final-url"); // Some clients add this - if (finalUrl.has_value()) { - url_str = std::string(*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]*)?)", + 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]*)?)", + 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]*)?)", + 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]*)?)", + R"(^(?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)", std::regex::icase); // Also match just the video ID (11 characters) @@ -1697,9 +1656,10 @@ namespace Echoion::Core bool YouTubeClient::isYouTubeUrl(std::string_view url) { - return url.find("faumaray.ru") != std::string::npos || - url.find("youtube.com") != std::string::npos || - url.find("youtu.be") != std::string::npos; + static const std::regex youtubeUrlPattern( + R"(^(?:https?://)?(?:www\.)?(?:youtube\.com(?:/|$)|youtu\.be(?:/|$)))", + std::regex::icase); + return std::regex_search(url.begin(), url.end(), youtubeUrlPattern); } void YouTubeClient::setUrlShorteningEnabled(bool enabled) @@ -1711,6 +1671,25 @@ namespace Echoion::Core std::format("URL shortening {}", enabled ? "enabled" : "disabled")); } + void YouTubeClient::setUrlShortenerProvider( + UrlShortener::ProviderGetter provider) + { + urlShortener_->setProvider(std::move(provider)); + } + + void YouTubeClient::setUrlShorteningSources( + const std::vector& sources) + { + urlShortener_->setSources(sources); + } + + void YouTubeClient::setUrlShorteningTimeout( + std::chrono::milliseconds timeout) + { + std::lock_guard lock(configMutex_); + urlShorteningTimeout_ = timeout; + } + void YouTubeClient::setAutoUpdateEnabled(bool enabled) { if (ytDlpManager_) { @@ -1727,35 +1706,46 @@ namespace Echoion::Core void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track) { bool enabled; + std::chrono::milliseconds timeout; { std::lock_guard lock(configMutex_); enabled = urlShorteningEnabled_; + timeout = urlShorteningTimeout_; } - if (!enabled || !urlShortener_ || track.id.empty()) { + if (!enabled || !urlShortener_ || + (track.shortenedUrl && !track.shortenedUrl->empty())) { return; } + std::string originalUrl = track.originalUrl; + if (originalUrl.empty() && track.source == Api::TrackSource::YouTube && + !track.id.empty()) { + originalUrl = + std::format("https://www.youtube.com/watch?v={}", track.id); + } + if (originalUrl.empty()) { + return; + } + const auto source = track.source; // Run URL shortening on the shared pool with a timeout. Best-effort: if // it times out we keep the track unshortened. The future is only read // on the ready path (which establishes happens-before), and on timeout // the task keeps running on the pool with its result discarded — no // detached thread and no busy-wait poll. - auto trackId = track.id; - auto future = - pool_.submit([this, trackId]() -> std::optional { - try { - auto result = urlShortener_->shortenYouTubeUrl(trackId); - if (result) { - return *result; - } - } catch (...) { - // Ignore exceptions - this is best-effort + auto future = pool_.submit([this, originalUrl = std::move(originalUrl), + source]() -> std::optional { + try { + auto result = urlShortener_->shortenUrl(originalUrl, source); + if (result) { + return *result; } - return std::nullopt; - }); + } catch (...) { + // Ignore exceptions - this is best-effort + } + return std::nullopt; + }); - if (future.wait_for(std::chrono::seconds(3)) == - std::future_status::ready) { + if (future.wait_for(timeout) == std::future_status::ready) { if (auto shortened = future.get()) { track.shortenedUrl = *shortened; Void::Log::debug("YouTubeClient", "{}", @@ -1765,7 +1755,8 @@ namespace Echoion::Core } } else { Void::Log::warn("YouTubeClient", "{}", - "URL shortening timed out after 3s"); + std::format("URL shortening timed out after {}ms", + timeout.count())); } } @@ -1773,9 +1764,11 @@ namespace Echoion::Core std::vector& tracks) { bool enabled; + std::chrono::milliseconds timeout; { std::lock_guard lock(configMutex_); enabled = urlShorteningEnabled_; + timeout = urlShorteningTimeout_; } if (!enabled || !urlShortener_ || tracks.empty()) { return; @@ -1798,30 +1791,42 @@ namespace Echoion::Core slots.reserve(tracks.size()); for (auto& track : tracks) { - if (track.id.empty()) { + if (track.shortenedUrl && !track.shortenedUrl->empty()) { continue; } - auto trackId = track.id; + std::string originalUrl = track.originalUrl; + if (originalUrl.empty() && + track.source == Api::TrackSource::YouTube && + !track.id.empty()) { + originalUrl = + std::format("https://www.youtube.com/watch?v={}", track.id); + } + if (originalUrl.empty()) { + continue; + } + const auto source = track.source; auto out = std::make_shared>(); - auto future = pool_.submit([this, trackId, out]() { - try { - auto result = urlShortener_->shortenYouTubeUrl(trackId); - if (result) { - *out = *result; + auto future = pool_.submit( + [this, originalUrl = std::move(originalUrl), source, out]() { + try { + auto result = + urlShortener_->shortenUrl(originalUrl, source); + if (result) { + *out = *result; + } + } catch (...) { + // Ignore exceptions - best-effort } - } catch (...) { - // Ignore exceptions - best-effort - } - }); + }); slots.push_back({&track, std::move(out), std::move(future)}); } - // Wait for all with an overall 5-second timeout. + // Wait for all with the configured overall timeout. auto start = std::chrono::steady_clock::now(); for (auto& slot : slots) { - auto remaining = std::chrono::seconds(5) - - (std::chrono::steady_clock::now() - start); - if (remaining <= std::chrono::seconds::zero()) { + auto remaining = + timeout - (std::chrono::steady_clock::now() - start); + if (remaining <= std::chrono::milliseconds::zero()) { break; } slot.future.wait_for(remaining); diff --git a/src/sources/YandexMusicSource.cpp b/src/sources/YandexMusicSource.cpp index 8555e61..33cd963 100644 --- a/src/sources/YandexMusicSource.cpp +++ b/src/sources/YandexMusicSource.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -62,27 +63,6 @@ namespace Echoion::Core return std::regex_search(url, playlist); } - std::string percentEncode(std::string_view text) - { - static constexpr char hex[] = "0123456789ABCDEF"; - std::string out; - out.reserve(text.size() * 3); - for (unsigned char c : text) { - const bool unreserved = (c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') || - (c >= '0' && c <= '9') || c == '-' || - c == '_' || c == '.' || c == '~'; - if (unreserved) { - out.push_back(static_cast(c)); - } else { - out.push_back('%'); - out.push_back(hex[c >> 4]); - out.push_back(hex[c & 0xF]); - } - } - return out; - } - std::string str(const Void::Json::Value& v, const char* key) { const auto* f = v.find(key); @@ -198,8 +178,8 @@ namespace Echoion::Core "Yandex Music not configured"); } - auto body = - apiGet("/search?type=track&page=0&text=" + percentEncode(query)); + auto body = apiGet("/search?type=track&page=0&text=" + + Void::Encoding::Url::encode(query)); if (!body) { return std::unexpected(body.error()); } diff --git a/tests/test_config_loader.cpp b/tests/test_config_loader.cpp new file mode 100644 index 0000000..fc10e9c --- /dev/null +++ b/tests/test_config_loader.cpp @@ -0,0 +1,111 @@ +#include "echoion/core/ConfigLoader.hpp" + +#include +#include +#include + +namespace +{ + int failures = 0; + + void expect(bool condition, std::string_view message) + { + if (!condition) { + std::cerr << "FAILED: " << message << '\n'; + ++failures; + } + } + + void expectShortening(std::string_view name, std::string_view json, + bool enabled, std::string_view provider) + { + const auto config = Echoion::Core::ConfigLoader::loadFromJson(json); + if (!config) { + std::cerr << "FAILED: " << name + << " did not parse: " << config.error().message << '\n'; + ++failures; + return; + } + + expect(config->urlShortening.enabled == enabled, + std::string{name} + " enabled state"); + expect(config->urlShortening.provider == provider, + std::string{name} + " provider"); + } +} // namespace + +int main() +{ + using Echoion::Core::ConfigLoader; + + const auto defaults = ConfigLoader::createDefaultConfig(); + expect(!defaults.urlShortening.enabled, + "generated defaults keep URL shortening disabled"); + + expectShortening("legacy disabled", + R"({ + "youtube": {"enableUrlShortening": false}, + "web": {"publicUrl": "https://bot.example"} + })", + false, "url-shortener-internal"); + + const auto legacyEnabled = ConfigLoader::loadFromJson(R"({ + "youtube": {"enableUrlShortening": true}, + "web": {"publicUrl": "https://bot.example"} + })"); + if (!legacyEnabled) { + std::cerr << "FAILED: legacy enabled did not parse: " + << legacyEnabled.error().message << '\n'; + ++failures; + } else { + expect(legacyEnabled->urlShortening.enabled, + "legacy enabled flag migrates through JSON updates"); + expect(legacyEnabled->urlShortening.provider == + "url-shortener-internal", + "legacy migration selects internal provider"); + expect(legacyEnabled->urlShortening.sources.size() == 1 && + legacyEnabled->urlShortening.sources.front() == "youtube", + "legacy migration limits shortening to YouTube"); + } + + expectShortening("explicit section wins", + R"({ + "youtube": {"enableUrlShortening": true}, + "urlShortening": { + "enabled": false, + "provider": "url-shortener-internal" + }, + "web": {"publicUrl": "https://bot.example"} + })", + false, "url-shortener-internal"); + + expectShortening("internal provider without public URL", + R"({ + "urlShortening": { + "enabled": true, + "provider": "url-shortener-internal" + } + })", + false, "url-shortener-internal"); + + expectShortening("internal provider with public URL", + R"({ + "urlShortening": { + "enabled": true, + "provider": "url-shortener-internal" + }, + "web": {"publicUrl": "https://bot.example"} + })", + true, "url-shortener-internal"); + + expectShortening("external provider without public URL", + R"({ + "urlShortening": { + "enabled": true, + "provider": "url-shortener-external" + } + })", + true, "url-shortener-external"); + + return failures == 0 ? 0 : 1; +} diff --git a/tests/test_url_shortener.cpp b/tests/test_url_shortener.cpp new file mode 100644 index 0000000..c7261f0 --- /dev/null +++ b/tests/test_url_shortener.cpp @@ -0,0 +1,154 @@ +#include "echoion/core/UrlShortener.hpp" +#include "echoion/core/YouTubeClient.hpp" + +#include +#include +#include +#include +#include +#include + +namespace +{ + class FakeShortener final : public Void::ShortUrl::IShortener + { + public: + + [[nodiscard]] std::uint32_t + service_version() const noexcept override + { + return version; + } + + [[nodiscard]] std::string_view provider_id() const noexcept override + { + return "test-shortener"; + } + + [[nodiscard]] Void::ShortUrl::Health health() const override + { + if (throwFromHealth) { + throw std::runtime_error("health failure"); + } + return {.status = healthStatus, .message = {}}; + } + + [[nodiscard]] Void::ShortUrl::ShortenResult + shorten(const Void::ShortUrl::ShortenRequest& request) override + { + ++calls; + lastTarget = request.target_url; + return { + .short_url = "https://sho.rt/abc", + .key = "abc", + .expires_at_unix_seconds = 0, + .error = {}, + }; + } + + std::uint32_t version{Void::ShortUrl::kServiceVersion}; + Void::ShortUrl::HealthStatus healthStatus{ + Void::ShortUrl::HealthStatus::healthy}; + bool throwFromHealth{false}; + int calls{0}; + std::string lastTarget; + }; + + bool expect(bool condition, std::string_view message) + { + if (!condition) { + std::cerr << message << '\n'; + } + return condition; + } +} // namespace + +int main() +{ + using Echoion::Api::ErrorCode; + using Echoion::Api::TrackSource; + using Echoion::Core::UrlShortener; + using Echoion::Core::YouTubeClient; + + if (!expect( + YouTubeClient::isYouTubeUrl( + "https://www.youtube.com/watch?v=dQw4w9WgXcQ") && + YouTubeClient::isYouTubeUrl("https://youtu.be/dQw4w9WgXcQ") && + !YouTubeClient::isYouTubeUrl( + "https://youtube.com.evil.test/watch?v=dQw4w9WgXcQ") && + !YouTubeClient::isYouTubeUrl( + "https://example.test/?next=youtube.com"), + "YouTube URL classification accepted a non-YouTube host")) { + return 1; + } + + auto provider = std::make_shared(); + UrlShortener shortener; + shortener.setProvider([provider] { return provider; }); + + constexpr std::array sourceCases = { + std::pair{"youtube", TrackSource::YouTube}, + std::pair{"yandex", TrackSource::Yandex}, + std::pair{"url", TrackSource::URL}, + std::pair{"soundcloud", TrackSource::SoundCloud}, + std::pair{"spotify", TrackSource::Spotify}, + std::pair{"plugin", TrackSource::Plugin}, + }; + for (const auto& [name, source] : sourceCases) { + shortener.setSources({name}); + auto result = + shortener.shortenUrl("https://example.test/track", source); + if (!expect(result && *result == "https://sho.rt/abc", + "configured source was not shortened")) { + return 1; + } + } + + const int acceptedCalls = provider->calls; + shortener.setSources({"url"}); + for (const auto source : + {TrackSource::Unknown, TrackSource::LocalFile, TrackSource::YouTube}) { + auto result = + shortener.shortenUrl("https://example.test/rejected", source); + if (!expect(!result && + result.error().code == ErrorCode::InvalidArgument, + "unconfigured or unsafe source was accepted")) { + return 1; + } + } + if (!expect(provider->calls == acceptedCalls, + "provider was called for a rejected source")) { + return 1; + } + + provider->healthStatus = Void::ShortUrl::HealthStatus::unhealthy; + auto unhealthy = + shortener.shortenUrl("https://example.test/track", TrackSource::URL); + if (!expect(!unhealthy && + unhealthy.error().code == ErrorCode::ServiceUnavailable, + "unhealthy provider was accepted")) { + return 1; + } + + provider->healthStatus = Void::ShortUrl::HealthStatus::healthy; + provider->version = Void::ShortUrl::kServiceVersion + 1; + auto incompatible = + shortener.shortenUrl("https://example.test/track", TrackSource::URL); + if (!expect(!incompatible && + incompatible.error().code == ErrorCode::ServiceUnavailable, + "incompatible provider was accepted")) { + return 1; + } + + provider->version = Void::ShortUrl::kServiceVersion; + provider->throwFromHealth = true; + auto throwing = + shortener.shortenUrl("https://example.test/track", TrackSource::URL); + if (!expect(!throwing && + throwing.error().code == ErrorCode::ServiceUnavailable, + "provider exception escaped the adapter")) { + return 1; + } + + return 0; +}