Initial commit

This commit is contained in:
faumaray committed 2026-02-01 23:04:49 +03:00
commit a583c17916
56 files changed
+11025

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
#pragma once
#include <echoion/api.hpp>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <atomic>
#include <span>
#include <optional>
// Forward declarations for FFmpeg
extern "C" {
struct AVFormatContext;
struct AVCodecContext;
struct AVFrame;
struct AVPacket;
struct SwrContext;
struct AVBufferRef;
}
namespace Echoion::Core {
class AudioDecoder {
public:
AudioDecoder();
~AudioDecoder();
// Initialize decoder with optional hardware acceleration
Api::Result<void> initialize(const Api::HwAccelConfig& hwConfig = {});
void shutdown();
// Open audio source (URL or file path)
Api::Result<void> openSource(const std::string& url);
void closeSource();
// Decode audio - returns zero-copy pooled buffer
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
// Seek to position
Api::Result<void> seek(std::chrono::milliseconds position);
// Get audio info
[[nodiscard]] Api::Result<Api::AudioStreamInfo> getStreamInfo() const;
// Get current position
[[nodiscard]] std::chrono::milliseconds getPosition() const;
// Check if decoder has more data
[[nodiscard]] bool hasMoreData() const;
// Set output format
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
// Set proxy configuration for network requests
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
// Hardware acceleration
[[nodiscard]] bool isHardwareAccelerated() const { return hwAccelEnabled_; }
[[nodiscard]] Api::HwAccelType getHwAccelType() const { return hwAccelType_; }
// Enable/disable zero-copy mode
void setZeroCopyEnabled(bool enabled) { zeroCopyEnabled_ = enabled; }
[[nodiscard]] bool isZeroCopyEnabled() const { return zeroCopyEnabled_; }
// Get decoder statistics
struct Stats {
uint64_t framesDecoded = 0;
uint64_t framesDropped = 0;
uint64_t bytesDecoded = 0;
std::chrono::milliseconds totalDecodeTime{0};
double averageDecodeTimeMs = 0.0;
bool hwAccelerationActive = false;
};
[[nodiscard]] Stats getStats() const;
// Get next S16 chunk (like reference implementation)
bool getNextChunk(std::vector<int16_t>& outChunk, bool blocking = false);
// Check if decode is finished
[[nodiscard]] bool isFinished() const { return eof_.load(); }
private:
void decodeThread();
Api::Result<void> readPacket();
Api::Result<Api::DecodedAudio> convertFrame();
void cleanupFfmpeg();
// Hardware acceleration setup
Api::Result<void> initializeHardwareAccel(const Api::HwAccelConfig& config);
void cleanupHardwareAccel();
// Zero-copy frame conversion
Api::Result<Api::DecodedAudio> convertFrameZeroCopy();
Api::Result<Api::DecodedAudio> convertFramePooled();
// FFmpeg contexts
AVFormatContext* formatContext_ = nullptr;
AVCodecContext* codecContext_ = nullptr;
AVFrame* frame_ = nullptr;
AVPacket* packet_ = nullptr;
SwrContext* swrContext_ = nullptr;
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
// Hardware acceleration
AVBufferRef* hwDeviceContext_ = nullptr;
AVBufferRef* hwFramesContext_ = nullptr;
bool hwAccelEnabled_ = false;
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
bool zeroCopyEnabled_ = true;
// Stream info
int audioStreamIndex_ = -1;
Api::AudioStreamInfo streamInfo_;
// Output format
uint32_t outputSampleRate_ = 48000;
uint32_t outputChannels_ = 2;
// Threading
std::jthread decodeThread_;
mutable std::mutex mutex_;
std::condition_variable cv_;
std::queue<Api::DecodedAudio> decodedQueue_;
static constexpr size_t MAX_QUEUE_SIZE = 50;
// S16 audio queue (like reference) - avoids float conversion
std::deque<std::vector<int16_t>> int16Queue_;
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
// State
std::atomic<bool> initialized_{false};
std::atomic<bool> decoding_{false};
std::atomic<bool> eof_{false};
std::atomic<bool> shouldExit_{false}; // For FFmpeg interrupt callback
std::chrono::milliseconds currentPosition_{0};
std::string currentUrl_;
std::optional<Api::ProxyConfig> proxyConfig_;
// Statistics
mutable std::mutex statsMutex_;
Stats stats_;
};
} // namespace Echoion::Core
+124
View File
@@ -0,0 +1,124 @@
#pragma once
#include <echoion/api.hpp>
#include "commands/Command.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include <map>
#include <vector>
#include <memory>
#include <mutex>
#include <string>
#include <functional>
namespace Echoion::Core {
class MusicManager;
// Function to check if client has permission (set by Core)
using PermissionCheckFunc = std::function<bool(uint64_t clientId, CommandCategory category)>;
/**
* @brief Manages command registration and dispatch.
*
* Usage:
* CommandManager mgr;
* mgr.registerCommand<PlayCommand>("play");
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
*/
class CommandManager {
public:
CommandManager();
~CommandManager() = default;
// Disable copy
CommandManager(const CommandManager&) = delete;
CommandManager& operator=(const CommandManager&) = delete;
// Enable move
CommandManager(CommandManager&&) = default;
CommandManager& operator=(CommandManager&&) = default;
/**
* @brief Registers a command class.
* @tparam T The command class (must inherit Command).
* @param primaryName The primary name/trigger (e.g., "play").
*/
template <typename T>
void registerCommand(const std::string& primaryName) {
auto cmd = std::make_shared<T>();
std::lock_guard<std::mutex> lock(mutex_);
// Register primary name
commands_[primaryName] = cmd;
uniqueCommands_.push_back({primaryName, cmd});
// Register aliases automatically from the class itself
for (auto alias : cmd->getAliases()) {
commands_[std::string(alias)] = cmd;
}
}
/**
* @brief Dispatches a command message to the appropriate handler.
* @param clientId The client ID who invoked the command.
* @param message The full message (including prefix, e.g., "!play song").
* @param musicManager Weak pointer to the MusicManager.
* @param replyFunc Function to call to send a reply.
* @param invokerName Name of the invoking user.
* @return true if a command was found and executed, false otherwise.
*/
[[nodiscard]] bool dispatch(
uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName = ""
);
[[nodiscard]] bool hasCommand(std::string_view name) const;
[[nodiscard]] std::optional<CommandPtr> getCommand(std::string_view name) const;
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getAllCommands() const;
// Get commands visible to a specific client (for help)
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getVisibleCommands(uint64_t clientId) const;
// Check if client can execute a command
[[nodiscard]] bool canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const;
void setPrefix(std::string_view prefix);
[[nodiscard]] std::string_view getPrefix() const { return prefix_; }
// Set permission check function
void setPermissionCheckFunc(PermissionCheckFunc func);
// Set server config for permission checks
void setServerConfig(const Api::AppConfig& config);
private:
struct CommandEntry {
std::string primaryName;
CommandPtr instance;
};
void registerBuiltinCommands();
// Internal Help Command (defined in .cpp to access registry)
class HelpCommand;
void registerHelpCommand();
std::string prefix_ = "!";
// Map for fast lookup: "play" -> PlayCommand
std::map<std::string, CommandPtr, std::less<>> commands_;
// List for generating help: {"play", PlayCommand}
std::vector<CommandEntry> uniqueCommands_;
mutable std::mutex mutex_;
// Permission checking
PermissionCheckFunc permissionCheck_;
std::optional<Api::AppConfig> serverConfig_;
};
} // namespace Echoion::Core
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <echoion/api.hpp>
#include <filesystem>
#include <string>
namespace Echoion::Core {
// Configuration loader for JSON config files (internal to Core)
class ConfigLoader {
public:
// Load configuration from JSON file
[[nodiscard]] static Api::Result<Api::AppConfig> loadFromFile(const std::filesystem::path& path);
// Save configuration to JSON file
[[nodiscard]] static Api::Result<void> saveToFile(const std::filesystem::path& path, const Api::AppConfig& config);
// Get default configuration path
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
// Create default configuration
[[nodiscard]] static Api::AppConfig createDefaultConfig();
private:
// Parse quality string to enum
[[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str);
[[nodiscard]] static std::string qualityToString(Api::AudioQuality quality);
};
} // namespace Echoion::Core
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <echoion/api.hpp>
#include <echoion/api/Database.hpp>
#include "MusicManager.hpp"
#include "CommandManager.hpp"
#include "NetworkClient.hpp"
#include "RpcServer.hpp"
#include "ConfigLoader.hpp"
#include <thread>
#include <mutex>
#include <atomic>
namespace Echoion::Core {
// Main Core implementation of ICoreInterface
class Core : public Api::ICoreInterface {
public:
Core();
~Core() override;
// ICoreInterface implementation
Api::Result<void> initialize(const std::filesystem::path& configPath) override;
Api::Result<void> shutdown() override;
[[nodiscard]] bool isInitialized() const noexcept override;
// Playback control
Api::Result<void> play(const Api::TrackInfo& track) override;
Api::Result<void> pause() override;
Api::Result<void> resume() override;
Api::Result<void> stop() override;
Api::Result<void> skip(uint32_t count) override;
Api::Result<void> seek(std::chrono::milliseconds position) override;
Api::Result<void> setVolume(float volume) override;
// Queue management
Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId) override;
Api::Result<void> removeFromQueue(uint64_t queueId) override;
Api::Result<void> clearQueue() override;
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const override;
Api::Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) override;
// Track info
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const override;
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const override;
// Playlist
Api::Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) override;
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const override;
// Configuration
Api::Result<void> updateConfig(const Api::AppConfig& config) override;
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const override;
// Reload config from disk (stored path from initialize)
Api::Result<void> reloadConfig();
// Hot reload
Api::Result<Api::HotReloadState> prepareForHotReload() override;
Api::Result<void> restoreAfterHotReload(const Api::HotReloadState& state) override;
// Event handling
void registerEventCallback(const Api::EventCallback& callback) override;
void unregisterEventCallback(const Api::EventCallback& callback) override;
// Plugin event processing
Api::Result<void> onPluginEvent(const Api::PluginEvent& event) override;
// Status
[[nodiscard]] std::string getVersion() const override;
[[nodiscard]] std::chrono::system_clock::time_point getUptime() const override;
// Additional methods for plugin integration
void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override;
void setAudioDataCallback(const MusicManager::AudioDataCallback& callback);
void triggerAutoConnect() override;
private:
void onMusicEvent(const Api::PluginEvent& event);
void broadcastEvent(const Api::PluginEvent& event);
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
void updateWhisperList();
void setupRpcHandlers();
// Components
std::shared_ptr<NetworkClient> networkClient_;
std::shared_ptr<MusicManager> musicManager_;
std::unique_ptr<CommandManager> commandManager_;
Api::PluginInterfacePtr pluginInterface_;
// State
Api::AppConfig config_; // Config loaded internally
std::filesystem::path configPath_; // Path to config file for reload
std::chrono::system_clock::time_point startTime_;
std::atomic<bool> initialized_{false};
// Event callbacks
std::vector<Api::EventCallback> eventCallbacks_;
mutable std::mutex eventMutex_;
// Admin tracking
std::vector<uint64_t> adminClients_;
mutable std::mutex adminMutex_;
// Database for persistence
std::shared_ptr<Api::Database> database_;
// RPC server for Desktop/API clients
std::shared_ptr<RpcServer> rpcServer_;
};
} // namespace Echoion::Core
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include <echoion/api.hpp>
#include <fstream>
#include <mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <filesystem>
#include <vector>
#include <chrono>
#include <array>
#include <map>
namespace Echoion::Core {
// Log file info for rotation
struct LogFileInfo {
std::filesystem::path path;
std::ofstream stream;
uint64_t size = 0;
std::chrono::system_clock::time_point createdAt;
};
class Logger : public Api::ILogger {
public:
explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion");
~Logger() override;
void log(Api::LogLevel level, std::string_view message,
std::source_location location) override;
void setMinLevel(Api::LogLevel level) override;
[[nodiscard]] Api::LogLevel getMinLevel() const override;
void registerCallback(const LogCallback& callback) override;
void unregisterCallback(const LogCallback& callback) override;
void flush();
void setConsoleOutput(bool enabled);
void setFileOutput(bool enabled);
void setMaxFileSize(uint64_t bytes);
void setMaxFiles(uint32_t count);
private:
void logWorker();
void rotateIfNeeded(Api::LogLevel level);
void openLogFiles();
void cleanupOldLogs();
[[nodiscard]] std::string formatLogEntry(const Api::LogEntry& entry);
[[nodiscard]] std::string levelToString(Api::LogLevel level);
[[nodiscard]] std::filesystem::path generateLogFilePath(Api::LogLevel level);
[[nodiscard]] std::string formatTimestamp(const std::chrono::system_clock::time_point& tp);
void writeToFile(Api::LogLevel level, const std::string& formattedEntry);
std::filesystem::path logDir_;
std::string baseName_;
// Separate files for each level + combined file
std::map<Api::LogLevel, LogFileInfo> levelFiles_;
LogFileInfo combinedFile_;
std::mutex fileMutex_;
std::mutex queueMutex_;
std::queue<Api::LogEntry> logQueue_;
std::thread workerThread_;
std::condition_variable cv_;
std::atomic<bool> running_{true};
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
std::atomic<bool> consoleOutput_{true};
std::atomic<bool> fileOutput_{true};
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB per file
std::atomic<uint32_t> maxFiles_{5};
std::vector<LogCallback> callbacks_;
std::mutex callbackMutex_;
};
} // namespace Echoion::Core
+133
View File
@@ -0,0 +1,133 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include "YouTubeClient.hpp"
#include "AudioDecoder.hpp"
#include "SubscriptionManager.hpp"
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <random>
#include <atomic>
#include <future>
#include <set>
#include <unordered_map>
#include <filesystem>
namespace Echoion::Core {
class MusicManager {
public:
MusicManager();
~MusicManager();
Api::Result<void> initialize(const Api::BotConfig& config,
std::shared_ptr<NetworkClient> networkClient,
std::shared_ptr<Api::Database> database = nullptr);
void shutdown();
[[nodiscard]] Api::Result<std::string> play(const std::string& query, uint64_t clientId);
[[nodiscard]] Api::Result<void> pause();
[[nodiscard]] Api::Result<void> resume();
[[nodiscard]] Api::Result<void> stop();
[[nodiscard]] Api::Result<void> skip(uint32_t count = 1);
[[nodiscard]] Api::Result<void> seek(std::chrono::milliseconds position);
[[nodiscard]] Api::Result<void> setVolume(float volume);
[[nodiscard]] Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId);
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
[[nodiscard]] Api::Result<void> clearQueue();
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const;
[[nodiscard]] Api::Result<void> moveInQueue(uint32_t from, uint32_t to);
[[nodiscard]] Api::Result<bool> toggleShuffle();
[[nodiscard]] Api::Result<bool> toggleRepeat();
[[nodiscard]] Api::Result<uint32_t> loadPlaylist(const std::string& playlistId, uint64_t clientId);
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const;
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const;
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
// Search result selection (client-specific)
void storePendingSearch(uint64_t clientId, const std::vector<Api::TrackInfo>& results);
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>> getPendingSearch(uint64_t clientId);
[[nodiscard]] Api::Result<std::string> selectSearchResult(
uint64_t clientId, uint32_t index, const std::string& invokerName);
// Help command
[[nodiscard]] std::string getHelpText() const;
// Subscription management
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
[[nodiscard]] Api::Result<std::string> unsubscribe(uint64_t clientId);
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
[[nodiscard]] std::set<uint64_t> getSubscribedClients() const;
[[nodiscard]] bool hasSubscribers() const;
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
[[nodiscard]] Api::Result<void> restoreFromHotReload(const Api::HotReloadState& state);
using AudioDataCallback = std::function<void(const std::span<const float>)>;
void setAudioDataCallback(const AudioDataCallback& callback);
using SubscriptionChangeCallback = std::function<void()>;
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
// Called when a client leaves the server
void onClientDisconnected(uint64_t clientId);
private:
void playbackThread();
[[nodiscard]] Api::Result<Api::TrackInfo> resolveQuery(const std::string& query);
[[nodiscard]] Api::Result<std::string> getStreamUrl(const Api::TrackInfo& track);
void onTrackFinished();
[[nodiscard]] Api::TrackInfo getNextTrack();
void shuffleQueue();
// Download audio through proxy for playback
[[nodiscard]] Api::Result<std::string> downloadAudioForPlayback(const std::string& url);
void cleanupTempFile(const std::string& filepath);
// Temporary file tracking
std::set<std::string> tempFiles_;
mutable std::mutex tempFilesMutex_;
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YouTubeClient> youTubeClient_;
std::unique_ptr<AudioDecoder> audioDecoder_;
std::unique_ptr<SubscriptionManager> subscriptionManager_;
Api::BotConfig config_;
std::vector<Api::QueueEntry> queue_;
std::optional<Api::QueueEntry> currentTrack_;
bool isPlaying_ = false;
bool isPaused_ = false;
bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused
float volume_ = 0.5f;
bool shuffle_ = false;
bool repeat_ = false;
uint64_t nextQueueId_ = 1;
std::jthread playbackThread_;
mutable std::mutex mutex_;
std::condition_variable cv_;
// Pending search results per client (for select command)
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>> pendingSearches_;
mutable std::mutex pendingSearchMutex_;
AudioDataCallback audioCallback_;
SubscriptionChangeCallback subscriptionChangeCallback_;
std::mt19937 rng_{std::random_device{}()};
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = 192000; // Match reference
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
};
} // namespace Echoion::Core
+202
View File
@@ -0,0 +1,202 @@
#pragma once
#include "boost/asio/ssl/context.hpp"
#include <echoion/api.hpp>
#include <glaze/glaze.hpp>
#include <thread>
#include <mutex>
#include <future>
#include <queue>
#include <atomic>
#include <chrono>
// Boost.Beast includes needed for template function
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
namespace Echoion::Core {
// Forward declaration for URL parsing
struct UrlComponents;
class NetworkClient : public Api::INetworkClient {
public:
NetworkClient();
~NetworkClient() override;
// Initialize with optional proxy
Api::Result<void> initialize(const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
void shutdown();
// Synchronous requests
[[nodiscard]] Api::Result<Api::HttpResponse> get(std::string_view url,
const std::vector<Api::HttpHeader>& headers = {});
[[nodiscard]] Api::Result<Api::HttpResponse> post(std::string_view url,
std::string_view body, const std::vector<Api::HttpHeader>& headers = {});
[[nodiscard]] Api::Result<Api::HttpResponse> request(const Api::HttpRequest& req);
// Asynchronous requests
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> getAsync(std::string_view url,
const std::vector<Api::HttpHeader>& headers = {});
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> postAsync(std::string_view url,
std::string_view body, const std::vector<Api::HttpHeader>& headers = {});
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> requestAsync(const Api::HttpRequest& req);
// Concurrent batch requests
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>> requestBatch(
const std::vector<Api::HttpRequest>& requests);
// JSON helpers using glaze
template<typename T>
[[nodiscard]] Api::Result<T> getJson(std::string_view url,
const std::vector<Api::HttpHeader>& headers = {}) {
auto response = get(url, headers);
if (!response) {
return std::unexpected(response.error());
}
T result;
auto ec = glz::read_json(result, response->bodyAsString());
if (ec) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString()))));
}
return result;
}
template<typename T, typename Body>
[[nodiscard]] Api::Result<T> postJson(std::string_view url, const Body& body,
const std::vector<Api::HttpHeader>& headers = {}) {
std::string jsonBody = glz::write_json(body);
auto response = post(url, jsonBody, headers);
if (!response) {
return std::unexpected(response.error());
}
T result;
auto ec = glz::read_json(result, response->bodyAsString());
if (ec) {
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString()))));
}
return result;
}
// Proxy configuration
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
void clearProxy();
// Retry configuration
void setRetryConfig(const Api::RetryConfig& config);
[[nodiscard]] Api::RetryConfig getRetryConfig() const;
private:
// Request execution
[[nodiscard]] Api::Result<Api::HttpResponse> executeWithRetry(const Api::HttpRequest& req);
[[nodiscard]] Api::Result<Api::HttpResponse> executeRequest(const Api::HttpRequest& req);
// Proxy and direct execution methods
[[nodiscard]] Api::HttpResponse executeWithProxy(
boost::asio::io_context& ioc,
boost::asio::ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout);
[[nodiscard]] Api::HttpResponse executeWithHttpProxy(
boost::asio::io_context& ioc,
boost::asio::ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout);
[[nodiscard]] Api::HttpResponse executeWithSocks5Proxy(
boost::asio::io_context& ioc,
boost::asio::ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy,
std::chrono::seconds timeout);
[[nodiscard]] Api::HttpResponse executeDirect(
boost::asio::io_context& ioc,
boost::asio::ssl::context& ctx,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
std::chrono::seconds timeout);
// HTTP request methods
// Note: sendHttpsRequest is a template, implemented in header below
template<typename Stream>
[[nodiscard]] Api::HttpResponse sendHttpsRequest(
Stream& stream,
const UrlComponents& urlComp,
const Api::HttpRequest& req);
[[nodiscard]] Api::HttpResponse sendHttpRequest(
boost::asio::ip::tcp::socket& socket,
const UrlComponents& urlComp,
const Api::HttpRequest& req);
[[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy(
boost::asio::ip::tcp::socket& socket,
const UrlComponents& urlComp,
const Api::HttpRequest& req,
const Api::ProxyConfig& proxy);
// Request/Response building
[[nodiscard]] boost::beast::http::request<boost::beast::http::string_body> buildBeastRequest(
const UrlComponents& urlComp,
const Api::HttpRequest& req);
[[nodiscard]] Api::HttpResponse convertBeastResponse(
const boost::beast::http::response<boost::beast::http::dynamic_body>& beastResponse);
[[nodiscard]] std::vector<Api::HttpHeader> addDefaultHeaders(const std::vector<Api::HttpHeader>& headers);
std::optional<Api::ProxyConfig> proxy_;
Api::RetryConfig retryConfig_;
mutable std::mutex mutex_;
std::atomic<bool> initialized_{false};
std::atomic<uint32_t> requestId_{0};
// Thread pool for async operations
std::vector<std::jthread> threadPool_;
std::queue<std::packaged_task<Api::Result<Api::HttpResponse>()>> taskQueue_;
std::mutex taskMutex_;
std::condition_variable taskCv_;
std::atomic<bool> stopThreads_{false};
static constexpr size_t THREAD_POOL_SIZE = 4;
};
// Template implementation for sendHttpsRequest
template<typename Stream>
Api::HttpResponse NetworkClient::sendHttpsRequest(
Stream& stream,
const UrlComponents& urlComp,
const Api::HttpRequest& req) {
namespace http = boost::beast::http;
// Build request
http::request<http::string_body> request = buildBeastRequest(urlComp, req);
// Send
http::write(stream, request);
// Read response
boost::beast::flat_buffer buffer;
http::response<http::dynamic_body> response;
http::read(stream, buffer, response);
// Convert to Api::HttpResponse
return convertBeastResponse(response);
}
} // namespace Echoion::Core
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <echoion/api.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <thread>
#include <mutex>
#include <set>
#include <functional>
#include <unordered_map>
namespace Echoion::Core {
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
class RpcServer : public std::enable_shared_from_this<RpcServer> {
public:
using CommandHandler = std::function<Api::Result<std::string>(const std::string& params, uint64_t clientId)>;
RpcServer();
~RpcServer();
// Initialize and start the server
Api::Result<void> start(uint16_t port = 8765);
void stop();
[[nodiscard]] bool isRunning() const { return running_; }
[[nodiscard]] uint16_t getPort() const { return port_; }
// Register command handlers
void registerHandler(const std::string& method, CommandHandler handler);
void unregisterHandler(const std::string& method);
// Authentication
void setAuthToken(const std::string& token);
[[nodiscard]] bool authenticate(const std::string& token);
void addAuthenticatedClient(uint64_t clientId);
void removeAuthenticatedClient(uint64_t clientId);
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
// Broadcast events to all connected clients
void broadcastEvent(const std::string& event, const std::string& data);
// Send event to specific client
void sendEvent(uint64_t clientId, const std::string& event, const std::string& data);
private:
void acceptLoop();
void handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
void processMessage(uint64_t clientId, const std::string& message);
void sendResponse(uint64_t clientId, const Api::RpcResponse& response);
void sendNotification(uint64_t clientId, const Api::RpcNotification& notification);
asio::io_context ioContext_;
std::optional<asio::ip::tcp::acceptor> acceptor_;
std::thread serverThread_;
std::atomic<bool> running_{false};
uint16_t port_ = 8765;
// Connected clients
std::unordered_map<uint64_t, std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>> clients_;
std::mutex clientsMutex_;
std::atomic<uint64_t> nextClientId_{1};
// Client threads (for proper cleanup)
std::vector<std::thread> clientThreads_;
std::mutex clientThreadsMutex_;
// Authenticated clients
std::set<uint64_t> authenticatedClients_;
std::mutex authMutex_;
std::string authToken_;
// Command handlers
std::unordered_map<std::string, CommandHandler> handlers_;
std::mutex handlersMutex_;
};
} // namespace Echoion::Core
+129
View File
@@ -0,0 +1,129 @@
#pragma once
#include <string>
#include <string_view>
#include <vector>
#include <optional>
#include <memory>
#include <mutex>
#include <filesystem>
#include <quickjs.h>
namespace Echoion::Core {
/**
* Signature cipher for YouTube stream URLs
* Uses QuickJS (when available) to execute the JavaScript decipher functions from player JS
*
* Based on yt-dlp's signature extraction logic
*/
class SignatureCipher {
public:
SignatureCipher();
~SignatureCipher();
// Disable copy, enable move
SignatureCipher(const SignatureCipher&) = delete;
SignatureCipher& operator=(const SignatureCipher&) = delete;
SignatureCipher(SignatureCipher&&) noexcept;
SignatureCipher& operator=(SignatureCipher&&) noexcept;
/**
* Initialize the QuickJS solver with core libraries
* Must be called before using the cipher
*/
void initialize();
/**
* Set the player JS code and extract decipher functions
* @param playerJsCode The raw player JavaScript code from YouTube
* @return true if extraction succeeded
*/
bool setPlayerJs(std::string_view playerJsCode);
/**
* Check if the cipher is ready (has valid decipher function)
*/
[[nodiscard]] bool isReady() const;
/**
* Decipher a signature cipher string
* Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
* @param signatureCipher The signature cipher string
* @return The full deciphered URL or empty string on failure
*/
[[nodiscard]] std::string decipher(std::string_view signatureCipher);
/**
* Solve a challenge (signature or n-param) using the preprocessed player
* @param challenge The challenge string to solve
* @param type "sig" for signature, "n" for n-parameter
* @return The solved challenge or empty string on failure
*/
[[nodiscard]] std::string solveChallenge(const std::string& challenge, const std::string& type);
/**
* Decipher the n-parameter for throttling
* @param nParam The encoded n parameter
* @return The deciphered n parameter
*/
[[nodiscard]] std::string decipherNParam(std::string_view nParam);
/**
* Clear the cipher state
*/
void clear();
/**
* Check if cipher has been initialized
*/
[[nodiscard]] bool isInitialized() const;
private:
/**
* Initialize QuickJS runtime and context with solver libraries
*/
void initSolver();
/**
* Download solver libraries from remote URL
* @param url The URL to download from
* @return The downloaded JS code or empty string on failure
*/
[[nodiscard]] std::optional<std::string> downloadSolverLibrary(
std::string_view url);
/**
* Get cache directory for storing solver libraries
*/
[[nodiscard]] std::filesystem::path getCacheDir();
/**
* Execute JavaScript code in QuickJS and return result
*/
[[nodiscard]] std::optional<std::string> executeJS(
std::string_view code,
std::string_view filename = "<script>");
/**
* Cleanup QuickJS resources
*/
void cleanupQuickJS();
JSRuntime* runtime_ = nullptr;
JSContext* context_ = nullptr;
// Player JS code and extracted functions
std::string playerJsCode_;
std::string preprocessedPlayer_;
// State
bool initialized_ = false;
bool solverInitialized_ = false;
bool hasPlayerJs_ = false;
mutable std::mutex mutex_;
};
} // namespace Echoion::Core
@@ -0,0 +1,45 @@
#pragma once
#include <echoion/api.hpp>
#include <set>
#include <string>
#include <mutex>
#include <memory>
namespace Echoion::Core {
/**
* Manages user subscriptions to the bot's audio output
* Subscriptions are persisted to database and survive client reloads
*/
class SubscriptionManager {
public:
SubscriptionManager();
~SubscriptionManager();
// Initialize and load subscriptions from database
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
void shutdown();
// Subscription management
bool subscribe(uint64_t clientId);
bool unsubscribe(uint64_t clientId);
bool isSubscribed(uint64_t clientId) const;
// Get all subscribed clients
std::set<uint64_t> getSubscribedClients() const;
// Check if anyone is subscribed
bool hasSubscribers() const;
// Get subscriber count
size_t getSubscriberCount() const;
private:
std::set<uint64_t> subscribedClients_;
mutable std::mutex mutex_;
std::shared_ptr<Api::Database> database_;
bool initialized_ = false;
};
} // namespace Echoion::Core
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include "YtDlpManager.hpp"
#include <regex>
#include <mutex>
#include <optional>
#include <string>
#include <memory>
namespace Echoion::Core {
class YouTubeClient {
public:
explicit YouTubeClient(std::shared_ptr<NetworkClient> networkClient);
~YouTubeClient();
// Initialize the client - downloads yt-dlp if needed
Api::Result<void> initialize();
void shutdown();
// Check if yt-dlp is available
[[nodiscard]] bool isAvailable() const;
// Get yt-dlp version
[[nodiscard]] std::string getYtDlpVersion() const;
// Force update yt-dlp
Api::Result<void> updateYtDlp();
// Search for videos using yt-dlp
[[nodiscard]] Api::Result<Api::SearchResult> search(std::string_view query,
std::optional<std::string> pageToken = std::nullopt);
// Get video details including stream URLs using yt-dlp
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
// Get playlist videos using yt-dlp
[[nodiscard]] Api::Result<Api::PlaylistInfo> getPlaylist(std::string_view playlistId);
// Extract video ID from various YouTube URL formats (handles redirects for short URLs)
[[nodiscard]] std::optional<std::string> extractVideoId(std::string_view url);
[[nodiscard]] static std::optional<std::string> extractPlaylistId(std::string_view url);
// Check if URL is a YouTube URL
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
// Get stream URL for a video (used by MusicManager)
[[nodiscard]] Api::Result<std::string> getStreamUrl(std::string_view videoId);
// Get best audio stream URL using yt-dlp
[[nodiscard]] Api::Result<std::string> getAudioStreamUrl(std::string_view videoId);
// Configure cookie options for yt-dlp
void setCookiesPath(const std::string& path);
void setCookiesFromBrowser(const std::string& browser);
private:
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YtDlpManager> ytDlpManager_;
std::atomic<bool> initialized_{false};
mutable std::mutex mutex_;
};
} // namespace Echoion::Core
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include <string>
#include <filesystem>
#include <atomic>
#include <mutex>
namespace Echoion::Core {
class YtDlpManager {
public:
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
~YtDlpManager();
// Initialize - checks for yt-dlp and downloads if needed
Api::Result<void> initialize();
// Get the path to the yt-dlp executable
[[nodiscard]] std::filesystem::path getExecutablePath() const;
// Check if yt-dlp is available
[[nodiscard]] bool isAvailable() const;
// Get yt-dlp version
[[nodiscard]] std::string getVersion() const;
// Force update yt-dlp to latest version
Api::Result<void> update();
// Execute yt-dlp with given arguments and return output
[[nodiscard]] std::string execute(const std::vector<std::string>& args) const;
// Set cookie options for YouTube authentication
void setCookiesPath(const std::string& path);
void setCookiesFromBrowser(const std::string& browser);
// Get cookie arguments for yt-dlp command
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
private:
// Get the storage directory for yt-dlp
[[nodiscard]] std::filesystem::path getStorageDir() const;
// Get the executable name based on platform
[[nodiscard]] std::string getExecutableName() const;
// Download yt-dlp from official source
Api::Result<void> downloadYtDlp();
// Make executable executable (Unix only)
Api::Result<void> makeExecutable();
// Check if update is needed (older than 7 days)
[[nodiscard]] bool shouldUpdate() const;
// Get download URL based on platform
[[nodiscard]] std::string getDownloadUrl() const;
std::shared_ptr<NetworkClient> networkClient_;
std::filesystem::path executablePath_;
std::atomic<bool> initialized_{false};
mutable std::mutex mutex_;
// Cookie configuration for YouTube authentication
std::optional<std::string> cookiesPath_;
std::optional<std::string> cookiesFromBrowser_;
// 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";
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe";
static constexpr std::string_view YTDLP_DOWNLOAD_MACOS =
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos";
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ClearCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->clearQueue();
if (!result) {
ECHOION_LOG_ERROR(std::format("Clear command failed: {}", result.error().message));
ctx.reply("Couldn't clear the queue. Please try again.");
return;
}
ctx.reply("Queue cleared!");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Clear command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Clears all tracks from the queue.";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"clr", "empty"};
}
};
} // namespace Echoion::Core
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include <echoion/api.hpp>
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
#include <memory>
#include <functional>
#include "echoion/core/MusicManager.hpp"
namespace Echoion::Core {
class MusicManager;
enum class CommandCategory {
Music,
Queue,
Playback,
Utility,
Admin
};
inline std::string toString(CommandCategory category) {
switch (category) {
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";
}
/**
* @brief Context passed to every command execution.
* Wraps all dependencies required to perform an action.
*/
struct CommandContext {
uint64_t clientId = 0;
std::string args; // Arguments excluding the command name
std::string_view invokerName;
// Dependencies
std::weak_ptr<MusicManager> musicManager;
// Reply callback - set by CommandManager
std::function<void(std::string_view)> replyCallback;
// Helper to reply to the user
void reply(std::string_view message) const {
if (replyCallback) {
replyCallback(message);
}
}
};
/**
* @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., "<url>").
*/
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<std::string_view> getAliases() const { return {}; }
/**
* @brief Returns whether this command requires admin privileges.
*/
virtual bool requiresAdmin() const { return false; }
};
using CommandPtr = std::shared_ptr<Command>;
} // namespace Echoion::Core
@@ -0,0 +1,25 @@
#pragma once
// New command system - header-only commands
#include "Command.hpp"
#include "PlayCommand.hpp"
#include "SelectCommand.hpp"
#include "PauseCommand.hpp"
#include "ResumeCommand.hpp"
#include "StopCommand.hpp"
#include "SkipCommand.hpp"
#include "SeekCommand.hpp"
#include "VolumeCommand.hpp"
#include "QueueCommand.hpp"
#include "RemoveCommand.hpp"
#include "ClearCommand.hpp"
#include "MoveCommand.hpp"
#include "ShuffleCommand.hpp"
#include "RepeatCommand.hpp"
#include "PlaylistCommand.hpp"
#include "NowPlayingCommand.hpp"
#include "SearchCommand.hpp"
#include "ReloadCommand.hpp"
#include "ReloadConfigCommand.hpp"
#include "SubscribeCommand.hpp"
#include "UnsubscribeCommand.hpp"
@@ -0,0 +1,82 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class MoveCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("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)");
return;
}
// Parse arguments: from and to positions
uint32_t from = 0, to = 0;
auto spacePos = ctx.args.find(' ');
if (spacePos == std::string::npos) {
ctx.reply("Please provide both from and to positions.");
return;
}
auto result1 = std::from_chars(ctx.args.data(),
ctx.args.data() + spacePos,
from);
auto result2 = std::from_chars(ctx.args.data() + spacePos + 1,
ctx.args.data() + ctx.args.size(),
to);
if (result1.ec != std::errc() || result2.ec != std::errc() || from == 0 || to == 0) {
ctx.reply("Please provide valid position numbers (starting from 1).");
return;
}
auto moveResult = manager->moveInQueue(from - 1, to - 1); // Convert to 0-based
if (!moveResult) {
ECHOION_LOG_ERROR(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.");
} else {
ctx.reply("Couldn't move that track. Please try again.");
}
return;
}
ctx.reply(std::format("Moved track from position {} to {}.", from, to));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Move command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Moves a track to a different position in the queue.";
}
std::string_view getUsage() const override {
return "<from> <to>";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"mv"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,66 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class NowPlayingCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto current = manager->getCurrentTrack();
if (!current) {
ECHOION_LOG_ERROR(std::format("NowPlaying command failed: {}", current.error().message));
ctx.reply("Couldn't get current track information.");
return;
}
if (!current->has_value()) {
ctx.reply("Nothing is currently playing. Add something with [prefix]play!");
return;
}
const auto& track = current->value();
std::string msg = std::format("\xf0\x9f\x8e\xb5 **{}** by **{}**",
track.track.title,
track.track.artist);
if (track.track.duration > std::chrono::seconds(0)) {
auto mins = std::chrono::minutes(track.track.duration->count()).count();
auto secs = std::chrono::seconds(track.track.duration->count()).count() % 60;
msg += std::format(" [{}:{:02}]", mins, secs);
}
if (!track.addedBy.empty()) {
msg += std::format(" (requested by {})", track.addedBy);
}
ctx.reply(msg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("NowPlaying command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Shows the currently playing track.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"np", "current", "playing"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,51 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class PauseCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->pause();
if (!result) {
ECHOION_LOG_ERROR(std::format("Pause command failed: {}", result.error().message));
if (result.error().code == Api::ErrorCode::InvalidArgument) {
ctx.reply("Nothing is playing right now.");
} else {
ctx.reply("Couldn't pause playback. Please try again.");
}
return;
}
ctx.reply("Playback paused.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Pause command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Pauses the current playback.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,125 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class PlayCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable. Please try again later.");
return;
}
if (ctx.args.empty()) {
ctx.reply("Usage: play <url or search query>\nExample: play never gonna give you up");
return;
}
// Check if it's a direct URL
if (ctx.args.find("http") == 0) {
auto result = manager->play(ctx.args, ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(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.");
break;
case Api::ErrorCode::InvalidUrl:
ctx.reply("That doesn't look like a valid URL.");
break;
default:
ctx.reply("Couldn't play that URL. Please try again.");
break;
}
return;
}
ctx.reply(std::format("Added to queue: {}", *result));
return;
}
// Otherwise, treat as search query
auto searchResult = manager->search(ctx.args);
if (!searchResult) {
ECHOION_LOG_ERROR(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.");
} else {
ctx.reply("Search failed. Please try again.");
}
return;
}
if (searchResult->tracks.empty()) {
ctx.reply("No results found. Try different keywords.");
return;
}
// Single result - play immediately
if (searchResult->tracks.size() == 1) {
const auto& track = searchResult->tracks[0];
auto playResult = manager->queueTrack(track, ctx.clientId);
if (!playResult) {
ECHOION_LOG_ERROR(std::format("Queue failed: {}", playResult.error().message));
ctx.reply("Couldn't add that track. Please try again.");
return;
}
ctx.reply(std::format("Added to queue: {}", track.title));
return;
}
// Multiple results - store and show list
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
std::string msg = "\xf0\x9f\x94\x8d Multiple results found. Use [prefix]select <number>:\n";
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
const auto& track = searchResult->tracks[i];
msg += std::format("{}. {}", i + 1, track.title);
if (!track.artist.empty()) {
msg += std::format(" by {}", track.artist);
}
if (track.duration.has_value()) {
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
msg += std::format(" [{}:{:02}]", mins, secs);
}
msg += "\n";
}
ctx.reply(msg);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Play command exception: {}", e.what()));
ctx.reply("Something went wrong while trying to play. Please try again.");
}
}
std::string_view getDescription() const override {
return "Plays a track from URL or searches and lets you select.";
}
std::string_view getUsage() const override {
return "<url or search query>";
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override {
return {"p", "add"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,80 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core {
class PlaylistCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
// List playlists
auto playlists = manager->getPlaylists();
if (!playlists) {
ECHOION_LOG_ERROR(std::format("Playlist list failed: {}", playlists.error().message));
ctx.reply("Couldn't retrieve playlists.");
return;
}
if (playlists->empty()) {
ctx.reply("No playlists available.");
return;
}
std::stringstream msg;
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
for (const auto& pl : *playlists) {
msg << std::format("- {} ({} tracks)\n", pl.name, pl.tracks.size());
}
ctx.reply(msg.str());
} else {
// Load playlist
auto result = manager->loadPlaylist(std::string(ctx.args), ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Playlist load failed: {}", result.error().message));
if (result.error().code == Api::ErrorCode::NotFound) {
ctx.reply("That playlist doesn't exist.");
} else {
ctx.reply("Couldn't load the playlist. Please try again.");
}
return;
}
ctx.reply(std::format("Loaded {} tracks from playlist '{}'!", *result, ctx.args));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Playlist command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Lists or loads a playlist.";
}
std::string_view getUsage() const override {
return "[playlist name]";
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override {
return {"pl"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,95 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core {
class QueueCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto current = manager->getCurrentTrack();
auto queue = manager->getQueue();
auto state = manager->getPlaybackState();
if (!queue) {
ECHOION_LOG_ERROR(std::format("Queue command failed: {}", queue.error().message));
ctx.reply("Couldn't get queue information.");
return;
}
std::stringstream msg;
msg << "\xf0\x9f\x93\x9c **Queue**\n";
// Current track
if (current && current->has_value()) {
const auto& track = current->value();
msg << std::format("\n**Now Playing:** {} by {}\n",
track.track.title,
track.track.artist);
}
// Queue
if (queue->empty()) {
msg << "\nThe queue is empty. Add songs with [prefix]play!";
} else {
msg << std::format("\n**Up Next ({} tracks):**\n", queue->size());
for (size_t i = 0; i < queue->size() && i < 10; ++i) {
const auto& entry = (*queue)[i];
msg << std::format("{}. {}", i + 1, entry.track.title);
if (!entry.addedBy.empty()) {
msg << std::format(" (by {})", entry.addedBy);
}
msg << "\n";
}
if (queue->size() > 10) {
msg << std::format("\n... and {} more", queue->size() - 10);
}
}
// 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));
}
ctx.reply(msg.str());
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Queue command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Shows the current queue and playback status.";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"q", "list"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,34 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ReloadCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
// This is a placeholder - actual reload is handled by the plugin
ECHOION_LOG_INFO("Reload requested by user");
ctx.reply("Reload is handled automatically by the plugin. Use the TS3 plugin menu to reload the core.");
}
std::string_view getDescription() const override {
return "Shows information about reloading the bot.";
}
CommandCategory getCategory() const override {
return CommandCategory::Admin;
}
bool requiresAdmin() const override {
return true;
}
std::vector<std::string_view> getAliases() const override {
return {"restart", "r"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,42 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include "echoion/core/Core.hpp" // For Core::reloadConfig
#include <format>
namespace Echoion::Core {
class ReloadConfigCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
// Note: ctx.core is not directly accessible, we need to use the MusicManager's core reference
// For now, reply with instructions
ctx.reply("Config reload: Please use !reload command or restart the bot for config changes to take effect.");
// TODO: Add core reference to CommandContext so commands can call Core methods
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("ReloadConfig command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Reloads the bot configuration from file.";
}
CommandCategory getCategory() const override {
return CommandCategory::Admin;
}
bool requiresAdmin() const override {
return true;
}
std::vector<std::string_view> getAliases() const override {
return {"reloadcfg", "rlcfg"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,70 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class RemoveCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
ctx.reply("Usage: remove <position>\nUse [prefix]queue to see track positions.");
return;
}
uint32_t position = 0;
auto result = std::from_chars(ctx.args.data(),
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).");
return;
}
auto remResult = manager->removeFromQueue(position - 1); // Convert to 0-based
if (!remResult) {
ECHOION_LOG_ERROR(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.");
} else {
ctx.reply("Couldn't remove that track. Please try again.");
}
return;
}
ctx.reply(std::format("Removed track at position {}.", position));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Remove command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Removes a track from the queue by position.";
}
std::string_view getUsage() const override {
return "<position>";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"rm", "delete", "del"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class RepeatCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->toggleRepeat();
if (!result) {
ECHOION_LOG_ERROR(std::format("Repeat command failed: {}", result.error().message));
ctx.reply("Couldn't toggle repeat. Please try again.");
return;
}
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON." : "Repeat is now OFF.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Repeat command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Toggles repeat mode for the current track.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"loop"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,51 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ResumeCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->resume();
if (!result) {
ECHOION_LOG_ERROR(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.");
}
return;
}
ctx.reply("Playback resumed.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Resume command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Resumes the paused playback.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"unpause", "continue"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,90 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <sstream>
namespace Echoion::Core {
class SearchCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
ctx.reply("Usage: search <query>\nExample: search never gonna give you up");
return;
}
auto result = manager->search(ctx.args);
if (!result) {
ECHOION_LOG_ERROR(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.");
} else {
ctx.reply("Search failed. Please try again later.");
}
return;
}
if (result->tracks.empty()) {
ctx.reply("No results found. Try different keywords.");
return;
}
// Store results for this client so they can use select
manager->storePendingSearch(ctx.clientId, result->tracks);
std::stringstream msg;
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args << "\":\n\n";
for (size_t i = 0; i < result->tracks.size() && i < 5; ++i) {
const auto& track = result->tracks[i];
msg << std::format("{}. {}", i + 1, track.title);
if (!track.artist.empty()) {
msg << std::format(" by {}", track.artist);
}
if (track.duration.has_value()) {
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
msg << std::format(" [{}:{:02}]", mins, secs);
}
msg << "\n";
}
msg << "\nUse [prefix]select <number> to play a result.";
ctx.reply(msg.str());
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Search command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Searches for tracks and shows results.";
}
std::string_view getUsage() const override {
return "<query>";
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override {
return {"find", "s"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,84 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <chrono>
#include <charconv>
namespace Echoion::Core {
class SeekCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
ctx.reply("Usage: seek <seconds>\nExample: seek 60 (jumps to 1 minute)");
return;
}
int seconds = 0;
auto parseResult = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
seconds);
if (parseResult.ec != std::errc()) {
ctx.reply("Please provide a valid number of seconds.");
return;
}
if (seconds < 0) {
ctx.reply("Time must be a positive number.");
return;
}
auto result = manager->seek(std::chrono::seconds(seconds));
if (!result) {
ECHOION_LOG_ERROR(std::format("Seek command failed: {}", result.error().message));
if (result.error().code == Api::ErrorCode::InvalidArgument) {
ctx.reply("Nothing is playing right now.");
} else if (result.error().code == Api::ErrorCode::NotSupported) {
ctx.reply("This track doesn't support seeking.");
} else {
ctx.reply("Couldn't seek. Please try again.");
}
return;
}
auto mins = seconds / 60;
auto secs = seconds % 60;
if (mins > 0) {
ctx.reply(std::format("Seeked to {}:{:02}.", mins, secs));
} else {
ctx.reply(std::format("Seeked to {} seconds.", seconds));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Seek command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Seeks to a position in the current track.";
}
std::string_view getUsage() const override {
return "<seconds>";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"jump"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,75 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class SelectCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
ctx.reply("Usage: select <number>\nSelect a track from your last search results.");
return;
}
// Parse index
uint32_t index = 0;
auto result = std::from_chars(ctx.args.data(),
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.).");
return;
}
std::string invokerName(ctx.invokerName);
auto selectResult = manager->selectSearchResult(ctx.clientId, index, invokerName);
if (!selectResult) {
ECHOION_LOG_ERROR(std::format("Select failed for client {} index {}: {}",
ctx.clientId, index, selectResult.error().message));
if (selectResult.error().code == Api::ErrorCode::NotFound) {
ctx.reply("No search results found. Use [prefix]play <query> to search first.");
} else {
ctx.reply("Couldn't select that track. Please try again.");
}
return;
}
ctx.reply(*selectResult);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Select command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Selects a track from your search results.";
}
std::string_view getUsage() const override {
return "<number>";
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::vector<std::string_view> getAliases() const override {
return {"sel", "pick", "choose"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class ShuffleCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->toggleShuffle();
if (!result) {
ECHOION_LOG_ERROR(std::format("Shuffle command failed: {}", result.error().message));
ctx.reply("Couldn't toggle shuffle. Please try again.");
return;
}
ctx.reply(*result ? "\xf0\x9f\x94\x80 Shuffle is now ON." : "Shuffle is now OFF.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Shuffle command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Toggles shuffle mode for the queue.";
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override {
return {"random"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,71 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class SkipCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
uint32_t count = 1;
if (!ctx.args.empty()) {
auto result = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
count);
if (result.ec != std::errc() || count == 0) {
ctx.reply("Please provide a valid number (1 or more).");
return;
}
}
auto result = manager->skip(count);
if (!result) {
ECHOION_LOG_ERROR(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.");
} else {
ctx.reply("Couldn't skip. Please try again.");
}
return;
}
if (count == 1) {
ctx.reply("Skipped to next track.");
} else {
ctx.reply(std::format("Skipped {} tracks.", count));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Skip command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Skips to the next track(s).";
}
std::string_view getUsage() const override {
return "[count]";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"next", "n"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class StopCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->stop();
if (!result) {
ECHOION_LOG_ERROR(std::format("Stop command failed: {}", result.error().message));
ctx.reply("Couldn't stop playback. Please try again.");
return;
}
ctx.reply("Playback stopped and queue cleared.");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Stop command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Stops playback and clears the queue.";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"s"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class SubscribeCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->subscribe(ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}", result.error().message));
ctx.reply("Couldn't subscribe you. Please try again.");
return;
}
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Subscribe command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Subscribes to the music bot to receive audio.";
}
CommandCategory getCategory() const override {
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override {
return {"sub", "join"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,46 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
class UnsubscribeCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
auto result = manager->unsubscribe(ctx.clientId);
if (!result) {
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}", result.error().message));
ctx.reply("Couldn't unsubscribe you. Please try again.");
return;
}
ctx.reply(*result);
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Unsubscribe command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Unsubscribes from the music bot.";
}
CommandCategory getCategory() const override {
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override {
return {"unsub", "leave"};
}
};
} // namespace Echoion::Core
@@ -0,0 +1,85 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
namespace Echoion::Core {
class VolumeCommand : public Command {
public:
void execute(const CommandContext& ctx) override {
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply("The music service is currently unavailable.");
return;
}
if (ctx.args.empty()) {
// Show current volume
auto state = manager->getPlaybackState();
if (state) {
ctx.reply(std::format("Current volume: {}%", static_cast<int>(state->volume * 100)));
} else {
ctx.reply("Unable to get current volume.");
}
return;
}
// Parse volume (0-100)
int volumePercent = 0;
auto result = std::from_chars(ctx.args.data(),
ctx.args.data() + ctx.args.size(),
volumePercent);
if (result.ec != std::errc()) {
ctx.reply("Please provide a valid number (0-100).");
return;
}
if (volumePercent < 0 || volumePercent > 100) {
ctx.reply("Volume must be between 0 and 100.");
return;
}
float volume = volumePercent / 100.0f;
auto volResult = manager->setVolume(volume);
if (!volResult) {
ECHOION_LOG_ERROR(std::format("Volume command failed: {}", volResult.error().message));
ctx.reply("Couldn't change volume. Please try again.");
return;
}
// Visual volume indicator
std::string indicator;
int bars = volumePercent / 10;
for (int i = 0; i < 10; ++i) {
indicator += (i < bars) ? "\xe2\x96\x88" : "\xe2\x96\x91"; // Full block / Light shade
}
ctx.reply(std::format("Volume: {}% {}", volumePercent, indicator));
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Volume command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
std::string_view getDescription() const override {
return "Sets or shows the playback volume.";
}
std::string_view getUsage() const override {
return "[0-100]";
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override {
return {"vol", "v"};
}
};
} // namespace Echoion::Core