Migrate core infrastructure to VoidLibrary
This commit is contained in:
1 parent
53801f2b53
commit
2bdb63766d
65 files changed
+16109
-12011
No files matched your search
+84
-36
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
@@ -6,38 +6,39 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
add_definitions(-DECHOION_API_EXPORT)
|
||||
|
||||
add_library(EchoionCore SHARED
|
||||
src/Logger.cpp
|
||||
src/NetworkClient.cpp
|
||||
src/SignatureCipher.cpp
|
||||
src/YouTubeClient.cpp
|
||||
src/YtDlpManager.cpp
|
||||
src/UrlShortener.cpp
|
||||
src/AudioDecoder.cpp
|
||||
src/CommandManager.cpp
|
||||
src/MusicManager.cpp
|
||||
src/SubscriptionManager.cpp
|
||||
src/Core.cpp
|
||||
src/Export.cpp
|
||||
src/EventBus.cpp
|
||||
src/Cache.cpp
|
||||
src/MemoryPool.cpp
|
||||
src/Database.cpp
|
||||
src/RpcServer.cpp
|
||||
src/ConfigLoader.cpp
|
||||
file(GLOB_RECURSE CORE_SOURCES
|
||||
CONFIGURE_DEPENDS
|
||||
"src/**.cpp"
|
||||
)
|
||||
add_library(EchoionCore SHARED ${CORE_SOURCES})
|
||||
|
||||
add_library(Echoion::Core ALIAS EchoionCore)
|
||||
|
||||
target_include_directories(EchoionCore PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../EchoionApi/include/echoion/api/config>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(EchoionCore PUBLIC Echoion::Api)
|
||||
# Core uses all API modules
|
||||
target_link_libraries(EchoionCore PUBLIC
|
||||
Echoion::ApiBase
|
||||
Echoion::ApiAudio
|
||||
Echoion::ApiTrack
|
||||
Echoion::ApiNetwork
|
||||
Echoion::ApiPlugin
|
||||
Echoion::ApiConfig
|
||||
Echoion::ApiRpc
|
||||
Echoion::ApiYouTube
|
||||
Echoion::ApiLogger
|
||||
Echoion::ApiEventBus
|
||||
Echoion::ApiDatabase
|
||||
Echoion::ApiOpaque
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiCoreInterface
|
||||
Echoion::ApiUtils
|
||||
)
|
||||
|
||||
find_package(glaze CONFIG REQUIRED)
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
|
||||
libavformat
|
||||
@@ -52,6 +53,21 @@ CPMAddPackage(
|
||||
GIT_TAG v0.11.0
|
||||
)
|
||||
|
||||
# quickjs-ng v0.11.0 compiles its C sources with -Werror, which trips newer GCC
|
||||
# diagnostics (e.g. -Wmaybe-uninitialized / -Wdiscarded-qualifiers under GCC 16+).
|
||||
# It is a vendored third-party dependency, so relax -Werror on every target it
|
||||
# defines (qjs, qjsc, qjs-libc, ...) rather than guessing target names.
|
||||
if(quickjs_SOURCE_DIR)
|
||||
get_property(_qjs_targets DIRECTORY "${quickjs_SOURCE_DIR}"
|
||||
PROPERTY BUILDSYSTEM_TARGETS)
|
||||
foreach(_qjs_target ${_qjs_targets})
|
||||
get_target_property(_qjs_type ${_qjs_target} TYPE)
|
||||
if(NOT _qjs_type STREQUAL "INTERFACE_LIBRARY")
|
||||
target_compile_options(${_qjs_target} PRIVATE -Wno-error)
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
set(AddBoost.cmake_VERSION 3.7.3)
|
||||
CPMAddPackage(
|
||||
NAME AddBoost.cmake
|
||||
@@ -68,19 +84,25 @@ add_boost(
|
||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||
)
|
||||
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
find_package(TBB REQUIRED)
|
||||
|
||||
target_link_libraries(EchoionCore
|
||||
target_link_libraries(EchoionCore
|
||||
PUBLIC
|
||||
PkgConfig::LIBAV
|
||||
TBB::tbb
|
||||
SQLite::SQLite3
|
||||
# VoidLibrary modules (migration target — replacing in-house infra)
|
||||
Void::Data
|
||||
Void::Functional
|
||||
Void::System
|
||||
Void::Log
|
||||
Void::Async
|
||||
Void::Containers
|
||||
Void::Resilience
|
||||
PRIVATE
|
||||
glaze::glaze
|
||||
Threads::Threads
|
||||
qjs
|
||||
Boost::beast
|
||||
@@ -88,7 +110,6 @@ target_link_libraries(EchoionCore
|
||||
Boost::asio
|
||||
OpenSSL::SSL
|
||||
OpenSSL::Crypto
|
||||
|
||||
)
|
||||
|
||||
if(MSVC)
|
||||
@@ -107,19 +128,46 @@ set_target_properties(EchoionCore PROPERTIES
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib
|
||||
)
|
||||
|
||||
# PackageProject.cmake configuration
|
||||
packageProject(
|
||||
NAME EchoionCore
|
||||
# Export EchoionCore
|
||||
target_include_directories(EchoionCore PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
install(TARGETS EchoionCore
|
||||
EXPORT EchoionCoreTargets
|
||||
RUNTIME DESTINATION bin
|
||||
LIBRARY DESTINATION lib
|
||||
ARCHIVE DESTINATION lib
|
||||
INCLUDES DESTINATION include
|
||||
)
|
||||
|
||||
install(EXPORT EchoionCoreTargets
|
||||
FILE EchoionCoreTargets.cmake
|
||||
NAMESPACE Echoion::
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
# Package config files
|
||||
include(CMakePackageConfigHelpers)
|
||||
write_basic_package_version_file(
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
|
||||
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
|
||||
)
|
||||
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
|
||||
"include(\"\${CMAKE_CURRENT_LIST_DIR}/EchoionCoreTargets.cmake\")
|
||||
include(CMakeFindDependencyMacro)
|
||||
find_dependency(EchoionApi)
|
||||
")
|
||||
|
||||
install(FILES
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfig.cmake"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/EchoionCoreConfigVersion.cmake"
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
# Optional: Bundle FFmpeg libraries for distribution
|
||||
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
|
||||
if(BUNDLE_FFMPEG)
|
||||
include(cmake/BundleFFmpeg.cmake)
|
||||
|
||||
@@ -1,146 +1,169 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include "NetworkTypes.hpp"
|
||||
#include <AudioTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <span>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <span>
|
||||
#include <thread>
|
||||
|
||||
// Forward declarations for FFmpeg
|
||||
extern "C" {
|
||||
struct AVFormatContext;
|
||||
struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
struct SwrContext;
|
||||
struct AVBufferRef;
|
||||
struct AVFormatContext;
|
||||
struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
struct SwrContext;
|
||||
struct AVBufferRef;
|
||||
}
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class AudioDecoder {
|
||||
public:
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
class AudioDecoder
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize decoder with optional hardware acceleration
|
||||
Api::Result<void> initialize(const Api::HwAccelConfig& hwConfig = {});
|
||||
void shutdown();
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
|
||||
// Open audio source (URL or file path)
|
||||
Api::Result<void> openSource(const std::string& url);
|
||||
void closeSource();
|
||||
// Initialize decoder with optional hardware acceleration
|
||||
Api::Result<void>
|
||||
initialize(const Api::HwAccelConfig& hwConfig = {});
|
||||
void shutdown();
|
||||
|
||||
// Decode audio - returns zero-copy pooled buffer
|
||||
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
||||
|
||||
// Seek to position
|
||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
// Open audio source (URL or file path)
|
||||
Api::Result<void> openSource(const std::string& url);
|
||||
void closeSource();
|
||||
|
||||
// Get audio info
|
||||
[[nodiscard]] Api::Result<Api::AudioStreamInfo> getStreamInfo() const;
|
||||
|
||||
// Get current position
|
||||
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
||||
|
||||
// Check if decoder has more data
|
||||
[[nodiscard]] bool hasMoreData() const;
|
||||
// Decode audio - returns zero-copy pooled buffer
|
||||
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
||||
|
||||
// Set output format
|
||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||
// Seek to position
|
||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
|
||||
// Set proxy configuration for network requests
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
|
||||
// Hardware acceleration
|
||||
[[nodiscard]] bool isHardwareAccelerated() const { return hwAccelEnabled_; }
|
||||
[[nodiscard]] Api::HwAccelType getHwAccelType() const { return hwAccelType_; }
|
||||
|
||||
// Enable/disable zero-copy mode
|
||||
void setZeroCopyEnabled(bool enabled) { zeroCopyEnabled_ = enabled; }
|
||||
[[nodiscard]] bool isZeroCopyEnabled() const { return zeroCopyEnabled_; }
|
||||
|
||||
// Get decoder statistics
|
||||
struct Stats {
|
||||
uint64_t framesDecoded = 0;
|
||||
uint64_t framesDropped = 0;
|
||||
uint64_t bytesDecoded = 0;
|
||||
std::chrono::milliseconds totalDecodeTime{0};
|
||||
double averageDecodeTimeMs = 0.0;
|
||||
bool hwAccelerationActive = false;
|
||||
};
|
||||
[[nodiscard]] Stats getStats() const;
|
||||
|
||||
// Get next S16 chunk (like reference implementation)
|
||||
bool getNextChunk(std::vector<int16_t>& outChunk, bool blocking = false);
|
||||
|
||||
// Check if decode is finished
|
||||
[[nodiscard]] bool isFinished() const { return eof_.load(); }
|
||||
// Get audio info
|
||||
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
|
||||
getStreamInfo() const;
|
||||
|
||||
private:
|
||||
void decodeThread();
|
||||
Api::Result<void> readPacket();
|
||||
Api::Result<Api::DecodedAudio> convertFrame();
|
||||
void cleanupFfmpeg();
|
||||
|
||||
// Hardware acceleration setup
|
||||
Api::Result<void> initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||
void cleanupHardwareAccel();
|
||||
// Get current position
|
||||
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
||||
|
||||
// Frame conversion (returns int16 for direct playback)
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
// Check if decoder has more data
|
||||
[[nodiscard]] bool hasMoreData() const;
|
||||
|
||||
// FFmpeg contexts
|
||||
AVFormatContext* formatContext_ = nullptr;
|
||||
AVCodecContext* codecContext_ = nullptr;
|
||||
AVFrame* frame_ = nullptr;
|
||||
AVPacket* packet_ = nullptr;
|
||||
SwrContext* swrContext_ = nullptr;
|
||||
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
|
||||
|
||||
// Hardware acceleration
|
||||
AVBufferRef* hwDeviceContext_ = nullptr;
|
||||
AVBufferRef* hwFramesContext_ = nullptr;
|
||||
bool hwAccelEnabled_ = false;
|
||||
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
|
||||
bool zeroCopyEnabled_ = true;
|
||||
// Set output format
|
||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||
|
||||
// Stream info
|
||||
int audioStreamIndex_ = -1;
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
|
||||
// Output format
|
||||
uint32_t outputSampleRate_ = 192000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
// Set proxy configuration for network requests
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
|
||||
// Threading
|
||||
std::jthread decodeThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::queue<Api::DecodedAudio> decodedQueue_;
|
||||
static constexpr size_t MAX_QUEUE_SIZE = 50;
|
||||
|
||||
// S16 audio queue (like reference) - avoids float conversion
|
||||
std::deque<std::vector<int16_t>> int16Queue_;
|
||||
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
||||
// Hardware acceleration
|
||||
[[nodiscard]] bool isHardwareAccelerated() const
|
||||
{
|
||||
return hwAccelEnabled_;
|
||||
}
|
||||
[[nodiscard]] Api::HwAccelType getHwAccelType() const
|
||||
{
|
||||
return hwAccelType_;
|
||||
}
|
||||
|
||||
// State
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> decoding_{false};
|
||||
std::atomic<bool> eof_{false};
|
||||
std::atomic<bool> shouldExit_{false}; // For FFmpeg interrupt callback
|
||||
std::chrono::milliseconds currentPosition_{0};
|
||||
std::string currentUrl_;
|
||||
// Enable/disable zero-copy mode
|
||||
void setZeroCopyEnabled(bool enabled)
|
||||
{
|
||||
zeroCopyEnabled_ = enabled;
|
||||
}
|
||||
[[nodiscard]] bool isZeroCopyEnabled() const
|
||||
{
|
||||
return zeroCopyEnabled_;
|
||||
}
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
|
||||
// Statistics
|
||||
mutable std::mutex statsMutex_;
|
||||
Stats stats_;
|
||||
};
|
||||
// Get decoder statistics
|
||||
struct Stats {
|
||||
uint64_t framesDecoded = 0;
|
||||
uint64_t framesDropped = 0;
|
||||
uint64_t bytesDecoded = 0;
|
||||
std::chrono::milliseconds totalDecodeTime{0};
|
||||
double averageDecodeTimeMs = 0.0;
|
||||
bool hwAccelerationActive = false;
|
||||
};
|
||||
[[nodiscard]] Stats getStats() const;
|
||||
|
||||
// Get next S16 chunk (like reference implementation)
|
||||
bool getNextChunk(std::vector<int16_t>& outChunk,
|
||||
bool blocking = false);
|
||||
|
||||
// Check if decode is finished
|
||||
[[nodiscard]] bool isFinished() const { return eof_.load(); }
|
||||
|
||||
private:
|
||||
|
||||
void decodeThread();
|
||||
Api::Result<void> readPacket();
|
||||
Api::Result<Api::DecodedAudio> convertFrame();
|
||||
void cleanupFfmpeg();
|
||||
|
||||
// Hardware acceleration setup
|
||||
Api::Result<void>
|
||||
initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||
void cleanupHardwareAccel();
|
||||
|
||||
// Frame conversion (returns int16 for direct playback)
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// FFmpeg contexts
|
||||
AVFormatContext* formatContext_ = nullptr;
|
||||
AVCodecContext* codecContext_ = nullptr;
|
||||
AVFrame* frame_ = nullptr;
|
||||
AVPacket* packet_ = nullptr;
|
||||
SwrContext* swrContext_ = nullptr;
|
||||
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
|
||||
|
||||
// Hardware acceleration
|
||||
AVBufferRef* hwDeviceContext_ = nullptr;
|
||||
AVBufferRef* hwFramesContext_ = nullptr;
|
||||
bool hwAccelEnabled_ = false;
|
||||
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
|
||||
bool zeroCopyEnabled_ = true;
|
||||
|
||||
// Stream info
|
||||
int audioStreamIndex_ = -1;
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
|
||||
// Output format
|
||||
uint32_t outputSampleRate_ = 192000;
|
||||
uint32_t outputChannels_ = 2;
|
||||
|
||||
// Threading
|
||||
std::jthread decodeThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::queue<Api::DecodedAudio> decodedQueue_;
|
||||
static constexpr size_t MAX_QUEUE_SIZE = 50;
|
||||
|
||||
// S16 audio queue (like reference) - avoids float conversion
|
||||
std::deque<std::vector<int16_t>> int16Queue_;
|
||||
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
||||
|
||||
// State
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> decoding_{false};
|
||||
std::atomic<bool> eof_{false};
|
||||
std::atomic<bool> shouldExit_{
|
||||
false}; // For FFmpeg interrupt callback
|
||||
std::chrono::milliseconds currentPosition_{0};
|
||||
std::string currentUrl_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
|
||||
// Statistics
|
||||
mutable std::mutex statsMutex_;
|
||||
Stats stats_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,10 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "commands/Command.hpp"
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <echoion/api.hpp>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <map>
|
||||
@@ -15,151 +16,163 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager;
|
||||
class MusicManager;
|
||||
|
||||
// Function to check if client has permission (set by Core)
|
||||
using PermissionCheckFunc = std::function<bool(uint64_t clientId, CommandCategory category)>;
|
||||
|
||||
/**
|
||||
* @brief Manages command registration and dispatch.
|
||||
*
|
||||
* Usage:
|
||||
* CommandManager mgr;
|
||||
* mgr.registerCommand<PlayCommand>("play");
|
||||
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
|
||||
*/
|
||||
class CommandManager {
|
||||
public:
|
||||
CommandManager();
|
||||
~CommandManager();
|
||||
|
||||
// Shutdown the command manager (stops thread pool)
|
||||
void shutdown();
|
||||
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
CommandManager& operator=(const CommandManager&) = delete;
|
||||
|
||||
// Enable move
|
||||
CommandManager(CommandManager&&) = default;
|
||||
CommandManager& operator=(CommandManager&&) = default;
|
||||
|
||||
/**
|
||||
* @brief Registers a command class.
|
||||
* @tparam T The command class (must inherit Command).
|
||||
* @param primaryName The primary name/trigger (e.g., "play").
|
||||
*/
|
||||
template <typename T>
|
||||
void registerCommand(const std::string& primaryName) {
|
||||
auto cmd = std::make_shared<T>();
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
// Register primary name
|
||||
commands_[primaryName] = cmd;
|
||||
uniqueCommands_.push_back({primaryName, cmd});
|
||||
|
||||
// Register aliases automatically from the class itself
|
||||
for (auto alias : cmd->getAliases()) {
|
||||
commands_[std::string(alias)] = cmd;
|
||||
}
|
||||
}
|
||||
// Function to check if client has permission (set by Core)
|
||||
using PermissionCheckFunc =
|
||||
std::function<bool(uint64_t clientId, CommandCategory category)>;
|
||||
|
||||
/**
|
||||
* @brief Dispatches a command message to the appropriate handler (ASYNC).
|
||||
* Commands are executed in a thread pool, allowing multiple users to
|
||||
* use the bot simultaneously without blocking.
|
||||
* @param clientId The client ID who invoked the command.
|
||||
* @param message The full message (including prefix, e.g., "!play song").
|
||||
* @param musicManager Weak pointer to the MusicManager.
|
||||
* @param replyFunc Function to call to send a reply.
|
||||
* @param invokerName Name of the invoking user.
|
||||
* @return true if a command was found and queued for execution, false
|
||||
* otherwise.
|
||||
* @brief Manages command registration and dispatch.
|
||||
*
|
||||
* Usage:
|
||||
* CommandManager mgr;
|
||||
* mgr.registerCommand<PlayCommand>("play");
|
||||
* mgr.dispatch(clientId, "play song name", musicManager, replyFunc);
|
||||
*/
|
||||
[[nodiscard]] bool dispatch(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
class CommandManager
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Executes a command synchronously (for internal use).
|
||||
* Prefer using dispatch() for normal command handling.
|
||||
*/
|
||||
[[nodiscard]] bool
|
||||
dispatchSync(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
CommandManager();
|
||||
~CommandManager();
|
||||
|
||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::optional<CommandPtr> getCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getAllCommands() const;
|
||||
|
||||
// Get commands visible to a specific client (for help)
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>> getVisibleCommands(uint64_t clientId) const;
|
||||
|
||||
// Check if client can execute a command
|
||||
[[nodiscard]] bool canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const;
|
||||
// Shutdown the command manager (stops thread pool)
|
||||
void shutdown();
|
||||
|
||||
void setPrefix(std::string_view prefix);
|
||||
[[nodiscard]] std::string_view getPrefix() const { return prefix_; }
|
||||
|
||||
// Set permission check function
|
||||
void setPermissionCheckFunc(PermissionCheckFunc func);
|
||||
// Set server config for permission checks
|
||||
void setServerConfig(const Api::AppConfig& config);
|
||||
// Disable copy
|
||||
CommandManager(const CommandManager&) = delete;
|
||||
CommandManager& operator=(const CommandManager&) = delete;
|
||||
|
||||
private:
|
||||
struct CommandEntry {
|
||||
std::string primaryName;
|
||||
CommandPtr instance;
|
||||
};
|
||||
// Enable move
|
||||
CommandManager(CommandManager&&) = default;
|
||||
CommandManager& operator=(CommandManager&&) = default;
|
||||
|
||||
void registerBuiltinCommands();
|
||||
|
||||
// Internal Help Command (defined in .cpp to access registry)
|
||||
class HelpCommand;
|
||||
void registerHelpCommand();
|
||||
/**
|
||||
* @brief Registers a command class.
|
||||
* @tparam T The command class (must inherit Command).
|
||||
* @param primaryName The primary name/trigger (e.g., "play").
|
||||
*/
|
||||
template <typename T>
|
||||
void registerCommand(const std::string& primaryName)
|
||||
{
|
||||
auto cmd = std::make_shared<T>();
|
||||
|
||||
std::string prefix_ = "!";
|
||||
|
||||
// Map for fast lookup: "play" -> PlayCommand
|
||||
std::map<std::string, CommandPtr, std::less<>> commands_;
|
||||
|
||||
// List for generating help: {"play", PlayCommand}
|
||||
std::vector<CommandEntry> uniqueCommands_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Permission checking
|
||||
PermissionCheckFunc permissionCheck_;
|
||||
std::optional<Api::AppConfig> serverConfig_;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
// Async command execution
|
||||
struct CommandTask {
|
||||
uint64_t clientId;
|
||||
std::string message;
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
std::function<void(std::string_view)> replyFunc;
|
||||
std::string invokerName;
|
||||
};
|
||||
// Register primary name
|
||||
commands_[primaryName] = cmd;
|
||||
uniqueCommands_.push_back({primaryName, cmd});
|
||||
|
||||
void startThreadPool();
|
||||
void processCommandQueue();
|
||||
void executeCommandAsync(CommandTask task);
|
||||
// Register aliases automatically from the class itself
|
||||
for (auto alias : cmd->getAliases()) {
|
||||
commands_[std::string(alias)] = cmd;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::jthread> workerThreads_;
|
||||
std::queue<CommandTask> commandQueue_;
|
||||
std::mutex queueMutex_;
|
||||
std::condition_variable queueCv_;
|
||||
std::atomic<bool> shutdown_{false};
|
||||
static constexpr size_t THREAD_POOL_SIZE =
|
||||
4; // Handle up to 4 concurrent commands
|
||||
/**
|
||||
* @brief Dispatches a command message to the appropriate handler
|
||||
* (ASYNC). Commands are executed in a thread pool, allowing
|
||||
* multiple users to use the bot simultaneously without blocking.
|
||||
* @param clientId The client ID who invoked the command.
|
||||
* @param message The full message (including prefix, e.g., "!play
|
||||
* song").
|
||||
* @param musicManager Weak pointer to the MusicManager.
|
||||
* @param replyFunc Function to call to send a reply.
|
||||
* @param invokerName Name of the invoking user.
|
||||
* @return true if a command was found and queued for execution,
|
||||
* false otherwise.
|
||||
*/
|
||||
[[nodiscard]] bool
|
||||
dispatch(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
|
||||
}; // namespace Echoion::Core
|
||||
/**
|
||||
* @brief Executes a command synchronously (for internal use).
|
||||
* Prefer using dispatch() for normal command handling.
|
||||
*/
|
||||
[[nodiscard]] bool
|
||||
dispatchSync(uint64_t clientId,
|
||||
std::string_view message,
|
||||
std::weak_ptr<MusicManager> musicManager,
|
||||
std::function<void(std::string_view)> replyFunc,
|
||||
std::string_view invokerName = "");
|
||||
|
||||
[[nodiscard]] bool hasCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::optional<CommandPtr>
|
||||
getCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
getAllCommands() const;
|
||||
|
||||
// Get commands visible to a specific client (for help)
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
getVisibleCommands(uint64_t clientId) const;
|
||||
|
||||
// Check if client can execute a command
|
||||
[[nodiscard]] bool canExecuteCommand(uint64_t clientId,
|
||||
const CommandPtr& cmd) const;
|
||||
|
||||
void setPrefix(std::string_view prefix);
|
||||
[[nodiscard]] std::string_view getPrefix() const { return prefix_; }
|
||||
|
||||
// Set permission check function
|
||||
void setPermissionCheckFunc(PermissionCheckFunc func);
|
||||
// Set server config for permission checks
|
||||
void setServerConfig(const Api::AppConfig& config);
|
||||
|
||||
private:
|
||||
|
||||
struct CommandEntry {
|
||||
std::string primaryName;
|
||||
CommandPtr instance;
|
||||
};
|
||||
|
||||
void registerBuiltinCommands();
|
||||
|
||||
// Internal Help Command (defined in .cpp to access registry)
|
||||
class HelpCommand;
|
||||
void registerHelpCommand();
|
||||
|
||||
std::string prefix_ = "!";
|
||||
|
||||
// Map for fast lookup: "play" -> PlayCommand
|
||||
std::map<std::string, CommandPtr, std::less<>> commands_;
|
||||
|
||||
// List for generating help: {"play", PlayCommand}
|
||||
std::vector<CommandEntry> uniqueCommands_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Permission checking
|
||||
PermissionCheckFunc permissionCheck_;
|
||||
std::optional<Api::AppConfig> serverConfig_;
|
||||
|
||||
// Async command execution
|
||||
struct CommandTask {
|
||||
uint64_t clientId;
|
||||
std::string message;
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
std::function<void(std::string_view)> replyFunc;
|
||||
std::string invokerName;
|
||||
};
|
||||
|
||||
void startThreadPool();
|
||||
void processCommandQueue();
|
||||
void executeCommandAsync(CommandTask task);
|
||||
|
||||
std::vector<std::jthread> workerThreads_;
|
||||
std::queue<CommandTask> commandQueue_;
|
||||
std::mutex queueMutex_;
|
||||
std::condition_variable queueCv_;
|
||||
std::atomic<bool> shutdown_{false};
|
||||
static constexpr size_t THREAD_POOL_SIZE =
|
||||
4; // Handle up to 4 concurrent commands
|
||||
|
||||
}; // namespace Echoion::Core
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,30 +1,132 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Configuration loader for JSON config files (internal to Core)
|
||||
class ConfigLoader {
|
||||
public:
|
||||
// Load configuration from JSON file
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig> loadFromFile(const std::filesystem::path& path);
|
||||
|
||||
// Save configuration to JSON file
|
||||
[[nodiscard]] static Api::Result<void> saveToFile(const std::filesystem::path& path, const Api::AppConfig& config);
|
||||
|
||||
// Get default configuration path
|
||||
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
||||
|
||||
// Create default configuration
|
||||
[[nodiscard]] static Api::AppConfig createDefaultConfig();
|
||||
// JSON structures for configuration (public for use by Core)
|
||||
struct BotConfigJson {
|
||||
std::string botName = "Echoion";
|
||||
std::string commandPrefix = "!";
|
||||
float defaultVolume = 0.5f;
|
||||
uint32_t maxQueueSize = 100;
|
||||
uint32_t trackTimeout = 30000;
|
||||
bool autoReconnect = true;
|
||||
uint32_t reconnectDelay = 5000;
|
||||
uint32_t maxReconnectAttempts = 5;
|
||||
std::string preferredQuality = "High";
|
||||
bool allowPlaylistImports = true;
|
||||
};
|
||||
|
||||
private:
|
||||
// Parse quality string to enum
|
||||
[[nodiscard]] static Api::AudioQuality parseQuality(const std::string& str);
|
||||
[[nodiscard]] static std::string qualityToString(Api::AudioQuality quality);
|
||||
};
|
||||
struct YouTubeConfigJson {
|
||||
std::optional<std::string> youtubeApiKey;
|
||||
std::optional<std::string> youtubeCookiesPath;
|
||||
std::optional<std::string> cookiesFromBrowser;
|
||||
uint32_t ytDlpMaxConcurrent = 4;
|
||||
bool ytDlpAsyncEnabled = true;
|
||||
bool enableUrlShortening = true;
|
||||
};
|
||||
|
||||
struct NetworkConfigJson {
|
||||
// Proxy settings (flat structure for backward compatibility)
|
||||
std::string proxyType = "HTTP";
|
||||
std::optional<std::string> proxyHost;
|
||||
std::optional<uint16_t> proxyPort;
|
||||
std::optional<std::string> proxyUsername;
|
||||
std::optional<std::string> proxyPassword;
|
||||
// RPC settings
|
||||
bool rpcEnabled = true;
|
||||
uint16_t rpcPort = 8765;
|
||||
std::string rpcBindAddress = "127.0.0.1";
|
||||
};
|
||||
|
||||
struct TeamSpeakConfigJson {
|
||||
std::string address = "localhost";
|
||||
uint16_t port = 9987;
|
||||
std::string serverPassword = "";
|
||||
std::string nickname = "EchoionBot";
|
||||
std::optional<std::string> defaultChannelId;
|
||||
std::optional<std::string> channelPassword;
|
||||
std::vector<uint64_t> adminGroups;
|
||||
std::vector<uint64_t> djGroups;
|
||||
std::vector<uint64_t> bannedGroups;
|
||||
};
|
||||
|
||||
struct SecurityConfigJson {
|
||||
bool requireAuthForAdmin = true;
|
||||
uint32_t maxLoginAttempts = 5;
|
||||
uint32_t lockoutDuration = 300000;
|
||||
uint32_t sessionTimeout = 3600000;
|
||||
bool enableAuditLog = true;
|
||||
std::optional<std::string> apiKey;
|
||||
bool allowCors = false;
|
||||
std::vector<std::string> corsOrigins;
|
||||
};
|
||||
|
||||
struct FeaturesConfigJson {
|
||||
bool enableHotReload = true;
|
||||
bool enableAutoReload = false;
|
||||
bool enableAutoUpdateCheck = true;
|
||||
bool autoStartOnSubscribe = true;
|
||||
bool pauseOnEmptySubscribers = true;
|
||||
bool resumeOnSubscriberReturn = true;
|
||||
std::string shuffleMode = "random";
|
||||
std::string repeatMode = "off";
|
||||
uint32_t maxHistorySize = 50;
|
||||
};
|
||||
|
||||
struct AdvancedConfigJson {
|
||||
uint32_t sampleRate = 192000;
|
||||
uint32_t channels = 2;
|
||||
uint32_t bufferSize = 7680;
|
||||
uint32_t commandThreadPoolSize = 4;
|
||||
uint32_t networkThreadPoolSize = 4;
|
||||
uint32_t decoderThreads = 2;
|
||||
bool cacheEnabled = true;
|
||||
std::string cacheMaxSize = "1GB";
|
||||
uint32_t cacheTTL = 86400;
|
||||
uint32_t tempCleanupInterval = 3600;
|
||||
};
|
||||
|
||||
struct AppConfigJson {
|
||||
BotConfigJson bot;
|
||||
YouTubeConfigJson youtube;
|
||||
NetworkConfigJson network;
|
||||
TeamSpeakConfigJson teamspeak;
|
||||
SecurityConfigJson security;
|
||||
FeaturesConfigJson features;
|
||||
AdvancedConfigJson advanced;
|
||||
};
|
||||
|
||||
// Configuration loader for JSON config files (internal to Core)
|
||||
class ConfigLoader
|
||||
{
|
||||
public:
|
||||
|
||||
// Load configuration from JSON file
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromFile(const std::filesystem::path& path);
|
||||
|
||||
// Save configuration to JSON file
|
||||
[[nodiscard]] static Api::Result<void>
|
||||
saveToFile(const std::filesystem::path& path,
|
||||
const Api::AppConfig& config);
|
||||
|
||||
// Get default configuration path
|
||||
[[nodiscard]] static std::filesystem::path getDefaultConfigPath();
|
||||
|
||||
// Create default configuration
|
||||
[[nodiscard]] static Api::AppConfig createDefaultConfig();
|
||||
|
||||
// Parse quality string to enum
|
||||
[[nodiscard]] static Api::AudioQuality
|
||||
parseQuality(const std::string& str);
|
||||
[[nodiscard]] static std::string
|
||||
qualityToString(Api::AudioQuality quality);
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+155
-85
@@ -1,111 +1,181 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <echoion/api/Database.hpp>
|
||||
#include "MusicManager.hpp"
|
||||
#include "CommandManager.hpp"
|
||||
#include "ConfigLoader.hpp"
|
||||
#include "MusicManager.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "RpcServer.hpp"
|
||||
#include "ConfigLoader.hpp"
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Database.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <StateBlob.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Main Core implementation of ICoreInterface
|
||||
class Core : public Api::ICoreInterface {
|
||||
public:
|
||||
Core();
|
||||
~Core() override;
|
||||
// Main Core implementation of ICoreInterface
|
||||
class Core : public Api::ICoreInterface
|
||||
{
|
||||
public:
|
||||
|
||||
// ICoreInterface implementation
|
||||
Api::Result<void> initialize(const std::filesystem::path& configPath) override;
|
||||
Api::Result<void> shutdown() override;
|
||||
[[nodiscard]] bool isInitialized() const noexcept override;
|
||||
Core();
|
||||
~Core() override;
|
||||
|
||||
// Playback control
|
||||
Api::Result<void> play(const Api::TrackInfo& track) override;
|
||||
Api::Result<void> pause() override;
|
||||
Api::Result<void> resume() override;
|
||||
Api::Result<void> stop() override;
|
||||
Api::Result<void> skip(uint32_t count) override;
|
||||
Api::Result<void> seek(std::chrono::milliseconds position) override;
|
||||
Api::Result<void> setVolume(float volume) override;
|
||||
// ICoreInterface - Lifecycle
|
||||
Api::Result<void>
|
||||
initialize(const std::filesystem::path& configPath) override;
|
||||
Api::Result<void> shutdown() override;
|
||||
[[nodiscard]] bool isInitialized() const noexcept override;
|
||||
|
||||
// Queue management
|
||||
Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId) override;
|
||||
Api::Result<void> removeFromQueue(uint64_t queueId) override;
|
||||
Api::Result<void> clearQueue() override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const override;
|
||||
Api::Result<void> moveInQueue(uint64_t queueId, uint32_t newPosition) override;
|
||||
// ICoreInterface - Playback control (decoupled)
|
||||
Api::Result<void> play(const std::string& trackId) override;
|
||||
Api::Result<void> pause() override;
|
||||
Api::Result<void> resume() override;
|
||||
Api::Result<void> stop() override;
|
||||
Api::Result<void> skip(uint32_t count) override;
|
||||
Api::Result<void> seek(std::chrono::milliseconds position) override;
|
||||
Api::Result<void> setVolume(float volume) override;
|
||||
|
||||
// Track info
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>> getCurrentTrack() const override;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const override;
|
||||
// ICoreInterface - Queue management (decoupled)
|
||||
Api::Result<uint64_t> queueTrack(const std::string& trackId,
|
||||
uint64_t clientId) override;
|
||||
Api::Result<void> removeFromQueue(uint64_t queueId) override;
|
||||
Api::Result<void> clearQueue() override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackSummary>>
|
||||
getQueueSummaries() const override;
|
||||
Api::Result<void> moveInQueue(uint64_t queueId,
|
||||
uint32_t newPosition) override;
|
||||
|
||||
// Playlist
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistId, uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>> getPlaylists() const override;
|
||||
// ICoreInterface - Track info (decoupled)
|
||||
[[nodiscard]] Api::Result<std::optional<Api::TrackSummary>>
|
||||
getCurrentTrackSummary() const override;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackSummary>
|
||||
getPlaybackSummary() const override;
|
||||
|
||||
// Configuration
|
||||
Api::Result<void> updateConfig(const Api::AppConfig& config) override;
|
||||
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const override;
|
||||
// Reload config from disk (stored path from initialize)
|
||||
Api::Result<void> reloadConfig();
|
||||
// ICoreInterface - Playlist (decoupled)
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistId,
|
||||
uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::vector<std::string>>
|
||||
getPlaylistIds() const override;
|
||||
|
||||
// Hot reload
|
||||
Api::Result<Api::HotReloadState> prepareForHotReload() override;
|
||||
Api::Result<void> restoreAfterHotReload(const Api::HotReloadState& state) override;
|
||||
// ICoreInterface - Configuration (decoupled)
|
||||
Api::Result<void>
|
||||
updateConfigJson(const std::string& configJson) override;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getConfigJson() const override;
|
||||
|
||||
// Event handling
|
||||
void registerEventCallback(const Api::EventCallback& callback) override;
|
||||
void unregisterEventCallback(const Api::EventCallback& callback) override;
|
||||
// ICoreInterface - Hot reload (decoupled)
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
prepareForHotReload() override;
|
||||
Api::Result<void>
|
||||
restoreAfterHotReload(const std::string& state) override;
|
||||
|
||||
// Plugin event processing
|
||||
Api::Result<void> onPluginEvent(const Api::PluginEvent& event) override;
|
||||
// ICoreInterface - Decoupled state management
|
||||
[[nodiscard]] Api::StateBlob saveState() override;
|
||||
Api::Result<void>
|
||||
restoreState(const Api::StateBlob& state) override;
|
||||
[[nodiscard]] uint32_t getStateFormatVersion() const override;
|
||||
[[nodiscard]] bool
|
||||
canRestoreStateVersion(uint32_t version) const override;
|
||||
|
||||
// Status
|
||||
[[nodiscard]] std::string getVersion() const override;
|
||||
[[nodiscard]] std::chrono::system_clock::time_point getUptime() const override;
|
||||
// ICoreInterface - Event handling
|
||||
void registerEventCallback(
|
||||
const Api::EventCallback& callback) override;
|
||||
void unregisterEventCallback(
|
||||
const Api::EventCallback& callback) override;
|
||||
|
||||
// Additional methods for plugin integration
|
||||
void setPluginInterface(Api::PluginInterfacePtr pluginInterface) override;
|
||||
void setAudioDataCallback(const MusicManager::AudioDataCallback& callback);
|
||||
void triggerAutoConnect() override;
|
||||
// ICoreInterface - Plugin event processing
|
||||
Api::Result<void>
|
||||
onPluginEvent(const Api::PluginEvent& event) override;
|
||||
|
||||
private:
|
||||
void onMusicEvent(const Api::PluginEvent& event);
|
||||
void broadcastEvent(const Api::PluginEvent& event);
|
||||
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
|
||||
void updateWhisperList();
|
||||
void setupRpcHandlers();
|
||||
// ICoreInterface - Status
|
||||
[[nodiscard]] std::string getVersion() const override;
|
||||
[[nodiscard]] std::chrono::system_clock::time_point
|
||||
getUptime() const override;
|
||||
|
||||
// Components
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
// ICoreInterface - Plugin interface
|
||||
void setPluginInterface(
|
||||
Api::PluginInterfacePtr pluginInterface) override;
|
||||
void triggerAutoConnect() override;
|
||||
|
||||
// State
|
||||
Api::AppConfig config_; // Config loaded internally
|
||||
std::filesystem::path configPath_; // Path to config file for reload
|
||||
std::chrono::system_clock::time_point startTime_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
// ICoreInterface - Advanced (for internal Core-to-Core use)
|
||||
[[nodiscard]] Api::Result<Api::OpaqueHandle<Api::TrackInfo>>
|
||||
getCurrentTrackHandle() const override;
|
||||
[[nodiscard]] Api::Result<
|
||||
std::vector<Api::OpaqueHandle<Api::QueueEntry>>>
|
||||
getQueueHandles() const override;
|
||||
[[nodiscard]] Api::Result<Api::AppConfigHandle>
|
||||
getConfigHandle() const override;
|
||||
Api::Result<void>
|
||||
updateConfigFromHandle(Api::AppConfigHandle config) override;
|
||||
|
||||
// Event callbacks
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
// Additional methods for internal use (not in interface)
|
||||
void setAudioDataCallback(
|
||||
const MusicManager::AudioDataCallback& callback);
|
||||
Api::Result<void> reloadConfig();
|
||||
|
||||
// Admin tracking
|
||||
std::vector<uint64_t> adminClients_;
|
||||
mutable std::mutex adminMutex_;
|
||||
|
||||
// Database for persistence
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
|
||||
// RPC server for Desktop/API clients
|
||||
std::shared_ptr<RpcServer> rpcServer_;
|
||||
};
|
||||
// Internal implementations using full types
|
||||
Api::Result<void> playTrack(const Api::TrackInfo& track);
|
||||
Api::Result<uint64_t> queueTrackFull(const Api::TrackInfo& track,
|
||||
uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
|
||||
getQueue() const;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState>
|
||||
getPlaybackState() const;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
Api::Result<void> updateConfig(const Api::AppConfig& config);
|
||||
[[nodiscard]] Api::Result<Api::AppConfig> getConfig() const;
|
||||
[[nodiscard]] Api::Result<Api::HotReloadState>
|
||||
prepareForHotReloadFull();
|
||||
Api::Result<void>
|
||||
restoreAfterHotReloadFull(const Api::HotReloadState& state);
|
||||
|
||||
// Generate RPC tokens for existing subscribers
|
||||
void generateRpcTokensForSubscribers();
|
||||
|
||||
private:
|
||||
|
||||
void onMusicEvent(const Api::PluginEvent& event);
|
||||
void broadcastEvent(const Api::PluginEvent& event);
|
||||
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
|
||||
void updateWhisperList();
|
||||
void setupRpcHandlers();
|
||||
void setupEventBusSubscriptions() const noexcept;
|
||||
|
||||
// Components
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
|
||||
// State
|
||||
Api::AppConfig config_;
|
||||
std::filesystem::path configPath_;
|
||||
std::chrono::system_clock::time_point startTime_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
|
||||
// Event callbacks
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
|
||||
// Admin tracking
|
||||
std::vector<uint64_t> adminClients_;
|
||||
mutable std::mutex adminMutex_;
|
||||
|
||||
// Database for persistence
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
|
||||
// RPC server for Desktop/API clients
|
||||
std::shared_ptr<RpcServer> rpcServer_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,79 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
#include <condition_variable>
|
||||
#include <LoggerInterface.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <array>
|
||||
#include <map>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Void::Logging
|
||||
{
|
||||
class MultiLogger;
|
||||
} // namespace Void::Logging
|
||||
|
||||
// Log file info for rotation
|
||||
struct LogFileInfo {
|
||||
std::filesystem::path path;
|
||||
std::ofstream stream;
|
||||
uint64_t size = 0;
|
||||
std::chrono::system_clock::time_point createdAt;
|
||||
};
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class Logger : public Api::ILogger {
|
||||
public:
|
||||
explicit Logger(std::string_view logDir = "logs", std::string_view baseName = "echoion");
|
||||
~Logger() override;
|
||||
// ILogger implementation backed by the Void::Logging framework.
|
||||
//
|
||||
// Output is produced by a Void MultiLogger fanning out to:
|
||||
// * a ConsoleLogger (stdout),
|
||||
// * a SplitFileLogger writing per-level files (<dir>/<level>.log) plus a
|
||||
// combined <dir>/all.log, each rolling independently by size, and
|
||||
// * a CallbackLogger bridging back to the registered ILogger callbacks.
|
||||
// The ILogger surface (levels, callbacks, console/file toggles, rotation
|
||||
// knobs) is preserved so existing call sites and the ECHOION_LOG_* macros
|
||||
// keep working unchanged.
|
||||
class Logger : public Api::ILogger
|
||||
{
|
||||
public:
|
||||
|
||||
void log(Api::LogLevel level, std::string_view message,
|
||||
std::source_location location) override;
|
||||
void setMinLevel(Api::LogLevel level) override;
|
||||
[[nodiscard]] Api::LogLevel getMinLevel() const override;
|
||||
void registerCallback(const LogCallback& callback) override;
|
||||
void unregisterCallback(const LogCallback& callback) override;
|
||||
explicit Logger(std::string_view logDir = "logs",
|
||||
std::string_view baseName = "echoion");
|
||||
~Logger() override;
|
||||
|
||||
void flush();
|
||||
void setConsoleOutput(bool enabled);
|
||||
void setFileOutput(bool enabled);
|
||||
void setMaxFileSize(uint64_t bytes);
|
||||
void setMaxFiles(uint32_t count);
|
||||
void log(Api::LogLevel level, std::string_view message,
|
||||
std::source_location location) override;
|
||||
void setMinLevel(Api::LogLevel level) override;
|
||||
[[nodiscard]] Api::LogLevel getMinLevel() const override;
|
||||
void registerCallback(const LogCallback& callback) override;
|
||||
void unregisterCallback(const LogCallback& callback) override;
|
||||
|
||||
private:
|
||||
void logWorker();
|
||||
void rotateIfNeeded(Api::LogLevel level);
|
||||
void openLogFiles();
|
||||
void cleanupOldLogs();
|
||||
void moveToHistory(const std::filesystem::path& filePath);
|
||||
void ensureHistoryDirExists();
|
||||
[[nodiscard]] std::string formatLogEntry(const Api::LogEntry& entry);
|
||||
[[nodiscard]] std::string levelToString(Api::LogLevel level);
|
||||
[[nodiscard]] std::filesystem::path generateLogFilePath(Api::LogLevel level);
|
||||
[[nodiscard]] std::string formatTimestamp(const std::chrono::system_clock::time_point& tp);
|
||||
void writeToFile(Api::LogLevel level, const std::string& formattedEntry);
|
||||
void flush();
|
||||
void setConsoleOutput(bool enabled);
|
||||
void setFileOutput(bool enabled);
|
||||
void setMaxFileSize(uint64_t bytes);
|
||||
void setMaxFiles(uint32_t count);
|
||||
|
||||
std::filesystem::path logDir_;
|
||||
std::string baseName_;
|
||||
|
||||
// Separate files for each level + combined file
|
||||
std::map<Api::LogLevel, LogFileInfo> levelFiles_;
|
||||
LogFileInfo combinedFile_;
|
||||
|
||||
std::mutex fileMutex_;
|
||||
std::mutex queueMutex_;
|
||||
std::queue<Api::LogEntry> logQueue_;
|
||||
std::thread workerThread_;
|
||||
std::condition_variable cv_;
|
||||
std::atomic<bool> running_{true};
|
||||
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
|
||||
std::atomic<bool> consoleOutput_{true};
|
||||
std::atomic<bool> fileOutput_{true};
|
||||
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB per file
|
||||
std::atomic<uint32_t> maxFiles_{5};
|
||||
std::vector<LogCallback> callbacks_;
|
||||
std::mutex callbackMutex_;
|
||||
};
|
||||
private:
|
||||
|
||||
// (Re)assemble the Void sink tree from the current toggles/limits.
|
||||
void rebuildSinks();
|
||||
// Fan a Void log entry out to the registered ILogger callbacks.
|
||||
void dispatchToCallbacks(Api::LogLevel level,
|
||||
const std::string& message,
|
||||
const std::string& file, uint32_t line,
|
||||
const std::string& function);
|
||||
|
||||
std::filesystem::path logDir_;
|
||||
std::string baseName_;
|
||||
|
||||
std::shared_ptr<Void::Logging::MultiLogger> sink_;
|
||||
std::mutex sinkMutex_;
|
||||
|
||||
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
|
||||
std::atomic<bool> consoleOutput_{true};
|
||||
std::atomic<bool> fileOutput_{true};
|
||||
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB
|
||||
std::atomic<uint32_t> maxFiles_{5};
|
||||
|
||||
std::vector<LogCallback> callbacks_;
|
||||
std::mutex callbackMutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,205 +1,271 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include "YouTubeClient.hpp"
|
||||
#include "AudioDecoder.hpp"
|
||||
#include "Database.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include "YouTubeClient.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include <atomic>
|
||||
#include <future>
|
||||
#include <set>
|
||||
#include <shared_mutex>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <filesystem>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager {
|
||||
public:
|
||||
MusicManager();
|
||||
~MusicManager();
|
||||
class MusicManager
|
||||
{
|
||||
public:
|
||||
|
||||
Api::Result<void> initialize(const Api::BotConfig& config,
|
||||
std::shared_ptr<NetworkClient> networkClient,
|
||||
std::shared_ptr<Api::Database> database = nullptr);
|
||||
void shutdown();
|
||||
MusicManager();
|
||||
~MusicManager();
|
||||
|
||||
[[nodiscard]] Api::Result<std::string> play(const std::string& query, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> pause();
|
||||
[[nodiscard]] Api::Result<void> resume();
|
||||
[[nodiscard]] Api::Result<void> stop();
|
||||
[[nodiscard]] Api::Result<void> skip(uint32_t count = 1);
|
||||
[[nodiscard]] Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
[[nodiscard]] Api::Result<void> setVolume(float volume);
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<NetworkClient> networkClient,
|
||||
std::shared_ptr<Api::Database> database = nullptr);
|
||||
void shutdown();
|
||||
|
||||
[[nodiscard]] Api::Result<uint64_t> queueTrack(const Api::TrackInfo& track, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
|
||||
[[nodiscard]] Api::Result<void> clearQueue();
|
||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>> getQueue() const;
|
||||
[[nodiscard]] Api::Result<void> moveInQueue(uint32_t from, uint32_t to);
|
||||
[[nodiscard]] Api::Result<bool> toggleShuffle();
|
||||
[[nodiscard]] Api::Result<bool> toggleRepeat();
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
play(const std::string& query, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> pause();
|
||||
[[nodiscard]] Api::Result<void> resume();
|
||||
[[nodiscard]] Api::Result<void> stop();
|
||||
[[nodiscard]] Api::Result<void> skip(uint32_t count = 1);
|
||||
[[nodiscard]] Api::Result<void>
|
||||
seek(std::chrono::milliseconds position);
|
||||
[[nodiscard]] Api::Result<void> setVolume(float volume);
|
||||
|
||||
// Load playlist asynchronously - returns immediately, processes in background
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl, uint64_t clientId);
|
||||
[[nodiscard]] bool isPlaylistLoading() const { return playlistLoading_.load(); }
|
||||
[[nodiscard]] size_t getPlaylistLoadProgress() const { return playlistLoadedCount_.load(); }
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
[[nodiscard]] Api::Result<uint64_t>
|
||||
queueTrack(const Api::TrackInfo& track, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
|
||||
[[nodiscard]] Api::Result<void> clearQueue();
|
||||
[[nodiscard]] Api::Result<std::vector<Api::QueueEntry>>
|
||||
getQueue() const;
|
||||
[[nodiscard]] Api::Result<void> moveInQueue(uint32_t from,
|
||||
uint32_t to);
|
||||
[[nodiscard]] Api::Result<bool> toggleShuffle();
|
||||
[[nodiscard]] Api::Result<bool> toggleRepeat();
|
||||
[[nodiscard]] Api::Result<void> shuffleQueue();
|
||||
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState> getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
// Load playlist asynchronously - returns immediately, processes in
|
||||
// background
|
||||
Api::Result<void> loadPlaylist(const std::string& playlistIdOrUrl,
|
||||
uint64_t clientId);
|
||||
[[nodiscard]] bool isPlaylistLoading() const
|
||||
{
|
||||
return playlistLoading_.load();
|
||||
}
|
||||
[[nodiscard]] size_t getPlaylistLoadProgress() const
|
||||
{
|
||||
return playlistLoadedCount_.load();
|
||||
}
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
|
||||
[[nodiscard]] Api::Result<Api::SearchResult> search(const std::string& query);
|
||||
|
||||
// Search result selection (client-specific)
|
||||
void storePendingSearch(uint64_t clientId, const std::vector<Api::TrackInfo>& results);
|
||||
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>> getPendingSearch(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string> selectSearchResult(
|
||||
uint64_t clientId, uint32_t index, const std::string& invokerName);
|
||||
[[nodiscard]] Api::Result<std::optional<Api::QueueEntry>>
|
||||
getCurrentTrack() const;
|
||||
[[nodiscard]] Api::Result<Api::PlaybackState>
|
||||
getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(const std::string& query);
|
||||
|
||||
// Subscription management (by client ID - internally uses UID for
|
||||
// persistence)
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string> unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients()
|
||||
const; // Returns only ONLINE subscribers' client IDs
|
||||
[[nodiscard]] bool hasSubscribers()
|
||||
const; // Returns true if any subscribers exist (online or offline)
|
||||
[[nodiscard]] bool hasOnlineSubscribers()
|
||||
const; // Returns true only if there are online subscribers
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
// Search result selection (client-specific)
|
||||
void storePendingSearch(uint64_t clientId,
|
||||
const std::vector<Api::TrackInfo>& results);
|
||||
[[nodiscard]] std::optional<std::vector<Api::TrackInfo>>
|
||||
getPendingSearch(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
selectSearchResult(uint64_t clientId,
|
||||
uint32_t index,
|
||||
const std::string& invokerName);
|
||||
|
||||
// Get UIDs of subscribers who are currently online
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
|
||||
// Called when a client connects to the server
|
||||
void onClientConnected(uint64_t clientId);
|
||||
// Subscription management (by client ID - internally uses UID for
|
||||
// persistence)
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients()
|
||||
const; // Returns only ONLINE subscribers' client IDs
|
||||
[[nodiscard]] bool
|
||||
hasSubscribers() const; // Returns true if any subscribers exist
|
||||
// (online or offline)
|
||||
[[nodiscard]] bool hasOnlineSubscribers()
|
||||
const; // Returns true only if there are online subscribers
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void>
|
||||
restoreFromHotReload(const Api::HotReloadState& state);
|
||||
// Get UIDs of subscribers who are currently online
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
|
||||
using AudioDataCallback = std::function<void(const std::span<const short>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
// Called when a client connects to the server
|
||||
void onClientConnected(uint64_t clientId);
|
||||
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(const SubscriptionChangeCallback& callback);
|
||||
[[nodiscard]] Api::HotReloadState getStateForHotReload() const;
|
||||
[[nodiscard]] Api::Result<void>
|
||||
restoreFromHotReload(const Api::HotReloadState& state);
|
||||
|
||||
using PlaybackStartCallback = std::function<void()>;
|
||||
void setPlaybackStartCallback(const PlaybackStartCallback& callback);
|
||||
using AudioDataCallback =
|
||||
std::function<void(const std::span<const short>)>;
|
||||
void setAudioDataCallback(const AudioDataCallback& callback);
|
||||
|
||||
// Callback to resolve client info (UID and nickname) from client ID
|
||||
using ClientInfoCallback =
|
||||
std::function<std::optional<std::pair<std::string, std::string>>(
|
||||
uint64_t clientId)>;
|
||||
void setClientInfoCallback(const ClientInfoCallback& callback);
|
||||
using SubscriptionChangeCallback = std::function<void()>;
|
||||
void setSubscriptionChangeCallback(
|
||||
const SubscriptionChangeCallback& callback);
|
||||
|
||||
// Callback to resolve client ID from UID
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
void setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
||||
using PlaybackStartCallback = std::function<void()>;
|
||||
void
|
||||
setPlaybackStartCallback(const PlaybackStartCallback& callback);
|
||||
|
||||
// Callback to resolve nickname from client ID
|
||||
using NicknameCallback =
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
// Callback to resolve client info (UID and nickname) from client ID
|
||||
using ClientInfoCallback = std::function<std::optional<
|
||||
std::pair<std::string, std::string>>(uint64_t clientId)>;
|
||||
void setClientInfoCallback(const ClientInfoCallback& callback);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
// Callback to resolve client ID from UID
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
void
|
||||
setUidToClientIdCallback(const UidToClientIdCallback& callback);
|
||||
|
||||
private:
|
||||
void playbackThread();
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> resolveQuery(const std::string& query);
|
||||
[[nodiscard]] Api::Result<std::string> getStreamUrl(const Api::TrackInfo& track);
|
||||
void onTrackFinished();
|
||||
[[nodiscard]] Api::TrackInfo getNextTrack();
|
||||
void shuffleQueue();
|
||||
|
||||
// Download audio through proxy for playback
|
||||
[[nodiscard]] Api::Result<std::string> downloadAudioForPlayback(const std::string& url);
|
||||
void cleanupTempFile(const std::string& filepath);
|
||||
|
||||
// Prefetch next track for seamless transitions
|
||||
void prefetchNextTrack();
|
||||
[[nodiscard]] bool shouldPrefetch() const;
|
||||
static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15); // Start prefetch 15s before end
|
||||
|
||||
// Temporary file tracking
|
||||
std::set<std::string> tempFiles_;
|
||||
mutable std::mutex tempFilesMutex_;
|
||||
|
||||
// Prefetch state for seamless playback
|
||||
struct PrefetchState {
|
||||
std::future<Api::Result<std::string>> streamUrlFuture;
|
||||
std::atomic<bool> isPrefetching{false};
|
||||
std::atomic<bool> hasPrefetched{false};
|
||||
std::optional<std::string> prefetchedUrl;
|
||||
} prefetchState_;
|
||||
|
||||
// Async playlist loading state
|
||||
std::thread playlistLoadThread_;
|
||||
std::atomic<bool> playlistLoading_{false};
|
||||
std::atomic<size_t> playlistLoadedCount_{0};
|
||||
std::atomic<size_t> playlistTotalCount_{0};
|
||||
// Callback to resolve nickname from client ID
|
||||
using NicknameCallback =
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
std::unique_ptr<AudioDecoder> audioDecoder_;
|
||||
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
Api::BotConfig config_;
|
||||
std::vector<Api::QueueEntry> queue_;
|
||||
std::optional<Api::QueueEntry> currentTrack_;
|
||||
bool isPlaying_ = false;
|
||||
bool isPaused_ = false;
|
||||
bool wasPausedForNoSubscribers_ = false; // Track if we auto-paused
|
||||
|
||||
// Accurate playback position tracking
|
||||
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
||||
std::chrono::steady_clock::time_point playbackStartTime_; // When current segment started
|
||||
std::chrono::milliseconds playbackBasePosition_{0}; // Position at start of current segment
|
||||
float volume_ = 0.5f;
|
||||
bool shuffle_ = false;
|
||||
bool repeat_ = false;
|
||||
uint64_t nextQueueId_ = 1;
|
||||
private:
|
||||
|
||||
std::jthread playbackThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::atomic<bool> playbackThreadRunning_{false}; // True while thread is actively running
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>> pendingSearches_;
|
||||
mutable std::mutex pendingSearchMutex_;
|
||||
void playbackThread();
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveQuery(const std::string& query);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrl(const Api::TrackInfo& track);
|
||||
void onTrackFinished();
|
||||
[[nodiscard]] Api::TrackInfo getNextTrack();
|
||||
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
// Generate silence/sine wave to keep audio stream alive during
|
||||
// transitions
|
||||
void generateTransitionAudio(std::chrono::milliseconds duration);
|
||||
void sendSilenceChunk();
|
||||
static constexpr auto TRANSITION_SILENCE_DURATION =
|
||||
std::chrono::milliseconds(100);
|
||||
static constexpr auto TRANSITION_FADE_DURATION =
|
||||
std::chrono::milliseconds(50);
|
||||
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
||||
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE = 7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
};
|
||||
// Download audio through proxy for playback
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
downloadAudioForPlayback(const std::string& url);
|
||||
void cleanupTempFile(const std::string& filepath);
|
||||
|
||||
// Prefetch next track for seamless transitions
|
||||
void prefetchNextTrack();
|
||||
[[nodiscard]] bool shouldPrefetch() const;
|
||||
static constexpr auto PREFETCH_THRESHOLD =
|
||||
std::chrono::seconds(15); // Start prefetch 15s before end
|
||||
|
||||
// Temporary file tracking
|
||||
std::set<std::string> tempFiles_;
|
||||
mutable std::shared_mutex tempFilesMutex_;
|
||||
|
||||
// Prefetch state for seamless playback
|
||||
struct PrefetchState {
|
||||
std::future<Api::Result<std::string>> streamUrlFuture;
|
||||
std::atomic<bool> isPrefetching{false};
|
||||
std::atomic<bool> hasPrefetched{false};
|
||||
std::optional<std::string> prefetchedUrl;
|
||||
} prefetchState_;
|
||||
|
||||
// Async playlist loading state
|
||||
std::thread playlistLoadThread_;
|
||||
std::atomic<bool> playlistLoading_{false};
|
||||
std::atomic<size_t> playlistLoadedCount_{0};
|
||||
std::atomic<size_t> playlistTotalCount_{0};
|
||||
|
||||
// Auto-start thread for playlist (must be joined, not detached)
|
||||
std::thread playlistAutoStartThread_;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
std::unique_ptr<AudioDecoder> audioDecoder_;
|
||||
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
||||
|
||||
Api::BotConfig config_;
|
||||
std::vector<Api::QueueEntry> queue_;
|
||||
std::optional<Api::QueueEntry> currentTrack_;
|
||||
std::atomic<bool> isPlaying_{false};
|
||||
std::atomic<bool> isPaused_{false};
|
||||
std::atomic<bool> wasPausedForNoSubscribers_{
|
||||
false}; // Track if we auto-paused
|
||||
|
||||
// Accurate playback position tracking
|
||||
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
||||
std::chrono::steady_clock::time_point
|
||||
playbackStartTime_; // When current segment started
|
||||
std::chrono::milliseconds playbackBasePosition_{
|
||||
0}; // Position at start of current segment
|
||||
std::atomic<float> volume_{0.5f};
|
||||
std::atomic<bool> shuffle_{false};
|
||||
std::atomic<bool> repeat_{false};
|
||||
uint64_t nextQueueId_ = 1;
|
||||
|
||||
// Shuffle state - maintains shuffled order of queue indices
|
||||
std::vector<size_t> shuffledIndices_;
|
||||
size_t shuffleIndex_ = 0;
|
||||
void rebuildShuffledIndices();
|
||||
void reshuffleRemaining();
|
||||
|
||||
std::jthread playbackThread_;
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::condition_variable_any cv_;
|
||||
std::atomic<bool> playbackThreadRunning_{
|
||||
false}; // True while thread is actively running
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
|
||||
pendingSearches_;
|
||||
mutable std::mutex pendingSearchMutex_;
|
||||
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
|
||||
// Position tracking for periodic event updates
|
||||
std::chrono::steady_clock::time_point lastPositionUpdate_{};
|
||||
static constexpr auto POSITION_UPDATE_INTERVAL =
|
||||
std::chrono::seconds(1);
|
||||
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
||||
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE =
|
||||
7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,202 +1,238 @@
|
||||
#pragma once
|
||||
|
||||
#include "boost/asio/ssl/context.hpp"
|
||||
#include <echoion/api.hpp>
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <future>
|
||||
#include <queue>
|
||||
#include <NetworkInterface.hpp>
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
|
||||
// Boost.Beast includes needed for template function
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Forward declaration for URL parsing
|
||||
struct UrlComponents;
|
||||
|
||||
class NetworkClient : public Api::INetworkClient
|
||||
{
|
||||
public:
|
||||
|
||||
NetworkClient();
|
||||
~NetworkClient() override;
|
||||
|
||||
namespace Echoion::Core {
|
||||
// Initialize with optional proxy
|
||||
Api::Result<void> initialize(
|
||||
const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
|
||||
void shutdown();
|
||||
|
||||
// Forward declaration for URL parsing
|
||||
struct UrlComponents;
|
||||
// Synchronous requests
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||
get(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||
post(std::string_view url, std::string_view body,
|
||||
const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||
request(const Api::HttpRequest& req);
|
||||
|
||||
class NetworkClient : public Api::INetworkClient {
|
||||
public:
|
||||
NetworkClient();
|
||||
~NetworkClient() override;
|
||||
// Asynchronous requests
|
||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>>
|
||||
getAsync(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>>
|
||||
postAsync(std::string_view url, std::string_view body,
|
||||
const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>>
|
||||
requestAsync(const Api::HttpRequest& req);
|
||||
|
||||
// Initialize with optional proxy
|
||||
Api::Result<void> initialize(const std::optional<Api::ProxyConfig>& proxy = std::nullopt);
|
||||
void shutdown();
|
||||
// Concurrent batch requests
|
||||
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>>
|
||||
requestBatch(const std::vector<Api::HttpRequest>& requests);
|
||||
|
||||
// Synchronous requests
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse> get(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse> post(std::string_view url,
|
||||
std::string_view body, const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse> request(const Api::HttpRequest& req);
|
||||
// JSON helpers using Void::Json reflection
|
||||
template <typename T>
|
||||
[[nodiscard]] Api::Result<T>
|
||||
getJson(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers = {})
|
||||
{
|
||||
auto response = get(url, headers);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
return parseJson<T>(response->bodyAsString());
|
||||
}
|
||||
|
||||
// Asynchronous requests
|
||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> getAsync(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> postAsync(std::string_view url,
|
||||
std::string_view body, const std::vector<Api::HttpHeader>& headers = {});
|
||||
[[nodiscard]] std::future<Api::Result<Api::HttpResponse>> requestAsync(const Api::HttpRequest& req);
|
||||
template <typename T, typename Body>
|
||||
[[nodiscard]] Api::Result<T>
|
||||
postJson(std::string_view url, const Body& body,
|
||||
const std::vector<Api::HttpHeader>& headers = {})
|
||||
{
|
||||
std::string jsonBody =
|
||||
Void::Json::serialize(Void::Json::to_json(body));
|
||||
auto response = post(url, jsonBody, headers);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
return parseJson<T>(response->bodyAsString());
|
||||
}
|
||||
|
||||
// Concurrent batch requests
|
||||
[[nodiscard]] std::vector<Api::Result<Api::HttpResponse>> requestBatch(
|
||||
const std::vector<Api::HttpRequest>& requests);
|
||||
private:
|
||||
|
||||
// JSON helpers using glaze
|
||||
template<typename T>
|
||||
[[nodiscard]] Api::Result<T> getJson(std::string_view url,
|
||||
const std::vector<Api::HttpHeader>& headers = {}) {
|
||||
auto response = get(url, headers);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
|
||||
T result;
|
||||
auto ec = glz::read_json(result, response->bodyAsString());
|
||||
if (ec) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString()))));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// Parse a response body into a reflectable type T via Void::Json.
|
||||
template <typename T>
|
||||
[[nodiscard]] static Api::Result<T>
|
||||
parseJson(const std::string& body)
|
||||
{
|
||||
auto parsed = Void::Json::parse(body);
|
||||
if (!parsed) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("JSON parse error ({}:{}): {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message)));
|
||||
}
|
||||
auto value = Void::Json::from_json<T>(*parsed);
|
||||
if (!value) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("JSON decode error: field '{}': {}",
|
||||
value.error().field, value.error().message)));
|
||||
}
|
||||
return std::move(*value);
|
||||
}
|
||||
|
||||
template<typename T, typename Body>
|
||||
[[nodiscard]] Api::Result<T> postJson(std::string_view url, const Body& body,
|
||||
const std::vector<Api::HttpHeader>& headers = {}) {
|
||||
std::string jsonBody = glz::write_json(body);
|
||||
auto response = post(url, jsonBody, headers);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
|
||||
T result;
|
||||
auto ec = glz::read_json(result, response->bodyAsString());
|
||||
if (ec) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("JSON parse error: {}", glz::format_error(ec, response->bodyAsString()))));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public:
|
||||
|
||||
// Proxy configuration
|
||||
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
|
||||
void clearProxy();
|
||||
// Proxy configuration
|
||||
void setProxy(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxy() const;
|
||||
void clearProxy();
|
||||
|
||||
// Retry configuration
|
||||
void setRetryConfig(const Api::RetryConfig& config);
|
||||
[[nodiscard]] Api::RetryConfig getRetryConfig() const;
|
||||
// Retry configuration
|
||||
void setRetryConfig(const Api::RetryConfig& config);
|
||||
[[nodiscard]] Api::RetryConfig getRetryConfig() const;
|
||||
|
||||
private:
|
||||
// Request execution
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse> executeWithRetry(const Api::HttpRequest& req);
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse> executeRequest(const Api::HttpRequest& req);
|
||||
|
||||
// Proxy and direct execution methods
|
||||
[[nodiscard]] Api::HttpResponse executeWithProxy(
|
||||
boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse executeWithHttpProxy(
|
||||
boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse executeWithSocks5Proxy(
|
||||
boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse executeDirect(
|
||||
boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
// HTTP request methods
|
||||
// Note: sendHttpsRequest is a template, implemented in header below
|
||||
template<typename Stream>
|
||||
[[nodiscard]] Api::HttpResponse sendHttpsRequest(
|
||||
Stream& stream,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse sendHttpRequest(
|
||||
boost::asio::ip::tcp::socket& socket,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy(
|
||||
boost::asio::ip::tcp::socket& socket,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy);
|
||||
|
||||
// Request/Response building
|
||||
[[nodiscard]] boost::beast::http::request<boost::beast::http::string_body> buildBeastRequest(
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse convertBeastResponse(
|
||||
const boost::beast::http::response<boost::beast::http::dynamic_body>& beastResponse);
|
||||
|
||||
[[nodiscard]] std::vector<Api::HttpHeader> addDefaultHeaders(const std::vector<Api::HttpHeader>& headers);
|
||||
private:
|
||||
|
||||
std::optional<Api::ProxyConfig> proxy_;
|
||||
Api::RetryConfig retryConfig_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<uint32_t> requestId_{0};
|
||||
|
||||
// Thread pool for async operations
|
||||
std::vector<std::jthread> threadPool_;
|
||||
std::queue<std::packaged_task<Api::Result<Api::HttpResponse>()>> taskQueue_;
|
||||
std::mutex taskMutex_;
|
||||
std::condition_variable taskCv_;
|
||||
std::atomic<bool> stopThreads_{false};
|
||||
static constexpr size_t THREAD_POOL_SIZE = 4;
|
||||
};
|
||||
// Request execution
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||
executeWithRetry(const Api::HttpRequest& req);
|
||||
[[nodiscard]] Api::Result<Api::HttpResponse>
|
||||
executeRequest(const Api::HttpRequest& req);
|
||||
|
||||
// Template implementation for sendHttpsRequest
|
||||
template<typename Stream>
|
||||
Api::HttpResponse NetworkClient::sendHttpsRequest(
|
||||
Stream& stream,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req) {
|
||||
namespace http = boost::beast::http;
|
||||
|
||||
// Build request
|
||||
http::request<http::string_body> request = buildBeastRequest(urlComp, req);
|
||||
|
||||
// Send
|
||||
http::write(stream, request);
|
||||
|
||||
// Read response
|
||||
boost::beast::flat_buffer buffer;
|
||||
http::response<http::dynamic_body> response;
|
||||
http::read(stream, buffer, response);
|
||||
|
||||
// Convert to Api::HttpResponse
|
||||
return convertBeastResponse(response);
|
||||
}
|
||||
// Proxy and direct execution methods
|
||||
[[nodiscard]] Api::HttpResponse
|
||||
executeWithProxy(boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse
|
||||
executeWithHttpProxy(boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse
|
||||
executeWithSocks5Proxy(boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse
|
||||
executeDirect(boost::asio::io_context& ioc,
|
||||
boost::asio::ssl::context& ctx,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
std::chrono::seconds timeout);
|
||||
|
||||
// HTTP request methods
|
||||
// Note: sendHttpsRequest is a template, implemented in header below
|
||||
template <typename Stream>
|
||||
[[nodiscard]] Api::HttpResponse
|
||||
sendHttpsRequest(Stream& stream,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse
|
||||
sendHttpRequest(boost::asio::ip::tcp::socket& socket,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse sendHttpRequestThroughProxy(
|
||||
boost::asio::ip::tcp::socket& socket,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req,
|
||||
const Api::ProxyConfig& proxy);
|
||||
|
||||
// Request/Response building
|
||||
[[nodiscard]] boost::beast::http::request<
|
||||
boost::beast::http::string_body>
|
||||
buildBeastRequest(const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req);
|
||||
|
||||
[[nodiscard]] Api::HttpResponse convertBeastResponse(
|
||||
const boost::beast::http::response<
|
||||
boost::beast::http::dynamic_body>& beastResponse);
|
||||
|
||||
[[nodiscard]] std::vector<Api::HttpHeader>
|
||||
addDefaultHeaders(const std::vector<Api::HttpHeader>& headers);
|
||||
|
||||
std::optional<Api::ProxyConfig> proxy_;
|
||||
Api::RetryConfig retryConfig_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<uint32_t> requestId_{0};
|
||||
|
||||
// Thread pool for async operations
|
||||
std::vector<std::jthread> threadPool_;
|
||||
std::queue<std::packaged_task<Api::Result<Api::HttpResponse>()>>
|
||||
taskQueue_;
|
||||
std::mutex taskMutex_;
|
||||
std::condition_variable taskCv_;
|
||||
std::atomic<bool> stopThreads_{false};
|
||||
static constexpr size_t THREAD_POOL_SIZE = 4;
|
||||
};
|
||||
|
||||
// Template implementation for sendHttpsRequest
|
||||
template <typename Stream>
|
||||
Api::HttpResponse
|
||||
NetworkClient::sendHttpsRequest(Stream& stream,
|
||||
const UrlComponents& urlComp,
|
||||
const Api::HttpRequest& req)
|
||||
{
|
||||
namespace http = boost::beast::http;
|
||||
|
||||
// Build request
|
||||
http::request<http::string_body> request =
|
||||
buildBeastRequest(urlComp, req);
|
||||
|
||||
// Send
|
||||
http::write(stream, request);
|
||||
|
||||
// Read response
|
||||
boost::beast::flat_buffer buffer;
|
||||
http::response<http::dynamic_body> response;
|
||||
http::read(stream, buffer, response);
|
||||
|
||||
// Convert to Api::HttpResponse
|
||||
return convertBeastResponse(response);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,81 +1,98 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <thread>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
namespace asio = boost::asio;
|
||||
namespace beast = boost::beast;
|
||||
namespace websocket = beast::websocket;
|
||||
namespace asio = boost::asio;
|
||||
namespace beast = boost::beast;
|
||||
namespace websocket = beast::websocket;
|
||||
|
||||
class RpcServer : public std::enable_shared_from_this<RpcServer> {
|
||||
public:
|
||||
using CommandHandler = std::function<Api::Result<std::string>(const std::string& params, uint64_t clientId)>;
|
||||
class RpcServer : public std::enable_shared_from_this<RpcServer>
|
||||
{
|
||||
public:
|
||||
|
||||
RpcServer();
|
||||
~RpcServer();
|
||||
using CommandHandler = std::function<Api::Result<std::string>(
|
||||
const std::string& params, uint64_t clientId)>;
|
||||
|
||||
// Initialize and start the server
|
||||
Api::Result<void> start(uint16_t port = 8765);
|
||||
void stop();
|
||||
[[nodiscard]] bool isRunning() const { return running_; }
|
||||
[[nodiscard]] uint16_t getPort() const { return port_; }
|
||||
RpcServer();
|
||||
~RpcServer();
|
||||
|
||||
// Register command handlers
|
||||
void registerHandler(const std::string& method, CommandHandler handler);
|
||||
void unregisterHandler(const std::string& method);
|
||||
// Initialize and start the server
|
||||
Api::Result<void> start(uint16_t port = 8765);
|
||||
void stop();
|
||||
[[nodiscard]] bool isRunning() const { return running_; }
|
||||
[[nodiscard]] uint16_t getPort() const { return port_; }
|
||||
|
||||
// Authentication
|
||||
void setAuthToken(const std::string& token);
|
||||
[[nodiscard]] bool authenticate(const std::string& token);
|
||||
void addAuthenticatedClient(uint64_t clientId);
|
||||
void removeAuthenticatedClient(uint64_t clientId);
|
||||
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
|
||||
// Register command handlers
|
||||
void registerHandler(const std::string& method,
|
||||
CommandHandler handler);
|
||||
void unregisterHandler(const std::string& method);
|
||||
|
||||
// Broadcast events to all connected clients
|
||||
void broadcastEvent(const std::string& event, const std::string& data);
|
||||
// Authentication
|
||||
void setAuthToken(const std::string& token);
|
||||
[[nodiscard]] bool authenticate(const std::string& token);
|
||||
void addAuthenticatedClient(uint64_t clientId);
|
||||
void removeAuthenticatedClient(uint64_t clientId);
|
||||
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
|
||||
|
||||
// Send event to specific client
|
||||
void sendEvent(uint64_t clientId, const std::string& event, const std::string& data);
|
||||
// Broadcast events to all connected clients
|
||||
void broadcastEvent(const std::string& event,
|
||||
const std::string& data);
|
||||
|
||||
private:
|
||||
void acceptLoop();
|
||||
void handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||
void processMessage(uint64_t clientId, const std::string& message);
|
||||
void sendResponse(uint64_t clientId, const Api::RpcResponse& response);
|
||||
void sendNotification(uint64_t clientId, const Api::RpcNotification& notification);
|
||||
// Send event to specific client
|
||||
void sendEvent(uint64_t clientId, const std::string& event,
|
||||
const std::string& data);
|
||||
|
||||
asio::io_context ioContext_;
|
||||
std::optional<asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread serverThread_;
|
||||
std::atomic<bool> running_{false};
|
||||
uint16_t port_ = 8765;
|
||||
private:
|
||||
|
||||
// Connected clients
|
||||
std::unordered_map<uint64_t, std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>> clients_;
|
||||
std::mutex clientsMutex_;
|
||||
std::atomic<uint64_t> nextClientId_{1};
|
||||
|
||||
// Client threads (for proper cleanup)
|
||||
std::vector<std::thread> clientThreads_;
|
||||
std::mutex clientThreadsMutex_;
|
||||
void acceptLoop();
|
||||
void handleClient(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||
void processMessage(uint64_t clientId, const std::string& message);
|
||||
void sendResponse(uint64_t clientId,
|
||||
const Api::RpcResponse& response);
|
||||
void sendNotification(uint64_t clientId,
|
||||
const Api::RpcNotification& notification);
|
||||
|
||||
// Authenticated clients
|
||||
std::set<uint64_t> authenticatedClients_;
|
||||
std::mutex authMutex_;
|
||||
std::string authToken_;
|
||||
asio::io_context ioContext_;
|
||||
std::optional<asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread serverThread_;
|
||||
std::atomic<bool> running_{false};
|
||||
uint16_t port_ = 8765;
|
||||
|
||||
// Command handlers
|
||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||
std::mutex handlersMutex_;
|
||||
};
|
||||
// Connected clients
|
||||
std::unordered_map<
|
||||
uint64_t,
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||
clients_;
|
||||
std::mutex clientsMutex_;
|
||||
std::atomic<uint64_t> nextClientId_{1};
|
||||
|
||||
// Client threads (for proper cleanup)
|
||||
std::vector<std::thread> clientThreads_;
|
||||
std::mutex clientThreadsMutex_;
|
||||
|
||||
// Authenticated clients
|
||||
std::set<uint64_t> authenticatedClients_;
|
||||
std::mutex authMutex_;
|
||||
std::string authToken_;
|
||||
|
||||
// Command handlers
|
||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||
std::mutex handlersMutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,87 @@
|
||||
#pragma once
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Session management for RPC clients
|
||||
// Supports 100+ concurrent authenticated sessions
|
||||
class SessionManager
|
||||
{
|
||||
public:
|
||||
|
||||
struct Session {
|
||||
uint64_t clientId;
|
||||
std::string authToken;
|
||||
std::chrono::steady_clock::time_point lastActivity;
|
||||
std::chrono::steady_clock::time_point createdAt;
|
||||
bool isAuthenticated;
|
||||
|
||||
// Optional: store client-specific state
|
||||
struct ClientState {
|
||||
std::optional<std::string> currentPlaylist;
|
||||
float preferredVolume = -1.0f; // -1 = use default
|
||||
// Add more client preferences here
|
||||
};
|
||||
std::optional<ClientState> clientState;
|
||||
};
|
||||
|
||||
struct Config {
|
||||
size_t maxSessions = 150; // 100 users + buffer
|
||||
std::chrono::seconds sessionTimeout{3600}; // 1 hour timeout
|
||||
std::chrono::seconds cleanupInterval{
|
||||
300}; // Cleanup every 5 min
|
||||
};
|
||||
|
||||
SessionManager();
|
||||
explicit SessionManager(const Config& config);
|
||||
|
||||
// Initialize session manager
|
||||
bool initialize();
|
||||
void shutdown();
|
||||
|
||||
// Create new session
|
||||
std::string createSession(uint64_t clientId);
|
||||
|
||||
// Authenticate session
|
||||
bool authenticateSession(const std::string& token);
|
||||
|
||||
// Validate and update session
|
||||
bool validateSession(const std::string& token);
|
||||
void updateActivity(const std::string& token);
|
||||
|
||||
// Get session info
|
||||
std::optional<Session> getSession(const std::string& token) const;
|
||||
|
||||
// End session
|
||||
void endSession(const std::string& token);
|
||||
void endSessionByClientId(uint64_t clientId);
|
||||
|
||||
// Get all active sessions
|
||||
std::vector<Session> getAllSessions() const;
|
||||
|
||||
// Get session count
|
||||
size_t getSessionCount() const;
|
||||
|
||||
// Cleanup expired sessions (call periodically)
|
||||
size_t cleanupExpiredSessions();
|
||||
|
||||
// Check if at capacity
|
||||
bool isAtCapacity() const;
|
||||
|
||||
private:
|
||||
|
||||
std::string generateToken();
|
||||
|
||||
Config config_;
|
||||
std::unordered_map<std::string, Session> sessions_;
|
||||
mutable std::mutex mutex_;
|
||||
std::atomic<bool> running_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,129 +1,138 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <filesystem>
|
||||
|
||||
#include <quickjs.h>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
/**
|
||||
* Signature cipher for YouTube stream URLs
|
||||
* Uses QuickJS (when available) to execute the JavaScript decipher functions from player JS
|
||||
*
|
||||
* Based on yt-dlp's signature extraction logic
|
||||
*/
|
||||
class SignatureCipher {
|
||||
public:
|
||||
SignatureCipher();
|
||||
~SignatureCipher();
|
||||
/**
|
||||
* Signature cipher for YouTube stream URLs
|
||||
* Uses QuickJS (when available) to execute the JavaScript decipher
|
||||
* functions from player JS
|
||||
*
|
||||
* Based on yt-dlp's signature extraction logic
|
||||
*/
|
||||
class SignatureCipher
|
||||
{
|
||||
public:
|
||||
|
||||
// Disable copy, enable move
|
||||
SignatureCipher(const SignatureCipher&) = delete;
|
||||
SignatureCipher& operator=(const SignatureCipher&) = delete;
|
||||
SignatureCipher(SignatureCipher&&) noexcept;
|
||||
SignatureCipher& operator=(SignatureCipher&&) noexcept;
|
||||
SignatureCipher();
|
||||
~SignatureCipher();
|
||||
|
||||
/**
|
||||
* Initialize the QuickJS solver with core libraries
|
||||
* Must be called before using the cipher
|
||||
*/
|
||||
void initialize();
|
||||
// Disable copy, enable move
|
||||
SignatureCipher(const SignatureCipher&) = delete;
|
||||
SignatureCipher& operator=(const SignatureCipher&) = delete;
|
||||
SignatureCipher(SignatureCipher&&) noexcept;
|
||||
SignatureCipher& operator=(SignatureCipher&&) noexcept;
|
||||
|
||||
/**
|
||||
* Set the player JS code and extract decipher functions
|
||||
* @param playerJsCode The raw player JavaScript code from YouTube
|
||||
* @return true if extraction succeeded
|
||||
*/
|
||||
bool setPlayerJs(std::string_view playerJsCode);
|
||||
/**
|
||||
* Initialize the QuickJS solver with core libraries
|
||||
* Must be called before using the cipher
|
||||
*/
|
||||
void initialize();
|
||||
|
||||
/**
|
||||
* Check if the cipher is ready (has valid decipher function)
|
||||
*/
|
||||
[[nodiscard]] bool isReady() const;
|
||||
/**
|
||||
* Set the player JS code and extract decipher functions
|
||||
* @param playerJsCode The raw player JavaScript code from YouTube
|
||||
* @return true if extraction succeeded
|
||||
*/
|
||||
bool setPlayerJs(std::string_view playerJsCode);
|
||||
|
||||
/**
|
||||
* Decipher a signature cipher string
|
||||
* Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
|
||||
* @param signatureCipher The signature cipher string
|
||||
* @return The full deciphered URL or empty string on failure
|
||||
*/
|
||||
[[nodiscard]] std::string decipher(std::string_view signatureCipher);
|
||||
/**
|
||||
* Check if the cipher is ready (has valid decipher function)
|
||||
*/
|
||||
[[nodiscard]] bool isReady() const;
|
||||
|
||||
/**
|
||||
* Solve a challenge (signature or n-param) using the preprocessed player
|
||||
* @param challenge The challenge string to solve
|
||||
* @param type "sig" for signature, "n" for n-parameter
|
||||
* @return The solved challenge or empty string on failure
|
||||
*/
|
||||
[[nodiscard]] std::string solveChallenge(const std::string& challenge, const std::string& type);
|
||||
/**
|
||||
* Decipher a signature cipher string
|
||||
* Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
|
||||
* @param signatureCipher The signature cipher string
|
||||
* @return The full deciphered URL or empty string on failure
|
||||
*/
|
||||
[[nodiscard]] std::string
|
||||
decipher(std::string_view signatureCipher);
|
||||
|
||||
/**
|
||||
* Decipher the n-parameter for throttling
|
||||
* @param nParam The encoded n parameter
|
||||
* @return The deciphered n parameter
|
||||
*/
|
||||
[[nodiscard]] std::string decipherNParam(std::string_view nParam);
|
||||
/**
|
||||
* Solve a challenge (signature or n-param) using the preprocessed
|
||||
* player
|
||||
* @param challenge The challenge string to solve
|
||||
* @param type "sig" for signature, "n" for n-parameter
|
||||
* @return The solved challenge or empty string on failure
|
||||
*/
|
||||
[[nodiscard]] std::string
|
||||
solveChallenge(const std::string& challenge,
|
||||
const std::string& type);
|
||||
|
||||
/**
|
||||
* Clear the cipher state
|
||||
*/
|
||||
void clear();
|
||||
/**
|
||||
* Decipher the n-parameter for throttling
|
||||
* @param nParam The encoded n parameter
|
||||
* @return The deciphered n parameter
|
||||
*/
|
||||
[[nodiscard]] std::string decipherNParam(std::string_view nParam);
|
||||
|
||||
/**
|
||||
* Check if cipher has been initialized
|
||||
*/
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
/**
|
||||
* Clear the cipher state
|
||||
*/
|
||||
void clear();
|
||||
|
||||
private:
|
||||
/**
|
||||
* Initialize QuickJS runtime and context with solver libraries
|
||||
*/
|
||||
void initSolver();
|
||||
/**
|
||||
* Check if cipher has been initialized
|
||||
*/
|
||||
[[nodiscard]] bool isInitialized() const;
|
||||
|
||||
/**
|
||||
* Download solver libraries from remote URL
|
||||
* @param url The URL to download from
|
||||
* @return The downloaded JS code or empty string on failure
|
||||
*/
|
||||
[[nodiscard]] std::optional<std::string> downloadSolverLibrary(
|
||||
std::string_view url);
|
||||
private:
|
||||
|
||||
/**
|
||||
* Get cache directory for storing solver libraries
|
||||
*/
|
||||
[[nodiscard]] std::filesystem::path getCacheDir();
|
||||
/**
|
||||
* Initialize QuickJS runtime and context with solver libraries
|
||||
*/
|
||||
void initSolver();
|
||||
|
||||
/**
|
||||
* Execute JavaScript code in QuickJS and return result
|
||||
*/
|
||||
[[nodiscard]] std::optional<std::string> executeJS(
|
||||
std::string_view code,
|
||||
std::string_view filename = "<script>");
|
||||
/**
|
||||
* Download solver libraries from remote URL
|
||||
* @param url The URL to download from
|
||||
* @return The downloaded JS code or empty string on failure
|
||||
*/
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
downloadSolverLibrary(std::string_view url);
|
||||
|
||||
/**
|
||||
* Cleanup QuickJS resources
|
||||
*/
|
||||
void cleanupQuickJS();
|
||||
/**
|
||||
* Get cache directory for storing solver libraries
|
||||
*/
|
||||
[[nodiscard]] std::filesystem::path getCacheDir();
|
||||
|
||||
JSRuntime* runtime_ = nullptr;
|
||||
JSContext* context_ = nullptr;
|
||||
/**
|
||||
* Execute JavaScript code in QuickJS and return result
|
||||
*/
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
executeJS(std::string_view code,
|
||||
std::string_view filename = "<script>");
|
||||
|
||||
// Player JS code and extracted functions
|
||||
std::string playerJsCode_;
|
||||
std::string preprocessedPlayer_;
|
||||
/**
|
||||
* Cleanup QuickJS resources
|
||||
*/
|
||||
void cleanupQuickJS();
|
||||
|
||||
// State
|
||||
bool initialized_ = false;
|
||||
bool solverInitialized_ = false;
|
||||
bool hasPlayerJs_ = false;
|
||||
JSRuntime* runtime_ = nullptr;
|
||||
JSContext* context_ = nullptr;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
// Player JS code and extracted functions
|
||||
std::string playerJsCode_;
|
||||
std::string preprocessedPlayer_;
|
||||
|
||||
// State
|
||||
bool initialized_ = false;
|
||||
bool solverInitialized_ = false;
|
||||
bool hasPlayerJs_ = false;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,64 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "Database.hpp"
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
/**
|
||||
* Manages user subscriptions to the bot's audio output
|
||||
* Subscriptions are persisted to database and survive client reloads
|
||||
* Uses unique client UID instead of session-specific client ID
|
||||
*/
|
||||
class SubscriptionManager {
|
||||
public:
|
||||
struct Subscriber {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
/**
|
||||
* Manages user subscriptions to the bot's audio output
|
||||
* Subscriptions are persisted to database and survive client reloads
|
||||
* Uses unique client UID instead of session-specific client ID
|
||||
*/
|
||||
class SubscriptionManager
|
||||
{
|
||||
public:
|
||||
|
||||
SubscriptionManager();
|
||||
~SubscriptionManager();
|
||||
struct Subscriber {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
|
||||
// Initialize and load subscriptions from database
|
||||
Api::Result<void> initialize(std::shared_ptr<Api::Database> database);
|
||||
void shutdown();
|
||||
SubscriptionManager();
|
||||
~SubscriptionManager();
|
||||
|
||||
// Subscription management (by UID)
|
||||
bool subscribe(const std::string& uid, const std::string& nickname);
|
||||
bool unsubscribe(const std::string& uid);
|
||||
bool isSubscribed(const std::string& uid) const;
|
||||
|
||||
// Get all subscribed UIDs
|
||||
std::vector<std::string> getSubscribedUids() const;
|
||||
|
||||
// Get all subscribers with info
|
||||
std::vector<Subscriber> getSubscribers() const;
|
||||
|
||||
// Get subscriber nickname
|
||||
std::optional<std::string> getSubscriberNickname(const std::string& uid) const;
|
||||
|
||||
// Update nickname for subscriber
|
||||
bool updateNickname(const std::string& uid, const std::string& nickname);
|
||||
|
||||
// Check if anyone is subscribed
|
||||
bool hasSubscribers() const;
|
||||
|
||||
// Get subscriber count
|
||||
size_t getSubscriberCount() const;
|
||||
|
||||
// Clear all subscriptions
|
||||
bool clearAll();
|
||||
// Initialize and load subscriptions from database
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<Api::Database> database);
|
||||
void shutdown();
|
||||
|
||||
private:
|
||||
std::set<std::string> subscribedUids_;
|
||||
mutable std::mutex mutex_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
bool initialized_ = false;
|
||||
};
|
||||
// Subscription management (by UID)
|
||||
bool subscribe(const std::string& uid, const std::string& nickname);
|
||||
bool unsubscribe(const std::string& uid);
|
||||
bool isSubscribed(const std::string& uid) const;
|
||||
|
||||
// Get all subscribed UIDs
|
||||
std::vector<std::string> getSubscribedUids() const;
|
||||
|
||||
// Get all subscribers with info
|
||||
std::vector<Subscriber> getSubscribers() const;
|
||||
|
||||
// Get subscriber nickname
|
||||
std::optional<std::string>
|
||||
getSubscriberNickname(const std::string& uid) const;
|
||||
|
||||
// Update nickname for subscriber
|
||||
bool updateNickname(const std::string& uid,
|
||||
const std::string& nickname);
|
||||
|
||||
// Check if anyone is subscribed
|
||||
bool hasSubscribers() const;
|
||||
|
||||
// Get subscriber count
|
||||
size_t getSubscriberCount() const;
|
||||
|
||||
// Clear all subscriptions
|
||||
bool clearAll();
|
||||
|
||||
private:
|
||||
|
||||
std::set<std::string> subscribedUids_;
|
||||
mutable std::mutex mutex_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
bool initialized_ = false;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,50 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "NetworkClient.hpp"
|
||||
#include <string>
|
||||
#include <optional>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// URL shortener service for faumaray.ru
|
||||
class UrlShortener {
|
||||
public:
|
||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||
~UrlShortener();
|
||||
// URL shortener service for faumaray.ru
|
||||
class UrlShortener
|
||||
{
|
||||
public:
|
||||
|
||||
// Shorten a YouTube URL via faumaray.ru
|
||||
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
||||
[[nodiscard]] Api::Result<std::string> shortenYouTubeUrl(std::string_view videoId);
|
||||
|
||||
// Shorten any URL via faumaray.ru
|
||||
[[nodiscard]] Api::Result<std::string> shortenUrl(std::string_view originalUrl);
|
||||
|
||||
// Get cached shortened URL if available
|
||||
[[nodiscard]] std::optional<std::string> getCachedUrl(std::string_view originalUrl) const;
|
||||
|
||||
// Clear the URL cache
|
||||
void clearCache();
|
||||
|
||||
// Set cache TTL (default: 24 hours)
|
||||
void setCacheTtl(std::chrono::hours ttl);
|
||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||
~UrlShortener();
|
||||
|
||||
private:
|
||||
struct CacheEntry {
|
||||
std::string shortenedUrl;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
mutable std::mutex cacheMutex_;
|
||||
std::unordered_map<std::string, CacheEntry> cache_;
|
||||
std::chrono::hours cacheTtl_{24};
|
||||
|
||||
// Clean expired entries from cache
|
||||
void cleanExpiredCache();
|
||||
};
|
||||
// Shorten a YouTube URL via faumaray.ru
|
||||
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenYouTubeUrl(std::string_view videoId);
|
||||
|
||||
// Shorten any URL via faumaray.ru
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenUrl(std::string_view originalUrl);
|
||||
|
||||
// Get cached shortened URL if available
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
getCachedUrl(std::string_view originalUrl) const;
|
||||
|
||||
// Clear the URL cache
|
||||
void clearCache();
|
||||
|
||||
// Set cache TTL (default: 24 hours)
|
||||
void setCacheTtl(std::chrono::hours ttl);
|
||||
|
||||
private:
|
||||
|
||||
struct CacheEntry {
|
||||
std::string shortenedUrl;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
mutable std::mutex cacheMutex_;
|
||||
std::unordered_map<std::string, CacheEntry> cache_;
|
||||
std::chrono::hours cacheTtl_{24};
|
||||
|
||||
// Clean expired entries from cache
|
||||
void cleanExpiredCache();
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -3,8 +3,11 @@
|
||||
#include "NetworkClient.hpp"
|
||||
#include "UrlShortener.hpp"
|
||||
#include "YtDlpManager.hpp"
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <YouTubeTypes.hpp>
|
||||
#include <chrono>
|
||||
#include <echoion/api.hpp>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
@@ -15,142 +18,159 @@
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class YouTubeClient {
|
||||
public:
|
||||
explicit YouTubeClient(std::shared_ptr<NetworkClient> networkClient);
|
||||
~YouTubeClient();
|
||||
class YouTubeClient
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize the client - downloads yt-dlp if needed
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
explicit YouTubeClient(
|
||||
std::shared_ptr<NetworkClient> networkClient);
|
||||
~YouTubeClient();
|
||||
|
||||
// Check if yt-dlp is available
|
||||
[[nodiscard]] bool isAvailable() const;
|
||||
|
||||
// Get yt-dlp version
|
||||
[[nodiscard]] std::string getYtDlpVersion() const;
|
||||
|
||||
// Force update yt-dlp
|
||||
Api::Result<void> updateYtDlp();
|
||||
// Initialize the client - downloads yt-dlp if needed
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
|
||||
// Search for videos using YouTube Data API v3 (or yt-dlp as fallback)
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
// Check if yt-dlp is available
|
||||
[[nodiscard]] bool isAvailable() const;
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo> getVideoInfo(std::string_view videoId);
|
||||
// Get yt-dlp version
|
||||
[[nodiscard]] std::string getYtDlpVersion() const;
|
||||
|
||||
// Get video details asynchronously
|
||||
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoAsync(std::string_view videoId);
|
||||
// Force update yt-dlp
|
||||
Api::Result<void> updateYtDlp();
|
||||
|
||||
// Get multiple video details concurrently
|
||||
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
||||
// Search for videos using YouTube Data API v3 (or yt-dlp as
|
||||
// fallback)
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
|
||||
// Get playlist videos - uses YouTube API v2 if key available, otherwise
|
||||
// yt-dlp Then resolves each track individually via yt-dlp for full metadata
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo>
|
||||
getPlaylist(std::string_view playlistId);
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
getVideoInfo(std::string_view videoId);
|
||||
|
||||
// Get playlist videos asynchronously with concurrent track resolution
|
||||
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
||||
getPlaylistAsync(std::string_view playlistId);
|
||||
// Get video details asynchronously
|
||||
[[nodiscard]] std::future<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoAsync(std::string_view videoId);
|
||||
|
||||
// Stream playlist tracks with callback - calls trackCallback for each track
|
||||
// as it is resolved, enabling immediate playback of first track
|
||||
void getPlaylistStreaming(std::string_view playlistId,
|
||||
std::function<void(Api::TrackInfo&&)> trackCallback,
|
||||
std::function<void(size_t totalTracks)> onPlaylistInfo = nullptr,
|
||||
std::function<void()> onComplete = nullptr);
|
||||
// Get multiple video details concurrently
|
||||
[[nodiscard]] std::vector<Api::Result<Api::TrackInfo>>
|
||||
getVideoInfoBatch(const std::vector<std::string>& videoIds);
|
||||
|
||||
// Extract video ID from various YouTube URL formats (handles redirects for
|
||||
// short URLs)
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string>
|
||||
extractPlaylistId(std::string_view url);
|
||||
// Get playlist videos - uses YouTube API v2 if key available,
|
||||
// otherwise yt-dlp Then resolves each track individually via yt-dlp
|
||||
// for full metadata
|
||||
[[nodiscard]] Api::Result<Api::PlaylistInfo>
|
||||
getPlaylist(std::string_view playlistId);
|
||||
|
||||
// Check if URL is a YouTube URL
|
||||
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
||||
// Get playlist videos asynchronously with concurrent track
|
||||
// resolution
|
||||
[[nodiscard]] std::future<Api::Result<Api::PlaylistInfo>>
|
||||
getPlaylistAsync(std::string_view playlistId);
|
||||
|
||||
// Get stream URL for a video (used by MusicManager)
|
||||
[[nodiscard]] Api::Result<std::string> getStreamUrl(std::string_view videoId);
|
||||
|
||||
// Get best audio stream URL using yt-dlp
|
||||
[[nodiscard]] Api::Result<std::string> getAudioStreamUrl(std::string_view videoId);
|
||||
|
||||
// Configure cookie options for yt-dlp
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
// Stream playlist tracks with callback - calls trackCallback for
|
||||
// each track as it is resolved, enabling immediate playback of
|
||||
// first track
|
||||
void getPlaylistStreaming(
|
||||
std::string_view playlistId,
|
||||
std::function<void(Api::TrackInfo&&)>
|
||||
trackCallback,
|
||||
std::function<void(size_t totalTracks)> onPlaylistInfo =
|
||||
nullptr,
|
||||
std::function<void()> onComplete = nullptr);
|
||||
|
||||
// Configure proxy for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
||||
// Extract video ID from various YouTube URL formats (handles
|
||||
// redirects for short URLs)
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string>
|
||||
extractPlaylistId(std::string_view url);
|
||||
|
||||
// Set YouTube API key for enhanced playlist resolution (optional)
|
||||
void setApiKey(const std::string& apiKey);
|
||||
[[nodiscard]] bool hasApiKey() const;
|
||||
// Check if URL is a YouTube URL
|
||||
[[nodiscard]] static bool isYouTubeUrl(std::string_view url);
|
||||
|
||||
// Configure concurrent resolution settings
|
||||
void setMaxConcurrentResolutions(size_t max);
|
||||
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
||||
// Get stream URL for a video (used by MusicManager)
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrl(std::string_view videoId);
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
// Get best audio stream URL using yt-dlp
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getAudioStreamUrl(std::string_view videoId);
|
||||
|
||||
private:
|
||||
// Configure cookie options for yt-dlp
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Internal search implementations
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithApi(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlp(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
// Configure proxy for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig>
|
||||
getProxyConfig() const;
|
||||
|
||||
// Fetch video durations for search results (batch API call)
|
||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||
const std::vector<std::string>& videoIds);
|
||||
// Set YouTube API key for enhanced playlist resolution (optional)
|
||||
void setApiKey(const std::string& apiKey);
|
||||
[[nodiscard]] bool hasApiKey() const;
|
||||
|
||||
// Parse ISO 8601 duration string
|
||||
[[nodiscard]] static std::chrono::seconds
|
||||
parseIso8601Duration(const std::string& duration);
|
||||
// Configure concurrent resolution settings
|
||||
void setMaxConcurrentResolutions(size_t max);
|
||||
[[nodiscard]] size_t getMaxConcurrentResolutions() const;
|
||||
|
||||
// URL encode/decode helpers
|
||||
[[nodiscard]] static std::string urlEncode(std::string_view value);
|
||||
[[nodiscard]] static std::string decodeHtmlEntities(std::string_view value);
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
|
||||
// Internal methods for playlist resolution
|
||||
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
|
||||
fetchPlaylistItems(std::string_view playlistId);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
|
||||
private:
|
||||
|
||||
// Build YouTube API v3 URL for playlist items
|
||||
[[nodiscard]] std::string buildPlaylistApiUrl(
|
||||
std::string_view playlistId,
|
||||
const std::optional<std::string>& pageToken = std::nullopt) const;
|
||||
// Internal search implementations
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithApi(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlp(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
std::unique_ptr<UrlShortener> urlShortener_;
|
||||
// Fetch video durations for search results (batch API call)
|
||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||
const std::vector<std::string>& videoIds);
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
// Parse ISO 8601 duration string
|
||||
[[nodiscard]] static std::chrono::seconds
|
||||
parseIso8601Duration(const std::string& duration);
|
||||
|
||||
// Configuration
|
||||
std::optional<std::string> apiKey_;
|
||||
mutable std::mutex configMutex_;
|
||||
size_t maxConcurrentResolutions_ = 4;
|
||||
bool urlShorteningEnabled_ = true;
|
||||
// URL encode/decode helpers
|
||||
[[nodiscard]] static std::string urlEncode(std::string_view value);
|
||||
[[nodiscard]] static std::string
|
||||
decodeHtmlEntities(std::string_view value);
|
||||
|
||||
// Populate shortened URLs for tracks
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
};
|
||||
// Internal methods for playlist resolution
|
||||
[[nodiscard]] Api::Result<std::vector<Api::YouTubePlaylistItem>>
|
||||
fetchPlaylistItems(std::string_view playlistId);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveTrackWithYtDlp(const Api::YouTubePlaylistItem& item);
|
||||
|
||||
// Build YouTube API v3 URL for playlist items
|
||||
[[nodiscard]] std::string buildPlaylistApiUrl(
|
||||
std::string_view playlistId,
|
||||
const std::optional<std::string>& pageToken =
|
||||
std::nullopt) const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::unique_ptr<YtDlpManager> ytDlpManager_;
|
||||
std::unique_ptr<UrlShortener> urlShortener_;
|
||||
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Configuration
|
||||
std::optional<std::string> apiKey_;
|
||||
mutable std::mutex configMutex_;
|
||||
size_t maxConcurrentResolutions_ = 4;
|
||||
bool urlShorteningEnabled_ = true;
|
||||
|
||||
// Populate shortened URLs for tracks
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,9 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include "NetworkClient.hpp"
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <YouTubeTypes.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <echoion/api.hpp>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
@@ -12,7 +14,8 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
struct YtDlpResult {
|
||||
std::string output;
|
||||
@@ -21,121 +24,122 @@ namespace Echoion::Core {
|
||||
std::chrono::milliseconds executionTime;
|
||||
};
|
||||
|
||||
class YtDlpManager {
|
||||
public:
|
||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||
~YtDlpManager();
|
||||
class YtDlpManager
|
||||
{
|
||||
public:
|
||||
|
||||
// Initialize - checks for yt-dlp and downloads if needed
|
||||
Api::Result<void> initialize();
|
||||
|
||||
// Get the path to the yt-dlp executable
|
||||
[[nodiscard]] std::filesystem::path getExecutablePath() const;
|
||||
|
||||
// Check if yt-dlp is available
|
||||
[[nodiscard]] bool isAvailable() const;
|
||||
|
||||
// Get yt-dlp version
|
||||
[[nodiscard]] std::string getVersion() const;
|
||||
|
||||
// Force update yt-dlp to latest version
|
||||
Api::Result<void> update();
|
||||
explicit YtDlpManager(std::shared_ptr<NetworkClient> networkClient);
|
||||
~YtDlpManager();
|
||||
|
||||
// Execute yt-dlp with given arguments and return output (synchronous)
|
||||
[[nodiscard]] std::string
|
||||
execute(const std::vector<std::string>& args) const;
|
||||
// Initialize - checks for yt-dlp and downloads if needed
|
||||
Api::Result<void> initialize();
|
||||
|
||||
// Execute yt-dlp asynchronously and return a future
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
// Get the path to the yt-dlp executable
|
||||
[[nodiscard]] std::filesystem::path getExecutablePath() const;
|
||||
|
||||
// Execute multiple yt-dlp commands concurrently
|
||||
[[nodiscard]] std::vector<YtDlpResult>
|
||||
executeBatch(const std::vector<std::vector<std::string>>& argsList);
|
||||
// Check if yt-dlp is available
|
||||
[[nodiscard]] bool isAvailable() const;
|
||||
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Get cookie arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
|
||||
// Get yt-dlp version
|
||||
[[nodiscard]] std::string getVersion() const;
|
||||
|
||||
// Set proxy configuration for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig> getProxyConfig() const;
|
||||
// Force update yt-dlp to latest version
|
||||
Api::Result<void> update();
|
||||
|
||||
// Configure thread pool size for async operations (default: 4)
|
||||
void setThreadPoolSize(size_t size);
|
||||
[[nodiscard]] size_t getThreadPoolSize() const;
|
||||
// Execute yt-dlp with given arguments and return output
|
||||
// (synchronous)
|
||||
[[nodiscard]] std::string
|
||||
execute(const std::vector<std::string>& args) const;
|
||||
|
||||
private:
|
||||
// Get the storage directory for yt-dlp
|
||||
[[nodiscard]] std::filesystem::path getStorageDir() const;
|
||||
|
||||
// Get the executable name based on platform
|
||||
[[nodiscard]] std::string getExecutableName() const;
|
||||
|
||||
// Download yt-dlp from official source
|
||||
Api::Result<void> downloadYtDlp();
|
||||
|
||||
// Make executable executable (Unix only)
|
||||
Api::Result<void> makeExecutable();
|
||||
|
||||
// Check if update is needed (older than 7 days)
|
||||
[[nodiscard]] bool shouldUpdate() const;
|
||||
|
||||
// Get download URL based on platform
|
||||
[[nodiscard]] std::string getDownloadUrl() const;
|
||||
// Execute yt-dlp asynchronously and return a future
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
|
||||
// Internal execute implementation
|
||||
[[nodiscard]] YtDlpResult
|
||||
executeInternal(const std::vector<std::string>& args) const;
|
||||
// Execute multiple yt-dlp commands concurrently
|
||||
[[nodiscard]] std::vector<YtDlpResult> executeBatch(
|
||||
const std::vector<std::vector<std::string>>& argsList);
|
||||
|
||||
// Build the full command with all options
|
||||
[[nodiscard]] std::string
|
||||
buildCommand(const std::vector<std::string>& args) const;
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
|
||||
// Get proxy arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
||||
// Get cookie arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getCookieArgs() const;
|
||||
|
||||
// Escape shell argument
|
||||
[[nodiscard]] static std::string escapeArg(const std::string& arg);
|
||||
// Set proxy configuration for yt-dlp
|
||||
void setProxyConfig(const std::optional<Api::ProxyConfig>& proxy);
|
||||
[[nodiscard]] std::optional<Api::ProxyConfig>
|
||||
getProxyConfig() const;
|
||||
|
||||
// Thread pool for async operations
|
||||
void startThreadPool();
|
||||
void stopThreadPool();
|
||||
void workerThread();
|
||||
// Configure thread pool size for async operations (default: 4)
|
||||
void setThreadPoolSize(size_t size);
|
||||
[[nodiscard]] size_t getThreadPoolSize() const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Cookie configuration for YouTube authentication
|
||||
std::optional<std::string> cookiesPath_;
|
||||
std::optional<std::string> cookiesFromBrowser_;
|
||||
private:
|
||||
|
||||
// Proxy configuration
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
mutable std::mutex proxyMutex_;
|
||||
// Get the storage directory for yt-dlp
|
||||
[[nodiscard]] std::filesystem::path getStorageDir() const;
|
||||
|
||||
// Thread pool for async operations
|
||||
size_t threadPoolSize_ = 4;
|
||||
std::vector<std::jthread> threadPool_;
|
||||
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
|
||||
std::mutex taskMutex_;
|
||||
std::condition_variable taskCv_;
|
||||
std::atomic<bool> stopThreads_{false};
|
||||
// Get the executable name based on platform
|
||||
[[nodiscard]] std::string getExecutableName() const;
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_VERSION_URL =
|
||||
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_MACOS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos";
|
||||
};
|
||||
// Download yt-dlp from official source
|
||||
Api::Result<void> downloadYtDlp();
|
||||
|
||||
// Make executable executable (Unix only)
|
||||
Api::Result<void> makeExecutable();
|
||||
|
||||
// Check if update is needed (older than 7 days)
|
||||
[[nodiscard]] bool shouldUpdate() const;
|
||||
|
||||
// Get download URL based on platform
|
||||
[[nodiscard]] std::string getDownloadUrl() const;
|
||||
|
||||
// Internal execute implementation
|
||||
[[nodiscard]] YtDlpResult
|
||||
executeInternal(const std::vector<std::string>& args) const;
|
||||
|
||||
// Get proxy arguments for yt-dlp command
|
||||
[[nodiscard]] std::vector<std::string> getProxyArgs() const;
|
||||
|
||||
// Thread pool for async operations
|
||||
void startThreadPool();
|
||||
void stopThreadPool();
|
||||
void workerThread();
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Cookie configuration for YouTube authentication
|
||||
std::optional<std::string> cookiesPath_;
|
||||
std::optional<std::string> cookiesFromBrowser_;
|
||||
|
||||
// Proxy configuration
|
||||
std::optional<Api::ProxyConfig> proxyConfig_;
|
||||
mutable std::mutex proxyMutex_;
|
||||
|
||||
// Thread pool for async operations
|
||||
size_t threadPoolSize_ = 4;
|
||||
std::vector<std::jthread> threadPool_;
|
||||
std::queue<std::packaged_task<YtDlpResult()>> taskQueue_;
|
||||
std::mutex taskMutex_;
|
||||
std::condition_variable taskCv_;
|
||||
std::atomic<bool> stopThreads_{false};
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_VERSION_URL =
|
||||
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp.exe";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_MACOS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp_macos";
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,43 +4,55 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class ClearCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class ClearCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->clearQueue();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Clear command failed: {}", result.error().message));
|
||||
ctx.reply("Couldn't clear the queue. Please try again.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Queue cleared!");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Clear command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->clearQueue();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Clear command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't clear the queue. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Clears all tracks from the queue.";
|
||||
}
|
||||
ctx.reply("Queue cleared!");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Clear command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Clears all tracks from the queue.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"clr", "empty"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"clr", "empty"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,106 +1,110 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api.hpp>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager;
|
||||
class MusicManager;
|
||||
|
||||
enum class CommandCategory {
|
||||
Music,
|
||||
Queue,
|
||||
Playback,
|
||||
Utility,
|
||||
Admin
|
||||
};
|
||||
enum class CommandCategory { Music, Queue, Playback, Utility, Admin };
|
||||
|
||||
inline std::string toString(CommandCategory category) {
|
||||
switch (category) {
|
||||
case CommandCategory::Music:
|
||||
return "Music";
|
||||
case CommandCategory::Queue:
|
||||
return "Queue";
|
||||
case CommandCategory::Playback:
|
||||
return "Playback";
|
||||
case CommandCategory::Utility:
|
||||
return "Utility";
|
||||
case CommandCategory::Admin:
|
||||
return "Admin";
|
||||
}
|
||||
return "Utility";
|
||||
}
|
||||
inline std::string toString(CommandCategory category)
|
||||
{
|
||||
switch (category) {
|
||||
case CommandCategory::Music:
|
||||
return "Music";
|
||||
case CommandCategory::Queue:
|
||||
return "Queue";
|
||||
case CommandCategory::Playback:
|
||||
return "Playback";
|
||||
case CommandCategory::Utility:
|
||||
return "Utility";
|
||||
case CommandCategory::Admin:
|
||||
return "Admin";
|
||||
}
|
||||
return "Utility";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Context passed to every command execution.
|
||||
* Wraps all dependencies required to perform an action.
|
||||
*/
|
||||
struct CommandContext {
|
||||
uint64_t clientId = 0;
|
||||
std::string prefix;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string_view invokerName;
|
||||
|
||||
// Dependencies
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
|
||||
// Reply callback - set by CommandManager
|
||||
std::function<void(std::string_view)> replyCallback;
|
||||
|
||||
// Helper to reply to the user
|
||||
void reply(std::string_view message) const {
|
||||
if (replyCallback) {
|
||||
replyCallback(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
/**
|
||||
* @brief Context passed to every command execution.
|
||||
* Wraps all dependencies required to perform an action.
|
||||
*/
|
||||
struct CommandContext {
|
||||
uint64_t clientId = 0;
|
||||
std::string prefix;
|
||||
std::string args; // Arguments excluding the command name
|
||||
std::string_view invokerName;
|
||||
|
||||
/**
|
||||
* @brief Interface that all commands must implement.
|
||||
*/
|
||||
class Command {
|
||||
public:
|
||||
virtual ~Command() = default;
|
||||
// Dependencies
|
||||
std::weak_ptr<MusicManager> musicManager;
|
||||
|
||||
/**
|
||||
* @brief The logic of the command.
|
||||
*/
|
||||
virtual void execute(const CommandContext& ctx) = 0;
|
||||
// Reply callback - set by CommandManager
|
||||
std::function<void(std::string_view)> replyCallback;
|
||||
|
||||
/**
|
||||
* @brief Returns the description used for help generation.
|
||||
*/
|
||||
virtual std::string_view getDescription() const = 0;
|
||||
// Helper to reply to the user
|
||||
void reply(std::string_view message) const
|
||||
{
|
||||
if (replyCallback) {
|
||||
replyCallback(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Returns usage syntax (e.g., "<url>").
|
||||
*/
|
||||
virtual std::string_view getUsage() const { return ""; }
|
||||
/**
|
||||
* @brief Interface that all commands must implement.
|
||||
*/
|
||||
class Command
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Returns the command category for grouping in help.
|
||||
*/
|
||||
virtual CommandCategory getCategory() const {
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
virtual ~Command() = default;
|
||||
|
||||
/**
|
||||
* @brief Returns aliases for this command.
|
||||
*/
|
||||
virtual std::vector<std::string_view> getAliases() const { return {}; }
|
||||
|
||||
/**
|
||||
* @brief Returns whether this command requires admin privileges.
|
||||
*/
|
||||
virtual bool requiresAdmin() const { return false; }
|
||||
};
|
||||
/**
|
||||
* @brief The logic of the command.
|
||||
*/
|
||||
virtual void execute(const CommandContext& ctx) = 0;
|
||||
|
||||
using CommandPtr = std::shared_ptr<Command>;
|
||||
/**
|
||||
* @brief Returns the description used for help generation.
|
||||
*/
|
||||
virtual std::string_view getDescription() const = 0;
|
||||
|
||||
/**
|
||||
* @brief Returns usage syntax (e.g., "<url>").
|
||||
*/
|
||||
virtual std::string_view getUsage() const { return ""; }
|
||||
|
||||
/**
|
||||
* @brief Returns the command category for grouping in help.
|
||||
*/
|
||||
virtual CommandCategory getCategory() const
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns aliases for this command.
|
||||
*/
|
||||
virtual std::vector<std::string_view> getAliases() const
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Returns whether this command requires admin privileges.
|
||||
*/
|
||||
virtual bool requiresAdmin() const { return false; }
|
||||
};
|
||||
|
||||
using CommandPtr = std::shared_ptr<Command>;
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,28 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
// New command system - header-only commands
|
||||
#include "Command.hpp"
|
||||
#include "PlayCommand.hpp"
|
||||
#include "SelectCommand.hpp"
|
||||
#include "PauseCommand.hpp"
|
||||
#include "ResumeCommand.hpp"
|
||||
#include "StopCommand.hpp"
|
||||
#include "SkipCommand.hpp"
|
||||
#include "SeekCommand.hpp"
|
||||
#include "VolumeCommand.hpp"
|
||||
#include "QueueCommand.hpp"
|
||||
#include "RemoveCommand.hpp"
|
||||
#include "ClearCommand.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "MoveCommand.hpp"
|
||||
#include "ShuffleCommand.hpp"
|
||||
#include "RepeatCommand.hpp"
|
||||
#include "PlaylistCommand.hpp"
|
||||
#include "NowPlayingCommand.hpp"
|
||||
#include "SearchCommand.hpp"
|
||||
#include "PauseCommand.hpp"
|
||||
#include "PlayCommand.hpp"
|
||||
#include "PlaylistCommand.hpp"
|
||||
#include "QueueCommand.hpp"
|
||||
#include "ReloadCommand.hpp"
|
||||
#include "ReloadConfigCommand.hpp"
|
||||
#include "RemoveCommand.hpp"
|
||||
#include "RepeatCommand.hpp"
|
||||
#include "ResumeCommand.hpp"
|
||||
#include "RpcInfoCommand.hpp"
|
||||
#include "SearchCommand.hpp"
|
||||
#include "SeekCommand.hpp"
|
||||
#include "SelectCommand.hpp"
|
||||
#include "ShuffleCommand.hpp"
|
||||
#include "SkipCommand.hpp"
|
||||
#include "StopCommand.hpp"
|
||||
#include "SubscribeCommand.hpp"
|
||||
#include "UnsubscribeCommand.hpp"
|
||||
#include "SubscribersCommand.hpp"
|
||||
#include "UnsubscribeIdCommand.hpp"
|
||||
#include "UnsubscribeAllCommand.hpp"
|
||||
#include "UnsubscribeCommand.hpp"
|
||||
#include "UnsubscribeIdCommand.hpp"
|
||||
#include "VolumeCommand.hpp"
|
||||
@@ -2,81 +2,98 @@
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MoveCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class MoveCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse arguments: from and to positions
|
||||
uint32_t from = 0, to = 0;
|
||||
|
||||
auto spacePos = ctx.args.find(' ');
|
||||
if (spacePos == std::string::npos) {
|
||||
ctx.reply("Please provide both from and to positions.");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 "
|
||||
"(moves track 5 to position 1)");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result1 = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + spacePos,
|
||||
from);
|
||||
auto result2 = std::from_chars(ctx.args.data() + spacePos + 1,
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
to);
|
||||
// Parse arguments: from and to positions
|
||||
uint32_t from = 0, to = 0;
|
||||
|
||||
if (result1.ec != std::errc() || result2.ec != std::errc() || from == 0 || to == 0) {
|
||||
ctx.reply("Please provide valid position numbers (starting from 1).");
|
||||
return;
|
||||
}
|
||||
auto spacePos = ctx.args.find(' ');
|
||||
if (spacePos == std::string::npos) {
|
||||
ctx.reply("Please provide both from and to positions.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto moveResult = manager->moveInQueue(from - 1, to - 1); // Convert to 0-based
|
||||
if (!moveResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Move command failed: {}", moveResult.error().message));
|
||||
|
||||
if (moveResult.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply("One of those positions doesn't exist in the queue.");
|
||||
} else {
|
||||
ctx.reply("Couldn't move that track. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
auto result1 = std::from_chars(
|
||||
ctx.args.data(), ctx.args.data() + spacePos, from);
|
||||
auto result2 =
|
||||
std::from_chars(ctx.args.data() + spacePos + 1,
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
to);
|
||||
|
||||
ctx.reply(std::format("Moved track from position {} to {}.", from, to));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Move command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
if (result1.ec != std::errc() ||
|
||||
result2.ec != std::errc() || from == 0 || to == 0) {
|
||||
ctx.reply("Please provide valid position numbers "
|
||||
"(starting from 1).");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Moves a track to a different position in the queue.";
|
||||
}
|
||||
auto moveResult = manager->moveInQueue(
|
||||
from - 1, to - 1); // Convert to 0-based
|
||||
if (!moveResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Move command failed: {}",
|
||||
moveResult.error().message));
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<from> <to>";
|
||||
}
|
||||
if (moveResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply("One of those positions doesn't exist in "
|
||||
"the queue.");
|
||||
} else {
|
||||
ctx.reply(
|
||||
"Couldn't move that track. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
ctx.reply(std::format(
|
||||
"Moved track from position {} to {}.", from, to));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Move command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"mv"};
|
||||
}
|
||||
};
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Moves a track to a different position in the queue.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<from> <to>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"mv"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,95 +4,113 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class NowPlayingCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
if (!current) {
|
||||
ECHOION_LOG_ERROR(std::format("NowPlaying command failed: {}", current.error().message));
|
||||
ctx.reply("Couldn't get current track information.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!current->has_value()) {
|
||||
ctx.reply(std::format(
|
||||
"Nothing is currently playing. Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", trackInfo.title, trackInfo.artist);
|
||||
}
|
||||
std::string linkText = trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*trackInfo.shortenedUrl)
|
||||
: displayText;
|
||||
std::string msg = std::format("\xf0\x9f\x8e\xb5 {}", linkText);
|
||||
|
||||
// Show current position / total duration
|
||||
auto playbackState = manager->getPlaybackState();
|
||||
if (playbackState && playbackState->currentTrack.has_value() &&
|
||||
trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
|
||||
auto position = playbackState->position;
|
||||
msg += std::format(" [{}/{}]",
|
||||
formatDuration(position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else if (trackInfo.duration.has_value() && trackInfo.duration->count() > 0) {
|
||||
msg += std::format(" [{}]", formatDuration(*trackInfo.duration));
|
||||
}
|
||||
|
||||
if (!track.addedBy.empty()) {
|
||||
msg += std::format(" (requested by {})", track.addedBy);
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("NowPlaying command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows the currently playing track.";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"np", "current", "playing"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
class NowPlayingCommand : public Command
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
public:
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
if (!current) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("NowPlaying command failed: {}",
|
||||
current.error().message));
|
||||
ctx.reply("Couldn't get current track information.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!current->has_value()) {
|
||||
ctx.reply(std::format("Nothing is currently playing. "
|
||||
"Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText = std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*trackInfo.shortenedUrl)
|
||||
: displayText;
|
||||
std::string msg =
|
||||
std::format("\xf0\x9f\x8e\xb5 {}", linkText);
|
||||
|
||||
// Show current position / total duration
|
||||
auto playbackState = manager->getPlaybackState();
|
||||
if (playbackState &&
|
||||
playbackState->currentTrack.has_value() &&
|
||||
trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
auto position = playbackState->position;
|
||||
msg += std::format(" [{}/{}]",
|
||||
formatDuration(position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
msg += std::format(" [{}]",
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
|
||||
if (!track.addedBy.empty()) {
|
||||
msg += std::format(" (requested by {})", track.addedBy);
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"NowPlaying command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the currently playing track.";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"np", "current", "playing"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,48 +4,61 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class PauseCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class PauseCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->pause();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Pause command failed: {}", result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
} else {
|
||||
ctx.reply("Couldn't pause playback. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Playback paused.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Pause command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->pause();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Pause command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Pauses the current playback.";
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
} else {
|
||||
ctx.reply(
|
||||
"Couldn't pause playback. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
ctx.reply("Playback paused.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Pause command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Pauses the current playback.";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,158 +4,186 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class PlayCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable. Please try again later.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: play <url or search query>\nExample: play never gonna give you up");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a direct URL
|
||||
if (ctx.args.find("http") == 0) {
|
||||
auto result = manager->play(ctx.args, ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Play URL failed '{}': {}",
|
||||
ctx.args, result.error().message));
|
||||
|
||||
switch (result.error().code) {
|
||||
case Api::ErrorCode::NetworkError:
|
||||
ctx.reply("Couldn't connect to that URL. Please check and try again.");
|
||||
break;
|
||||
case Api::ErrorCode::InvalidUrl:
|
||||
ctx.reply("That doesn't look like a valid URL.");
|
||||
break;
|
||||
default:
|
||||
ctx.reply("Couldn't play that URL. Please try again.");
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// result contains the track title
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, treat as search query
|
||||
auto searchResult = manager->search(ctx.args);
|
||||
if (!searchResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Search failed for '{}': {}",
|
||||
ctx.args, searchResult.error().message));
|
||||
|
||||
if (searchResult.error().code == Api::ErrorCode::NetworkError) {
|
||||
ctx.reply("Couldn't connect to search service. Please check your connection.");
|
||||
} else {
|
||||
ctx.reply("Search failed. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (searchResult->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Single result - play immediately
|
||||
if (searchResult->tracks.size() == 1) {
|
||||
const auto& track = searchResult->tracks[0];
|
||||
auto playResult = manager->queueTrack(track, ctx.clientId);
|
||||
if (!playResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Queue failed: {}", playResult.error().message));
|
||||
ctx.reply("Couldn't add that track. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
ctx.reply(std::format("Added to queue: {}", linkText));
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple results - store and show list
|
||||
manager->storePendingSearch(ctx.clientId, searchResult->tracks);
|
||||
|
||||
std::string msg = std::format("\xf0\x9f\x94\x8d Multiple results "
|
||||
"found. Use {}select <number>:\n",
|
||||
ctx.prefix);
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5; ++i) {
|
||||
const auto& track = searchResult->tracks[i];
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg += std::format("{}. {}", i + 1, linkText);
|
||||
if (track.duration.has_value()) {
|
||||
msg +=
|
||||
std::format(" [{}]", formatDuration(*track.duration));
|
||||
}
|
||||
msg += "\n";
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Play command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong while trying to play. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Plays a track from URL or searches and lets you select.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<url or search query>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"p", "add"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
class PlayCommand : public Command
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
public:
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable. "
|
||||
"Please try again later.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: play <url or search query>\nExample: "
|
||||
"play never gonna give you up");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a direct URL
|
||||
if (ctx.args.find("http") == 0) {
|
||||
auto result = manager->play(ctx.args, ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Play URL failed '{}': {}",
|
||||
ctx.args, result.error().message));
|
||||
|
||||
switch (result.error().code) {
|
||||
case Api::ErrorCode::NetworkError:
|
||||
ctx.reply("Couldn't connect to that URL. "
|
||||
"Please check and try again.");
|
||||
break;
|
||||
case Api::ErrorCode::InvalidUrl:
|
||||
ctx.reply(
|
||||
"That doesn't look like a valid URL.");
|
||||
break;
|
||||
default:
|
||||
ctx.reply("Couldn't play that URL. Please "
|
||||
"try again.");
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// result contains the track title
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, treat as search query
|
||||
auto searchResult = manager->search(ctx.args);
|
||||
if (!searchResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
searchResult.error().message));
|
||||
|
||||
if (searchResult.error().code ==
|
||||
Api::ErrorCode::NetworkError) {
|
||||
ctx.reply("Couldn't connect to search service. "
|
||||
"Please check your connection.");
|
||||
} else {
|
||||
ctx.reply("Search failed. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (searchResult->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Single result - play immediately
|
||||
if (searchResult->tracks.size() == 1) {
|
||||
const auto& track = searchResult->tracks[0];
|
||||
auto playResult =
|
||||
manager->queueTrack(track, ctx.clientId);
|
||||
if (!playResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Queue failed: {}",
|
||||
playResult.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't add that track. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
ctx.reply(std::format("Added to queue: {}", linkText));
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple results - store and show list
|
||||
manager->storePendingSearch(ctx.clientId,
|
||||
searchResult->tracks);
|
||||
|
||||
std::string msg =
|
||||
std::format("\xf0\x9f\x94\x8d Multiple results "
|
||||
"found. Use {}select <number>:\n",
|
||||
ctx.prefix);
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5;
|
||||
++i) {
|
||||
const auto& track = searchResult->tracks[i];
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg += std::format("{}. {}", i + 1, linkText);
|
||||
if (track.duration.has_value()) {
|
||||
msg += std::format(" [{}]",
|
||||
formatDuration(*track.duration));
|
||||
}
|
||||
msg += "\n";
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Play command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong while trying to play. "
|
||||
"Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a track from URL or searches and lets you "
|
||||
"select.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -5,76 +5,97 @@
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class PlaylistCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class PlaylistCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
// List playlists
|
||||
auto playlists = manager->getPlaylists();
|
||||
if (!playlists) {
|
||||
ECHOION_LOG_ERROR(std::format("Playlist list failed: {}", playlists.error().message));
|
||||
ctx.reply("Couldn't retrieve playlists.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (playlists->empty()) {
|
||||
ctx.reply("No playlists available.");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
// List playlists
|
||||
auto playlists = manager->getPlaylists();
|
||||
if (!playlists) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Playlist list failed: {}",
|
||||
playlists.error().message));
|
||||
ctx.reply("Couldn't retrieve playlists.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
|
||||
for (const auto& pl : *playlists) {
|
||||
msg << std::format("- {} ({} tracks)\n", pl.name, pl.tracks.size());
|
||||
}
|
||||
if (playlists->empty()) {
|
||||
ctx.reply("No playlists available.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} else {
|
||||
// Load playlist
|
||||
auto result = manager->loadPlaylist(std::string(ctx.args), ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Playlist load failed: {}", result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply("That playlist doesn't exist.");
|
||||
} else {
|
||||
ctx.reply("Couldn't load the playlist. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
|
||||
for (const auto& pl : *playlists) {
|
||||
msg << std::format("- {} ({} tracks)\n", pl.name,
|
||||
pl.tracks.size());
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Loading playlist '{}'... Tracks will be added to the queue as they are resolved.", ctx.args));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Playlist command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
ctx.reply(msg.str());
|
||||
} else {
|
||||
// Load playlist
|
||||
auto result = manager->loadPlaylist(
|
||||
std::string(ctx.args), ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Playlist load failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Lists or loads a playlist.";
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply("That playlist doesn't exist.");
|
||||
} else {
|
||||
ctx.reply("Couldn't load the playlist. Please "
|
||||
"try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "[playlist name]";
|
||||
}
|
||||
ctx.reply(std::format(
|
||||
"Loading playlist '{}'... Tracks will be added to "
|
||||
"the queue as they are resolved.",
|
||||
ctx.args));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Playlist command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Lists or loads a playlist.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"pl"};
|
||||
}
|
||||
};
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "[playlist name]";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"pl"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -5,189 +5,200 @@
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class QueueCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class QueueCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
auto queue = manager->getQueue();
|
||||
auto state = manager->getPlaybackState();
|
||||
|
||||
if (!queue) {
|
||||
ECHOION_LOG_ERROR(std::format("Queue command failed: {}", queue.error().message));
|
||||
ctx.reply("Couldn't get queue information.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse page number from args (default to 1)
|
||||
int page = 1;
|
||||
if (!ctx.args.empty()) {
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
page = std::stoi(std::string(ctx.args));
|
||||
if (page < 1) {
|
||||
page = 1;
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
} catch (...) {
|
||||
page = 1;
|
||||
}
|
||||
}
|
||||
|
||||
constexpr int ITEMS_PER_PAGE = 10;
|
||||
int totalPages =
|
||||
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
|
||||
ITEMS_PER_PAGE;
|
||||
if (totalPages == 0) {
|
||||
totalPages = 1;
|
||||
}
|
||||
auto current = manager->getCurrentTrack();
|
||||
auto queue = manager->getQueue();
|
||||
auto state = manager->getPlaybackState();
|
||||
|
||||
// Clamp page to valid range
|
||||
if (page > totalPages) {
|
||||
page = totalPages;
|
||||
}
|
||||
if (!queue) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Queue command failed: {}", queue.error().message));
|
||||
ctx.reply("Couldn't get queue information.");
|
||||
return;
|
||||
}
|
||||
|
||||
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
||||
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
||||
static_cast<int>(queue->size()));
|
||||
// Parse page number from args (default to 1)
|
||||
int page = 1;
|
||||
if (!ctx.args.empty()) {
|
||||
try {
|
||||
page = std::stoi(std::string(ctx.args));
|
||||
if (page < 1) {
|
||||
page = 1;
|
||||
}
|
||||
} catch (...) {
|
||||
page = 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
||||
<< totalPages << ")\n";
|
||||
constexpr int ITEMS_PER_PAGE = 10;
|
||||
int totalPages =
|
||||
(static_cast<int>(queue->size()) + ITEMS_PER_PAGE - 1) /
|
||||
ITEMS_PER_PAGE;
|
||||
if (totalPages == 0) {
|
||||
totalPages = 1;
|
||||
}
|
||||
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
// Clamp page to valid range
|
||||
if (page > totalPages) {
|
||||
page = totalPages;
|
||||
}
|
||||
|
||||
// Build time display: [current/total] or [total]
|
||||
std::string timeStr;
|
||||
if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
if (state) {
|
||||
timeStr =
|
||||
std::format(" [{}/{}]",
|
||||
formatDuration(state->position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
int startIdx = (page - 1) * ITEMS_PER_PAGE;
|
||||
int endIdx = std::min(startIdx + ITEMS_PER_PAGE,
|
||||
static_cast<int>(queue->size()));
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
||||
<< totalPages << ")\n";
|
||||
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
|
||||
// Build time display: [current/total] or [total]
|
||||
std::string timeStr;
|
||||
if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
if (state) {
|
||||
timeStr = std::format(
|
||||
" [{}/{}]",
|
||||
formatDuration(state->position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else {
|
||||
timeStr = std::format(
|
||||
" [{}]",
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
}
|
||||
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText = std::format(
|
||||
"{} by {}", trackInfo.title, trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({}){}", displayText,
|
||||
*trackInfo.shortenedUrl, timeStr)
|
||||
: displayText + timeStr;
|
||||
msg << std::format("\n**Now Playing:** {}\n", linkText);
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << std::format(
|
||||
"\nThe queue is empty. Add songs with {}play !",
|
||||
ctx.prefix);
|
||||
} else {
|
||||
timeStr = std::format(
|
||||
" [{}]", formatDuration(*trackInfo.duration));
|
||||
}
|
||||
}
|
||||
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText = std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({}){}", displayText,
|
||||
*trackInfo.shortenedUrl, timeStr)
|
||||
: displayText + timeStr;
|
||||
msg << std::format("\n**Now Playing:** {}\n", linkText);
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << std::format(
|
||||
"\nThe queue is empty. Add songs with {}play !",
|
||||
ctx.prefix);
|
||||
} else {
|
||||
msg << std::format("\n**Up Next ({} tracks):**\n",
|
||||
queue->size());
|
||||
for (int i = startIdx; i < endIdx; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
const auto& trackInfo = entry.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} [{}] by {}", trackInfo.title,
|
||||
formatDuration(*trackInfo.duration),
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({}) [{}]", displayText,
|
||||
msg << std::format("\n**Up Next ({} tracks):**\n",
|
||||
queue->size());
|
||||
for (int i = startIdx; i < endIdx; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
const auto& trackInfo = entry.track;
|
||||
std::string displayText = trackInfo.title;
|
||||
if (!trackInfo.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format(
|
||||
"[{}]({}) [{}]", displayText,
|
||||
*trackInfo.shortenedUrl,
|
||||
formatDuration(*trackInfo.duration))
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << std::format(" (by {})", entry.addedBy);
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << std::format(" (by {})", entry.addedBy);
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
if (totalPages > 1) {
|
||||
msg << std::format(
|
||||
"\nUse {}queue <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
}
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
if (totalPages > 1) {
|
||||
msg << std::format("\nUse {}queue <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
// State indicators
|
||||
if (state) {
|
||||
msg << "\n\n";
|
||||
if (state->isPaused) {
|
||||
msg << "\xe2\x8f\xb8 Paused | ";
|
||||
}
|
||||
if (state->shuffle) {
|
||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||
}
|
||||
if (state->repeat) {
|
||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||
}
|
||||
msg << std::format(
|
||||
"Volume: {}%",
|
||||
static_cast<int>(state->volume * 100));
|
||||
}
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
// State indicators
|
||||
if (state) {
|
||||
msg << "\n\n";
|
||||
if (state->isPaused) {
|
||||
msg << "\xe2\x8f\xb8 Paused | ";
|
||||
}
|
||||
if (state->shuffle) {
|
||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||
}
|
||||
if (state->repeat) {
|
||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||
}
|
||||
msg << std::format("Volume: {}%", static_cast<int>(state->volume * 100));
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
std::string_view getUsage() const override { return "[page]"; }
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the current queue and playback status.";
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[page]"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"q", "list"};
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
private:
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"q", "list"};
|
||||
}
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,31 +4,38 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class ReloadCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
// This is a placeholder - actual reload is handled by the plugin
|
||||
ECHOION_LOG_INFO("Reload requested by user");
|
||||
ctx.reply("Reload is handled automatically by the plugin. Use the TS3 plugin menu to reload the core.");
|
||||
}
|
||||
class ReloadCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows information about reloading the bot.";
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
// This is a placeholder - actual reload is handled by the
|
||||
// plugin
|
||||
ECHOION_LOG_INFO("Reload requested by user");
|
||||
ctx.reply("Reload is handled automatically by the plugin. Use "
|
||||
"the TS3 plugin menu to reload the core.");
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows information about reloading the bot.";
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override {
|
||||
return true;
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"restart", "r"};
|
||||
}
|
||||
};
|
||||
bool requiresAdmin() const override { return true; }
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"restart", "r"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,42 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Core.hpp" // For Core::reloadConfig
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/Core.hpp" // For Core::reloadConfig
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class ReloadConfigCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
// Note: ctx.core is not directly accessible, we need to use the MusicManager's core reference
|
||||
// For now, reply with instructions
|
||||
ctx.reply("Config reload: Please use !reload command or restart the bot for config changes to take effect.");
|
||||
|
||||
// TODO: Add core reference to CommandContext so commands can call Core methods
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("ReloadConfig command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
class ReloadConfigCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Reloads the bot configuration from file.";
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
// Note: ctx.core is not directly accessible, we need to use
|
||||
// the MusicManager's core reference For now, reply with
|
||||
// instructions
|
||||
ctx.reply(
|
||||
"Config reload: Please use !reload command or restart "
|
||||
"the bot for config changes to take effect.");
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
// TODO: Add core reference to CommandContext so commands
|
||||
// can call Core methods
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"ReloadConfig command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override {
|
||||
return true;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Reloads the bot configuration from file.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"reloadcfg", "rlcfg"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"reloadcfg", "rlcfg"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -2,71 +2,88 @@
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class RemoveCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class RemoveCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(std::format("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t position = 0;
|
||||
auto result = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
position);
|
||||
if (result.ec != std::errc() || position == 0) {
|
||||
ctx.reply("Please provide a valid position number (starting from 1).");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
std::format("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
auto remResult = manager->removeFromQueue(position - 1); // Convert to 0-based
|
||||
if (!remResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Remove command failed: {}", remResult.error().message));
|
||||
|
||||
if (remResult.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply("That position doesn't exist in the queue.");
|
||||
} else {
|
||||
ctx.reply("Couldn't remove that track. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
uint32_t position = 0;
|
||||
auto result =
|
||||
std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
position);
|
||||
if (result.ec != std::errc() || position == 0) {
|
||||
ctx.reply("Please provide a valid position number "
|
||||
"(starting from 1).");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Removed track at position {}.", position));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Remove command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto remResult = manager->removeFromQueue(
|
||||
position - 1); // Convert to 0-based
|
||||
if (!remResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Remove command failed: {}",
|
||||
remResult.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Removes a track from the queue by position.";
|
||||
}
|
||||
if (remResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(
|
||||
"That position doesn't exist in the queue.");
|
||||
} else {
|
||||
ctx.reply("Couldn't remove that track. Please try "
|
||||
"again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<position>";
|
||||
}
|
||||
ctx.reply(
|
||||
std::format("Removed track at position {}.", position));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Remove command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Removes a track from the queue by position.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"rm", "delete", "del"};
|
||||
}
|
||||
};
|
||||
std::string_view getUsage() const override { return "<position>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"rm", "delete", "del"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,43 +4,55 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class RepeatCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class RepeatCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->toggleRepeat();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Repeat command failed: {}", result.error().message));
|
||||
ctx.reply("Couldn't toggle repeat. Please try again.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON." : "Repeat is now OFF.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Repeat command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->toggleRepeat();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Repeat command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply("Couldn't toggle repeat. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Toggles repeat mode for the current track.";
|
||||
}
|
||||
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON."
|
||||
: "Repeat is now OFF.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Repeat command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles repeat mode for the current track.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"loop"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"loop"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,48 +4,61 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class ResumeCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class ResumeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->resume();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Resume command failed: {}", result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Playback isn't paused right now.");
|
||||
} else {
|
||||
ctx.reply("Couldn't resume playback. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Playback resumed.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Resume command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->resume();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Resume command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Resumes the paused playback.";
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Playback isn't paused right now.");
|
||||
} else {
|
||||
ctx.reply(
|
||||
"Couldn't resume playback. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
ctx.reply("Playback resumed.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Resume command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"unpause", "continue"};
|
||||
}
|
||||
};
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Resumes the paused playback.";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unpause", "continue"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class RpcInfoCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override;
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Get RPC server connection information";
|
||||
}
|
||||
std::string_view getUsage() const override { return ""; }
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"rpc", "api", "remote"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -5,110 +5,126 @@
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SearchCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: search <query>\nExample: search never gonna give you up");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->search(ctx.args);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Search failed for '{}': {}",
|
||||
ctx.args, result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::NetworkError) {
|
||||
ctx.reply("Couldn't connect to search service. Please check your connection.");
|
||||
} else {
|
||||
ctx.reply("Search failed. Please try again later.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (result->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Store results for this client so they can use select
|
||||
manager->storePendingSearch(ctx.clientId, result->tracks);
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args << "\":\n\n";
|
||||
|
||||
for (size_t i = 0; i < result->tracks.size() && i < 5; ++i) {
|
||||
const auto& track = result->tracks[i];
|
||||
// Format as [Title by Artist](shortenedUrl) with duration
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText =
|
||||
std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (track.duration.has_value()) {
|
||||
msg << std::format(" [{}]",
|
||||
formatDuration(*track.duration));
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
msg << std::format("\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
|
||||
ctx.reply(msg.str());
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Search command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Searches for tracks and shows results.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<query>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"find", "s"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string formatDuration(std::chrono::milliseconds duration)
|
||||
class SearchCommand : public Command
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
public:
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: search <query>\nExample: search "
|
||||
"never gonna give you up");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->search(ctx.args);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::NetworkError) {
|
||||
ctx.reply("Couldn't connect to search service. "
|
||||
"Please check your connection.");
|
||||
} else {
|
||||
ctx.reply("Search failed. Please try again later.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (result->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Store results for this client so they can use select
|
||||
manager->storePendingSearch(ctx.clientId, result->tracks);
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args
|
||||
<< "\":\n\n";
|
||||
|
||||
for (size_t i = 0; i < result->tracks.size() && i < 5;
|
||||
++i) {
|
||||
const auto& track = result->tracks[i];
|
||||
// Format as [Title by Artist](shortenedUrl) with
|
||||
// duration
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (track.duration.has_value()) {
|
||||
msg << std::format(" [{}]",
|
||||
formatDuration(*track.duration));
|
||||
}
|
||||
msg << "\n";
|
||||
}
|
||||
|
||||
msg << std::format(
|
||||
"\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
|
||||
ctx.reply(msg.str());
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Search command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Searches for tracks and shows results.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"find", "s"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -2,123 +2,147 @@
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <chrono>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SeekCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class SeekCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: seek <+/-seconds>\nExamples:\n seek +30 (skip forward 30s)\n seek -10 (skip back 10s)\n seek 60 (jump to 1 minute mark)");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the seek argument (supports +30, -10, or absolute 60)
|
||||
std::string_view arg = ctx.args;
|
||||
bool relative = false;
|
||||
bool forward = true;
|
||||
|
||||
if (arg.starts_with('+')) {
|
||||
relative = true;
|
||||
forward = true;
|
||||
arg = arg.substr(1);
|
||||
} else if (arg.starts_with('-')) {
|
||||
relative = true;
|
||||
forward = false;
|
||||
arg = arg.substr(1);
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
"Usage: seek <+/-seconds>\nExamples:\n seek +30 "
|
||||
"(skip forward 30s)\n seek -10 (skip back 10s)\n "
|
||||
"seek 60 (jump to 1 minute mark)");
|
||||
return;
|
||||
}
|
||||
|
||||
int seconds = 0;
|
||||
auto parseResult = std::from_chars(arg.data(),
|
||||
arg.data() + arg.size(),
|
||||
seconds);
|
||||
if (parseResult.ec != std::errc() || seconds < 0) {
|
||||
ctx.reply("Please provide a valid number of seconds.\nExamples: seek +30, seek -10, seek 60");
|
||||
return;
|
||||
}
|
||||
// Parse the seek argument (supports +30, -10, or absolute
|
||||
// 60)
|
||||
std::string_view arg = ctx.args;
|
||||
bool relative = false;
|
||||
bool forward = true;
|
||||
|
||||
std::chrono::milliseconds targetPosition;
|
||||
std::string positionStr;
|
||||
if (arg.starts_with('+')) {
|
||||
relative = true;
|
||||
forward = true;
|
||||
arg = arg.substr(1);
|
||||
} else if (arg.starts_with('-')) {
|
||||
relative = true;
|
||||
forward = false;
|
||||
arg = arg.substr(1);
|
||||
}
|
||||
|
||||
if (relative) {
|
||||
// Get current position from playback state
|
||||
auto state = manager->getPlaybackState();
|
||||
if (!state) {
|
||||
ctx.reply("Unable to get current playback position.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto currentPos = state->position;
|
||||
if (forward) {
|
||||
targetPosition = currentPos + std::chrono::seconds(seconds);
|
||||
positionStr = std::format("+{}s", seconds);
|
||||
} else {
|
||||
// Seek backward
|
||||
if (currentPos.count() < seconds * 1000) {
|
||||
targetPosition = std::chrono::milliseconds(0);
|
||||
} else {
|
||||
targetPosition = currentPos - std::chrono::seconds(seconds);
|
||||
}
|
||||
positionStr = std::format("-{}s", seconds);
|
||||
}
|
||||
} else {
|
||||
// Absolute seek (legacy behavior)
|
||||
targetPosition = std::chrono::seconds(seconds);
|
||||
auto mins = seconds / 60;
|
||||
auto secs = seconds % 60;
|
||||
positionStr = std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
int seconds = 0;
|
||||
auto parseResult = std::from_chars(
|
||||
arg.data(), arg.data() + arg.size(), seconds);
|
||||
if (parseResult.ec != std::errc() || seconds < 0) {
|
||||
ctx.reply(
|
||||
"Please provide a valid number of "
|
||||
"seconds.\nExamples: seek +30, seek -10, seek 60");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->seek(targetPosition);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command failed: {}", result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
} else if (result.error().code == Api::ErrorCode::NotSupported) {
|
||||
ctx.reply("This track doesn't support seeking.");
|
||||
} else {
|
||||
ctx.reply("Couldn't seek. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::chrono::milliseconds targetPosition;
|
||||
std::string positionStr;
|
||||
|
||||
if (relative) {
|
||||
ctx.reply(std::format("Seeked {} from current position.", positionStr));
|
||||
} else {
|
||||
ctx.reply(std::format("Seeked to position {}.", positionStr));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
if (relative) {
|
||||
// Get current position from playback state
|
||||
auto state = manager->getPlaybackState();
|
||||
if (!state) {
|
||||
ctx.reply(
|
||||
"Unable to get current playback position.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Seeks to a position in the current track. Use +seconds to skip forward, -seconds to skip backward.";
|
||||
}
|
||||
auto currentPos = state->position;
|
||||
if (forward) {
|
||||
targetPosition =
|
||||
currentPos + std::chrono::seconds(seconds);
|
||||
positionStr = std::format("+{}s", seconds);
|
||||
} else {
|
||||
// Seek backward
|
||||
if (currentPos.count() < seconds * 1000) {
|
||||
targetPosition = std::chrono::milliseconds(0);
|
||||
} else {
|
||||
targetPosition =
|
||||
currentPos - std::chrono::seconds(seconds);
|
||||
}
|
||||
positionStr = std::format("-{}s", seconds);
|
||||
}
|
||||
} else {
|
||||
// Absolute seek (legacy behavior)
|
||||
targetPosition = std::chrono::seconds(seconds);
|
||||
auto mins = seconds / 60;
|
||||
auto secs = seconds % 60;
|
||||
positionStr = std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<+/-seconds>";
|
||||
}
|
||||
auto result = manager->seek(targetPosition);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
} else if (result.error().code ==
|
||||
Api::ErrorCode::NotSupported) {
|
||||
ctx.reply("This track doesn't support seeking.");
|
||||
} else {
|
||||
ctx.reply("Couldn't seek. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"jump"};
|
||||
}
|
||||
};
|
||||
if (relative) {
|
||||
ctx.reply(std::format(
|
||||
"Seeked {} from current position.", positionStr));
|
||||
} else {
|
||||
ctx.reply(
|
||||
std::format("Seeked to position {}.", positionStr));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Seek command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Seeks to a position in the current track. Use +seconds "
|
||||
"to skip forward, -seconds to skip backward.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<+/-seconds>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"jump"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -2,76 +2,91 @@
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SelectCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class SelectCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: select <number>\nSelect a track from your last search results.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse index
|
||||
uint32_t index = 0;
|
||||
auto result = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
index);
|
||||
if (result.ec != std::errc() || index == 0) {
|
||||
ctx.reply("Please provide a valid number (1, 2, 3, etc.).");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: select <number>\nSelect a track from "
|
||||
"your last search results.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string invokerName(ctx.invokerName);
|
||||
auto selectResult = manager->selectSearchResult(ctx.clientId, index, invokerName);
|
||||
|
||||
if (!selectResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Select failed for client {} index {}: {}",
|
||||
ctx.clientId, index, selectResult.error().message));
|
||||
|
||||
if (selectResult.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply(std::format("No search results found. Use {}play "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
} else {
|
||||
ctx.reply("Couldn't select that track. Please try again.");
|
||||
// Parse index
|
||||
uint32_t index = 0;
|
||||
auto result =
|
||||
std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
index);
|
||||
if (result.ec != std::errc() || index == 0) {
|
||||
ctx.reply(
|
||||
"Please provide a valid number (1, 2, 3, etc.).");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string invokerName(ctx.invokerName);
|
||||
auto selectResult = manager->selectSearchResult(
|
||||
ctx.clientId, index, invokerName);
|
||||
|
||||
if (!selectResult) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Select failed for client {} index {}: {}",
|
||||
ctx.clientId, index, selectResult.error().message));
|
||||
|
||||
if (selectResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(std::format(
|
||||
"No search results found. Use {}play "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
} else {
|
||||
ctx.reply("Couldn't select that track. Please try "
|
||||
"again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*selectResult);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Select command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ctx.reply(*selectResult);
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Selects a track from your search results.";
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Select command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
std::string_view getUsage() const override { return "<number>"; }
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Selects a track from your search results.";
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "<number>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"sel", "pick", "choose"};
|
||||
}
|
||||
};
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sel", "pick", "choose"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,43 +4,48 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class ShuffleCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class ShuffleCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->toggleShuffle();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Shuffle command failed: {}", result.error().message));
|
||||
ctx.reply("Couldn't toggle shuffle. Please try again.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result ? "\xf0\x9f\x94\x80 Shuffle is now ON." : "Shuffle is now OFF.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Shuffle command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
// Actually shuffle the queue (not just toggle mode)
|
||||
manager->shuffleQueue();
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Toggles shuffle mode for the queue.";
|
||||
}
|
||||
ctx.reply("\xf0\x9f\x94\x80 Queue shuffled!");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Shuffle command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles shuffle mode for the queue.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"random"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Queue;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"random"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -2,70 +2,81 @@
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SkipCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class SkipCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
uint32_t count = 1;
|
||||
if (!ctx.args.empty()) {
|
||||
auto result = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
count);
|
||||
if (result.ec != std::errc() || count == 0) {
|
||||
ctx.reply("Please provide a valid number (1 or more).");
|
||||
return;
|
||||
}
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->skip(count);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Skip command failed: {}", result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply("No more tracks in the queue to skip to.");
|
||||
} else {
|
||||
ctx.reply("Couldn't skip. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
uint32_t count = 1;
|
||||
if (!ctx.args.empty()) {
|
||||
auto result =
|
||||
std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
count);
|
||||
if (result.ec != std::errc() || count == 0) {
|
||||
ctx.reply(
|
||||
"Please provide a valid number (1 or more).");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (count == 1) {
|
||||
ctx.reply("Skipped to next track.");
|
||||
} else {
|
||||
ctx.reply(std::format("Skipped {} tracks.", count));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Skip command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->skip(count);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Skip command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Skips to the next track(s).";
|
||||
}
|
||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply(
|
||||
"No more tracks in the queue to skip to.");
|
||||
} else {
|
||||
ctx.reply("Couldn't skip. Please try again.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "[count]";
|
||||
}
|
||||
if (count == 1) {
|
||||
ctx.reply("Skipped to next track.");
|
||||
} else {
|
||||
ctx.reply(std::format("Skipped {} tracks.", count));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Skip command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Skips to the next track(s).";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"next", "n"};
|
||||
}
|
||||
};
|
||||
std::string_view getUsage() const override { return "[count]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"next", "n"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,43 +4,53 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class StopCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class StopCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->stop();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Stop command failed: {}", result.error().message));
|
||||
ctx.reply("Couldn't stop playback. Please try again.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Playback stopped and queue cleared.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Stop command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->stop();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Stop command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply("Couldn't stop playback. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Stops playback and clears the queue.";
|
||||
}
|
||||
ctx.reply("Playback stopped and queue cleared.");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Stop command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Stops playback and clears the queue.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"s"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"s"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,43 +4,53 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SubscribeCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class SubscribeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->subscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}", result.error().message));
|
||||
ctx.reply("Couldn't subscribe you. Please try again.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Subscribe command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->subscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply("Couldn't subscribe you. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Subscribes to the music bot to receive audio.";
|
||||
}
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Subscribe command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Subscribes to the music bot to receive audio.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"sub", "join"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sub", "join"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -4,43 +4,54 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class UnsubscribeCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class UnsubscribeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
auto result = manager->unsubscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}", result.error().message));
|
||||
ctx.reply("Couldn't unsubscribe you. Please try again.");
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Unsubscribe command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
auto result = manager->unsubscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't unsubscribe you. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Unsubscribes from the music bot.";
|
||||
}
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribe command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Unsubscribes from the music bot.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"unsub", "leave"};
|
||||
}
|
||||
};
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"unsub", "leave"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -2,84 +2,100 @@
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class VolumeCommand : public Command {
|
||||
public:
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
class VolumeCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
// Show current volume
|
||||
auto state = manager->getPlaybackState();
|
||||
if (state) {
|
||||
ctx.reply(std::format("Current volume: {}%", static_cast<int>(state->volume * 100)));
|
||||
} else {
|
||||
ctx.reply("Unable to get current volume.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse volume (0-100)
|
||||
int volumePercent = 0;
|
||||
auto result = std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
volumePercent);
|
||||
if (result.ec != std::errc()) {
|
||||
ctx.reply("Please provide a valid number (0-100).");
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
// Show current volume
|
||||
auto state = manager->getPlaybackState();
|
||||
if (state) {
|
||||
ctx.reply(std::format(
|
||||
"Current volume: {}%",
|
||||
static_cast<int>(state->volume * 100)));
|
||||
} else {
|
||||
ctx.reply("Unable to get current volume.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (volumePercent < 0 || volumePercent > 100) {
|
||||
ctx.reply("Volume must be between 0 and 100.");
|
||||
return;
|
||||
}
|
||||
// Parse volume (0-100)
|
||||
int volumePercent = 0;
|
||||
auto result =
|
||||
std::from_chars(ctx.args.data(),
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
volumePercent);
|
||||
if (result.ec != std::errc()) {
|
||||
ctx.reply("Please provide a valid number (0-100).");
|
||||
return;
|
||||
}
|
||||
|
||||
float volume = volumePercent / 100.0f;
|
||||
auto volResult = manager->setVolume(volume);
|
||||
if (!volResult) {
|
||||
ECHOION_LOG_ERROR(std::format("Volume command failed: {}", volResult.error().message));
|
||||
ctx.reply("Couldn't change volume. Please try again.");
|
||||
return;
|
||||
}
|
||||
if (volumePercent < 0 || volumePercent > 100) {
|
||||
ctx.reply("Volume must be between 0 and 100.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Visual volume indicator
|
||||
std::string indicator;
|
||||
int bars = volumePercent / 10;
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
indicator += (i < bars) ? "\xe2\x96\x88" : "\xe2\x96\x91"; // Full block / Light shade
|
||||
}
|
||||
|
||||
ctx.reply(std::format("Volume: {}% {}", volumePercent, indicator));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Volume command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
float volume = volumePercent / 100.0f;
|
||||
auto volResult = manager->setVolume(volume);
|
||||
if (!volResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Volume command failed: {}",
|
||||
volResult.error().message));
|
||||
ctx.reply("Couldn't change volume. Please try again.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Sets or shows the playback volume.";
|
||||
}
|
||||
// Visual volume indicator
|
||||
std::string indicator;
|
||||
int bars = volumePercent / 10;
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
indicator +=
|
||||
(i < bars)
|
||||
? "\xe2\x96\x88"
|
||||
: "\xe2\x96\x91"; // Full block / Light shade
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override {
|
||||
return "[0-100]";
|
||||
}
|
||||
ctx.reply(std::format(
|
||||
"Volume: {}% {}", volumePercent, indicator));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Volume command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override {
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Sets or shows the playback volume.";
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"vol", "v"};
|
||||
}
|
||||
};
|
||||
std::string_view getUsage() const override { return "[0-100]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"vol", "v"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
#include "Types.hpp"
|
||||
#include "echoion/core/state/StateVersions.hpp"
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Handles migration between state versions
|
||||
class StateMigration
|
||||
{
|
||||
public:
|
||||
|
||||
// Migrate from any old version to current
|
||||
static Api::Result<StateV1> migrate(uint32_t fromVersion,
|
||||
const std::string& jsonData);
|
||||
|
||||
// Specific migrations
|
||||
static StateV1 fromV0(const StateV0& v0);
|
||||
|
||||
// Check if migration path exists
|
||||
static bool canMigrate(uint32_t fromVersion);
|
||||
|
||||
private:
|
||||
|
||||
// Migration chain: V0 -> V1 -> V2 -> ...
|
||||
// Each version only knows how to migrate from previous
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
#include "StateBlob.hpp"
|
||||
#include "echoion/core/state/StateVersions.hpp"
|
||||
#include <Types.hpp>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class StateSerializer
|
||||
{
|
||||
public:
|
||||
|
||||
// Current version being used
|
||||
static constexpr uint32_t CURRENT_VERSION = 1;
|
||||
|
||||
// Serialize current state to opaque blob
|
||||
static Api::StateBlob serialize(const StateV1& state);
|
||||
|
||||
// Deserialize blob to current version (handles migration)
|
||||
static Api::Result<StateV1> deserialize(const Api::StateBlob& blob);
|
||||
|
||||
// Check if version is supported
|
||||
static bool isVersionSupported(uint32_t version);
|
||||
|
||||
// Get supported version range
|
||||
static uint32_t getMinimumSupportedVersion();
|
||||
static uint32_t getCurrentVersion();
|
||||
|
||||
private:
|
||||
|
||||
// Extract version from JSON blob
|
||||
static uint32_t extractVersion(const std::string& jsonStr);
|
||||
|
||||
// Helper to get current timestamp
|
||||
static std::string getCurrentTimestampISO8601();
|
||||
|
||||
// Make it accessible to StateMigration
|
||||
friend class StateMigration;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
#include "TrackTypes.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
using namespace Echoion::Api;
|
||||
|
||||
// State V0 - Initial version (placeholder for testing migration)
|
||||
struct StateV0 {
|
||||
std::vector<std::string> trackIds;
|
||||
float volume = 0.5f;
|
||||
};
|
||||
|
||||
// State V1 - Current version with full playback state
|
||||
struct StateV1 {
|
||||
// Playback state
|
||||
struct PlaybackState {
|
||||
TrackInfo currentTrack;
|
||||
int64_t positionMs = 0; // Use int64 for JSON compatibility
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
float volume = 0.5f;
|
||||
bool shuffle = false;
|
||||
bool repeat = false;
|
||||
};
|
||||
|
||||
// Queue entry with metadata
|
||||
struct QueueEntryState {
|
||||
TrackInfo track;
|
||||
uint64_t queueId = 0;
|
||||
std::string addedBy;
|
||||
std::string addedAt; // ISO 8601
|
||||
};
|
||||
|
||||
// Session state for RPC clients
|
||||
struct SessionState {
|
||||
uint64_t clientId = 0;
|
||||
std::string authToken;
|
||||
std::string lastActivity; // ISO 8601
|
||||
};
|
||||
|
||||
// Main state
|
||||
PlaybackState playback;
|
||||
bool hasPlayback =
|
||||
false; // Flag to indicate if playback state is valid
|
||||
std::vector<QueueEntryState> queue;
|
||||
std::vector<SessionState> sessions;
|
||||
|
||||
// Version info
|
||||
uint32_t version = 1;
|
||||
std::string savedAt; // ISO 8601
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
|
||||
// StateV0/StateV1 (and the nested PlaybackState/QueueEntryState/SessionState)
|
||||
// are plain reflectable aggregates whose member names are the desired JSON
|
||||
// keys, so Void::Json reflection serializes them with no annotations. The only
|
||||
// non-reflectable member is TrackInfo, which supplies its own
|
||||
// to_json()/from_json() in TrackTypes.hpp.
|
||||
+704
-570
File diff suppressed because it is too large.
Load diff
@@ -1,46 +0,0 @@
|
||||
#include "echoion/api/Cache.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
|
||||
namespace Echoion::Api {
|
||||
|
||||
CacheManager& CacheManager::instance() {
|
||||
static CacheManager instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void CacheManager::initialize() {
|
||||
ECHOION_LOG_INFO("CacheManager initialized");
|
||||
}
|
||||
|
||||
void CacheManager::shutdown() {
|
||||
clearAll();
|
||||
ECHOION_LOG_INFO("CacheManager shutdown");
|
||||
}
|
||||
|
||||
void CacheManager::purgeAllExpired() {
|
||||
size_t totalPurged = 0;
|
||||
totalPurged += httpCache_.purgeExpired();
|
||||
totalPurged += trackCache_.purgeExpired();
|
||||
totalPurged += metadataCache_.purgeExpired();
|
||||
|
||||
if (totalPurged > 0) {
|
||||
ECHOION_LOG_INFO(std::format("Purged {} expired cache entries", totalPurged));
|
||||
}
|
||||
}
|
||||
|
||||
void CacheManager::clearAll() {
|
||||
httpCache_.clear();
|
||||
trackCache_.clear();
|
||||
metadataCache_.clear();
|
||||
ECHOION_LOG_INFO("All caches cleared");
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, CacheStats> CacheManager::getAllStats() const {
|
||||
return {
|
||||
{"http", httpCache_.getStats()},
|
||||
{"track", trackCache_.getStats()},
|
||||
{"metadata", metadataCache_.getStats()}
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+478
-430
@@ -1,468 +1,516 @@
|
||||
#include "echoion/api/ConfigTypes.hpp"
|
||||
#include "echoion/core/CommandManager.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/commands/Command.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <algorithm>
|
||||
#include <echoion/core/commands/Commands.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// --- Internal Help Command ---
|
||||
class CommandManager::HelpCommand : public Command {
|
||||
CommandManager& manager_;
|
||||
// --- Internal Help Command ---
|
||||
class CommandManager::HelpCommand : public Command
|
||||
{
|
||||
CommandManager& manager_;
|
||||
|
||||
public:
|
||||
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override {
|
||||
try {
|
||||
auto prefix = manager_.getPrefix();
|
||||
|
||||
std::string helpMsg = std::format("\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
|
||||
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
|
||||
explicit HelpCommand(CommandManager& mgr) : manager_(mgr) {}
|
||||
|
||||
// Get commands visible to this client
|
||||
auto visibleCommands = manager_.getVisibleCommands(ctx.clientId);
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto prefix = manager_.getPrefix();
|
||||
|
||||
// Group commands by category
|
||||
std::map<CommandCategory, std::vector<std::pair<std::string, CommandPtr>>> grouped;
|
||||
|
||||
for (const auto& [name, cmd] : visibleCommands) {
|
||||
grouped[cmd->getCategory()].push_back({name, cmd});
|
||||
}
|
||||
std::string helpMsg = std::format(
|
||||
"\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
|
||||
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
|
||||
|
||||
for (const auto& [cat, cmds] : grouped) {
|
||||
helpMsg += std::format("**{} Commands**\n", toString(cat));
|
||||
// Get commands visible to this client
|
||||
auto visibleCommands =
|
||||
manager_.getVisibleCommands(ctx.clientId);
|
||||
|
||||
for (const auto& [name, cmd] : cmds) {
|
||||
// Format: prefix!command usage
|
||||
if (!cmd->getUsage().empty()) {
|
||||
helpMsg += std::format("`{}{}` {}\n", prefix, name, cmd->getUsage());
|
||||
} else {
|
||||
helpMsg += std::format("`{}{}`\n", prefix, name);
|
||||
}
|
||||
// Group commands by category
|
||||
std::map<CommandCategory,
|
||||
std::vector<std::pair<std::string, CommandPtr>>>
|
||||
grouped;
|
||||
|
||||
// Description
|
||||
helpMsg += std::format("> {}\n", cmd->getDescription());
|
||||
for (const auto& [name, cmd] : visibleCommands) {
|
||||
grouped[cmd->getCategory()].push_back({name, cmd});
|
||||
}
|
||||
|
||||
// Aliases
|
||||
auto aliases = cmd->getAliases();
|
||||
if (!aliases.empty()) {
|
||||
helpMsg += "> Aliases: ";
|
||||
for (size_t i = 0; i < aliases.size(); ++i) {
|
||||
helpMsg += std::format("`{}{}`", prefix, aliases[i]);
|
||||
if (i < aliases.size() - 1) {
|
||||
helpMsg += ", ";
|
||||
}
|
||||
}
|
||||
helpMsg += "\n";
|
||||
}
|
||||
for (const auto& [cat, cmds] : grouped) {
|
||||
helpMsg +=
|
||||
std::format("**{} Commands**\n", toString(cat));
|
||||
|
||||
helpMsg += "\n";
|
||||
}
|
||||
}
|
||||
for (const auto& [name, cmd] : cmds) {
|
||||
// Format: prefix!command usage
|
||||
if (!cmd->getUsage().empty()) {
|
||||
helpMsg += std::format("`{}{}` {}\n",
|
||||
prefix,
|
||||
name,
|
||||
cmd->getUsage());
|
||||
} else {
|
||||
helpMsg +=
|
||||
std::format("`{}{}`\n", prefix, name);
|
||||
}
|
||||
|
||||
ctx.reply(helpMsg);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Help command exception: {}", e.what()));
|
||||
ctx.reply("Couldn't generate help. Please try again.");
|
||||
}
|
||||
}
|
||||
// Description
|
||||
helpMsg +=
|
||||
std::format("> {}\n", cmd->getDescription());
|
||||
|
||||
std::string_view getDescription() const override {
|
||||
return "Shows this help message with all available commands.";
|
||||
}
|
||||
// Aliases
|
||||
auto aliases = cmd->getAliases();
|
||||
if (!aliases.empty()) {
|
||||
helpMsg += "> Aliases: ";
|
||||
for (size_t i = 0; i < aliases.size(); ++i) {
|
||||
helpMsg += std::format(
|
||||
"`{}{}`", prefix, aliases[i]);
|
||||
if (i < aliases.size() - 1) {
|
||||
helpMsg += ", ";
|
||||
}
|
||||
}
|
||||
helpMsg += "\n";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[command]"; }
|
||||
|
||||
CommandCategory getCategory() const override { return CommandCategory::Utility; }
|
||||
helpMsg += "\n";
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override {
|
||||
return {"h", "?", "commands"};
|
||||
}
|
||||
};
|
||||
ctx.reply(helpMsg);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Help command exception: {}", e.what()));
|
||||
ctx.reply("Couldn't generate help. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Manager Implementation ---
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows this help message with all available commands.";
|
||||
}
|
||||
|
||||
CommandManager::CommandManager() {
|
||||
registerBuiltinCommands();
|
||||
registerHelpCommand();
|
||||
startThreadPool();
|
||||
}
|
||||
std::string_view getUsage() const override { return "[command]"; }
|
||||
|
||||
CommandManager::~CommandManager() {
|
||||
shutdown();
|
||||
}
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"h", "?", "commands"};
|
||||
}
|
||||
};
|
||||
|
||||
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));
|
||||
}
|
||||
// --- Manager Implementation ---
|
||||
|
||||
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(
|
||||
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)
|
||||
? 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)
|
||||
? 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));
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to lowercase for lookup
|
||||
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 false;
|
||||
}
|
||||
command = it->second;
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
if (!canExecuteCommand(clientId, command)) {
|
||||
replyFunc("You don't have permission to use this command.");
|
||||
return true;
|
||||
}
|
||||
|
||||
CommandContext ctx{
|
||||
.clientId = clientId,
|
||||
.prefix = prefix_,
|
||||
.args = std::move(argsStr),
|
||||
.invokerName = invokerName,
|
||||
.musicManager = musicManager,
|
||||
.replyCallback = std::move(replyFunc)
|
||||
};
|
||||
|
||||
try {
|
||||
command->execute(ctx);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Command execution error [{}]: {}", cmdKey, e.what()));
|
||||
ctx.reply("An unexpected error occurred. Our team has been notified.");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CommandManager::hasCommand(std::string_view name) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return commands_.contains(std::string(name));
|
||||
}
|
||||
|
||||
std::optional<CommandPtr> CommandManager::getCommand(std::string_view name) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = commands_.find(std::string(name));
|
||||
if (it != commands_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getAllCommands() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<std::pair<std::string, CommandPtr>> result;
|
||||
result.reserve(uniqueCommands_.size());
|
||||
for (const auto& entry : uniqueCommands_) {
|
||||
result.emplace_back(entry.primaryName, entry.instance);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, CommandPtr>> CommandManager::getVisibleCommands(uint64_t clientId) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<std::pair<std::string, CommandPtr>> result;
|
||||
|
||||
for (const auto& entry : uniqueCommands_) {
|
||||
// Only include if client can execute it
|
||||
if (canExecuteCommand(clientId, entry.instance)) {
|
||||
result.emplace_back(entry.primaryName, entry.instance);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool CommandManager::canExecuteCommand(uint64_t clientId, const CommandPtr& cmd) const {
|
||||
if (!cmd->requiresAdmin()) {
|
||||
return true; // Non-admin commands are always allowed
|
||||
}
|
||||
|
||||
// If no server config is set, deny admin commands
|
||||
if (!serverConfig_.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If no admin groups configured, deny everyone
|
||||
if (serverConfig_->server.adminGroups.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check permission via callback if set
|
||||
if (permissionCheck_ && (cmd->requiresAdmin() ||
|
||||
cmd->getCategory() == CommandCategory::Admin)) {
|
||||
return permissionCheck_(clientId, cmd->getCategory());
|
||||
CommandManager::CommandManager()
|
||||
{
|
||||
registerBuiltinCommands();
|
||||
registerHelpCommand();
|
||||
startThreadPool();
|
||||
}
|
||||
|
||||
// Default: deny admin commands if no checker configured
|
||||
return false;
|
||||
}
|
||||
CommandManager::~CommandManager() { shutdown(); }
|
||||
|
||||
void CommandManager::setPrefix(std::string_view prefix) {
|
||||
prefix_ = prefix;
|
||||
}
|
||||
void CommandManager::shutdown()
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
shutdown_ = true;
|
||||
}
|
||||
queueCv_.notify_all();
|
||||
|
||||
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
permissionCheck_ = std::move(func);
|
||||
}
|
||||
for (auto& thread : workerThreads_) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
workerThreads_.clear();
|
||||
}
|
||||
|
||||
void CommandManager::setServerConfig(const Api::AppConfig& config) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
serverConfig_ = config;
|
||||
}
|
||||
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::registerBuiltinCommands() {
|
||||
registerCommand<PlayCommand>("play");
|
||||
registerCommand<SelectCommand>("select");
|
||||
registerCommand<PauseCommand>("pause");
|
||||
registerCommand<ResumeCommand>("resume");
|
||||
registerCommand<StopCommand>("stop");
|
||||
registerCommand<SkipCommand>("skip");
|
||||
// registerCommand<SeekCommand>("seek");
|
||||
registerCommand<VolumeCommand>("volume");
|
||||
registerCommand<QueueCommand>("queue");
|
||||
registerCommand<RemoveCommand>("remove");
|
||||
registerCommand<ClearCommand>("clear");
|
||||
registerCommand<MoveCommand>("move");
|
||||
registerCommand<ShuffleCommand>("shuffle");
|
||||
registerCommand<RepeatCommand>("repeat");
|
||||
registerCommand<PlaylistCommand>("playlist");
|
||||
registerCommand<NowPlayingCommand>("np");
|
||||
registerCommand<SearchCommand>("search");
|
||||
registerCommand<ReloadCommand>("reload");
|
||||
registerCommand<ReloadConfigCommand>("reloadconfig");
|
||||
registerCommand<SubscribeCommand>("subscribe");
|
||||
registerCommand<UnsubscribeCommand>("unsubscribe");
|
||||
registerCommand<SubscribersCommand>("subscribers");
|
||||
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
||||
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
||||
}
|
||||
void CommandManager::processCommandQueue()
|
||||
{
|
||||
while (true) {
|
||||
CommandTask task;
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
||||
queueCv_.wait(lock, [this] {
|
||||
return shutdown_ || !commandQueue_.empty();
|
||||
});
|
||||
|
||||
void CommandManager::registerHelpCommand() {
|
||||
auto helpCmd = std::make_shared<HelpCommand>(*this);
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
commands_["help"] = helpCmd;
|
||||
uniqueCommands_.push_back({"help", helpCmd});
|
||||
|
||||
for (auto alias : helpCmd->getAliases()) {
|
||||
commands_[std::string(alias)] = helpCmd;
|
||||
}
|
||||
}
|
||||
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(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)
|
||||
? 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)
|
||||
? 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));
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to lowercase for lookup
|
||||
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 false;
|
||||
}
|
||||
command = it->second;
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
if (!canExecuteCommand(clientId, command)) {
|
||||
replyFunc("You don't have permission to use this command.");
|
||||
return true;
|
||||
}
|
||||
|
||||
CommandContext ctx{.clientId = clientId,
|
||||
.prefix = prefix_,
|
||||
.args = std::move(argsStr),
|
||||
.invokerName = invokerName,
|
||||
.musicManager = musicManager,
|
||||
.replyCallback = std::move(replyFunc)};
|
||||
|
||||
try {
|
||||
command->execute(ctx);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Command execution error [{}]: {}", cmdKey, e.what()));
|
||||
ctx.reply(
|
||||
"An unexpected error occurred. Our team has been notified.");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CommandManager::hasCommand(std::string_view name) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return commands_.contains(std::string(name));
|
||||
}
|
||||
|
||||
std::optional<CommandPtr>
|
||||
CommandManager::getCommand(std::string_view name) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = commands_.find(std::string(name));
|
||||
if (it != commands_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, CommandPtr>>
|
||||
CommandManager::getAllCommands() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<std::pair<std::string, CommandPtr>> result;
|
||||
result.reserve(uniqueCommands_.size());
|
||||
for (const auto& entry : uniqueCommands_) {
|
||||
result.emplace_back(entry.primaryName, entry.instance);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, CommandPtr>>
|
||||
CommandManager::getVisibleCommands(uint64_t clientId) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::vector<std::pair<std::string, CommandPtr>> result;
|
||||
|
||||
for (const auto& entry : uniqueCommands_) {
|
||||
// Only include if client can execute it
|
||||
if (canExecuteCommand(clientId, entry.instance)) {
|
||||
result.emplace_back(entry.primaryName, entry.instance);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool CommandManager::canExecuteCommand(uint64_t clientId,
|
||||
const CommandPtr& cmd) const
|
||||
{
|
||||
if (!cmd->requiresAdmin()) {
|
||||
return true; // Non-admin commands are always allowed
|
||||
}
|
||||
|
||||
// If no server config is set, deny admin commands
|
||||
if (!serverConfig_.has_value()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If no admin groups configured, deny everyone
|
||||
if (serverConfig_->teamspeak.adminGroups.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check permission via callback if set
|
||||
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)
|
||||
{
|
||||
prefix_ = prefix;
|
||||
}
|
||||
|
||||
void CommandManager::setPermissionCheckFunc(PermissionCheckFunc func)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
permissionCheck_ = std::move(func);
|
||||
}
|
||||
|
||||
void CommandManager::setServerConfig(const Api::AppConfig& config)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
serverConfig_ = config;
|
||||
}
|
||||
|
||||
void CommandManager::registerBuiltinCommands()
|
||||
{
|
||||
registerCommand<PlayCommand>("play");
|
||||
registerCommand<SelectCommand>("select");
|
||||
registerCommand<PauseCommand>("pause");
|
||||
registerCommand<ResumeCommand>("resume");
|
||||
registerCommand<StopCommand>("stop");
|
||||
registerCommand<SkipCommand>("skip");
|
||||
// registerCommand<SeekCommand>("seek");
|
||||
registerCommand<VolumeCommand>("volume");
|
||||
registerCommand<QueueCommand>("queue");
|
||||
registerCommand<RemoveCommand>("remove");
|
||||
registerCommand<ClearCommand>("clear");
|
||||
registerCommand<MoveCommand>("move");
|
||||
registerCommand<ShuffleCommand>("shuffle");
|
||||
registerCommand<RepeatCommand>("repeat");
|
||||
registerCommand<PlaylistCommand>("playlist");
|
||||
registerCommand<NowPlayingCommand>("np");
|
||||
registerCommand<SearchCommand>("search");
|
||||
registerCommand<ReloadCommand>("reload");
|
||||
registerCommand<ReloadConfigCommand>("reloadconfig");
|
||||
registerCommand<SubscribeCommand>("subscribe");
|
||||
registerCommand<UnsubscribeCommand>("unsubscribe");
|
||||
registerCommand<SubscribersCommand>("subscribers");
|
||||
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
||||
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
||||
registerCommand<RpcInfoCommand>("rpc");
|
||||
}
|
||||
|
||||
void CommandManager::registerHelpCommand()
|
||||
{
|
||||
auto helpCmd = std::make_shared<HelpCommand>(*this);
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
commands_["help"] = helpCmd;
|
||||
uniqueCommands_.push_back({"help", helpCmd});
|
||||
|
||||
for (auto alias : helpCmd->getAliases()) {
|
||||
commands_[std::string(alias)] = helpCmd;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+424
-369
@@ -1,378 +1,433 @@
|
||||
#include "LoggerInterface.hpp"
|
||||
#include "Types.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include "echoion/api/AudioTypes.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <fstream>
|
||||
#include <AudioTypes.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core {
|
||||
// NOTE: The Echoion::Core::*Json mirror structs are plain reflectable
|
||||
// aggregates whose member names are exactly the desired JSON keys, so
|
||||
// Void::Json reflection (Json::to_json / Json::from_json) produces the same
|
||||
// document the former glz::meta specializations did — no annotations needed.
|
||||
|
||||
// JSON structures for configuration
|
||||
struct BotConfigJson {
|
||||
std::string botName = "Echoion";
|
||||
std::string commandPrefix = "!";
|
||||
float defaultVolume = 0.5f;
|
||||
bool autoReconnect = true;
|
||||
uint32_t reconnectDelay = 5000;
|
||||
uint32_t maxReconnectAttempts = 5;
|
||||
std::optional<std::string> proxyHost;
|
||||
std::optional<uint16_t> proxyPort;
|
||||
std::optional<std::string> proxyUsername;
|
||||
std::optional<std::string> proxyPassword;
|
||||
std::optional<std::string> proxyType;
|
||||
std::optional<std::string> youtubeApiKey;
|
||||
std::string preferredQuality = "High";
|
||||
bool allowPlaylistImports = true;
|
||||
uint32_t maxQueueSize = 100;
|
||||
uint32_t trackTimeout = 30000;
|
||||
std::optional<std::string> youtubeCookiesPath;
|
||||
std::optional<std::string> cookiesFromBrowser;
|
||||
uint32_t ytDlpMaxConcurrent = 4;
|
||||
bool ytDlpAsyncEnabled = true;
|
||||
bool enableUrlShortening = true;
|
||||
};
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
struct ServerConfigJson {
|
||||
std::string address;
|
||||
uint16_t port = 9987;
|
||||
std::string serverPassword = "";
|
||||
std::string nickname = "EchoionBot";
|
||||
std::optional<std::string> defaultChannelId;
|
||||
std::optional<std::string> channelPassword;
|
||||
std::vector<uint64_t> adminGroups;
|
||||
std::vector<uint64_t> djGroups;
|
||||
std::vector<uint64_t> bannedGroups;
|
||||
};
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromFile(const std::filesystem::path& path)
|
||||
{
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}",
|
||||
path.string())));
|
||||
}
|
||||
|
||||
struct SecurityConfigJson {
|
||||
bool requireAuthForAdmin = true;
|
||||
uint32_t maxLoginAttempts = 5;
|
||||
uint32_t lockoutDuration = 300000;
|
||||
uint32_t sessionTimeout = 3600000;
|
||||
bool enableAuditLog = true;
|
||||
};
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to open configuration file: {}",
|
||||
path.string())));
|
||||
}
|
||||
|
||||
struct AppConfigJson {
|
||||
BotConfigJson bot;
|
||||
ServerConfigJson server;
|
||||
SecurityConfigJson security;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
|
||||
// Glaze metadata for JSON serialization
|
||||
template<> struct glz::meta<Echoion::Core::BotConfigJson> {
|
||||
using T = Echoion::Core::BotConfigJson;
|
||||
static constexpr auto value = object(
|
||||
"botName", &T::botName,
|
||||
"commandPrefix", &T::commandPrefix,
|
||||
"defaultVolume", &T::defaultVolume,
|
||||
"autoReconnect", &T::autoReconnect,
|
||||
"reconnectDelay", &T::reconnectDelay,
|
||||
"maxReconnectAttempts", &T::maxReconnectAttempts,
|
||||
"proxyHost", &T::proxyHost,
|
||||
"proxyPort", &T::proxyPort,
|
||||
"proxyUsername", &T::proxyUsername,
|
||||
"proxyPassword", &T::proxyPassword,
|
||||
"proxyType", &T::proxyType,
|
||||
"youtubeApiKey", &T::youtubeApiKey,
|
||||
"preferredQuality", &T::preferredQuality,
|
||||
"allowPlaylistImports", &T::allowPlaylistImports,
|
||||
"maxQueueSize", &T::maxQueueSize,
|
||||
"trackTimeout", &T::trackTimeout,
|
||||
"youtubeCookiesPath", &T::youtubeCookiesPath,
|
||||
"cookiesFromBrowser", &T::cookiesFromBrowser,
|
||||
"ytDlpMaxConcurrent", &T::ytDlpMaxConcurrent,
|
||||
"ytDlpAsyncEnabled", &T::ytDlpAsyncEnabled,
|
||||
"enableUrlShortening", &T::enableUrlShortening
|
||||
);
|
||||
};
|
||||
|
||||
template<> struct glz::meta<Echoion::Core::ServerConfigJson> {
|
||||
using T = Echoion::Core::ServerConfigJson;
|
||||
static constexpr auto value = object(
|
||||
"address", &T::address,
|
||||
"port", &T::port,
|
||||
"serverPassword", &T::serverPassword,
|
||||
"nickname", &T::nickname,
|
||||
"defaultChannelId", &T::defaultChannelId,
|
||||
"channelPassword", &T::channelPassword,
|
||||
"adminGroups", &T::adminGroups,
|
||||
"djGroups", &T::djGroups,
|
||||
"bannedGroups", &T::bannedGroups
|
||||
);
|
||||
};
|
||||
|
||||
template<> struct glz::meta<Echoion::Core::SecurityConfigJson> {
|
||||
using T = Echoion::Core::SecurityConfigJson;
|
||||
static constexpr auto value = object(
|
||||
"requireAuthForAdmin", &T::requireAuthForAdmin,
|
||||
"maxLoginAttempts", &T::maxLoginAttempts,
|
||||
"lockoutDuration", &T::lockoutDuration,
|
||||
"sessionTimeout", &T::sessionTimeout,
|
||||
"enableAuditLog", &T::enableAuditLog
|
||||
);
|
||||
};
|
||||
|
||||
template<> struct glz::meta<Echoion::Core::AppConfigJson> {
|
||||
using T = Echoion::Core::AppConfigJson;
|
||||
static constexpr auto value = object(
|
||||
"bot", &T::bot,
|
||||
"server", &T::server,
|
||||
"security", &T::security
|
||||
);
|
||||
};
|
||||
|
||||
namespace Echoion::Core {
|
||||
|
||||
Api::Result<Api::AppConfig> ConfigLoader::loadFromFile(const std::filesystem::path& path) {
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}", path.string())));
|
||||
}
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to open configuration file: {}", path.string())));
|
||||
}
|
||||
|
||||
std::string content((std::istreambuf_iterator<char>(file)),
|
||||
std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
AppConfigJson jsonConfig;
|
||||
auto ec = glz::read_json(jsonConfig, content);
|
||||
if (ec) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("Failed to parse configuration: {}", glz::format_error(ec, content))));
|
||||
}
|
||||
|
||||
// Convert to API config
|
||||
Api::AppConfig config;
|
||||
|
||||
// Bot config
|
||||
config.bot.botName = jsonConfig.bot.botName;
|
||||
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
|
||||
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
|
||||
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
|
||||
config.bot.reconnectDelay = std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
|
||||
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
|
||||
config.bot.preferredQuality = parseQuality(jsonConfig.bot.preferredQuality);
|
||||
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
|
||||
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
|
||||
|
||||
// Proxy config
|
||||
if (jsonConfig.bot.proxyHost.has_value() && jsonConfig.bot.proxyPort.has_value()) {
|
||||
Api::ProxyConfig proxy;
|
||||
proxy.host = *jsonConfig.bot.proxyHost;
|
||||
proxy.port = *jsonConfig.bot.proxyPort;
|
||||
proxy.username = jsonConfig.bot.proxyUsername;
|
||||
proxy.password = jsonConfig.bot.proxyPassword;
|
||||
// Parse proxy type (default to HTTP)
|
||||
if (jsonConfig.bot.proxyType.has_value()) {
|
||||
const auto& typeStr = *jsonConfig.bot.proxyType;
|
||||
if (typeStr == "SOCKS5" || typeStr == "socks5") {
|
||||
proxy.type = Api::ProxyType::SOCKS5;
|
||||
} else {
|
||||
proxy.type = Api::ProxyType::HTTP;
|
||||
}
|
||||
} else {
|
||||
proxy.type = Api::ProxyType::HTTP;
|
||||
}
|
||||
config.bot.proxy = proxy;
|
||||
}
|
||||
|
||||
// YouTube API key
|
||||
if (jsonConfig.bot.youtubeApiKey.has_value()) {
|
||||
config.bot.youtubeApiKey = jsonConfig.bot.youtubeApiKey;
|
||||
}
|
||||
|
||||
// YouTube cookies
|
||||
if (jsonConfig.bot.youtubeCookiesPath.has_value()) {
|
||||
config.bot.youtubeCookiesPath = jsonConfig.bot.youtubeCookiesPath;
|
||||
}
|
||||
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;
|
||||
config.server.port = jsonConfig.server.port;
|
||||
config.server.serverPassword = jsonConfig.server.serverPassword;
|
||||
config.server.nickname = jsonConfig.server.nickname;
|
||||
config.server.defaultChannelId = jsonConfig.server.defaultChannelId;
|
||||
config.server.channelPassword = jsonConfig.server.channelPassword;
|
||||
config.server.adminGroups = jsonConfig.server.adminGroups;
|
||||
config.server.djGroups = jsonConfig.server.djGroups;
|
||||
config.server.bannedGroups = jsonConfig.server.bannedGroups;
|
||||
|
||||
// Security config
|
||||
config.security.requireAuthForAdmin = jsonConfig.security.requireAuthForAdmin;
|
||||
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
|
||||
config.security.lockoutDuration = std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
|
||||
config.security.sessionTimeout = std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
|
||||
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Configuration loaded from {}", path.string()));
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::Result<void> ConfigLoader::saveToFile(const std::filesystem::path& path, const Api::AppConfig& config) {
|
||||
AppConfigJson jsonConfig;
|
||||
|
||||
// Bot config
|
||||
jsonConfig.bot.botName = config.bot.botName;
|
||||
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
|
||||
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
|
||||
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
|
||||
jsonConfig.bot.reconnectDelay = static_cast<uint32_t>(config.bot.reconnectDelay.count());
|
||||
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
|
||||
jsonConfig.bot.preferredQuality = qualityToString(config.bot.preferredQuality);
|
||||
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
|
||||
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
|
||||
jsonConfig.bot.trackTimeout = static_cast<uint32_t>(config.bot.trackTimeout.count());
|
||||
|
||||
// Proxy config
|
||||
if (config.bot.proxy.has_value()) {
|
||||
jsonConfig.bot.proxyHost = config.bot.proxy->host;
|
||||
jsonConfig.bot.proxyPort = config.bot.proxy->port;
|
||||
jsonConfig.bot.proxyUsername = config.bot.proxy->username;
|
||||
jsonConfig.bot.proxyPassword = config.bot.proxy->password;
|
||||
jsonConfig.bot.proxyType = config.bot.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5" : "HTTP";
|
||||
}
|
||||
|
||||
// YouTube API key
|
||||
if (config.bot.youtubeApiKey.has_value()) {
|
||||
jsonConfig.bot.youtubeApiKey = *config.bot.youtubeApiKey;
|
||||
}
|
||||
|
||||
// YouTube cookies
|
||||
if (config.bot.youtubeCookiesPath.has_value()) {
|
||||
jsonConfig.bot.youtubeCookiesPath = *config.bot.youtubeCookiesPath;
|
||||
}
|
||||
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;
|
||||
jsonConfig.server.port = config.server.port;
|
||||
jsonConfig.server.serverPassword = config.server.serverPassword;
|
||||
jsonConfig.server.nickname = config.server.nickname;
|
||||
jsonConfig.server.defaultChannelId = config.server.defaultChannelId;
|
||||
jsonConfig.server.channelPassword = config.server.channelPassword;
|
||||
jsonConfig.server.adminGroups = config.server.adminGroups;
|
||||
jsonConfig.server.djGroups = config.server.djGroups;
|
||||
jsonConfig.server.bannedGroups = config.server.bannedGroups;
|
||||
|
||||
// Security config
|
||||
jsonConfig.security.requireAuthForAdmin = config.security.requireAuthForAdmin;
|
||||
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
|
||||
jsonConfig.security.lockoutDuration = static_cast<uint32_t>(config.security.lockoutDuration.count());
|
||||
jsonConfig.security.sessionTimeout = static_cast<uint32_t>(config.security.sessionTimeout.count());
|
||||
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
|
||||
|
||||
auto json = glz::write_json(jsonConfig);
|
||||
if (!json.has_value())
|
||||
{
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ParseError,
|
||||
std::format("Failed to serialize: {}", json.error().custom_error_message)));
|
||||
}
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}", path.string())));
|
||||
}
|
||||
|
||||
file << json.value();
|
||||
file.close();
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Configuration saved to {}", path.string()));
|
||||
return {};
|
||||
}
|
||||
|
||||
std::filesystem::path ConfigLoader::getDefaultConfigPath() {
|
||||
// Try to get config path from environment or use default
|
||||
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
||||
if (configHome) {
|
||||
return std::filesystem::path(configHome) / "echoion" / "config.json";
|
||||
}
|
||||
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home) {
|
||||
return std::filesystem::path(home) / ".config" / "echoion" / "config.json";
|
||||
}
|
||||
|
||||
// Fallback to current directory
|
||||
return "echoion_config.json";
|
||||
}
|
||||
|
||||
Api::AppConfig ConfigLoader::createDefaultConfig() {
|
||||
Api::AppConfig config;
|
||||
|
||||
// Default bot config
|
||||
config.bot.botName = "Echoion";
|
||||
config.bot.commandPrefix = "!";
|
||||
config.bot.defaultVolume = 0.5f;
|
||||
config.bot.autoReconnect = true;
|
||||
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
|
||||
config.bot.maxReconnectAttempts = 5;
|
||||
config.bot.preferredQuality = Api::AudioQuality::High;
|
||||
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";
|
||||
config.server.port = 9987;
|
||||
config.server.nickname = "EchoionBot";
|
||||
|
||||
// Default security config
|
||||
config.security.requireAuthForAdmin = true;
|
||||
config.security.maxLoginAttempts = 5;
|
||||
config.security.lockoutDuration = std::chrono::milliseconds(300000);
|
||||
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
|
||||
config.security.enableAuditLog = true;
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str) {
|
||||
if (str == "Low") return Api::AudioQuality::Low;
|
||||
if (str == "Medium") return Api::AudioQuality::Medium;
|
||||
if (str == "High") return Api::AudioQuality::High;
|
||||
if (str == "VeryHigh") return Api::AudioQuality::VeryHigh;
|
||||
if (str == "Lossless") return Api::AudioQuality::Lossless;
|
||||
return Api::AudioQuality::High; // Default
|
||||
}
|
||||
|
||||
std::string ConfigLoader::qualityToString(Api::AudioQuality quality) {
|
||||
switch (quality) {
|
||||
case Api::AudioQuality::Low: return "Low";
|
||||
case Api::AudioQuality::Medium: return "Medium";
|
||||
case Api::AudioQuality::High: return "High";
|
||||
case Api::AudioQuality::VeryHigh: return "VeryHigh";
|
||||
case Api::AudioQuality::Lossless: return "Lossless";
|
||||
default: return "High";
|
||||
}
|
||||
}
|
||||
std::string content((std::istreambuf_iterator<char>(file)),
|
||||
std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
auto parsed = Void::Json::parse(content);
|
||||
if (!parsed) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("Failed to parse configuration ({}:{}): {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message)));
|
||||
}
|
||||
|
||||
// Tolerant deserialization: unknown JSON fields are ignored and missing
|
||||
// fields keep their default-initialized values (matches the former
|
||||
// glz::opts{error_on_unknown_keys=false, error_on_missing_keys=false}).
|
||||
auto jsonResult = Void::Json::from_json<AppConfigJson>(*parsed);
|
||||
if (!jsonResult) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("Failed to parse configuration: field '{}': {}",
|
||||
jsonResult.error().field,
|
||||
jsonResult.error().message)));
|
||||
}
|
||||
AppConfigJson jsonConfig = std::move(*jsonResult);
|
||||
|
||||
// Convert to API config
|
||||
Api::AppConfig config;
|
||||
|
||||
// Bot config
|
||||
config.bot.botName = jsonConfig.bot.botName;
|
||||
config.bot.commandPrefix = jsonConfig.bot.commandPrefix;
|
||||
config.bot.defaultVolume = jsonConfig.bot.defaultVolume;
|
||||
config.bot.maxQueueSize = jsonConfig.bot.maxQueueSize;
|
||||
config.bot.trackTimeout =
|
||||
std::chrono::milliseconds(jsonConfig.bot.trackTimeout);
|
||||
config.bot.autoReconnect = jsonConfig.bot.autoReconnect;
|
||||
config.bot.reconnectDelay =
|
||||
std::chrono::milliseconds(jsonConfig.bot.reconnectDelay);
|
||||
config.bot.maxReconnectAttempts = jsonConfig.bot.maxReconnectAttempts;
|
||||
config.bot.preferredQuality =
|
||||
parseQuality(jsonConfig.bot.preferredQuality);
|
||||
config.bot.allowPlaylistImports = jsonConfig.bot.allowPlaylistImports;
|
||||
|
||||
// YouTube config
|
||||
if (jsonConfig.youtube.youtubeApiKey.has_value()) {
|
||||
config.youtube.youtubeApiKey = jsonConfig.youtube.youtubeApiKey;
|
||||
}
|
||||
if (jsonConfig.youtube.youtubeCookiesPath.has_value()) {
|
||||
config.youtube.youtubeCookiesPath =
|
||||
jsonConfig.youtube.youtubeCookiesPath;
|
||||
}
|
||||
if (jsonConfig.youtube.cookiesFromBrowser.has_value()) {
|
||||
config.youtube.cookiesFromBrowser =
|
||||
jsonConfig.youtube.cookiesFromBrowser;
|
||||
}
|
||||
config.youtube.ytDlpMaxConcurrent =
|
||||
std::min(static_cast<size_t>(jsonConfig.youtube.ytDlpMaxConcurrent),
|
||||
size_t(8));
|
||||
config.youtube.ytDlpAsyncEnabled = jsonConfig.youtube.ytDlpAsyncEnabled;
|
||||
config.youtube.enableUrlShortening =
|
||||
jsonConfig.youtube.enableUrlShortening;
|
||||
|
||||
// Network config
|
||||
if (jsonConfig.network.proxyHost.has_value() &&
|
||||
jsonConfig.network.proxyPort.has_value()) {
|
||||
Api::ProxyConfig proxy;
|
||||
proxy.host = *jsonConfig.network.proxyHost;
|
||||
proxy.port = *jsonConfig.network.proxyPort;
|
||||
proxy.username = jsonConfig.network.proxyUsername;
|
||||
proxy.password = jsonConfig.network.proxyPassword;
|
||||
const auto& typeStr = jsonConfig.network.proxyType;
|
||||
if (typeStr == "SOCKS5" || typeStr == "socks5") {
|
||||
proxy.type = Api::ProxyType::SOCKS5;
|
||||
} else {
|
||||
proxy.type = Api::ProxyType::HTTP;
|
||||
}
|
||||
config.network.proxy = proxy;
|
||||
}
|
||||
config.network.rpcEnabled = jsonConfig.network.rpcEnabled;
|
||||
config.network.rpcPort = jsonConfig.network.rpcPort;
|
||||
config.network.rpcBindAddress = jsonConfig.network.rpcBindAddress;
|
||||
|
||||
// TeamSpeak config
|
||||
config.teamspeak.address = jsonConfig.teamspeak.address;
|
||||
config.teamspeak.port = jsonConfig.teamspeak.port;
|
||||
config.teamspeak.serverPassword = jsonConfig.teamspeak.serverPassword;
|
||||
config.teamspeak.nickname = jsonConfig.teamspeak.nickname;
|
||||
config.teamspeak.defaultChannelId =
|
||||
jsonConfig.teamspeak.defaultChannelId;
|
||||
config.teamspeak.channelPassword = jsonConfig.teamspeak.channelPassword;
|
||||
config.teamspeak.adminGroups = jsonConfig.teamspeak.adminGroups;
|
||||
config.teamspeak.djGroups = jsonConfig.teamspeak.djGroups;
|
||||
config.teamspeak.bannedGroups = jsonConfig.teamspeak.bannedGroups;
|
||||
|
||||
// Security config
|
||||
config.security.requireAuthForAdmin =
|
||||
jsonConfig.security.requireAuthForAdmin;
|
||||
config.security.maxLoginAttempts = jsonConfig.security.maxLoginAttempts;
|
||||
config.security.lockoutDuration =
|
||||
std::chrono::milliseconds(jsonConfig.security.lockoutDuration);
|
||||
config.security.sessionTimeout =
|
||||
std::chrono::milliseconds(jsonConfig.security.sessionTimeout);
|
||||
config.security.enableAuditLog = jsonConfig.security.enableAuditLog;
|
||||
if (jsonConfig.security.apiKey.has_value()) {
|
||||
config.security.apiKey = jsonConfig.security.apiKey;
|
||||
}
|
||||
config.security.allowCors = jsonConfig.security.allowCors;
|
||||
config.security.corsOrigins = jsonConfig.security.corsOrigins;
|
||||
|
||||
// Features config
|
||||
config.features.enableHotReload = jsonConfig.features.enableHotReload;
|
||||
config.features.enableAutoReload = jsonConfig.features.enableAutoReload;
|
||||
config.features.enableAutoUpdateCheck =
|
||||
jsonConfig.features.enableAutoUpdateCheck;
|
||||
config.features.autoStartOnSubscribe =
|
||||
jsonConfig.features.autoStartOnSubscribe;
|
||||
config.features.pauseOnEmptySubscribers =
|
||||
jsonConfig.features.pauseOnEmptySubscribers;
|
||||
config.features.resumeOnSubscriberReturn =
|
||||
jsonConfig.features.resumeOnSubscriberReturn;
|
||||
config.features.shuffleMode = jsonConfig.features.shuffleMode;
|
||||
config.features.repeatMode = jsonConfig.features.repeatMode;
|
||||
config.features.maxHistorySize = jsonConfig.features.maxHistorySize;
|
||||
|
||||
// Advanced config
|
||||
config.advanced.sampleRate = jsonConfig.advanced.sampleRate;
|
||||
config.advanced.channels = jsonConfig.advanced.channels;
|
||||
config.advanced.bufferSize = jsonConfig.advanced.bufferSize;
|
||||
config.advanced.commandThreadPoolSize =
|
||||
jsonConfig.advanced.commandThreadPoolSize;
|
||||
config.advanced.networkThreadPoolSize =
|
||||
jsonConfig.advanced.networkThreadPoolSize;
|
||||
config.advanced.decoderThreads = jsonConfig.advanced.decoderThreads;
|
||||
config.advanced.cacheEnabled = jsonConfig.advanced.cacheEnabled;
|
||||
config.advanced.cacheMaxSize = jsonConfig.advanced.cacheMaxSize;
|
||||
config.advanced.cacheTTL = jsonConfig.advanced.cacheTTL;
|
||||
config.advanced.tempCleanupInterval =
|
||||
jsonConfig.advanced.tempCleanupInterval;
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< std::endl;
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
ConfigLoader::saveToFile(const std::filesystem::path& path,
|
||||
const Api::AppConfig& config)
|
||||
{
|
||||
AppConfigJson jsonConfig;
|
||||
|
||||
// Bot config
|
||||
jsonConfig.bot.botName = config.bot.botName;
|
||||
jsonConfig.bot.commandPrefix = config.bot.commandPrefix;
|
||||
jsonConfig.bot.defaultVolume = config.bot.defaultVolume;
|
||||
jsonConfig.bot.maxQueueSize = config.bot.maxQueueSize;
|
||||
jsonConfig.bot.trackTimeout =
|
||||
static_cast<uint32_t>(config.bot.trackTimeout.count());
|
||||
jsonConfig.bot.autoReconnect = config.bot.autoReconnect;
|
||||
jsonConfig.bot.reconnectDelay =
|
||||
static_cast<uint32_t>(config.bot.reconnectDelay.count());
|
||||
jsonConfig.bot.maxReconnectAttempts = config.bot.maxReconnectAttempts;
|
||||
jsonConfig.bot.preferredQuality =
|
||||
qualityToString(config.bot.preferredQuality);
|
||||
jsonConfig.bot.allowPlaylistImports = config.bot.allowPlaylistImports;
|
||||
|
||||
// YouTube config
|
||||
if (config.youtube.youtubeApiKey.has_value()) {
|
||||
jsonConfig.youtube.youtubeApiKey = *config.youtube.youtubeApiKey;
|
||||
}
|
||||
if (config.youtube.youtubeCookiesPath.has_value()) {
|
||||
jsonConfig.youtube.youtubeCookiesPath =
|
||||
*config.youtube.youtubeCookiesPath;
|
||||
}
|
||||
if (config.youtube.cookiesFromBrowser.has_value()) {
|
||||
jsonConfig.youtube.cookiesFromBrowser =
|
||||
*config.youtube.cookiesFromBrowser;
|
||||
}
|
||||
jsonConfig.youtube.ytDlpMaxConcurrent =
|
||||
static_cast<uint32_t>(config.youtube.ytDlpMaxConcurrent);
|
||||
jsonConfig.youtube.ytDlpAsyncEnabled = config.youtube.ytDlpAsyncEnabled;
|
||||
jsonConfig.youtube.enableUrlShortening =
|
||||
config.youtube.enableUrlShortening;
|
||||
|
||||
// Network config
|
||||
if (config.network.proxy.has_value()) {
|
||||
jsonConfig.network.proxyHost = config.network.proxy->host;
|
||||
jsonConfig.network.proxyPort = config.network.proxy->port;
|
||||
jsonConfig.network.proxyUsername = config.network.proxy->username;
|
||||
jsonConfig.network.proxyPassword = config.network.proxy->password;
|
||||
jsonConfig.network.proxyType =
|
||||
config.network.proxy->type == Api::ProxyType::SOCKS5 ? "SOCKS5"
|
||||
: "HTTP";
|
||||
}
|
||||
jsonConfig.network.rpcEnabled = config.network.rpcEnabled;
|
||||
jsonConfig.network.rpcPort = config.network.rpcPort;
|
||||
jsonConfig.network.rpcBindAddress = config.network.rpcBindAddress;
|
||||
|
||||
// TeamSpeak config
|
||||
jsonConfig.teamspeak.address = config.teamspeak.address;
|
||||
jsonConfig.teamspeak.port = config.teamspeak.port;
|
||||
jsonConfig.teamspeak.serverPassword = config.teamspeak.serverPassword;
|
||||
jsonConfig.teamspeak.nickname = config.teamspeak.nickname;
|
||||
jsonConfig.teamspeak.defaultChannelId =
|
||||
config.teamspeak.defaultChannelId;
|
||||
jsonConfig.teamspeak.channelPassword = config.teamspeak.channelPassword;
|
||||
jsonConfig.teamspeak.adminGroups = config.teamspeak.adminGroups;
|
||||
jsonConfig.teamspeak.djGroups = config.teamspeak.djGroups;
|
||||
jsonConfig.teamspeak.bannedGroups = config.teamspeak.bannedGroups;
|
||||
|
||||
// Security config
|
||||
jsonConfig.security.requireAuthForAdmin =
|
||||
config.security.requireAuthForAdmin;
|
||||
jsonConfig.security.maxLoginAttempts = config.security.maxLoginAttempts;
|
||||
jsonConfig.security.lockoutDuration =
|
||||
static_cast<uint32_t>(config.security.lockoutDuration.count());
|
||||
jsonConfig.security.sessionTimeout =
|
||||
static_cast<uint32_t>(config.security.sessionTimeout.count());
|
||||
jsonConfig.security.enableAuditLog = config.security.enableAuditLog;
|
||||
if (config.security.apiKey.has_value()) {
|
||||
jsonConfig.security.apiKey = *config.security.apiKey;
|
||||
}
|
||||
jsonConfig.security.allowCors = config.security.allowCors;
|
||||
jsonConfig.security.corsOrigins = config.security.corsOrigins;
|
||||
|
||||
// Features config
|
||||
jsonConfig.features.enableHotReload = config.features.enableHotReload;
|
||||
jsonConfig.features.enableAutoReload = config.features.enableAutoReload;
|
||||
jsonConfig.features.enableAutoUpdateCheck =
|
||||
config.features.enableAutoUpdateCheck;
|
||||
jsonConfig.features.autoStartOnSubscribe =
|
||||
config.features.autoStartOnSubscribe;
|
||||
jsonConfig.features.pauseOnEmptySubscribers =
|
||||
config.features.pauseOnEmptySubscribers;
|
||||
jsonConfig.features.resumeOnSubscriberReturn =
|
||||
config.features.resumeOnSubscriberReturn;
|
||||
jsonConfig.features.shuffleMode = config.features.shuffleMode;
|
||||
jsonConfig.features.repeatMode = config.features.repeatMode;
|
||||
jsonConfig.features.maxHistorySize = config.features.maxHistorySize;
|
||||
|
||||
// Advanced config
|
||||
jsonConfig.advanced.sampleRate = config.advanced.sampleRate;
|
||||
jsonConfig.advanced.channels = config.advanced.channels;
|
||||
jsonConfig.advanced.bufferSize = config.advanced.bufferSize;
|
||||
jsonConfig.advanced.commandThreadPoolSize =
|
||||
config.advanced.commandThreadPoolSize;
|
||||
jsonConfig.advanced.networkThreadPoolSize =
|
||||
config.advanced.networkThreadPoolSize;
|
||||
jsonConfig.advanced.decoderThreads = config.advanced.decoderThreads;
|
||||
jsonConfig.advanced.cacheEnabled = config.advanced.cacheEnabled;
|
||||
jsonConfig.advanced.cacheMaxSize = config.advanced.cacheMaxSize;
|
||||
jsonConfig.advanced.cacheTTL = config.advanced.cacheTTL;
|
||||
jsonConfig.advanced.tempCleanupInterval =
|
||||
config.advanced.tempCleanupInterval;
|
||||
|
||||
const std::string json = Void::Json::serialize(
|
||||
Void::Json::to_json(jsonConfig), {.pretty = true});
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}",
|
||||
path.string())));
|
||||
}
|
||||
|
||||
file << json;
|
||||
file.close();
|
||||
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("Configuration saved to {}", path.string()));
|
||||
return {};
|
||||
}
|
||||
|
||||
std::filesystem::path ConfigLoader::getDefaultConfigPath()
|
||||
{
|
||||
// Try to get config path from environment or use default
|
||||
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
||||
if (configHome) {
|
||||
return std::filesystem::path(configHome) / "echoion" /
|
||||
"config.json";
|
||||
}
|
||||
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home) {
|
||||
return std::filesystem::path(home) / ".config" / "echoion" /
|
||||
"config.json";
|
||||
}
|
||||
|
||||
// Fallback to current directory
|
||||
return "echoion_config.json";
|
||||
}
|
||||
|
||||
Api::AppConfig ConfigLoader::createDefaultConfig()
|
||||
{
|
||||
Api::AppConfig config;
|
||||
|
||||
// Default bot config
|
||||
config.bot.botName = "Echoion";
|
||||
config.bot.commandPrefix = "!";
|
||||
config.bot.defaultVolume = 0.5f;
|
||||
config.bot.maxQueueSize = 100;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(30000);
|
||||
config.bot.autoReconnect = true;
|
||||
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
|
||||
config.bot.maxReconnectAttempts = 5;
|
||||
config.bot.preferredQuality = Api::AudioQuality::High;
|
||||
config.bot.allowPlaylistImports = true;
|
||||
|
||||
// Default YouTube config
|
||||
config.youtube.ytDlpMaxConcurrent = 4;
|
||||
config.youtube.ytDlpAsyncEnabled = true;
|
||||
config.youtube.enableUrlShortening = true;
|
||||
|
||||
// Default network config
|
||||
config.network.rpcEnabled = true;
|
||||
config.network.rpcPort = 8765;
|
||||
config.network.rpcBindAddress = "127.0.0.1";
|
||||
|
||||
// Default TeamSpeak config
|
||||
config.teamspeak.address = "localhost";
|
||||
config.teamspeak.port = 9987;
|
||||
config.teamspeak.nickname = "EchoionBot";
|
||||
|
||||
// Default security config
|
||||
config.security.requireAuthForAdmin = true;
|
||||
config.security.maxLoginAttempts = 5;
|
||||
config.security.lockoutDuration = std::chrono::milliseconds(300000);
|
||||
config.security.sessionTimeout = std::chrono::milliseconds(3600000);
|
||||
config.security.enableAuditLog = true;
|
||||
config.security.allowCors = false;
|
||||
|
||||
// Default features config
|
||||
config.features.enableHotReload = true;
|
||||
config.features.enableAutoReload = false;
|
||||
config.features.enableAutoUpdateCheck = true;
|
||||
config.features.autoStartOnSubscribe = true;
|
||||
config.features.pauseOnEmptySubscribers = true;
|
||||
config.features.resumeOnSubscriberReturn = true;
|
||||
config.features.shuffleMode = "random";
|
||||
config.features.repeatMode = "off";
|
||||
config.features.maxHistorySize = 50;
|
||||
|
||||
// Default advanced config
|
||||
config.advanced.sampleRate = 192000;
|
||||
config.advanced.channels = 2;
|
||||
config.advanced.bufferSize = 7680;
|
||||
config.advanced.commandThreadPoolSize = 4;
|
||||
config.advanced.networkThreadPoolSize = 4;
|
||||
config.advanced.decoderThreads = 2;
|
||||
config.advanced.cacheEnabled = true;
|
||||
config.advanced.cacheMaxSize = "1GB";
|
||||
config.advanced.cacheTTL = 86400;
|
||||
config.advanced.tempCleanupInterval = 3600;
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::AudioQuality ConfigLoader::parseQuality(const std::string& str)
|
||||
{
|
||||
if (str == "Low") {
|
||||
return Api::AudioQuality::Low;
|
||||
}
|
||||
if (str == "Medium") {
|
||||
return Api::AudioQuality::Medium;
|
||||
}
|
||||
if (str == "High") {
|
||||
return Api::AudioQuality::High;
|
||||
}
|
||||
if (str == "VeryHigh") {
|
||||
return Api::AudioQuality::VeryHigh;
|
||||
}
|
||||
if (str == "Lossless") {
|
||||
return Api::AudioQuality::Lossless;
|
||||
}
|
||||
return Api::AudioQuality::High; // Default
|
||||
}
|
||||
|
||||
std::string ConfigLoader::qualityToString(Api::AudioQuality quality)
|
||||
{
|
||||
switch (quality) {
|
||||
case Api::AudioQuality::Low:
|
||||
return "Low";
|
||||
case Api::AudioQuality::Medium:
|
||||
return "Medium";
|
||||
case Api::AudioQuality::High:
|
||||
return "High";
|
||||
case Api::AudioQuality::VeryHigh:
|
||||
return "VeryHigh";
|
||||
case Api::AudioQuality::Lossless:
|
||||
return "Lossless";
|
||||
default:
|
||||
return "High";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,178 @@
|
||||
#include "ConfigManager.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
ConfigManager& ConfigManager::instance()
|
||||
{
|
||||
static ConfigManager instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
bool ConfigManager::initialize(const std::filesystem::path& configPath)
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
bool success = loadFromFileInternal();
|
||||
initialized_.store(success);
|
||||
return success;
|
||||
}
|
||||
|
||||
bool ConfigManager::initialize()
|
||||
{
|
||||
return initialize(getDefaultConfigPath());
|
||||
}
|
||||
|
||||
AppConfig ConfigManager::getConfig() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_;
|
||||
}
|
||||
|
||||
const BotConfig& ConfigManager::getBot() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.bot;
|
||||
}
|
||||
|
||||
const YouTubeConfig& ConfigManager::getYouTube() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.youtube;
|
||||
}
|
||||
|
||||
const NetworkConfig& ConfigManager::getNetwork() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.network;
|
||||
}
|
||||
|
||||
const TeamSpeakConfig& ConfigManager::getTeamSpeak() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.teamspeak;
|
||||
}
|
||||
|
||||
const SecurityConfig& ConfigManager::getSecurity() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.security;
|
||||
}
|
||||
|
||||
const FeaturesConfig& ConfigManager::getFeatures() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.features;
|
||||
}
|
||||
|
||||
const AdvancedConfig& ConfigManager::getAdvanced() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.advanced;
|
||||
}
|
||||
|
||||
bool ConfigManager::reload()
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
return loadFromFileInternal();
|
||||
}
|
||||
|
||||
bool ConfigManager::save()
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return saveToFileInternal();
|
||||
}
|
||||
|
||||
void ConfigManager::updateConfig(const AppConfig& config, bool saveToFile)
|
||||
{
|
||||
{
|
||||
std::unique_lock lock(mutex_);
|
||||
config_ = config;
|
||||
}
|
||||
|
||||
if (saveToFile) {
|
||||
save();
|
||||
}
|
||||
|
||||
notifyCallbacks();
|
||||
}
|
||||
|
||||
bool ConfigManager::isInitialized() const { return initialized_.load(); }
|
||||
|
||||
std::filesystem::path ConfigManager::getConfigPath() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
|
||||
std::filesystem::path ConfigManager::getDefaultConfigPath()
|
||||
{
|
||||
const char* configHome = std::getenv("XDG_CONFIG_HOME");
|
||||
if (configHome) {
|
||||
return std::filesystem::path(configHome) / "echoion" /
|
||||
"config.json";
|
||||
}
|
||||
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home) {
|
||||
return std::filesystem::path(home) / ".config" / "echoion" /
|
||||
"config.json";
|
||||
}
|
||||
|
||||
return "echoion_config.json";
|
||||
}
|
||||
|
||||
void ConfigManager::onConfigChanged(ConfigChangedCallback callback)
|
||||
{
|
||||
std::unique_lock lock(callbackMutex_);
|
||||
callbacks_.push_back(std::move(callback));
|
||||
}
|
||||
|
||||
bool ConfigManager::createDefaultConfigIfNeeded()
|
||||
{
|
||||
if (!std::filesystem::exists(configPath_)) {
|
||||
std::filesystem::create_directories(configPath_.parent_path());
|
||||
return save();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ConfigManager::notifyCallbacks()
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
std::shared_lock cbLock(callbackMutex_);
|
||||
|
||||
for (const auto& callback : callbacks_) {
|
||||
callback(config_);
|
||||
}
|
||||
}
|
||||
|
||||
bool ConfigManager::loadFromFileInternal()
|
||||
{
|
||||
// Delegate to Core::ConfigLoader, which performs the JSON <-> AppConfig
|
||||
// mapping (via the *Json mirror structs and Void::Json reflection).
|
||||
auto result = Core::ConfigLoader::loadFromFile(configPath_);
|
||||
if (!result) {
|
||||
std::cerr << std::format("Failed to load config: {}\n",
|
||||
result.error().toString());
|
||||
return false;
|
||||
}
|
||||
config_ = std::move(*result);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ConfigManager::saveToFileInternal()
|
||||
{
|
||||
auto result = Core::ConfigLoader::saveToFile(configPath_, config_);
|
||||
if (!result) {
|
||||
std::cerr << std::format("Failed to save config: {}\n",
|
||||
result.error().toString());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+2080
-958
File diff suppressed because it is too large.
Load diff
+1091
-639
File diff suppressed because it is too large.
Load diff
+10
-181
@@ -1,185 +1,14 @@
|
||||
#include "echoion/api/EventBus.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <format>
|
||||
#include <EventBus.hpp>
|
||||
|
||||
namespace Echoion::Api {
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
// Global event bus instance
|
||||
EventBus& GlobalEventBus::instance() {
|
||||
static EventBus instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
EventBus::EventBus() = default;
|
||||
|
||||
EventBus::~EventBus() {
|
||||
stop();
|
||||
}
|
||||
|
||||
void EventBus::start() {
|
||||
if (running_.exchange(true)) {
|
||||
return; // Already running
|
||||
}
|
||||
|
||||
stopRequested_ = false;
|
||||
eventThread_ = std::jthread([this] { processEvents(); });
|
||||
ECHOION_LOG_INFO("EventBus started");
|
||||
}
|
||||
|
||||
void EventBus::stop() {
|
||||
if (!running_.exchange(false)) {
|
||||
return; // Not running
|
||||
}
|
||||
|
||||
stopRequested_ = true;
|
||||
queueCv_.notify_all();
|
||||
|
||||
if (eventThread_.joinable()) {
|
||||
eventThread_.join();
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("EventBus stopped");
|
||||
}
|
||||
|
||||
void EventBus::unsubscribe(const SubscriptionToken& token) {
|
||||
if (!token.isValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::unique_lock<std::shared_mutex> lock(handlersMutex_);
|
||||
auto it = handlers_.find(token.getType());
|
||||
if (it != handlers_.end()) {
|
||||
it->second.erase(token.getId());
|
||||
if (it->second.empty()) {
|
||||
handlers_.erase(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void EventBus::processOne() {
|
||||
std::shared_ptr<IEvent> evt;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
if (eventQueue_.empty()) {
|
||||
return;
|
||||
}
|
||||
evt = std::move(eventQueue_.front());
|
||||
eventQueue_.pop();
|
||||
}
|
||||
|
||||
// Get handlers for this event type
|
||||
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
|
||||
auto it = handlers_.find(evt->getType());
|
||||
if (it != handlers_.end()) {
|
||||
// Copy handlers to avoid holding lock during callback
|
||||
auto handlers = it->second;
|
||||
lock.unlock();
|
||||
|
||||
for (const auto& [id, handler] : handlers) {
|
||||
try {
|
||||
if (handler) {
|
||||
(*handler)(evt);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool EventBus::waitAndProcessOne(std::chrono::milliseconds timeout) {
|
||||
std::shared_ptr<IEvent> evt;
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
||||
if (!queueCv_.wait_for(lock, timeout, [this] {
|
||||
return !eventQueue_.empty() || stopRequested_.load();
|
||||
})) {
|
||||
return false; // Timeout
|
||||
}
|
||||
|
||||
if (stopRequested_ || eventQueue_.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
evt = std::move(eventQueue_.front());
|
||||
eventQueue_.pop();
|
||||
}
|
||||
|
||||
// Get handlers for this event type
|
||||
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
|
||||
auto it = handlers_.find(evt->getType());
|
||||
if (it != handlers_.end()) {
|
||||
auto handlers = it->second;
|
||||
lock.unlock();
|
||||
|
||||
for (const auto& [id, handler] : handlers) {
|
||||
try {
|
||||
if (handler) {
|
||||
(*handler)(evt);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void EventBus::clearQueue() {
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
std::queue<std::shared_ptr<IEvent>> empty;
|
||||
std::swap(eventQueue_, empty);
|
||||
}
|
||||
|
||||
size_t EventBus::getPendingEventCount() const {
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
return eventQueue_.size();
|
||||
}
|
||||
|
||||
void EventBus::processEvents() {
|
||||
while (!stopRequested_) {
|
||||
std::shared_ptr<IEvent> evt;
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
||||
queueCv_.wait(lock, [this] {
|
||||
return !eventQueue_.empty() || stopRequested_.load();
|
||||
});
|
||||
|
||||
if (stopRequested_) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (eventQueue_.empty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
evt = std::move(eventQueue_.front());
|
||||
eventQueue_.pop();
|
||||
}
|
||||
|
||||
// Get handlers for this event type
|
||||
std::shared_lock<std::shared_mutex> lock(handlersMutex_);
|
||||
auto it = handlers_.find(evt->getType());
|
||||
if (it != handlers_.end()) {
|
||||
// Copy handlers to avoid holding lock during callback
|
||||
auto handlers = it->second;
|
||||
lock.unlock();
|
||||
|
||||
for (const auto& [id, handler] : handlers) {
|
||||
try {
|
||||
if (handler) {
|
||||
(*handler)(evt);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Event handler exception: {}", e.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Global event bus instance. The EventBus type is otherwise header-only
|
||||
// (it delegates to Void::EventBus); only the singleton lives here.
|
||||
EventBus& GlobalEventBus::instance()
|
||||
{
|
||||
static EventBus instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+10
-14
@@ -1,23 +1,19 @@
|
||||
#include "echoion/api/Export.hpp"
|
||||
#include <Export.hpp>
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Api {
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
CoreInterfacePtr CreateCore() {
|
||||
return std::make_shared<Core::Core>();
|
||||
}
|
||||
CoreInterfacePtr CreateCore() { return std::make_shared<Core::Core>(); }
|
||||
|
||||
void DestroyCore(ICoreInterface* core) {
|
||||
delete core;
|
||||
}
|
||||
void DestroyCore(ICoreInterface* core) { delete core; }
|
||||
|
||||
const char* GetApiVersion() {
|
||||
return VERSION_STRING;
|
||||
}
|
||||
const char* GetApiVersion() { return VERSION_STRING; }
|
||||
|
||||
bool IsApiCompatible(uint32_t major, uint32_t minor) {
|
||||
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
|
||||
}
|
||||
bool IsApiCompatible(uint32_t major, uint32_t minor)
|
||||
{
|
||||
return major == VERSION_MAJOR && minor <= VERSION_MINOR;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+185
-353
@@ -1,381 +1,213 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <iostream>
|
||||
#include <format>
|
||||
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/SplitFileLogger.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Logging::Level toVoidLevel(Echoion::Api::LogLevel level)
|
||||
{
|
||||
using A = Echoion::Api::LogLevel;
|
||||
using V = Void::Logging::Level;
|
||||
switch (level) {
|
||||
case A::Debug:
|
||||
return V::Debug;
|
||||
case A::Info:
|
||||
return V::Info;
|
||||
case A::Warning:
|
||||
return V::Warning;
|
||||
case A::Error:
|
||||
return V::Error;
|
||||
case A::Critical:
|
||||
return V::Fatal;
|
||||
}
|
||||
return V::Info;
|
||||
}
|
||||
|
||||
Logger::Logger(std::string_view logDir, std::string_view baseName)
|
||||
: logDir_(logDir)
|
||||
, baseName_(baseName) {
|
||||
|
||||
// Ensure log directory exists
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(logDir_, ec);
|
||||
|
||||
// Ensure history directory exists
|
||||
ensureHistoryDirExists();
|
||||
|
||||
// Open log files for each level
|
||||
openLogFiles();
|
||||
|
||||
// Start worker thread
|
||||
workerThread_ = std::thread(&Logger::logWorker, this);
|
||||
}
|
||||
[[nodiscard]] Echoion::Api::LogLevel fromVoidLevel(Void::Logging::Level level)
|
||||
{
|
||||
using A = Echoion::Api::LogLevel;
|
||||
using V = Void::Logging::Level;
|
||||
switch (level) {
|
||||
case V::Trace:
|
||||
case V::Debug:
|
||||
return A::Debug;
|
||||
case V::Info:
|
||||
return A::Info;
|
||||
case V::Warning:
|
||||
return A::Warning;
|
||||
case V::Error:
|
||||
return A::Error;
|
||||
case V::Fatal:
|
||||
return A::Critical;
|
||||
case V::Disabled:
|
||||
return A::Debug;
|
||||
}
|
||||
return A::Info;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Logger::~Logger() {
|
||||
running_ = false;
|
||||
cv_.notify_all();
|
||||
if (workerThread_.joinable()) {
|
||||
workerThread_.join();
|
||||
}
|
||||
|
||||
// Close all file streams
|
||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
||||
for (auto& [level, info] : levelFiles_) {
|
||||
if (info.stream.is_open()) {
|
||||
info.stream.close();
|
||||
}
|
||||
}
|
||||
if (combinedFile_.stream.is_open()) {
|
||||
combinedFile_.stream.close();
|
||||
}
|
||||
}
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
void Logger::ensureHistoryDirExists() {
|
||||
std::error_code ec;
|
||||
auto historyDir = logDir_ / "history";
|
||||
std::filesystem::create_directories(historyDir, ec);
|
||||
}
|
||||
Logger::Logger(std::string_view logDir, std::string_view baseName)
|
||||
: logDir_(logDir), baseName_(baseName)
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(logDir_, ec);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::openLogFiles() {
|
||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
||||
|
||||
// Open file for each log level
|
||||
for (auto level : {Api::LogLevel::Debug, Api::LogLevel::Info,
|
||||
Api::LogLevel::Warning, Api::LogLevel::Error, Api::LogLevel::Critical}) {
|
||||
auto path = generateLogFilePath(level);
|
||||
LogFileInfo info;
|
||||
info.path = path;
|
||||
info.stream.open(path, std::ios::app);
|
||||
info.createdAt = std::chrono::system_clock::now();
|
||||
|
||||
// Get current file size
|
||||
if (std::filesystem::exists(path)) {
|
||||
info.size = std::filesystem::file_size(path);
|
||||
}
|
||||
|
||||
levelFiles_[level] = std::move(info);
|
||||
}
|
||||
|
||||
// Open combined log file
|
||||
auto combinedPath = logDir_ / std::format("{}_all.log", baseName_);
|
||||
combinedFile_.path = combinedPath;
|
||||
combinedFile_.stream.open(combinedPath, std::ios::app);
|
||||
combinedFile_.createdAt = std::chrono::system_clock::now();
|
||||
if (std::filesystem::exists(combinedPath)) {
|
||||
combinedFile_.size = std::filesystem::file_size(combinedPath);
|
||||
}
|
||||
}
|
||||
Logger::~Logger()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
if (sink_) {
|
||||
sink_->flush();
|
||||
sink_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
std::filesystem::path Logger::generateLogFilePath(Api::LogLevel level) {
|
||||
std::string levelStr;
|
||||
switch (level) {
|
||||
case Api::LogLevel::Debug: levelStr = "debug"; break;
|
||||
case Api::LogLevel::Info: levelStr = "info"; break;
|
||||
case Api::LogLevel::Warning: levelStr = "warning"; break;
|
||||
case Api::LogLevel::Error: levelStr = "error"; break;
|
||||
case Api::LogLevel::Critical: levelStr = "critical"; break;
|
||||
default: levelStr = "unknown"; break;
|
||||
}
|
||||
return logDir_ / std::format("{}_{}.log", baseName_, levelStr);
|
||||
}
|
||||
void Logger::rebuildSinks()
|
||||
{
|
||||
namespace VL = Void::Logging;
|
||||
|
||||
void Logger::log(Api::LogLevel level, std::string_view message, std::source_location location) {
|
||||
if (level < minLevel_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Api::LogEntry entry;
|
||||
entry.timestamp = std::chrono::system_clock::now();
|
||||
entry.level = level;
|
||||
entry.message = std::string(message);
|
||||
entry.sourceFile = location.file_name();
|
||||
entry.sourceLine = location.line();
|
||||
entry.function = location.function_name();
|
||||
entry.threadId = std::this_thread::get_id();
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(queueMutex_);
|
||||
logQueue_.push(std::move(entry));
|
||||
}
|
||||
cv_.notify_one();
|
||||
}
|
||||
auto multi = std::make_shared<VL::MultiLogger>();
|
||||
|
||||
void Logger::logWorker() {
|
||||
while (running_.load()) {
|
||||
std::unique_lock<std::mutex> lock(queueMutex_);
|
||||
cv_.wait(lock, [this] { return !logQueue_.empty() || !running_.load(); });
|
||||
|
||||
while (!logQueue_.empty()) {
|
||||
auto entry = std::move(logQueue_.front());
|
||||
logQueue_.pop();
|
||||
lock.unlock();
|
||||
|
||||
// Format the log entry
|
||||
std::string formatted = formatLogEntry(entry);
|
||||
|
||||
// Console output
|
||||
if (consoleOutput_.load()) {
|
||||
if (entry.level >= Api::LogLevel::Error) {
|
||||
std::cerr << formatted << std::endl;
|
||||
} else {
|
||||
std::cout << formatted << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
// File output
|
||||
if (fileOutput_.load()) {
|
||||
rotateIfNeeded(entry.level);
|
||||
writeToFile(entry.level, formatted);
|
||||
}
|
||||
|
||||
// Callbacks
|
||||
{
|
||||
std::lock_guard<std::mutex> cbLock(callbackMutex_);
|
||||
for (const auto& callback : callbacks_) {
|
||||
callback(entry);
|
||||
}
|
||||
}
|
||||
|
||||
lock.lock();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Shared layout approximating the previous Logger output:
|
||||
// [2024-01-01 12:00:00.123] [INFO] [thread] file.cpp - message
|
||||
auto formatter = std::make_shared<const VL::PatternFormatter>(
|
||||
"[{time}] [{level}] [{thread}] {file} - {message}");
|
||||
|
||||
void Logger::writeToFile(Api::LogLevel level, const std::string& formattedEntry) {
|
||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
||||
|
||||
// Write to level-specific file
|
||||
auto it = levelFiles_.find(level);
|
||||
if (it != levelFiles_.end() && it->second.stream.is_open()) {
|
||||
it->second.stream << formattedEntry << std::endl;
|
||||
it->second.size += formattedEntry.size() + 1;
|
||||
}
|
||||
|
||||
// Write to combined file
|
||||
if (combinedFile_.stream.is_open()) {
|
||||
combinedFile_.stream << formattedEntry << std::endl;
|
||||
combinedFile_.size += formattedEntry.size() + 1;
|
||||
}
|
||||
}
|
||||
if (consoleOutput_.load()) {
|
||||
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
|
||||
console->set_formatter(formatter);
|
||||
multi->add(std::move(console));
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
if (fileOutput_.load()) {
|
||||
VL::SplitFileOptions opts;
|
||||
opts.combined = true; // also write <dir>/all.log
|
||||
opts.max_bytes = static_cast<std::size_t>(maxFileSize_.load());
|
||||
opts.max_files = static_cast<std::size_t>(maxFiles_.load());
|
||||
if (auto fileSink = VL::SplitFileLogger::open(logDir_, opts)) {
|
||||
(*fileSink)->set_formatter(formatter);
|
||||
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Bridge Void entries back to the registered ILogger callbacks so
|
||||
// existing log subscribers (e.g. RPC log streaming) keep receiving
|
||||
// Api::LogEntry records, asynchronously as before.
|
||||
multi->add(std::make_shared<VL::CallbackLogger>(
|
||||
[this](const VL::Entry& entry) {
|
||||
dispatchToCallbacks(fromVoidLevel(entry.level), entry.message,
|
||||
entry.location.file_name(),
|
||||
entry.location.line(),
|
||||
entry.location.function_name());
|
||||
}));
|
||||
|
||||
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();
|
||||
|
||||
auto basePath = it->second.path;
|
||||
|
||||
// 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()));
|
||||
}
|
||||
|
||||
// Reopen
|
||||
it->second.stream.open(basePath, std::ios::app);
|
||||
it->second.size = 0;
|
||||
it->second.createdAt = std::chrono::system_clock::now();
|
||||
}
|
||||
|
||||
// Check combined file
|
||||
if (combinedFile_.size >= maxSize) {
|
||||
combinedFile_.stream.close();
|
||||
|
||||
auto basePath = combinedFile_.path;
|
||||
|
||||
// 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()));
|
||||
}
|
||||
|
||||
combinedFile_.stream.open(basePath, std::ios::app);
|
||||
combinedFile_.size = 0;
|
||||
combinedFile_.createdAt = std::chrono::system_clock::now();
|
||||
}
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
sink_ = std::move(multi);
|
||||
}
|
||||
|
||||
std::string Logger::formatLogEntry(const Api::LogEntry& entry) {
|
||||
return std::format("[{}] [{}] [{}] {} - {}",
|
||||
formatTimestamp(entry.timestamp),
|
||||
levelToString(entry.level),
|
||||
entry.threadId,
|
||||
entry.sourceFile.substr(entry.sourceFile.find_last_of("/\\") + 1),
|
||||
entry.message);
|
||||
}
|
||||
void Logger::dispatchToCallbacks(Api::LogLevel level,
|
||||
const std::string& message,
|
||||
const std::string& file, uint32_t line,
|
||||
const std::string& function)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
if (callbacks_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::string Logger::levelToString(Api::LogLevel level) {
|
||||
switch (level) {
|
||||
case Api::LogLevel::Debug: return "DEBUG";
|
||||
case Api::LogLevel::Info: return "INFO";
|
||||
case Api::LogLevel::Warning: return "WARN";
|
||||
case Api::LogLevel::Error: return "ERROR";
|
||||
case Api::LogLevel::Critical: return "CRITICAL";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
Api::LogEntry entry;
|
||||
entry.level = level;
|
||||
entry.message = message;
|
||||
entry.sourceFile = file;
|
||||
entry.sourceLine = line;
|
||||
entry.function = function;
|
||||
entry.threadId = std::this_thread::get_id();
|
||||
entry.timestamp = std::chrono::system_clock::now();
|
||||
|
||||
std::string Logger::formatTimestamp(const std::chrono::system_clock::time_point& tp) {
|
||||
auto time_t = std::chrono::system_clock::to_time_t(tp);
|
||||
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
tp.time_since_epoch()) % 1000;
|
||||
|
||||
std::tm tm;
|
||||
localtime_r(&time_t, &tm);
|
||||
|
||||
return std::format("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:03d}",
|
||||
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
|
||||
tm.tm_hour, tm.tm_min, tm.tm_sec, ms.count());
|
||||
}
|
||||
for (const auto& callback : callbacks_) {
|
||||
callback(entry);
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::setMinLevel(Api::LogLevel level) {
|
||||
minLevel_.store(level);
|
||||
}
|
||||
void Logger::log(Api::LogLevel level, std::string_view message,
|
||||
std::source_location location)
|
||||
{
|
||||
if (level < minLevel_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Api::LogLevel Logger::getMinLevel() const {
|
||||
return minLevel_.load();
|
||||
}
|
||||
std::shared_ptr<Void::Logging::MultiLogger> sink;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
sink = sink_;
|
||||
}
|
||||
if (sink) {
|
||||
sink->log(toVoidLevel(level), message, location);
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::registerCallback(const LogCallback& callback) {
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
callbacks_.push_back(callback);
|
||||
}
|
||||
void Logger::setMinLevel(Api::LogLevel level) { minLevel_.store(level); }
|
||||
|
||||
void Logger::unregisterCallback(const LogCallback& callback) {
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
|
||||
[&callback](const auto& cb) { return &cb == &callback; }), callbacks_.end());
|
||||
}
|
||||
Api::LogLevel Logger::getMinLevel() const { return minLevel_.load(); }
|
||||
|
||||
void Logger::flush() {
|
||||
std::lock_guard<std::mutex> lock(fileMutex_);
|
||||
for (auto& [level, info] : levelFiles_) {
|
||||
if (info.stream.is_open()) {
|
||||
info.stream.flush();
|
||||
}
|
||||
}
|
||||
if (combinedFile_.stream.is_open()) {
|
||||
combinedFile_.stream.flush();
|
||||
}
|
||||
}
|
||||
void Logger::registerCallback(const LogCallback& callback)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
callbacks_.push_back(callback);
|
||||
}
|
||||
|
||||
void Logger::setConsoleOutput(bool enabled) {
|
||||
consoleOutput_.store(enabled);
|
||||
}
|
||||
void Logger::unregisterCallback(const LogCallback& callback)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
|
||||
[&callback](const auto& cb) {
|
||||
return &cb == &callback;
|
||||
}),
|
||||
callbacks_.end());
|
||||
}
|
||||
|
||||
void Logger::setFileOutput(bool enabled) {
|
||||
fileOutput_.store(enabled);
|
||||
}
|
||||
void Logger::flush()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
if (sink_) {
|
||||
sink_->flush();
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::setMaxFileSize(uint64_t bytes) {
|
||||
maxFileSize_.store(bytes);
|
||||
}
|
||||
void Logger::setConsoleOutput(bool enabled)
|
||||
{
|
||||
consoleOutput_.store(enabled);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::setMaxFiles(uint32_t count) {
|
||||
maxFiles_.store(count);
|
||||
}
|
||||
void Logger::setFileOutput(bool enabled)
|
||||
{
|
||||
fileOutput_.store(enabled);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::setMaxFileSize(uint64_t bytes)
|
||||
{
|
||||
maxFileSize_.store(bytes);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::setMaxFiles(uint32_t count)
|
||||
{
|
||||
maxFiles_.store(count);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+50
-37
@@ -1,47 +1,60 @@
|
||||
#include "echoion/api/MemoryPool.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <MemoryPool.hpp>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api {
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
AudioBufferPool& AudioBufferPool::instance() {
|
||||
static AudioBufferPool instance;
|
||||
return instance;
|
||||
}
|
||||
AudioBufferPool& AudioBufferPool::instance()
|
||||
{
|
||||
static AudioBufferPool instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize) {
|
||||
bufferSize_ = bufferSize;
|
||||
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::initialize(size_t bufferSize, size_t poolSize)
|
||||
{
|
||||
bufferSize_ = bufferSize;
|
||||
pool_ = std::make_unique<Void::BufferPool::BufferPool<int16_t>>();
|
||||
|
||||
void AudioBufferPool::shutdown() {
|
||||
pool_.reset();
|
||||
ECHOION_LOG_INFO("AudioBufferPool shutdown");
|
||||
}
|
||||
// Pre-warm the size-class bucket: acquire then immediately drop
|
||||
// `poolSize` buffers so subsequent acquireBuffer() calls reuse storage.
|
||||
{
|
||||
std::vector<AudioSampleBuffer> warm;
|
||||
warm.reserve(poolSize);
|
||||
for (size_t i = 0; i < poolSize; ++i) {
|
||||
warm.push_back(pool_->acquire(bufferSize));
|
||||
}
|
||||
} // buffers returned to the pool here
|
||||
|
||||
PooledPtr<int16_t> AudioBufferPool::acquireBuffer() {
|
||||
if (!pool_) {
|
||||
return PooledPtr<int16_t>();
|
||||
}
|
||||
|
||||
int16_t* ptr = pool_->acquire();
|
||||
if (!ptr) {
|
||||
ECHOION_LOG_WARNING("AudioBufferPool exhausted - consider increasing pool size");
|
||||
return PooledPtr<int16_t>();
|
||||
}
|
||||
|
||||
return PooledPtr<int16_t>(ptr, pool_.get());
|
||||
}
|
||||
ECHOION_LOG_INFO(std::format(
|
||||
"AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
|
||||
poolSize, bufferSize,
|
||||
(bufferSize * poolSize * sizeof(int16_t)) / 1024));
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getAvailableBuffers() const {
|
||||
if (!pool_) return 0;
|
||||
return pool_->available();
|
||||
}
|
||||
void AudioBufferPool::shutdown()
|
||||
{
|
||||
pool_.reset();
|
||||
ECHOION_LOG_INFO("AudioBufferPool shutdown");
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getTotalBuffers() const {
|
||||
if (!pool_) return 0;
|
||||
return pool_->capacity();
|
||||
}
|
||||
AudioSampleBuffer AudioBufferPool::acquireBuffer()
|
||||
{
|
||||
if (!pool_) {
|
||||
return AudioSampleBuffer{};
|
||||
}
|
||||
return pool_->acquire(bufferSize_);
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getAvailableBuffers() const
|
||||
{
|
||||
return pool_ ? pool_->stats().pooled : 0;
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getTotalBuffers() const
|
||||
{
|
||||
return pool_ ? static_cast<size_t>(pool_->stats().allocations) : 0;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+2295
-1718
File diff suppressed because it is too large.
Load diff
+871
-755
File diff suppressed because it is too large.
Load diff
+410
-347
@@ -1,400 +1,463 @@
|
||||
#include "echoion/core/RpcServer.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <glaze/glaze.hpp>
|
||||
#include <format>
|
||||
#include "echoion/core/RpcServer.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
RpcServer::RpcServer() = default;
|
||||
RpcServer::RpcServer() = default;
|
||||
|
||||
RpcServer::~RpcServer() {
|
||||
stop();
|
||||
}
|
||||
RpcServer::~RpcServer() { stop(); }
|
||||
|
||||
Api::Result<void> RpcServer::start(uint16_t port) {
|
||||
if (running_.exchange(true)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists, "RPC server already running"));
|
||||
}
|
||||
Api::Result<void> RpcServer::start(uint16_t port)
|
||||
{
|
||||
if (running_.exchange(true)) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::AlreadyExists,
|
||||
"RPC server already running"));
|
||||
}
|
||||
|
||||
port_ = port;
|
||||
port_ = port;
|
||||
|
||||
try {
|
||||
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
|
||||
acceptor_.emplace(ioContext_);
|
||||
acceptor_->open(endpoint.protocol());
|
||||
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
||||
acceptor_->bind(endpoint);
|
||||
acceptor_->listen();
|
||||
try {
|
||||
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
|
||||
acceptor_.emplace(ioContext_);
|
||||
acceptor_->open(endpoint.protocol());
|
||||
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
|
||||
acceptor_->bind(endpoint);
|
||||
acceptor_->listen();
|
||||
|
||||
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
|
||||
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
|
||||
|
||||
ECHOION_LOG_INFO(std::format("RPC server started on port {}", port));
|
||||
return {};
|
||||
} catch (const std::exception& e) {
|
||||
running_ = false;
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
std::format("Failed to start RPC server: {}", e.what())));
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("RPC server started on port {}", port));
|
||||
return {};
|
||||
} catch (const std::exception& e) {
|
||||
running_ = false;
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ServiceUnavailable,
|
||||
std::format("Failed to start RPC server: {}", e.what())));
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::stop() {
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
void RpcServer::stop()
|
||||
{
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Cancel any pending async operations
|
||||
if (acceptor_.has_value()) {
|
||||
boost::system::error_code ec;
|
||||
acceptor_->cancel(ec);
|
||||
}
|
||||
|
||||
ioContext_.stop();
|
||||
try {
|
||||
// Cancel any pending async operations
|
||||
if (acceptor_.has_value()) {
|
||||
boost::system::error_code ec;
|
||||
acceptor_->cancel(ec);
|
||||
}
|
||||
|
||||
// Close all client connections
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
for (auto& [id, ws] : clients_) {
|
||||
if (ws->is_open()) {
|
||||
beast::error_code ec;
|
||||
ws->close(websocket::close_code::normal, ec);
|
||||
}
|
||||
}
|
||||
clients_.clear();
|
||||
}
|
||||
ioContext_.stop();
|
||||
|
||||
// Wait for all client threads to finish (with timeout)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||
for (auto& thread : clientThreads_) {
|
||||
if (thread.joinable()) {
|
||||
thread.detach(); // Don't wait, just detach
|
||||
}
|
||||
}
|
||||
clientThreads_.clear();
|
||||
}
|
||||
// Close all client connections
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
for (auto& [id, ws] : clients_) {
|
||||
if (ws->is_open()) {
|
||||
beast::error_code ec;
|
||||
ws->close(websocket::close_code::normal, ec);
|
||||
}
|
||||
}
|
||||
clients_.clear();
|
||||
}
|
||||
|
||||
// Wait for server thread with timeout
|
||||
if (serverThread_.joinable()) {
|
||||
// Give it a moment to clean up
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (serverThread_.joinable() &&
|
||||
std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
if (serverThread_.joinable()) {
|
||||
serverThread_.detach(); // Force detach if still running
|
||||
}
|
||||
}
|
||||
|
||||
if (acceptor_.has_value()) {
|
||||
boost::system::error_code ec;
|
||||
acceptor_->close(ec);
|
||||
}
|
||||
// Wait for all client threads to finish (with timeout)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||
for (auto& thread : clientThreads_) {
|
||||
if (thread.joinable()) {
|
||||
// Give each thread a short time to finish
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (thread.joinable() &&
|
||||
std::chrono::steady_clock::now() - start <
|
||||
std::chrono::milliseconds(100)) {
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds(10));
|
||||
}
|
||||
if (thread.joinable()) {
|
||||
thread.detach(); // Only detach if still running
|
||||
// after timeout
|
||||
}
|
||||
}
|
||||
}
|
||||
clientThreads_.clear();
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("RPC server stopped");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Error stopping RPC server: {}", e.what()));
|
||||
}
|
||||
}
|
||||
// Wait for server thread with timeout
|
||||
if (serverThread_.joinable()) {
|
||||
// Give it a moment to clean up
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (serverThread_.joinable() &&
|
||||
std::chrono::steady_clock::now() - start <
|
||||
std::chrono::seconds(2)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
if (serverThread_.joinable()) {
|
||||
serverThread_.detach(); // Force detach if still running
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::acceptLoop() {
|
||||
ECHOION_LOG_INFO("RPC server accept loop started");
|
||||
while (running_.load()) {
|
||||
try {
|
||||
asio::ip::tcp::socket socket(ioContext_);
|
||||
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
|
||||
|
||||
// Use async accept with cancellation support
|
||||
std::atomic<bool> acceptComplete{false};
|
||||
boost::system::error_code acceptEc;
|
||||
|
||||
acceptor_->async_accept(socket, [&](const boost::system::error_code& ec) {
|
||||
acceptEc = ec;
|
||||
acceptComplete = true;
|
||||
});
|
||||
|
||||
// Poll until accept completes or we're stopped
|
||||
while (!acceptComplete.load() && running_.load()) {
|
||||
ioContext_.poll_one();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
|
||||
// Cancel pending operation if we're stopping
|
||||
if (!running_.load()) {
|
||||
acceptor_->cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
if (acceptEc) {
|
||||
throw std::runtime_error(acceptEc.message());
|
||||
}
|
||||
|
||||
ECHOION_LOG_DEBUG(std::format("RPC server accepted TCP connection from {}:{}",
|
||||
socket.remote_endpoint().address().to_string(),
|
||||
socket.remote_endpoint().port()));
|
||||
if (acceptor_.has_value()) {
|
||||
boost::system::error_code ec;
|
||||
acceptor_->close(ec);
|
||||
}
|
||||
|
||||
if (!running_.load()) break;
|
||||
ECHOION_LOG_INFO("RPC server stopped");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Error stopping RPC server: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
auto ws = std::make_shared<websocket::stream<asio::ip::tcp::socket>>(std::move(socket));
|
||||
ws->accept();
|
||||
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
||||
void RpcServer::acceptLoop()
|
||||
{
|
||||
ECHOION_LOG_INFO("RPC server accept loop started");
|
||||
while (running_.load()) {
|
||||
try {
|
||||
asio::ip::tcp::socket socket(ioContext_);
|
||||
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
|
||||
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
}
|
||||
// Use async accept with cancellation support
|
||||
std::atomic<bool> acceptComplete{false};
|
||||
boost::system::error_code acceptEc;
|
||||
|
||||
ECHOION_LOG_DEBUG(std::format("RPC client {} connected", clientId));
|
||||
acceptor_->async_accept(
|
||||
socket, [&](const boost::system::error_code& ec) {
|
||||
acceptEc = ec;
|
||||
acceptComplete = true;
|
||||
});
|
||||
|
||||
// Handle client in separate thread
|
||||
std::thread clientThread([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
// Cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_.erase(clientId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
ECHOION_LOG_DEBUG(std::format("RPC client {} disconnected", clientId));
|
||||
});
|
||||
|
||||
// Track the thread for proper cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||
// Clean up any finished threads first
|
||||
clientThreads_.erase(
|
||||
std::remove_if(clientThreads_.begin(), clientThreads_.end(),
|
||||
[](std::thread& t) {
|
||||
if (!t.joinable()) return true;
|
||||
return false;
|
||||
}),
|
||||
clientThreads_.end()
|
||||
);
|
||||
clientThreads_.push_back(std::move(clientThread));
|
||||
}
|
||||
// Poll until accept completes or we're stopped
|
||||
while (!acceptComplete.load() && running_.load()) {
|
||||
ioContext_.poll_one();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
// If we're shutting down, exit gracefully
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
ECHOION_LOG_ERROR(std::format("RPC accept error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO("RPC server accept loop stopped");
|
||||
}
|
||||
// Cancel pending operation if we're stopping
|
||||
if (!running_.load()) {
|
||||
acceptor_->cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
void RpcServer::handleClient(std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws) {
|
||||
beast::flat_buffer buffer;
|
||||
if (acceptEc) {
|
||||
throw std::runtime_error(acceptEc.message());
|
||||
}
|
||||
|
||||
while (running_.load() && ws->is_open()) {
|
||||
try {
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC server accepted TCP connection from {}:{}",
|
||||
socket.remote_endpoint().address().to_string(),
|
||||
socket.remote_endpoint().port()));
|
||||
|
||||
if (ec == websocket::error::closed) {
|
||||
break;
|
||||
}
|
||||
if (ec) {
|
||||
ECHOION_LOG_ERROR(std::format("WebSocket read error: {}", ec.message()));
|
||||
break;
|
||||
}
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
std::string message = beast::buffers_to_string(buffer.data());
|
||||
buffer.consume(buffer.size());
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(socket));
|
||||
ws->accept();
|
||||
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
||||
|
||||
// Find client ID
|
||||
uint64_t clientId = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
for (const auto& [id, clientWs] : clients_) {
|
||||
if (clientWs.get() == ws.get()) {
|
||||
clientId = id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
}
|
||||
|
||||
if (clientId != 0) {
|
||||
processMessage(clientId, message);
|
||||
}
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC client {} connected", clientId));
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Client handling error: {}", e.what()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Handle client in separate thread
|
||||
std::thread clientThread([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
void RpcServer::processMessage(uint64_t clientId, const std::string& message) {
|
||||
try {
|
||||
Api::RpcRequest request;
|
||||
auto ec = glz::read_json(request, message);
|
||||
if (ec) {
|
||||
Api::RpcResponse response;
|
||||
response.requestId = 0;
|
||||
response.success = false;
|
||||
response.error = "{\"code\":5,\"message\":\"Invalid JSON\",\"source\":\"RpcServer\"}";
|
||||
response.success = false;
|
||||
sendResponse(clientId, response);
|
||||
return;
|
||||
}
|
||||
// Cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_.erase(clientId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC client {} disconnected", clientId));
|
||||
});
|
||||
|
||||
// Check authentication (except for Authenticate method)
|
||||
if (request.method != Api::RpcMethod::Authenticate) {
|
||||
if (!isClientAuthenticated(clientId)) {
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
response.success = false;
|
||||
response.error = "{\"code\":10,\"message\":\"Not authenticated\",\"source\":\"RpcServer\"}";
|
||||
response.success = false;
|
||||
sendResponse(clientId, response);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Track the thread for proper cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientThreadsMutex_);
|
||||
// Clean up any finished threads first
|
||||
clientThreads_.erase(std::remove_if(clientThreads_.begin(),
|
||||
clientThreads_.end(),
|
||||
[](std::thread& t) {
|
||||
if (!t.joinable()) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}),
|
||||
clientThreads_.end());
|
||||
clientThreads_.push_back(std::move(clientThread));
|
||||
}
|
||||
|
||||
// Find handler
|
||||
std::string methodName = std::to_string(static_cast<int>(request.method));
|
||||
CommandHandler handler;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
auto it = handlers_.find(methodName);
|
||||
if (it != handlers_.end()) {
|
||||
handler = it->second;
|
||||
}
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
// If we're shutting down, exit gracefully
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("RPC accept error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO("RPC server accept loop stopped");
|
||||
}
|
||||
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
response.timestamp = std::chrono::system_clock::now();
|
||||
void RpcServer::handleClient(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
|
||||
{
|
||||
beast::flat_buffer buffer;
|
||||
|
||||
if (handler) {
|
||||
auto result = handler(request.params.value_or(""), clientId);
|
||||
if (result) {
|
||||
response.success = true;
|
||||
response.result = *result;
|
||||
} else {
|
||||
response.success = false;
|
||||
response.error = std::format("{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
|
||||
static_cast<uint32_t>(result.error().code),
|
||||
result.error().message,
|
||||
result.error().source);
|
||||
}
|
||||
} else {
|
||||
response.success = false;
|
||||
response.error = "{\"code\":2,\"message\":\"Unknown method\",\"source\":\"RpcServer\"}";
|
||||
}
|
||||
while (running_.load() && ws->is_open()) {
|
||||
try {
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
|
||||
sendResponse(clientId, response);
|
||||
if (ec == websocket::error::closed) {
|
||||
break;
|
||||
}
|
||||
if (ec) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("WebSocket read error: {}", ec.message()));
|
||||
break;
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Message processing error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
std::string message = beast::buffers_to_string(buffer.data());
|
||||
buffer.consume(buffer.size());
|
||||
|
||||
void RpcServer::sendResponse(uint64_t clientId, const Api::RpcResponse& response) {
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
auto it = clients_.find(clientId);
|
||||
if (it == clients_.end() || !it->second->is_open()) {
|
||||
return;
|
||||
}
|
||||
// Find client ID
|
||||
uint64_t clientId = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
for (const auto& [id, clientWs] : clients_) {
|
||||
if (clientWs.get() == ws.get()) {
|
||||
clientId = id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
auto json = glz::write_json(response);
|
||||
if (json) {
|
||||
it->second->write(asio::buffer(*json));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
if (clientId != 0) {
|
||||
processMessage(clientId, message);
|
||||
}
|
||||
|
||||
void RpcServer::sendNotification(uint64_t clientId, const Api::RpcNotification& notification) {
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
auto it = clients_.find(clientId);
|
||||
if (it == clients_.end() || !it->second->is_open()) {
|
||||
return;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Client handling error: {}", e.what()));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
auto json = glz::write_json(notification);
|
||||
if (json) {
|
||||
it->second->write(asio::buffer(*json));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Send notification error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
void RpcServer::processMessage(uint64_t clientId,
|
||||
const std::string& message)
|
||||
{
|
||||
try {
|
||||
Api::RpcRequest request;
|
||||
bool decoded = false;
|
||||
if (auto parsed = Void::Json::parse(message)) {
|
||||
if (auto req = Void::Json::from_json<Api::RpcRequest>(*parsed)) {
|
||||
request = std::move(*req);
|
||||
decoded = true;
|
||||
}
|
||||
}
|
||||
if (!decoded) {
|
||||
Api::RpcResponse response;
|
||||
response.requestId = 0;
|
||||
response.success = false;
|
||||
response.error = "{\"code\":5,\"message\":\"Invalid "
|
||||
"JSON\",\"source\":\"RpcServer\"}";
|
||||
response.success = false;
|
||||
sendResponse(clientId, response);
|
||||
return;
|
||||
}
|
||||
|
||||
void RpcServer::broadcastEvent(const std::string& event, const std::string& data) {
|
||||
Api::RpcNotification notification;
|
||||
notification.event = event;
|
||||
notification.data = data;
|
||||
notification.timestamp = std::chrono::system_clock::now();
|
||||
// Check authentication (except for Authenticate method)
|
||||
if (request.method != Api::RpcMethod::Authenticate) {
|
||||
if (!isClientAuthenticated(clientId)) {
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
response.success = false;
|
||||
response.error =
|
||||
"{\"code\":10,\"message\":\"Not "
|
||||
"authenticated\",\"source\":\"RpcServer\"}";
|
||||
response.success = false;
|
||||
sendResponse(clientId, response);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
for (const auto& [clientId, ws] : clients_) {
|
||||
if (ws->is_open() && isClientAuthenticated(clientId)) {
|
||||
try {
|
||||
auto json = glz::write_json(notification);
|
||||
if (json) {
|
||||
ws->write(asio::buffer(*json));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Broadcast error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Find handler
|
||||
std::string methodName =
|
||||
std::to_string(static_cast<int>(request.method));
|
||||
CommandHandler handler;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
auto it = handlers_.find(methodName);
|
||||
if (it != handlers_.end()) {
|
||||
handler = it->second;
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::sendEvent(uint64_t clientId, const std::string& event, const std::string& data) {
|
||||
Api::RpcNotification notification;
|
||||
notification.event = event;
|
||||
notification.data = data;
|
||||
notification.timestamp = std::chrono::system_clock::now();
|
||||
sendNotification(clientId, notification);
|
||||
}
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
response.timestamp = std::chrono::system_clock::now();
|
||||
|
||||
void RpcServer::registerHandler(const std::string& method, CommandHandler handler) {
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
handlers_[method] = std::move(handler);
|
||||
}
|
||||
if (handler) {
|
||||
auto result = handler(request.params.value_or(""), clientId);
|
||||
if (result) {
|
||||
response.success = true;
|
||||
response.result = *result;
|
||||
} else {
|
||||
response.success = false;
|
||||
response.error = std::format(
|
||||
"{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
|
||||
static_cast<uint32_t>(result.error().code),
|
||||
result.error().message,
|
||||
result.error().source);
|
||||
}
|
||||
} else {
|
||||
response.success = false;
|
||||
response.error = "{\"code\":2,\"message\":\"Unknown "
|
||||
"method\",\"source\":\"RpcServer\"}";
|
||||
}
|
||||
|
||||
void RpcServer::unregisterHandler(const std::string& method) {
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
handlers_.erase(method);
|
||||
}
|
||||
sendResponse(clientId, response);
|
||||
|
||||
void RpcServer::setAuthToken(const std::string& token) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authToken_ = token;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Message processing error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
bool RpcServer::authenticate(const std::string& token) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
return authToken_.empty() || token == authToken_;
|
||||
}
|
||||
void RpcServer::sendResponse(uint64_t clientId,
|
||||
const Api::RpcResponse& response)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
auto it = clients_.find(clientId);
|
||||
if (it == clients_.end() || !it->second->is_open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
void RpcServer::addAuthenticatedClient(uint64_t clientId) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.insert(clientId);
|
||||
}
|
||||
try {
|
||||
const std::string json =
|
||||
Void::Json::serialize(Void::Json::to_json(response));
|
||||
it->second->write(asio::buffer(json));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::removeAuthenticatedClient(uint64_t clientId) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
void RpcServer::sendNotification(uint64_t clientId,
|
||||
const Api::RpcNotification& notification)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
auto it = clients_.find(clientId);
|
||||
if (it == clients_.end() || !it->second->is_open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool RpcServer::isClientAuthenticated(uint64_t clientId) {
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
return authenticatedClients_.contains(clientId);
|
||||
}
|
||||
try {
|
||||
const std::string json =
|
||||
Void::Json::serialize(Void::Json::to_json(notification));
|
||||
it->second->write(asio::buffer(json));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Send notification error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::broadcastEvent(const std::string& event,
|
||||
const std::string& data)
|
||||
{
|
||||
Api::RpcNotification notification;
|
||||
notification.event = event;
|
||||
notification.data = data;
|
||||
notification.timestamp = std::chrono::system_clock::now();
|
||||
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
for (const auto& [clientId, ws] : clients_) {
|
||||
if (ws->is_open() && isClientAuthenticated(clientId)) {
|
||||
try {
|
||||
const std::string json = Void::Json::serialize(
|
||||
Void::Json::to_json(notification));
|
||||
ws->write(asio::buffer(json));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Broadcast error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::sendEvent(uint64_t clientId, const std::string& event,
|
||||
const std::string& data)
|
||||
{
|
||||
Api::RpcNotification notification;
|
||||
notification.event = event;
|
||||
notification.data = data;
|
||||
notification.timestamp = std::chrono::system_clock::now();
|
||||
sendNotification(clientId, notification);
|
||||
}
|
||||
|
||||
void RpcServer::registerHandler(const std::string& method,
|
||||
CommandHandler handler)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
handlers_[method] = std::move(handler);
|
||||
}
|
||||
|
||||
void RpcServer::unregisterHandler(const std::string& method)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(handlersMutex_);
|
||||
handlers_.erase(method);
|
||||
}
|
||||
|
||||
void RpcServer::setAuthToken(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authToken_ = token;
|
||||
}
|
||||
|
||||
bool RpcServer::authenticate(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
return authToken_.empty() || token == authToken_;
|
||||
}
|
||||
|
||||
void RpcServer::addAuthenticatedClient(uint64_t clientId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.insert(clientId);
|
||||
}
|
||||
|
||||
void RpcServer::removeAuthenticatedClient(uint64_t clientId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
|
||||
bool RpcServer::isClientAuthenticated(uint64_t clientId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
return authenticatedClients_.contains(clientId);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,203 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/SessionManager.hpp"
|
||||
#include <format>
|
||||
#include <iomanip>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
SessionManager::SessionManager() = default;
|
||||
|
||||
SessionManager::SessionManager(const Config& config) : config_(config) {}
|
||||
|
||||
bool SessionManager::initialize()
|
||||
{
|
||||
running_ = true;
|
||||
ECHOION_LOG_INFO(std::format(
|
||||
"SessionManager initialized: max {} sessions, timeout {}s",
|
||||
config_.maxSessions, config_.sessionTimeout.count()));
|
||||
return true;
|
||||
}
|
||||
|
||||
void SessionManager::shutdown()
|
||||
{
|
||||
running_ = false;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sessions_.clear();
|
||||
ECHOION_LOG_INFO("SessionManager shut down");
|
||||
}
|
||||
|
||||
std::string SessionManager::createSession(uint64_t clientId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
// Check capacity
|
||||
if (sessions_.size() >= config_.maxSessions) {
|
||||
ECHOION_LOG_WARNING(
|
||||
"Session capacity reached, rejecting new session");
|
||||
return "";
|
||||
}
|
||||
|
||||
// Generate unique token
|
||||
std::string token = generateToken();
|
||||
|
||||
Session session;
|
||||
session.clientId = clientId;
|
||||
session.authToken = token;
|
||||
session.lastActivity = std::chrono::steady_clock::now();
|
||||
session.createdAt = session.lastActivity;
|
||||
session.isAuthenticated = false;
|
||||
|
||||
sessions_[token] = std::move(session);
|
||||
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("Created session for client {}", clientId));
|
||||
return token;
|
||||
}
|
||||
|
||||
bool SessionManager::authenticateSession(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = sessions_.find(token);
|
||||
if (it == sessions_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
it->second.isAuthenticated = true;
|
||||
it->second.lastActivity = std::chrono::steady_clock::now();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SessionManager::validateSession(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = sessions_.find(token);
|
||||
if (it == sessions_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check timeout
|
||||
auto elapsed =
|
||||
std::chrono::steady_clock::now() - it->second.lastActivity;
|
||||
if (elapsed > config_.sessionTimeout) {
|
||||
sessions_.erase(it);
|
||||
return false;
|
||||
}
|
||||
|
||||
return it->second.isAuthenticated;
|
||||
}
|
||||
|
||||
void SessionManager::updateActivity(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = sessions_.find(token);
|
||||
if (it != sessions_.end()) {
|
||||
it->second.lastActivity = std::chrono::steady_clock::now();
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<SessionManager::Session>
|
||||
SessionManager::getSession(const std::string& token) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = sessions_.find(token);
|
||||
if (it != sessions_.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void SessionManager::endSession(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
sessions_.erase(token);
|
||||
}
|
||||
|
||||
void SessionManager::endSessionByClientId(uint64_t clientId)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
for (auto it = sessions_.begin(); it != sessions_.end();) {
|
||||
if (it->second.clientId == clientId) {
|
||||
it = sessions_.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<SessionManager::Session> SessionManager::getAllSessions() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
std::vector<Session> result;
|
||||
result.reserve(sessions_.size());
|
||||
|
||||
for (const auto& [token, session] : sessions_) {
|
||||
result.push_back(session);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
size_t SessionManager::getSessionCount() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return sessions_.size();
|
||||
}
|
||||
|
||||
size_t SessionManager::cleanupExpiredSessions()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
size_t cleaned = 0;
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
|
||||
for (auto it = sessions_.begin(); it != sessions_.end();) {
|
||||
auto elapsed = now - it->second.lastActivity;
|
||||
if (elapsed > config_.sessionTimeout) {
|
||||
it = sessions_.erase(it);
|
||||
cleaned++;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (cleaned > 0) {
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("Cleaned up {} expired sessions", cleaned));
|
||||
}
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
bool SessionManager::isAtCapacity() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return sessions_.size() >= config_.maxSessions;
|
||||
}
|
||||
|
||||
std::string SessionManager::generateToken()
|
||||
{
|
||||
// Generate random 32-byte token
|
||||
static std::random_device rd;
|
||||
static std::mt19937 gen(rd());
|
||||
static std::uniform_int_distribution<> dis(0, 255);
|
||||
|
||||
std::stringstream ss;
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
ss << std::hex << std::setw(2) << std::setfill('0') << dis(gen);
|
||||
}
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+754
-671
File diff suppressed because it is too large.
Load diff
+198
-174
@@ -1,192 +1,216 @@
|
||||
#include "LoggerInterface.hpp"
|
||||
#include "echoion/core/SubscriptionManager.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
SubscriptionManager::SubscriptionManager() = default;
|
||||
SubscriptionManager::SubscriptionManager() = default;
|
||||
|
||||
SubscriptionManager::~SubscriptionManager() {
|
||||
shutdown();
|
||||
}
|
||||
SubscriptionManager::~SubscriptionManager() { shutdown(); }
|
||||
|
||||
Api::Result<void> SubscriptionManager::initialize(std::shared_ptr<Api::Database> database) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (initialized_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
database_ = std::move(database);
|
||||
if (!database_) {
|
||||
return std::unexpected(Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"Database not available"));
|
||||
}
|
||||
|
||||
// Load existing subscriptions from database
|
||||
auto result = database_->getAllSubscribers();
|
||||
if (!result) {
|
||||
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}", result.error().message));
|
||||
// Not fatal - start with empty subscriptions
|
||||
} else {
|
||||
for (const auto& subscriber : *result) {
|
||||
subscribedUids_.insert(subscriber.uid);
|
||||
}
|
||||
}
|
||||
|
||||
initialized_ = true;
|
||||
ECHOION_LOG_INFO(std::format("SubscriptionManager initialized ({} subscribers)",
|
||||
subscribedUids_.size()));
|
||||
return {};
|
||||
}
|
||||
Api::Result<void>
|
||||
SubscriptionManager::initialize(std::shared_ptr<Api::Database> database)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
void SubscriptionManager::shutdown() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
if (!initialized_) {
|
||||
return;
|
||||
}
|
||||
|
||||
initialized_ = false;
|
||||
database_.reset();
|
||||
subscribedUids_.clear();
|
||||
ECHOION_LOG_INFO("SubscriptionManager shutdown");
|
||||
}
|
||||
if (initialized_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
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 (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(uid, nickname);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Failed to add subscriber {} to database: {}",
|
||||
uid, result.error().message));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
subscribedUids_.insert(uid);
|
||||
ECHOION_LOG_INFO(std::format("Client {} ({}) subscribed", nickname, uid));
|
||||
return true;
|
||||
}
|
||||
database_ = std::move(database);
|
||||
if (!database_) {
|
||||
return std::unexpected(Api::Error(
|
||||
Api::ErrorCode::ServiceUnavailable, "Database not available"));
|
||||
}
|
||||
|
||||
bool SubscriptionManager::unsubscribe(const std::string& uid) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
bool removed = subscribedUids_.erase(uid) > 0;
|
||||
if (removed) {
|
||||
// Remove from database
|
||||
if (database_) {
|
||||
auto result = database_->removeSubscriber(uid);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Failed to remove subscriber {} from database: {}",
|
||||
uid, result.error().message));
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
// Load existing subscriptions from database
|
||||
auto result = database_->getAllSubscribers();
|
||||
if (!result) {
|
||||
ECHOION_LOG_WARNING(std::format("Failed to load subscriptions: {}",
|
||||
result.error().message));
|
||||
// Not fatal - start with empty subscriptions
|
||||
} else {
|
||||
for (const auto& subscriber : *result) {
|
||||
subscribedUids_.insert(subscriber.uid);
|
||||
}
|
||||
}
|
||||
|
||||
bool SubscriptionManager::isSubscribed(const std::string& uid) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return subscribedUids_.contains(uid);
|
||||
}
|
||||
initialized_ = true;
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("SubscriptionManager initialized ({} subscribers)",
|
||||
subscribedUids_.size()));
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<std::string> SubscriptionManager::getSubscribedUids() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return std::vector<std::string>(subscribedUids_.begin(), subscribedUids_.end());
|
||||
}
|
||||
void SubscriptionManager::shutdown()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
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;
|
||||
}
|
||||
if (!initialized_) {
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
initialized_ = false;
|
||||
database_.reset();
|
||||
subscribedUids_.clear();
|
||||
ECHOION_LOG_INFO("SubscriptionManager shutdown");
|
||||
}
|
||||
|
||||
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::subscribe(const std::string& uid,
|
||||
const std::string& nickname)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
bool SubscriptionManager::hasSubscribers() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return !subscribedUids_.empty();
|
||||
}
|
||||
// Check if already subscribed (ensures uniqueness)
|
||||
if (subscribedUids_.contains(uid)) {
|
||||
// Update nickname even if already subscribed
|
||||
if (database_) {
|
||||
database_->addSubscriber(uid, nickname);
|
||||
}
|
||||
return false; // Already subscribed
|
||||
}
|
||||
|
||||
size_t SubscriptionManager::getSubscriberCount() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return subscribedUids_.size();
|
||||
}
|
||||
// Add to database first
|
||||
if (database_) {
|
||||
auto result = database_->addSubscriber(uid, nickname);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Failed to add subscriber {} to database: {}",
|
||||
uid, result.error().message));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
subscribedUids_.insert(uid);
|
||||
ECHOION_LOG_INFO(
|
||||
std::format("Client {} ({}) subscribed", nickname, uid));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SubscriptionManager::unsubscribe(const std::string& uid)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
bool removed = subscribedUids_.erase(uid) > 0;
|
||||
if (removed) {
|
||||
// Remove from database
|
||||
if (database_) {
|
||||
auto result = database_->removeSubscriber(uid);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Failed to remove subscriber {} from database: {}", uid,
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO(std::format("Client {} unsubscribed", uid));
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
bool SubscriptionManager::isSubscribed(const std::string& uid) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return subscribedUids_.contains(uid);
|
||||
}
|
||||
|
||||
std::vector<std::string> SubscriptionManager::getSubscribedUids() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
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 !subscribedUids_.empty();
|
||||
}
|
||||
|
||||
size_t SubscriptionManager::getSubscriberCount() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
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
|
||||
+148
-131
@@ -1,144 +1,161 @@
|
||||
#include "echoion/core/UrlShortener.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/UrlShortener.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <format>
|
||||
#include <glaze/glaze.hpp>
|
||||
|
||||
namespace Echoion::Core {
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
|
||||
: networkClient_(std::move(networkClient)) {
|
||||
}
|
||||
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
|
||||
: networkClient_(std::move(networkClient))
|
||||
{
|
||||
}
|
||||
|
||||
UrlShortener::~UrlShortener() = default;
|
||||
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::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"));
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
if (!networkClient_) {
|
||||
return std::unexpected(
|
||||
Api::Error(Api::ErrorCode::ServiceUnavailable,
|
||||
"Network client not available"));
|
||||
}
|
||||
|
||||
void UrlShortener::clearCache() {
|
||||
std::lock_guard<std::mutex> lock(cacheMutex_);
|
||||
cache_.clear();
|
||||
}
|
||||
// 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";
|
||||
|
||||
void UrlShortener::setCacheTtl(std::chrono::hours ttl) {
|
||||
cacheTtl_ = ttl;
|
||||
}
|
||||
// Build JSON request body - API expects "longUrl" field
|
||||
std::string jsonBody =
|
||||
std::format(R"({{"longUrl":"{}"}})", originalUrl);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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"}
|
||||
auto parsed = Void::Json::parse(response->body);
|
||||
if (!parsed) {
|
||||
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;
|
||||
const Void::Json::Value* shortUrl = parsed->find("shortUrl");
|
||||
if (shortUrl && shortUrl->is_string()) {
|
||||
shortenedUrl = shortUrl->as_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
|
||||
+1449
-1346
File diff suppressed because it is too large.
Load diff
+620
-627
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,109 @@
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include "echoion/core/commands/RpcInfoCommand.hpp"
|
||||
#include <ConfigManager.hpp>
|
||||
#include <format>
|
||||
#include <future>
|
||||
#include <regex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
std::string getPublicIpAddress()
|
||||
{
|
||||
// Try to get public IP from external services
|
||||
static std::string cachedIp;
|
||||
static std::chrono::steady_clock::time_point lastFetch;
|
||||
|
||||
// Cache IP for 5 minutes to avoid excessive API calls
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
if (!cachedIp.empty() &&
|
||||
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch)
|
||||
.count() < 5) {
|
||||
return cachedIp;
|
||||
}
|
||||
|
||||
// List of services to try
|
||||
const std::vector<std::string> ipServices = {
|
||||
"https://api.ipify.org", "https://checkip.amazonaws.com",
|
||||
"https://icanhazip.com", "https://ifconfig.me/ip"};
|
||||
|
||||
// Create a temporary network client for IP lookup
|
||||
auto networkClient = std::make_shared<NetworkClient>();
|
||||
auto initResult = networkClient->initialize();
|
||||
if (!initResult) {
|
||||
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
|
||||
}
|
||||
|
||||
for (const auto& service : ipServices) {
|
||||
try {
|
||||
auto result = networkClient->get(service);
|
||||
if (result && result->isSuccess()) {
|
||||
// Extract IP from response body (trim whitespace)
|
||||
std::string ip = result->body;
|
||||
// Remove whitespace and newlines
|
||||
ip.erase(std::remove_if(ip.begin(), ip.end(),
|
||||
[](unsigned char c) {
|
||||
return std::isspace(c);
|
||||
}),
|
||||
ip.end());
|
||||
|
||||
// Validate IP format (basic check)
|
||||
std::regex ipRegex(
|
||||
R"(^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)");
|
||||
if (std::regex_match(ip, ipRegex)) {
|
||||
cachedIp = ip;
|
||||
lastFetch = now;
|
||||
return cachedIp;
|
||||
}
|
||||
}
|
||||
} catch (...) {
|
||||
// Try next service
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Return cached IP or localhost if all services failed
|
||||
return cachedIp.empty() ? "127.0.0.1" : cachedIp;
|
||||
}
|
||||
|
||||
void RpcInfoCommand::execute(const CommandContext& ctx)
|
||||
{
|
||||
// Get RPC configuration from global ConfigManager
|
||||
const auto& networkConfig = ECHOION_NETWORK;
|
||||
uint16_t rpcPort = networkConfig.rpcPort;
|
||||
std::string rpcBindAddress = networkConfig.rpcBindAddress;
|
||||
|
||||
// Determine the public IP to show
|
||||
std::string publicIp = getPublicIpAddress();
|
||||
|
||||
// If bind address is not localhost, use it
|
||||
if (rpcBindAddress != "127.0.0.1" && rpcBindAddress != "localhost") {
|
||||
publicIp = rpcBindAddress;
|
||||
}
|
||||
|
||||
// Format message using plain text (compatible with TS3 BBCode and TS6
|
||||
// Markdown)
|
||||
std::string message = std::format(
|
||||
"**RPC Server Information**\n\n"
|
||||
"The RPC server allows remote control via WebSocket API.\n\n"
|
||||
"**Connection Details:**\n"
|
||||
"Address: {}:{}\n"
|
||||
"Protocol: WebSocket (ws://)\n\n"
|
||||
"**To connect:**\n"
|
||||
"1. Subscribe to the bot with !subscribe\n"
|
||||
"2. Connect to ws://{}:{}\n"
|
||||
"3. Send auth request with your nickname: "
|
||||
"{{\"nickname\":\"YourName\"}}\n"
|
||||
"4. Check your TeamSpeak PM for the token\n"
|
||||
"5. Authenticate with: {{\"token\":\"YOUR_TOKEN\"}}\n\n"
|
||||
"**Available endpoints:**\n"
|
||||
"- Playback control (play, pause, skip, volume)\n"
|
||||
"- Queue management\n"
|
||||
"- Track information\n"
|
||||
"- Real-time event updates",
|
||||
publicIp, rpcPort, publicIp, rpcPort);
|
||||
|
||||
ctx.reply(message);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,73 @@
|
||||
#include "echoion/core/state/StateMigration.hpp"
|
||||
#include "echoion/core/state/StateSerializer.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
Api::Result<StateV1> StateMigration::migrate(uint32_t fromVersion,
|
||||
const std::string& jsonData)
|
||||
{
|
||||
// Migration chain: fromVersion -> ... -> CURRENT_VERSION
|
||||
// For now, only V0 -> V1 is implemented
|
||||
// Future: V1 -> V2, V2 -> V3, etc.
|
||||
|
||||
if (fromVersion == 0) {
|
||||
auto parsed = Void::Json::parse(jsonData);
|
||||
if (!parsed) {
|
||||
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
|
||||
"Failed to parse V0 state"});
|
||||
}
|
||||
auto v0 = Void::Json::from_json<StateV0>(*parsed);
|
||||
if (!v0) {
|
||||
return std::unexpected(Api::Error{Api::ErrorCode::ParseError,
|
||||
"Failed to parse V0 state"});
|
||||
}
|
||||
return fromV0(*v0);
|
||||
}
|
||||
|
||||
// Add more migrations here as versions evolve
|
||||
// if (fromVersion == 1) { return fromV1(...); }
|
||||
|
||||
return std::unexpected(Api::Error{
|
||||
Api::ErrorCode::IncompatibleVersion,
|
||||
std::format("No migration path from version {}", fromVersion)});
|
||||
}
|
||||
|
||||
StateV1 StateMigration::fromV0(const StateV0& v0)
|
||||
{
|
||||
StateV1 v1;
|
||||
|
||||
// Migrate queue
|
||||
for (const auto& trackId : v0.trackIds) {
|
||||
StateV1::QueueEntryState entry;
|
||||
entry.track.id = trackId;
|
||||
entry.track.title = "Unknown";
|
||||
entry.track.artist = "Unknown";
|
||||
v1.queue.push_back(std::move(entry));
|
||||
}
|
||||
|
||||
// Migrate playback state
|
||||
if (!v1.queue.empty()) {
|
||||
StateV1::PlaybackState playback;
|
||||
playback.currentTrack = v1.queue[0].track;
|
||||
playback.volume = v0.volume;
|
||||
v1.playback = std::move(playback);
|
||||
v1.hasPlayback = true;
|
||||
}
|
||||
|
||||
v1.version = 1;
|
||||
v1.savedAt = StateSerializer::getCurrentTimestampISO8601();
|
||||
|
||||
return v1;
|
||||
}
|
||||
|
||||
bool StateMigration::canMigrate(uint32_t fromVersion)
|
||||
{
|
||||
return fromVersion >= StateSerializer::getMinimumSupportedVersion() &&
|
||||
fromVersion < StateSerializer::getCurrentVersion();
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,144 @@
|
||||
// #include "echoion/api/base/StateBlob.hpp"
|
||||
#include "echoion/core/state/StateMigration.hpp"
|
||||
#include "echoion/core/state/StateSerializer.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <format>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
Api::StateBlob StateSerializer::serialize(const StateV1& state)
|
||||
{
|
||||
// Serialize to JSON using Void::Json reflection
|
||||
std::string jsonStr =
|
||||
Void::Json::serialize(Void::Json::to_json(state));
|
||||
|
||||
// Convert to binary blob
|
||||
std::vector<uint8_t> data(jsonStr.begin(), jsonStr.end());
|
||||
|
||||
return Api::StateBlob{.data = std::move(data),
|
||||
.version = CURRENT_VERSION,
|
||||
.timestamp = getCurrentTimestampISO8601()};
|
||||
}
|
||||
|
||||
Api::Result<StateV1>
|
||||
StateSerializer::deserialize(const Api::StateBlob& blob)
|
||||
{
|
||||
if (blob.data.empty()) {
|
||||
return std::unexpected(Api::Error{Api::ErrorCode::InvalidArgument,
|
||||
"Empty state blob"});
|
||||
}
|
||||
|
||||
// Convert blob to string
|
||||
std::string jsonStr(blob.data.begin(), blob.data.end());
|
||||
|
||||
// Extract version
|
||||
uint32_t dataVersion = extractVersion(jsonStr);
|
||||
|
||||
// Check if version is supported
|
||||
if (!isVersionSupported(dataVersion)) {
|
||||
if (dataVersion > CURRENT_VERSION) {
|
||||
return std::unexpected(Api::Error{
|
||||
Api::ErrorCode::IncompatibleVersion,
|
||||
std::format("State version {} is from a newer Core. "
|
||||
"Please update/restart to load this state.",
|
||||
dataVersion)});
|
||||
} else {
|
||||
return std::unexpected(Api::Error{
|
||||
Api::ErrorCode::IncompatibleVersion,
|
||||
std::format("State version {} is too old. "
|
||||
"Maximum supported age is {} versions.",
|
||||
dataVersion,
|
||||
Api::MAX_SUPPORTED_STATE_VERSION_AGE)});
|
||||
}
|
||||
}
|
||||
|
||||
// If current version, parse directly
|
||||
if (dataVersion == CURRENT_VERSION) {
|
||||
auto parsed = Void::Json::parse(jsonStr);
|
||||
if (!parsed) {
|
||||
return std::unexpected(Api::Error{
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("Failed to parse state ({}:{}): {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message)});
|
||||
}
|
||||
auto state = Void::Json::from_json<StateV1>(*parsed);
|
||||
if (!state) {
|
||||
return std::unexpected(Api::Error{
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("Failed to decode state: field '{}': {}",
|
||||
state.error().field, state.error().message)});
|
||||
}
|
||||
return *state;
|
||||
}
|
||||
|
||||
// Otherwise, migrate
|
||||
return StateMigration::migrate(dataVersion, jsonStr);
|
||||
}
|
||||
|
||||
bool StateSerializer::isVersionSupported(uint32_t version)
|
||||
{
|
||||
if (version > CURRENT_VERSION) {
|
||||
return false; // Future version
|
||||
}
|
||||
|
||||
uint32_t minVersion = getMinimumSupportedVersion();
|
||||
return version >= minVersion && version <= CURRENT_VERSION;
|
||||
}
|
||||
|
||||
uint32_t StateSerializer::getMinimumSupportedVersion()
|
||||
{
|
||||
// Support 10 versions back, but not below 1
|
||||
return (CURRENT_VERSION > Api::MAX_SUPPORTED_STATE_VERSION_AGE)
|
||||
? CURRENT_VERSION - Api::MAX_SUPPORTED_STATE_VERSION_AGE
|
||||
: 1;
|
||||
}
|
||||
|
||||
uint32_t StateSerializer::getCurrentVersion() { return CURRENT_VERSION; }
|
||||
|
||||
uint32_t StateSerializer::extractVersion(const std::string& jsonStr)
|
||||
{
|
||||
// Quick extraction without full parse
|
||||
// Look for "version": N pattern
|
||||
size_t pos = jsonStr.find("\"version\"");
|
||||
if (pos != std::string::npos) {
|
||||
pos = jsonStr.find(':', pos);
|
||||
if (pos != std::string::npos) {
|
||||
// Skip whitespace
|
||||
pos++;
|
||||
while (pos < jsonStr.size() &&
|
||||
std::isspace(static_cast<unsigned char>(jsonStr[pos]))) {
|
||||
pos++;
|
||||
}
|
||||
// Parse number
|
||||
if (pos < jsonStr.size() &&
|
||||
std::isdigit(static_cast<unsigned char>(jsonStr[pos]))) {
|
||||
try {
|
||||
return static_cast<uint32_t>(
|
||||
std::stoul(jsonStr.substr(pos)));
|
||||
} catch (...) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Default to 0 (unknown/legacy)
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string StateSerializer::getCurrentTimestampISO8601()
|
||||
{
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto time_t_now = std::chrono::system_clock::to_time_t(now);
|
||||
|
||||
std::stringstream ss;
|
||||
ss << std::put_time(std::gmtime(&time_t_now), "%Y-%m-%dT%H:%M:%SZ");
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Reference in new issue
Block a user