Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:42 +03:00
1 parent 9f06af6c80
commit 7975f2b38e
19 files changed
+2020 -747

No files matched your search

+18 -1
View File
@@ -116,7 +116,7 @@ target_link_libraries(EchoionCore
PUBLIC PUBLIC
PkgConfig::LIBAV PkgConfig::LIBAV
TBB::tbb TBB::tbb
SQLite3::SQLite3 SQLite::SQLite3
# VoidLibrary modules (migration target — replacing in-house infra) # VoidLibrary modules (migration target — replacing in-house infra)
Void::Data Void::Data
Void::Functional Void::Functional
@@ -131,6 +131,7 @@ target_link_libraries(EchoionCore
Void::Net Void::Net
Void::Sqlite Void::Sqlite
Void::Service Void::Service
Void::ShortUrl
Void::Plugin Void::Plugin
PRIVATE PRIVATE
Threads::Threads Threads::Threads
@@ -220,6 +221,14 @@ install(FILES
) )
if(BUILD_TESTS) 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 add_executable(echoion_core_extension_state_tests
tests/test_extension_state.cpp) tests/test_extension_state.cpp)
target_include_directories(echoion_core_extension_state_tests PRIVATE 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) target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore)
add_test(NAME echoion_core_teamspeak_directory_tests add_test(NAME echoion_core_teamspeak_directory_tests
COMMAND 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() endif()
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF) option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
+9 -1
View File
@@ -4,6 +4,7 @@
#include <Types.hpp> #include <Types.hpp>
#include <filesystem> #include <filesystem>
#include <string> #include <string>
#include <string_view>
namespace Echoion::Core namespace Echoion::Core
{ {
@@ -22,6 +23,12 @@ namespace Echoion::Core
[[nodiscard]] static Api::Result<Api::AppConfig> [[nodiscard]] static Api::Result<Api::AppConfig>
loadFromFile(const std::filesystem::path& path); 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<Api::AppConfig>
loadFromJson(std::string_view json);
// Save configuration to JSON file // Save configuration to JSON file
[[nodiscard]] static Api::Result<void> [[nodiscard]] static Api::Result<void>
saveToFile(const std::filesystem::path& path, saveToFile(const std::filesystem::path& path,
@@ -34,7 +41,8 @@ namespace Echoion::Core
[[nodiscard]] static Api::AppConfig createDefaultConfig(); [[nodiscard]] static Api::AppConfig createDefaultConfig();
// Clamp/normalize values that carry hard limits after loading // 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); static void normalize(Api::AppConfig& config);
}; };
+6 -2
View File
@@ -136,6 +136,8 @@ namespace Echoion::Core
void setAudioDataCallback( void setAudioDataCallback(
const MusicManager::AudioDataCallback& callback); const MusicManager::AudioDataCallback& callback);
Api::Result<void> reloadConfig() override; Api::Result<void> reloadConfig() override;
[[nodiscard]] Api::Result<std::string>
managePluginsJson(const std::string& requestJson) override;
// Internal implementations using full types // Internal implementations using full types
Api::Result<void> playTrack(const Api::TrackInfo& track); Api::Result<void> playTrack(const Api::TrackInfo& track);
@@ -168,6 +170,7 @@ namespace Echoion::Core
void updateWhisperList(); void updateWhisperList();
void setupRpcHandlers(); void setupRpcHandlers();
void setupEventBusSubscriptions() noexcept; void setupEventBusSubscriptions() noexcept;
void applyUrlShorteningConfig();
// Fetch an online client's avatar bytes (TS local cache, then the // Fetch an online client's avatar bytes (TS local cache, then the
// myTeamSpeak URL, then a legacy file-transfer download) and // myTeamSpeak URL, then a legacy file-transfer download) and
@@ -256,8 +259,9 @@ namespace Echoion::Core
std::shared_ptr<RpcServer> rpcServer_; std::shared_ptr<RpcServer> rpcServer_;
#ifdef ECHOION_WITH_WEB #ifdef ECHOION_WITH_WEB
// Browser web interface: serves the static dashboard and same-origin // Browser web interface: serves the static dashboard and
// RPC bridge. Bot control still terminates at the RPC server. // same-origin RPC bridge. Bot control still terminates at the RPC
// server.
std::shared_ptr<Web::HttpServer> webServer_; std::shared_ptr<Web::HttpServer> webServer_;
#endif #endif
+83 -34
View File
@@ -1,14 +1,20 @@
#pragma once #pragma once
#include <ExtensionPlugin.hpp> #include <ExtensionPlugin.hpp>
#include <NetworkTypes.hpp>
#include <Void/Plugin/Manager.hpp> #include <Void/Plugin/Manager.hpp>
#include <Void/Service/PluginService.hpp>
#include <Void/Service/Registry.hpp>
#include <Void/ShortUrl/ShortUrl.hpp>
#include <filesystem> #include <filesystem>
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <unordered_map>
#include <vector> #include <vector>
namespace Echoion::Core namespace Echoion::Core
@@ -19,41 +25,84 @@ namespace Echoion::Core
class PluginHost final : public std::enable_shared_from_this<PluginHost> class PluginHost final : public std::enable_shared_from_this<PluginHost>
{ {
public: public:
PluginHost(CommandManager& commands, std::shared_ptr<MusicManager> music,
std::function<bool(uint64_t)> isAdmin,
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink = {});
~PluginHost();
void loadDirectory(const std::filesystem::path& directory); struct Configuration {
void setChangeCallback(std::function<void()> callback); std::filesystem::path configDirectory;
void dispatch(const Api::PluginEvent& event) const; std::filesystem::path stateDirectory;
[[nodiscard]] Api::Result<std::string> call( std::string publicUrl;
std::string_view plugin, std::string_view method, std::optional<Void::Net::ProxyConfig> proxy;
std::string params, uint64_t clientId) const; std::string shortenerProvider = "url-shortener-internal";
[[nodiscard]] std::vector<Api::ExtensionWebAsset> webAssets() const; };
[[nodiscard]] std::vector<std::string> names() const;
struct State {
std::string name;
std::string json;
std::uint32_t version{};
};
[[nodiscard]] std::vector<State> snapshotStates() const;
void restoreStates(const std::vector<State>& states);
private: PluginHost(CommandManager& commands,
void publish(std::string_view name); std::shared_ptr<MusicManager>
void unpublish(std::string_view name); music,
void notifyChanged() const; std::function<bool(uint64_t)>
isAdmin,
std::function<void(std::shared_ptr<ITrackSource>)>
mediaSink,
Configuration configuration);
~PluginHost();
CommandManager& commands_; void loadDirectory(const std::filesystem::path& directory);
std::shared_ptr<MusicManager> music_; void loadManagedDirectory(const std::filesystem::path& directory);
std::function<bool(uint64_t)> isAdmin_; [[nodiscard]] Api::Result<std::string>
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink_; manage(const std::string& requestJson);
Void::Plugin::PluginManager plugins_; void setChangeCallback(std::function<void()> callback);
Void::Plugin::ReloadCallbackId reloadCallback_{}; void dispatch(const Api::PluginEvent& event) const;
mutable std::mutex mutex_; [[nodiscard]] Api::Result<std::string>
std::vector<std::shared_ptr<class PluginTrackSource>> sources_; call(std::string_view plugin, std::string_view method,
std::function<void()> changeCallback_; std::string params, uint64_t clientId) const;
[[nodiscard]] std::vector<Api::ExtensionWebAsset> webAssets() const;
[[nodiscard]] std::vector<std::string> names() const;
[[nodiscard]] bool reconfigure(Configuration configuration);
[[nodiscard]] std::shared_ptr<Void::ShortUrl::IShortener>
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<State> snapshotStates() const;
void restoreStates(const std::vector<State>& 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<MusicManager> music_;
std::function<bool(uint64_t)> isAdmin_;
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink_;
Void::Plugin::PluginManager plugins_;
Void::Service::ServiceRegistry shortenerRegistry_;
Void::Service::ServiceRegistry internalShortenerRegistry_;
std::unique_ptr<
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
shortenerBinding_;
std::unique_ptr<
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
internalShortenerBinding_;
Void::Plugin::ReloadCallbackId reloadCallback_{};
mutable std::mutex reconfigureMutex_;
mutable std::mutex mutex_;
Configuration configuration_;
std::vector<std::shared_ptr<class PluginTrackSource>> sources_;
std::function<void()> changeCallback_;
struct ManagedPlugin {
std::string version;
std::filesystem::path path;
};
std::filesystem::path managedDirectory_;
std::unordered_map<std::string, ManagedPlugin> managed_;
std::unordered_map<std::string, std::filesystem::path> loadedPaths_;
}; };
} } // namespace Echoion::Core
+1 -1
View File
@@ -97,7 +97,7 @@ namespace Echoion::Core::Dto
int source = 0; int source = 0;
std::optional<std::string> thumbnailUrl; std::optional<std::string> thumbnailUrl;
std::optional<std::string> url; // originalUrl (play-by-url) std::optional<std::string> 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). // it for "open original link" (falls back to url).
std::optional<std::string> shortenedUrl; std::optional<std::string> shortenedUrl;
}; };
+23 -36
View File
@@ -1,58 +1,45 @@
#pragma once #pragma once
#include "NetworkClient.hpp" #include <TrackTypes.hpp>
#include <NetworkTypes.hpp>
#include <Types.hpp> #include <Types.hpp>
#include <Void/ShortUrl/ShortUrl.hpp>
#include <chrono> #include <chrono>
#include <functional>
#include <memory>
#include <mutex> #include <mutex>
#include <optional>
#include <string> #include <string>
#include <unordered_map> #include <string_view>
#include <unordered_set>
#include <vector>
namespace Echoion::Core namespace Echoion::Core
{ {
// Thin Core adapter around the universal Void ShortUrl service. It owns no
// URL shortener service for faumaray.ru // 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 class UrlShortener
{ {
public: public:
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient); using ProviderGetter = std::function<
~UrlShortener(); std::shared_ptr<Void::ShortUrl::IShortener>()>;
void setProvider(ProviderGetter provider);
void setSources(const std::vector<std::string>& sources);
// Shorten a YouTube URL via faumaray.ru
// Returns shortened URL in format: https://faumaray.ru/xxxxx
[[nodiscard]] Api::Result<std::string> [[nodiscard]] Api::Result<std::string>
shortenYouTubeUrl(std::string_view videoId); shortenUrl(std::string_view originalUrl,
Api::TrackSource source) const;
// Shorten any URL via faumaray.ru
[[nodiscard]] Api::Result<std::string>
shortenUrl(std::string_view originalUrl);
// Get cached shortened URL if available
[[nodiscard]] std::optional<std::string>
getCachedUrl(std::string_view originalUrl) const;
// Clear the URL cache
void clearCache();
// Set cache TTL (default: 24 hours)
void setCacheTtl(std::chrono::hours ttl);
private: private:
struct CacheEntry { [[nodiscard]] bool sourceAllowed(Api::TrackSource source) const;
std::string shortenedUrl;
std::chrono::system_clock::time_point timestamp;
};
std::shared_ptr<NetworkClient> networkClient_; mutable std::mutex mutex_;
mutable std::mutex cacheMutex_; ProviderGetter provider_;
std::unordered_map<std::string, CacheEntry> cache_; std::unordered_set<Api::TrackSource> sources_ = {
std::chrono::hours cacheTtl_{24}; Api::TrackSource::YouTube};
// Clean expired entries from cache
void cleanExpiredCache();
}; };
} // namespace Echoion::Core } // namespace Echoion::Core
+10 -5
View File
@@ -102,8 +102,7 @@ namespace Echoion::Core
nullptr, nullptr,
std::function<void()> onComplete = nullptr); std::function<void()> onComplete = nullptr);
// Extract video ID from various YouTube URL formats (handles // Extract a video ID from known YouTube URL formats or a bare ID.
// redirects for short URLs)
[[nodiscard]] std::optional<std::string> [[nodiscard]] std::optional<std::string>
extractVideoId(std::string_view url); extractVideoId(std::string_view url);
[[nodiscard]] static std::optional<std::string> [[nodiscard]] static std::optional<std::string>
@@ -153,6 +152,14 @@ namespace Echoion::Core
// Enable/disable URL shortening for track links // Enable/disable URL shortening for track links
void setUrlShorteningEnabled(bool enabled); void setUrlShorteningEnabled(bool enabled);
void setUrlShortenerProvider(UrlShortener::ProviderGetter provider);
void setUrlShorteningSources(
const std::vector<std::string>& 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<Api::TrackInfo>& tracks);
void populateShortenedUrl(Api::TrackInfo& track);
// Gate yt-dlp's periodic background self-update // Gate yt-dlp's periodic background self-update
// (features.enableAutoUpdateCheck). Set before initialize(). // (features.enableAutoUpdateCheck). Set before initialize().
@@ -208,9 +215,7 @@ namespace Echoion::Core
mutable std::mutex configMutex_; mutable std::mutex configMutex_;
size_t maxConcurrentResolutions_ = 4; size_t maxConcurrentResolutions_ = 4;
bool urlShorteningEnabled_ = true; bool urlShorteningEnabled_ = true;
std::chrono::milliseconds urlShorteningTimeout_{3000};
// Populate shortened URLs for tracks
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
void populateShortenedUrl(Api::TrackInfo& track);
}; };
} // namespace Echoion::Core } // namespace Echoion::Core
+1 -1
View File
@@ -94,7 +94,7 @@ namespace Echoion::Core
return escapeMarkdown(text); 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 // available, otherwise the original source URL (e.g. the YouTube or
// Yandex Music page). Used so every list — search, queue, history, // Yandex Music page). Used so every list — search, queue, history,
// favorites, stats — links to the real track, never the CDN/stream URL. // favorites, stats — links to the real track, never the CDN/stream URL.
+97 -15
View File
@@ -1,13 +1,17 @@
#include <Void/Log/Log.hpp>
#include "Types.hpp" #include "Types.hpp"
#include "echoion/core/ConfigLoader.hpp" #include "echoion/core/ConfigLoader.hpp"
#include <AudioTypes.hpp> #include <AudioTypes.hpp>
#include <Void/Data/Json.hpp> #include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp> #include <Void/Data/Reflect.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <array>
#include <format> #include <format>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <ranges>
#include <string> #include <string>
#include <string_view>
namespace Echoion::Core namespace Echoion::Core
{ {
@@ -23,29 +27,97 @@ namespace Echoion::Core
if (config.bot.language != "en" && config.bot.language != "ru") { if (config.bot.language != "en" && config.bot.language != "ru") {
config.bot.language = "en"; 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<std::string_view, 6> 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<Api::AppConfig> Api::Result<Api::AppConfig>
ConfigLoader::loadFromFile(const std::filesystem::path& path) ConfigLoader::loadFromFile(const std::filesystem::path& path)
{ {
if (!std::filesystem::exists(path)) { if (!std::filesystem::exists(path)) {
return Api::fail(Api::ErrorCode::NotFound, return Api::fail(
std::format("Configuration file not found: {}", Api::ErrorCode::NotFound,
path.string())); std::format("Configuration file not found: {}", path.string()));
} }
std::ifstream file(path); std::ifstream file(path);
if (!file.is_open()) { if (!file.is_open()) {
return Api::fail(Api::ErrorCode::PermissionDenied, return Api::fail(
std::format("Failed to open configuration file: {}", Api::ErrorCode::PermissionDenied,
path.string())); std::format("Failed to open configuration file: {}",
path.string()));
} }
std::string content((std::istreambuf_iterator<char>(file)), std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>()); std::istreambuf_iterator<char>());
file.close(); 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<Api::AppConfig>
ConfigLoader::loadFromJson(std::string_view json)
{
auto parsed = Void::Json::parse(json);
if (!parsed) { if (!parsed) {
return Api::fail( return Api::fail(
Api::ErrorCode::ParseError, Api::ErrorCode::ParseError,
@@ -66,11 +138,15 @@ namespace Echoion::Core
} }
Api::AppConfig config = std::move(*result); 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); normalize(config);
std::cout << std::format("[INFO] Configuration loaded from {}",
path.string())
<< '\n';
return config; return config;
} }
@@ -82,15 +158,17 @@ namespace Echoion::Core
Void::Json::to_json(config), {.pretty = true}); Void::Json::to_json(config), {.pretty = true});
std::ofstream file(path); std::ofstream file(path);
if (!file.is_open()) { if (!file.is_open()) {
return Api::fail(Api::ErrorCode::PermissionDenied, return Api::fail(
std::format("Failed to write configuration file: {}", Api::ErrorCode::PermissionDenied,
path.string())); std::format("Failed to write configuration file: {}",
path.string()));
} }
file << json; file << json;
file.close(); file.close();
Void::Log::info("ConfigLoader", "{}", Void::Log::info(
"ConfigLoader", "{}",
std::format("Configuration saved to {}", path.string())); std::format("Configuration saved to {}", path.string()));
return {}; return {};
} }
@@ -130,6 +208,10 @@ namespace Echoion::Core
config.youtube.ytDlpMaxConcurrent = 4; config.youtube.ytDlpMaxConcurrent = 4;
config.youtube.ytDlpAsyncEnabled = true; config.youtube.ytDlpAsyncEnabled = true;
config.youtube.enableUrlShortening = 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 // Default network config
config.network.rpcEnabled = true; config.network.rpcEnabled = true;
+235 -120
View File
@@ -18,6 +18,7 @@
#include <Void/Log/LoggingAdapter.hpp> #include <Void/Log/LoggingAdapter.hpp>
#include <Void/Log/Sinks.hpp> #include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp> #include <Void/Log/SplitFileLogger.hpp>
#include <Void/Text/Base64.hpp>
#include <algorithm> #include <algorithm>
#include <cstdlib> #include <cstdlib>
#include <ctime> #include <ctime>
@@ -43,87 +44,28 @@ namespace Echoion::Core
return configPath.parent_path(); return configPath.parent_path();
} }
// Decode cached avatar bytes before serving them over HTTP. Returns PluginHost::Configuration
// empty on malformed input. pluginHostConfiguration(const Api::AppConfig& config,
#ifdef ECHOION_WITH_WEB const std::filesystem::path& configPath,
std::string decodeBase64(const std::string& in) const std::filesystem::path& statePath)
{ {
static constexpr auto val = [](char c) -> int { std::filesystem::path pluginConfig = config.plugins.configDirectory;
if (c >= 'A' && c <= 'Z') { if (pluginConfig.empty()) {
return c - 'A'; pluginConfig = configPath.parent_path() / "plugins.d";
} } else if (pluginConfig.is_relative()) {
if (c >= 'a' && c <= 'z') { pluginConfig = configPath.parent_path() / pluginConfig;
return c - 'a' + 26; }
} std::error_code error;
if (c >= '0' && c <= '9') { std::filesystem::create_directories(pluginConfig, error);
return c - '0' + 52; return {
} .configDirectory = std::move(pluginConfig),
if (c == '+') { .stateDirectory = statePath,
return 62; .publicUrl = config.web.publicUrl,
} .proxy = config.network.proxy,
if (c == '/') { .shortenerProvider = config.urlShortening.enabled
return 63; ? config.urlShortening.provider
} : std::string{},
return -1;
}; };
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<char>((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<unsigned char>(in[i]) << 16) |
(static_cast<unsigned char>(in[i + 1]) << 8) |
static_cast<unsigned char>(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<unsigned char>(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<unsigned char>(in[i]) << 16) |
(static_cast<unsigned char>(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 // Best content type for avatar bytes: honour a valid image/* hint
@@ -516,18 +458,57 @@ namespace Echoion::Core
extensionPlugins_ = std::make_shared<PluginHost>( extensionPlugins_ = std::make_shared<PluginHost>(
*commandManager_, musicManager_, *commandManager_, musicManager_,
[this](uint64_t clientId) { return isAdmin(clientId); }); [this](uint64_t clientId) { return isAdmin(clientId); },
std::function<void(std::shared_ptr<ITrackSource>)>{},
pluginHostConfiguration(config_, configPath_, stateDir));
if (rpcServer_) { if (rpcServer_) {
extensionPlugins_->setChangeCallback([server = rpcServer_] { extensionPlugins_->setChangeCallback([server = rpcServer_] {
server->broadcastEvent("plugins.updated", "{}"); server->broadcastEvent("plugins.updated", "{}");
}); });
} }
extensionPlugins_->loadDirectory(stateDir / "plugins"); extensionPlugins_->loadDirectory(stateDir / "plugins");
extensionPlugins_->loadManagedDirectory(stateDir / "plugins" /
".managed");
applyUrlShorteningConfig();
#ifdef ECHOION_WITH_WEB #ifdef ECHOION_WITH_WEB
// Browser web interface (independent of the RPC transport above). // Browser web interface (independent of the RPC transport above).
if (config_.web.enabled) { if (config_.web.enabled) {
webServer_ = std::make_shared<Web::HttpServer>(); webServer_ = std::make_shared<Web::HttpServer>();
webServer_->setShortLinkResolver(
[host = std::weak_ptr<PluginHost>{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] { webServer_->setDashboardProvider([this] {
using Void::Json::Value; using Void::Json::Value;
auto dashboard = directoryService_->publicJson(); auto dashboard = directoryService_->publicJson();
@@ -602,7 +583,9 @@ namespace Echoion::Core
return std::nullopt; return std::nullopt;
} }
if (!(*stored)->dataBase64.empty()) { if (!(*stored)->dataBase64.empty()) {
auto bytes = decodeBase64((*stored)->dataBase64); auto bytes = Void::Encoding::Base64::decode(
(*stored)->dataBase64)
.value_or(std::string{});
if (!bytes.empty()) { if (!bytes.empty()) {
return Web::HttpServer::AvatarImage{ return Web::HttpServer::AvatarImage{
.contentType = (*stored)->mime, .contentType = (*stored)->mime,
@@ -622,7 +605,9 @@ namespace Echoion::Core
if (database_) { if (database_) {
[[maybe_unused]] auto put = [[maybe_unused]] auto put =
database_->putCachedAvatar( database_->putCachedAvatar(
u, type, encodeBase64(resp->body)); u, type,
Void::Encoding::Base64::encode(
resp->body));
} }
return Web::HttpServer::AvatarImage{ return Web::HttpServer::AvatarImage{
.contentType = std::move(type), .contentType = std::move(type),
@@ -659,6 +644,7 @@ namespace Echoion::Core
webCfg.rpcUrl = config_.web.rpcUrl; webCfg.rpcUrl = config_.web.rpcUrl;
webCfg.watchUrl = config_.web.watchUrl; webCfg.watchUrl = config_.web.watchUrl;
webCfg.nowPlayingVideo = config_.web.nowPlayingVideo; webCfg.nowPlayingVideo = config_.web.nowPlayingVideo;
webCfg.trustedProxyCidrs = config_.web.trustedProxyCidrs;
webCfg.rpcPort = webCfg.rpcPort =
config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765; config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765;
if (!webServer_->start(webCfg)) { if (!webServer_->start(webCfg)) {
@@ -759,8 +745,6 @@ namespace Echoion::Core
musicManager_->shutdown(); musicManager_->shutdown();
} }
extensionPlugins_.reset();
#ifdef ECHOION_WITH_WEB #ifdef ECHOION_WITH_WEB
// Providers and the RPC bridge capture Core services, so drain all HTTP // Providers and the RPC bridge capture Core services, so drain all HTTP
// workers before destroying any of those dependencies. // workers before destroying any of those dependencies.
@@ -770,6 +754,8 @@ namespace Echoion::Core
} }
#endif #endif
extensionPlugins_.reset();
if (networkClient_) { if (networkClient_) {
networkClient_->shutdown(); networkClient_->shutdown();
} }
@@ -1164,31 +1150,88 @@ namespace Echoion::Core
Api::Result<void> Core::updateConfig(const Api::AppConfig& config) Api::Result<void> Core::updateConfig(const Api::AppConfig& config)
{ {
// Update local config copy auto candidate = config;
config_ = 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_) { if (commandManager_) {
commandManager_->setPrefix(config.bot.commandPrefix); commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config); commandManager_->setServerConfig(config_);
} }
// Re-apply network settings to every outbound client (NetworkClient, // Re-apply network settings to every outbound client (NetworkClient,
// yt-dlp, ffmpeg), not just the HTTP client. // yt-dlp, ffmpeg), not just the HTTP client.
if (musicManager_) { if (musicManager_) {
musicManager_->applyBotConfig(config.bot); musicManager_->applyBotConfig(config_.bot);
musicManager_->applyFeaturesConfig(config.features); musicManager_->applyFeaturesConfig(config_.features);
musicManager_->applyNetworkConfig(config.network); musicManager_->applyNetworkConfig(config_.network);
musicManager_->applyYouTubeConfig(config.youtube); musicManager_->applyYouTubeConfig(config_.youtube);
musicManager_->applySourcesConfig(config.sources); musicManager_->applySourcesConfig(config_.sources);
} else if (networkClient_) { } else if (networkClient_) {
networkClient_->setProxy(config.network.proxy); networkClient_->setProxy(config_.network.proxy);
} }
applyUrlShorteningConfig();
broadcastEvent( broadcastEvent(
Api::PluginEvent{.type = Api::PluginEventType::ConfigurationChanged, Api::PluginEvent{.type = Api::PluginEventType::ConfigurationChanged,
.clientId = 0, .clientId = 0,
.timestamp = std::chrono::system_clock::now()}); .timestamp = std::chrono::system_clock::now()});
eventBus_.publish(Api::Events::ConfigReloaded{.newConfig = config.bot}); eventBus_.publish(
Api::Events::ConfigReloaded{.newConfig = config_.bot});
return {}; return {};
} }
@@ -1197,28 +1240,11 @@ namespace Echoion::Core
Api::Result<void> Core::updateConfigJson(const std::string& configJson) Api::Result<void> Core::updateConfigJson(const std::string& configJson)
{ {
// Parse JSON config using Void::Json reflection auto config = ConfigLoader::loadFromJson(configJson);
auto parsed = Void::Json::parse(configJson); if (!config) {
if (!parsed) { return std::unexpected(config.error());
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Failed to parse config JSON ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message));
} }
// Deserialize the full Api::AppConfig document directly via reflection. return updateConfig(*config);
auto jsonResult = Void::Json::from_json<Api::AppConfig>(*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);
} }
Api::Result<std::string> Core::getConfigJson() const Api::Result<std::string> Core::getConfigJson() const
@@ -1228,6 +1254,19 @@ namespace Echoion::Core
{.pretty = true}); {.pretty = true});
} }
Api::Result<std::string>
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<void> Core::reloadConfig() Api::Result<void> Core::reloadConfig()
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireInitialized(); !r) {
@@ -1245,8 +1284,62 @@ namespace Echoion::Core
return std::unexpected(configResult.error()); return std::unexpected(configResult.error());
} }
// Update local config auto candidate = *configResult;
config_ = *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 // Keep the shared ConfigManager in sync so components that read through
// it (cookies, API key, etc.) see the reloaded values. // it (cookies, API key, etc.) see the reloaded values.
configManager_.updateConfig(config_, false); configManager_.updateConfig(config_, false);
@@ -1270,6 +1363,7 @@ namespace Echoion::Core
} else if (networkClient_) { } else if (networkClient_) {
networkClient_->setProxy(config_.network.proxy); networkClient_->setProxy(config_.network.proxy);
} }
applyUrlShorteningConfig();
eventBus_.publish( eventBus_.publish(
Api::Events::ConfigReloaded{.newConfig = config_.bot}); Api::Events::ConfigReloaded{.newConfig = config_.bot});
@@ -1278,6 +1372,27 @@ namespace Echoion::Core
return {}; 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<PluginHost>{extensionPlugins_}] {
if (auto pinned = host.lock()) {
return pinned->shortener();
}
return std::shared_ptr<Void::ShortUrl::IShortener>{};
});
}
Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull() Api::Result<Api::HotReloadState> Core::prepareForHotReloadFull()
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireInitialized(); !r) {
@@ -2071,8 +2186,8 @@ namespace Echoion::Core
} }
std::string type = sniffImageMime(bytes, hint); std::string type = sniffImageMime(bytes, hint);
if (database_) { if (database_) {
[[maybe_unused]] auto put = [[maybe_unused]] auto put = database_->putCachedAvatar(
database_->putCachedAvatar(uid, type, encodeBase64(bytes)); uid, type, Void::Encoding::Base64::encode(bytes));
} }
return std::pair{std::move(type), std::move(bytes)}; return std::pair{std::move(type), std::move(bytes)};
}; };
+35
View File
@@ -124,6 +124,41 @@ namespace Echoion::Core
std::move(request->params), std::move(request->params),
clientId); 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<int>(rpcMethod)),
[this, operation = std::move(operation)](
const std::string& params,
uint64_t clientId) -> Api::Result<std::string> {
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 // Authentication - expects JSON with either "nickname" (for initial
// request) or "token" (for validation). The same handler backs // request) or "token" (for validation). The same handler backs
// Authenticate, RequestLoginToken and ValidateLoginToken. // Authenticate, RequestLoginToken and ValidateLoginToken.
+12 -26
View File
@@ -2,6 +2,7 @@
#include <Void/Data/Json.hpp> #include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/Text/Url.hpp>
#include <algorithm> #include <algorithm>
#include <cctype> #include <cctype>
#include <charconv> #include <charconv>
@@ -12,25 +13,6 @@ namespace Echoion::Core
{ {
namespace 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<char>(c);
} else {
out += '%';
out += hex[c >> 4];
out += hex[c & 0x0F];
}
}
return out;
}
// Read an optional string field from a JSON object value. // Read an optional string field from a JSON object value.
std::string strField(const Void::Json::Value& obj, std::string_view key) std::string strField(const Void::Json::Value& obj, std::string_view key)
{ {
@@ -131,9 +113,11 @@ namespace Echoion::Core
std::string url = std::format( std::string url = std::format(
"https://lrclib.net/api/get?artist_name={}&track_name={}" "https://lrclib.net/api/get?artist_name={}&track_name={}"
"&duration={}", "&duration={}",
urlEncode(artist), urlEncode(title), durationSec); Void::Encoding::Url::encode(artist),
Void::Encoding::Url::encode(title), durationSec);
if (!album.empty()) { 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); if (auto resp = net_->get(url);
resp && resp->status == 200 && !resp->body.empty()) { resp && resp->status == 200 && !resp->body.empty()) {
@@ -150,9 +134,10 @@ namespace Echoion::Core
// 2) Search fallback — take the first result that carries lyrics. // 2) Search fallback — take the first result that carries lyrics.
std::string searchUrl = std::string searchUrl =
std::format("https://lrclib.net/api/search?track_name={}", std::format("https://lrclib.net/api/search?track_name={}",
urlEncode(title)); Void::Encoding::Url::encode(title));
if (!artist.empty()) { 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); if (auto resp = net_->get(searchUrl);
resp && resp->status == 200 && !resp->body.empty()) { 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); std::string_view tag(raw.data() + pos + 1, close - pos - 1);
// A timestamp starts with a digit; [ar:], [ti:] etc. don't. // A timestamp starts with a digit; [ar:], [ti:] etc. don't.
if (!tag.empty() && std::isdigit(static_cast<unsigned char>( if (!tag.empty() &&
tag.front()))) { std::isdigit(static_cast<unsigned char>(tag.front()))) {
auto colon = tag.find(':'); auto colon = tag.find(':');
if (colon != std::string_view::npos) { if (colon != std::string_view::npos) {
int minutes = 0; int minutes = 0;
double seconds = 0.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). // Parse the seconds part (may be fractional).
std::string sec(tag.substr(colon + 1)); std::string sec(tag.substr(colon + 1));
try { try {
+43 -30
View File
@@ -105,9 +105,7 @@ namespace Echoion::Core
youtubeConfig.ytDlpMaxConcurrent); youtubeConfig.ytDlpMaxConcurrent);
} }
// Configure URL shortening // URL shortening is configured by Core after extension services load.
youTubeClient_->setUrlShorteningEnabled(
youtubeConfig.enableUrlShortening);
auto ytResult = youTubeClient_->initialize(); auto ytResult = youTubeClient_->initialize();
if (!ytResult) { if (!ytResult) {
@@ -267,8 +265,6 @@ namespace Echoion::Core
youTubeClient_->setMaxConcurrentResolutions( youTubeClient_->setMaxConcurrentResolutions(
youtube.ytDlpMaxConcurrent); youtube.ytDlpMaxConcurrent);
} }
youTubeClient_->setUrlShorteningEnabled(youtube.enableUrlShortening);
const bool hasKey = youtube.youtubeApiKey.has_value() && const bool hasKey = youtube.youtubeApiKey.has_value() &&
!youtube.youtubeApiKey->empty(); !youtube.youtubeApiKey->empty();
Void::Log::info("MusicManager", "{}", Void::Log::info("MusicManager", "{}",
@@ -463,7 +459,9 @@ namespace Echoion::Core
void MusicManager::addTrackSource(std::shared_ptr<ITrackSource> source) void MusicManager::addTrackSource(std::shared_ptr<ITrackSource> source)
{ {
if (router_) router_->addSource(std::move(source)); if (router_) {
router_->addSource(std::move(source));
}
} }
void MusicManager::shutdown() void MusicManager::shutdown()
@@ -809,8 +807,8 @@ namespace Echoion::Core
// Daily counters / top-requesters stats. clientId 0 is radio/system // Daily counters / top-requesters stats. clientId 0 is radio/system
// (autoplay refill) — automatic adds don't count as user requests. // (autoplay refill) — automatic adds don't count as user requests.
if (database_ && clientId != 0) { if (database_ && clientId != 0) {
(void)database_->logQueueAddition( (void)database_->logQueueAddition(clientUid(clientId).value_or(""),
clientUid(clientId).value_or(""), nicknameFor(clientId)); nicknameFor(clientId));
} }
// Auto-start when idle with an online audience. // Auto-start when idle with an online audience.
@@ -953,6 +951,9 @@ namespace Echoion::Core
importRunning_ = false; importRunning_ = false;
return; return;
} }
if (youTubeClient_) {
youTubeClient_->populateShortenedUrls(*tracks);
}
size_t queued = 0; size_t queued = 0;
for (const auto& track : *tracks) { for (const auto& track : *tracks) {
if (queueTrack(track, clientId)) { if (queueTrack(track, clientId)) {
@@ -1057,26 +1058,33 @@ namespace Echoion::Core
// YouTube search goes through the router (Invidious/Piped/ytdlp); // YouTube search goes through the router (Invidious/Piped/ytdlp);
// Yandex is called directly (its canHandle rejects text, so the // Yandex is called directly (its canHandle rejects text, so the
// router never routes bare queries to it). // router never routes bare queries to it).
const auto applyShortening =
[this](Api::Result<Api::SearchResult> result) {
if (result && youTubeClient_) {
youTubeClient_->populateShortenedUrls(result->tracks);
}
return result;
};
const auto youtube = [&]() -> Api::Result<Api::SearchResult> { const auto youtube = [&]() -> Api::Result<Api::SearchResult> {
if (router_) { if (router_) {
return router_->search(query); return applyShortening(router_->search(query));
} }
if (youTubeClient_) { if (youTubeClient_) {
return youTubeClient_->search(query); return applyShortening(youTubeClient_->search(query));
} }
return Api::fail(Api::ErrorCode::ServiceUnavailable, return Api::fail(Api::ErrorCode::ServiceUnavailable,
"YouTube search unavailable"); "YouTube search unavailable");
}; };
const auto yandex = [&]() -> Api::Result<Api::SearchResult> { const auto yandex = [&]() -> Api::Result<Api::SearchResult> {
if (yandexSource_ && yandexSource_->isAvailable()) { if (yandexSource_ && yandexSource_->isAvailable()) {
return yandexSource_->search(query); return applyShortening(yandexSource_->search(query));
} }
return Api::fail(Api::ErrorCode::ServiceUnavailable, return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Yandex Music not configured"); "Yandex Music not configured");
}; };
const auto soundcloud = [&]() -> Api::Result<Api::SearchResult> { const auto soundcloud = [&]() -> Api::Result<Api::SearchResult> {
if (youTubeClient_) { if (youTubeClient_) {
return youTubeClient_->searchSoundCloud(query); return applyShortening(youTubeClient_->searchSoundCloud(query));
} }
return Api::fail(Api::ErrorCode::ServiceUnavailable, return Api::fail(Api::ErrorCode::ServiceUnavailable,
"SoundCloud search unavailable"); "SoundCloud search unavailable");
@@ -1167,6 +1175,9 @@ namespace Echoion::Core
auto selected = auto selected =
(*pending)[index - 1]; // Convert to 0-based (copy to modify) (*pending)[index - 1]; // Convert to 0-based (copy to modify)
selected.requestedBy = invokerName; selected.requestedBy = invokerName;
if (youTubeClient_) {
youTubeClient_->populateShortenedUrl(selected);
}
auto result = queueTrack(selected, clientId); auto result = queueTrack(selected, clientId);
if (!result) { if (!result) {
@@ -1569,9 +1580,8 @@ namespace Echoion::Core
// Queue tracks that are both unplayed-recently and within the // Queue tracks that are both unplayed-recently and within the
// radio duration cap. Stops once maxToQueue have been queued. // radio duration cap. Stops once maxToQueue have been queued.
auto queueRadio = auto queueRadio = [&](const std::vector<Api::TrackInfo>& tracks,
[&](const std::vector<Api::TrackInfo>& tracks, size_t maxToQueue) -> size_t {
size_t maxToQueue) -> size_t {
size_t queued = 0; size_t queued = 0;
for (const auto& track : tracks) { for (const auto& track : tracks) {
if (recentUrls.contains(track.originalUrl)) { if (recentUrls.contains(track.originalUrl)) {
@@ -1607,14 +1617,13 @@ namespace Echoion::Core
related = youTubeClient_->radioMix(seed, 10); related = youTubeClient_->radioMix(seed, 10);
} }
if (related && !related->empty()) { if (related && !related->empty()) {
queued = queueRadio(*related, std::numeric_limits< queued = queueRadio(*related,
size_t>::max()); std::numeric_limits<size_t>::max());
if (queued > 0) { if (queued > 0) {
Void::Log::info( Void::Log::info(
"MusicManager", "{}", "MusicManager", "{}",
std::format( std::format("Autoplay queued {} related track(s)",
"Autoplay queued {} related track(s)", queued));
queued));
} }
} }
} }
@@ -1628,10 +1637,9 @@ namespace Echoion::Core
random && !random->empty()) { random && !random->empty()) {
queued = queueRadio(*random, 1); queued = queueRadio(*random, 1);
if (queued > 0) { if (queued > 0) {
Void::Log::info( Void::Log::info("MusicManager", "{}",
"MusicManager", "{}", "Autoplay queued a random music video "
"Autoplay queued a random music video " "(no unplayed related track found)");
"(no unplayed related track found)");
} }
} }
} }
@@ -1641,9 +1649,8 @@ namespace Echoion::Core
engine_->start(); engine_->start();
} }
} else { } else {
Void::Log::debug( Void::Log::debug("MusicManager", "{}",
"MusicManager", "{}", "Autoplay found no track to queue");
"Autoplay found no track to queue");
} }
autoplayFetching_ = false; autoplayFetching_ = false;
}); });
@@ -1706,6 +1713,12 @@ namespace Echoion::Core
Api::Result<Api::TrackInfo> Api::Result<Api::TrackInfo>
MusicManager::resolveQuery(const std::string& query) MusicManager::resolveQuery(const std::string& query)
{ {
const auto finalize = [this](Api::Result<Api::TrackInfo> result) {
if (result && youTubeClient_) {
youTubeClient_->populateShortenedUrl(*result);
}
return result;
};
// Playlist URLs are still resolved through the YouTube client (the // Playlist URLs are still resolved through the YouTube client (the
// router's sources resolve single tracks). // router's sources resolve single tracks).
if (config_.allowPlaylistImports && if (config_.allowPlaylistImports &&
@@ -1717,13 +1730,13 @@ namespace Echoion::Core
std::format("Extracted playlist ID: '{}'", *playlistId)); std::format("Extracted playlist ID: '{}'", *playlistId));
auto playlist = youTubeClient_->getPlaylist(*playlistId); auto playlist = youTubeClient_->getPlaylist(*playlistId);
if (playlist && !playlist->tracks.empty()) { if (playlist && !playlist->tracks.empty()) {
return playlist->tracks[0]; return finalize(playlist->tracks[0]);
} }
} }
} }
if (router_) { if (router_) {
return router_->resolve(query); return finalize(router_->resolve(query));
} }
auto searchResult = youTubeClient_->search(query); auto searchResult = youTubeClient_->search(query);
@@ -1733,7 +1746,7 @@ namespace Echoion::Core
if (searchResult->tracks.empty()) { if (searchResult->tracks.empty()) {
return Api::fail(Api::ErrorCode::NotFound, "No results found"); return Api::fail(Api::ErrorCode::NotFound, "No results found");
} }
return searchResult->tracks[0]; return finalize(searchResult->tracks[0]);
} }
Api::Result<std::string> Api::Result<std::string>
+949 -224
View File
File diff suppressed because it is too large. Load diff
+135 -138
View File
@@ -1,158 +1,155 @@
#include <Void/Log/Log.hpp>
#include "echoion/core/UrlShortener.hpp" #include "echoion/core/UrlShortener.hpp"
#include <Void/Data/Json.hpp>
#include <format> #include <Void/Log/Log.hpp>
#include <algorithm>
#include <cctype>
#include <exception>
#include <optional>
#include <utility>
namespace Echoion::Core namespace Echoion::Core
{ {
namespace
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient))
{ {
} std::string lower(std::string value)
UrlShortener::~UrlShortener() = default;
Api::Result<std::string>
UrlShortener::shortenYouTubeUrl(std::string_view videoId)
{
std::string originalUrl =
std::format("https://www.youtube.com/watch?v={}", videoId);
return shortenUrl(originalUrl);
}
Api::Result<std::string>
UrlShortener::shortenUrl(std::string_view originalUrl)
{
// Check cache first
{ {
std::lock_guard<std::mutex> lock(cacheMutex_); std::ranges::transform(value, value.begin(), [](unsigned char ch) {
auto it = cache_.find(std::string(originalUrl)); return static_cast<char>(std::tolower(ch));
if (it != cache_.end()) { });
auto now = std::chrono::system_clock::now(); return value;
if (now - it->second.timestamp < cacheTtl_) { }
Void::Log::debug("UrlShortener", "{}", std::format("URL cache hit: {} -> {}",
originalUrl, std::optional<Api::TrackSource> sourceFromName(std::string name)
it->second.shortenedUrl)); {
return it->second.shortenedUrl; name = lower(std::move(name));
} if (name == "youtube") {
// Expired, remove from cache return Api::TrackSource::YouTube;
cache_.erase(it); }
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_) { void UrlShortener::setProvider(ProviderGetter provider)
return Api::fail(Api::ErrorCode::ServiceUnavailable, {
"Network client not available"); std::lock_guard lock(mutex_);
provider_ = std::move(provider);
}
void UrlShortener::setSources(const std::vector<std::string>& sources)
{
std::unordered_set<Api::TrackSource> 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<std::string>
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 ProviderGetter getter;
// POST /shorten with JSON body {"longUrl": "https://..."} {
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"} std::lock_guard lock(mutex_);
std::string apiUrl = "https://faumaray.ru/shorten"; getter = provider_;
// Build JSON request body - API expects "longUrl" field
std::string jsonBody =
std::format(R"({{"longUrl":"{}"}})", originalUrl);
std::vector<Void::Net::Header> 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");
} }
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 { try {
// Parse response - expecting {"shortUrl": auto provider = getter ? getter() : nullptr;
// "https://faumaray.ru/xxxxx"} if (!provider || provider->service_version() !=
auto parsed = Void::Json::parse(response->body); Void::ShortUrl::kServiceVersion) {
if (!parsed) { return Api::fail(Api::ErrorCode::ServiceUnavailable,
Void::Log::warn("UrlShortener", "{}", "Failed to parse URL shortening response"); "URL shortener provider is unavailable");
return Api::fail(Api::ErrorCode::ParseError, }
"Failed to parse shortening response"); 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; auto result =
const Void::Json::Value* shortUrl = parsed->find("shortUrl"); provider->shorten({.target_url = std::string(originalUrl),
if (shortUrl && shortUrl->is_string()) { .custom_key = {},
shortenedUrl = shortUrl->as_string(); .expires_at_unix_seconds = 0});
} else { if (!result.ok() || result.short_url.empty()) {
Void::Log::warn("UrlShortener", "{}", "No shortUrl field in response"); return Api::fail(apiError(result.error.code),
return Api::fail(Api::ErrorCode::ParseError, result.error.message.empty()
"No shortUrl in response"); ? "URL shortening failed"
} : result.error.message);
// Cache the result
{
std::lock_guard<std::mutex> 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<std::string>
UrlShortener::getCachedUrl(std::string_view originalUrl) const
{
std::lock_guard<std::mutex> 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<std::mutex> lock(cacheMutex_);
cache_.clear();
}
void UrlShortener::setCacheTtl(std::chrono::hours ttl) { cacheTtl_ = ttl; }
void UrlShortener::cleanExpiredCache()
{
std::lock_guard<std::mutex> 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;
} }
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 } // namespace Echoion::Core
+95 -90
View File
@@ -31,7 +31,7 @@ namespace Echoion::Core
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient) YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)), : networkClient_(std::move(networkClient)),
ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)), ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)),
urlShortener_(std::make_unique<UrlShortener>(networkClient_)) urlShortener_(std::make_unique<UrlShortener>())
{ {
} }
@@ -492,9 +492,8 @@ namespace Echoion::Core
return results; return results;
} }
Api::Result<Api::SearchResult> Api::Result<Api::SearchResult> YouTubeClient::search(
YouTubeClient::search(std::string_view query, std::string_view query, std::optional<std::string> pageToken)
std::optional<std::string> pageToken)
{ {
if (!initialized_) { if (!initialized_) {
@@ -839,8 +838,7 @@ namespace Echoion::Core
} }
Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlp( Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlp(
std::string_view query, std::string_view query, const std::optional<std::string>& /*pageToken*/)
const std::optional<std::string>& /*pageToken*/)
{ {
return searchWithYtDlpProvider(query, "ytsearch5", return searchWithYtDlpProvider(query, "ytsearch5",
Api::TrackSource::YouTube); Api::TrackSource::YouTube);
@@ -853,9 +851,10 @@ namespace Echoion::Core
Api::TrackSource::SoundCloud); Api::TrackSource::SoundCloud);
} }
Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlpProvider( Api::Result<Api::SearchResult>
std::string_view query, std::string_view searchPrefix, YouTubeClient::searchWithYtDlpProvider(std::string_view query,
Api::TrackSource source) std::string_view searchPrefix,
Api::TrackSource source)
{ {
if (!ytDlpManager_->isAvailable()) { if (!ytDlpManager_->isAvailable()) {
@@ -1061,10 +1060,9 @@ namespace Echoion::Core
// per call; combined with the shuffled results this gives the radio a // per call; combined with the shuffled results this gives the radio a
// varied backstop when no related/unplayed track is available. // varied backstop when no related/unplayed track is available.
static const std::array<std::string_view, 10> kQueries = { static const std::array<std::string_view, 10> kQueries = {
"popular music", "top hits", "rock music", "popular music", "top hits", "rock music", "electronic music",
"electronic music", "hip hop music", "lofi hip hop", "hip hop music", "lofi hip hop", "pop music", "jazz music",
"pop music", "jazz music", "indie music", "indie music", "dance music"};
"dance music"};
static thread_local std::mt19937 rng(std::random_device{}()); static thread_local std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<size_t> pick(0, kQueries.size() - 1); std::uniform_int_distribution<size_t> pick(0, kQueries.size() - 1);
@@ -1610,60 +1608,21 @@ namespace Echoion::Core
{ {
std::string url_str(url); 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<Void::Net::Header> 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 // More comprehensive regex patterns for YouTube URLs
static const std::regex watch_pattern( 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); std::regex::icase);
static const std::regex short_pattern( 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); std::regex::icase);
static const std::regex embed_pattern( 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); std::regex::icase);
static const std::regex shorts_pattern( 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); std::regex::icase);
// Also match just the video ID (11 characters) // Also match just the video ID (11 characters)
@@ -1697,9 +1656,10 @@ namespace Echoion::Core
bool YouTubeClient::isYouTubeUrl(std::string_view url) bool YouTubeClient::isYouTubeUrl(std::string_view url)
{ {
return url.find("faumaray.ru") != std::string::npos || static const std::regex youtubeUrlPattern(
url.find("youtube.com") != std::string::npos || R"(^(?:https?://)?(?:www\.)?(?:youtube\.com(?:/|$)|youtu\.be(?:/|$)))",
url.find("youtu.be") != std::string::npos; std::regex::icase);
return std::regex_search(url.begin(), url.end(), youtubeUrlPattern);
} }
void YouTubeClient::setUrlShorteningEnabled(bool enabled) void YouTubeClient::setUrlShorteningEnabled(bool enabled)
@@ -1711,6 +1671,25 @@ namespace Echoion::Core
std::format("URL shortening {}", enabled ? "enabled" : "disabled")); std::format("URL shortening {}", enabled ? "enabled" : "disabled"));
} }
void YouTubeClient::setUrlShortenerProvider(
UrlShortener::ProviderGetter provider)
{
urlShortener_->setProvider(std::move(provider));
}
void YouTubeClient::setUrlShorteningSources(
const std::vector<std::string>& sources)
{
urlShortener_->setSources(sources);
}
void YouTubeClient::setUrlShorteningTimeout(
std::chrono::milliseconds timeout)
{
std::lock_guard lock(configMutex_);
urlShorteningTimeout_ = timeout;
}
void YouTubeClient::setAutoUpdateEnabled(bool enabled) void YouTubeClient::setAutoUpdateEnabled(bool enabled)
{ {
if (ytDlpManager_) { if (ytDlpManager_) {
@@ -1727,35 +1706,46 @@ namespace Echoion::Core
void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track) void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track)
{ {
bool enabled; bool enabled;
std::chrono::milliseconds timeout;
{ {
std::lock_guard<std::mutex> lock(configMutex_); std::lock_guard<std::mutex> lock(configMutex_);
enabled = urlShorteningEnabled_; enabled = urlShorteningEnabled_;
timeout = urlShorteningTimeout_;
} }
if (!enabled || !urlShortener_ || track.id.empty()) { if (!enabled || !urlShortener_ ||
(track.shortenedUrl && !track.shortenedUrl->empty())) {
return; 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 // 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 // it times out we keep the track unshortened. The future is only read
// on the ready path (which establishes happens-before), and on timeout // on the ready path (which establishes happens-before), and on timeout
// the task keeps running on the pool with its result discarded — no // the task keeps running on the pool with its result discarded — no
// detached thread and no busy-wait poll. // detached thread and no busy-wait poll.
auto trackId = track.id; auto future = pool_.submit([this, originalUrl = std::move(originalUrl),
auto future = source]() -> std::optional<std::string> {
pool_.submit([this, trackId]() -> std::optional<std::string> { try {
try { auto result = urlShortener_->shortenUrl(originalUrl, source);
auto result = urlShortener_->shortenYouTubeUrl(trackId); if (result) {
if (result) { return *result;
return *result;
}
} catch (...) {
// Ignore exceptions - this is best-effort
} }
return std::nullopt; } catch (...) {
}); // Ignore exceptions - this is best-effort
}
return std::nullopt;
});
if (future.wait_for(std::chrono::seconds(3)) == if (future.wait_for(timeout) == std::future_status::ready) {
std::future_status::ready) {
if (auto shortened = future.get()) { if (auto shortened = future.get()) {
track.shortenedUrl = *shortened; track.shortenedUrl = *shortened;
Void::Log::debug("YouTubeClient", "{}", Void::Log::debug("YouTubeClient", "{}",
@@ -1765,7 +1755,8 @@ namespace Echoion::Core
} }
} else { } else {
Void::Log::warn("YouTubeClient", "{}", 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<Api::TrackInfo>& tracks) std::vector<Api::TrackInfo>& tracks)
{ {
bool enabled; bool enabled;
std::chrono::milliseconds timeout;
{ {
std::lock_guard<std::mutex> lock(configMutex_); std::lock_guard<std::mutex> lock(configMutex_);
enabled = urlShorteningEnabled_; enabled = urlShorteningEnabled_;
timeout = urlShorteningTimeout_;
} }
if (!enabled || !urlShortener_ || tracks.empty()) { if (!enabled || !urlShortener_ || tracks.empty()) {
return; return;
@@ -1798,30 +1791,42 @@ namespace Echoion::Core
slots.reserve(tracks.size()); slots.reserve(tracks.size());
for (auto& track : tracks) { for (auto& track : tracks) {
if (track.id.empty()) { if (track.shortenedUrl && !track.shortenedUrl->empty()) {
continue; 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<std::optional<std::string>>(); auto out = std::make_shared<std::optional<std::string>>();
auto future = pool_.submit([this, trackId, out]() { auto future = pool_.submit(
try { [this, originalUrl = std::move(originalUrl), source, out]() {
auto result = urlShortener_->shortenYouTubeUrl(trackId); try {
if (result) { auto result =
*out = *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)}); 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(); auto start = std::chrono::steady_clock::now();
for (auto& slot : slots) { for (auto& slot : slots) {
auto remaining = std::chrono::seconds(5) - auto remaining =
(std::chrono::steady_clock::now() - start); timeout - (std::chrono::steady_clock::now() - start);
if (remaining <= std::chrono::seconds::zero()) { if (remaining <= std::chrono::milliseconds::zero()) {
break; break;
} }
slot.future.wait_for(remaining); slot.future.wait_for(remaining);
+3 -23
View File
@@ -2,6 +2,7 @@
#include <Void/Data/Json.hpp> #include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/Text/Url.hpp>
#include <format> #include <format>
#include <openssl/evp.h> #include <openssl/evp.h>
#include <regex> #include <regex>
@@ -62,27 +63,6 @@ namespace Echoion::Core
return std::regex_search(url, playlist); 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<char>(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) std::string str(const Void::Json::Value& v, const char* key)
{ {
const auto* f = v.find(key); const auto* f = v.find(key);
@@ -198,8 +178,8 @@ namespace Echoion::Core
"Yandex Music not configured"); "Yandex Music not configured");
} }
auto body = auto body = apiGet("/search?type=track&page=0&text=" +
apiGet("/search?type=track&page=0&text=" + percentEncode(query)); Void::Encoding::Url::encode(query));
if (!body) { if (!body) {
return std::unexpected(body.error()); return std::unexpected(body.error());
} }
+111
View File
@@ -0,0 +1,111 @@
#include "echoion/core/ConfigLoader.hpp"
#include <iostream>
#include <string>
#include <string_view>
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;
}
+154
View File
@@ -0,0 +1,154 @@
#include "echoion/core/UrlShortener.hpp"
#include "echoion/core/YouTubeClient.hpp"
#include <array>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
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<FakeShortener>();
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;
}