many different fixes
This commit is contained in:
1 parent
a583c17916
commit
53801f2b53
36 files changed
+5149
-1291
No files matched your search
@@ -89,10 +89,9 @@ private:
|
||||
// Hardware acceleration setup
|
||||
Api::Result<void> initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||
void cleanupHardwareAccel();
|
||||
|
||||
// Zero-copy frame conversion
|
||||
Api::Result<Api::DecodedAudio> convertFrameZeroCopy();
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// Frame conversion (returns int16 for direct playback)
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// FFmpeg contexts
|
||||
AVFormatContext* formatContext_ = nullptr;
|
||||
@@ -114,8 +113,8 @@ private:
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
|
||||
// Output format
|
||||
uint32_t outputSampleRate_ = 48000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
uint32_t outputSampleRate_ = 192000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
|
||||
// Threading
|
||||
std::jthread decodeThread_;
|
||||
@@ -135,7 +134,9 @@ private:
|
||||
std::atomic<bool> shouldExit_{false}; // For FFmpeg interrupt callback
|
||||
std::chrono::milliseconds currentPosition_{0};
|
||||
std::string currentUrl_;
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
|
||||
// Statistics
|
||||
mutable std::mutex statsMutex_;
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "commands/Command.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <echoion/api.hpp>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
@@ -28,10 +33,13 @@ using PermissionCheckFunc = std::function<bool(uint64_t clientId, CommandCategor
|
||||
class CommandManager {
|
||||
public:
|
||||
CommandManager();
|
||||
~CommandManager() = default;
|
||||
~CommandManager();
|
||||
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
// Shutdown the command manager (stops thread pool)
|
||||
void shutdown();
|
||||
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
CommandManager& operator=(const CommandManager&) = delete;
|
||||
|
||||
// Enable move
|
||||
@@ -59,25 +67,37 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Dispatches a command message to the appropriate handler.
|
||||
* @param clientId The client ID who invoked the command.
|
||||
* @param message The full message (including prefix, e.g., "!play song").
|
||||
* @param musicManager Weak pointer to the MusicManager.
|
||||
* @param replyFunc Function to call to send a reply.
|
||||
* @param invokerName Name of the invoking user.
|
||||
* @return true if a command was found and executed, false otherwise.
|
||||
*/
|
||||
[[nodiscard]] bool dispatch(
|
||||
uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = ""
|
||||
);
|
||||
/**
|
||||
* @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 = "");
|
||||
|
||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::optional<CommandPtr> getCommand(std::string_view name) const;
|
||||
/**
|
||||
* @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)
|
||||
@@ -119,6 +139,27 @@ private:
|
||||
// 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
|
||||
@@ -46,6 +46,8 @@ private:
|
||||
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);
|
||||
|
||||
@@ -44,13 +44,19 @@ public:
|
||||
[[nodiscard]] Api::Result<bool> toggleShuffle();
|
||||
[[nodiscard]] Api::Result<bool> toggleRepeat();
|
||||
|
||||
[[nodiscard]] Api::Result<uint32_t> loadPlaylist(const std::string& playlistId, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const;
|
||||
// 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<std::optional<Api::QueueEntry>> getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
|
||||
[[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);
|
||||
@@ -61,24 +67,60 @@ public:
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
|
||||
// Subscription management
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string> unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients() const;
|
||||
[[nodiscard]] bool hasSubscribers() const;
|
||||
// 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 float>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
// Called when a client connects to the server
|
||||
void onClientConnected(uint64_t clientId);
|
||||
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void>
|
||||
restoreFromHotReload(const Api::HotReloadState& state);
|
||||
|
||||
using AudioDataCallback = std::function<void(const std::span<const short>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
|
||||
|
||||
using PlaybackStartCallback = std::function<void()>;
|
||||
void setPlaybackStartCallback(const PlaybackStartCallback& 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);
|
||||
|
||||
// Callback to resolve client ID from UID
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
void setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
||||
|
||||
// Callback to resolve nickname from client ID
|
||||
using NicknameCallback =
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
private:
|
||||
void playbackThread();
|
||||
@@ -92,9 +134,28 @@ private:
|
||||
[[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};
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
@@ -107,6 +168,11 @@ private:
|
||||
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;
|
||||
@@ -115,6 +181,7 @@ 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_;
|
||||
@@ -122,12 +189,17 @@ private:
|
||||
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = 192000; // Match reference
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
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
|
||||
@@ -5,15 +5,22 @@
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
SubscriptionManager();
|
||||
~SubscriptionManager();
|
||||
|
||||
@@ -21,22 +28,34 @@ public:
|
||||
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
|
||||
void shutdown();
|
||||
|
||||
// Subscription management
|
||||
bool subscribe(uint64_t clientId);
|
||||
bool unsubscribe(uint64_t clientId);
|
||||
bool isSubscribed(uint64_t clientId) const;
|
||||
// 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 clients
|
||||
std::set<uint64_t> getSubscribedClients() 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<uint64_t> subscribedClients_;
|
||||
std::set<std::string> subscribedUids_;
|
||||
mutable std::mutex mutex_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
bool initialized_ = false;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <chrono>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
// URL shortener service for faumaray.ru
|
||||
class UrlShortener {
|
||||
public:
|
||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||
~UrlShortener();
|
||||
|
||||
// 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
|
||||
@@ -1,13 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include "UrlShortener.hpp"
|
||||
#include "YtDlpManager.hpp"
|
||||
#include <regex>
|
||||
#include <chrono>
|
||||
#include <echoion/api.hpp>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
@@ -29,21 +35,46 @@ public:
|
||||
// Force update yt-dlp
|
||||
Api::Result<void> updateYtDlp();
|
||||
|
||||
// Search for videos using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
// 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 video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
||||
|
||||
// Get playlist videos using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo> getPlaylist(std::string_view playlistId);
|
||||
// Get video details asynchronously
|
||||
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoAsync(std::string_view videoId);
|
||||
|
||||
// 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 multiple video details concurrently
|
||||
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
||||
|
||||
// Check if URL is a YouTube 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);
|
||||
|
||||
// Get playlist videos asynchronously with concurrent track resolution
|
||||
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
||||
getPlaylistAsync(std::string_view playlistId);
|
||||
|
||||
// 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);
|
||||
|
||||
// Extract video ID from various YouTube URL formats (handles redirects for
|
||||
// short URLs)
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string>
|
||||
extractPlaylistId(std::string_view url);
|
||||
|
||||
// Check if URL is a YouTube URL
|
||||
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
||||
|
||||
// Get stream URL for a video (used by MusicManager)
|
||||
@@ -56,12 +87,70 @@ public:
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
private:
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
// Configure proxy for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
||||
|
||||
// Set YouTube API key for enhanced playlist resolution (optional)
|
||||
void setApiKey(const std::string& apiKey);
|
||||
[[nodiscard]] bool hasApiKey() const;
|
||||
|
||||
// Configure concurrent resolution settings
|
||||
void setMaxConcurrentResolutions(size_t max);
|
||||
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
|
||||
private:
|
||||
|
||||
// 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);
|
||||
|
||||
// Fetch video durations for search results (batch API call)
|
||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||
const std::vector<std::string>& videoIds);
|
||||
|
||||
// Parse ISO 8601 duration string
|
||||
[[nodiscard]] static std::chrono::seconds
|
||||
parseIso8601Duration(const std::string& duration);
|
||||
|
||||
// URL encode/decode helpers
|
||||
[[nodiscard]] static std::string urlEncode(std::string_view value);
|
||||
[[nodiscard]] static std::string decodeHtmlEntities(std::string_view value);
|
||||
|
||||
// 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
|
||||
@@ -1,14 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include <string>
|
||||
#include <filesystem>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <echoion/api.hpp>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
struct YtDlpResult {
|
||||
std::string output;
|
||||
int exitCode;
|
||||
bool success;
|
||||
std::chrono::milliseconds executionTime;
|
||||
};
|
||||
|
||||
class YtDlpManager {
|
||||
public:
|
||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||
@@ -28,17 +40,34 @@ public:
|
||||
|
||||
// Force update yt-dlp to latest version
|
||||
Api::Result<void> update();
|
||||
|
||||
// Execute yt-dlp with given arguments and return output
|
||||
[[nodiscard]] std::string execute(const std::vector<std::string>& args) const;
|
||||
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Execute yt-dlp with given arguments and return output (synchronous)
|
||||
[[nodiscard]] std::string
|
||||
execute(const std::vector<std::string>& args) const;
|
||||
|
||||
// Execute yt-dlp asynchronously and return a future
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
|
||||
// Execute multiple yt-dlp commands concurrently
|
||||
[[nodiscard]] std::vector<YtDlpResult>
|
||||
executeBatch(const std::vector<std::vector<std::string>>& argsList);
|
||||
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Get cookie arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
|
||||
|
||||
// Set proxy configuration for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
||||
|
||||
// Configure thread pool size for async operations (default: 4)
|
||||
void setThreadPoolSize(size_t size);
|
||||
[[nodiscard]] size_t getThreadPoolSize() const;
|
||||
|
||||
private:
|
||||
// Get the storage directory for yt-dlp
|
||||
[[nodiscard]] std::filesystem::path getStorageDir() const;
|
||||
@@ -58,19 +87,50 @@ private:
|
||||
// Get download URL based on platform
|
||||
[[nodiscard]] std::string getDownloadUrl() const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
// Internal execute implementation
|
||||
[[nodiscard]] YtDlpResult
|
||||
executeInternal(const std::vector<std::string>& args) const;
|
||||
|
||||
// Build the full command with all options
|
||||
[[nodiscard]] std::string
|
||||
buildCommand(const std::vector<std::string>& args) const;
|
||||
|
||||
// Get proxy arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
||||
|
||||
// Escape shell argument
|
||||
[[nodiscard]] static std::string escapeArg(const std::string& arg);
|
||||
|
||||
// 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_;
|
||||
|
||||
// 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 =
|
||||
|
||||
// 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";
|
||||
|
||||
@@ -43,7 +43,8 @@ inline std::string toString(CommandCategory category) {
|
||||
*/
|
||||
struct CommandContext {
|
||||
uint64_t clientId = 0;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string prefix;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string_view invokerName;
|
||||
|
||||
// Dependencies
|
||||
|
||||
@@ -23,3 +23,6 @@
|
||||
#include "ReloadConfigCommand.hpp"
|
||||
#include "SubscribeCommand.hpp"
|
||||
#include "UnsubscribeCommand.hpp"
|
||||
#include "SubscribersCommand.hpp"
|
||||
#include "UnsubscribeIdCommand.hpp"
|
||||
#include "UnsubscribeAllCommand.hpp"
|
||||
@@ -24,22 +24,39 @@ public:
|
||||
}
|
||||
|
||||
if (!current->has_value()) {
|
||||
ctx.reply("Nothing is currently playing. Add something with [prefix]play!");
|
||||
return;
|
||||
ctx.reply(std::format(
|
||||
"Nothing is currently playing. Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& track = current->value();
|
||||
std::string msg = std::format("\xf0\x9f\x8e\xb5 **{}** by **{}**",
|
||||
track.track.title,
|
||||
track.track.artist);
|
||||
|
||||
if (track.track.duration > std::chrono::seconds(0)) {
|
||||
auto mins = std::chrono::minutes(track.track.duration->count()).count();
|
||||
auto secs = std::chrono::seconds(track.track.duration->count()).count() % 60;
|
||||
msg += std::format(" [{}:{:02}]", mins, secs);
|
||||
}
|
||||
|
||||
if (!track.addedBy.empty()) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -61,6 +78,21 @@ public:
|
||||
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
|
||||
@@ -42,7 +42,8 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
// result contains the track title
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -75,25 +76,45 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Added to queue: {}", track.title));
|
||||
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 = "\xf0\x9f\x94\x8d Multiple results found. Use [prefix]select <number>:\n";
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
|
||||
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];
|
||||
msg += std::format("{}. {}", i + 1, track.title);
|
||||
if (!track.artist.empty()) {
|
||||
msg += std::format(" by {}", track.artist);
|
||||
}
|
||||
if (track.duration.has_value()) {
|
||||
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
|
||||
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
|
||||
msg += std::format(" [{}:{:02}]", mins, secs);
|
||||
}
|
||||
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";
|
||||
}
|
||||
|
||||
@@ -120,6 +141,21 @@ public:
|
||||
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
|
||||
@@ -52,7 +52,7 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Loaded {} tracks from playlist '{}'!", *result, ctx.args));
|
||||
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()));
|
||||
|
||||
@@ -27,69 +27,167 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue**\n";
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
msg << std::format("\n**Now Playing:** {} by {}\n",
|
||||
track.track.title,
|
||||
track.track.artist);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << "\nThe queue is empty. Add songs with [prefix]play!";
|
||||
} else {
|
||||
msg << std::format("\n**Up Next ({} tracks):**\n", queue->size());
|
||||
for (size_t i = 0; i < queue->size() && i < 10; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
msg << std::format("{}. {}", i + 1, entry.track.title);
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << std::format(" (by {})", entry.addedBy);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
if (queue->size() > 10) {
|
||||
msg << std::format("\n... and {} more", queue->size() - 10);
|
||||
}
|
||||
}
|
||||
// Clamp page to valid range
|
||||
if (page > totalPages) {
|
||||
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));
|
||||
}
|
||||
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
||||
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
||||
static_cast<int>(queue->size()));
|
||||
|
||||
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::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
||||
<< totalPages << ")\n";
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
// 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::vector<std::string_view> getAliases() const override {
|
||||
return {"q", "list"};
|
||||
}
|
||||
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,
|
||||
*trackInfo.shortenedUrl,
|
||||
formatDuration(*trackInfo.duration))
|
||||
: 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);
|
||||
}
|
||||
}
|
||||
|
||||
// State indicators
|
||||
if (state) {
|
||||
msg << "\n\n";
|
||||
if (state->isPaused) {
|
||||
msg << "\xe2\x8f\xb8 Paused | ";
|
||||
}
|
||||
if (state->shuffle) {
|
||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||
}
|
||||
if (state->repeat) {
|
||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||
}
|
||||
msg << std::format("Volume: {}%", static_cast<int>(state->volume * 100));
|
||||
}
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[page]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"q", "list"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -18,8 +18,10 @@ public:
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: remove <position>\nUse [prefix]queue to see track positions.");
|
||||
return;
|
||||
ctx.reply(std::format("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t position = 0;
|
||||
|
||||
@@ -48,21 +48,30 @@ public:
|
||||
|
||||
for (size_t i = 0; i < result->tracks.size() && i < 5; ++i) {
|
||||
const auto& track = result->tracks[i];
|
||||
msg << std::format("{}. {}", i + 1, track.title);
|
||||
if (!track.artist.empty()) {
|
||||
msg << std::format(" by {}", track.artist);
|
||||
}
|
||||
if (track.duration.has_value()) {
|
||||
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
|
||||
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
|
||||
msg << std::format(" [{}:{:02}]", mins, secs);
|
||||
}
|
||||
// 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 << "\nUse [prefix]select <number> to play a result.";
|
||||
msg << std::format("\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
|
||||
ctx.reply(msg.str());
|
||||
ctx.reply(msg.str());
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Search command exception: {}", e.what()));
|
||||
@@ -85,6 +94,21 @@ public:
|
||||
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
|
||||
@@ -19,25 +19,67 @@ public:
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: seek <seconds>\nExample: seek 60 (jumps to 1 minute)");
|
||||
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;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
int seconds = 0;
|
||||
auto parseResult = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
auto parseResult = std::from_chars(arg.data(),
|
||||
arg.data() + arg.size(),
|
||||
seconds);
|
||||
if (parseResult.ec != std::errc()) {
|
||||
ctx.reply("Please provide a valid number of 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;
|
||||
}
|
||||
|
||||
if (seconds < 0) {
|
||||
ctx.reply("Time must be a positive number.");
|
||||
return;
|
||||
std::chrono::milliseconds targetPosition;
|
||||
std::string positionStr;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
auto result = manager->seek(std::chrono::seconds(seconds));
|
||||
auto result = manager->seek(targetPosition);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command failed: {}", result.error().message));
|
||||
|
||||
@@ -51,12 +93,10 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
auto mins = seconds / 60;
|
||||
auto secs = seconds % 60;
|
||||
if (mins > 0) {
|
||||
ctx.reply(std::format("Seeked to {}:{:02}.", mins, secs));
|
||||
if (relative) {
|
||||
ctx.reply(std::format("Seeked {} from current position.", positionStr));
|
||||
} else {
|
||||
ctx.reply(std::format("Seeked to {} seconds.", seconds));
|
||||
ctx.reply(std::format("Seeked to position {}.", positionStr));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command exception: {}", e.what()));
|
||||
@@ -65,11 +105,11 @@ public:
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Seeks to a position in the current track.";
|
||||
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>";
|
||||
return "<+/-seconds>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
|
||||
@@ -40,11 +40,13 @@ public:
|
||||
ctx.clientId, index, selectResult.error().message));
|
||||
|
||||
if (selectResult.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply("No search results found. Use [prefix]play <query> to search first.");
|
||||
} else {
|
||||
ctx.reply("Couldn't select that track. Please try again.");
|
||||
}
|
||||
return;
|
||||
ctx.reply(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);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SubscribersCommand : 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 subscribers = manager->getSubscribers();
|
||||
auto onlineUids = manager->getOnlineSubscriberUids();
|
||||
|
||||
if (subscribers.empty()) {
|
||||
ctx.reply(
|
||||
"No subscribers. Use !subscribe to receive audio.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Separate online and offline
|
||||
std::vector<SubscriptionManager::Subscriber> online;
|
||||
std::vector<SubscriptionManager::Subscriber> offline;
|
||||
|
||||
for (const auto& sub : subscribers) {
|
||||
if (onlineUids.contains(sub.uid)) {
|
||||
online.push_back(sub);
|
||||
} else {
|
||||
offline.push_back(sub);
|
||||
}
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x8b **Subscribed Users** ("
|
||||
<< subscribers.size() << " total)\n";
|
||||
msg << "\xf0\x9f\x9f\xa2 Online: " << online.size()
|
||||
<< " | \xe2\x9a\xaa Offline: " << offline.size()
|
||||
<< "\n\n";
|
||||
|
||||
// Online subscribers
|
||||
if (!online.empty()) {
|
||||
msg << "**\xf0\x9f\x9f\xa2 Online:**\n";
|
||||
for (size_t i = 0; i < online.size(); ++i) {
|
||||
const auto& sub = online[i];
|
||||
msg << std::format("{}. **{}**\n", i + 1,
|
||||
sub.nickname);
|
||||
msg << std::format(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
// Offline subscribers
|
||||
if (!offline.empty()) {
|
||||
msg << "**\xe2\x9a\xaa Offline:**\n";
|
||||
for (size_t i = 0; i < offline.size(); ++i) {
|
||||
const auto& sub = offline[i];
|
||||
msg << std::format("{}. **{}**\n", i + 1,
|
||||
sub.nickname);
|
||||
msg << std::format(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
msg << "Use `!unsubscribeid <uid>` to remove a specific "
|
||||
"subscriber.\n";
|
||||
msg << "Use `!unsubscribeall` to remove all subscribers.";
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Subscribers command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Lists all subscribed users (online/offline).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"subs", "listsubs"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeAllCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->clearAllSubscriptions();
|
||||
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Unsubscribe all failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't clear subscriptions. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribeall command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Removes all subscriptions (admin only).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsuball", "clearsubs"};
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeIdCommand : 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("Please provide a user UID. Use !subscribers "
|
||||
"to see UIDs.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string uid(ctx.args);
|
||||
auto result = manager->unsubscribeByUid(uid);
|
||||
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Unsubscribe by ID failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't unsubscribe user. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribeid command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Unsubscribes a user by their UID (admin only).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<uid>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsubid", "removeuser"};
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Reference in new issue
Block a user