many different fixes
This commit is contained in:
1 parent
a583c17916
commit
53801f2b53
36 files changed
+5149
-1291
No files matched your search
+17
-15
@@ -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()
|
||||
@@ -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_$<CONFIG>.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_$<CONFIG>.sh \"${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}\"
|
||||
ERROR_QUIET
|
||||
)
|
||||
")
|
||||
endif()
|
||||
endfunction()
|
||||
@@ -89,10 +89,9 @@ private:
|
||||
// Hardware acceleration setup
|
||||
Api::Result<void> initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||
void cleanupHardwareAccel();
|
||||
|
||||
// Zero-copy frame conversion
|
||||
Api::Result<Api::DecodedAudio> convertFrameZeroCopy();
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// Frame conversion (returns int16 for direct playback)
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// FFmpeg contexts
|
||||
AVFormatContext* formatContext_ = nullptr;
|
||||
@@ -114,8 +113,8 @@ private:
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
|
||||
// Output format
|
||||
uint32_t outputSampleRate_ = 48000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
uint32_t outputSampleRate_ = 192000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
|
||||
// Threading
|
||||
std::jthread decodeThread_;
|
||||
@@ -135,7 +134,9 @@ private:
|
||||
std::atomic<bool> shouldExit_{false}; // For FFmpeg interrupt callback
|
||||
std::chrono::milliseconds currentPosition_{0};
|
||||
std::string currentUrl_;
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
|
||||
// Statistics
|
||||
mutable std::mutex statsMutex_;
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "commands/Command.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <echoion/api.hpp>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
@@ -28,10 +33,13 @@ using PermissionCheckFunc = std::function<bool(uint64_t clientId, CommandCategor
|
||||
class CommandManager {
|
||||
public:
|
||||
CommandManager();
|
||||
~CommandManager() = default;
|
||||
~CommandManager();
|
||||
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
// Shutdown the command manager (stops thread pool)
|
||||
void shutdown();
|
||||
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
CommandManager& operator=(const CommandManager&) = delete;
|
||||
|
||||
// Enable move
|
||||
@@ -59,25 +67,37 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Dispatches a command message to the appropriate handler.
|
||||
* @param clientId The client ID who invoked the command.
|
||||
* @param message The full message (including prefix, e.g., "!play song").
|
||||
* @param musicManager Weak pointer to the MusicManager.
|
||||
* @param replyFunc Function to call to send a reply.
|
||||
* @param invokerName Name of the invoking user.
|
||||
* @return true if a command was found and executed, false otherwise.
|
||||
*/
|
||||
[[nodiscard]] bool dispatch(
|
||||
uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = ""
|
||||
);
|
||||
/**
|
||||
* @brief Dispatches a command message to the appropriate handler (ASYNC).
|
||||
* Commands are executed in a thread pool, allowing multiple users to
|
||||
* use the bot simultaneously without blocking.
|
||||
* @param clientId The client ID who invoked the command.
|
||||
* @param message The full message (including prefix, e.g., "!play song").
|
||||
* @param musicManager Weak pointer to the MusicManager.
|
||||
* @param replyFunc Function to call to send a reply.
|
||||
* @param invokerName Name of the invoking user.
|
||||
* @return true if a command was found and queued for execution, false
|
||||
* otherwise.
|
||||
*/
|
||||
[[nodiscard]] bool dispatch(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
|
||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::optional<CommandPtr> getCommand(std::string_view name) const;
|
||||
/**
|
||||
* @brief Executes a command synchronously (for internal use).
|
||||
* Prefer using dispatch() for normal command handling.
|
||||
*/
|
||||
[[nodiscard]] bool
|
||||
dispatchSync(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
|
||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::optional<CommandPtr> getCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getAllCommands() const;
|
||||
|
||||
// Get commands visible to a specific client (for help)
|
||||
@@ -119,6 +139,27 @@ private:
|
||||
// Permission checking
|
||||
PermissionCheckFunc permissionCheck_;
|
||||
std::optional<Api::AppConfig> serverConfig_;
|
||||
};
|
||||
|
||||
// Async command execution
|
||||
struct CommandTask {
|
||||
uint64_t clientId;
|
||||
std::string message;
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
std::function<void(std::string_view)> replyFunc;
|
||||
std::string invokerName;
|
||||
};
|
||||
|
||||
void startThreadPool();
|
||||
void processCommandQueue();
|
||||
void executeCommandAsync(CommandTask task);
|
||||
|
||||
std::vector<std::jthread> workerThreads_;
|
||||
std::queue<CommandTask> commandQueue_;
|
||||
std::mutex queueMutex_;
|
||||
std::condition_variable queueCv_;
|
||||
std::atomic<bool> shutdown_{false};
|
||||
static constexpr size_t THREAD_POOL_SIZE =
|
||||
4; // Handle up to 4 concurrent commands
|
||||
|
||||
}; // namespace Echoion::Core
|
||||
} // namespace Echoion::Core
|
||||
@@ -46,6 +46,8 @@ private:
|
||||
void rotateIfNeeded(Api::LogLevel level);
|
||||
void openLogFiles();
|
||||
void cleanupOldLogs();
|
||||
void moveToHistory(const std::filesystem::path& filePath);
|
||||
void ensureHistoryDirExists();
|
||||
[[nodiscard]] std::string formatLogEntry(const Api::LogEntry& entry);
|
||||
[[nodiscard]] std::string levelToString(Api::LogLevel level);
|
||||
[[nodiscard]] std::filesystem::path generateLogFilePath(Api::LogLevel level);
|
||||
|
||||
@@ -44,13 +44,19 @@ public:
|
||||
[[nodiscard]] Api::Result<bool> toggleShuffle();
|
||||
[[nodiscard]] Api::Result<bool> toggleRepeat();
|
||||
|
||||
[[nodiscard]] Api::Result<uint32_t> loadPlaylist(const std::string& playlistId, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const;
|
||||
// Load playlist asynchronously - returns immediately, processes in background
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId);
|
||||
[[nodiscard]] bool isPlaylistLoading() const { return playlistLoading_.load(); }
|
||||
[[nodiscard]] size_t getPlaylistLoadProgress() const { return playlistLoadedCount_.load(); }
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
|
||||
|
||||
// Search result selection (client-specific)
|
||||
void storePendingSearch(uint64_t clientId, const std::vector<Api::TrackInfo>& results);
|
||||
@@ -61,24 +67,60 @@ public:
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
|
||||
// Subscription management
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string> unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients() const;
|
||||
[[nodiscard]] bool hasSubscribers() const;
|
||||
// Subscription management (by client ID - internally uses UID for
|
||||
// persistence)
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string> unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients()
|
||||
const; // Returns only ONLINE subscribers' client IDs
|
||||
[[nodiscard]] bool hasSubscribers()
|
||||
const; // Returns true if any subscribers exist (online or offline)
|
||||
[[nodiscard]] bool hasOnlineSubscribers()
|
||||
const; // Returns true only if there are online subscribers
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void> restoreFromHotReload(const Api::HotReloadState& state);
|
||||
// Get UIDs of subscribers who are currently online
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
|
||||
using AudioDataCallback = std::function<void(const std::span<const float>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
// Called when a client connects to the server
|
||||
void onClientConnected(uint64_t clientId);
|
||||
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void>
|
||||
restoreFromHotReload(const Api::HotReloadState& state);
|
||||
|
||||
using AudioDataCallback = std::function<void(const std::span<const short>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
|
||||
|
||||
using PlaybackStartCallback = std::function<void()>;
|
||||
void setPlaybackStartCallback(const PlaybackStartCallback& callback);
|
||||
|
||||
// Callback to resolve client info (UID and nickname) from client ID
|
||||
using ClientInfoCallback =
|
||||
std::function<std::optional<std::pair<std::string, std::string>>(
|
||||
uint64_t clientId)>;
|
||||
void setClientInfoCallback(const ClientInfoCallback& callback);
|
||||
|
||||
// Callback to resolve client ID from UID
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
void setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
||||
|
||||
// Callback to resolve nickname from client ID
|
||||
using NicknameCallback =
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
private:
|
||||
void playbackThread();
|
||||
@@ -92,9 +134,28 @@ private:
|
||||
[[nodiscard]] Api::Result<std::string> downloadAudioForPlayback(const std::string& url);
|
||||
void cleanupTempFile(const std::string& filepath);
|
||||
|
||||
// Prefetch next track for seamless transitions
|
||||
void prefetchNextTrack();
|
||||
[[nodiscard]] bool shouldPrefetch() const;
|
||||
static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15); // Start prefetch 15s before end
|
||||
|
||||
// Temporary file tracking
|
||||
std::set<std::string> tempFiles_;
|
||||
mutable std::mutex tempFilesMutex_;
|
||||
|
||||
// Prefetch state for seamless playback
|
||||
struct PrefetchState {
|
||||
std::future<Api::Result<std::string>> streamUrlFuture;
|
||||
std::atomic<bool> isPrefetching{false};
|
||||
std::atomic<bool> hasPrefetched{false};
|
||||
std::optional<std::string> prefetchedUrl;
|
||||
} prefetchState_;
|
||||
|
||||
// Async playlist loading state
|
||||
std::thread playlistLoadThread_;
|
||||
std::atomic<bool> playlistLoading_{false};
|
||||
std::atomic<size_t> playlistLoadedCount_{0};
|
||||
std::atomic<size_t> playlistTotalCount_{0};
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
@@ -107,6 +168,11 @@ private:
|
||||
bool isPlaying_ = false;
|
||||
bool isPaused_ = false;
|
||||
bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused
|
||||
|
||||
// Accurate playback position tracking
|
||||
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
||||
std::chrono::steady_clock::time_point playbackStartTime_; // When current segment started
|
||||
std::chrono::milliseconds playbackBasePosition_{0}; // Position at start of current segment
|
||||
float volume_ = 0.5f;
|
||||
bool shuffle_ = false;
|
||||
bool repeat_ = false;
|
||||
@@ -115,6 +181,7 @@ private:
|
||||
std::jthread playbackThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::atomic<bool> playbackThreadRunning_{false}; // True while thread is actively running
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>> pendingSearches_;
|
||||
@@ -122,12 +189,17 @@ private:
|
||||
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE = 192000; // Match reference
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
||||
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -5,15 +5,22 @@
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
/**
|
||||
* Manages user subscriptions to the bot's audio output
|
||||
* Subscriptions are persisted to database and survive client reloads
|
||||
* Uses unique client UID instead of session-specific client ID
|
||||
*/
|
||||
class SubscriptionManager {
|
||||
public:
|
||||
struct Subscriber {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
|
||||
SubscriptionManager();
|
||||
~SubscriptionManager();
|
||||
|
||||
@@ -21,22 +28,34 @@ public:
|
||||
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
|
||||
void shutdown();
|
||||
|
||||
// Subscription management
|
||||
bool subscribe(uint64_t clientId);
|
||||
bool unsubscribe(uint64_t clientId);
|
||||
bool isSubscribed(uint64_t clientId) const;
|
||||
// Subscription management (by UID)
|
||||
bool subscribe(const std::string& uid, const std::string& nickname);
|
||||
bool unsubscribe(const std::string& uid);
|
||||
bool isSubscribed(const std::string& uid) const;
|
||||
|
||||
// Get all subscribed clients
|
||||
std::set<uint64_t> getSubscribedClients() const;
|
||||
// Get all subscribed UIDs
|
||||
std::vector<std::string> getSubscribedUids() const;
|
||||
|
||||
// Get all subscribers with info
|
||||
std::vector<Subscriber> getSubscribers() const;
|
||||
|
||||
// Get subscriber nickname
|
||||
std::optional<std::string> getSubscriberNickname(const std::string& uid) const;
|
||||
|
||||
// Update nickname for subscriber
|
||||
bool updateNickname(const std::string& uid, const std::string& nickname);
|
||||
|
||||
// Check if anyone is subscribed
|
||||
bool hasSubscribers() const;
|
||||
|
||||
// Get subscriber count
|
||||
size_t getSubscriberCount() const;
|
||||
|
||||
// Clear all subscriptions
|
||||
bool clearAll();
|
||||
|
||||
private:
|
||||
std::set<uint64_t> subscribedClients_;
|
||||
std::set<std::string> subscribedUids_;
|
||||
mutable std::mutex mutex_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
bool initialized_ = false;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <chrono>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
// URL shortener service for faumaray.ru
|
||||
class UrlShortener {
|
||||
public:
|
||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||
~UrlShortener();
|
||||
|
||||
// Shorten a YouTube URL via faumaray.ru
|
||||
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
||||
[[nodiscard]] Api::Result<std::string> shortenYouTubeUrl(std::string_view videoId);
|
||||
|
||||
// Shorten any URL via faumaray.ru
|
||||
[[nodiscard]] Api::Result<std::string> shortenUrl(std::string_view originalUrl);
|
||||
|
||||
// Get cached shortened URL if available
|
||||
[[nodiscard]] std::optional<std::string> getCachedUrl(std::string_view originalUrl) const;
|
||||
|
||||
// Clear the URL cache
|
||||
void clearCache();
|
||||
|
||||
// Set cache TTL (default: 24 hours)
|
||||
void setCacheTtl(std::chrono::hours ttl);
|
||||
|
||||
private:
|
||||
struct CacheEntry {
|
||||
std::string shortenedUrl;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
mutable std::mutex cacheMutex_;
|
||||
std::unordered_map<std::string, CacheEntry> cache_;
|
||||
std::chrono::hours cacheTtl_{24};
|
||||
|
||||
// Clean expired entries from cache
|
||||
void cleanExpiredCache();
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,13 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include "UrlShortener.hpp"
|
||||
#include "YtDlpManager.hpp"
|
||||
#include <regex>
|
||||
#include <chrono>
|
||||
#include <echoion/api.hpp>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
@@ -29,21 +35,46 @@ public:
|
||||
// Force update yt-dlp
|
||||
Api::Result<void> updateYtDlp();
|
||||
|
||||
// Search for videos using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
// Search for videos using YouTube Data API v3 (or yt-dlp as fallback)
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
||||
|
||||
// Get playlist videos using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo> getPlaylist(std::string_view playlistId);
|
||||
// Get video details asynchronously
|
||||
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoAsync(std::string_view videoId);
|
||||
|
||||
// Extract video ID from various YouTube URL formats (handles redirects for short URLs)
|
||||
[[nodiscard]] std::optional<std::string> extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string> extractPlaylistId(std::string_view url);
|
||||
// Get multiple video details concurrently
|
||||
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
||||
|
||||
// Check if URL is a YouTube URL
|
||||
// Get playlist videos - uses YouTube API v2 if key available, otherwise
|
||||
// yt-dlp Then resolves each track individually via yt-dlp for full metadata
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo>
|
||||
getPlaylist(std::string_view playlistId);
|
||||
|
||||
// Get playlist videos asynchronously with concurrent track resolution
|
||||
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
||||
getPlaylistAsync(std::string_view playlistId);
|
||||
|
||||
// Stream playlist tracks with callback - calls trackCallback for each track
|
||||
// as it is resolved, enabling immediate playback of first track
|
||||
void getPlaylistStreaming(std::string_view playlistId,
|
||||
std::function<void(Api::TrackInfo&&)> trackCallback,
|
||||
std::function<void(size_t totalTracks)> onPlaylistInfo = nullptr,
|
||||
std::function<void()> onComplete = nullptr);
|
||||
|
||||
// Extract video ID from various YouTube URL formats (handles redirects for
|
||||
// short URLs)
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string>
|
||||
extractPlaylistId(std::string_view url);
|
||||
|
||||
// Check if URL is a YouTube URL
|
||||
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
||||
|
||||
// Get stream URL for a video (used by MusicManager)
|
||||
@@ -56,12 +87,70 @@ public:
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
private:
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
// Configure proxy for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
||||
|
||||
// Set YouTube API key for enhanced playlist resolution (optional)
|
||||
void setApiKey(const std::string& apiKey);
|
||||
[[nodiscard]] bool hasApiKey() const;
|
||||
|
||||
// Configure concurrent resolution settings
|
||||
void setMaxConcurrentResolutions(size_t max);
|
||||
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
|
||||
private:
|
||||
|
||||
// Internal search implementations
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithApi(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlp(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
|
||||
// Fetch video durations for search results (batch API call)
|
||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||
const std::vector<std::string>& videoIds);
|
||||
|
||||
// Parse ISO 8601 duration string
|
||||
[[nodiscard]] static std::chrono::seconds
|
||||
parseIso8601Duration(const std::string& duration);
|
||||
|
||||
// URL encode/decode helpers
|
||||
[[nodiscard]] static std::string urlEncode(std::string_view value);
|
||||
[[nodiscard]] static std::string decodeHtmlEntities(std::string_view value);
|
||||
|
||||
// Internal methods for playlist resolution
|
||||
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
|
||||
fetchPlaylistItems(std::string_view playlistId);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
|
||||
|
||||
// Build YouTube API v3 URL for playlist items
|
||||
[[nodiscard]] std::string buildPlaylistApiUrl(
|
||||
std::string_view playlistId,
|
||||
const std::optional<std::string>& pageToken = std::nullopt) const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
std::unique_ptr<UrlShortener> urlShortener_;
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Configuration
|
||||
std::optional<std::string> apiKey_;
|
||||
mutable std::mutex configMutex_;
|
||||
size_t maxConcurrentResolutions_ = 4;
|
||||
bool urlShorteningEnabled_ = true;
|
||||
|
||||
// Populate shortened URLs for tracks
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,14 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include <string>
|
||||
#include <filesystem>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <echoion/api.hpp>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
struct YtDlpResult {
|
||||
std::string output;
|
||||
int exitCode;
|
||||
bool success;
|
||||
std::chrono::milliseconds executionTime;
|
||||
};
|
||||
|
||||
class YtDlpManager {
|
||||
public:
|
||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||
@@ -28,17 +40,34 @@ public:
|
||||
|
||||
// Force update yt-dlp to latest version
|
||||
Api::Result<void> update();
|
||||
|
||||
// Execute yt-dlp with given arguments and return output
|
||||
[[nodiscard]] std::string execute(const std::vector<std::string>& args) const;
|
||||
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Execute yt-dlp with given arguments and return output (synchronous)
|
||||
[[nodiscard]] std::string
|
||||
execute(const std::vector<std::string>& args) const;
|
||||
|
||||
// Execute yt-dlp asynchronously and return a future
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
|
||||
// Execute multiple yt-dlp commands concurrently
|
||||
[[nodiscard]] std::vector<YtDlpResult>
|
||||
executeBatch(const std::vector<std::vector<std::string>>& argsList);
|
||||
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Get cookie arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
|
||||
|
||||
// Set proxy configuration for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
||||
|
||||
// Configure thread pool size for async operations (default: 4)
|
||||
void setThreadPoolSize(size_t size);
|
||||
[[nodiscard]] size_t getThreadPoolSize() const;
|
||||
|
||||
private:
|
||||
// Get the storage directory for yt-dlp
|
||||
[[nodiscard]] std::filesystem::path getStorageDir() const;
|
||||
@@ -58,19 +87,50 @@ private:
|
||||
// Get download URL based on platform
|
||||
[[nodiscard]] std::string getDownloadUrl() const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
// Internal execute implementation
|
||||
[[nodiscard]] YtDlpResult
|
||||
executeInternal(const std::vector<std::string>& args) const;
|
||||
|
||||
// Build the full command with all options
|
||||
[[nodiscard]] std::string
|
||||
buildCommand(const std::vector<std::string>& args) const;
|
||||
|
||||
// Get proxy arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
||||
|
||||
// Escape shell argument
|
||||
[[nodiscard]] static std::string escapeArg(const std::string& arg);
|
||||
|
||||
// Thread pool for async operations
|
||||
void startThreadPool();
|
||||
void stopThreadPool();
|
||||
void workerThread();
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Cookie configuration for YouTube authentication
|
||||
std::optional<std::string> cookiesPath_;
|
||||
std::optional<std::string> cookiesFromBrowser_;
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_VERSION_URL =
|
||||
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||
|
||||
// Proxy configuration
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
mutable std::mutex proxyMutex_;
|
||||
|
||||
// Thread pool for async operations
|
||||
size_t threadPoolSize_ = 4;
|
||||
std::vector<std::jthread> threadPool_;
|
||||
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
|
||||
std::mutex taskMutex_;
|
||||
std::condition_variable taskCv_;
|
||||
std::atomic<bool> stopThreads_{false};
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_VERSION_URL =
|
||||
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe";
|
||||
|
||||
@@ -43,7 +43,8 @@ inline std::string toString(CommandCategory category) {
|
||||
*/
|
||||
struct CommandContext {
|
||||
uint64_t clientId = 0;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string prefix;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string_view invokerName;
|
||||
|
||||
// Dependencies
|
||||
|
||||
@@ -23,3 +23,6 @@
|
||||
#include "ReloadConfigCommand.hpp"
|
||||
#include "SubscribeCommand.hpp"
|
||||
#include "UnsubscribeCommand.hpp"
|
||||
#include "SubscribersCommand.hpp"
|
||||
#include "UnsubscribeIdCommand.hpp"
|
||||
#include "UnsubscribeAllCommand.hpp"
|
||||
@@ -24,22 +24,39 @@ public:
|
||||
}
|
||||
|
||||
if (!current->has_value()) {
|
||||
ctx.reply("Nothing is currently playing. Add something with [prefix]play!");
|
||||
return;
|
||||
ctx.reply(std::format(
|
||||
"Nothing is currently playing. Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& track = current->value();
|
||||
std::string msg = std::format("\xf0\x9f\x8e\xb5 **{}** by **{}**",
|
||||
track.track.title,
|
||||
track.track.artist);
|
||||
|
||||
if (track.track.duration > std::chrono::seconds(0)) {
|
||||
auto mins = std::chrono::minutes(track.track.duration->count()).count();
|
||||
auto secs = std::chrono::seconds(track.track.duration->count()).count() % 60;
|
||||
msg += std::format(" [{}:{:02}]", mins, secs);
|
||||
}
|
||||
|
||||
if (!track.addedBy.empty()) {
|
||||
const auto& trackInfo = track.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", trackInfo.title, trackInfo.artist);
|
||||
}
|
||||
std::string linkText = trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*trackInfo.shortenedUrl)
|
||||
: displayText;
|
||||
std::string msg = std::format("\xf0\x9f\x8e\xb5 {}", linkText);
|
||||
|
||||
// Show current position / total duration
|
||||
auto playbackState = manager->getPlaybackState();
|
||||
if (playbackState && playbackState->currentTrack.has_value() &&
|
||||
trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
|
||||
auto position = playbackState->position;
|
||||
msg += std::format(" [{}/{}]",
|
||||
formatDuration(position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else if (trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
|
||||
msg += std::format(" [{}]", formatDuration(*trackInfo.duration));
|
||||
}
|
||||
|
||||
if (!track.addedBy.empty()) {
|
||||
msg += std::format(" (requested by {})", track.addedBy);
|
||||
}
|
||||
|
||||
@@ -61,6 +78,21 @@ public:
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"np", "current", "playing"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -42,7 +42,8 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
// result contains the track title
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -75,25 +76,45 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Added to queue: {}", track.title));
|
||||
return;
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
ctx.reply(std::format("Added to queue: {}", linkText));
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple results - store and show list
|
||||
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
|
||||
|
||||
std::string msg = "\xf0\x9f\x94\x8d Multiple results found. Use [prefix]select <number>:\n";
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
|
||||
std::string msg = std::format("\xf0\x9f\x94\x8d Multiple results "
|
||||
"found. Use {}select <number>:\n",
|
||||
ctx.prefix);
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
|
||||
const auto& track = searchResult->tracks[i];
|
||||
msg += std::format("{}. {}", i + 1, track.title);
|
||||
if (!track.artist.empty()) {
|
||||
msg += std::format(" by {}", track.artist);
|
||||
}
|
||||
if (track.duration.has_value()) {
|
||||
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
|
||||
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
|
||||
msg += std::format(" [{}:{:02}]", mins, secs);
|
||||
}
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg += std::format("{}. {}", i + 1, linkText);
|
||||
if (track.duration.has_value()) {
|
||||
msg +=
|
||||
std::format(" [{}]", formatDuration(*track.duration));
|
||||
}
|
||||
msg += "\n";
|
||||
}
|
||||
|
||||
@@ -120,6 +141,21 @@ public:
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"p", "add"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -52,7 +52,7 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Loaded {} tracks from playlist '{}'!", *result, ctx.args));
|
||||
ctx.reply(std::format("Loading playlist '{}'... Tracks will be added to the queue as they are resolved.", ctx.args));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Playlist command exception: {}", e.what()));
|
||||
|
||||
@@ -27,69 +27,167 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue**\n";
|
||||
// Parse page number from args (default to 1)
|
||||
int page = 1;
|
||||
if (!ctx.args.empty()) {
|
||||
try {
|
||||
page = std::stoi(std::string(ctx.args));
|
||||
if (page < 1) {
|
||||
page = 1;
|
||||
}
|
||||
} catch (...) {
|
||||
page = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
msg << std::format("\n**Now Playing:** {} by {}\n",
|
||||
track.track.title,
|
||||
track.track.artist);
|
||||
}
|
||||
constexpr int ITEMS_PER_PAGE = 10;
|
||||
int totalPages =
|
||||
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
|
||||
ITEMS_PER_PAGE;
|
||||
if (totalPages == 0) {
|
||||
totalPages = 1;
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << "\nThe queue is empty. Add songs with [prefix]play!";
|
||||
} else {
|
||||
msg << std::format("\n**Up Next ({} tracks):**\n", queue->size());
|
||||
for (size_t i = 0; i < queue->size() && i < 10; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
msg << std::format("{}. {}", i + 1, entry.track.title);
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << std::format(" (by {})", entry.addedBy);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
if (queue->size() > 10) {
|
||||
msg << std::format("\n... and {} more", queue->size() - 10);
|
||||
}
|
||||
}
|
||||
// Clamp page to valid range
|
||||
if (page > totalPages) {
|
||||
page = totalPages;
|
||||
}
|
||||
|
||||
// State indicators
|
||||
if (state) {
|
||||
msg << "\n\n";
|
||||
if (state->isPaused) {
|
||||
msg << "\xe2\x8f\xb8 Paused | ";
|
||||
}
|
||||
if (state->shuffle) {
|
||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||
}
|
||||
if (state->repeat) {
|
||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||
}
|
||||
msg << std::format("Volume: {}%", static_cast<int>(state->volume * 100));
|
||||
}
|
||||
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
||||
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
||||
static_cast<int>(queue->size()));
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
||||
<< totalPages << ")\n";
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
// Build time display: [current/total] or [total]
|
||||
std::string timeStr;
|
||||
if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
if (state) {
|
||||
timeStr =
|
||||
std::format(" [{}/{}]",
|
||||
formatDuration(state->position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else {
|
||||
timeStr = std::format(
|
||||
" [{}]", formatDuration(*trackInfo.duration));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"q", "list"};
|
||||
}
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText = std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({}){}", displayText,
|
||||
*trackInfo.shortenedUrl, timeStr)
|
||||
: displayText + timeStr;
|
||||
msg << std::format("\n**Now Playing:** {}\n", linkText);
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << std::format(
|
||||
"\nThe queue is empty. Add songs with {}play !",
|
||||
ctx.prefix);
|
||||
} else {
|
||||
msg << std::format("\n**Up Next ({} tracks):**\n",
|
||||
queue->size());
|
||||
for (int i = startIdx; i < endIdx; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
const auto& trackInfo = entry.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} [{}] by {}", trackInfo.title,
|
||||
formatDuration(*trackInfo.duration),
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({}) [{}]", displayText,
|
||||
*trackInfo.shortenedUrl,
|
||||
formatDuration(*trackInfo.duration))
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << std::format(" (by {})", entry.addedBy);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
if (totalPages > 1) {
|
||||
msg << std::format("\nUse {}queue <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
}
|
||||
}
|
||||
|
||||
// State indicators
|
||||
if (state) {
|
||||
msg << "\n\n";
|
||||
if (state->isPaused) {
|
||||
msg << "\xe2\x8f\xb8 Paused | ";
|
||||
}
|
||||
if (state->shuffle) {
|
||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||
}
|
||||
if (state->repeat) {
|
||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||
}
|
||||
msg << std::format("Volume: {}%", static_cast<int>(state->volume * 100));
|
||||
}
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[page]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"q", "list"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -18,8 +18,10 @@ public:
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: remove <position>\nUse [prefix]queue to see track positions.");
|
||||
return;
|
||||
ctx.reply(std::format("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t position = 0;
|
||||
|
||||
@@ -48,21 +48,30 @@ public:
|
||||
|
||||
for (size_t i = 0; i < result->tracks.size() && i < 5; ++i) {
|
||||
const auto& track = result->tracks[i];
|
||||
msg << std::format("{}. {}", i + 1, track.title);
|
||||
if (!track.artist.empty()) {
|
||||
msg << std::format(" by {}", track.artist);
|
||||
}
|
||||
if (track.duration.has_value()) {
|
||||
auto mins = std::chrono::duration_cast<std::chrono::minutes>(*track.duration).count();
|
||||
auto secs = std::chrono::duration_cast<std::chrono::seconds>(*track.duration).count() % 60;
|
||||
msg << std::format(" [{}:{:02}]", mins, secs);
|
||||
}
|
||||
// Format as [Title by Artist](shortenedUrl) with duration
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (track.duration.has_value()) {
|
||||
msg << std::format(" [{}]",
|
||||
formatDuration(*track.duration));
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
msg << "\nUse [prefix]select <number> to play a result.";
|
||||
msg << std::format("\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
|
||||
ctx.reply(msg.str());
|
||||
ctx.reply(msg.str());
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Search command exception: {}", e.what()));
|
||||
@@ -85,6 +94,21 @@ public:
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"find", "s"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -19,25 +19,67 @@ public:
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: seek <seconds>\nExample: seek 60 (jumps to 1 minute)");
|
||||
ctx.reply("Usage: seek <+/-seconds>\nExamples:\n seek +30 (skip forward 30s)\n seek -10 (skip back 10s)\n seek 60 (jump to 1 minute mark)");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the seek argument (supports +30, -10, or absolute 60)
|
||||
std::string_view arg = ctx.args;
|
||||
bool relative = false;
|
||||
bool forward = true;
|
||||
|
||||
if (arg.starts_with('+')) {
|
||||
relative = true;
|
||||
forward = true;
|
||||
arg = arg.substr(1);
|
||||
} else if (arg.starts_with('-')) {
|
||||
relative = true;
|
||||
forward = false;
|
||||
arg = arg.substr(1);
|
||||
}
|
||||
|
||||
int seconds = 0;
|
||||
auto parseResult = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
auto parseResult = std::from_chars(arg.data(),
|
||||
arg.data() + arg.size(),
|
||||
seconds);
|
||||
if (parseResult.ec != std::errc()) {
|
||||
ctx.reply("Please provide a valid number of seconds.");
|
||||
if (parseResult.ec != std::errc() || seconds < 0) {
|
||||
ctx.reply("Please provide a valid number of seconds.\nExamples: seek +30, seek -10, seek 60");
|
||||
return;
|
||||
}
|
||||
|
||||
if (seconds < 0) {
|
||||
ctx.reply("Time must be a positive number.");
|
||||
return;
|
||||
std::chrono::milliseconds targetPosition;
|
||||
std::string positionStr;
|
||||
|
||||
if (relative) {
|
||||
// Get current position from playback state
|
||||
auto state = manager->getPlaybackState();
|
||||
if (!state) {
|
||||
ctx.reply("Unable to get current playback position.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto currentPos = state->position;
|
||||
if (forward) {
|
||||
targetPosition = currentPos + std::chrono::seconds(seconds);
|
||||
positionStr = std::format("+{}s", seconds);
|
||||
} else {
|
||||
// Seek backward
|
||||
if (currentPos.count() < seconds * 1000) {
|
||||
targetPosition = std::chrono::milliseconds(0);
|
||||
} else {
|
||||
targetPosition = currentPos - std::chrono::seconds(seconds);
|
||||
}
|
||||
positionStr = std::format("-{}s", seconds);
|
||||
}
|
||||
} else {
|
||||
// Absolute seek (legacy behavior)
|
||||
targetPosition = std::chrono::seconds(seconds);
|
||||
auto mins = seconds / 60;
|
||||
auto secs = seconds % 60;
|
||||
positionStr = std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
|
||||
auto result = manager->seek(std::chrono::seconds(seconds));
|
||||
auto result = manager->seek(targetPosition);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command failed: {}", result.error().message));
|
||||
|
||||
@@ -51,12 +93,10 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
auto mins = seconds / 60;
|
||||
auto secs = seconds % 60;
|
||||
if (mins > 0) {
|
||||
ctx.reply(std::format("Seeked to {}:{:02}.", mins, secs));
|
||||
if (relative) {
|
||||
ctx.reply(std::format("Seeked {} from current position.", positionStr));
|
||||
} else {
|
||||
ctx.reply(std::format("Seeked to {} seconds.", seconds));
|
||||
ctx.reply(std::format("Seeked to position {}.", positionStr));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command exception: {}", e.what()));
|
||||
@@ -65,11 +105,11 @@ public:
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Seeks to a position in the current track.";
|
||||
return "Seeks to a position in the current track. Use +seconds to skip forward, -seconds to skip backward.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<seconds>";
|
||||
return "<+/-seconds>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
|
||||
@@ -40,11 +40,13 @@ public:
|
||||
ctx.clientId, index, selectResult.error().message));
|
||||
|
||||
if (selectResult.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply("No search results found. Use [prefix]play <query> to search first.");
|
||||
} else {
|
||||
ctx.reply("Couldn't select that track. Please try again.");
|
||||
}
|
||||
return;
|
||||
ctx.reply(std::format("No search results found. Use {}play "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
} else {
|
||||
ctx.reply("Couldn't select that track. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*selectResult);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SubscribersCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto subscribers = manager->getSubscribers();
|
||||
auto onlineUids = manager->getOnlineSubscriberUids();
|
||||
|
||||
if (subscribers.empty()) {
|
||||
ctx.reply(
|
||||
"No subscribers. Use !subscribe to receive audio.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Separate online and offline
|
||||
std::vector<SubscriptionManager::Subscriber> online;
|
||||
std::vector<SubscriptionManager::Subscriber> offline;
|
||||
|
||||
for (const auto& sub : subscribers) {
|
||||
if (onlineUids.contains(sub.uid)) {
|
||||
online.push_back(sub);
|
||||
} else {
|
||||
offline.push_back(sub);
|
||||
}
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x8b **Subscribed Users** ("
|
||||
<< subscribers.size() << " total)\n";
|
||||
msg << "\xf0\x9f\x9f\xa2 Online: " << online.size()
|
||||
<< " | \xe2\x9a\xaa Offline: " << offline.size()
|
||||
<< "\n\n";
|
||||
|
||||
// Online subscribers
|
||||
if (!online.empty()) {
|
||||
msg << "**\xf0\x9f\x9f\xa2 Online:**\n";
|
||||
for (size_t i = 0; i < online.size(); ++i) {
|
||||
const auto& sub = online[i];
|
||||
msg << std::format("{}. **{}**\n", i + 1,
|
||||
sub.nickname);
|
||||
msg << std::format(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
// Offline subscribers
|
||||
if (!offline.empty()) {
|
||||
msg << "**\xe2\x9a\xaa Offline:**\n";
|
||||
for (size_t i = 0; i < offline.size(); ++i) {
|
||||
const auto& sub = offline[i];
|
||||
msg << std::format("{}. **{}**\n", i + 1,
|
||||
sub.nickname);
|
||||
msg << std::format(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
msg << "Use `!unsubscribeid <uid>` to remove a specific "
|
||||
"subscriber.\n";
|
||||
msg << "Use `!unsubscribeall` to remove all subscribers.";
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Subscribers command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Lists all subscribed users (online/offline).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"subs", "listsubs"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeAllCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->clearAllSubscriptions();
|
||||
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Unsubscribe all failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't clear subscriptions. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribeall command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Removes all subscriptions (admin only).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsuball", "clearsubs"};
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,71 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeIdCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Please provide a user UID. Use !subscribers "
|
||||
"to see UIDs.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string uid(ctx.args);
|
||||
auto result = manager->unsubscribeByUid(uid);
|
||||
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Unsubscribe by ID failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't unsubscribe user. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribeid command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Unsubscribes a user by their UID (admin only).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<uid>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsubid", "removeuser"};
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+20
-30
@@ -234,6 +234,8 @@ Api::Result<void> AudioDecoder::openSource(const std::string& url) {
|
||||
streamInfo_.hwAccelerated = hwAccelEnabled_;
|
||||
streamInfo_.hwAccelType = hwAccelType_;
|
||||
|
||||
streamSampleRate_ = static_cast<uint32_t>(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<Api::DecodedAudio> AudioDecoder::decodeFrame() {
|
||||
}
|
||||
static int callCount = 0;
|
||||
|
||||
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk, bool blocking) {
|
||||
callCount++;
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
bool AudioDecoder::getNextChunk(std::vector<short>& outChunk, bool blocking)
|
||||
{
|
||||
callCount++;
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
if (blocking) {
|
||||
cv_.wait(lock, [this] { return !int16Queue_.empty() || eof_.load(); });
|
||||
@@ -369,7 +372,9 @@ Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position) {
|
||||
|
||||
avcodec_flush_buffers(codecContext_);
|
||||
currentPosition_ = position;
|
||||
|
||||
|
||||
// Clear pending audio data
|
||||
int16Queue_.clear();
|
||||
std::queue<Api::DecodedAudio> empty;
|
||||
std::swap(decodedQueue_, empty);
|
||||
|
||||
@@ -384,6 +389,9 @@ Api::Result<Api::AudioStreamInfo> 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<void> AudioDecoder::readPacket() {
|
||||
|
||||
Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame() {
|
||||
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
|
||||
std::vector<float> outputBuffer(outSamples * outputChannels_);
|
||||
// Use int16_t for direct output (no float conversion)
|
||||
std::vector<int16_t> outputBuffer(outSamples * outputChannels_);
|
||||
|
||||
uint8_t* outData = reinterpret_cast<uint8_t*>(outputBuffer.data());
|
||||
const uint8_t** inData = const_cast<const uint8_t**>(frame_->extended_data);
|
||||
@@ -584,7 +593,8 @@ Api::Result<Api::DecodedAudio> 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<Api::DecodedAudio> AudioDecoder::convertFrame() {
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> 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<uint8_t*>(pooledBuffer.get());
|
||||
const uint8_t** inData = const_cast<const uint8_t**>(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() {
|
||||
|
||||
+205
-15
@@ -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 <echoion/core/commands/Commands.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/commands/Command.hpp"
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <echoion/core/commands/Commands.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
@@ -89,6 +90,122 @@ public:
|
||||
CommandManager::CommandManager() {
|
||||
registerBuiltinCommands();
|
||||
registerHelpCommand();
|
||||
startThreadPool();
|
||||
}
|
||||
|
||||
CommandManager::~CommandManager() {
|
||||
shutdown();
|
||||
}
|
||||
|
||||
void CommandManager::shutdown() {
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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> musicManager,
|
||||
std::function<void(std::string_view)> 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<ResumeCommand>("resume");
|
||||
registerCommand<StopCommand>("stop");
|
||||
registerCommand<SkipCommand>("skip");
|
||||
registerCommand<SeekCommand>("seek");
|
||||
registerCommand<VolumeCommand>("volume");
|
||||
registerCommand<QueueCommand>("queue");
|
||||
// registerCommand<SeekCommand>("seek");
|
||||
registerCommand<VolumeCommand>("volume");
|
||||
registerCommand<QueueCommand>("queue");
|
||||
registerCommand<RemoveCommand>("remove");
|
||||
registerCommand<ClearCommand>("clear");
|
||||
registerCommand<MoveCommand>("move");
|
||||
@@ -260,6 +447,9 @@ void CommandManager::registerBuiltinCommands() {
|
||||
registerCommand<ReloadConfigCommand>("reloadconfig");
|
||||
registerCommand<SubscribeCommand>("subscribe");
|
||||
registerCommand<UnsubscribeCommand>("unsubscribe");
|
||||
registerCommand<SubscribersCommand>("subscribers");
|
||||
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
||||
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
||||
}
|
||||
|
||||
void CommandManager::registerHelpCommand() {
|
||||
|
||||
+24
-1
@@ -26,6 +26,9 @@ struct BotConfigJson {
|
||||
uint32_t trackTimeout = 30000;
|
||||
std::optional<std::string> youtubeCookiesPath;
|
||||
std::optional<std::string> cookiesFromBrowser;
|
||||
uint32_t ytDlpMaxConcurrent = 4;
|
||||
bool ytDlpAsyncEnabled = true;
|
||||
bool enableUrlShortening = true;
|
||||
};
|
||||
|
||||
struct ServerConfigJson {
|
||||
@@ -77,7 +80,10 @@ template<> struct glz::meta<Echoion::Core::BotConfigJson> {
|
||||
"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<Api::AppConfig> 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<size_t>(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<void> 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<uint32_t>(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";
|
||||
|
||||
+231
-118
@@ -3,6 +3,7 @@
|
||||
#include <echoion/api/Database.hpp>
|
||||
#include <format>
|
||||
#include <algorithm>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
@@ -50,22 +51,25 @@ Api::Result<void> Core::initialize(const std::filesystem::path& configPath) {
|
||||
return std::unexpected(netResult.error());
|
||||
}
|
||||
|
||||
// Initialize database
|
||||
database_ = std::make_shared<Api::Database>();
|
||||
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::Database>();
|
||||
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<MusicManager>();
|
||||
auto musicResult = musicManager_->initialize(config_.bot, networkClient_, database_);
|
||||
if (!musicResult) {
|
||||
// Initialize music manager
|
||||
musicManager_ = std::make_shared<MusicManager>();
|
||||
auto musicResult =
|
||||
musicManager_->initialize(config_.bot, networkClient_, database_);
|
||||
if (!musicResult) {
|
||||
return std::unexpected(musicResult.error());
|
||||
}
|
||||
|
||||
@@ -80,89 +84,162 @@ Api::Result<void> 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<const float> 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<int16_t> 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<int16_t>(sample * 32767.0f);
|
||||
}
|
||||
|
||||
// Send to plugin
|
||||
auto result = pluginInterface_->sendAudioData(std::span<const uint8_t>(
|
||||
reinterpret_cast<const uint8_t*>(int16Data.data()),
|
||||
int16Data.size() * sizeof(int16_t)));
|
||||
|
||||
callCount++;
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
if (std::chrono::duration_cast<std::chrono::seconds>(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<const short> data) {
|
||||
static int callCount = 0;
|
||||
static auto lastLog = std::chrono::steady_clock::now();
|
||||
|
||||
// Start RPC server for Desktop/API clients
|
||||
rpcServer_ = std::make_shared<RpcServer>();
|
||||
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<std::chrono::seconds>(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<std::pair<std::string, std::string>> {
|
||||
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<uint64_t> {
|
||||
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<std::string> {
|
||||
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<RpcServer>();
|
||||
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<uintptr_t>(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<void> Core::shutdown() {
|
||||
|
||||
ECHOION_LOG_INFO("Shutting down Echoion Core...");
|
||||
|
||||
if (commandManager_) {
|
||||
commandManager_->shutdown();
|
||||
}
|
||||
|
||||
if (musicManager_) {
|
||||
musicManager_->shutdown();
|
||||
}
|
||||
@@ -211,7 +292,7 @@ Api::Result<void> Core::shutdown() {
|
||||
}
|
||||
|
||||
initialized_ = false;
|
||||
ECHOION_LOG_INFO("Echoion Core shutdown complete");
|
||||
ECHOION_LOG_INFO(std::format("Echoion Core shutdown complete (this={})", reinterpret_cast<uintptr_t>(this)));
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -559,15 +640,27 @@ void Core::unregisterEventCallback(const Api::EventCallback& callback) {
|
||||
}
|
||||
|
||||
Api::Result<void> Core::onPluginEvent(const Api::PluginEvent& event) {
|
||||
ECHOION_LOG_DEBUG(std::format("Core::onPluginEvent called (this={}, initialized={})",
|
||||
reinterpret_cast<uintptr_t>(this), initialized_.load()));
|
||||
if (!initialized_) {
|
||||
ECHOION_LOG_WARNING(std::format("Core::onPluginEvent: Core not initialized (this={}), ignoring event type={}",
|
||||
reinterpret_cast<uintptr_t>(this), static_cast<int>(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<void> 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<uintptr_t>(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<uint64_t> 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<uint64_t> 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() {
|
||||
|
||||
+104
-20
@@ -3,6 +3,7 @@
|
||||
#include <sqlite3.h>
|
||||
#include <format>
|
||||
#include <cstring>
|
||||
#include <shared_mutex>
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
@@ -18,10 +19,15 @@ public:
|
||||
Database::Database() : impl_(std::make_unique<DatabaseImpl>()) {}
|
||||
|
||||
Database::~Database() {
|
||||
shutdown();
|
||||
// Only shutdown if not already shut down
|
||||
if (!shutdown_.load()) {
|
||||
shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
Result<void> Database::initialize(const DatabaseConfig& config) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
impl_->config = config;
|
||||
|
||||
int rc = sqlite3_open(config.path.c_str(), &impl_->db);
|
||||
@@ -30,7 +36,7 @@ Result<void> 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<void> Database::initialize(const DatabaseConfig& config) {
|
||||
sqlite3_busy_timeout(impl_->db,
|
||||
static_cast<int>(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<void> 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<std::shared_mutex> 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<std::shared_mutex> lock(mutex_);
|
||||
return impl_->initialized;
|
||||
}
|
||||
|
||||
@@ -171,7 +191,35 @@ Result<void> 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<uint64_t> Database::createPlaylist(const std::string& name,
|
||||
const std::string& description, uint64_t createdBy, bool isPublic) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO playlists (name, description, created_by, is_public)
|
||||
@@ -212,6 +261,8 @@ Result<uint64_t> Database::createPlaylist(const std::string& name,
|
||||
}
|
||||
|
||||
Result<std::optional<Playlist>> Database::getPlaylist(uint64_t id) {
|
||||
std::shared_lock<std::shared_mutex> 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<std::optional<Playlist>> Database::getPlaylist(uint64_t id) {
|
||||
}
|
||||
|
||||
Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId) {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
std::vector<Playlist> playlists;
|
||||
|
||||
const char* sql = R"(
|
||||
@@ -303,6 +355,7 @@ Result<std::vector<Playlist>> Database::getUserPlaylists(uint64_t userId) {
|
||||
}
|
||||
|
||||
Result<void> Database::deletePlaylist(uint64_t id) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql = "DELETE FROM playlists WHERE id = ?;";
|
||||
|
||||
sqlite3_stmt* stmt;
|
||||
@@ -320,6 +373,7 @@ Result<void> Database::deletePlaylist(uint64_t id) {
|
||||
|
||||
Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
|
||||
const TrackInfo& track, uint32_t position) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO playlist_tracks
|
||||
@@ -354,7 +408,10 @@ Result<void> Database::addTrackToPlaylist(uint64_t playlistId,
|
||||
|
||||
// Playback history
|
||||
Result<void> 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<std::shared_mutex> lock(mutex_);
|
||||
|
||||
const char* sql = R"(
|
||||
INSERT INTO playback_history
|
||||
@@ -382,7 +439,10 @@ Result<void> Database::recordPlayback(const TrackInfo& track,
|
||||
}
|
||||
|
||||
Result<std::vector<PlaybackHistoryEntry>> Database::getPlaybackHistory(
|
||||
uint64_t userId, size_t limit, size_t offset) {
|
||||
uint64_t userId,
|
||||
size_t limit,
|
||||
size_t offset) {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
|
||||
std::vector<PlaybackHistoryEntry> history;
|
||||
|
||||
@@ -422,6 +482,7 @@ Result<std::vector<PlaybackHistoryEntry>> Database::getPlaybackHistory(
|
||||
|
||||
// Favorites
|
||||
Result<void> Database::addFavorite(uint64_t userId, const TrackInfo& track) {
|
||||
std::unique_lock<std::shared_mutex> 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<void> Database::addFavorite(uint64_t userId, const TrackInfo& track) {
|
||||
}
|
||||
|
||||
Result<void> Database::removeFavorite(uint64_t userId, const std::string& trackUrl) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql = "DELETE FROM user_favorites WHERE user_id = ? AND track_url = ?;";
|
||||
|
||||
sqlite3_stmt* stmt;
|
||||
@@ -464,6 +526,7 @@ Result<void> Database::removeFavorite(uint64_t userId, const std::string& trackU
|
||||
}
|
||||
|
||||
Result<bool> Database::isFavorite(uint64_t userId, const std::string& trackUrl) {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql =
|
||||
"SELECT 1 FROM user_favorites WHERE user_id = ? AND track_url = ? LIMIT 1;";
|
||||
|
||||
@@ -483,6 +546,7 @@ Result<bool> Database::isFavorite(uint64_t userId, const std::string& trackUrl)
|
||||
}
|
||||
|
||||
Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId) {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
std::vector<FavoriteTrack> favorites;
|
||||
|
||||
const char* sql = R"(
|
||||
@@ -515,6 +579,7 @@ Result<std::vector<FavoriteTrack>> Database::getFavorites(uint64_t userId) {
|
||||
|
||||
// Maintenance
|
||||
Result<void> Database::trimHistory(size_t keepCount) {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql = R"(
|
||||
DELETE FROM playback_history
|
||||
WHERE id NOT IN (
|
||||
@@ -541,6 +606,7 @@ Result<void> Database::trimHistory(size_t keepCount) {
|
||||
}
|
||||
|
||||
Result<void> Database::clearUserData(uint64_t userId) {
|
||||
std::unique_lock<std::shared_mutex> 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<void> Database::clearUserData(uint64_t userId) {
|
||||
}
|
||||
|
||||
Result<void> Database::vacuum() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
sqlite3_exec(impl_->db, "VACUUM;", nullptr, nullptr, nullptr);
|
||||
return {};
|
||||
}
|
||||
|
||||
// Subscriptions
|
||||
Result<void> Database::addSubscriber(uint64_t clientId) {
|
||||
Result<void> Database::addSubscriber(const std::string& uid, const std::string& nickname) {
|
||||
std::unique_lock<std::shared_mutex> 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<void> Database::addSubscriber(uint64_t clientId) {
|
||||
sqlite3_errmsg(impl_->db)));
|
||||
}
|
||||
|
||||
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(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<void> Database::removeSubscriber(uint64_t clientId) {
|
||||
const char* sql = "DELETE FROM subscriptions WHERE client_id = ?;";
|
||||
Result<void> Database::removeSubscriber(const std::string& uid) {
|
||||
std::unique_lock<std::shared_mutex> 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<void> Database::removeSubscriber(uint64_t clientId) {
|
||||
sqlite3_errmsg(impl_->db)));
|
||||
}
|
||||
|
||||
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(clientId));
|
||||
sqlite3_bind_text(stmt, 1, uid.c_str(), -1, SQLITE_STATIC);
|
||||
sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<bool> Database::isSubscriber(uint64_t clientId) {
|
||||
Result<bool> Database::isSubscriber(const std::string& uid) {
|
||||
std::shared_lock<std::shared_mutex> 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<bool> Database::isSubscriber(uint64_t clientId) {
|
||||
sqlite3_errmsg(impl_->db)));
|
||||
}
|
||||
|
||||
sqlite3_bind_int64(stmt, 1, static_cast<sqlite3_int64>(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<std::vector<uint64_t>> Database::getAllSubscribers() {
|
||||
std::vector<uint64_t> subscribers;
|
||||
Result<std::vector<Database::SubscriberInfo>> Database::getAllSubscribers() {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
std::vector<SubscriberInfo> 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<std::vector<uint64_t>> Database::getAllSubscribers() {
|
||||
}
|
||||
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
subscribers.push_back(static_cast<uint64_t>(sqlite3_column_int64(stmt, 0)));
|
||||
SubscriberInfo info;
|
||||
info.uid = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
|
||||
info.nickname = reinterpret_cast<const char*>(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<void> Database::clearAllSubscribers() {
|
||||
std::unique_lock<std::shared_mutex> lock(mutex_);
|
||||
sqlite3_exec(impl_->db, "DELETE FROM subscriptions;", nullptr, nullptr, nullptr);
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<size_t> Database::getSubscriberCount() {
|
||||
std::shared_lock<std::shared_mutex> lock(mutex_);
|
||||
const char* sql = "SELECT COUNT(*) FROM subscriptions;";
|
||||
|
||||
sqlite3_stmt* stmt;
|
||||
|
||||
+95
-9
@@ -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<std::mutex> 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<std::pair<std::filesystem::path, std::filesystem::file_time_type>> 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<std::mutex> 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);
|
||||
|
||||
+8
-8
@@ -10,9 +10,9 @@ AudioBufferPool& AudioBufferPool::instance() {
|
||||
|
||||
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
|
||||
bufferSize_ = bufferSize;
|
||||
pool_ = std::make_unique<MemoryPool<float>>(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<MemoryPool<int16_t>>(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<float> AudioBufferPool::acquireBuffer() {
|
||||
PooledPtr<int16_t> AudioBufferPool::acquireBuffer() {
|
||||
if (!pool_) {
|
||||
return PooledPtr<float>();
|
||||
return PooledPtr<int16_t>();
|
||||
}
|
||||
|
||||
float* ptr = pool_->acquire();
|
||||
int16_t* ptr = pool_->acquire();
|
||||
if (!ptr) {
|
||||
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
|
||||
return PooledPtr<float>();
|
||||
return PooledPtr<int16_t>();
|
||||
}
|
||||
|
||||
return PooledPtr<float>(ptr, pool_.get());
|
||||
return PooledPtr<int16_t>(ptr, pool_.get());
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getAvailableBuffers() const {
|
||||
|
||||
+1377
-569
File diff suppressed because it is too large.
Load diff
@@ -339,8 +339,8 @@ Api::Result<Api::HttpResponse> 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<asio::ip::tcp::socket> 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<asio::ip::tcp::socket> 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);
|
||||
|
||||
+97
-20
@@ -28,14 +28,14 @@ Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database>
|
||||
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<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
return subscribedClients_.contains(clientId);
|
||||
return subscribedUids_.contains(uid);
|
||||
}
|
||||
|
||||
std::set<uint64_t> SubscriptionManager::getSubscribedClients() const {
|
||||
std::vector<std::string> SubscriptionManager::getSubscribedUids() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return subscribedClients_;
|
||||
return std::vector<std::string>(subscribedUids_.begin(), subscribedUids_.end());
|
||||
}
|
||||
|
||||
std::vector<SubscriptionManager::Subscriber> SubscriptionManager::getSubscribers() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<Subscriber> 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<std::string> SubscriptionManager::getSubscriberNickname(const std::string& uid) const {
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
return !subscribedClients_.empty();
|
||||
return !subscribedUids_.empty();
|
||||
}
|
||||
|
||||
size_t SubscriptionManager::getSubscriberCount() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return subscribedClients_.size();
|
||||
return subscribedUids_.size();
|
||||
}
|
||||
|
||||
bool SubscriptionManager::clearAll() {
|
||||
std::lock_guard<std::mutex> 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
|
||||
@@ -0,0 +1,144 @@
|
||||
#include "echoion/core/UrlShortener.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <glaze/glaze.hpp>
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
|
||||
: networkClient_(std::move(networkClient)) {
|
||||
}
|
||||
|
||||
UrlShortener::~UrlShortener() = default;
|
||||
|
||||
Api::Result<std::string> UrlShortener::shortenYouTubeUrl(std::string_view videoId) {
|
||||
std::string originalUrl = std::format("https://www.youtube.com/watch?v={}", videoId);
|
||||
return shortenUrl(originalUrl);
|
||||
}
|
||||
|
||||
Api::Result<std::string> UrlShortener::shortenUrl(std::string_view originalUrl) {
|
||||
// Check cache first
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<Api::HttpHeader> 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<std::string>();
|
||||
} 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<std::mutex> 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<std::string> UrlShortener::getCachedUrl(std::string_view originalUrl) const {
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lock(cacheMutex_);
|
||||
cache_.clear();
|
||||
}
|
||||
|
||||
void UrlShortener::setCacheTtl(std::chrono::hours ttl) {
|
||||
cacheTtl_ = ttl;
|
||||
}
|
||||
|
||||
void UrlShortener::cleanExpiredCache() {
|
||||
std::lock_guard<std::mutex> 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
|
||||
+1435
-185
File diff suppressed because it is too large.
Load diff
+301
-72
@@ -1,11 +1,12 @@
|
||||
#include "echoion/core/YtDlpManager.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <cstdlib>
|
||||
#include "echoion/core/YtDlpManager.hpp"
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <future>
|
||||
#include <glaze/glaze.hpp>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
@@ -20,7 +21,7 @@ YtDlpManager::YtDlpManager(std::shared_ptr<NetworkClient> 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<void> YtDlpManager::initialize() {
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO(std::format("yt-dlp ready: {}", version));
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
initialized_ = true;
|
||||
return {};
|
||||
|
||||
// Start thread pool for async operations
|
||||
startThreadPool();
|
||||
|
||||
std::lock_guard<std::mutex> 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<YtDlpResult()> task;
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
return threadPoolSize_;
|
||||
}
|
||||
|
||||
void YtDlpManager::setProxyConfig(const std::optional<Api::ProxyConfig>& proxy)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<Api::ProxyConfig> YtDlpManager::getProxyConfig() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(proxyMutex_);
|
||||
return proxyConfig_;
|
||||
}
|
||||
|
||||
std::vector<std::string> YtDlpManager::getProxyArgs() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(proxyMutex_);
|
||||
std::vector<std::string> 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<void> YtDlpManager::downloadYtDlp() {
|
||||
@@ -374,50 +518,86 @@ std::vector<std::string> YtDlpManager::getCookieArgs() const {
|
||||
}
|
||||
|
||||
std::string YtDlpManager::execute(const std::vector<std::string>& 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<std::string>& 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<char, 8192> 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<std::chrono::milliseconds>(endTime -
|
||||
startTime);
|
||||
result.output = std::move(output);
|
||||
result.success = (result.exitCode == 0);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string
|
||||
YtDlpManager::buildCommand(const std::vector<std::string>& 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<std::string>& 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<char, 8192> 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<YtDlpResult>
|
||||
YtDlpManager::executeAsync(const std::vector<std::string>& args)
|
||||
{
|
||||
std::packaged_task<YtDlpResult()> task(
|
||||
[this, args]() { return executeInternal(args); });
|
||||
|
||||
auto future = task.get_future();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(taskMutex_);
|
||||
taskQueue_.push(std::move(task));
|
||||
}
|
||||
|
||||
taskCv_.notify_one();
|
||||
return future;
|
||||
}
|
||||
|
||||
std::vector<YtDlpResult> YtDlpManager::executeBatch(
|
||||
const std::vector<std::vector<std::string>>& argsList)
|
||||
{
|
||||
|
||||
std::vector<std::future<YtDlpResult>> futures;
|
||||
futures.reserve(argsList.size());
|
||||
|
||||
// Launch all tasks
|
||||
for (const auto& args : argsList) {
|
||||
futures.push_back(executeAsync(args));
|
||||
}
|
||||
|
||||
// Collect results
|
||||
std::vector<YtDlpResult> results;
|
||||
results.reserve(argsList.size());
|
||||
|
||||
for (auto& future : futures) {
|
||||
results.push_back(future.get());
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Reference in new issue
Block a user