From 5c036d91fb4666ba072137e839c448b03892270d Mon Sep 17 00:00:00 2001 From: faumaray Date: Sat, 11 Jul 2026 00:45:17 +0300 Subject: [PATCH] making WEB Signed-off-by: faumaray --- CMakeLists.txt | 2 +- include/echoion/core/AudioDecoder.hpp | 23 + include/echoion/core/CommandManager.hpp | 45 +- include/echoion/core/Core.hpp | 71 +- include/echoion/core/LyricsService.hpp | 76 ++ include/echoion/core/MusicManager.hpp | 62 +- include/echoion/core/RpcDtos.hpp | 145 ++- include/echoion/core/RpcServer.hpp | 12 + include/echoion/core/Socks5HttpBridge.hpp | 90 ++ include/echoion/core/SubscriptionService.hpp | 12 +- include/echoion/core/YouTubeClient.hpp | 20 + include/echoion/core/YtDlpManager.hpp | 15 +- .../echoion/core/commands/AnnounceCommand.hpp | 9 +- .../echoion/core/commands/AutoplayCommand.hpp | 19 +- .../echoion/core/commands/ClearCommand.hpp | 22 +- include/echoion/core/commands/Command.hpp | 78 +- include/echoion/core/commands/Commands.hpp | 16 +- .../echoion/core/commands/FavoriteCommand.hpp | 44 +- .../echoion/core/commands/HistoryCommand.hpp | 6 +- .../echoion/core/commands/LanguageCommand.hpp | 111 +++ .../echoion/core/commands/LyricsCommand.hpp | 84 ++ include/echoion/core/commands/MoveCommand.hpp | 39 +- .../core/commands/NowPlayingCommand.hpp | 48 +- .../echoion/core/commands/PauseCommand.hpp | 24 +- include/echoion/core/commands/PlayCommand.hpp | 74 +- .../echoion/core/commands/PlaylistCommand.hpp | 40 +- .../echoion/core/commands/QueueCommand.hpp | 93 +- .../echoion/core/commands/ReloadCommand.hpp | 10 +- .../core/commands/ReloadConfigCommand.hpp | 16 +- .../echoion/core/commands/RemoveCommand.hpp | 35 +- .../echoion/core/commands/RepeatCommand.hpp | 21 +- .../echoion/core/commands/ResumeCommand.hpp | 22 +- .../echoion/core/commands/SearchCommand.hpp | 38 +- include/echoion/core/commands/SeekCommand.hpp | 41 +- .../echoion/core/commands/SelectCommand.hpp | 41 +- .../echoion/core/commands/ShuffleCommand.hpp | 22 +- include/echoion/core/commands/SkipCommand.hpp | 30 +- .../core/commands/SoundCloudPlayCommand.hpp | 35 + .../core/commands/SoundCloudSearchCommand.hpp | 32 + .../echoion/core/commands/StatsCommand.hpp | 8 +- include/echoion/core/commands/StopCommand.hpp | 20 +- .../core/commands/SubscribeCommand.hpp | 23 +- .../core/commands/SubscribersCommand.hpp | 55 +- .../core/commands/UnsubscribeAllCommand.hpp | 22 +- .../core/commands/UnsubscribeCommand.hpp | 24 +- .../core/commands/UnsubscribeIdCommand.hpp | 27 +- .../echoion/core/commands/VolumeCommand.hpp | 33 +- include/echoion/core/i18n/Localization.hpp | 31 + .../echoion/core/playback/PlaybackEngine.hpp | 51 +- include/echoion/core/state/StateVersions.hpp | 1 + include/echoion/core/util/Paginate.hpp | 18 + src/AudioDecoder.cpp | 215 +++-- src/CommandManager.cpp | 343 ++++++- src/ConfigLoader.cpp | 6 + src/ConfigManager.cpp | 5 +- src/Core.cpp | 889 ++++++++++++++---- src/CoreEventRelay.cpp | 47 +- src/CoreRpcHandlers.cpp | 686 ++++++++++++-- src/Database.cpp | 413 +++++++- src/LyricsService.cpp | 239 +++++ src/MusicManager.cpp | 764 +++++++++++---- src/RpcServer.cpp | 252 +++-- src/Socks5HttpBridge.cpp | 403 ++++++++ src/SubscriptionManager.cpp | 9 +- src/SubscriptionService.cpp | 20 +- src/YouTubeClient.cpp | 146 ++- src/YtDlpManager.cpp | 262 +++--- src/i18n/Localization.cpp | 68 ++ src/i18n/RussianCatalog.inc | 200 ++++ src/playback/PlaybackEngine.cpp | 135 ++- src/sources/YtDlpSource.cpp | 17 +- src/util/Paginate.cpp | 63 ++ 72 files changed, 5875 insertions(+), 1243 deletions(-) create mode 100644 include/echoion/core/LyricsService.hpp create mode 100644 include/echoion/core/Socks5HttpBridge.hpp create mode 100644 include/echoion/core/commands/LanguageCommand.hpp create mode 100644 include/echoion/core/commands/LyricsCommand.hpp create mode 100644 include/echoion/core/commands/SoundCloudPlayCommand.hpp create mode 100644 include/echoion/core/commands/SoundCloudSearchCommand.hpp create mode 100644 include/echoion/core/i18n/Localization.hpp create mode 100644 include/echoion/core/util/Paginate.hpp create mode 100644 src/LyricsService.cpp create mode 100644 src/Socks5HttpBridge.cpp create mode 100644 src/i18n/Localization.cpp create mode 100644 src/i18n/RussianCatalog.inc create mode 100644 src/util/Paginate.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7595aa2..c45b630 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,7 +116,7 @@ target_link_libraries(EchoionCore PUBLIC PkgConfig::LIBAV TBB::tbb - SQLite::SQLite3 + SQLite3::SQLite3 # VoidLibrary modules (migration target — replacing in-house infra) Void::Data Void::Functional diff --git a/include/echoion/core/AudioDecoder.hpp b/include/echoion/core/AudioDecoder.hpp index fedecad..e5f02ae 100644 --- a/include/echoion/core/AudioDecoder.hpp +++ b/include/echoion/core/AudioDecoder.hpp @@ -67,9 +67,26 @@ namespace Echoion::Core // Check if decode is finished [[nodiscard]] bool isFinished() const { return eof_.load(); } + // Decoded audio waiting in the queue, in interleaved S16 samples. + // The crossfade readiness gate uses this: a fade only starts once + // the incoming decoder has buffered enough audio to survive it. + [[nodiscard]] std::size_t queuedSamples() const; + + // True when the decode queue is at capacity (the decode thread is + // backpressured) — waiting longer cannot buffer any more. + [[nodiscard]] bool queueSaturated() const; + private: void decodeThread(); + // One read→decode→flush pass over the source; returns on EOF or + // shutdown. decodeThread() parks between sessions awaiting a + // seek request, so a post-EOF seek resumes decoding. + void decodeSession(); + // Perform a pending seek request on the decode thread (the only + // thread allowed to touch the FFmpeg contexts while decoding). + // Returns true if a request was consumed. + bool consumePendingSeek(); // Borrow a chunk buffer of `samples` length from the recycle // free-list (reusing pooled storage), or allocate one if the // free-list is empty. @@ -100,6 +117,9 @@ namespace Echoion::Core // S16 audio queue (like reference) - avoids float conversion std::deque> int16Queue_; static constexpr size_t MAX_INT16_QUEUE_SIZE = 100; + // Max samples per swr_convert() output call; outputBuffer_ is + // sized for this. + static constexpr int MAX_OUT_SAMPLES = 4096; // Free-list of recycled chunk buffers. getNextChunk() swaps the // caller's previous buffer in here and decodeThread() reuses that @@ -116,6 +136,9 @@ namespace Echoion::Core // Decode position in ms; written by the decode thread per frame, // read cross-thread by getPosition() (prefetch decisions). std::atomic currentPositionMs_{0}; + // Pending seek target in ms, -1 = none. Written by seek() under + // mutex_ (coordinated with eof_), consumed by the decode thread. + std::atomic seekRequestMs_{-1}; std::string currentUrl_; std::atomic streamSampleRate_{48000}; diff --git a/include/echoion/core/CommandManager.hpp b/include/echoion/core/CommandManager.hpp index 3527f12..2b462af 100644 --- a/include/echoion/core/CommandManager.hpp +++ b/include/echoion/core/CommandManager.hpp @@ -6,16 +6,18 @@ #include #include #include -#include +#include #include #include #include #include #include #include +#include #include #include #include +#include #include namespace Echoion::Core @@ -148,6 +150,47 @@ namespace Echoion::Core class HelpCommand; void registerHelpCommand(); + // Internal page-navigator command (!page/!next/!prev), defined in + // the .cpp so it can reach the paged-reply cache below. + class PageNavCommand; + void registerPageCommands(); + + // Resolve the language a client should be answered in: their stored + // per-user preference (kv_store "lang:") if any, else the + // configured bot default, else English. + [[nodiscard]] I18n::Language resolveLanguage( + uint64_t clientId, + const std::weak_ptr& musicManager) const; + + // --- Oversized-reply pagination ------------------------------- + // Long replies (from any command except help / the navigator) are + // kept to a single message: page 1 is sent with a footer and the + // remaining pages are cached here for !page/!next/!prev. + struct PagedReply { + std::vector pages; + std::size_t current = 0; + std::chrono::steady_clock::time_point ts{}; + }; + mutable std::mutex pagedMutex_; + std::unordered_map pagedReplies_; + static constexpr std::size_t kPageLimitBytes = 700; + static constexpr std::chrono::minutes kPageTtl{10}; + + // Split `text` into pages, cache pages 2..N for `clientId`, and + // return page 1 (with a footer when there is more than one page). + // Replies that already fit one message pass through unchanged. + std::string paginateReply(uint64_t clientId, std::string text, + I18n::Language lang); + + // Re-render a cached page for `clientId`. When `absolute` is set + // the current page jumps to it (1-based, clamped); otherwise it + // moves by `delta`. Returns std::nullopt when nothing is cached / + // expired. + std::optional + renderCachedPage(uint64_t clientId, + std::optional absolute, int delta, + I18n::Language lang); + std::string prefix_ = "!"; // Non-owning service registry threaded into each CommandContext diff --git a/include/echoion/core/Core.hpp b/include/echoion/core/Core.hpp index 0a44eef..73d89b2 100644 --- a/include/echoion/core/Core.hpp +++ b/include/echoion/core/Core.hpp @@ -2,9 +2,13 @@ #include "CommandManager.hpp" #include "ConfigLoader.hpp" +#include "LyricsService.hpp" #include "MusicManager.hpp" #include "NetworkClient.hpp" #include "RpcServer.hpp" +#ifdef ECHOION_WITH_WEB +#include "echoion/web/HttpServer.hpp" +#endif #include #include #include @@ -16,9 +20,13 @@ #include #include #include +#include #include #include +#include #include +#include +#include namespace Void::Logging { @@ -154,10 +162,24 @@ namespace Echoion::Core void onMusicEvent(const Api::PluginEvent& event); void broadcastEvent(const Api::PluginEvent& event); [[nodiscard]] bool isAdmin(uint64_t clientId) const; + [[nodiscard]] bool isDj(uint64_t clientId) const; void updateWhisperList(); void setupRpcHandlers(); void setupEventBusSubscriptions() noexcept; + // Fetch an online client's avatar bytes (TS local cache, then the + // myTeamSpeak URL, then a legacy file-transfer download) and persist + // them — and the myTS URL — to the database keyed by uid. Returns + // {contentType, bytes} on success. Web-agnostic; used by both the + // avatar HTTP provider and the background warmer. + [[nodiscard]] std::optional> + fetchClientAvatarBytes(const std::string& uid, + uint64_t clientId); + // Periodically cache avatars for every online client so they remain + // available (from the DB) once the user goes offline. Runs on + // avatarWarmer_. + void warmAvatarCache(); + // Build the console + split-file logging stack and install it as // the global Void::Log sink (logSink_ must outlive logging). void installLogging(); @@ -167,6 +189,7 @@ namespace Echoion::Core // Components std::shared_ptr networkClient_; + std::shared_ptr lyricsService_; std::shared_ptr musicManager_; std::unique_ptr commandManager_; Api::PluginInterfacePtr pluginInterface_; @@ -176,21 +199,67 @@ namespace Echoion::Core std::filesystem::path configPath_; std::chrono::system_clock::time_point startTime_; std::atomic initialized_{false}; + // Guards triggerAutoConnect() against duplicate connection + // attempts (reset on a failed initiation so a retry can run). + std::atomic autoConnectInitiated_{false}; // Event callbacks std::vector eventCallbacks_; mutable std::mutex eventMutex_; - // Admin tracking + // Admin / DJ tracking (RPC clients whose TeamSpeak identity is in + // a configured teamspeak.adminGroups / djGroups server group). std::vector adminClients_; + std::vector djClients_; mutable std::mutex adminMutex_; + // Authenticated RPC client -> stable TS uid + nickname, resolved + // at token auth. Keys per-user features (favorites, vote-skip). + struct RpcIdentity { + std::string uid; + std::string nickname; + }; + std::map rpcIdentities_; + mutable std::mutex rpcIdentityMutex_; + [[nodiscard]] std::optional + rpcIdentity(uint64_t clientId) const; + + // Full identity behind an RPC token: uid, display nickname and + // admin standing. Shared by token auth, IP autologin and the + // watch-together identity resolver. + struct TokenIdentity { + std::string uid; + std::string nickname; + bool isAdmin = false; + bool isDj = false; + }; + [[nodiscard]] std::optional + identityForToken(const std::string& token); + // Mark an RPC connection authenticated as `identity` (auth set, + // admin list, per-client identity map). + void registerRpcAuth(uint64_t clientId, + const TokenIdentity& identity); + // Guards RestartWebInterface against overlapping restarts. + std::atomic webRestartPending_{false}; + // Database for persistence std::shared_ptr database_; + // Background avatar cache warmer + the uids already cached this + // session (so we don't re-download an unchanged avatar every cycle). + std::jthread avatarWarmer_; + std::unordered_set warmedUids_; + // RPC server for Desktop/API clients std::shared_ptr rpcServer_; +#ifdef ECHOION_WITH_WEB + // Browser web interface: serves the static UI and hosts the + // independent sync-watch WebSocket. Bot control from the browser + // goes straight to the RPC server, so this holds no bot handles. + std::shared_ptr webServer_; +#endif + // Composition root: a type-keyed registry of all Core services // (logger, config, event bus, network, database, music, rpc). // initialize() provides each instance; resolveServices() and other diff --git a/include/echoion/core/LyricsService.hpp b/include/echoion/core/LyricsService.hpp new file mode 100644 index 0000000..9aa4e24 --- /dev/null +++ b/include/echoion/core/LyricsService.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include "echoion/core/NetworkClient.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + + // Fetches song lyrics from lrclib.net (free, no auth) for the currently + // playing track. Returns both plain lyrics and, when available, LRC + // time-synced lines so the web UI can highlight the active line against the + // playback clock. Results are cached in-process for a while since lyrics + // never change and the same track is asked about repeatedly (chat command, + // web panel, reconnects). + // + // Reachable by chat commands via the service registry and directly by the + // RPC handlers. All network calls are synchronous; callers already run off + // the audio thread (command thread pool / RPC worker). + class LyricsService + { + public: + + struct Line { + std::int64_t ms = 0; // offset from track start + std::string text; + }; + + struct Lyrics { + bool found = false; + std::string plain; // full plain-text lyrics + std::vector synced; // empty when only plain exists + std::string source; // "lrclib" when resolved + std::string title; // as reported by the provider + std::string artist; + }; + + explicit LyricsService(std::shared_ptr net); + + // Resolve lyrics for a track. `durationSec` == 0 means unknown and + // skips the exact-duration lookup (search fallback still runs). + [[nodiscard]] Lyrics fetch(const std::string& title, + const std::string& artist, + const std::string& album, + long long durationSec); + + private: + + [[nodiscard]] Lyrics + fetchUncached(const std::string& title, + const std::string& artist, + const std::string& album, + long long durationSec) const; + + // Parse an LRC-format string ("[mm:ss.xx] text") into sorted, + // timestamped lines, ignoring metadata tags ([ar:], [ti:], …). + [[nodiscard]] static std::vector + parseLrc(const std::string& lrc); + + std::shared_ptr net_; + + struct Entry { + Lyrics value; + std::chrono::steady_clock::time_point at; + }; + mutable std::mutex mutex_; + std::unordered_map cache_; + static constexpr std::chrono::hours kCacheTtl{6}; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 7946b86..19ee323 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -4,6 +4,7 @@ #include "NetworkClient.hpp" #include "PlaylistLoader.hpp" #include "RpcTypes.hpp" +#include "Socks5HttpBridge.hpp" #include "SubscriptionManager.hpp" #include "SubscriptionService.hpp" #include "TrackCache.hpp" @@ -100,6 +101,21 @@ namespace Echoion::Core seek(std::chrono::milliseconds position); [[nodiscard]] Api::Result setVolume(float volume); + // Vote-to-skip the current track. Votes are keyed by the voter's + // stable uid and reset whenever the current track changes. The + // threshold is features.voteSkipThreshold, or a majority of + // online subscribers when 0. Reaching it skips the track. + struct VoteSkipStatus { + uint32_t votes = 0; + uint32_t needed = 0; + bool voted = false; // caller has an active vote + bool skipped = false; + }; + [[nodiscard]] Api::Result + voteSkip(const std::string& uid); + [[nodiscard]] VoteSkipStatus + voteSkipStatus(const std::string& uid) const; + [[nodiscard]] Api::Result queueTrack(const Api::TrackInfo& track, uint64_t clientId); [[nodiscard]] Api::Result removeFromQueue(uint32_t position); @@ -134,7 +150,7 @@ namespace Echoion::Core [[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const; // Which catalog(s) a text search targets. - enum class SearchScope { All, YouTube, Yandex }; + enum class SearchScope { All, YouTube, Yandex, SoundCloud }; [[nodiscard]] Api::Result search(const std::string& query, @@ -158,6 +174,17 @@ namespace Echoion::Core return autoplay_.load(); } + // Start playback (or seed radio) if nothing is playing and an + // online subscriber is listening. Idempotent — safe to call after a + // restore/hot-reload or when a subscriber connects, so radio resumes + // without a manual !play / !radio toggle. + void maybeAutoStart(); + + // Set shuffle/repeat mode directly (used when restoring persisted + // state); persists the session snapshot. + void setShuffle(bool enabled); + void setRepeat(bool enabled); + // Help command [[nodiscard]] std::string getHelpText() const; @@ -278,6 +305,17 @@ namespace Echoion::Core std::chrono::milliseconds duration) override; void onEngineIdle() override; void onLocalFileDone(const std::string& path) override; + + // Persist the live queue + shuffle/repeat/autoplay to the database + // (kv "session.state") so a full restart can restore them; restore + // them at startup. persistSession() is a no-op while a restore is in + // progress to avoid recursive writes. includeCurrent=false drops + // the currently-playing track from the snapshot — used by stop(), + // where the engine clears its entry asynchronously and would + // otherwise be persisted as still queued. + void persistSession(bool includeCurrent = true); + void restoreSession(); + std::atomic restoringSession_{false}; void onPlaybackError(const Api::Error& error, const std::optional& entry) override; @@ -309,9 +347,13 @@ namespace Echoion::Core downloadAudioForPlayback(const Api::TrackInfo& track); void cleanupTempFile(const std::string& filepath); - // True when a SOCKS5 proxy is configured: ffmpeg cannot route - // IP-locked googlevideo URLs through it, so those are downloaded. - [[nodiscard]] bool socksProxyActive() const; + // The proxy the playback engine (ffmpeg) should use. ffmpeg only + // speaks HTTP CONNECT, so a SOCKS5 config starts the local + // Socks5HttpBridge and is rewritten to an Http proxy pointing at + // it; Http/none pass through unchanged (and stop the bridge). + [[nodiscard]] std::optional + effectiveEngineProxy( + const std::optional& proxy); // ---- state ----------------------------------------------------- @@ -342,6 +384,14 @@ namespace Echoion::Core QueueService queue_; std::unique_ptr trackCache_; + // Vote-to-skip state: voter uids for the queue entry identified + // by voteSkipQueueId_ (cleared lazily when the track changes). + mutable std::mutex voteSkipMutex_; + std::set voteSkipUids_; + uint64_t voteSkipQueueId_ = 0; + std::atomic voteSkipThreshold_{0}; // 0 = auto majority + [[nodiscard]] uint32_t voteSkipNeeded() const; + // Autoplay state: seed track for recommendations + re-entrancy // guard for the async fetch. The seed's catalog decides where // related tracks are pulled from (YouTube radio mix vs. Yandex @@ -364,6 +414,10 @@ namespace Echoion::Core std::atomic importRunning_{false}; std::jthread importThread_; std::unique_ptr engine_; + // HTTP CONNECT -> SOCKS5 tunnel for ffmpeg (see + // effectiveEngineProxy); only running while the configured proxy + // is SOCKS5. + std::unique_ptr ffmpegProxyBridge_; std::unique_ptr subscriptions_; // Pending search results per client (for select command) diff --git a/include/echoion/core/RpcDtos.hpp b/include/echoion/core/RpcDtos.hpp index bf11b69..110307d 100644 --- a/include/echoion/core/RpcDtos.hpp +++ b/include/echoion/core/RpcDtos.hpp @@ -73,10 +73,18 @@ namespace Echoion::Core::Dto }; struct ManageUsersRequest { - std::string action; // "list" | "remove" + std::string action; // "list" | "remove" | "clearAll" std::optional uid; }; + struct UrlRequest { + std::string url; + }; + + struct AnnounceRequest { + std::string text; + }; + // ── RPC handler responses ─────────────────────────────────────────────── struct Track { @@ -88,6 +96,9 @@ 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 + // it for "open original link" (falls back to url). + std::optional shortenedUrl; }; [[nodiscard]] inline Track toTrack(const Api::TrackInfo& t) @@ -104,7 +115,28 @@ namespace Echoion::Core::Dto .thumbnailUrl = t.thumbnailUrl, .url = t.originalUrl.empty() ? std::nullopt - : std::optional(t.originalUrl)}; + : std::optional(t.originalUrl), + .shortenedUrl = + t.shortenedUrl && !t.shortenedUrl->empty() + ? t.shortenedUrl + : std::nullopt}; + } + + // Inverse of toTrack (client-supplied tracks, e.g. AddFavorite). + [[nodiscard]] inline Api::TrackInfo fromTrack(const Track& t) + { + Api::TrackInfo info; + info.id = t.id; + info.title = t.title; + info.artist = t.artist; + info.album = t.album; + if (t.duration) { + info.duration = std::chrono::milliseconds(*t.duration); + } + info.source = static_cast(t.source); + info.thumbnailUrl = t.thumbnailUrl; + info.originalUrl = t.url.value_or(""); + return info; } struct QueueItem { @@ -127,6 +159,12 @@ namespace Echoion::Core::Dto float volume = 0.0f; bool repeat = false; bool shuffle = false; + // Radio mode: auto-enqueue related tracks when the queue runs dry. + bool autoplay = false; + // Vote-skip state for the current track (additive fields). + std::uint32_t skipVotes = 0; + std::uint32_t skipVotesNeeded = 0; + bool skipVoted = false; }; struct Success { @@ -143,6 +181,37 @@ namespace Echoion::Core::Dto float volume = 0.0f; }; + struct Autoplay { + bool autoplay = false; + }; + + // Per-user preferences stored in the kv store; `language` shares the + // "lang:" key with the !lang chat command so the web switcher and + // the bot stay in sync. + struct UserPrefs { + std::string language; + }; + + // Custom emoji metadata (name + mime); the image itself is served at + // GET /emoji/, not inlined here. + struct CustomEmojiDto { + std::string name; + std::string mime; + std::string addedBy; + }; + struct CustomEmojiList { + std::vector emojis; + }; + // AddCustomEmoji request: name + mime + base64-encoded image bytes. + struct AddEmojiRequest { + std::string name; + std::string mime; + std::string dataBase64; + }; + struct EmojiNameRequest { + std::string name; + }; + struct QueuedResponse { bool success = true; std::uint64_t queueId = 0; @@ -192,6 +261,13 @@ namespace Echoion::Core::Dto std::uint32_t connectedClients = 0; std::uint32_t subscribers = 0; std::uint32_t queueLength = 0; + std::uint32_t onlineSubscribers = 0; + // Nicknames behind onlineSubscribers, so non-admin clients can + // render a "listening now" list without the admin user API. + std::vector onlineSubscriberNames; + // TeamSpeak uids parallel to onlineSubscriberNames (same order), so + // the web UI can fetch each listener's avatar at /avatar/. + std::vector onlineSubscriberUids; }; struct AuditEntryDto { @@ -207,12 +283,77 @@ namespace Echoion::Core::Dto struct SubscriberDto { std::string uid; std::string nickname; + bool online = false; }; struct UsersResponse { std::vector users; }; + // Authenticate success. isAdmin/isDj/uid/nickname are additive — older + // clients that only read `message` keep working. + struct AuthSuccess { + bool success = true; + std::string message; + bool isAdmin = false; + bool isDj = false; + std::string uid; + std::string nickname; + // Set by address-based autologin so the client can persist the + // session token it never typed; empty for normal token auth. + std::string token; + }; + + struct AddFavoriteRequest { + Track track; + }; + + struct FavoritesResponse { + std::vector tracks; + }; + + // GetLyrics response: plain text plus, when available, time-synced lines + // (ms offset from track start) so the web UI can highlight the active line. + struct LyricsLineDto { + std::int64_t ms = 0; + std::string text; + }; + + struct LyricsResponse { + bool found = false; + std::string plain; + std::vector synced; + std::string source; // "lrclib" when resolved + std::string title; + std::string artist; + }; + + struct VoteSkipResponse { + std::uint32_t votes = 0; + std::uint32_t needed = 0; + bool voted = false; + bool skipped = false; + }; + + struct RequesterDto { + std::string uid; + std::string nickname; + std::uint64_t count = 0; + }; + + struct AggregateStatsResponse { + std::uint64_t tracksToday = 0; + std::uint64_t listeningMsToday = 0; + std::uint64_t queueAdditionsToday = 0; + std::uint64_t skipsToday = 0; + std::uint64_t playsTotal = 0; + std::uint64_t skipsTotal = 0; + std::vector topRequesters; + std::uint64_t youtubeCount = 0; + std::uint64_t yandexCount = 0; + std::uint64_t otherCount = 0; + }; + // ── Event-broadcast payloads ──────────────────────────────────────────── struct TrackBrief { diff --git a/include/echoion/core/RpcServer.hpp b/include/echoion/core/RpcServer.hpp index 731f533..44327f7 100644 --- a/include/echoion/core/RpcServer.hpp +++ b/include/echoion/core/RpcServer.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -53,6 +54,13 @@ namespace Echoion::Core void removeAuthenticatedClient(uint64_t clientId); [[nodiscard]] bool isClientAuthenticated(uint64_t clientId); + // The client's effective network address: the X-Echoion-Client-Ip + // header set by the web server's /rpc bridge (trusted only from + // loopback peers), else the socket's remote address. Used for + // address-based autologin. + [[nodiscard]] std::optional + getClientAddress(uint64_t clientId) const; + // Server introspection (for GetServerInfo / GetAuditLog). struct AuditEntry { uint64_t clientId = 0; @@ -74,6 +82,8 @@ namespace Echoion::Core private: void acceptLoop(); + void doAccept(); + void onAccept(asio::ip::tcp::socket socket); void handleClient( std::shared_ptr> ws); void processMessage(uint64_t clientId, const std::string& message); @@ -93,6 +103,8 @@ namespace Echoion::Core uint64_t, std::shared_ptr>> clients_; + // clientId -> effective network address (see getClientAddress). + std::unordered_map clientAddresses_; mutable std::mutex clientsMutex_; std::atomic nextClientId_{1}; diff --git a/include/echoion/core/Socks5HttpBridge.hpp b/include/echoion/core/Socks5HttpBridge.hpp new file mode 100644 index 0000000..f9c9837 --- /dev/null +++ b/include/echoion/core/Socks5HttpBridge.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + + // Local HTTP CONNECT proxy that tunnels through a SOCKS5 upstream. + // + // FFmpeg has no SOCKS5 support at all — its http protocol only knows the + // `http_proxy` option, which speaks HTTP CONNECT. To stream IP-locked + // googlevideo URLs directly through a SOCKS5 proxy, the decoder is pointed + // at 127.0.0.1: and every CONNECT is forwarded through the + // configured SOCKS5 proxy (greeting/auth/CONNECT handshake, then a raw + // byte pump in both directions). + // + // Only the two decoder slots stream concurrently, so a blocking + // thread-per-connection design is deliberate: no io_context pump, no + // async state machines. + class Socks5HttpBridge + { + public: + + Socks5HttpBridge() = default; + ~Socks5HttpBridge(); + + Socks5HttpBridge(const Socks5HttpBridge&) = delete; + Socks5HttpBridge& operator=(const Socks5HttpBridge&) = delete; + + // Bind 127.0.0.1:, start the accept thread and return + // the bound port. Restarts (against the new upstream) when already + // running. + Api::Result start(const Void::Net::ProxyConfig& socks5); + + // Close the acceptor and every live tunnel; joins all threads. + void stop(); + + [[nodiscard]] bool running() const { return running_.load(); } + [[nodiscard]] uint16_t port() const { return port_; } + + // The SOCKS5 endpoint the bridge currently forwards to (empty when + // stopped). Lets callers skip a restart when the config is + // unchanged. + [[nodiscard]] std::optional upstream() const; + + private: + + struct Connection { + boost::asio::ip::tcp::socket client; + boost::asio::ip::tcp::socket upstream; + std::atomic done{false}; + std::thread worker; + + explicit Connection(boost::asio::io_context& io) + : client(io), upstream(io) + { + } + }; + + void acceptLoop(); + void serve(Connection& conn); + // SOCKS5 greeting/auth/CONNECT for host:port on conn.upstream. + // Throws std::runtime_error on any protocol failure. + void socks5Connect(boost::asio::ip::tcp::socket& upstream, + const std::string& host, uint16_t targetPort, + const Void::Net::ProxyConfig& proxy); + // Drop connections whose worker already finished (joins them). + void pruneFinished(); + + boost::asio::io_context io_; + std::optional acceptor_; + std::thread acceptThread_; + uint16_t port_ = 0; + std::atomic running_{false}; + + mutable std::mutex mutex_; // guards upstream_ and connections_ + std::optional upstream_; + std::vector> connections_; + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/SubscriptionService.hpp b/include/echoion/core/SubscriptionService.hpp index 3eece09..b519187 100644 --- a/include/echoion/core/SubscriptionService.hpp +++ b/include/echoion/core/SubscriptionService.hpp @@ -81,10 +81,16 @@ namespace Echoion::Core [[nodiscard]] std::vector getSubscribers() const; - // Presence events from the plugin. onClientConnected returns true - // when a subscribed user came online and playback should + // Presence events from the plugin. onClientConnected resolves the + // client once and hands the uid back so callers don't repeat the + // (plugin round-trip) lookup: subscribedUid is set when the + // client is a subscriber; mayAutoStart when playback should // auto-start if tracks are queued. - bool onClientConnected(uint64_t clientId); + struct ClientConnectResult { + std::optional subscribedUid; + bool mayAutoStart = false; + }; + ClientConnectResult onClientConnected(uint64_t clientId); void onClientDisconnected(uint64_t clientId); private: diff --git a/include/echoion/core/YouTubeClient.hpp b/include/echoion/core/YouTubeClient.hpp index 8fbbe0d..4efcb84 100644 --- a/include/echoion/core/YouTubeClient.hpp +++ b/include/echoion/core/YouTubeClient.hpp @@ -49,12 +49,25 @@ namespace Echoion::Core search(std::string_view query, std::optional pageToken = std::nullopt); + // Search SoundCloud via yt-dlp (scsearch). Returns SoundCloud + // tracks whose originalUrl is the permalink, streamable through the + // ytdlp-direct source. + [[nodiscard]] Api::Result + searchSoundCloud(std::string_view query); + // Related tracks for radio autoplay: lists the YouTube "mix" // playlist (RD) via yt-dlp --flat-playlist. Runs through // the proxy like every yt-dlp call, so it works under SOCKS5. [[nodiscard]] Api::Result> radioMix(const std::string& videoId, size_t limit = 10); + // Fetch music-video candidates for a random search query. Used as a + // radio fallback when no unplayed related track can be found (or + // there is no seed). Goes through yt-dlp/proxy like radioMix; the + // returned list is shuffled so the caller can pick/filter freely. + [[nodiscard]] Api::Result> + randomMusicVideo(size_t limit = 10); + // Get video details including stream URLs using yt-dlp [[nodiscard]] Api::Result getVideoInfo(std::string_view videoId); @@ -156,6 +169,13 @@ namespace Echoion::Core [[nodiscard]] Api::Result searchWithYtDlp(std::string_view query, const std::optional& pageToken); + // Shared yt-dlp search backend. `searchPrefix` is the yt-dlp search + // selector (e.g. "ytsearch5", "scsearch5"); `source` tags the + // resulting tracks and decides how originalUrl is built. + [[nodiscard]] Api::Result + searchWithYtDlpProvider(std::string_view query, + std::string_view searchPrefix, + Api::TrackSource source); // Fetch video durations for search results (batch API call) void fetchVideoDurations(std::vector& tracks, diff --git a/include/echoion/core/YtDlpManager.hpp b/include/echoion/core/YtDlpManager.hpp index 8bd71ed..b31aad5 100644 --- a/include/echoion/core/YtDlpManager.hpp +++ b/include/echoion/core/YtDlpManager.hpp @@ -50,8 +50,9 @@ namespace Echoion::Core // Get yt-dlp version [[nodiscard]] std::string getVersion() const; - // Force update yt-dlp to latest version - Api::Result update(); + // Force update yt-dlp to latest version; returns the verified + // version string of the freshly installed binary. + Api::Result update(); // Execute yt-dlp with given arguments and return output // (synchronous) @@ -62,10 +63,6 @@ namespace Echoion::Core [[nodiscard]] std::future executeAsync(const std::vector& args); - // Execute multiple yt-dlp commands concurrently - [[nodiscard]] std::vector executeBatch( - const std::vector>& argsList); - // Set cookie options for YouTube authentication void setCookiesPath(const std::string& path); void setCookiesFromBrowser(const std::string& browser); @@ -93,8 +90,8 @@ namespace Echoion::Core // Download yt-dlp from official source Api::Result downloadYtDlp(); - // Make executable executable (Unix only) - Api::Result makeExecutable(); + // Make the given file executable (Unix only) + Api::Result makeExecutable(const std::filesystem::path& path); // Check if update is needed (older than 7 days) [[nodiscard]] bool shouldUpdate() const; @@ -135,8 +132,6 @@ namespace Echoion::Core std::unique_ptr pool_; // yt-dlp download URLs - static constexpr std::string_view YTDLP_VERSION_URL = - "https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest"; static constexpr std::string_view YTDLP_DOWNLOAD_LINUX = "https://github.com/yt-dlp/yt-dlp/releases/latest/download/" "yt-dlp"; diff --git a/include/echoion/core/commands/AnnounceCommand.hpp b/include/echoion/core/commands/AnnounceCommand.hpp index 92da64b..e328d92 100644 --- a/include/echoion/core/commands/AnnounceCommand.hpp +++ b/include/echoion/core/commands/AnnounceCommand.hpp @@ -20,17 +20,18 @@ namespace Echoion::Core { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply("The music service is currently unavailable."); + ctx.reply( + ctx.tr("The music service is currently unavailable.")); return; } if (ctx.args.empty()) { - ctx.reply(std::format( - "Usage: {}announce ", ctx.prefix)); + ctx.reply( + ctx.trf("Usage: {}announce ", ctx.prefix)); return; } const size_t reached = manager->setAnnouncement(ctx.args); - ctx.reply(std::format( + ctx.reply(ctx.trf( "Announcement saved and delivered to {} online " "subscriber(s). Offline subscribers get it on their " "next connect.", diff --git a/include/echoion/core/commands/AutoplayCommand.hpp b/include/echoion/core/commands/AutoplayCommand.hpp index a2c6ca3..ecccde2 100644 --- a/include/echoion/core/commands/AutoplayCommand.hpp +++ b/include/echoion/core/commands/AutoplayCommand.hpp @@ -23,8 +23,8 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } @@ -32,7 +32,8 @@ namespace Echoion::Core std::string arg(ctx.args); std::transform(arg.begin(), arg.end(), arg.begin(), [](unsigned char c) { - return static_cast(std::tolower(c)); + return static_cast( + std::tolower(c)); }); if (arg == "on" || arg == "true" || arg == "1" || arg == "enable") { @@ -45,17 +46,19 @@ namespace Echoion::Core manager->setAutoplay(enable); if (enable) { - ctx.reply( + ctx.reply(ctx.tr( "\xf0\x9f\x93\xbb Autoplay is ON \xe2\x80\x94 I'll " - "keep the music going with related tracks."); + "keep the music going with related tracks.")); } else { - ctx.reply("\xf0\x9f\x93\xbb Autoplay is OFF."); + ctx.reply(ctx.tr("\xf0\x9f\x93\xbb Autoplay is OFF.")); } } catch (const std::exception& e) { - Void::Log::error("AutoplayCommand", "{}", + Void::Log::error( + "AutoplayCommand", "{}", std::format("Autoplay command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/ClearCommand.hpp b/include/echoion/core/commands/ClearCommand.hpp index 4fcb0e3..bc2a88f 100644 --- a/include/echoion/core/commands/ClearCommand.hpp +++ b/include/echoion/core/commands/ClearCommand.hpp @@ -16,26 +16,28 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->clearQueue(); if (!result) { - Void::Log::error("ClearCommand", "{}", - std::format("Clear command failed: {}", - result.error().message)); - ctx.reply( - "Couldn't clear the queue. Please try again."); + Void::Log::error("ClearCommand", "{}", + std::format("Clear command failed: {}", + result.error().message)); + ctx.reply(ctx.tr( + "Couldn't clear the queue. Please try again.")); return; } - ctx.reply("Queue cleared!"); + ctx.reply(ctx.tr("Queue cleared!")); } catch (const std::exception& e) { - Void::Log::error("ClearCommand", "{}", + Void::Log::error( + "ClearCommand", "{}", std::format("Clear command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/Command.hpp b/include/echoion/core/commands/Command.hpp index 56b33db..8d877db 100644 --- a/include/echoion/core/commands/Command.hpp +++ b/include/echoion/core/commands/Command.hpp @@ -1,6 +1,7 @@ #pragma once #include "echoion/core/MusicManager.hpp" +#include "echoion/core/i18n/Localization.hpp" #include #include #include @@ -136,8 +137,12 @@ namespace Echoion::Core // (non-owning; outlives the command). Populated by CommandManager. const Void::Service::ServiceRegistry* services = nullptr; + // Language the invoking user should be answered in. Resolved by + // CommandManager (per-user kv override, else the config default). + I18n::Language language = I18n::Language::English; + // Reply callback - set by CommandManager - std::function replyCallback; + std::function replyCallback = {}; // Helper to reply to the user void reply(std::string_view message) const @@ -147,6 +152,24 @@ namespace Echoion::Core } } + // Translate an English source string into the invoker's language. + // Missing translations fall back to the English original. + [[nodiscard]] std::string_view tr(std::string_view english) const + { + return I18n::translate(english, language); + } + + // Translate a std::format-style English template, then substitute + // the arguments. The template is translated at runtime, so callers + // use this instead of std::format for user-facing text. + template + [[nodiscard]] std::string trf(std::string_view englishFmt, + Args&&... args) const + { + return std::vformat(I18n::translate(englishFmt, language), + std::make_format_args(args...)); + } + // Resolve a shared service by interface, or nullptr if the // registry is absent / the service was not provided. template @@ -156,6 +179,49 @@ namespace Echoion::Core } }; + // Format a duration as m:ss (or h:mm:ss past an hour). Shared by the + // track-listing commands (!np, !queue) so their timestamps line up. + inline std::string formatDuration(std::chrono::milliseconds duration) + { + auto totalSeconds = duration.count() / 1000; + auto hours = totalSeconds / 3600; + auto mins = (totalSeconds % 3600) / 60; + auto secs = totalSeconds % 60; + if (hours > 0) { + return std::format("{}:{:02}:{:02}", hours, mins, secs); + } + return std::format("{}:{:02}", mins, secs); + } + + // A compact one-line playback status readout (volume / shuffle / repeat / + // radio) shared by !help, !np and !list so all three show the same + // at-a-glance state. Rendered as a Markdown blockquote line. Returns an + // empty string when playback state is unavailable. Radio comes from + // autoplayEnabled() since PlaybackState carries no autoplay field. + inline std::string playbackStatusLine(const CommandContext& ctx) + { + auto mm = ctx.musicManager.lock(); + if (!mm) { + return {}; + } + auto st = mm->getPlaybackState(); + if (!st) { + return {}; + } + auto onOff = [&](bool b) -> std::string_view { + return b ? ctx.tr("On") : ctx.tr("Off"); + }; + return ctx.trf( + "> \xf0\x9f\x8e\x9a {} {}% \xc2\xb7 " + "\xf0\x9f\x94\x80 {} {} \xc2\xb7 " + "\xf0\x9f\x94\x81 {} {} \xc2\xb7 " + "\xf0\x9f\x93\xbb {} {}", + ctx.tr("Volume"), static_cast(st->volume * 100), + ctx.tr("Shuffle"), onOff(st->shuffle), + ctx.tr("Repeat"), onOff(st->repeat), + ctx.tr("Radio"), onOff(mm->autoplayEnabled())); + } + /** * @brief Interface that all commands must implement. */ @@ -200,6 +266,16 @@ namespace Echoion::Core * @brief Returns whether this command requires admin privileges. */ virtual bool requiresAdmin() const { return false; } + + /** + * @brief Whether an over-long reply from this command should be + * auto-paginated into a single message with a "!page" footer. + * + * Defaults to true. Commands that manage their own output shape + * (help's collapsible sections, the page navigator itself) return + * false so their replies are sent verbatim. + */ + virtual bool autoPaginate() const { return true; } }; using CommandPtr = std::shared_ptr; diff --git a/include/echoion/core/commands/Commands.hpp b/include/echoion/core/commands/Commands.hpp index feaa9cb..6b5ad25 100644 --- a/include/echoion/core/commands/Commands.hpp +++ b/include/echoion/core/commands/Commands.hpp @@ -5,6 +5,10 @@ #include "AutoplayCommand.hpp" #include "ClearCommand.hpp" #include "Command.hpp" +#include "FavoriteCommand.hpp" +#include "HistoryCommand.hpp" +#include "LanguageCommand.hpp" +#include "LyricsCommand.hpp" #include "MoveCommand.hpp" #include "NowPlayingCommand.hpp" #include "PauseCommand.hpp" @@ -21,18 +25,18 @@ #include "SeekCommand.hpp" #include "SelectCommand.hpp" #include "ShuffleCommand.hpp" -#include "FavoriteCommand.hpp" -#include "HistoryCommand.hpp" #include "SkipCommand.hpp" +#include "SoundCloudPlayCommand.hpp" +#include "SoundCloudSearchCommand.hpp" #include "StatsCommand.hpp" #include "StopCommand.hpp" -#include "YandexPlayCommand.hpp" -#include "YandexSearchCommand.hpp" -#include "YoutubePlayCommand.hpp" -#include "YoutubeSearchCommand.hpp" #include "SubscribeCommand.hpp" #include "SubscribersCommand.hpp" #include "UnsubscribeAllCommand.hpp" #include "UnsubscribeCommand.hpp" #include "UnsubscribeIdCommand.hpp" #include "VolumeCommand.hpp" +#include "YandexPlayCommand.hpp" +#include "YandexSearchCommand.hpp" +#include "YoutubePlayCommand.hpp" +#include "YoutubeSearchCommand.hpp" diff --git a/include/echoion/core/commands/FavoriteCommand.hpp b/include/echoion/core/commands/FavoriteCommand.hpp index 2eb2588..10e3e65 100644 --- a/include/echoion/core/commands/FavoriteCommand.hpp +++ b/include/echoion/core/commands/FavoriteCommand.hpp @@ -22,13 +22,13 @@ namespace Echoion::Core auto manager = ctx.musicManager.lock(); auto db = ctx.service(); if (!manager || !db) { - ctx.reply("Favorites are unavailable."); + ctx.reply(ctx.tr("Favorites are unavailable.")); return; } auto uid = manager->clientUid(ctx.clientId); if (!uid) { - ctx.reply("Couldn't identify you on the server."); + ctx.reply(ctx.tr("Couldn't identify you on the server.")); return; } const uint64_t userKey = fnv1a(*uid); @@ -44,7 +44,7 @@ namespace Echoion::Core } else if (sub == "remove" || sub == "rm") { removeFavorite(ctx, *db, userKey, rest); } else { - ctx.reply(std::format( + ctx.reply(ctx.trf( "Usage: {}fav add | list | play | remove ", ctx.prefix)); } @@ -117,11 +117,11 @@ namespace Echoion::Core { auto favorites = db.getFavorites(userKey); if (!favorites) { - ctx.reply("Couldn't read your favorites."); + ctx.reply(ctx.tr("Couldn't read your favorites.")); return; } if (favorites->empty()) { - ctx.reply(std::format( + ctx.reply(ctx.trf( "You have no favorites yet. Save the current track " "with {}fav add", ctx.prefix)); @@ -130,8 +130,8 @@ namespace Echoion::Core std::string msg = "Your favorites:"; size_t index = 1; for (const auto& fav : *favorites) { - msg += std::format("\n{}. {}", index++, - trackLink(fav.track)); + msg += + std::format("\n{}. {}", index++, trackLink(fav.track)); } ctx.reply(msg); } @@ -142,15 +142,14 @@ namespace Echoion::Core { auto current = manager.getCurrentTrack(); if (!current || !current->has_value()) { - ctx.reply("Nothing is playing right now."); + ctx.reply(ctx.tr("Nothing is playing right now.")); return; } const auto& track = (*current)->track; if (db.addFavorite(userKey, track)) { - ctx.reply(std::format("Added to favorites: {}", - track.title)); + ctx.reply(ctx.trf("Added to favorites: {}", track.title)); } else { - ctx.reply("Couldn't save the favorite."); + ctx.reply(ctx.tr("Couldn't save the favorite.")); } } @@ -160,22 +159,22 @@ namespace Echoion::Core { auto index = parseIndex(arg); if (!index) { - ctx.reply("Usage: fav play (see fav list)"); + ctx.reply( + ctx.tr("Usage: fav play (see fav list)")); return; } auto favorites = db.getFavorites(userKey); if (!favorites || *index > favorites->size()) { - ctx.reply("No favorite with that number."); + ctx.reply(ctx.tr("No favorite with that number.")); return; } const auto& track = (*favorites)[*index - 1].track; - auto result = - manager.play(track.originalUrl, ctx.clientId); + auto result = manager.play(track.originalUrl, ctx.clientId); if (result) { ctx.reply(*result); } else { - ctx.reply(std::format("Couldn't play it: {}", - result.error().message)); + ctx.reply(ctx.trf("Couldn't play it: {}", + result.error().message)); } } @@ -185,20 +184,21 @@ namespace Echoion::Core { auto index = parseIndex(arg); if (!index) { - ctx.reply("Usage: fav remove (see fav list)"); + ctx.reply( + ctx.tr("Usage: fav remove (see fav list)")); return; } auto favorites = db.getFavorites(userKey); if (!favorites || *index > favorites->size()) { - ctx.reply("No favorite with that number."); + ctx.reply(ctx.tr("No favorite with that number.")); return; } const auto& fav = (*favorites)[*index - 1]; if (db.removeFavorite(userKey, fav.track.originalUrl)) { - ctx.reply(std::format("Removed from favorites: {}", - fav.track.title)); + ctx.reply( + ctx.trf("Removed from favorites: {}", fav.track.title)); } else { - ctx.reply("Couldn't remove the favorite."); + ctx.reply(ctx.tr("Couldn't remove the favorite.")); } } }; diff --git a/include/echoion/core/commands/HistoryCommand.hpp b/include/echoion/core/commands/HistoryCommand.hpp index 6a372d7..1bc18ae 100644 --- a/include/echoion/core/commands/HistoryCommand.hpp +++ b/include/echoion/core/commands/HistoryCommand.hpp @@ -18,7 +18,7 @@ namespace Echoion::Core { auto db = ctx.service(); if (!db) { - ctx.reply("History is unavailable (no database)."); + ctx.reply(ctx.tr("History is unavailable (no database).")); return; } @@ -35,11 +35,11 @@ namespace Echoion::Core auto recent = db->getRecentlyPlayed(0, limit); if (!recent) { - ctx.reply("Couldn't read the playback history."); + ctx.reply(ctx.tr("Couldn't read the playback history.")); return; } if (recent->empty()) { - ctx.reply("Nothing has been played yet."); + ctx.reply(ctx.tr("Nothing has been played yet.")); return; } diff --git a/include/echoion/core/commands/LanguageCommand.hpp b/include/echoion/core/commands/LanguageCommand.hpp new file mode 100644 index 0000000..37a7b3b --- /dev/null +++ b/include/echoion/core/commands/LanguageCommand.hpp @@ -0,0 +1,111 @@ +#pragma once + +#include "../MusicManager.hpp" +#include "../i18n/Localization.hpp" +#include "Command.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Core +{ + + // !language [en|ru] — show or set the caller's reply language. The choice + // is stored per user (keyed by the stable TS3 unique identifier) in + // kv_store so it survives reconnects and restarts. With no argument it + // reports the current language and the available options. + class LanguageCommand : public Command + { + public: + + void execute(const CommandContext& ctx) override + { + std::string arg = trimmedLower(ctx.args); + + if (arg.empty()) { + ctx.reply( + ctx.trf("Current language: {}. Available: en, ru. Use " + "{}language .", + I18n::languageName(ctx.language), ctx.prefix)); + return; + } + + const bool isEn = + arg == "en" || arg == "eng" || arg == "english"; + const bool isRu = arg == "ru" || arg == "rus" || + arg == "russian" || + arg == "\xd1\x80\xd1\x83\xd1\x81\xd1\x81" + "\xd0\xba\xd0\xb8\xd0\xb9"; + if (!isEn && !isRu) { + ctx.reply(ctx.tr("Unknown language. Choose 'en' or 'ru'.")); + return; + } + const I18n::Language newLang = + isRu ? I18n::Language::Russian : I18n::Language::English; + + auto manager = ctx.musicManager.lock(); + auto db = ctx.service(); + if (!manager || !db) { + ctx.reply( + ctx.tr("Language settings are unavailable right now.")); + return; + } + + auto uid = manager->clientUid(ctx.clientId); + if (!uid || uid->empty()) { + ctx.reply(ctx.tr("Couldn't identify you on the server.")); + return; + } + + auto saved = db->setKv( + "lang:" + *uid, std::string(I18n::languageCode(newLang))); + if (!saved) { + ctx.reply(ctx.tr( + "Couldn't save your language. Please try again.")); + return; + } + + // Confirm in the newly selected language. + std::string name(I18n::languageName(newLang)); + ctx.reply(std::vformat( + I18n::translate("\xe2\x9c\x85 Language set to {}.", + newLang), + std::make_format_args(name))); + } + + std::string_view getDescription() const override + { + return "Sets your reply language (English or Russian)."; + } + + std::string_view getUsage() const override { return "[en|ru]"; } + + CommandCategory getCategory() const override + { + return CommandCategory::Utility; + } + + std::vector getAliases() const override + { + return {"lang"}; + } + + private: + + static std::string trimmedLower(std::string_view in) + { + size_t b = in.find_first_not_of(" \t"); + if (b == std::string_view::npos) { + return {}; + } + size_t e = in.find_last_not_of(" \t"); + std::string out(in.substr(b, e - b + 1)); + std::transform(out.begin(), out.end(), out.begin(), + [](unsigned char c) { return std::tolower(c); }); + return out; + } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/LyricsCommand.hpp b/include/echoion/core/commands/LyricsCommand.hpp new file mode 100644 index 0000000..2489d6f --- /dev/null +++ b/include/echoion/core/commands/LyricsCommand.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include "Command.hpp" +#include "echoion/core/LyricsService.hpp" +#include +#include + +namespace Echoion::Core +{ + + // !lyrics — show the lyrics of the currently playing track (via lrclib). + class LyricsCommand : public Command + { + public: + + void execute(const CommandContext& ctx) override + { + try { + auto manager = ctx.musicManager.lock(); + if (!manager) { + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); + return; + } + + auto current = manager->getCurrentTrack(); + if (!current || !current->has_value()) { + ctx.reply(ctx.trf("Nothing is currently playing. " + "Add something with {}play !", + ctx.prefix)); + return; + } + + const auto& track = current->value().track; + + auto lyrics = ctx.service(); + if (!lyrics) { + ctx.reply(ctx.tr("Lyrics are unavailable right now.")); + return; + } + + long long durationSec = + track.duration.has_value() + ? track.duration->count() / 1000 + : 0; + auto result = lyrics->fetch(track.title, track.artist, + track.album, durationSec); + + if (!result.found || result.plain.empty()) { + ctx.reply(ctx.trf("No lyrics found for {}.", + trackLink(track))); + return; + } + + std::string msg = std::format( + "\xf0\x9f\x8e\xa4 {}\n\n{}", trackLink(track), + result.plain); + ctx.reply(msg); + } catch (const std::exception& e) { + Void::Log::error( + "LyricsCommand", "{}", + std::format("Lyrics command exception: {}", e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); + } + } + + std::string_view getDescription() const override + { + return "Shows the lyrics of the current track."; + } + + CommandCategory getCategory() const override + { + return CommandCategory::Music; + } + + std::vector getAliases() const override + { + return {"ly"}; + } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/MoveCommand.hpp b/include/echoion/core/commands/MoveCommand.hpp index 675f251..a9d8235 100644 --- a/include/echoion/core/commands/MoveCommand.hpp +++ b/include/echoion/core/commands/MoveCommand.hpp @@ -17,14 +17,15 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } if (ctx.args.empty()) { - ctx.reply("Usage: move \nExample: move 5 1 " - "(moves track 5 to position 1)"); + ctx.reply( + ctx.tr("Usage: move \nExample: move 5 1 " + "(moves track 5 to position 1)")); return; } @@ -33,7 +34,8 @@ namespace Echoion::Core auto spacePos = ctx.args.find(' '); if (spacePos == std::string::npos) { - ctx.reply("Please provide both from and to positions."); + ctx.reply(ctx.tr( + "Please provide both from and to positions.")); return; } @@ -46,35 +48,40 @@ namespace Echoion::Core if (result1.ec != std::errc() || result2.ec != std::errc() || from == 0 || to == 0) { - ctx.reply("Please provide valid position numbers " - "(starting from 1)."); + ctx.reply( + ctx.tr("Please provide valid position numbers " + "(starting from 1).")); return; } auto moveResult = manager->moveInQueue( from - 1, to - 1); // Convert to 0-based if (!moveResult) { - Void::Log::error("MoveCommand", "{}", + Void::Log::error( + "MoveCommand", "{}", std::format("Move command failed: {}", moveResult.error().message)); if (moveResult.error().code == Api::ErrorCode::NotFound) { - ctx.reply("One of those positions doesn't exist in " - "the queue."); + ctx.reply(ctx.tr( + "One of those positions doesn't exist in " + "the queue.")); } else { - ctx.reply( - "Couldn't move that track. Please try again."); + ctx.reply(ctx.tr( + "Couldn't move that track. Please try again.")); } return; } - ctx.reply(std::format( - "Moved track from position {} to {}.", from, to)); + ctx.reply(ctx.trf("Moved track from position {} to {}.", + from, to)); } catch (const std::exception& e) { - Void::Log::error("MoveCommand", "{}", + Void::Log::error( + "MoveCommand", "{}", std::format("Move command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/NowPlayingCommand.hpp b/include/echoion/core/commands/NowPlayingCommand.hpp index 434825e..2acfb7a 100644 --- a/include/echoion/core/commands/NowPlayingCommand.hpp +++ b/include/echoion/core/commands/NowPlayingCommand.hpp @@ -16,24 +16,26 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto current = manager->getCurrentTrack(); if (!current) { - Void::Log::error("NowPlayingCommand", "{}", + Void::Log::error( + "NowPlayingCommand", "{}", std::format("NowPlaying command failed: {}", current.error().message)); - ctx.reply("Couldn't get current track information."); + ctx.reply( + ctx.tr("Couldn't get current track information.")); return; } if (!current->has_value()) { - ctx.reply(std::format("Nothing is currently playing. " - "Add something with {}play !", - ctx.prefix)); + ctx.reply(ctx.trf("Nothing is currently playing. " + "Add something with {}play !", + ctx.prefix)); return; } @@ -70,11 +72,21 @@ namespace Echoion::Core escapeMarkdown(track.addedBy)); } + // Same at-a-glance status footer as !help and !list. + if (std::string status = playbackStatusLine(ctx); + !status.empty()) { + msg += "\n\n"; + msg += status; + } + ctx.reply(msg); } catch (const std::exception& e) { - Void::Log::error("NowPlayingCommand", "{}", std::format( - "NowPlaying command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "NowPlayingCommand", "{}", + std::format("NowPlaying command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } @@ -92,22 +104,6 @@ namespace Echoion::Core { return {"np", "current", "playing"}; } - - private: - - static std::string - formatDuration(std::chrono::milliseconds duration) - { - auto totalSeconds = duration.count() / 1000; - auto hours = totalSeconds / 3600; - auto mins = (totalSeconds % 3600) / 60; - auto secs = totalSeconds % 60; - - if (hours > 0) { - return std::format("{}:{:02}:{:02}", hours, mins, secs); - } - return std::format("{}:{:02}", mins, secs); - } }; } // namespace Echoion::Core diff --git a/include/echoion/core/commands/PauseCommand.hpp b/include/echoion/core/commands/PauseCommand.hpp index 7e0c106..026a39a 100644 --- a/include/echoion/core/commands/PauseCommand.hpp +++ b/include/echoion/core/commands/PauseCommand.hpp @@ -16,32 +16,34 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->pause(); if (!result) { - Void::Log::error("PauseCommand", "{}", - std::format("Pause command failed: {}", - result.error().message)); + Void::Log::error("PauseCommand", "{}", + std::format("Pause command failed: {}", + result.error().message)); if (result.error().code == Api::ErrorCode::InvalidArgument) { - ctx.reply("Nothing is playing right now."); + ctx.reply(ctx.tr("Nothing is playing right now.")); } else { - ctx.reply( - "Couldn't pause playback. Please try again."); + ctx.reply(ctx.tr( + "Couldn't pause playback. Please try again.")); } return; } - ctx.reply("Playback paused."); + ctx.reply(ctx.tr("Playback paused.")); } catch (const std::exception& e) { - Void::Log::error("PauseCommand", "{}", + Void::Log::error( + "PauseCommand", "{}", std::format("Pause command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/PlayCommand.hpp b/include/echoion/core/commands/PlayCommand.hpp index c362c5f..6066247 100644 --- a/include/echoion/core/commands/PlayCommand.hpp +++ b/include/echoion/core/commands/PlayCommand.hpp @@ -22,16 +22,17 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply("The music service is currently unavailable. " - "Please try again later."); + ctx.reply(ctx.tr( + "The music service is currently unavailable. " + "Please try again later.")); return; } if (ctx.args.empty()) { - ctx.reply(std::format( - "Usage: {} \nExample: {} never " - "gonna give you up", - label(), label())); + ctx.reply(ctx.trf("Usage: {} \nExample: {} never " + "gonna give you up", + label(), label())); return; } @@ -39,50 +40,57 @@ namespace Echoion::Core if (ctx.args.find("http") == 0) { auto result = manager->play(ctx.args, ctx.clientId); if (!result) { - Void::Log::error("PlayCommand", "{}", - std::format("Play URL failed '{}': {}", ctx.args, - result.error().message)); + Void::Log::error( + "PlayCommand", "{}", + std::format("Play URL failed '{}': {}", + ctx.args, result.error().message)); switch (result.error().code) { case Api::ErrorCode::NetworkError: - ctx.reply("Couldn't connect to that URL. " - "Please check and try again."); + ctx.reply( + ctx.tr("Couldn't connect to that URL. " + "Please check and try again.")); break; case Api::ErrorCode::InvalidUrl: - ctx.reply( - "That doesn't look like a valid URL."); + ctx.reply(ctx.tr( + "That doesn't look like a valid URL.")); break; default: - ctx.reply("Couldn't play that URL. Please " - "try again."); + ctx.reply( + ctx.tr("Couldn't play that URL. Please " + "try again.")); break; } return; } - ctx.reply(std::format("Added to queue: {}", *result)); + ctx.reply(ctx.trf("Added to queue: {}", *result)); return; } // Otherwise, search the chosen catalog(s). auto searchResult = manager->search(ctx.args, scope()); if (!searchResult) { - Void::Log::error("PlayCommand", "{}", + Void::Log::error( + "PlayCommand", "{}", std::format("Search failed for '{}': {}", ctx.args, searchResult.error().message)); if (searchResult.error().code == Api::ErrorCode::NetworkError) { - ctx.reply("Couldn't connect to search service. " - "Please check your connection."); + ctx.reply( + ctx.tr("Couldn't connect to search service. " + "Please check your connection.")); } else { - ctx.reply("Search failed. Please try again."); + ctx.reply( + ctx.tr("Search failed. Please try again.")); } return; } if (searchResult->tracks.empty()) { - ctx.reply("No results found. Try different keywords."); + ctx.reply(ctx.tr( + "No results found. Try different keywords.")); return; } @@ -92,11 +100,12 @@ namespace Echoion::Core auto playResult = manager->queueTrack(track, ctx.clientId); if (!playResult) { - Void::Log::error("PlayCommand", "{}", + Void::Log::error( + "PlayCommand", "{}", std::format("Queue failed: {}", playResult.error().message)); - ctx.reply( - "Couldn't add that track. Please try again."); + ctx.reply(ctx.tr( + "Couldn't add that track. Please try again.")); return; } @@ -105,7 +114,7 @@ namespace Echoion::Core displayText = std::format("{} by {}", track.title, track.artist); } - ctx.reply(std::format( + ctx.reply(ctx.trf( "Added to queue: {}", markdownLink(displayText, trackLinkUrl(track)))); return; @@ -115,9 +124,10 @@ namespace Echoion::Core manager->storePendingSearch(ctx.clientId, searchResult->tracks); - std::string msg = std::format( - "Multiple results \xe2\x80\x94 use {}select :\n\n", - ctx.prefix); + std::string msg = + std::format("Multiple results \xe2\x80\x94 use " + "{}select :\n\n", + ctx.prefix); for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) { const auto& track = searchResult->tracks[i]; @@ -139,10 +149,12 @@ namespace Echoion::Core ctx.reply(msg); } catch (const std::exception& e) { - Void::Log::error("PlayCommand", "{}", + Void::Log::error( + "PlayCommand", "{}", std::format("Play command exception: {}", e.what())); - ctx.reply("Something went wrong while trying to play. " - "Please try again."); + ctx.reply( + ctx.tr("Something went wrong while trying to play. " + "Please try again.")); } } diff --git a/include/echoion/core/commands/PlaylistCommand.hpp b/include/echoion/core/commands/PlaylistCommand.hpp index d66298c..b76d5fb 100644 --- a/include/echoion/core/commands/PlaylistCommand.hpp +++ b/include/echoion/core/commands/PlaylistCommand.hpp @@ -17,8 +17,8 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } @@ -26,23 +26,25 @@ namespace Echoion::Core // List playlists auto playlists = manager->getPlaylists(); if (!playlists) { - Void::Log::error("PlaylistCommand", "{}", + Void::Log::error( + "PlaylistCommand", "{}", std::format("Playlist list failed: {}", playlists.error().message)); - ctx.reply("Couldn't retrieve playlists."); + ctx.reply(ctx.tr("Couldn't retrieve playlists.")); return; } if (playlists->empty()) { - ctx.reply("No playlists available."); + ctx.reply(ctx.tr("No playlists available.")); return; } std::stringstream msg; - msg << "\xf0\x9f\x93\x81 Available playlists:\n"; + msg << ctx.tr( + "\xf0\x9f\x93\x81 Available playlists:\n"); for (const auto& pl : *playlists) { - msg << std::format("- {} ({} tracks)\n", pl.name, - pl.tracks.size()); + msg << ctx.trf("- {} ({} tracks)\n", pl.name, + pl.tracks.size()); } ctx.reply(msg.str()); @@ -51,29 +53,35 @@ namespace Echoion::Core auto result = manager->loadPlaylist( std::string(ctx.args), ctx.clientId); if (!result) { - Void::Log::error("PlaylistCommand", "{}", + Void::Log::error( + "PlaylistCommand", "{}", std::format("Playlist load failed: {}", result.error().message)); if (result.error().code == Api::ErrorCode::NotFound) { - ctx.reply("That playlist doesn't exist."); + ctx.reply( + ctx.tr("That playlist doesn't exist.")); } else { - ctx.reply("Couldn't load the playlist. Please " - "try again."); + ctx.reply( + ctx.tr("Couldn't load the playlist. Please " + "try again.")); } return; } - ctx.reply(std::format( + ctx.reply(ctx.trf( "Loading playlist '{}'... Tracks will be added to " "the queue as they are resolved.", ctx.args)); } } catch (const std::exception& e) { - Void::Log::error("PlaylistCommand", "{}", std::format( - "Playlist command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "PlaylistCommand", "{}", + std::format("Playlist command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/QueueCommand.hpp b/include/echoion/core/commands/QueueCommand.hpp index 2f7520a..0b2f9e1 100644 --- a/include/echoion/core/commands/QueueCommand.hpp +++ b/include/echoion/core/commands/QueueCommand.hpp @@ -17,8 +17,8 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } @@ -27,9 +27,10 @@ namespace Echoion::Core auto state = manager->getPlaybackState(); if (!queue) { - Void::Log::error("QueueCommand", "{}", std::format( - "Queue command failed: {}", queue.error().message)); - ctx.reply("Couldn't get queue information."); + Void::Log::error("QueueCommand", "{}", + std::format("Queue command failed: {}", + queue.error().message)); + ctx.reply(ctx.tr("Couldn't get queue information.")); return; } @@ -64,9 +65,16 @@ namespace Echoion::Core static_cast(queue->size())); std::stringstream msg; - msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/" - << totalPages << ")\n"; - + // Same at-a-glance status footer as !help and !np. A + // "Paused" marker is prepended since the queue view is + // where a stopped playhead is most relevant. + if (std::string status = playbackStatusLine(ctx); + !status.empty()) { + if (state && state->isPaused) { + msg << ctx.tr("\xe2\x8f\xb8 Paused\n"); + } + msg << status; + } // Current track if (current && current->has_value()) { const auto& track = current->value(); @@ -94,21 +102,20 @@ namespace Echoion::Core displayText = std::format( "{} by {}", trackInfo.title, trackInfo.artist); } - msg << std::format( + msg << ctx.trf( "\n**Now Playing:** {}{}\n", - markdownLink(displayText, - trackLinkUrl(trackInfo)), + markdownLink(displayText, trackLinkUrl(trackInfo)), timeStr); } // Queue if (queue->empty()) { - msg << std::format( + msg << ctx.trf( "\nThe queue is empty. Add songs with {}play !", ctx.prefix); } else { - msg << std::format("\n**Up Next ({} tracks):**\n", - queue->size()); + msg << ctx.trf("\n**Up Next ({} tracks):**\n", + queue->size()); for (int i = startIdx; i < endIdx; ++i) { const auto& entry = (*queue)[i]; const auto& trackInfo = entry.track; @@ -118,52 +125,38 @@ namespace Echoion::Core std::format("{} by {}", trackInfo.title, trackInfo.artist); } - msg << std::format( + msg << ctx.trf( "{}. {}", i + 1, markdownLink(displayText, trackLinkUrl(trackInfo))); if (trackInfo.duration.has_value()) { - msg << std::format( + msg << ctx.trf( " {} {}", kDot, formatDuration(*trackInfo.duration)); } if (!entry.addedBy.empty()) { - msg << std::format( - " (by {})", escapeMarkdown(entry.addedBy)); + msg << ctx.trf(" (by {})", + escapeMarkdown(entry.addedBy)); } - msg << "\n"; + msg << ctx.tr("\n"); } if (totalPages > 1) { - msg << std::format( - "\nUse {}queue to see more " - "(page {} of {})", - ctx.prefix, page, totalPages); + msg << ctx.trf("\nUse {}queue to see more " + "(page {} of {})", + ctx.prefix, page, totalPages); } } - // State indicators - if (state) { - msg << "\n\n"; - if (state->isPaused) { - msg << "\xe2\x8f\xb8 Paused | "; - } - if (state->shuffle) { - msg << "\xf0\x9f\x94\x80 Shuffle | "; - } - if (state->repeat) { - msg << "\xf0\x9f\x94\x81 Repeat | "; - } - msg << std::format( - "Volume: {}%", - static_cast(state->volume * 100)); - } - + msg << ctx.tr("\xf0\x9f\x93\x9c **Queue** (Page ") << page + << "/" << totalPages << ctx.tr(")\n"); ctx.reply(msg.str()); } catch (const std::exception& e) { - Void::Log::error("QueueCommand", "{}", + Void::Log::error( + "QueueCommand", "{}", std::format("Queue command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } @@ -183,22 +176,6 @@ namespace Echoion::Core { return {"q", "list"}; } - - private: - - static std::string - formatDuration(std::chrono::milliseconds duration) - { - auto totalSeconds = duration.count() / 1000; - auto hours = totalSeconds / 3600; - auto mins = (totalSeconds % 3600) / 60; - auto secs = totalSeconds % 60; - - if (hours > 0) { - return std::format("{}:{:02}:{:02}", hours, mins, secs); - } - return std::format("{}:{:02}", mins, secs); - } }; } // namespace Echoion::Core diff --git a/include/echoion/core/commands/ReloadCommand.hpp b/include/echoion/core/commands/ReloadCommand.hpp index 50186d9..bead2a5 100644 --- a/include/echoion/core/commands/ReloadCommand.hpp +++ b/include/echoion/core/commands/ReloadCommand.hpp @@ -22,15 +22,17 @@ namespace Echoion::Core if (auto core = ctx.service()) { auto result = core->reloadConfig(); if (result) { - ctx.reply("✅ Configuration reloaded. For a full core " - "reload, use the TS plugin menu."); + ctx.reply( + ctx.tr("✅ Configuration reloaded. For a full core " + "reload, use the TS plugin menu.")); } else { ctx.reply(std::string("❌ Config reload failed: ") + result.error().message); } } else { - ctx.reply("Reload is handled by the plugin. Use the TS " - "plugin menu to reload the core."); + ctx.reply( + ctx.tr("Reload is handled by the plugin. Use the TS " + "plugin menu to reload the core.")); } } diff --git a/include/echoion/core/commands/ReloadConfigCommand.hpp b/include/echoion/core/commands/ReloadConfigCommand.hpp index 38c15f5..79d6770 100644 --- a/include/echoion/core/commands/ReloadConfigCommand.hpp +++ b/include/echoion/core/commands/ReloadConfigCommand.hpp @@ -17,21 +17,27 @@ namespace Echoion::Core try { auto core = ctx.service(); if (!core) { - ctx.reply("Config reload is unavailable right now."); + ctx.reply( + ctx.tr("Config reload is unavailable right now.")); return; } auto result = core->reloadConfig(); if (result) { - ctx.reply("✅ Configuration reloaded from disk."); + ctx.reply( + ctx.tr("✅ Configuration reloaded from disk.")); } else { ctx.reply(std::string("❌ Failed to reload config: ") + result.error().message); } } catch (const std::exception& e) { - Void::Log::error("ReloadConfigCommand", "{}", std::format( - "ReloadConfig command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "ReloadConfigCommand", + "{}", + std::format("ReloadConfig command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/RemoveCommand.hpp b/include/echoion/core/commands/RemoveCommand.hpp index ce619f5..4ff0b88 100644 --- a/include/echoion/core/commands/RemoveCommand.hpp +++ b/include/echoion/core/commands/RemoveCommand.hpp @@ -17,16 +17,16 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } if (ctx.args.empty()) { ctx.reply( - std::format("Usage: remove \nUse {}queue " - "to see track positions.", - ctx.prefix)); + ctx.trf("Usage: remove \nUse {}queue " + "to see track positions.", + ctx.prefix)); return; } @@ -36,35 +36,40 @@ namespace Echoion::Core ctx.args.data() + ctx.args.size(), position); if (result.ec != std::errc() || position == 0) { - ctx.reply("Please provide a valid position number " - "(starting from 1)."); + ctx.reply( + ctx.tr("Please provide a valid position number " + "(starting from 1).")); return; } auto remResult = manager->removeFromQueue( position - 1); // Convert to 0-based if (!remResult) { - Void::Log::error("RemoveCommand", "{}", + Void::Log::error( + "RemoveCommand", "{}", std::format("Remove command failed: {}", remResult.error().message)); if (remResult.error().code == Api::ErrorCode::NotFound) { - ctx.reply( - "That position doesn't exist in the queue."); + ctx.reply(ctx.tr( + "That position doesn't exist in the queue.")); } else { - ctx.reply("Couldn't remove that track. Please try " - "again."); + ctx.reply( + ctx.tr("Couldn't remove that track. Please try " + "again.")); } return; } ctx.reply( - std::format("Removed track at position {}.", position)); + ctx.trf("Removed track at position {}.", position)); } catch (const std::exception& e) { - Void::Log::error("RemoveCommand", "{}", + Void::Log::error( + "RemoveCommand", "{}", std::format("Remove command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/RepeatCommand.hpp b/include/echoion/core/commands/RepeatCommand.hpp index 9e5cc5b..c70dfbb 100644 --- a/include/echoion/core/commands/RepeatCommand.hpp +++ b/include/echoion/core/commands/RepeatCommand.hpp @@ -16,26 +16,31 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->toggleRepeat(); if (!result) { - Void::Log::error("RepeatCommand", "{}", + Void::Log::error( + "RepeatCommand", "{}", std::format("Repeat command failed: {}", result.error().message)); - ctx.reply("Couldn't toggle repeat. Please try again."); + ctx.reply(ctx.tr( + "Couldn't toggle repeat. Please try again.")); return; } - ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON." - : "Repeat is now OFF."); + ctx.reply(*result + ? ctx.tr("\xf0\x9f\x94\x81 Repeat is now ON.") + : ctx.tr("Repeat is now OFF.")); } catch (const std::exception& e) { - Void::Log::error("RepeatCommand", "{}", + Void::Log::error( + "RepeatCommand", "{}", std::format("Repeat command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/ResumeCommand.hpp b/include/echoion/core/commands/ResumeCommand.hpp index b8d54e7..7cac76a 100644 --- a/include/echoion/core/commands/ResumeCommand.hpp +++ b/include/echoion/core/commands/ResumeCommand.hpp @@ -16,32 +16,36 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->resume(); if (!result) { - Void::Log::error("ResumeCommand", "{}", + Void::Log::error( + "ResumeCommand", "{}", std::format("Resume command failed: {}", result.error().message)); if (result.error().code == Api::ErrorCode::InvalidArgument) { - ctx.reply("Playback isn't paused right now."); - } else { ctx.reply( - "Couldn't resume playback. Please try again."); + ctx.tr("Playback isn't paused right now.")); + } else { + ctx.reply(ctx.tr( + "Couldn't resume playback. Please try again.")); } return; } - ctx.reply("Playback resumed."); + ctx.reply(ctx.tr("Playback resumed.")); } catch (const std::exception& e) { - Void::Log::error("ResumeCommand", "{}", + Void::Log::error( + "ResumeCommand", "{}", std::format("Resume command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SearchCommand.hpp b/include/echoion/core/commands/SearchCommand.hpp index 45d853f..2f6047d 100644 --- a/include/echoion/core/commands/SearchCommand.hpp +++ b/include/echoion/core/commands/SearchCommand.hpp @@ -20,34 +20,38 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } if (ctx.args.empty()) { - ctx.reply(std::format("Usage: {} ", label())); + ctx.reply(ctx.trf("Usage: {} ", label())); return; } auto result = manager->search(ctx.args, scope()); if (!result) { - Void::Log::error("SearchCommand", "{}", + Void::Log::error( + "SearchCommand", "{}", std::format("Search failed for '{}': {}", ctx.args, result.error().message)); if (result.error().code == Api::ErrorCode::NetworkError) { - ctx.reply("Couldn't connect to search service. " - "Please check your connection."); + ctx.reply( + ctx.tr("Couldn't connect to search service. " + "Please check your connection.")); } else { - ctx.reply("Search failed. Please try again later."); + ctx.reply(ctx.tr( + "Search failed. Please try again later.")); } return; } if (result->tracks.empty()) { - ctx.reply("No results found. Try different keywords."); + ctx.reply(ctx.tr( + "No results found. Try different keywords.")); return; } @@ -55,7 +59,8 @@ namespace Echoion::Core manager->storePendingSearch(ctx.clientId, result->tracks); std::stringstream msg; - msg << "Search results for \"" << ctx.args << "\":\n\n"; + msg << ctx.tr("Search results for \"") << ctx.args + << ctx.tr("\":\n\n"); for (size_t i = 0; i < result->tracks.size() && i < 5; ++i) { @@ -67,26 +72,27 @@ namespace Echoion::Core } // [escaped title](url) · duration (no [] around the // duration: TeamSpeak parses [..] as a link reference). - msg << std::format( + msg << ctx.trf( "{}. {}", i + 1, markdownLink(displayText, trackLinkUrl(track))); if (track.duration.has_value()) { msg << " " << kDot << " " << formatDuration(*track.duration); } - msg << "\n"; + msg << ctx.tr("\n"); } - msg << std::format( - "\nUse {}select to play a result.", - ctx.prefix); + msg << ctx.trf("\nUse {}select to play a result.", + ctx.prefix); ctx.reply(msg.str()); } catch (const std::exception& e) { - Void::Log::error("SearchCommand", "{}", + Void::Log::error( + "SearchCommand", "{}", std::format("Search command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SeekCommand.hpp b/include/echoion/core/commands/SeekCommand.hpp index 9a90b14..eae645f 100644 --- a/include/echoion/core/commands/SeekCommand.hpp +++ b/include/echoion/core/commands/SeekCommand.hpp @@ -18,16 +18,16 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } if (ctx.args.empty()) { - ctx.reply( + ctx.reply(ctx.tr( "Usage: seek <+/-seconds>\nExamples:\n seek +30 " "(skip forward 30s)\n seek -10 (skip back 10s)\n " - "seek 60 (jump to 1 minute mark)"); + "seek 60 (jump to 1 minute mark)")); return; } @@ -51,9 +51,9 @@ namespace Echoion::Core auto parseResult = std::from_chars( arg.data(), arg.data() + arg.size(), seconds); if (parseResult.ec != std::errc() || seconds < 0) { - ctx.reply( + ctx.reply(ctx.tr( "Please provide a valid number of " - "seconds.\nExamples: seek +30, seek -10, seek 60"); + "seconds.\nExamples: seek +30, seek -10, seek 60")); return; } @@ -64,8 +64,8 @@ namespace Echoion::Core // Get current position from playback state auto state = manager->getPlaybackState(); if (!state) { - ctx.reply( - "Unable to get current playback position."); + ctx.reply(ctx.tr( + "Unable to get current playback position.")); return; } @@ -94,32 +94,37 @@ namespace Echoion::Core auto result = manager->seek(targetPosition); if (!result) { - Void::Log::error("SeekCommand", "{}", std::format("Seek command failed: {}", - result.error().message)); + Void::Log::error("SeekCommand", "{}", + std::format("Seek command failed: {}", + result.error().message)); if (result.error().code == Api::ErrorCode::InvalidArgument) { - ctx.reply("Nothing is playing right now."); + ctx.reply(ctx.tr("Nothing is playing right now.")); } else if (result.error().code == Api::ErrorCode::NotSupported) { - ctx.reply("This track doesn't support seeking."); + ctx.reply( + ctx.tr("This track doesn't support seeking.")); } else { - ctx.reply("Couldn't seek. Please try again."); + ctx.reply( + ctx.tr("Couldn't seek. Please try again.")); } return; } if (relative) { - ctx.reply(std::format( - "Seeked {} from current position.", positionStr)); + ctx.reply(ctx.trf("Seeked {} from current position.", + positionStr)); } else { ctx.reply( - std::format("Seeked to position {}.", positionStr)); + ctx.trf("Seeked to position {}.", positionStr)); } } catch (const std::exception& e) { - Void::Log::error("SeekCommand", "{}", + Void::Log::error( + "SeekCommand", "{}", std::format("Seek command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SelectCommand.hpp b/include/echoion/core/commands/SelectCommand.hpp index 2f16f0a..12d723a 100644 --- a/include/echoion/core/commands/SelectCommand.hpp +++ b/include/echoion/core/commands/SelectCommand.hpp @@ -17,14 +17,15 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } if (ctx.args.empty()) { - ctx.reply("Usage: select \nSelect a track from " - "your last search results."); + ctx.reply(ctx.tr( + "Usage: select \nSelect a track from " + "your last search results.")); return; } @@ -35,8 +36,8 @@ namespace Echoion::Core ctx.args.data() + ctx.args.size(), index); if (result.ec != std::errc() || index == 0) { - ctx.reply( - "Please provide a valid number (1, 2, 3, etc.)."); + ctx.reply(ctx.tr( + "Please provide a valid number (1, 2, 3, etc.).")); return; } @@ -45,19 +46,23 @@ namespace Echoion::Core ctx.clientId, index, invokerName); if (!selectResult) { - Void::Log::error("SelectCommand", "{}", std::format( - "Select failed for client {} index {}: {}", - ctx.clientId, index, selectResult.error().message)); + Void::Log::error( + "SelectCommand", "{}", + std::format( + "Select failed for client {} index {}: {}", + ctx.clientId, index, + selectResult.error().message)); if (selectResult.error().code == Api::ErrorCode::NotFound) { - ctx.reply(std::format( - "No search results found. Use {}play " - " to search first.", - ctx.prefix)); + ctx.reply( + ctx.trf("No search results found. Use {}play " + " to search first.", + ctx.prefix)); } else { - ctx.reply("Couldn't select that track. Please try " - "again."); + ctx.reply( + ctx.tr("Couldn't select that track. Please try " + "again.")); } return; } @@ -65,9 +70,11 @@ namespace Echoion::Core ctx.reply(*selectResult); } catch (const std::exception& e) { - Void::Log::error("SelectCommand", "{}", + Void::Log::error( + "SelectCommand", "{}", std::format("Select command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/ShuffleCommand.hpp b/include/echoion/core/commands/ShuffleCommand.hpp index 8b2c830..1884874 100644 --- a/include/echoion/core/commands/ShuffleCommand.hpp +++ b/include/echoion/core/commands/ShuffleCommand.hpp @@ -16,19 +16,29 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } // Actually shuffle the queue (not just toggle mode) - manager->shuffleQueue(); + if (auto result = manager->shuffleQueue(); !result) { + Void::Log::warn( + "ShuffleCommand", "{}", + std::format("Shuffle failed: {}", + result.error().message)); + ctx.reply(ctx.tr( + "Something went wrong. Please try again.")); + return; + } - ctx.reply("\xf0\x9f\x94\x80 Queue shuffled!"); + ctx.reply(ctx.tr("\xf0\x9f\x94\x80 Queue shuffled!")); } catch (const std::exception& e) { - Void::Log::error("ShuffleCommand", "{}", + Void::Log::error( + "ShuffleCommand", "{}", std::format("Shuffle command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SkipCommand.hpp b/include/echoion/core/commands/SkipCommand.hpp index b4382f7..0cd0da3 100644 --- a/include/echoion/core/commands/SkipCommand.hpp +++ b/include/echoion/core/commands/SkipCommand.hpp @@ -17,8 +17,8 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } @@ -29,35 +29,39 @@ namespace Echoion::Core ctx.args.data() + ctx.args.size(), count); if (result.ec != std::errc() || count == 0) { - ctx.reply( - "Please provide a valid number (1 or more)."); + ctx.reply(ctx.tr( + "Please provide a valid number (1 or more).")); return; } } auto result = manager->skip(count); if (!result) { - Void::Log::error("SkipCommand", "{}", std::format("Skip command failed: {}", - result.error().message)); + Void::Log::error("SkipCommand", "{}", + std::format("Skip command failed: {}", + result.error().message)); if (result.error().code == Api::ErrorCode::NotFound) { - ctx.reply( - "No more tracks in the queue to skip to."); + ctx.reply(ctx.tr( + "No more tracks in the queue to skip to.")); } else { - ctx.reply("Couldn't skip. Please try again."); + ctx.reply( + ctx.tr("Couldn't skip. Please try again.")); } return; } if (count == 1) { - ctx.reply("Skipped to next track."); + ctx.reply(ctx.tr("Skipped to next track.")); } else { - ctx.reply(std::format("Skipped {} tracks.", count)); + ctx.reply(ctx.trf("Skipped {} tracks.", count)); } } catch (const std::exception& e) { - Void::Log::error("SkipCommand", "{}", + Void::Log::error( + "SkipCommand", "{}", std::format("Skip command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SoundCloudPlayCommand.hpp b/include/echoion/core/commands/SoundCloudPlayCommand.hpp new file mode 100644 index 0000000..ab865e9 --- /dev/null +++ b/include/echoion/core/commands/SoundCloudPlayCommand.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include "PlayCommand.hpp" + +namespace Echoion::Core +{ + + // !psc / !playsc — play from SoundCloud only (URL or search). + class SoundCloudPlayCommand : public PlayCommandBase + { + public: + + std::string_view getDescription() const override + { + return "Plays from SoundCloud only (URL or search)."; + } + std::string_view getUsage() const override + { + return ""; + } + std::vector getAliases() const override + { + return {"playsc"}; + } + + protected: + + MusicManager::SearchScope scope() const override + { + return MusicManager::SearchScope::SoundCloud; + } + std::string_view label() const override { return "psc"; } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/SoundCloudSearchCommand.hpp b/include/echoion/core/commands/SoundCloudSearchCommand.hpp new file mode 100644 index 0000000..304f5e5 --- /dev/null +++ b/include/echoion/core/commands/SoundCloudSearchCommand.hpp @@ -0,0 +1,32 @@ +#pragma once + +#include "SearchCommand.hpp" + +namespace Echoion::Core +{ + + // !soundcloud / !sc — search SoundCloud only. + class SoundCloudSearchCommand : public SearchCommandBase + { + public: + + std::string_view getDescription() const override + { + return "Search SoundCloud only for tracks."; + } + std::string_view getUsage() const override { return ""; } + std::vector getAliases() const override + { + return {"sc", "scloud"}; + } + + protected: + + MusicManager::SearchScope scope() const override + { + return MusicManager::SearchScope::SoundCloud; + } + std::string_view label() const override { return "soundcloud"; } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/StatsCommand.hpp b/include/echoion/core/commands/StatsCommand.hpp index 83ce9d5..f381d1a 100644 --- a/include/echoion/core/commands/StatsCommand.hpp +++ b/include/echoion/core/commands/StatsCommand.hpp @@ -16,18 +16,18 @@ namespace Echoion::Core { auto db = ctx.service(); if (!db) { - ctx.reply("Statistics are unavailable (no database)."); + ctx.reply( + ctx.tr("Statistics are unavailable (no database).")); return; } auto stats = db->getStatistics(0); if (!stats) { - ctx.reply("Couldn't read playback statistics."); + ctx.reply(ctx.tr("Couldn't read playback statistics.")); return; } - const auto totalMinutes = - stats->totalPlaytimeMs / 1000 / 60; + const auto totalMinutes = stats->totalPlaytimeMs / 1000 / 60; std::string msg = std::format( "\xf0\x9f\x93\x8a Plays: {} {} Unique tracks: {} {} " "Playtime: {}h {}m", diff --git a/include/echoion/core/commands/StopCommand.hpp b/include/echoion/core/commands/StopCommand.hpp index 19faf2d..353432d 100644 --- a/include/echoion/core/commands/StopCommand.hpp +++ b/include/echoion/core/commands/StopCommand.hpp @@ -16,24 +16,28 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->stop(); if (!result) { - Void::Log::error("StopCommand", "{}", std::format("Stop command failed: {}", - result.error().message)); - ctx.reply("Couldn't stop playback. Please try again."); + Void::Log::error("StopCommand", "{}", + std::format("Stop command failed: {}", + result.error().message)); + ctx.reply(ctx.tr( + "Couldn't stop playback. Please try again.")); return; } - ctx.reply("Playback stopped and queue cleared."); + ctx.reply(ctx.tr("Playback stopped and queue cleared.")); } catch (const std::exception& e) { - Void::Log::error("StopCommand", "{}", + Void::Log::error( + "StopCommand", "{}", std::format("Stop command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SubscribeCommand.hpp b/include/echoion/core/commands/SubscribeCommand.hpp index b96dc04..5985525 100644 --- a/include/echoion/core/commands/SubscribeCommand.hpp +++ b/include/echoion/core/commands/SubscribeCommand.hpp @@ -16,24 +16,31 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->subscribe(ctx.clientId); if (!result) { - Void::Log::error("SubscribeCommand", "{}", std::format("Subscribe failed: {}", - result.error().message)); - ctx.reply("Couldn't subscribe you. Please try again."); + Void::Log::error("SubscribeCommand", + "{}", + std::format("Subscribe failed: {}", + result.error().message)); + ctx.reply(ctx.tr( + "Couldn't subscribe you. Please try again.")); return; } ctx.reply(*result); } catch (const std::exception& e) { - Void::Log::error("SubscribeCommand", "{}", std::format( - "Subscribe command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "SubscribeCommand", + "{}", + std::format("Subscribe command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/SubscribersCommand.hpp b/include/echoion/core/commands/SubscribersCommand.hpp index aa973b2..cb98474 100644 --- a/include/echoion/core/commands/SubscribersCommand.hpp +++ b/include/echoion/core/commands/SubscribersCommand.hpp @@ -1,8 +1,8 @@ #pragma once #include "Command.hpp" -#include #include "echoion/core/MusicManager.hpp" +#include #include #include #include @@ -19,8 +19,8 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } @@ -28,8 +28,8 @@ namespace Echoion::Core auto onlineUids = manager->getOnlineSubscriberUids(); if (subscribers.empty()) { - ctx.reply( - "No subscribers. Use !subscribe to receive audio."); + ctx.reply(ctx.tr("No subscribers. Use !subscribe to " + "receive audio.")); return; } @@ -46,45 +46,48 @@ namespace Echoion::Core } std::stringstream msg; - msg << "\xf0\x9f\x93\x8b **Subscribed Users** (" - << subscribers.size() << " total)\n"; - msg << "\xf0\x9f\x9f\xa2 Online: " << online.size() - << " | \xe2\x9a\xaa Offline: " << offline.size() - << "\n\n"; + msg << ctx.tr("\xf0\x9f\x93\x8b **Subscribed Users** (") + << subscribers.size() << ctx.tr(" total)\n"); + msg << ctx.tr("\xf0\x9f\x9f\xa2 Online: ") << online.size() + << ctx.tr(" | \xe2\x9a\xaa Offline: ") << offline.size() + << ctx.tr("\n\n"); // Online subscribers if (!online.empty()) { - msg << "**\xf0\x9f\x9f\xa2 Online:**\n"; + msg << ctx.tr("**\xf0\x9f\x9f\xa2 Online:**\n"); for (size_t i = 0; i < online.size(); ++i) { const auto& sub = online[i]; - msg << std::format("{}. **{}**\n", i + 1, - sub.nickname); - msg << std::format(" UID: `{}`\n", sub.uid); + msg << ctx.trf("{}. **{}**\n", i + 1, sub.nickname); + msg << ctx.trf(" UID: `{}`\n", sub.uid); } - msg << "\n"; + msg << ctx.tr("\n"); } // Offline subscribers if (!offline.empty()) { - msg << "**\xe2\x9a\xaa Offline:**\n"; + msg << ctx.tr("**\xe2\x9a\xaa Offline:**\n"); for (size_t i = 0; i < offline.size(); ++i) { const auto& sub = offline[i]; - msg << std::format("{}. **{}**\n", i + 1, - sub.nickname); - msg << std::format(" UID: `{}`\n", sub.uid); + msg << ctx.trf("{}. **{}**\n", i + 1, sub.nickname); + msg << ctx.trf(" UID: `{}`\n", sub.uid); } - msg << "\n"; + msg << ctx.tr("\n"); } - msg << "Use `!unsubscribeid ` to remove a specific " - "subscriber.\n"; - msg << "Use `!unsubscribeall` to remove all subscribers."; + msg << ctx.tr( + "Use `!unsubscribeid ` to remove a specific " + "subscriber.\n"); + msg << ctx.tr( + "Use `!unsubscribeall` to remove all subscribers."); ctx.reply(msg.str()); } catch (const std::exception& e) { - Void::Log::error("SubscribersCommand", "{}", std::format( - "Subscribers command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "SubscribersCommand", "{}", + std::format("Subscribers command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/UnsubscribeAllCommand.hpp b/include/echoion/core/commands/UnsubscribeAllCommand.hpp index 17323a9..926a648 100644 --- a/include/echoion/core/commands/UnsubscribeAllCommand.hpp +++ b/include/echoion/core/commands/UnsubscribeAllCommand.hpp @@ -1,8 +1,8 @@ #pragma once #include "Command.hpp" -#include #include "echoion/core/MusicManager.hpp" +#include #include namespace Echoion::Core @@ -17,27 +17,31 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->clearAllSubscriptions(); if (!result) { - Void::Log::error("UnsubscribeAllCommand", "{}", + Void::Log::error( + "UnsubscribeAllCommand", "{}", std::format("Unsubscribe all failed: {}", result.error().message)); - ctx.reply( - "Couldn't clear subscriptions. Please try again."); + ctx.reply(ctx.tr( + "Couldn't clear subscriptions. Please try again.")); return; } ctx.reply(*result); } catch (const std::exception& e) { - Void::Log::error("UnsubscribeAllCommand", "{}", std::format( - "Unsubscribeall command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "UnsubscribeAllCommand", "{}", + std::format("Unsubscribeall command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/UnsubscribeCommand.hpp b/include/echoion/core/commands/UnsubscribeCommand.hpp index 580306c..aa95f49 100644 --- a/include/echoion/core/commands/UnsubscribeCommand.hpp +++ b/include/echoion/core/commands/UnsubscribeCommand.hpp @@ -16,25 +16,31 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } auto result = manager->unsubscribe(ctx.clientId); if (!result) { - Void::Log::error("UnsubscribeCommand", "{}", std::format("Unsubscribe failed: {}", - result.error().message)); - ctx.reply( - "Couldn't unsubscribe you. Please try again."); + Void::Log::error("UnsubscribeCommand", + "{}", + std::format("Unsubscribe failed: {}", + result.error().message)); + ctx.reply(ctx.tr( + "Couldn't unsubscribe you. Please try again.")); return; } ctx.reply(*result); } catch (const std::exception& e) { - Void::Log::error("UnsubscribeCommand", "{}", std::format( - "Unsubscribe command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "UnsubscribeCommand", + "{}", + std::format("Unsubscribe command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/UnsubscribeIdCommand.hpp b/include/echoion/core/commands/UnsubscribeIdCommand.hpp index f13ab9e..89cf3be 100644 --- a/include/echoion/core/commands/UnsubscribeIdCommand.hpp +++ b/include/echoion/core/commands/UnsubscribeIdCommand.hpp @@ -1,8 +1,8 @@ #pragma once #include "Command.hpp" -#include #include "echoion/core/MusicManager.hpp" +#include #include namespace Echoion::Core @@ -17,14 +17,15 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } if (ctx.args.empty()) { - ctx.reply("Please provide a user UID. Use !subscribers " - "to see UIDs."); + ctx.reply(ctx.tr( + "Please provide a user UID. Use !subscribers " + "to see UIDs.")); return; } @@ -32,19 +33,23 @@ namespace Echoion::Core auto result = manager->unsubscribeByUid(uid); if (!result) { - Void::Log::error("UnsubscribeIdCommand", "{}", + Void::Log::error( + "UnsubscribeIdCommand", "{}", std::format("Unsubscribe by ID failed: {}", result.error().message)); - ctx.reply( - "Couldn't unsubscribe user. Please try again."); + ctx.reply(ctx.tr( + "Couldn't unsubscribe user. Please try again.")); return; } ctx.reply(*result); } catch (const std::exception& e) { - Void::Log::error("UnsubscribeIdCommand", "{}", std::format( - "Unsubscribeid command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + Void::Log::error( + "UnsubscribeIdCommand", "{}", + std::format("Unsubscribeid command exception: {}", + e.what())); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/commands/VolumeCommand.hpp b/include/echoion/core/commands/VolumeCommand.hpp index f9e8154..74cb69d 100644 --- a/include/echoion/core/commands/VolumeCommand.hpp +++ b/include/echoion/core/commands/VolumeCommand.hpp @@ -17,8 +17,8 @@ namespace Echoion::Core try { auto manager = ctx.musicManager.lock(); if (!manager) { - ctx.reply( - "The music service is currently unavailable."); + ctx.reply(ctx.tr( + "The music service is currently unavailable.")); return; } @@ -26,11 +26,11 @@ namespace Echoion::Core // Show current volume auto state = manager->getPlaybackState(); if (state) { - ctx.reply(std::format( - "Current volume: {}%", - static_cast(state->volume * 100))); + ctx.reply( + ctx.trf("Current volume: {}%", + static_cast(state->volume * 100))); } else { - ctx.reply("Unable to get current volume."); + ctx.reply(ctx.tr("Unable to get current volume.")); } return; } @@ -42,22 +42,25 @@ namespace Echoion::Core ctx.args.data() + ctx.args.size(), volumePercent); if (result.ec != std::errc()) { - ctx.reply("Please provide a valid number (0-100)."); + ctx.reply( + ctx.tr("Please provide a valid number (0-100).")); return; } if (volumePercent < 0 || volumePercent > 100) { - ctx.reply("Volume must be between 0 and 100."); + ctx.reply(ctx.tr("Volume must be between 0 and 100.")); return; } float volume = volumePercent / 100.0f; auto volResult = manager->setVolume(volume); if (!volResult) { - Void::Log::error("VolumeCommand", "{}", + Void::Log::error( + "VolumeCommand", "{}", std::format("Volume command failed: {}", volResult.error().message)); - ctx.reply("Couldn't change volume. Please try again."); + ctx.reply(ctx.tr( + "Couldn't change volume. Please try again.")); return; } @@ -71,12 +74,14 @@ namespace Echoion::Core : "\xe2\x96\x91"; // Full block / Light shade } - ctx.reply(std::format( - "Volume: {}% {}", volumePercent, indicator)); + ctx.reply( + ctx.trf("Volume: {}% {}", volumePercent, indicator)); } catch (const std::exception& e) { - Void::Log::error("VolumeCommand", "{}", + Void::Log::error( + "VolumeCommand", "{}", std::format("Volume command exception: {}", e.what())); - ctx.reply("Something went wrong. Please try again."); + ctx.reply( + ctx.tr("Something went wrong. Please try again.")); } } diff --git a/include/echoion/core/i18n/Localization.hpp b/include/echoion/core/i18n/Localization.hpp new file mode 100644 index 0000000..1e1c204 --- /dev/null +++ b/include/echoion/core/i18n/Localization.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include + +namespace Echoion::Core::I18n +{ + + // Languages the bot can reply in. English is the source language: every + // English string in the code is a valid translation key, so English never + // needs a table entry. + enum class Language { English, Russian }; + + // Parse a language code ("en"/"ru", case-insensitive). Unknown codes fall + // back to English so a bad config/kv value never breaks replies. + Language parseLanguage(std::string_view code); + + // The canonical code ("en"/"ru") — used as the kv_store / config value. + std::string_view languageCode(Language lang); + + // Human-readable, self-referential name ("English" / "Русский"). + std::string_view languageName(Language lang); + + // Translate an English source string to `lang`. Returns the original string + // unchanged when `lang` is English or no translation is registered, so a + // missing entry degrades gracefully to English rather than to an empty + // message. + std::string_view translate(std::string_view english, Language lang); + +} // namespace Echoion::Core::I18n diff --git a/include/echoion/core/playback/PlaybackEngine.hpp b/include/echoion/core/playback/PlaybackEngine.hpp index c3bd766..8afb852 100644 --- a/include/echoion/core/playback/PlaybackEngine.hpp +++ b/include/echoion/core/playback/PlaybackEngine.hpp @@ -63,9 +63,9 @@ namespace Echoion::Core virtual void onLocalFileDone(const std::string& path) = 0; // A track failed to resolve or open (before the engine advanced // past it). Called on the engine thread. - virtual void - onPlaybackError(const Api::Error& error, - const std::optional& entry) = 0; + virtual void onPlaybackError( + const Api::Error& error, + const std::optional& entry) = 0; }; // Real-time playback engine with gapless track transitions. @@ -86,9 +86,13 @@ namespace Echoion::Core static constexpr int CHUNK_MS = 20; static constexpr size_t SHORTS_PER_CHUNK = (SAMPLE_RATE * CHANNELS * CHUNK_MS) / 1000; - static constexpr auto PREFETCH_THRESHOLD = - std::chrono::seconds(15); + static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15); static constexpr int MAX_CONSECUTIVE_FAILURES = 5; + // Grace while a download-to-file retry is in flight. Must cover + // YouTubeClient::downloadAudioToFile's 180s wait — the normal + // resolve grace (bot.trackTimeout, ~10s) would skip the track + // long before the download lands. + static constexpr int64_t DOWNLOAD_GRACE_MS = 200'000; // How long the engine emits silence waiting for a late resolve // before it gives up on the track and advances. Configurable via @@ -119,8 +123,8 @@ namespace Echoion::Core explicit PlaybackEngine(IPlaybackHost& host); ~PlaybackEngine(); - Api::Result initialize( - const std::optional& proxy); + Api::Result + initialize(const std::optional& proxy); void shutdown(); void setProxyConfig( @@ -171,10 +175,14 @@ namespace Echoion::Core std::string url; bool isLocalFile = false; }; - struct CmdStart {}; - struct CmdPause {}; - struct CmdResume {}; - struct CmdStop {}; + struct CmdStart { + }; + struct CmdPause { + }; + struct CmdResume { + }; + struct CmdStop { + }; struct CmdSkip { uint32_t count = 1; }; @@ -188,8 +196,8 @@ namespace Echoion::Core bool paused = false; }; using Command = - std::variant; + std::variant; void post(Command cmd); @@ -202,10 +210,10 @@ namespace Echoion::Core struct DecoderSlot { enum class State { - Idle, // nothing assigned + Idle, // nothing assigned Resolving, // resolveFuture in flight Warming, // decoder open, pre-filling its queue - Active, // currently feeding the ring buffer + Active, // currently feeding the ring buffer }; State state = State::Idle; @@ -268,7 +276,9 @@ namespace Echoion::Core void clearFade() { fadeTail_.clear(); - fadePos_ = 0; + fadeTailPos_ = 0; + fadeEnvPos_ = 0; + fadeIncomingStarved_ = false; } // AGC gain for one chunk (updates the internal RMS/gain state). [[nodiscard]] float agcGainFor(std::size_t samples); @@ -302,8 +312,15 @@ namespace Echoion::Core // Crossfade state (engine thread only): the outgoing track's // remaining PCM, mixed into the incoming track equal-power. + // The tail cursor and the envelope advance independently: the + // tail plays continuously, while the envelope only progresses as + // incoming audio is actually delivered — so a network-starved + // incoming stream stretches the fade instead of being chopped + // against a racing envelope. std::vector fadeTail_; - std::size_t fadePos_ = 0; + std::size_t fadeTailPos_ = 0; + std::size_t fadeEnvPos_ = 0; + bool fadeIncomingStarved_ = false; // AGC state (engine thread only): EMA of mean-square level and // the current smoothed gain in dB. diff --git a/include/echoion/core/state/StateVersions.hpp b/include/echoion/core/state/StateVersions.hpp index 761ad21..10d540d 100644 --- a/include/echoion/core/state/StateVersions.hpp +++ b/include/echoion/core/state/StateVersions.hpp @@ -49,6 +49,7 @@ namespace Echoion::Core PlaybackState playback; bool hasPlayback = false; // Flag to indicate if playback state is valid + bool autoplay = false; // Radio mode on/off (persisted for restart) std::vector queue; std::vector sessions; diff --git a/include/echoion/core/util/Paginate.hpp b/include/echoion/core/util/Paginate.hpp new file mode 100644 index 0000000..2801f08 --- /dev/null +++ b/include/echoion/core/util/Paginate.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include +#include + +namespace Echoion::Core::Util +{ + + // Split `text` into pages no larger than `limit` bytes each, breaking on + // line boundaries where possible and hard-splitting over-long lines on a + // UTF-8 code-point boundary. Every returned page is <= `limit` bytes, so a + // caller can append a short footer and still stay under the transport's + // single-message cap. Returns a single element when `text` already fits. + std::vector paginate(std::string_view text, std::size_t limit); + +} // namespace Echoion::Core::Util diff --git a/src/AudioDecoder.cpp b/src/AudioDecoder.cpp index 995c403..04d94e5 100644 --- a/src/AudioDecoder.cpp +++ b/src/AudioDecoder.cpp @@ -59,9 +59,13 @@ namespace Echoion::Core "Decoder not initialized"); } - std::lock_guard lock(mutex_); + // Close the previous source BEFORE taking mutex_: closeSource() + // joins the decode thread, and that thread may be parked in a + // cv_.wait on mutex_ (backpressure or EOF park) — it needs the + // mutex to wake up and exit, so joining while holding it deadlocks. closeSource(); + std::lock_guard lock(mutex_); currentUrl_ = url; AVDictionary* options = nullptr; @@ -83,25 +87,31 @@ namespace Echoion::Core av_dict_set(&options, "reconnect", "1", 0); av_dict_set(&options, "reconnect_streamed", "1", 0); av_dict_set(&options, "reconnect_delay_max", "5", 0); - av_dict_set(&options, "analyzeduration", "20000000", 0); - av_dict_set(&options, "probesize", "10240000", 0); + // Keep the open cheap: find_stream_info reads min(analyzeduration, + // EOF) of media before returning, and openSource runs on the + // engine thread — large values froze playback for seconds when a + // proxied stream was opened for prefetch. Every source the bot + // plays (webm/opus, m4a, mp3, wav) carries codec parameters in its + // header, so 1s of analysis is plenty. + av_dict_set(&options, "analyzeduration", "1000000", 0); + av_dict_set(&options, "probesize", "1048576", 0); if (proxyConfig_.has_value() && proxyConfig_->enabled()) { - std::string proxyUrl; - if ((proxyConfig_->kind == Void::Net::ProxyConfig::Kind::Socks5)) { - // Use standard socks5:// scheme. FFmpeg http protocol handles - // this correctly. socks5h:// is often rejected by the http - // protocol handler, causing proxy bypass. - if (proxyConfig_->has_auth()) { - proxyUrl = std::format( - "socks5h://{}:{}@{}:{}", *proxyConfig_->username, - *proxyConfig_->password, proxyConfig_->host, - proxyConfig_->port); - } else { - proxyUrl = std::format("socks5://{}:{}", proxyConfig_->host, - proxyConfig_->port); - } + if (proxyConfig_->kind == Void::Net::ProxyConfig::Kind::Socks5) { + // FFmpeg has no SOCKS5 support (its http protocol only knows + // http_proxy / HTTP CONNECT). MusicManager rewrites SOCKS5 + // configs to the local Socks5HttpBridge before they reach the + // decoder; anything still arriving here would be silently + // ignored by FFmpeg, so skip it loudly instead. + Void::Log::warn( + "AudioDecoder", "{}", + std::format("SOCKS5 proxy {}:{} not usable by FFmpeg; " + "connecting directly", + proxyConfig_->host, proxyConfig_->port)); } else { + // The option is named http_proxy; FFmpeg drops unknown dict + // keys silently, so a wrong name means a direct connection. + std::string proxyUrl; if (proxyConfig_->has_auth()) { proxyUrl = std::format( "http://{}:{}@{}:{}", *proxyConfig_->username, @@ -111,22 +121,19 @@ namespace Echoion::Core proxyUrl = std::format("http://{}:{}", proxyConfig_->host, proxyConfig_->port); } + av_dict_set(&options, "http_proxy", proxyUrl.c_str(), 0); + Void::Log::info("AudioDecoder", "{}", + std::format("Using proxy for ffmpeg: {}:{}", + proxyConfig_->host, + proxyConfig_->port)); } - - av_dict_set(&options, "proxy", proxyUrl.c_str(), 0); - - av_dict_set( - &options, "protocol_whitelist", - "file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5", 0); - Void::Log::info("AudioDecoder", "{}", - std::format("Using proxy for ffmpeg: {}:{}", - proxyConfig_->host, - proxyConfig_->port)); } + // Log the URL truncated (googlevideo URLs run to ~1 KB); the "…" + // makes clear the full URL is what actually reaches FFmpeg. Void::Log::debug( "AudioDecoder", "{}", - std::format("Opening audio source: {}", url.substr(0, 80))); + std::format("Opening audio source: {}…", url.substr(0, 80))); // Allocate format context first (needed for interrupt callback) formatContext_ = avformat_alloc_context(); @@ -161,7 +168,7 @@ namespace Echoion::Core return Api::fail( Api::ErrorCode::AudioError, std::format( - "Failed to open audio source: {} (FFmpeg error {}: {})", + "Failed to open audio source: {}… (FFmpeg error {}: {})", url.substr(0, 80), ret, errbuf)); } Void::Log::debug("AudioDecoder", "{}", "avformat_open_input succeeded"); @@ -276,8 +283,7 @@ namespace Echoion::Core &swrContext_, &outLayout, AV_SAMPLE_FMT_S16, static_cast(outputSampleRate_), &codecContext_->ch_layout, codecContext_->sample_fmt, codecContext_->sample_rate, 0, nullptr); - if (codecContext_->sample_rate != - static_cast(outputSampleRate_)) { + if (codecContext_->sample_rate != static_cast(outputSampleRate_)) { av_opt_set_int(swrContext_, "linear_interp", 1, 0); av_opt_set_int(swrContext_, "filter_size", 256, 0); } @@ -288,13 +294,13 @@ namespace Echoion::Core } // Allocate output buffer for S16 samples (like reference) - constexpr int maxSamples = 4096; av_samples_alloc(&outputBuffer_, nullptr, - static_cast(outputChannels_), maxSamples, + static_cast(outputChannels_), MAX_OUT_SAMPLES, AV_SAMPLE_FMT_S16, 0); decoding_ = true; shouldExit_ = false; + seekRequestMs_ = -1; decodeThread_ = std::jthread(&AudioDecoder::decodeThread, this); Void::Log::info( @@ -321,6 +327,7 @@ namespace Echoion::Core currentUrl_.clear(); currentPositionMs_ = 0; eof_ = false; + seekRequestMs_ = -1; shouldExit_ = false; // Reset for next use } @@ -352,29 +359,81 @@ namespace Echoion::Core return true; } + std::size_t AudioDecoder::queuedSamples() const + { + std::lock_guard lock(mutex_); + std::size_t total = 0; + for (const auto& chunk : int16Queue_) { + total += chunk.size(); + } + return total; + } + + bool AudioDecoder::queueSaturated() const + { + std::lock_guard lock(mutex_); + return int16Queue_.size() >= MAX_INT16_QUEUE_SIZE; + } + Api::Result AudioDecoder::seek(std::chrono::milliseconds position) { if (!formatContext_ || audioStreamIndex_ < 0) { return Api::fail(Api::ErrorCode::AudioError, "No source open"); } + // No FFmpeg calls here: av_seek_frame() must not race the decode + // thread's av_read_frame(). Publish a request instead; the decode + // thread performs it in consumePendingSeek(). std::lock_guard lock(mutex_); + seekRequestMs_ = position.count(); + // Stop feeding stale pre-seek audio immediately (the decode thread + // clears again, authoritatively, once the seek is performed). + int16Queue_.clear(); + // Under mutex_ together with the request: the playback engine must + // never observe isFinished() while a seek is pending, and a decode + // thread parked at EOF must resume. + eof_ = false; + currentPositionMs_ = position.count(); + cv_.notify_all(); + return {}; + } - int64_t targetPts = position.count() * AV_TIME_BASE / 1000; - int ret = - av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD); - - if (ret < 0) { - return Api::fail(Api::ErrorCode::AudioError, "Seek failed"); + bool AudioDecoder::consumePendingSeek() + { + const int64_t targetMs = seekRequestMs_.exchange(-1); + if (targetMs < 0) { + return false; } + const int64_t targetPts = targetMs * AV_TIME_BASE / 1000; + int ret = + av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD); + if (ret < 0) { + char errbuf[256]; + av_strerror(ret, errbuf, sizeof(errbuf)); + Void::Log::error( + "AudioDecoder", "{}", + std::format("Seek to {}ms failed: {}", targetMs, errbuf)); + return true; // consumed; keep decoding from the current position + } + + // Also exits codec drain mode, so decoding can resume after EOF. avcodec_flush_buffers(codecContext_); - currentPositionMs_ = position.count(); - // Clear pending audio data - int16Queue_.clear(); + // Discard samples still buffered inside swresample from before the + // seek. + while (swr_convert(swrContext_, &outputBuffer_, MAX_OUT_SAMPLES, + nullptr, 0) > 0) { + } - return {}; + { + // Authoritative clear: drops any pre-seek chunk pushed between + // seek()'s clear and this point. + std::lock_guard lock(mutex_); + int16Queue_.clear(); + } + currentPositionMs_ = targetMs; + return true; } Api::Result AudioDecoder::getStreamInfo() const @@ -426,22 +485,64 @@ namespace Echoion::Core void AudioDecoder::decodeThread() { Void::Log::debug("AudioDecoder", "{}", "Decode thread started"); - constexpr int maxSamples = 4096; + + // Session loop: a session ends at EOF (or shutdown). Instead of + // exiting at EOF, park and wait for a seek request so a post-EOF + // seek can resume decoding on this same thread. + while (decoding_.load()) { + decodeSession(); + if (!decoding_.load()) { + break; + } + + // EOF park. eof_ and seekRequestMs_ are written together under + // mutex_ (here and in seek()), so the playback engine can never + // observe a stale isFinished() while a seek is pending. + std::unique_lock lock(mutex_); + if (seekRequestMs_.load() < 0) { + eof_ = true; // real end of track: no seek raced the flush + cv_.notify_all(); + } + cv_.wait(lock, [this] { + return seekRequestMs_.load() >= 0 || !decoding_; + }); + if (!decoding_) { + break; + } + eof_ = false; // resuming after a post-EOF seek + } + + // Unblock any blocking getNextChunk() callers on shutdown. + eof_ = true; + cv_.notify_all(); + Void::Log::debug("AudioDecoder", "{}", "Decode thread exiting"); + } + + void AudioDecoder::decodeSession() + { + constexpr int maxSamples = MAX_OUT_SAMPLES; int packetsRead = 0; int framesProduced = 0; while (decoding_.load()) { + // A pending seek is performed here, on the decode thread — the + // only thread allowed to touch the FFmpeg contexts. + consumePendingSeek(); + // Check queue size limit { std::unique_lock lock(mutex_); if (int16Queue_.size() >= MAX_INT16_QUEUE_SIZE) { cv_.wait(lock, [this] { return int16Queue_.size() < MAX_INT16_QUEUE_SIZE || - !decoding_; + !decoding_ || seekRequestMs_.load() >= 0; }); if (!decoding_) { break; } + if (seekRequestMs_.load() >= 0) { + continue; // perform the seek at the loop top + } } } @@ -481,8 +582,7 @@ namespace Echoion::Core if (frame_->pts != AV_NOPTS_VALUE) { AVRational tb = formatContext_->streams[audioStreamIndex_]->time_base; - currentPositionMs_ = - frame_->pts * 1000 * tb.num / tb.den; + currentPositionMs_ = frame_->pts * 1000 * tb.num / tb.den; } // Convert to S16 and queue. One output buffer holds at most @@ -496,8 +596,7 @@ namespace Echoion::Core int inSamples = frame_->nb_samples; while (true) { int outSamples = swr_convert(swrContext_, &outputBuffer_, - maxSamples, inData, - inSamples); + maxSamples, inData, inSamples); inData = nullptr; // input consumed on the first call inSamples = 0; if (outSamples <= 0) { @@ -505,7 +604,8 @@ namespace Echoion::Core } const size_t chunkSamples = outSamples * outputChannels_; - std::vector chunk = acquireChunkBuffer(chunkSamples); + std::vector chunk = + acquireChunkBuffer(chunkSamples); std::memcpy(chunk.data(), outputBuffer_, chunkSamples * sizeof(int16_t)); @@ -531,8 +631,7 @@ namespace Echoion::Core break; } - const uint8_t** inData = - const_cast(frame_->data); + const uint8_t** inData = const_cast(frame_->data); int inSamples = frame_->nb_samples; while (true) { int outSamples = swr_convert(swrContext_, &outputBuffer_, @@ -576,12 +675,12 @@ namespace Echoion::Core framesProduced++; } - eof_ = true; - cv_.notify_all(); - - Void::Log::info("AudioDecoder", "{}", - std::format("Decode finished. Packets: {}, Frames: {}", - packetsRead, framesProduced)); + // eof_ is set by decodeThread()'s EOF park (not here) so that a seek + // racing the final flush cannot leave a stale finished state. + Void::Log::info( + "AudioDecoder", "{}", + std::format("Decode session finished. Packets: {}, Frames: {}", + packetsRead, framesProduced)); } void AudioDecoder::cleanupFfmpeg() diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index b6bdf7c..45a804c 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -1,11 +1,16 @@ #include "echoion/core/CommandManager.hpp" -#include #include "echoion/core/MusicManager.hpp" #include "echoion/core/commands/Command.hpp" +#include "echoion/core/i18n/Localization.hpp" +#include "echoion/core/util/Paginate.hpp" #include +#include +#include #include +#include #include #include +#include #include namespace Echoion::Core @@ -26,11 +31,35 @@ namespace Echoion::Core auto prefix = manager_.getPrefix(); std::string helpMsg = - "# \xf0\x9f\x8e\xb5 Echoion Bot Help\n\n"; - helpMsg += std::format( - "> [!TIP]\n> Prefix is `{}` \xe2\x80\x94 e.g. " - "`{}play lofi`\n\n", - prefix, prefix); + std::string(ctx.tr("# \xf0\x9f\x8e\xb5 Echoion Bot " + "Help")) + + "\n\n"; + + // Playback status header so !help doubles as a quick + // readout of volume / shuffle / repeat / radio state. + // Shared with !np and !list via playbackStatusLine(). + if (std::string status = playbackStatusLine(ctx); + !status.empty()) { + helpMsg += status; + helpMsg += "\n\n"; + } + + helpMsg += + ctx.trf("> [!TIP]\n> Prefix is `{}` \xe2\x80\x94 e.g. " + "`{}play lofi`\n\n", + prefix, prefix); + + // Link the browser UI when it is enabled and has a public + // address (web.publicUrl). + if (manager_.serverConfig_ && + manager_.serverConfig_->web.enabled && + !manager_.serverConfig_->web.publicUrl.empty()) { + helpMsg += ctx.trf( + "> \xf0\x9f\x8c\x90 {}\n\n", + markdownLink(ctx.tr("Open the web interface"), + manager_.serverConfig_->web + .publicUrl)); + } // Get commands visible to this client auto visibleCommands = @@ -71,25 +100,27 @@ namespace Echoion::Core // Collapsible section per category. TeamSpeak uses the // markdown-it container syntax ":::details " … // ":::" (not HTML <details>). - helpMsg += std::format(":::details {} {} Commands\n\n", - categoryEmoji(cat), - toString(cat)); + helpMsg += ctx.trf(":::details {} {} Commands\n\n", + categoryEmoji(cat), + ctx.tr(toString(cat))); for (const auto& [name, cmd] : cmds) { if (!cmd->getUsage().empty()) { - helpMsg += std::format("`{}{}` {}\n", prefix, - name, cmd->getUsage()); + helpMsg += + std::format("`{}{}` {}\n", prefix, name, + ctx.tr(cmd->getUsage())); } else { helpMsg += std::format("`{}{}`\n", prefix, name); } - helpMsg += - std::format("> {}\n", cmd->getDescription()); + helpMsg += std::format( + "> {}\n", ctx.tr(cmd->getDescription())); auto aliases = cmd->getAliases(); if (!aliases.empty()) { - helpMsg += "> Aliases: "; + helpMsg += + std::format("> {} ", ctx.tr("Aliases:")); for (size_t i = 0; i < aliases.size(); ++i) { helpMsg += std::format("`{}{}`", prefix, aliases[i]); @@ -108,9 +139,11 @@ namespace Echoion::Core ctx.reply(helpMsg); } catch (const std::exception& e) { - Void::Log::error("CommandManager", "{}", + Void::Log::error( + "CommandManager", "{}", std::format("Help command exception: {}", e.what())); - ctx.reply("Couldn't generate help. Please try again."); + ctx.reply( + ctx.tr("Couldn't generate help. Please try again.")); } } @@ -130,6 +163,94 @@ namespace Echoion::Core { return {"h", "?", "commands"}; } + + // Help builds its own collapsible layout and is intentionally + // multi-message; never auto-paginate it. + bool autoPaginate() const override { return false; } + }; + + // --- Internal Page Navigator (!page / !next / !prev) --- + // mode 0 => "!page [n|next|prev]" (argument-driven); +1 => "!next"; + // -1 => "!prev". Re-sends a page of the caller's last long reply. + class CommandManager::PageNavCommand : public Command + { + CommandManager& manager_; + int mode_; + + public: + + PageNavCommand(CommandManager& mgr, int mode) + : manager_(mgr), mode_(mode) + { + } + + void execute(const CommandContext& ctx) override + { + std::optional<long> absolute; + int delta = mode_; + + if (mode_ == 0) { + std::string arg = ctx.args; + size_t b = arg.find_first_not_of(" \t"); + size_t e = arg.find_last_not_of(" \t"); + arg = (b == std::string::npos) ? std::string() + : arg.substr(b, e - b + 1); + + if (arg.empty() || arg == "next" || arg == "+") { + delta = 1; + } else if (arg == "prev" || arg == "back" || arg == "-") { + delta = -1; + } else { + try { + absolute = std::stol(arg); + delta = 0; + } catch (const std::exception&) { + ctx.reply(ctx.trf( + "Usage: {}page <n>, or {}next / {}prev.", + ctx.prefix, ctx.prefix, ctx.prefix)); + return; + } + } + } + + auto page = manager_.renderCachedPage(ctx.clientId, absolute, + delta, ctx.language); + if (!page) { + ctx.reply(ctx.tr( + "Nothing to page through \xe2\x80\x94 run a command " + "that lists results first.")); + return; + } + ctx.reply(*page); + } + + std::string_view getDescription() const override + { + return "Shows another page of the last long reply (also " + "!next / !prev)."; + } + + std::string_view getUsage() const override + { + return "[n|next|prev]"; + } + + CommandCategory getCategory() const override + { + return CommandCategory::Utility; + } + + std::vector<std::string_view> getAliases() const override + { + // Only the argument-driven "page" instance exposes an alias; + // the dedicated next/prev instances are registered by name. + return mode_ == 0 ? std::vector<std::string_view>{"p"} + : std::vector<std::string_view>{}; + } + + // Each cached page already fits one message; sending it verbatim + // avoids a pointless second round of pagination. + bool autoPaginate() const override { return false; } }; // --- Manager Implementation --- @@ -138,6 +259,7 @@ namespace Echoion::Core { registerBuiltinCommands(); registerHelpCommand(); + registerPageCommands(); startThreadPool(); } @@ -154,7 +276,8 @@ namespace Echoion::Core { pool_ = std::make_unique<Void::Concurrency::ThreadPool>(THREAD_POOL_SIZE); - Void::Log::info("CommandManager", "{}", + Void::Log::info( + "CommandManager", "{}", std::format("CommandManager thread pool started with {} workers", THREAD_POOL_SIZE)); } @@ -191,8 +314,8 @@ namespace Echoion::Core } std::string cmdKey(cmdName); - std::transform( - cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower); + std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), + ::tolower); CommandPtr command; { @@ -204,26 +327,43 @@ namespace Echoion::Core command = it->second; } + // Resolve the invoker's language up front so even the permission / + // error fallbacks below are localized. + const I18n::Language lang = + resolveLanguage(task.clientId, task.musicManager); + // Check permissions if (!canExecuteCommand(task.clientId, command)) { - task.replyFunc( - "You don't have permission to use this command."); + task.replyFunc(std::string(I18n::translate( + "You don't have permission to use this command.", lang))); return; } - // Execute command CommandContext ctx{.clientId = task.clientId, .prefix = prefix_, .args = std::move(argsStr), .invokerName = task.invokerName, .musicManager = task.musicManager, .services = services_, - .replyCallback = std::move(task.replyFunc)}; + .language = lang}; + + if (command->autoPaginate()) { + // Copy (not move) the sink so the catch-block fallback below + // can still reach the user if execute() throws. + ctx.replyCallback = [this, cid = task.clientId, lang, + sink = + task.replyFunc](std::string_view msg) { + sink(paginateReply(cid, std::string(msg), lang)); + }; + } else { + ctx.replyCallback = task.replyFunc; + } command->execute(ctx); } catch (const std::exception& e) { - Void::Log::error("CommandManager", "{}", + Void::Log::error( + "CommandManager", "{}", std::format("Async command execution error: {}", e.what())); try { task.replyFunc( @@ -277,7 +417,9 @@ namespace Echoion::Core // Check permissions synchronously (fast check) if (!canExecuteCommand(clientId, command)) { - replyFunc("You don't have permission to use this command."); + replyFunc(std::string(I18n::translate( + "You don't have permission to use this command.", + resolveLanguage(clientId, musicManager)))); return true; // Command was found but not allowed } @@ -349,25 +491,40 @@ namespace Echoion::Core // Check permissions if (!canExecuteCommand(clientId, command)) { - replyFunc("You don't have permission to use this command."); + replyFunc(std::string(I18n::translate( + "You don't have permission to use this command.", + resolveLanguage(clientId, musicManager)))); return true; } + const I18n::Language lang = resolveLanguage(clientId, musicManager); + CommandContext ctx{.clientId = clientId, .prefix = prefix_, .args = std::move(argsStr), .invokerName = invokerName, .musicManager = musicManager, .services = services_, - .replyCallback = std::move(replyFunc)}; + .language = lang}; + + if (command->autoPaginate()) { + ctx.replyCallback = + [this, clientId, lang, + sink = std::move(replyFunc)](std::string_view msg) { + sink(paginateReply(clientId, std::string(msg), lang)); + }; + } else { + ctx.replyCallback = std::move(replyFunc); + } try { command->execute(ctx); } catch (const std::exception& e) { - Void::Log::error("CommandManager", "{}", std::format( - "Command execution error [{}]: {}", cmdKey, e.what())); - ctx.reply( - "An unexpected error occurred. Our team has been notified."); + Void::Log::error("CommandManager", "{}", + std::format("Command execution error [{}]: {}", + cmdKey, e.what())); + ctx.reply(ctx.tr( + "An unexpected error occurred. Our team has been notified.")); } return true; @@ -468,6 +625,7 @@ namespace Echoion::Core registerCommand<PlayCommand>("play"); registerCommand<YoutubePlayCommand>("pyt"); registerCommand<YandexPlayCommand>("pya"); + registerCommand<SoundCloudPlayCommand>("psc"); registerCommand<SelectCommand>("select"); registerCommand<PauseCommand>("pause"); registerCommand<ResumeCommand>("resume"); @@ -484,9 +642,11 @@ namespace Echoion::Core registerCommand<RepeatCommand>("repeat"); registerCommand<PlaylistCommand>("playlist"); registerCommand<NowPlayingCommand>("np"); + registerCommand<LyricsCommand>("lyrics"); registerCommand<SearchCommand>("search"); registerCommand<YoutubeSearchCommand>("youtube"); registerCommand<YandexSearchCommand>("yandex"); + registerCommand<SoundCloudSearchCommand>("soundcloud"); registerCommand<ReloadCommand>("reload"); registerCommand<ReloadConfigCommand>("reloadconfig"); registerCommand<SubscribeCommand>("subscribe"); @@ -499,6 +659,7 @@ namespace Echoion::Core registerCommand<StatsCommand>("stats"); registerCommand<FavoriteCommand>("fav"); registerCommand<AnnounceCommand>("announce"); + registerCommand<LanguageCommand>("language"); } void CommandManager::registerHelpCommand() @@ -515,4 +676,124 @@ namespace Echoion::Core } } + void CommandManager::registerPageCommands() + { + auto pageCmd = std::make_shared<PageNavCommand>(*this, 0); + auto nextCmd = std::make_shared<PageNavCommand>(*this, 1); + auto prevCmd = std::make_shared<PageNavCommand>(*this, -1); + + std::lock_guard<std::mutex> lock(mutex_); + + // Only "page" is listed in help; next/prev are convenience shortcuts. + commands_["page"] = pageCmd; + uniqueCommands_.push_back({"page", pageCmd}); + for (auto alias : pageCmd->getAliases()) { + commands_[std::string(alias)] = pageCmd; + } + commands_["next"] = nextCmd; + commands_["prev"] = prevCmd; + } + + namespace + { + // Append a localized "Page X/Y · nav" footer to a page. Single-page + // replies get no footer. + std::string withPageFooter(const std::string& page, std::size_t index, + std::size_t total, std::string_view prefix, + I18n::Language lang) + { + if (total <= 1) { + return page; + } + std::string tmpl(I18n::translate( + "\n\n\xe2\x80\x94 Page {}/{} \xc2\xb7 {}next \xc2\xb7 " + "{}prev \xc2\xb7 {}page <n>", + lang)); + std::size_t human = index + 1; + std::string pfx(prefix); + return page + std::vformat(tmpl, std::make_format_args( + human, total, pfx, pfx, pfx)); + } + } // namespace + + I18n::Language CommandManager::resolveLanguage( + uint64_t clientId, + const std::weak_ptr<MusicManager>& musicManager) const + { + I18n::Language lang = I18n::Language::English; + { + std::lock_guard<std::mutex> lock(mutex_); + if (serverConfig_) { + lang = I18n::parseLanguage(serverConfig_->bot.language); + } + } + + auto manager = musicManager.lock(); + if (!manager || !services_) { + return lang; + } + auto uid = manager->clientUid(clientId); + if (!uid || uid->empty()) { + return lang; + } + auto db = services_->get<Api::Database>(); + if (!db) { + return lang; + } + auto stored = db->getKv("lang:" + *uid); + if (stored && *stored) { + lang = I18n::parseLanguage(**stored); + } + return lang; + } + + std::string CommandManager::paginateReply(uint64_t clientId, + std::string text, + I18n::Language lang) + { + if (text.size() <= kPageLimitBytes) { + return text; + } + + auto pages = Util::paginate(text, kPageLimitBytes); + if (pages.size() <= 1) { + return pages.empty() ? text : std::move(pages.front()); + } + + std::lock_guard<std::mutex> lock(pagedMutex_); + PagedReply& entry = pagedReplies_[clientId]; + entry.pages = std::move(pages); + entry.current = 0; + entry.ts = std::chrono::steady_clock::now(); + return withPageFooter(entry.pages.front(), 0, entry.pages.size(), + prefix_, lang); + } + + std::optional<std::string> + CommandManager::renderCachedPage(uint64_t clientId, + std::optional<long> absolute, + int delta, I18n::Language lang) + { + std::lock_guard<std::mutex> lock(pagedMutex_); + auto it = pagedReplies_.find(clientId); + if (it == pagedReplies_.end()) { + return std::nullopt; + } + PagedReply& pr = it->second; + if (pr.pages.empty() || + std::chrono::steady_clock::now() - pr.ts > kPageTtl) { + pagedReplies_.erase(it); + return std::nullopt; + } + + const long count = static_cast<long>(pr.pages.size()); + long target = + absolute ? (*absolute - 1) : static_cast<long>(pr.current) + delta; + target = std::clamp(target, 0L, count - 1); + pr.current = static_cast<std::size_t>(target); + pr.ts = std::chrono::steady_clock::now(); + return withPageFooter(pr.pages[pr.current], pr.current, pr.pages.size(), + prefix_, lang); + } + } // namespace Echoion::Core diff --git a/src/ConfigLoader.cpp b/src/ConfigLoader.cpp index c2765fa..2b42854 100644 --- a/src/ConfigLoader.cpp +++ b/src/ConfigLoader.cpp @@ -17,6 +17,12 @@ namespace Echoion::Core // yt-dlp concurrency is hard-capped regardless of what the file says. config.youtube.ytDlpMaxConcurrent = std::min(config.youtube.ytDlpMaxConcurrent, size_t(8)); + + // Bot language: only "en"/"ru" are understood; anything else (including + // an empty field) falls back to English so replies never break. + if (config.bot.language != "en" && config.bot.language != "ru") { + config.bot.language = "en"; + } } Api::Result<Api::AppConfig> diff --git a/src/ConfigManager.cpp b/src/ConfigManager.cpp index 2739f6e..cbc4456 100644 --- a/src/ConfigManager.cpp +++ b/src/ConfigManager.cpp @@ -2,6 +2,7 @@ #include "echoion/core/ConfigLoader.hpp" #include <format> #include <iostream> +#include <tuple> namespace Echoion::Api { @@ -94,7 +95,9 @@ namespace Echoion::Api } if (saveToFile) { - save(); + // save() already reports failures (saveToFileInternal); the + // in-memory update stands either way. + std::ignore = save(); } notifyCallbacks(); diff --git a/src/Core.cpp b/src/Core.cpp index e1c5cd3..c0e4c36 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -1,6 +1,7 @@ #include "echoion/core/ConfigLoader.hpp" #include "echoion/core/Core.hpp" #include "echoion/core/RpcDtos.hpp" +#include "echoion/core/i18n/Localization.hpp" #include "echoion/core/state/StateSerializer.hpp" #include "echoion/core/state/StateVersions.hpp" #include <ConfigManager.hpp> @@ -17,6 +18,7 @@ #include <algorithm> #include <ctime> #include <format> +#include <fstream> #include <iomanip> #include <iostream> #include <sstream> @@ -26,11 +28,101 @@ namespace Echoion::Core { namespace { + // Decode a base64 string to raw bytes (used for custom emoji images + // served over HTTP). Returns empty on malformed input. + std::string decodeBase64(const std::string& in) + { + 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::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; + } + + // 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[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + 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 + // (e.g. an HTTP Content-Type), else sniff the magic number. + std::string sniffImageMime(std::string_view bytes, std::string_view hint) + { + if (hint.starts_with("image/")) { + return std::string(hint); + } + if (bytes.starts_with("\x89PNG")) { + return "image/png"; + } + if (bytes.starts_with("\xFF\xD8")) { + return "image/jpeg"; + } + if (bytes.starts_with("GIF8")) { + return "image/gif"; + } + if (bytes.starts_with("RIFF")) { + return "image/webp"; + } + return "application/octet-stream"; + } + // Build the console + split-file logging stack and install it as the // process-wide Void::Log sink. Replaces the old ILogger/LoggerRegistry // indirection; every ECHOION_LOG_* macro is now a Void::Log:: call. - [[nodiscard]] std::shared_ptr<Void::Logging::MultiLogger> - buildLogSink() + [[nodiscard]] std::shared_ptr<Void::Logging::MultiLogger> buildLogSink() { namespace VL = Void::Logging; auto multi = std::make_shared<VL::MultiLogger>(); @@ -88,7 +180,12 @@ namespace Echoion::Core Core::~Core() { if (initialized_) { - shutdown(); + if (auto result = shutdown(); !result) { + Void::Log::warn( + "Core", "{}", + std::format("Shutdown from destructor failed: {}", + result.error().message)); + } } } @@ -96,7 +193,7 @@ namespace Echoion::Core { if (initialized_) { return Api::fail(Api::ErrorCode::AlreadyExists, - "Core already initialized"); + "Core already initialized"); } installLogging(); // Store config path for later reload @@ -107,11 +204,18 @@ namespace Echoion::Core auto configResult = ConfigLoader::loadFromFile(configPath); if (!configResult) { // Try to create default config - Void::Log::warn("Core", "{}", + Void::Log::warn( + "Core", "{}", std::format("Failed to load config: {}, creating default", configResult.error().message)); config_ = ConfigLoader::createDefaultConfig(); - ConfigLoader::saveToFile(configPath, config_); + if (auto saved = ConfigLoader::saveToFile(configPath, config_); + !saved) { + Void::Log::warn( + "Core", "{}", + std::format("Failed to write default config: {}", + saved.error().message)); + } } else { config_ = *configResult; } @@ -120,7 +224,8 @@ namespace Echoion::Core configManager_.updateConfig(config_, false); Void::Log::info("Core", "{}", "Global ConfigManager initialized"); - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", std::format("Core loaded config - Server: {}:{}, Nickname: {}", config_.teamspeak.address, config_.teamspeak.port, config_.teamspeak.nickname)); @@ -139,14 +244,18 @@ namespace Echoion::Core return std::unexpected(netResult.error()); } + // Lyrics provider (lrclib) — shares the proxy-aware network client. + lyricsService_ = std::make_shared<LyricsService>(networkClient_); + // Initialize database alongside config file database_ = std::make_shared<Api::Database>(); Api::DatabaseConfig dbConfig; dbConfig.path = configPath.parent_path() / "echoion.db"; auto dbResult = database_->initialize(dbConfig); if (!dbResult) { - Void::Log::warn("Core", "{}", std::format("Failed to initialize database: {}", - dbResult.error().message)); + Void::Log::warn("Core", "{}", + std::format("Failed to initialize database: {}", + dbResult.error().message)); // Not fatal - continue without database database_ = nullptr; } else { @@ -199,10 +308,11 @@ namespace Echoion::Core // Check if server groups are available if (clientInfo.serverGroups.empty()) { - Void::Log::warn("Core", "{}", + Void::Log::warn( + "Core", "{}", "Cannot check admin permissions: server " "groups not available for client " + - std::to_string(clientId)); + std::to_string(clientId)); return false; // Server groups not available, deny admin // access } @@ -225,28 +335,30 @@ namespace Echoion::Core // Set up audio data callback // Receives int16 audio from MusicManager, sends directly to plugin - musicManager_->setAudioDataCallback( - [this](const std::span<const short> data) { - static int callCount = 0; - static auto lastLog = std::chrono::steady_clock::now(); + musicManager_->setAudioDataCallback([this](const std::span<const short> + data) { + static int callCount = 0; + static auto lastLog = std::chrono::steady_clock::now(); - if (pluginInterface_ && !data.empty()) { - // Send int16 data directly to plugin (no conversion needed) - auto result = pluginInterface_->sendAudioData(data); + if (pluginInterface_ && !data.empty()) { + // Send int16 data directly to plugin (no conversion needed) + auto result = pluginInterface_->sendAudioData(data); - callCount++; - auto now = std::chrono::steady_clock::now(); - if (std::chrono::duration_cast<std::chrono::seconds>( - now - lastLog) - .count() >= 5) { - Void::Log::debug("Core", "{}", std::format( + callCount++; + auto now = std::chrono::steady_clock::now(); + if (std::chrono::duration_cast<std::chrono::seconds>(now - + lastLog) + .count() >= 5) { + Void::Log::debug( + "Core", "{}", + std::format( "Audio callback: {} calls, {} samples, result: {}", callCount, data.size(), result.has_value() ? "ok" : "error")); - lastLog = now; - } + lastLog = now; } - }); + } + }); // Proactive private-message send path (announcements). musicManager_->setMessageCallback( @@ -267,34 +379,40 @@ namespace Echoion::Core // Set up client info callback to resolve UID and nickname from client // ID - musicManager_->setClientInfoCallback( - [this](uint64_t clientId) - -> std::optional<std::pair<std::string, std::string>> { - if (!pluginInterface_) { - Void::Log::warn("Core", "{}", - "ClientInfoCallback: pluginInterface is null"); - return std::nullopt; - } - auto clientInfoResult = pluginInterface_->getClient(clientId); - if (!clientInfoResult || !clientInfoResult->has_value()) { - Void::Log::warn("Core", "{}", std::format( + musicManager_->setClientInfoCallback([this](uint64_t clientId) + -> std::optional< + std::pair<std::string, + std::string>> { + if (!pluginInterface_) { + Void::Log::warn("Core", "{}", + "ClientInfoCallback: pluginInterface is null"); + return std::nullopt; + } + auto clientInfoResult = pluginInterface_->getClient(clientId); + if (!clientInfoResult || !clientInfoResult->has_value()) { + Void::Log::warn( + "Core", "{}", + std::format( "ClientInfoCallback: getClient failed for client {}", clientId)); - return std::nullopt; - } - auto clientInfo = clientInfoResult->value(); - if (!clientInfo.uniqueIdentifier) { - Void::Log::warn("Core", "{}", std::format( + return std::nullopt; + } + auto clientInfo = clientInfoResult->value(); + if (!clientInfo.uniqueIdentifier) { + Void::Log::warn( + "Core", "{}", + std::format( "ClientInfoCallback: client {} has no uniqueIdentifier", clientId)); - return std::nullopt; - } - Void::Log::debug("Core", "{}", - std::format("ClientInfoCallback: Got UID for client {}: {}", - clientId, *clientInfo.uniqueIdentifier)); - return std::make_pair(*clientInfo.uniqueIdentifier, - clientInfo.nickname); - }); + return std::nullopt; + } + Void::Log::debug( + "Core", "{}", + std::format("ClientInfoCallback: Got UID for client {}: {}", + clientId, *clientInfo.uniqueIdentifier)); + return std::make_pair(*clientInfo.uniqueIdentifier, + clientInfo.nickname); + }); // Set up UID to client ID callback musicManager_->setUidToClientIdCallback( @@ -338,17 +456,164 @@ namespace Echoion::Core config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765; auto rpcResult = rpcServer_->start(rpcPort); if (!rpcResult) { - Void::Log::warn("Core", "{}", std::format("Failed to start RPC server: {}", - rpcResult.error().message)); + Void::Log::warn("Core", "{}", + std::format("Failed to start RPC server: {}", + rpcResult.error().message)); // Not fatal - continue without RPC rpcServer_.reset(); } else { - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", std::format("RPC server started on port {}", rpcPort)); setupRpcHandlers(); setupEventBusSubscriptions(); } +#ifdef ECHOION_WITH_WEB + // Browser web interface (independent of the RPC transport above). + if (config_.web.enabled) { + webServer_ = std::make_shared<Web::HttpServer>(); + // Watch-together control requires a signed-in user; the web + // server validates tokens through Core (it has no DB handle). + webServer_->setIdentityResolver( + [this](const std::string& token) + -> std::optional<Web::WatchSessionManager::Identity> { + auto identity = identityForToken(token); + if (!identity) { + return std::nullopt; + } + return Web::WatchSessionManager::Identity{ + .uid = identity->uid, + .nickname = identity->nickname, + .isAdmin = identity->isAdmin}; + }); + // Avatar images for GET /avatar/<uid>: resolve the uid to an online + // client and serve its TeamSpeak avatar. Sources, in order: the TS + // client's own cache (in-view clients), an active file-transfer + // download from the server (clients out of view), and finally the + // DB copy persisted from a previous fetch. The first request for a + // not-yet-downloaded avatar triggers the async download and 404s; + // once it arrives, a later request serves and persists it. + webServer_->setAvatarProvider( + [this](const std::string& uid) + -> std::optional<Web::HttpServer::AvatarImage> { + // Offline/miss path: serve the persisted bytes, else + // re-fetch from the stored myTeamSpeak URL (public GCS, + // reachable even when the user is offline) and cache it. + auto fromStore = [this](const std::string& u) + -> std::optional<Web::HttpServer::AvatarImage> { + if (!database_) { + return std::nullopt; + } + auto stored = database_->getCachedAvatar(u); + if (!stored || !stored->has_value()) { + return std::nullopt; + } + if (!(*stored)->dataBase64.empty()) { + auto bytes = decodeBase64((*stored)->dataBase64); + if (!bytes.empty()) { + return Web::HttpServer::AvatarImage{ + .contentType = (*stored)->mime, + .bytes = std::move(bytes)}; + } + } + if (!(*stored)->url.empty() && networkClient_) { + auto resp = + networkClient_->getDirect((*stored)->url); + if (resp && resp->ok() && !resp->body.empty()) { + std::string_view ct; + if (auto h = resp->header("Content-Type")) { + ct = *h; + } + std::string type = + sniffImageMime(resp->body, ct); + if (database_) { + [[maybe_unused]] auto put = + database_->putCachedAvatar( + u, type, + encodeBase64(resp->body)); + } + return Web::HttpServer::AvatarImage{ + .contentType = std::move(type), + .bytes = std::move(resp->body)}; + } + } + return std::nullopt; + }; + + // Online client: fetch live (also persists bytes + url). + if (pluginInterface_) { + if (auto clients = pluginInterface_->getClients()) { + for (const auto& c : *clients) { + if (c.uniqueIdentifier != uid) { + continue; + } + if (auto r = + fetchClientAvatarBytes(uid, c.id)) { + return Web::HttpServer::AvatarImage{ + .contentType = std::move(r->first), + .bytes = std::move(r->second)}; + } + break; + } + } + } + // Offline or live miss: persisted bytes / stored-url. + return fromStore(uid); + }); + // Custom emoji images for GET /emoji/<name>: decode the stored + // base64 payload to raw bytes with its mime type. + webServer_->setEmojiProvider( + [this](const std::string& name) + -> std::optional<Web::HttpServer::AvatarImage> { + if (!database_) { + return std::nullopt; + } + auto emoji = database_->getCustomEmoji(name); + if (!emoji || !emoji->has_value()) { + return std::nullopt; + } + auto bytes = decodeBase64((*emoji)->dataBase64); + if (bytes.empty()) { + return std::nullopt; + } + return Web::HttpServer::AvatarImage{ + .contentType = (*emoji)->mime, + .bytes = std::move(bytes)}; + }); + Web::HttpServer::Config webCfg; + webCfg.port = config_.web.port; + webCfg.bindAddress = config_.web.bindAddress; + webCfg.webRoot = config_.web.webRoot; + webCfg.rpcUrl = config_.web.rpcUrl; + webCfg.nowPlayingVideo = config_.web.nowPlayingVideo; + webCfg.rpcPort = + config_.network.rpcPort > 0 ? config_.network.rpcPort : 8765; + if (!webServer_->start(webCfg)) { + Void::Log::warn( + "Core", "{}", + "Failed to start web interface; continuing without it"); + webServer_.reset(); + } + } + + // Proactively cache avatars for every online client so they stay + // available (from the DB / stored myTS URL) once the user goes offline. + // A short-cycle poll keeps up with clients whose avatar variables sync a + // moment after they come into view. + avatarWarmer_ = std::jthread([this](std::stop_token st) { + while (!st.stop_requested()) { + for (int i = 0; i < 30 && !st.stop_requested(); ++i) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + if (st.stop_requested()) { + break; + } + warmAvatarCache(); + } + }); +#endif + // ── Compose the service registry ───────────────────────────────── // Register every Core service by interface so code can resolve them // via registry_.require<I>() instead of reaching for global singletons. @@ -359,8 +624,7 @@ namespace Echoion::Core using T = std::remove_reference_t<decltype(*p)>; return std::shared_ptr<T>(p, [](T*) {}); }; - registry_.provide<Api::ConfigManager>( - alias(&configManager_)); + registry_.provide<Api::ConfigManager>(alias(&configManager_)); registry_.provide<Void::EventBus::EventBus>(alias(&eventBus_)); // Expose Core itself so commands can reach Core operations // (e.g. reloadConfig) through the registry. @@ -369,6 +633,9 @@ namespace Echoion::Core if (networkClient_) { registry_.provide<Api::INetworkClient>(networkClient_); } + if (lyricsService_) { + registry_.provide<LyricsService>(lyricsService_); + } if (database_) { registry_.provide<Api::Database>(database_); } @@ -383,41 +650,19 @@ namespace Echoion::Core startTime_ = std::chrono::system_clock::now(); initialized_ = true; - Void::Log::info("Core", "{}", std::format("Core initialized (this={})", - reinterpret_cast<uintptr_t>(this))); + Void::Log::info("Core", "{}", + std::format("Core initialized (this={})", + reinterpret_cast<uintptr_t>(this))); unsigned int hwThreads = std::thread::hardware_concurrency(); - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", std::format("Hardware concurrency: {} threads", hwThreads)); Void::Log::info("Core", "{}", "Echoion Core initialized successfully"); - // Auto-connect to server if configured - if (!config_.teamspeak.address.empty() && pluginInterface_) { - Void::Log::info("Core", "{}", std::format("Auto-connecting to {}:{}...", - config_.teamspeak.address, - config_.teamspeak.port)); - - // Convert TeamSpeakConfig to ServerConfig for the plugin interface - Api::ServerConfig serverConfig; - serverConfig.address = config_.teamspeak.address; - serverConfig.port = config_.teamspeak.port; - serverConfig.serverPassword = config_.teamspeak.serverPassword; - serverConfig.nickname = config_.teamspeak.nickname; - serverConfig.defaultChannelId = config_.teamspeak.defaultChannelId; - serverConfig.channelPassword = config_.teamspeak.channelPassword; - serverConfig.adminGroups = config_.teamspeak.adminGroups; - serverConfig.djGroups = config_.teamspeak.djGroups; - serverConfig.bannedGroups = config_.teamspeak.bannedGroups; - - auto connectResult = - pluginInterface_->connectToServer(serverConfig); - if (!connectResult) { - Void::Log::error("Core", "{}", std::format("Auto-connect failed: {}", - connectResult.error().message)); - } else { - Void::Log::info("Core", "{}", "Auto-connect initiated"); - } - } + // Auto-connect happens in setPluginInterface(): the plugin interface + // is never available this early in the real load order, and a second + // connect path here caused duplicate connection attempts. return {}; } @@ -430,6 +675,10 @@ namespace Echoion::Core Void::Log::info("Core", "{}", "Shutting down Echoion Core..."); + // Stop the avatar warmer before tearing down the deps it touches + // (plugin/network/database). jthread move-assign requests stop + joins. + avatarWarmer_ = {}; + if (commandManager_) { commandManager_->shutdown(); } @@ -447,6 +696,13 @@ namespace Echoion::Core rpcServer_.reset(); } +#ifdef ECHOION_WITH_WEB + if (webServer_) { + webServer_->stop(); + webServer_.reset(); + } +#endif + if (database_) { database_->shutdown(); database_.reset(); @@ -463,8 +719,9 @@ namespace Echoion::Core } initialized_ = false; - Void::Log::info("Core", "{}", std::format("Echoion Core shutdown complete (this={})", - reinterpret_cast<uintptr_t>(this))); + Void::Log::info("Core", "{}", + std::format("Echoion Core shutdown complete (this={})", + reinterpret_cast<uintptr_t>(this))); return {}; } @@ -710,7 +967,7 @@ namespace Echoion::Core if (!found) { return Api::fail(Api::ErrorCode::NotFound, - "Track not found in queue"); + "Track not found in queue"); } return musicManager_->moveInQueue(fromPosition, newPosition); @@ -856,8 +1113,7 @@ namespace Echoion::Core .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 {}; } @@ -905,7 +1161,7 @@ namespace Echoion::Core if (configPath_.empty()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Config path not set"); + "Config path not set"); } // Reload config from disk @@ -929,7 +1185,8 @@ namespace Echoion::Core // Re-apply network settings so a proxy edit actually reaches every // outbound client (HTTP NetworkClient, yt-dlp, ffmpeg) — not just the - // config copy. Without this the YouTube API kept using the old/no proxy. + // config copy. Without this the YouTube API kept using the old/no + // proxy. if (musicManager_) { musicManager_->applyBotConfig(config_.bot); musicManager_->applyFeaturesConfig(config_.features); @@ -992,7 +1249,8 @@ namespace Echoion::Core return std::unexpected(r.error()); } - Void::Log::info("Core", "{}", "Preparing for hot reload (decoupled)..."); + Void::Log::info("Core", "{}", + "Preparing for hot reload (decoupled)..."); broadcastEvent( Api::PluginEvent{.type = Api::PluginEventType::HotReloadRequested, @@ -1011,7 +1269,8 @@ namespace Echoion::Core return std::unexpected(r.error()); } - Void::Log::info("Core", "{}", "Restoring after hot reload (decoupled)..."); + Void::Log::info("Core", "{}", + "Restoring after hot reload (decoupled)..."); // Deserialize state from JSON auto parsed = Void::Json::parse(state); @@ -1042,7 +1301,8 @@ namespace Echoion::Core .clientId = 0, .timestamp = std::chrono::system_clock::now()}); - Void::Log::info("Core", "{}", "Hot reload restore complete (decoupled)"); + Void::Log::info("Core", "{}", + "Hot reload restore complete (decoupled)"); return {}; } @@ -1070,8 +1330,7 @@ namespace Echoion::Core if (playbackSummary) { playback.volume = playbackSummary->volume; } - // Note: isPlaying, isPaused, shuffle, repeat would need to be - // captured from MusicManager For now, we'll capture what we can + // shuffle/repeat are filled in below from getPlaybackState(). state.playback = std::move(playback); state.hasPlayback = true; } @@ -1089,18 +1348,27 @@ namespace Echoion::Core } } + // Capture playback modes so a reload keeps shuffle/repeat/radio. + state.autoplay = musicManager_->autoplayEnabled(); + if (auto ps = musicManager_->getPlaybackState()) { + state.playback.shuffle = ps->shuffle; + state.playback.repeat = ps->repeat; + } + // Serialize using StateSerializer auto blob = StateSerializer::serialize(state); - Void::Log::info("Core", "{}", std::format("State saved: version={}, size={} bytes", - blob.version, blob.size())); + Void::Log::info("Core", "{}", + std::format("State saved: version={}, size={} bytes", + blob.version, blob.size())); return blob; } Api::Result<void> Core::restoreState(const Api::StateBlob& state) { - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", std::format("Restoring Core state: version={}", state.version)); auto result = StateSerializer::deserialize(state); @@ -1114,32 +1382,38 @@ namespace Echoion::Core const StateV1& stateData = *result; - // Restore playback state - if (stateData.hasPlayback) { - const auto& playback = stateData.playback; - // Restore track, position, volume, etc. - // This would involve calling MusicManager methods - // For now, we'll just log it - Void::Log::info("Core", "{}", std::format("Restoring playback: {} - {}", - playback.currentTrack.title, - playback.currentTrack.artist)); - } + // MusicManager already reloads its persisted session (queue + modes) + // from the database at startup. Only fall back to re-adding from this + // blob when that left the queue empty (e.g. an older core without kv + // session persistence), so a hot reload never appends a second copy of + // every track regardless of load/restore ordering. + auto existingQueue = musicManager_->getQueue(); + const bool alreadyRestored = existingQueue && !existingQueue->empty(); - // Restore queue - for (const auto& entry : stateData.queue) { - // Add to music manager queue - auto result = musicManager_->queueTrack(entry.track, 0); - if (result) { - Void::Log::info("Core", "{}", - std::format("Restored queue entry: {} (ID: {})", - entry.track.title, *result)); - } else { - Void::Log::warn("Core", "{}", - std::format("Failed to restore queue entry '{}': {}", - entry.track.title, result.error().message)); + if (!alreadyRestored) { + musicManager_->setShuffle(stateData.playback.shuffle); + musicManager_->setRepeat(stateData.playback.repeat); + for (const auto& entry : stateData.queue) { + auto result = musicManager_->queueTrack(entry.track, 0); + if (result) { + Void::Log::info( + "Core", "{}", + std::format("Restored queue entry: {} (ID: {})", + entry.track.title, *result)); + } else { + Void::Log::warn( + "Core", "{}", + std::format("Failed to restore queue entry '{}': {}", + entry.track.title, result.error().message)); + } } } + // Autoplay's authoritative store is its own kv (already loaded); the + // blob value matches. Kick playback/radio without a manual toggle. + musicManager_->setAutoplay(stateData.autoplay); + musicManager_->maybeAutoStart(); + Void::Log::info("Core", "{}", "State restored successfully"); return {}; } @@ -1212,7 +1486,7 @@ namespace Echoion::Core { if (!config.isValid()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Invalid config handle"); + "Invalid config handle"); } // Update from the handle @@ -1235,23 +1509,27 @@ namespace Echoion::Core Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event) { - Void::Log::debug("Core", "{}", std::format( - "Core::onPluginEvent called (this={}, initialized={})", - reinterpret_cast<uintptr_t>(this), initialized_.load())); + Void::Log::debug( + "Core", "{}", + std::format("Core::onPluginEvent called (this={}, initialized={})", + reinterpret_cast<uintptr_t>(this), + initialized_.load())); if (!initialized_) { - Void::Log::warn("Core", "{}", + Void::Log::warn( + "Core", "{}", std::format("Core::onPluginEvent: Core not initialized " "(this={}), ignoring event type={}", reinterpret_cast<uintptr_t>(this), static_cast<int>(event.type))); - return Api::fail( - Api::ErrorCode::ServiceUnavailable, "Core not initialized"); + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Core not initialized"); } // Debug logging for command events if (event.type == Api::PluginEventType::TextMessageReceived && event.message) { - Void::Log::debug("Core", "{}", + Void::Log::debug( + "Core", "{}", std::format("Core received message: {} from client {}", *event.message, event.clientId)); } @@ -1261,7 +1539,8 @@ namespace Echoion::Core if (event.message) { // Check if it's a command if (event.message->starts_with(config_.bot.commandPrefix)) { - Void::Log::debug("Core", "{}", + Void::Log::debug( + "Core", "{}", std::format("Processing command: {} from client {}", *event.message, event.clientId)); // Create reply callback @@ -1299,36 +1578,56 @@ namespace Echoion::Core if (!handled) { if (pluginInterface_) { - pluginInterface_->sendTextMessage( + auto lang = + I18n::parseLanguage(config_.bot.language); + (void)pluginInterface_->sendTextMessage( event.clientId, - std::format("Unknown command. Type {}help " - "for available commands.", - config_.bot.commandPrefix)); + std::vformat( + I18n::translate( + "Unknown command. Type {}help " + "for available commands.", + lang), + std::make_format_args( + config_.bot.commandPrefix))); } } } } break; + case Api::PluginEventType::ConnectionEstablished: + // The client list is only now available: the whisper list and + // auto-start decisions made during init all saw 0 online + // subscribers, so redo them. Late enter-view events are + // covered by the ClientConnected path below. + Void::Log::info("Core", "{}", + "Connection established, refreshing online " + "subscribers"); + updateWhisperList(); + if (musicManager_) { + musicManager_->maybeAutoStart(); + } + break; + case Api::PluginEventType::ClientConnected: - Void::Log::info("Core", "{}", - std::format("Client {} connected, updating whisper list", - event.clientId)); + Void::Log::info( + "Core", "{}", + std::format("Client {} connected", event.clientId)); + // The whisper list refreshes via the subscription-change + // callback when this client turns out to be a subscriber; + // non-subscribers never affect it. if (musicManager_) { musicManager_->onClientConnected(event.clientId); } - // Update whisper list after client connect - updateWhisperList(); break; case Api::PluginEventType::ClientDisconnected: - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", std::format("Client {} disconnected", event.clientId)); if (musicManager_) { musicManager_->onClientDisconnected(event.clientId); } - // Update whisper list after client disconnect - updateWhisperList(); break; default: @@ -1350,44 +1649,63 @@ namespace Echoion::Core void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface) { pluginInterface_ = std::move(pluginInterface); - Void::Log::info("Core", "{}", std::format("Plugin interface set (this={})", - reinterpret_cast<uintptr_t>(this))); - - // Now that we have the plugin interface, update the whisper list - // This is needed because subscriptions may have been loaded from - // database before the plugin interface was available - updateWhisperList(); + Void::Log::info("Core", "{}", + std::format("Plugin interface set (this={})", + reinterpret_cast<uintptr_t>(this))); // Trigger auto-connect now that plugin interface is available if (initialized_ && !config_.teamspeak.address.empty()) { - Void::Log::info("Core", "{}", + Void::Log::info( + "Core_SetPluginInterface", "{}", "Plugin interface available, triggering auto-connect..."); triggerAutoConnect(); } + // Subscribers can only be resolved to online clients once the plugin + // interface is set, so this is the earliest point a restored session + // (queue / radio) can actually begin playing after a load or reload. + if (musicManager_) { + // Now that we have the plugin interface, update the whisper list + // This is needed because subscriptions may have been loaded from + // database before the plugin interface was available + updateWhisperList(); + + musicManager_->maybeAutoStart(); + } } void Core::triggerAutoConnect() { if (!initialized_) { - Void::Log::warn("Core", "{}", "Cannot auto-connect: Core not initialized"); + Void::Log::warn("Core", "{}", + "Cannot auto-connect: Core not initialized"); return; } if (!pluginInterface_) { - Void::Log::warn("Core", "{}", - "Cannot auto-connect: Plugin interface not set"); + Void::Log::warn("Core", "{}", + "Cannot auto-connect: Plugin interface not set"); return; } if (config_.teamspeak.address.empty()) { - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", "Auto-connect skipped: No server address configured"); return; } - Void::Log::info("Core", "{}", std::format("Auto-connecting to {}:{}...", - config_.teamspeak.address, - config_.teamspeak.port)); + // Idempotent: multiple callers (setPluginInterface, plugin exports) + // must not stack connection attempts. + if (autoConnectInitiated_.exchange(true)) { + Void::Log::debug("Core", "{}", + "Auto-connect already initiated, skipping"); + return; + } + + Void::Log::info("Core", "{}", + std::format("Auto-connecting to {}:{}...", + config_.teamspeak.address, + config_.teamspeak.port)); // Convert TeamSpeakConfig to ServerConfig for the plugin interface Api::ServerConfig serverConfig; @@ -1403,10 +1721,15 @@ namespace Echoion::Core auto connectResult = pluginInterface_->connectToServer(serverConfig); if (!connectResult) { - Void::Log::error("Core", "{}", std::format("Auto-connect failed: {}", - connectResult.error().message)); + autoConnectInitiated_ = false; // allow a retry + Void::Log::error("Core", "{}", + std::format("Auto-connect failed: {}", + connectResult.error().message)); } else { - Void::Log::info("Core", "{}", "Auto-connect initiated"); + // No whisper-list update here: the client list is empty until + // ConnectionEstablished, whose handler refreshes it. + Void::Log::info("Core_triggerAutoConnect", "{}", + "Auto-connect initiated"); } } @@ -1427,7 +1750,8 @@ namespace Echoion::Core try { callback(event); } catch (const std::exception& e) { - Void::Log::error("Core", "{}", + Void::Log::error( + "Core", "{}", std::format("Event callback error: {}", e.what())); } } @@ -1488,16 +1812,18 @@ namespace Echoion::Core .id = event.trackSummary->id, .title = event.trackSummary->title, .artist = event.trackSummary->artist, - .duration = event.trackSummary->duration - ? event.trackSummary->duration->count() / 1000 - : 0}); + .duration = + event.trackSummary->duration + ? event.trackSummary->duration->count() / 1000 + : 0}); } if (event.volume.has_value()) { eventData = toJson(Dto::Volume{.volume = *event.volume}); } if (event.queuePosition.has_value()) { - eventData = toJson(Dto::Position{ - .position = static_cast<std::int64_t>(*event.queuePosition)}); + eventData = + toJson(Dto::Position{.position = static_cast<std::int64_t>( + *event.queuePosition)}); } if (event.clientId > 0) { eventData = toJson(Dto::ClientId{.clientId = event.clientId}); @@ -1514,10 +1840,206 @@ namespace Echoion::Core clientId) != adminClients_.end(); } + bool Core::isDj(uint64_t clientId) const + { + std::lock_guard<std::mutex> lock(adminMutex_); + return std::find(djClients_.begin(), djClients_.end(), clientId) != + djClients_.end(); + } + + std::optional<Core::RpcIdentity> Core::rpcIdentity(uint64_t clientId) const + { + std::lock_guard<std::mutex> lock(rpcIdentityMutex_); + if (auto it = rpcIdentities_.find(clientId); + it != rpcIdentities_.end()) { + return it->second; + } + return std::nullopt; + } + + std::optional<Core::TokenIdentity> + Core::identityForToken(const std::string& token) + { + if (!database_ || token.empty()) { + return std::nullopt; + } + auto valid = database_->validateRpcToken(token); + if (!valid || !*valid) { + return std::nullopt; + } + auto uidRes = database_->getUidFromRpcToken(token); + if (!uidRes || !uidRes->has_value()) { + return std::nullopt; + } + + TokenIdentity identity; + identity.uid = **uidRes; + // Nickname from the subscriber record (stable even when the user is + // offline in TeamSpeak). + if (auto subs = database_->getAllSubscribers()) { + for (const auto& s : *subs) { + if (s.uid == identity.uid) { + identity.nickname = s.nickname; + break; + } + } + } + // Admin / DJ if the TeamSpeak identity is in a configured admin or + // DJ server group (resolvable only while the user is online). + if (pluginInterface_ && (!config_.teamspeak.adminGroups.empty() || + !config_.teamspeak.djGroups.empty())) { + if (auto clients = pluginInterface_->getClients()) { + auto inAnyGroup = [](const std::vector<uint64_t>& wanted, + const std::vector<uint64_t>& groups) { + for (uint64_t w : wanted) { + for (uint64_t g : groups) { + if (w == g) { + return true; + } + } + } + return false; + }; + for (const auto& c : *clients) { + if (c.uniqueIdentifier != identity.uid) { + continue; + } + identity.isAdmin = inAnyGroup( + config_.teamspeak.adminGroups, c.serverGroups); + identity.isDj = inAnyGroup(config_.teamspeak.djGroups, + c.serverGroups); + if (identity.nickname.empty()) { + identity.nickname = c.nickname; + } + break; + } + } + } + return identity; + } + + void Core::registerRpcAuth(uint64_t clientId, const TokenIdentity& identity) + { + if (rpcServer_) { + rpcServer_->addAuthenticatedClient(clientId); + } + if (identity.isAdmin || identity.isDj) { + std::lock_guard<std::mutex> lock(adminMutex_); + if (identity.isAdmin) { + adminClients_.push_back(clientId); + } + if (identity.isDj) { + djClients_.push_back(clientId); + } + } + { + std::lock_guard<std::mutex> lock(rpcIdentityMutex_); + rpcIdentities_[clientId] = RpcIdentity{ + .uid = identity.uid, .nickname = identity.nickname}; + } + } + + std::optional<std::pair<std::string, std::string>> + Core::fetchClientAvatarBytes(const std::string& uid, uint64_t clientId) + { + if (!pluginInterface_) { + return std::nullopt; + } + auto store = [&](std::string bytes, std::string_view hint) + -> std::optional<std::pair<std::string, std::string>> { + if (bytes.empty()) { + return std::nullopt; + } + std::string type = sniffImageMime(bytes, hint); + if (database_) { + [[maybe_unused]] auto put = database_->putCachedAvatar( + uid, type, encodeBase64(bytes)); + } + return std::pair{std::move(type), std::move(bytes)}; + }; + + // 1) The TS client's own avatar cache (in-view clients). + if (auto path = pluginInterface_->getClientAvatarPath(clientId); + path && path->has_value()) { + std::ifstream f(**path, std::ios::binary); + if (f) { + std::string bytes((std::istreambuf_iterator<char>(f)), + std::istreambuf_iterator<char>()); + if (auto r = store(std::move(bytes), "")) { + return r; + } + } + } + // 2) The myTeamSpeak avatar: a public GCS URL, reachable even when the + // user is offline. Persist the url first so an offline request can + // re-fetch it, then download and cache the bytes. + if (auto url = pluginInterface_->getClientAvatarUrl(clientId); + url && url->has_value()) { + if (database_) { + [[maybe_unused]] auto pu = + database_->putCachedAvatarUrl(uid, **url); + } + if (networkClient_) { + auto resp = networkClient_->getDirect(**url); + if (resp && resp->ok() && !resp->body.empty()) { + std::string_view ct; + if (auto h = resp->header("Content-Type")) { + ct = *h; + } + if (auto r = store(std::move(resp->body), ct)) { + return r; + } + } + } + } + // 3) Legacy file-transfer avatar (async; first call just triggers it). + if (auto p = pluginInterface_->requestClientAvatar(clientId, + "cache/avatars"); + p && p->has_value()) { + std::ifstream f(**p, std::ios::binary); + if (f) { + std::string bytes((std::istreambuf_iterator<char>(f)), + std::istreambuf_iterator<char>()); + if (auto r = store(std::move(bytes), "")) { + return r; + } + } + } + return std::nullopt; + } + + void Core::warmAvatarCache() + { + if (!pluginInterface_ || !database_) { + return; + } + auto clients = pluginInterface_->getClients(); + if (!clients) { + return; + } + for (const auto& c : *clients) { + if (!c.uniqueIdentifier || c.uniqueIdentifier->empty()) { + continue; + } + const std::string& cuid = *c.uniqueIdentifier; + if (warmedUids_.contains(cuid)) { + continue; + } + if (auto r = fetchClientAvatarBytes(cuid, c.id)) { + warmedUids_.insert(cuid); + Void::Log::info( + "Avatar", "{}", + std::format("warmed avatar for uid='{}' ({} bytes)", cuid, + r->second.size())); + } + } + } + void Core::updateWhisperList() { if (!pluginInterface_ || !musicManager_) { - Void::Log::warn("Core", "{}", + Void::Log::warn( + "Core", "{}", "updateWhisperList: pluginInterface or musicManager is null"); return; } @@ -1526,14 +2048,16 @@ namespace Echoion::Core std::vector<uint64_t> subscriberVec(subscribers.begin(), subscribers.end()); - Void::Log::info("Core", "{}", + Void::Log::info( + "Core", "{}", std::format("Updating whisper list with {} online subscribers", subscriberVec.size())); auto result = pluginInterface_->setWhisperList(subscriberVec); if (!result) { - Void::Log::warn("Core", "{}", std::format("Failed to update whisper list: {}", - result.error().message)); + Void::Log::warn("Core", "{}", + std::format("Failed to update whisper list: {}", + result.error().message)); } else { Void::Log::info("Core", "{}", "Whisper list updated successfully"); } @@ -1545,13 +2069,15 @@ namespace Echoion::Core return; } - Void::Log::info("Core", "{}", "Generating RPC tokens for existing subscribers..."); + Void::Log::info("Core", "{}", + "Generating RPC tokens for existing subscribers..."); // Get all subscriber UIDs auto uidsResult = database_->getAllSubscriberUids(); if (!uidsResult) { - Void::Log::warn("Core", "{}", std::format("Failed to get subscriber UIDs: {}", - uidsResult.error().message)); + Void::Log::warn("Core", "{}", + std::format("Failed to get subscriber UIDs: {}", + uidsResult.error().message)); return; } @@ -1562,7 +2088,8 @@ namespace Echoion::Core // Check if token already exists auto existingToken = database_->getExistingRpcToken(uid); if (!existingToken) { - Void::Log::warn("Core", "{}", + Void::Log::warn( + "Core", "{}", std::format("Failed to check existing token for UID {}: {}", uid, existingToken.error().message)); continue; @@ -1576,7 +2103,8 @@ namespace Echoion::Core // Generate new token auto tokenResult = database_->generateRpcToken(uid); if (!tokenResult) { - Void::Log::warn("Core", "{}", + Void::Log::warn( + "Core", "{}", std::format("Failed to generate token for UID {}: {}", uid, tokenResult.error().message)); } else { @@ -1584,9 +2112,10 @@ namespace Echoion::Core } } - Void::Log::info("Core", "{}", std::format("RPC token generation complete: {} new " - "tokens generated, {} already existed", - generatedCount, existingCount)); + Void::Log::info("Core", "{}", + std::format("RPC token generation complete: {} new " + "tokens generated, {} already existed", + generatedCount, existingCount)); } } // namespace Echoion::Core diff --git a/src/CoreEventRelay.cpp b/src/CoreEventRelay.cpp index ab640a3..42486e8 100644 --- a/src/CoreEventRelay.cpp +++ b/src/CoreEventRelay.cpp @@ -33,9 +33,15 @@ namespace Echoion::Core // Record playback start in database if (database_) { - database_->recordPlayback(evt.track, evt.clientId, - std::chrono::milliseconds(0), - false); + if (auto result = database_->recordPlayback( + evt.track, evt.clientId, + std::chrono::milliseconds(0), false); + !result) { + Void::Log::warn( + "Core", "{}", + std::format("Failed to record playback start: {}", + result.error().message)); + } } }); @@ -58,7 +64,7 @@ namespace Echoion::Core }); eventBus_.subscribe<PlaybackStopped>( - [this](const PlaybackStopped& evt) mutable { + [this](const PlaybackStopped&) mutable { if (rpcServer_) { rpcServer_->broadcastEvent("playback.stopped", "{}"); } @@ -85,9 +91,22 @@ namespace Echoion::Core // Update playback record as completed, keeping the history // bounded per features.maxHistorySize. if (database_) { - database_->recordPlayback(evt.track, 0, evt.finalPosition, - true); - database_->trimHistory(config_.features.maxHistorySize); + if (auto result = database_->recordPlayback( + evt.track, 0, evt.finalPosition, true); + !result) { + Void::Log::warn( + "Core", "{}", + std::format("Failed to record playback: {}", + result.error().message)); + } + if (auto result = database_->trimHistory( + config_.features.maxHistorySize); + !result) { + Void::Log::warn( + "Core", "{}", + std::format("Failed to trim history: {}", + result.error().message)); + } } }); @@ -146,7 +165,7 @@ namespace Echoion::Core }); eventBus_.subscribe<QueueCleared>( - [this](const QueueCleared& evt) mutable { + [this](const QueueCleared&) mutable { if (rpcServer_) { rpcServer_->broadcastEvent("queue.cleared", "{}"); } @@ -197,8 +216,16 @@ namespace Echoion::Core evt.playlistId, evt.playlistId, "Loaded from YouTube", 0, true); if (result) { - database_->addTrackToPlaylist(result.value(), evt.track, - evt.loadedCount - 1); + if (auto added = database_->addTrackToPlaylist( + result.value(), evt.track, + evt.loadedCount - 1); + !added) { + Void::Log::warn( + "Core", "{}", + std::format( + "Failed to add track to playlist: {}", + added.error().message)); + } } } }); diff --git a/src/CoreRpcHandlers.cpp b/src/CoreRpcHandlers.cpp index be4e682..f4f10cb 100644 --- a/src/CoreRpcHandlers.cpp +++ b/src/CoreRpcHandlers.cpp @@ -9,12 +9,28 @@ #include <algorithm> #include <chrono> #include <format> +#include <set> #include <string> #include <thread> namespace Echoion::Core { + namespace + { + // Stable 64-bit key for a TS uid string (FNV-1a): the favorites + // tables key users by integer id, while RPC auth yields string uids. + [[nodiscard]] uint64_t uidHash(const std::string& uid) + { + uint64_t hash = 14695981039346656037ULL; + for (unsigned char c : uid) { + hash ^= c; + hash *= 1099511628211ULL; + } + return hash; + } + } // namespace + void Core::setupRpcHandlers() { if (!rpcServer_) { @@ -43,46 +59,18 @@ namespace Echoion::Core // If token provided, validate it if (req.token.has_value()) { - auto validResult = database_->validateRpcToken(*req.token); - if (!validResult) { - return std::unexpected(validResult.error()); - } - if (*validResult) { - rpcServer_->addAuthenticatedClient(clientId); - // Mark the client as admin if its TeamSpeak identity is - // in a configured admin server group. - if (auto uid = - database_->getUidFromRpcToken(*req.token); - uid && uid->has_value() && pluginInterface_ && - !config_.teamspeak.adminGroups.empty()) { - if (auto clients = pluginInterface_->getClients()) { - for (const auto& c : *clients) { - if (c.uniqueIdentifier == **uid) { - bool admin = false; - for (uint64_t ag : - config_.teamspeak.adminGroups) { - for (uint64_t cg : c.serverGroups) { - if (ag == cg) { - admin = true; - } - } - } - if (admin) { - std::lock_guard<std::mutex> lock( - adminMutex_); - adminClients_.push_back(clientId); - } - break; - } - } - } - } - return toJson(Dto::SuccessMessage{ - .message = "Authentication successful"}); - } else { + auto identity = identityForToken(*req.token); + if (!identity) { return Api::fail( Api::ErrorCode::PermissionDenied, "Invalid token"); } + registerRpcAuth(clientId, *identity); + return toJson(Dto::AuthSuccess{ + .message = "Authentication successful", + .isAdmin = identity->isAdmin, + .isDj = identity->isDj, + .uid = identity->uid, + .nickname = identity->nickname}); } // If nickname provided, search for subscriber and send token @@ -178,6 +166,301 @@ namespace Echoion::Core static_cast<int>(Api::RpcMethod::ValidateLoginToken)), authHandler); + // Address-based autologin: if the caller's network address matches an + // online subscriber's TeamSpeak address, sign them in without a typed + // token and hand back their persistent one. Trust tradeoff: clients + // behind one NAT share an address — acceptable for a private bot. + rpcServer_->registerHandler( + std::to_string( + static_cast<int>(Api::RpcMethod::AuthenticateByAddress)), + [this](const std::string&, + uint64_t clientId) -> Api::Result<std::string> { + if (!database_ || !musicManager_ || !pluginInterface_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Autologin unavailable"); + } + auto address = rpcServer_->getClientAddress(clientId); + if (!address) { + return Api::fail(Api::ErrorCode::NotFound, + "Caller address unknown"); + } + const auto onlineUids = + musicManager_->getOnlineSubscriberUids(); + auto clients = pluginInterface_->getClients(); + if (!clients) { + return std::unexpected(clients.error()); + } + for (const auto& c : *clients) { + if (!c.uniqueIdentifier || + !onlineUids.contains(*c.uniqueIdentifier)) { + continue; + } + auto ip = pluginInterface_->getClientIp(c.id); + if (!ip || !ip->has_value() || **ip != *address) { + continue; + } + const std::string& uid = *c.uniqueIdentifier; + // Reuse (or mint) the user's persistent token so the + // browser can store a normal session credential. + std::string token; + auto existing = database_->getExistingRpcToken(uid); + if (existing && existing->has_value()) { + token = **existing; + } else { + auto minted = database_->generateRpcToken(uid); + if (!minted) { + return std::unexpected(minted.error()); + } + token = *minted; + } + auto identity = identityForToken(token); + if (!identity) { + break; + } + registerRpcAuth(clientId, *identity); + return toJson(Dto::AuthSuccess{ + .message = "Signed in by network address", + .isAdmin = identity->isAdmin, + .isDj = identity->isDj, + .uid = identity->uid, + .nickname = identity->nickname, + .token = token}); + } + return Api::fail(Api::ErrorCode::NotFound, + "No online subscriber matches this address"); + }); + +#ifdef ECHOION_WITH_WEB + // Restart the web interface in place (config edits to web.* take + // effect after ReloadConfig + this). The browser reaches the RPC + // through the web server's own /rpc bridge, so respond first and + // restart on a delayed background thread; watch rooms live in the + // HttpServer object and survive the stop()/start(). + rpcServer_->registerHandler( + std::to_string( + static_cast<int>(Api::RpcMethod::RestartWebInterface)), + [this](const std::string&, + uint64_t clientId) -> Api::Result<std::string> { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!webServer_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Web interface is not running"); + } + if (webRestartPending_.exchange(true)) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Restart already in progress"); + } + Web::HttpServer::Config webCfg; + webCfg.port = config_.web.port; + webCfg.bindAddress = config_.web.bindAddress; + webCfg.webRoot = config_.web.webRoot; + webCfg.rpcUrl = config_.web.rpcUrl; + webCfg.nowPlayingVideo = config_.web.nowPlayingVideo; + webCfg.rpcPort = config_.network.rpcPort > 0 + ? config_.network.rpcPort + : 8765; + const bool enabled = config_.web.enabled; + std::thread([this, webCfg, enabled]() { + std::this_thread::sleep_for( + std::chrono::milliseconds(500)); + webServer_->stop(); + if (enabled && !webServer_->start(webCfg)) { + Void::Log::error("Core", "{}", + "Web interface failed to restart"); + } + webRestartPending_ = false; + }).detach(); + return toJson(Dto::SuccessMessage{ + .message = "Web interface restarting"}); + }); +#endif + + // Per-user preferences. Language shares the "lang:<uid>" kv key with + // the !lang chat command, so switching in the web UI and in + // TeamSpeak are the same setting. + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::GetUserPrefs)), + [this](const std::string&, + uint64_t clientId) -> Api::Result<std::string> { + auto identity = rpcIdentity(clientId); + if (!identity || !database_) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Authentication required"); + } + Dto::UserPrefs prefs; + if (auto lang = database_->getKv("lang:" + identity->uid); + lang && lang->has_value()) { + prefs.language = **lang; + } + return toJson(prefs); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::SetUserPrefs)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result<std::string> { + auto identity = rpcIdentity(clientId); + if (!identity || !database_) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Authentication required"); + } + auto parsed = Void::Json::parse(params); + if (!parsed) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid parameters"); + } + auto prefs = Void::Json::from_json<Dto::UserPrefs>(*parsed); + if (!prefs) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid parameters"); + } + if (!prefs->language.empty()) { + if (prefs->language != "en" && prefs->language != "ru") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Unsupported language"); + } + auto res = database_->setKv("lang:" + identity->uid, + prefs->language); + if (!res) { + return std::unexpected(res.error()); + } + } + return toJson(*prefs); + }); + + // ── Custom emojis (web watch chat/reactions) ──────────────────────── + // Listing is open to any authenticated user; adding/removing is + // admin-only. Images are served at GET /emoji/<name>. + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::GetCustomEmojis)), + [this](const std::string&, + uint64_t) -> Api::Result<std::string> { + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto emojis = database_->getCustomEmojis(); + if (!emojis) { + return std::unexpected(emojis.error()); + } + Dto::CustomEmojiList list; + for (const auto& e : *emojis) { + list.emojis.push_back(Dto::CustomEmojiDto{ + .name = e.name, + .mime = e.mime, + .addedBy = e.addedBy}); + } + return toJson(list); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::AddCustomEmoji)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result<std::string> { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto parsed = Void::Json::parse(params); + if (!parsed) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid parameters"); + } + auto req = + Void::Json::from_json<Dto::AddEmojiRequest>(*parsed); + if (!req) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid parameters"); + } + // Shortcode-safe name: [a-z0-9_], 1..32 chars. + const std::string& name = req->name; + const bool nameOk = + !name.empty() && name.size() <= 32 && + std::all_of(name.begin(), name.end(), [](char c) { + return (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || c == '_'; + }); + if (!nameOk) { + return Api::fail( + Api::ErrorCode::InvalidArgument, + "Emoji name must be 1-32 chars of a-z, 0-9, _"); + } + // Cap the payload (~64KB image → ~88KB base64). + if (req->dataBase64.size() > 90000) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Emoji image too large (max ~64KB)"); + } + if (req->mime != "image/png" && req->mime != "image/gif" && + req->mime != "image/webp" && req->mime != "image/jpeg") { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Unsupported image type"); + } + auto res = database_->addCustomEmoji( + name, req->mime, req->dataBase64, + std::to_string(clientId)); + if (!res) { + return std::unexpected(res.error()); + } + return toJson(Dto::CustomEmojiDto{.name = name, + .mime = req->mime}); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast<int>(Api::RpcMethod::RemoveCustomEmoji)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result<std::string> { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto parsed = Void::Json::parse(params); + if (!parsed) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid parameters"); + } + auto req = + Void::Json::from_json<Dto::EmojiNameRequest>(*parsed); + if (!req || req->name.empty()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid parameters"); + } + auto res = database_->removeCustomEmoji(req->name); + if (!res) { + return std::unexpected(res.error()); + } + return toJson(Dto::Success{}); + }); + + // Radio (autoplay) toggle — same switch as the !autoplay command. + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::ToggleAutoplay)), + [this](const std::string&, + uint64_t clientId) -> Api::Result<std::string> { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!musicManager_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Music manager unavailable"); + } + const bool enabled = !musicManager_->autoplayEnabled(); + musicManager_->setAutoplay(enabled); + return toJson(Dto::Autoplay{.autoplay = enabled}); + }); + // Playback control rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::Play)), @@ -209,8 +492,8 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::Pause)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result<std::string> { + [this](const std::string& /*params*/, + uint64_t /*clientId*/) -> Api::Result<std::string> { auto result = pause(); if (!result) { return std::unexpected(result.error()); @@ -220,8 +503,8 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::Resume)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result<std::string> { + [this](const std::string& /*params*/, + uint64_t /*clientId*/) -> Api::Result<std::string> { auto result = resume(); if (!result) { return std::unexpected(result.error()); @@ -231,8 +514,8 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::Stop)), - [this](const std::string& params, - uint64_t clientId) -> Api::Result<std::string> { + [this](const std::string& /*params*/, + uint64_t /*clientId*/) -> Api::Result<std::string> { auto result = stop(); if (!result) { return std::unexpected(result.error()); @@ -240,10 +523,18 @@ namespace Echoion::Core return toJson(Dto::Success{}); }); + // Skip over RPC is a force-skip: DJ/Admin only. Regular web users + // skip through VoteSkip instead. (The !skip chat command is + // unaffected.) rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::Skip)), [this](const std::string& params, - uint64_t) -> Api::Result<std::string> { + uint64_t clientId) -> Api::Result<std::string> { + if (!isAdmin(clientId) && !isDj(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "DJ or admin privileges required — use " + "vote skip instead"); + } uint32_t count = 1; if (auto parsed = Void::Json::parse(params)) { if (auto req = @@ -261,7 +552,7 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::SetVolume)), [this](const std::string& params, - uint64_t clientId) -> Api::Result<std::string> { + uint64_t /*clientId*/) -> Api::Result<std::string> { // Parse {"volume":0.0-1.0} via reflection DTO. auto parsed = Void::Json::parse(params); if (!parsed) { @@ -284,7 +575,7 @@ namespace Echoion::Core // Queue management rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::GetQueue)), - [this](const std::string& params, uint64_t clientId) + [this](const std::string& /*params*/, uint64_t /*clientId*/) -> Api::Result<std::string> { auto queue = getQueue(); if (!queue) { @@ -304,7 +595,7 @@ namespace Echoion::Core rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::GetCurrentTrack)), - [this](const std::string& params, uint64_t clientId) + [this](const std::string& /*params*/, uint64_t /*clientId*/) -> Api::Result<std::string> { auto track = getCurrentTrack(); if (!track) { @@ -318,20 +609,65 @@ namespace Echoion::Core return toJson(resp); }); + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::GetLyrics)), + [this](const std::string& /*params*/, + uint64_t /*clientId*/) -> Api::Result<std::string> { + Dto::LyricsResponse resp; + if (!lyricsService_) { + return toJson(resp); // found = false + } + auto track = getCurrentTrack(); + if (!track || !track->has_value()) { + return toJson(resp); + } + const auto& info = track->value().track; + long long durationSec = + info.duration.has_value() + ? info.duration->count() / 1000 + : 0; + auto lyrics = lyricsService_->fetch(info.title, info.artist, + info.album, durationSec); + resp.found = lyrics.found; + resp.plain = lyrics.plain; + resp.source = lyrics.source; + resp.title = lyrics.title; + resp.artist = lyrics.artist; + resp.synced.reserve(lyrics.synced.size()); + for (const auto& line : lyrics.synced) { + resp.synced.push_back( + Dto::LyricsLineDto{.ms = line.ms, .text = line.text}); + } + return toJson(resp); + }); + rpcServer_->registerHandler( std::to_string(static_cast<int>(Api::RpcMethod::GetStatus)), - [this](const std::string& params, + [this](const std::string& /*params*/, uint64_t clientId) -> Api::Result<std::string> { auto state = getPlaybackState(); if (!state) { return std::unexpected(state.error()); } - return toJson(Dto::Status{.isPlaying = state->isPlaying, - .isPaused = state->isPaused, - .volume = state->volume, - .repeat = state->repeat, - .shuffle = state->shuffle}); + MusicManager::VoteSkipStatus voteSkip; + if (musicManager_) { + auto identity = rpcIdentity(clientId); + voteSkip = musicManager_->voteSkipStatus( + identity ? identity->uid : ""); + } + return toJson( + Dto::Status{.isPlaying = state->isPlaying, + .isPaused = state->isPaused, + .volume = state->volume, + .repeat = state->repeat, + .shuffle = state->shuffle, + .autoplay = musicManager_ + ? musicManager_->autoplayEnabled() + : false, + .skipVotes = voteSkip.votes, + .skipVotesNeeded = voteSkip.needed, + .skipVoted = voteSkip.voted}); }); rpcServer_->registerHandler( @@ -780,6 +1116,11 @@ namespace Echoion::Core { std::lock_guard<std::mutex> lock(adminMutex_); std::erase(adminClients_, clientId); + std::erase(djClients_, clientId); + } + { + std::lock_guard<std::mutex> lock(rpcIdentityMutex_); + rpcIdentities_.erase(clientId); } return toJson(Dto::Success{}); }); @@ -803,6 +1144,25 @@ namespace Echoion::Core info.queueLength = static_cast<std::uint32_t>(queue->size()); } + if (musicManager_) { + const auto onlineUids = + musicManager_->getOnlineSubscriberUids(); + info.onlineSubscribers = + static_cast<std::uint32_t>(onlineUids.size()); + // Nicknames for the non-admin "listening now" card. + if (database_) { + if (auto subs = database_->getAllSubscribers()) { + for (const auto& s : *subs) { + if (onlineUids.contains(s.uid)) { + info.onlineSubscriberNames.push_back( + s.nickname.empty() ? s.uid + : s.nickname); + info.onlineSubscriberUids.push_back(s.uid); + } + } + } + } + } return toJson(info); }); @@ -855,8 +1215,29 @@ namespace Echoion::Core return Api::fail(Api::ErrorCode::InvalidArgument, "uid required for remove"); } - auto result = database_->removeSubscriber(*req->uid); - if (!result) { + // Through MusicManager so runtime state (whisper list, + // pause-on-empty) stays consistent with the database. + if (musicManager_) { + auto result = + musicManager_->unsubscribeByUid(*req->uid); + if (!result) { + return std::unexpected(result.error()); + } + } else if (auto result = + database_->removeSubscriber(*req->uid); + !result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + } + if (req->action == "clearAll") { + if (musicManager_) { + auto result = musicManager_->clearAllSubscriptions(); + if (!result) { + return std::unexpected(result.error()); + } + } else if (auto result = database_->clearAllSubscribers(); + !result) { return std::unexpected(result.error()); } return toJson(Dto::Success{}); @@ -866,11 +1247,17 @@ namespace Echoion::Core if (!subs) { return std::unexpected(subs.error()); } + std::set<std::string> online; + if (musicManager_) { + online = musicManager_->getOnlineSubscriberUids(); + } Dto::UsersResponse resp; resp.users.reserve(subs->size()); for (const auto& s : *subs) { resp.users.push_back(Dto::SubscriberDto{ - .uid = s.uid, .nickname = s.nickname}); + .uid = s.uid, + .nickname = s.nickname, + .online = online.contains(s.uid)}); } return toJson(resp); }); @@ -909,6 +1296,193 @@ namespace Echoion::Core .message = "Shutting down"}); }); + // ── Web UI additions ──────────────────────────────────────────────── + + // Resolves the caller's stable uid; per-user methods refuse clients + // that authenticated before identities were tracked (re-auth fixes). + auto requireUid = + [this](uint64_t clientId) -> Api::Result<std::string> { + auto identity = rpcIdentity(clientId); + if (!identity || identity->uid.empty()) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Token authentication required"); + } + return identity->uid; + }; + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::GetFavorites)), + [this, requireUid](const std::string&, + uint64_t clientId) -> Api::Result<std::string> { + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto uid = requireUid(clientId); + if (!uid) { + return std::unexpected(uid.error()); + } + auto favorites = database_->getFavorites(uidHash(*uid)); + if (!favorites) { + return std::unexpected(favorites.error()); + } + Dto::FavoritesResponse resp; + resp.tracks.reserve(favorites->size()); + for (const auto& fav : *favorites) { + resp.tracks.push_back(Dto::toTrack(fav.track)); + } + return toJson(resp); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::AddFavorite)), + [this, requireUid](const std::string& params, + uint64_t clientId) -> Api::Result<std::string> { + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto uid = requireUid(clientId); + if (!uid) { + return std::unexpected(uid.error()); + } + auto parsed = Void::Json::parse(params); + if (!parsed) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid add-favorite request"); + } + auto req = + Void::Json::from_json<Dto::AddFavoriteRequest>(*parsed); + if (!req || (!req->track.url && req->track.title.empty())) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Track is required"); + } + auto result = database_->addFavorite( + uidHash(*uid), Dto::fromTrack(req->track)); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::RemoveFavorite)), + [this, requireUid](const std::string& params, + uint64_t clientId) -> Api::Result<std::string> { + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto uid = requireUid(clientId); + if (!uid) { + return std::unexpected(uid.error()); + } + auto parsed = Void::Json::parse(params); + if (!parsed) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid remove-favorite request"); + } + auto req = Void::Json::from_json<Dto::UrlRequest>(*parsed); + if (!req || req->url.empty()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Track url is required"); + } + auto result = + database_->removeFavorite(uidHash(*uid), req->url); + if (!result) { + return std::unexpected(result.error()); + } + return toJson(Dto::Success{}); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::VoteSkip)), + [this, requireUid](const std::string&, + uint64_t clientId) -> Api::Result<std::string> { + if (!musicManager_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Music manager unavailable"); + } + auto uid = requireUid(clientId); + if (!uid) { + return std::unexpected(uid.error()); + } + auto status = musicManager_->voteSkip(*uid); + if (!status) { + return std::unexpected(status.error()); + } + const Dto::VoteSkipResponse resp{ + .votes = status->votes, + .needed = status->needed, + .voted = status->voted, + .skipped = status->skipped}; + rpcServer_->broadcastEvent("voteskip.updated", toJson(resp)); + return toJson(resp); + }); + + rpcServer_->registerHandler( + std::to_string(static_cast<int>(Api::RpcMethod::Announce)), + [this](const std::string& params, + uint64_t clientId) -> Api::Result<std::string> { + if (!isAdmin(clientId)) { + return Api::fail(Api::ErrorCode::PermissionDenied, + "Admin privileges required"); + } + if (!musicManager_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Music manager unavailable"); + } + auto parsed = Void::Json::parse(params); + if (!parsed) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Invalid announce request"); + } + auto req = Void::Json::from_json<Dto::AnnounceRequest>(*parsed); + if (!req || req->text.empty()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Announcement text is required"); + } + const size_t reached = + musicManager_->setAnnouncement(req->text); + return toJson(Dto::SuccessMessage{ + .message = std::format( + "Announcement delivered to {} online subscriber(s)", + reached)}); + }); + + rpcServer_->registerHandler( + std::to_string( + static_cast<int>(Api::RpcMethod::GetAggregateStats)), + [this](const std::string&, + uint64_t) -> Api::Result<std::string> { + if (!database_) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "Database unavailable"); + } + auto stats = database_->getAggregateStats(); + if (!stats) { + return std::unexpected(stats.error()); + } + Dto::AggregateStatsResponse resp; + resp.tracksToday = stats->tracksToday; + resp.listeningMsToday = stats->listeningMsToday; + resp.queueAdditionsToday = stats->queueAdditionsToday; + resp.skipsToday = stats->skipsToday; + resp.playsTotal = stats->playsTotal; + resp.skipsTotal = stats->skipsTotal; + resp.topRequesters.reserve(stats->topRequesters.size()); + for (const auto& r : stats->topRequesters) { + resp.topRequesters.push_back( + Dto::RequesterDto{.uid = r.uid, + .nickname = r.nickname, + .count = r.count}); + } + resp.youtubeCount = stats->youtubeCount; + resp.yandexCount = stats->yandexCount; + resp.otherCount = stats->otherCount; + return toJson(resp); + }); + Void::Log::info("Core", "{}", "RPC handlers registered"); } diff --git a/src/Database.cpp b/src/Database.cpp index 1d3eb72..a1470fb 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -2,6 +2,7 @@ #include <Void/Log/Log.hpp> #include <Void/Math/Random.hpp> #include <Void/Sqlite/Sqlite.hpp> +#include <algorithm> #include <cstring> #include <format> #include <shared_mutex> @@ -312,7 +313,115 @@ namespace Echoion::Api "Database migration 6 applied: track_short_url columns added"); } - impl_->version = 6; + // Migration 7: aggregate-stats support — skip tracking on history and + // a queue-addition log (daily counters + top requesters for the web + // dashboard). + if (currentVersion < 7) { + const char* migration7 = R"( + ALTER TABLE playback_history ADD COLUMN skipped INTEGER DEFAULT 0; + CREATE TABLE IF NOT EXISTS queue_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + uid TEXT, + nickname TEXT, + added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ); + CREATE INDEX IF NOT EXISTS idx_queue_log_date ON queue_log(added_at); + )"; + + if (auto r = impl_->voidDb.exec(migration7); !r) { + return fail(ErrorCode::DatabaseError, r.error().message()); + } + + [[maybe_unused]] auto ins = impl_->voidDb.exec( + "INSERT INTO schema_migrations (version) VALUES (7)"); + + Void::Log::info("Database", "{}", + "Database migration 7 applied: skip tracking and queue log"); + } + + // Migration 8: persist track thumbnails with history and favorites so + // the web UI can show original artwork for reconstructed tracks + // (playlist_tracks already stores track_thumbnail since v1). + if (currentVersion < 8) { + const char* migration8 = R"( + ALTER TABLE playback_history ADD COLUMN track_thumbnail TEXT; + ALTER TABLE user_favorites ADD COLUMN track_thumbnail TEXT; + )"; + + if (auto r = impl_->voidDb.exec(migration8); !r) { + return fail(ErrorCode::DatabaseError, r.error().message()); + } + + [[maybe_unused]] auto ins = impl_->voidDb.exec( + "INSERT INTO schema_migrations (version) VALUES (8)"); + + Void::Log::info("Database", "{}", + "Database migration 8 applied: track_thumbnail columns added"); + } + + // Migration 9: custom emojis for the web UI (admin-managed image + // emotes, referenced by :name: shortcodes in watch chat/reactions). + if (currentVersion < 9) { + const char* migration9 = R"( + CREATE TABLE IF NOT EXISTS custom_emojis ( + name TEXT PRIMARY KEY, + mime TEXT NOT NULL, + data TEXT NOT NULL, -- base64-encoded image bytes + added_by TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ); + )"; + + if (auto r = impl_->voidDb.exec(migration9); !r) { + return fail(ErrorCode::DatabaseError, r.error().message()); + } + + [[maybe_unused]] auto ins = impl_->voidDb.exec( + "INSERT INTO schema_migrations (version) VALUES (9)"); + + Void::Log::info("Database", "{}", + "Database migration 9 applied: custom_emojis table added"); + } + + // Migration 10: cached TeamSpeak avatars for the web UI, keyed by uid, + // so avatars survive the client going offline/out-of-view. + if (currentVersion < 10) { + const char* migration10 = R"( + CREATE TABLE IF NOT EXISTS cached_avatars ( + uid TEXT PRIMARY KEY, + mime TEXT NOT NULL, + data TEXT NOT NULL, -- base64-encoded image bytes + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ); + )"; + + if (auto r = impl_->voidDb.exec(migration10); !r) { + return fail(ErrorCode::DatabaseError, r.error().message()); + } + + [[maybe_unused]] auto ins = impl_->voidDb.exec( + "INSERT INTO schema_migrations (version) VALUES (10)"); + + Void::Log::info("Database", "{}", + "Database migration 10 applied: cached_avatars table added"); + } + + // Migration 11: remember the source avatar URL alongside the cached + // bytes, so an offline user's avatar can be re-fetched from it. + if (currentVersion < 11) { + // ADD COLUMN is a no-op-safe schema bump; ignore "duplicate column" + // if a prior partial run already added it. + [[maybe_unused]] auto alt = impl_->voidDb.exec( + "ALTER TABLE cached_avatars ADD COLUMN url TEXT;"); + + [[maybe_unused]] auto ins = impl_->voidDb.exec( + "INSERT INTO schema_migrations (version) VALUES (11)"); + + Void::Log::info("Database", "{}", + "Database migration 11 applied: cached_avatars.url added"); + } + + impl_->version = 11; return {}; } @@ -576,8 +685,8 @@ namespace Echoion::Api const char* sql = R"( INSERT INTO playback_history - (track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url) - VALUES (?, ?, ?, ?, ?, ?, ?); + (track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url, track_thumbnail) + VALUES (?, ?, ?, ?, ?, ?, ?, ?); )"; auto stmtRes = impl_->voidDb.prepare(sql); @@ -591,7 +700,53 @@ namespace Echoion::Api .bind(4, static_cast<std::int64_t>(playedBy)) .bind(5, static_cast<std::int64_t>(duration.count())) .bind(6, completed ? 1 : 0) - .bind(7, track.shortenedUrl.value_or("")); + .bind(7, track.shortenedUrl.value_or("")) + .bind(8, track.thumbnailUrl.value_or("")); + [[maybe_unused]] auto stepRes = stmt.step(); + + return {}; + } + + Result<void> Database::recordSkip(const TrackInfo& track, uint64_t playedBy) + { + std::unique_lock<std::shared_mutex> lock(mutex_); + + const char* sql = R"( + INSERT INTO playback_history + (track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url, track_thumbnail, skipped) + VALUES (?, ?, ?, ?, 0, 0, ?, ?, 1); + )"; + + auto stmtRes = impl_->voidDb.prepare(sql); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, track.originalUrl) + .bind(2, track.title) + .bind(3, track.artist) + .bind(4, static_cast<std::int64_t>(playedBy)) + .bind(5, track.shortenedUrl.value_or("")) + .bind(6, track.thumbnailUrl.value_or("")); + [[maybe_unused]] auto stepRes = stmt.step(); + + return {}; + } + + Result<void> Database::logQueueAddition(const std::string& uid, + const std::string& nickname) + { + std::unique_lock<std::shared_mutex> lock(mutex_); + + const char* sql = + "INSERT INTO queue_log (uid, nickname) VALUES (?, ?);"; + + auto stmtRes = impl_->voidDb.prepare(sql); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, uid).bind(2, nickname); [[maybe_unused]] auto stepRes = stmt.step(); return {}; @@ -606,7 +761,7 @@ namespace Echoion::Api std::vector<PlaybackHistoryEntry> history; const char* sql = R"( - SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed, track_short_url + SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed, track_short_url, track_thumbnail FROM playback_history WHERE played_by = ? ORDER BY played_at DESC @@ -635,6 +790,9 @@ namespace Echoion::Api if (auto shortUrl = stmt.column_text(7); !shortUrl.empty()) { entry.track.shortenedUrl = shortUrl; } + if (auto thumb = stmt.column_text(8); !thumb.empty()) { + entry.track.thumbnailUrl = thumb; + } history.push_back(entry); } @@ -647,8 +805,8 @@ namespace Echoion::Api std::unique_lock<std::shared_mutex> lock(mutex_); const char* sql = R"( INSERT OR REPLACE INTO user_favorites - (user_id, track_url, track_title, track_artist, track_short_url) - VALUES (?, ?, ?, ?, ?); + (user_id, track_url, track_title, track_artist, track_short_url, track_thumbnail) + VALUES (?, ?, ?, ?, ?, ?); )"; auto stmtRes = impl_->voidDb.prepare(sql); @@ -662,6 +820,7 @@ namespace Echoion::Api stmt.bind(3, track.title); stmt.bind(4, track.artist); stmt.bind(5, track.shortenedUrl.value_or("")); + stmt.bind(6, track.thumbnailUrl.value_or("")); [[maybe_unused]] auto stepRes = stmt.step(); @@ -716,7 +875,7 @@ namespace Echoion::Api std::vector<FavoriteTrack> favorites; const char* sql = R"( - SELECT track_url, track_title, track_artist, added_at, track_short_url + SELECT track_url, track_title, track_artist, added_at, track_short_url, track_thumbnail FROM user_favorites WHERE user_id = ? ORDER BY added_at DESC; @@ -741,6 +900,9 @@ namespace Echoion::Api if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) { fav.track.shortenedUrl = shortUrl; } + if (auto thumb = stmt.column_text(5); !thumb.empty()) { + fav.track.thumbnailUrl = thumb; + } fav.userId = userId; favorites.push_back(fav); } @@ -1052,7 +1214,7 @@ namespace Echoion::Api // userId 0 = global history. Deduplicate by URL, newest first. const char* sql = R"( - SELECT track_url, track_title, track_artist, MAX(played_at), MAX(track_short_url) + SELECT track_url, track_title, track_artist, MAX(played_at), MAX(track_short_url), MAX(track_thumbnail) FROM playback_history WHERE (?1 = 0 OR played_by = ?1) GROUP BY track_url @@ -1076,6 +1238,9 @@ namespace Echoion::Api if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) { track.shortenedUrl = shortUrl; } + if (auto thumb = stmt.column_text(5); !thumb.empty()) { + track.thumbnailUrl = thumb; + } tracks.push_back(std::move(track)); } return tracks; @@ -1169,6 +1334,90 @@ namespace Echoion::Api return result; } + Result<AggregateStats> Database::getAggregateStats() + { + std::shared_lock<std::shared_mutex> lock(mutex_); + AggregateStats stats; + + // played_at/added_at are CURRENT_TIMESTAMP (UTC); "today" follows the + // same clock. + { + const char* sql = R"( + SELECT + SUM(CASE WHEN completed = 1 AND date(played_at) = date('now') THEN 1 ELSE 0 END), + SUM(CASE WHEN completed = 1 AND date(played_at) = date('now') THEN duration_ms ELSE 0 END), + SUM(CASE WHEN skipped = 1 AND date(played_at) = date('now') THEN 1 ELSE 0 END), + SUM(CASE WHEN completed = 1 THEN 1 ELSE 0 END), + SUM(CASE WHEN skipped = 1 THEN 1 ELSE 0 END), + SUM(CASE WHEN track_url LIKE '%youtu%' THEN 1 ELSE 0 END), + SUM(CASE WHEN track_url LIKE '%yandex%' THEN 1 ELSE 0 END), + COUNT(*) + FROM playback_history; + )"; + auto stmtRes = impl_->voidDb.prepare(sql); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, + stmtRes.error().message()); + } + auto& stmt = *stmtRes; + if (stmt.step().value_or(false)) { + stats.tracksToday = static_cast<uint64_t>(stmt.column_int(0)); + stats.listeningMsToday = + static_cast<uint64_t>(stmt.column_int(1)); + stats.skipsToday = static_cast<uint64_t>(stmt.column_int(2)); + stats.playsTotal = static_cast<uint64_t>(stmt.column_int(3)); + stats.skipsTotal = static_cast<uint64_t>(stmt.column_int(4)); + stats.youtubeCount = static_cast<uint64_t>(stmt.column_int(5)); + stats.yandexCount = static_cast<uint64_t>(stmt.column_int(6)); + const auto total = static_cast<uint64_t>(stmt.column_int(7)); + stats.otherCount = + total - std::min(total, stats.youtubeCount + + stats.yandexCount); + } + } + + { + const char* sql = R"( + SELECT COUNT(*) FROM queue_log WHERE date(added_at) = date('now'); + )"; + auto stmtRes = impl_->voidDb.prepare(sql); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, + stmtRes.error().message()); + } + auto& stmt = *stmtRes; + if (stmt.step().value_or(false)) { + stats.queueAdditionsToday = + static_cast<uint64_t>(stmt.column_int(0)); + } + } + + { + const char* sql = R"( + SELECT nickname, COUNT(*) AS adds, MAX(uid) AS uid + FROM queue_log + WHERE nickname IS NOT NULL AND nickname != '' + GROUP BY nickname + ORDER BY adds DESC + LIMIT 5; + )"; + auto stmtRes = impl_->voidDb.prepare(sql); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, + stmtRes.error().message()); + } + auto& stmt = *stmtRes; + while (stmt.step().value_or(false)) { + stats.topRequesters.push_back(AggregateStats::TopRequester{ + .uid = stmt.column_text(2), + .nickname = stmt.column_text(0), + .count = static_cast<uint64_t>(stmt.column_int(1))}); + } + } + + return stats; + } + Result<std::optional<std::string>> Database::getKv(const std::string& key) { std::shared_lock<std::shared_mutex> lock(mutex_); @@ -1202,6 +1451,152 @@ namespace Echoion::Api return {}; } + Result<std::vector<Database::CustomEmoji>> Database::getCustomEmojis() + { + std::shared_lock<std::shared_mutex> lock(mutex_); + auto stmtRes = impl_->voidDb.prepare( + "SELECT name, mime, data, added_by FROM custom_emojis " + "ORDER BY name;"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + std::vector<CustomEmoji> out; + while (stmt.step().value_or(false)) { + out.push_back(CustomEmoji{.name = stmt.column_text(0), + .mime = stmt.column_text(1), + .dataBase64 = stmt.column_text(2), + .addedBy = stmt.column_text(3)}); + } + return out; + } + + Result<std::optional<Database::CustomEmoji>> + Database::getCustomEmoji(const std::string& name) + { + std::shared_lock<std::shared_mutex> lock(mutex_); + auto stmtRes = impl_->voidDb.prepare( + "SELECT name, mime, data, added_by FROM custom_emojis " + "WHERE name = ?;"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, name); + if (stmt.step().value_or(false)) { + return std::optional<CustomEmoji>{ + CustomEmoji{.name = stmt.column_text(0), + .mime = stmt.column_text(1), + .dataBase64 = stmt.column_text(2), + .addedBy = stmt.column_text(3)}}; + } + return std::optional<CustomEmoji>{}; + } + + Result<void> Database::addCustomEmoji(const std::string& name, + const std::string& mime, + const std::string& dataBase64, + const std::string& addedBy) + { + std::unique_lock<std::shared_mutex> lock(mutex_); + auto stmtRes = impl_->voidDb.prepare(R"( + INSERT OR REPLACE INTO custom_emojis (name, mime, data, added_by) + VALUES (?, ?, ?, ?); + )"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, name).bind(2, mime).bind(3, dataBase64).bind(4, addedBy); + if (auto stepRes = stmt.step(); !stepRes) { + return fail(ErrorCode::DatabaseError, stepRes.error().message()); + } + return {}; + } + + Result<void> Database::removeCustomEmoji(const std::string& name) + { + std::unique_lock<std::shared_mutex> lock(mutex_); + auto stmtRes = + impl_->voidDb.prepare("DELETE FROM custom_emojis WHERE name = ?;"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, name); + [[maybe_unused]] auto stepRes = stmt.step(); + return {}; + } + + Result<std::optional<Database::CachedAvatar>> + Database::getCachedAvatar(const std::string& uid) + { + std::shared_lock<std::shared_mutex> lock(mutex_); + auto stmtRes = impl_->voidDb.prepare( + "SELECT uid, mime, data, COALESCE(url, '') FROM cached_avatars " + "WHERE uid = ?;"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, uid); + if (stmt.step().value_or(false)) { + return std::optional<CachedAvatar>{ + CachedAvatar{.uid = stmt.column_text(0), + .mime = stmt.column_text(1), + .dataBase64 = stmt.column_text(2), + .url = stmt.column_text(3)}}; + } + return std::optional<CachedAvatar>{}; + } + + Result<void> Database::putCachedAvatar(const std::string& uid, + const std::string& mime, + const std::string& dataBase64) + { + std::unique_lock<std::shared_mutex> lock(mutex_); + // Upsert the image but keep any url already recorded for this uid. + auto stmtRes = impl_->voidDb.prepare(R"( + INSERT INTO cached_avatars (uid, mime, data, updated_at) + VALUES (?, ?, ?, CURRENT_TIMESTAMP) + ON CONFLICT(uid) DO UPDATE SET + mime = excluded.mime, + data = excluded.data, + updated_at = CURRENT_TIMESTAMP; + )"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, uid).bind(2, mime).bind(3, dataBase64); + if (auto stepRes = stmt.step(); !stepRes) { + return fail(ErrorCode::DatabaseError, stepRes.error().message()); + } + return {}; + } + + Result<void> Database::putCachedAvatarUrl(const std::string& uid, + const std::string& url) + { + std::unique_lock<std::shared_mutex> lock(mutex_); + // Insert a url-only row (empty mime/data satisfy NOT NULL) or update the + // url on an existing one, without touching cached bytes. + auto stmtRes = impl_->voidDb.prepare(R"( + INSERT INTO cached_avatars (uid, mime, data, url) + VALUES (?, '', '', ?) + ON CONFLICT(uid) DO UPDATE SET url = excluded.url; + )"); + if (!stmtRes) { + return fail(ErrorCode::DatabaseError, stmtRes.error().message()); + } + auto& stmt = *stmtRes; + stmt.bind(1, uid).bind(2, url); + if (auto stepRes = stmt.step(); !stepRes) { + return fail(ErrorCode::DatabaseError, stepRes.error().message()); + } + return {}; + } + Result<void> Database::executeQuery(const std::string& sql, RowCallback callback) { diff --git a/src/LyricsService.cpp b/src/LyricsService.cpp new file mode 100644 index 0000000..13208d0 --- /dev/null +++ b/src/LyricsService.cpp @@ -0,0 +1,239 @@ +#include "echoion/core/LyricsService.hpp" + +#include <Void/Data/Json.hpp> +#include <Void/Log/Log.hpp> +#include <algorithm> +#include <cctype> +#include <charconv> +#include <format> +#include <sstream> + +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<char>(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) + { + const auto* v = obj.find(key); + if (v && v->is_string()) { + return v->as_string(); + } + return {}; + } + + bool boolField(const Void::Json::Value& obj, std::string_view key) + { + const auto* v = obj.find(key); + return v && v->is_bool() && v->as_bool(); + } + } // namespace + + LyricsService::LyricsService(std::shared_ptr<NetworkClient> net) + : net_(std::move(net)) + { + } + + LyricsService::Lyrics LyricsService::fetch(const std::string& title, + const std::string& artist, + const std::string& album, + long long durationSec) + { + if (title.empty()) { + return {}; + } + + const std::string key = + std::format("{}|{}|{}", artist, title, durationSec); + { + std::lock_guard<std::mutex> lock(mutex_); + auto it = cache_.find(key); + if (it != cache_.end() && + std::chrono::steady_clock::now() - it->second.at < kCacheTtl) { + return it->second.value; + } + } + + Lyrics result = fetchUncached(title, artist, album, durationSec); + + { + std::lock_guard<std::mutex> lock(mutex_); + cache_[key] = Entry{result, std::chrono::steady_clock::now()}; + } + return result; + } + + LyricsService::Lyrics + LyricsService::fetchUncached(const std::string& title, + const std::string& artist, + const std::string& album, + long long durationSec) const + { + if (!net_) { + return {}; + } + + // Turn one lrclib track object into our Lyrics shape. + auto fromObject = [&](const Void::Json::Value& obj) -> Lyrics { + Lyrics out; + if (boolField(obj, "instrumental")) { + out.found = true; + out.plain = "[Instrumental]"; + out.source = "lrclib"; + out.title = strField(obj, "trackName"); + out.artist = strField(obj, "artistName"); + return out; + } + const std::string plain = strField(obj, "plainLyrics"); + const std::string synced = strField(obj, "syncedLyrics"); + if (plain.empty() && synced.empty()) { + return {}; + } + out.found = true; + out.plain = plain; + out.synced = parseLrc(synced); + out.source = "lrclib"; + out.title = strField(obj, "trackName"); + out.artist = strField(obj, "artistName"); + // Fall back to the synced text when only synced lyrics exist. + if (out.plain.empty() && !out.synced.empty()) { + std::string joined; + for (const auto& line : out.synced) { + joined += line.text; + joined += '\n'; + } + out.plain = joined; + } + return out; + }; + + // 1) Exact match by artist/title/album/duration. + if (durationSec > 0 && !artist.empty()) { + std::string url = std::format( + "https://lrclib.net/api/get?artist_name={}&track_name={}" + "&duration={}", + urlEncode(artist), urlEncode(title), durationSec); + if (!album.empty()) { + url += std::format("&album_name={}", urlEncode(album)); + } + if (auto resp = net_->get(url); + resp && resp->status == 200 && !resp->body.empty()) { + if (auto parsed = Void::Json::parse(resp->body); + parsed && parsed->is_object()) { + Lyrics out = fromObject(*parsed); + if (out.found) { + return out; + } + } + } + } + + // 2) Search fallback — take the first result that carries lyrics. + std::string searchUrl = + std::format("https://lrclib.net/api/search?track_name={}", + urlEncode(title)); + if (!artist.empty()) { + searchUrl += std::format("&artist_name={}", urlEncode(artist)); + } + if (auto resp = net_->get(searchUrl); + resp && resp->status == 200 && !resp->body.empty()) { + if (auto parsed = Void::Json::parse(resp->body); + parsed && parsed->is_array()) { + for (const auto& entry : parsed->as_array()) { + if (!entry.is_object()) { + continue; + } + Lyrics out = fromObject(entry); + if (out.found) { + return out; + } + } + } + } + + return {}; + } + + std::vector<LyricsService::Line> + LyricsService::parseLrc(const std::string& lrc) + { + std::vector<Line> lines; + if (lrc.empty()) { + return lines; + } + + std::istringstream stream(lrc); + std::string raw; + while (std::getline(stream, raw)) { + if (!raw.empty() && raw.back() == '\r') { + raw.pop_back(); + } + // Collect every [..] timestamp prefix on this line. + std::vector<std::int64_t> stamps; + std::size_t pos = 0; + while (pos < raw.size() && raw[pos] == '[') { + std::size_t close = raw.find(']', pos); + if (close == std::string::npos) { + break; + } + 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<unsigned char>( + 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); + // Parse the seconds part (may be fractional). + std::string sec(tag.substr(colon + 1)); + try { + seconds = std::stod(sec); + } catch (const std::exception&) { + seconds = 0.0; + } + stamps.push_back(static_cast<std::int64_t>( + minutes * 60000LL + + static_cast<std::int64_t>(seconds * 1000.0))); + } + } + pos = close + 1; + } + if (stamps.empty()) { + continue; + } + std::string text = raw.substr(pos); + // Trim leading spaces on the lyric text. + auto start = text.find_first_not_of(" \t"); + text = (start == std::string::npos) ? std::string{} + : text.substr(start); + for (auto ms : stamps) { + lines.push_back(Line{ms, text}); + } + } + + std::sort(lines.begin(), lines.end(), + [](const Line& a, const Line& b) { return a.ms < b.ms; }); + return lines; + } + +} // namespace Echoion::Core diff --git a/src/MusicManager.cpp b/src/MusicManager.cpp index 97407b8..34d8fe0 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -2,14 +2,29 @@ #include "echoion/core/MusicManager.hpp" #include "echoion/core/PlaylistLoader.hpp" #include "echoion/core/sources/DirectUrlSource.hpp" +#include "echoion/core/state/StateVersions.hpp" +#include <Database.hpp> #include <Events.hpp> +#include <Void/Data/Json.hpp> #include <Void/Log/Log.hpp> #include <algorithm> +#include <chrono> #include <filesystem> #include <format> +#include <limits> #include <optional> +#include <set> #include <thread> +namespace +{ + // Radio never queues a track longer than this. Long items (livestreams, + // DJ sets, hour-long mixes) show up in YouTube "mix" playlists and derail + // the station; tracks with unknown duration are still allowed so radio + // doesn't stall on missing metadata. + constexpr auto kRadioMaxTrackDuration = std::chrono::minutes(12); +} // namespace + namespace Echoion::Core { @@ -35,10 +50,14 @@ namespace Echoion::Core // needed if (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) { networkClient_->setProxy(networkConfig.proxy); - Void::Log::info("MusicManager", "{}", std::format( - "NetworkClient using {} proxy: {}:{}", - (networkConfig.proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" : "HTTP", - networkConfig.proxy->host, networkConfig.proxy->port)); + Void::Log::info("MusicManager", "{}", + std::format("NetworkClient using {} proxy: {}:{}", + (networkConfig.proxy->kind == + Void::Net::ProxyConfig::Kind::Socks5) + ? "SOCKS5" + : "HTTP", + networkConfig.proxy->host, + networkConfig.proxy->port)); } youTubeClient_ = std::make_shared<YouTubeClient>(networkClient_); @@ -55,12 +74,14 @@ namespace Echoion::Core // Configure YouTube cookies if provided if (youtubeConfig.youtubeCookiesPath.has_value()) { youTubeClient_->setCookiesPath(*youtubeConfig.youtubeCookiesPath); - Void::Log::info("MusicManager", "{}", std::format("Using YouTube cookies from file: {}", - *youtubeConfig.youtubeCookiesPath)); + Void::Log::info("MusicManager", "{}", + std::format("Using YouTube cookies from file: {}", + *youtubeConfig.youtubeCookiesPath)); } else if (youtubeConfig.cookiesFromBrowser.has_value()) { youTubeClient_->setCookiesFromBrowser( *youtubeConfig.cookiesFromBrowser); - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("Using YouTube cookies from browser: {}", *youtubeConfig.cookiesFromBrowser)); } @@ -88,7 +109,8 @@ namespace Echoion::Core auto ytResult = youTubeClient_->initialize(); if (!ytResult) { - Void::Log::warn("MusicManager", "{}", + Void::Log::warn( + "MusicManager", "{}", std::format("Failed to initialize YouTube client: {}", ytResult.error().message)); } @@ -106,8 +128,7 @@ namespace Echoion::Core // Yandex Music first, direct audio URLs, direct yt-dlp for // non-YouTube extractors, proxied yt-dlp as the last resort. const auto tempDir = - (std::filesystem::temp_directory_path() / "echoion_audio") - .string(); + (std::filesystem::temp_directory_path() / "echoion_audio").string(); innertubeSource_ = std::make_shared<InnertubeSource>(networkClient_); yandexSource_ = std::make_shared<YandexMusicSource>(networkClient_); auto directUrl = std::make_shared<DirectUrlSource>(); @@ -126,7 +147,7 @@ namespace Echoion::Core static_cast<IPlaybackHost&>(*this)); auto engineResult = engine_->initialize( (networkConfig.proxy.has_value() && networkConfig.proxy->enabled()) - ? networkConfig.proxy + ? effectiveEngineProxy(networkConfig.proxy) : std::nullopt); if (!engineResult) { return engineResult; @@ -149,8 +170,7 @@ namespace Echoion::Core } subscriptions_->setPauseResumeHooks( [this]() { - if (!engine_ || !engine_->isPlaying() || - engine_->isPaused()) { + if (!engine_ || !engine_->isPlaying() || engine_->isPaused()) { return false; } engine_->pause(); @@ -167,7 +187,8 @@ namespace Echoion::Core }); auto subResult = subscriptions_->initialize(database); if (!subResult) { - Void::Log::warn("MusicManager", "{}", + Void::Log::warn( + "MusicManager", "{}", std::format("Failed to initialize subscription manager: {}", subResult.error().message)); // Not fatal - continue without subscriptions @@ -181,6 +202,12 @@ namespace Echoion::Core queue_.setRepeat(features.repeatMode != "off" && !features.repeatMode.empty()); + // Restore a queue/mode/autoplay snapshot persisted before the last + // shutdown so a full restart resumes where it left off. Runs after the + // engine/subscriptions/config are ready; maybeAutoStart() inside is a + // no-op until a subscriber is online (onClientConnected handles that). + restoreSession(); + Void::Log::info("MusicManager", "{}", "MusicManager initialized"); return {}; } @@ -200,15 +227,18 @@ namespace Echoion::Core youTubeClient_->setProxyConfig(proxy); } if (engine_) { - engine_->setProxyConfig(proxy); + engine_->setProxyConfig(effectiveEngineProxy(proxy)); } if (enabled) { - Void::Log::info("MusicManager", "{}", std::format( - "Network config re-applied: {} proxy {}:{}", - (proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) ? "SOCKS5" - : "HTTP", - proxy->host, proxy->port)); + Void::Log::info( + "MusicManager", "{}", + std::format( + "Network config re-applied: {} proxy {}:{}", + (proxy->kind == Void::Net::ProxyConfig::Kind::Socks5) + ? "SOCKS5" + : "HTTP", + proxy->host, proxy->port)); } else { Void::Log::info("MusicManager", "{}", "Network config re-applied: proxy disabled"); @@ -238,7 +268,7 @@ namespace Echoion::Core youTubeClient_->setUrlShorteningEnabled(youtube.enableUrlShortening); const bool hasKey = youtube.youtubeApiKey.has_value() && - !youtube.youtubeApiKey->empty(); + !youtube.youtubeApiKey->empty(); Void::Log::info("MusicManager", "{}", std::format("YouTube config re-applied (API key: {})", hasKey ? "set" : "none (yt-dlp)")); @@ -256,6 +286,7 @@ namespace Echoion::Core void MusicManager::applyFeaturesConfig(const Api::FeaturesConfig& features) { autoStartOnSubscribe_ = features.autoStartOnSubscribe; + voteSkipThreshold_ = features.voteSkipThreshold; // A runtime !autoplay toggle (persisted in kv) always wins over the // config default, so a reload doesn't silently flip radio back. bool autoplayPref = features.autoplay; @@ -286,8 +317,10 @@ namespace Echoion::Core if (database_) { (void)database_->setKv("autoplay.enabled", enabled ? "1" : "0"); } - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("Autoplay {}", enabled ? "enabled" : "disabled")); + persistSession(); // Enabling while nothing is playing: kick an immediate refill so the // radio starts without waiting for the next track to finish. if (enabled && engine_ && !engine_->isPlaying()) { @@ -295,6 +328,118 @@ namespace Echoion::Core } } + void MusicManager::maybeAutoStart() + { + if (!engine_ || !hasOnlineSubscribers()) { + return; + } + if (!queue_.empty()) { + Void::Log::info( + "MusicManager", "{}", + "maybeAutoStart: queue has tracks, starting playback"); + if (playbackStartCallback_) { + playbackStartCallback_(); + } + engine_->start(); + } else if (autoplay_.load()) { + Void::Log::info( + "MusicManager", "{}", + "maybeAutoStart: autoplay on with empty queue, starting radio"); + onEngineIdle(); + } + } + + void MusicManager::setShuffle(bool enabled) + { + queue_.setShuffle(enabled); + persistSession(); + } + + void MusicManager::setRepeat(bool enabled) + { + queue_.setRepeat(enabled); + persistSession(); + } + + void MusicManager::persistSession(bool includeCurrent) + { + if (!database_ || restoringSession_.load()) { + return; + } + StateV1 st; + // The currently-playing track leads the persisted list so it replays + // from the start after a restart (its live stream URL is not reusable). + if (includeCurrent) { + if (auto cur = getCurrentTrack(); cur && cur->has_value()) { + StateV1::QueueEntryState e; + e.track = cur->value().track; + e.addedBy = cur->value().addedBy; + st.queue.push_back(std::move(e)); + } + } + if (auto q = getQueue()) { + for (const auto& entry : *q) { + StateV1::QueueEntryState e; + e.track = entry.track; + e.addedBy = entry.addedBy; + st.queue.push_back(std::move(e)); + } + } + st.playback.shuffle = queue_.shuffleEnabled(); + st.playback.repeat = queue_.repeatEnabled(); + st.autoplay = autoplay_.load(); + + std::string json = Void::Json::serialize(Void::Json::to_json(st)); + if (!json.empty()) { + (void)database_->setKv("session.state", json); + } + } + + void MusicManager::restoreSession() + { + if (!database_) { + return; + } + auto stored = database_->getKv("session.state"); + if (!stored || !*stored || (*stored)->empty()) { + return; + } + auto parsed = Void::Json::parse(**stored); + if (!parsed) { + return; + } + auto st = Void::Json::from_json<StateV1>(*parsed); + if (!st) { + Void::Log::warn("MusicManager", "{}", + std::format("Failed to restore session: {}", + st.error().message)); + return; + } + + restoringSession_ = true; + queue_.setShuffle(st->playback.shuffle); + queue_.setRepeat(st->playback.repeat); + // Autoplay is deliberately NOT taken from the session snapshot: it has + // its own authoritative kv ("autoplay.enabled") already loaded by + // applyFeaturesConfig(), so a stale snapshot can't flip radio off. + size_t restored = 0; + for (const auto& entry : st->queue) { + if (queueTrack(entry.track, 0)) { + ++restored; + } + } + restoringSession_ = false; + + Void::Log::info( + "MusicManager", "{}", + std::format("Restored session: {} queued track(s), shuffle={}, " + "repeat={}, autoplay={}", + restored, st->playback.shuffle, st->playback.repeat, + autoplay_.load())); + + maybeAutoStart(); + } + void MusicManager::applySourcesConfig(const Api::SourcesConfig& sources) { if (!router_) { @@ -311,8 +456,7 @@ namespace Echoion::Core sources.yandexToken.value_or("")); } router_->setHedgeDelay(sources.hedgeDelay); - Void::Log::info("MusicManager", "{}", - "Sources config applied"); + Void::Log::info("MusicManager", "{}", "Sources config applied"); } void MusicManager::shutdown() @@ -333,6 +477,10 @@ namespace Echoion::Core engine_->shutdown(); } + // The ffmpeg proxy bridge outlives the engine's decoders, never the + // other way around. + ffmpegProxyBridge_.reset(); + // Clean up temp files { std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); @@ -340,7 +488,8 @@ namespace Echoion::Core std::error_code ec; std::filesystem::remove(filepath, ec); if (!ec) { - Void::Log::debug("MusicManager", "{}", + Void::Log::debug( + "MusicManager", "{}", std::format("Cleaned up temp file: {}", filepath)); } } @@ -366,7 +515,8 @@ namespace Echoion::Core Api::Result<std::string> MusicManager::play(const std::string& query, uint64_t clientId) { - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("Play request: '{}' from client {}", query, clientId)); // Yandex collections dropped into !play import the whole collection @@ -385,8 +535,9 @@ namespace Echoion::Core auto track = resolveQuery(query); if (!track) { - Void::Log::error("MusicManager", "{}", std::format("Failed to resolve query '{}': {}", - query, track.error().message)); + Void::Log::error("MusicManager", "{}", + std::format("Failed to resolve query '{}': {}", + query, track.error().message)); return std::unexpected(track.error()); } @@ -395,36 +546,37 @@ namespace Echoion::Core // Idle: play immediately. Resolution happens here on the command // thread so failures surface to the user synchronously. if (engine_ && !engine_->isPlaying() && !engine_->currentEntry()) { - Api::QueueEntry entry{ - .queueId = queue_.allocateQueueId(), - .track = *track, - .addedAt = std::chrono::system_clock::now(), - .addedBy = nickname, - .isPlaying = true, - .position = std::chrono::milliseconds(0)}; + Api::QueueEntry entry{.queueId = queue_.allocateQueueId(), + .track = *track, + .addedAt = std::chrono::system_clock::now(), + .addedBy = nickname, + .isPlaying = true, + .position = std::chrono::milliseconds(0)}; auto streamUrl = resolveStream(entry, false); if (!streamUrl) { Void::Log::error("MusicManager", "{}", - std::format("Failed to get stream URL: {}", - streamUrl.error().message)); + std::format("Failed to get stream URL: {}", + streamUrl.error().message)); return std::unexpected(streamUrl.error()); } const bool isLocal = !streamUrl->starts_with("http"); - engine_->playNow(std::move(entry), *streamUrl, isLocal); + engine_->playNow(std::move(entry), std::move(*streamUrl), isLocal); // Update the whisper list before audio starts flowing. if (playbackStartCallback_) { playbackStartCallback_(); } - Void::Log::info("MusicManager", "{}", std::format("Now playing: {} - {}", track->title, - track->artist)); + Void::Log::info("MusicManager", "{}", + std::format("Now playing: {} - {}", track->title, + track->artist)); return std::format("{} - {}", track->title, track->artist); } - Void::Log::debug("MusicManager", "{}", "Already playing, adding to queue"); + Void::Log::debug("MusicManager", "{}", + "Already playing, adding to queue"); auto queueId = queueTrack(*track, clientId); if (!queueId) { return std::unexpected(queueId.error()); @@ -438,13 +590,13 @@ namespace Echoion::Core { if (!engine_ || !engine_->isPlaying() || engine_->isPaused()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Nothing is playing"); + "Nothing is playing"); } engine_->pause(); emitPauseState(true); Void::Log::info("MusicManager", "{}", - std::format("Playback paused at {}ms", - engine_->position().count())); + std::format("Playback paused at {}ms", + engine_->position().count())); return {}; } @@ -487,10 +639,13 @@ namespace Echoion::Core Void::Log::info("MusicManager", "{}", "Playback stopped"); - emit(Api::Events::PlaybackStopped{ - .lastTrack = lastTrack, - .finalPosition = finalPosition}); + emit(Api::Events::PlaybackStopped{.lastTrack = lastTrack, + .finalPosition = finalPosition}); + // The engine clears its current entry asynchronously (CmdStop is + // posted to its thread); persisting it here would resurrect the + // stopped track after a restart. An explicit stop keeps nothing. + persistSession(/*includeCurrent=*/false); return {}; } @@ -498,21 +653,107 @@ namespace Echoion::Core { if (!engine_ || !engine_->isPlaying()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Nothing is playing"); + "Nothing is playing"); + } + // Record the abandoned track for the skip-rate stats before it's + // replaced. + if (database_) { + if (auto entry = engine_->currentEntry()) { + (void)database_->recordSkip(entry->track, 0); + } } engine_->skip(count); - Void::Log::info("MusicManager", "{}", std::format("Skipped {} track(s)", count)); + Void::Log::info("MusicManager", "{}", + std::format("Skipped {} track(s)", count)); + persistSession(); return {}; } + uint32_t MusicManager::voteSkipNeeded() const + { + if (const uint32_t configured = voteSkipThreshold_.load(); + configured > 0) { + return configured; + } + const size_t online = getOnlineSubscriberUids().size(); + return static_cast<uint32_t>(std::max<size_t>(1, online / 2 + 1)); + } + + Api::Result<MusicManager::VoteSkipStatus> + MusicManager::voteSkip(const std::string& uid) + { + if (!engine_ || !engine_->isPlaying()) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Nothing is playing"); + } + auto entry = engine_->currentEntry(); + if (!entry) { + return Api::fail(Api::ErrorCode::InvalidArgument, + "Nothing is playing"); + } + + VoteSkipStatus status; + status.needed = voteSkipNeeded(); + { + std::lock_guard<std::mutex> lock(voteSkipMutex_); + if (voteSkipQueueId_ != entry->queueId) { + voteSkipUids_.clear(); + voteSkipQueueId_ = entry->queueId; + } + // Second vote from the same uid retracts the first. + if (auto [it, inserted] = voteSkipUids_.insert(uid); !inserted) { + voteSkipUids_.erase(it); + } + status.voted = voteSkipUids_.contains(uid); + status.votes = static_cast<uint32_t>(voteSkipUids_.size()); + if (status.votes >= status.needed) { + voteSkipUids_.clear(); + status.skipped = true; + } + } + + if (status.skipped) { + Void::Log::info( + "MusicManager", "{}", + std::format("Vote-skip threshold reached ({}/{}), skipping", + status.votes, status.needed)); + if (auto result = skip(1); !result) { + return std::unexpected(result.error()); + } + } + return status; + } + + MusicManager::VoteSkipStatus + MusicManager::voteSkipStatus(const std::string& uid) const + { + VoteSkipStatus status; + status.needed = voteSkipNeeded(); + if (!engine_) { + return status; + } + auto entry = engine_->currentEntry(); + if (!entry) { + return status; + } + std::lock_guard<std::mutex> lock(voteSkipMutex_); + if (voteSkipQueueId_ != entry->queueId) { + return status; // stale votes for a previous track + } + status.votes = static_cast<uint32_t>(voteSkipUids_.size()); + status.voted = voteSkipUids_.contains(uid); + return status; + } + Api::Result<void> MusicManager::seek(std::chrono::milliseconds position) { if (!engine_ || !engine_->isPlaying()) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Nothing is playing"); + "Nothing is playing"); } engine_->seekTo(position); - Void::Log::info("MusicManager", "{}", std::format("Seeked to {} ms", position.count())); + Void::Log::info("MusicManager", "{}", + std::format("Seeked to {} ms", position.count())); return {}; } @@ -520,14 +761,15 @@ namespace Echoion::Core { if (volume < 0.0f || volume > 1.0f) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Volume must be 0.0-1.0"); + "Volume must be 0.0-1.0"); } float oldVolume = engine_ ? engine_->volume() : 0.0f; if (engine_) { engine_->setVolume(volume); } - Void::Log::info("MusicManager", "{}", std::format("Volume set to {}", volume)); + Void::Log::info("MusicManager", "{}", + std::format("Volume set to {}", volume)); emit(Api::Events::VolumeChanged{ .oldVolume = oldVolume, @@ -553,13 +795,20 @@ namespace Echoion::Core return queueId; } - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("Queued: {} - {}", track.title, track.artist)); + // 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)); + } + // Auto-start when idle with an online audience. - if (autoStartOnSubscribe_.load() && engine_ && - !engine_->isPlaying() && !engine_->currentEntry() && - hasOnlineSubscribers()) { + if (autoStartOnSubscribe_.load() && engine_ && !engine_->isPlaying() && + !engine_->currentEntry() && hasOnlineSubscribers()) { Void::Log::info("MusicManager", "{}", "Auto-starting playback for queued track"); if (playbackStartCallback_) { @@ -568,6 +817,7 @@ namespace Echoion::Core engine_->start(); } + persistSession(); return queueId; } @@ -578,7 +828,8 @@ namespace Echoion::Core return std::unexpected(removed.error()); } - Void::Log::info("MusicManager", "{}", std::format("Removed track at position {}", position)); + Void::Log::info("MusicManager", "{}", + std::format("Removed track at position {}", position)); emit(Api::Events::TrackRemoved{ .track = removed->track, @@ -586,6 +837,7 @@ namespace Echoion::Core .removedByClientId = 0, .queueLength = static_cast<uint32_t>(queue_.size())}); + persistSession(); return {}; } @@ -594,9 +846,10 @@ namespace Echoion::Core const uint32_t previousLength = queue_.clear(); Void::Log::info("MusicManager", "{}", "Queue cleared"); - emit(Api::Events::QueueCleared{ - .clearedByClientId = 0, .previousLength = previousLength}); + emit(Api::Events::QueueCleared{.clearedByClientId = 0, + .previousLength = previousLength}); + persistSession(); return {}; } @@ -612,14 +865,15 @@ namespace Echoion::Core return std::unexpected(moved.error()); } - Void::Log::info("MusicManager", "{}", std::format("Moved track from {} to {}", from, to)); + Void::Log::info("MusicManager", "{}", + std::format("Moved track from {} to {}", from, to)); - emit( - Api::Events::QueueReordered{.queueId = *moved, - .oldPosition = from, - .newPosition = to, - .changedByClientId = 0}); + emit(Api::Events::QueueReordered{.queueId = *moved, + .oldPosition = from, + .newPosition = to, + .changedByClientId = 0}); + persistSession(); return {}; } @@ -629,9 +883,10 @@ namespace Echoion::Core Void::Log::info("MusicManager", "{}", enabled ? "Shuffle enabled" : "Shuffle disabled"); - emit(Api::Events::ShuffleChanged{ - .enabled = enabled, .changedByClientId = 0}); + emit(Api::Events::ShuffleChanged{.enabled = enabled, + .changedByClientId = 0}); + persistSession(); return enabled; } @@ -641,9 +896,10 @@ namespace Echoion::Core Void::Log::info("MusicManager", "{}", enabled ? "Repeat enabled" : "Repeat disabled"); - emit(Api::Events::RepeatChanged{ - .enabled = enabled, .changedByClientId = 0}); + emit(Api::Events::RepeatChanged{.enabled = enabled, + .changedByClientId = 0}); + persistSession(); return enabled; } @@ -651,6 +907,7 @@ namespace Echoion::Core { queue_.shuffleInPlace(); emit(Api::Events::QueueShuffled{.triggeredByClientId = 0}); + persistSession(); return {}; } @@ -684,8 +941,8 @@ namespace Echoion::Core auto tracks = yandexSource_->playlistTracks(playlistIdOrUrl); if (!tracks) { Void::Log::warn("MusicManager", "{}", - std::format("Collection import failed: {}", - tracks.error().message)); + std::format("Collection import failed: {}", + tracks.error().message)); importRunning_ = false; return; } @@ -695,7 +952,8 @@ namespace Echoion::Core ++queued; } } - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("Imported {} track(s) from collection", queued)); if (queued > 0 && engine_) { @@ -718,8 +976,7 @@ namespace Echoion::Core // The engine's Start command is idempotent and cheap: if the queue is // still empty (streaming race) the engine just stays idle and the // next queueTrack pokes it again — no delay thread needed. - if (autoStartOnSubscribe_.load() && engine_ && - hasOnlineSubscribers()) { + if (autoStartOnSubscribe_.load() && engine_ && hasOnlineSubscribers()) { if (playbackStartCallback_) { playbackStartCallback_(); } @@ -774,8 +1031,7 @@ namespace Echoion::Core Api::Result<Api::PlaybackState> MusicManager::getPlaybackState() const { Api::PlaybackState state; - state.currentTrack = - engine_ ? engine_->currentEntry() : std::nullopt; + state.currentTrack = engine_ ? engine_->currentEntry() : std::nullopt; state.queue = queue_.snapshot(); state.isPlaying = engine_ && engine_->isPlaying(); state.isPaused = engine_ && engine_->isPaused(); @@ -811,6 +1067,13 @@ namespace Echoion::Core return Api::fail(Api::ErrorCode::ServiceUnavailable, "Yandex Music not configured"); }; + const auto soundcloud = [&]() -> Api::Result<Api::SearchResult> { + if (youTubeClient_) { + return youTubeClient_->searchSoundCloud(query); + } + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "SoundCloud search unavailable"); + }; if (scope == SearchScope::YouTube) { return youtube(); @@ -818,6 +1081,9 @@ namespace Echoion::Core if (scope == SearchScope::Yandex) { return yandex(); } + if (scope == SearchScope::SoundCloud) { + return soundcloud(); + } // All: merge both catalogs (YouTube first). Succeed if either does. Api::SearchResult merged; @@ -849,8 +1115,9 @@ namespace Echoion::Core { std::lock_guard<std::mutex> lock(pendingSearchMutex_); pendingSearches_[clientId] = results; - Void::Log::debug("MusicManager", "{}", std::format("Stored {} search results for client {}", - results.size(), clientId)); + Void::Log::debug("MusicManager", "{}", + std::format("Stored {} search results for client {}", + results.size(), clientId)); } std::optional<std::vector<Api::TrackInfo>> @@ -873,14 +1140,14 @@ namespace Echoion::Core if (index == 0) { return Api::fail(Api::ErrorCode::InvalidArgument, - "Index must be 1 or greater"); + "Index must be 1 or greater"); } auto pending = getPendingSearch(clientId); if (!pending) { return Api::fail(Api::ErrorCode::NotFound, - "No pending search results. Use search or play " - "commands first."); + "No pending search results. Use search or play " + "commands first."); } if (index > pending->size()) { @@ -924,6 +1191,7 @@ namespace Echoion::Core state.playbackPosition = state.playback.position; state.config = config_; + state.autoplay = autoplay_.load(); return state; } @@ -932,6 +1200,7 @@ namespace Echoion::Core MusicManager::restoreFromHotReload(const Api::HotReloadState& state) { config_ = state.config; + autoplay_ = state.autoplay; queue_.setShuffle(state.playback.shuffle); queue_.setRepeat(state.playback.repeat); queue_.replaceAll(state.queue); @@ -939,7 +1208,8 @@ namespace Echoion::Core engine_->setVolume(state.playback.volume); } - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("restoreFromHotReload: shouldPreservePlayback={}, " "hasStreamUrl={}, isPlaying={}, hasCurrentTrack={}", state.shouldPreservePlayback(), @@ -950,8 +1220,8 @@ namespace Echoion::Core if (engine_ && state.shouldPreservePlayback() && state.currentStreamUrl && state.playback.currentTrack) { Void::Log::info("MusicManager", "{}", - std::format("Restoring playback from position {}ms", - state.playbackPosition.count())); + std::format("Restoring playback from position {}ms", + state.playbackPosition.count())); engine_->restore(*state.playback.currentTrack, *state.currentStreamUrl, state.playbackPosition, state.playback.isPaused); @@ -959,12 +1229,23 @@ namespace Echoion::Core playbackStartCallback_(); } } else if (engine_ && !queue_.empty() && hasOnlineSubscribers()) { - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", "Playback not restored but queue has items, auto-starting"); if (playbackStartCallback_) { playbackStartCallback_(); } engine_->start(); + } else if (engine_ && autoplay_.load() && queue_.empty() && + hasOnlineSubscribers()) { + // Radio was on before the reload: the transient radio queue is + // gone, so kick a refill instead of sitting idle. onEngineIdle() + // self-guards and seeds from history when no session seed exists. + Void::Log::info( + "MusicManager", "{}", + "Playback not restored, autoplay on with empty queue, " + "starting radio"); + onEngineIdle(); } Void::Log::info("MusicManager", "{}", "State restored from hot reload"); @@ -1029,24 +1310,23 @@ namespace Echoion::Core bool preferDownload) { const std::string cacheKey = - entry.track.id.empty() ? entry.track.originalUrl - : entry.track.id; + entry.track.id.empty() ? entry.track.originalUrl : entry.track.id; // A previously downloaded copy trumps every source: instant start, // works offline. if (trackCache_ && !preferDownload) { if (auto cached = trackCache_->lookup(cacheKey)) { - Void::Log::info("MusicManager", "{}", + Void::Log::info( + "MusicManager", "{}", std::format("Track cache hit for {}", cacheKey)); return *cached; } } // yt-dlp downloads the audio to a local file through the configured - // proxy (it handles SOCKS5, which ffmpeg cannot) — the shared path - // for both the explicit retry and the proactive SOCKS5 case below. - const auto downloadToFile = - [this, &entry, &cacheKey]() -> Api::Result<std::string> { + // proxy — the fallback when a served URL turns out unplayable. + const auto downloadToFile = [this, &entry, + &cacheKey]() -> Api::Result<std::string> { auto downloaded = downloadAudioForPlayback(entry.track); if (downloaded) { if (trackCache_ && trackCache_->enabled()) { @@ -1060,8 +1340,7 @@ namespace Echoion::Core }; // Retry after a failed open: the served URL was bad (expired cache - // entry, dead instance, or ffmpeg can't stream it through the - // configured SOCKS5 proxy). Evict the cache and download instead. + // entry or dead instance). Evict the cache and download instead. if (preferDownload) { if (router_) { router_->invalidate(cacheKey); @@ -1075,25 +1354,6 @@ namespace Echoion::Core return std::unexpected(handle.error()); } - // ffmpeg cannot route an IP-locked googlevideo URL through a - // SOCKS5 proxy (it silently ignores socks5:// and times out at - // -110). Under SOCKS5, take the download path proactively for - // such URLs instead of eating a ~15s ffmpeg timeout per track. - // Instance-proxied URLs (Invidious local=true, Piped - // pipedproxy.*), Yandex CDN and local files are reachable and - // left untouched. - if (!handle->isLocalFile && socksProxyActive() && - handle->url.find("googlevideo.com") != std::string::npos) { - Void::Log::info("MusicManager", "{}", - "SOCKS5 proxy: downloading googlevideo audio (ffmpeg " - "cannot stream it directly)"); - if (auto downloaded = downloadToFile()) { - return downloaded; - } - // Download failed — fall back to the (likely doomed) direct - // URL rather than nothing; the engine retry covers it. - } - if (handle->isLocalFile) { std::unique_lock<std::shared_mutex> lock(tempFilesMutex_); tempFiles_.insert(handle->url); @@ -1104,14 +1364,48 @@ namespace Echoion::Core return getStreamUrl(entry.track); } - bool MusicManager::socksProxyActive() const + std::optional<Void::Net::ProxyConfig> MusicManager::effectiveEngineProxy( + const std::optional<Void::Net::ProxyConfig>& proxy) { - if (!configManager_) { - return false; + const bool socks5 = proxy.has_value() && proxy->enabled() && + proxy->kind == Void::Net::ProxyConfig::Kind::Socks5; + + if (!socks5) { + // Http/none: ffmpeg handles these natively; drop a stale bridge. + if (ffmpegProxyBridge_) { + ffmpegProxyBridge_->stop(); + } + return proxy; } - const auto& proxy = configManager_->getNetwork().proxy; - return proxy.has_value() && proxy->enabled() && - proxy->kind == Void::Net::ProxyConfig::Kind::Socks5; + + if (!ffmpegProxyBridge_) { + ffmpegProxyBridge_ = std::make_unique<Socks5HttpBridge>(); + } + + // Reuse a running bridge when the SOCKS5 endpoint is unchanged + // (config reloads re-apply the network section unconditionally). + const auto current = ffmpegProxyBridge_->upstream(); + if (!ffmpegProxyBridge_->running() || !current || + current->host != proxy->host || current->port != proxy->port || + current->username != proxy->username || + current->password != proxy->password) { + auto port = ffmpegProxyBridge_->start(*proxy); + if (!port) { + Void::Log::error( + "MusicManager", "{}", + std::format("SOCKS5 bridge failed to start ({}); ffmpeg " + "will connect directly and rely on the " + "download fallback", + port.error().message)); + return proxy; // decoder skips Socks5-kind configs + } + } + + Void::Net::ProxyConfig bridged; + bridged.kind = Void::Net::ProxyConfig::Kind::Http; + bridged.host = "127.0.0.1"; + bridged.port = ffmpegProxyBridge_->port(); + return bridged; } std::optional<Api::QueueEntry> MusicManager::peekNextTrack() @@ -1135,12 +1429,16 @@ namespace Echoion::Core void MusicManager::onTrackStarted(const Api::QueueEntry& entry) { Void::Log::info("MusicManager", "{}", - std::format("Now playing: {} - {}", entry.track.title, - entry.track.artist)); - emit(Api::Events::PlaybackStarted{ - .track = entry.track, - .clientId = 0, - .position = std::chrono::milliseconds(0)}); + std::format("Now playing: {} - {}", entry.track.title, + entry.track.artist)); + emit(Api::Events::PlaybackStarted{.track = entry.track, + .clientId = 0, + .position = + std::chrono::milliseconds(0)}); + // Rewrite the snapshot on every track transition so it always leads + // with the entry that is actually playing — this also corrects the + // snapshot skip() writes while the engine is still switching tracks. + persistSession(); } void MusicManager::onTrackFinished(const Api::QueueEntry& entry, @@ -1162,10 +1460,9 @@ namespace Echoion::Core autoplaySeedSource_ = AutoplaySeedSource::Yandex; } - emit(Api::Events::TrackFinished{ - .track = entry.track, - .autoSkipped = false, - .finalPosition = finalPosition}); + emit(Api::Events::TrackFinished{.track = entry.track, + .autoSkipped = false, + .finalPosition = finalPosition}); } void MusicManager::onPositionTick(const Api::QueueEntry& entry, @@ -1179,11 +1476,10 @@ namespace Echoion::Core 100.0f; } - emit(Api::Events::PlaybackPositionChanged{ - .track = entry.track, - .position = position, - .duration = duration, - .progressPercent = progress}); + emit(Api::Events::PlaybackPositionChanged{.track = entry.track, + .position = position, + .duration = duration, + .progressPercent = progress}); } std::optional<std::pair<std::string, MusicManager::AutoplaySeedSource>> @@ -1243,9 +1539,8 @@ namespace Echoion::Core seedSource = fromHistory->second; } } - if (seed.empty() || seedSource == AutoplaySeedSource::None) { - return; - } + // Note: no early return when there is still no seed — the fetch thread + // falls back to a random music video so radio can start from cold. bool expected = false; if (!autoplayFetching_.compare_exchange_strong(expected, true)) { return; // fetch already in flight @@ -1255,50 +1550,93 @@ namespace Echoion::Core autoplayThread_.join(); // previous fetch already finished } autoplayThread_ = std::jthread([this, seed, seedSource]() { - // Related tracks come from the same catalog as the seed: - // YouTube via a yt-dlp radio mix, Yandex via its similar-tracks - // endpoint. - Api::Result<std::vector<Api::TrackInfo>> related = - Api::fail(Api::ErrorCode::ServiceUnavailable, - "Autoplay source unavailable"); - if (seedSource == AutoplaySeedSource::Yandex) { - if (yandexSource_) { - related = yandexSource_->related(seed, 10); - } - } else if (youTubeClient_) { - related = youTubeClient_->radioMix(seed, 10); - } - if (related && !related->empty()) { - // Skip anything played recently to avoid radio loops. - std::set<std::string> recentUrls; - if (database_) { - if (auto recent = database_->getRecentlyPlayed(0, 50)) { - for (const auto& t : *recent) { - recentUrls.insert(t.originalUrl); - } + // Skip anything played recently to avoid radio loops. + std::set<std::string> recentUrls; + if (database_) { + if (auto recent = database_->getRecentlyPlayed(0, 50)) { + for (const auto& t : *recent) { + recentUrls.insert(t.originalUrl); } } + } + + // Queue tracks that are both unplayed-recently and within the + // radio duration cap. Stops once maxToQueue have been queued. + auto queueRadio = + [&](const std::vector<Api::TrackInfo>& tracks, + size_t maxToQueue) -> size_t { size_t queued = 0; - for (const auto& track : *related) { + for (const auto& track : tracks) { if (recentUrls.contains(track.originalUrl)) { continue; } + if (track.duration && + *track.duration > kRadioMaxTrackDuration) { + continue; + } if (queueTrack(track, 0)) { - ++queued; + if (++queued >= maxToQueue) { + break; + } } } - if (queued > 0) { - Void::Log::info( - "MusicManager", "{}", - std::format("Autoplay queued {} related track(s)", - queued)); - if (engine_) { - engine_->start(); + return queued; + }; + + size_t queued = 0; + + // Related tracks come from the same catalog as the seed: + // YouTube via a yt-dlp radio mix, Yandex via its similar-tracks + // endpoint. + if (!seed.empty() && seedSource != AutoplaySeedSource::None) { + Api::Result<std::vector<Api::TrackInfo>> related = + Api::fail(Api::ErrorCode::ServiceUnavailable, + "Autoplay source unavailable"); + if (seedSource == AutoplaySeedSource::Yandex) { + if (yandexSource_) { + related = yandexSource_->related(seed, 10); } + } else if (youTubeClient_) { + related = youTubeClient_->radioMix(seed, 10); + } + if (related && !related->empty()) { + queued = queueRadio(*related, std::numeric_limits< + size_t>::max()); + if (queued > 0) { + Void::Log::info( + "MusicManager", "{}", + std::format( + "Autoplay queued {} related track(s)", + queued)); + } + } + } + + // No seed, empty mix, or every related track was recently played / + // too long: fall back to a single random music video. When it + // finishes it becomes the next seed, so related-track radio + // resumes from it on the following idle. + if (queued == 0 && youTubeClient_) { + if (auto random = youTubeClient_->randomMusicVideo(15); + 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)"); + } + } + } + + if (queued > 0) { + if (engine_) { + engine_->start(); } } else { - Void::Log::debug("MusicManager", "{}", - "Autoplay found no related tracks"); + Void::Log::debug( + "MusicManager", "{}", + "Autoplay found no track to queue"); } autoplayFetching_ = false; }); @@ -1323,11 +1661,11 @@ namespace Echoion::Core return; } if (paused) { - emit(Api::Events::PlaybackPaused{ - .track = entry->track, .position = engine_->position()}); + emit(Api::Events::PlaybackPaused{.track = entry->track, + .position = engine_->position()}); } else { - emit(Api::Events::PlaybackResumed{ - .track = entry->track, .position = engine_->position()}); + emit(Api::Events::PlaybackResumed{.track = entry->track, + .position = engine_->position()}); } } @@ -1344,6 +1682,12 @@ namespace Echoion::Core std::string MusicManager::nicknameFor(uint64_t clientId) const { + // clientId 0 is the sentinel for system/radio-added tracks (autoplay). + // TeamSpeak client IDs are >= 1, so this never collides with a real + // user and gives the queue a friendly "(by radio)" instead of "(by 0)". + if (clientId == 0) { + return "radio"; + } if (nicknameCallback_) { if (auto n = nicknameCallback_(clientId)) { return *n; @@ -1357,10 +1701,12 @@ namespace Echoion::Core { // Playlist URLs are still resolved through the YouTube client (the // router's sources resolve single tracks). - if (config_.allowPlaylistImports && YouTubeClient::isYouTubeUrl(query) && + if (config_.allowPlaylistImports && + YouTubeClient::isYouTubeUrl(query) && !youTubeClient_->extractVideoId(query).has_value()) { if (auto playlistId = YouTubeClient::extractPlaylistId(query)) { - Void::Log::debug("MusicManager", "{}", + Void::Log::debug( + "MusicManager", "{}", std::format("Extracted playlist ID: '{}'", *playlistId)); auto playlist = youTubeClient_->getPlaylist(*playlistId); if (playlist && !playlist->tracks.empty()) { @@ -1387,7 +1733,8 @@ namespace Echoion::Core MusicManager::getStreamUrl(const Api::TrackInfo& track) { if (track.streamUrl) { - Void::Log::debug("MusicManager", "{}", "Using pre-resolved stream URL"); + Void::Log::debug("MusicManager", "{}", + "Using pre-resolved stream URL"); return *track.streamUrl; } @@ -1418,6 +1765,7 @@ namespace Echoion::Core !search <query> - Search YouTube + Yandex Music !youtube <query> - Search YouTube only (alias: yb, yt) !yandex <query> - Search Yandex Music only (alias: ya) +!soundcloud <query> - Search SoundCloud only (alias: sc) !history [n] - Show recently played tracks !stats - Show playback statistics !fav add|list|play <n> - Manage your favorite tracks @@ -1436,16 +1784,22 @@ Subscriptions are persistent across server reconnects.)"; { if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Subscription manager not initialized"); + "Subscription manager not initialized"); } - return subscriptions_->subscribe(clientId); + auto result = subscriptions_->subscribe(clientId); + if (result) { + // A newly-listening user should hear the restored queue / radio + // without also having to !play. + maybeAutoStart(); + } + return result; } Api::Result<std::string> MusicManager::unsubscribe(uint64_t clientId) { if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Subscription manager not initialized"); + "Subscription manager not initialized"); } return subscriptions_->unsubscribe(clientId); } @@ -1455,7 +1809,7 @@ Subscriptions are persistent across server reconnects.)"; { if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Subscription manager not initialized"); + "Subscription manager not initialized"); } return subscriptions_->unsubscribeByUid(uid); } @@ -1464,7 +1818,7 @@ Subscriptions are persistent across server reconnects.)"; { if (!subscriptions_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Subscription manager not initialized"); + "Subscription manager not initialized"); } return subscriptions_->clearAllSubscriptions(); } @@ -1489,9 +1843,8 @@ Subscriptions are persistent across server reconnects.)"; std::vector<SubscriptionManager::Subscriber> MusicManager::getSubscribers() const { - return subscriptions_ - ? subscriptions_->getSubscribers() - : std::vector<SubscriptionManager::Subscriber>{}; + return subscriptions_ ? subscriptions_->getSubscribers() + : std::vector<SubscriptionManager::Subscriber>{}; } bool MusicManager::hasSubscribers() const @@ -1506,29 +1859,41 @@ Subscriptions are persistent across server reconnects.)"; void MusicManager::onClientConnected(uint64_t clientId) { - Void::Log::info("MusicManager", "{}", std::format("onClientConnected: client {}", clientId)); + Void::Log::info("MusicManager", "{}", + std::format("onClientConnected: client {}", clientId)); if (!subscriptions_) { return; } - const bool mayAutoStart = subscriptions_->onClientConnected(clientId); - if (mayAutoStart && autoStartOnSubscribe_.load() && engine_ && + const auto connect = subscriptions_->onClientConnected(clientId); + if (connect.mayAutoStart && autoStartOnSubscribe_.load() && engine_ && !engine_->isPlaying() && !engine_->currentEntry() && !queue_.empty()) { Void::Log::info("MusicManager", "{}", - "Online subscriber connected with tracks in queue, " - "auto-starting"); + "Online subscriber connected with tracks in queue, " + "auto-starting"); if (playbackStartCallback_) { playbackStartCallback_(); } engine_->start(); + } else if (connect.mayAutoStart && autoplay_.load() && engine_ && + !engine_->isPlaying() && !engine_->currentEntry() && + queue_.empty()) { + // First subscriber back after a restart with radio enabled but an + // empty queue: kick a refill so the radio starts without needing a + // manual !play. onEngineIdle() self-guards and seeds from history. + Void::Log::info( + "MusicManager", "{}", + "Online subscriber connected, autoplay on with empty queue, " + "starting radio"); + onEngineIdle(); } - // Deliver a pending announcement to this subscriber once. - if (auto uid = clientUid(clientId); - uid && subscriptions_->isSubscribed(clientId)) { - deliverAnnouncementTo(clientId, *uid); + // Deliver a pending announcement to this subscriber once (uid was + // already resolved by the subscription service above). + if (connect.subscribedUid) { + deliverAnnouncementTo(clientId, *connect.subscribedUid); } } @@ -1599,8 +1964,8 @@ Subscriptions are persistent across server reconnects.)"; messageCallback_(clientId, **textKv); (void)database_->setKv(seenKey, std::to_string(currentId)); Void::Log::info("MusicManager", "{}", - std::format("Announcement (id {}) delivered to {}", currentId, - uid)); + std::format("Announcement (id {}) delivered to {}", + currentId, uid)); return true; } @@ -1651,11 +2016,12 @@ Subscriptions are persistent across server reconnects.)"; std::error_code ec; std::filesystem::remove(filepath, ec); if (ec) { - Void::Log::warn("MusicManager", "{}", std::format("Failed to remove temp file {}: {}", - filepath, ec.message())); + Void::Log::warn("MusicManager", "{}", + std::format("Failed to remove temp file {}: {}", + filepath, ec.message())); } else { Void::Log::debug("MusicManager", "{}", - std::format("Cleaned up temp file: {}", filepath)); + std::format("Cleaned up temp file: {}", filepath)); } } diff --git a/src/RpcServer.cpp b/src/RpcServer.cpp index 171d759..0e6b4a1 100644 --- a/src/RpcServer.cpp +++ b/src/RpcServer.cpp @@ -22,6 +22,10 @@ namespace Echoion::Core port_ = port; try { + // A prior stop() left the io_context in the stopped state; reset + // it so acceptLoop()'s run() actually processes work. + ioContext_.restart(); + asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); acceptor_.emplace(ioContext_); acceptor_->open(endpoint.protocol()); @@ -99,98 +103,142 @@ namespace Echoion::Core void RpcServer::acceptLoop() { Void::Log::info("RpcServer", "{}", "RPC server accept loop started"); - while (running_.load()) { + + // Arm the first async accept, then let the io_context drive re-arming + // from the completion handler. This model is cleanly interruptible: + // stop() cancels the acceptor (the pending accept completes with + // operation_aborted and does not re-arm) and calls ioContext_.stop(), + // so run() returns promptly. A blocking synchronous accept, by + // contrast, cannot be reliably woken from another thread on Linux. + doAccept(); + + for (;;) { try { - asio::ip::tcp::socket socket(ioContext_); - Void::Log::debug("RpcServer", "{}", "RPC server waiting for connection..."); - - // Use async accept with cancellation support - std::atomic<bool> acceptComplete{false}; - boost::system::error_code acceptEc; - - acceptor_->async_accept( - socket, [&](const boost::system::error_code& ec) { - acceptEc = ec; - acceptComplete = true; - }); - - // Block until the accept completes or we're stopped. stop() - // clears running_, cancels the acceptor and calls - // ioContext_.stop(), so run_one() returns promptly instead of - // the previous 10ms busy-poll. - while (!acceptComplete.load() && running_.load()) { - if (ioContext_.stopped()) { - break; - } - ioContext_.run_one(); - } - - // Cancel pending operation if we're stopping - if (!running_.load()) { - acceptor_->cancel(); - break; - } - - if (acceptEc) { - throw std::runtime_error(acceptEc.message()); - } - - Void::Log::debug("RpcServer", "{}", - std::format("RPC server accepted TCP connection from {}:{}", - socket.remote_endpoint().address().to_string(), - socket.remote_endpoint().port())); - - if (!running_.load()) { - break; - } - - auto ws = - std::make_shared<websocket::stream<asio::ip::tcp::socket>>( - std::move(socket)); - ws->accept(); - Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed"); - - uint64_t clientId = nextClientId_++; - { - std::lock_guard<std::mutex> lock(clientsMutex_); - clients_[clientId] = ws; - } - - Void::Log::debug("RpcServer", "{}", - std::format("RPC client {} connected", clientId)); - - // Handle the client on the worker pool (drained/joined by - // ~ThreadPool on stop). - if (clientPool_) { - clientPool_->submit([this, clientId, ws]() { - handleClient(ws); - - // Cleanup - { - std::lock_guard<std::mutex> lock(clientsMutex_); - clients_.erase(clientId); - } - { - std::lock_guard<std::mutex> lock(authMutex_); - authenticatedClients_.erase(clientId); - } - Void::Log::debug("RpcServer", "{}", std::format( - "RPC client {} disconnected", clientId)); - }); - } - + ioContext_.run(); + break; // returned normally: acceptor cancelled, no more work } catch (const std::exception& e) { - // If we're shutting down, exit gracefully + // A handler threw (should not happen: the accept path uses + // error_code overloads). Never re-arm into a tight spin -- + // bail if we're stopping, otherwise resume the event loop. + Void::Log::error("RpcServer", "{}", + std::format("RPC accept loop error: {}", e.what())); if (!running_.load()) { break; } - Void::Log::error("RpcServer", "{}", - std::format("RPC accept error: {}", e.what())); } } Void::Log::info("RpcServer", "{}", "RPC server accept loop stopped"); } + void RpcServer::doAccept() + { + auto socket = std::make_shared<asio::ip::tcp::socket>(ioContext_); + acceptor_->async_accept( + *socket, + [this, socket](const boost::system::error_code& ec) { + // Cancelled by stop(): tear-down, do not re-arm. + if (ec == asio::error::operation_aborted || + !running_.load()) { + return; + } + if (ec) { + // Transient accept error (peer vanished mid-handshake, + // fd pressure, ...). Log once and re-arm -- the loop is + // event-driven, so this cannot busy-spin the way the old + // run_one() loop did. + Void::Log::warn("RpcServer", "{}", + std::format("RPC accept failed: {}", ec.message())); + } else { + onAccept(std::move(*socket)); + } + if (running_.load()) { + doAccept(); + } + }); + } + + void RpcServer::onAccept(asio::ip::tcp::socket socket) + { + // Non-throwing remote_endpoint: on a torn-down socket this would + // otherwise throw "Bad file descriptor" -- the original spam source. + boost::system::error_code epc; + std::string peerAddress; + bool peerIsLoopback = false; + if (auto ep = socket.remote_endpoint(epc); !epc) { + peerAddress = ep.address().to_string(); + peerIsLoopback = ep.address().is_loopback(); + Void::Log::debug("RpcServer", "{}", + std::format("RPC server accepted TCP connection from {}:{}", + peerAddress, ep.port())); + } + + auto ws = + std::make_shared<websocket::stream<asio::ip::tcp::socket>>( + std::move(socket)); + + // Read the upgrade request explicitly so handshake headers are + // visible: the web server's /rpc bridge forwards the browser's real + // address in X-Echoion-Client-Ip (trusted from loopback only). + beast::error_code wsEc; + beast::flat_buffer handshakeBuffer; + beast::http::request<beast::http::string_body> upgradeReq; + beast::http::read(ws->next_layer(), handshakeBuffer, upgradeReq, wsEc); + if (wsEc || !websocket::is_upgrade(upgradeReq)) { + Void::Log::debug("RpcServer", "{}", + std::format("WebSocket handshake failed: {}", + wsEc ? wsEc.message() : "not an upgrade")); + return; + } + std::string clientAddress = peerAddress; + if (peerIsLoopback) { + if (auto fwd = upgradeReq.find("X-Echoion-Client-Ip"); + fwd != upgradeReq.end() && !fwd->value().empty()) { + clientAddress = std::string(fwd->value()); + } + } + + // error_code overload: a failed handshake is a normal client-side + // event, not an "RPC accept error". + ws->accept(upgradeReq, wsEc); + if (wsEc) { + Void::Log::debug("RpcServer", "{}", + std::format("WebSocket handshake failed: {}", wsEc.message())); + return; + } + Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed"); + + uint64_t clientId = nextClientId_++; + { + std::lock_guard<std::mutex> lock(clientsMutex_); + clients_[clientId] = ws; + clientAddresses_[clientId] = clientAddress; + } + + Void::Log::debug("RpcServer", "{}", + std::format("RPC client {} connected", clientId)); + + // Handle the client on the worker pool (drained/joined by ~ThreadPool + // on stop). + if (clientPool_) { + clientPool_->submit([this, clientId, ws]() { + handleClient(ws); + + // Cleanup + { + std::lock_guard<std::mutex> lock(clientsMutex_); + clients_.erase(clientId); + clientAddresses_.erase(clientId); + } + { + std::lock_guard<std::mutex> lock(authMutex_); + authenticatedClients_.erase(clientId); + } + Void::Log::debug("RpcServer", "{}", std::format( + "RPC client {} disconnected", clientId)); + }); + } + } + void RpcServer::handleClient( std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws) { @@ -201,12 +249,26 @@ namespace Echoion::Core beast::error_code ec; ws->read(buffer, ec); - if (ec == websocket::error::closed) { - break; - } if (ec) { - Void::Log::error("RpcServer", "{}", - std::format("WebSocket read error: {}", ec.message())); + // Browsers reach us through the HttpServer /rpc TCP tunnel; + // closing a tab tears the upstream socket down abruptly, so + // the read fails with ENOTCONN/eof/reset rather than a clean + // WebSocket close frame. These are all normal disconnects — + // log them at debug so routine tab churn doesn't spam errors. + const bool cleanDisconnect = + ec == websocket::error::closed || + ec == asio::error::eof || + ec == asio::error::connection_reset || + ec == asio::error::not_connected || + ec == asio::error::broken_pipe || + ec == asio::error::operation_aborted; + if (cleanDisconnect) { + Void::Log::debug("RpcServer", "{}", + std::format("WebSocket closed: {}", ec.message())); + } else { + Void::Log::error("RpcServer", "{}", + std::format("WebSocket read error: {}", ec.message())); + } break; } @@ -260,8 +322,9 @@ namespace Echoion::Core return; } - // Check authentication (except for Authenticate method) - if (request.method != Api::RpcMethod::Authenticate) { + // Check authentication (except for the sign-in methods) + if (request.method != Api::RpcMethod::Authenticate && + request.method != Api::RpcMethod::AuthenticateByAddress) { if (!isClientAuthenticated(clientId)) { Api::RpcResponse response; response.requestId = request.id; @@ -461,4 +524,15 @@ namespace Echoion::Core return authenticatedClients_.contains(clientId); } + std::optional<std::string> + RpcServer::getClientAddress(uint64_t clientId) const + { + std::lock_guard<std::mutex> lock(clientsMutex_); + auto it = clientAddresses_.find(clientId); + if (it == clientAddresses_.end() || it->second.empty()) { + return std::nullopt; + } + return it->second; + } + } // namespace Echoion::Core diff --git a/src/Socks5HttpBridge.cpp b/src/Socks5HttpBridge.cpp new file mode 100644 index 0000000..d67cbdc --- /dev/null +++ b/src/Socks5HttpBridge.cpp @@ -0,0 +1,403 @@ +#include "echoion/core/Socks5HttpBridge.hpp" + +#include <Void/Log/Log.hpp> + +#include <boost/asio/read.hpp> +#include <boost/asio/read_until.hpp> +#include <boost/asio/write.hpp> + +#include <array> +#include <charconv> +#include <format> +#include <stdexcept> +#include <string> +#include <string_view> + +#ifndef _WIN32 +#include <sys/socket.h> +#include <sys/time.h> +#endif + +namespace Echoion::Core +{ + namespace + { + namespace asio = boost::asio; + using tcp = boost::asio::ip::tcp; + + // SO_RCVTIMEO/SO_SNDTIMEO for the blocking upstream dial + handshake, + // so a dead SOCKS5 proxy cannot hang a tunnel thread until stop(). + // Cleared (0) again for the relay phase — a paused stream may + // legitimately sit idle far longer than any sane handshake timeout. + void setSocketTimeouts(tcp::socket& socket, long seconds) + { +#ifdef _WIN32 + DWORD ms = static_cast<DWORD>(seconds * 1000); + setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast<const char*>(&ms), sizeof(ms)); + setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, + reinterpret_cast<const char*>(&ms), sizeof(ms)); +#else + timeval tv{.tv_sec = seconds, .tv_usec = 0}; + setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, + sizeof(tv)); + setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, + sizeof(tv)); +#endif + } + + // One direction of the tunnel; runs until either side closes. + void pump(tcp::socket& from, tcp::socket& to) + { + std::array<char, 16 * 1024> buf; + boost::system::error_code ec; + while (true) { + const std::size_t n = from.read_some(asio::buffer(buf), ec); + if (ec || n == 0) { + break; + } + asio::write(to, asio::buffer(buf.data(), n), ec); + if (ec) { + break; + } + } + // Half-close so the peer's read loop terminates too. + to.shutdown(tcp::socket::shutdown_send, ec); + } + + // "CONNECT host:port HTTP/1.1" -> {host, port}. Handles the bracketed + // IPv6 authority form ("[::1]:443"). + std::optional<std::pair<std::string, uint16_t>> + parseConnectTarget(std::string_view requestLine) + { + if (!requestLine.starts_with("CONNECT ")) { + return std::nullopt; + } + requestLine.remove_prefix(8); + const auto space = requestLine.find(' '); + if (space == std::string_view::npos) { + return std::nullopt; + } + std::string_view authority = requestLine.substr(0, space); + + std::string_view host; + std::string_view portStr; + if (authority.starts_with('[')) { + const auto close = authority.find(']'); + if (close == std::string_view::npos || + close + 1 >= authority.size() || + authority[close + 1] != ':') { + return std::nullopt; + } + host = authority.substr(1, close - 1); + portStr = authority.substr(close + 2); + } else { + const auto colon = authority.rfind(':'); + if (colon == std::string_view::npos) { + return std::nullopt; + } + host = authority.substr(0, colon); + portStr = authority.substr(colon + 1); + } + + uint16_t port = 0; + const auto [ptr, ec] = std::from_chars( + portStr.data(), portStr.data() + portStr.size(), port); + if (ec != std::errc{} || ptr != portStr.data() + portStr.size() || + host.empty() || port == 0) { + return std::nullopt; + } + return std::make_pair(std::string(host), port); + } + + void writeAll(tcp::socket& socket, std::string_view data) + { + boost::system::error_code ec; + asio::write(socket, asio::buffer(data), ec); + } + } // namespace + + Socks5HttpBridge::~Socks5HttpBridge() { stop(); } + + Api::Result<uint16_t> + Socks5HttpBridge::start(const Void::Net::ProxyConfig& socks5) + { + stop(); + + try { + acceptor_.emplace(io_, + tcp::endpoint(asio::ip::make_address("127.0.0.1"), + 0)); + port_ = acceptor_->local_endpoint().port(); + } catch (const std::exception& e) { + acceptor_.reset(); + return Api::fail( + Api::ErrorCode::NetworkError, + std::format("Failed to bind SOCKS5 bridge: {}", e.what())); + } + + { + std::lock_guard<std::mutex> lock(mutex_); + upstream_ = socks5; + } + running_ = true; + acceptThread_ = std::thread([this]() { acceptLoop(); }); + + Void::Log::info( + "Socks5HttpBridge", "{}", + std::format("HTTP->SOCKS5 bridge on 127.0.0.1:{} (upstream {}:{})", + port_, socks5.host, socks5.port)); + return port_; + } + + void Socks5HttpBridge::stop() + { + if (!running_.exchange(false)) { + return; + } + + boost::system::error_code ec; + if (acceptor_) { + acceptor_->close(ec); + } + if (acceptThread_.joinable()) { + acceptThread_.join(); + } + acceptor_.reset(); + + std::vector<std::unique_ptr<Connection>> connections; + { + std::lock_guard<std::mutex> lock(mutex_); + connections.swap(connections_); + upstream_.reset(); + } + for (auto& conn : connections) { + conn->client.close(ec); + conn->upstream.close(ec); + } + for (auto& conn : connections) { + if (conn->worker.joinable()) { + conn->worker.join(); + } + } + port_ = 0; + } + + std::optional<Void::Net::ProxyConfig> Socks5HttpBridge::upstream() const + { + std::lock_guard<std::mutex> lock(mutex_); + return upstream_; + } + + void Socks5HttpBridge::acceptLoop() + { + while (running_.load()) { + auto conn = std::make_unique<Connection>(io_); + boost::system::error_code ec; + acceptor_->accept(conn->client, ec); + if (ec) { + // close() from stop() lands here. + break; + } + + Connection* raw = conn.get(); + { + std::lock_guard<std::mutex> lock(mutex_); + pruneFinished(); + connections_.push_back(std::move(conn)); + } + raw->worker = std::thread([this, raw]() { + serve(*raw); + raw->done = true; + }); + } + } + + void Socks5HttpBridge::pruneFinished() + { + // Caller holds mutex_. + std::erase_if(connections_, [](const std::unique_ptr<Connection>& c) { + if (!c->done.load()) { + return false; + } + if (c->worker.joinable()) { + c->worker.join(); + } + return true; + }); + } + + void Socks5HttpBridge::serve(Connection& conn) + { + boost::system::error_code ec; + + // Read the request head; ffmpeg sends a single CONNECT for https + // targets. Bound the handshake so a stuck client can't pin the thread. + setSocketTimeouts(conn.client, 15); + + asio::streambuf head; + asio::read_until(conn.client, head, "\r\n\r\n", ec); + if (ec) { + conn.client.close(ec); + return; + } + std::istream stream(&head); + std::string requestLine; + std::getline(stream, requestLine); + if (!requestLine.empty() && requestLine.back() == '\r') { + requestLine.pop_back(); + } + + const auto target = parseConnectTarget(requestLine); + if (!target) { + Void::Log::warn( + "Socks5HttpBridge", "{}", + std::format("Rejected non-CONNECT request: '{}'", requestLine)); + writeAll(conn.client, + "HTTP/1.1 405 Method Not Allowed\r\n\r\n"); + conn.client.close(ec); + return; + } + + std::optional<Void::Net::ProxyConfig> proxy = upstream(); + if (!proxy) { + writeAll(conn.client, "HTTP/1.1 502 Bad Gateway\r\n\r\n"); + conn.client.close(ec); + return; + } + + try { + setSocketTimeouts(conn.upstream, 15); + tcp::resolver resolver(io_); + asio::connect(conn.upstream, + resolver.resolve(proxy->host, + std::to_string(proxy->port))); + socks5Connect(conn.upstream, target->first, target->second, + *proxy); + } catch (const std::exception& e) { + Void::Log::warn( + "Socks5HttpBridge", "{}", + std::format("Tunnel to {}:{} failed: {}", target->first, + target->second, e.what())); + writeAll(conn.client, "HTTP/1.1 502 Bad Gateway\r\n\r\n"); + conn.client.close(ec); + conn.upstream.close(ec); + return; + } + + writeAll(conn.client, "HTTP/1.1 200 Connection established\r\n\r\n"); + + // Relay phase: no timeouts — a paused stream may idle for minutes. + setSocketTimeouts(conn.client, 0); + setSocketTimeouts(conn.upstream, 0); + + std::thread downstream( + [&conn]() { pump(conn.upstream, conn.client); }); + pump(conn.client, conn.upstream); + downstream.join(); + + conn.client.close(ec); + conn.upstream.close(ec); + } + + void Socks5HttpBridge::socks5Connect(tcp::socket& upstream, + const std::string& host, + uint16_t targetPort, + const Void::Net::ProxyConfig& proxy) + { + // Greeting: no-auth, plus user/pass when credentials are configured. + std::vector<uint8_t> greeting{0x05}; + if (proxy.has_auth()) { + greeting.insert(greeting.end(), {0x02, 0x00, 0x02}); + } else { + greeting.insert(greeting.end(), {0x01, 0x00}); + } + asio::write(upstream, asio::buffer(greeting)); + + std::array<uint8_t, 2> sel{}; + asio::read(upstream, asio::buffer(sel)); + if (sel[0] != 0x05) { + throw std::runtime_error("SOCKS5: invalid version"); + } + if (sel[1] == 0x02) { + if (!proxy.has_auth()) { + throw std::runtime_error("SOCKS5: auth required"); + } + std::vector<uint8_t> auth{0x01}; + auth.push_back(static_cast<uint8_t>(proxy.username->size())); + auth.insert(auth.end(), proxy.username->begin(), + proxy.username->end()); + auth.push_back(static_cast<uint8_t>(proxy.password->size())); + auth.insert(auth.end(), proxy.password->begin(), + proxy.password->end()); + asio::write(upstream, asio::buffer(auth)); + std::array<uint8_t, 2> authReply{}; + asio::read(upstream, asio::buffer(authReply)); + if (authReply[0] != 0x01 || authReply[1] != 0x00) { + throw std::runtime_error("SOCKS5: authentication failed"); + } + } else if (sel[1] != 0x00) { + throw std::runtime_error("SOCKS5: no acceptable auth method"); + } + + // CONNECT request: literal IPs as ATYP 1/4, otherwise the domain form + // (ATYP 3) so the proxy resolves — important when googlevideo DNS is + // poisoned or blocked locally. + std::vector<uint8_t> connectReq{0x05, 0x01, 0x00}; + boost::system::error_code addrEc; + const auto addr = asio::ip::make_address(host, addrEc); + if (!addrEc) { + if (addr.is_v4()) { + connectReq.push_back(0x01); + for (auto b : addr.to_v4().to_bytes()) { + connectReq.push_back(b); + } + } else { + connectReq.push_back(0x04); + for (auto b : addr.to_v6().to_bytes()) { + connectReq.push_back(b); + } + } + } else { + connectReq.push_back(0x03); + connectReq.push_back(static_cast<uint8_t>(host.size())); + connectReq.insert(connectReq.end(), host.begin(), host.end()); + } + connectReq.push_back(static_cast<uint8_t>((targetPort >> 8) & 0xFF)); + connectReq.push_back(static_cast<uint8_t>(targetPort & 0xFF)); + asio::write(upstream, asio::buffer(connectReq)); + + std::array<uint8_t, 4> reply{}; + asio::read(upstream, asio::buffer(reply)); + if (reply[0] != 0x05) { + throw std::runtime_error("SOCKS5: invalid connect reply"); + } + if (reply[1] != 0x00) { + throw std::runtime_error(std::format( + "SOCKS5: connect failed (code {})", int(reply[1]))); + } + // Drain the bound address the proxy reports. + switch (reply[3]) { + case 0x01: { + std::array<uint8_t, 6> bound{}; + asio::read(upstream, asio::buffer(bound)); + break; + } + case 0x03: { + std::array<uint8_t, 1> len{}; + asio::read(upstream, asio::buffer(len)); + std::vector<uint8_t> bound(len[0] + 2u); + asio::read(upstream, asio::buffer(bound)); + break; + } + case 0x04: { + std::array<uint8_t, 18> bound{}; + asio::read(upstream, asio::buffer(bound)); + break; + } + default: + break; + } + } + +} // namespace Echoion::Core diff --git a/src/SubscriptionManager.cpp b/src/SubscriptionManager.cpp index ce16987..4dcce05 100644 --- a/src/SubscriptionManager.cpp +++ b/src/SubscriptionManager.cpp @@ -65,7 +65,14 @@ namespace Echoion::Core if (subscribedUids_.contains(uid)) { // Update nickname even if already subscribed if (database_) { - database_->addSubscriber(uid, nickname); + if (auto result = database_->addSubscriber(uid, nickname); + !result) { + Void::Log::warn( + "SubscriptionManager", "{}", + std::format( + "Failed to refresh subscriber {} nickname: {}", + uid, result.error().message)); + } } return false; // Already subscribed } diff --git a/src/SubscriptionService.cpp b/src/SubscriptionService.cpp index 35ffd17..62f0ce6 100644 --- a/src/SubscriptionService.cpp +++ b/src/SubscriptionService.cpp @@ -40,8 +40,8 @@ namespace Echoion::Core // A subscriber appeared: if this policy paused playback earlier, // bring it back. - if (added && pausedForNoSubscribers_.load() && - resumeOnReturn_.load() && requestResume_) { + if (added && pausedForNoSubscribers_.load() && resumeOnReturn_.load() && + requestResume_) { if (requestResume_()) { pausedForNoSubscribers_ = false; } @@ -201,21 +201,24 @@ namespace Echoion::Core return manager_->getSubscribers(); } - bool SubscriptionService::onClientConnected(uint64_t clientId) + SubscriptionService::ClientConnectResult + SubscriptionService::onClientConnected(uint64_t clientId) { + ClientConnectResult result; if (!manager_ || !clientInfo_) { - return false; + return result; } auto clientInfo = clientInfo_(clientId); if (!clientInfo) { - return false; + return result; } const auto& [uid, nickname] = *clientInfo; if (!manager_->isSubscribed(uid)) { - return false; + return result; } + result.subscribedUid = uid; Void::Log::info( "SubscriptionService", "{}", @@ -233,10 +236,11 @@ namespace Echoion::Core if (requestResume_()) { pausedForNoSubscribers_ = false; } - return false; // resumed; no auto-start needed + return result; // resumed; no auto-start needed } - return true; // subscribed user online; caller may auto-start playback + result.mayAutoStart = true; // caller may auto-start playback + return result; } void SubscriptionService::onClientDisconnected(uint64_t clientId) diff --git a/src/YouTubeClient.cpp b/src/YouTubeClient.cpp index ec809ac..4c828ed 100644 --- a/src/YouTubeClient.cpp +++ b/src/YouTubeClient.cpp @@ -5,6 +5,7 @@ #include <Void/Text/Url.hpp> #include <Void/Time/Format.hpp> #include <algorithm> +#include <array> #include <atomic> #include <cctype> #include <filesystem> @@ -12,6 +13,7 @@ #include <future> #include <iomanip> #include <memory> +#include <random> #include <regex> #include <sstream> #include <thread> @@ -155,7 +157,11 @@ namespace Echoion::Core return Api::fail(Api::ErrorCode::ServiceUnavailable, "yt-dlp manager not initialized"); } - return ytDlpManager_->update(); + auto result = ytDlpManager_->update(); + if (!result) { + return std::unexpected(result.error()); + } + return {}; } Api::Result<std::string> @@ -275,6 +281,7 @@ namespace Echoion::Core } std::string url = result.output; + Void::Log::debug("YouTubeClient", "{}", url); // -g may print multiple lines (video+audio); take the first. if (auto nl = url.find('\n'); nl != std::string::npos) { url.resize(nl); @@ -485,8 +492,9 @@ namespace Echoion::Core return results; } - Api::Result<Api::SearchResult> YouTubeClient::search( - std::string_view query, std::optional<std::string> pageToken) + Api::Result<Api::SearchResult> + YouTubeClient::search(std::string_view query, + std::optional<std::string> pageToken) { if (!initialized_) { @@ -831,7 +839,23 @@ namespace Echoion::Core } Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlp( - std::string_view query, const std::optional<std::string>& pageToken) + std::string_view query, + const std::optional<std::string>& /*pageToken*/) + { + return searchWithYtDlpProvider(query, "ytsearch5", + Api::TrackSource::YouTube); + } + + Api::Result<Api::SearchResult> + YouTubeClient::searchSoundCloud(std::string_view query) + { + return searchWithYtDlpProvider(query, "scsearch5", + Api::TrackSource::SoundCloud); + } + + Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlpProvider( + std::string_view query, std::string_view searchPrefix, + Api::TrackSource source) { if (!ytDlpManager_->isAvailable()) { @@ -842,8 +866,8 @@ namespace Echoion::Core Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp search..."); auto searchStart = std::chrono::steady_clock::now(); - // yt-dlp search format: ytsearch5:query - std::string searchQuery = std::format("ytsearch5:{}", query); + // yt-dlp search format, e.g. ytsearch5:query or scsearch5:query + std::string searchQuery = std::format("{}:{}", searchPrefix, query); auto result = ytDlpManager_->executeAsync( {searchQuery, "-J", "--flat-playlist", "--no-warnings"}); @@ -908,11 +932,16 @@ namespace Echoion::Core if ((entry).has("thumbnail")) { track.thumbnailUrl = (entry).get_str("thumbnail"); } - // Set originalUrl so we can extract video ID later for - // streaming - track.originalUrl = std::format( - "https://www.youtube.com/watch?v={}", track.id); - track.source = Api::TrackSource::YouTube; + // Set originalUrl so the track can be resolved later. For + // YouTube it's the watch URL (id is the video id); other + // providers (SoundCloud) carry the permalink in `url`. + if (source == Api::TrackSource::YouTube) { + track.originalUrl = std::format( + "https://www.youtube.com/watch?v={}", track.id); + } else if ((entry).has("url")) { + track.originalUrl = (entry).get_str("url"); + } + track.source = source; searchResult.tracks.push_back(track); } @@ -1019,6 +1048,101 @@ namespace Echoion::Core } } + Api::Result<std::vector<Api::TrackInfo>> + YouTubeClient::randomMusicVideo(size_t limit) + { + if (!ytDlpManager_->isAvailable()) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available"); + } + + // Curated music-oriented queries so a plain ytsearch skews toward + // actual music rather than talk/gaming clips. One is picked at random + // 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<std::string_view, 10> kQueries = { + "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<size_t> pick(0, kQueries.size() - 1); + const std::string_view query = kQueries[pick(rng)]; + + // ytsearch<N>: returns the top N results for the query as a flat + // playlist — cheap metadata only, same as radioMix. + const std::string searchUrl = + std::format("ytsearch{}:{}", limit + 10, query); + auto future = ytDlpManager_->executeAsync( + {searchUrl, "-J", "--flat-playlist", "--no-warnings"}); + + auto waitStatus = future.wait_for(std::chrono::seconds(30)); + if (waitStatus == std::future_status::timeout) { + return Api::fail(Api::ErrorCode::NetworkError, + "yt-dlp random music search timed out"); + } + auto ytdlpResult = future.get(); + if (!ytdlpResult.success || ytdlpResult.output.empty()) { + return Api::fail(Api::ErrorCode::NetworkError, + "yt-dlp random music search failed"); + } + + try { + auto parsed = Void::Json::parse(ytdlpResult.output); + if (!parsed) { + return Api::fail( + Api::ErrorCode::ParseError, + "Failed to parse yt-dlp random music search output"); + } + const JValue& json = *parsed; + + std::vector<Api::TrackInfo> tracks; + if (const JValue* entries = (json).child_array("entries")) { + for (const JValue& entry : entries->as_array()) { + if (!(entry).has("id")) { + continue; + } + Api::TrackInfo track; + track.id = (entry).get_str("id"); + if ((entry).has("title")) { + track.title = + Void::Text::html_unescape((entry).get_str("title")); + } + if ((entry).has("uploader")) { + track.artist = Void::Text::html_unescape( + (entry).get_str("uploader")); + } + if ((entry).has("duration")) { + track.duration = std::chrono::seconds( + static_cast<int64_t>((entry).get_num("duration"))); + } + if ((entry).has("thumbnail")) { + track.thumbnailUrl = (entry).get_str("thumbnail"); + } + track.requestedBy = "radio\\autoplay"; + track.addedAt = std::chrono::system_clock::now(); + track.originalUrl = std::format( + "https://www.youtube.com/watch?v={}", track.id); + track.source = Api::TrackSource::YouTube; + tracks.push_back(std::move(track)); + } + } + + // Shuffle so the caller's "take the first acceptable one" pick is + // effectively random across the result set. + std::shuffle(tracks.begin(), tracks.end(), rng); + populateShortenedUrls(tracks); + return tracks; + + } catch (const std::exception& e) { + return Api::fail( + Api::ErrorCode::ParseError, + std::format("Exception parsing yt-dlp random music search: {}", + e.what())); + } + } + Api::Result<Api::PlaylistInfo> YouTubeClient::getPlaylist(std::string_view playlistId) { diff --git a/src/YtDlpManager.cpp b/src/YtDlpManager.cpp index 31a470a..81650ad 100644 --- a/src/YtDlpManager.cpp +++ b/src/YtDlpManager.cpp @@ -1,9 +1,11 @@ -#include <Void/Log/Log.hpp> #include "echoion/core/YtDlpManager.hpp" +#include <Void/Log/Log.hpp> #include <Void/System/Process.hpp> #include <array> +#include <cerrno> #include <chrono> #include <cstdlib> +#include <cstring> #include <format> #include <fstream> #include <future> @@ -113,15 +115,18 @@ namespace Echoion::Core return {}; } - Void::Log::info("YtDlpManager", "{}", "Initializing yt-dlp manager..."); + Void::Log::info("YtDlpManager", "{}", + "Initializing yt-dlp manager..."); // Create storage directory if needed std::filesystem::path storageDir = getStorageDir(); - Void::Log::debug("YtDlpManager", "{}", + Void::Log::debug( + "YtDlpManager", "{}", std::format("yt-dlp storage dir: {}", storageDir.string())); if (!std::filesystem::exists(storageDir)) { - Void::Log::info("YtDlpManager", "{}", "Creating yt-dlp storage directory..."); + Void::Log::info("YtDlpManager", "{}", + "Creating yt-dlp storage directory..."); try { std::filesystem::create_directories(storageDir); } catch (const std::exception& e) { @@ -134,10 +139,11 @@ namespace Echoion::Core } executablePath_ = storageDir / getExecutableName(); - Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp executable path: {}", - executablePath_.string())); + Void::Log::debug("YtDlpManager", "{}", + std::format("yt-dlp executable path: {}", + executablePath_.string())); - } // Release lock; everything below runs off the caller's thread. + } // Release lock; everything below runs off the caller's thread. // Download/update and the subprocess version check can take seconds // (10s timeout each) — that used to run inline and stalled every @@ -147,32 +153,38 @@ namespace Echoion::Core // preserved: downloadYtDlp()/getVersion() run without mutex_ held // (getVersion -> execute -> getCookieArgs takes it). initThread_ = std::jthread([this]() { + // update() already verifies the fresh binary; only probe the + // version ourselves when no (successful) update ran. + std::string version; const bool exists = std::filesystem::exists(executablePath_); if (!exists) { Void::Log::info("YtDlpManager", "{}", "yt-dlp not found, downloading..."); auto result = downloadYtDlp(); if (!result) { - Void::Log::error( - "YtDlpManager", "{}", - std::format("yt-dlp download failed: {}", - result.error().message)); + Void::Log::error("YtDlpManager", "{}", + std::format("yt-dlp download failed: {}", + result.error().message)); return; } } else if (autoUpdateEnabled_.load() && shouldUpdate()) { Void::Log::info("YtDlpManager", "{}", "yt-dlp may be outdated, updating..."); auto result = update(); - if (!result) { + if (result) { + version = *result; + } else { Void::Log::warn("YtDlpManager", "{}", - std::format("yt-dlp update failed: {}", - result.error().toString())); + std::format("yt-dlp update failed: {}", + result.error().toString())); } } - Void::Log::info("YtDlpManager", "{}", - "Checking yt-dlp version..."); - const std::string version = getVersion(); + if (version.empty()) { + Void::Log::info("YtDlpManager", "{}", + "Checking yt-dlp version..."); + version = getVersion(); + } if (version.empty()) { Void::Log::error("YtDlpManager", "{}", "yt-dlp executable not working"); @@ -201,15 +213,19 @@ namespace Echoion::Core unsigned int hardwareThreads = std::thread::hardware_concurrency(); if (hardwareThreads > 0 && threadPoolSize_ > hardwareThreads / 2) { threadPoolSize_ = std::max(1u, hardwareThreads / 2); - Void::Log::info("YtDlpManager", "{}", std::format( - "Auto-adjusted yt-dlp thread pool to {} threads (hardware: {})", - threadPoolSize_, hardwareThreads)); + Void::Log::info("YtDlpManager", "{}", + std::format("Auto-adjusted yt-dlp thread pool to " + "{} threads (hardware: {})", + threadPoolSize_, hardwareThreads)); } - Void::Log::info("YtDlpManager", "{}", std::format( - "Starting yt-dlp thread pool with {} threads", threadPoolSize_)); + Void::Log::info( + "YtDlpManager", "{}", + std::format("Starting yt-dlp thread pool with {} threads", + threadPoolSize_)); - pool_ = std::make_unique<Void::Concurrency::ThreadPool>(threadPoolSize_); + pool_ = + std::make_unique<Void::Concurrency::ThreadPool>(threadPoolSize_); } void YtDlpManager::stopThreadPool() @@ -250,8 +266,9 @@ namespace Echoion::Core std::lock_guard<std::mutex> lock(proxyMutex_); proxyConfig_ = proxy; if (proxy.has_value() && proxy->enabled()) { - Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp proxy configured: {}:{}", - proxy->host, proxy->port)); + Void::Log::info("YtDlpManager", "{}", + std::format("yt-dlp proxy configured: {}:{}", + proxy->host, proxy->port)); } else { Void::Log::info("YtDlpManager", "{}", "yt-dlp proxy cleared"); } @@ -302,11 +319,12 @@ namespace Echoion::Core { if (!networkClient_) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Network client not available"); + "Network client not available"); } std::string downloadUrl = getDownloadUrl(); - Void::Log::info("YtDlpManager", "{}", + Void::Log::info( + "YtDlpManager", "{}", std::format("Downloading yt-dlp from: {}", downloadUrl)); std::vector<Void::Net::Header> headers = { @@ -322,8 +340,8 @@ namespace Echoion::Core auto result = networkClient_->get(downloadUrl, headers); if (!result) { return Api::fail(Api::ErrorCode::NetworkError, - std::format("Failed to download yt-dlp: {}", - result.error().message)); + std::format("Failed to download yt-dlp: {}", + result.error().message)); } response = std::move(*result); @@ -352,8 +370,9 @@ namespace Echoion::Core } } - Void::Log::info("YtDlpManager", "{}", std::format("Following redirect (HTTP {}): {}", - response.status, newUrl)); + Void::Log::info("YtDlpManager", "{}", + std::format("Following redirect (HTTP {}): {}", + response.status, newUrl)); downloadUrl = newUrl; redirectCount++; continue; @@ -364,23 +383,42 @@ namespace Echoion::Core if (!response.ok()) { return Api::fail(Api::ErrorCode::NetworkError, - std::format("Failed to download yt-dlp: HTTP {}", - response.status)); + std::format("Failed to download yt-dlp: HTTP {}", + response.status)); } - Void::Log::info("YtDlpManager", "{}", + Void::Log::info( + "YtDlpManager", "{}", std::format("Downloaded {} bytes", response.body.size())); - // Write to file + // Write to a temp file next to the target, verify it, then atomically + // rename over the real path. Writing the live binary in place fails + // with ETXTBSY while any yt-dlp process is running; rename never + // touches the executing inode, so the swap always succeeds. + const std::filesystem::path tempPath = + executablePath_.string() + ".new"; try { - std::ofstream file(executablePath_, std::ios::binary); + errno = 0; + std::ofstream file(tempPath, std::ios::binary | std::ios::trunc); if (!file) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Failed to open yt-dlp file for writing"); + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format("Failed to open '{}' for writing: {}", + tempPath.string(), std::strerror(errno))); } - file.write(response.body.data(), response.body.size()); + file.write(response.body.data(), + static_cast<std::streamsize>(response.body.size())); file.close(); + if (!file) { + std::filesystem::remove(tempPath); + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format("Failed to write '{}': {}", tempPath.string(), + std::strerror(errno))); + } } catch (const std::exception& e) { + std::error_code ec; + std::filesystem::remove(tempPath, ec); return Api::fail( Api::ErrorCode::ServiceUnavailable, std::format("Failed to write yt-dlp file: {}", e.what())); @@ -388,12 +426,40 @@ namespace Echoion::Core // Make executable on Unix #ifndef _WIN32 - auto execResult = makeExecutable(); + auto execResult = makeExecutable(tempPath); if (!execResult) { + std::error_code ec; + std::filesystem::remove(tempPath, ec); return execResult; } #endif + // Verify the downloaded binary actually runs before swapping it in; + // a truncated/corrupt download must never replace a working one. + auto probe = Void::Process::run(tempPath, {"--version"}, {}, + std::chrono::seconds(10)); + if (!probe || probe->exit_code != 0) { + std::error_code ec; + std::filesystem::remove(tempPath, ec); + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format("Downloaded yt-dlp failed verification: {}", + probe ? std::format("exit code {}", + probe->exit_code) + : probe.error().message())); + } + + std::error_code renameEc; + std::filesystem::rename(tempPath, executablePath_, renameEc); + if (renameEc) { + std::error_code ec; + std::filesystem::remove(tempPath, ec); + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format("Failed to move '{}' into place: {}", + tempPath.string(), renameEc.message())); + } + // Write timestamp file for update checking try { std::ofstream tsFile(getStorageDir() / ".last_update"); @@ -409,15 +475,19 @@ namespace Echoion::Core return {}; } - Api::Result<void> YtDlpManager::makeExecutable() + Api::Result<void> + YtDlpManager::makeExecutable(const std::filesystem::path& path) { #ifdef _WIN32 + (void)path; return {}; // Windows doesn't need this #else - if (chmod(executablePath_.c_str(), + if (chmod(path.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Failed to make yt-dlp executable"); + return Api::fail( + Api::ErrorCode::ServiceUnavailable, + std::format("Failed to make '{}' executable: {}", + path.string(), std::strerror(errno))); } return {}; #endif @@ -453,66 +523,42 @@ namespace Echoion::Core } } - Api::Result<void> YtDlpManager::update() + Api::Result<std::string> YtDlpManager::update() { - std::lock_guard<std::mutex> lock(mutex_); - + // No mutex_ here: downloadYtDlp() verifies the new binary and swaps + // it in atomically (no backup needed), and getVersion() -> execute() + // -> getCookieArgs() takes mutex_ itself — holding it across the call + // would self-deadlock. Same lock discipline as initialize(). Void::Log::info("YtDlpManager", "{}", "Updating yt-dlp..."); - // Backup current version - std::filesystem::path backupPath = executablePath_.string() + ".backup"; - try { - if (std::filesystem::exists(executablePath_)) { - std::filesystem::copy_file( - executablePath_, backupPath, - std::filesystem::copy_options::overwrite_existing); - } - } catch (...) { - } - - // Download new version auto result = downloadYtDlp(); if (!result) { - // Restore backup if available - try { - if (std::filesystem::exists(backupPath)) { - std::filesystem::copy_file( - backupPath, executablePath_, - std::filesystem::copy_options::overwrite_existing); - } - } catch (...) { - } - return result; + return std::unexpected(result.error()); } - // Remove backup - try { - std::filesystem::remove(backupPath); - } catch (...) { - } - - // Verify new version works - std::string version = getVersion(); + const std::string version = getVersion(); if (version.empty()) { return Api::fail(Api::ErrorCode::ServiceUnavailable, - "Updated yt-dlp not working"); + "Updated yt-dlp not working"); } - Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp updated to: {}", version)); - return {}; + Void::Log::info("YtDlpManager", "{}", + std::format("yt-dlp updated to: {}", version)); + return version; } std::string YtDlpManager::getVersion() const { if (!std::filesystem::exists(executablePath_)) { - Void::Log::warn("YtDlpManager", "{}", - "yt-dlp executable not found for version check"); + Void::Log::warn("YtDlpManager", "{}", + "yt-dlp executable not found for version check"); return ""; } Void::Log::debug("YtDlpManager", "{}", "Executing yt-dlp --version..."); std::string result = execute({"--version"}); - Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp --version output: '{}'", result)); + Void::Log::debug("YtDlpManager", "{}", + std::format("yt-dlp --version output: '{}'", result)); // Remove trailing newline if (!result.empty() && result.back() == '\n') { @@ -526,14 +572,16 @@ namespace Echoion::Core { std::lock_guard<std::mutex> lock(mutex_); cookiesPath_ = path; - Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp cookies path set to: {}", path)); + Void::Log::info("YtDlpManager", "{}", + std::format("yt-dlp cookies path set to: {}", path)); } void YtDlpManager::setCookiesFromBrowser(const std::string& browser) { std::lock_guard<std::mutex> lock(mutex_); cookiesFromBrowser_ = browser; - Void::Log::info("YtDlpManager", "{}", + Void::Log::info( + "YtDlpManager", "{}", std::format("yt-dlp will use cookies from browser: {}", browser)); } @@ -574,7 +622,8 @@ namespace Echoion::Core // Assemble argv: proxy args, then cookie args, then caller args. // Void::Process::run executes the binary directly (no shell), so no - // manual quoting/escaping is required and arguments are passed verbatim. + // manual quoting/escaping is required and arguments are passed + // verbatim. std::vector<std::string> processArgs; const auto proxyArgs = getProxyArgs(); processArgs.insert(processArgs.end(), proxyArgs.begin(), @@ -589,9 +638,15 @@ namespace Echoion::Core (args.size() == 1 && args[0] == "--version"); const auto timeout = std::chrono::seconds(isVersionCheck ? 10 : 60); - Void::Log::debug("YtDlpManager", "{}", std::format("Executing yt-dlp: {} ({} args)", - executablePath_.string(), - processArgs.size())); + auto argsStr = std::accumulate( + std::next(processArgs.begin()), + processArgs.end(), + processArgs[0], + [](std::string a, std::string b) { return a + " " + b; }); + Void::Log::debug( + "YtDlpManager", "{}", + std::format("Executing yt-dlp: {} ({} args) commandArgs: {}", + executablePath_.string(), processArgs.size(), argsStr)); auto procResult = Void::Process::run(executablePath_, processArgs, {}, timeout); @@ -602,8 +657,9 @@ namespace Echoion::Core startTime); if (!procResult) { - Void::Log::warn("YtDlpManager", "{}", std::format("Failed to execute yt-dlp: {}", - procResult.error().message())); + Void::Log::warn("YtDlpManager", "{}", + std::format("Failed to execute yt-dlp: {}", + procResult.error().message())); return result; } @@ -614,7 +670,6 @@ namespace Echoion::Core return result; } - std::future<YtDlpResult> YtDlpManager::executeAsync(const std::vector<std::string>& args) { @@ -629,27 +684,4 @@ namespace Echoion::Core return pool_->submit([this, args]() { return executeInternal(args); }); } - std::vector<YtDlpResult> YtDlpManager::executeBatch( - const std::vector<std::vector<std::string>>& argsList) - { - - std::vector<std::future<YtDlpResult>> futures; - futures.reserve(argsList.size()); - - // Launch all tasks - for (const auto& args : argsList) { - futures.push_back(executeAsync(args)); - } - - // Collect results - std::vector<YtDlpResult> results; - results.reserve(argsList.size()); - - for (auto& future : futures) { - results.push_back(future.get()); - } - - return results; - } - } // namespace Echoion::Core diff --git a/src/i18n/Localization.cpp b/src/i18n/Localization.cpp new file mode 100644 index 0000000..7b1a11d --- /dev/null +++ b/src/i18n/Localization.cpp @@ -0,0 +1,68 @@ +#include "echoion/core/i18n/Localization.hpp" + +#include <algorithm> +#include <cctype> +#include <string> +#include <unordered_map> + +namespace Echoion::Core::I18n +{ + + Language parseLanguage(std::string_view code) + { + std::string lower(code); + std::transform(lower.begin(), lower.end(), lower.begin(), + [](unsigned char c) { return std::tolower(c); }); + if (lower == "ru" || lower == "russian" || + lower == "\xd1\x80\xd1\x83" || + lower == "\xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0" + "\xb9") { + return Language::Russian; + } + return Language::English; + } + + std::string_view languageCode(Language lang) + { + return lang == Language::Russian ? "ru" : "en"; + } + + std::string_view languageName(Language lang) + { + // Self-referential (shown when a user picks a language). + return lang == Language::Russian ? "\xd0\xa0\xd1\x83\xd1\x81\xd1\x81" + "\xd0\xba\xd0\xb8\xd0\xb9" + : "English"; + } + + namespace + { + // English source string -> Russian translation. Keys must match the + // English text passed to CommandContext::tr/trf exactly (adjacent + // string literals are already concatenated by the compiler). A missing + // key simply renders the English original, so partial coverage is safe. + const std::unordered_map<std::string_view, std::string_view>& + russianCatalog() + { + static const std::unordered_map<std::string_view, std::string_view> + kMap = { + // Populated in Localization.cpp catalog section. +#include "RussianCatalog.inc" + }; + return kMap; + } + } // namespace + + std::string_view translate(std::string_view english, Language lang) + { + if (lang == Language::English || english.empty()) { + return english; + } + const auto& map = russianCatalog(); + if (auto it = map.find(english); it != map.end()) { + return it->second; + } + return english; + } + +} // namespace Echoion::Core::I18n diff --git a/src/i18n/RussianCatalog.inc b/src/i18n/RussianCatalog.inc new file mode 100644 index 0000000..5ecb30a --- /dev/null +++ b/src/i18n/RussianCatalog.inc @@ -0,0 +1,200 @@ +// Auto-generated English -> Russian translation entries. +// Consumed by Localization.cpp. Keys must byte-match tr()/trf() sources. + +{"\n\n— Page {}/{} · {}next · {}prev · {}page <n>", "\n\n— Страница {}/{} · {}next · {}prev · {}page <n>"}, +{"\n**Now Playing:** {}{}\n", "\n**Сейчас играет:** {}{}\n"}, +{"\n**Up Next ({} tracks):**\n", "\n**Далее ({} треков):**\n"}, +{"\nThe queue is empty. Add songs with {}play !", "\nОчередь пуста. Добавьте треки командой {}play !"}, +{"\nUse {}queue <page> to see more (page {} of {})", "\nИспользуйте {}queue <страница>, чтобы увидеть больше (страница {} из {})"}, +{"\nUse {}select <number> to play a result.", "\nИспользуйте {}select <номер>, чтобы включить результат."}, +{" total)\n", " всего)\n"}, +{" | ⚪ Offline: ", " | ⚪ Не в сети: "}, +{"# 🎵 Echoion Bot Help", "# 🎵 Справка Echoion"}, +{"**⚪ Offline:**\n", "**⚪ Не в сети:**\n"}, +{"**🟢 Online:**\n", "**🟢 В сети:**\n"}, +{"- {} ({} tracks)\n", "- {} ({} треков)\n"}, +{":::details {} {} Commands\n\n", ":::details {} {} — команды\n\n"}, +{"> [!TIP]\n> Prefix is `{}` — e.g. `{}play lofi`\n\n", "> [!TIP]\n> Префикс — `{}`, например `{}play lofi`\n\n"}, +{"> 🎚 {} {}% · 🔀 {} {} · 🔁 {} {} · 📻 {} {}\n\n", "> 🎚 {} {}% · 🔀 {} {} · 🔁 {} {} · 📻 {} {}\n\n"}, +{"Added to favorites: {}", "Добавлено в избранное: {}"}, +{"Added to queue: {}", "Добавлено в очередь: {}"}, +{"Aliases:", "Псевдонимы:"}, +{"An unexpected error occurred. Our team has been notified.", "Произошла непредвиденная ошибка. Мы уже уведомлены."}, +{"Announcement saved and delivered to {} online subscriber(s). Offline subscribers get it on their next connect.", "Объявление сохранено и доставлено {} подписчикам в сети. Остальные получат его при следующем подключении."}, +{"Config reload is unavailable right now.", "Перезагрузка конфигурации сейчас недоступна."}, +{"Couldn't add that track. Please try again.", "Не удалось добавить трек. Попробуйте ещё раз."}, +{"Couldn't change volume. Please try again.", "Не удалось изменить громкость. Попробуйте ещё раз."}, +{"Couldn't clear subscriptions. Please try again.", "Не удалось очистить подписки. Попробуйте ещё раз."}, +{"Couldn't clear the queue. Please try again.", "Не удалось очистить очередь. Попробуйте ещё раз."}, +{"Couldn't connect to search service. Please check your connection.", "Не удалось подключиться к поиску. Проверьте соединение."}, +{"Couldn't connect to that URL. Please check and try again.", "Не удалось подключиться по этой ссылке. Проверьте её и попробуйте снова."}, +{"Couldn't generate help. Please try again.", "Не удалось сформировать справку. Попробуйте ещё раз."}, +{"Couldn't get current track information.", "Не удалось получить информацию о текущем треке."}, +{"Couldn't get queue information.", "Не удалось получить информацию об очереди."}, +{"Couldn't identify you on the server.", "Не удалось определить вас на сервере."}, +{"Couldn't load the playlist. Please try again.", "Не удалось загрузить плейлист. Попробуйте ещё раз."}, +{"Couldn't move that track. Please try again.", "Не удалось переместить трек. Попробуйте ещё раз."}, +{"Couldn't pause playback. Please try again.", "Не удалось поставить на паузу. Попробуйте ещё раз."}, +{"Couldn't play it: {}", "Не удалось воспроизвести: {}"}, +{"Couldn't play that URL. Please try again.", "Не удалось воспроизвести эту ссылку. Попробуйте ещё раз."}, +{"Couldn't read playback statistics.", "Не удалось прочитать статистику воспроизведения."}, +{"Couldn't read the playback history.", "Не удалось прочитать историю воспроизведения."}, +{"Couldn't read your favorites.", "Не удалось прочитать ваше избранное."}, +{"Couldn't remove that track. Please try again.", "Не удалось удалить трек. Попробуйте ещё раз."}, +{"Couldn't remove the favorite.", "Не удалось удалить из избранного."}, +{"Couldn't resume playback. Please try again.", "Не удалось возобновить воспроизведение. Попробуйте ещё раз."}, +{"Couldn't retrieve playlists.", "Не удалось получить плейлисты."}, +{"Couldn't save the favorite.", "Не удалось сохранить в избранное."}, +{"Couldn't save your language. Please try again.", "Не удалось сохранить язык. Попробуйте ещё раз."}, +{"Couldn't seek. Please try again.", "Не удалось перемотать. Попробуйте ещё раз."}, +{"Couldn't select that track. Please try again.", "Не удалось выбрать трек. Попробуйте ещё раз."}, +{"Couldn't skip. Please try again.", "Не удалось пропустить. Попробуйте ещё раз."}, +{"Couldn't stop playback. Please try again.", "Не удалось остановить воспроизведение. Попробуйте ещё раз."}, +{"Couldn't subscribe you. Please try again.", "Не удалось оформить подписку. Попробуйте ещё раз."}, +{"Couldn't toggle repeat. Please try again.", "Не удалось переключить повтор. Попробуйте ещё раз."}, +{"Couldn't unsubscribe user. Please try again.", "Не удалось отписать пользователя. Попробуйте ещё раз."}, +{"Couldn't unsubscribe you. Please try again.", "Не удалось отписать вас. Попробуйте ещё раз."}, +{"Current language: {}. Available: en, ru. Use {}language <en|ru>.", "Текущий язык: {}. Доступно: en, ru. Используйте {}language <en|ru>."}, +{"Current volume: {}%", "Текущая громкость: {}%"}, +{"Favorites are unavailable.", "Избранное недоступно."}, +{"History is unavailable (no database).", "История недоступна (нет базы данных)."}, +{"Language settings are unavailable right now.", "Настройки языка сейчас недоступны."}, +{"Loading playlist '{}'... Tracks will be added to the queue as they are resolved.", "Загрузка плейлиста «{}»... Треки будут добавляться в очередь по мере обработки."}, +{"Moved track from position {} to {}.", "Трек перемещён с позиции {} на {}."}, +{"No favorite with that number.", "Нет избранного с таким номером."}, +{"No more tracks in the queue to skip to.", "В очереди больше нет треков для пропуска."}, +{"No playlists available.", "Нет доступных плейлистов."}, +{"No results found. Try different keywords.", "Ничего не найдено. Попробуйте другие слова."}, +{"No search results found. Use {}play <query> to search first.", "Результатов поиска нет. Сначала выполните поиск: {}play <запрос>."}, +{"No subscribers. Use !subscribe to receive audio.", "Подписчиков нет. Используйте !subscribe, чтобы получать звук."}, +{"Nothing has been played yet.", "Пока ничего не воспроизводилось."}, +{"Nothing is currently playing. Add something with {}play !", "Сейчас ничего не играет. Добавьте что-нибудь командой {}play !"}, +{"Nothing is playing right now.", "Сейчас ничего не играет."}, +{"Nothing to page through — run a command that lists results first.", "Нечего листать — сначала выполните команду со списком результатов."}, +{"Off", "выкл"}, +{"On", "вкл"}, +{"One of those positions doesn't exist in the queue.", "Одной из этих позиций нет в очереди."}, +{"Open the web interface", "Открыть веб-интерфейс"}, +{"Playback isn't paused right now.", "Воспроизведение сейчас не на паузе."}, +{"Playback paused.", "Воспроизведение приостановлено."}, +{"Playback resumed.", "Воспроизведение возобновлено."}, +{"Playback stopped and queue cleared.", "Воспроизведение остановлено, очередь очищена."}, +{"Please provide a user UID. Use !subscribers to see UIDs.", "Укажите UID пользователя. Используйте !subscribers, чтобы увидеть UID."}, +{"Please provide a valid number (0-100).", "Укажите корректное число (0-100)."}, +{"Please provide a valid number (1 or more).", "Укажите корректное число (1 или больше)."}, +{"Please provide a valid number (1, 2, 3, etc.).", "Укажите корректное число (1, 2, 3 и т.д.)."}, +{"Please provide a valid number of seconds.\nExamples: seek +30, seek -10, seek 60", "Укажите корректное число секунд.\nПримеры: seek +30, seek -10, seek 60"}, +{"Please provide a valid position number (starting from 1).", "Укажите корректный номер позиции (начиная с 1)."}, +{"Please provide both from and to positions.", "Укажите позиции «откуда» и «куда»."}, +{"Please provide valid position numbers (starting from 1).", "Укажите корректные номера позиций (начиная с 1)."}, +{"Queue cleared!", "Очередь очищена!"}, +{"Radio", "Радио"}, +{"Reload is handled by the plugin. Use the TS plugin menu to reload the core.", "Перезагрузка выполняется плагином. Используйте меню плагина TS, чтобы перезагрузить ядро."}, +{"Removed from favorites: {}", "Удалено из избранного: {}"}, +{"Removed track at position {}.", "Удалён трек на позиции {}."}, +{"Repeat", "Повтор"}, +{"Repeat is now OFF.", "Повтор выключен."}, +{"Search failed. Please try again later.", "Поиск не удался. Попробуйте позже."}, +{"Search failed. Please try again.", "Поиск не удался. Попробуйте ещё раз."}, +{"Search results for \"", "Результаты поиска по \""}, +{"Seeked to position {}.", "Перемотано на позицию {}."}, +{"Seeked {} from current position.", "Перемотано на {} от текущей позиции."}, +{"Shuffle", "Перемешивание"}, +{"Skipped to next track.", "Пропущено к следующему треку."}, +{"Skipped {} tracks.", "Пропущено треков: {}."}, +{"Something went wrong while trying to play. Please try again.", "Что-то пошло не так при воспроизведении. Попробуйте ещё раз."}, +{"Something went wrong. Please try again.", "Что-то пошло не так. Попробуйте ещё раз."}, +{"Statistics are unavailable (no database).", "Статистика недоступна (нет базы данных)."}, +{"That doesn't look like a valid URL.", "Это не похоже на корректную ссылку."}, +{"That playlist doesn't exist.", "Такого плейлиста не существует."}, +{"That position doesn't exist in the queue.", "Такой позиции нет в очереди."}, +{"The music service is currently unavailable.", "Музыкальный сервис сейчас недоступен."}, +{"The music service is currently unavailable. Please try again later.", "Музыкальный сервис сейчас недоступен. Попробуйте позже."}, +{"This track doesn't support seeking.", "Этот трек не поддерживает перемотку."}, +{"Unable to get current playback position.", "Не удалось получить текущую позицию воспроизведения."}, +{"Unable to get current volume.", "Не удалось получить текущую громкость."}, +{"Unknown language. Choose 'en' or 'ru'.", "Неизвестный язык. Выберите «en» или «ru»."}, +{"Unknown command. Type {}help for available commands.", "Неизвестная команда. Введите {}help, чтобы увидеть список команд."}, +{"Usage: fav play <number> (see fav list)", "Использование: fav play <номер> (см. fav list)"}, +{"Usage: fav remove <number> (see fav list)", "Использование: fav remove <номер> (см. fav list)"}, +{"Usage: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)", "Использование: move <откуда> <куда>\nПример: move 5 1 (переместит трек 5 на позицию 1)"}, +{"Usage: remove <position>\nUse {}queue to see track positions.", "Использование: remove <позиция>\nИспользуйте {}queue, чтобы увидеть позиции треков."}, +{"Usage: seek <+/-seconds>\nExamples:\n seek +30 (skip forward 30s)\n seek -10 (skip back 10s)\n seek 60 (jump to 1 minute mark)", "Использование: seek <+/-секунды>\nПримеры:\n seek +30 (вперёд на 30с)\n seek -10 (назад на 10с)\n seek 60 (к отметке 1 минута)"}, +{"Usage: select <number>\nSelect a track from your last search results.", "Использование: select <номер>\nВыберите трек из последних результатов поиска."}, +{"Usage: {} <query>", "Использование: {} <запрос>"}, +{"Usage: {} <url or search query>\nExample: {} never gonna give you up", "Использование: {} <ссылка или поисковый запрос>\nПример: {} never gonna give you up"}, +{"Usage: {}announce <message>", "Использование: {}announce <сообщение>"}, +{"Usage: {}fav add | list | play <n> | remove <n>", "Использование: {}fav add | list | play <n> | remove <n>"}, +{"Usage: {}page <n>, or {}next / {}prev.", "Использование: {}page <n> или {}next / {}prev."}, +{"Use `!unsubscribeall` to remove all subscribers.", "Используйте `!unsubscribeall`, чтобы удалить всех подписчиков."}, +{"Use `!unsubscribeid <uid>` to remove a specific subscriber.\n", "Используйте `!unsubscribeid <uid>`, чтобы удалить конкретного подписчика.\n"}, +{"Volume", "Громкость"}, +{"Volume must be between 0 and 100.", "Громкость должна быть от 0 до 100."}, +{"Volume: {}%", "Громкость: {}%"}, +{"Volume: {}% {}", "Громкость: {}% {}"}, +{"You don't have permission to use this command.", "У вас нет прав на использование этой команды."}, +{"You have no favorites yet. Save the current track with {}fav add", "У вас пока нет избранного. Сохраните текущий трек командой {}fav add"}, +{"⏸ Paused | ", "⏸ Пауза | "}, +{"✅ Configuration reloaded from disk.", "✅ Конфигурация перезагружена с диска."}, +{"✅ Configuration reloaded. For a full core reload, use the TS plugin menu.", "✅ Конфигурация перезагружена. Для полной перезагрузки ядра используйте меню плагина TS."}, +{"✅ Language set to {}.", "✅ Язык установлен: {}."}, +{"📁 Available playlists:\n", "📁 Доступные плейлисты:\n"}, +{"📋 **Subscribed Users** (", "📋 **Подписчики** ("}, +{"📜 **Queue** (Page ", "📜 **Очередь** (страница "}, +{"📻 Autoplay is OFF.", "📻 Автовоспроизведение выключено."}, +{"📻 Autoplay is ON — I'll keep the music going with related tracks.", "📻 Автовоспроизведение включено — буду добавлять похожие треки."}, +{"🔀 Queue shuffled!", "🔀 Очередь перемешана!"}, +{"🔀 Shuffle | ", "🔀 Перемешивание | "}, +{"🔁 Repeat is now ON.", "🔁 Повтор включён."}, +{"🔁 Repeat | ", "🔁 Повтор | "}, +{"🟢 Online: ", "🟢 В сети: "}, + +// --- Command descriptions & usage hints (shown in !help) --- +{"Clears all tracks from the queue.", "Очищает все треки из очереди."}, +{"Get RPC server connection information", "Показать данные подключения к RPC-серверу"}, +{"Lists all subscribed users (online/offline).", "Показывает всех подписчиков (в сети/не в сети)."}, +{"Lists or loads a playlist.", "Показывает или загружает плейлист."}, +{"Manage your favorite tracks", "Управление избранными треками"}, +{"Moves a track to a different position in the queue.", "Перемещает трек на другую позицию в очереди."}, +{"Pauses the current playback.", "Ставит воспроизведение на паузу."}, +{"Plays a track from URL, or searches YouTube and Yandex Music and lets you select.", "Воспроизводит трек по ссылке или ищет на YouTube и Yandex Music с выбором."}, +{"Plays from Yandex Music only (URL or search).", "Воспроизводит только из Yandex Music (ссылка или поиск)."}, +{"Plays from YouTube only (URL or search).", "Воспроизводит только из YouTube (ссылка или поиск)."}, +{"Reloads the bot configuration from file.", "Перезагружает конфигурацию бота из файла."}, +{"Removes a track from the queue by position.", "Удаляет трек из очереди по позиции."}, +{"Removes all subscriptions (admin only).", "Удаляет все подписки (только админ)."}, +{"Resumes the paused playback.", "Возобновляет приостановленное воспроизведение."}, +{"Search Yandex Music only for tracks.", "Искать треки только в Yandex Music."}, +{"Search YouTube and Yandex Music for tracks.", "Искать треки на YouTube и Yandex Music."}, +{"Search YouTube only for tracks.", "Искать треки только на YouTube."}, +{"Seeks to a position in the current track. Use +seconds to skip forward, -seconds to skip backward.", "Перемотка текущего трека. +секунды — вперёд, -секунды — назад."}, +{"Selects a track from your search results.", "Выбирает трек из результатов поиска."}, +{"Send an announcement to all subscribers (admin).", "Отправляет объявление всем подписчикам (админ)."}, +{"Sets or shows the playback volume.", "Устанавливает или показывает громкость воспроизведения."}, +{"Sets your reply language (English or Russian).", "Устанавливает язык ответов (английский или русский)."}, +{"Show playback statistics", "Показать статистику воспроизведения"}, +{"Show recently played tracks", "Показать недавно проигранные треки"}, +{"Shows information about reloading the bot.", "Показывает информацию о перезапуске бота."}, +{"Shows the current queue and playback status.", "Показывает текущую очередь и статус воспроизведения."}, +{"Shows the currently playing track.", "Показывает текущий трек."}, +{"Skips to the next track(s).", "Пропускает к следующему треку(ам)."}, +{"Stops playback and clears the queue.", "Останавливает воспроизведение и очищает очередь."}, +{"Subscribes to the music bot to receive audio.", "Подписаться на музыкального бота, чтобы получать звук."}, +{"Toggles radio mode: auto-queues related tracks when the queue runs out.", "Переключает режим радио: добавляет похожие треки, когда очередь заканчивается."}, +{"Toggles repeat mode for the current track.", "Переключает режим повтора текущего трека."}, +{"Toggles shuffle mode for the queue.", "Переключает режим перемешивания очереди."}, +{"Unsubscribes a user by their UID (admin only).", "Отписывает пользователя по его UID (только админ)."}, +{"Unsubscribes from the music bot.", "Отписаться от музыкального бота."}, +{"Shows this help message with all available commands.", "Показывает эту справку со всеми доступными командами."}, +{"Shows another page of the last long reply (also !next / !prev).", "Показывает другую страницу последнего длинного ответа (также !next / !prev)."}, +{"<+/-seconds>", "<+/-секунды>"}, +{"<from> <to>", "<откуда> <куда>"}, +{"<message>", "<сообщение>"}, +{"<number>", "<номер>"}, +{"<position>", "<позиция>"}, +{"<query>", "<запрос>"}, +{"<url or search query>", "<ссылка или поисковый запрос>"}, +{"[count]", "[кол-во]"}, +{"[playlist name]", "[название плейлиста]"}, +{"[command]", "[команда]"}, +{"[n|next|prev]", "[n|next|prev]"}, diff --git a/src/playback/PlaybackEngine.cpp b/src/playback/PlaybackEngine.cpp index cc03aa6..fba7f5f 100644 --- a/src/playback/PlaybackEngine.cpp +++ b/src/playback/PlaybackEngine.cpp @@ -11,6 +11,18 @@ namespace Echoion::Core { constexpr size_t MAX_BUFFER_SHORTS = PlaybackEngine::SHORTS_PER_CHUNK * 50; + + // Crossfade readiness gate cap (1.5s of stereo PCM): never demand + // more buffered incoming audio than the decoder queue can physically + // hold (~2s for Opus/YouTube), or long fades could never start. + constexpr size_t FADE_GATE_CAP_SHORTS = + PlaybackEngine::SAMPLE_RATE * PlaybackEngine::CHANNELS * 3 / 2; + + // Micro-ramp (~4ms) applied to the incoming track when it resumes + // after a mid-fade buffer underrun, so it doesn't cut back in with + // an audible step while the outgoing tail is still playing. + constexpr size_t FADE_RAMP_SHORTS = + PlaybackEngine::SAMPLE_RATE * PlaybackEngine::CHANNELS * 4 / 1000; } // namespace PlaybackEngine::PlaybackEngine(IPlaybackHost& host) : host_(host) {} @@ -209,7 +221,23 @@ namespace Echoion::Core if (duration.count() > 0 && duration - position <= std::chrono::milliseconds(fade)) { - beginCrossfade(); + // A proxied network stream may still be filling its + // decode queue. Only start the fade once the incoming + // side has buffered enough audio to survive it — + // otherwise the fade envelope races ahead of the + // starving ring and chops the incoming audio ~50 + // times a second (an audible buzz over the outgoing + // tail). If the gate never passes, EOF falls back to + // the plain gapless handoff. + const auto fadeShorts = static_cast<std::size_t>( + fade * SAMPLE_RATE * CHANNELS / 1000); + const std::size_t ready = + std::min(fadeShorts, FADE_GATE_CAP_SHORTS); + if (next_.decoder->isFinished() || + next_.decoder->queueSaturated() || + next_.decoder->queuedSamples() >= ready) { + beginCrossfade(); + } } } } @@ -219,7 +247,7 @@ namespace Echoion::Core // 4) Emit one chunk per 20ms tick. const bool fading = - !fadeTail_.empty() && fadePos_ < fadeTail_.size(); + !fadeTail_.empty() && fadeEnvPos_ < fadeTail_.size(); if (ring_.size() >= SHORTS_PER_CHUNK || fading) { // Full chunk available, OR a crossfade is in progress (the // outgoing tail covers a not-yet-full incoming ring so the @@ -241,8 +269,14 @@ namespace Echoion::Core if (silenceSince_.time_since_epoch().count() == 0) { silenceSince_ = std::chrono::steady_clock::now(); } + // A download-to-file retry legitimately takes far longer than + // the normal resolve grace; don't skip a track whose download + // is still in progress. + const int64_t graceMs = current_.triedDownload + ? DOWNLOAD_GRACE_MS + : resolveGraceMs_.load(); if (std::chrono::steady_clock::now() - silenceSince_ > - std::chrono::milliseconds(resolveGraceMs_.load())) { + std::chrono::milliseconds(graceMs)) { Void::Log::warn( "PlaybackEngine", "{}", "Track resolve exceeded grace period, skipping"); @@ -321,6 +355,9 @@ namespace Echoion::Core auto entry = *slot.entry; slot.state = DecoderSlot::State::Resolving; slot.resolveStartedAt = std::chrono::steady_clock::now(); + // Restart the silence-grace clock: time burnt on the failed direct + // open must not count against the download's (longer) grace window. + silenceSince_ = {}; slot.resolveFuture = std::async(std::launch::async, [this, entry]() { // preferDownload=true evicts the poisoned cache entry and // downloads through the proxy (yt-dlp handles SOCKS5). @@ -434,6 +471,9 @@ namespace Echoion::Core } ring_.clear(); clearFade(); + // seek() is asynchronous: it publishes a request that the decode + // thread performs. Failure here only means "no source open"; + // av_seek_frame errors are logged by the decoder itself. auto result = current_.decoder->seek(cmd.position); if (result) { clock_.seekTo(cmd.position); @@ -617,7 +657,9 @@ namespace Echoion::Core crossfadeMs_.load() * SAMPLE_RATE * CHANNELS / 1000); fadeTail_.clear(); - fadePos_ = 0; + fadeTailPos_ = 0; + fadeEnvPos_ = 0; + fadeIncomingStarved_ = false; fadeTail_.reserve(ring_.size() + maxTailSamples); for (std::size_t i = 0; i < ring_.size(); ++i) { fadeTail_.push_back(ring_[i]); @@ -811,37 +853,84 @@ namespace Echoion::Core if (fromRing) { const size_t available = std::min(ring_.size(), SHORTS_PER_CHUNK); const bool fading = - !fadeTail_.empty() && fadePos_ < fadeTail_.size(); + !fadeTail_.empty() && fadeEnvPos_ < fadeTail_.size(); - // The number of output samples we actually fill: during a fade - // we emit a FULL chunk even when the incoming ring is still - // short (the outgoing tail covers the gap), so a track handoff - // never leaves the TS3 device starved. Otherwise it's just what - // the ring holds. - const size_t filled = fading ? SHORTS_PER_CHUNK : available; + // The number of output samples we actually fill and how much of + // the ring we consume. During a fade we emit a FULL chunk even + // when the incoming ring is short (the outgoing tail covers the + // gap), so a track handoff never leaves the TS3 device starved. + // Otherwise it's just what the ring holds. + size_t filled = available; + size_t consumed = available; if (fading) { - // Equal-power blend: incoming (ring, or 0 if not ready yet) - // rises while the outgoing tail falls, across the whole - // chunk. + // Equal-power blend: the incoming (ring) rises while the + // outgoing tail falls. The tail plays continuously; the + // envelope only advances as incoming audio is delivered, so + // an underrun stretches the fade instead of chopping the + // incoming signal against a racing envelope. + filled = SHORTS_PER_CHUNK; const auto fadeLen = static_cast<float>(fadeTail_.size()); + const bool starved = available < SHORTS_PER_CHUNK; + + // Starvation boundaries get micro-ramps on the incoming + // signal: the first starved tick ramps it out over the + // samples that remain, and the first tick after recovery + // ramps it back in — the incoming never appears or vanishes + // with an audible step under the still-playing tail. While + // starvation persists nothing is consumed (the ring is left + // to refill to a full chunk). + const size_t rampOut = + (starved && !fadeIncomingStarved_) ? available : 0; + const size_t rampIn = + (!starved && fadeIncomingStarved_) ? FADE_RAMP_SHORTS : 0; + consumed = starved ? rampOut : SHORTS_PER_CHUNK; + for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) { - const float incoming = - i < available ? static_cast<float>(ring_[i]) : 0.0f; + const bool hasIncoming = i < consumed; + float incoming = 0.0f; + if (hasIncoming) { + incoming = static_cast<float>(ring_[i]); + if (rampOut > 0) { + incoming *= 1.0f - + static_cast<float>(i) / + static_cast<float>(rampOut); + } else if (i < rampIn) { + incoming *= static_cast<float>(i) / + static_cast<float>(rampIn); + } + } + float mixed = incoming; - if (fadePos_ < fadeTail_.size()) { + if (fadeEnvPos_ < fadeTail_.size()) { const float theta = - (static_cast<float>(fadePos_) / fadeLen) * + (static_cast<float>(fadeEnvPos_) / fadeLen) * 1.57079632679f; // pi/2 + const float tail = + fadeTailPos_ < fadeTail_.size() + ? static_cast<float>(fadeTail_[fadeTailPos_]) + : 0.0f; mixed = incoming * std::sin(theta) + - static_cast<float>(fadeTail_[fadePos_]) * - std::cos(theta); - ++fadePos_; + tail * std::cos(theta); + if (fadeTailPos_ < fadeTail_.size()) { + ++fadeTailPos_; + } + // Envelope lockstep: advance with delivered incoming + // samples. Once the tail itself is exhausted there + // is nothing left to hold for — let the envelope + // complete so the incoming finishes its rise (or, + // with both sources dry, the fade ends and normal + // starvation handling resumes). + if (hasIncoming || + fadeTailPos_ >= fadeTail_.size()) { + ++fadeEnvPos_; + } } outChunk_[i] = static_cast<short>(std::clamp( static_cast<int>(mixed), -32768, 32767)); } - if (fadePos_ >= fadeTail_.size()) { + fadeIncomingStarved_ = starved; + if (fadeEnvPos_ >= fadeTail_.size()) { clearFade(); } } else { @@ -868,7 +957,7 @@ namespace Echoion::Core std::fill(outChunk_.begin() + static_cast<std::ptrdiff_t>(filled), outChunk_.end(), 0); - ring_.popFront(available); + ring_.popFront(consumed); } else { std::fill(outChunk_.begin(), outChunk_.end(), 0); } diff --git a/src/sources/YtDlpSource.cpp b/src/sources/YtDlpSource.cpp index ea897cf..aa7007c 100644 --- a/src/sources/YtDlpSource.cpp +++ b/src/sources/YtDlpSource.cpp @@ -78,7 +78,22 @@ namespace Echoion::Core t.id = urlOrId; t.title = urlOrId; t.source = Api::TrackSource::URL; - t.originalUrl = urlOrId; + // If a YouTube video id is still extractable here (e.g. a youtu.be + // short link that skipped the video-info path), expand it to the + // canonical watch URL so originalUrl is never a shortened form — + // mirrors InnertubeSource so "open original link" opens the long URL. + if (client_) { + if (auto videoId = client_->extractVideoId(urlOrId)) { + t.id = *videoId; + t.source = Api::TrackSource::YouTube; + t.originalUrl = + std::format("https://www.youtube.com/watch?v={}", *videoId); + } else { + t.originalUrl = urlOrId; + } + } else { + t.originalUrl = urlOrId; + } t.addedAt = std::chrono::system_clock::now(); return t; } diff --git a/src/util/Paginate.cpp b/src/util/Paginate.cpp new file mode 100644 index 0000000..a4c02fb --- /dev/null +++ b/src/util/Paginate.cpp @@ -0,0 +1,63 @@ +#include "echoion/core/util/Paginate.hpp" + +namespace Echoion::Core::Util +{ + + std::vector<std::string> paginate(std::string_view text, std::size_t limit) + { + std::vector<std::string> pages; + if (limit == 0) { + pages.emplace_back(text); + return pages; + } + if (text.size() <= limit) { + pages.emplace_back(text); + return pages; + } + + std::string current; + auto flush = [&] { + if (!current.empty()) { + pages.push_back(current); + current.clear(); + } + }; + + std::size_t pos = 0; + while (pos < text.size()) { + const std::size_t nl = text.find('\n', pos); + std::string line = + (nl == std::string_view::npos) + ? std::string(text.substr(pos)) + : std::string(text.substr(pos, nl - pos + 1)); + pos = (nl == std::string_view::npos) ? text.size() : nl + 1; + + // Start a new page when appending this line would overflow. + if (!current.empty() && current.size() + line.size() > limit) { + flush(); + } + + // Hard-split a single line that is itself longer than the limit, + // cutting on a UTF-8 continuation boundary so multi-byte code + // points are never severed. + while (line.size() > limit) { + std::size_t cut = limit; + while (cut > 0 && + (static_cast<unsigned char>(line[cut]) & 0xC0) == 0x80) { + --cut; + } + if (cut == 0) { + cut = limit; // pathological line; avoid an infinite loop + } + flush(); + pages.push_back(line.substr(0, cut)); + line.erase(0, cut); + } + + current += line; + } + flush(); + return pages; + } + +} // namespace Echoion::Core::Util