own implementation of singleton and logger
This commit is contained in:
1 parent
f6c5bcca39
commit
6aed7b0027
19 files changed
+744
-205
No files matched your search
@@ -16,7 +16,6 @@ file(
|
|||||||
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)
|
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)
|
||||||
|
|
||||||
# ---- Deps: libssh2 ----
|
# ---- Deps: libssh2 ----
|
||||||
find_package(quill REQUIRED)
|
|
||||||
find_package(glaze REQUIRED)
|
find_package(glaze REQUIRED)
|
||||||
find_package(GStreamer REQUIRED)
|
find_package(GStreamer REQUIRED)
|
||||||
find_package(PkgConfig REQUIRED)
|
find_package(PkgConfig REQUIRED)
|
||||||
@@ -39,14 +38,6 @@ CPMAddPackage(
|
|||||||
GITHUB_REPOSITORY quickjs-ng/quickjs
|
GITHUB_REPOSITORY quickjs-ng/quickjs
|
||||||
GIT_TAG v0.11.0
|
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")
|
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
|
target_link_libraries(${CMAKE_PROJECT_NAME}Core PUBLIC
|
||||||
quill::quill
|
|
||||||
glaze::glaze
|
glaze::glaze
|
||||||
cpr::cpr
|
cpr::cpr
|
||||||
singleton::singleton-atomic
|
|
||||||
pthread PkgConfig::LIBAV qjs
|
pthread PkgConfig::LIBAV qjs
|
||||||
)
|
)
|
||||||
target_link_libraries(${CMAKE_PROJECT_NAME}Plugin PUBLIC
|
target_link_libraries(${CMAKE_PROJECT_NAME}Plugin PUBLIC
|
||||||
|
|||||||
@@ -0,0 +1,321 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <fstream>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <format>
|
||||||
|
#include <print>
|
||||||
|
#include <chrono>
|
||||||
|
#include <source_location>
|
||||||
|
#include <mutex>
|
||||||
|
#include <thread>
|
||||||
|
#include <string>
|
||||||
|
#include <deque>
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <atomic>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
#include <ts6bot/Config.hpp>
|
||||||
|
|
||||||
|
#include "Singleton.hpp"
|
||||||
|
|
||||||
|
class Logger : public Singleton<Logger> {
|
||||||
|
friend class Singleton<Logger>;
|
||||||
|
|
||||||
|
// 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 <typename... Args>
|
||||||
|
void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string<Args...> 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>(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 <typename... Args>
|
||||||
|
void trace(std::format_string<Args...> fmt, Args&&... args) {
|
||||||
|
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
void info(std::format_string<Args...> fmt, Args&&... args) {
|
||||||
|
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
void error(std::format_string<Args...> fmt, Args&&... args) {
|
||||||
|
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
void warn(std::format_string<Args...> fmt, Args&&... args) {
|
||||||
|
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
void debug(std::format_string<Args...> fmt, Args&&... args) {
|
||||||
|
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward<Args>(args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
void critical(std::format_string<Args...> fmt, Args&&... args) {
|
||||||
|
log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward<Args>(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<LogEntry> 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<std::chrono::seconds>(duration);
|
||||||
|
const auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(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<ts6bot::LogLevel, std::ofstream> m_logFiles;
|
||||||
|
|
||||||
|
// Concurrency
|
||||||
|
std::deque<LogEntry> m_logQueue;
|
||||||
|
std::mutex m_queueMutex;
|
||||||
|
std::condition_variable m_cv;
|
||||||
|
std::jthread m_workerThread;
|
||||||
|
std::atomic<bool> 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__)
|
||||||
+3
-10
@@ -3,16 +3,8 @@
|
|||||||
// #include "Youtube/Client.hpp"
|
// #include "Youtube/Client.hpp"
|
||||||
#include "ts6bot/AudioDecoder.hpp"
|
#include "ts6bot/AudioDecoder.hpp"
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <quill/Backend.h>
|
|
||||||
#include <quill/Frontend.h>
|
|
||||||
#include <quill/LogMacros.h>
|
|
||||||
#include <quill/Logger.h>
|
|
||||||
#include <quill/core/SinkManager.h>
|
|
||||||
#include <singleton_atomic.hpp>
|
|
||||||
#include "ts6bot/Config.hpp"
|
#include "ts6bot/Config.hpp"
|
||||||
#include <ts6bot/MusicManager.hpp>
|
#include <ts6bot/MusicManager.hpp>
|
||||||
#include "quill/sinks/FileSink.h"
|
|
||||||
#include "quill/sinks/ConsoleSink.h"
|
|
||||||
#include <ts6bot/Proxy.hpp>
|
#include <ts6bot/Proxy.hpp>
|
||||||
|
|
||||||
#include "PluginDefinitions.hpp"
|
#include "PluginDefinitions.hpp"
|
||||||
@@ -20,7 +12,6 @@
|
|||||||
|
|
||||||
class EchoionCore : public IEchoionPlugin {
|
class EchoionCore : public IEchoionPlugin {
|
||||||
// Dependencies
|
// Dependencies
|
||||||
quill::Logger *m_logger = nullptr;
|
|
||||||
std::shared_ptr<TS3Functions> m_ts3;
|
std::shared_ptr<TS3Functions> m_ts3;
|
||||||
std::unique_ptr<MusicManager> m_musicManager;
|
std::unique_ptr<MusicManager> m_musicManager;
|
||||||
|
|
||||||
@@ -415,5 +406,7 @@ extern "C" {
|
|||||||
return new EchoionCore(std::make_shared<TS3Functions>(*funcs));
|
return new EchoionCore(std::make_shared<TS3Functions>(*funcs));
|
||||||
}
|
}
|
||||||
|
|
||||||
void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; }
|
void DestroyPlugin(const IEchoionPlugin *plugin) {
|
||||||
|
delete plugin;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -26,13 +26,15 @@ namespace definitions {
|
|||||||
struct QueueItem {
|
struct QueueItem {
|
||||||
std::string name;
|
std::string name;
|
||||||
std::string videoId;
|
std::string videoId;
|
||||||
|
std::string shortUrl;
|
||||||
|
std::string length;
|
||||||
std::string requester;
|
std::string requester;
|
||||||
std::optional<Streams> streams;
|
std::optional<Streams> streams;
|
||||||
|
|
||||||
QueueItem() = default;
|
QueueItem() = default;
|
||||||
|
|
||||||
QueueItem(std::string name, std::string videoId, std::string requested_by, const std::optional<Streams> & streams)
|
QueueItem(std::string name, std::string videoId,std::string shortUrl,std::string length, std::string requested_by, const std::optional<Streams> & streams)
|
||||||
: name{std::move(name)}, videoId(std::move(videoId)), requester{std::move(requested_by)}, streams{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 thumbnail;
|
||||||
std::string viewCount;
|
std::string viewCount;
|
||||||
std::string url;
|
std::string url;
|
||||||
|
std::string shortUrl;
|
||||||
std::string videoId;
|
std::string videoId;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -71,6 +74,6 @@ template <> struct glz::meta<definitions::Streams> {
|
|||||||
template <> struct glz::meta<definitions::QueueItem> {
|
template <> struct glz::meta<definitions::QueueItem> {
|
||||||
using T = definitions::QueueItem;
|
using T = definitions::QueueItem;
|
||||||
static constexpr auto value =
|
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);
|
"streams", &T::streams);
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <concepts>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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 <typename T>
|
||||||
|
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<typename... Args>
|
||||||
|
ConstructorProxy(Args&&... args) : T(std::forward<Args>(args)...) {}
|
||||||
|
};
|
||||||
|
public:
|
||||||
|
// Delete copy/move
|
||||||
|
Singleton(const Singleton&) = delete;
|
||||||
|
Singleton& operator=(const Singleton&) = delete;
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
static std::shared_ptr<T> 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<T>.
|
||||||
|
ptr = std::make_shared<ConstructorProxy>(std::forward<Args>(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<T> 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<shared_ptr> is a C++20 feature, perfect for C++26
|
||||||
|
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
|
||||||
|
static inline std::mutex m_lifecycle_mutex;
|
||||||
|
};
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
#include <vector>
|
||||||
|
#include <functional>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
|
class SingletonManager {
|
||||||
|
public:
|
||||||
|
// Priority: Higher numbers are destroyed LAST (e.g., Logger = 100)
|
||||||
|
static void registerShutdown(const int priority, const std::function<void()> &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<void()> func; };
|
||||||
|
static inline std::vector<Entry> m_registry;
|
||||||
|
};
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
#include <quickjs.h>
|
#include <quickjs.h>
|
||||||
// Project (Assuming similar structure to your Spotify bot)
|
// Project (Assuming similar structure to your Spotify bot)
|
||||||
#include <ts6bot/Proxy.hpp>
|
#include <ts6bot/Proxy.hpp>
|
||||||
|
#include <Logger.hpp>
|
||||||
#include <PluginDefinitions.hpp>
|
#include <PluginDefinitions.hpp>
|
||||||
|
|
||||||
namespace YouTube {
|
namespace YouTube {
|
||||||
@@ -40,6 +40,23 @@ struct Snippet {
|
|||||||
std::string liveBroadcastContent;
|
std::string liveBroadcastContent;
|
||||||
std::string publishTime;
|
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<std::string, Thumbnail> thumbnails;
|
||||||
|
std::string channelTitle;
|
||||||
|
std::string playlistId;
|
||||||
|
int position;
|
||||||
|
PlayListResourceId resourceId;
|
||||||
|
std::string videoOwnerChannelTitle;
|
||||||
|
std::string videoOwnerChannelId;
|
||||||
|
};
|
||||||
|
|
||||||
struct ResourceId {
|
struct ResourceId {
|
||||||
std::string kind;
|
std::string kind;
|
||||||
@@ -84,6 +101,13 @@ struct SearchResult {
|
|||||||
Snippet snippet;
|
Snippet snippet;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
struct SearchPlaylistResult {
|
||||||
|
std::string kind;
|
||||||
|
std::string etag;
|
||||||
|
std::string id;
|
||||||
|
PlayListSnippet snippet;
|
||||||
|
};
|
||||||
|
|
||||||
// API Response Wrappers
|
// API Response Wrappers
|
||||||
template <typename T> struct PageResult {
|
template <typename T> struct PageResult {
|
||||||
std::string kind;
|
std::string kind;
|
||||||
@@ -151,7 +175,9 @@ struct SearchParams {
|
|||||||
std::string videoDuration = "any"; // any, long, medium, short
|
std::string videoDuration = "any"; // any, long, medium, short
|
||||||
bool rawQuery = false; // Set to true to preserve -, |, etc. in query
|
bool rawQuery = false; // Set to true to preserve -, |, etc. in query
|
||||||
};
|
};
|
||||||
|
struct ShortenResponse {
|
||||||
|
std::string shortUrl;
|
||||||
|
};
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Main YouTube Client
|
// Main YouTube Client
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -178,6 +204,8 @@ public:
|
|||||||
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
|
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
|
||||||
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
|
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
|
||||||
|
|
||||||
|
auto ShortUrl(const std::string& url) const -> Result<std::string>;
|
||||||
|
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// Search API
|
// Search API
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
@@ -214,8 +242,9 @@ public:
|
|||||||
// https://developers.google.com/youtube/v3/docs/playlistItems/list
|
// https://developers.google.com/youtube/v3/docs/playlistItems/list
|
||||||
auto GetPlaylistItems(const std::string &playlistId,
|
auto GetPlaylistItems(const std::string &playlistId,
|
||||||
const std::string &pageToken = "")
|
const std::string &pageToken = "")
|
||||||
-> Result<PageResult<SearchResult>>; // Reusing SearchResult as structure
|
-> Result<PageResult<SearchPlaylistResult>>; // Reusing SearchResult as structure
|
||||||
// is similar enough for snippet
|
// is similar enough for snippet
|
||||||
|
auto GetPlaylistVideos(const std::string& playlistId) -> Result<std::vector<Video>>;
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// Player API (The "Extraction" Logic)
|
// Player API (The "Extraction" Logic)
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
#include <thread>
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "Logger.hpp"
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
#include <libavcodec/avcodec.h>
|
#include <libavcodec/avcodec.h>
|
||||||
#include <libavformat/avformat.h>
|
#include <libavformat/avformat.h>
|
||||||
@@ -37,10 +39,6 @@ public:
|
|||||||
bool IsFinished() const { return m_finished.load(); }
|
bool IsFinished() const { return m_finished.load(); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void Log(const std::string &msg) {
|
|
||||||
std::lock_guard<std::mutex> lock(m_logMtx);
|
|
||||||
std::cout << "[AudioDecoder] " << msg << std::endl;
|
|
||||||
}
|
|
||||||
void Cleanup();
|
void Cleanup();
|
||||||
void InternalDecode(std::string url, int targetSampleRate);
|
void InternalDecode(std::string url, int targetSampleRate);
|
||||||
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
|
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
|
||||||
|
|||||||
@@ -1,15 +1,24 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <singleton_atomic.hpp>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <ts6bot/Proxy.hpp>
|
#include <ts6bot/Proxy.hpp>
|
||||||
|
|
||||||
#include <glaze/glaze.hpp>
|
#include <glaze/glaze.hpp>
|
||||||
|
|
||||||
|
#include "Singleton.hpp"
|
||||||
|
|
||||||
namespace ts6bot {
|
namespace ts6bot {
|
||||||
|
|
||||||
enum class LogLevel { Critical, Error, Warning, Info, Trace };
|
enum class LogLevel {
|
||||||
|
Trace,
|
||||||
|
Debug,
|
||||||
|
Info,
|
||||||
|
Warning,
|
||||||
|
Error,
|
||||||
|
Critical,
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
struct ServerQueryConfig {
|
struct ServerQueryConfig {
|
||||||
std::string host{"127.0.0.1"};
|
std::string host{"127.0.0.1"};
|
||||||
@@ -48,7 +57,8 @@ struct Config {
|
|||||||
ProxyConfiguration proxy{};
|
ProxyConfiguration proxy{};
|
||||||
};
|
};
|
||||||
|
|
||||||
class Configuration : public SingletonAtomic<Configuration> {
|
class Configuration : public Singleton<Configuration> {
|
||||||
|
friend class Singleton<Configuration>;
|
||||||
public:
|
public:
|
||||||
const Config getConfig() const noexcept { return m_config; }
|
const Config getConfig() const noexcept { return m_config; }
|
||||||
|
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <string_view>
|
|
||||||
|
|
||||||
#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
|
|
||||||
@@ -10,22 +10,21 @@
|
|||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <singleton_atomic.hpp>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <teamspeak/public_definitions.h>
|
#include <teamspeak/public_definitions.h>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
#include <ts3_functions.h>
|
#include <ts3_functions.h>
|
||||||
#include <ts6bot/AudioDecoder.hpp>
|
#include <ts6bot/AudioDecoder.hpp>
|
||||||
#include <quill/Logger.h>
|
|
||||||
#include <quill/LogMacros.h>
|
|
||||||
#include <vector>
|
#include <vector>
|
||||||
class MusicManager {
|
class MusicManager {
|
||||||
public:
|
public:
|
||||||
explicit MusicManager(std::shared_ptr<TS3Functions> functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID = 0);
|
explicit MusicManager(std::shared_ptr<TS3Functions> functions, std::uint64_t serverConnectionHandlerID = 0);
|
||||||
~MusicManager();
|
~MusicManager();
|
||||||
|
|
||||||
struct Music {
|
struct Music {
|
||||||
std::string name;
|
std::string name;
|
||||||
|
std::string shortUrl;
|
||||||
|
std::string length;
|
||||||
std::string videoId;
|
std::string videoId;
|
||||||
std::string requestedBy;
|
std::string requestedBy;
|
||||||
YouTube::Result<definitions::Streams> streams;
|
YouTube::Result<definitions::Streams> streams;
|
||||||
@@ -54,13 +53,15 @@ public:
|
|||||||
std::optional<Music> getCurrent() const { return m_current; }
|
std::optional<Music> getCurrent() const { return m_current; }
|
||||||
void removeFromQueue(std::size_t index);
|
void removeFromQueue(std::size_t index);
|
||||||
void removeFromQueue(const std::string &name);
|
void removeFromQueue(const std::string &name);
|
||||||
void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& req, std::optional<definitions::Streams> 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<definitions::Streams> streams);
|
||||||
void checkQueueAndPlay();
|
void checkQueueAndPlay();
|
||||||
|
|
||||||
// Youtube / Search
|
// Youtube / Search
|
||||||
std::vector<definitions::SearchResultItem> search(std::string name, int maxResults = 5) const;
|
std::vector<definitions::SearchResultItem> search(std::string name, int maxResults = 5) const;
|
||||||
void playUrl(std::string url, const std::string &requester = "");
|
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<std::string> extractPlaylistId(std::string_view url);
|
||||||
// Selection Logic
|
// Selection Logic
|
||||||
// Stores the results for a specific user to select later
|
// Stores the results for a specific user to select later
|
||||||
void storePendingSearch(anyID clientId,
|
void storePendingSearch(anyID clientId,
|
||||||
@@ -72,7 +73,6 @@ private:
|
|||||||
static std::string formatDuration(const std::string &isoDuration);
|
static std::string formatDuration(const std::string &isoDuration);
|
||||||
void updateWhisperList();
|
void updateWhisperList();
|
||||||
|
|
||||||
quill::Logger* m_logger;
|
|
||||||
std::shared_ptr<TS3Functions> m_functions{nullptr};
|
std::shared_ptr<TS3Functions> m_functions{nullptr};
|
||||||
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
|
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
|
||||||
std::unique_ptr<YouTube::Client> m_client{nullptr};
|
std::unique_ptr<YouTube::Client> m_client{nullptr};
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <functional>
|
|
||||||
#include <thread>
|
|
||||||
|
|
||||||
class SignalShutdown {
|
|
||||||
public:
|
|
||||||
explicit SignalShutdown(std::function<void()> onShutdown);
|
|
||||||
~SignalShutdown();
|
|
||||||
|
|
||||||
SignalShutdown(const SignalShutdown&) = delete;
|
|
||||||
SignalShutdown& operator=(const SignalShutdown&) = delete;
|
|
||||||
|
|
||||||
private:
|
|
||||||
std::function<void()> m_OnShutdown;
|
|
||||||
std::thread m_Thread;
|
|
||||||
bool m_Running = true;
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <functional>
|
||||||
|
#include <thread>
|
||||||
|
#include <csignal>
|
||||||
|
class SignalShutdown {
|
||||||
|
public:
|
||||||
|
explicit SignalShutdown(std::function<void()> 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<void()> m_OnShutdown;
|
||||||
|
std::jthread m_Thread;
|
||||||
|
bool m_Running = true;
|
||||||
|
};
|
||||||
@@ -63,7 +63,7 @@ void AudioDecoder::StartDecode(const std::string &url, int targetSampleRate) {
|
|||||||
}
|
}
|
||||||
void AudioDecoder::InternalDecode(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;
|
AVPacket *pkt = nullptr;
|
||||||
AVFrame *frame = nullptr;
|
AVFrame *frame = nullptr;
|
||||||
uint8_t *outputBuffer = 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,
|
av_samples_alloc(&outputBuffer, nullptr, 2, maxSamples, AV_SAMPLE_FMT_S16,
|
||||||
0);
|
0);
|
||||||
|
|
||||||
Log("Decoder initialized. Starting stream...");
|
LOG_DEBUG("Decoder initialized. Starting stream...");
|
||||||
while (!m_cancelRequested) {
|
while (!m_cancelRequested) {
|
||||||
int readRet = av_read_frame(m_formatCtx, pkt);
|
int readRet = av_read_frame(m_formatCtx, pkt);
|
||||||
if (readRet == AVERROR_EOF)
|
if (readRet == AVERROR_EOF)
|
||||||
@@ -221,5 +221,5 @@ void AudioDecoder::InternalDecode(std::string url, int targetSampleRate) {
|
|||||||
av_freep(&outputBuffer);
|
av_freep(&outputBuffer);
|
||||||
av_frame_free(&frame);
|
av_frame_free(&frame);
|
||||||
av_packet_free(&pkt);
|
av_packet_free(&pkt);
|
||||||
Log("Internal thread exited.");
|
LOG_DEBUG("Internal thread exited.");
|
||||||
}
|
}
|
||||||
+78
-25
@@ -10,11 +10,12 @@
|
|||||||
#include <ranges>
|
#include <ranges>
|
||||||
#include <regex>
|
#include <regex>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <quill/Frontend.h>
|
|
||||||
|
|
||||||
MusicManager::MusicManager(std::shared_ptr<TS3Functions> functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID)
|
#include "Logger.hpp"
|
||||||
: m_logger(logger), m_functions(std::move(functions)), m_serverConnectionHandlerID(serverConnectionHandlerID) {
|
|
||||||
auto config = ts6bot::Configuration::GetInstance()->getConfig();
|
MusicManager::MusicManager(std::shared_ptr<TS3Functions> functions, std::uint64_t serverConnectionHandlerID)
|
||||||
|
: m_functions(std::move(functions)), m_serverConnectionHandlerID(serverConnectionHandlerID) {
|
||||||
|
auto config = ts6bot::Configuration::getInstance()->getConfig();
|
||||||
m_client = std::make_unique<YouTube::Client>(config.music.youtubeApiToken);
|
m_client = std::make_unique<YouTube::Client>(config.music.youtubeApiToken);
|
||||||
m_client->SetProxy(static_cast<ProxyConfig>(config.proxy));
|
m_client->SetProxy(static_cast<ProxyConfig>(config.proxy));
|
||||||
|
|
||||||
@@ -23,7 +24,7 @@ MusicManager::MusicManager(std::shared_ptr<TS3Functions> functions, quill::Logge
|
|||||||
err != ERROR_ok) {
|
err != ERROR_ok) {
|
||||||
char *errorMsg = nullptr;
|
char *errorMsg = nullptr;
|
||||||
m_functions->getErrorMessage(err, &errorMsg);
|
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);
|
m_functions->freeMemory(errorMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +77,7 @@ std::vector<definitions::SearchResultItem> MusicManager::search(std::string name
|
|||||||
|
|
||||||
auto searchRes = m_client->Search(params);
|
auto searchRes = m_client->Search(params);
|
||||||
if (!searchRes) {
|
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 {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,15 +92,19 @@ std::vector<definitions::SearchResultItem> MusicManager::search(std::string name
|
|||||||
auto videosRes = m_client->GetVideos(videoIds);
|
auto videosRes = m_client->GetVideos(videoIds);
|
||||||
std::vector<definitions::SearchResultItem> resultItems;
|
std::vector<definitions::SearchResultItem> resultItems;
|
||||||
|
|
||||||
|
|
||||||
if (!videosRes) {
|
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) {
|
for (const auto &item : searchRes->items) {
|
||||||
|
auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" + item.id.videoId);
|
||||||
|
|
||||||
resultItems.push_back(
|
resultItems.push_back(
|
||||||
{.name = item.snippet.title,
|
{.name = item.snippet.title,
|
||||||
.length = "??:??",
|
.length = "??:??",
|
||||||
.thumbnail = item.snippet.thumbnails.empty() ? "" : item.snippet.thumbnails.begin()->second.url,
|
.thumbnail = item.snippet.thumbnails.empty() ? "" : item.snippet.thumbnails.begin()->second.url,
|
||||||
.viewCount = "N/A",
|
.viewCount = "N/A",
|
||||||
.url = "https://youtube.com/watch?v=" + item.id.videoId,
|
.url = "https://youtube.com/watch?v=" + item.id.videoId,
|
||||||
|
.shortUrl = shortUrl.value_or(""),
|
||||||
.videoId = item.id.videoId});
|
.videoId = item.id.videoId});
|
||||||
}
|
}
|
||||||
return resultItems;
|
return resultItems;
|
||||||
@@ -113,6 +118,7 @@ std::vector<definitions::SearchResultItem> MusicManager::search(std::string name
|
|||||||
else
|
else
|
||||||
thumbUrl = video.snippet.thumbnails.begin()->second.url;
|
thumbUrl = video.snippet.thumbnails.begin()->second.url;
|
||||||
}
|
}
|
||||||
|
auto shortUrl = m_client->ShortUrl("https://youtube.com/watch?v=" + video.id);
|
||||||
|
|
||||||
resultItems.push_back(
|
resultItems.push_back(
|
||||||
{.name = video.snippet.title,
|
{.name = video.snippet.title,
|
||||||
@@ -120,6 +126,7 @@ std::vector<definitions::SearchResultItem> MusicManager::search(std::string name
|
|||||||
.thumbnail = thumbUrl,
|
.thumbnail = thumbUrl,
|
||||||
.viewCount = video.statistics.viewCount,
|
.viewCount = video.statistics.viewCount,
|
||||||
.url = "https://youtube.com/watch?v=" + video.id,
|
.url = "https://youtube.com/watch?v=" + video.id,
|
||||||
|
.shortUrl = shortUrl.value_or(""),
|
||||||
.videoId = video.id});
|
.videoId = video.id});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,40 +136,86 @@ std::vector<definitions::SearchResultItem> MusicManager::search(std::string name
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Playback & Queue
|
// Playback & Queue
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
std::optional<std::string> 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) {
|
void MusicManager::playUrl(std::string url, const std::string &requester) {
|
||||||
const auto videoIdOpt = m_client->ExtractVideoId(url);
|
const auto videoIdOpt = m_client->ExtractVideoId(url);
|
||||||
if (!videoIdOpt) {
|
if (!videoIdOpt) {
|
||||||
LOG_WARNING(m_logger, "Invalid YouTube URI: {}", url);
|
LOG_WARN("Invalid YouTube URI: {}", url);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::string& vid = *videoIdOpt;
|
const std::string& vid = *videoIdOpt;
|
||||||
std::string title = "Unknown Title";
|
std::string title = "Unknown Title";
|
||||||
|
std::string shortUrl;
|
||||||
if (const auto videoInfo = m_client->GetVideo(vid, "snippet")) {
|
std::string length;
|
||||||
|
if (const auto videoInfo = m_client->GetVideo(vid, "snippet,contentDetails")) {
|
||||||
title = videoInfo->snippet.title;
|
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);
|
std::lock_guard lock(m_queueMtx);
|
||||||
// Fetch streams immediately (Note: This might be blocking, consider doing it in the loop if UI hangs)
|
// Fetch streams immediately (Note: This might be blocking, consider doing it in the loop if UI hangs)
|
||||||
m_queue.push_back({.name = title,
|
m_queue.push_back({.name = title,
|
||||||
|
.shortUrl = shortUrl,
|
||||||
|
.length =length,
|
||||||
.videoId = vid,
|
.videoId = vid,
|
||||||
.requestedBy = requester,
|
.requestedBy = requester,
|
||||||
.streams = m_client->GetBestStreams(vid)});
|
.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
|
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<definitions::Streams> streams) {
|
const std::string& req, std::optional<definitions::Streams> streams) {
|
||||||
std::lock_guard lock(m_queueMtx);
|
std::lock_guard lock(m_queueMtx);
|
||||||
Music m;
|
Music m;
|
||||||
m.name = title;
|
m.name = title;
|
||||||
m.videoId = vid;
|
m.videoId = vid;
|
||||||
m.requestedBy = req;
|
m.requestedBy = req;
|
||||||
|
m.shortUrl = shortUrl;
|
||||||
|
m.length = length;
|
||||||
if(streams) {
|
if(streams) {
|
||||||
m.streams = YouTube::Result<definitions::Streams>(streams.value());
|
m.streams = YouTube::Result<definitions::Streams>(streams.value());
|
||||||
}
|
}
|
||||||
@@ -216,7 +269,7 @@ void MusicManager::loop(std::stop_token st) {
|
|||||||
// Initial setup delay
|
// Initial setup delay
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
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) {
|
if (m_serverConnectionHandlerID == 0) {
|
||||||
// Connect GUI Tab
|
// Connect GUI Tab
|
||||||
if (auto err = m_functions->guiConnect(
|
if (auto err = m_functions->guiConnect(
|
||||||
@@ -226,7 +279,7 @@ void MusicManager::loop(std::stop_token st) {
|
|||||||
&m_serverConnectionHandlerID);
|
&m_serverConnectionHandlerID);
|
||||||
err != ERROR_ok) {
|
err != ERROR_ok) {
|
||||||
char* msg; m_functions->getErrorMessage(err, &msg);
|
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);
|
m_functions->freeMemory(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,10 +288,10 @@ void MusicManager::loop(std::stop_token st) {
|
|||||||
m_functions->closePlaybackDevice(m_serverConnectionHandlerID);
|
m_functions->closePlaybackDevice(m_serverConnectionHandlerID);
|
||||||
|
|
||||||
if(m_functions->openCaptureDevice(m_serverConnectionHandlerID, "custom", "custom") != ERROR_ok)
|
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)
|
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<AudioDecoder>();
|
m_microphone = std::make_unique<AudioDecoder>();
|
||||||
|
|
||||||
constexpr int SAMPLE_RATE = 192000;
|
constexpr int SAMPLE_RATE = 192000;
|
||||||
@@ -263,17 +316,17 @@ void MusicManager::loop(std::stop_token st) {
|
|||||||
m_isIdle = false;
|
m_isIdle = false;
|
||||||
// 2. Resolve Streams if needed (Hot reload might have provided them, new search might not)
|
// 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()) {
|
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);
|
m_current->streams = m_client->GetBestStreams(m_current->videoId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!m_current->streams || m_current->streams->audio.url.empty()) {
|
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;
|
m_current = std::nullopt;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
LOG_INFO(m_logger, "Now Playing: {}", m_current->name);
|
LOG_INFO("Now Playing: {}", m_current->name);
|
||||||
|
|
||||||
// 3. Start Decoding
|
// 3. Start Decoding
|
||||||
m_microphone->StartDecode(m_current->streams->audio.url, SAMPLE_RATE);
|
m_microphone->StartDecode(m_current->streams->audio.url, SAMPLE_RATE);
|
||||||
@@ -351,12 +404,12 @@ void MusicManager::loop(std::stop_token st) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_microphone->Cancel();
|
m_microphone->Cancel();
|
||||||
LOG_INFO(m_logger, "Finished track: {}", m_current->name);
|
LOG_INFO("Finished track: {}", m_current->name);
|
||||||
m_current = std::nullopt;
|
m_current = std::nullopt;
|
||||||
|
|
||||||
// Check for Graceful Stop (Update)
|
// Check for Graceful Stop (Update)
|
||||||
if (m_stopAfterCurrent) {
|
if (m_stopAfterCurrent) {
|
||||||
LOG_INFO(m_logger, "Graceful stop requested. Stopping main loop.");
|
LOG_INFO("Graceful stop requested. Stopping main loop.");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -376,7 +429,7 @@ void MusicManager::addSubscriberToOnline(anyID id) {
|
|||||||
m_offlineSubscribers.erase(id);
|
m_offlineSubscribers.erase(id);
|
||||||
m_onlineSubscribers.insert(id);
|
m_onlineSubscribers.insert(id);
|
||||||
updateWhisperList();
|
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) {
|
void MusicManager::addSubscriberToOffline(const anyID id) {
|
||||||
@@ -384,7 +437,7 @@ void MusicManager::addSubscriberToOffline(const anyID id) {
|
|||||||
m_onlineSubscribers.erase(id);
|
m_onlineSubscribers.erase(id);
|
||||||
m_offlineSubscribers.insert(id);
|
m_offlineSubscribers.insert(id);
|
||||||
updateWhisperList();
|
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_onlineSubscribers.erase(id);
|
||||||
m_offlineSubscribers.erase(id);
|
m_offlineSubscribers.erase(id);
|
||||||
updateWhisperList();
|
updateWhisperList();
|
||||||
LOG_INFO(m_logger, "User {} Unsubscribed", id);
|
LOG_INFO("User {} Unsubscribed", id);
|
||||||
}
|
}
|
||||||
std::set<uint64_t> MusicManager::getOnlineSubscribers() const {
|
std::set<uint64_t> MusicManager::getOnlineSubscribers() const {
|
||||||
std::lock_guard lock(const_cast<std::mutex&>(m_subMtx));
|
std::lock_guard lock(const_cast<std::mutex&>(m_subMtx));
|
||||||
|
|||||||
+31
-44
@@ -1,49 +1,23 @@
|
|||||||
#include <Plugin.hpp>
|
#include <Plugin.hpp>
|
||||||
|
|
||||||
|
#include "Logger.hpp"
|
||||||
|
|
||||||
|
|
||||||
void EchoionCore::Initialize(bool start) {
|
void EchoionCore::Initialize(bool start) {
|
||||||
// Init Logger
|
// Init Logger
|
||||||
try {
|
Logger::init(ts6bot::LogLevel::Trace);
|
||||||
quill::BackendOptions backend_options;
|
LOG_INFO("Core Initializing...");
|
||||||
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<quill::ConsoleSink>("console");
|
|
||||||
auto file_sink = quill::Frontend::create_or_get_sink<quill::FileSink>(
|
|
||||||
"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...");
|
|
||||||
|
|
||||||
// Config
|
// Config
|
||||||
char path[512];
|
char path[512];
|
||||||
m_ts3->getConfigPath(path, 512);
|
m_ts3->getConfigPath(path, 512);
|
||||||
ts6bot::Configuration::Construct(std::string(path) + "bot.json");
|
|
||||||
// Services
|
// Services
|
||||||
auto cfg = ts6bot::Configuration::GetInstance()->getConfig();
|
auto cfg = ts6bot::Configuration::init(std::string(path) + "bot.json")->getConfig();
|
||||||
|
|
||||||
if (start) {
|
if (start) {
|
||||||
m_musicManager = std::make_unique<MusicManager>(m_ts3, m_logger);
|
m_musicManager = std::make_unique<MusicManager>(m_ts3);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (const std::exception &e) {
|
|
||||||
std::cerr << e.what() << std::endl;
|
|
||||||
} // Ignore if already active
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void EchoionCore::Shutdown() {
|
void EchoionCore::Shutdown() {
|
||||||
@@ -51,7 +25,8 @@ void EchoionCore::Initialize(bool start) {
|
|||||||
m_musicManager->stop();
|
m_musicManager->stop();
|
||||||
m_musicManager.reset();
|
m_musicManager.reset();
|
||||||
}
|
}
|
||||||
quill::Backend::stop();
|
ts6bot::Configuration::destroyInstance();
|
||||||
|
Logger::destroyInstance();
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- HOT RELOAD ---
|
// --- HOT RELOAD ---
|
||||||
@@ -72,7 +47,7 @@ void EchoionCore::Initialize(bool start) {
|
|||||||
auto q = m_musicManager->getQueue();
|
auto q = m_musicManager->getQueue();
|
||||||
for (const auto &i : q) {
|
for (const auto &i : q) {
|
||||||
std::optional<definitions::Streams> streams = (i.streams.has_value() ? std::optional(i.streams.value()) : std::nullopt);
|
std::optional<definitions::Streams> 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);
|
state.queue.push_back(temp);
|
||||||
}
|
}
|
||||||
auto subs = m_musicManager->getOnlineSubscribers();
|
auto subs = m_musicManager->getOnlineSubscribers();
|
||||||
@@ -89,14 +64,14 @@ void EchoionCore::Initialize(bool start) {
|
|||||||
void EchoionCore::DeserializeState(const std::string &jsonState) {
|
void EchoionCore::DeserializeState(const std::string &jsonState) {
|
||||||
definitions::PluginState state;
|
definitions::PluginState state;
|
||||||
if (auto err = glz::read_json(state, jsonState); !err) {
|
if (auto err = glz::read_json(state, jsonState); !err) {
|
||||||
if (m_musicManager)
|
if (!m_musicManager)
|
||||||
m_musicManager = std::make_unique<MusicManager>(m_ts3, m_logger, state.serverConnection);
|
m_musicManager = std::make_unique<MusicManager>(m_ts3, state.serverConnection);
|
||||||
for (auto s : state.onlineSubscribers)
|
for (auto s : state.onlineSubscribers)
|
||||||
m_musicManager->addSubscriberToOnline(s);
|
m_musicManager->addSubscriberToOnline(s);
|
||||||
for (auto s : state.offlineSubscribers)
|
for (auto s : state.offlineSubscribers)
|
||||||
m_musicManager->addSubscriberToOffline(s);
|
m_musicManager->addSubscriberToOffline(s);
|
||||||
for (const auto &item : state.queue) {
|
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);
|
item.requester, item.streams);
|
||||||
}
|
}
|
||||||
m_musicManager->setServerConnectionHandlerID(state.serverConnection);
|
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,
|
int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targetMode, anyID toID, anyID fromID,
|
||||||
const char *fromName, const char *fromUniqueIdentifier, const char *message,
|
const char *fromName, const char *fromUniqueIdentifier, const char *message,
|
||||||
int ffIgnored) {
|
int ffIgnored) {
|
||||||
|
if (!m_musicManager)
|
||||||
|
return 1;
|
||||||
auto reply = [this](const uint64 sc, const anyID toId, const std::string &text) {
|
auto reply = [this](const uint64 sc, const anyID toId, const std::string &text) {
|
||||||
const char* returnCode = nullptr;
|
const char* returnCode = nullptr;
|
||||||
this->m_ts3->requestSendPrivateTextMsg(sc, text.c_str(), toId,returnCode);
|
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) {
|
} else if (results.size() == 1) {
|
||||||
this->m_musicManager->playUrl(results[0].url, fromName);
|
this->m_musicManager->playUrl(results[0].url, fromName);
|
||||||
this->m_ts3->requestSendPrivateTextMsg(
|
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 {
|
} else {
|
||||||
this->m_musicManager->storePendingSearch(fromID, results);
|
this->m_musicManager->storePendingSearch(fromID, results);
|
||||||
std::string list = "Multiple results found. Use .select <number>:\n";
|
std::string list = "Multiple results found. Use .select <number>:\n";
|
||||||
for (size_t i = 0; i < results.size(); ++i) {
|
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);
|
this->m_ts3->requestSendPrivateTextMsg(serverConnectionHandlerID, list.c_str(), fromID, nullptr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} 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") {
|
}
|
||||||
|
} else if (command == ".select") {
|
||||||
try {
|
try {
|
||||||
int idx = std::stoi(args);
|
int idx = std::stoi(args);
|
||||||
if (this->m_musicManager->selectSearchResult(fromID, idx, fromName)) {
|
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 q = this->m_musicManager->getQueue();
|
||||||
auto current = this->m_musicManager->getCurrent();
|
auto current = this->m_musicManager->getCurrent();
|
||||||
std::string str =
|
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())
|
if (q.empty() && str.empty())
|
||||||
reply(serverConnectionHandlerID, fromID, "Queue is empty");
|
reply(serverConnectionHandlerID, fromID, "Queue is empty");
|
||||||
|
|
||||||
for (auto i = 0; i < q.size(); i++) {
|
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);
|
reply(serverConnectionHandlerID, fromID, str);
|
||||||
} else if (command == ".sub") {
|
} else if (command == ".sub") {
|
||||||
@@ -202,7 +187,7 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targ
|
|||||||
} else if (command == ".help") {
|
} else if (command == ".help") {
|
||||||
reply(serverConnectionHandlerID, fromID,
|
reply(serverConnectionHandlerID, fromID,
|
||||||
".play <ссылка или название>\n.select "
|
".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");
|
".unsub");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,6 +197,8 @@ int EchoionCore::onTextMessageEvent(uint64 serverConnectionHandlerID, anyID targ
|
|||||||
void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID,
|
void EchoionCore::onClientMoveEvent(uint64 serverConnectionHandlerID, anyID clientID, uint64 oldChannelID, uint64 newChannelID,
|
||||||
int visibility, const char *moveMessage) {
|
int visibility, const char *moveMessage) {
|
||||||
|
|
||||||
|
if (!m_musicManager)
|
||||||
|
return;
|
||||||
anyID myID;
|
anyID myID;
|
||||||
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
|
this->m_ts3->getClientID(serverConnectionHandlerID, &myID);
|
||||||
if (clientID == myID)
|
if (clientID == myID)
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
#include "ts6bot/SignalShutdown.hpp"
|
|
||||||
#include <csignal>
|
|
||||||
#include <pthread.h>
|
|
||||||
|
|
||||||
SignalShutdown::SignalShutdown(std::function<void()> 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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+75
-11
@@ -7,6 +7,7 @@
|
|||||||
#include "cpr/proxyauth.h"
|
#include "cpr/proxyauth.h"
|
||||||
#include "cpr/response.h"
|
#include "cpr/response.h"
|
||||||
#include "cpr/session.h"
|
#include "cpr/session.h"
|
||||||
|
#include <glaze/glaze.hpp>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <curl/curl.h>
|
#include <curl/curl.h>
|
||||||
#include <curl/easy.h>
|
#include <curl/easy.h>
|
||||||
@@ -16,6 +17,9 @@
|
|||||||
#include <print>
|
#include <print>
|
||||||
#include <ranges>
|
#include <ranges>
|
||||||
#include <regex>
|
#include <regex>
|
||||||
|
|
||||||
|
#include "Logger.hpp"
|
||||||
|
#include "cpr/api.h"
|
||||||
using json = nlohmann::json;
|
using json = nlohmann::json;
|
||||||
namespace YouTube {
|
namespace YouTube {
|
||||||
|
|
||||||
@@ -25,7 +29,6 @@ namespace YouTube {
|
|||||||
|
|
||||||
Client::Client(std::string apiKey, std::string accessToken)
|
Client::Client(std::string apiKey, std::string accessToken)
|
||||||
: m_ApiKey(std::move(apiKey)), m_AccessToken(std::move(accessToken)) {
|
: m_ApiKey(std::move(apiKey)), m_AccessToken(std::move(accessToken)) {
|
||||||
|
|
||||||
// Initialize QuickJS
|
// Initialize QuickJS
|
||||||
m_rt = JS_NewRuntime();
|
m_rt = JS_NewRuntime();
|
||||||
JS_SetMemoryLimit(m_rt, 64 * 1024 * 1024);
|
JS_SetMemoryLimit(m_rt, 64 * 1024 * 1024);
|
||||||
@@ -111,6 +114,33 @@ std::string Client::SolveChallenge(const std::string &challenge,
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
auto Client::ShortUrl(const std::string& url) const -> Result<std::string> {
|
||||||
|
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<definitions::Streams> {
|
auto Client::GetBestStreams(const std::string &videoId) -> Result<definitions::Streams> {
|
||||||
// 1. Get base.js and signatureTimestamp via Watch Page
|
// 1. Get base.js and signatureTimestamp via Watch Page
|
||||||
auto watchPage = PerformRequest(
|
auto watchPage = PerformRequest(
|
||||||
@@ -127,7 +157,7 @@ auto Client::GetBestStreams(const std::string &videoId) -> Result<definitions::S
|
|||||||
return std::unexpected(ApiError{0, "Failed to find player JS", ""});
|
return std::unexpected(ApiError{0, "Failed to find player JS", ""});
|
||||||
|
|
||||||
std::string base_url = "https://www.youtube.com" + js_m.str();
|
std::string base_url = "https://www.youtube.com" + js_m.str();
|
||||||
std::cout << js_m.str() << std::endl;
|
LOG_TRACE("{}", js_m.str());
|
||||||
// Fetch player JS (using simple CURL/CPR or your PerformRequest)
|
// Fetch player JS (using simple CURL/CPR or your PerformRequest)
|
||||||
auto playerJs = PerformRequest(
|
auto playerJs = PerformRequest(
|
||||||
"https://www.youtube.com", js_m.str(), {},
|
"https://www.youtube.com", js_m.str(), {},
|
||||||
@@ -270,7 +300,7 @@ auto Client::PerformRequest(const std::string &purl,
|
|||||||
if (!body.empty()) {
|
if (!body.empty()) {
|
||||||
session.SetBody(cpr::Body{body});
|
session.SetBody(cpr::Body{body});
|
||||||
}
|
}
|
||||||
std::cout << session.GetFullRequestUrl() << std::endl;
|
LOG_TRACE("{}",session.GetFullRequestUrl());
|
||||||
// Headers
|
// Headers
|
||||||
// struct curl_slist *headers = nullptr;
|
// struct curl_slist *headers = nullptr;
|
||||||
// headers = curl_slist_append(headers, "Accept: application/json");
|
// headers = curl_slist_append(headers, "Accept: application/json");
|
||||||
@@ -284,7 +314,7 @@ auto Client::PerformRequest(const std::string &purl,
|
|||||||
// }
|
// }
|
||||||
cpr::Response response;
|
cpr::Response response;
|
||||||
if (m_Verbose) {
|
if (m_Verbose) {
|
||||||
std::println("Request: {} {}", method == HttpMethod::GET ? "GET" : "POST",
|
LOG_DEBUG("Request: {} {}", method == HttpMethod::GET ? "GET" : "POST",
|
||||||
url.str());
|
url.str());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,7 +340,7 @@ auto Client::PerformRequest(const std::string &purl,
|
|||||||
response.text, response.error.message});
|
response.text, response.error.message});
|
||||||
}
|
}
|
||||||
|
|
||||||
std::println("Response Code: {}", response.status_code);
|
LOG_DEBUG("Response Code: {}", response.status_code);
|
||||||
|
|
||||||
// 4. Handle Errors (HTTP 4xx/5xx)
|
// 4. Handle Errors (HTTP 4xx/5xx)
|
||||||
|
|
||||||
@@ -388,7 +418,7 @@ auto Client::PerformInternalRequest(const std::string &endpoint,
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (m_Verbose) {
|
if (m_Verbose) {
|
||||||
std::println("Internal Request: POST {}", fullUrl);
|
LOG_DEBUG("Internal Request: POST {}", fullUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
CURLcode res = curl_easy_perform(curl.get());
|
CURLcode res = curl_easy_perform(curl.get());
|
||||||
@@ -545,7 +575,7 @@ auto Client::Search(const SearchParams ¶ms)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (m_Verbose) {
|
if (m_Verbose) {
|
||||||
std::println("Search response: {}", response.value());
|
LOG_DEBUG("Search response: {}", response.value());
|
||||||
}
|
}
|
||||||
|
|
||||||
PageResult<SearchResult> results;
|
PageResult<SearchResult> results;
|
||||||
@@ -599,6 +629,40 @@ auto Client::GetVideo(const std::string &id, const std::string &part)
|
|||||||
return res->at(0);
|
return res->at(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add to your Client class implementation
|
||||||
|
auto Client::GetPlaylistVideos(const std::string& playlistId) -> Result<std::vector<Video>> {
|
||||||
|
std::vector<Video> allVideos;
|
||||||
|
std::string nextPageToken = "";
|
||||||
|
std::set<std::string> seenTokens; // To prevent circular loops in Mixes
|
||||||
|
int pagesFetched = 0;
|
||||||
|
const int MAX_PAGES = 5; // Adjust based on how many songs you want to allow per playlist
|
||||||
|
|
||||||
|
do {
|
||||||
|
auto res = GetPlaylistItems(playlistId, nextPageToken);
|
||||||
|
if (!res || res->items.empty()) break;
|
||||||
|
|
||||||
|
std::vector<std::string> ids;
|
||||||
|
for (const auto& item : res->items) {
|
||||||
|
ids.push_back(item.snippet.resourceId.videoId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Batch fetch video details (Duration, Title, etc.)
|
||||||
|
if (!ids.empty()) {
|
||||||
|
auto details = GetVideos(ids, "snippet,contentDetails");
|
||||||
|
if (details) {
|
||||||
|
allVideos.insert(allVideos.end(), details->begin(), details->end());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seenTokens.insert(nextPageToken);
|
||||||
|
nextPageToken = res->nextPageToken;
|
||||||
|
pagesFetched++;
|
||||||
|
|
||||||
|
// Stop if we see a token we've already used or hit page limit
|
||||||
|
} while (!nextPageToken.empty() && !seenTokens.contains(nextPageToken) && pagesFetched < MAX_PAGES);
|
||||||
|
|
||||||
|
return allVideos;
|
||||||
|
}
|
||||||
auto Client::GetVideos(const std::vector<std::string> &ids,
|
auto Client::GetVideos(const std::vector<std::string> &ids,
|
||||||
const std::string &part) -> Result<std::vector<Video>> {
|
const std::string &part) -> Result<std::vector<Video>> {
|
||||||
cpr::Parameters query;
|
cpr::Parameters query;
|
||||||
@@ -628,7 +692,7 @@ auto Client::GetVideos(const std::vector<std::string> &ids,
|
|||||||
|
|
||||||
auto Client::GetPlaylistItems(const std::string &playlistId,
|
auto Client::GetPlaylistItems(const std::string &playlistId,
|
||||||
const std::string &pageToken)
|
const std::string &pageToken)
|
||||||
-> Result<PageResult<SearchResult>> {
|
-> Result<PageResult<SearchPlaylistResult>> {
|
||||||
cpr::Parameters query;
|
cpr::Parameters query;
|
||||||
query.Add({"part", "snippet"});
|
query.Add({"part", "snippet"});
|
||||||
query.Add({"playlistId", playlistId});
|
query.Add({"playlistId", playlistId});
|
||||||
@@ -643,13 +707,13 @@ auto Client::GetPlaylistItems(const std::string &playlistId,
|
|||||||
// Note: PlaylistItems resource structure is slightly different from
|
// Note: PlaylistItems resource structure is slightly different from
|
||||||
// SearchResult, but often close enough for basic snippet extraction. In
|
// SearchResult, but often close enough for basic snippet extraction. In
|
||||||
// strict production, define a separate PlaylistItems struct.
|
// strict production, define a separate PlaylistItems struct.
|
||||||
PageResult<SearchResult> page;
|
PageResult<SearchPlaylistResult> page;
|
||||||
auto parse_err =
|
auto parse_err =
|
||||||
glz::read<glz::opts{.error_on_unknown_keys = false}>(page, *response);
|
glz::read<glz::opts{.error_on_unknown_keys = false}>(page, *response);
|
||||||
|
|
||||||
(page, *response);
|
|
||||||
|
|
||||||
if (parse_err) {
|
if (parse_err) {
|
||||||
|
LOG_ERROR("Error when reading playlist items: {}", glz::format_error(parse_err, *response));
|
||||||
|
LOG_DEBUG("Error when reading playlist items: {}",*response);
|
||||||
return std::unexpected(ApiError{0, "JSON Parse Error",
|
return std::unexpected(ApiError{0, "JSON Parse Error",
|
||||||
glz::format_error(parse_err, *response)});
|
glz::format_error(parse_err, *response)});
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-3
@@ -9,10 +9,13 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <thread>
|
#include <thread>
|
||||||
|
|
||||||
|
#include "SignalShutdown.hpp"
|
||||||
|
|
||||||
namespace fs = std::filesystem;
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
// --- GLOBALS ---
|
// --- GLOBALS ---
|
||||||
std::shared_ptr<TS3Functions> ts3_funcs;
|
std::shared_ptr<TS3Functions> ts3_funcs;
|
||||||
|
std::shared_ptr<SignalShutdown> shutdownHandler;
|
||||||
IEchoionPlugin *corePlugin = nullptr;
|
IEchoionPlugin *corePlugin = nullptr;
|
||||||
void *libHandle = nullptr;
|
void *libHandle = nullptr;
|
||||||
std::atomic<bool> keepRunning{true};
|
std::atomic<bool> keepRunning{true};
|
||||||
@@ -25,7 +28,6 @@ const std::string CORE_LIB_NAME = "Echoion.ts";
|
|||||||
// --- LOGGING ---
|
// --- LOGGING ---
|
||||||
void LogLoader(const std::string &msg) {
|
void LogLoader(const std::string &msg) {
|
||||||
std::string m = "[EchoionLoader] " + msg;
|
std::string m = "[EchoionLoader] " + msg;
|
||||||
ts3_funcs->printMessageToCurrentTab(m.c_str());
|
|
||||||
std::cout << m << std::endl;
|
std::cout << m << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,9 +51,11 @@ void UnloadCore(const bool saveState, std::string &stateOut) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
corePlugin->Shutdown(); // Stop threads/logger
|
corePlugin->Shutdown(); // Stop threads/logger
|
||||||
|
LogLoader("Core shut down");
|
||||||
if (const auto destroy = (DestroyPluginFunc)dlsym(libHandle, "DestroyPlugin"))
|
if (const auto destroy = (DestroyPluginFunc)dlsym(libHandle, "DestroyPlugin")) {
|
||||||
destroy(corePlugin);
|
destroy(corePlugin);
|
||||||
|
LogLoader("Plugin destroyed successfully.");
|
||||||
|
}
|
||||||
corePlugin = nullptr;
|
corePlugin = nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -164,6 +168,16 @@ void ts3plugin_setFunctionPointers(const TS3Functions funcs) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int ts3plugin_init() {
|
int ts3plugin_init() {
|
||||||
|
shutdownHandler=std::make_shared<SignalShutdown>([]() {
|
||||||
|
keepRunning = false;
|
||||||
|
std::string dummy;
|
||||||
|
UnloadCore(false, dummy);
|
||||||
|
if(pluginID) {
|
||||||
|
free(pluginID);
|
||||||
|
pluginID = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
if (LoadCore("")) {
|
if (LoadCore("")) {
|
||||||
updateWatcherThread = std::jthread(UpdateLoop);
|
updateWatcherThread = std::jthread(UpdateLoop);
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
Reference in new issue
Block a user