From 53801f2b5388b9f89f8510790aba376efda39507 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 3 Feb 2026 05:07:15 +0300 Subject: [PATCH] many different fixes --- CMakeLists.txt | 32 +- cmake/BundleFFmpeg.cmake | 48 + include/echoion/core/AudioDecoder.hpp | 15 +- include/echoion/core/CommandManager.hpp | 91 +- include/echoion/core/Logger.hpp | 2 + include/echoion/core/MusicManager.hpp | 124 +- include/echoion/core/SubscriptionManager.hpp | 33 +- include/echoion/core/UrlShortener.hpp | 50 + include/echoion/core/YouTubeClient.hpp | 131 +- include/echoion/core/YtDlpManager.hpp | 96 +- include/echoion/core/commands/Command.hpp | 3 +- include/echoion/core/commands/Commands.hpp | 3 + .../core/commands/NowPlayingCommand.hpp | 58 +- include/echoion/core/commands/PlayCommand.hpp | 64 +- .../echoion/core/commands/PlaylistCommand.hpp | 2 +- .../echoion/core/commands/QueueCommand.hpp | 210 +- .../echoion/core/commands/RemoveCommand.hpp | 6 +- .../echoion/core/commands/SearchCommand.hpp | 46 +- include/echoion/core/commands/SeekCommand.hpp | 72 +- .../echoion/core/commands/SelectCommand.hpp | 12 +- .../core/commands/SubscribersCommand.hpp | 109 + .../core/commands/UnsubscribeAllCommand.hpp | 64 + .../core/commands/UnsubscribeIdCommand.hpp | 71 + src/AudioDecoder.cpp | 50 +- src/CommandManager.cpp | 220 +- src/ConfigLoader.cpp | 25 +- src/Core.cpp | 349 ++- src/Database.cpp | 124 +- src/Logger.cpp | 104 +- src/MemoryPool.cpp | 16 +- src/MusicManager.cpp | 1946 ++++++++++++----- src/NetworkClient.cpp | 10 +- src/SubscriptionManager.cpp | 117 +- src/UrlShortener.cpp | 144 ++ src/YouTubeClient.cpp | 1620 ++++++++++++-- src/YtDlpManager.cpp | 373 +++- 36 files changed, 5149 insertions(+), 1291 deletions(-) create mode 100644 cmake/BundleFFmpeg.cmake create mode 100644 include/echoion/core/UrlShortener.hpp create mode 100644 include/echoion/core/commands/SubscribersCommand.hpp create mode 100644 include/echoion/core/commands/UnsubscribeAllCommand.hpp create mode 100644 include/echoion/core/commands/UnsubscribeIdCommand.hpp create mode 100644 src/UrlShortener.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 24e4e4e..a784d59 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,6 +13,7 @@ add_library(EchoionCore SHARED src/SignatureCipher.cpp src/YouTubeClient.cpp src/YtDlpManager.cpp + src/UrlShortener.cpp src/AudioDecoder.cpp src/CommandManager.cpp src/MusicManager.cpp @@ -106,20 +107,21 @@ set_target_properties(EchoionCore PROPERTIES ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib ) -include(GNUInstallDirs) -install(TARGETS EchoionCore - EXPORT EchoionCoreTargets - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} +# PackageProject.cmake configuration +packageProject( + NAME EchoionCore + VERSION ${PROJECT_VERSION} + NAMESPACE Echoion + BINARY_DIR ${PROJECT_BINARY_DIR} + INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include + INCLUDE_DESTINATION include + COMPATIBILITY SameMajorVersion + DISABLE_VERSION_SUFFIX YES ) -install(EXPORT EchoionCoreTargets - FILE EchoionCoreTargets.cmake - NAMESPACE Echoion:: - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/EchoionCore -) - -install(DIRECTORY include/ - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} -) +# Optional: Bundle FFmpeg libraries for distribution +option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF) +if(BUNDLE_FFMPEG) + include(cmake/BundleFFmpeg.cmake) + bundle_ffmpeg_libraries(EchoionCore) +endif() diff --git a/cmake/BundleFFmpeg.cmake b/cmake/BundleFFmpeg.cmake new file mode 100644 index 0000000..9cd9ff6 --- /dev/null +++ b/cmake/BundleFFmpeg.cmake @@ -0,0 +1,48 @@ +# BundleFFmpeg.cmake - Helper to bundle FFmpeg libraries on install + +function(bundle_ffmpeg_libraries target) + if(NOT TARGET ${target}) + return() + endif() + + if(UNIX AND NOT APPLE) + # Create post-install script to copy FFmpeg libs + file(GENERATE OUTPUT ${CMAKE_BINARY_DIR}/bundle_ffmpeg_$.sh + CONTENT "#!/bin/bash +# Bundle FFmpeg libraries +set -e + +dest_dir=\"$1\" +mkdir -p \"\$dest_dir\" + +# Find FFmpeg libraries +ffmpeg_libs=($(pkg-config --libs-only-L libavformat libavcodec libswresample libavutil 2>/dev/null | sed 's/-L//g')) + +for libdir in \"\${ffmpeg_libs[@]}\" /usr/lib /usr/local/lib; do + if [ -d \"\$libdir\" ]; then + for lib in avformat avcodec swresample avutil; do + # Try different naming conventions + for pattern in \"lib\${lib}.so*\" \"lib\${lib}-*.so*\"; do + for file in \$libdir/\$pattern; do + if [ -f \"\$file\" ] && [ ! -L \"\$file\" ]; then + cp -v \"\$file\" \"\$dest_dir/\" 2>/dev/null || true + fi + done + done + done + fi +done + +echo \"FFmpeg libraries bundled to \$dest_dir\" +" + FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + ) + + install(CODE " + execute_process( + COMMAND ${CMAKE_BINARY_DIR}/bundle_ffmpeg_$.sh \"${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}\" + ERROR_QUIET + ) + ") + endif() +endfunction() diff --git a/include/echoion/core/AudioDecoder.hpp b/include/echoion/core/AudioDecoder.hpp index 4b89e31..df3a86d 100644 --- a/include/echoion/core/AudioDecoder.hpp +++ b/include/echoion/core/AudioDecoder.hpp @@ -89,10 +89,9 @@ private: // Hardware acceleration setup Api::Result initializeHardwareAccel(const Api::HwAccelConfig& config); void cleanupHardwareAccel(); - - // Zero-copy frame conversion - Api::Result convertFrameZeroCopy(); - Api::Result convertFramePooled(); + + // Frame conversion (returns int16 for direct playback) + Api::Result 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 shouldExit_{false}; // For FFmpeg interrupt callback std::chrono::milliseconds currentPosition_{0}; std::string currentUrl_; - std::optional proxyConfig_; + + std::atomic streamSampleRate_{48000}; + std::optional proxyConfig_; // Statistics mutable std::mutex statsMutex_; diff --git a/include/echoion/core/CommandManager.hpp b/include/echoion/core/CommandManager.hpp index 23eac18..88849fb 100644 --- a/include/echoion/core/CommandManager.hpp +++ b/include/echoion/core/CommandManager.hpp @@ -1,14 +1,19 @@ #pragma once -#include #include "commands/Command.hpp" #include "echoion/api/ConfigTypes.hpp" +#include +#include +#include +#include +#include #include -#include #include #include +#include #include -#include +#include +#include namespace Echoion::Core { @@ -28,10 +33,13 @@ using PermissionCheckFunc = std::function musicManager, - std::function 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, + std::function replyFunc, + std::string_view invokerName = ""); - [[nodiscard]] bool hasCommand(std::string_view name) const; - [[nodiscard]] std::optional 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, + std::function replyFunc, + std::string_view invokerName = ""); + + [[nodiscard]] bool hasCommand(std::string_view name) const; + [[nodiscard]] std::optional getCommand(std::string_view name) const; [[nodiscard]] std::vector> getAllCommands() const; // Get commands visible to a specific client (for help) @@ -119,6 +139,27 @@ private: // Permission checking PermissionCheckFunc permissionCheck_; std::optional serverConfig_; -}; + // Async command execution + struct CommandTask { + uint64_t clientId; + std::string message; + std::weak_ptr musicManager; + std::function replyFunc; + std::string invokerName; + }; + + void startThreadPool(); + void processCommandQueue(); + void executeCommandAsync(CommandTask task); + + std::vector workerThreads_; + std::queue commandQueue_; + std::mutex queueMutex_; + std::condition_variable queueCv_; + std::atomic shutdown_{false}; + static constexpr size_t THREAD_POOL_SIZE = + 4; // Handle up to 4 concurrent commands + +}; // namespace Echoion::Core } // namespace Echoion::Core diff --git a/include/echoion/core/Logger.hpp b/include/echoion/core/Logger.hpp index 272579e..340becb 100644 --- a/include/echoion/core/Logger.hpp +++ b/include/echoion/core/Logger.hpp @@ -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); diff --git a/include/echoion/core/MusicManager.hpp b/include/echoion/core/MusicManager.hpp index 48da4f2..2e43f0c 100644 --- a/include/echoion/core/MusicManager.hpp +++ b/include/echoion/core/MusicManager.hpp @@ -44,13 +44,19 @@ public: [[nodiscard]] Api::Result toggleShuffle(); [[nodiscard]] Api::Result toggleRepeat(); - [[nodiscard]] Api::Result loadPlaylist(const std::string& playlistId, uint64_t clientId); - [[nodiscard]] Api::Result> getPlaylists() const; + // Load playlist asynchronously - returns immediately, processes in background + Api::Result 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> + getPlaylists() const; - [[nodiscard]] Api::Result> getCurrentTrack() const; - [[nodiscard]] Api::Result getPlaybackState() const; + [[nodiscard]] Api::Result> + getCurrentTrack() const; + [[nodiscard]] Api::Result getPlaybackState() const; + [[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const; - [[nodiscard]] Api::Result search(const std::string& query); + [[nodiscard]] Api::Result search(const std::string& query); // Search result selection (client-specific) void storePendingSearch(uint64_t clientId, const std::vector& results); @@ -61,24 +67,60 @@ public: // Help command [[nodiscard]] std::string getHelpText() const; - // Subscription management - [[nodiscard]] Api::Result subscribe(uint64_t clientId); - [[nodiscard]] Api::Result unsubscribe(uint64_t clientId); - [[nodiscard]] bool isSubscribed(uint64_t clientId) const; - [[nodiscard]] std::set getSubscribedClients() const; - [[nodiscard]] bool hasSubscribers() const; + // Subscription management (by client ID - internally uses UID for + // persistence) + [[nodiscard]] Api::Result subscribe(uint64_t clientId); + [[nodiscard]] Api::Result unsubscribe(uint64_t clientId); + [[nodiscard]] bool isSubscribed(uint64_t clientId) const; + [[nodiscard]] std::set 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 + getSubscribers() const; + [[nodiscard]] Api::Result + unsubscribeByUid(const std::string& uid); + [[nodiscard]] Api::Result clearAllSubscriptions(); - [[nodiscard]] Api::HotReloadState getStateForHotReload() const; - [[nodiscard]] Api::Result restoreFromHotReload(const Api::HotReloadState& state); + // Get UIDs of subscribers who are currently online + [[nodiscard]] std::set getOnlineSubscriberUids() const; - using AudioDataCallback = std::function)>; - void setAudioDataCallback(const AudioDataCallback& callback); - - using SubscriptionChangeCallback = std::function; - 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 + restoreFromHotReload(const Api::HotReloadState& state); + + using AudioDataCallback = std::function)>; + void setAudioDataCallback(const AudioDataCallback& callback); + + using SubscriptionChangeCallback = std::function; + void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback); + + using PlaybackStartCallback = std::function; + void setPlaybackStartCallback(const PlaybackStartCallback& callback); + + // Callback to resolve client info (UID and nickname) from client ID + using ClientInfoCallback = + std::function>( + uint64_t clientId)>; + void setClientInfoCallback(const ClientInfoCallback& callback); + + // Callback to resolve client ID from UID + using UidToClientIdCallback = + std::function(const std::string& uid)>; + void setUidToClientIdCallback(const UidToClientIdCallback& callback); + + // Callback to resolve nickname from client ID + using NicknameCallback = + std::function(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 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 tempFiles_; mutable std::mutex tempFilesMutex_; + + // Prefetch state for seamless playback + struct PrefetchState { + std::future> streamUrlFuture; + std::atomic isPrefetching{false}; + std::atomic hasPrefetched{false}; + std::optional prefetchedUrl; + } prefetchState_; + + // Async playlist loading state + std::thread playlistLoadThread_; + std::atomic playlistLoading_{false}; + std::atomic playlistLoadedCount_{0}; + std::atomic playlistTotalCount_{0}; std::shared_ptr networkClient_; std::unique_ptr 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 playbackThreadRunning_{false}; // True while thread is actively running // Pending search results per client (for select command) std::unordered_map> 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 diff --git a/include/echoion/core/SubscriptionManager.hpp b/include/echoion/core/SubscriptionManager.hpp index efb1eae..e1526e7 100644 --- a/include/echoion/core/SubscriptionManager.hpp +++ b/include/echoion/core/SubscriptionManager.hpp @@ -5,15 +5,22 @@ #include #include #include +#include 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 initialize(std::shared_ptr 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 getSubscribedClients() const; + // Get all subscribed UIDs + std::vector getSubscribedUids() const; + + // Get all subscribers with info + std::vector getSubscribers() const; + + // Get subscriber nickname + std::optional 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 subscribedClients_; + std::set subscribedUids_; mutable std::mutex mutex_; std::shared_ptr database_; bool initialized_ = false; diff --git a/include/echoion/core/UrlShortener.hpp b/include/echoion/core/UrlShortener.hpp new file mode 100644 index 0000000..9f9d626 --- /dev/null +++ b/include/echoion/core/UrlShortener.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include +#include "NetworkClient.hpp" +#include +#include +#include +#include +#include + +namespace Echoion::Core { + +// URL shortener service for faumaray.ru +class UrlShortener { +public: + explicit UrlShortener(std::shared_ptr networkClient); + ~UrlShortener(); + + // Shorten a YouTube URL via faumaray.ru + // Returns shortened URL in format: https://faumaray.ru/xxxxx + [[nodiscard]] Api::Result shortenYouTubeUrl(std::string_view videoId); + + // Shorten any URL via faumaray.ru + [[nodiscard]] Api::Result shortenUrl(std::string_view originalUrl); + + // Get cached shortened URL if available + [[nodiscard]] std::optional 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_; + mutable std::mutex cacheMutex_; + std::unordered_map cache_; + std::chrono::hours cacheTtl_{24}; + + // Clean expired entries from cache + void cleanExpiredCache(); +}; + +} // namespace Echoion::Core diff --git a/include/echoion/core/YouTubeClient.hpp b/include/echoion/core/YouTubeClient.hpp index 85815b6..d681c24 100644 --- a/include/echoion/core/YouTubeClient.hpp +++ b/include/echoion/core/YouTubeClient.hpp @@ -1,13 +1,19 @@ #pragma once -#include #include "NetworkClient.hpp" +#include "UrlShortener.hpp" #include "YtDlpManager.hpp" -#include +#include +#include +#include +#include +#include #include #include +#include #include -#include +#include +#include namespace Echoion::Core { @@ -29,21 +35,46 @@ public: // Force update yt-dlp Api::Result updateYtDlp(); - // Search for videos using yt-dlp - [[nodiscard]] Api::Result search(std::string_view query, - std::optional pageToken = std::nullopt); + // Search for videos using YouTube Data API v3 (or yt-dlp as fallback) + [[nodiscard]] Api::Result + search(std::string_view query, + std::optional pageToken = std::nullopt); - // Get video details including stream URLs using yt-dlp - [[nodiscard]] Api::Result getVideoInfo(std::string_view videoId); + // Get video details including stream URLs using yt-dlp + [[nodiscard]] Api::Result getVideoInfo(std::string_view videoId); - // Get playlist videos using yt-dlp - [[nodiscard]] Api::Result getPlaylist(std::string_view playlistId); + // Get video details asynchronously + [[nodiscard]] std::future> + getVideoInfoAsync(std::string_view videoId); - // Extract video ID from various YouTube URL formats (handles redirects for short URLs) - [[nodiscard]] std::optional extractVideoId(std::string_view url); - [[nodiscard]] static std::optional extractPlaylistId(std::string_view url); + // Get multiple video details concurrently + [[nodiscard]] std::vector> + getVideoInfoBatch(const std::vector& 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 + getPlaylist(std::string_view playlistId); + + // Get playlist videos asynchronously with concurrent track resolution + [[nodiscard]] std::future> + 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 trackCallback, + std::function onPlaylistInfo = nullptr, + std::function onComplete = nullptr); + + // Extract video ID from various YouTube URL formats (handles redirects for + // short URLs) + [[nodiscard]] std::optional + extractVideoId(std::string_view url); + [[nodiscard]] static std::optional + 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_; - std::unique_ptr ytDlpManager_; - - std::atomic initialized_{false}; - mutable std::mutex mutex_; -}; + // Configure proxy for yt-dlp + void setProxyConfig(const std::optional& proxy); + [[nodiscard]] std::optional 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 + searchWithApi(std::string_view query, + const std::optional& pageToken); + [[nodiscard]] Api::Result + searchWithYtDlp(std::string_view query, + const std::optional& pageToken); + + // Fetch video durations for search results (batch API call) + void fetchVideoDurations(std::vector& tracks, + const std::vector& 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> + fetchPlaylistItems(std::string_view playlistId); + [[nodiscard]] Api::Result + resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item); + + // Build YouTube API v3 URL for playlist items + [[nodiscard]] std::string buildPlaylistApiUrl( + std::string_view playlistId, + const std::optional& pageToken = std::nullopt) const; + + std::shared_ptr networkClient_; + std::unique_ptr ytDlpManager_; + std::unique_ptr urlShortener_; + + std::atomic initialized_{false}; + mutable std::mutex mutex_; + + // Configuration + std::optional apiKey_; + mutable std::mutex configMutex_; + size_t maxConcurrentResolutions_ = 4; + bool urlShorteningEnabled_ = true; + + // Populate shortened URLs for tracks + void populateShortenedUrls(std::vector& tracks); + void populateShortenedUrl(Api::TrackInfo& track); +}; } // namespace Echoion::Core diff --git a/include/echoion/core/YtDlpManager.hpp b/include/echoion/core/YtDlpManager.hpp index 50856bc..c3d32d1 100644 --- a/include/echoion/core/YtDlpManager.hpp +++ b/include/echoion/core/YtDlpManager.hpp @@ -1,14 +1,26 @@ #pragma once -#include #include "NetworkClient.hpp" -#include -#include #include +#include +#include +#include +#include #include +#include +#include +#include +#include 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); @@ -28,17 +40,34 @@ public: // Force update yt-dlp to latest version Api::Result update(); - - // Execute yt-dlp with given arguments and return output - [[nodiscard]] std::string execute(const std::vector& 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& args) const; + + // Execute yt-dlp asynchronously and return a future + [[nodiscard]] std::future + executeAsync(const std::vector& args); + + // Execute multiple yt-dlp commands concurrently + [[nodiscard]] std::vector + executeBatch(const std::vector>& 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 getCookieArgs() const; + // Set proxy configuration for yt-dlp + void setProxyConfig(const std::optional& proxy); + [[nodiscard]] std::optional 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_; - std::filesystem::path executablePath_; - std::atomic initialized_{false}; + // Internal execute implementation + [[nodiscard]] YtDlpResult + executeInternal(const std::vector& args) const; + + // Build the full command with all options + [[nodiscard]] std::string + buildCommand(const std::vector& args) const; + + // Get proxy arguments for yt-dlp command + [[nodiscard]] std::vector 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_; + std::filesystem::path executablePath_; + std::atomic initialized_{false}; mutable std::mutex mutex_; // Cookie configuration for YouTube authentication std::optional cookiesPath_; std::optional 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 proxyConfig_; + mutable std::mutex proxyMutex_; + + // Thread pool for async operations + size_t threadPoolSize_ = 4; + std::vector threadPool_; + std::queue> taskQueue_; + std::mutex taskMutex_; + std::condition_variable taskCv_; + std::atomic 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"; diff --git a/include/echoion/core/commands/Command.hpp b/include/echoion/core/commands/Command.hpp index 835df23..28a69c3 100644 --- a/include/echoion/core/commands/Command.hpp +++ b/include/echoion/core/commands/Command.hpp @@ -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 diff --git a/include/echoion/core/commands/Commands.hpp b/include/echoion/core/commands/Commands.hpp index bf36d08..0b6334b 100644 --- a/include/echoion/core/commands/Commands.hpp +++ b/include/echoion/core/commands/Commands.hpp @@ -23,3 +23,6 @@ #include "ReloadConfigCommand.hpp" #include "SubscribeCommand.hpp" #include "UnsubscribeCommand.hpp" +#include "SubscribersCommand.hpp" +#include "UnsubscribeIdCommand.hpp" +#include "UnsubscribeAllCommand.hpp" diff --git a/include/echoion/core/commands/NowPlayingCommand.hpp b/include/echoion/core/commands/NowPlayingCommand.hpp index 5759099..d65b168 100644 --- a/include/echoion/core/commands/NowPlayingCommand.hpp +++ b/include/echoion/core/commands/NowPlayingCommand.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 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 diff --git a/include/echoion/core/commands/PlayCommand.hpp b/include/echoion/core/commands/PlayCommand.hpp index 106bce6..9e6ee3b 100644 --- a/include/echoion/core/commands/PlayCommand.hpp +++ b/include/echoion/core/commands/PlayCommand.hpp @@ -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 :\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 :\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(*track.duration).count(); - auto secs = std::chrono::duration_cast(*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 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 diff --git a/include/echoion/core/commands/PlaylistCommand.hpp b/include/echoion/core/commands/PlaylistCommand.hpp index 27a9b59..83164db 100644 --- a/include/echoion/core/commands/PlaylistCommand.hpp +++ b/include/echoion/core/commands/PlaylistCommand.hpp @@ -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())); diff --git a/include/echoion/core/commands/QueueCommand.hpp b/include/echoion/core/commands/QueueCommand.hpp index 947097d..c2b9dbd 100644 --- a/include/echoion/core/commands/QueueCommand.hpp +++ b/include/echoion/core/commands/QueueCommand.hpp @@ -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(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(state->volume * 100)); - } + int startIdx = (page - 1) * ITEMS_PER_PAGE; + int endIdx = std::min(startIdx + ITEMS_PER_PAGE, + static_cast(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 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 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(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 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 diff --git a/include/echoion/core/commands/RemoveCommand.hpp b/include/echoion/core/commands/RemoveCommand.hpp index c096ff4..4ec4022 100644 --- a/include/echoion/core/commands/RemoveCommand.hpp +++ b/include/echoion/core/commands/RemoveCommand.hpp @@ -18,8 +18,10 @@ public: } if (ctx.args.empty()) { - ctx.reply("Usage: remove \nUse [prefix]queue to see track positions."); - return; + ctx.reply(std::format("Usage: remove \nUse {}queue " + "to see track positions.", + ctx.prefix)); + return; } uint32_t position = 0; diff --git a/include/echoion/core/commands/SearchCommand.hpp b/include/echoion/core/commands/SearchCommand.hpp index aeae260..4852f95 100644 --- a/include/echoion/core/commands/SearchCommand.hpp +++ b/include/echoion/core/commands/SearchCommand.hpp @@ -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(*track.duration).count(); - auto secs = std::chrono::duration_cast(*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 to play a result."; + msg << std::format("\nUse {}select 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 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 diff --git a/include/echoion/core/commands/SeekCommand.hpp b/include/echoion/core/commands/SeekCommand.hpp index 4488ca4..430ea24 100644 --- a/include/echoion/core/commands/SeekCommand.hpp +++ b/include/echoion/core/commands/SeekCommand.hpp @@ -19,25 +19,67 @@ public: } if (ctx.args.empty()) { - ctx.reply("Usage: seek \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 ""; + return "<+/-seconds>"; } CommandCategory getCategory() const override { diff --git a/include/echoion/core/commands/SelectCommand.hpp b/include/echoion/core/commands/SelectCommand.hpp index 45b8158..180e326 100644 --- a/include/echoion/core/commands/SelectCommand.hpp +++ b/include/echoion/core/commands/SelectCommand.hpp @@ -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 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 " + " to search first.", + ctx.prefix)); + } else { + ctx.reply("Couldn't select that track. Please try again."); + } + return; } ctx.reply(*selectResult); diff --git a/include/echoion/core/commands/SubscribersCommand.hpp b/include/echoion/core/commands/SubscribersCommand.hpp new file mode 100644 index 0000000..7b726d5 --- /dev/null +++ b/include/echoion/core/commands/SubscribersCommand.hpp @@ -0,0 +1,109 @@ +#pragma once + +#include "Command.hpp" +#include "echoion/core/Logger.hpp" +#include "echoion/core/MusicManager.hpp" +#include +#include +#include + +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 online; + std::vector 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 ` 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 getAliases() const override + { + return {"subs", "listsubs"}; + } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/UnsubscribeAllCommand.hpp b/include/echoion/core/commands/UnsubscribeAllCommand.hpp new file mode 100644 index 0000000..92cd12c --- /dev/null +++ b/include/echoion/core/commands/UnsubscribeAllCommand.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "Command.hpp" +#include "echoion/core/Logger.hpp" +#include "echoion/core/MusicManager.hpp" +#include + +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 getAliases() const override + { + return {"unsuball", "clearsubs"}; + } + + bool requiresAdmin() const override { return true; } + }; + +} // namespace Echoion::Core diff --git a/include/echoion/core/commands/UnsubscribeIdCommand.hpp b/include/echoion/core/commands/UnsubscribeIdCommand.hpp new file mode 100644 index 0000000..216b3ea --- /dev/null +++ b/include/echoion/core/commands/UnsubscribeIdCommand.hpp @@ -0,0 +1,71 @@ +#pragma once + +#include "Command.hpp" +#include "echoion/core/Logger.hpp" +#include "echoion/core/MusicManager.hpp" +#include + +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 ""; } + + CommandCategory getCategory() const override + { + return CommandCategory::Admin; + } + + std::vector getAliases() const override + { + return {"unsubid", "removeuser"}; + } + + bool requiresAdmin() const override { return true; } + }; + +} // namespace Echoion::Core diff --git a/src/AudioDecoder.cpp b/src/AudioDecoder.cpp index 1175956..fedaccc 100644 --- a/src/AudioDecoder.cpp +++ b/src/AudioDecoder.cpp @@ -234,6 +234,8 @@ Api::Result AudioDecoder::openSource(const std::string& url) { streamInfo_.hwAccelerated = hwAccelEnabled_; streamInfo_.hwAccelType = hwAccelType_; + streamSampleRate_ = static_cast(codecContext_->sample_rate > 0 ? codecContext_->sample_rate : 48000); + if (formatContext_->duration != AV_NOPTS_VALUE) { streamInfo_.duration = std::chrono::milliseconds( formatContext_->duration * 1000 / AV_TIME_BASE); @@ -326,10 +328,11 @@ Api::Result AudioDecoder::decodeFrame() { } static int callCount = 0; -bool AudioDecoder::getNextChunk(std::vector& outChunk, bool blocking) { - callCount++; - - std::unique_lock lock(mutex_); +bool AudioDecoder::getNextChunk(std::vector& outChunk, bool blocking) +{ + callCount++; + + std::unique_lock lock(mutex_); if (blocking) { cv_.wait(lock, [this] { return !int16Queue_.empty() || eof_.load(); }); @@ -369,7 +372,9 @@ Api::Result AudioDecoder::seek(std::chrono::milliseconds position) { avcodec_flush_buffers(codecContext_); currentPosition_ = position; - + + // Clear pending audio data + int16Queue_.clear(); std::queue empty; std::swap(decodedQueue_, empty); @@ -384,6 +389,9 @@ Api::Result AudioDecoder::getStreamInfo() const { } std::chrono::milliseconds AudioDecoder::getPosition() const { + // Return last known position from FFmpeg decoding + // Note: This is updated when frames are decoded, not when played + // For accurate playback position, use MusicManager::getPlaybackPosition() return currentPosition_; } @@ -565,7 +573,8 @@ Api::Result AudioDecoder::readPacket() { Api::Result AudioDecoder::convertFrame() { int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples); - std::vector outputBuffer(outSamples * outputChannels_); + // Use int16_t for direct output (no float conversion) + std::vector outputBuffer(outSamples * outputChannels_); uint8_t* outData = reinterpret_cast(outputBuffer.data()); const uint8_t** inData = const_cast(frame_->extended_data); @@ -584,7 +593,8 @@ Api::Result AudioDecoder::convertFrame() { } Api::DecodedAudio audio; - audio.view = Api::FloatAudioView(outputBuffer.data(), outputBuffer.size(), outputChannels_); + audio.samples = std::move(outputBuffer); + audio.view = Api::Int16AudioView(audio.samples.data(), audio.samples.size(), outputChannels_); audio.sampleRate = outputSampleRate_; audio.channels = outputChannels_; audio.timestamp = currentPosition_; @@ -592,29 +602,9 @@ Api::Result AudioDecoder::convertFrame() { } Api::Result AudioDecoder::convertFramePooled() { - int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples); - auto pooledBuffer = Api::AudioBufferPool::instance().acquireBuffer(); - if (!pooledBuffer) return convertFrame(); - - uint8_t* outData = reinterpret_cast(pooledBuffer.get()); - const uint8_t** inData = const_cast(frame_->extended_data); - - int converted = swr_convert(swrContext_, &outData, outSamples, inData, frame_->nb_samples); - if (converted < 0) return std::unexpected(Api::Error(Api::ErrorCode::AudioError, "Resampling failed")); - - if (frame_->pts != AV_NOPTS_VALUE) { - AVRational timeBase = formatContext_->streams[audioStreamIndex_]->time_base; - currentPosition_ = std::chrono::milliseconds( - frame_->pts * 1000 * timeBase.num / timeBase.den); - } - - Api::DecodedAudio audio; - audio.pooledSamples = std::move(pooledBuffer); - audio.view = Api::FloatAudioView(audio.pooledSamples.get(), converted * outputChannels_, outputChannels_); - audio.sampleRate = outputSampleRate_; - audio.channels = outputChannels_; - audio.timestamp = currentPosition_; - return audio; + // Using int16_t (short) for direct TeamSpeak compatibility + // Both pooled and non-pooled versions now use the same int16 format + return convertFrame(); } void AudioDecoder::cleanupFfmpeg() { diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index 510234a..34d95e8 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -1,11 +1,12 @@ -#include "echoion/core/CommandManager.hpp" #include "echoion/api/ConfigTypes.hpp" -#include "echoion/core/MusicManager.hpp" +#include "echoion/core/CommandManager.hpp" #include "echoion/core/Logger.hpp" -#include +#include "echoion/core/MusicManager.hpp" +#include "echoion/core/commands/Command.hpp" #include -#include +#include #include +#include namespace Echoion::Core { @@ -89,6 +90,122 @@ public: CommandManager::CommandManager() { registerBuiltinCommands(); registerHelpCommand(); + startThreadPool(); +} + +CommandManager::~CommandManager() { + shutdown(); +} + +void CommandManager::shutdown() { + { + std::lock_guard lock(queueMutex_); + shutdown_ = true; + } + queueCv_.notify_all(); + + for (auto& thread : workerThreads_) { + if (thread.joinable()) { + thread.join(); + } + } + workerThreads_.clear(); +} + +void CommandManager::startThreadPool() { + for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) { + workerThreads_.emplace_back([this]() { + processCommandQueue(); + }); + } + ECHOION_LOG_INFO(std::format("CommandManager thread pool started with {} workers", THREAD_POOL_SIZE)); +} + +void CommandManager::processCommandQueue() { + while (true) { + CommandTask task; + { + std::unique_lock lock(queueMutex_); + queueCv_.wait(lock, [this] { return shutdown_ || !commandQueue_.empty(); }); + + if (shutdown_ && commandQueue_.empty()) { + return; + } + + task = std::move(commandQueue_.front()); + commandQueue_.pop(); + } + + // Execute the command + executeCommandAsync(std::move(task)); + } +} + +void CommandManager::executeCommandAsync(CommandTask task) { + try { + // Re-parse the command (same logic as dispatch) + std::string_view message = task.message; + if (!message.starts_with(prefix_)) { + return; + } + + // Skip prefix and trim + std::string_view input = message.substr(prefix_.length()); + size_t start = input.find_first_not_of(" \t"); + if (start == std::string_view::npos) return; + input = input.substr(start); + + // Split command and args + size_t spacePos = input.find_first_of(" \t"); + std::string_view cmdName = (spacePos == std::string_view::npos) + ? input + : input.substr(0, spacePos); + + std::string argsStr; + if (spacePos != std::string_view::npos) { + size_t argStart = input.find_first_not_of(" \t", spacePos); + if (argStart != std::string_view::npos) { + argsStr = std::string(input.substr(argStart)); + } + } + + std::string cmdKey(cmdName); + std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower); + + CommandPtr command; + { + std::lock_guard lock(mutex_); + auto it = commands_.find(cmdKey); + if (it == commands_.end()) { + return; + } + command = it->second; + } + + // Check permissions + if (!canExecuteCommand(task.clientId, command)) { + task.replyFunc("You don't have permission to use this command."); + return; + } + + // Execute command + CommandContext ctx{ + .clientId = task.clientId, + .prefix = prefix_, + .args = std::move(argsStr), + .invokerName = task.invokerName, + .musicManager = task.musicManager, + .replyCallback = std::move(task.replyFunc) + }; + + command->execute(ctx); + + } catch (const std::exception& e) { + ECHOION_LOG_ERROR(std::format("Async command execution error: {}", e.what())); + try { + task.replyFunc("An error occurred while executing the command."); + } catch (...) {} + } } bool CommandManager::dispatch( @@ -110,6 +227,73 @@ bool CommandManager::dispatch( } input = input.substr(start); + // Split command and arguments + size_t spacePos = input.find_first_of(" \t"); + std::string_view cmdName = (spacePos == std::string_view::npos) + ? input + : input.substr(0, spacePos); + + // Convert to lowercase for lookup + std::string cmdKey(cmdName); + std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower); + + // Check if command exists + CommandPtr command; + { + std::lock_guard lock(mutex_); + auto it = commands_.find(cmdKey); + if (it == commands_.end()) { + return false; + } + command = it->second; + } + + // Check permissions synchronously (fast check) + if (!canExecuteCommand(clientId, command)) { + replyFunc("You don't have permission to use this command."); + return true; // Command was found but not allowed + } + + // Queue the command for async execution + CommandTask task{ + .clientId = clientId, + .message = std::string(message), + .musicManager = musicManager, + .replyFunc = std::move(replyFunc), + .invokerName = std::string(invokerName) + }; + + { + std::lock_guard lock(queueMutex_); + if (shutdown_) { + return false; + } + commandQueue_.push(std::move(task)); + } + queueCv_.notify_one(); + + return true; +} + +bool CommandManager::dispatchSync( + uint64_t clientId, + std::string_view message, + std::weak_ptr musicManager, + std::function replyFunc, + std::string_view invokerName) { + + if (!message.starts_with(prefix_)) { + return false; + } + + // Skip prefix and trim leading whitespace + std::string_view input = message.substr(prefix_.length()); + size_t start = input.find_first_not_of(" \t"); + if (start == std::string_view::npos) { + return false; + } + input = input.substr(start); + // Split command and arguments size_t spacePos = input.find_first_of(" \t"); std::string_view cmdName = (spacePos == std::string_view::npos) @@ -141,11 +325,12 @@ bool CommandManager::dispatch( // Check permissions if (!canExecuteCommand(clientId, command)) { replyFunc("You don't have permission to use this command."); - return true; // Command was found but not allowed + return true; } CommandContext ctx{ .clientId = clientId, + .prefix = prefix_, .args = std::move(argsStr), .invokerName = invokerName, .musicManager = musicManager, @@ -155,7 +340,8 @@ bool CommandManager::dispatch( try { command->execute(ctx); } catch (const std::exception& e) { - ECHOION_LOG_ERROR(std::format("Command execution error [{}]: {}", cmdKey, e.what())); + ECHOION_LOG_ERROR( + std::format("Command execution error [{}]: {}", cmdKey, e.what())); ctx.reply("An unexpected error occurred. Our team has been notified."); } @@ -216,12 +402,13 @@ bool CommandManager::canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) } // Check permission via callback if set - if (permissionCheck_) { - return permissionCheck_(clientId, cmd->getCategory()); - } - - // Default: deny admin commands if no checker configured - return false; + if (permissionCheck_ && (cmd->requiresAdmin() || + cmd->getCategory() == CommandCategory::Admin)) { + return permissionCheck_(clientId, cmd->getCategory()); + } + + // Default: deny admin commands if no checker configured + return false; } void CommandManager::setPrefix(std::string_view prefix) { @@ -245,9 +432,9 @@ void CommandManager::registerBuiltinCommands() { registerCommand("resume"); registerCommand("stop"); registerCommand("skip"); - registerCommand("seek"); - registerCommand("volume"); - registerCommand("queue"); + // registerCommand("seek"); + registerCommand("volume"); + registerCommand("queue"); registerCommand("remove"); registerCommand("clear"); registerCommand("move"); @@ -260,6 +447,9 @@ void CommandManager::registerBuiltinCommands() { registerCommand("reloadconfig"); registerCommand("subscribe"); registerCommand("unsubscribe"); + registerCommand("subscribers"); + registerCommand("unsubscribeid"); + registerCommand("unsubscribeall"); } void CommandManager::registerHelpCommand() { diff --git a/src/ConfigLoader.cpp b/src/ConfigLoader.cpp index 2eb17c7..83e5182 100644 --- a/src/ConfigLoader.cpp +++ b/src/ConfigLoader.cpp @@ -26,6 +26,9 @@ struct BotConfigJson { uint32_t trackTimeout = 30000; std::optional youtubeCookiesPath; std::optional cookiesFromBrowser; + uint32_t ytDlpMaxConcurrent = 4; + bool ytDlpAsyncEnabled = true; + bool enableUrlShortening = true; }; struct ServerConfigJson { @@ -77,7 +80,10 @@ template<> struct glz::meta { "maxQueueSize", &T::maxQueueSize, "trackTimeout", &T::trackTimeout, "youtubeCookiesPath", &T::youtubeCookiesPath, - "cookiesFromBrowser", &T::cookiesFromBrowser + "cookiesFromBrowser", &T::cookiesFromBrowser, + "ytDlpMaxConcurrent", &T::ytDlpMaxConcurrent, + "ytDlpAsyncEnabled", &T::ytDlpAsyncEnabled, + "enableUrlShortening", &T::enableUrlShortening ); }; @@ -189,6 +195,13 @@ Api::Result ConfigLoader::loadFromFile(const std::filesystem::pa if (jsonConfig.bot.cookiesFromBrowser.has_value()) { config.bot.cookiesFromBrowser = jsonConfig.bot.cookiesFromBrowser; } + + // yt-dlp settings + config.bot.ytDlpMaxConcurrent = std::min(static_cast(jsonConfig.bot.ytDlpMaxConcurrent), size_t(8)); + config.bot.ytDlpAsyncEnabled = jsonConfig.bot.ytDlpAsyncEnabled; + + // URL shortening settings + config.bot.enableUrlShortening = jsonConfig.bot.enableUrlShortening; // Server config config.server.address = jsonConfig.server.address; @@ -248,6 +261,13 @@ Api::Result ConfigLoader::saveToFile(const std::filesystem::path& path, co if (config.bot.cookiesFromBrowser.has_value()) { jsonConfig.bot.cookiesFromBrowser = *config.bot.cookiesFromBrowser; } + + // yt-dlp settings + jsonConfig.bot.ytDlpMaxConcurrent = static_cast(config.bot.ytDlpMaxConcurrent); + jsonConfig.bot.ytDlpAsyncEnabled = config.bot.ytDlpAsyncEnabled; + + // URL shortening settings + jsonConfig.bot.enableUrlShortening = config.bot.enableUrlShortening; // Server config jsonConfig.server.address = config.server.address; @@ -316,6 +336,9 @@ Api::AppConfig ConfigLoader::createDefaultConfig() { config.bot.allowPlaylistImports = true; config.bot.maxQueueSize = 100; config.bot.trackTimeout = std::chrono::milliseconds(30000); + config.bot.ytDlpMaxConcurrent = 4; + config.bot.ytDlpAsyncEnabled = true; + config.bot.enableUrlShortening = true; // Default server config config.server.address = "localhost"; diff --git a/src/Core.cpp b/src/Core.cpp index 5b25ebf..a65f87d 100644 --- a/src/Core.cpp +++ b/src/Core.cpp @@ -3,6 +3,7 @@ #include #include #include +#include namespace Echoion::Core { @@ -50,22 +51,25 @@ Api::Result Core::initialize(const std::filesystem::path& configPath) { return std::unexpected(netResult.error()); } - // Initialize database - database_ = std::make_shared(); - auto dbResult = database_->initialize(); - if (!dbResult) { - ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}", - dbResult.error().message)); - // Not fatal - continue without database - database_ = nullptr; - } else { - ECHOION_LOG_INFO("Database initialized successfully"); - } + // Initialize database alongside config file + database_ = std::make_shared(); + Api::DatabaseConfig dbConfig; + dbConfig.path = configPath.parent_path() / "echoion.db"; + auto dbResult = database_->initialize(dbConfig); + if (!dbResult) { + ECHOION_LOG_WARNING(std::format("Failed to initialize database: {}", + dbResult.error().message)); + // Not fatal - continue without database + database_ = nullptr; + } else { + ECHOION_LOG_INFO("Database initialized successfully"); + } - // Initialize music manager - musicManager_ = std::make_shared(); - auto musicResult = musicManager_->initialize(config_.bot, networkClient_, database_); - if (!musicResult) { + // Initialize music manager + musicManager_ = std::make_shared(); + auto musicResult = + musicManager_->initialize(config_.bot, networkClient_, database_); + if (!musicResult) { return std::unexpected(musicResult.error()); } @@ -80,89 +84,162 @@ Api::Result Core::initialize(const std::filesystem::path& configPath) { if (!pluginInterface_) return false; // Get client info from plugin - auto clientInfo = pluginInterface_->getClient(clientId); - if (!clientInfo || !clientInfo->has_value()) { - return false; - } - - // Admin category requires admin group membership - if (category == CommandCategory::Admin) { - // Check if any admin groups are configured - if (config_.server.adminGroups.empty()) { - return false; // No admin groups configured = no admin access - } - - // Check if client is in any admin group - // This would need to be implemented with proper group checking - // For now, we'll rely on the TS3 plugin to provide this info - // through a future interface - return false; // Default deny until proper group check is implemented - } - - return true; // Non-admin categories are allowed + auto clientInfoResult = pluginInterface_->getClient(clientId); + if (!clientInfoResult || !clientInfoResult->has_value()) { + return false; + } + auto clientInfo = clientInfoResult->value(); + + // Admin category requires admin group membership + if (category == CommandCategory::Admin) { + // Check if any admin groups are configured + if (config_.server.adminGroups.empty()) { + return false; // No admin groups configured = no admin access + } + + // Check if server groups are available + if (clientInfo.serverGroups.empty()) { + ECHOION_LOG_WARNING("Cannot check admin permissions: server " + "groups not available for client " + + std::to_string(clientId)); + return false; // Server groups not available, deny admin access + } + + // Check if client is in any admin group + for (uint64_t adminGroupId : config_.server.adminGroups) { + for (uint64_t clientGroupId : clientInfo.serverGroups) { + if (adminGroupId == clientGroupId) { + return true; // Client is in an admin group + } + } + } + + return false; // Client is not in any admin group + } + + return true; // Non-admin categories are allowed }); - // Set up audio data callback - // Receives float audio from MusicManager (-1.0 to 1.0), converts to bytes for plugin - musicManager_->setAudioDataCallback([this](const std::span data) { - static int callCount = 0; - static auto lastLog = std::chrono::steady_clock::now(); - - if (pluginInterface_ && !data.empty()) { - // Convert float (-1.0 to 1.0) to int16 for TeamSpeak - // Use 32768.0f scaling but ensure we don't overflow - std::vector int16Data(data.size()); - for (size_t i = 0; i < data.size(); ++i) { - float sample = data[i]; - // Soft clipping to prevent hard distortion - if (sample > 0.95f) sample = 0.95f + (sample - 0.95f) * 0.5f; - if (sample < -0.95f) sample = -0.95f + (sample + 0.95f) * 0.5f; - int16Data[i] = static_cast(sample * 32767.0f); - } - - // Send to plugin - auto result = pluginInterface_->sendAudioData(std::span( - reinterpret_cast(int16Data.data()), - int16Data.size() * sizeof(int16_t))); - - callCount++; - auto now = std::chrono::steady_clock::now(); - if (std::chrono::duration_cast(now - lastLog).count() >= 5) { - ECHOION_LOG_DEBUG(std::format("Audio callback: {} calls, {} samples, result: {}", - callCount, data.size(), result.has_value() ? "ok" : "error")); - lastLog = now; - } - } - }); - - // Set up subscription change callback to update whisper list - musicManager_->setSubscriptionChangeCallback([this]() { - updateWhisperList(); - }); - - // Set initial whisper list from loaded subscriptions - updateWhisperList(); + // Set up audio data callback + // Receives int16 audio from MusicManager, sends directly to plugin + musicManager_->setAudioDataCallback([this]( + const std::span data) { + static int callCount = 0; + static auto lastLog = std::chrono::steady_clock::now(); - // Start RPC server for Desktop/API clients - rpcServer_ = std::make_shared(); - uint16_t rpcPort = config_.bot.rpcPort > 0 ? config_.bot.rpcPort : 8765; - auto rpcResult = rpcServer_->start(rpcPort); - if (!rpcResult) { - ECHOION_LOG_WARNING(std::format("Failed to start RPC server: {}", - rpcResult.error().message)); - // Not fatal - continue without RPC - rpcServer_.reset(); - } else { - ECHOION_LOG_INFO(std::format("RPC server started on port {}", rpcPort)); - setupRpcHandlers(); - } + if (pluginInterface_ && !data.empty()) { + // Send int16 data directly to plugin (no conversion needed) + auto result = pluginInterface_->sendAudioData(data); - startTime_ = std::chrono::system_clock::now(); - initialized_ = true; + callCount++; + auto now = std::chrono::steady_clock::now(); + if (std::chrono::duration_cast(now - lastLog) + .count() >= 5) { + ECHOION_LOG_DEBUG(std::format( + "Audio callback: {} calls, {} samples, result: {}", + callCount, data.size(), + result.has_value() ? "ok" : "error")); + lastLog = now; + } + } + }); - ECHOION_LOG_INFO("Echoion Core initialized successfully"); - - // Auto-connect to server if configured + // Set up subscription change callback to update whisper list + musicManager_->setSubscriptionChangeCallback( + [this]() { updateWhisperList(); }); + + // Set up playback start callback to update whisper list before playing + musicManager_->setPlaybackStartCallback([this]() { updateWhisperList(); }); + + // Set up client info callback to resolve UID and nickname from client ID + musicManager_->setClientInfoCallback( + [this](uint64_t clientId) + -> std::optional> { + if (!pluginInterface_) { + ECHOION_LOG_WARNING( + "ClientInfoCallback: pluginInterface is null"); + return std::nullopt; + } + auto clientInfoResult = pluginInterface_->getClient(clientId); + if (!clientInfoResult || !clientInfoResult->has_value()) { + ECHOION_LOG_WARNING(std::format( + "ClientInfoCallback: getClient failed for client {}", + clientId)); + return std::nullopt; + } + auto clientInfo = clientInfoResult->value(); + if (!clientInfo.uniqueIdentifier) { + ECHOION_LOG_WARNING(std::format( + "ClientInfoCallback: client {} has no uniqueIdentifier", + clientId)); + return std::nullopt; + } + ECHOION_LOG_DEBUG( + std::format("ClientInfoCallback: Got UID for client {}: {}", + clientId, *clientInfo.uniqueIdentifier)); + return std::make_pair(*clientInfo.uniqueIdentifier, + clientInfo.nickname); + }); + + // Set up UID to client ID callback + musicManager_->setUidToClientIdCallback( + [this](const std::string& uid) -> std::optional { + if (!pluginInterface_) { + return std::nullopt; + } + auto clients = pluginInterface_->getClients(); + if (!clients) { + return std::nullopt; + } + for (const auto& client : *clients) { + if (client.uniqueIdentifier && + *client.uniqueIdentifier == uid) { + return client.id; + } + } + return std::nullopt; + }); + + // Set up nickname callback + musicManager_->setNicknameCallback( + [this](uint64_t clientId) -> std::optional { + if (!pluginInterface_) { + return std::nullopt; + } + auto clientInfoResult = pluginInterface_->getClient(clientId); + if (!clientInfoResult || !clientInfoResult->has_value()) { + return std::nullopt; + } + return clientInfoResult->value().nickname; + }); + + // Don't call updateWhisperList here - pluginInterface is not set yet + // It will be called when setPluginInterface is called, or when + // subscriptions change + + // Start RPC server for Desktop/API clients + rpcServer_ = std::make_shared(); + uint16_t rpcPort = config_.bot.rpcPort > 0 ? config_.bot.rpcPort : 8765; + auto rpcResult = rpcServer_->start(rpcPort); + if (!rpcResult) { + ECHOION_LOG_WARNING(std::format("Failed to start RPC server: {}", + rpcResult.error().message)); + // Not fatal - continue without RPC + rpcServer_.reset(); + } else { + ECHOION_LOG_INFO(std::format("RPC server started on port {}", rpcPort)); + setupRpcHandlers(); + } + + startTime_ = std::chrono::system_clock::now(); + initialized_ = true; + ECHOION_LOG_INFO(std::format("Core initialized (this={})", reinterpret_cast(this))); + + unsigned int hwThreads = std::thread::hardware_concurrency(); + ECHOION_LOG_INFO(std::format("Hardware concurrency: {} threads", hwThreads)); + ECHOION_LOG_INFO("Echoion Core initialized successfully"); + + // Auto-connect to server if configured if (!config_.server.address.empty() && pluginInterface_) { ECHOION_LOG_INFO(std::format("Auto-connecting to {}:{}...", config_.server.address, config_.server.port)); @@ -186,6 +263,10 @@ Api::Result Core::shutdown() { ECHOION_LOG_INFO("Shutting down Echoion Core..."); + if (commandManager_) { + commandManager_->shutdown(); + } + if (musicManager_) { musicManager_->shutdown(); } @@ -211,7 +292,7 @@ Api::Result Core::shutdown() { } initialized_ = false; - ECHOION_LOG_INFO("Echoion Core shutdown complete"); + ECHOION_LOG_INFO(std::format("Echoion Core shutdown complete (this={})", reinterpret_cast(this))); return {}; } @@ -559,15 +640,27 @@ void Core::unregisterEventCallback(const Api::EventCallback& callback) { } Api::Result Core::onPluginEvent(const Api::PluginEvent& event) { + ECHOION_LOG_DEBUG(std::format("Core::onPluginEvent called (this={}, initialized={})", + reinterpret_cast(this), initialized_.load())); if (!initialized_) { + ECHOION_LOG_WARNING(std::format("Core::onPluginEvent: Core not initialized (this={}), ignoring event type={}", + reinterpret_cast(this), static_cast(event.type))); return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Core not initialized")); } + // Debug logging for command events + if (event.type == Api::PluginEventType::TextMessageReceived && event.message) { + ECHOION_LOG_DEBUG(std::format("Core received message: {} from client {}", + *event.message, event.clientId)); + } + switch (event.type) { case Api::PluginEventType::TextMessageReceived: if (event.message) { // Check if it's a command if (event.message->starts_with(config_.bot.commandPrefix)) { + ECHOION_LOG_DEBUG(std::format("Processing command: {} from client {}", + *event.message, event.clientId)); // Create reply callback auto replyFunc = [this](uint64_t clientId, std::string_view message) { if (pluginInterface_) { @@ -596,20 +689,27 @@ Api::Result Core::onPluginEvent(const Api::PluginEvent& event) { break; case Api::PluginEventType::ClientConnected: - ECHOION_LOG_INFO(std::format("Client {} connected", event.clientId)); - break; + ECHOION_LOG_INFO(std::format( + "Client {} connected, updating whisper list", event.clientId)); + if (musicManager_) { + musicManager_->onClientConnected(event.clientId); + } + // Update whisper list after client connect + updateWhisperList(); + break; - case Api::PluginEventType::ClientDisconnected: - ECHOION_LOG_INFO(std::format("Client {} disconnected", event.clientId)); - if (musicManager_) { - musicManager_->onClientDisconnected(event.clientId); - } - // Update whisper list after client disconnect - updateWhisperList(); - break; + case Api::PluginEventType::ClientDisconnected: + ECHOION_LOG_INFO( + std::format("Client {} disconnected", event.clientId)); + if (musicManager_) { + musicManager_->onClientDisconnected(event.clientId); + } + // Update whisper list after client disconnect + updateWhisperList(); + break; - default: - // Forward other events to subscribers + default: + // Forward other events to subscribers broadcastEvent(event); break; } @@ -627,6 +727,12 @@ std::chrono::system_clock::time_point Core::getUptime() const { void Core::setPluginInterface(Api::PluginInterfacePtr pluginInterface) { pluginInterface_ = std::move(pluginInterface); + ECHOION_LOG_INFO(std::format("Plugin interface set (this={})", reinterpret_cast(this))); + + // Now that we have the plugin interface, update the whisper list + // This is needed because subscriptions may have been loaded from database + // before the plugin interface was available + updateWhisperList(); } void Core::triggerAutoConnect() { @@ -754,18 +860,25 @@ bool Core::isAdmin(uint64_t clientId) const { void Core::updateWhisperList() { if (!pluginInterface_ || !musicManager_) { - return; - } - - auto subscribers = musicManager_->getSubscribedClients(); - std::vector subscriberVec(subscribers.begin(), subscribers.end()); - - ECHOION_LOG_DEBUG(std::format("Updating whisper list with {} subscribers", subscriberVec.size())); - - auto result = pluginInterface_->setWhisperList(subscriberVec); - if (!result) { - ECHOION_LOG_WARNING(std::format("Failed to update whisper list: {}", result.error().message)); - } + ECHOION_LOG_WARNING( + "updateWhisperList: pluginInterface or musicManager is null"); + return; + } + + auto subscribers = musicManager_->getSubscribedClients(); + std::vector subscriberVec(subscribers.begin(), subscribers.end()); + + ECHOION_LOG_INFO( + std::format("Updating whisper list with {} online subscribers", + subscriberVec.size())); + + auto result = pluginInterface_->setWhisperList(subscriberVec); + if (!result) { + ECHOION_LOG_WARNING(std::format("Failed to update whisper list: {}", + result.error().message)); + } else { + ECHOION_LOG_INFO("Whisper list updated successfully"); + } } void Core::setupRpcHandlers() { diff --git a/src/Database.cpp b/src/Database.cpp index 30db87b..8485c52 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -3,6 +3,7 @@ #include #include #include +#include namespace Echoion::Api { @@ -18,10 +19,15 @@ public: Database::Database() : impl_(std::make_unique()) {} Database::~Database() { - shutdown(); + // Only shutdown if not already shut down + if (!shutdown_.load()) { + shutdown(); + } } Result Database::initialize(const DatabaseConfig& config) { + std::unique_lock lock(mutex_); + impl_->config = config; int rc = sqlite3_open(config.path.c_str(), &impl_->db); @@ -30,7 +36,7 @@ Result Database::initialize(const DatabaseConfig& config) { std::format("Failed to open database: {}", sqlite3_errmsg(impl_->db)))); } - // Enable WAL mode + // Enable WAL mode for better concurrency if (config.walMode) { char* errMsg = nullptr; sqlite3_exec(impl_->db, "PRAGMA journal_mode=WAL;", nullptr, nullptr, &errMsg); @@ -41,8 +47,11 @@ Result Database::initialize(const DatabaseConfig& config) { sqlite3_busy_timeout(impl_->db, static_cast(config.busyTimeout.count())); - // Run migrations + // Run migrations (without lock to avoid deadlock, since migrate() will acquire lock) + lock.unlock(); auto result = migrate(); + lock.lock(); + if (!result) { return result; } @@ -53,6 +62,13 @@ Result Database::initialize(const DatabaseConfig& config) { } void Database::shutdown() { + // Check if already shut down to avoid mutex operations after destruction + if (shutdown_.exchange(true)) { + return; // Already shut down + } + + std::unique_lock lock(mutex_); + if (impl_->db) { sqlite3_close(impl_->db); impl_->db = nullptr; @@ -61,6 +77,10 @@ void Database::shutdown() { } bool Database::isInitialized() const { + if (shutdown_.load()) { + return false; + } + std::shared_lock lock(mutex_); return impl_->initialized; } @@ -171,7 +191,35 @@ Result Database::migrate() { ECHOION_LOG_INFO("Database migration 1 applied"); } - impl_->version = 1; + // Migration 2: Fix subscriptions table to use UID instead of client_id + if (currentVersion < 2) { + const char* migration2 = R"( + DROP TABLE IF EXISTS subscriptions; + + CREATE TABLE subscriptions ( + uid TEXT PRIMARY KEY, + nickname TEXT, + subscribed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ); + + CREATE INDEX IF NOT EXISTS idx_subscriptions_uid ON subscriptions(uid); + )"; + + sqlite3_exec(impl_->db, migration2, nullptr, nullptr, &errMsg); + if (errMsg) { + std::string error = errMsg; + sqlite3_free(errMsg); + return std::unexpected(Error(ErrorCode::DatabaseError, error)); + } + + sqlite3_exec(impl_->db, + "INSERT INTO schema_migrations (version) VALUES (2)", + nullptr, nullptr, nullptr); + + ECHOION_LOG_INFO("Database migration 2 applied: subscriptions now use UID"); + } + + impl_->version = 2; return {}; } @@ -182,6 +230,7 @@ int Database::getCurrentVersion() const { // Playlist operations Result Database::createPlaylist(const std::string& name, const std::string& description, uint64_t createdBy, bool isPublic) { + std::unique_lock lock(mutex_); const char* sql = R"( INSERT INTO playlists (name, description, created_by, is_public) @@ -212,6 +261,8 @@ Result Database::createPlaylist(const std::string& name, } Result> Database::getPlaylist(uint64_t id) { + std::shared_lock lock(mutex_); + const char* sql = R"( SELECT id, name, description, created_by, created_at, updated_at, is_public FROM playlists WHERE id = ?; @@ -272,6 +323,7 @@ Result> Database::getPlaylist(uint64_t id) { } Result> Database::getUserPlaylists(uint64_t userId) { + std::shared_lock lock(mutex_); std::vector playlists; const char* sql = R"( @@ -303,6 +355,7 @@ Result> Database::getUserPlaylists(uint64_t userId) { } Result Database::deletePlaylist(uint64_t id) { + std::unique_lock lock(mutex_); const char* sql = "DELETE FROM playlists WHERE id = ?;"; sqlite3_stmt* stmt; @@ -320,6 +373,7 @@ Result Database::deletePlaylist(uint64_t id) { Result Database::addTrackToPlaylist(uint64_t playlistId, const TrackInfo& track, uint32_t position) { + std::unique_lock lock(mutex_); const char* sql = R"( INSERT INTO playlist_tracks @@ -354,7 +408,10 @@ Result Database::addTrackToPlaylist(uint64_t playlistId, // Playback history Result Database::recordPlayback(const TrackInfo& track, - uint64_t playedBy, std::chrono::milliseconds duration, bool completed) { + uint64_t playedBy, + std::chrono::milliseconds duration, + bool completed) { + std::unique_lock lock(mutex_); const char* sql = R"( INSERT INTO playback_history @@ -382,7 +439,10 @@ Result Database::recordPlayback(const TrackInfo& track, } Result> Database::getPlaybackHistory( - uint64_t userId, size_t limit, size_t offset) { + uint64_t userId, + size_t limit, + size_t offset) { + std::shared_lock lock(mutex_); std::vector history; @@ -422,6 +482,7 @@ Result> Database::getPlaybackHistory( // Favorites Result Database::addFavorite(uint64_t userId, const TrackInfo& track) { + std::unique_lock lock(mutex_); const char* sql = R"( INSERT OR REPLACE INTO user_favorites (user_id, track_url, track_title, track_artist) @@ -446,6 +507,7 @@ Result Database::addFavorite(uint64_t userId, const TrackInfo& track) { } Result Database::removeFavorite(uint64_t userId, const std::string& trackUrl) { + std::unique_lock lock(mutex_); const char* sql = "DELETE FROM user_favorites WHERE user_id = ? AND track_url = ?;"; sqlite3_stmt* stmt; @@ -464,6 +526,7 @@ Result Database::removeFavorite(uint64_t userId, const std::string& trackU } Result Database::isFavorite(uint64_t userId, const std::string& trackUrl) { + std::shared_lock lock(mutex_); const char* sql = "SELECT 1 FROM user_favorites WHERE user_id = ? AND track_url = ? LIMIT 1;"; @@ -483,6 +546,7 @@ Result Database::isFavorite(uint64_t userId, const std::string& trackUrl) } Result> Database::getFavorites(uint64_t userId) { + std::shared_lock lock(mutex_); std::vector favorites; const char* sql = R"( @@ -515,6 +579,7 @@ Result> Database::getFavorites(uint64_t userId) { // Maintenance Result Database::trimHistory(size_t keepCount) { + std::unique_lock lock(mutex_); const char* sql = R"( DELETE FROM playback_history WHERE id NOT IN ( @@ -541,6 +606,7 @@ Result Database::trimHistory(size_t keepCount) { } Result Database::clearUserData(uint64_t userId) { + std::unique_lock lock(mutex_); const char* sql1 = "DELETE FROM user_favorites WHERE user_id = ?;"; const char* sql2 = "DELETE FROM playback_history WHERE played_by = ?;"; const char* sql3 = "DELETE FROM playlists WHERE created_by = ?;"; @@ -559,15 +625,17 @@ Result Database::clearUserData(uint64_t userId) { } Result Database::vacuum() { + std::unique_lock lock(mutex_); sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr); return {}; } // Subscriptions -Result Database::addSubscriber(uint64_t clientId) { +Result Database::addSubscriber(const std::string& uid, const std::string& nickname) { + std::unique_lock lock(mutex_); const char* sql = R"( - INSERT OR REPLACE INTO subscriptions (client_id) - VALUES (?); + INSERT OR REPLACE INTO subscriptions (uid, nickname, subscribed_at) + VALUES (?, ?, CURRENT_TIMESTAMP); )"; sqlite3_stmt* stmt; @@ -576,15 +644,17 @@ Result Database::addSubscriber(uint64_t clientId) { sqlite3_errmsg(impl_->db))); } - sqlite3_bind_int64(stmt, 1, static_cast(clientId)); + sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); + sqlite3_bind_text(stmt, 2, nickname.c_str(), -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); return {}; } -Result Database::removeSubscriber(uint64_t clientId) { - const char* sql = "DELETE FROM subscriptions WHERE client_id = ?;"; +Result Database::removeSubscriber(const std::string& uid) { + std::unique_lock lock(mutex_); + const char* sql = "DELETE FROM subscriptions WHERE uid = ?;"; sqlite3_stmt* stmt; if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) { @@ -592,16 +662,17 @@ Result Database::removeSubscriber(uint64_t clientId) { sqlite3_errmsg(impl_->db))); } - sqlite3_bind_int64(stmt, 1, static_cast(clientId)); + sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); return {}; } -Result Database::isSubscriber(uint64_t clientId) { +Result Database::isSubscriber(const std::string& uid) { + std::shared_lock lock(mutex_); const char* sql = - "SELECT 1 FROM subscriptions WHERE client_id = ? LIMIT 1;"; + "SELECT 1 FROM subscriptions WHERE uid = ? LIMIT 1;"; sqlite3_stmt* stmt; if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) { @@ -609,17 +680,18 @@ Result Database::isSubscriber(uint64_t clientId) { sqlite3_errmsg(impl_->db))); } - sqlite3_bind_int64(stmt, 1, static_cast(clientId)); + sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC); bool found = sqlite3_step(stmt) == SQLITE_ROW; sqlite3_finalize(stmt); return found; } -Result> Database::getAllSubscribers() { - std::vector subscribers; +Result> Database::getAllSubscribers() { + std::shared_lock lock(mutex_); + std::vector subscribers; - const char* sql = "SELECT client_id FROM subscriptions;"; + const char* sql = "SELECT uid, nickname, subscribed_at FROM subscriptions;"; sqlite3_stmt* stmt; if (sqlite3_prepare_v2(impl_->db, sql, -1, &stmt, nullptr) != SQLITE_OK) { @@ -628,14 +700,26 @@ Result> Database::getAllSubscribers() { } while (sqlite3_step(stmt) == SQLITE_ROW) { - subscribers.push_back(static_cast(sqlite3_column_int64(stmt, 0))); + SubscriberInfo info; + info.uid = reinterpret_cast(sqlite3_column_text(stmt, 0)); + info.nickname = reinterpret_cast(sqlite3_column_text(stmt, 1)); + info.subscribedAt = std::chrono::system_clock::from_time_t( + sqlite3_column_int64(stmt, 2)); + subscribers.push_back(std::move(info)); } sqlite3_finalize(stmt); return subscribers; } +Result Database::clearAllSubscribers() { + std::unique_lock lock(mutex_); + sqlite3_exec(impl_->db, "DELETE FROM subscriptions;", nullptr, nullptr, nullptr); + return {}; +} + Result Database::getSubscriberCount() { + std::shared_lock lock(mutex_); const char* sql = "SELECT COUNT(*) FROM subscriptions;"; sqlite3_stmt* stmt; diff --git a/src/Logger.cpp b/src/Logger.cpp index dcd0495..dea8f64 100644 --- a/src/Logger.cpp +++ b/src/Logger.cpp @@ -13,6 +13,9 @@ Logger::Logger(std::string_view logDir, std::string_view baseName) std::error_code ec; std::filesystem::create_directories(logDir_, ec); + // Ensure history directory exists + ensureHistoryDirExists(); + // Open log files for each level openLogFiles(); @@ -39,6 +42,12 @@ Logger::~Logger() { } } +void Logger::ensureHistoryDirExists() { + std::error_code ec; + auto historyDir = logDir_ / "history"; + std::filesystem::create_directories(historyDir, ec); +} + void Logger::openLogFiles() { std::lock_guard lock(fileMutex_); @@ -161,27 +170,94 @@ void Logger::writeToFile(Api::LogLevel level, const std::string& formattedEntry) } } +void Logger::moveToHistory(const std::filesystem::path& filePath) { + ensureHistoryDirExists(); + + auto historyDir = logDir_ / "history"; + auto fileName = filePath.filename().string(); + + // Generate timestamp for unique filename + auto now = std::chrono::system_clock::now(); + auto time_t = std::chrono::system_clock::to_time_t(now); + std::tm tm; + localtime_r(&time_t, &tm); + + std::string timestamp = std::format("{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + + auto historyPath = historyDir / std::format("{}.{}", fileName, timestamp); + + std::error_code ec; + std::filesystem::rename(filePath, historyPath, ec); + if (!ec) { + // Clean up old history files (keep last 30) + cleanupOldLogs(); + } +} + +void Logger::cleanupOldLogs() { + ensureHistoryDirExists(); + + auto historyDir = logDir_ / "history"; + if (!std::filesystem::exists(historyDir)) { + return; + } + + // Get all files in history directory + std::vector> files; + + for (const auto& entry : std::filesystem::directory_iterator(historyDir)) { + if (entry.is_regular_file()) { + files.emplace_back(entry.path(), entry.last_write_time()); + } + } + + // Sort by modification time (oldest first) + std::sort(files.begin(), files.end(), + [](const auto& a, const auto& b) { return a.second < b.second; }); + + // Keep only the most recent 30 files + const size_t maxHistoryFiles = 30; + if (files.size() > maxHistoryFiles) { + std::error_code ec; + for (size_t i = 0; i < files.size() - maxHistoryFiles; ++i) { + std::filesystem::remove(files[i].first, ec); + } + } +} + void Logger::rotateIfNeeded(Api::LogLevel level) { std::lock_guard lock(fileMutex_); auto maxSize = maxFileSize_.load(); + auto maxFiles = maxFiles_.load(); // Check level-specific file auto it = levelFiles_.find(level); if (it != levelFiles_.end() && it->second.size >= maxSize) { it->second.stream.close(); - // Rotate: move current to .1, .1 to .2, etc. auto basePath = it->second.path; - for (int i = maxFiles_.load() - 1; i > 0; --i) { - auto oldPath = std::format("{}.{}" , basePath.string(), i); - auto newPath = std::format("{}.{}" , basePath.string(), i + 1); + + // Move oldest to history if at max files + auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles); + if (std::filesystem::exists(oldestPath)) { + moveToHistory(oldestPath); + } + + // Rotate: move .4 to .5, .3 to .4, etc. + for (int i = maxFiles - 1; i > 0; --i) { + auto oldPath = std::format("{}.{}", basePath.string(), i); + auto newPath = std::format("{}.{}", basePath.string(), i + 1); if (std::filesystem::exists(oldPath)) { std::filesystem::rename(oldPath, newPath); } } + + // Move current to .1 if (std::filesystem::exists(basePath)) { - std::filesystem::rename(basePath, std::format("{}.1" , basePath.string())); + std::filesystem::rename(basePath, std::format("{}.1", basePath.string())); } // Reopen @@ -195,15 +271,25 @@ void Logger::rotateIfNeeded(Api::LogLevel level) { combinedFile_.stream.close(); auto basePath = combinedFile_.path; - for (int i = maxFiles_.load() - 1; i > 0; --i) { - auto oldPath = std::format("{}.{}" , basePath.string(), i); - auto newPath = std::format("{}.{}" , basePath.string(), i + 1); + + // Move oldest to history if at max files + auto oldestPath = std::format("{}.{}", basePath.string(), maxFiles); + if (std::filesystem::exists(oldestPath)) { + moveToHistory(oldestPath); + } + + // Rotate: move .4 to .5, .3 to .4, etc. + for (int i = maxFiles - 1; i > 0; --i) { + auto oldPath = std::format("{}.{}", basePath.string(), i); + auto newPath = std::format("{}.{}", basePath.string(), i + 1); if (std::filesystem::exists(oldPath)) { std::filesystem::rename(oldPath, newPath); } } + + // Move current to .1 if (std::filesystem::exists(basePath)) { - std::filesystem::rename(basePath, std::format("{}.1" , basePath.string())); + std::filesystem::rename(basePath, std::format("{}.1", basePath.string())); } combinedFile_.stream.open(basePath, std::ios::app); diff --git a/src/MemoryPool.cpp b/src/MemoryPool.cpp index 410e079..9bdfb83 100644 --- a/src/MemoryPool.cpp +++ b/src/MemoryPool.cpp @@ -10,9 +10,9 @@ AudioBufferPool& AudioBufferPool::instance() { void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) { bufferSize_ = bufferSize; - pool_ = std::make_unique>(bufferSize, poolSize); - ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} MB)", - poolSize, bufferSize, (bufferSize * poolSize * sizeof(float)) / (1024 * 1024))); + pool_ = std::make_unique>(bufferSize, poolSize); + ECHOION_LOG_INFO(std::format("AudioBufferPool initialized: {} buffers of {} samples (~{} KB)", + poolSize, bufferSize, (bufferSize * poolSize * sizeof(int16_t)) / 1024)); } void AudioBufferPool::shutdown() { @@ -20,18 +20,18 @@ void AudioBufferPool::shutdown() { ECHOION_LOG_INFO("AudioBufferPool shutdown"); } -PooledPtr AudioBufferPool::acquireBuffer() { +PooledPtr AudioBufferPool::acquireBuffer() { if (!pool_) { - return PooledPtr(); + return PooledPtr(); } - float* ptr = pool_->acquire(); + int16_t* ptr = pool_->acquire(); if (!ptr) { ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size"); - return PooledPtr(); + return PooledPtr(); } - return PooledPtr(ptr, pool_.get()); + return PooledPtr(ptr, pool_.get()); } size_t AudioBufferPool::getAvailableBuffers() const { diff --git a/src/MusicManager.cpp b/src/MusicManager.cpp index 940a385..08a986b 100644 --- a/src/MusicManager.cpp +++ b/src/MusicManager.cpp @@ -1,9 +1,11 @@ #include "echoion/core/MusicManager.hpp" #include -#include #include -#include #include +#include +#include +#include +#include namespace Echoion::Core { @@ -45,43 +47,64 @@ Api::Result MusicManager::initialize(const Api::BotConfig& config, youTubeClient_->setCookiesFromBrowser(*config.cookiesFromBrowser); ECHOION_LOG_INFO(std::format("Using YouTube cookies from browser: {}", *config.cookiesFromBrowser)); } - - auto ytResult = youTubeClient_->initialize(); - if (!ytResult) { - ECHOION_LOG_WARNING(std::format("Failed to initialize YouTube client: {}", - ytResult.error().message)); - } - audioDecoder_ = std::make_unique(); - auto decoderResult = audioDecoder_->initialize(); - if (!decoderResult) { - return std::unexpected(decoderResult.error()); - } + // Configure proxy for YouTube client + if (config.proxy.has_value() && config.proxy->isValid()) { + youTubeClient_->setProxyConfig(config.proxy); + } - audioDecoder_->setOutputFormat(TEAMSPEAK_SAMPLE_RATE, TEAMSPEAK_CHANNELS); - - // Set proxy config from BotConfig if enabled - if (config.proxy.has_value() && config.proxy->isValid()) { - audioDecoder_->setProxyConfig(config.proxy); - ECHOION_LOG_INFO(std::format("AudioDecoder using {} proxy: {}:{}", - config.proxy->isSocks5() ? "SOCKS5" : "HTTP", - config.proxy->host, - config.proxy->port)); - } - - // Initialize subscription manager with database - subscriptionManager_ = std::make_unique(); - auto subResult = subscriptionManager_->initialize(database); - if (!subResult) { - ECHOION_LOG_WARNING(std::format("Failed to initialize subscription manager: {}", - subResult.error().message)); - // Not fatal - continue without subscriptions - } - - volume_ = config.defaultVolume; + // Configure YouTube API key if provided + if (config.youtubeApiKey.has_value() && !config.youtubeApiKey->empty()) { + youTubeClient_->setApiKey(*config.youtubeApiKey); + } - ECHOION_LOG_INFO("MusicManager initialized"); - return {}; + // Configure concurrent resolution limit + if (config.ytDlpMaxConcurrent > 0) { + youTubeClient_->setMaxConcurrentResolutions(config.ytDlpMaxConcurrent); + } + + // Configure URL shortening + youTubeClient_->setUrlShorteningEnabled(config.enableUrlShortening); + + auto ytResult = youTubeClient_->initialize(); + if (!ytResult) { + ECHOION_LOG_WARNING( + std::format("Failed to initialize YouTube client: {}", + ytResult.error().message)); + } + + audioDecoder_ = std::make_unique(); + auto decoderResult = audioDecoder_->initialize(); + if (!decoderResult) { + return std::unexpected(decoderResult.error()); + } + + audioDecoder_->setOutputFormat(TEAMSPEAK_SAMPLE_RATE, TEAMSPEAK_CHANNELS); + + // Set proxy config from BotConfig if enabled + if (config.proxy.has_value() && config.proxy->isValid()) { + audioDecoder_->setProxyConfig(config.proxy); + ECHOION_LOG_INFO( + std::format("AudioDecoder using {} proxy: {}:{}", + config.proxy->isSocks5() ? "SOCKS5" : "HTTP", + config.proxy->host, + config.proxy->port)); + } + + // Initialize subscription manager with database + subscriptionManager_ = std::make_unique(); + auto subResult = subscriptionManager_->initialize(database); + if (!subResult) { + ECHOION_LOG_WARNING( + std::format("Failed to initialize subscription manager: {}", + subResult.error().message)); + // Not fatal - continue without subscriptions + } + + volume_ = config.defaultVolume; + + ECHOION_LOG_INFO("MusicManager initialized"); + return {}; } void MusicManager::shutdown() { @@ -92,25 +115,31 @@ void MusicManager::shutdown() { playbackThread_.join(); } - if (audioDecoder_) { - audioDecoder_->shutdown(); - } - - // Clean up temp files - std::lock_guard lock(tempFilesMutex_); - for (const auto& filepath : tempFiles_) { - std::error_code ec; - std::filesystem::remove(filepath, ec); - if (!ec) { - ECHOION_LOG_DEBUG(std::format("Cleaned up temp file: {}", filepath)); - } - } - tempFiles_.clear(); - - // Also clean up any remaining files in temp directory - auto cacheDir = std::filesystem::temp_directory_path() / "echoion_audio"; - std::error_code ec; - if (std::filesystem::exists(cacheDir, ec)) { + // Detach playlist loading thread if still running + if (playlistLoadThread_.joinable()) { + playlistLoadThread_.detach(); + } + + if (audioDecoder_) { + audioDecoder_->shutdown(); + } + + // Clean up temp files + std::lock_guard lock(tempFilesMutex_); + for (const auto& filepath : tempFiles_) { + std::error_code ec; + std::filesystem::remove(filepath, ec); + if (!ec) { + ECHOION_LOG_DEBUG( + std::format("Cleaned up temp file: {}", filepath)); + } + } + tempFiles_.clear(); + + // Also clean up any remaining files in temp directory + auto cacheDir = std::filesystem::temp_directory_path() / "echoion_audio"; + std::error_code ec; + if (std::filesystem::exists(cacheDir, ec)) { for (const auto& entry : std::filesystem::directory_iterator(cacheDir, ec)) { std::filesystem::remove(entry.path(), ec); } @@ -121,104 +150,169 @@ void MusicManager::shutdown() { Api::Result MusicManager::play(const std::string& query, uint64_t clientId) { ECHOION_LOG_INFO(std::format("Play request: '{}' from client {}", query, clientId)); - - auto track = resolveQuery(query); - if (!track) { - ECHOION_LOG_ERROR(std::format("Failed to resolve query '{}': {}", query, track.error().message)); - return std::unexpected(track.error()); - } - - ECHOION_LOG_INFO(std::format("Resolved track: {} - {} ({}:{}", - track->title, track->artist, - track->source == Api::TrackSource::YouTube ? "YouTube" : "Unknown", - track->streamUrl.has_value() ? "direct" : "needs extraction")); + auto startTime = std::chrono::steady_clock::now(); - if (!isPlaying_ && !currentTrack_.has_value()) { - currentTrack_ = Api::QueueEntry{ - .queueId = nextQueueId_++, - .track = *track, - .addedAt = std::chrono::system_clock::now(), - .addedBy = std::to_string(clientId), - .isPlaying = true, - .position = std::chrono::milliseconds(0) - }; + // Get nickname for the client + std::string nickname = std::to_string(clientId); + if (nicknameCallback_) { + if (auto n = nicknameCallback_(clientId)) { + nickname = *n; + } + } - ECHOION_LOG_DEBUG("Getting stream URL..."); - auto streamUrl = getStreamUrl(*track); - if (!streamUrl) { - ECHOION_LOG_ERROR(std::format("Failed to get stream URL: {}", streamUrl.error().message)); - currentTrack_.reset(); - return std::unexpected(streamUrl.error()); - } + auto track = resolveQuery(query); + auto afterResolve = std::chrono::steady_clock::now(); + ECHOION_LOG_DEBUG( + std::format("resolveQuery took {} ms", + std::chrono::duration_cast( + afterResolve - startTime) + .count())); + if (!track) { + ECHOION_LOG_ERROR(std::format("Failed to resolve query '{}': {}", query, + track.error().message)); + return std::unexpected(track.error()); + } - ECHOION_LOG_DEBUG("Opening audio source..."); - auto openResult = audioDecoder_->openSource(*streamUrl); - - // If direct open fails and we have a proxy, try downloading through proxy - if (!openResult && config_.proxy.has_value() && config_.proxy->isValid()) { - ECHOION_LOG_INFO("Direct open failed, trying download through proxy..."); - auto downloadedPath = downloadAudioForPlayback(*streamUrl); - if (downloadedPath) { - ECHOION_LOG_INFO(std::format("Downloaded audio to: {}", *downloadedPath)); - openResult = audioDecoder_->openSource(*downloadedPath); - if (openResult) { - // Track temp file for cleanup - std::lock_guard lock(tempFilesMutex_); - tempFiles_.insert(*downloadedPath); - } - } else { - ECHOION_LOG_WARNING(std::format("Failed to download through proxy: {}", - downloadedPath.error().message)); - } - } - - if (!openResult) { - ECHOION_LOG_ERROR(std::format("Failed to open audio source: {}", openResult.error().message)); - currentTrack_.reset(); - return std::unexpected(openResult.error()); - } + ECHOION_LOG_INFO(std::format( + "Resolved track: {} - {} ({}:{}", track->title, track->artist, + track->source == Api::TrackSource::YouTube ? "YouTube" : "Unknown", + track->streamUrl.has_value() ? "direct" : "needs extraction")); - isPlaying_ = true; - isPaused_ = false; + if (!isPlaying_ && !currentTrack_.has_value()) { + currentTrack_ = + Api::QueueEntry{.queueId = nextQueueId_++, + .track = *track, + .addedAt = std::chrono::system_clock::now(), + .addedBy = nickname, + .isPlaying = true, + .position = std::chrono::milliseconds(0)}; - if (!playbackThread_.joinable()) { - playbackThread_ = std::jthread(&MusicManager::playbackThread, this); - } + ECHOION_LOG_DEBUG("Getting stream URL..."); + auto streamStart = std::chrono::steady_clock::now(); + auto streamUrl = getStreamUrl(*track); + ECHOION_LOG_DEBUG( + std::format("getStreamUrl took {} ms", + std::chrono::duration_cast( + std::chrono::steady_clock::now() - streamStart) + .count())); + if (!streamUrl) { + ECHOION_LOG_ERROR(std::format("Failed to get stream URL: {}", + streamUrl.error().message)); + currentTrack_.reset(); + return std::unexpected(streamUrl.error()); + } - cv_.notify_one(); + ECHOION_LOG_DEBUG("Opening audio source..."); + auto openResult = audioDecoder_->openSource(*streamUrl); - ECHOION_LOG_INFO(std::format("Now playing: {} - {}", track->title, track->artist)); - return std::format("{} - {}", track->title, track->artist); - } + // If direct open fails and we have a proxy, try downloading through + // proxy + if (!openResult && config_.proxy.has_value() && + config_.proxy->isValid()) { + ECHOION_LOG_INFO( + "Direct open failed, trying download through proxy..."); + auto downloadedPath = downloadAudioForPlayback(*streamUrl); + if (downloadedPath) { + ECHOION_LOG_INFO( + std::format("Downloaded audio to: {}", *downloadedPath)); + openResult = audioDecoder_->openSource(*downloadedPath); + if (openResult) { + // Track temp file for cleanup + std::lock_guard lock(tempFilesMutex_); + tempFiles_.insert(*downloadedPath); + } + } else { + ECHOION_LOG_WARNING( + std::format("Failed to download through proxy: {}", + downloadedPath.error().message)); + } + } - ECHOION_LOG_DEBUG("Already playing, adding to queue"); - auto queueId = queueTrack(*track, clientId); - if (!queueId) { - return std::unexpected(queueId.error()); - } + if (!openResult) { + ECHOION_LOG_ERROR(std::format("Failed to open audio source: {}", + openResult.error().message)); + currentTrack_.reset(); + return std::unexpected(openResult.error()); + } - return std::format("Added to queue: {} - {}", track->title, track->artist); + isPlaying_ = true; + isPaused_ = false; + + // Initialize time-based position tracking + playbackPosition_ = std::chrono::milliseconds(0); + playbackBasePosition_ = std::chrono::milliseconds(0); + playbackStartTime_ = std::chrono::steady_clock::now(); + + // Reset prefetch state for this new track + prefetchState_.hasPrefetched = false; + prefetchState_.isPrefetching = false; + + // Notify that playback is starting (updates whisper list) + if (playbackStartCallback_) { + playbackStartCallback_(); + } + + // Start playback thread if not running (check both joinable and running + // flag) + if (!playbackThread_.joinable() || !playbackThreadRunning_) { + // Join old thread if it exists but isn't running + if (playbackThread_.joinable()) { + ECHOION_LOG_INFO( + "Joining old playback thread before starting new one..."); + playbackThread_.join(); + } + playbackThread_ = std::jthread(&MusicManager::playbackThread, this); + ECHOION_LOG_INFO("Playback thread started"); + } + + cv_.notify_one(); + + ECHOION_LOG_INFO( + std::format("Now playing: {} - {}", track->title, track->artist)); + return std::format("{} - {}", track->title, track->artist); + } + + ECHOION_LOG_DEBUG("Already playing, adding to queue"); + auto queueId = queueTrack(*track, clientId); + if (!queueId) { + return std::unexpected(queueId.error()); + } + + return std::format("Added to queue: {} - {}", track->title, track->artist); } Api::Result MusicManager::pause() { - if (!isPlaying_ || isPaused_) { - return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Nothing is playing")); - } + std::lock_guard lock(mutex_); - isPaused_ = true; - ECHOION_LOG_INFO("Playback paused"); - return {}; + if (!isPlaying_ || isPaused_) { + return std::unexpected( + Api::Error(Api::ErrorCode::InvalidArgument, "Nothing is playing")); + } + + // Capture current position before pausing + playbackPosition_ = getPlaybackPosition(); + isPaused_ = true; + ECHOION_LOG_INFO( + std::format("Playback paused at {}ms", playbackPosition_.count())); + return {}; } Api::Result MusicManager::resume() { - if (!isPlaying_ || !isPaused_) { - return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Not paused")); - } + std::lock_guard lock(mutex_); - isPaused_ = false; - cv_.notify_one(); - ECHOION_LOG_INFO("Playback resumed"); - return {}; + if (!isPlaying_ || !isPaused_) { + return std::unexpected( + Api::Error(Api::ErrorCode::InvalidArgument, "Not paused")); + } + + // Reset time tracking from current position + playbackBasePosition_ = playbackPosition_; + playbackStartTime_ = std::chrono::steady_clock::now(); + isPaused_ = false; + cv_.notify_one(); + ECHOION_LOG_INFO( + std::format("Playback resumed from {}ms", playbackPosition_.count())); + return {}; } Api::Result MusicManager::stop() { @@ -266,19 +360,25 @@ Api::Result MusicManager::skip(uint32_t count) { .position = std::chrono::milliseconds(0) }; - auto streamUrl = getStreamUrl(nextTrack); - if (streamUrl) { - audioDecoder_->closeSource(); - auto openResult = audioDecoder_->openSource(*streamUrl); - if (!openResult) { - ECHOION_LOG_ERROR(std::format("Failed to open stream: {}", openResult.error().message)); - } - } - } + // Reset position tracking for new track + playbackPosition_ = std::chrono::milliseconds(0); + playbackBasePosition_ = std::chrono::milliseconds(0); + playbackStartTime_ = std::chrono::steady_clock::now(); - cv_.notify_one(); - ECHOION_LOG_INFO(std::format("Skipped {} track(s)", count)); - return {}; + auto streamUrl = getStreamUrl(nextTrack); + if (streamUrl) { + audioDecoder_->closeSource(); + auto openResult = audioDecoder_->openSource(*streamUrl); + if (!openResult) { + ECHOION_LOG_ERROR(std::format("Failed to open stream: {}", + openResult.error().message)); + } + } + } + + cv_.notify_one(); + ECHOION_LOG_INFO(std::format("Skipped {} track(s)", count)); + return {}; } Api::Result MusicManager::seek(std::chrono::milliseconds position) { @@ -291,12 +391,19 @@ Api::Result MusicManager::seek(std::chrono::milliseconds position) { return std::unexpected(result.error()); } - if (currentTrack_) { - currentTrack_->position = position; - } + // Update time-based tracking + playbackPosition_ = position; + playbackBasePosition_ = position; + if (!isPaused_) { + playbackStartTime_ = std::chrono::steady_clock::now(); + } - ECHOION_LOG_INFO(std::format("Seeked to {} ms", position.count())); - return {}; + if (currentTrack_) { + currentTrack_->position = position; + } + + ECHOION_LOG_INFO(std::format("Seeked to {} ms", position.count())); + return {}; } Api::Result MusicManager::setVolume(float volume) { @@ -313,48 +420,89 @@ Api::Result MusicManager::queueTrack(const Api::TrackInfo& track, uint uint64_t queueId; bool shouldStart = false; bool needToStartThread = false; - - { - std::lock_guard lock(mutex_); - if (queue_.size() >= config_.maxQueueSize) { - return std::unexpected(Api::Error(Api::ErrorCode::InvalidArgument, "Queue is full")); - } + // Get nickname for the client + std::string nickname = std::to_string(clientId); + if (nicknameCallback_) { + if (auto n = nicknameCallback_(clientId)) { + nickname = *n; + } + } - queueId = nextQueueId_++; - queue_.push_back(Api::QueueEntry{ - .queueId = queueId, - .track = track, - .addedAt = std::chrono::system_clock::now(), - .addedBy = std::to_string(clientId), - .isPlaying = false, - .position = std::nullopt - }); + { + std::lock_guard lock(mutex_); - ECHOION_LOG_INFO(std::format("Queued: {} - {}", track.title, track.artist)); - - // Check if we should auto-start playback - // Conditions: not playing, not paused, has subscribers, and this was the first track - shouldStart = !isPlaying_ && !isPaused_ && !currentTrack_.has_value() && - hasSubscribers() && queue_.size() == 1; - needToStartThread = !playbackThread_.joinable(); - } - - if (shouldStart) { - ECHOION_LOG_INFO("Auto-starting playback for first track in queue"); - - if (needToStartThread) { - // Start the playback thread - isPlaying_ = true; - playbackThread_ = std::jthread(&MusicManager::playbackThread, this); - ECHOION_LOG_INFO("Started playback thread for auto-play"); - } - - // Notify the thread to process - cv_.notify_one(); - } - - return queueId; + if (queue_.size() >= config_.maxQueueSize) { + return std::unexpected( + Api::Error(Api::ErrorCode::InvalidArgument, "Queue is full")); + } + + queueId = nextQueueId_++; + queue_.push_back( + Api::QueueEntry{.queueId = queueId, + .track = track, + .addedAt = std::chrono::system_clock::now(), + .addedBy = nickname, + .isPlaying = false, + .position = std::nullopt}); + + ECHOION_LOG_INFO( + std::format("Queued: {} - {}", track.title, track.artist)); + + // Check if we should auto-start playback + // Conditions: not playing, not paused, has ONLINE subscribers, and this + // was the first track + shouldStart = !isPlaying_ && !isPaused_ && !currentTrack_.has_value() && + hasOnlineSubscribers() && queue_.size() == 1; + needToStartThread = + !playbackThread_.joinable() && !playbackThreadRunning_; + + ECHOION_LOG_DEBUG( + std::format("queueTrack debug: shouldStart={}, " + "needToStartThread={}, isPlaying_={}, " + "thread_joinable={}, thread_running={}, queue_size={}", + shouldStart, needToStartThread, isPlaying_, + playbackThread_.joinable(), + playbackThreadRunning_.load(), queue_.size())); + } + + if (shouldStart) { + ECHOION_LOG_INFO("Auto-starting playback for first track in queue"); + + // Check if we need to handle an old thread that's done but still + // joinable + if (playbackThread_.joinable() && !playbackThreadRunning_) { + ECHOION_LOG_INFO( + "Joining finished playback thread before starting new one..."); + playbackThread_.join(); + ECHOION_LOG_INFO("Old thread joined"); + needToStartThread = true; + } + + if (needToStartThread) { + // Start the playback thread + isPlaying_ = true; + isPaused_ = false; + + // Initialize time-based position tracking + playbackPosition_ = std::chrono::milliseconds(0); + playbackBasePosition_ = std::chrono::milliseconds(0); + playbackStartTime_ = std::chrono::steady_clock::now(); + + // Notify that playback is starting (updates whisper list) + if (playbackStartCallback_) { + playbackStartCallback_(); + } + + playbackThread_ = std::jthread(&MusicManager::playbackThread, this); + ECHOION_LOG_INFO("Started playback thread for auto-play"); + } + + // Notify the thread to process + cv_.notify_one(); + } + + return queueId; } Api::Result MusicManager::removeFromQueue(uint32_t position) { @@ -408,48 +556,121 @@ Api::Result MusicManager::toggleRepeat() { return repeat_; } -Api::Result MusicManager::loadPlaylist(const std::string& playlistId, uint64_t clientId) { - if (!youTubeClient_) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTube client not available")); - } +Api::Result MusicManager::loadPlaylist(const std::string& playlistIdOrUrl, + uint64_t clientId) +{ + if (!youTubeClient_) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "YouTube client not available")); + } - auto playlist = youTubeClient_->getPlaylist(playlistId); - if (!playlist) { - return std::unexpected(playlist.error()); - } + // Check if already loading a playlist + if (playlistLoading_.load()) { + return std::unexpected( + Api::Error(Api::ErrorCode::AlreadyExists, + "Already loading a playlist, please wait")); + } - std::vector tracks = playlist->tracks; - - if (tracks.empty()) { - return 0; - } + // Extract playlist ID if a full URL was provided + std::string playlistId = playlistIdOrUrl; + if (YouTubeClient::isYouTubeUrl(playlistIdOrUrl)) { + auto extractedId = youTubeClient_->extractPlaylistId(playlistIdOrUrl); + if (extractedId) { + playlistId = *extractedId; + ECHOION_LOG_DEBUG( + std::format("Extracted playlist ID '{}' from URL", playlistId)); + } else { + return std::unexpected( + Api::Error(Api::ErrorCode::InvalidArgument, + "Could not extract playlist ID from URL")); + } + } - std::atomic added{0}; - std::mutex queueMutex; - std::vector> futures; + // Join previous thread if any + if (playlistLoadThread_.joinable()) { + playlistLoadThread_.detach(); + } - size_t batchSize = (tracks.size() + CONCURRENT_LOAD_THREADS - 1) / CONCURRENT_LOAD_THREADS; - - for (uint32_t t = 0; t < CONCURRENT_LOAD_THREADS && t * batchSize < tracks.size(); ++t) { - size_t start = t * batchSize; - size_t end = std::min(start + batchSize, tracks.size()); - - futures.push_back(std::async(std::launch::async, [&, start, end, clientId]() { - for (size_t i = start; i < end; ++i) { - auto result = queueTrack(tracks[i], clientId); - if (result) { - added.fetch_add(1); - } - } - })); - } + // Reset loading state + playlistLoading_ = true; + playlistLoadedCount_ = 0; + playlistTotalCount_ = 0; - for (auto& f : futures) { - f.wait(); - } + ECHOION_LOG_INFO( + std::format("Starting async playlist load: {}", playlistId)); - ECHOION_LOG_INFO(std::format("Loaded {} tracks from playlist", added.load())); - return added.load(); + // Start playlist loading in background thread + playlistLoadThread_ = std::thread([this, playlistId, clientId]() { + std::atomic added{0}; + std::atomic firstTrackAdded{false}; + std::mutex startPlaybackMutex; + + // Use streaming playlist loading - tracks are added as soon as they are + // resolved + youTubeClient_->getPlaylistStreaming( + playlistId, + // Track callback - called for each track as it is resolved + [this, &added, &firstTrackAdded, &startPlaybackMutex, + clientId](Api::TrackInfo&& track) { + playlistLoadedCount_.fetch_add(1); + + bool isFirst = false; + { + std::lock_guard lock(startPlaybackMutex); + isFirst = !firstTrackAdded.load(); + if (isFirst) { + firstTrackAdded = true; + } + } + + // Add track to queue + auto result = queueTrack(track, clientId); + if (result) { + added.fetch_add(1); + + // Start playback immediately on first track + if (isFirst) { + ECHOION_LOG_INFO( + std::format("First track resolved: {} - {}. " + "Starting playback...", + track.title, track.artist)); + + // Start playback in background thread to not block + // streaming + std::thread([this]() { + // Small delay to ensure queue is updated + std::this_thread::sleep_for( + std::chrono::milliseconds(100)); + + std::lock_guard lock(mutex_); + if (!isPlaying_ && !queue_.empty()) { + // Trigger playback start + cv_.notify_one(); + ECHOION_LOG_INFO( + "Playback started from playlist"); + } + }).detach(); + } + } + }, + // On playlist info callback - called when total track count is + // known + [this, playlistId](size_t totalTracks) { + playlistTotalCount_ = totalTracks; + ECHOION_LOG_INFO( + std::format("Playlist '{}' has {} tracks, resolving...", + playlistId, totalTracks)); + }, + // On complete callback + [this, &added]() { + ECHOION_LOG_INFO( + std::format("Playlist streaming complete. Added {} tracks", + added.load())); + playlistLoading_ = false; + }); + }); // End of background thread + + return {}; // Return immediately, loading continues in background } Api::Result> MusicManager::getPlaylists() const { @@ -461,6 +682,39 @@ Api::Result> MusicManager::getCurrentTrack() cons return currentTrack_; } +std::chrono::milliseconds MusicManager::getPlaybackPosition() const +{ + if (!isPlaying_) { + return std::chrono::milliseconds(0); + } + + if (isPaused_) { + return playbackPosition_; + } + + // Safety check: if playbackStartTime_ is not initialized, return base + // position + if (playbackStartTime_.time_since_epoch().count() == 0) { + ECHOION_LOG_DEBUG( + "getPlaybackPosition: playbackStartTime_ not initialized"); + return playbackBasePosition_; + } + + // Calculate elapsed time since last start/resume + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - playbackStartTime_); + auto position = playbackBasePosition_ + elapsed; + + // Sanity check: position shouldn't be negative or more than 24 hours + if (position.count() < 0 || position.count() > 86400000) { + ECHOION_LOG_WARNING(std::format( + "getPlaybackPosition: Invalid position: {}ms", position.count())); + return std::chrono::milliseconds(0); + } + + return position; +} + Api::Result MusicManager::getPlaybackState() const { std::lock_guard lock(mutex_); @@ -469,14 +723,13 @@ Api::Result MusicManager::getPlaybackState() const { state.queue = queue_; state.isPlaying = isPlaying_; state.isPaused = isPaused_; - state.position = currentTrack_ && currentTrack_->position ? - *currentTrack_->position : std::chrono::milliseconds(0); - state.volume = volume_; - state.repeat = repeat_; - state.shuffle = shuffle_; - state.lastUpdate = std::chrono::system_clock::now(); + state.position = getPlaybackPosition(); + state.volume = volume_; + state.repeat = repeat_; + state.shuffle = shuffle_; + state.lastUpdate = std::chrono::system_clock::now(); - return state; + return state; } Api::Result MusicManager::search(const std::string& query) { @@ -529,26 +782,50 @@ Api::Result MusicManager::selectSearchResult( if (!result) { return std::unexpected(result.error()); } - - return std::format("Added to queue: {}", selected.title); + + std::string displayText = selected.title; + if (!selected.artist.empty()) { + displayText = std::format("{} by {}", selected.title, selected.artist); + } + return std::format("Added to queue: [{}]({})", displayText, + selected.shortenedUrl.value_or(selected.originalUrl)); } Api::HotReloadState MusicManager::getStateForHotReload() const { std::lock_guard lock(mutex_); Api::HotReloadState state; - state.playback = getPlaybackState().value_or(Api::PlaybackState{}); - state.queue = queue_; - - if (currentTrack_ && currentTrack_->track.streamUrl) { - state.currentStreamUrl = currentTrack_->track.streamUrl; - } - - state.playbackPosition = currentTrack_ && currentTrack_->position ? - *currentTrack_->position : std::chrono::milliseconds(0); - state.config = config_; - return state; + // Build playback state directly (don't call getPlaybackState to avoid + // double-lock) + state.playback.currentTrack = currentTrack_; + state.playback.queue = queue_; + state.playback.isPlaying = isPlaying_; + state.playback.isPaused = isPaused_; + // Calculate position directly using time-based tracking + if (isPlaying_ && !isPaused_) { + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - playbackStartTime_); + state.playback.position = playbackBasePosition_ + elapsed; + } else { + state.playback.position = + isPaused_ ? playbackPosition_ : std::chrono::milliseconds(0); + } + state.playback.volume = volume_; + state.playback.repeat = repeat_; + state.playback.shuffle = shuffle_; + state.playback.lastUpdate = std::chrono::system_clock::now(); + + state.queue = queue_; + + if (currentTrack_ && currentTrack_->track.streamUrl) { + state.currentStreamUrl = currentTrack_->track.streamUrl; + } + + state.playbackPosition = state.playback.position; + state.config = config_; + + return state; } Api::Result MusicManager::restoreFromHotReload(const Api::HotReloadState& state) { @@ -558,26 +835,82 @@ Api::Result MusicManager::restoreFromHotReload(const Api::HotReloadState& shuffle_ = state.playback.shuffle; repeat_ = state.playback.repeat; - if (state.shouldPreservePlayback() && state.currentStreamUrl) { - auto openResult = audioDecoder_->openSource(*state.currentStreamUrl); - if (openResult) { - auto seekResult = audioDecoder_->seek(state.playbackPosition); + ECHOION_LOG_INFO( + std::format("restoreFromHotReload: shouldPreservePlayback={}, " + "hasStreamUrl={}, isPlaying={}, hasCurrentTrack={}", + state.shouldPreservePlayback(), + state.currentStreamUrl.has_value(), + state.playback.isPlaying, + state.playback.currentTrack.has_value())); + + if (state.shouldPreservePlayback() && state.currentStreamUrl) { + ECHOION_LOG_INFO(std::format("Restoring playback from position {}ms", + state.playbackPosition.count())); + auto openResult = audioDecoder_->openSource(*state.currentStreamUrl); + if (openResult) { + auto seekResult = audioDecoder_->seek(state.playbackPosition); if (seekResult) { currentTrack_ = state.playback.currentTrack; isPlaying_ = true; isPaused_ = state.playback.isPaused; - if (!playbackThread_.joinable()) { - playbackThread_ = std::jthread(&MusicManager::playbackThread, this); - } + // Initialize position tracking from restored state + playbackPosition_ = state.playbackPosition; + playbackBasePosition_ = state.playbackPosition; + if (!isPaused_) { + playbackStartTime_ = std::chrono::steady_clock::now(); + } - cv_.notify_one(); - } - } - } + // Start thread if not running (check both joinable and running + // flag) + if (!playbackThread_.joinable() || !playbackThreadRunning_) { + if (playbackThread_.joinable()) { + playbackThread_.join(); + } + playbackThread_ = + std::jthread(&MusicManager::playbackThread, this); + } - ECHOION_LOG_INFO("State restored from hot reload"); - return {}; + cv_.notify_one(); + ECHOION_LOG_INFO("Playback restored successfully"); + } else { + ECHOION_LOG_ERROR( + std::format("Failed to seek to position {}ms: {}", + state.playbackPosition.count(), + seekResult.error().message)); + } + } else { + ECHOION_LOG_ERROR(std::format("Failed to open stream URL: {}", + openResult.error().message)); + } + } else { + ECHOION_LOG_INFO( + std::format("Playback not restored: conditions not met " + "(isPlaying={}, hasTrack={}, hasUrl={})", + state.playback.isPlaying, + state.playback.currentTrack.has_value(), + state.currentStreamUrl.has_value())); + } + + // If playback wasn't restored but we have queue and subscribers, start + // thread for auto-start + if (!currentTrack_.has_value() && !queue_.empty() && + hasOnlineSubscribers()) { + ECHOION_LOG_INFO("Playback not restored but queue has items, starting " + "thread for auto-start"); + if (playbackThread_.joinable()) { + playbackThread_.join(); + } + // Start thread so it can auto-start from queue + if (!playbackThread_.joinable() || !playbackThreadRunning_) { + + playbackThread_ = std::jthread(&MusicManager::playbackThread, this); + } + cv_.notify_one(); + } + + ECHOION_LOG_INFO("State restored from hot reload"); + return {}; } void MusicManager::setAudioDataCallback(const AudioDataCallback& callback) { @@ -588,215 +921,326 @@ void MusicManager::setSubscriptionChangeCallback(const SubscriptionChangeCallbac subscriptionChangeCallback_ = callback; } +void MusicManager::setPlaybackStartCallback( + const PlaybackStartCallback& callback) +{ + playbackStartCallback_ = callback; +} + +void MusicManager::setClientInfoCallback(const ClientInfoCallback& callback) +{ + clientInfoCallback_ = callback; +} + +void MusicManager::setUidToClientIdCallback( + const UidToClientIdCallback& callback) +{ + uidToClientIdCallback_ = callback; +} + +void MusicManager::setNicknameCallback(const NicknameCallback& callback) +{ + nicknameCallback_ = callback; +} + void MusicManager::playbackThread() { ECHOION_LOG_DEBUG("Playback thread started"); - - // Constants for 192kHz 20ms chunks (like reference) - constexpr int CHUNK_MS = 20; - constexpr size_t SHORTS_PER_CHUNK = (TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000; - constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50; - - std::vector localAudioBuffer; - auto next = std::chrono::steady_clock::now(); - int chunksSent = 0; - - while (true) { - { - std::unique_lock lock(mutex_); - cv_.wait(lock, [this] { - return !isPlaying_ || !isPaused_ || - (hasSubscribers() && !queue_.empty() && !currentTrack_.has_value()); - }); - - // Auto-start if we have subscribers and queue but no current track - if (hasSubscribers() && !queue_.empty() && !currentTrack_.has_value() && !wasPausedForNoSubscribers_) { - if (!isPlaying_) { - isPlaying_ = true; - isPaused_ = false; - } - // Start first track from queue - auto firstTrack = queue_.front(); - queue_.erase(queue_.begin()); - - auto streamUrl = getStreamUrl(firstTrack.track); - if (streamUrl) { - currentTrack_ = Api::QueueEntry{ - .queueId = firstTrack.queueId, - .track = firstTrack.track, - .addedAt = firstTrack.addedAt, - .addedBy = firstTrack.addedBy, - .isPlaying = true, - .position = std::chrono::milliseconds(0) - }; - - lock.unlock(); - auto openResult = audioDecoder_->openSource(*streamUrl); - if (!openResult) { - ECHOION_LOG_ERROR(std::format("Failed to open first track: {}", openResult.error().message)); - lock.lock(); - currentTrack_.reset(); - isPlaying_ = false; - continue; - } - lock.lock(); - - ECHOION_LOG_INFO(std::format("Auto-started playback: {} - {}", - firstTrack.track.title, firstTrack.track.artist)); - } - } - - if (!isPlaying_) break; - } + playbackThreadRunning_ = true; - if (isPaused_) continue; + // Constants for 192kHz 20ms chunks (like reference) + constexpr int CHUNK_MS = 20; + constexpr size_t SHORTS_PER_CHUNK = + (TEAMSPEAK_SAMPLE_RATE * TEAMSPEAK_CHANNELS * CHUNK_MS) / 1000; + constexpr size_t MAX_BUFFER_SHORTS = SHORTS_PER_CHUNK * 50; - // Pull data from decoder (like reference) - if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) { - std::vector incomingChunk; - if (audioDecoder_->getNextChunk(incomingChunk)) { - localAudioBuffer.insert(localAudioBuffer.end(), - incomingChunk.begin(), incomingChunk.end()); - if (chunksSent == 0) { - ECHOION_LOG_DEBUG(std::format("First chunk received: {} samples", - incomingChunk.size())); - } - } - } + std::vector localAudioBuffer; + auto next = std::chrono::steady_clock::now(); + int chunksSent = 0; - // Send audio when we have enough - if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) { - // Apply volume (squared for better perception, not cubed to avoid over-amplification) - float volMult = volume_ * volume_; - std::vector floatChunk(SHORTS_PER_CHUNK); + while (true) { + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [this] { + return !isPlaying_ || !isPaused_ || + (hasOnlineSubscribers() && !queue_.empty() && + !currentTrack_.has_value()); + }); - for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) { - // Convert int16 to float and apply volume - float sample = (localAudioBuffer[i] / 32768.0f) * volMult; - // Soft limiting to prevent clipping - floatChunk[i] = std::clamp(sample, -0.95f, 0.95f); - } + // Auto-start if we have ONLINE subscribers and queue but no current + // track + if (hasOnlineSubscribers() && !queue_.empty() && + !currentTrack_.has_value() && !wasPausedForNoSubscribers_) { + if (!isPlaying_) { + isPlaying_ = true; + isPaused_ = false; - localAudioBuffer.erase(localAudioBuffer.begin(), - localAudioBuffer.begin() + SHORTS_PER_CHUNK); + // Initialize time-based position tracking + playbackPosition_ = std::chrono::milliseconds(0); + playbackBasePosition_ = std::chrono::milliseconds(0); + playbackStartTime_ = std::chrono::steady_clock::now(); - // Send float audio to callback - if (audioCallback_) { - audioCallback_(std::span(floatChunk.data(), floatChunk.size())); - - chunksSent++; - if (chunksSent == 1 || chunksSent % 100 == 0) { - ECHOION_LOG_DEBUG(std::format("Sent {} chunks, buffer: {}", - chunksSent, localAudioBuffer.size())); - } - } else if (chunksSent == 0) { - ECHOION_LOG_WARNING("No audio callback set!"); - } + // Notify that playback is starting (updates whisper list) + if (playbackStartCallback_) { + playbackStartCallback_(); + } + } + // Start first track from queue + auto firstTrack = queue_.front(); + queue_.erase(queue_.begin()); - // Precision timing (like reference) - next += std::chrono::milliseconds(CHUNK_MS); - std::this_thread::sleep_until(next); - } else { - // Buffer underrun - wait for more data - if (chunksSent == 0) { - ECHOION_LOG_DEBUG(std::format("Waiting for data: {} < {}", - localAudioBuffer.size(), SHORTS_PER_CHUNK)); - } - - std::vector incoming; - if (audioDecoder_->getNextChunk(incoming, true)) { // Blocking wait - localAudioBuffer.insert(localAudioBuffer.end(), - incoming.begin(), incoming.end()); - continue; - } + auto streamUrl = getStreamUrl(firstTrack.track); + if (streamUrl) { + currentTrack_ = Api::QueueEntry{ + .queueId = firstTrack.queueId, + .track = firstTrack.track, + .addedAt = firstTrack.addedAt, + .addedBy = firstTrack.addedBy, + .isPlaying = true, + .position = std::chrono::milliseconds(0)}; - // Check if finished - bool decoderFinished = audioDecoder_->isFinished(); - - if (decoderFinished) { - // Send ALL remaining data in multiple chunks if needed (LAST FLUSH) - size_t totalFlushed = 0; - while (!localAudioBuffer.empty()) { - size_t toSend = std::min(localAudioBuffer.size(), SHORTS_PER_CHUNK); - totalFlushed += toSend; - - float volMult = volume_ * volume_; - std::vector floatChunk(SHORTS_PER_CHUNK, 0.0f); - - // Copy actual data, rest is silence - for (size_t i = 0; i < toSend; ++i) { - float sample = (localAudioBuffer[i] / 32768.0f) * volMult; - floatChunk[i] = std::clamp(sample, -0.95f, 0.95f); - } - - if (audioCallback_) { - audioCallback_(std::span(floatChunk.data(), floatChunk.size())); - chunksSent++; - - // Small delay to let audio play - std::this_thread::sleep_for(std::chrono::milliseconds(CHUNK_MS)); - } - - // Remove sent samples from buffer - localAudioBuffer.erase(localAudioBuffer.begin(), - localAudioBuffer.begin() + toSend); - } - - if (totalFlushed > 0) { - ECHOION_LOG_INFO(std::format("Playback finished with last flush, sent {} chunks, flushed {} samples", - chunksSent, totalFlushed)); - } else { - ECHOION_LOG_INFO(std::format("Playback finished, sent {} chunks", chunksSent)); - } - - onTrackFinished(); - - // Check if playback should continue (more tracks available) - { - std::lock_guard lock(mutex_); - if (!isPlaying_) { - ECHOION_LOG_DEBUG("Playback stopped (no more tracks)"); - break; // Exit thread if no more tracks - } - } - - // Reset for next track - chunksSent = 0; - next = std::chrono::steady_clock::now(); - ECHOION_LOG_DEBUG("Continuing to next track..."); - continue; - } - } - } - - ECHOION_LOG_DEBUG("Playback thread exiting"); + lock.unlock(); + auto openResult = audioDecoder_->openSource(*streamUrl); + if (!openResult) { + ECHOION_LOG_ERROR( + std::format("Failed to open first track: {}", + openResult.error().message)); + lock.lock(); + currentTrack_.reset(); + isPlaying_ = false; + continue; + } + lock.lock(); + + ECHOION_LOG_INFO(std::format( + "Auto-started playback: {} - {}", + firstTrack.track.title, firstTrack.track.artist)); + } + } + + if (!isPlaying_) { + break; + } + } + + if (isPaused_) { + continue; + } + + // Pull data from decoder (like reference) + if (localAudioBuffer.size() < MAX_BUFFER_SHORTS) { + std::vector incomingChunk; + if (audioDecoder_->getNextChunk(incomingChunk)) { + localAudioBuffer.insert(localAudioBuffer.end(), + incomingChunk.begin(), + incomingChunk.end()); + if (chunksSent == 0) { + ECHOION_LOG_DEBUG( + std::format("First chunk received: {} samples", + incomingChunk.size())); + } + } + } + // Update current position periodically (every ~2 seconds) + if (chunksSent == 0 && currentTrack_.has_value()) { + std::lock_guard lock(mutex_); + playbackPosition_ = std::chrono::milliseconds(0); + playbackBasePosition_ = std::chrono::milliseconds(0); + playbackStartTime_ = std::chrono::steady_clock::now(); + currentTrack_->position = getPlaybackPosition(); + } + // Check if we should prefetch next track for seamless transition + if (shouldPrefetch()) { + prefetchNextTrack(); + } + + // Note: Position is calculated on-demand via getPlaybackPosition() + // No need to periodically update currentTrack_->position + + // Send audio when we have enough + if (localAudioBuffer.size() >= SHORTS_PER_CHUNK) { + // Apply volume (squared for better perception, not cubed to + // avoid over-amplification) + float volMult = std::pow(volume_, 3.0f); + std::vector audioChunk(SHORTS_PER_CHUNK); + + // Debug: Check if audio data is valid (first chunk only) + if (chunksSent == 0) { + int nonZeroCount = 0; + int maxSample = 0; + for (size_t i = 0; + i < std::min(size_t(100), localAudioBuffer.size()); + ++i) { + if (localAudioBuffer[i] != 0) { + nonZeroCount++; + } + maxSample = std::max(maxSample, std::abs(static_cast( + localAudioBuffer[i]))); + } + ECHOION_LOG_DEBUG( + std::format("Audio debug: volume={:.3f}, volMult={:.3f}, " + "nonZero={}/100, maxSample={}", + volume_, volMult, nonZeroCount, maxSample)); + } + + for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) { + // Apply volume with soft limiting to prevent clipping + int sample = static_cast(localAudioBuffer[i] * volMult); + audioChunk[i] = + static_cast(std::clamp(sample, -32768, 32767)); + } + + localAudioBuffer.erase(localAudioBuffer.begin(), + localAudioBuffer.begin() + SHORTS_PER_CHUNK); + + // Send audio to callback + if (audioCallback_) { + audioCallback_(std::span(audioChunk.data(), + audioChunk.size())); + + chunksSent++; + if (chunksSent == 1 || chunksSent % 100 == 0) { + ECHOION_LOG_DEBUG(std::format("Sent {} chunks, buffer: {}", + chunksSent, + localAudioBuffer.size())); + } + } else if (chunksSent == 0) { + ECHOION_LOG_WARNING("No audio callback set!"); + } + + // Precision timing (like reference) + next += std::chrono::milliseconds(CHUNK_MS); + std::this_thread::sleep_until(next); + } else { + // Buffer underrun - wait for more data + if (chunksSent == 0) { + ECHOION_LOG_DEBUG(std::format("Waiting for data: {} < {}", + localAudioBuffer.size(), + SHORTS_PER_CHUNK)); + } + + std::vector incoming; + if (audioDecoder_->getNextChunk(incoming, + true)) { // Blocking wait + localAudioBuffer.insert(localAudioBuffer.end(), + incoming.begin(), incoming.end()); + continue; + } + + // Check if finished + bool decoderFinished = audioDecoder_->isFinished(); + + if (decoderFinished) { + // Send ALL remaining data in multiple chunks if needed + // (LAST FLUSH) + size_t totalFlushed = 0; + while (!localAudioBuffer.empty()) { + size_t toSend = + std::min(localAudioBuffer.size(), SHORTS_PER_CHUNK); + totalFlushed += toSend; + + float volMult = std::pow(volume_, 3.0f); + + std::vector audioChunk(SHORTS_PER_CHUNK, 0); + + // Copy actual data, rest is silence + for (size_t i = 0; i < toSend; ++i) { + // Apply volume with soft limiting + int sample = + static_cast(localAudioBuffer[i] * volMult); + // Soft limiting to prevent clipping + audioChunk[i] = static_cast( + std::clamp(sample, -32768, 32767)); + } + + if (audioCallback_) { + audioCallback_(std::span( + audioChunk.data(), audioChunk.size())); + chunksSent++; + + // Small delay to let audio play + std::this_thread::sleep_for( + std::chrono::milliseconds(CHUNK_MS)); + } + + // Remove sent samples from buffer + localAudioBuffer.erase(localAudioBuffer.begin(), + localAudioBuffer.begin() + toSend); + } + + if (totalFlushed > 0) { + ECHOION_LOG_INFO( + std::format("Playback finished with last flush, " + "sent {} chunks, flushed {} samples", + chunksSent, totalFlushed)); + } else { + ECHOION_LOG_INFO(std::format( + "Playback finished, sent {} chunks", chunksSent)); + } + + onTrackFinished(); + + // Check if playback should continue (more tracks available) + { + std::lock_guard lock(mutex_); + ECHOION_LOG_DEBUG(std::format( + "Playback thread: isPlaying_={}, queue_size={}, " + "currentTrack.has_value={}", + isPlaying_, queue_.size(), currentTrack_.has_value())); + if (!isPlaying_) { + ECHOION_LOG_INFO( + "Playback thread exiting: isPlaying_ is false"); + break; // Exit thread if no more tracks + } + } + + // Reset for next track + chunksSent = 0; + next = std::chrono::steady_clock::now(); + ECHOION_LOG_DEBUG("Continuing to next track..."); + continue; + } + } + } + + ECHOION_LOG_DEBUG("Playback thread exiting"); + playbackThreadRunning_ = false; } Api::Result MusicManager::resolveQuery(const std::string& query) { if (YouTubeClient::isYouTubeUrl(query)) { - auto videoId = youTubeClient_->extractVideoId(query); - if (videoId) { - return youTubeClient_->getVideoInfo(*videoId); - } + ECHOION_LOG_DEBUG( + std::format("Extracting video ID from URL: {}", query)); + auto videoId = youTubeClient_->extractVideoId(query); + if (videoId) { + ECHOION_LOG_DEBUG( + std::format("Extracted video ID: '{}'", *videoId)); + return youTubeClient_->getVideoInfo(*videoId); + } else { + ECHOION_LOG_WARNING("Failed to extract video ID from URL"); + } - auto playlistId = youTubeClient_->extractPlaylistId(query); - if (playlistId) { - auto playlist = youTubeClient_->getPlaylist(*playlistId); - if (playlist && !playlist->tracks.empty()) { - return playlist->tracks[0]; - } - } - } + auto playlistId = youTubeClient_->extractPlaylistId(query); + if (playlistId) { + ECHOION_LOG_DEBUG( + std::format("Extracted playlist ID: '{}'", *playlistId)); + auto playlist = youTubeClient_->getPlaylist(*playlistId); + if (playlist && !playlist->tracks.empty()) { + return playlist->tracks[0]; + } + } + } - auto searchResult = youTubeClient_->search(query); - if (!searchResult) { - return std::unexpected(searchResult.error()); - } + auto searchResult = youTubeClient_->search(query); + if (!searchResult) { + return std::unexpected(searchResult.error()); + } - if (searchResult->tracks.empty()) { - return std::unexpected(Api::Error(Api::ErrorCode::NotFound, "No results found")); - } + if (searchResult->tracks.empty()) { + return std::unexpected( + Api::Error(Api::ErrorCode::NotFound, "No results found")); + } - return searchResult->tracks[0]; + return searchResult->tracks[0]; } Api::Result MusicManager::getStreamUrl(const Api::TrackInfo& track) { @@ -826,52 +1270,94 @@ Api::Result MusicManager::getStreamUrl(const Api::TrackInfo& track) void MusicManager::onTrackFinished() { std::lock_guard lock(mutex_); - if (repeat_ && currentTrack_.has_value()) { - auto streamUrl = getStreamUrl(currentTrack_->track); - if (streamUrl) { - audioDecoder_->closeSource(); - audioDecoder_->openSource(*streamUrl); - } - return; - } + // Reset prefetch state for next track + prefetchState_.hasPrefetched = false; - if (queue_.empty()) { - // Queue is empty - stop playback but keep thread running for next track - isPlaying_ = false; - currentTrack_.reset(); - audioDecoder_->closeSource(); - ECHOION_LOG_INFO("Queue empty, playback stopped"); - return; - } + if (repeat_ && currentTrack_.has_value()) { + auto streamUrl = getStreamUrl(currentTrack_->track); + if (streamUrl) { + audioDecoder_->closeSource(); + audioDecoder_->openSource(*streamUrl); + } + return; + } - // Play next track from queue - auto nextTrack = getNextTrack(); - ECHOION_LOG_INFO(std::format("Playing next track: {} - {}", nextTrack.title, nextTrack.artist)); - - currentTrack_ = Api::QueueEntry{ - .queueId = nextQueueId_++, - .track = nextTrack, - .addedAt = std::chrono::system_clock::now(), - .addedBy = currentTrack_->addedBy, - .isPlaying = true, - .position = std::chrono::milliseconds(0) - }; + if (queue_.empty()) { + // Queue is empty - stop playback but keep thread running for next track + isPlaying_ = false; + currentTrack_.reset(); + audioDecoder_->closeSource(); + ECHOION_LOG_INFO("Queue empty, playback stopped"); + return; + } - auto streamUrl = getStreamUrl(nextTrack); - if (streamUrl) { - audioDecoder_->closeSource(); - auto result = audioDecoder_->openSource(*streamUrl); - if (!result) { - ECHOION_LOG_ERROR(std::format("Failed to open next track: {}", result.error().message)); - // Remove the failed track and try next - queue_.erase(queue_.begin()); - onTrackFinished(); - } - } else { - ECHOION_LOG_ERROR("Failed to get stream URL for next track"); - queue_.erase(queue_.begin()); - onTrackFinished(); - } + // Play next track from queue + auto nextTrack = getNextTrack(); + ECHOION_LOG_INFO(std::format("Playing next track: {} - {}", nextTrack.title, + nextTrack.artist)); + + currentTrack_ = Api::QueueEntry{.queueId = nextQueueId_++, + .track = nextTrack, + .addedAt = std::chrono::system_clock::now(), + .addedBy = currentTrack_->addedBy, + .isPlaying = true, + .position = std::chrono::milliseconds(0)}; + + // Reset position tracking for new track + playbackPosition_ = std::chrono::milliseconds(0); + playbackBasePosition_ = std::chrono::milliseconds(0); + playbackStartTime_ = std::chrono::steady_clock::now(); + + // Try to use prefetched URL first (seamless transition) + std::optional streamUrl; + if (prefetchState_.streamUrlFuture.valid()) { + auto status = + prefetchState_.streamUrlFuture.wait_for(std::chrono::seconds(0)); + if (status == std::future_status::ready) { + auto result = prefetchState_.streamUrlFuture.get(); + if (result) { + ECHOION_LOG_INFO( + "Using prefetched stream URL for seamless transition"); + streamUrl = *result; + } + } + } + + // If prefetch not ready or failed, fetch synchronously + if (!streamUrl) { + if (prefetchState_.isPrefetching) { + ECHOION_LOG_INFO("Waiting for prefetch to complete..."); + auto result = prefetchState_.streamUrlFuture.get(); + if (result) { + streamUrl = *result; + } + } + + if (!streamUrl) { + ECHOION_LOG_DEBUG( + "No prefetched URL available, fetching synchronously"); + auto result = getStreamUrl(nextTrack); + if (result) { + streamUrl = *result; + } + } + } + + if (streamUrl) { + audioDecoder_->closeSource(); + auto result = audioDecoder_->openSource(*streamUrl); + if (!result) { + ECHOION_LOG_ERROR(std::format("Failed to open next track: {}", + result.error().message)); + // Remove the failed track and try next + queue_.erase(queue_.begin()); + onTrackFinished(); + } + } else { + ECHOION_LOG_ERROR("Failed to get stream URL for next track"); + queue_.erase(queue_.begin()); + onTrackFinished(); + } } Api::TrackInfo MusicManager::getNextTrack() { @@ -897,17 +1383,18 @@ void MusicManager::shuffleQueue() { } std::string MusicManager::getHelpText() const { - return R"(Echoion Music Bot Commands: + return R"(Echoion Music Bot Commands: !play - Play a song or add to queue (supports YouTube URLs and search) !pause - Pause playback !resume - Resume playback !stop - Stop playback and clear queue !skip [n] - Skip current song (optionally skip n songs) -!queue - Show current queue +!queue [page] - Show current queue (optionally specify page number) !volume <0-100> - Set volume level !search - Search for tracks !subscribe - Subscribe to bot's audio output (whisper mode) !unsubscribe - Unsubscribe from bot's audio output +!subscribers - List all subscribed users !help - Show this help message The bot only outputs audio to subscribed users. Subscribe to hear the music! @@ -919,27 +1406,46 @@ Api::Result MusicManager::subscribe(uint64_t clientId) { return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized")); } - - bool added = subscriptionManager_->subscribe(clientId); - - // If we have subscribers now and were paused due to no subscribers, resume - if (added && wasPausedForNoSubscribers_ && isPaused_) { - auto result = resume(); - if (result) { - wasPausedForNoSubscribers_ = false; - } - } - - // Notify about subscription change - if (added && subscriptionChangeCallback_) { - subscriptionChangeCallback_(); - } - - if (added) { - return "You are now subscribed to the bot's audio output!"; - } else { - return "You are already subscribed."; - } + + // Get client info (UID and nickname) from the callback + if (!clientInfoCallback_) { + return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized, + "Client info callback not set")); + } + + auto clientInfo = clientInfoCallback_(clientId); + if (!clientInfo) { + return std::unexpected( + Api::Error(Api::ErrorCode::NotFound, "Could not get client info")); + } + + const auto& [uid, nickname] = *clientInfo; + bool added = subscriptionManager_->subscribe(uid, nickname); + + ECHOION_LOG_INFO(std::format("Subscribe: client {} ({}), added={}", + clientId, nickname, added)); + + // If we have subscribers now and were paused due to no subscribers, resume + if (added && wasPausedForNoSubscribers_ && isPaused_) { + auto result = resume(); + if (result) { + wasPausedForNoSubscribers_ = false; + } + } + + // Notify about subscription change - always trigger for subscribe to update + // whisper list This ensures offline->online transitions update the whisper + // list + if (subscriptionChangeCallback_) { + ECHOION_LOG_INFO("Subscribe: triggering subscriptionChangeCallback"); + subscriptionChangeCallback_(); + } + + if (added) { + return "You are now subscribed to the bot's audio output!"; + } else { + return "You are still subscribed (was already in database)."; + } } Api::Result MusicManager::unsubscribe(uint64_t clientId) { @@ -947,42 +1453,161 @@ Api::Result MusicManager::unsubscribe(uint64_t clientId) { return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "Subscription manager not initialized")); } - - bool removed = subscriptionManager_->unsubscribe(clientId); - - // If no subscribers left and we're playing, pause - if (removed && !subscriptionManager_->hasSubscribers() && isPlaying_ && !isPaused_) { - ECHOION_LOG_INFO("No subscribers left, pausing playback"); - auto result = pause(); - if (result) { - wasPausedForNoSubscribers_ = true; - } - } - - // Notify about subscription change - if (removed && subscriptionChangeCallback_) { - subscriptionChangeCallback_(); - } - - if (removed) { - return "You are now unsubscribed from the bot's audio output."; - } else { - return "You were not subscribed."; - } + + // Get client UID from the callback + if (!clientInfoCallback_) { + return std::unexpected(Api::Error(Api::ErrorCode::NotInitialized, + "Client info callback not set")); + } + + auto clientInfo = clientInfoCallback_(clientId); + if (!clientInfo) { + return std::unexpected( + Api::Error(Api::ErrorCode::NotFound, "Could not get client info")); + } + + const auto& [uid, nickname] = *clientInfo; + bool removed = subscriptionManager_->unsubscribe(uid); + + // If no online subscribers left and we're playing, pause + if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) { + ECHOION_LOG_INFO("No online subscribers left, pausing playback"); + auto result = pause(); + if (result) { + wasPausedForNoSubscribers_ = true; + } + } + + // Notify about subscription change + if (removed && subscriptionChangeCallback_) { + subscriptionChangeCallback_(); + } + + if (removed) { + return "You are now unsubscribed from the bot's audio output."; + } else { + return "You were not subscribed."; + } } -bool MusicManager::isSubscribed(uint64_t clientId) const { - if (!subscriptionManager_) { - return false; - } - return subscriptionManager_->isSubscribed(clientId); +Api::Result MusicManager::unsubscribeByUid(const std::string& uid) +{ + if (!subscriptionManager_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Subscription manager not initialized")); + } + + bool removed = subscriptionManager_->unsubscribe(uid); + + // If no online subscribers left and we're playing, pause + if (removed && !hasOnlineSubscribers() && isPlaying_ && !isPaused_) { + ECHOION_LOG_INFO("No online subscribers left, pausing playback"); + auto result = pause(); + if (result) { + wasPausedForNoSubscribers_ = true; + } + } + + // Notify about subscription change + if (removed && subscriptionChangeCallback_) { + subscriptionChangeCallback_(); + } + + if (removed) { + return "Subscriber removed successfully."; + } else { + return "Subscriber not found."; + } +} + +Api::Result MusicManager::clearAllSubscriptions() +{ + if (!subscriptionManager_) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "Subscription manager not initialized")); + } + + bool cleared = subscriptionManager_->clearAll(); + + // Pause playback if no subscribers + if (cleared && isPlaying_ && !isPaused_) { + ECHOION_LOG_INFO("All subscriptions cleared, pausing playback"); + auto result = pause(); + if (result) { + wasPausedForNoSubscribers_ = true; + } + } + + // Notify about subscription change + if (cleared && subscriptionChangeCallback_) { + subscriptionChangeCallback_(); + } + + if (cleared) { + return "All subscriptions cleared."; + } else { + return "Failed to clear subscriptions."; + } +} + +bool MusicManager::isSubscribed(uint64_t clientId) const +{ + if (!subscriptionManager_ || !clientInfoCallback_) { + return false; + } + auto clientInfo = clientInfoCallback_(clientId); + if (!clientInfo) { + return false; + } + return subscriptionManager_->isSubscribed(clientInfo->first); +} + +std::set MusicManager::getOnlineSubscriberUids() const +{ + std::set onlineUids; + if (!subscriptionManager_ || !uidToClientIdCallback_) { + return onlineUids; + } + + auto allUids = subscriptionManager_->getSubscribedUids(); + for (const auto& uid : allUids) { + // If we can resolve UID to a client ID, the user is online + if (uidToClientIdCallback_(uid).has_value()) { + onlineUids.insert(uid); + } + } + + return onlineUids; } std::set MusicManager::getSubscribedClients() const { - if (!subscriptionManager_) { - return {}; - } - return subscriptionManager_->getSubscribedClients(); + if (!subscriptionManager_ || !uidToClientIdCallback_) { + return {}; + } + + // Resolve UIDs to current session client IDs + std::set clientIds; + auto uids = subscriptionManager_->getSubscribedUids(); + + for (const auto& uid : uids) { + auto clientId = uidToClientIdCallback_(uid); + if (clientId) { + clientIds.insert(*clientId); + } + } + + return clientIds; +} + +std::vector + MusicManager::getSubscribers() const +{ + if (!subscriptionManager_) { + return {}; + } + return subscriptionManager_->getSubscribers(); } bool MusicManager::hasSubscribers() const { @@ -992,32 +1617,120 @@ bool MusicManager::hasSubscribers() const { return subscriptionManager_->hasSubscribers(); } +bool MusicManager::hasOnlineSubscribers() const +{ + if (!subscriptionManager_ || !uidToClientIdCallback_) { + return false; + } + + // Check if any subscribed UID can be resolved to a current client ID + auto uids = subscriptionManager_->getSubscribedUids(); + for (const auto& uid : uids) { + if (uidToClientIdCallback_(uid).has_value()) { + return true; + } + } + return false; +} + +void MusicManager::onClientConnected(uint64_t clientId) +{ + ECHOION_LOG_INFO(std::format("onClientConnected: client {}", clientId)); + + if (!subscriptionManager_ || !clientInfoCallback_) { + ECHOION_LOG_WARNING("onClientConnected: subscriptionManager or " + "clientInfoCallback not set"); + return; + } + + // Get the client's UID + auto clientInfo = clientInfoCallback_(clientId); + if (!clientInfo) { + ECHOION_LOG_WARNING(std::format( + "onClientConnected: could not get client info for {}", clientId)); + return; + } + + const auto& [uid, nickname] = *clientInfo; + + ECHOION_LOG_INFO(std::format( + "onClientConnected: client {} ({}), uid={}, isSubscribed={}", clientId, + nickname, uid, subscriptionManager_->isSubscribed(uid))); + + // Check if this user is subscribed (in offline subscribers) + if (subscriptionManager_->isSubscribed(uid)) { + ECHOION_LOG_INFO( + std::format("Subscribed user {} ({}) connected, moving to online", + nickname, uid)); + + // Update their nickname in case it changed + subscriptionManager_->updateNickname(uid, nickname); + + // Update whisper list to include them + if (subscriptionChangeCallback_) { + ECHOION_LOG_INFO( + "onClientConnected: triggering subscriptionChangeCallback"); + subscriptionChangeCallback_(); + } + + // If we were paused due to no online subscribers, resume playback + if (wasPausedForNoSubscribers_ && isPlaying_ && isPaused_) { + ECHOION_LOG_INFO("Online subscriber returned, resuming playback"); + auto result = resume(); + if (result) { + wasPausedForNoSubscribers_ = false; + } + } + // If we're not playing but have tracks in queue, auto-start + else if (!isPlaying_ && !currentTrack_.has_value() && !queue_.empty()) { + ECHOION_LOG_INFO("Online subscriber connected with tracks in " + "queue, auto-starting"); + // Notify playback thread to start + cv_.notify_one(); + } + } + // If not subscribed, do nothing +} + void MusicManager::onClientDisconnected(uint64_t clientId) { // Clean up any pending search results for this client { std::lock_guard lock(pendingSearchMutex_); pendingSearches_.erase(clientId); } - - if (!subscriptionManager_) { - return; - } - - // Remove client from subscriptions - bool wasSubscribed = subscriptionManager_->isSubscribed(clientId); - if (wasSubscribed) { - subscriptionManager_->unsubscribe(clientId); - ECHOION_LOG_INFO(std::format("Client {} disconnected, removed from subscriptions", clientId)); - - // Check if we need to pause due to no subscribers - if (!subscriptionManager_->hasSubscribers() && isPlaying_ && !isPaused_) { - ECHOION_LOG_INFO("No subscribers left after disconnect, pausing playback"); - auto result = pause(); - if (result) { - wasPausedForNoSubscribers_ = true; - } - } - } + + if (!subscriptionManager_ || !clientInfoCallback_) { + return; + } + + // Get the client's UID + auto clientInfo = clientInfoCallback_(clientId); + if (!clientInfo) { + return; + } + + const auto& [uid, nickname] = *clientInfo; + + // If this was a subscribed user, update whisper list + if (subscriptionManager_->isSubscribed(uid)) { + ECHOION_LOG_INFO(std::format( + "Subscribed user {} ({}) disconnected, moving to offline", nickname, + uid)); + + // Update whisper list to remove them + if (subscriptionChangeCallback_) { + subscriptionChangeCallback_(); + } + + // If no more online subscribers and we're playing, pause + if (!hasOnlineSubscribers() && isPlaying_ && !isPaused_) { + ECHOION_LOG_INFO("No online subscribers left, pausing playback"); + auto result = pause(); + if (result) { + wasPausedForNoSubscribers_ = true; + } + } + } } Api::Result MusicManager::downloadAudioForPlayback(const std::string& url) { @@ -1078,4 +1791,99 @@ void MusicManager::cleanupTempFile(const std::string& filepath) { } } +bool MusicManager::shouldPrefetch() const +{ + std::lock_guard lock(mutex_); + + // Don't prefetch if not playing, no current track, or queue is empty + if (!isPlaying_ || !currentTrack_.has_value() || queue_.empty()) { + return false; + } + + // Don't prefetch if already prefetched or currently prefetching + if (prefetchState_.hasPrefetched.load() || + prefetchState_.isPrefetching.load()) { + return false; + } + + // Check if we're near the end of the current track + auto position = audioDecoder_->getPosition(); + auto streamInfo = audioDecoder_->getStreamInfo(); + + if (!streamInfo) { + ECHOION_LOG_DEBUG("Prefetch: No stream info available"); + return false; + } + + // Handle short tracks: if total duration is less than prefetch threshold, + // start prefetching after we've played at least 2 seconds (to avoid + // immediate prefetch) + if (streamInfo->duration <= PREFETCH_THRESHOLD) { + bool shouldPrefetch = position >= std::chrono::seconds(2); + if (shouldPrefetch) { + ECHOION_LOG_DEBUG(std::format( + "Prefetch: Short track ({}s), position {}s - should prefetch", + streamInfo->duration.count(), position.count())); + } + return shouldPrefetch; + } + + // Normal case: Prefetch when we're within PREFETCH_THRESHOLD of the end + auto timeRemaining = streamInfo->duration - position; + bool shouldPrefetch = timeRemaining <= PREFETCH_THRESHOLD && + timeRemaining > std::chrono::seconds(0); + + // Log when we're getting close to prefetch threshold + if (timeRemaining <= std::chrono::seconds(20) && + timeRemaining > std::chrono::seconds(0)) { + ECHOION_LOG_DEBUG(std::format( + "Prefetch: Time remaining {}s, threshold {}s - {}", + std::chrono::duration_cast(timeRemaining) + .count(), + PREFETCH_THRESHOLD.count(), + shouldPrefetch ? "WILL PREFETCH" : "waiting")); + } + + return shouldPrefetch; +} + +void MusicManager::prefetchNextTrack() +{ + // Check and set prefetching flag + bool expected = false; + if (!prefetchState_.isPrefetching.compare_exchange_strong(expected, true)) { + return; // Already prefetching + } + + ECHOION_LOG_INFO("Starting prefetch of next track stream URL"); + + // Get next track info (copy to avoid holding lock during async operation) + Api::TrackInfo nextTrack; + { + std::lock_guard lock(mutex_); + if (queue_.empty()) { + prefetchState_.isPrefetching = false; + return; + } + nextTrack = + shuffle_ ? queue_[rng_() % queue_.size()].track : queue_[0].track; + } + + // Start async prefetch + prefetchState_.streamUrlFuture = std::async( + std::launch::async, [this, nextTrack]() -> Api::Result { + auto result = getStreamUrl(nextTrack); + if (result) { + ECHOION_LOG_INFO("Prefetch completed successfully"); + } else { + ECHOION_LOG_WARNING( + std::format("Prefetch failed: {}", result.error().message)); + } + return result; + }); + + prefetchState_.hasPrefetched = true; + prefetchState_.isPrefetching = false; +} + } // namespace Echoion::Core diff --git a/src/NetworkClient.cpp b/src/NetworkClient.cpp index 6fd12dd..003ef40 100644 --- a/src/NetworkClient.cpp +++ b/src/NetworkClient.cpp @@ -339,8 +339,8 @@ Api::Result NetworkClient::executeRequest(const Api::HttpRequ asio::io_context ioc; ssl::context ctx(ssl::context::tlsv12_client); ctx.set_default_verify_paths(); - - // Resolve timeout + ctx.set_verify_mode(ssl::verify_none); + // Resolve timeout auto timeout = std::chrono::seconds(req.timeout.count()); Api::HttpResponse response; @@ -433,8 +433,7 @@ Api::HttpResponse NetworkClient::executeWithHttpProxy( // Upgrade socket to SSL ssl::stream stream(std::move(socket), ctx); - stream.set_verify_mode(ssl::verify_peer); - stream.set_verify_callback(ssl::host_name_verification(urlComp.host)); + // SSL verification mode is already set in ctx (verify_none) // Perform SSL handshake stream.handshake(ssl::stream_base::client); @@ -609,8 +608,7 @@ Api::HttpResponse NetworkClient::executeWithSocks5Proxy( if (urlComp.isHttps) { // Upgrade socket to SSL for HTTPS ssl::stream stream(std::move(socket), ctx); - stream.set_verify_mode(ssl::verify_peer); - stream.set_verify_callback(ssl::host_name_verification(urlComp.host)); + // SSL verification mode is already set in ctx (verify_none) // Perform SSL handshake stream.handshake(ssl::stream_base::client); diff --git a/src/SubscriptionManager.cpp b/src/SubscriptionManager.cpp index edd9e6f..689ae26 100644 --- a/src/SubscriptionManager.cpp +++ b/src/SubscriptionManager.cpp @@ -28,14 +28,14 @@ Api::Result SubscriptionManager::initialize(std::shared_ptr ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}", result.error().message)); // Not fatal - start with empty subscriptions } else { - for (auto clientId : *result) { - subscribedClients_.insert(clientId); + for (const auto& subscriber : *result) { + subscribedUids_.insert(subscriber.uid); } } initialized_ = true; ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)", - subscribedClients_.size())); + subscribedUids_.size())); return {}; } @@ -48,68 +48,145 @@ void SubscriptionManager::shutdown() { initialized_ = false; database_.reset(); + subscribedUids_.clear(); ECHOION_LOG_INFO("SubscriptionManager shutdown"); } -bool SubscriptionManager::subscribe(uint64_t clientId) { +bool SubscriptionManager::subscribe(const std::string& uid, const std::string& nickname) { std::lock_guard lock(mutex_); // Check if already subscribed (ensures uniqueness) - if (subscribedClients_.contains(clientId)) { + if (subscribedUids_.contains(uid)) { + // Update nickname even if already subscribed + if (database_) { + database_->addSubscriber(uid, nickname); + } return false; // Already subscribed } // Add to database first if (database_) { - auto result = database_->addSubscriber(clientId); + auto result = database_->addSubscriber(uid, nickname); if (!result) { ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}", - clientId, result.error().message)); + uid, result.error().message)); return false; } } - subscribedClients_.insert(clientId); - ECHOION_LOG_INFO(std::format("Client {} subscribed", clientId)); + subscribedUids_.insert(uid); + ECHOION_LOG_INFO(std::format("Client {} ({}) subscribed", nickname, uid)); return true; } -bool SubscriptionManager::unsubscribe(uint64_t clientId) { +bool SubscriptionManager::unsubscribe(const std::string& uid) { std::lock_guard lock(mutex_); - bool removed = subscribedClients_.erase(clientId) > 0; + bool removed = subscribedUids_.erase(uid) > 0; if (removed) { // Remove from database if (database_) { - auto result = database_->removeSubscriber(clientId); + auto result = database_->removeSubscriber(uid); if (!result) { ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}", - clientId, result.error().message)); + uid, result.error().message)); } } - ECHOION_LOG_INFO(std::format("Client {} unsubscribed", clientId)); + ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid)); } return removed; } -bool SubscriptionManager::isSubscribed(uint64_t clientId) const { +bool SubscriptionManager::isSubscribed(const std::string& uid) const { std::lock_guard lock(mutex_); - return subscribedClients_.contains(clientId); + return subscribedUids_.contains(uid); } -std::set SubscriptionManager::getSubscribedClients() const { +std::vector SubscriptionManager::getSubscribedUids() const { std::lock_guard lock(mutex_); - return subscribedClients_; + return std::vector(subscribedUids_.begin(), subscribedUids_.end()); +} + +std::vector SubscriptionManager::getSubscribers() const { + std::lock_guard lock(mutex_); + std::vector result; + + if (!database_) { + return result; + } + + auto dbSubscribers = database_->getAllSubscribers(); + if (dbSubscribers) { + for (const auto& info : *dbSubscribers) { + if (subscribedUids_.contains(info.uid)) { + result.push_back({info.uid, info.nickname}); + } + } + } + return result; +} + +std::optional SubscriptionManager::getSubscriberNickname(const std::string& uid) const { + std::lock_guard lock(mutex_); + + if (!subscribedUids_.contains(uid) || !database_) { + return std::nullopt; + } + + auto subscribers = database_->getAllSubscribers(); + if (subscribers) { + for (const auto& info : *subscribers) { + if (info.uid == uid) { + return info.nickname; + } + } + } + return std::nullopt; +} + +bool SubscriptionManager::updateNickname(const std::string& uid, const std::string& nickname) { + std::lock_guard lock(mutex_); + + if (!subscribedUids_.contains(uid)) { + return false; + } + + if (database_) { + auto result = database_->addSubscriber(uid, nickname); + if (!result) { + ECHOION_LOG_ERROR(std::format("Failed to update nickname for {}: {}", + uid, result.error().message)); + return false; + } + } + return true; } bool SubscriptionManager::hasSubscribers() const { std::lock_guard lock(mutex_); - return !subscribedClients_.empty(); + return !subscribedUids_.empty(); } size_t SubscriptionManager::getSubscriberCount() const { std::lock_guard lock(mutex_); - return subscribedClients_.size(); + return subscribedUids_.size(); +} + +bool SubscriptionManager::clearAll() { + std::lock_guard lock(mutex_); + + if (database_) { + auto result = database_->clearAllSubscribers(); + if (!result) { + ECHOION_LOG_ERROR(std::format("Failed to clear all subscribers: {}", + result.error().message)); + return false; + } + } + + subscribedUids_.clear(); + ECHOION_LOG_INFO("All subscriptions cleared"); + return true; } } // namespace Echoion::Core diff --git a/src/UrlShortener.cpp b/src/UrlShortener.cpp new file mode 100644 index 0000000..cb9c15d --- /dev/null +++ b/src/UrlShortener.cpp @@ -0,0 +1,144 @@ +#include "echoion/core/UrlShortener.hpp" +#include "echoion/core/Logger.hpp" +#include +#include + +namespace Echoion::Core { + +UrlShortener::UrlShortener(std::shared_ptr networkClient) + : networkClient_(std::move(networkClient)) { +} + +UrlShortener::~UrlShortener() = default; + +Api::Result UrlShortener::shortenYouTubeUrl(std::string_view videoId) { + std::string originalUrl = std::format("https://www.youtube.com/watch?v={}", videoId); + return shortenUrl(originalUrl); +} + +Api::Result UrlShortener::shortenUrl(std::string_view originalUrl) { + // Check cache first + { + std::lock_guard lock(cacheMutex_); + auto it = cache_.find(std::string(originalUrl)); + if (it != cache_.end()) { + auto now = std::chrono::system_clock::now(); + if (now - it->second.timestamp < cacheTtl_) { + ECHOION_LOG_DEBUG(std::format("URL cache hit: {} -> {}", + originalUrl, it->second.shortenedUrl)); + return it->second.shortenedUrl; + } + // Expired, remove from cache + cache_.erase(it); + } + } + + if (!networkClient_) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "Network client not available")); + } + + // faumaray.ru API endpoint for URL shortening + // POST /shorten with JSON body {"longUrl": "https://..."} + // Response: {"shortUrl": "https://faumaray.ru/xxxxx"} + std::string apiUrl = "https://faumaray.ru/shorten"; + + // Build JSON request body - API expects "longUrl" field + std::string jsonBody = std::format(R"({{"longUrl":"{}"}})", originalUrl); + + std::vector headers = { + {"Content-Type", "application/json"}, + {"User-Agent", "EchoionBot/1.0"} + }; + + ECHOION_LOG_DEBUG(std::format("Shortening URL via faumaray.ru: {}", originalUrl)); + + auto response = networkClient_->post(apiUrl, jsonBody, headers); + + if (!response) { + ECHOION_LOG_WARNING(std::format("URL shortening failed: {}", + response.error().message)); + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + "Failed to shorten URL")); + } + + if (!response->isSuccess()) { + ECHOION_LOG_WARNING(std::format("URL shortening returned HTTP {}", + response->statusCode)); + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + std::format("Shortening service returned HTTP {}", response->statusCode))); + } + + try { + // Parse response - expecting {"shortUrl": "https://faumaray.ru/xxxxx"} + glz::generic json; + if (glz::read_json(json, response->body)) { + ECHOION_LOG_WARNING("Failed to parse URL shortening response"); + return std::unexpected(Api::Error(Api::ErrorCode::ParseError, + "Failed to parse shortening response")); + } + + std::string shortenedUrl; + if (json.contains("shortUrl")) { + shortenedUrl = json["shortUrl"].get(); + } else { + ECHOION_LOG_WARNING("No shortUrl field in response"); + return std::unexpected(Api::Error(Api::ErrorCode::ParseError, + "No shortUrl in response")); + } + + // Cache the result + { + std::lock_guard lock(cacheMutex_); + cache_[std::string(originalUrl)] = { + .shortenedUrl = shortenedUrl, + .timestamp = std::chrono::system_clock::now() + }; + } + + ECHOION_LOG_DEBUG(std::format("URL shortened: {} -> {}", originalUrl, shortenedUrl)); + return shortenedUrl; + + } catch (const std::exception& e) { + ECHOION_LOG_WARNING(std::format("Exception parsing shortening response: {}", + e.what())); + return std::unexpected(Api::Error(Api::ErrorCode::ParseError, + "Exception during URL shortening")); + } +} + +std::optional UrlShortener::getCachedUrl(std::string_view originalUrl) const { + std::lock_guard lock(cacheMutex_); + auto it = cache_.find(std::string(originalUrl)); + if (it != cache_.end()) { + auto now = std::chrono::system_clock::now(); + if (now - it->second.timestamp < cacheTtl_) { + return it->second.shortenedUrl; + } + } + return std::nullopt; +} + +void UrlShortener::clearCache() { + std::lock_guard lock(cacheMutex_); + cache_.clear(); +} + +void UrlShortener::setCacheTtl(std::chrono::hours ttl) { + cacheTtl_ = ttl; +} + +void UrlShortener::cleanExpiredCache() { + std::lock_guard lock(cacheMutex_); + auto now = std::chrono::system_clock::now(); + + for (auto it = cache_.begin(); it != cache_.end();) { + if (now - it->second.timestamp >= cacheTtl_) { + it = cache_.erase(it); + } else { + ++it; + } + } +} + +} // namespace Echoion::Core diff --git a/src/YouTubeClient.cpp b/src/YouTubeClient.cpp index bf5f57f..f060b0d 100644 --- a/src/YouTubeClient.cpp +++ b/src/YouTubeClient.cpp @@ -1,16 +1,193 @@ -#include "echoion/core/YouTubeClient.hpp" +#include "echoion/api/LoggerInterface.hpp" #include "echoion/core/Logger.hpp" -#include -#include +#include "echoion/core/YouTubeClient.hpp" #include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include namespace Echoion::Core { -YouTubeClient::YouTubeClient(std::shared_ptr networkClient) - : networkClient_(std::move(networkClient)) - , ytDlpManager_(std::make_unique(networkClient_)) { -} + // URL encode helper function + std::string YouTubeClient::urlEncode(std::string_view value) + { + std::ostringstream encoded; + encoded.fill('0'); + encoded << std::hex; + + for (char c : value) { + if (std::isalnum(static_cast(c)) || c == '-' || + c == '_' || c == '.' || c == '~') { + encoded << c; + } else { + encoded << std::uppercase; + encoded << '%' << std::setw(2) + << static_cast(static_cast(c)); + encoded << std::nouppercase; + } + } + + return encoded.str(); + } + + // HTML entity decode helper function + std::string YouTubeClient::decodeHtmlEntities(std::string_view value) + { + std::string result; + result.reserve(value.size()); + + for (size_t i = 0; i < value.size(); ++i) { + if (value[i] == '&' && i + 1 < value.size()) { + // Check for numeric entities &#nnnn; or &#xhhhh; + if (value[i + 1] == '#') { + size_t endPos = value.find(';', i + 2); + if (endPos != std::string_view::npos) { + try { + if (i + 2 < value.size() && value[i + 2] == 'x') { + // Hexadecimal: &#xhhhh; + std::string hex( + value.substr(i + 3, endPos - i - 3)); + char32_t codePoint = + std::stoul(hex, nullptr, 16); + // Convert to UTF-8 + if (codePoint <= 0x7F) { + result += static_cast(codePoint); + } else if (codePoint <= 0x7FF) { + result += static_cast( + 0xC0 | (codePoint >> 6)); + result += static_cast( + 0x80 | (codePoint & 0x3F)); + } else if (codePoint <= 0xFFFF) { + result += static_cast( + 0xE0 | (codePoint >> 12)); + result += static_cast( + 0x80 | ((codePoint >> 6) & 0x3F)); + result += static_cast( + 0x80 | (codePoint & 0x3F)); + } else { + result += static_cast( + 0xF0 | (codePoint >> 18)); + result += static_cast( + 0x80 | ((codePoint >> 12) & 0x3F)); + result += static_cast( + 0x80 | ((codePoint >> 6) & 0x3F)); + result += static_cast( + 0x80 | (codePoint & 0x3F)); + } + } else { + // Decimal: &#nnnn; + std::string num( + value.substr(i + 2, endPos - i - 2)); + char32_t codePoint = std::stoul(num); + // Convert to UTF-8 + if (codePoint <= 0x7F) { + result += static_cast(codePoint); + } else if (codePoint <= 0x7FF) { + result += static_cast( + 0xC0 | (codePoint >> 6)); + result += static_cast( + 0x80 | (codePoint & 0x3F)); + } else if (codePoint <= 0xFFFF) { + result += static_cast( + 0xE0 | (codePoint >> 12)); + result += static_cast( + 0x80 | ((codePoint >> 6) & 0x3F)); + result += static_cast( + 0x80 | (codePoint & 0x3F)); + } else { + result += static_cast( + 0xF0 | (codePoint >> 18)); + result += static_cast( + 0x80 | ((codePoint >> 12) & 0x3F)); + result += static_cast( + 0x80 | ((codePoint >> 6) & 0x3F)); + result += static_cast( + 0x80 | (codePoint & 0x3F)); + } + } + i = endPos; + continue; + } catch (...) { + // Fall through to append '&' + } + } + } + + // Check for named entities + size_t endPos = value.find(';', i + 1); + if (endPos != std::string_view::npos && endPos - i <= 10) { + std::string_view entity = + value.substr(i + 1, endPos - i - 1); + if (entity == "quot") { + result += '"'; + i = endPos; + continue; + } else if (entity == "amp") { + result += '&'; + i = endPos; + continue; + } else if (entity == "apos") { + result += '\''; + i = endPos; + continue; + } else if (entity == "lt") { + result += '<'; + i = endPos; + continue; + } else if (entity == "gt") { + result += '>'; + i = endPos; + continue; + } else if (entity == "nbsp") { + result += ' '; + i = endPos; + continue; + } else if (entity == "copy") { + result += '\xC2\xA9'; + i = endPos; + continue; + } else if (entity == "reg") { + result += '\xC2\xAE'; + i = endPos; + continue; + } else if (entity == "trade") { + result += '\xE2\x84\xA2'; + i = endPos; + continue; + } else if (entity == "mdash") { + result += '\xE2\x80\x94'; + i = endPos; + continue; + } else if (entity == "ndash") { + result += '\xE2\x80\x93'; + i = endPos; + continue; + } else if (entity == "hellip") { + result += '\xE2\x80\xA6'; + i = endPos; + continue; + } + } + } + result += value[i]; + } + + return result; + } + + YouTubeClient::YouTubeClient(std::shared_ptr networkClient) + : networkClient_(std::move(networkClient)), + ytDlpManager_(std::make_unique(networkClient_)), + urlShortener_(std::make_unique(networkClient_)) + { + } YouTubeClient::~YouTubeClient() { shutdown(); @@ -26,10 +203,13 @@ Api::Result YouTubeClient::initialize() { if (!result) { return result; } - - initialized_ = true; - ECHOION_LOG_INFO("YouTube client initialized successfully"); - return {}; + + // Set thread pool size based on configuration + ytDlpManager_->setThreadPoolSize(maxConcurrentResolutions_); + + initialized_ = true; + ECHOION_LOG_INFO("YouTube client initialized successfully"); + return {}; } void YouTubeClient::setCookiesPath(const std::string& path) { @@ -44,6 +224,64 @@ void YouTubeClient::setCookiesFromBrowser(const std::string& browser) { } } +void YouTubeClient::setProxyConfig(const std::optional& proxy) +{ + if (ytDlpManager_) { + ytDlpManager_->setProxyConfig(proxy); + } + + std::lock_guard lock(configMutex_); + if (proxy.has_value() && proxy->isValid()) { + ECHOION_LOG_INFO(std::format("YouTubeClient proxy configured: {}:{}", + proxy->host, proxy->port)); + } +} + +std::optional YouTubeClient::getProxyConfig() const +{ + if (ytDlpManager_) { + return ytDlpManager_->getProxyConfig(); + } + return std::nullopt; +} + +void YouTubeClient::setApiKey(const std::string& apiKey) +{ + std::lock_guard lock(configMutex_); + apiKey_ = apiKey; + ECHOION_LOG_INFO( + "YouTube API key configured for enhanced playlist resolution"); +} + +bool YouTubeClient::hasApiKey() const +{ + std::lock_guard lock(configMutex_); + return apiKey_.has_value() && !apiKey_->empty(); +} + +void YouTubeClient::setMaxConcurrentResolutions(size_t max) +{ + if (max == 0) { + max = 1; + } + if (max > 8) { + max = 8; // Cap at 8 concurrent resolutions + } + + std::lock_guard lock(configMutex_); + maxConcurrentResolutions_ = max; + + if (ytDlpManager_) { + ytDlpManager_->setThreadPoolSize(max); + } +} + +size_t YouTubeClient::getMaxConcurrentResolutions() const +{ + std::lock_guard lock(configMutex_); + return maxConcurrentResolutions_; +} + void YouTubeClient::shutdown() { initialized_ = false; } @@ -75,33 +313,65 @@ Api::Result YouTubeClient::getAudioStreamUrl(std::string_view video return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "yt-dlp not available")); } - - ECHOION_LOG_INFO(std::format("Getting audio stream URL for video: {}", videoId)); - - // Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm) - // 140 = AAC 128kbps (m4a), 251 = Opus 160kbps (webm) - std::string url = std::format("https://www.youtube.com/watch?v={}", videoId); - // Fallback: try any audio format - ECHOION_LOG_INFO("Trying any audio format..."); - - std::string result = ytDlpManager_->execute({ - url, - "-f", "bestaudio/251/140", - "-g", - "--no-warnings" - }); - - if (!result.empty() && result.back() == '\n') { - result.pop_back(); - } - - if (!result.empty() && result.find("http") == 0) { - ECHOION_LOG_INFO("Successfully got audio URL from yt-dlp (fallback)"); - return result; - } - - return std::unexpected(Api::Error(Api::ErrorCode::NotFound, - "Failed to get audio URL from yt-dlp")); + + if (videoId.empty()) { + return std::unexpected( + Api::Error(Api::ErrorCode::InvalidArgument, "Video ID is empty")); + } + + auto startTime = std::chrono::steady_clock::now(); + ECHOION_LOG_INFO( + std::format("Getting audio stream URL for video: {}", videoId)); + + // Use yt-dlp to get best audio URL - prefer AAC (m4a) over Opus (webm) + // 140 = AAC 128kbps (m4a), 251 = Opus 160kbps (webm) + // Pass just the video ID to yt-dlp + std::string videoIdStr(videoId); + + ECHOION_LOG_DEBUG("Starting yt-dlp audio URL extraction..."); + auto future = ytDlpManager_->executeAsync( + {videoIdStr, "-f", "bestaudio/251/140", "-g", "--no-warnings"}); + + // Wait with timeout (30 seconds) + ECHOION_LOG_DEBUG("Waiting for yt-dlp audio URL (30s timeout)..."); + auto waitStatus = future.wait_for(std::chrono::seconds(30)); + + if (waitStatus == std::future_status::timeout) { + ECHOION_LOG_WARNING("yt-dlp audio URL extraction timed out after 30s"); + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + "yt-dlp audio URL extraction timed out")); + } + + auto ytdlpResult = future.get(); + + if (!ytdlpResult.success) { + ECHOION_LOG_WARNING("yt-dlp audio URL extraction failed"); + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + "yt-dlp audio URL extraction failed")); + } + + std::string result = ytdlpResult.output; + + if (!result.empty() && result.back() == '\n') { + result.pop_back(); + } + + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - startTime) + .count(); + + if (!result.empty() && result.find("http") == 0) { + ECHOION_LOG_INFO(std::format( + "Successfully got audio URL from yt-dlp in {} ms", elapsed)); + return result; + } + + ECHOION_LOG_WARNING(std::format( + "Failed to get audio URL from yt-dlp after {} ms", elapsed)); + return std::unexpected(Api::Error(Api::ErrorCode::NotFound, + "Failed to get audio URL from yt-dlp")); } Api::Result YouTubeClient::getStreamUrl(std::string_view videoId) { @@ -118,44 +388,111 @@ Api::Result YouTubeClient::getVideoInfo(std::string_view videoId return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "yt-dlp not available")); } - - std::string url = std::format("https://www.youtube.com/watch?v={}", videoId); - std::string jsonStr = ytDlpManager_->execute({ - url, - "-J", - "--no-warnings" - }); - - if (jsonStr.empty()) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - "yt-dlp failed to get video info")); - } - - try { - glz::generic json; - if (glz::read_json(json, jsonStr)) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - "Failed to parse yt-dlp output")); - } - - Api::TrackInfo info; - if (json.contains("id")) info.id = json["id"].get(); - if (json.contains("title")) info.title = json["title"].get(); - if (json.contains("uploader")) info.artist = json["uploader"].get(); + + // Validate video ID + if (videoId.empty()) { + return std::unexpected( + Api::Error(Api::ErrorCode::InvalidArgument, "Video ID is empty")); + } + + ECHOION_LOG_DEBUG(std::format("Getting video info for ID: '{}'", videoId)); + auto infoStart = std::chrono::steady_clock::now(); + + // Pass just the video ID to yt-dlp (it can handle both ID and URL) + std::string videoIdStr(videoId); + auto result = + ytDlpManager_->executeAsync({videoIdStr, "-J", "--no-warnings"}); + + // Wait with timeout (30 seconds) + ECHOION_LOG_DEBUG("Waiting for yt-dlp video info (30s timeout)..."); + auto waitStatus = result.wait_for(std::chrono::seconds(30)); + + if (waitStatus == std::future_status::timeout) { + ECHOION_LOG_WARNING("yt-dlp video info timed out after 30s"); + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + "yt-dlp video info timed out")); + } + + auto ytdlpResult = result.get(); + + ECHOION_LOG_DEBUG( + std::format("yt-dlp video info completed in {} ms", + std::chrono::duration_cast( + std::chrono::steady_clock::now() - infoStart) + .count())); + + if (!ytdlpResult.success || ytdlpResult.output.empty()) { + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + "yt-dlp failed to get video info")); + } + + try { + glz::generic json; + if (glz::read_json(json, ytdlpResult.output)) { + return std::unexpected(Api::Error(Api::ErrorCode::ParseError, + "Failed to parse yt-dlp output")); + } + + Api::TrackInfo info; + if (json.contains("id")) { + info.id = json["id"].get(); + } + if (json.contains("title")) { + info.title = decodeHtmlEntities(json["title"].get()); + } + if (json.contains("uploader")) info.artist = json["uploader"].get(); if (json.contains("duration")) { info.duration = std::chrono::seconds(static_cast(json["duration"].get())); } if (json.contains("thumbnail")) info.thumbnailUrl = json["thumbnail"].get(); // Set originalUrl so we can extract video ID later for streaming - info.originalUrl = url; - info.source = Api::TrackSource::YouTube; - return info; - - } catch (const std::exception& e) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - std::format("Exception parsing yt-dlp output: {}", e.what()))); - } + info.originalUrl = + std::format("https://www.youtube.com/watch?v={}", info.id); + info.source = Api::TrackSource::YouTube; + + // Populate shortened URL + populateShortenedUrl(info); + + return info; + + } catch (const std::exception& e) { + return std::unexpected(Api::Error( + Api::ErrorCode::ParseError, + std::format("Exception parsing yt-dlp output: {}", e.what()))); + } +} + +std::future> + YouTubeClient::getVideoInfoAsync(std::string_view videoId) +{ + return std::async(std::launch::async, + [this, videoIdStr = std::string(videoId)]() { + return getVideoInfo(videoIdStr); + }); +} + +std::vector> + YouTubeClient::getVideoInfoBatch(const std::vector& videoIds) +{ + + std::vector>> futures; + futures.reserve(videoIds.size()); + + // Launch all requests concurrently + for (const auto& videoId : videoIds) { + futures.push_back(getVideoInfoAsync(videoId)); + } + + // Collect results + std::vector> results; + results.reserve(videoIds.size()); + + for (auto& future : futures) { + results.push_back(future.get()); + } + + return results; } Api::Result YouTubeClient::search(std::string_view query, @@ -165,64 +502,483 @@ Api::Result YouTubeClient::search(std::string_view query, return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized")); } - - if (!ytDlpManager_->isAvailable()) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "yt-dlp not available")); - } - - // yt-dlp search format: ytsearch5:query - std::string searchQuery = std::format("ytsearch5:{}", query); - - std::string jsonStr = ytDlpManager_->execute({ - searchQuery, - "-J", - "--flat-playlist", - "--no-warnings" - }); - - if (jsonStr.empty()) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - "yt-dlp search failed")); - } - - try { - glz::generic json; - if (glz::read_json(json, jsonStr)) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - "Failed to parse yt-dlp search output")); - } - - Api::SearchResult result; - result.query = std::string(query); - - if (json.contains("entries") && json["entries"].is_array()) { - for (const auto& entry : json["entries"].get>()) { - if (!entry.contains("id")) continue; - - Api::TrackInfo track; - track.id = entry["id"].get(); - if (entry.contains("title")) track.title = entry["title"].get(); - if (entry.contains("uploader")) track.artist = entry["uploader"].get(); - if (entry.contains("duration")) { - track.duration = std::chrono::seconds(static_cast(entry["duration"].get())); - } - if (entry.contains("thumbnail")) track.thumbnailUrl = entry["thumbnail"].get(); - // Set originalUrl so we can extract video ID later for streaming - track.originalUrl = std::format("https://www.youtube.com/watch?v={}", track.id); - track.source = Api::TrackSource::YouTube; - - result.tracks.push_back(track); - } - } - - result.totalResults = result.tracks.size(); - return result; - - } catch (const std::exception& e) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - std::format("Exception parsing yt-dlp search: {}", e.what()))); - } + + auto startTime = std::chrono::steady_clock::now(); + Api::Result result; + + // Use YouTube Data API v3 if key is available + if (hasApiKey()) { + ECHOION_LOG_INFO(std::format("Searching YouTube via API: '{}'", query)); + result = searchWithApi(query, pageToken); + } else { + // Fallback to yt-dlp if no API key + ECHOION_LOG_WARNING( + "No YouTube API key configured, falling back to yt-dlp for search"); + result = searchWithYtDlp(query, pageToken); + } + + ECHOION_LOG_INFO( + std::format("YouTube search took {} ms", + std::chrono::duration_cast( + std::chrono::steady_clock::now() - startTime) + .count())); + return result; +} + +Api::Result + YouTubeClient::searchWithApi(std::string_view query, + const std::optional& pageToken) +{ + + std::string apiKey; + { + std::lock_guard lock(configMutex_); + if (!apiKey_.has_value() || apiKey_->empty()) { + return std::unexpected( + Api::Error(Api::ErrorCode::ServiceUnavailable, + "YouTube API key not configured")); + } + apiKey = *apiKey_; + } + + // Build YouTube Data API v3 search URL + std::string url = + std::format("https://www.googleapis.com/youtube/v3/" + "search?part=snippet&type=video&maxResults=10&q={}&key={}", + urlEncode(query), apiKey); + + if (pageToken.has_value()) { + url += std::format("&pageToken={}", *pageToken); + } + + // Execute with timeout (10 seconds for API search) + ECHOION_LOG_DEBUG("Executing YouTube API search with 10s timeout..."); + + // Use shared promise so detached thread can safely complete + auto responsePromise = + std::make_shared>>(); + std::future> responseFuture = + responsePromise->get_future(); + + std::thread apiThread([this, url = std::string(url), responsePromise]() { + ECHOION_LOG_DEBUG("API request thread started"); + try { + auto result = networkClient_->get(url); + responsePromise->set_value(std::move(result)); + } catch (...) { + responsePromise->set_exception(std::current_exception()); + } + ECHOION_LOG_DEBUG("API request thread completed"); + }); + + // Wait with timeout + auto waitStatus = responseFuture.wait_for(std::chrono::seconds(10)); + + if (waitStatus == std::future_status::timeout) { + ECHOION_LOG_WARNING("YouTube API search timed out after 10s"); + apiThread.detach(); // Thread owns shared_ptr, safe to detach + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + "YouTube API search timed out")); + } + + ECHOION_LOG_DEBUG("Joining API request thread..."); + apiThread.join(); + ECHOION_LOG_DEBUG("API request thread joined"); + + // Get the response + Api::Result response; + try { + response = responseFuture.get(); + } catch (const std::exception& e) { + ECHOION_LOG_ERROR( + std::format("API request threw exception: {}", e.what())); + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + std::format("API request failed: {}", e.what()))); + } + + // Log response status + if (response) { + ECHOION_LOG_DEBUG( + std::format("API response status: {}", response->statusCode)); + } else { + ECHOION_LOG_WARNING( + std::format("API request failed: {}", response.error().message)); + } + + if (!response || !response->isSuccess()) { + return std::unexpected(Api::Error( + Api::ErrorCode::NetworkError, + std::format("YouTube API search failed: {}", + response ? std::to_string(response->statusCode) + : "no response"))); + } + + try { + glz::generic json; + if (glz::read_json(json, response->body)) { + return std::unexpected( + Api::Error(Api::ErrorCode::ParseError, + "Failed to parse YouTube API search response")); + } + + Api::SearchResult result; + result.query = std::string(query); + + // Extract total results + if (json.contains("pageInfo") && json["pageInfo"].is_object()) { + const auto& pageInfo = json["pageInfo"]; + if (pageInfo.contains("totalResults")) { + result.totalResults = static_cast( + pageInfo["totalResults"].get()); + } + } + + // Store next page token if available + if (json.contains("nextPageToken") && + json["nextPageToken"].is_string()) { + result.nextPageToken = json["nextPageToken"].get(); + } + + // Extract search results + if (json.contains("items") && json["items"].is_array()) { + std::vector videoIds; + + for (const auto& item : + json["items"].get>()) { + if (!item.contains("id") || !item["id"].is_object()) { + continue; + } + + const auto& id = item["id"]; + if (!id.contains("videoId")) { + continue; + } + + std::string videoId = id["videoId"].get(); + videoIds.push_back(videoId); + + Api::TrackInfo track; + track.id = videoId; + track.source = Api::TrackSource::YouTube; + track.originalUrl = + std::format("https://www.youtube.com/watch?v={}", videoId); + + if (item.contains("snippet") && item["snippet"].is_object()) { + const auto& snippet = item["snippet"]; + if (snippet.contains("title")) { + track.title = decodeHtmlEntities( + snippet["title"].get()); + } + if (snippet.contains("channelTitle")) { + track.artist = decodeHtmlEntities( + snippet["channelTitle"].get()); + } + if (snippet.contains("thumbnails") && + snippet["thumbnails"].is_object()) { + const auto& thumbnails = snippet["thumbnails"]; + // Get the highest quality thumbnail available + if (thumbnails.contains("high")) { + track.thumbnailUrl = + thumbnails["high"]["url"].get(); + } else if (thumbnails.contains("medium")) { + track.thumbnailUrl = + thumbnails["medium"]["url"].get(); + } else if (thumbnails.contains("default")) { + track.thumbnailUrl = + thumbnails["default"]["url"].get(); + } + } + } + + result.tracks.push_back(std::move(track)); + } + + // Fetch duration for each video using videos endpoint (batch + // request) + if (!videoIds.empty()) { + ECHOION_LOG_DEBUG("Fetching video durations..."); + fetchVideoDurations(result.tracks, videoIds); + ECHOION_LOG_DEBUG("Video durations fetched"); + } + } + + ECHOION_LOG_INFO(std::format("YouTube API search returned {} results", + result.tracks.size())); + + // Populate shortened URLs for all tracks (already non-blocking with + // timeout) + ECHOION_LOG_DEBUG("Populating shortened URLs..."); + populateShortenedUrls(result.tracks); + ECHOION_LOG_DEBUG("Shortened URLs populated"); + + ECHOION_LOG_DEBUG("Returning search result"); + return result; + + } catch (const std::exception& e) { + return std::unexpected(Api::Error( + Api::ErrorCode::ParseError, + std::format("Exception parsing YouTube API search: {}", e.what()))); + } +} + +void YouTubeClient::fetchVideoDurations( + std::vector& tracks, + const std::vector& videoIds) +{ + + if (!hasApiKey() || videoIds.empty()) { + return; + } + + // Build comma-separated video IDs + std::string idList; + for (size_t i = 0; i < videoIds.size(); ++i) { + if (i > 0) { + idList += ","; + } + idList += videoIds[i]; + } + + std::string url; + { + std::lock_guard lock(configMutex_); + url = std::format("https://www.googleapis.com/youtube/v3/" + "videos?part=contentDetails&id={}&key={}", + idList, *apiKey_); + } + + // Execute with timeout (5 seconds) to avoid blocking + // Use shared promise so detached thread can safely complete + auto responsePromise = + std::make_shared>>(); + std::future> responseFuture = + responsePromise->get_future(); + + std::thread durationThread( + [this, url = std::string(url), responsePromise]() { + try { + auto result = networkClient_->get(url); + responsePromise->set_value(std::move(result)); + } catch (...) { + responsePromise->set_exception(std::current_exception()); + } + }); + + auto waitStatus = responseFuture.wait_for(std::chrono::seconds(5)); + + if (waitStatus == std::future_status::timeout) { + ECHOION_LOG_WARNING("Video duration fetch timed out after 5s"); + durationThread.detach(); + return; + } + + durationThread.join(); + + Api::Result response; + try { + response = responseFuture.get(); + } catch (const std::exception& e) { + ECHOION_LOG_WARNING( + std::format("Video duration request failed: {}", e.what())); + return; + } + + if (!response || !response->isSuccess()) { + ECHOION_LOG_WARNING("Failed to fetch video durations from YouTube API"); + return; + } + + try { + glz::generic json; + if (glz::read_json(json, response->body)) { + return; + } + + // Create a map of video ID to duration + std::unordered_map durationMap; + + if (json.contains("items") && json["items"].is_array()) { + for (const auto& item : + json["items"].get>()) { + if (!item.contains("id") || !item.contains("contentDetails")) { + continue; + } + + std::string videoId = item["id"].get(); + const auto& contentDetails = item["contentDetails"]; + + if (contentDetails.contains("duration")) { + std::string durationStr = + contentDetails["duration"].get(); + auto duration = parseIso8601Duration(durationStr); + if (duration.count() > 0) { + ECHOION_LOG_DEBUG( + std::format("Got duration: {}, parse as: {}", + durationStr, duration)); + durationMap[videoId] = duration; + } + } + } + } + + // Apply durations to tracks + for (auto& track : tracks) { + auto it = durationMap.find(track.id); + if (it != durationMap.end()) { + track.duration = std::chrono::duration_cast(it->second); + } + } + + } catch (const std::exception& e) { + ECHOION_LOG_WARNING( + std::format("Failed to parse video durations: {}", e.what())); + } +} + +std::chrono::seconds + YouTubeClient::parseIso8601Duration(const std::string& duration) +{ + // Parse ISO 8601 duration format (PT#M#S) + // Examples: PT3M30S, PT1H2M3S, PT45S + std::chrono::seconds result{0}; + + if (duration.empty() || duration[0] != 'P' || duration[1] != 'T') { + return result; + } + + size_t pos = 2; + int hours = 0, minutes = 0, seconds = 0; + + while (pos < duration.size()) { + size_t numEnd = pos; + while (numEnd < duration.size() && std::isdigit(duration[numEnd])) { + ++numEnd; + } + + if (numEnd == pos) { + break; + } + + int value = std::stoi(duration.substr(pos, numEnd - pos)); + + if (numEnd < duration.size()) { + char unit = duration[numEnd]; + if (unit == 'H') { + hours = value; + } else if (unit == 'M') { + minutes = value; + } else if (unit == 'S') { + seconds = value; + } + pos = numEnd + 1; + } else { + break; + } + } + + return std::chrono::seconds(hours * 3600 + minutes * 60 + seconds); +} + +Api::Result + YouTubeClient::searchWithYtDlp(std::string_view query, + const std::optional& pageToken) +{ + + if (!ytDlpManager_->isAvailable()) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available")); + } + + ECHOION_LOG_DEBUG("Starting yt-dlp search..."); + auto searchStart = std::chrono::steady_clock::now(); + + // yt-dlp search format: ytsearch5:query + std::string searchQuery = std::format("ytsearch5:{}", query); + + auto result = ytDlpManager_->executeAsync( + {searchQuery, "-J", "--flat-playlist", "--no-warnings"}); + + // Wait with timeout (30 seconds for yt-dlp search) + ECHOION_LOG_DEBUG("Waiting for yt-dlp search result (30s timeout)..."); + auto waitStatus = result.wait_for(std::chrono::seconds(30)); + + if (waitStatus == std::future_status::timeout) { + ECHOION_LOG_WARNING("yt-dlp search timed out after 30s"); + return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, + "yt-dlp search timed out")); + } + + auto ytdlpResult = result.get(); + + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - searchStart) + .count(); + ECHOION_LOG_DEBUG(std::format("yt-dlp search completed in {} ms", elapsed)); + + if (!ytdlpResult.success || ytdlpResult.output.empty()) { + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, "yt-dlp search failed")); + } + + try { + glz::generic json; + if (glz::read_json(json, ytdlpResult.output)) { + return std::unexpected( + Api::Error(Api::ErrorCode::ParseError, + "Failed to parse yt-dlp search output")); + } + + Api::SearchResult searchResult; + searchResult.query = std::string(query); + + if (json.contains("entries") && json["entries"].is_array()) { + for (const auto& entry : + json["entries"].get>()) { + if (!entry.contains("id")) { + continue; + } + + Api::TrackInfo track; + track.id = entry["id"].get(); + if (entry.contains("title")) { + track.title = + decodeHtmlEntities(entry["title"].get()); + } + if (entry.contains("uploader")) { + track.artist = decodeHtmlEntities( + entry["uploader"].get()); + } + if (entry.contains("duration")) { + track.duration = std::chrono::seconds( + static_cast(entry["duration"].get())); + } + if (entry.contains("thumbnail")) { + track.thumbnailUrl = entry["thumbnail"].get(); + } + // Set originalUrl so we can extract video ID later for + // streaming + track.originalUrl = + std::format("https://www.youtube.com/watch?v={}", track.id); + track.source = Api::TrackSource::YouTube; + + searchResult.tracks.push_back(track); + } + } + + searchResult.totalResults = + static_cast(searchResult.tracks.size()); + + // Populate shortened URLs for all tracks + populateShortenedUrls(searchResult.tracks); + + return searchResult; + + } catch (const std::exception& e) { + return std::unexpected(Api::Error( + Api::ErrorCode::ParseError, + std::format("Exception parsing yt-dlp search: {}", e.what()))); + } } Api::Result YouTubeClient::getPlaylist(std::string_view playlistId) { @@ -230,62 +986,422 @@ Api::Result YouTubeClient::getPlaylist(std::string_view playl return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, "YouTubeClient not initialized")); } - - if (!ytDlpManager_->isAvailable()) { - return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, - "yt-dlp not available")); - } - - std::string url = std::format("https://www.youtube.com/playlist?list={}", playlistId); - - std::string jsonStr = ytDlpManager_->execute({ - url, - "-J", - "--flat-playlist", - "--no-warnings" - }); - - if (jsonStr.empty()) { - return std::unexpected(Api::Error(Api::ErrorCode::NetworkError, - "yt-dlp playlist fetch failed")); - } - - try { - glz::generic json; - if (glz::read_json(json, jsonStr)) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - "Failed to parse yt-dlp playlist output")); - } - - Api::PlaylistInfo info; - if (json.contains("title")) info.name = json["title"].get(); - if (json.contains("id")) info.id = json["id"].get(); - - if (json.contains("entries") && json["entries"].is_array()) { - for (const auto& entry : json["entries"].get>()) { - if (!entry.contains("id")) continue; - - Api::TrackInfo track; - track.id = entry["id"].get(); - if (entry.contains("title")) track.title = entry["title"].get(); - if (entry.contains("uploader")) track.artist = entry["uploader"].get(); - if (entry.contains("duration")) { - track.duration = std::chrono::seconds(static_cast(entry["duration"].get())); - } - // Set originalUrl so we can extract video ID later for streaming - track.originalUrl = std::format("https://www.youtube.com/watch?v={}", track.id); - track.source = Api::TrackSource::YouTube; - - info.tracks.push_back(track); - } - } - - return info; - - } catch (const std::exception& e) { - return std::unexpected(Api::Error(Api::ErrorCode::ParseError, - std::format("Exception parsing yt-dlp playlist: {}", e.what()))); - } + + ECHOION_LOG_INFO(std::format("Fetching playlist: {}", playlistId)); + + // Step 1: Fetch playlist items (via API v2 if key available, else yt-dlp) + auto itemsResult = fetchPlaylistItems(playlistId); + if (!itemsResult) { + return std::unexpected(itemsResult.error()); + } + + const auto& items = *itemsResult; + if (items.empty()) { + Api::PlaylistInfo emptyInfo; + emptyInfo.id = std::string(playlistId); + emptyInfo.name = "Empty Playlist"; + return emptyInfo; + } + + ECHOION_LOG_INFO( + std::format("Found {} tracks in playlist, resolving individually...", + items.size())); + + // Step 2: Resolve each track individually via yt-dlp (concurrently) + Api::PlaylistInfo info; + info.id = std::string(playlistId); + + // Process tracks in batches to avoid overwhelming the system + const size_t batchSize = maxConcurrentResolutions_; + std::vector resolvedTracks; + resolvedTracks.reserve(items.size()); + + for (size_t i = 0; i < items.size(); i += batchSize) { + size_t end = std::min(i + batchSize, items.size()); + std::vector>> futures; + + // Launch concurrent resolutions for this batch + for (size_t j = i; j < end; ++j) { + futures.push_back( + std::async(std::launch::async, [this, &items, j]() { + return resolveTrackWithYtDlp(items[j]); + })); + } + + // Collect results + for (auto& future : futures) { + auto result = future.get(); + if (result) { + resolvedTracks.push_back(std::move(*result)); + } else { + ECHOION_LOG_WARNING(std::format("Failed to resolve track: {}", + result.error().message)); + } + } + + ECHOION_LOG_DEBUG(std::format( + "Resolved batch {}/{} ({} tracks so far)", (i / batchSize) + 1, + (items.size() + batchSize - 1) / batchSize, resolvedTracks.size())); + } + + info.tracks = std::move(resolvedTracks); + + // Set playlist name from first track if available + if (!info.tracks.empty() && !items.empty()) { + // Try to get playlist title from yt-dlp if we used it + // Otherwise use a default name + info.name = std::format("Playlist ({} tracks)", info.tracks.size()); + } + + ECHOION_LOG_INFO( + std::format("Successfully resolved {}/{} tracks from playlist", + info.tracks.size(), items.size())); + + // Populate shortened URLs for all tracks + populateShortenedUrls(info.tracks); + + return info; +} + +std::future> + YouTubeClient::getPlaylistAsync(std::string_view playlistId) +{ + return std::async(std::launch::async, + [this, playlistIdStr = std::string(playlistId)]() { + return getPlaylist(playlistIdStr); + }); +} + +void YouTubeClient::getPlaylistStreaming( + std::string_view playlistId, + std::function trackCallback, + std::function onPlaylistInfo, + std::function onComplete) +{ + if (!initialized_ || !trackCallback) { + if (onComplete) onComplete(); + return; + } + + ECHOION_LOG_INFO(std::format("Streaming playlist: {}", playlistId)); + + // Fetch playlist items first (quick operation) + auto itemsResult = fetchPlaylistItems(playlistId); + if (!itemsResult || itemsResult->empty()) { + ECHOION_LOG_WARNING("No items found in playlist or fetch failed"); + if (onComplete) onComplete(); + return; + } + + const auto& items = *itemsResult; + ECHOION_LOG_INFO(std::format("Streaming {} tracks from playlist", items.size())); + + // Notify about total tracks + if (onPlaylistInfo) { + onPlaylistInfo(items.size()); + } + + // Resolve tracks in batches and call callback immediately for each resolved track + const size_t batchSize = maxConcurrentResolutions_; + + for (size_t i = 0; i < items.size(); i += batchSize) { + size_t end = std::min(i + batchSize, items.size()); + std::vector>> futures; + + // Launch concurrent resolutions for this batch + for (size_t j = i; j < end; ++j) { + futures.push_back( + std::async(std::launch::async, [this, &items, j]() { + return resolveTrackWithYtDlp(items[j]); + })); + } + + // Collect results and immediately call callback for each + for (auto& future : futures) { + auto result = future.get(); + if (result) { + // Populate shortened URL for this track + populateShortenedUrl(*result); + // Immediately notify callback - enables quick playback start + trackCallback(std::move(*result)); + } else { + ECHOION_LOG_WARNING(std::format("Failed to resolve track: {}", + result.error().message)); + } + } + + ECHOION_LOG_DEBUG(std::format( + "Processed batch {}/{}", (i / batchSize) + 1, + (items.size() + batchSize - 1) / batchSize)); + } + + ECHOION_LOG_INFO("Playlist streaming complete"); + if (onComplete) onComplete(); +} + +Api::Result> + YouTubeClient::fetchPlaylistItems(std::string_view playlistId) +{ + + std::vector items; + + // Try using YouTube Data API v3 if key is available + if (hasApiKey()) { + ECHOION_LOG_INFO("Using YouTube Data API v3 for playlist fetch"); + + std::optional pageToken; + do { + std::string apiUrl = buildPlaylistApiUrl(playlistId, pageToken); + + auto response = networkClient_->get(apiUrl); + if (!response || !response->isSuccess()) { + ECHOION_LOG_WARNING( + "YouTube API request failed, falling back to yt-dlp"); + break; // Fall back to yt-dlp + } + + try { + glz::generic json; + if (glz::read_json(json, response->body)) { + ECHOION_LOG_WARNING("Failed to parse YouTube API response, " + "falling back to yt-dlp"); + break; + } + + if (json.contains("items") && json["items"].is_array()) { + for (const auto& item : + json["items"].get>()) { + if (!item.contains("snippet") || + !item.contains("contentDetails")) { + continue; + } + + const auto& snippet = item["snippet"]; + const auto& contentDetails = item["contentDetails"]; + + Api::YouTubePlaylistItem playlistItem; + + if (contentDetails.contains("videoId")) { + playlistItem.videoId = + contentDetails["videoId"].get(); + } + + if (snippet.contains("title")) { + playlistItem.title = + snippet["title"].get(); + } + + if (snippet.contains("thumbnails") && + snippet["thumbnails"].is_object()) { + const auto& thumbnails = snippet["thumbnails"]; + // Get the highest quality thumbnail available + if (thumbnails.contains("high")) { + playlistItem.thumbnailUrl = + thumbnails["high"]["url"] + .get(); + } else if (thumbnails.contains("medium")) { + playlistItem.thumbnailUrl = + thumbnails["medium"]["url"] + .get(); + } else if (thumbnails.contains("default")) { + playlistItem.thumbnailUrl = + thumbnails["default"]["url"] + .get(); + } + } + + items.push_back(std::move(playlistItem)); + } + } + + // Check for next page + if (json.contains("nextPageToken") && + json["nextPageToken"].is_string()) { + pageToken = json["nextPageToken"].get(); + } else { + pageToken = std::nullopt; + } + + } catch (const std::exception& e) { + ECHOION_LOG_WARNING(std::format( + "Error parsing YouTube API response: {}", e.what())); + break; // Fall back to yt-dlp + } + } while (pageToken.has_value()); + + if (!items.empty()) { + ECHOION_LOG_INFO( + std::format("Fetched {} tracks via YouTube API", items.size())); + return items; + } + } + + // Fallback: Use yt-dlp to fetch playlist items + ECHOION_LOG_INFO("Using yt-dlp for playlist fetch"); + + if (!ytDlpManager_->isAvailable()) { + return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable, + "yt-dlp not available")); + } + + std::string url = + std::format("https://www.youtube.com/playlist?list={}", playlistId); + + auto result = ytDlpManager_->executeAsync( + {url, "-J", "--flat-playlist", "--no-warnings"}); + + auto ytdlpResult = result.get(); + + if (!ytdlpResult.success || ytdlpResult.output.empty()) { + return std::unexpected( + Api::Error(Api::ErrorCode::NetworkError, + "Failed to fetch playlist via yt-dlp")); + } + + try { + glz::generic json; + if (glz::read_json(json, ytdlpResult.output)) { + return std::unexpected( + Api::Error(Api::ErrorCode::ParseError, + "Failed to parse yt-dlp playlist output")); + } + + if (json.contains("entries") && json["entries"].is_array()) { + for (const auto& entry : + json["entries"].get>()) { + if (!entry.contains("id")) { + continue; + } + + Api::YouTubePlaylistItem item; + item.videoId = entry["id"].get(); + if (entry.contains("title")) { + item.title = + decodeHtmlEntities(entry["title"].get()); + } + if (entry.contains("thumbnails") && + entry["thumbnails"].is_array()) { + const auto& thumbs = + entry["thumbnails"].get>(); + if (!thumbs.empty() && thumbs.back().contains("url")) { + item.thumbnailUrl = + thumbs.back()["url"].get(); + } + } + + items.push_back(std::move(item)); + } + } + + ECHOION_LOG_INFO( + std::format("Fetched {} tracks via yt-dlp", items.size())); + return items; + + } catch (const std::exception& e) { + return std::unexpected(Api::Error( + Api::ErrorCode::ParseError, + std::format("Exception parsing playlist: {}", e.what()))); + } +} + +Api::Result + YouTubeClient::resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item) +{ + + if (!ytDlpManager_->isAvailable()) { + // Return basic info without yt-dlp resolution + Api::TrackInfo track; + track.id = item.videoId; + track.title = item.title; + track.thumbnailUrl = item.thumbnailUrl; + track.source = Api::TrackSource::YouTube; + track.originalUrl = + std::format("https://www.youtube.com/watch?v={}", item.videoId); + return track; + } + + std::string url = + std::format("https://www.youtube.com/watch?v={}", item.videoId); + + auto result = ytDlpManager_->executeAsync({url, "-J", "--no-warnings"}); + + auto ytdlpResult = result.get(); + + if (!ytdlpResult.success || ytdlpResult.output.empty()) { + // Return basic info on failure + Api::TrackInfo track; + track.id = item.videoId; + track.title = item.title; + track.thumbnailUrl = item.thumbnailUrl; + track.source = Api::TrackSource::YouTube; + track.originalUrl = url; + return track; + } + + try { + glz::generic json; + if (glz::read_json(json, ytdlpResult.output)) { + // Return basic info on parse failure + Api::TrackInfo track; + track.id = item.videoId; + track.title = item.title; + track.thumbnailUrl = item.thumbnailUrl; + track.source = Api::TrackSource::YouTube; + track.originalUrl = url; + return track; + } + + Api::TrackInfo track; + if (json.contains("id")) { + track.id = json["id"].get(); + } + if (json.contains("title")) { + track.title = decodeHtmlEntities(json["title"].get()); + } + if (json.contains("uploader")) { + track.artist = + decodeHtmlEntities(json["uploader"].get()); + } + if (json.contains("duration")) { + track.duration = std::chrono::seconds( + static_cast(json["duration"].get())); + } + if (json.contains("thumbnail")) { + track.thumbnailUrl = json["thumbnail"].get(); + } + + track.originalUrl = url; + track.source = Api::TrackSource::YouTube; + return track; + + } catch (const std::exception& e) { + // Return basic info on exception + Api::TrackInfo track; + track.id = item.videoId; + track.title = item.title; + track.thumbnailUrl = item.thumbnailUrl; + track.source = Api::TrackSource::YouTube; + track.originalUrl = url; + return track; + } +} + +std::string YouTubeClient::buildPlaylistApiUrl( + std::string_view playlistId, + const std::optional& pageToken) const +{ + + std::lock_guard lock(configMutex_); + std::string url = std::format("https://www.googleapis.com/youtube/v3/" + "playlistItems?part=snippet,contentDetails&" + "playlistId={}&maxResults=50&key={}", + playlistId, *apiKey_); + + if (pageToken.has_value()) { + url += std::format("&pageToken={}", *pageToken); + } + + return url; } std::optional YouTubeClient::extractVideoId(std::string_view url) { @@ -367,7 +1483,141 @@ std::optional YouTubeClient::extractPlaylistId(std::string_view url } bool YouTubeClient::isYouTubeUrl(std::string_view url) { - return url.find("youtube.com") != std::string::npos || url.find("youtu.be") != std::string::npos; + return url.find("faumaray.ru") != std::string::npos || url.find("youtube.com") != std::string::npos || url.find("youtu.be") != std::string::npos; +} + +void YouTubeClient::setUrlShorteningEnabled(bool enabled) +{ + std::lock_guard lock(configMutex_); + urlShorteningEnabled_ = enabled; + ECHOION_LOG_INFO( + std::format("URL shortening {}", enabled ? "enabled" : "disabled")); +} + +bool YouTubeClient::isUrlShorteningEnabled() const +{ + std::lock_guard lock(configMutex_); + return urlShorteningEnabled_; +} + +void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track) +{ + if (!urlShorteningEnabled_ || !urlShortener_ || track.id.empty()) { + return; + } + + // Run URL shortening asynchronously with timeout to avoid blocking + // This is a best-effort feature - if it fails or times out, we still have + // the track. Use shared_ptr to ensure data lives for detached thread. + auto trackId = track.id; + auto shortenedUrl = std::make_shared>(); + auto completed = std::make_shared>(false); + + std::thread shortenThread([this, trackId, shortenedUrl, completed]() { + try { + auto result = urlShortener_->shortenYouTubeUrl(trackId); + if (result) { + *shortenedUrl = *result; + } + } catch (...) { + // Ignore exceptions - this is best-effort + } + *completed = true; + }); + + // Wait up to 3 seconds for URL shortening + auto start = std::chrono::steady_clock::now(); + while (!*completed && + std::chrono::steady_clock::now() - start < std::chrono::seconds(3)) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + + if (*completed) { + // Thread completed, join it and apply result + if (shortenThread.joinable()) { + shortenThread.join(); + } + if (shortenedUrl->has_value()) { + track.shortenedUrl = *shortenedUrl; + ECHOION_LOG_DEBUG(std::format("URL shortened for {}: {}", + track.title, + track.shortenedUrl.value())); + } + } else { + // Timeout - thread owns shared_ptr, safe to detach + ECHOION_LOG_WARNING( + "URL shortening timed out after 3s, detaching thread"); + shortenThread.detach(); + } +} + +void YouTubeClient::populateShortenedUrls(std::vector& tracks) +{ + if (!urlShorteningEnabled_ || !urlShortener_ || tracks.empty()) { + return; + } + + // Shorten URLs in parallel using async with timeout + std::vector> futures; + futures.reserve(tracks.size()); + + for (auto& track : tracks) { + if (track.id.empty()) { + continue; + } + + futures.push_back(std::async(std::launch::async, [this, &track]() { + // Each URL shortening has its own 3-second timeout + // Use shared_ptr for safe detached thread execution + auto trackId = track.id; + auto shortenedUrl = std::make_shared>(); + auto completed = std::make_shared>(false); + + std::thread t([this, trackId, shortenedUrl, completed]() { + try { + auto result = urlShortener_->shortenYouTubeUrl(trackId); + if (result) { + *shortenedUrl = *result; + } + } catch (...) { + // Ignore exceptions + } + *completed = true; + }); + + // Wait for completion or timeout + auto start = std::chrono::steady_clock::now(); + while (!*completed && std::chrono::steady_clock::now() - start < + std::chrono::seconds(3)) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + + if (*completed) { + // Thread completed, join and apply result + if (t.joinable()) { + t.join(); + } + if (shortenedUrl->has_value()) { + track.shortenedUrl = *shortenedUrl; + } + } else { + // Timeout - thread owns shared_ptr, safe to detach + t.detach(); + } + })); + } + + // Wait for all with overall 5-second timeout + auto start = std::chrono::steady_clock::now(); + for (auto& f : futures) { + auto remaining = std::chrono::seconds(5) - + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + if (remaining.count() <= 0) { + break; + } + f.wait_for(remaining); + } } } // namespace Echoion::Core diff --git a/src/YtDlpManager.cpp b/src/YtDlpManager.cpp index e556a58..4156848 100644 --- a/src/YtDlpManager.cpp +++ b/src/YtDlpManager.cpp @@ -1,11 +1,12 @@ -#include "echoion/core/YtDlpManager.hpp" #include "echoion/core/Logger.hpp" -#include -#include -#include -#include +#include "echoion/core/YtDlpManager.hpp" #include #include +#include +#include +#include +#include +#include #ifdef _WIN32 #include @@ -20,7 +21,7 @@ YtDlpManager::YtDlpManager(std::shared_ptr networkClient) : networkClient_(std::move(networkClient)) { } -YtDlpManager::~YtDlpManager() = default; +YtDlpManager::~YtDlpManager() { stopThreadPool(); } std::filesystem::path YtDlpManager::getStorageDir() const { // Store in ~/.local/share/echoion/yt-dlp on Linux @@ -138,10 +139,153 @@ Api::Result YtDlpManager::initialize() { } ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version)); - - std::lock_guard lock(mutex_); - initialized_ = true; - return {}; + + // Start thread pool for async operations + startThreadPool(); + + std::lock_guard lock(mutex_); + initialized_ = true; + return {}; +} + +void YtDlpManager::startThreadPool() +{ + stopThreadPool(); // Clear any existing threads first + + // Auto-adjust thread pool size based on hardware + unsigned int hardwareThreads = std::thread::hardware_concurrency(); + if (hardwareThreads > 0 && threadPoolSize_ > hardwareThreads / 2) { + threadPoolSize_ = std::max(1u, hardwareThreads / 2); + ECHOION_LOG_INFO(std::format( + "Auto-adjusted yt-dlp thread pool to {} threads (hardware: {})", + threadPoolSize_, hardwareThreads)); + } + + ECHOION_LOG_INFO(std::format("Starting yt-dlp thread pool with {} threads", + threadPoolSize_)); + + for (size_t i = 0; i < threadPoolSize_; ++i) { + threadPool_.emplace_back([this] { workerThread(); }); + } +} + +void YtDlpManager::stopThreadPool() +{ + stopThreads_ = true; + taskCv_.notify_all(); + + for (auto& thread : threadPool_) { + if (thread.joinable()) { + thread.join(); + } + } + threadPool_.clear(); + stopThreads_ = false; +} + +void YtDlpManager::workerThread() +{ + while (!stopThreads_.load()) { + std::packaged_task task; + + { + std::unique_lock lock(taskMutex_); + taskCv_.wait(lock, [this] { + return !taskQueue_.empty() || stopThreads_.load(); + }); + + if (stopThreads_.load()) { + return; + } + + if (!taskQueue_.empty()) { + task = std::move(taskQueue_.front()); + taskQueue_.pop(); + } + } + + if (task.valid()) { + task(); + } + } +} + +void YtDlpManager::setThreadPoolSize(size_t size) +{ + if (size == 0) { + size = 1; + } + if (size > 16) { + size = 16; // Cap at 16 threads + } + + std::lock_guard lock(mutex_); + if (threadPoolSize_ != size) { + threadPoolSize_ = size; + if (initialized_) { + // Restart thread pool with new size + stopThreadPool(); + startThreadPool(); + } + } +} + +size_t YtDlpManager::getThreadPoolSize() const +{ + std::lock_guard lock(mutex_); + return threadPoolSize_; +} + +void YtDlpManager::setProxyConfig(const std::optional& proxy) +{ + std::lock_guard lock(proxyMutex_); + proxyConfig_ = proxy; + if (proxy.has_value() && proxy->isValid()) { + ECHOION_LOG_INFO(std::format("yt-dlp proxy configured: {}:{}", + proxy->host, proxy->port)); + } else { + ECHOION_LOG_INFO("yt-dlp proxy cleared"); + } +} + +std::optional YtDlpManager::getProxyConfig() const +{ + std::lock_guard lock(proxyMutex_); + return proxyConfig_; +} + +std::vector YtDlpManager::getProxyArgs() const +{ + std::lock_guard lock(proxyMutex_); + std::vector proxyArgs; + + if (!proxyConfig_.has_value() || !proxyConfig_->isValid()) { + return proxyArgs; + } + + const auto& proxy = *proxyConfig_; + std::string proxyUrl; + + if (proxy.isSocks5()) { + if (proxy.requiresAuth()) { + proxyUrl = std::format("socks5://{}:{}@{}:{}", *proxy.username, + *proxy.password, proxy.host, proxy.port); + } else { + proxyUrl = std::format("socks5://{}:{}", proxy.host, proxy.port); + } + } else { + if (proxy.requiresAuth()) { + proxyUrl = std::format("http://{}:{}@{}:{}", *proxy.username, + *proxy.password, proxy.host, proxy.port); + } else { + proxyUrl = std::format("http://{}:{}", proxy.host, proxy.port); + } + } + + proxyArgs.push_back("--proxy"); + proxyArgs.push_back(proxyUrl); + + return proxyArgs; } Api::Result YtDlpManager::downloadYtDlp() { @@ -374,50 +518,86 @@ std::vector YtDlpManager::getCookieArgs() const { } std::string YtDlpManager::execute(const std::vector& args) const { - if (!std::filesystem::exists(executablePath_)) { - return ""; - } - - std::string cmd = executablePath_.string(); - - // Add cookie arguments first - auto cookieArgs = getCookieArgs(); - for (const auto& arg : cookieArgs) { - cmd += " "; - // Simple escaping - if (arg.find(' ') != std::string::npos || - arg.find('"') != std::string::npos || - arg.find('\\') != std::string::npos) { - std::string escaped; - for (char c : arg) { - if (c == '"') escaped += "\\"; - escaped += c; - } - cmd += "\"" + escaped + "\""; - } else { - cmd += arg; - } - } - - for (const auto& arg : args) { - cmd += " "; - // Simple escaping - wrap in quotes if contains spaces or special chars - if (arg.find(' ') != std::string::npos || - arg.find('"') != std::string::npos || - arg.find('\\') != std::string::npos) { - // Escape existing quotes and wrap - std::string escaped; - for (char c : arg) { - if (c == '"') escaped += "\\"; - escaped += c; - } - cmd += "\"" + escaped + "\""; - } else { - cmd += arg; - } - } - - // Suppress stderr + return executeInternal(args).output; +} + +YtDlpResult + YtDlpManager::executeInternal(const std::vector& args) const +{ + YtDlpResult result; + result.success = false; + result.exitCode = -1; + + if (!std::filesystem::exists(executablePath_)) { + return result; + } + + auto startTime = std::chrono::steady_clock::now(); + std::string cmd = buildCommand(args); + + ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd.substr(0, 200))); + + std::array buffer; + std::string output; + +#ifdef _WIN32 + FILE* pipe = _popen(cmd.c_str(), "r"); +#else + FILE* pipe = popen(cmd.c_str(), "r"); +#endif + if (!pipe) { + ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution"); + return result; + } + + while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) { + output += buffer.data(); + } + +#ifdef _WIN32 + result.exitCode = _pclose(pipe); +#else + result.exitCode = pclose(pipe); + if (WIFEXITED(result.exitCode)) { + result.exitCode = WEXITSTATUS(result.exitCode); + } +#endif + + auto endTime = std::chrono::steady_clock::now(); + result.executionTime = + std::chrono::duration_cast(endTime - + startTime); + result.output = std::move(output); + result.success = (result.exitCode == 0); + + return result; +} + +std::string + YtDlpManager::buildCommand(const std::vector& args) const +{ + std::string cmd = executablePath_.string(); + + // Add proxy arguments first (before cookies) + auto proxyArgs = getProxyArgs(); + for (const auto& arg : proxyArgs) { + cmd += " "; + cmd += escapeArg(arg); + } + + // Add cookie arguments + auto cookieArgs = getCookieArgs(); + for (const auto& arg : cookieArgs) { + cmd += " "; + cmd += escapeArg(arg); + } + + for (const auto& arg : args) { + cmd += " "; + cmd += escapeArg(arg); + } + + // Suppress stderr #ifdef _WIN32 cmd += " 2>nul"; #else @@ -433,24 +613,73 @@ std::string YtDlpManager::execute(const std::vector& args) const { #elif defined(__APPLE__) cmd = std::format("gtimeout {} {} 2>/dev/null || {}", timeoutSec, cmd, cmd); #endif - - ECHOION_LOG_DEBUG(std::format("Executing yt-dlp: {}", cmd)); - - std::array buffer; - std::string result; - - FILE* pipe = popen(cmd.c_str(), "r"); - if (!pipe) { - ECHOION_LOG_WARNING("Failed to open pipe for yt-dlp execution"); - return ""; - } - - while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) { - result += buffer.data(); - } - - pclose(pipe); - return result; + + return cmd; +} + +std::string YtDlpManager::escapeArg(const std::string& arg) +{ + // Simple escaping - wrap in quotes if contains spaces or special chars + if (arg.find(' ') != std::string::npos || + arg.find('"') != std::string::npos || + arg.find('\\') != std::string::npos || + arg.find('>') != std::string::npos || + arg.find('<') != std::string::npos || + arg.find('|') != std::string::npos || + arg.find('&') != std::string::npos || + arg.find('$') != std::string::npos || + arg.find('`') != std::string::npos) { + // Escape existing quotes and wrap + std::string escaped; + for (char c : arg) { + if (c == '"') { + escaped += "\\"; + } + escaped += c; + } + return "\"" + escaped + "\""; + } + return arg; +} + +std::future + YtDlpManager::executeAsync(const std::vector& args) +{ + std::packaged_task task( + [this, args]() { return executeInternal(args); }); + + auto future = task.get_future(); + + { + std::lock_guard lock(taskMutex_); + taskQueue_.push(std::move(task)); + } + + taskCv_.notify_one(); + return future; +} + +std::vector YtDlpManager::executeBatch( + const std::vector>& argsList) +{ + + std::vector> futures; + futures.reserve(argsList.size()); + + // Launch all tasks + for (const auto& args : argsList) { + futures.push_back(executeAsync(args)); + } + + // Collect results + std::vector results; + results.reserve(argsList.size()); + + for (auto& future : futures) { + results.push_back(future.get()); + } + + return results; } } // namespace Echoion::Core