#pragma once #include "echoion/core/MusicManager.hpp" #include "echoion/core/i18n/Localization.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace Echoion::Core { class MusicManager; // Declaration order also decides the order of the collapsible sections // in !help (the help map is keyed by this enum). Play and Search lead so // their related commands are grouped together up top. enum class CommandCategory { Play, Search, Music, Queue, Playback, Utility, Admin }; inline std::string toString(CommandCategory category) { switch (category) { case CommandCategory::Play: return "Play"; case CommandCategory::Search: return "Search"; case CommandCategory::Music: return "Music"; case CommandCategory::Queue: return "Queue"; case CommandCategory::Playback: return "Playback"; case CommandCategory::Utility: return "Utility"; case CommandCategory::Admin: return "Admin"; } return "Utility"; } // Middot separator (U+00B7) used between a track link and its duration. inline constexpr std::string_view kDot = "\xc2\xb7"; // Escape Markdown punctuation in dynamic text (track titles, etc.) so it // cannot break an enclosing [text](url) link or apply stray formatting. inline std::string escapeMarkdown(std::string_view text) { std::string out; out.reserve(text.size() + 8); for (char c : text) { switch (c) { case '\\': case '`': case '*': case '_': case '[': case ']': case '(': case ')': case '~': case '|': out += '\\'; [[fallthrough]]; default: out += c; } } return out; } // Render `text` as a Markdown link to `url` (escaping the text). When `url` // is empty/absent the escaped text is returned without a link. inline std::string markdownLink(std::string_view text, const std::optional& url) { if (url.has_value() && !url->empty()) { return std::format("[{}]({})", escapeMarkdown(text), *url); } return escapeMarkdown(text); } // The best public link for a track: the provider-generated short link when // available, otherwise the original source URL (e.g. the YouTube or // Yandex Music page). Used so every list — search, queue, history, // favorites, stats — links to the real track, never the CDN/stream URL. inline std::optional trackLinkUrl(const Api::TrackInfo& track) { if (track.shortenedUrl.has_value() && !track.shortenedUrl->empty()) { return track.shortenedUrl; } if (!track.originalUrl.empty()) { return track.originalUrl; } return std::nullopt; } // Render "Title by Artist" (or just Title) as a Markdown link to the // track's best public URL. inline std::string trackLink(const Api::TrackInfo& track) { std::string display = track.title; if (!track.artist.empty()) { display = std::format("{} by {}", track.title, track.artist); } return markdownLink(display, trackLinkUrl(track)); } /** * @brief Context passed to every command execution. * Wraps all dependencies required to perform an action. */ struct CommandContext { uint64_t clientId = 0; std::string prefix; std::string args; // Arguments excluding the command name std::string_view invokerName; // Dependencies std::weak_ptr musicManager; // Service registry for resolving shared services by interface // (non-owning; outlives the command). Populated by CommandManager. const Void::Service::ServiceRegistry* services = nullptr; // Language the invoking user should be answered in. Resolved by // CommandManager (per-user kv override, else the config default). I18n::Language language = I18n::Language::English; // Reply callback - set by CommandManager std::function replyCallback = {}; // Helper to reply to the user void reply(std::string_view message) const { if (replyCallback) { replyCallback(message); } } // Translate an English source string into the invoker's language. // Missing translations fall back to the English original. [[nodiscard]] std::string_view tr(std::string_view english) const { return I18n::translate(english, language); } // Translate a std::format-style English template, then substitute // the arguments. The template is translated at runtime, so callers // use this instead of std::format for user-facing text. template [[nodiscard]] std::string trf(std::string_view englishFmt, Args&&... args) const { return std::vformat(I18n::translate(englishFmt, language), std::make_format_args(args...)); } // Resolve a shared service by interface, or nullptr if the // registry is absent / the service was not provided. template [[nodiscard]] std::shared_ptr service() const { return services ? services->get() : nullptr; } }; // Format a duration as m:ss (or h:mm:ss past an hour). Shared by the // track-listing commands (!np, !queue) so their timestamps line up. inline std::string formatDuration(std::chrono::milliseconds duration) { auto totalSeconds = duration.count() / 1000; auto hours = totalSeconds / 3600; auto mins = (totalSeconds % 3600) / 60; auto secs = totalSeconds % 60; if (hours > 0) { return std::format("{}:{:02}:{:02}", hours, mins, secs); } return std::format("{}:{:02}", mins, secs); } // A compact one-line playback status readout (volume / shuffle / repeat / // radio) shared by !help, !np and !list so all three show the same // at-a-glance state. Rendered as a Markdown blockquote line. Returns an // empty string when playback state is unavailable. Radio comes from // autoplayEnabled() since PlaybackState carries no autoplay field. inline std::string playbackStatusLine(const CommandContext& ctx) { auto mm = ctx.musicManager.lock(); if (!mm) { return {}; } auto st = mm->getPlaybackState(); if (!st) { return {}; } auto onOff = [&](bool b) -> std::string_view { return b ? ctx.tr("On") : ctx.tr("Off"); }; return ctx.trf( "> \xf0\x9f\x8e\x9a {} {}% \xc2\xb7 " "\xf0\x9f\x94\x80 {} {} \xc2\xb7 " "\xf0\x9f\x94\x81 {} {} \xc2\xb7 " "\xf0\x9f\x93\xbb {} {}", ctx.tr("Volume"), static_cast(st->volume * 100), ctx.tr("Shuffle"), onOff(st->shuffle), ctx.tr("Repeat"), onOff(st->repeat), ctx.tr("Radio"), onOff(mm->autoplayEnabled())); } /** * @brief Interface that all commands must implement. */ class Command { public: virtual ~Command() = default; /** * @brief The logic of the command. */ virtual void execute(const CommandContext& ctx) = 0; /** * @brief Returns the description used for help generation. */ virtual std::string_view getDescription() const = 0; /** * @brief Returns usage syntax (e.g., ""). */ virtual std::string_view getUsage() const { return ""; } /** * @brief Returns the command category for grouping in help. */ virtual CommandCategory getCategory() const { return CommandCategory::Utility; } /** * @brief Returns aliases for this command. */ virtual std::vector getAliases() const { return {}; } /** * @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; } // namespace Echoion::Core