From 6aed7b0027b8b955589345a7ea35e98c35eaf78d Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 19 Jan 2026 15:36:21 +0300 Subject: [PATCH] own implementation of singleton and logger --- CMakeLists.txt | 11 - include/Core/Logger.hpp | 321 +++++++++++++++++++++++++ include/Core/Plugin.hpp | 13 +- include/Core/PluginDefinitions.hpp | 9 +- include/Core/Singleton.hpp | 77 ++++++ include/Core/SingletonManager.hpp | 30 +++ include/Core/Youtube/Client.hpp | 35 ++- include/Core/ts6bot/AudioDecoder.hpp | 6 +- include/Core/ts6bot/Config.hpp | 16 +- include/Core/ts6bot/Log.hpp | 22 -- include/Core/ts6bot/MusicManager.hpp | 14 +- include/Core/ts6bot/SignalShutdown.hpp | 17 -- include/Shared/SignalShutdown.hpp | 49 ++++ src/Core/AudioDecoder.cpp | 6 +- src/Core/MusicManager.cpp | 103 ++++++-- src/Core/Plugin.cpp | 77 +++--- src/Core/SignalShutdown.cpp | 39 --- src/Core/Youtube/Client.cpp | 86 ++++++- src/Plugin/Plugin.cpp | 20 +- 19 files changed, 745 insertions(+), 206 deletions(-) create mode 100644 include/Core/Logger.hpp create mode 100644 include/Core/Singleton.hpp create mode 100644 include/Core/SingletonManager.hpp delete mode 100644 include/Core/ts6bot/Log.hpp delete mode 100644 include/Core/ts6bot/SignalShutdown.hpp create mode 100644 include/Shared/SignalShutdown.hpp delete mode 100644 src/Core/SignalShutdown.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ecf323d..9037db7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,7 +16,6 @@ file( include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake) # ---- Deps: libssh2 ---- -find_package(quill REQUIRED) find_package(glaze REQUIRED) find_package(GStreamer REQUIRED) find_package(PkgConfig REQUIRED) @@ -39,14 +38,6 @@ CPMAddPackage( GITHUB_REPOSITORY quickjs-ng/quickjs GIT_TAG v0.11.0 ) -CPMAddPackage( - NAME singleton - GITHUB_REPOSITORY jimmy-park/singleton - GIT_TAG 1.6.0 - OPTIONS - "SINGLETON_INSTALL ON" - "SINGLETON_INJECT_ABSTRACT_CLASS ON" -) file(GLOB_RECURSE PSOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/Plugin/**.cpp") @@ -87,10 +78,8 @@ target_compile_options(${CMAKE_PROJECT_NAME}Plugin PRIVATE ) target_link_libraries(${CMAKE_PROJECT_NAME}Core PUBLIC - quill::quill glaze::glaze cpr::cpr - singleton::singleton-atomic pthread PkgConfig::LIBAV qjs ) target_link_libraries(${CMAKE_PROJECT_NAME}Plugin PUBLIC diff --git a/include/Core/Logger.hpp b/include/Core/Logger.hpp new file mode 100644 index 0000000..28404b2 --- /dev/null +++ b/include/Core/Logger.hpp @@ -0,0 +1,321 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "Singleton.hpp" + +class Logger : public Singleton { + friend class Singleton; + + // ANSI Color codes + struct Colors { + static constexpr auto RESET = "\033[0m"; + static constexpr auto TRACE = "\033[37m"; // White + static constexpr auto DEBUG = "\033[36m"; // Cyan + static constexpr auto INFO = "\033[32m"; // Green + static constexpr auto WARNING = "\033[33m"; // Yellow + static constexpr auto ERROR = "\033[31m"; // Red + static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red + }; + + // Internal structure to hold log data in the queue + struct LogEntry { + std::chrono::system_clock::time_point timestamp; + std::thread::id threadId; + std::source_location sourceLoc; + ts6bot::LogLevel level; + std::string message; // Pre-formatted user message + }; + +public: + explicit Logger(const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info) + : m_minLevel(logLevel), m_exit(false) + { + // 1. Setup File Sinks (Synchronous init) + try { + namespace fs = std::filesystem; + const fs::path logDir = "logs"; + if (!fs::exists(logDir)) fs::create_directories(logDir); + + // Time for filename (UTC) + const auto now = std::chrono::system_clock::now(); + auto now_utc = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), now}; + std::string timestamp = std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc); + + // Open trace file (all logs) + std::string traceFilename = std::format("trace_{}.log", timestamp); + m_logFiles[ts6bot::LogLevel::Trace].open(logDir / traceFilename, std::ios::out | std::ios::app); + + // Open error file + std::string errorFilename = std::format("error_{}.log", timestamp); + m_logFiles[ts6bot::LogLevel::Error].open(logDir / errorFilename, std::ios::out | std::ios::app); + + // Open warning file + std::string warningFilename = std::format("warning_{}.log", timestamp); + m_logFiles[ts6bot::LogLevel::Warning].open(logDir / warningFilename, std::ios::out | std::ios::app); + + // Open critical file + std::string criticalFilename = std::format("critical_{}.log", timestamp); + m_logFiles[ts6bot::LogLevel::Critical].open(logDir / criticalFilename, std::ios::out | std::ios::app); + + // Check if files opened successfully + for (const auto& [level, file] : m_logFiles) { + if (!file.is_open()) { + std::println(std::cerr, "Logger Error: Failed to open log file for level: {}", levelToString(level)); + } + } + } catch (const std::exception& e) { + std::println(std::cerr, "Logger Initialization Error: {}", e.what()); + } + + // 2. Start Worker Thread + m_workerThread = std::jthread([this](const std::stop_token &st) { + this->workerLoop(st); + }); + } + + ~Logger() override { + // Signal exit and wake up worker + m_exit = true; + m_cv.notify_one(); + // m_workerThread destructor will wait for join automatically + + // Close all log files + for (auto &file: m_logFiles | std::views::values) { + if (file.is_open()) { + file.close(); + } + } + } + + // --- Public Logging API --- + + // Generic log function + template + void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string fmt, Args&&... args) { + if (level < m_minLevel || level == ts6bot::LogLevel::None) return; + + try { + // 1. Capture context immediately + + // 3. Push to Queue + { + LogEntry entry{ + .timestamp = std::chrono::system_clock::now(), + .threadId = std::this_thread::get_id(), + .sourceLoc = loc, + .level = level, + // 2. Format message immediately (capture by value) to avoid dangling references + .message = std::format(fmt, std::forward(args)...) + }; + std::lock_guard lock(m_queueMutex); + m_logQueue.push_back(std::move(entry)); + } + m_cv.notify_one(); + + } catch (const std::exception& e) { + // Fallback if formatting fails + std::println(std::cerr, "Logging Error: {}", e.what()); + } + } + + // Convenience Wrappers + template + void trace(std::format_string fmt, Args&&... args) { + log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward(args)...); + } + + template + void info(std::format_string fmt, Args&&... args) { + log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward(args)...); + } + + template + void error(std::format_string fmt, Args&&... args) { + log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward(args)...); + } + + template + void warn(std::format_string fmt, Args&&... args) { + log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward(args)...); + } + + template + void debug(std::format_string fmt, Args&&... args) { + log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward(args)...); + } + + template + void critical(std::format_string fmt, Args&&... args) { + log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward(args)...); + } + + void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; } + +private: + // --- Backend Worker --- + void workerLoop(std::stop_token st) { + while (!st.stop_requested() || !isQueueEmpty()) { + std::unique_lock lock(m_queueMutex); + + // Wait until data is available or stop is requested + m_cv.wait(lock, [this, &st] { + return !m_logQueue.empty() || st.stop_requested() || m_exit; + }); + + if (m_logQueue.empty()) { + if (st.stop_requested() || m_exit) break; + continue; + } + + // Swap queue to local buffer to minimize lock time + std::deque localQueue; + std::swap(localQueue, m_logQueue); + lock.unlock(); + + // Process Batch + for (const auto& entry : localQueue) { + writeLog(entry); + } + } + } + + bool isQueueEmpty() { + std::lock_guard lock(m_queueMutex); + return m_logQueue.empty(); + } + + void writeLog(const LogEntry& entry) { + // Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line LOG_LEVEL message" + + auto utc_time = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), entry.timestamp}; + + // Extract nanoseconds + const auto duration = entry.timestamp.time_since_epoch(); + const auto seconds = std::chrono::duration_cast(duration); + const auto nanoseconds = std::chrono::duration_cast(duration - seconds); + + // Format source location + std::string sourceLocation = std::format("{}:{}", + entry.sourceLoc.file_name(), + entry.sourceLoc.line()); + + // Get thread ID as integer + std::ostringstream threadIdStream; + threadIdStream << entry.threadId; + std::string threadIdStr = threadIdStream.str(); + + // Construct log without colors (for file) + const std::string fileLog = std::format("{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n", + utc_time, + nanoseconds.count(), + threadIdStr, + sourceLocation, + levelToString(entry.level), + entry.message + ); + + // Construct colored log (for console) + const char* color = getColorForLevel(entry.level); + std::string consoleLog = std::format("{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n", + color, + utc_time, + nanoseconds.count(), + Colors::RESET, + threadIdStr, + sourceLocation, + color, + levelToString(entry.level), + Colors::RESET, + entry.message + ); + + // Print to Console with colors + std::print(std::cout, "{}", consoleLog); + + // Write to trace file (all logs) - no colors + if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) { + m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog; + m_logFiles.at(ts6bot::LogLevel::Trace).flush(); + } + + // Write to specific level files - no colors + if (entry.level == ts6bot::LogLevel::Error && m_logFiles.at(ts6bot::LogLevel::Error).is_open()) { + m_logFiles.at(ts6bot::LogLevel::Error) << fileLog; + m_logFiles.at(ts6bot::LogLevel::Error).flush(); + } + else if (entry.level == ts6bot::LogLevel::Warning && m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) { + m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog; + m_logFiles.at(ts6bot::LogLevel::Warning).flush(); + } + else if (entry.level == ts6bot::LogLevel::Critical && m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) { + m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog; + m_logFiles.at(ts6bot::LogLevel::Critical).flush(); + } + } + + static const char* getColorForLevel(const ts6bot::LogLevel level) { + switch (level) { + case ts6bot::LogLevel::Trace: return Colors::TRACE; + case ts6bot::LogLevel::Debug: return Colors::DEBUG; + case ts6bot::LogLevel::Info: return Colors::INFO; + case ts6bot::LogLevel::Warning: return Colors::WARNING; + case ts6bot::LogLevel::Error: return Colors::ERROR; + case ts6bot::LogLevel::Critical: return Colors::CRITICAL; + default: return Colors::RESET; + } + } + + static std::string_view levelToString(const ts6bot::LogLevel level) { + switch (level) { + case ts6bot::LogLevel::Trace: return "TRACE"; + case ts6bot::LogLevel::Debug: return "DEBUG"; + case ts6bot::LogLevel::Info: return "INFO"; + case ts6bot::LogLevel::Warning: return "WARNING"; + case ts6bot::LogLevel::Error: return "ERROR"; + case ts6bot::LogLevel::Critical: return "CRITICAL"; + default: return "UNKNOWN"; + } + } + +private: + ts6bot::LogLevel m_minLevel; + std::unordered_map m_logFiles; + + // Concurrency + std::deque m_logQueue; + std::mutex m_queueMutex; + std::condition_variable m_cv; + std::jthread m_workerThread; + std::atomic m_exit; +}; + +#define LOG_IF_ALIVE(level, fmt, ...) \ +do { \ +if (Logger::isAlive()) { \ +Logger::getInstance()->log(level, std::source_location::current(), fmt __VA_OPT__(,) __VA_ARGS__); \ +} \ +} while (0) + +// --- Public API Macros --- +#define LOG_TRACE(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(,) __VA_ARGS__) +#define LOG_DEBUG(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(,) __VA_ARGS__) +#define LOG_INFO(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(,) __VA_ARGS__) +#define LOG_WARN(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(,) __VA_ARGS__) +#define LOG_ERROR(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(,) __VA_ARGS__) +#define LOG_CRITICAL(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(,) __VA_ARGS__) \ No newline at end of file diff --git a/include/Core/Plugin.hpp b/include/Core/Plugin.hpp index c678a51..e541b2e 100644 --- a/include/Core/Plugin.hpp +++ b/include/Core/Plugin.hpp @@ -3,16 +3,8 @@ // #include "Youtube/Client.hpp" #include "ts6bot/AudioDecoder.hpp" #include -#include -#include -#include -#include -#include -#include #include "ts6bot/Config.hpp" #include -#include "quill/sinks/FileSink.h" -#include "quill/sinks/ConsoleSink.h" #include #include "PluginDefinitions.hpp" @@ -20,7 +12,6 @@ class EchoionCore : public IEchoionPlugin { // Dependencies - quill::Logger *m_logger = nullptr; std::shared_ptr m_ts3; std::unique_ptr m_musicManager; @@ -415,5 +406,7 @@ extern "C" { return new EchoionCore(std::make_shared(*funcs)); } - void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; } + void DestroyPlugin(const IEchoionPlugin *plugin) { + delete plugin; + } } diff --git a/include/Core/PluginDefinitions.hpp b/include/Core/PluginDefinitions.hpp index df5ed41..d8b99d0 100644 --- a/include/Core/PluginDefinitions.hpp +++ b/include/Core/PluginDefinitions.hpp @@ -26,13 +26,15 @@ namespace definitions { struct QueueItem { std::string name; std::string videoId; + std::string shortUrl; + std::string length; std::string requester; std::optional streams; QueueItem() = default; - QueueItem(std::string name, std::string videoId, std::string requested_by, const std::optional & streams) - : name{std::move(name)}, videoId(std::move(videoId)), requester{std::move(requested_by)}, streams{streams} {} + QueueItem(std::string name, std::string videoId,std::string shortUrl,std::string length, std::string requested_by, const std::optional & streams) + : name{std::move(name)}, videoId(std::move(videoId)),shortUrl(std::move(shortUrl)), length(std::move(length)), requester{std::move(requested_by)}, streams{streams} {} }; @@ -43,6 +45,7 @@ namespace definitions { std::string thumbnail; std::string viewCount; std::string url; + std::string shortUrl; std::string videoId; }; @@ -71,6 +74,6 @@ template <> struct glz::meta { template <> struct glz::meta { using T = definitions::QueueItem; static constexpr auto value = - object("name", &T::name, "videoId", &T::videoId, "requester", &T::requester, + object("name", &T::name, "videoId", &T::videoId, "shortUrl", &T::shortUrl, "length", &T::length, "requester", &T::requester, "streams", &T::streams); }; \ No newline at end of file diff --git a/include/Core/Singleton.hpp b/include/Core/Singleton.hpp new file mode 100644 index 0000000..1ce9aed --- /dev/null +++ b/include/Core/Singleton.hpp @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include + +/** + * @brief C++26 Smart Singleton for DLL Hot-Reloading. + * Uses shared_ptr to ensure memory safety across thread boundaries + * during forceful destruction and DLL unloads. + */ +template +class Singleton { +private: + // This "Token" trick allows std::shared_ptr to create the object + // even if T's constructor is private/protected. + struct ConstructorProxy : public T { + template + ConstructorProxy(Args&&... args) : T(std::forward(args)...) {} + }; +public: + // Delete copy/move + Singleton(const Singleton&) = delete; + Singleton& operator=(const Singleton&) = delete; + + template + static std::shared_ptr init(Args&&... args) { + auto ptr = m_instance.load(std::memory_order_acquire); + if (ptr) return ptr; + + std::lock_guard lock(m_lifecycle_mutex); + ptr = m_instance.load(std::memory_order_relaxed); + if (!ptr) { + // We wrap T in ConstructorProxy so 'new' works here, + // but the resulting shared_ptr is still shared_ptr. + ptr = std::make_shared(std::forward(args)...); + m_instance.store(ptr, std::memory_order_release); + } + return ptr; + } + + /** + * @brief Access the existing instance. + * @throws std::runtime_error if init() hasn't been called yet. + */ + static std::shared_ptr getInstance() { + auto ptr = m_instance.load(std::memory_order_acquire); + if (!ptr) { + throw std::runtime_error("Singleton accessed via get() before init()!"); + } + return ptr; + } + + /** + * @brief Safe destruction for DLL unloading. + * Shared_ptr ensures that threads currently using the instance + * don't crash; the memory is freed only when the last reference drops. + */ + static void destroyInstance() { + std::lock_guard lock(m_lifecycle_mutex); + m_instance.store(nullptr, std::memory_order_release); + } + + static bool isAlive() { + return m_instance.load(std::memory_order_acquire) != nullptr; + } + +protected: + Singleton() = default; + virtual ~Singleton() = default; + +private: + // atomic is a C++20 feature, perfect for C++26 + static inline std::atomic> m_instance{nullptr}; + static inline std::mutex m_lifecycle_mutex; +}; \ No newline at end of file diff --git a/include/Core/SingletonManager.hpp b/include/Core/SingletonManager.hpp new file mode 100644 index 0000000..f1800ba --- /dev/null +++ b/include/Core/SingletonManager.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +class SingletonManager { +public: + // Priority: Higher numbers are destroyed LAST (e.g., Logger = 100) + static void registerShutdown(const int priority, const std::function &shutdownFunc) { + m_registry.push_back({priority, shutdownFunc}); + // Sort so that high priority stays at the end (destroyed last) + std::ranges::sort(m_registry, [](const auto& a, const auto& b) { + return a.priority < b.priority; + }); + } + + static void shutdownAll() { + // Destroy in reverse priority (highest priority first? No, usually reverse order of arrival) + // Here we destroy from lowest priority to highest. + for (auto& [priority, func] : m_registry) { + std::cerr << priority << ": " << &func << std::endl; + func(); + } + m_registry.clear(); + } + +private: + struct Entry { int priority; std::function func; }; + static inline std::vector m_registry; +}; diff --git a/include/Core/Youtube/Client.hpp b/include/Core/Youtube/Client.hpp index 4033eee..8fd2609 100644 --- a/include/Core/Youtube/Client.hpp +++ b/include/Core/Youtube/Client.hpp @@ -15,7 +15,7 @@ #include // Project (Assuming similar structure to your Spotify bot) #include - +#include #include namespace YouTube { @@ -40,6 +40,23 @@ struct Snippet { std::string liveBroadcastContent; std::string publishTime; }; + struct PlayListResourceId { + std::string kind; + std::string videoId; + }; + struct PlayListSnippet{ + std::string publishedAt; + std::string channelId; + std::string title; + std::string description; + std::map thumbnails; + std::string channelTitle; + std::string playlistId; + int position; + PlayListResourceId resourceId; + std::string videoOwnerChannelTitle; + std::string videoOwnerChannelId; + }; struct ResourceId { std::string kind; @@ -84,6 +101,13 @@ struct SearchResult { Snippet snippet; }; +struct SearchPlaylistResult { + std::string kind; + std::string etag; + std::string id; + PlayListSnippet snippet; +}; + // API Response Wrappers template struct PageResult { std::string kind; @@ -151,7 +175,9 @@ struct SearchParams { std::string videoDuration = "any"; // any, long, medium, short bool rawQuery = false; // Set to true to preserve -, |, etc. in query }; - + struct ShortenResponse { + std::string shortUrl; + }; // ============================================================================ // Main YouTube Client // ============================================================================ @@ -178,6 +204,8 @@ public: void SetAccessToken(std::string token) { m_AccessToken = std::move(token); } void SetApiKey(std::string key) { m_ApiKey = std::move(key); } + auto ShortUrl(const std::string& url) const -> Result; + // ======================================================================== // Search API // ======================================================================== @@ -214,8 +242,9 @@ public: // https://developers.google.com/youtube/v3/docs/playlistItems/list auto GetPlaylistItems(const std::string &playlistId, const std::string &pageToken = "") - -> Result>; // Reusing SearchResult as structure + -> Result>; // Reusing SearchResult as structure // is similar enough for snippet + auto GetPlaylistVideos(const std::string& playlistId) -> Result>; // ======================================================================== // Player API (The "Extraction" Logic) // ======================================================================== diff --git a/include/Core/ts6bot/AudioDecoder.hpp b/include/Core/ts6bot/AudioDecoder.hpp index 3b3322c..e2f94d8 100644 --- a/include/Core/ts6bot/AudioDecoder.hpp +++ b/include/Core/ts6bot/AudioDecoder.hpp @@ -8,6 +8,8 @@ #include #include +#include "Logger.hpp" + extern "C" { #include #include @@ -37,10 +39,6 @@ public: bool IsFinished() const { return m_finished.load(); } private: - void Log(const std::string &msg) { - std::lock_guard lock(m_logMtx); - std::cout << "[AudioDecoder] " << msg << std::endl; - } void Cleanup(); void InternalDecode(std::string url, int targetSampleRate); std::atomic m_status{DecodeStatus::Idle}; diff --git a/include/Core/ts6bot/Config.hpp b/include/Core/ts6bot/Config.hpp index f657fab..7b2808e 100644 --- a/include/Core/ts6bot/Config.hpp +++ b/include/Core/ts6bot/Config.hpp @@ -1,15 +1,24 @@ #pragma once #include #include -#include #include #include #include +#include "Singleton.hpp" + namespace ts6bot { -enum class LogLevel { Critical, Error, Warning, Info, Trace }; + enum class LogLevel { + Trace, + Debug, + Info, + Warning, + Error, + Critical, + None +}; struct ServerQueryConfig { std::string host{"127.0.0.1"}; @@ -48,7 +57,8 @@ struct Config { ProxyConfiguration proxy{}; }; -class Configuration : public SingletonAtomic { + class Configuration : public Singleton { + friend class Singleton; public: const Config getConfig() const noexcept { return m_config; } diff --git a/include/Core/ts6bot/Log.hpp b/include/Core/ts6bot/Log.hpp deleted file mode 100644 index a93b14c..0000000 --- a/include/Core/ts6bot/Log.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include - -#include "quill/Backend.h" -#include "quill/Frontend.h" -#include "quill/LogMacros.h" -#include "quill/Logger.h" -#include "quill/sinks/FileSink.h" -#include "quill/sinks/ConsoleSink.h" - -namespace ts6bot { - -class Log { -public: - static void init(std::string_view file_path); - static quill::Logger* logger(); - -private: - static quill::Logger* g_logger; -}; - -} // namespace ts6bot diff --git a/include/Core/ts6bot/MusicManager.hpp b/include/Core/ts6bot/MusicManager.hpp index 829608f..06e1fc8 100644 --- a/include/Core/ts6bot/MusicManager.hpp +++ b/include/Core/ts6bot/MusicManager.hpp @@ -10,22 +10,21 @@ #include #include #include -#include #include #include #include #include #include -#include -#include #include class MusicManager { public: - explicit MusicManager(std::shared_ptr functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID = 0); + explicit MusicManager(std::shared_ptr functions, std::uint64_t serverConnectionHandlerID = 0); ~MusicManager(); struct Music { std::string name; + std::string shortUrl; + std::string length; std::string videoId; std::string requestedBy; YouTube::Result streams; @@ -54,13 +53,15 @@ public: std::optional getCurrent() const { return m_current; } void removeFromQueue(std::size_t index); void removeFromQueue(const std::string &name); - void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& req, std::optional streams); + void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& shortUrl, const std::string& length, const std::string& req, std::optional streams); void checkQueueAndPlay(); // Youtube / Search std::vector search(std::string name, int maxResults = 5) const; void playUrl(std::string url, const std::string &requester = ""); - + void playPlaylist(const std::string& playlistId, const std::string& requester); + // Helper to extract playlist ID from URL + std::optional extractPlaylistId(std::string_view url); // Selection Logic // Stores the results for a specific user to select later void storePendingSearch(anyID clientId, @@ -72,7 +73,6 @@ private: static std::string formatDuration(const std::string &isoDuration); void updateWhisperList(); - quill::Logger* m_logger; std::shared_ptr m_functions{nullptr}; std::unique_ptr m_microphone{nullptr}; std::unique_ptr m_client{nullptr}; diff --git a/include/Core/ts6bot/SignalShutdown.hpp b/include/Core/ts6bot/SignalShutdown.hpp deleted file mode 100644 index a9a9aa6..0000000 --- a/include/Core/ts6bot/SignalShutdown.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include -#include - -class SignalShutdown { -public: - explicit SignalShutdown(std::function onShutdown); - ~SignalShutdown(); - - SignalShutdown(const SignalShutdown&) = delete; - SignalShutdown& operator=(const SignalShutdown&) = delete; - -private: - std::function m_OnShutdown; - std::thread m_Thread; - bool m_Running = true; -}; diff --git a/include/Shared/SignalShutdown.hpp b/include/Shared/SignalShutdown.hpp new file mode 100644 index 0000000..95b3db9 --- /dev/null +++ b/include/Shared/SignalShutdown.hpp @@ -0,0 +1,49 @@ +#pragma once +#include +#include +#include +class SignalShutdown { +public: + explicit SignalShutdown(std::function onShutdown) + : m_OnShutdown(std::move(onShutdown)) + { + // Block signals in this thread (and thus in subsequently created threads) + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGINT); + sigaddset(&set, SIGTERM); + sigaddset(&set, SIGHUP); + sigaddset(&set, SIGQUIT); + pthread_sigmask(SIG_BLOCK, &set, nullptr); + + m_Thread = std::jthread([this, set]() mutable { + while (m_Running) { + int sig = 0; + if (sigwait(&set, &sig) == 0) { + if (!m_Running) break; + if (m_OnShutdown) m_OnShutdown(); + // After requesting shutdown once, allow main to exit + break; + } + } + }); + } + ~SignalShutdown() { + m_Running = false; + // Send a signal to unblock sigwait if desired; easiest is detach-safe join + if (m_Thread.joinable()) { + // If main exits without signals, thread may still be blocked in sigwait. + // In that case, process teardown ends it anyway; but we prefer not to hang. + // So we simply detach. + m_Thread.detach(); + } + } + + SignalShutdown(const SignalShutdown&) = delete; + SignalShutdown& operator=(const SignalShutdown&) = delete; + +private: + std::function m_OnShutdown; + std::jthread m_Thread; + bool m_Running = true; +}; diff --git a/src/Core/AudioDecoder.cpp b/src/Core/AudioDecoder.cpp index 3ed8763..d74d3b6 100644 --- a/src/Core/AudioDecoder.cpp +++ b/src/Core/AudioDecoder.cpp @@ -63,7 +63,7 @@ void AudioDecoder::StartDecode(const std::string &url, int targetSampleRate) { } void AudioDecoder::InternalDecode(std::string url, int targetSampleRate) { - auto config = ts6bot::Configuration::GetInstance()->getConfig(); + auto config = ts6bot::Configuration::getInstance()->getConfig(); AVPacket *pkt = nullptr; AVFrame *frame = nullptr; uint8_t *outputBuffer = nullptr; @@ -144,7 +144,7 @@ void AudioDecoder::InternalDecode(std::string url, int targetSampleRate) { av_samples_alloc(&outputBuffer, nullptr, 2, maxSamples, AV_SAMPLE_FMT_S16, 0); - Log("Decoder initialized. Starting stream..."); + LOG_DEBUG("Decoder initialized. Starting stream..."); while (!m_cancelRequested) { int readRet = av_read_frame(m_formatCtx, pkt); if (readRet == AVERROR_EOF) @@ -221,5 +221,5 @@ void AudioDecoder::InternalDecode(std::string url, int targetSampleRate) { av_freep(&outputBuffer); av_frame_free(&frame); av_packet_free(&pkt); - Log("Internal thread exited."); + LOG_DEBUG("Internal thread exited."); } diff --git a/src/Core/MusicManager.cpp b/src/Core/MusicManager.cpp index f206a19..9833a72 100644 --- a/src/Core/MusicManager.cpp +++ b/src/Core/MusicManager.cpp @@ -10,11 +10,12 @@ #include #include #include -#include -MusicManager::MusicManager(std::shared_ptr functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID) - : m_logger(logger), m_functions(std::move(functions)), m_serverConnectionHandlerID(serverConnectionHandlerID) { - auto config = ts6bot::Configuration::GetInstance()->getConfig(); +#include "Logger.hpp" + +MusicManager::MusicManager(std::shared_ptr functions, std::uint64_t serverConnectionHandlerID) + : m_functions(std::move(functions)), m_serverConnectionHandlerID(serverConnectionHandlerID) { + auto config = ts6bot::Configuration::getInstance()->getConfig(); m_client = std::make_unique(config.music.youtubeApiToken); m_client->SetProxy(static_cast(config.proxy)); @@ -23,7 +24,7 @@ MusicManager::MusicManager(std::shared_ptr functions, quill::Logge err != ERROR_ok) { char *errorMsg = nullptr; m_functions->getErrorMessage(err, &errorMsg); - LOG_ERROR(m_logger, "Unable to register custom device: {}", errorMsg); + LOG_ERROR("Unable to register custom device: {}", errorMsg); m_functions->freeMemory(errorMsg); } @@ -76,7 +77,7 @@ std::vector MusicManager::search(std::string name auto searchRes = m_client->Search(params); if (!searchRes) { - LOG_ERROR(m_logger, "Search failed: {} - {}", searchRes.error().status, searchRes.error().message); + LOG_ERROR("Search failed: {} - {}", searchRes.error().status, searchRes.error().message); return {}; } @@ -91,15 +92,19 @@ std::vector MusicManager::search(std::string name auto videosRes = m_client->GetVideos(videoIds); std::vector resultItems; + if (!videosRes) { - LOG_WARNING(m_logger, "Failed to fetch video details, using snippets."); + LOG_WARN("Failed to fetch video details, using snippets."); for (const auto &item : searchRes->items) { + auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" + item.id.videoId); + resultItems.push_back( {.name = item.snippet.title, .length = "??:??", .thumbnail = item.snippet.thumbnails.empty() ? "" : item.snippet.thumbnails.begin()->second.url, .viewCount = "N/A", .url = "https://youtube.com/watch?v=" + item.id.videoId, + .shortUrl = shortUrl.value_or(""), .videoId = item.id.videoId}); } return resultItems; @@ -113,6 +118,7 @@ std::vector MusicManager::search(std::string name else thumbUrl = video.snippet.thumbnails.begin()->second.url; } + auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" + video.id); resultItems.push_back( {.name = video.snippet.title, @@ -120,6 +126,7 @@ std::vector MusicManager::search(std::string name .thumbnail = thumbUrl, .viewCount = video.statistics.viewCount, .url = "https://youtube.com/watch?v=" + video.id, + .shortUrl = shortUrl.value_or(""), .videoId = video.id}); } @@ -129,40 +136,86 @@ std::vector MusicManager::search(std::string name // ============================================================================ // Playback & Queue // ============================================================================ +std::optional MusicManager::extractPlaylistId(std::string_view url) { + static const std::regex pl_pattern(R"(list=([a-zA-Z0-9_-]+))", std::regex::icase); + std::cmatch match; + if (std::regex_search(url.data(), match, pl_pattern)) { + return match[1].str(); + } + return std::nullopt; +} +void MusicManager::playPlaylist(const std::string& playlistId, const std::string& requester) { + LOG_INFO("Fetching playlist: {}", playlistId); + + auto videos = m_client->GetPlaylistVideos(playlistId); + if (!videos || videos->empty()) { + LOG_ERROR("Failed to load playlist items for {}", playlistId); + return; + } + + std::lock_guard lock(m_queueMtx); + for (const auto& video : *videos) { + // Optimization: We skip calling m_client->ShortUrl() here + // to prevent hitting rate limits on large playlists. + std::string shortUrl; + if (const auto url = m_client->ShortUrl("https://youtube.com/watch?v=" + video.id); url) { + shortUrl = url.value_or(""); + } + auto vid = Music{ .name = video.snippet.title, + .shortUrl = shortUrl, // Set to empty to save requests + .length = formatDuration(video.contentDetails.duration), + .videoId = video.id, + .requestedBy = requester, + .streams = definitions::Streams() // Will be resolved by the loop thread when played + }; + m_queue.emplace_back(vid); + } + + LOG_INFO("Added {} videos from playlist to queue.", videos->size()); + m_cv.notify_one(); +} void MusicManager::playUrl(std::string url, const std::string &requester) { const auto videoIdOpt = m_client->ExtractVideoId(url); if (!videoIdOpt) { - LOG_WARNING(m_logger, "Invalid YouTube URI: {}", url); + LOG_WARN("Invalid YouTube URI: {}", url); return; } const std::string& vid = *videoIdOpt; std::string title = "Unknown Title"; - - if (const auto videoInfo = m_client->GetVideo(vid, "snippet")) { + std::string shortUrl; + std::string length; + if (const auto videoInfo = m_client->GetVideo(vid, "snippet,contentDetails")) { title = videoInfo->snippet.title; + length = formatDuration(videoInfo->contentDetails.duration); + } + if (const auto url = m_client->ShortUrl("https://youtube.com/watch?v=" + vid)) { + shortUrl = url.value_or(""); } - { std::lock_guard lock(m_queueMtx); // Fetch streams immediately (Note: This might be blocking, consider doing it in the loop if UI hangs) m_queue.push_back({.name = title, + .shortUrl = shortUrl, + .length =length, .videoId = vid, .requestedBy = requester, .streams = m_client->GetBestStreams(vid)}); } - LOG_INFO(m_logger, "Added to queue: {}", title); + LOG_INFO("Added to queue: {}", title); m_cv.notify_one(); // Wake up loop } -void MusicManager::addToQueueDirect(const std::string& vid, const std::string& title, +void MusicManager::addToQueueDirect(const std::string& vid, const std::string& title,const std::string& shortUrl, const std::string& length, const std::string& req, std::optional streams) { std::lock_guard lock(m_queueMtx); Music m; m.name = title; m.videoId = vid; m.requestedBy = req; + m.shortUrl = shortUrl; + m.length = length; if(streams) { m.streams = YouTube::Result(streams.value()); } @@ -216,7 +269,7 @@ void MusicManager::loop(std::stop_token st) { // Initial setup delay std::this_thread::sleep_for(std::chrono::seconds(5)); - auto config = ts6bot::Configuration::GetInstance()->getConfig(); + auto config = ts6bot::Configuration::getInstance()->getConfig(); if (m_serverConnectionHandlerID == 0) { // Connect GUI Tab if (auto err = m_functions->guiConnect( @@ -226,7 +279,7 @@ void MusicManager::loop(std::stop_token st) { &m_serverConnectionHandlerID); err != ERROR_ok) { char* msg; m_functions->getErrorMessage(err, &msg); - LOG_ERROR(m_logger, "GUI Connect failed: {}", msg); + LOG_ERROR("GUI Connect failed: {}", msg); m_functions->freeMemory(msg); } } @@ -235,10 +288,10 @@ void MusicManager::loop(std::stop_token st) { m_functions->closePlaybackDevice(m_serverConnectionHandlerID); if(m_functions->openCaptureDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok) - LOG_ERROR(m_logger, "Failed to open Capture Device"); + LOG_ERROR("Failed to open Capture Device"); if(m_functions->openPlaybackDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok) - LOG_ERROR(m_logger, "Failed to open Playback Device"); + LOG_ERROR("Failed to open Playback Device"); m_microphone = std::make_unique(); constexpr int SAMPLE_RATE = 192000; @@ -263,17 +316,17 @@ void MusicManager::loop(std::stop_token st) { m_isIdle = false; // 2. Resolve Streams if needed (Hot reload might have provided them, new search might not) if (!m_current->streams || m_current->streams->audio.url.empty()) { - LOG_INFO(m_logger, "Resolving streams for {}", m_current->name); + LOG_INFO("Resolving streams for {}", m_current->name); m_current->streams = m_client->GetBestStreams(m_current->videoId); } if (!m_current->streams || m_current->streams->audio.url.empty()) { - LOG_ERROR(m_logger, "Failed to get stream for {}", m_current->name); + LOG_ERROR("Failed to get stream for {}", m_current->name); m_current = std::nullopt; continue; } - LOG_INFO(m_logger, "Now Playing: {}", m_current->name); + LOG_INFO("Now Playing: {}", m_current->name); // 3. Start Decoding m_microphone->StartDecode(m_current->streams->audio.url, SAMPLE_RATE); @@ -351,12 +404,12 @@ void MusicManager::loop(std::stop_token st) { } m_microphone->Cancel(); - LOG_INFO(m_logger, "Finished track: {}", m_current->name); + LOG_INFO("Finished track: {}", m_current->name); m_current = std::nullopt; // Check for Graceful Stop (Update) if (m_stopAfterCurrent) { - LOG_INFO(m_logger, "Graceful stop requested. Stopping main loop."); + LOG_INFO("Graceful stop requested. Stopping main loop."); break; } } @@ -376,7 +429,7 @@ void MusicManager::addSubscriberToOnline(anyID id) { m_offlineSubscribers.erase(id); m_onlineSubscribers.insert(id); updateWhisperList(); - LOG_INFO(m_logger, "User {} added to Online Subscribers", id); + LOG_INFO("User {} added to Online Subscribers", id); } void MusicManager::addSubscriberToOffline(const anyID id) { @@ -384,7 +437,7 @@ void MusicManager::addSubscriberToOffline(const anyID id) { m_onlineSubscribers.erase(id); m_offlineSubscribers.insert(id); updateWhisperList(); - LOG_INFO(m_logger, "User {} added to Offline Subscribers", id); + LOG_INFO("User {} added to Offline Subscribers", id); } @@ -404,7 +457,7 @@ void MusicManager::unSubscribe(anyID id) { m_onlineSubscribers.erase(id); m_offlineSubscribers.erase(id); updateWhisperList(); - LOG_INFO(m_logger, "User {} Unsubscribed", id); + LOG_INFO("User {} Unsubscribed", id); } std::set MusicManager::getOnlineSubscribers() const { std::lock_guard lock(const_cast(m_subMtx)); diff --git a/src/Core/Plugin.cpp b/src/Core/Plugin.cpp index 96616d5..cac0ea2 100644 --- a/src/Core/Plugin.cpp +++ b/src/Core/Plugin.cpp @@ -1,49 +1,23 @@ #include +#include "Logger.hpp" + void EchoionCore::Initialize(bool start) { // Init Logger - try { - quill::BackendOptions backend_options; - backend_options.check_printable_char = {}; - quill::Backend::start(backend_options); - // m_logger = quill::getor("Core", quill::file_handler("echoion.log", "w")); - auto console_sink = quill::Frontend::create_or_get_sink("console"); - auto file_sink = quill::Frontend::create_or_get_sink( - "logs/echoion.log", - []() - { - quill::FileSinkConfig cfg {}; - cfg.set_open_mode('w'); - cfg.set_filename_append_option(quill::FilenameAppendOption::StartDateTime); - return cfg; - }(), - quill::FileEventNotifier{}); - quill::PatternFormatterOptions pfo; - pfo.format_pattern = - "%(time) [%(thread_id)] %(source_location:<28) " - "%(log_level:<9) %(message)"; - pfo.timestamp_pattern = ("%H:%M:%S.%Qns"); - pfo.timestamp_timezone = quill::Timezone::GmtTime; - - m_logger = quill::Frontend::create_or_get_logger("root", {std::move(file_sink),std::move(console_sink)}, pfo); - m_logger->set_log_level(quill::LogLevel::TraceL1); - LOG_INFO(m_logger, "Core Initializing..."); + Logger::init(ts6bot::LogLevel::Trace); + LOG_INFO("Core Initializing..."); // Config char path[512]; m_ts3->getConfigPath(path, 512); - ts6bot::Configuration::Construct(std::string(path) + "bot.json"); // Services - auto cfg = ts6bot::Configuration::GetInstance()->getConfig(); + auto cfg = ts6bot::Configuration::init(std::string(path) + "bot.json")->getConfig(); if (start) { - m_musicManager = std::make_unique(m_ts3, m_logger); + m_musicManager = std::make_unique(m_ts3); } - } - catch (const std::exception &e) { - std::cerr << e.what() << std::endl; - } // Ignore if already active + } void EchoionCore::Shutdown() { @@ -51,7 +25,8 @@ void EchoionCore::Initialize(bool start) { m_musicManager->stop(); m_musicManager.reset(); } - quill::Backend::stop(); + ts6bot::Configuration::destroyInstance(); + Logger::destroyInstance(); } // --- HOT RELOAD --- @@ -72,7 +47,7 @@ void EchoionCore::Initialize(bool start) { auto q = m_musicManager->getQueue(); for (const auto &i : q) { std::optional streams = (i.streams.has_value() ? std::optional(i.streams.value()) : std::nullopt); - auto temp = definitions::QueueItem(i.name, i.videoId, i.requestedBy, streams); + auto temp = definitions::QueueItem(i.name, i.videoId,i.shortUrl,i.length, i.requestedBy, streams); state.queue.push_back(temp); } auto subs = m_musicManager->getOnlineSubscribers(); @@ -89,14 +64,14 @@ void EchoionCore::Initialize(bool start) { void EchoionCore::DeserializeState(const std::string &jsonState) { definitions::PluginState state; if (auto err = glz::read_json(state, jsonState); !err) { - if (m_musicManager) - m_musicManager = std::make_unique(m_ts3, m_logger, state.serverConnection); + if (!m_musicManager) + m_musicManager = std::make_unique(m_ts3, state.serverConnection); for (auto s : state.onlineSubscribers) m_musicManager->addSubscriberToOnline(s); for (auto s : state.offlineSubscribers) m_musicManager->addSubscriberToOffline(s); for (const auto &item : state.queue) { - m_musicManager->addToQueueDirect(item.videoId, item.name, + m_musicManager->addToQueueDirect(item.videoId, item.name, item.shortUrl, item.length, item.requester, item.streams); } m_musicManager->setServerConnectionHandlerID(state.serverConnection); @@ -107,6 +82,8 @@ void EchoionCore::Initialize(bool start) { int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targetMode, anyID toID, anyID fromID, const char *fromName, const char *fromUniqueIdentifier, const char *message, int ffIgnored) { + if (!m_musicManager) + return 1; auto reply = [this](const uint64 sc, const anyID toId, const std::string &text) { const char* returnCode = nullptr; this->m_ts3->requestSendPrivateTextMsg(sc, text.c_str(), toId,returnCode); @@ -148,18 +125,25 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targ } else if (results.size() == 1) { this->m_musicManager->playUrl(results[0].url, fromName); this->m_ts3->requestSendPrivateTextMsg( - serverConnectionHandlerID, ("Playing: " + results[0].name).c_str(), fromID, nullptr); + serverConnectionHandlerID, std::format("Playing: [{}]({})", results[0].name, results[0].shortUrl).c_str(), fromID, nullptr); } else { this->m_musicManager->storePendingSearch(fromID, results); std::string list = "Multiple results found. Use .select :\n"; for (size_t i = 0; i < results.size(); ++i) { - list += std::format("{}. {} [{}]\n",(i+1), results[i].name, results[i].length); + list += std::format("{}. [{}]({}) [{}]\n",(i+1), results[i].name, results[i].shortUrl, results[i].length); } this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, list.c_str(), fromID, nullptr); } } - } - else if (command == ".select") { + } else if (command == ".playlist") { + if (args.find("http") == 0) { + if (auto plId = this->m_musicManager->extractPlaylistId(args)) { + this->m_musicManager->playPlaylist(*plId, fromName); + this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, "Added PlayList to queue.", fromID, + nullptr); + } + } + } else if (command == ".select") { try { int idx = std::stoi(args); if (this->m_musicManager->selectSearchResult(fromID, idx, fromName)) { @@ -183,14 +167,15 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targ auto q = this->m_musicManager->getQueue(); auto current = this->m_musicManager->getCurrent(); std::string str = - current ? std::format("Now playing: {}\n\n", current.value().name) + current ? std::format("Now playing: [{}]({}) [{}]\n\n", current.value().name, current.value().shortUrl,current.value().length) : ""; if (q.empty() && str.empty()) reply(serverConnectionHandlerID, fromID, "Queue is empty"); for (auto i = 0; i < q.size(); i++) { - str += std::format("{}. {}\n", i, q.at(i).name); + LOG_DEBUG("Adding to list {}", q.at(i).name); + str += std::format("{}. [{}]({}) [{}]\n", i+1, q.at(i).name, q.at(i).shortUrl, q.at(i).length); } reply(serverConnectionHandlerID, fromID, str); } else if (command == ".sub") { @@ -202,7 +187,7 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targ } else if (command == ".help") { reply(serverConnectionHandlerID, fromID, ".play <ссылка или название>\n.select " - "<#>\n.stop\n.skip\\next\n.queue\\list\n.sub\n" + "<#>\n.playlist <ссылка в которой есть \"list=\">\n.stop\n.skip\\next\n.queue\\list\n.sub\n" ".unsub"); } @@ -212,6 +197,8 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targ void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char *moveMessage) { + if (!m_musicManager) + return; anyID myID; this->m_ts3->getClientID(serverConnectionHandlerID, &myID); if (clientID == myID) diff --git a/src/Core/SignalShutdown.cpp b/src/Core/SignalShutdown.cpp deleted file mode 100644 index 57769f3..0000000 --- a/src/Core/SignalShutdown.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "ts6bot/SignalShutdown.hpp" -#include -#include - -SignalShutdown::SignalShutdown(std::function onShutdown) - : m_OnShutdown(std::move(onShutdown)) -{ - // Block signals in this thread (and thus in subsequently created threads) - sigset_t set; - sigemptyset(&set); - sigaddset(&set, SIGINT); - sigaddset(&set, SIGTERM); - sigaddset(&set, SIGHUP); - sigaddset(&set, SIGQUIT); - pthread_sigmask(SIG_BLOCK, &set, nullptr); - - m_Thread = std::thread([this, set]() mutable { - while (m_Running) { - int sig = 0; - if (sigwait(&set, &sig) == 0) { - if (!m_Running) break; - if (m_OnShutdown) m_OnShutdown(); - // After requesting shutdown once, allow main to exit - break; - } - } - }); -} - -SignalShutdown::~SignalShutdown() { - m_Running = false; - // Send a signal to unblock sigwait if desired; easiest is detach-safe join - if (m_Thread.joinable()) { - // If main exits without signals, thread may still be blocked in sigwait. - // In that case, process teardown ends it anyway; but we prefer not to hang. - // So we simply detach. - m_Thread.detach(); - } -} diff --git a/src/Core/Youtube/Client.cpp b/src/Core/Youtube/Client.cpp index 4b24bbe..5e402af 100644 --- a/src/Core/Youtube/Client.cpp +++ b/src/Core/Youtube/Client.cpp @@ -7,6 +7,7 @@ #include "cpr/proxyauth.h" #include "cpr/response.h" #include "cpr/session.h" +#include #include #include #include @@ -16,6 +17,9 @@ #include #include #include + +#include "Logger.hpp" +#include "cpr/api.h" using json = nlohmann::json; namespace YouTube { @@ -25,7 +29,6 @@ namespace YouTube { Client::Client(std::string apiKey, std::string accessToken) : m_ApiKey(std::move(apiKey)), m_AccessToken(std::move(accessToken)) { - // Initialize QuickJS m_rt = JS_NewRuntime(); JS_SetMemoryLimit(m_rt, 64 * 1024 * 1024); @@ -111,6 +114,33 @@ std::string Client::SolveChallenge(const std::string &challenge, return out; } + auto Client::ShortUrl(const std::string& url) const -> Result { + try { + // Prepare the JSON body for your Express server + std::string jsonBody = std::format(R"({{"longUrl": "{}"}})", url); + + auto response = cpr::Post( + cpr::Url{"https://faumaray.ru/shorten"}, + cpr::Body{jsonBody}, + cpr::Header{{"Content-Type", "application/json"}}, + cpr::Timeout{2000} // 2s timeout so the bot doesn't hang + ); + + if (response.status_code == 200) { + ShortenResponse res; + auto glz_err = glz::read_json(res, response.text); + if (!glz_err) { + return res.shortUrl; + } + } + LOG_WARN("Shortener failed (Code: {}), using original URL", response.status_code); + } catch (const std::exception& e) { + LOG_ERROR("Shortener exception: {}", e.what()); + } + return url; // Fallback to long URL on failure +} + + auto Client::GetBestStreams(const std::string &videoId) -> Result { // 1. Get base.js and signatureTimestamp via Watch Page auto watchPage = PerformRequest( @@ -127,7 +157,7 @@ auto Client::GetBestStreams(const std::string &videoId) -> Result results; @@ -599,6 +629,40 @@ auto Client::GetVideo(const std::string &id, const std::string &part) return res->at(0); } + // Add to your Client class implementation + auto Client::GetPlaylistVideos(const std::string& playlistId) -> Result> { + std::vector