Migrate core infrastructure to VoidLibrary

This commit is contained in:
faumaray committed 2026-06-22 15:53:23 +03:00
1 parent 53801f2b53
commit 2bdb63766d
65 files changed
+16109 -12011

No files matched your search

+144 -121
View File
@@ -1,146 +1,169 @@
#pragma once
#include <echoion/api.hpp>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include "NetworkTypes.hpp"
#include <AudioTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <span>
#include <condition_variable>
#include <mutex>
#include <optional>
#include <queue>
#include <span>
#include <thread>
// Forward declarations for FFmpeg
extern "C" {
struct AVFormatContext;
struct AVCodecContext;
struct AVFrame;
struct AVPacket;
struct SwrContext;
struct AVBufferRef;
struct AVFormatContext;
struct AVCodecContext;
struct AVFrame;
struct AVPacket;
struct SwrContext;
struct AVBufferRef;
}
namespace Echoion::Core {
namespace Echoion::Core
{
class AudioDecoder {
public:
AudioDecoder();
~AudioDecoder();
class AudioDecoder
{
public:
// Initialize decoder with optional hardware acceleration
Api::Result<void> initialize(const Api::HwAccelConfig& hwConfig = {});
void shutdown();
AudioDecoder();
~AudioDecoder();
// Open audio source (URL or file path)
Api::Result<void> openSource(const std::string& url);
void closeSource();
// Initialize decoder with optional hardware acceleration
Api::Result<void>
initialize(const Api::HwAccelConfig& hwConfig = {});
void shutdown();
// Decode audio - returns zero-copy pooled buffer
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
// Seek to position
Api::Result<void> seek(std::chrono::milliseconds position);
// Open audio source (URL or file path)
Api::Result<void> openSource(const std::string& url);
void closeSource();
// 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;
// Decode audio - returns zero-copy pooled buffer
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
// Set output format
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
// Seek to position
Api::Result<void> seek(std::chrono::milliseconds position);
// 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(); }
// Get audio info
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
getStreamInfo() const;
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();
// Get current position
[[nodiscard]] std::chrono::milliseconds getPosition() const;
// Frame conversion (returns int16 for direct playback)
Api::Result<Api::DecodedAudio> convertFramePooled();
// Check if decoder has more data
[[nodiscard]] bool hasMoreData() const;
// 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;
// Set output format
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
// Stream info
int audioStreamIndex_ = -1;
Api::AudioStreamInfo streamInfo_;
// Output format
uint32_t outputSampleRate_ = 192000;
uint32_t outputChannels_ = 2;
// Set proxy configuration for network requests
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
// 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;
// Hardware acceleration
[[nodiscard]] bool isHardwareAccelerated() const
{
return hwAccelEnabled_;
}
[[nodiscard]] Api::HwAccelType getHwAccelType() const
{
return hwAccelType_;
}
// 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_;
// Enable/disable zero-copy mode
void setZeroCopyEnabled(bool enabled)
{
zeroCopyEnabled_ = enabled;
}
[[nodiscard]] bool isZeroCopyEnabled() const
{
return zeroCopyEnabled_;
}
std::atomic<uint32_t> streamSampleRate_{48000};
std::optional<Api::ProxyConfig> proxyConfig_;
// Statistics
mutable std::mutex statsMutex_;
Stats stats_;
};
// 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();
// Frame conversion (returns int16 for direct playback)
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_ = 192000;
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::atomic<uint32_t> streamSampleRate_{48000};
std::optional<Api::ProxyConfig> proxyConfig_;
// Statistics
mutable std::mutex statsMutex_;
Stats stats_;
};
} // namespace Echoion::Core
+147 -134
View File
@@ -1,10 +1,11 @@
#pragma once
#include "commands/Command.hpp"
#include "echoion/api/ConfigTypes.hpp"
#include <ConfigTypes.hpp>
#include <PluginTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <echoion/api.hpp>
#include <functional>
#include <future>
#include <map>
@@ -15,151 +16,163 @@
#include <thread>
#include <vector>
namespace Echoion::Core {
namespace Echoion::Core
{
class MusicManager;
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();
// Shutdown the command manager (stops thread pool)
void shutdown();
// 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;
}
}
// Function to check if client has permission (set by Core)
using PermissionCheckFunc =
std::function<bool(uint64_t clientId, CommandCategory category)>;
/**
* @brief Dispatches a command message to the appropriate handler (ASYNC).
* Commands are executed in a thread pool, allowing multiple users to
* use the bot simultaneously without blocking.
* @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 queued for execution, false
* otherwise.
* @brief Manages command registration and dispatch.
*
* Usage:
* CommandManager mgr;
* mgr.registerCommand<PlayCommand>("play");
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
*/
[[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 = "");
class CommandManager
{
public:
/**
* @brief Executes a command synchronously (for internal use).
* Prefer using dispatch() for normal command handling.
*/
[[nodiscard]] bool
dispatchSync(uint64_t clientId,
std::string_view message,
std::weak_ptr<MusicManager> musicManager,
std::function<void(std::string_view)> replyFunc,
std::string_view invokerName = "");
CommandManager();
~CommandManager();
[[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;
// Shutdown the command manager (stops thread pool)
void shutdown();
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);
// Disable copy
CommandManager(const CommandManager&) = delete;
CommandManager& operator=(const CommandManager&) = delete;
private:
struct CommandEntry {
std::string primaryName;
CommandPtr instance;
};
// Enable move
CommandManager(CommandManager&&) = default;
CommandManager& operator=(CommandManager&&) = default;
void registerBuiltinCommands();
// Internal Help Command (defined in .cpp to access registry)
class HelpCommand;
void registerHelpCommand();
/**
* @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::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_;
std::lock_guard<std::mutex> lock(mutex_);
// Async command execution
struct CommandTask {
uint64_t clientId;
std::string message;
std::weak_ptr<MusicManager> musicManager;
std::function<void(std::string_view)> replyFunc;
std::string invokerName;
};
// Register primary name
commands_[primaryName] = cmd;
uniqueCommands_.push_back({primaryName, cmd});
void startThreadPool();
void processCommandQueue();
void executeCommandAsync(CommandTask task);
// Register aliases automatically from the class itself
for (auto alias : cmd->getAliases()) {
commands_[std::string(alias)] = cmd;
}
}
std::vector<std::jthread> workerThreads_;
std::queue<CommandTask> commandQueue_;
std::mutex queueMutex_;
std::condition_variable queueCv_;
std::atomic<bool> shutdown_{false};
static constexpr size_t THREAD_POOL_SIZE =
4; // Handle up to 4 concurrent commands
/**
* @brief Dispatches a command message to the appropriate handler
* (ASYNC). Commands are executed in a thread pool, allowing
* multiple users to use the bot simultaneously without blocking.
* @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 queued for execution,
* 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 = "");
}; // namespace Echoion::Core
/**
* @brief Executes a command synchronously (for internal use).
* Prefer using dispatch() for normal command handling.
*/
[[nodiscard]] bool
dispatchSync(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_;
// Async command execution
struct CommandTask {
uint64_t clientId;
std::string message;
std::weak_ptr<MusicManager> musicManager;
std::function<void(std::string_view)> replyFunc;
std::string invokerName;
};
void startThreadPool();
void processCommandQueue();
void executeCommandAsync(CommandTask task);
std::vector<std::jthread> workerThreads_;
std::queue<CommandTask> commandQueue_;
std::mutex queueMutex_;
std::condition_variable queueCv_;
std::atomic<bool> shutdown_{false};
static constexpr size_t THREAD_POOL_SIZE =
4; // Handle up to 4 concurrent commands
}; // namespace Echoion::Core
} // namespace Echoion::Core
+123 -21
View File
@@ -1,30 +1,132 @@
#pragma once
#include <echoion/api.hpp>
#include <ConfigTypes.hpp>
#include <Types.hpp>
#include <filesystem>
#include <string>
namespace Echoion::Core {
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();
// JSON structures for configuration (public for use by Core)
struct BotConfigJson {
std::string botName = "Echoion";
std::string commandPrefix = "!";
float defaultVolume = 0.5f;
uint32_t maxQueueSize = 100;
uint32_t trackTimeout = 30000;
bool autoReconnect = true;
uint32_t reconnectDelay = 5000;
uint32_t maxReconnectAttempts = 5;
std::string preferredQuality = "High";
bool allowPlaylistImports = true;
};
private:
// Parse quality string to enum
[[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str);
[[nodiscard]] static std::string qualityToString(Api::AudioQuality quality);
};
struct YouTubeConfigJson {
std::optional<std::string> youtubeApiKey;
std::optional<std::string> youtubeCookiesPath;
std::optional<std::string> cookiesFromBrowser;
uint32_t ytDlpMaxConcurrent = 4;
bool ytDlpAsyncEnabled = true;
bool enableUrlShortening = true;
};
struct NetworkConfigJson {
// Proxy settings (flat structure for backward compatibility)
std::string proxyType = "HTTP";
std::optional<std::string> proxyHost;
std::optional<uint16_t> proxyPort;
std::optional<std::string> proxyUsername;
std::optional<std::string> proxyPassword;
// RPC settings
bool rpcEnabled = true;
uint16_t rpcPort = 8765;
std::string rpcBindAddress = "127.0.0.1";
};
struct TeamSpeakConfigJson {
std::string address = "localhost";
uint16_t port = 9987;
std::string serverPassword = "";
std::string nickname = "EchoionBot";
std::optional<std::string> defaultChannelId;
std::optional<std::string> channelPassword;
std::vector<uint64_t> adminGroups;
std::vector<uint64_t> djGroups;
std::vector<uint64_t> bannedGroups;
};
struct SecurityConfigJson {
bool requireAuthForAdmin = true;
uint32_t maxLoginAttempts = 5;
uint32_t lockoutDuration = 300000;
uint32_t sessionTimeout = 3600000;
bool enableAuditLog = true;
std::optional<std::string> apiKey;
bool allowCors = false;
std::vector<std::string> corsOrigins;
};
struct FeaturesConfigJson {
bool enableHotReload = true;
bool enableAutoReload = false;
bool enableAutoUpdateCheck = true;
bool autoStartOnSubscribe = true;
bool pauseOnEmptySubscribers = true;
bool resumeOnSubscriberReturn = true;
std::string shuffleMode = "random";
std::string repeatMode = "off";
uint32_t maxHistorySize = 50;
};
struct AdvancedConfigJson {
uint32_t sampleRate = 192000;
uint32_t channels = 2;
uint32_t bufferSize = 7680;
uint32_t commandThreadPoolSize = 4;
uint32_t networkThreadPoolSize = 4;
uint32_t decoderThreads = 2;
bool cacheEnabled = true;
std::string cacheMaxSize = "1GB";
uint32_t cacheTTL = 86400;
uint32_t tempCleanupInterval = 3600;
};
struct AppConfigJson {
BotConfigJson bot;
YouTubeConfigJson youtube;
NetworkConfigJson network;
TeamSpeakConfigJson teamspeak;
SecurityConfigJson security;
FeaturesConfigJson features;
AdvancedConfigJson advanced;
};
// 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();
// 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
+155 -85
View File
@@ -1,111 +1,181 @@
#pragma once
#include <echoion/api.hpp>
#include <echoion/api/Database.hpp>
#include "MusicManager.hpp"
#include "CommandManager.hpp"
#include "ConfigLoader.hpp"
#include "MusicManager.hpp"
#include "NetworkClient.hpp"
#include "RpcServer.hpp"
#include "ConfigLoader.hpp"
#include <thread>
#include <mutex>
#include <ConfigTypes.hpp>
#include <CoreInterface.hpp>
#include <Database.hpp>
#include <RpcTypes.hpp>
#include <StateBlob.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <mutex>
#include <thread>
namespace Echoion::Core {
namespace Echoion::Core
{
// Main Core implementation of ICoreInterface
class Core : public Api::ICoreInterface {
public:
Core();
~Core() override;
// Main Core implementation of ICoreInterface
class Core : public Api::ICoreInterface
{
public:
// ICoreInterface implementation
Api::Result<void> initialize(const std::filesystem::path& configPath) override;
Api::Result<void> shutdown() override;
[[nodiscard]] bool isInitialized() const noexcept override;
Core();
~Core() 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;
// ICoreInterface - Lifecycle
Api::Result<void>
initialize(const std::filesystem::path& configPath) override;
Api::Result<void> shutdown() override;
[[nodiscard]] bool isInitialized() const noexcept 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;
// ICoreInterface - Playback control (decoupled)
Api::Result<void> play(const std::string& trackId) 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;
// Track info
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const override;
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const override;
// ICoreInterface - Queue management (decoupled)
Api::Result<uint64_t> queueTrack(const std::string& trackId,
uint64_t clientId) override;
Api::Result<void> removeFromQueue(uint64_t queueId) override;
Api::Result<void> clearQueue() override;
[[nodiscard]] Api::Result<std::vector<Api::TrackSummary>>
getQueueSummaries() const override;
Api::Result<void> moveInQueue(uint64_t queueId,
uint32_t newPosition) override;
// Playlist
Api::Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) override;
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const override;
// ICoreInterface - Track info (decoupled)
[[nodiscard]] Api::Result<std::optional<Api::TrackSummary>>
getCurrentTrackSummary() const override;
[[nodiscard]] Api::Result<Api::PlaybackSummary>
getPlaybackSummary() 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();
// ICoreInterface - Playlist (decoupled)
Api::Result<void> loadPlaylist(const std::string& playlistId,
uint64_t clientId) override;
[[nodiscard]] Api::Result<std::vector<std::string>>
getPlaylistIds() const override;
// Hot reload
Api::Result<Api::HotReloadState> prepareForHotReload() override;
Api::Result<void> restoreAfterHotReload(const Api::HotReloadState& state) override;
// ICoreInterface - Configuration (decoupled)
Api::Result<void>
updateConfigJson(const std::string& configJson) override;
[[nodiscard]] Api::Result<std::string>
getConfigJson() const override;
// Event handling
void registerEventCallback(const Api::EventCallback& callback) override;
void unregisterEventCallback(const Api::EventCallback& callback) override;
// ICoreInterface - Hot reload (decoupled)
[[nodiscard]] Api::Result<std::string>
prepareForHotReload() override;
Api::Result<void>
restoreAfterHotReload(const std::string& state) override;
// Plugin event processing
Api::Result<void> onPluginEvent(const Api::PluginEvent& event) override;
// ICoreInterface - Decoupled state management
[[nodiscard]] Api::StateBlob saveState() override;
Api::Result<void>
restoreState(const Api::StateBlob& state) override;
[[nodiscard]] uint32_t getStateFormatVersion() const override;
[[nodiscard]] bool
canRestoreStateVersion(uint32_t version) const override;
// Status
[[nodiscard]] std::string getVersion() const override;
[[nodiscard]] std::chrono::system_clock::time_point getUptime() const override;
// ICoreInterface - Event handling
void registerEventCallback(
const Api::EventCallback& callback) override;
void unregisterEventCallback(
const Api::EventCallback& callback) override;
// Additional methods for plugin integration
void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override;
void setAudioDataCallback(const MusicManager::AudioDataCallback& callback);
void triggerAutoConnect() override;
// ICoreInterface - Plugin event processing
Api::Result<void>
onPluginEvent(const Api::PluginEvent& event) 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();
// ICoreInterface - Status
[[nodiscard]] std::string getVersion() const override;
[[nodiscard]] std::chrono::system_clock::time_point
getUptime() const override;
// Components
std::shared_ptr<NetworkClient> networkClient_;
std::shared_ptr<MusicManager> musicManager_;
std::unique_ptr<CommandManager> commandManager_;
Api::PluginInterfacePtr pluginInterface_;
// ICoreInterface - Plugin interface
void setPluginInterface(
Api::PluginInterfacePtr pluginInterface) override;
void triggerAutoConnect() override;
// 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};
// ICoreInterface - Advanced (for internal Core-to-Core use)
[[nodiscard]] Api::Result<Api::OpaqueHandle<Api::TrackInfo>>
getCurrentTrackHandle() const override;
[[nodiscard]] Api::Result<
std::vector<Api::OpaqueHandle<Api::QueueEntry>>>
getQueueHandles() const override;
[[nodiscard]] Api::Result<Api::AppConfigHandle>
getConfigHandle() const override;
Api::Result<void>
updateConfigFromHandle(Api::AppConfigHandle config) override;
// Event callbacks
std::vector<Api::EventCallback> eventCallbacks_;
mutable std::mutex eventMutex_;
// Additional methods for internal use (not in interface)
void setAudioDataCallback(
const MusicManager::AudioDataCallback& callback);
Api::Result<void> reloadConfig();
// 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_;
};
// Internal implementations using full types
Api::Result<void> playTrack(const Api::TrackInfo& track);
Api::Result<uint64_t> queueTrackFull(const Api::TrackInfo& track,
uint64_t clientId);
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
getQueue() const;
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
getCurrentTrack() const;
[[nodiscard]] Api::Result<Api::PlaybackState>
getPlaybackState() const;
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
getPlaylists() const;
Api::Result<void> updateConfig(const Api::AppConfig& config);
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const;
[[nodiscard]] Api::Result<Api::HotReloadState>
prepareForHotReloadFull();
Api::Result<void>
restoreAfterHotReloadFull(const Api::HotReloadState& state);
// Generate RPC tokens for existing subscribers
void generateRpcTokensForSubscribers();
private:
void onMusicEvent(const Api::PluginEvent& event);
void broadcastEvent(const Api::PluginEvent& event);
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
void updateWhisperList();
void setupRpcHandlers();
void setupEventBusSubscriptions() const noexcept;
// Components
std::shared_ptr<NetworkClient> networkClient_;
std::shared_ptr<MusicManager> musicManager_;
std::unique_ptr<CommandManager> commandManager_;
Api::PluginInterfacePtr pluginInterface_;
// State
Api::AppConfig config_;
std::filesystem::path configPath_;
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
+63 -65
View File
@@ -1,79 +1,77 @@
#pragma once
#include <echoion/api.hpp>
#include <fstream>
#include <mutex>
#include <queue>
#include <thread>
#include <condition_variable>
#include <LoggerInterface.hpp>
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include <chrono>
#include <array>
#include <map>
namespace Echoion::Core {
namespace Void::Logging
{
class MultiLogger;
} // namespace Void::Logging
// 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;
};
namespace Echoion::Core
{
class Logger : public Api::ILogger {
public:
explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion");
~Logger() override;
// ILogger implementation backed by the Void::Logging framework.
//
// Output is produced by a Void MultiLogger fanning out to:
// * a ConsoleLogger (stdout),
// * a SplitFileLogger writing per-level files (<dir>/<level>.log) plus a
// combined <dir>/all.log, each rolling independently by size, and
// * a CallbackLogger bridging back to the registered ILogger callbacks.
// The ILogger surface (levels, callbacks, console/file toggles, rotation
// knobs) is preserved so existing call sites and the ECHOION_LOG_* macros
// keep working unchanged.
class Logger : public Api::ILogger
{
public:
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;
explicit Logger(std::string_view logDir = "logs",
std::string_view baseName = "echoion");
~Logger() override;
void flush();
void setConsoleOutput(bool enabled);
void setFileOutput(bool enabled);
void setMaxFileSize(uint64_t bytes);
void setMaxFiles(uint32_t count);
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;
private:
void logWorker();
void rotateIfNeeded(Api::LogLevel level);
void openLogFiles();
void cleanupOldLogs();
void moveToHistory(const std::filesystem::path& filePath);
void ensureHistoryDirExists();
[[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);
void flush();
void setConsoleOutput(bool enabled);
void setFileOutput(bool enabled);
void setMaxFileSize(uint64_t bytes);
void setMaxFiles(uint32_t count);
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_;
};
private:
// (Re)assemble the Void sink tree from the current toggles/limits.
void rebuildSinks();
// Fan a Void log entry out to the registered ILogger callbacks.
void dispatchToCallbacks(Api::LogLevel level,
const std::string& message,
const std::string& file, uint32_t line,
const std::string& function);
std::filesystem::path logDir_;
std::string baseName_;
std::shared_ptr<Void::Logging::MultiLogger> sink_;
std::mutex sinkMutex_;
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
std::atomic<uint32_t> maxFiles_{5};
std::vector<LogCallback> callbacks_;
std::mutex callbackMutex_;
};
} // namespace Echoion::Core
+234 -168
View File
@@ -1,205 +1,271 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include "YouTubeClient.hpp"
#include "AudioDecoder.hpp"
#include "Database.hpp"
#include "NetworkClient.hpp"
#include "RpcTypes.hpp"
#include "SubscriptionManager.hpp"
#include <thread>
#include <mutex>
#include "YouTubeClient.hpp"
#include <ConfigTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <atomic>
#include <condition_variable>
#include <filesystem>
#include <future>
#include <mutex>
#include <queue>
#include <random>
#include <atomic>
#include <future>
#include <set>
#include <shared_mutex>
#include <thread>
#include <unordered_map>
#include <filesystem>
namespace Echoion::Core {
namespace Echoion::Core
{
class MusicManager {
public:
MusicManager();
~MusicManager();
class MusicManager
{
public:
Api::Result<void> initialize(const Api::BotConfig& config,
std::shared_ptr<NetworkClient> networkClient,
std::shared_ptr<Api::Database> database = nullptr);
void shutdown();
MusicManager();
~MusicManager();
[[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);
Api::Result<void>
initialize(std::shared_ptr<NetworkClient> networkClient,
std::shared_ptr<Api::Database> database = nullptr);
void shutdown();
[[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<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);
// Load playlist asynchronously - returns immediately, processes in background
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId);
[[nodiscard]] bool isPlaylistLoading() const { return playlistLoading_.load(); }
[[nodiscard]] size_t getPlaylistLoadProgress() const { return playlistLoadedCount_.load(); }
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
getPlaylists() const;
[[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<void> shuffleQueue();
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
getCurrentTrack() const;
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
// Load playlist asynchronously - returns immediately, processes in
// background
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl,
uint64_t clientId);
[[nodiscard]] bool isPlaylistLoading() const
{
return playlistLoading_.load();
}
[[nodiscard]] size_t getPlaylistLoadProgress() const
{
return playlistLoadedCount_.load();
}
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
getPlaylists() 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);
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
getCurrentTrack() const;
[[nodiscard]] Api::Result<Api::PlaybackState>
getPlaybackState() const;
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
// Help command
[[nodiscard]] std::string getHelpText() const;
[[nodiscard]] Api::Result<Api::SearchResult>
search(const std::string& query);
// Subscription management (by client ID - internally uses UID for
// persistence)
[[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; // Returns only ONLINE subscribers' client IDs
[[nodiscard]] bool hasSubscribers()
const; // Returns true if any subscribers exist (online or offline)
[[nodiscard]] bool hasOnlineSubscribers()
const; // Returns true only if there are online subscribers
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
getSubscribers() const;
[[nodiscard]] Api::Result<std::string>
unsubscribeByUid(const std::string& uid);
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
// 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);
// Get UIDs of subscribers who are currently online
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
// Help command
[[nodiscard]] std::string getHelpText() const;
// Called when a client connects to the server
void onClientConnected(uint64_t clientId);
// Subscription management (by client ID - internally uses UID for
// persistence)
[[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; // Returns only ONLINE subscribers' client IDs
[[nodiscard]] bool
hasSubscribers() const; // Returns true if any subscribers exist
// (online or offline)
[[nodiscard]] bool hasOnlineSubscribers()
const; // Returns true only if there are online subscribers
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
getSubscribers() const;
[[nodiscard]] Api::Result<std::string>
unsubscribeByUid(const std::string& uid);
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
[[nodiscard]] Api::Result<void>
restoreFromHotReload(const Api::HotReloadState& state);
// Get UIDs of subscribers who are currently online
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
using AudioDataCallback = std::function<void(const std::span<const short>)>;
void setAudioDataCallback(const AudioDataCallback& callback);
// Called when a client connects to the server
void onClientConnected(uint64_t clientId);
using SubscriptionChangeCallback = std::function<void()>;
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
[[nodiscard]] Api::Result<void>
restoreFromHotReload(const Api::HotReloadState& state);
using PlaybackStartCallback = std::function<void()>;
void setPlaybackStartCallback(const PlaybackStartCallback& callback);
using AudioDataCallback =
std::function<void(const std::span<const short>)>;
void setAudioDataCallback(const AudioDataCallback& callback);
// Callback to resolve client info (UID and nickname) from client ID
using ClientInfoCallback =
std::function<std::optional<std::pair<std::string, std::string>>(
uint64_t clientId)>;
void setClientInfoCallback(const ClientInfoCallback& callback);
using SubscriptionChangeCallback = std::function<void()>;
void setSubscriptionChangeCallback(
const SubscriptionChangeCallback& callback);
// Callback to resolve client ID from UID
using UidToClientIdCallback =
std::function<std::optional<uint64_t>(const std::string& uid)>;
void setUidToClientIdCallback(const UidToClientIdCallback& callback);
using PlaybackStartCallback = std::function<void()>;
void
setPlaybackStartCallback(const PlaybackStartCallback& callback);
// Callback to resolve nickname from client ID
using NicknameCallback =
std::function<std::optional<std::string>(uint64_t clientId)>;
void setNicknameCallback(const NicknameCallback& callback);
// Callback to resolve client info (UID and nickname) from client ID
using ClientInfoCallback = std::function<std::optional<
std::pair<std::string, std::string>>(uint64_t clientId)>;
void setClientInfoCallback(const ClientInfoCallback& callback);
// Called when a client leaves the server
void onClientDisconnected(uint64_t clientId);
// Callback to resolve client ID from UID
using UidToClientIdCallback =
std::function<std::optional<uint64_t>(const std::string& uid)>;
void
setUidToClientIdCallback(const UidToClientIdCallback& callback);
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);
// Prefetch next track for seamless transitions
void prefetchNextTrack();
[[nodiscard]] bool shouldPrefetch() const;
static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15); // Start prefetch 15s before end
// Temporary file tracking
std::set<std::string> tempFiles_;
mutable std::mutex tempFilesMutex_;
// Prefetch state for seamless playback
struct PrefetchState {
std::future<Api::Result<std::string>> streamUrlFuture;
std::atomic<bool> isPrefetching{false};
std::atomic<bool> hasPrefetched{false};
std::optional<std::string> prefetchedUrl;
} prefetchState_;
// Async playlist loading state
std::thread playlistLoadThread_;
std::atomic<bool> playlistLoading_{false};
std::atomic<size_t> playlistLoadedCount_{0};
std::atomic<size_t> playlistTotalCount_{0};
// Callback to resolve nickname from client ID
using NicknameCallback =
std::function<std::optional<std::string>(uint64_t clientId)>;
void setNicknameCallback(const NicknameCallback& callback);
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YouTubeClient> youTubeClient_;
std::unique_ptr<AudioDecoder> audioDecoder_;
std::unique_ptr<SubscriptionManager> subscriptionManager_;
// Called when a client leaves the server
void onClientDisconnected(uint64_t clientId);
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
// Accurate playback position tracking
std::chrono::milliseconds playbackPosition_{0}; // Current position
std::chrono::steady_clock::time_point playbackStartTime_; // When current segment started
std::chrono::milliseconds playbackBasePosition_{0}; // Position at start of current segment
float volume_ = 0.5f;
bool shuffle_ = false;
bool repeat_ = false;
uint64_t nextQueueId_ = 1;
private:
std::jthread playbackThread_;
mutable std::mutex mutex_;
std::condition_variable cv_;
std::atomic<bool> playbackThreadRunning_{false}; // True while thread is actively running
// Pending search results per client (for select command)
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>> pendingSearches_;
mutable std::mutex pendingSearchMutex_;
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();
AudioDataCallback audioCallback_;
SubscriptionChangeCallback subscriptionChangeCallback_;
PlaybackStartCallback playbackStartCallback_;
ClientInfoCallback clientInfoCallback_;
UidToClientIdCallback uidToClientIdCallback_;
NicknameCallback nicknameCallback_;
std::mt19937 rng_{std::random_device{}()};
// Generate silence/sine wave to keep audio stream alive during
// transitions
void generateTransitionAudio(std::chrono::milliseconds duration);
void sendSilenceChunk();
static constexpr auto TRANSITION_SILENCE_DURATION =
std::chrono::milliseconds(100);
static constexpr auto TRANSITION_FADE_DURATION =
std::chrono::milliseconds(50);
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
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;
};
// Download audio through proxy for playback
[[nodiscard]] Api::Result<std::string>
downloadAudioForPlayback(const std::string& url);
void cleanupTempFile(const std::string& filepath);
// Prefetch next track for seamless transitions
void prefetchNextTrack();
[[nodiscard]] bool shouldPrefetch() const;
static constexpr auto PREFETCH_THRESHOLD =
std::chrono::seconds(15); // Start prefetch 15s before end
// Temporary file tracking
std::set<std::string> tempFiles_;
mutable std::shared_mutex tempFilesMutex_;
// Prefetch state for seamless playback
struct PrefetchState {
std::future<Api::Result<std::string>> streamUrlFuture;
std::atomic<bool> isPrefetching{false};
std::atomic<bool> hasPrefetched{false};
std::optional<std::string> prefetchedUrl;
} prefetchState_;
// Async playlist loading state
std::thread playlistLoadThread_;
std::atomic<bool> playlistLoading_{false};
std::atomic<size_t> playlistLoadedCount_{0};
std::atomic<size_t> playlistTotalCount_{0};
// Auto-start thread for playlist (must be joined, not detached)
std::thread playlistAutoStartThread_;
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_;
std::atomic<bool> isPlaying_{false};
std::atomic<bool> isPaused_{false};
std::atomic<bool> wasPausedForNoSubscribers_{
false}; // Track if we auto-paused
// Accurate playback position tracking
std::chrono::milliseconds playbackPosition_{0}; // Current position
std::chrono::steady_clock::time_point
playbackStartTime_; // When current segment started
std::chrono::milliseconds playbackBasePosition_{
0}; // Position at start of current segment
std::atomic<float> volume_{0.5f};
std::atomic<bool> shuffle_{false};
std::atomic<bool> repeat_{false};
uint64_t nextQueueId_ = 1;
// Shuffle state - maintains shuffled order of queue indices
std::vector<size_t> shuffledIndices_;
size_t shuffleIndex_ = 0;
void rebuildShuffledIndices();
void reshuffleRemaining();
std::jthread playbackThread_;
mutable std::shared_mutex mutex_;
std::condition_variable_any cv_;
std::atomic<bool> playbackThreadRunning_{
false}; // True while thread is actively running
// 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_;
PlaybackStartCallback playbackStartCallback_;
ClientInfoCallback clientInfoCallback_;
UidToClientIdCallback uidToClientIdCallback_;
NicknameCallback nicknameCallback_;
std::mt19937 rng_{std::random_device{}()};
// Position tracking for periodic event updates
std::chrono::steady_clock::time_point lastPositionUpdate_{};
static constexpr auto POSITION_UPDATE_INTERVAL =
std::chrono::seconds(1);
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
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
+209 -173
View File
@@ -1,202 +1,238 @@
#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 <NetworkInterface.hpp>
#include <NetworkTypes.hpp>
#include <Types.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <atomic>
#include <chrono>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
// 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;
namespace Echoion::Core {
// Initialize with optional proxy
Api::Result<void> initialize(
const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
void shutdown();
// Forward declaration for URL parsing
struct UrlComponents;
// 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);
class NetworkClient : public Api::INetworkClient {
public:
NetworkClient();
~NetworkClient() override;
// 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);
// Initialize with optional proxy
Api::Result<void> initialize(const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
void shutdown();
// Concurrent batch requests
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>>
requestBatch(const std::vector<Api::HttpRequest>& requests);
// 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);
// JSON helpers using Void::Json reflection
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());
}
return parseJson<T>(response->bodyAsString());
}
// 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);
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 =
Void::Json::serialize(Void::Json::to_json(body));
auto response = post(url, jsonBody, headers);
if (!response) {
return std::unexpected(response.error());
}
return parseJson<T>(response->bodyAsString());
}
// Concurrent batch requests
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>> requestBatch(
const std::vector<Api::HttpRequest>& requests);
private:
// 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;
}
// Parse a response body into a reflectable type T via Void::Json.
template <typename T>
[[nodiscard]] static Api::Result<T>
parseJson(const std::string& body)
{
auto parsed = Void::Json::parse(body);
if (!parsed) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
std::format("JSON parse error ({}:{}): {}",
parsed.error().line, parsed.error().col,
parsed.error().message)));
}
auto value = Void::Json::from_json<T>(*parsed);
if (!value) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
std::format("JSON decode error: field '{}': {}",
value.error().field, value.error().message)));
}
return std::move(*value);
}
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;
}
public:
// Proxy configuration
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
void clearProxy();
// 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;
// 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);
private:
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;
};
// Request execution
[[nodiscard]] Api::Result<Api::HttpResponse>
executeWithRetry(const Api::HttpRequest& req);
[[nodiscard]] Api::Result<Api::HttpResponse>
executeRequest(const Api::HttpRequest& req);
// 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);
}
// 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
+74 -57
View File
@@ -1,81 +1,98 @@
#pragma once
#include <echoion/api.hpp>
#include <PluginTypes.hpp>
#include <RpcTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <thread>
#include <functional>
#include <mutex>
#include <set>
#include <functional>
#include <thread>
#include <unordered_map>
namespace Echoion::Core {
namespace Echoion::Core
{
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace websocket = beast::websocket;
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)>;
class RpcServer : public std::enable_shared_from_this<RpcServer>
{
public:
RpcServer();
~RpcServer();
using CommandHandler = std::function<Api::Result<std::string>(
const std::string& params, uint64_t clientId)>;
// 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_; }
RpcServer();
~RpcServer();
// Register command handlers
void registerHandler(const std::string& method, CommandHandler handler);
void unregisterHandler(const std::string& method);
// 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_; }
// 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);
// Register command handlers
void registerHandler(const std::string& method,
CommandHandler handler);
void unregisterHandler(const std::string& method);
// Broadcast events to all connected clients
void broadcastEvent(const std::string& event, const std::string& data);
// 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);
// Send event to specific client
void sendEvent(uint64_t clientId, const std::string& event, const std::string& data);
// Broadcast events to all connected clients
void broadcastEvent(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);
// Send event to specific client
void sendEvent(uint64_t clientId, const std::string& event,
const std::string& data);
asio::io_context ioContext_;
std::optional<asio::ip::tcp::acceptor> acceptor_;
std::thread serverThread_;
std::atomic<bool> running_{false};
uint16_t port_ = 8765;
private:
// 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_;
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);
// Authenticated clients
std::set<uint64_t> authenticatedClients_;
std::mutex authMutex_;
std::string authToken_;
asio::io_context ioContext_;
std::optional<asio::ip::tcp::acceptor> acceptor_;
std::thread serverThread_;
std::atomic<bool> running_{false};
uint16_t port_ = 8765;
// Command handlers
std::unordered_map<std::string, CommandHandler> handlers_;
std::mutex handlersMutex_;
};
// 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
+87
View File
@@ -0,0 +1,87 @@
#pragma once
#include <chrono>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <unordered_map>
namespace Echoion::Core
{
// Session management for RPC clients
// Supports 100+ concurrent authenticated sessions
class SessionManager
{
public:
struct Session {
uint64_t clientId;
std::string authToken;
std::chrono::steady_clock::time_point lastActivity;
std::chrono::steady_clock::time_point createdAt;
bool isAuthenticated;
// Optional: store client-specific state
struct ClientState {
std::optional<std::string> currentPlaylist;
float preferredVolume = -1.0f; // -1 = use default
// Add more client preferences here
};
std::optional<ClientState> clientState;
};
struct Config {
size_t maxSessions = 150; // 100 users + buffer
std::chrono::seconds sessionTimeout{3600}; // 1 hour timeout
std::chrono::seconds cleanupInterval{
300}; // Cleanup every 5 min
};
SessionManager();
explicit SessionManager(const Config& config);
// Initialize session manager
bool initialize();
void shutdown();
// Create new session
std::string createSession(uint64_t clientId);
// Authenticate session
bool authenticateSession(const std::string& token);
// Validate and update session
bool validateSession(const std::string& token);
void updateActivity(const std::string& token);
// Get session info
std::optional<Session> getSession(const std::string& token) const;
// End session
void endSession(const std::string& token);
void endSessionByClientId(uint64_t clientId);
// Get all active sessions
std::vector<Session> getAllSessions() const;
// Get session count
size_t getSessionCount() const;
// Cleanup expired sessions (call periodically)
size_t cleanupExpiredSessions();
// Check if at capacity
bool isAtCapacity() const;
private:
std::string generateToken();
Config config_;
std::unordered_map<std::string, Session> sessions_;
mutable std::mutex mutex_;
std::atomic<bool> running_{false};
};
} // namespace Echoion::Core
+109 -100
View File
@@ -1,129 +1,138 @@
#pragma once
#include <filesystem>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include <optional>
#include <memory>
#include <mutex>
#include <filesystem>
#include <quickjs.h>
namespace Echoion::Core {
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();
/**
* 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:
// Disable copy, enable move
SignatureCipher(const SignatureCipher&) = delete;
SignatureCipher& operator=(const SignatureCipher&) = delete;
SignatureCipher(SignatureCipher&&) noexcept;
SignatureCipher& operator=(SignatureCipher&&) noexcept;
SignatureCipher();
~SignatureCipher();
/**
* Initialize the QuickJS solver with core libraries
* Must be called before using the cipher
*/
void initialize();
// Disable copy, enable move
SignatureCipher(const SignatureCipher&) = delete;
SignatureCipher& operator=(const SignatureCipher&) = delete;
SignatureCipher(SignatureCipher&&) noexcept;
SignatureCipher& operator=(SignatureCipher&&) noexcept;
/**
* 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);
/**
* Initialize the QuickJS solver with core libraries
* Must be called before using the cipher
*/
void initialize();
/**
* Check if the cipher is ready (has valid decipher function)
*/
[[nodiscard]] bool isReady() const;
/**
* 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);
/**
* 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);
/**
* Check if the cipher is ready (has valid decipher function)
*/
[[nodiscard]] bool isReady() const;
/**
* 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 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);
/**
* 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);
/**
* 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);
/**
* Clear the cipher state
*/
void clear();
/**
* 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);
/**
* Check if cipher has been initialized
*/
[[nodiscard]] bool isInitialized() const;
/**
* Clear the cipher state
*/
void clear();
private:
/**
* Initialize QuickJS runtime and context with solver libraries
*/
void initSolver();
/**
* Check if cipher has been initialized
*/
[[nodiscard]] bool isInitialized() const;
/**
* 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);
private:
/**
* Get cache directory for storing solver libraries
*/
[[nodiscard]] std::filesystem::path getCacheDir();
/**
* Initialize QuickJS runtime and context with solver libraries
*/
void initSolver();
/**
* Execute JavaScript code in QuickJS and return result
*/
[[nodiscard]] std::optional<std::string> executeJS(
std::string_view code,
std::string_view filename = "<script>");
/**
* 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);
/**
* Cleanup QuickJS resources
*/
void cleanupQuickJS();
/**
* Get cache directory for storing solver libraries
*/
[[nodiscard]] std::filesystem::path getCacheDir();
JSRuntime* runtime_ = nullptr;
JSContext* context_ = nullptr;
/**
* Execute JavaScript code in QuickJS and return result
*/
[[nodiscard]] std::optional<std::string>
executeJS(std::string_view code,
std::string_view filename = "<script>");
// Player JS code and extracted functions
std::string playerJsCode_;
std::string preprocessedPlayer_;
/**
* Cleanup QuickJS resources
*/
void cleanupQuickJS();
// State
bool initialized_ = false;
bool solverInitialized_ = false;
bool hasPlayerJs_ = false;
JSRuntime* runtime_ = nullptr;
JSContext* context_ = nullptr;
mutable std::mutex mutex_;
};
// 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
+60 -51
View File
@@ -1,64 +1,73 @@
#pragma once
#include <echoion/api.hpp>
#include "Database.hpp"
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <mutex>
#include <memory>
#include <vector>
namespace Echoion::Core {
namespace Echoion::Core
{
/**
* Manages user subscriptions to the bot's audio output
* Subscriptions are persisted to database and survive client reloads
* Uses unique client UID instead of session-specific client ID
*/
class SubscriptionManager {
public:
struct Subscriber {
std::string uid;
std::string nickname;
};
/**
* Manages user subscriptions to the bot's audio output
* Subscriptions are persisted to database and survive client reloads
* Uses unique client UID instead of session-specific client ID
*/
class SubscriptionManager
{
public:
SubscriptionManager();
~SubscriptionManager();
struct Subscriber {
std::string uid;
std::string nickname;
};
// Initialize and load subscriptions from database
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
void shutdown();
SubscriptionManager();
~SubscriptionManager();
// Subscription management (by UID)
bool subscribe(const std::string& uid, const std::string& nickname);
bool unsubscribe(const std::string& uid);
bool isSubscribed(const std::string& uid) const;
// Get all subscribed UIDs
std::vector<std::string> getSubscribedUids() const;
// Get all subscribers with info
std::vector<Subscriber> getSubscribers() const;
// Get subscriber nickname
std::optional<std::string> getSubscriberNickname(const std::string& uid) const;
// Update nickname for subscriber
bool updateNickname(const std::string& uid, const std::string& nickname);
// Check if anyone is subscribed
bool hasSubscribers() const;
// Get subscriber count
size_t getSubscriberCount() const;
// Clear all subscriptions
bool clearAll();
// Initialize and load subscriptions from database
Api::Result<void>
initialize(std::shared_ptr<Api::Database> database);
void shutdown();
private:
std::set<std::string> subscribedUids_;
mutable std::mutex mutex_;
std::shared_ptr<Api::Database> database_;
bool initialized_ = false;
};
// Subscription management (by UID)
bool subscribe(const std::string& uid, const std::string& nickname);
bool unsubscribe(const std::string& uid);
bool isSubscribed(const std::string& uid) const;
// Get all subscribed UIDs
std::vector<std::string> getSubscribedUids() const;
// Get all subscribers with info
std::vector<Subscriber> getSubscribers() const;
// Get subscriber nickname
std::optional<std::string>
getSubscriberNickname(const std::string& uid) const;
// Update nickname for subscriber
bool updateNickname(const std::string& uid,
const std::string& nickname);
// Check if anyone is subscribed
bool hasSubscribers() const;
// Get subscriber count
size_t getSubscriberCount() const;
// Clear all subscriptions
bool clearAll();
private:
std::set<std::string> subscribedUids_;
mutable std::mutex mutex_;
std::shared_ptr<Api::Database> database_;
bool initialized_ = false;
};
} // namespace Echoion::Core
+48 -40
View File
@@ -1,50 +1,58 @@
#pragma once
#include <echoion/api.hpp>
#include "NetworkClient.hpp"
#include <string>
#include <optional>
#include <mutex>
#include <unordered_map>
#include <NetworkTypes.hpp>
#include <Types.hpp>
#include <chrono>
#include <mutex>
#include <optional>
#include <string>
#include <unordered_map>
namespace Echoion::Core {
namespace Echoion::Core
{
// URL shortener service for faumaray.ru
class UrlShortener {
public:
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
~UrlShortener();
// URL shortener service for faumaray.ru
class UrlShortener
{
public:
// Shorten a YouTube URL via faumaray.ru
// Returns shortened URL in format: https://faumaray.ru/xxxxx
[[nodiscard]] Api::Result<std::string> shortenYouTubeUrl(std::string_view videoId);
// Shorten any URL via faumaray.ru
[[nodiscard]] Api::Result<std::string> shortenUrl(std::string_view originalUrl);
// Get cached shortened URL if available
[[nodiscard]] std::optional<std::string> getCachedUrl(std::string_view originalUrl) const;
// Clear the URL cache
void clearCache();
// Set cache TTL (default: 24 hours)
void setCacheTtl(std::chrono::hours ttl);
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
~UrlShortener();
private:
struct CacheEntry {
std::string shortenedUrl;
std::chrono::system_clock::time_point timestamp;
};
std::shared_ptr<NetworkClient> networkClient_;
mutable std::mutex cacheMutex_;
std::unordered_map<std::string, CacheEntry> cache_;
std::chrono::hours cacheTtl_{24};
// Clean expired entries from cache
void cleanExpiredCache();
};
// Shorten a YouTube URL via faumaray.ru
// Returns shortened URL in format: https://faumaray.ru/xxxxx
[[nodiscard]] Api::Result<std::string>
shortenYouTubeUrl(std::string_view videoId);
// Shorten any URL via faumaray.ru
[[nodiscard]] Api::Result<std::string>
shortenUrl(std::string_view originalUrl);
// Get cached shortened URL if available
[[nodiscard]] std::optional<std::string>
getCachedUrl(std::string_view originalUrl) const;
// Clear the URL cache
void clearCache();
// Set cache TTL (default: 24 hours)
void setCacheTtl(std::chrono::hours ttl);
private:
struct CacheEntry {
std::string shortenedUrl;
std::chrono::system_clock::time_point timestamp;
};
std::shared_ptr<NetworkClient> networkClient_;
mutable std::mutex cacheMutex_;
std::unordered_map<std::string, CacheEntry> cache_;
std::chrono::hours cacheTtl_{24};
// Clean expired entries from cache
void cleanExpiredCache();
};
} // namespace Echoion::Core
+131 -111
View File
@@ -3,8 +3,11 @@
#include "NetworkClient.hpp"
#include "UrlShortener.hpp"
#include "YtDlpManager.hpp"
#include <NetworkTypes.hpp>
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <YouTubeTypes.hpp>
#include <chrono>
#include <echoion/api.hpp>
#include <functional>
#include <future>
#include <memory>
@@ -15,142 +18,159 @@
#include <unordered_map>
#include <vector>
namespace Echoion::Core {
namespace Echoion::Core
{
class YouTubeClient {
public:
explicit YouTubeClient(std::shared_ptr<NetworkClient> networkClient);
~YouTubeClient();
class YouTubeClient
{
public:
// Initialize the client - downloads yt-dlp if needed
Api::Result<void> initialize();
void shutdown();
explicit YouTubeClient(
std::shared_ptr<NetworkClient> networkClient);
~YouTubeClient();
// 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();
// Initialize the client - downloads yt-dlp if needed
Api::Result<void> initialize();
void shutdown();
// Search for videos using YouTube Data API v3 (or yt-dlp as fallback)
[[nodiscard]] Api::Result<Api::SearchResult>
search(std::string_view query,
std::optional<std::string> pageToken = std::nullopt);
// Check if yt-dlp is available
[[nodiscard]] bool isAvailable() const;
// Get video details including stream URLs using yt-dlp
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
// Get yt-dlp version
[[nodiscard]] std::string getYtDlpVersion() const;
// Get video details asynchronously
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
getVideoInfoAsync(std::string_view videoId);
// Force update yt-dlp
Api::Result<void> updateYtDlp();
// Get multiple video details concurrently
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
getVideoInfoBatch(const std::vector<std::string>& videoIds);
// Search for videos using YouTube Data API v3 (or yt-dlp as
// fallback)
[[nodiscard]] Api::Result<Api::SearchResult>
search(std::string_view query,
std::optional<std::string> pageToken = std::nullopt);
// Get playlist videos - uses YouTube API v2 if key available, otherwise
// yt-dlp Then resolves each track individually via yt-dlp for full metadata
[[nodiscard]] Api::Result<Api::PlaylistInfo>
getPlaylist(std::string_view playlistId);
// Get video details including stream URLs using yt-dlp
[[nodiscard]] Api::Result<Api::TrackInfo>
getVideoInfo(std::string_view videoId);
// Get playlist videos asynchronously with concurrent track resolution
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
getPlaylistAsync(std::string_view playlistId);
// Get video details asynchronously
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
getVideoInfoAsync(std::string_view videoId);
// Stream playlist tracks with callback - calls trackCallback for each track
// as it is resolved, enabling immediate playback of first track
void getPlaylistStreaming(std::string_view playlistId,
std::function<void(Api::TrackInfo&&)> trackCallback,
std::function<void(size_t totalTracks)> onPlaylistInfo = nullptr,
std::function<void()> onComplete = nullptr);
// Get multiple video details concurrently
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
getVideoInfoBatch(const std::vector<std::string>& videoIds);
// 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);
// Get playlist videos - uses YouTube API v2 if key available,
// otherwise yt-dlp Then resolves each track individually via yt-dlp
// for full metadata
[[nodiscard]] Api::Result<Api::PlaylistInfo>
getPlaylist(std::string_view playlistId);
// Check if URL is a YouTube URL
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
// Get playlist videos asynchronously with concurrent track
// resolution
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
getPlaylistAsync(std::string_view playlistId);
// 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);
// Stream playlist tracks with callback - calls trackCallback for
// each track as it is resolved, enabling immediate playback of
// first track
void getPlaylistStreaming(
std::string_view playlistId,
std::function<void(Api::TrackInfo&&)>
trackCallback,
std::function<void(size_t totalTracks)> onPlaylistInfo =
nullptr,
std::function<void()> onComplete = nullptr);
// Configure proxy for yt-dlp
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
// 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);
// Set YouTube API key for enhanced playlist resolution (optional)
void setApiKey(const std::string& apiKey);
[[nodiscard]] bool hasApiKey() const;
// Check if URL is a YouTube URL
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
// Configure concurrent resolution settings
void setMaxConcurrentResolutions(size_t max);
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
// Get stream URL for a video (used by MusicManager)
[[nodiscard]] Api::Result<std::string>
getStreamUrl(std::string_view videoId);
// Enable/disable URL shortening for track links
void setUrlShorteningEnabled(bool enabled);
[[nodiscard]] bool isUrlShorteningEnabled() const;
// Get best audio stream URL using yt-dlp
[[nodiscard]] Api::Result<std::string>
getAudioStreamUrl(std::string_view videoId);
private:
// Configure cookie options for yt-dlp
void setCookiesPath(const std::string& path);
void setCookiesFromBrowser(const std::string& browser);
// Internal search implementations
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithApi(std::string_view query,
const std::optional<std::string>& pageToken);
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithYtDlp(std::string_view query,
const std::optional<std::string>& pageToken);
// Configure proxy for yt-dlp
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig>
getProxyConfig() const;
// Fetch video durations for search results (batch API call)
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
const std::vector<std::string>& videoIds);
// Set YouTube API key for enhanced playlist resolution (optional)
void setApiKey(const std::string& apiKey);
[[nodiscard]] bool hasApiKey() const;
// Parse ISO 8601 duration string
[[nodiscard]] static std::chrono::seconds
parseIso8601Duration(const std::string& duration);
// Configure concurrent resolution settings
void setMaxConcurrentResolutions(size_t max);
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
// URL encode/decode helpers
[[nodiscard]] static std::string urlEncode(std::string_view value);
[[nodiscard]] static std::string decodeHtmlEntities(std::string_view value);
// Enable/disable URL shortening for track links
void setUrlShorteningEnabled(bool enabled);
[[nodiscard]] bool isUrlShorteningEnabled() const;
// Internal methods for playlist resolution
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
fetchPlaylistItems(std::string_view playlistId);
[[nodiscard]] Api::Result<Api::TrackInfo>
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
private:
// Build YouTube API v3 URL for playlist items
[[nodiscard]] std::string buildPlaylistApiUrl(
std::string_view playlistId,
const std::optional<std::string>& pageToken = std::nullopt) const;
// Internal search implementations
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithApi(std::string_view query,
const std::optional<std::string>& pageToken);
[[nodiscard]] Api::Result<Api::SearchResult>
searchWithYtDlp(std::string_view query,
const std::optional<std::string>& pageToken);
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YtDlpManager> ytDlpManager_;
std::unique_ptr<UrlShortener> urlShortener_;
// Fetch video durations for search results (batch API call)
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
const std::vector<std::string>& videoIds);
std::atomic<bool> initialized_{false};
mutable std::mutex mutex_;
// Parse ISO 8601 duration string
[[nodiscard]] static std::chrono::seconds
parseIso8601Duration(const std::string& duration);
// Configuration
std::optional<std::string> apiKey_;
mutable std::mutex configMutex_;
size_t maxConcurrentResolutions_ = 4;
bool urlShorteningEnabled_ = true;
// URL encode/decode helpers
[[nodiscard]] static std::string urlEncode(std::string_view value);
[[nodiscard]] static std::string
decodeHtmlEntities(std::string_view value);
// Populate shortened URLs for tracks
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
void populateShortenedUrl(Api::TrackInfo& track);
};
// Internal methods for playlist resolution
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
fetchPlaylistItems(std::string_view playlistId);
[[nodiscard]] Api::Result<Api::TrackInfo>
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
// Build YouTube API v3 URL for playlist items
[[nodiscard]] std::string buildPlaylistApiUrl(
std::string_view playlistId,
const std::optional<std::string>& pageToken =
std::nullopt) const;
std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<YtDlpManager> ytDlpManager_;
std::unique_ptr<UrlShortener> urlShortener_;
std::atomic<bool> initialized_{false};
mutable std::mutex mutex_;
// Configuration
std::optional<std::string> apiKey_;
mutable std::mutex configMutex_;
size_t maxConcurrentResolutions_ = 4;
bool urlShorteningEnabled_ = true;
// Populate shortened URLs for tracks
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
void populateShortenedUrl(Api::TrackInfo& track);
};
} // namespace Echoion::Core
+105 -101
View File
@@ -1,9 +1,11 @@
#pragma once
#include "NetworkClient.hpp"
#include <TrackTypes.hpp>
#include <Types.hpp>
#include <YouTubeTypes.hpp>
#include <atomic>
#include <condition_variable>
#include <echoion/api.hpp>
#include <filesystem>
#include <future>
#include <mutex>
@@ -12,7 +14,8 @@
#include <thread>
#include <vector>
namespace Echoion::Core {
namespace Echoion::Core
{
struct YtDlpResult {
std::string output;
@@ -21,121 +24,122 @@ namespace Echoion::Core {
std::chrono::milliseconds executionTime;
};
class YtDlpManager {
public:
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
~YtDlpManager();
class YtDlpManager
{
public:
// 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();
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
~YtDlpManager();
// Execute yt-dlp with given arguments and return output (synchronous)
[[nodiscard]] std::string
execute(const std::vector<std::string>& args) const;
// Initialize - checks for yt-dlp and downloads if needed
Api::Result<void> initialize();
// Execute yt-dlp asynchronously and return a future
[[nodiscard]] std::future<YtDlpResult>
executeAsync(const std::vector<std::string>& args);
// Get the path to the yt-dlp executable
[[nodiscard]] std::filesystem::path getExecutablePath() const;
// Execute multiple yt-dlp commands concurrently
[[nodiscard]] std::vector<YtDlpResult>
executeBatch(const std::vector<std::vector<std::string>>& argsList);
// Check if yt-dlp is available
[[nodiscard]] bool isAvailable() 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;
// Get yt-dlp version
[[nodiscard]] std::string getVersion() const;
// Set proxy configuration for yt-dlp
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
// Force update yt-dlp to latest version
Api::Result<void> update();
// Configure thread pool size for async operations (default: 4)
void setThreadPoolSize(size_t size);
[[nodiscard]] size_t getThreadPoolSize() const;
// Execute yt-dlp with given arguments and return output
// (synchronous)
[[nodiscard]] std::string
execute(const std::vector<std::string>& args) 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;
// Execute yt-dlp asynchronously and return a future
[[nodiscard]] std::future<YtDlpResult>
executeAsync(const std::vector<std::string>& args);
// Internal execute implementation
[[nodiscard]] YtDlpResult
executeInternal(const std::vector<std::string>& args) const;
// Execute multiple yt-dlp commands concurrently
[[nodiscard]] std::vector<YtDlpResult> executeBatch(
const std::vector<std::vector<std::string>>& argsList);
// Build the full command with all options
[[nodiscard]] std::string
buildCommand(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 proxy arguments for yt-dlp command
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
// Get cookie arguments for yt-dlp command
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
// Escape shell argument
[[nodiscard]] static std::string escapeArg(const std::string& arg);
// Set proxy configuration for yt-dlp
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
[[nodiscard]] std::optional<Api::ProxyConfig>
getProxyConfig() const;
// Thread pool for async operations
void startThreadPool();
void stopThreadPool();
void workerThread();
// Configure thread pool size for async operations (default: 4)
void setThreadPoolSize(size_t size);
[[nodiscard]] size_t getThreadPoolSize() 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_;
private:
// Proxy configuration
std::optional<Api::ProxyConfig> proxyConfig_;
mutable std::mutex proxyMutex_;
// Get the storage directory for yt-dlp
[[nodiscard]] std::filesystem::path getStorageDir() const;
// Thread pool for async operations
size_t threadPoolSize_ = 4;
std::vector<std::jthread> threadPool_;
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
std::mutex taskMutex_;
std::condition_variable taskCv_;
std::atomic<bool> stopThreads_{false};
// Get the executable name based on platform
[[nodiscard]] std::string getExecutableName() const;
// 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";
};
// 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;
// Internal execute implementation
[[nodiscard]] YtDlpResult
executeInternal(const std::vector<std::string>& args) const;
// Get proxy arguments for yt-dlp command
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
// Thread pool for async operations
void startThreadPool();
void stopThreadPool();
void workerThread();
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_;
// Proxy configuration
std::optional<Api::ProxyConfig> proxyConfig_;
mutable std::mutex proxyMutex_;
// Thread pool for async operations
size_t threadPoolSize_ = 4;
std::vector<std::jthread> threadPool_;
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
std::mutex taskMutex_;
std::condition_variable taskCv_;
std::atomic<bool> stopThreads_{false};
// 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
+44 -32
View File
@@ -4,43 +4,55 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class ClearCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
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;
}
std::string_view getDescription() const override {
return "Clears all tracks from the queue.";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::string_view getDescription() const override
{
return "Clears all tracks from the queue.";
}
std::vector<std::string_view> getAliases() const override {
return {"clr", "empty"};
}
};
CommandCategory getCategory() const override
{
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override
{
return {"clr", "empty"};
}
};
} // namespace Echoion::Core
+90 -86
View File
@@ -1,106 +1,110 @@
#pragma once
#include <echoion/api.hpp>
#include "echoion/core/MusicManager.hpp"
#include <ConfigTypes.hpp>
#include <Types.hpp>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include <memory>
#include <functional>
#include "echoion/core/MusicManager.hpp"
namespace Echoion::Core {
namespace Echoion::Core
{
class MusicManager;
class MusicManager;
enum class CommandCategory {
Music,
Queue,
Playback,
Utility,
Admin
};
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";
}
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 prefix;
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 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;
/**
* @brief Interface that all commands must implement.
*/
class Command {
public:
virtual ~Command() = default;
// Dependencies
std::weak_ptr<MusicManager> musicManager;
/**
* @brief The logic of the command.
*/
virtual void execute(const CommandContext& ctx) = 0;
// Reply callback - set by CommandManager
std::function<void(std::string_view)> replyCallback;
/**
* @brief Returns the description used for help generation.
*/
virtual std::string_view getDescription() const = 0;
// Helper to reply to the user
void reply(std::string_view message) const
{
if (replyCallback) {
replyCallback(message);
}
}
};
/**
* @brief Returns usage syntax (e.g., "<url>").
*/
virtual std::string_view getUsage() const { return ""; }
/**
* @brief Interface that all commands must implement.
*/
class Command
{
public:
/**
* @brief Returns the command category for grouping in help.
*/
virtual CommandCategory getCategory() const {
return CommandCategory::Utility;
}
virtual ~Command() = default;
/**
* @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; }
};
/**
* @brief The logic of the command.
*/
virtual void execute(const CommandContext& ctx) = 0;
using CommandPtr = std::shared_ptr<Command>;
/**
* @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
+18 -17
View File
@@ -1,28 +1,29 @@
#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 "Command.hpp"
#include "MoveCommand.hpp"
#include "ShuffleCommand.hpp"
#include "RepeatCommand.hpp"
#include "PlaylistCommand.hpp"
#include "NowPlayingCommand.hpp"
#include "SearchCommand.hpp"
#include "PauseCommand.hpp"
#include "PlayCommand.hpp"
#include "PlaylistCommand.hpp"
#include "QueueCommand.hpp"
#include "ReloadCommand.hpp"
#include "ReloadConfigCommand.hpp"
#include "RemoveCommand.hpp"
#include "RepeatCommand.hpp"
#include "ResumeCommand.hpp"
#include "RpcInfoCommand.hpp"
#include "SearchCommand.hpp"
#include "SeekCommand.hpp"
#include "SelectCommand.hpp"
#include "ShuffleCommand.hpp"
#include "SkipCommand.hpp"
#include "StopCommand.hpp"
#include "SubscribeCommand.hpp"
#include "UnsubscribeCommand.hpp"
#include "SubscribersCommand.hpp"
#include "UnsubscribeIdCommand.hpp"
#include "UnsubscribeAllCommand.hpp"
#include "UnsubscribeCommand.hpp"
#include "UnsubscribeIdCommand.hpp"
#include "VolumeCommand.hpp"
+80 -63
View File
@@ -2,81 +2,98 @@
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
#include <format>
namespace Echoion::Core {
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;
}
class MoveCommand : public Command
{
public:
if (ctx.args.empty()) {
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)");
return;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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;
}
if (ctx.args.empty()) {
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 "
"(moves track 5 to position 1)");
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);
// Parse arguments: from and to positions
uint32_t from = 0, to = 0;
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 spacePos = ctx.args.find(' ');
if (spacePos == std::string::npos) {
ctx.reply("Please provide both from and to positions.");
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;
}
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);
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.");
}
}
if (result1.ec != std::errc() ||
result2.ec != std::errc() || from == 0 || to == 0) {
ctx.reply("Please provide valid position numbers "
"(starting from 1).");
return;
}
std::string_view getDescription() const override {
return "Moves a track to a different position in the queue.";
}
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));
std::string_view getUsage() const override {
return "<from> <to>";
}
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;
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
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::vector<std::string_view> getAliases() const override {
return {"mv"};
}
};
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
@@ -4,95 +4,113 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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(std::format(
"Nothing is currently playing. Add something with {}play !",
ctx.prefix));
return;
}
const auto& track = current->value();
const auto& trackInfo = track.track;
std::string displayText = trackInfo.title;
if (!trackInfo.artist.empty()) {
displayText =
std::format("{} by {}", trackInfo.title, trackInfo.artist);
}
std::string linkText = trackInfo.shortenedUrl.has_value() &&
!trackInfo.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*trackInfo.shortenedUrl)
: displayText;
std::string msg = std::format("\xf0\x9f\x8e\xb5 {}", linkText);
// Show current position / total duration
auto playbackState = manager->getPlaybackState();
if (playbackState && playbackState->currentTrack.has_value() &&
trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
auto position = playbackState->position;
msg += std::format(" [{}/{}]",
formatDuration(position),
formatDuration(*trackInfo.duration));
} else if (trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
msg += std::format(" [{}]", formatDuration(*trackInfo.duration));
}
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"};
}
private:
static std::string formatDuration(std::chrono::milliseconds duration)
class NowPlayingCommand : public Command
{
auto totalSeconds = duration.count() / 1000;
auto hours = totalSeconds / 3600;
auto mins = (totalSeconds % 3600) / 60;
auto secs = totalSeconds % 60;
public:
if (hours > 0) {
return std::format("{}:{:02}:{:02}", hours, mins, secs);
}
return std::format("{}:{:02}", mins, secs);
}
};
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(std::format("Nothing is currently playing. "
"Add something with {}play !",
ctx.prefix));
return;
}
const auto& track = current->value();
const auto& trackInfo = track.track;
std::string displayText = trackInfo.title;
if (!trackInfo.artist.empty()) {
displayText = std::format("{} by {}", trackInfo.title,
trackInfo.artist);
}
std::string linkText =
trackInfo.shortenedUrl.has_value() &&
!trackInfo.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*trackInfo.shortenedUrl)
: displayText;
std::string msg =
std::format("\xf0\x9f\x8e\xb5 {}", linkText);
// Show current position / total duration
auto playbackState = manager->getPlaybackState();
if (playbackState &&
playbackState->currentTrack.has_value() &&
trackInfo.duration.has_value() &&
trackInfo.duration->count() > 0) {
auto position = playbackState->position;
msg += std::format(" [{}/{}]",
formatDuration(position),
formatDuration(*trackInfo.duration));
} else if (trackInfo.duration.has_value() &&
trackInfo.duration->count() > 0) {
msg += std::format(" [{}]",
formatDuration(*trackInfo.duration));
}
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"};
}
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
+50 -37
View File
@@ -4,48 +4,61 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class PauseCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
auto result = manager->pause();
if (!result) {
ECHOION_LOG_ERROR(
std::format("Pause command failed: {}",
result.error().message));
std::string_view getDescription() const override {
return "Pauses the current playback.";
}
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;
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
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::vector<std::string_view> getAliases() const override {
return {};
}
};
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
+178 -150
View File
@@ -4,158 +4,186 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
// result contains the track title
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;
}
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText =
std::format("{} by {}", track.title, track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
ctx.reply(std::format("Added to queue: {}", linkText));
return;
}
// Multiple results - store and show list
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
std::string msg = std::format("\xf0\x9f\x94\x8d Multiple results "
"found. Use {}select <number>:\n",
ctx.prefix);
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
const auto& track = searchResult->tracks[i];
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText =
std::format("{} by {}", track.title, track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
msg += std::format("{}. {}", i + 1, linkText);
if (track.duration.has_value()) {
msg +=
std::format(" [{}]", formatDuration(*track.duration));
}
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"};
}
private:
static std::string formatDuration(std::chrono::milliseconds duration)
class PlayCommand : public Command
{
auto totalSeconds = duration.count() / 1000;
auto hours = totalSeconds / 3600;
auto mins = (totalSeconds % 3600) / 60;
auto secs = totalSeconds % 60;
public:
if (hours > 0) {
return std::format("{}:{:02}:{:02}", hours, mins, secs);
}
return std::format("{}:{:02}", mins, secs);
}
};
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;
}
// result contains the track title
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;
}
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText = std::format("{} by {}", track.title,
track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
ctx.reply(std::format("Added to queue: {}", linkText));
return;
}
// Multiple results - store and show list
manager->storePendingSearch(ctx.clientId,
searchResult->tracks);
std::string msg =
std::format("\xf0\x9f\x94\x8d Multiple results "
"found. Use {}select <number>:\n",
ctx.prefix);
for (size_t i = 0; i < searchResult->tracks.size() && i < 5;
++i) {
const auto& track = searchResult->tracks[i];
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText = std::format("{} by {}", track.title,
track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
msg += std::format("{}. {}", i + 1, linkText);
if (track.duration.has_value()) {
msg += std::format(" [{}]",
formatDuration(*track.duration));
}
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"};
}
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
@@ -5,76 +5,97 @@
#include <format>
#include <sstream>
namespace Echoion::Core {
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;
}
class PlaylistCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
return;
}
if (playlists->empty()) {
ctx.reply("No playlists available.");
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;
}
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());
}
if (playlists->empty()) {
ctx.reply("No playlists available.");
return;
}
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;
}
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(std::format("Loading playlist '{}'... Tracks will be added to the queue as they are resolved.", 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.");
}
}
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));
std::string_view getDescription() const override {
return "Lists or loads a playlist.";
}
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;
}
std::string_view getUsage() const override {
return "[playlist name]";
}
ctx.reply(std::format(
"Loading playlist '{}'... Tracks will be added to "
"the queue as they are resolved.",
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Music;
}
std::string_view getDescription() const override
{
return "Lists or loads a playlist.";
}
std::vector<std::string_view> getAliases() const override {
return {"pl"};
}
};
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
+170 -159
View File
@@ -5,189 +5,200 @@
#include <format>
#include <sstream>
namespace Echoion::Core {
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;
}
class QueueCommand : public Command
{
public:
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;
}
// Parse page number from args (default to 1)
int page = 1;
if (!ctx.args.empty()) {
void execute(const CommandContext& ctx) override
{
try {
page = std::stoi(std::string(ctx.args));
if (page < 1) {
page = 1;
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
return;
}
} catch (...) {
page = 1;
}
}
constexpr int ITEMS_PER_PAGE = 10;
int totalPages =
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
ITEMS_PER_PAGE;
if (totalPages == 0) {
totalPages = 1;
}
auto current = manager->getCurrentTrack();
auto queue = manager->getQueue();
auto state = manager->getPlaybackState();
// Clamp page to valid range
if (page > totalPages) {
page = totalPages;
}
if (!queue) {
ECHOION_LOG_ERROR(std::format(
"Queue command failed: {}", queue.error().message));
ctx.reply("Couldn't get queue information.");
return;
}
int startIdx = (page - 1) * ITEMS_PER_PAGE;
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
static_cast<int>(queue->size()));
// Parse page number from args (default to 1)
int page = 1;
if (!ctx.args.empty()) {
try {
page = std::stoi(std::string(ctx.args));
if (page < 1) {
page = 1;
}
} catch (...) {
page = 1;
}
}
std::stringstream msg;
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
<< totalPages << ")\n";
constexpr int ITEMS_PER_PAGE = 10;
int totalPages =
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
ITEMS_PER_PAGE;
if (totalPages == 0) {
totalPages = 1;
}
// Current track
if (current && current->has_value()) {
const auto& track = current->value();
const auto& trackInfo = track.track;
// Clamp page to valid range
if (page > totalPages) {
page = totalPages;
}
// Build time display: [current/total] or [total]
std::string timeStr;
if (trackInfo.duration.has_value() &&
trackInfo.duration->count() > 0) {
if (state) {
timeStr =
std::format(" [{}/{}]",
formatDuration(state->position),
formatDuration(*trackInfo.duration));
int startIdx = (page - 1) * ITEMS_PER_PAGE;
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
static_cast<int>(queue->size()));
std::stringstream msg;
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
<< totalPages << ")\n";
// Current track
if (current && current->has_value()) {
const auto& track = current->value();
const auto& trackInfo = track.track;
// Build time display: [current/total] or [total]
std::string timeStr;
if (trackInfo.duration.has_value() &&
trackInfo.duration->count() > 0) {
if (state) {
timeStr = std::format(
" [{}/{}]",
formatDuration(state->position),
formatDuration(*trackInfo.duration));
} else {
timeStr = std::format(
" [{}]",
formatDuration(*trackInfo.duration));
}
}
std::string displayText = trackInfo.title;
if (!trackInfo.artist.empty()) {
displayText = std::format(
"{} by {}", trackInfo.title, trackInfo.artist);
}
std::string linkText =
trackInfo.shortenedUrl.has_value() &&
!trackInfo.shortenedUrl->empty()
? std::format("[{}]({}){}", displayText,
*trackInfo.shortenedUrl, timeStr)
: displayText + timeStr;
msg << std::format("\n**Now Playing:** {}\n", linkText);
}
// Queue
if (queue->empty()) {
msg << std::format(
"\nThe queue is empty. Add songs with {}play !",
ctx.prefix);
} else {
timeStr = std::format(
" [{}]", formatDuration(*trackInfo.duration));
}
}
std::string displayText = trackInfo.title;
if (!trackInfo.artist.empty()) {
displayText = std::format("{} by {}", trackInfo.title,
trackInfo.artist);
}
std::string linkText =
trackInfo.shortenedUrl.has_value() &&
!trackInfo.shortenedUrl->empty()
? std::format("[{}]({}){}", displayText,
*trackInfo.shortenedUrl, timeStr)
: displayText + timeStr;
msg << std::format("\n**Now Playing:** {}\n", linkText);
}
// Queue
if (queue->empty()) {
msg << std::format(
"\nThe queue is empty. Add songs with {}play !",
ctx.prefix);
} else {
msg << std::format("\n**Up Next ({} tracks):**\n",
queue->size());
for (int i = startIdx; i < endIdx; ++i) {
const auto& entry = (*queue)[i];
const auto& trackInfo = entry.track;
std::string displayText = trackInfo.title;
if (!trackInfo.artist.empty()) {
displayText =
std::format("{} [{}] by {}", trackInfo.title,
formatDuration(*trackInfo.duration),
trackInfo.artist);
}
std::string linkText =
trackInfo.shortenedUrl.has_value() &&
!trackInfo.shortenedUrl->empty()
? std::format("[{}]({}) [{}]", displayText,
msg << std::format("\n**Up Next ({} tracks):**\n",
queue->size());
for (int i = startIdx; i < endIdx; ++i) {
const auto& entry = (*queue)[i];
const auto& trackInfo = entry.track;
std::string displayText = trackInfo.title;
if (!trackInfo.artist.empty()) {
displayText =
std::format("{} by {}", trackInfo.title,
trackInfo.artist);
}
std::string linkText =
trackInfo.shortenedUrl.has_value() &&
!trackInfo.shortenedUrl->empty()
? std::format(
"[{}]({}) [{}]", displayText,
*trackInfo.shortenedUrl,
formatDuration(*trackInfo.duration))
: displayText;
msg << std::format("{}. {}", i + 1, linkText);
if (!entry.addedBy.empty()) {
msg << std::format(" (by {})", entry.addedBy);
: displayText;
msg << std::format("{}. {}", i + 1, linkText);
if (!entry.addedBy.empty()) {
msg << std::format(" (by {})", entry.addedBy);
}
msg << "\n";
}
if (totalPages > 1) {
msg << std::format(
"\nUse {}queue <page> to see more "
"(page {} of {})",
ctx.prefix, page, totalPages);
}
}
msg << "\n";
}
if (totalPages > 1) {
msg << std::format("\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));
}
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.");
}
}
// 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));
std::string_view getDescription() const override
{
return "Shows the current queue and playback status.";
}
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 getUsage() const override { return "[page]"; }
std::string_view getDescription() const override
{
return "Shows the current queue and playback status.";
}
CommandCategory getCategory() const override
{
return CommandCategory::Queue;
}
std::string_view getUsage() const override { return "[page]"; }
std::vector<std::string_view> getAliases() const override
{
return {"q", "list"};
}
CommandCategory getCategory() const override
{
return CommandCategory::Queue;
}
private:
std::vector<std::string_view> getAliases() const override
{
return {"q", "list"};
}
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;
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);
}
};
if (hours > 0) {
return std::format("{}:{:02}:{:02}", hours, mins, secs);
}
return std::format("{}:{:02}", mins, secs);
}
};
} // namespace Echoion::Core
+28 -21
View File
@@ -4,31 +4,38 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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.");
}
class ReloadCommand : public Command
{
public:
std::string_view getDescription() const override {
return "Shows information about reloading the bot.";
}
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.");
}
CommandCategory getCategory() const override {
return CommandCategory::Admin;
}
std::string_view getDescription() const override
{
return "Shows information about reloading the bot.";
}
bool requiresAdmin() const override {
return true;
}
CommandCategory getCategory() const override
{
return CommandCategory::Admin;
}
std::vector<std::string_view> getAliases() const override {
return {"restart", "r"};
}
};
bool requiresAdmin() const override { return true; }
std::vector<std::string_view> getAliases() const override
{
return {"restart", "r"};
}
};
} // namespace Echoion::Core
@@ -1,42 +1,52 @@
#pragma once
#include "Command.hpp"
#include "echoion/core/Core.hpp" // For Core::reloadConfig
#include "echoion/core/Logger.hpp"
#include "echoion/core/Core.hpp" // For Core::reloadConfig
#include <format>
namespace Echoion::Core {
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.");
}
}
class ReloadConfigCommand : public Command
{
public:
std::string_view getDescription() const override {
return "Reloads the bot configuration from file.";
}
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.");
CommandCategory getCategory() const override {
return CommandCategory::Admin;
}
// 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.");
}
}
bool requiresAdmin() const override {
return true;
}
std::string_view getDescription() const override
{
return "Reloads the bot configuration from file.";
}
std::vector<std::string_view> getAliases() const override {
return {"reloadcfg", "rlcfg"};
}
};
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
+72 -55
View File
@@ -2,71 +2,88 @@
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
#include <format>
namespace Echoion::Core {
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;
}
class RemoveCommand : public Command
{
public:
if (ctx.args.empty()) {
ctx.reply(std::format("Usage: remove <position>\nUse {}queue "
"to see track positions.",
ctx.prefix));
return;
}
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 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;
}
if (ctx.args.empty()) {
ctx.reply(
std::format("Usage: remove <position>\nUse {}queue "
"to see track positions.",
ctx.prefix));
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;
}
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;
}
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.");
}
}
auto remResult = manager->removeFromQueue(
position - 1); // Convert to 0-based
if (!remResult) {
ECHOION_LOG_ERROR(
std::format("Remove command failed: {}",
remResult.error().message));
std::string_view getDescription() const override {
return "Removes a track from the queue by position.";
}
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;
}
std::string_view getUsage() const override {
return "<position>";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::string_view getDescription() const override
{
return "Removes a track from the queue by position.";
}
std::vector<std::string_view> getAliases() const override {
return {"rm", "delete", "del"};
}
};
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
+44 -32
View File
@@ -4,43 +4,55 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class RepeatCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
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;
}
std::string_view getDescription() const override {
return "Toggles repeat mode for the current track.";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::string_view getDescription() const override
{
return "Toggles repeat mode for the current track.";
}
std::vector<std::string_view> getAliases() const override {
return {"loop"};
}
};
CommandCategory getCategory() const override
{
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override
{
return {"loop"};
}
};
} // namespace Echoion::Core
+50 -37
View File
@@ -4,48 +4,61 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class ResumeCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
auto result = manager->resume();
if (!result) {
ECHOION_LOG_ERROR(
std::format("Resume command failed: {}",
result.error().message));
std::string_view getDescription() const override {
return "Resumes the paused playback.";
}
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;
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
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::vector<std::string_view> getAliases() const override {
return {"unpause", "continue"};
}
};
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,28 @@
#pragma once
#include "Command.hpp"
namespace Echoion::Core
{
class RpcInfoCommand : public Command
{
public:
void execute(const CommandContext& ctx) override;
std::string_view getDescription() const override
{
return "Get RPC server connection information";
}
std::string_view getUsage() const override { return ""; }
CommandCategory getCategory() const override
{
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override
{
return {"rpc", "api", "remote"};
}
};
} // namespace Echoion::Core
+118 -102
View File
@@ -5,110 +5,126 @@
#include <format>
#include <sstream>
namespace Echoion::Core {
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];
// Format as [Title by Artist](shortenedUrl) with duration
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText =
std::format("{} by {}", track.title, track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
msg << std::format("{}. {}", i + 1, linkText);
if (track.duration.has_value()) {
msg << std::format(" [{}]",
formatDuration(*track.duration));
}
msg << "\n";
}
msg << std::format("\nUse {}select <number> to play a result.",
ctx.prefix);
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"};
}
private:
static std::string formatDuration(std::chrono::milliseconds duration)
class SearchCommand : public Command
{
auto totalSeconds = duration.count() / 1000;
auto hours = totalSeconds / 3600;
auto mins = (totalSeconds % 3600) / 60;
auto secs = totalSeconds % 60;
public:
if (hours > 0) {
return std::format("{}:{:02}:{:02}", hours, mins, secs);
}
return std::format("{}:{:02}", mins, secs);
}
};
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];
// Format as [Title by Artist](shortenedUrl) with
// duration
std::string displayText = track.title;
if (!track.artist.empty()) {
displayText = std::format("{} by {}", track.title,
track.artist);
}
std::string linkText =
track.shortenedUrl.has_value() &&
!track.shortenedUrl->empty()
? std::format("[{}]({})", displayText,
*track.shortenedUrl)
: displayText;
msg << std::format("{}. {}", i + 1, linkText);
if (track.duration.has_value()) {
msg << std::format(" [{}]",
formatDuration(*track.duration));
}
msg << "\n";
}
msg << std::format(
"\nUse {}select <number> to play a result.",
ctx.prefix);
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"};
}
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
+128 -104
View File
@@ -2,123 +2,147 @@
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <chrono>
#include <charconv>
#include <chrono>
#include <format>
namespace Echoion::Core {
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;
}
class SeekCommand : public Command
{
public:
if (ctx.args.empty()) {
ctx.reply("Usage: seek <+/-seconds>\nExamples:\n seek +30 (skip forward 30s)\n seek -10 (skip back 10s)\n seek 60 (jump to 1 minute mark)");
return;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
return;
}
// Parse the seek argument (supports +30, -10, or absolute 60)
std::string_view arg = ctx.args;
bool relative = false;
bool forward = true;
if (arg.starts_with('+')) {
relative = true;
forward = true;
arg = arg.substr(1);
} else if (arg.starts_with('-')) {
relative = true;
forward = false;
arg = arg.substr(1);
}
if (ctx.args.empty()) {
ctx.reply(
"Usage: seek <+/-seconds>\nExamples:\n seek +30 "
"(skip forward 30s)\n seek -10 (skip back 10s)\n "
"seek 60 (jump to 1 minute mark)");
return;
}
int seconds = 0;
auto parseResult = std::from_chars(arg.data(),
arg.data() + arg.size(),
seconds);
if (parseResult.ec != std::errc() || seconds < 0) {
ctx.reply("Please provide a valid number of seconds.\nExamples: seek +30, seek -10, seek 60");
return;
}
// Parse the seek argument (supports +30, -10, or absolute
// 60)
std::string_view arg = ctx.args;
bool relative = false;
bool forward = true;
std::chrono::milliseconds targetPosition;
std::string positionStr;
if (arg.starts_with('+')) {
relative = true;
forward = true;
arg = arg.substr(1);
} else if (arg.starts_with('-')) {
relative = true;
forward = false;
arg = arg.substr(1);
}
if (relative) {
// Get current position from playback state
auto state = manager->getPlaybackState();
if (!state) {
ctx.reply("Unable to get current playback position.");
return;
}
auto currentPos = state->position;
if (forward) {
targetPosition = currentPos + std::chrono::seconds(seconds);
positionStr = std::format("+{}s", seconds);
} else {
// Seek backward
if (currentPos.count() < seconds * 1000) {
targetPosition = std::chrono::milliseconds(0);
} else {
targetPosition = currentPos - std::chrono::seconds(seconds);
}
positionStr = std::format("-{}s", seconds);
}
} else {
// Absolute seek (legacy behavior)
targetPosition = std::chrono::seconds(seconds);
auto mins = seconds / 60;
auto secs = seconds % 60;
positionStr = std::format("{}:{:02}", mins, secs);
}
int seconds = 0;
auto parseResult = std::from_chars(
arg.data(), arg.data() + arg.size(), seconds);
if (parseResult.ec != std::errc() || seconds < 0) {
ctx.reply(
"Please provide a valid number of "
"seconds.\nExamples: seek +30, seek -10, seek 60");
return;
}
auto result = manager->seek(targetPosition);
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;
}
std::chrono::milliseconds targetPosition;
std::string positionStr;
if (relative) {
ctx.reply(std::format("Seeked {} from current position.", positionStr));
} else {
ctx.reply(std::format("Seeked to position {}.", positionStr));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format("Seek command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
if (relative) {
// Get current position from playback state
auto state = manager->getPlaybackState();
if (!state) {
ctx.reply(
"Unable to get current playback position.");
return;
}
std::string_view getDescription() const override {
return "Seeks to a position in the current track. Use +seconds to skip forward, -seconds to skip backward.";
}
auto currentPos = state->position;
if (forward) {
targetPosition =
currentPos + std::chrono::seconds(seconds);
positionStr = std::format("+{}s", seconds);
} else {
// Seek backward
if (currentPos.count() < seconds * 1000) {
targetPosition = std::chrono::milliseconds(0);
} else {
targetPosition =
currentPos - std::chrono::seconds(seconds);
}
positionStr = std::format("-{}s", seconds);
}
} else {
// Absolute seek (legacy behavior)
targetPosition = std::chrono::seconds(seconds);
auto mins = seconds / 60;
auto secs = seconds % 60;
positionStr = std::format("{}:{:02}", mins, secs);
}
std::string_view getUsage() const override {
return "<+/-seconds>";
}
auto result = manager->seek(targetPosition);
if (!result) {
ECHOION_LOG_ERROR(std::format("Seek command failed: {}",
result.error().message));
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
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;
}
std::vector<std::string_view> getAliases() const override {
return {"jump"};
}
};
if (relative) {
ctx.reply(std::format(
"Seeked {} from current position.", positionStr));
} else {
ctx.reply(
std::format("Seeked to position {}.", positionStr));
}
} 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. Use +seconds "
"to skip forward, -seconds to skip backward.";
}
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
+75 -60
View File
@@ -2,76 +2,91 @@
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
#include <format>
namespace Echoion::Core {
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;
}
class SelectCommand : public Command
{
public:
if (ctx.args.empty()) {
ctx.reply("Usage: select <number>\nSelect a track from your last search results.");
return;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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;
}
if (ctx.args.empty()) {
ctx.reply("Usage: select <number>\nSelect a track from "
"your last search results.");
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(std::format("No search results found. Use {}play "
"<query> to search first.",
ctx.prefix));
} else {
ctx.reply("Couldn't select that track. Please try again.");
// 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(std::format(
"No search results found. Use {}play "
"<query> to search first.",
ctx.prefix));
} 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.");
}
return;
}
}
ctx.reply(*selectResult);
std::string_view getDescription() const override
{
return "Selects a track from your search results.";
}
} 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 getUsage() const override { return "<number>"; }
std::string_view getDescription() const override {
return "Selects a track from your search results.";
}
CommandCategory getCategory() const override
{
return CommandCategory::Music;
}
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"};
}
};
std::vector<std::string_view> getAliases() const override
{
return {"sel", "pick", "choose"};
}
};
} // namespace Echoion::Core
@@ -4,43 +4,48 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class ShuffleCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
// Actually shuffle the queue (not just toggle mode)
manager->shuffleQueue();
std::string_view getDescription() const override {
return "Toggles shuffle mode for the queue.";
}
ctx.reply("\xf0\x9f\x94\x80 Queue shuffled!");
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(
std::format("Shuffle command exception: {}", e.what()));
ctx.reply("Something went wrong. Please try again.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Queue;
}
std::string_view getDescription() const override
{
return "Toggles shuffle mode for the queue.";
}
std::vector<std::string_view> getAliases() const override {
return {"random"};
}
};
CommandCategory getCategory() const override
{
return CommandCategory::Queue;
}
std::vector<std::string_view> getAliases() const override
{
return {"random"};
}
};
} // namespace Echoion::Core
+66 -55
View File
@@ -2,70 +2,81 @@
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
#include <format>
namespace Echoion::Core {
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;
}
class SkipCommand : public Command
{
public:
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;
}
}
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->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;
}
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;
}
}
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.");
}
}
auto result = manager->skip(count);
if (!result) {
ECHOION_LOG_ERROR(std::format("Skip command failed: {}",
result.error().message));
std::string_view getDescription() const override {
return "Skips to the next track(s).";
}
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;
}
std::string_view getUsage() const override {
return "[count]";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::string_view getDescription() const override
{
return "Skips to the next track(s).";
}
std::vector<std::string_view> getAliases() const override {
return {"next", "n"};
}
};
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
+42 -32
View File
@@ -4,43 +4,53 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class StopCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
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;
}
std::string_view getDescription() const override {
return "Stops playback and clears the queue.";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::string_view getDescription() const override
{
return "Stops playback and clears the queue.";
}
std::vector<std::string_view> getAliases() const override {
return {"s"};
}
};
CommandCategory getCategory() const override
{
return CommandCategory::Playback;
}
std::vector<std::string_view> getAliases() const override
{
return {"s"};
}
};
} // namespace Echoion::Core
@@ -4,43 +4,53 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class SubscribeCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
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;
}
std::string_view getDescription() const override {
return "Subscribes to the music bot to receive audio.";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Utility;
}
std::string_view getDescription() const override
{
return "Subscribes to the music bot to receive audio.";
}
std::vector<std::string_view> getAliases() const override {
return {"sub", "join"};
}
};
CommandCategory getCategory() const override
{
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override
{
return {"sub", "join"};
}
};
} // namespace Echoion::Core
@@ -4,43 +4,54 @@
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
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;
}
class UnsubscribeCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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.");
}
}
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;
}
std::string_view getDescription() const override {
return "Unsubscribes from the music bot.";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Utility;
}
std::string_view getDescription() const override
{
return "Unsubscribes from the music bot.";
}
std::vector<std::string_view> getAliases() const override {
return {"unsub", "leave"};
}
};
CommandCategory getCategory() const override
{
return CommandCategory::Utility;
}
std::vector<std::string_view> getAliases() const override
{
return {"unsub", "leave"};
}
};
} // namespace Echoion::Core
+83 -67
View File
@@ -2,84 +2,100 @@
#include "Command.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
#include <charconv>
#include <format>
namespace Echoion::Core {
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;
}
class VolumeCommand : public Command
{
public:
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;
}
void execute(const CommandContext& ctx) override
{
try {
auto manager = ctx.musicManager.lock();
if (!manager) {
ctx.reply(
"The music service is currently unavailable.");
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 (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;
}
if (volumePercent < 0 || volumePercent > 100) {
ctx.reply("Volume must be between 0 and 100.");
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;
}
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;
}
if (volumePercent < 0 || volumePercent > 100) {
ctx.reply("Volume must be between 0 and 100.");
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.");
}
}
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;
}
std::string_view getDescription() const override {
return "Sets or shows the playback volume.";
}
// 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
}
std::string_view getUsage() const override {
return "[0-100]";
}
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.");
}
}
CommandCategory getCategory() const override {
return CommandCategory::Playback;
}
std::string_view getDescription() const override
{
return "Sets or shows the playback volume.";
}
std::vector<std::string_view> getAliases() const override {
return {"vol", "v"};
}
};
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
@@ -0,0 +1,31 @@
#pragma once
#include "Types.hpp"
#include "echoion/core/state/StateVersions.hpp"
#include <cstdint>
#include <string>
namespace Echoion::Core
{
// Handles migration between state versions
class StateMigration
{
public:
// Migrate from any old version to current
static Api::Result<StateV1> migrate(uint32_t fromVersion,
const std::string& jsonData);
// Specific migrations
static StateV1 fromV0(const StateV0& v0);
// Check if migration path exists
static bool canMigrate(uint32_t fromVersion);
private:
// Migration chain: V0 -> V1 -> V2 -> ...
// Each version only knows how to migrate from previous
};
} // namespace Echoion::Core
@@ -0,0 +1,43 @@
#pragma once
#include "StateBlob.hpp"
#include "echoion/core/state/StateVersions.hpp"
#include <Types.hpp>
#include <cstdint>
#include <string>
namespace Echoion::Core
{
class StateSerializer
{
public:
// Current version being used
static constexpr uint32_t CURRENT_VERSION = 1;
// Serialize current state to opaque blob
static Api::StateBlob serialize(const StateV1& state);
// Deserialize blob to current version (handles migration)
static Api::Result<StateV1> deserialize(const Api::StateBlob& blob);
// Check if version is supported
static bool isVersionSupported(uint32_t version);
// Get supported version range
static uint32_t getMinimumSupportedVersion();
static uint32_t getCurrentVersion();
private:
// Extract version from JSON blob
static uint32_t extractVersion(const std::string& jsonStr);
// Helper to get current timestamp
static std::string getCurrentTimestampISO8601();
// Make it accessible to StateMigration
friend class StateMigration;
};
} // namespace Echoion::Core
@@ -0,0 +1,66 @@
#pragma once
#include "TrackTypes.hpp"
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
namespace Echoion::Core
{
using namespace Echoion::Api;
// State V0 - Initial version (placeholder for testing migration)
struct StateV0 {
std::vector<std::string> trackIds;
float volume = 0.5f;
};
// State V1 - Current version with full playback state
struct StateV1 {
// Playback state
struct PlaybackState {
TrackInfo currentTrack;
int64_t positionMs = 0; // Use int64 for JSON compatibility
bool isPlaying = false;
bool isPaused = false;
float volume = 0.5f;
bool shuffle = false;
bool repeat = false;
};
// Queue entry with metadata
struct QueueEntryState {
TrackInfo track;
uint64_t queueId = 0;
std::string addedBy;
std::string addedAt; // ISO 8601
};
// Session state for RPC clients
struct SessionState {
uint64_t clientId = 0;
std::string authToken;
std::string lastActivity; // ISO 8601
};
// Main state
PlaybackState playback;
bool hasPlayback =
false; // Flag to indicate if playback state is valid
std::vector<QueueEntryState> queue;
std::vector<SessionState> sessions;
// Version info
uint32_t version = 1;
std::string savedAt; // ISO 8601
};
} // namespace Echoion::Core
// StateV0/StateV1 (and the nested PlaybackState/QueueEntryState/SessionState)
// are plain reflectable aggregates whose member names are the desired JSON
// keys, so Void::Json reflection serializes them with no annotations. The only
// non-reflectable member is TrackInfo, which supplies its own
// to_json()/from_json() in TrackTypes.hpp.