1 parent
d146f11f02
commit
5c036d91fb
72 files changed
+5875
-1243
No files matched your search
+1
-1
@@ -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
|
||||
|
||||
@@ -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<std::vector<int16_t>> 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<int64_t> currentPositionMs_{0};
|
||||
// Pending seek target in ms, -1 = none. Written by seek() under
|
||||
// mutex_ (coordinated with eof_), consumed by the decode thread.
|
||||
std::atomic<int64_t> seekRequestMs_{-1};
|
||||
std::string currentUrl_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
|
||||
@@ -6,16 +6,18 @@
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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:<uid>") if any, else the
|
||||
// configured bot default, else English.
|
||||
[[nodiscard]] I18n::Language resolveLanguage(
|
||||
uint64_t clientId,
|
||||
const std::weak_ptr<MusicManager>& 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<std::string> pages;
|
||||
std::size_t current = 0;
|
||||
std::chrono::steady_clock::time_point ts{};
|
||||
};
|
||||
mutable std::mutex pagedMutex_;
|
||||
std::unordered_map<uint64_t, PagedReply> 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<std::string>
|
||||
renderCachedPage(uint64_t clientId,
|
||||
std::optional<long> absolute, int delta,
|
||||
I18n::Language lang);
|
||||
|
||||
std::string prefix_ = "!";
|
||||
|
||||
// Non-owning service registry threaded into each CommandContext
|
||||
|
||||
@@ -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 <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
@@ -16,9 +20,13 @@
|
||||
#include <Types.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <atomic>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
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<std::pair<std::string, std::string>>
|
||||
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> networkClient_;
|
||||
std::shared_ptr<LyricsService> lyricsService_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
@@ -176,21 +199,67 @@ namespace Echoion::Core
|
||||
std::filesystem::path configPath_;
|
||||
std::chrono::system_clock::time_point startTime_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
// Guards triggerAutoConnect() against duplicate connection
|
||||
// attempts (reset on a failed initiation so a retry can run).
|
||||
std::atomic<bool> autoConnectInitiated_{false};
|
||||
|
||||
// Event callbacks
|
||||
std::vector<Api::EventCallback> 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<uint64_t> adminClients_;
|
||||
std::vector<uint64_t> 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<uint64_t, RpcIdentity> rpcIdentities_;
|
||||
mutable std::mutex rpcIdentityMutex_;
|
||||
[[nodiscard]] std::optional<RpcIdentity>
|
||||
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<TokenIdentity>
|
||||
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<bool> webRestartPending_{false};
|
||||
|
||||
// Database for persistence
|
||||
std::shared_ptr<Api::Database> 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<std::string> warmedUids_;
|
||||
|
||||
// RPC server for Desktop/API clients
|
||||
std::shared_ptr<RpcServer> 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<Web::HttpServer> 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
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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<Line> 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<NetworkClient> 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<Line>
|
||||
parseLrc(const std::string& lrc);
|
||||
|
||||
std::shared_ptr<NetworkClient> net_;
|
||||
|
||||
struct Entry {
|
||||
Lyrics value;
|
||||
std::chrono::steady_clock::time_point at;
|
||||
};
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_map<std::string, Entry> cache_;
|
||||
static constexpr std::chrono::hours kCacheTtl{6};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -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<void> 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<VoteSkipStatus>
|
||||
voteSkip(const std::string& uid);
|
||||
[[nodiscard]] VoteSkipStatus
|
||||
voteSkipStatus(const std::string& uid) const;
|
||||
|
||||
[[nodiscard]] Api::Result<uint64_t>
|
||||
queueTrack(const Api::TrackInfo& track, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> 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<Api::SearchResult>
|
||||
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<bool> restoringSession_{false};
|
||||
void onPlaybackError(const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& 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<Void::Net::ProxyConfig>
|
||||
effectiveEngineProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// ---- state -----------------------------------------------------
|
||||
|
||||
@@ -342,6 +384,14 @@ namespace Echoion::Core
|
||||
QueueService queue_;
|
||||
std::unique_ptr<TrackCache> 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<std::string> voteSkipUids_;
|
||||
uint64_t voteSkipQueueId_ = 0;
|
||||
std::atomic<uint32_t> 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<bool> importRunning_{false};
|
||||
std::jthread importThread_;
|
||||
std::unique_ptr<PlaybackEngine> engine_;
|
||||
// HTTP CONNECT -> SOCKS5 tunnel for ffmpeg (see
|
||||
// effectiveEngineProxy); only running while the configured proxy
|
||||
// is SOCKS5.
|
||||
std::unique_ptr<Socks5HttpBridge> ffmpegProxyBridge_;
|
||||
std::unique_ptr<SubscriptionService> subscriptions_;
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
|
||||
@@ -73,10 +73,18 @@ namespace Echoion::Core::Dto
|
||||
};
|
||||
|
||||
struct ManageUsersRequest {
|
||||
std::string action; // "list" | "remove"
|
||||
std::string action; // "list" | "remove" | "clearAll"
|
||||
std::optional<std::string> 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<std::string> thumbnailUrl;
|
||||
std::optional<std::string> 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<std::string> 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<Api::TrackSource>(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:<uid>" 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/<name>, not inlined here.
|
||||
struct CustomEmojiDto {
|
||||
std::string name;
|
||||
std::string mime;
|
||||
std::string addedBy;
|
||||
};
|
||||
struct CustomEmojiList {
|
||||
std::vector<CustomEmojiDto> 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<std::string> onlineSubscriberNames;
|
||||
// TeamSpeak uids parallel to onlineSubscriberNames (same order), so
|
||||
// the web UI can fetch each listener's avatar at /avatar/<uid>.
|
||||
std::vector<std::string> 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<SubscriberDto> 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<Track> 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<LyricsLineDto> 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<RequesterDto> topRequesters;
|
||||
std::uint64_t youtubeCount = 0;
|
||||
std::uint64_t yandexCount = 0;
|
||||
std::uint64_t otherCount = 0;
|
||||
};
|
||||
|
||||
// ── Event-broadcast payloads ────────────────────────────────────────────
|
||||
|
||||
struct TrackBrief {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
@@ -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<std::string>
|
||||
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<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||
void processMessage(uint64_t clientId, const std::string& message);
|
||||
@@ -93,6 +103,8 @@ namespace Echoion::Core
|
||||
uint64_t,
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||
clients_;
|
||||
// clientId -> effective network address (see getClientAddress).
|
||||
std::unordered_map<uint64_t, std::string> clientAddresses_;
|
||||
mutable std::mutex clientsMutex_;
|
||||
std::atomic<uint64_t> nextClientId_{1};
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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:<port()> 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:<ephemeral>, start the accept thread and return
|
||||
// the bound port. Restarts (against the new upstream) when already
|
||||
// running.
|
||||
Api::Result<uint16_t> 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<Void::Net::ProxyConfig> upstream() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Connection {
|
||||
boost::asio::ip::tcp::socket client;
|
||||
boost::asio::ip::tcp::socket upstream;
|
||||
std::atomic<bool> 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<boost::asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread acceptThread_;
|
||||
uint16_t port_ = 0;
|
||||
std::atomic<bool> running_{false};
|
||||
|
||||
mutable std::mutex mutex_; // guards upstream_ and connections_
|
||||
std::optional<Void::Net::ProxyConfig> upstream_;
|
||||
std::vector<std::unique_ptr<Connection>> connections_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -81,10 +81,16 @@ namespace Echoion::Core
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
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<std::string> subscribedUid;
|
||||
bool mayAutoStart = false;
|
||||
};
|
||||
ClientConnectResult onClientConnected(uint64_t clientId);
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
private:
|
||||
|
||||
@@ -49,12 +49,25 @@ namespace Echoion::Core
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> 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<Api::SearchResult>
|
||||
searchSoundCloud(std::string_view query);
|
||||
|
||||
// Related tracks for radio autoplay: lists the YouTube "mix"
|
||||
// playlist (RD<videoId>) via yt-dlp --flat-playlist. Runs through
|
||||
// the proxy like every yt-dlp call, so it works under SOCKS5.
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
|
||||
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<std::vector<Api::TrackInfo>>
|
||||
randomMusicVideo(size_t limit = 10);
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
getVideoInfo(std::string_view videoId);
|
||||
@@ -156,6 +169,13 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlp(std::string_view query,
|
||||
const std::optional<std::string>& 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<Api::SearchResult>
|
||||
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<Api::TrackInfo>& tracks,
|
||||
|
||||
@@ -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<void> update();
|
||||
// Force update yt-dlp to latest version; returns the verified
|
||||
// version string of the freshly installed binary.
|
||||
Api::Result<std::string> update();
|
||||
|
||||
// Execute yt-dlp with given arguments and return output
|
||||
// (synchronous)
|
||||
@@ -62,10 +63,6 @@ namespace Echoion::Core
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
|
||||
// Execute multiple yt-dlp commands concurrently
|
||||
[[nodiscard]] std::vector<YtDlpResult> executeBatch(
|
||||
const std::vector<std::vector<std::string>>& 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<void> downloadYtDlp();
|
||||
|
||||
// Make executable executable (Unix only)
|
||||
Api::Result<void> makeExecutable();
|
||||
// Make the given file executable (Unix only)
|
||||
Api::Result<void> 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<Void::Concurrency::ThreadPool> 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";
|
||||
|
||||
@@ -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 <message>", ctx.prefix));
|
||||
ctx.reply(
|
||||
ctx.trf("Usage: {}announce <message>", 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.",
|
||||
|
||||
@@ -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<char>(std::tolower(c));
|
||||
return static_cast<char>(
|
||||
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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/i18n/Localization.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
@@ -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<void(std::string_view)> replyCallback;
|
||||
std::function<void(std::string_view)> 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 <typename... Args>
|
||||
[[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 <typename I>
|
||||
@@ -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<int>(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<Command>;
|
||||
|
||||
@@ -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"
|
||||
@@ -22,13 +22,13 @@ namespace Echoion::Core
|
||||
auto manager = ctx.musicManager.lock();
|
||||
auto db = ctx.service<Api::Database>();
|
||||
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 <n> | remove <n>",
|
||||
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 <number> (see fav list)");
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: fav play <number> (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 <number> (see fav list)");
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: fav remove <number> (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."));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace Echoion::Core
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "../i18n/Localization.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
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 <en|ru>.",
|
||||
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<Api::Database>();
|
||||
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<std::string_view> 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
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/LyricsService.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
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<LyricsService>();
|
||||
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<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"ly"};
|
||||
}
|
||||
};
|
||||
|
||||
} // 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("Usage: move <from> <to>\nExample: move 5 1 "
|
||||
"(moves track 5 to position 1)");
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: move <from> <to>\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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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: {} <url or search query>\nExample: {} never "
|
||||
"gonna give you up",
|
||||
label(), label()));
|
||||
ctx.reply(ctx.trf("Usage: {} <url or search "
|
||||
"query>\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 <number>:\n\n",
|
||||
ctx.prefix);
|
||||
std::string msg =
|
||||
std::format("Multiple results \xe2\x80\x94 use "
|
||||
"{}select <number>:\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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<int>(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 <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
msg << ctx.trf("\nUse {}queue <page> 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<int>(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
|
||||
@@ -22,15 +22,17 @@ namespace Echoion::Core
|
||||
if (auto core = ctx.service<Api::ICoreInterface>()) {
|
||||
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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,21 +17,27 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto core = ctx.service<Api::ICoreInterface>();
|
||||
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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
ctx.trf("Usage: remove <position>\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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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: {} <query>", label()));
|
||||
ctx.reply(ctx.trf("Usage: {} <query>", 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 <number> to play a result.",
|
||||
ctx.prefix);
|
||||
msg << ctx.trf("\nUse {}select <number> 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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 <number>\nSelect a track from "
|
||||
"your last search results.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Usage: select <number>\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 "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
ctx.reply(
|
||||
ctx.trf("No search results found. Use {}play "
|
||||
"<query> 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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> 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
|
||||
@@ -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 "<query>"; }
|
||||
std::vector<std::string_view> 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
|
||||
@@ -16,18 +16,18 @@ namespace Echoion::Core
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
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",
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
@@ -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 <uid>` to remove a specific "
|
||||
"subscriber.\n";
|
||||
msg << "Use `!unsubscribeall` to remove all subscribers.";
|
||||
msg << ctx.tr(
|
||||
"Use `!unsubscribeid <uid>` 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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<int>(state->volume * 100)));
|
||||
ctx.reply(
|
||||
ctx.trf("Current volume: {}%",
|
||||
static_cast<int>(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."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
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
|
||||
@@ -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<Api::QueueEntry>& entry) = 0;
|
||||
virtual void onPlaybackError(
|
||||
const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& 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<void> initialize(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
Api::Result<void>
|
||||
initialize(const std::optional<Void::Net::ProxyConfig>& 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<CmdPlayNow, CmdStart, CmdPause, CmdResume,
|
||||
CmdStop, CmdSkip, CmdSeek, CmdRestore>;
|
||||
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume, CmdStop,
|
||||
CmdSkip, CmdSeek, CmdRestore>;
|
||||
|
||||
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<short> 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.
|
||||
|
||||
@@ -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<QueueEntryState> queue;
|
||||
std::vector<SessionState> sessions;
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
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<std::string> paginate(std::string_view text, std::size_t limit);
|
||||
|
||||
} // namespace Echoion::Core::Util
|
||||
+157
-58
@@ -59,9 +59,13 @@ namespace Echoion::Core
|
||||
"Decoder not initialized");
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<int>(outputSampleRate_), &codecContext_->ch_layout,
|
||||
codecContext_->sample_fmt, codecContext_->sample_rate, 0, nullptr);
|
||||
if (codecContext_->sample_rate !=
|
||||
static_cast<int>(outputSampleRate_)) {
|
||||
if (codecContext_->sample_rate != static_cast<int>(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<int>(outputChannels_), maxSamples,
|
||||
static_cast<int>(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<std::mutex> lock(mutex_);
|
||||
std::size_t total = 0;
|
||||
for (const auto& chunk : int16Queue_) {
|
||||
total += chunk.size();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
bool AudioDecoder::queueSaturated() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return int16Queue_.size() >= MAX_INT16_QUEUE_SIZE;
|
||||
}
|
||||
|
||||
Api::Result<void> 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<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
int16Queue_.clear();
|
||||
}
|
||||
currentPositionMs_ = targetMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
Api::Result<Api::AudioStreamInfo> 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<std::mutex> 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<std::mutex> 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<int16_t> chunk = acquireChunkBuffer(chunkSamples);
|
||||
std::vector<int16_t> 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<const uint8_t**>(frame_->data);
|
||||
const uint8_t** inData = const_cast<const uint8_t**>(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()
|
||||
|
||||
+312
-31
@@ -1,11 +1,16 @@
|
||||
#include "echoion/core/CommandManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/commands/Command.hpp"
|
||||
#include "echoion/core/i18n/Localization.hpp"
|
||||
#include "echoion/core/util/Paginate.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Database.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <echoion/core/commands/Commands.hpp>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
|
||||
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 <title>" …
|
||||
// ":::" (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
|
||||
@@ -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>
|
||||
|
||||
@@ -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();
|
||||
|
||||
+709
-180
File diff suppressed because it is too large.
Load diff
+37
-10
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
+630
-56
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
+404
-9
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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
|
||||
+565
-199
File diff suppressed because it is too large.
Load diff
+163
-89
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
+135
-11
@@ -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)
|
||||
{
|
||||
|
||||
+147
-115
@@ -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
|
||||
@@ -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
|
||||
@@ -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]"},
|
||||
+112
-23
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user