Compare commits
32
Commits
0e08ccaefa
..
v2.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2ec314eb9 | ||
|
|
16d9a667eb | ||
|
|
d456257d0c | ||
|
|
cbb178d83d | ||
|
|
29c7e60733 | ||
|
|
4b6f3165b2 | ||
|
|
b08f8ad29b | ||
|
|
915e2ab981 | ||
|
|
9637f1eef7 | ||
|
|
a277f2102b | ||
|
|
dfbbdaaf01 | ||
|
|
7975f2b38e | ||
|
|
9f06af6c80 | ||
|
|
39aff68d8d | ||
|
|
01362d2e51 | ||
|
|
5c036d91fb | ||
|
|
d146f11f02 | ||
|
|
df99b6ea7f | ||
|
|
b9c6c5dbc9 | ||
|
|
352101e657 | ||
|
|
5796ccbc74 | ||
|
|
7e3081ecd1 | ||
|
|
1f26927ad6 | ||
|
|
583e4e752d | ||
|
|
499143050b | ||
|
|
1efdbe0771 | ||
|
|
622335260f | ||
|
|
0e090168e8 | ||
|
|
30884ad0b5 | ||
|
|
0779fdcf20 | ||
|
|
75ee32a24b | ||
|
|
2d7651c308 |
No files matched your search
@@ -0,0 +1,55 @@
|
||||
name: Independent component release
|
||||
on:
|
||||
push:
|
||||
tags: [v*]
|
||||
schedule:
|
||||
- cron: '17 2 * * *'
|
||||
workflow_dispatch:
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: echoion-release-serial
|
||||
steps:
|
||||
- name: Check out component
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Check out pinned public release tools
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
repository: Void/Echoion
|
||||
ref: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
|
||||
path: .echoion-release-tools
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Build, publish, and merge feed transaction
|
||||
shell: bash
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.COMPONENT_OBJECT_STORAGE_ACCESS_KEY }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.COMPONENT_OBJECT_STORAGE_SECRET_KEY }}
|
||||
AWS_DEFAULT_REGION: ${{ vars.COMPONENT_OBJECT_STORAGE_REGION }}
|
||||
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
|
||||
ECHOION_DISTRIBUTION_BACKEND: ${{ vars.ECHOION_DISTRIBUTION_BACKEND }}
|
||||
ECHOION_DISTRIBUTION_BASE_URL: ${{ vars.ECHOION_DISTRIBUTION_BASE_URL }}
|
||||
ECHOION_FEED_BASE_URL: ${{ vars.ECHOION_FEED_BASE_URL }}
|
||||
ECHOION_FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }}
|
||||
ECHOION_FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }}
|
||||
ECHOION_FEED_REPOSITORY: ssh://gitea@git.faumaray.ru/Void/Echoion.git
|
||||
ECHOION_FEED_SIGNING_KEY_ID: ${{ vars.ECHOION_FEED_SIGNING_KEY_ID }}
|
||||
ECHOION_OBJECT_STORAGE_BUCKET: ${{ vars.COMPONENT_OBJECT_STORAGE_BUCKET }}
|
||||
ECHOION_OBJECT_STORAGE_ENDPOINT: ${{ vars.COMPONENT_OBJECT_STORAGE_ENDPOINT }}
|
||||
ECHOION_OBJECT_STORAGE_PREFIX: ${{ vars.COMPONENT_OBJECT_STORAGE_PREFIX }}
|
||||
ECHOION_RELEASE_TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
|
||||
GITEA_API_URL: ${{ gitea.api_url }}
|
||||
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
||||
GITEA_REF_NAME: ${{ gitea.ref_name }}
|
||||
GITEA_RUN_NUMBER: ${{ gitea.run_number }}
|
||||
GITEA_SHA: ${{ gitea.sha }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
|
||||
RELEASE_TOOLS_REF: ${{ vars.ECHOION_RELEASE_TOOLS_REF }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$RELEASE_TOOLS_REF" =~ ^[0-9a-f]{40}$ ]]
|
||||
test "$(git -C .echoion-release-tools rev-parse HEAD)" = "$RELEASE_TOOLS_REF"
|
||||
.echoion-release-tools/scripts/release-component.sh component.release.json
|
||||
+171
-20
@@ -1,5 +1,36 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
||||
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
|
||||
set(ECHOION_PRODUCT_VERSION 0.0.0)
|
||||
endif()
|
||||
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
|
||||
set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
|
||||
endif()
|
||||
project(EchoionCore VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
|
||||
|
||||
if(PROJECT_IS_TOP_LEVEL)
|
||||
set(BUILD_SHARED_LIBS ON CACHE BOOL
|
||||
"Build shared component dependencies" FORCE)
|
||||
file(DOWNLOAD
|
||||
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake"
|
||||
EXPECTED_HASH
|
||||
SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791)
|
||||
include("${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake")
|
||||
CPMAddPackage(
|
||||
NAME Void
|
||||
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
|
||||
GIT_TAG main
|
||||
OPTIONS "VOID_ENABLE_TESTING OFF")
|
||||
CPMAddPackage(
|
||||
NAME EchoionApi
|
||||
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/echoionapi.git
|
||||
GIT_TAG main)
|
||||
option(BUILD_TESTS "Build component tests" ON)
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -11,6 +42,12 @@ file(GLOB_RECURSE CORE_SOURCES
|
||||
"src/**.cpp"
|
||||
)
|
||||
add_library(EchoionCore SHARED ${CORE_SOURCES})
|
||||
target_compile_definitions(EchoionCore PRIVATE
|
||||
ECHOION_CORE_VERSION="${ECHOION_COMPONENT_VERSION}"
|
||||
ECHOION_MODULE_BUILD
|
||||
ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||
ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||
ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH})
|
||||
|
||||
add_library(Echoion::Core ALIAS EchoionCore)
|
||||
|
||||
@@ -37,14 +74,15 @@ target_link_libraries(EchoionCore PUBLIC
|
||||
Echoion::ApiPluginInterface
|
||||
Echoion::ApiCoreInterface
|
||||
Echoion::ApiUtils
|
||||
Echoion::ApiModuleAbi
|
||||
)
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(LIBAV REQUIRED IMPORTED_TARGET
|
||||
libavformat
|
||||
libavcodec
|
||||
libswresample
|
||||
libavutil
|
||||
libavformat>=59
|
||||
libavcodec>=59
|
||||
libswresample>=4
|
||||
libavutil>=57
|
||||
)
|
||||
|
||||
CPMAddPackage(
|
||||
@@ -68,32 +106,61 @@ if(quickjs_SOURCE_DIR)
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
set(AddBoost.cmake_VERSION 3.7.3)
|
||||
CPMAddPackage(
|
||||
NAME AddBoost.cmake
|
||||
VERSION "${AddBoost.cmake_VERSION}"
|
||||
URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz"
|
||||
)
|
||||
set(TRY_BOOST_VERSION "1.90.0")
|
||||
set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;")
|
||||
set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system")
|
||||
set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url")
|
||||
# Boost: the process must contain exactly ONE copy of the compiled Boost
|
||||
# libraries. VoidLibrary links the SYSTEM Boost, so EchoionCore must use the
|
||||
# same one — vendoring a second copy (the old AddBoost path fetched 1.90
|
||||
# alongside the system 1.91) put two libboost_url.so versions into the
|
||||
# process and the cross-bound symbols corrupted every parsed URL
|
||||
# (SIGSEGV in boost::urls::url_view). Fall back to fetching only when no
|
||||
# usable system Boost exists (in which case Void fetched the same one).
|
||||
find_package(Boost 1.87 CONFIG QUIET COMPONENTS url thread container)
|
||||
if(Boost_FOUND)
|
||||
message(STATUS "EchoionCore using system Boost ${Boost_VERSION}")
|
||||
# Distros ship CMake configs only for the compiled Boost libraries;
|
||||
# header-only components (asio, beast, uuid) have none. Map the targets
|
||||
# EchoionCore links onto the installed headers.
|
||||
foreach(_hdr asio beast uuid system)
|
||||
if(NOT TARGET Boost::${_hdr})
|
||||
add_library(_boost_${_hdr}_hdr INTERFACE)
|
||||
add_library(Boost::${_hdr} ALIAS _boost_${_hdr}_hdr)
|
||||
target_include_directories(_boost_${_hdr}_hdr INTERFACE
|
||||
"${Boost_INCLUDE_DIRS}")
|
||||
endif()
|
||||
endforeach()
|
||||
else()
|
||||
set(AddBoost.cmake_VERSION 3.7.3)
|
||||
CPMAddPackage(
|
||||
NAME AddBoost.cmake
|
||||
VERSION "${AddBoost.cmake_VERSION}"
|
||||
URL "https://github.com/Arniiiii/AddBoost.cmake/archive/refs/tags/${AddBoost.cmake_VERSION}.tar.gz"
|
||||
)
|
||||
set(TRY_BOOST_VERSION "1.90.0")
|
||||
set(BOOST_MY_OPTIONS "BOOST_ENABLE_PYTHON ON;")
|
||||
set(BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "thread;system")
|
||||
set(BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED "asio;beast;uuid;container;cobalt;url")
|
||||
|
||||
add_boost(
|
||||
TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
|
||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||
)
|
||||
add_boost(
|
||||
TRY_BOOST_VERSION BOOST_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED
|
||||
BOOST_NOT_HEADER_ONLY_COMPONENTS_THAT_YOU_NEED EchoionCore
|
||||
)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
# FindSQLite3 exposed only SQLite::SQLite3 before CMake 4.3. Keep the
|
||||
# component's preferred target name available across the supported CMake 4.x
|
||||
# range; an alias created inside sibling VoidLibrary is not visible here.
|
||||
if(NOT TARGET SQLite3::SQLite3 AND TARGET SQLite::SQLite3)
|
||||
add_library(SQLite3::SQLite3 ALIAS SQLite::SQLite3)
|
||||
endif()
|
||||
find_package(TBB REQUIRED)
|
||||
|
||||
target_link_libraries(EchoionCore
|
||||
PUBLIC
|
||||
PkgConfig::LIBAV
|
||||
TBB::tbb
|
||||
SQLite::SQLite3
|
||||
SQLite3::SQLite3
|
||||
# VoidLibrary modules (migration target — replacing in-house infra)
|
||||
Void::Data
|
||||
Void::Functional
|
||||
@@ -108,6 +175,7 @@ target_link_libraries(EchoionCore
|
||||
Void::Net
|
||||
Void::Sqlite
|
||||
Void::Service
|
||||
Void::ShortUrl
|
||||
Void::Plugin
|
||||
PRIVATE
|
||||
Threads::Threads
|
||||
@@ -126,6 +194,42 @@ else()
|
||||
target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTS)
|
||||
include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake")
|
||||
|
||||
add_executable(echoion_log_rotation_tests
|
||||
tests/test_log_rotation.cpp
|
||||
src/LogRotation.cpp
|
||||
)
|
||||
target_include_directories(echoion_log_rotation_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_log_rotation_tests PRIVATE cxx_std_26)
|
||||
add_test(NAME echoion_log_rotation_tests
|
||||
COMMAND echoion_log_rotation_tests)
|
||||
endif()
|
||||
|
||||
# Precompiled headers for the heavy translation units (MusicManager.cpp ~2.4k
|
||||
# lines, Core.cpp, YouTubeClient.cpp). These pull in the same expensive standard
|
||||
# and Void headers, so compiling them once cuts a large slice off build time.
|
||||
# Disabled automatically under unity builds (CMake forbids combining the two).
|
||||
option(ECHOION_ENABLE_PCH "Use precompiled headers for EchoionCore" ON)
|
||||
if(ECHOION_ENABLE_PCH AND NOT CMAKE_UNITY_BUILD)
|
||||
target_precompile_headers(EchoionCore PRIVATE
|
||||
<string>
|
||||
<string_view>
|
||||
<vector>
|
||||
<memory>
|
||||
<optional>
|
||||
<chrono>
|
||||
<format>
|
||||
<mutex>
|
||||
<thread>
|
||||
<atomic>
|
||||
<functional>
|
||||
)
|
||||
endif()
|
||||
|
||||
set_target_properties(EchoionCore PROPERTIES
|
||||
OUTPUT_NAME "Echoion"
|
||||
PREFIX ""
|
||||
@@ -155,6 +259,9 @@ install(EXPORT EchoionCoreTargets
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
install(FILES abi/module.json
|
||||
DESTINATION share/echoion/components/EchoionCore/${PROJECT_VERSION}/abi)
|
||||
|
||||
# Package config files
|
||||
include(CMakePackageConfigHelpers)
|
||||
write_basic_package_version_file(
|
||||
@@ -175,6 +282,50 @@ install(FILES
|
||||
DESTINATION lib/cmake/EchoionCore
|
||||
)
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_core_config_loader_tests
|
||||
tests/test_config_loader.cpp)
|
||||
target_include_directories(echoion_core_config_loader_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_config_loader_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_config_loader_tests
|
||||
COMMAND echoion_core_config_loader_tests)
|
||||
|
||||
add_executable(echoion_core_extension_state_tests
|
||||
tests/test_extension_state.cpp)
|
||||
target_include_directories(echoion_core_extension_state_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_extension_state_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_extension_state_tests
|
||||
COMMAND echoion_core_extension_state_tests)
|
||||
|
||||
add_executable(echoion_core_teamspeak_directory_tests
|
||||
tests/test_teamspeak_directory.cpp
|
||||
src/TeamSpeakDirectoryService.cpp)
|
||||
target_include_directories(echoion_core_teamspeak_directory_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_teamspeak_directory_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_teamspeak_directory_tests
|
||||
COMMAND echoion_core_teamspeak_directory_tests)
|
||||
|
||||
add_executable(echoion_core_url_shortener_tests
|
||||
tests/test_url_shortener.cpp)
|
||||
target_include_directories(echoion_core_url_shortener_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include")
|
||||
target_link_libraries(echoion_core_url_shortener_tests PRIVATE EchoionCore)
|
||||
add_test(NAME echoion_core_url_shortener_tests
|
||||
COMMAND echoion_core_url_shortener_tests)
|
||||
|
||||
add_executable(echoion_core_plugin_compatibility_tests
|
||||
tests/test_plugin_compatibility.cpp)
|
||||
target_include_directories(echoion_core_plugin_compatibility_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/src")
|
||||
target_link_libraries(echoion_core_plugin_compatibility_tests PRIVATE
|
||||
EchoionCore)
|
||||
void_add_tests(echoion_core_plugin_compatibility_tests)
|
||||
endif()
|
||||
|
||||
option(BUNDLE_FFMPEG "Bundle FFmpeg libraries with installation" OFF)
|
||||
if(BUNDLE_FFMPEG)
|
||||
include(cmake/BundleFFmpeg.cmake)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"contractId": "echoion.module.core",
|
||||
"descriptor": "echoion_module_descriptor_v1",
|
||||
"querySymbol": "echoion_module_abi_query",
|
||||
"moduleId": "EchoionCore",
|
||||
"activation": "reloadable",
|
||||
"dependencies": [
|
||||
{
|
||||
"moduleId": "EchoionApi",
|
||||
"versionRange": "^2.0.0",
|
||||
"abiHash": "sha256:d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"componentId": "EchoionCore",
|
||||
"productCompatibility": ">=2.0.0 <3.0.0",
|
||||
"publishNightly": true,
|
||||
"cmakeOptions": {}
|
||||
}
|
||||
@@ -5,11 +5,11 @@
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <span>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// Forward declarations for FFmpeg
|
||||
extern "C" {
|
||||
@@ -18,12 +18,15 @@ struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
struct SwrContext;
|
||||
struct AVBufferRef;
|
||||
}
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// FFmpeg-backed streaming decoder. openSource() spawns a decode jthread
|
||||
// that resamples to interleaved S16 at the configured output format and
|
||||
// fills int16Queue_ (bounded, backpressured); the playback side drains it
|
||||
// chunk-by-chunk via getNextChunk().
|
||||
class AudioDecoder
|
||||
{
|
||||
public:
|
||||
@@ -31,18 +34,13 @@ namespace Echoion::Core
|
||||
AudioDecoder();
|
||||
~AudioDecoder();
|
||||
|
||||
// Initialize decoder with optional hardware acceleration
|
||||
Api::Result<void>
|
||||
initialize(const Api::HwAccelConfig& hwConfig = {});
|
||||
Api::Result<void> initialize();
|
||||
void shutdown();
|
||||
|
||||
// Open audio source (URL or file path)
|
||||
Api::Result<void> openSource(const std::string& url);
|
||||
void closeSource();
|
||||
|
||||
// Decode audio - returns zero-copy pooled buffer
|
||||
[[nodiscard]] Api::Result<Api::DecodedAudio> decodeFrame();
|
||||
|
||||
// Seek to position
|
||||
Api::Result<void> seek(std::chrono::milliseconds position);
|
||||
|
||||
@@ -50,71 +48,51 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<Api::AudioStreamInfo>
|
||||
getStreamInfo() const;
|
||||
|
||||
// Get current position
|
||||
// Get current decode position (runs ahead of playback by up to
|
||||
// the queued chunk depth; use MusicManager for playback position)
|
||||
[[nodiscard]] std::chrono::milliseconds getPosition() const;
|
||||
|
||||
// Check if decoder has more data
|
||||
[[nodiscard]] bool hasMoreData() const;
|
||||
|
||||
// Set output format
|
||||
void setOutputFormat(uint32_t sampleRate, uint32_t channels);
|
||||
|
||||
// Set proxy configuration for network requests
|
||||
void setProxyConfig(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// Hardware acceleration
|
||||
[[nodiscard]] bool isHardwareAccelerated() const
|
||||
{
|
||||
return hwAccelEnabled_;
|
||||
}
|
||||
[[nodiscard]] Api::HwAccelType getHwAccelType() const
|
||||
{
|
||||
return hwAccelType_;
|
||||
}
|
||||
|
||||
// Enable/disable zero-copy mode
|
||||
void setZeroCopyEnabled(bool enabled)
|
||||
{
|
||||
zeroCopyEnabled_ = enabled;
|
||||
}
|
||||
[[nodiscard]] bool isZeroCopyEnabled() const
|
||||
{
|
||||
return zeroCopyEnabled_;
|
||||
}
|
||||
|
||||
// Get decoder statistics
|
||||
struct Stats {
|
||||
uint64_t framesDecoded = 0;
|
||||
uint64_t framesDropped = 0;
|
||||
uint64_t bytesDecoded = 0;
|
||||
std::chrono::milliseconds totalDecodeTime{0};
|
||||
double averageDecodeTimeMs = 0.0;
|
||||
bool hwAccelerationActive = false;
|
||||
};
|
||||
[[nodiscard]] Stats getStats() const;
|
||||
|
||||
// Get next S16 chunk (like reference implementation)
|
||||
// Get next S16 chunk. Swaps the caller's buffer for the queued
|
||||
// one, so the caller's previous storage is recycled into the
|
||||
// decode free-list — no per-chunk copy or allocation.
|
||||
bool getNextChunk(std::vector<int16_t>& outChunk,
|
||||
bool blocking = false);
|
||||
|
||||
// Check if decode is finished
|
||||
[[nodiscard]] bool isFinished() const { return eof_.load(); }
|
||||
|
||||
// Decoded audio waiting in the queue, in interleaved S16 samples.
|
||||
// The crossfade readiness gate uses this: a fade only starts once
|
||||
// the incoming decoder has buffered enough audio to survive it.
|
||||
[[nodiscard]] std::size_t queuedSamples() const;
|
||||
|
||||
// True when the decode queue is at capacity (the decode thread is
|
||||
// backpressured) — waiting longer cannot buffer any more.
|
||||
[[nodiscard]] bool queueSaturated() const;
|
||||
|
||||
private:
|
||||
|
||||
void decodeThread();
|
||||
Api::Result<void> readPacket();
|
||||
Api::Result<Api::DecodedAudio> convertFrame();
|
||||
// One read→decode→flush pass over the source; returns on EOF or
|
||||
// shutdown. decodeThread() parks between sessions awaiting a
|
||||
// seek request, so a post-EOF seek resumes decoding.
|
||||
void decodeSession();
|
||||
// Perform a pending seek request on the decode thread (the only
|
||||
// thread allowed to touch the FFmpeg contexts while decoding).
|
||||
// Returns true if a request was consumed.
|
||||
bool consumePendingSeek();
|
||||
// Borrow a chunk buffer of `samples` length from the recycle
|
||||
// free-list (reusing pooled storage), or allocate one if the
|
||||
// free-list is empty.
|
||||
std::vector<int16_t> acquireChunkBuffer(size_t samples);
|
||||
void cleanupFfmpeg();
|
||||
|
||||
// Hardware acceleration setup
|
||||
Api::Result<void>
|
||||
initializeHardwareAccel(const Api::HwAccelConfig& config);
|
||||
void cleanupHardwareAccel();
|
||||
|
||||
// Frame conversion (returns int16 for direct playback)
|
||||
Api::Result<Api::DecodedAudio> convertFramePooled();
|
||||
|
||||
// FFmpeg contexts
|
||||
AVFormatContext* formatContext_ = nullptr;
|
||||
AVCodecContext* codecContext_ = nullptr;
|
||||
@@ -123,13 +101,6 @@ namespace Echoion::Core
|
||||
SwrContext* swrContext_ = nullptr;
|
||||
uint8_t* outputBuffer_ = nullptr; // For S16 output like reference
|
||||
|
||||
// Hardware acceleration
|
||||
AVBufferRef* hwDeviceContext_ = nullptr;
|
||||
AVBufferRef* hwFramesContext_ = nullptr;
|
||||
bool hwAccelEnabled_ = false;
|
||||
Api::HwAccelType hwAccelType_ = Api::HwAccelType::None;
|
||||
bool zeroCopyEnabled_ = true;
|
||||
|
||||
// Stream info
|
||||
int audioStreamIndex_ = -1;
|
||||
Api::AudioStreamInfo streamInfo_;
|
||||
@@ -142,12 +113,19 @@ namespace Echoion::Core
|
||||
std::jthread decodeThread_;
|
||||
mutable std::mutex mutex_;
|
||||
std::condition_variable cv_;
|
||||
std::queue<Api::DecodedAudio> decodedQueue_;
|
||||
static constexpr size_t MAX_QUEUE_SIZE = 50;
|
||||
|
||||
// S16 audio queue (like reference) - avoids float conversion
|
||||
std::deque<std::vector<int16_t>> int16Queue_;
|
||||
static constexpr size_t MAX_INT16_QUEUE_SIZE = 100;
|
||||
// Max samples per swr_convert() output call; outputBuffer_ is
|
||||
// sized for this.
|
||||
static constexpr int MAX_OUT_SAMPLES = 4096;
|
||||
|
||||
// Free-list of recycled chunk buffers. getNextChunk() swaps the
|
||||
// caller's previous buffer in here and decodeThread() reuses that
|
||||
// storage instead of allocating a fresh vector per frame.
|
||||
// Guarded by mutex_ (same as int16Queue_).
|
||||
std::vector<std::vector<int16_t>> recycledChunks_;
|
||||
|
||||
// State
|
||||
std::atomic<bool> initialized_{false};
|
||||
@@ -155,15 +133,16 @@ namespace Echoion::Core
|
||||
std::atomic<bool> eof_{false};
|
||||
std::atomic<bool> shouldExit_{
|
||||
false}; // For FFmpeg interrupt callback
|
||||
std::chrono::milliseconds currentPosition_{0};
|
||||
// Decode position in ms; written by the decode thread per frame,
|
||||
// read cross-thread by getPosition() (prefetch decisions).
|
||||
std::atomic<int64_t> currentPositionMs_{0};
|
||||
// Pending seek target in ms, -1 = none. Written by seek() under
|
||||
// mutex_ (coordinated with eof_), consumed by the decode thread.
|
||||
std::atomic<int64_t> seekRequestMs_{-1};
|
||||
std::string currentUrl_;
|
||||
|
||||
std::atomic<uint32_t> streamSampleRate_{48000};
|
||||
std::optional<Void::Net::ProxyConfig> proxyConfig_;
|
||||
|
||||
// Statistics
|
||||
mutable std::mutex statsMutex_;
|
||||
Stats stats_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -6,16 +6,18 @@
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -118,6 +120,9 @@ namespace Echoion::Core
|
||||
getCommand(std::string_view name) const;
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
getAllCommands() const;
|
||||
[[nodiscard]] bool registerExternalCommand(
|
||||
std::string owner, std::string primaryName, CommandPtr command);
|
||||
void unregisterExternalCommands(std::string_view owner);
|
||||
|
||||
// Get commands visible to a specific client (for help)
|
||||
[[nodiscard]] std::vector<std::pair<std::string, CommandPtr>>
|
||||
@@ -148,6 +153,47 @@ namespace Echoion::Core
|
||||
class HelpCommand;
|
||||
void registerHelpCommand();
|
||||
|
||||
// Internal page-navigator command (!page/!next/!prev), defined in
|
||||
// the .cpp so it can reach the paged-reply cache below.
|
||||
class PageNavCommand;
|
||||
void registerPageCommands();
|
||||
|
||||
// Resolve the language a client should be answered in: their stored
|
||||
// per-user preference (kv_store "lang:<uid>") if any, else the
|
||||
// configured bot default, else English.
|
||||
[[nodiscard]] I18n::Language resolveLanguage(
|
||||
uint64_t clientId,
|
||||
const std::weak_ptr<MusicManager>& musicManager) const;
|
||||
|
||||
// --- Oversized-reply pagination -------------------------------
|
||||
// Long replies (from any command except help / the navigator) are
|
||||
// kept to a single message: page 1 is sent with a footer and the
|
||||
// remaining pages are cached here for !page/!next/!prev.
|
||||
struct PagedReply {
|
||||
std::vector<std::string> pages;
|
||||
std::size_t current = 0;
|
||||
std::chrono::steady_clock::time_point ts{};
|
||||
};
|
||||
mutable std::mutex pagedMutex_;
|
||||
std::unordered_map<uint64_t, PagedReply> pagedReplies_;
|
||||
static constexpr std::size_t kPageLimitBytes = 700;
|
||||
static constexpr std::chrono::minutes kPageTtl{10};
|
||||
|
||||
// Split `text` into pages, cache pages 2..N for `clientId`, and
|
||||
// return page 1 (with a footer when there is more than one page).
|
||||
// Replies that already fit one message pass through unchanged.
|
||||
std::string paginateReply(uint64_t clientId, std::string text,
|
||||
I18n::Language lang);
|
||||
|
||||
// Re-render a cached page for `clientId`. When `absolute` is set
|
||||
// the current page jumps to it (1-based, clamped); otherwise it
|
||||
// moves by `delta`. Returns std::nullopt when nothing is cached /
|
||||
// expired.
|
||||
std::optional<std::string>
|
||||
renderCachedPage(uint64_t clientId,
|
||||
std::optional<long> absolute, int delta,
|
||||
I18n::Language lang);
|
||||
|
||||
std::string prefix_ = "!";
|
||||
|
||||
// Non-owning service registry threaded into each CommandContext
|
||||
@@ -159,6 +205,8 @@ namespace Echoion::Core
|
||||
|
||||
// List for generating help: {"play", PlayCommand}
|
||||
std::vector<CommandEntry> uniqueCommands_;
|
||||
std::map<std::string, std::vector<CommandPtr>, std::less<>>
|
||||
externalCommands_;
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <Types.hpp>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -22,6 +23,12 @@ namespace Echoion::Core
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromFile(const std::filesystem::path& path);
|
||||
|
||||
// Parse, migrate, and normalize a complete JSON configuration. This
|
||||
// is shared by file loading and live configuration updates so
|
||||
// legacy fields have identical behavior through both entry points.
|
||||
[[nodiscard]] static Api::Result<Api::AppConfig>
|
||||
loadFromJson(std::string_view json);
|
||||
|
||||
// Save configuration to JSON file
|
||||
[[nodiscard]] static Api::Result<void>
|
||||
saveToFile(const std::filesystem::path& path,
|
||||
@@ -34,7 +41,8 @@ namespace Echoion::Core
|
||||
[[nodiscard]] static Api::AppConfig createDefaultConfig();
|
||||
|
||||
// Clamp/normalize values that carry hard limits after loading
|
||||
// (e.g. the yt-dlp concurrency cap). Applied by loadFromFile.
|
||||
// (e.g. the yt-dlp concurrency cap). Applied by all load/update
|
||||
// paths.
|
||||
static void normalize(Api::AppConfig& config);
|
||||
};
|
||||
|
||||
|
||||
@@ -2,25 +2,41 @@
|
||||
|
||||
#include "CommandManager.hpp"
|
||||
#include "ConfigLoader.hpp"
|
||||
#include "LyricsService.hpp"
|
||||
#include "MusicManager.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "RpcServer.hpp"
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
#include "echoion/web/HttpServer.hpp"
|
||||
#endif
|
||||
#include <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Database.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <StateBlob.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <atomic>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
class MultiLogger;
|
||||
}
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class PluginHost;
|
||||
class TeamSpeakDirectoryService;
|
||||
|
||||
// Main Core implementation of ICoreInterface
|
||||
class Core : public Api::ICoreInterface
|
||||
@@ -50,8 +66,6 @@ namespace Echoion::Core
|
||||
uint64_t clientId) override;
|
||||
Api::Result<void> removeFromQueue(uint64_t queueId) override;
|
||||
Api::Result<void> clearQueue() override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackSummary>>
|
||||
getQueueSummaries() const override;
|
||||
Api::Result<void> moveInQueue(uint64_t queueId,
|
||||
uint32_t newPosition) override;
|
||||
|
||||
@@ -121,7 +135,9 @@ namespace Echoion::Core
|
||||
// Additional methods for internal use (not in interface)
|
||||
void setAudioDataCallback(
|
||||
const MusicManager::AudioDataCallback& callback);
|
||||
Api::Result<void> reloadConfig();
|
||||
Api::Result<void> reloadConfig() override;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
managePluginsJson(const std::string& requestJson) override;
|
||||
|
||||
// Internal implementations using full types
|
||||
Api::Result<void> playTrack(const Api::TrackInfo& track);
|
||||
@@ -150,14 +166,40 @@ namespace Echoion::Core
|
||||
void onMusicEvent(const Api::PluginEvent& event);
|
||||
void broadcastEvent(const Api::PluginEvent& event);
|
||||
[[nodiscard]] bool isAdmin(uint64_t clientId) const;
|
||||
[[nodiscard]] bool isDj(uint64_t clientId) const;
|
||||
void updateWhisperList();
|
||||
void setupRpcHandlers();
|
||||
void setupEventBusSubscriptions() noexcept;
|
||||
void applyUrlShorteningConfig();
|
||||
|
||||
// Fetch an online client's avatar bytes (TS local cache, then the
|
||||
// myTeamSpeak URL, then a legacy file-transfer download) and
|
||||
// persist them — and the myTS URL — to the database keyed by uid.
|
||||
// Returns {contentType, bytes} on success. Web-agnostic; used by
|
||||
// both the avatar HTTP provider and the background warmer.
|
||||
[[nodiscard]] std::optional<std::pair<std::string, std::string>>
|
||||
fetchClientAvatarBytes(const std::string& uid,
|
||||
uint64_t clientId);
|
||||
// Periodically cache avatars for every online client so they remain
|
||||
// available (from the DB) once the user goes offline. Runs on
|
||||
// avatarWarmer_.
|
||||
void warmAvatarCache();
|
||||
|
||||
// Build the console + split-file logging stack and install it as
|
||||
// the global Void::Log sink (logSink_ must outlive logging).
|
||||
void installLogging(const std::filesystem::path& logDirectory,
|
||||
const Api::LoggingConfig& config);
|
||||
|
||||
// Guard helper: ok if initialized, else a ServiceUnavailable error.
|
||||
[[nodiscard]] Api::Result<void> requireInitialized() const noexcept;
|
||||
|
||||
// Components
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<LyricsService> lyricsService_;
|
||||
std::shared_ptr<MusicManager> musicManager_;
|
||||
std::unique_ptr<CommandManager> commandManager_;
|
||||
std::shared_ptr<PluginHost> extensionPlugins_;
|
||||
std::shared_ptr<TeamSpeakDirectoryService> directoryService_;
|
||||
Api::PluginInterfacePtr pluginInterface_;
|
||||
|
||||
// State
|
||||
@@ -165,21 +207,65 @@ namespace Echoion::Core
|
||||
std::filesystem::path configPath_;
|
||||
std::chrono::system_clock::time_point startTime_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
// Guards triggerAutoConnect() against duplicate connection
|
||||
// attempts (reset on a failed initiation so a retry can run).
|
||||
std::atomic<bool> autoConnectInitiated_{false};
|
||||
|
||||
// Event callbacks
|
||||
std::vector<Api::EventCallback> eventCallbacks_;
|
||||
mutable std::mutex eventMutex_;
|
||||
|
||||
// Admin tracking
|
||||
std::vector<uint64_t> adminClients_;
|
||||
mutable std::mutex adminMutex_;
|
||||
// Authenticated RPC client -> stable TS uid + nickname, resolved
|
||||
// at token auth. Keys per-user features (favorites, vote-skip).
|
||||
struct RpcIdentity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
std::map<uint64_t, RpcIdentity> rpcIdentities_;
|
||||
mutable std::mutex rpcIdentityMutex_;
|
||||
[[nodiscard]] std::optional<RpcIdentity>
|
||||
rpcIdentity(uint64_t clientId) const;
|
||||
[[nodiscard]] bool hasLiveTeamSpeakRole(
|
||||
uint64_t clientId,
|
||||
const std::vector<uint64_t>& configuredGroups) const;
|
||||
|
||||
// Full identity behind an RPC token: uid, display nickname and
|
||||
// admin standing. Shared by token auth and IP autologin.
|
||||
struct TokenIdentity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
bool isAdmin = false;
|
||||
bool isDj = false;
|
||||
};
|
||||
[[nodiscard]] std::optional<TokenIdentity>
|
||||
identityForToken(const std::string& token);
|
||||
// Mark an RPC connection authenticated as `identity` and retain its
|
||||
// stable TeamSpeak identity. Roles are checked live for each
|
||||
// request.
|
||||
void registerRpcAuth(uint64_t clientId,
|
||||
const TokenIdentity& identity);
|
||||
// Guards RestartWebInterface against overlapping restarts.
|
||||
std::atomic<bool> webRestartPending_{false};
|
||||
|
||||
// Database for persistence
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
|
||||
// Background avatar cache warmer + the uids already cached this
|
||||
// session (so we don't re-download an unchanged avatar every
|
||||
// cycle).
|
||||
std::jthread avatarWarmer_;
|
||||
std::unordered_set<std::string> warmedUids_;
|
||||
|
||||
// RPC server for Desktop/API clients
|
||||
std::shared_ptr<RpcServer> rpcServer_;
|
||||
|
||||
#ifdef ECHOION_WITH_WEB
|
||||
// Browser web interface: serves the static dashboard and
|
||||
// same-origin RPC bridge. Bot control still terminates at the RPC
|
||||
// server.
|
||||
std::shared_ptr<Web::HttpServer> webServer_;
|
||||
#endif
|
||||
|
||||
// Composition root: a type-keyed registry of all Core services
|
||||
// (logger, config, event bus, network, database, music, rpc).
|
||||
// initialize() provides each instance; resolveServices() and other
|
||||
@@ -197,6 +283,10 @@ namespace Echoion::Core
|
||||
// (replaces the former ConfigManager singleton).
|
||||
Api::ConfigManager configManager_;
|
||||
|
||||
// Owns the logging stack installed as the global Void::Log sink;
|
||||
// must outlive any logging (i.e. the whole process).
|
||||
std::shared_ptr<Void::Logging::MultiLogger> logSink_;
|
||||
|
||||
public:
|
||||
|
||||
// Access the service registry (composition root).
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <system_error>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Archive a non-empty active log into <directory>/history and prune the
|
||||
// oldest archives. This is intentionally performed before opening the
|
||||
// logger so every process start gets a fresh active file.
|
||||
[[nodiscard]] std::error_code
|
||||
rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept;
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,77 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <LoggerInterface.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
class MultiLogger;
|
||||
} // namespace Void::Logging
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// ILogger implementation backed by the Void::Logging framework.
|
||||
//
|
||||
// Output is produced by a Void MultiLogger fanning out to:
|
||||
// * a ConsoleLogger (stdout),
|
||||
// * a SplitFileLogger writing per-level files (<dir>/<level>.log) plus a
|
||||
// combined <dir>/all.log, each rolling independently by size, and
|
||||
// * a CallbackLogger bridging back to the registered ILogger callbacks.
|
||||
// The ILogger surface (levels, callbacks, console/file toggles, rotation
|
||||
// knobs) is preserved so existing call sites and the ECHOION_LOG_* macros
|
||||
// keep working unchanged.
|
||||
class Logger : public Api::ILogger
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Logger(std::string_view logDir = "logs",
|
||||
std::string_view baseName = "echoion");
|
||||
~Logger() override;
|
||||
|
||||
void log(Api::LogLevel level, std::string_view message,
|
||||
std::source_location location) override;
|
||||
void setMinLevel(Api::LogLevel level) override;
|
||||
[[nodiscard]] Api::LogLevel getMinLevel() const override;
|
||||
void registerCallback(const LogCallback& callback) override;
|
||||
void unregisterCallback(const LogCallback& callback) override;
|
||||
|
||||
void flush();
|
||||
void setConsoleOutput(bool enabled);
|
||||
void setFileOutput(bool enabled);
|
||||
void setMaxFileSize(uint64_t bytes);
|
||||
void setMaxFiles(uint32_t count);
|
||||
|
||||
private:
|
||||
|
||||
// (Re)assemble the Void sink tree from the current toggles/limits.
|
||||
void rebuildSinks();
|
||||
// Fan a Void log entry out to the registered ILogger callbacks.
|
||||
void dispatchToCallbacks(Api::LogLevel level,
|
||||
const std::string& message,
|
||||
const std::string& file, uint32_t line,
|
||||
const std::string& function);
|
||||
|
||||
std::filesystem::path logDir_;
|
||||
std::string baseName_;
|
||||
|
||||
std::shared_ptr<Void::Logging::MultiLogger> sink_;
|
||||
std::mutex sinkMutex_;
|
||||
|
||||
std::atomic<Api::LogLevel> minLevel_{Api::LogLevel::Info};
|
||||
std::atomic<bool> consoleOutput_{true};
|
||||
std::atomic<bool> fileOutput_{true};
|
||||
std::atomic<uint64_t> maxFileSize_{10 * 1024 * 1024}; // 10 MB
|
||||
std::atomic<uint32_t> maxFiles_{5};
|
||||
|
||||
std::vector<LogCallback> callbacks_;
|
||||
std::mutex callbackMutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Fetches song lyrics from lrclib.net (free, no auth) for the currently
|
||||
// playing track. Returns both plain lyrics and, when available, LRC
|
||||
// time-synced lines so the web UI can highlight the active line against the
|
||||
// playback clock. Results are cached in-process for a while since lyrics
|
||||
// never change and the same track is asked about repeatedly (chat command,
|
||||
// web panel, reconnects).
|
||||
//
|
||||
// Reachable by chat commands via the service registry and directly by the
|
||||
// RPC handlers. All network calls are synchronous; callers already run off
|
||||
// the audio thread (command thread pool / RPC worker).
|
||||
class LyricsService
|
||||
{
|
||||
public:
|
||||
|
||||
struct Line {
|
||||
std::int64_t ms = 0; // offset from track start
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct Lyrics {
|
||||
bool found = false;
|
||||
std::string plain; // full plain-text lyrics
|
||||
std::vector<Line> synced; // empty when only plain exists
|
||||
std::string source; // "lrclib" when resolved
|
||||
std::string title; // as reported by the provider
|
||||
std::string artist;
|
||||
};
|
||||
|
||||
explicit LyricsService(std::shared_ptr<NetworkClient> net);
|
||||
|
||||
// Resolve lyrics for a track. `durationSec` == 0 means unknown and
|
||||
// skips the exact-duration lookup (search fallback still runs).
|
||||
[[nodiscard]] Lyrics fetch(const std::string& title,
|
||||
const std::string& artist,
|
||||
const std::string& album,
|
||||
long long durationSec);
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Lyrics
|
||||
fetchUncached(const std::string& title,
|
||||
const std::string& artist,
|
||||
const std::string& album,
|
||||
long long durationSec) const;
|
||||
|
||||
// Parse an LRC-format string ("[mm:ss.xx] text") into sorted,
|
||||
// timestamped lines, ignoring metadata tags ([ar:], [ti:], …).
|
||||
[[nodiscard]] static std::vector<Line>
|
||||
parseLrc(const std::string& lrc);
|
||||
|
||||
std::shared_ptr<NetworkClient> net_;
|
||||
|
||||
struct Entry {
|
||||
Lyrics value;
|
||||
std::chrono::steady_clock::time_point at;
|
||||
};
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_map<std::string, Entry> cache_;
|
||||
static constexpr std::chrono::hours kCacheTtl{6};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,37 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include "AudioDecoder.hpp"
|
||||
#include "Database.hpp"
|
||||
#include "NetworkClient.hpp"
|
||||
#include "PlaylistLoader.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include "Socks5HttpBridge.hpp"
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include "SubscriptionService.hpp"
|
||||
#include "TrackCache.hpp"
|
||||
#include "YouTubeClient.hpp"
|
||||
#include "playback/PlaybackEngine.hpp"
|
||||
#include "playback/QueueService.hpp"
|
||||
#include "sources/InnertubeSource.hpp"
|
||||
#include "sources/YandexMusicSource.hpp"
|
||||
#include "sources/SourceRouter.hpp"
|
||||
#include "sources/YtDlpSource.hpp"
|
||||
#include <ConfigManager.hpp>
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <random>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <shared_mutex>
|
||||
#include <thread>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class MusicManager
|
||||
// Facade over the playback services. Public surface is unchanged (Core,
|
||||
// the RPC handlers and ~27 commands call it); internally it wires:
|
||||
// - PlaybackEngine: real-time loop, both decoders, gapless handoff
|
||||
// - QueueService: queue + shuffle/repeat (self-locking)
|
||||
// - SubscriptionService: audience bookkeeping + pause-on-empty policy
|
||||
// and implements IPlaybackHost for the engine (stream resolution, queue
|
||||
// access, event publication).
|
||||
class MusicManager : private IPlaybackHost
|
||||
{
|
||||
public:
|
||||
|
||||
MusicManager();
|
||||
~MusicManager();
|
||||
~MusicManager() override;
|
||||
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<NetworkClient> networkClient,
|
||||
@@ -49,6 +65,40 @@ namespace Echoion::Core
|
||||
configManager_ = cfg;
|
||||
}
|
||||
|
||||
// Re-apply network settings (proxy) to every outbound client:
|
||||
// the HTTP NetworkClient (YouTube Data API, URL shortener), the
|
||||
// yt-dlp subprocess, and the ffmpeg decoders. Call after a
|
||||
// config reload so proxy changes actually take effect everywhere
|
||||
// instead of only living in the config copy.
|
||||
void applyNetworkConfig(const Api::NetworkConfig& network);
|
||||
|
||||
// Re-apply YouTube settings (API key, cookies, concurrency, URL
|
||||
// shortening) to the YouTube client after a config reload. Passing
|
||||
// an empty/absent API key clears it, restoring the yt-dlp fallback.
|
||||
void applyYouTubeConfig(const Api::YouTubeConfig& youtube);
|
||||
|
||||
// Re-apply the source-chain settings (order, cooldown, instance
|
||||
// lists) after a config reload.
|
||||
void applySourcesConfig(const Api::SourcesConfig& sources);
|
||||
void addTrackSource(std::shared_ptr<ITrackSource> source);
|
||||
void setSharedYouTubeClient(std::shared_ptr<YouTubeClient> client)
|
||||
{
|
||||
youTubeClient_ = std::move(client);
|
||||
}
|
||||
[[nodiscard]] std::shared_ptr<YouTubeClient> sharedYouTubeClient() const
|
||||
{
|
||||
return youTubeClient_;
|
||||
}
|
||||
// Re-apply bot settings (queue size, track timeout, playlist
|
||||
// import gate) after a config reload. Does not touch the live
|
||||
// volume.
|
||||
void applyBotConfig(const Api::BotConfig& bot);
|
||||
|
||||
// Re-apply feature toggles (subscriber pause/resume policy,
|
||||
// auto-start, history size, autoplay) after a config reload.
|
||||
// shuffleMode/repeatMode are applied at cold start only.
|
||||
void applyFeaturesConfig(const Api::FeaturesConfig& features);
|
||||
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
play(const std::string& query, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> pause();
|
||||
@@ -59,6 +109,21 @@ namespace Echoion::Core
|
||||
seek(std::chrono::milliseconds position);
|
||||
[[nodiscard]] Api::Result<void> setVolume(float volume);
|
||||
|
||||
// Vote-to-skip the current track. Votes are keyed by the voter's
|
||||
// stable uid and reset whenever the current track changes. The
|
||||
// threshold is features.voteSkipThreshold, or a majority of
|
||||
// online subscribers when 0. Reaching it skips the track.
|
||||
struct VoteSkipStatus {
|
||||
uint32_t votes = 0;
|
||||
uint32_t needed = 0;
|
||||
bool voted = false; // caller has an active vote
|
||||
bool skipped = false;
|
||||
};
|
||||
[[nodiscard]] Api::Result<VoteSkipStatus>
|
||||
voteSkip(const std::string& uid);
|
||||
[[nodiscard]] VoteSkipStatus
|
||||
voteSkipStatus(const std::string& uid) const;
|
||||
|
||||
[[nodiscard]] Api::Result<uint64_t>
|
||||
queueTrack(const Api::TrackInfo& track, uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<void> removeFromQueue(uint32_t position);
|
||||
@@ -77,11 +142,11 @@ namespace Echoion::Core
|
||||
uint64_t clientId);
|
||||
[[nodiscard]] bool isPlaylistLoading() const
|
||||
{
|
||||
return playlistLoading_.load();
|
||||
return playlistLoader_ && playlistLoader_->isLoading();
|
||||
}
|
||||
[[nodiscard]] size_t getPlaylistLoadProgress() const
|
||||
{
|
||||
return playlistLoadedCount_.load();
|
||||
return playlistLoader_ ? playlistLoader_->loadedCount() : 0;
|
||||
}
|
||||
[[nodiscard]] Api::Result<std::vector<Api::PlaylistInfo>>
|
||||
getPlaylists() const;
|
||||
@@ -92,8 +157,12 @@ namespace Echoion::Core
|
||||
getPlaybackState() const;
|
||||
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
|
||||
|
||||
// Which catalog(s) a text search targets.
|
||||
enum class SearchScope { All, YouTube, Yandex, SoundCloud };
|
||||
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(const std::string& query);
|
||||
search(const std::string& query,
|
||||
SearchScope scope = SearchScope::All);
|
||||
|
||||
// Search result selection (client-specific)
|
||||
void storePendingSearch(uint64_t clientId,
|
||||
@@ -105,6 +174,25 @@ namespace Echoion::Core
|
||||
uint32_t index,
|
||||
const std::string& invokerName);
|
||||
|
||||
// Radio/autoplay toggle. Persisted in kv so it survives restart;
|
||||
// enabling while idle kicks an immediate related-track refill.
|
||||
void setAutoplay(bool enabled);
|
||||
[[nodiscard]] bool autoplayEnabled() const
|
||||
{
|
||||
return autoplay_.load();
|
||||
}
|
||||
|
||||
// Start playback (or seed radio) if nothing is playing and an
|
||||
// online subscriber is listening. Idempotent — safe to call after a
|
||||
// restore/hot-reload or when a subscriber connects, so radio resumes
|
||||
// without a manual !play / !radio toggle.
|
||||
void maybeAutoStart();
|
||||
|
||||
// Set shuffle/repeat mode directly (used when restoring persisted
|
||||
// state); persists the session snapshot.
|
||||
void setShuffle(bool enabled);
|
||||
void setRepeat(bool enabled);
|
||||
|
||||
// Help command
|
||||
[[nodiscard]] std::string getHelpText() const;
|
||||
|
||||
@@ -165,11 +253,83 @@ namespace Echoion::Core
|
||||
std::function<std::optional<std::string>(uint64_t clientId)>;
|
||||
void setNicknameCallback(const NicknameCallback& callback);
|
||||
|
||||
// Callback to send a private text message to a client (wired by
|
||||
// Core to the plugin). Used for proactive announcements.
|
||||
using MessageCallback =
|
||||
std::function<void(uint64_t clientId, const std::string&)>;
|
||||
void setMessageCallback(const MessageCallback& callback)
|
||||
{
|
||||
messageCallback_ = callback;
|
||||
}
|
||||
|
||||
// Set the current announcement (admin !announce) and deliver it
|
||||
// to online subscribers now. Bumps the stored announcement id so
|
||||
// a fresh post reaches everyone once. Returns how many online
|
||||
// subscribers were reached immediately.
|
||||
[[nodiscard]] size_t setAnnouncement(const std::string& text);
|
||||
|
||||
// Called when a client leaves the server
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
// Resolve the stable TS3 unique identifier for a session client
|
||||
// id (used to key per-user persistent data such as favorites).
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
clientUid(uint64_t clientId) const
|
||||
{
|
||||
if (clientInfoCallback_) {
|
||||
if (auto info = clientInfoCallback_(clientId)) {
|
||||
return info->first;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Persistent storage shared with commands (may be null when the
|
||||
// database failed to open).
|
||||
[[nodiscard]] std::shared_ptr<Api::Database> database() const
|
||||
{
|
||||
return database_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// ---- IPlaybackHost (called from the engine) --------------------
|
||||
|
||||
void emitAudio(std::span<const short> samples) override;
|
||||
Api::Result<std::string>
|
||||
resolveStream(const Api::QueueEntry& entry,
|
||||
bool preferDownload) override;
|
||||
std::optional<Api::QueueEntry> peekNextTrack() override;
|
||||
std::optional<Api::QueueEntry>
|
||||
takeNextTrack(uint64_t expectedQueueId) override;
|
||||
std::optional<Api::QueueEntry> takeAnyNextTrack() override;
|
||||
bool repeatEnabled() const override;
|
||||
void onTrackStarted(const Api::QueueEntry& entry) override;
|
||||
void onTrackFinished(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds finalPosition)
|
||||
override;
|
||||
void onPositionTick(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds position,
|
||||
std::chrono::milliseconds duration) override;
|
||||
void onEngineIdle() override;
|
||||
void onLocalFileDone(const std::string& path) override;
|
||||
|
||||
// Persist the live queue + shuffle/repeat/autoplay to the database
|
||||
// (kv "session.state") so a full restart can restore them; restore
|
||||
// them at startup. persistSession() is a no-op while a restore is in
|
||||
// progress to avoid recursive writes. includeCurrent=false drops
|
||||
// the currently-playing track from the snapshot — used by stop(),
|
||||
// where the engine clears its entry asynchronously and would
|
||||
// otherwise be persisted as still queued.
|
||||
void persistSession(bool includeCurrent = true);
|
||||
void restoreSession();
|
||||
std::atomic<bool> restoringSession_{false};
|
||||
void onPlaybackError(const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& entry)
|
||||
override;
|
||||
|
||||
// ---- helpers ---------------------------------------------------
|
||||
|
||||
// Publish a domain event on the injected bus (no-op until set).
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
@@ -178,119 +338,117 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
void playbackThread();
|
||||
// Auto-start the playback loop when a playlist's first track lands.
|
||||
void requestPlaybackStart();
|
||||
// Publish PlaybackPaused/PlaybackResumed with the current track
|
||||
// and position (called from pause/resume and the subscriber
|
||||
// policy hooks so the Desktop sees every pause-state change).
|
||||
void emitPauseState(bool paused);
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolveQuery(const std::string& query);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrl(const Api::TrackInfo& track);
|
||||
void onTrackFinished();
|
||||
[[nodiscard]] Api::TrackInfo getNextTrack();
|
||||
|
||||
// Generate silence/sine wave to keep audio stream alive during
|
||||
// transitions
|
||||
void generateTransitionAudio(std::chrono::milliseconds duration);
|
||||
void sendSilenceChunk();
|
||||
static constexpr auto TRANSITION_SILENCE_DURATION =
|
||||
std::chrono::milliseconds(100);
|
||||
static constexpr auto TRANSITION_FADE_DURATION =
|
||||
std::chrono::milliseconds(50);
|
||||
[[nodiscard]] std::string nicknameFor(uint64_t clientId) const;
|
||||
|
||||
// Download audio through proxy for playback
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
downloadAudioForPlayback(const std::string& url);
|
||||
downloadAudioForPlayback(const Api::TrackInfo& track);
|
||||
void cleanupTempFile(const std::string& filepath);
|
||||
|
||||
// Prefetch next track for seamless transitions
|
||||
void prefetchNextTrack();
|
||||
[[nodiscard]] bool shouldPrefetch() const;
|
||||
static constexpr auto PREFETCH_THRESHOLD =
|
||||
std::chrono::seconds(15); // Start prefetch 15s before end
|
||||
// The proxy the playback engine (ffmpeg) should use. ffmpeg only
|
||||
// speaks HTTP CONNECT, so a SOCKS5 config starts the local
|
||||
// Socks5HttpBridge and is rewritten to an Http proxy pointing at
|
||||
// it; Http/none pass through unchanged (and stop the bridge).
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig>
|
||||
effectiveEngineProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// ---- state -----------------------------------------------------
|
||||
|
||||
// Temporary file tracking
|
||||
std::set<std::string> tempFiles_;
|
||||
mutable std::shared_mutex tempFilesMutex_;
|
||||
|
||||
// Prefetch state for seamless playback
|
||||
struct PrefetchState {
|
||||
std::future<Api::Result<std::string>> streamUrlFuture;
|
||||
std::atomic<bool> isPrefetching{false};
|
||||
std::atomic<bool> hasPrefetched{false};
|
||||
std::optional<std::string> prefetchedUrl;
|
||||
} prefetchState_;
|
||||
|
||||
// Async playlist loading state
|
||||
std::thread playlistLoadThread_;
|
||||
std::atomic<bool> playlistLoading_{false};
|
||||
std::atomic<size_t> playlistLoadedCount_{0};
|
||||
std::atomic<size_t> playlistTotalCount_{0};
|
||||
|
||||
// Auto-start thread for playlist (must be joined, not detached)
|
||||
std::thread playlistAutoStartThread_;
|
||||
// Async playlist loading (background thread owned by the loader).
|
||||
std::unique_ptr<PlaylistLoader> playlistLoader_;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::shared_ptr<Api::Database> database_;
|
||||
// Non-owning application event bus (provided by Core).
|
||||
Void::EventBus::EventBus* eventBus_ = nullptr;
|
||||
// Non-owning config holder (provided by Core).
|
||||
Api::ConfigManager* configManager_ = nullptr;
|
||||
std::unique_ptr<YouTubeClient> youTubeClient_;
|
||||
std::unique_ptr<AudioDecoder> audioDecoder_;
|
||||
std::unique_ptr<SubscriptionManager> subscriptionManager_;
|
||||
std::shared_ptr<YouTubeClient> youTubeClient_;
|
||||
|
||||
// Source-resolution chain (proxy-free first, proxied last).
|
||||
std::unique_ptr<SourceRouter> router_;
|
||||
std::shared_ptr<InnertubeSource> innertubeSource_;
|
||||
std::shared_ptr<YandexMusicSource> yandexSource_;
|
||||
std::shared_ptr<YtDlpSource> ytdlpProxied_;
|
||||
|
||||
Api::BotConfig config_;
|
||||
std::vector<Api::QueueEntry> queue_;
|
||||
std::optional<Api::QueueEntry> currentTrack_;
|
||||
std::atomic<bool> isPlaying_{false};
|
||||
std::atomic<bool> isPaused_{false};
|
||||
std::atomic<bool> wasPausedForNoSubscribers_{
|
||||
false}; // Track if we auto-paused
|
||||
std::atomic<bool> autoStartOnSubscribe_{true};
|
||||
std::atomic<bool> autoplay_{false};
|
||||
QueueService queue_;
|
||||
std::unique_ptr<TrackCache> trackCache_;
|
||||
|
||||
// Accurate playback position tracking
|
||||
std::chrono::milliseconds playbackPosition_{0}; // Current position
|
||||
std::chrono::steady_clock::time_point
|
||||
playbackStartTime_; // When current segment started
|
||||
std::chrono::milliseconds playbackBasePosition_{
|
||||
0}; // Position at start of current segment
|
||||
std::atomic<float> volume_{0.5f};
|
||||
std::atomic<bool> shuffle_{false};
|
||||
std::atomic<bool> repeat_{false};
|
||||
uint64_t nextQueueId_ = 1;
|
||||
// Vote-to-skip state: voter uids for the queue entry identified
|
||||
// by voteSkipQueueId_ (cleared lazily when the track changes).
|
||||
mutable std::mutex voteSkipMutex_;
|
||||
std::set<std::string> voteSkipUids_;
|
||||
uint64_t voteSkipQueueId_ = 0;
|
||||
std::atomic<uint32_t> voteSkipThreshold_{0}; // 0 = auto majority
|
||||
[[nodiscard]] uint32_t voteSkipNeeded() const;
|
||||
|
||||
// Shuffle state - maintains shuffled order of queue indices
|
||||
std::vector<size_t> shuffledIndices_;
|
||||
size_t shuffleIndex_ = 0;
|
||||
void rebuildShuffledIndices();
|
||||
void reshuffleRemaining();
|
||||
// Autoplay state: seed track for recommendations + re-entrancy
|
||||
// guard for the async fetch. The seed's catalog decides where
|
||||
// related tracks are pulled from (YouTube radio mix vs. Yandex
|
||||
// similar tracks).
|
||||
enum class AutoplaySeedSource { None, YouTube, Yandex };
|
||||
mutable std::mutex autoplaySeedMutex_;
|
||||
std::string autoplaySeedId_;
|
||||
AutoplaySeedSource autoplaySeedSource_ = AutoplaySeedSource::None;
|
||||
std::atomic<bool> autoplayFetching_{false};
|
||||
std::jthread autoplayThread_;
|
||||
|
||||
std::jthread playbackThread_;
|
||||
mutable std::shared_mutex mutex_;
|
||||
std::condition_variable_any cv_;
|
||||
std::atomic<bool> playbackThreadRunning_{
|
||||
false}; // True while thread is actively running
|
||||
// Fallback seed for radio when nothing has been played this
|
||||
// session: derive one from the most recent history entry.
|
||||
[[nodiscard]] std::optional<
|
||||
std::pair<std::string, AutoplaySeedSource>>
|
||||
autoplaySeedFromHistory() const;
|
||||
|
||||
// Spotify/Yandex collection imports (background metadata fetch;
|
||||
// enqueue itself is instant).
|
||||
std::atomic<bool> importRunning_{false};
|
||||
std::jthread importThread_;
|
||||
std::unique_ptr<PlaybackEngine> engine_;
|
||||
// HTTP CONNECT -> SOCKS5 tunnel for ffmpeg (see
|
||||
// effectiveEngineProxy); only running while the configured proxy
|
||||
// is SOCKS5.
|
||||
std::unique_ptr<Socks5HttpBridge> ffmpegProxyBridge_;
|
||||
std::unique_ptr<SubscriptionService> subscriptions_;
|
||||
|
||||
// Pending search results per client (for select command)
|
||||
std::unordered_map<uint64_t, std::vector<Api::TrackInfo>>
|
||||
pendingSearches_;
|
||||
mutable std::mutex pendingSearchMutex_;
|
||||
|
||||
// Callbacks are stored here as well as forwarded to the
|
||||
// subscription service: Core may register them before
|
||||
// initialize() has created the service.
|
||||
AudioDataCallback audioCallback_;
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
PlaybackStartCallback playbackStartCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
MessageCallback messageCallback_;
|
||||
|
||||
// Deliver the current announcement to (clientId, uid) if that
|
||||
// subscriber hasn't seen it yet (per-uid seen-id in kv_store).
|
||||
// Returns true when a message was actually sent.
|
||||
bool deliverAnnouncementTo(uint64_t clientId,
|
||||
const std::string& uid);
|
||||
SubscriptionChangeCallback subscriptionChangeCallback_;
|
||||
ClientInfoCallback clientInfoCallback_;
|
||||
UidToClientIdCallback uidToClientIdCallback_;
|
||||
NicknameCallback nicknameCallback_;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
|
||||
// Position tracking for periodic event updates
|
||||
std::chrono::steady_clock::time_point lastPositionUpdate_{};
|
||||
static constexpr auto POSITION_UPDATE_INTERVAL =
|
||||
std::chrono::seconds(1);
|
||||
|
||||
static constexpr uint32_t TEAMSPEAK_SAMPLE_RATE =
|
||||
192000; // Match TeamSpeak CODEC_OPUS_MUSIC
|
||||
static constexpr uint32_t TEAMSPEAK_CHANNELS = 2;
|
||||
static constexpr size_t AUDIO_BUFFER_SIZE =
|
||||
7680; // 20ms @ 192kHz stereo
|
||||
static constexpr uint32_t CONCURRENT_LOAD_THREADS = 4;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -2,14 +2,10 @@
|
||||
|
||||
#include <NetworkInterface.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Functional/Retry.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <atomic>
|
||||
#include <format>
|
||||
#include <future>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
@@ -45,48 +41,14 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
request(const Void::Net::Request& req) override;
|
||||
|
||||
// Asynchronous requests
|
||||
[[nodiscard]] std::future<Api::Result<Void::Net::Response>>
|
||||
getAsync(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {})
|
||||
override;
|
||||
[[nodiscard]] std::future<Api::Result<Void::Net::Response>>
|
||||
postAsync(std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers = {})
|
||||
override;
|
||||
[[nodiscard]] std::future<Api::Result<Void::Net::Response>>
|
||||
requestAsync(const Void::Net::Request& req) override;
|
||||
|
||||
// Concurrent batch requests
|
||||
[[nodiscard]] std::vector<Api::Result<Void::Net::Response>>
|
||||
requestBatch(const std::vector<Void::Net::Request>& requests);
|
||||
|
||||
// JSON helpers using Void::Json reflection
|
||||
template <typename T>
|
||||
[[nodiscard]] Api::Result<T>
|
||||
getJson(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {})
|
||||
{
|
||||
auto response = get(url, headers);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
return parseJson<T>(response->body);
|
||||
}
|
||||
|
||||
template <typename T, typename Body>
|
||||
[[nodiscard]] Api::Result<T>
|
||||
postJson(std::string_view url, const Body& body,
|
||||
const std::vector<Void::Net::Header>& headers = {})
|
||||
{
|
||||
std::string jsonBody =
|
||||
Void::Json::serialize(Void::Json::to_json(body));
|
||||
auto response = post(url, jsonBody, headers);
|
||||
if (!response) {
|
||||
return std::unexpected(response.error());
|
||||
}
|
||||
return parseJson<T>(response->body);
|
||||
}
|
||||
// GET that never uses the configured proxy and does not retry —
|
||||
// for endpoints that must be reached directly and cheaply
|
||||
// (Invidious/Piped instance probes and API calls, public-IP
|
||||
// detection). Callers implement their own fallback across
|
||||
// instances, so retrying a dead one is counterproductive.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
getDirect(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers = {});
|
||||
|
||||
// Proxy configuration
|
||||
void setProxy(
|
||||
@@ -97,28 +59,6 @@ namespace Echoion::Core
|
||||
|
||||
private:
|
||||
|
||||
template <typename T>
|
||||
[[nodiscard]] static Api::Result<T>
|
||||
parseJson(const std::string& body)
|
||||
{
|
||||
auto parsed = Void::Json::parse(body);
|
||||
if (!parsed) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("JSON parse error ({}:{}): {}",
|
||||
parsed.error().line, parsed.error().col,
|
||||
parsed.error().message));
|
||||
}
|
||||
auto value = Void::Json::from_json<T>(*parsed);
|
||||
if (!value) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
std::format("JSON decode error: field '{}': {}",
|
||||
value.error().field, value.error().message));
|
||||
}
|
||||
return std::move(*value);
|
||||
}
|
||||
|
||||
// Execute with retry/backoff (Void::Retry); single attempt via
|
||||
// Void::Net::HttpClient.
|
||||
[[nodiscard]] Api::Result<Void::Net::Response>
|
||||
@@ -140,10 +80,6 @@ namespace Echoion::Core
|
||||
.multiplier = 2.0}};
|
||||
std::vector<std::uint16_t> retryableStatusCodes_{408, 429, 500,
|
||||
502, 503, 504};
|
||||
|
||||
// Worker pool backing the *Async / requestBatch fan-outs, replacing
|
||||
// a per-call std::async OS-thread spawn with bounded thread reuse.
|
||||
Void::Concurrency::ThreadPool pool_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class YouTubeClient;
|
||||
|
||||
// Drives async, streaming playlist loading off the audio path. Owns the
|
||||
// background load thread; resolved tracks are handed to the owner's queue
|
||||
// via the enqueue callback, and the owner is asked to start playback on the
|
||||
// first track via requestStart. Event publishing goes through the bus.
|
||||
class PlaylistLoader
|
||||
{
|
||||
public:
|
||||
|
||||
// Returns true if the track was accepted into the queue.
|
||||
using EnqueueFn =
|
||||
std::function<bool(const Api::TrackInfo&, uint64_t)>;
|
||||
using PlaybackStartFn = std::function<void()>;
|
||||
|
||||
PlaylistLoader(YouTubeClient* yt, Void::EventBus::EventBus* bus,
|
||||
EnqueueFn enqueue, PlaybackStartFn requestStart)
|
||||
: yt_(yt), bus_(bus), enqueue_(std::move(enqueue)),
|
||||
requestStart_(std::move(requestStart))
|
||||
{
|
||||
}
|
||||
|
||||
~PlaylistLoader()
|
||||
{
|
||||
if (loadThread_.joinable()) {
|
||||
loadThread_.join();
|
||||
}
|
||||
}
|
||||
|
||||
PlaylistLoader(const PlaylistLoader&) = delete;
|
||||
PlaylistLoader& operator=(const PlaylistLoader&) = delete;
|
||||
|
||||
[[nodiscard]] Api::Result<void>
|
||||
load(const std::string& playlistIdOrUrl, uint64_t clientId);
|
||||
|
||||
[[nodiscard]] bool isLoading() const { return loading_.load(); }
|
||||
[[nodiscard]] std::size_t loadedCount() const
|
||||
{
|
||||
return loadedCount_.load();
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
if (bus_) {
|
||||
bus_->publish<T>(std::move(event));
|
||||
}
|
||||
}
|
||||
|
||||
YouTubeClient* yt_;
|
||||
Void::EventBus::EventBus* bus_;
|
||||
EnqueueFn enqueue_;
|
||||
PlaybackStartFn requestStart_;
|
||||
|
||||
std::thread loadThread_;
|
||||
std::atomic<bool> loading_{false};
|
||||
std::atomic<std::size_t> loadedCount_{0};
|
||||
std::atomic<std::size_t> totalCount_{0};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <Void/Service/PluginService.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
class CommandManager;
|
||||
class MusicManager;
|
||||
class ITrackSource;
|
||||
|
||||
class PluginHost final : public std::enable_shared_from_this<PluginHost>
|
||||
{
|
||||
public:
|
||||
|
||||
struct Configuration {
|
||||
std::filesystem::path configDirectory;
|
||||
std::filesystem::path stateDirectory;
|
||||
std::string publicUrl;
|
||||
std::optional<Void::Net::ProxyConfig> proxy;
|
||||
std::string shortenerProvider = "url-shortener-internal";
|
||||
};
|
||||
|
||||
PluginHost(CommandManager& commands,
|
||||
std::shared_ptr<MusicManager>
|
||||
music,
|
||||
std::function<bool(uint64_t)>
|
||||
isAdmin,
|
||||
std::function<void(std::shared_ptr<ITrackSource>)>
|
||||
mediaSink,
|
||||
Configuration configuration);
|
||||
~PluginHost();
|
||||
|
||||
void loadDirectory(const std::filesystem::path& directory);
|
||||
void loadManagedDirectory(const std::filesystem::path& directory);
|
||||
// Bind and validate cross-plugin services after every startup
|
||||
// directory has been loaded.
|
||||
[[nodiscard]] bool finalizeLoading();
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
manage(const std::string& requestJson);
|
||||
void setChangeCallback(std::function<void()> callback);
|
||||
void dispatch(const Api::PluginEvent& event) const;
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
call(std::string_view plugin, std::string_view method,
|
||||
std::string params, uint64_t clientId) const;
|
||||
[[nodiscard]] std::vector<Api::ExtensionWebAsset> webAssets() const;
|
||||
[[nodiscard]] std::vector<std::string> names() const;
|
||||
[[nodiscard]] bool reconfigure(Configuration configuration);
|
||||
[[nodiscard]] std::shared_ptr<Void::ShortUrl::IShortener>
|
||||
shortener() const;
|
||||
[[nodiscard]] Void::ShortUrl::ResolveResult
|
||||
resolveShortLink(std::string_view key) const;
|
||||
struct State {
|
||||
std::string name;
|
||||
std::string json;
|
||||
std::uint32_t version{};
|
||||
};
|
||||
[[nodiscard]] std::vector<State> snapshotStates() const;
|
||||
void restoreStates(const std::vector<State>& states);
|
||||
|
||||
private:
|
||||
|
||||
void publish(std::string name);
|
||||
void unpublish(std::string name);
|
||||
void notifyChanged() const;
|
||||
[[nodiscard]] std::string
|
||||
pluginConfiguration(std::string_view name) const;
|
||||
[[nodiscard]] bool bindShortenerServices();
|
||||
|
||||
CommandManager& commands_;
|
||||
std::shared_ptr<MusicManager> music_;
|
||||
std::function<bool(uint64_t)> isAdmin_;
|
||||
std::function<void(std::shared_ptr<ITrackSource>)> mediaSink_;
|
||||
Void::Plugin::PluginManager plugins_;
|
||||
Void::Service::ServiceRegistry shortenerRegistry_;
|
||||
Void::Service::ServiceRegistry internalShortenerRegistry_;
|
||||
std::unique_ptr<
|
||||
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
|
||||
shortenerBinding_;
|
||||
std::unique_ptr<
|
||||
Void::Service::PluginServiceBinding<Void::ShortUrl::IShortener>>
|
||||
internalShortenerBinding_;
|
||||
Void::Plugin::ReloadCallbackId reloadCallback_{};
|
||||
mutable std::mutex reconfigureMutex_;
|
||||
mutable std::mutex mutex_;
|
||||
Configuration configuration_;
|
||||
std::vector<std::shared_ptr<class PluginTrackSource>> sources_;
|
||||
std::function<void()> changeCallback_;
|
||||
struct ManagedPlugin {
|
||||
std::string version;
|
||||
std::filesystem::path path;
|
||||
};
|
||||
std::filesystem::path managedDirectory_;
|
||||
std::unordered_map<std::string, ManagedPlugin> managed_;
|
||||
std::unordered_map<std::string, std::filesystem::path> loadedPaths_;
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,441 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <ExtensionPlugin.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Serialize any reflectable DTO to a JSON string (correct escaping).
|
||||
template <typename T> [[nodiscard]] std::string toJson(const T& dto)
|
||||
{
|
||||
return Void::Json::serialize(Void::Json::to_json(dto));
|
||||
}
|
||||
} // namespace Echoion::Core
|
||||
|
||||
// Reflectable DTOs for the RPC responses and event-broadcast payloads. These
|
||||
// are serialized with Void::Json (reflection) instead of hand-built strings,
|
||||
// so member names are the JSON keys and values are always correctly escaped.
|
||||
namespace Echoion::Core::Dto
|
||||
{
|
||||
|
||||
// ── RPC request payloads (parsed) ───────────────────────────────────────
|
||||
|
||||
struct AuthRequest {
|
||||
std::optional<std::string> nickname;
|
||||
std::optional<std::string> token;
|
||||
};
|
||||
|
||||
struct SeekRequest {
|
||||
std::int64_t position = 0; // milliseconds
|
||||
};
|
||||
|
||||
struct VolumeRequest {
|
||||
float volume = 0.5f; // normalised 0.0 - 1.0
|
||||
};
|
||||
|
||||
struct SkipRequest {
|
||||
std::uint32_t count = 1;
|
||||
};
|
||||
|
||||
struct QueueTrackRequest {
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct QueueIdRequest {
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct MoveRequest {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t newPosition = 0;
|
||||
};
|
||||
|
||||
struct SearchRequest {
|
||||
std::string query;
|
||||
};
|
||||
|
||||
struct TrackIdRequest {
|
||||
std::string id;
|
||||
};
|
||||
|
||||
struct PlaylistIdRequest {
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
struct SavePlaylistRequest {
|
||||
std::string name;
|
||||
std::string description;
|
||||
};
|
||||
|
||||
struct ManageUsersRequest {
|
||||
std::string action; // "list" | "remove" | "clearAll"
|
||||
std::optional<std::string> uid;
|
||||
};
|
||||
|
||||
struct UrlRequest {
|
||||
std::string url;
|
||||
};
|
||||
|
||||
struct AnnounceRequest {
|
||||
std::string text;
|
||||
};
|
||||
|
||||
// ── RPC handler responses ───────────────────────────────────────────────
|
||||
|
||||
struct Track {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::string album;
|
||||
std::optional<std::int64_t> duration; // milliseconds
|
||||
int source = 0;
|
||||
std::optional<std::string> thumbnailUrl;
|
||||
std::optional<std::string> url; // originalUrl (play-by-url)
|
||||
// Provider-generated shortened link when available; the web UI prefers
|
||||
// it for "open original link" (falls back to url).
|
||||
std::optional<std::string> shortenedUrl;
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Track toTrack(const Api::TrackInfo& t)
|
||||
{
|
||||
return Track{.id = t.id,
|
||||
.title = t.title,
|
||||
.artist = t.artist,
|
||||
.album = t.album,
|
||||
.duration = t.duration
|
||||
? std::optional<std::int64_t>(
|
||||
t.duration->count())
|
||||
: std::nullopt,
|
||||
.source = static_cast<int>(t.source),
|
||||
.thumbnailUrl = t.thumbnailUrl,
|
||||
.url = t.originalUrl.empty()
|
||||
? std::nullopt
|
||||
: std::optional(t.originalUrl),
|
||||
.shortenedUrl =
|
||||
t.shortenedUrl && !t.shortenedUrl->empty()
|
||||
? t.shortenedUrl
|
||||
: std::nullopt};
|
||||
}
|
||||
|
||||
// Inverse of toTrack (client-supplied tracks, e.g. AddFavorite).
|
||||
[[nodiscard]] inline Api::TrackInfo fromTrack(const Track& t)
|
||||
{
|
||||
Api::TrackInfo info;
|
||||
info.id = t.id;
|
||||
info.title = t.title;
|
||||
info.artist = t.artist;
|
||||
info.album = t.album;
|
||||
if (t.duration) {
|
||||
info.duration = std::chrono::milliseconds(*t.duration);
|
||||
}
|
||||
info.source = static_cast<Api::TrackSource>(t.source);
|
||||
info.thumbnailUrl = t.thumbnailUrl;
|
||||
info.originalUrl = t.url.value_or("");
|
||||
return info;
|
||||
}
|
||||
|
||||
struct QueueItem {
|
||||
std::uint64_t queueId = 0;
|
||||
Track track;
|
||||
bool isPlaying = false;
|
||||
};
|
||||
|
||||
struct QueueResponse {
|
||||
std::vector<QueueItem> queue;
|
||||
};
|
||||
|
||||
struct CurrentTrackResponse {
|
||||
std::optional<Track> track;
|
||||
};
|
||||
|
||||
struct Status {
|
||||
bool isPlaying = false;
|
||||
bool isPaused = false;
|
||||
float volume = 0.0f;
|
||||
bool repeat = false;
|
||||
bool shuffle = false;
|
||||
// Radio mode: auto-enqueue related tracks when the queue runs dry.
|
||||
bool autoplay = false;
|
||||
// Vote-skip state for the current track (additive fields).
|
||||
std::uint32_t skipVotes = 0;
|
||||
std::uint32_t skipVotesNeeded = 0;
|
||||
bool skipVoted = false;
|
||||
};
|
||||
|
||||
struct Success {
|
||||
bool success = true;
|
||||
};
|
||||
|
||||
struct SuccessMessage {
|
||||
bool success = true;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
struct SuccessVolume {
|
||||
bool success = true;
|
||||
float volume = 0.0f;
|
||||
};
|
||||
|
||||
struct Capabilities {
|
||||
bool plugins = false;
|
||||
bool webExtensions = false;
|
||||
};
|
||||
|
||||
struct PluginCallRequest {
|
||||
std::string plugin;
|
||||
std::string method;
|
||||
std::string params;
|
||||
};
|
||||
|
||||
struct PluginExtensions {
|
||||
std::vector<Api::ExtensionWebAsset> assets;
|
||||
};
|
||||
|
||||
struct Autoplay {
|
||||
bool autoplay = false;
|
||||
};
|
||||
|
||||
// Per-user preferences stored in the kv store; `language` shares the
|
||||
// "lang:<uid>" key with the !lang chat command so the web switcher and
|
||||
// the bot stay in sync.
|
||||
struct UserPrefs {
|
||||
std::string language;
|
||||
};
|
||||
|
||||
struct QueuedResponse {
|
||||
bool success = true;
|
||||
std::uint64_t queueId = 0;
|
||||
};
|
||||
|
||||
struct SearchResults {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct PlaylistBrief {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::uint32_t trackCount = 0;
|
||||
};
|
||||
|
||||
struct PlaylistList {
|
||||
std::vector<PlaylistBrief> playlists;
|
||||
};
|
||||
|
||||
struct PlaylistContents {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct HistoryRequest {
|
||||
std::uint32_t limit = 20;
|
||||
};
|
||||
|
||||
struct HistoryResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
struct StatsResponse {
|
||||
std::uint64_t totalPlays = 0;
|
||||
std::uint64_t totalTracks = 0;
|
||||
std::uint64_t totalPlaytimeMs = 0;
|
||||
std::optional<std::string> mostPlayedTitle;
|
||||
std::uint64_t mostPlayedCount = 0;
|
||||
};
|
||||
|
||||
struct ServerInfo {
|
||||
std::string version;
|
||||
std::int64_t uptimeSeconds = 0;
|
||||
std::uint32_t connectedClients = 0;
|
||||
std::uint32_t subscribers = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
std::uint32_t onlineSubscribers = 0;
|
||||
// Nicknames behind onlineSubscribers, so non-admin clients can
|
||||
// render a "listening now" list without the admin user API.
|
||||
std::vector<std::string> onlineSubscriberNames;
|
||||
// TeamSpeak uids parallel to onlineSubscriberNames (same order), so
|
||||
// the web UI can fetch each listener's avatar at /avatar/<uid>.
|
||||
std::vector<std::string> onlineSubscriberUids;
|
||||
};
|
||||
|
||||
struct AuditEntryDto {
|
||||
std::uint64_t clientId = 0;
|
||||
int method = 0;
|
||||
std::int64_t timestamp = 0; // unix seconds
|
||||
};
|
||||
|
||||
struct AuditLogResponse {
|
||||
std::vector<AuditEntryDto> entries;
|
||||
};
|
||||
|
||||
struct SubscriberDto {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
bool online = false;
|
||||
};
|
||||
|
||||
struct UsersResponse {
|
||||
std::vector<SubscriberDto> users;
|
||||
};
|
||||
|
||||
// Authenticate success. isAdmin/isDj/uid/nickname are additive — older
|
||||
// clients that only read `message` keep working.
|
||||
struct AuthSuccess {
|
||||
bool success = true;
|
||||
std::string message;
|
||||
bool isAdmin = false;
|
||||
bool isDj = false;
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
// Set by address-based autologin so the client can persist the
|
||||
// session token it never typed; empty for normal token auth.
|
||||
std::string token;
|
||||
};
|
||||
|
||||
struct AddFavoriteRequest {
|
||||
Track track;
|
||||
};
|
||||
|
||||
struct FavoritesResponse {
|
||||
std::vector<Track> tracks;
|
||||
};
|
||||
|
||||
// GetLyrics response: plain text plus, when available, time-synced lines
|
||||
// (ms offset from track start) so the web UI can highlight the active line.
|
||||
struct LyricsLineDto {
|
||||
std::int64_t ms = 0;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct LyricsResponse {
|
||||
bool found = false;
|
||||
std::string plain;
|
||||
std::vector<LyricsLineDto> synced;
|
||||
std::string source; // "lrclib" when resolved
|
||||
std::string title;
|
||||
std::string artist;
|
||||
};
|
||||
|
||||
struct VoteSkipResponse {
|
||||
std::uint32_t votes = 0;
|
||||
std::uint32_t needed = 0;
|
||||
bool voted = false;
|
||||
bool skipped = false;
|
||||
};
|
||||
|
||||
struct RequesterDto {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
std::uint64_t count = 0;
|
||||
};
|
||||
|
||||
struct AggregateStatsResponse {
|
||||
std::uint64_t tracksToday = 0;
|
||||
std::uint64_t listeningMsToday = 0;
|
||||
std::uint64_t queueAdditionsToday = 0;
|
||||
std::uint64_t skipsToday = 0;
|
||||
std::uint64_t playsTotal = 0;
|
||||
std::uint64_t skipsTotal = 0;
|
||||
std::vector<RequesterDto> topRequesters;
|
||||
std::uint64_t youtubeCount = 0;
|
||||
std::uint64_t yandexCount = 0;
|
||||
std::uint64_t otherCount = 0;
|
||||
};
|
||||
|
||||
// ── Event-broadcast payloads ────────────────────────────────────────────
|
||||
|
||||
struct TrackBrief {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
};
|
||||
|
||||
struct PlaybackStarted {
|
||||
TrackBrief track;
|
||||
std::int64_t position = 0;
|
||||
};
|
||||
|
||||
struct Position {
|
||||
std::int64_t position = 0;
|
||||
};
|
||||
|
||||
struct PositionProgress {
|
||||
std::int64_t position = 0;
|
||||
std::int64_t duration = 0;
|
||||
float progress = 0.0f;
|
||||
};
|
||||
|
||||
struct Volume {
|
||||
float volume = 0.0f;
|
||||
};
|
||||
|
||||
struct Shuffle {
|
||||
bool shuffle = false;
|
||||
};
|
||||
|
||||
struct Repeat {
|
||||
bool repeat = false;
|
||||
};
|
||||
|
||||
struct TrackQueued {
|
||||
std::uint64_t queueId = 0;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::uint32_t position = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
};
|
||||
|
||||
struct TrackRemoved {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t queueLength = 0;
|
||||
};
|
||||
|
||||
struct QueueReordered {
|
||||
std::uint64_t queueId = 0;
|
||||
std::uint32_t oldPosition = 0;
|
||||
std::uint32_t newPosition = 0;
|
||||
};
|
||||
|
||||
struct PlaylistId {
|
||||
std::string playlistId;
|
||||
};
|
||||
|
||||
struct PlaylistTrackLoaded {
|
||||
std::string playlistId;
|
||||
std::uint32_t loaded = 0;
|
||||
std::uint32_t total = 0;
|
||||
};
|
||||
|
||||
struct PlaylistLoadCompleted {
|
||||
std::string playlistId;
|
||||
std::uint32_t totalTracks = 0;
|
||||
bool success = false;
|
||||
};
|
||||
|
||||
struct User {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
};
|
||||
|
||||
struct ClientId {
|
||||
std::uint64_t clientId = 0;
|
||||
};
|
||||
|
||||
// Plugin-event track payload (duration in seconds, matching the legacy
|
||||
// broadcastEvent shape).
|
||||
struct EventTrack {
|
||||
std::string id;
|
||||
std::string title;
|
||||
std::string artist;
|
||||
std::int64_t duration = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core::Dto
|
||||
@@ -8,12 +8,16 @@
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -50,6 +54,23 @@ namespace Echoion::Core
|
||||
void removeAuthenticatedClient(uint64_t clientId);
|
||||
[[nodiscard]] bool isClientAuthenticated(uint64_t clientId);
|
||||
|
||||
// The client's effective network address: the X-Echoion-Client-Ip
|
||||
// header set by the web server's /rpc bridge (trusted only from
|
||||
// loopback peers), else the socket's remote address. Used for
|
||||
// address-based autologin.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
getClientAddress(uint64_t clientId) const;
|
||||
|
||||
// Server introspection (for GetServerInfo / GetAuditLog).
|
||||
struct AuditEntry {
|
||||
uint64_t clientId = 0;
|
||||
int method = 0;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
[[nodiscard]] std::vector<AuditEntry> getAuditLog() const;
|
||||
[[nodiscard]] size_t getClientCount() const;
|
||||
[[nodiscard]] std::chrono::seconds getUptime() const;
|
||||
|
||||
// Broadcast events to all connected clients
|
||||
void broadcastEvent(const std::string& event,
|
||||
const std::string& data);
|
||||
@@ -61,6 +82,8 @@ namespace Echoion::Core
|
||||
private:
|
||||
|
||||
void acceptLoop();
|
||||
void doAccept();
|
||||
void onAccept(asio::ip::tcp::socket socket);
|
||||
void handleClient(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||
void processMessage(uint64_t clientId, const std::string& message);
|
||||
@@ -80,7 +103,9 @@ namespace Echoion::Core
|
||||
uint64_t,
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||
clients_;
|
||||
std::mutex clientsMutex_;
|
||||
// clientId -> effective network address (see getClientAddress).
|
||||
std::unordered_map<uint64_t, std::string> clientAddresses_;
|
||||
mutable std::mutex clientsMutex_;
|
||||
std::atomic<uint64_t> nextClientId_{1};
|
||||
|
||||
// Per-client handlers run on a Void worker pool instead of one
|
||||
@@ -96,6 +121,13 @@ namespace Echoion::Core
|
||||
std::mutex authMutex_;
|
||||
std::string authToken_;
|
||||
|
||||
// Audit ring + uptime tracking
|
||||
mutable std::mutex auditMutex_;
|
||||
std::deque<AuditEntry> auditLog_;
|
||||
static constexpr size_t MAX_AUDIT_ENTRIES = 500;
|
||||
std::chrono::steady_clock::time_point startTime_{
|
||||
std::chrono::steady_clock::now()};
|
||||
|
||||
// Command handlers
|
||||
std::unordered_map<std::string, CommandHandler> handlers_;
|
||||
std::mutex handlersMutex_;
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
#include <quickjs.h>
|
||||
// Opaque quickjs handles — only the .cpp needs <quickjs.h>, and keeping it
|
||||
// out of this header keeps the quickjs include dir private to EchoionCore.
|
||||
struct JSRuntime;
|
||||
struct JSContext;
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Local HTTP CONNECT proxy that tunnels through a SOCKS5 upstream.
|
||||
//
|
||||
// FFmpeg has no SOCKS5 support at all — its http protocol only knows the
|
||||
// `http_proxy` option, which speaks HTTP CONNECT. To stream IP-locked
|
||||
// googlevideo URLs directly through a SOCKS5 proxy, the decoder is pointed
|
||||
// at 127.0.0.1:<port()> and every CONNECT is forwarded through the
|
||||
// configured SOCKS5 proxy (greeting/auth/CONNECT handshake, then a raw
|
||||
// byte pump in both directions).
|
||||
//
|
||||
// Only the two decoder slots stream concurrently, so a blocking
|
||||
// thread-per-connection design is deliberate: no io_context pump, no
|
||||
// async state machines.
|
||||
class Socks5HttpBridge
|
||||
{
|
||||
public:
|
||||
|
||||
Socks5HttpBridge() = default;
|
||||
~Socks5HttpBridge();
|
||||
|
||||
Socks5HttpBridge(const Socks5HttpBridge&) = delete;
|
||||
Socks5HttpBridge& operator=(const Socks5HttpBridge&) = delete;
|
||||
|
||||
// Bind 127.0.0.1:<ephemeral>, start the accept thread and return
|
||||
// the bound port. Restarts (against the new upstream) when already
|
||||
// running.
|
||||
Api::Result<uint16_t> start(const Void::Net::ProxyConfig& socks5);
|
||||
|
||||
// Close the acceptor and every live tunnel; joins all threads.
|
||||
void stop();
|
||||
|
||||
[[nodiscard]] bool running() const { return running_.load(); }
|
||||
[[nodiscard]] uint16_t port() const { return port_; }
|
||||
|
||||
// The SOCKS5 endpoint the bridge currently forwards to (empty when
|
||||
// stopped). Lets callers skip a restart when the config is
|
||||
// unchanged.
|
||||
[[nodiscard]] std::optional<Void::Net::ProxyConfig> upstream() const;
|
||||
|
||||
private:
|
||||
|
||||
struct Connection {
|
||||
boost::asio::ip::tcp::socket client;
|
||||
boost::asio::ip::tcp::socket upstream;
|
||||
std::atomic<bool> done{false};
|
||||
std::thread worker;
|
||||
|
||||
explicit Connection(boost::asio::io_context& io)
|
||||
: client(io), upstream(io)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
void acceptLoop();
|
||||
void serve(Connection& conn);
|
||||
// SOCKS5 greeting/auth/CONNECT for host:port on conn.upstream.
|
||||
// Throws std::runtime_error on any protocol failure.
|
||||
void socks5Connect(boost::asio::ip::tcp::socket& upstream,
|
||||
const std::string& host, uint16_t targetPort,
|
||||
const Void::Net::ProxyConfig& proxy);
|
||||
// Drop connections whose worker already finished (joins them).
|
||||
void pruneFinished();
|
||||
|
||||
boost::asio::io_context io_;
|
||||
std::optional<boost::asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread acceptThread_;
|
||||
uint16_t port_ = 0;
|
||||
std::atomic<bool> running_{false};
|
||||
|
||||
mutable std::mutex mutex_; // guards upstream_ and connections_
|
||||
std::optional<Void::Net::ProxyConfig> upstream_;
|
||||
std::vector<std::unique_ptr<Connection>> connections_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
#include "SubscriptionManager.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Async/EventBus.hpp>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Subscription bookkeeping + audience policy, extracted from
|
||||
// MusicManager. Owns the persistent SubscriptionManager and the
|
||||
// client-resolution callbacks; drives the pause-on-empty /
|
||||
// resume-on-return policy through two injected hooks so it never touches
|
||||
// playback internals directly.
|
||||
class SubscriptionService
|
||||
{
|
||||
public:
|
||||
|
||||
using ClientInfoCallback = std::function<std::optional<
|
||||
std::pair<std::string, std::string>>(uint64_t clientId)>;
|
||||
using UidToClientIdCallback =
|
||||
std::function<std::optional<uint64_t>(const std::string& uid)>;
|
||||
using ChangeCallback = std::function<void()>;
|
||||
// requestPause returns true when playback was actually paused by
|
||||
// this policy (so a returning subscriber should resume it).
|
||||
using RequestPause = std::function<bool()>;
|
||||
using RequestResume = std::function<bool()>;
|
||||
|
||||
Api::Result<void>
|
||||
initialize(std::shared_ptr<Api::Database> database);
|
||||
|
||||
void setEventBus(Void::EventBus::EventBus* bus) { eventBus_ = bus; }
|
||||
void setClientInfoCallback(ClientInfoCallback cb)
|
||||
{
|
||||
clientInfo_ = std::move(cb);
|
||||
}
|
||||
void setUidToClientIdCallback(UidToClientIdCallback cb)
|
||||
{
|
||||
uidToClientId_ = std::move(cb);
|
||||
}
|
||||
void setChangeCallback(ChangeCallback cb)
|
||||
{
|
||||
onChange_ = std::move(cb);
|
||||
}
|
||||
void setPauseResumeHooks(RequestPause pause, RequestResume resume)
|
||||
{
|
||||
requestPause_ = std::move(pause);
|
||||
requestResume_ = std::move(resume);
|
||||
}
|
||||
|
||||
// Audience policy toggles (features.pauseOnEmptySubscribers /
|
||||
// features.resumeOnSubscriberReturn); re-applied on config
|
||||
// reload.
|
||||
void setPolicy(bool pauseOnEmpty, bool resumeOnReturn)
|
||||
{
|
||||
pauseOnEmpty_ = pauseOnEmpty;
|
||||
resumeOnReturn_ = resumeOnReturn;
|
||||
}
|
||||
|
||||
// Command surface (message strings go back to the chat user).
|
||||
[[nodiscard]] Api::Result<std::string> subscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribe(uint64_t clientId);
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
unsubscribeByUid(const std::string& uid);
|
||||
[[nodiscard]] Api::Result<std::string> clearAllSubscriptions();
|
||||
|
||||
[[nodiscard]] bool isSubscribed(uint64_t clientId) const;
|
||||
[[nodiscard]] bool hasSubscribers() const;
|
||||
[[nodiscard]] bool hasOnlineSubscribers() const;
|
||||
[[nodiscard]] std::set<uint64_t> getSubscribedClients() const;
|
||||
[[nodiscard]] std::set<std::string> getOnlineSubscriberUids() const;
|
||||
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
|
||||
getSubscribers() const;
|
||||
|
||||
// Presence events from the plugin. onClientConnected resolves the
|
||||
// client once and hands the uid back so callers don't repeat the
|
||||
// (plugin round-trip) lookup: subscribedUid is set when the
|
||||
// client is a subscriber; mayAutoStart when playback should
|
||||
// auto-start if tracks are queued.
|
||||
struct ClientConnectResult {
|
||||
std::optional<std::string> subscribedUid;
|
||||
bool mayAutoStart = false;
|
||||
};
|
||||
ClientConnectResult onClientConnected(uint64_t clientId);
|
||||
void onClientDisconnected(uint64_t clientId);
|
||||
|
||||
private:
|
||||
|
||||
template <typename T> void emit(T event)
|
||||
{
|
||||
if (eventBus_) {
|
||||
eventBus_->publish<T>(std::move(event));
|
||||
}
|
||||
}
|
||||
|
||||
// Pause playback if the audience vanished; remember that WE
|
||||
// paused so the next returning subscriber resumes.
|
||||
void pauseIfAudienceGone();
|
||||
|
||||
std::unique_ptr<SubscriptionManager> manager_;
|
||||
Void::EventBus::EventBus* eventBus_ = nullptr;
|
||||
ClientInfoCallback clientInfo_;
|
||||
UidToClientIdCallback uidToClientId_;
|
||||
ChangeCallback onChange_;
|
||||
RequestPause requestPause_;
|
||||
RequestResume requestResume_;
|
||||
std::atomic<bool> pausedForNoSubscribers_{false};
|
||||
std::atomic<bool> pauseOnEmpty_{true};
|
||||
std::atomic<bool> resumeOnReturn_{true};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginInterface.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// One authoritative, event-refreshed TeamSpeak topology cache. The public
|
||||
// serializer is deliberately structural: it has no fields for UIDs, groups,
|
||||
// database IDs, addresses, or query clients, so private data cannot leak by
|
||||
// accidentally toggling a flag at the HTTP boundary.
|
||||
class TeamSpeakDirectoryService
|
||||
{
|
||||
public:
|
||||
|
||||
struct Snapshot {
|
||||
Api::ServerInfo server;
|
||||
std::vector<Api::ChannelInfo> channels;
|
||||
std::vector<Api::ClientInfo> clients;
|
||||
bool connected = false;
|
||||
std::uint64_t revision = 0;
|
||||
};
|
||||
|
||||
void setPluginInterface(Api::PluginInterfacePtr plugin);
|
||||
[[nodiscard]] Api::Result<void> refresh();
|
||||
void handleEvent(Api::PluginEventType type);
|
||||
|
||||
[[nodiscard]] Snapshot snapshot() const;
|
||||
[[nodiscard]] Void::Json::Value publicJson() const;
|
||||
[[nodiscard]] Void::Json::Value adminJson() const;
|
||||
|
||||
// TeamSpeak stores a sibling's predecessor id in channel_order.
|
||||
// This helper turns that linked-list representation into display
|
||||
// order and deterministically appends malformed/orphaned entries.
|
||||
[[nodiscard]] static std::vector<Api::ChannelInfo>
|
||||
orderChannels(std::vector<Api::ChannelInfo> channels);
|
||||
|
||||
private:
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
Api::PluginInterfacePtr plugin_;
|
||||
Snapshot snapshot_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Persistent on-disk cache of downloaded audio files, keyed by track id.
|
||||
// Survives restarts (lives under XDG_CACHE_HOME/echoion/tracks); evicts
|
||||
// least-recently-used files past maxBytes and entries older than the
|
||||
// TTL. Honors advanced.cacheEnabled / cacheMaxSize / cacheTTL.
|
||||
class TrackCache
|
||||
{
|
||||
public:
|
||||
|
||||
struct Config {
|
||||
bool enabled = true;
|
||||
uint64_t maxBytes = 1ull << 30; // 1 GiB
|
||||
std::chrono::seconds ttl{86400};
|
||||
};
|
||||
|
||||
// dirOverride points tests at a temp dir.
|
||||
explicit TrackCache(Config config,
|
||||
std::filesystem::path dirOverride = {});
|
||||
|
||||
// Parse "1GB"/"500MB"/"1024" (bytes) size strings; 0 on garbage.
|
||||
[[nodiscard]] static uint64_t
|
||||
parseSize(const std::string& text);
|
||||
|
||||
[[nodiscard]] bool enabled() const { return config_.enabled; }
|
||||
|
||||
// Cached file path for the track id, when present and fresh.
|
||||
// Bumps the file's LRU timestamp.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
lookup(const std::string& trackId);
|
||||
|
||||
// Move a downloaded file into the cache; returns the new path
|
||||
// (or the original on failure/disabled). Triggers eviction.
|
||||
[[nodiscard]] std::string store(const std::string& trackId,
|
||||
const std::string& filePath);
|
||||
|
||||
// True when the path lives inside the cache directory — such
|
||||
// files must NOT be deleted after playback.
|
||||
[[nodiscard]] bool owns(const std::string& filePath) const;
|
||||
|
||||
// Drop expired entries and evict LRU past the size budget.
|
||||
void sweep();
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& directory() const
|
||||
{
|
||||
return dir_;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] std::filesystem::path
|
||||
pathFor(const std::string& trackId,
|
||||
const std::string& extension) const;
|
||||
[[nodiscard]] static std::string
|
||||
sanitize(const std::string& trackId);
|
||||
// Eviction pass; caller holds mutex_.
|
||||
void sweepLocked();
|
||||
|
||||
Config config_;
|
||||
std::filesystem::path dir_;
|
||||
mutable std::mutex mutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,58 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "NetworkClient.hpp"
|
||||
#include <NetworkTypes.hpp>
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/ShortUrl/ShortUrl.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <string_view>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// URL shortener service for faumaray.ru
|
||||
// Thin Core adapter around the universal Void ShortUrl service. It owns no
|
||||
// provider and performs no HTTP itself: the getter returns a pinned service
|
||||
// instance for each operation, making calls safe across plugin hot reloads.
|
||||
class UrlShortener
|
||||
{
|
||||
public:
|
||||
|
||||
explicit UrlShortener(std::shared_ptr<NetworkClient> networkClient);
|
||||
~UrlShortener();
|
||||
using ProviderGetter = std::function<
|
||||
std::shared_ptr<Void::ShortUrl::IShortener>()>;
|
||||
|
||||
void setProvider(ProviderGetter provider);
|
||||
void setSources(const std::vector<std::string>& sources);
|
||||
|
||||
// Shorten a YouTube URL via faumaray.ru
|
||||
// Returns shortened URL in format: https://faumaray.ru/xxxxx
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenYouTubeUrl(std::string_view videoId);
|
||||
|
||||
// Shorten any URL via faumaray.ru
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
shortenUrl(std::string_view originalUrl);
|
||||
|
||||
// Get cached shortened URL if available
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
getCachedUrl(std::string_view originalUrl) const;
|
||||
|
||||
// Clear the URL cache
|
||||
void clearCache();
|
||||
|
||||
// Set cache TTL (default: 24 hours)
|
||||
void setCacheTtl(std::chrono::hours ttl);
|
||||
shortenUrl(std::string_view originalUrl,
|
||||
Api::TrackSource source) const;
|
||||
|
||||
private:
|
||||
|
||||
struct CacheEntry {
|
||||
std::string shortenedUrl;
|
||||
std::chrono::system_clock::time_point timestamp;
|
||||
};
|
||||
[[nodiscard]] bool sourceAllowed(Api::TrackSource source) const;
|
||||
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
mutable std::mutex cacheMutex_;
|
||||
std::unordered_map<std::string, CacheEntry> cache_;
|
||||
std::chrono::hours cacheTtl_{24};
|
||||
|
||||
// Clean expired entries from cache
|
||||
void cleanExpiredCache();
|
||||
mutable std::mutex mutex_;
|
||||
ProviderGetter provider_;
|
||||
std::unordered_set<Api::TrackSource> sources_ = {
|
||||
Api::TrackSource::YouTube};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -49,6 +49,25 @@ namespace Echoion::Core
|
||||
search(std::string_view query,
|
||||
std::optional<std::string> pageToken = std::nullopt);
|
||||
|
||||
// Search SoundCloud via yt-dlp (scsearch). Returns SoundCloud
|
||||
// tracks whose originalUrl is the permalink, streamable through the
|
||||
// ytdlp-direct source.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchSoundCloud(std::string_view query);
|
||||
|
||||
// Related tracks for radio autoplay: lists the YouTube "mix"
|
||||
// playlist (RD<videoId>) via yt-dlp --flat-playlist. Runs through
|
||||
// the proxy like every yt-dlp call, so it works under SOCKS5.
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
|
||||
radioMix(const std::string& videoId, size_t limit = 10);
|
||||
|
||||
// Fetch music-video candidates for a random search query. Used as a
|
||||
// radio fallback when no unplayed related track can be found (or
|
||||
// there is no seed). Goes through yt-dlp/proxy like radioMix; the
|
||||
// returned list is shuffled so the caller can pick/filter freely.
|
||||
[[nodiscard]] Api::Result<std::vector<Api::TrackInfo>>
|
||||
randomMusicVideo(size_t limit = 10);
|
||||
|
||||
// Get video details including stream URLs using yt-dlp
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
getVideoInfo(std::string_view videoId);
|
||||
@@ -83,8 +102,7 @@ namespace Echoion::Core
|
||||
nullptr,
|
||||
std::function<void()> onComplete = nullptr);
|
||||
|
||||
// Extract video ID from various YouTube URL formats (handles
|
||||
// redirects for short URLs)
|
||||
// Extract a video ID from known YouTube URL formats or a bare ID.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
extractVideoId(std::string_view url);
|
||||
[[nodiscard]] static std::optional<std::string>
|
||||
@@ -100,6 +118,20 @@ namespace Echoion::Core
|
||||
// Get best audio stream URL using yt-dlp
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getAudioStreamUrl(std::string_view videoId);
|
||||
// Resolve a stream URL for any yt-dlp-supported page URL
|
||||
// (SoundCloud, Bandcamp, VK, radio pages, ...). When useProxy is
|
||||
// false the configured proxy is explicitly bypassed with a
|
||||
// trailing --proxy "" (yt-dlp honours the last occurrence).
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
getStreamUrlForPage(std::string_view pageUrl, bool useProxy);
|
||||
|
||||
// Download the best audio to a file via yt-dlp (used when the
|
||||
// stream URL can't be opened directly — e.g. behind a SOCKS5 proxy
|
||||
// that ffmpeg can't use). yt-dlp applies the proxy + cookies and
|
||||
// writes to disk; returns the resulting file path.
|
||||
[[nodiscard]] Api::Result<std::string>
|
||||
downloadAudioToFile(std::string_view videoIdOrUrl,
|
||||
const std::string& outDir);
|
||||
|
||||
// Configure cookie options for yt-dlp
|
||||
void setCookiesPath(const std::string& path);
|
||||
@@ -120,6 +152,18 @@ namespace Echoion::Core
|
||||
|
||||
// Enable/disable URL shortening for track links
|
||||
void setUrlShorteningEnabled(bool enabled);
|
||||
void setUrlShortenerProvider(UrlShortener::ProviderGetter provider);
|
||||
void setUrlShorteningSources(
|
||||
const std::vector<std::string>& sources);
|
||||
void setUrlShorteningTimeout(std::chrono::milliseconds timeout);
|
||||
// Apply the provider-neutral policy to resolved tracks from any
|
||||
// source. Operations are best-effort and timeout-bounded.
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
|
||||
// Gate yt-dlp's periodic background self-update
|
||||
// (features.enableAutoUpdateCheck). Set before initialize().
|
||||
void setAutoUpdateEnabled(bool enabled);
|
||||
[[nodiscard]] bool isUrlShorteningEnabled() const;
|
||||
|
||||
private:
|
||||
@@ -131,6 +175,13 @@ namespace Echoion::Core
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlp(std::string_view query,
|
||||
const std::optional<std::string>& pageToken);
|
||||
// Shared yt-dlp search backend. `searchPrefix` is the yt-dlp search
|
||||
// selector (e.g. "ytsearch5", "scsearch5"); `source` tags the
|
||||
// resulting tracks and decides how originalUrl is built.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
searchWithYtDlpProvider(std::string_view query,
|
||||
std::string_view searchPrefix,
|
||||
Api::TrackSource source);
|
||||
|
||||
// Fetch video durations for search results (batch API call)
|
||||
void fetchVideoDurations(std::vector<Api::TrackInfo>& tracks,
|
||||
@@ -164,9 +215,7 @@ namespace Echoion::Core
|
||||
mutable std::mutex configMutex_;
|
||||
size_t maxConcurrentResolutions_ = 4;
|
||||
bool urlShorteningEnabled_ = true;
|
||||
std::chrono::milliseconds urlShorteningTimeout_{3000};
|
||||
|
||||
// Populate shortened URLs for tracks
|
||||
void populateShortenedUrls(std::vector<Api::TrackInfo>& tracks);
|
||||
void populateShortenedUrl(Api::TrackInfo& track);
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
@@ -34,6 +34,13 @@ namespace Echoion::Core
|
||||
// Initialize - checks for yt-dlp and downloads if needed
|
||||
Api::Result<void> initialize();
|
||||
|
||||
// Gate the periodic (7-day) background self-update. Configured
|
||||
// via features.enableAutoUpdateCheck; set BEFORE initialize().
|
||||
void setAutoUpdateEnabled(bool enabled)
|
||||
{
|
||||
autoUpdateEnabled_ = enabled;
|
||||
}
|
||||
|
||||
// Get the path to the yt-dlp executable
|
||||
[[nodiscard]] std::filesystem::path getExecutablePath() const;
|
||||
|
||||
@@ -43,8 +50,9 @@ namespace Echoion::Core
|
||||
// Get yt-dlp version
|
||||
[[nodiscard]] std::string getVersion() const;
|
||||
|
||||
// Force update yt-dlp to latest version
|
||||
Api::Result<void> update();
|
||||
// Force update yt-dlp to latest version; returns the verified
|
||||
// version string of the freshly installed binary.
|
||||
Api::Result<std::string> update();
|
||||
|
||||
// Execute yt-dlp with given arguments and return output
|
||||
// (synchronous)
|
||||
@@ -55,10 +63,6 @@ namespace Echoion::Core
|
||||
[[nodiscard]] std::future<YtDlpResult>
|
||||
executeAsync(const std::vector<std::string>& args);
|
||||
|
||||
// Execute multiple yt-dlp commands concurrently
|
||||
[[nodiscard]] std::vector<YtDlpResult> executeBatch(
|
||||
const std::vector<std::vector<std::string>>& argsList);
|
||||
|
||||
// Set cookie options for YouTube authentication
|
||||
void setCookiesPath(const std::string& path);
|
||||
void setCookiesFromBrowser(const std::string& browser);
|
||||
@@ -86,8 +90,8 @@ namespace Echoion::Core
|
||||
// Download yt-dlp from official source
|
||||
Api::Result<void> downloadYtDlp();
|
||||
|
||||
// Make executable executable (Unix only)
|
||||
Api::Result<void> makeExecutable();
|
||||
// Make the given file executable (Unix only)
|
||||
Api::Result<void> makeExecutable(const std::filesystem::path& path);
|
||||
|
||||
// Check if update is needed (older than 7 days)
|
||||
[[nodiscard]] bool shouldUpdate() const;
|
||||
@@ -109,6 +113,9 @@ namespace Echoion::Core
|
||||
std::shared_ptr<NetworkClient> networkClient_;
|
||||
std::filesystem::path executablePath_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
std::atomic<bool> autoUpdateEnabled_{true};
|
||||
// Background download/verify (joined in the destructor).
|
||||
std::jthread initThread_;
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
// Cookie configuration for YouTube authentication
|
||||
@@ -125,11 +132,12 @@ namespace Echoion::Core
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
|
||||
|
||||
// yt-dlp download URLs
|
||||
static constexpr std::string_view YTDLP_VERSION_URL =
|
||||
"https://api.github.com/repos/yt-dlp/yt-dlp/releases/latest";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX =
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX_X86_64 =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp";
|
||||
"yt-dlp_linux";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_LINUX_AARCH64 =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp_linux_aarch64";
|
||||
static constexpr std::string_view YTDLP_DOWNLOAD_WINDOWS =
|
||||
"https://github.com/yt-dlp/yt-dlp/releases/latest/download/"
|
||||
"yt-dlp.exe";
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !announce <text> — admin-only. Stores the announcement and delivers it
|
||||
// as a private message to each subscriber exactly once: to those online
|
||||
// now, and to others the next time they connect. Persisted per-uid, so a
|
||||
// bot restart never re-sends, and re-running !announce with new text
|
||||
// reaches everyone once more.
|
||||
class AnnounceCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
ctx.tr("The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
ctx.trf("Usage: {}announce <message>", ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const size_t reached = manager->setAnnouncement(ctx.args);
|
||||
ctx.reply(ctx.trf(
|
||||
"Announcement saved and delivered to {} online "
|
||||
"subscriber(s). Offline subscribers get it on their "
|
||||
"next connect.",
|
||||
reached));
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Send an announcement to all subscribers (admin).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<message>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Admin;
|
||||
}
|
||||
|
||||
bool requiresAdmin() const override { return true; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !autoplay [on|off] / !radio — toggle endless related-track playback.
|
||||
// With no argument it flips the current state. The choice is persisted so
|
||||
// it survives restarts. Related tracks come from the same catalog as the
|
||||
// last played track (YouTube radio mix or Yandex similar tracks).
|
||||
class AutoplayCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
bool enable = !manager->autoplayEnabled();
|
||||
std::string arg(ctx.args);
|
||||
std::transform(arg.begin(), arg.end(), arg.begin(),
|
||||
[](unsigned char c) {
|
||||
return static_cast<char>(
|
||||
std::tolower(c));
|
||||
});
|
||||
if (arg == "on" || arg == "true" || arg == "1" ||
|
||||
arg == "enable") {
|
||||
enable = true;
|
||||
} else if (arg == "off" || arg == "false" || arg == "0" ||
|
||||
arg == "disable") {
|
||||
enable = false;
|
||||
}
|
||||
|
||||
manager->setAutoplay(enable);
|
||||
|
||||
if (enable) {
|
||||
ctx.reply(ctx.tr(
|
||||
"\xf0\x9f\x93\xbb Autoplay is ON \xe2\x80\x94 I'll "
|
||||
"keep the music going with related tracks."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("\xf0\x9f\x93\xbb Autoplay is OFF."));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"AutoplayCommand", "{}",
|
||||
std::format("Autoplay command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Toggles radio mode: auto-queues related tracks when "
|
||||
"the queue runs out.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[on|off]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Playback;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"radio"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,26 +16,28 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->clearQueue();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Clear command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't clear the queue. Please try again.");
|
||||
Void::Log::error("ClearCommand", "{}",
|
||||
std::format("Clear command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't clear the queue. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Queue cleared!");
|
||||
ctx.reply(ctx.tr("Queue cleared!"));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"ClearCommand", "{}",
|
||||
std::format("Clear command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/i18n/Localization.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <Void/Service/Registry.hpp>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
@@ -16,11 +19,26 @@ namespace Echoion::Core
|
||||
|
||||
class MusicManager;
|
||||
|
||||
enum class CommandCategory { Music, Queue, Playback, Utility, Admin };
|
||||
// Declaration order also decides the order of the collapsible sections
|
||||
// in !help (the help map is keyed by this enum). Play and Search lead so
|
||||
// their related commands are grouped together up top.
|
||||
enum class CommandCategory {
|
||||
Play,
|
||||
Search,
|
||||
Music,
|
||||
Queue,
|
||||
Playback,
|
||||
Utility,
|
||||
Admin
|
||||
};
|
||||
|
||||
inline std::string toString(CommandCategory category)
|
||||
{
|
||||
switch (category) {
|
||||
case CommandCategory::Play:
|
||||
return "Play";
|
||||
case CommandCategory::Search:
|
||||
return "Search";
|
||||
case CommandCategory::Music:
|
||||
return "Music";
|
||||
case CommandCategory::Queue:
|
||||
@@ -35,6 +53,73 @@ namespace Echoion::Core
|
||||
return "Utility";
|
||||
}
|
||||
|
||||
// Middot separator (U+00B7) used between a track link and its duration.
|
||||
inline constexpr std::string_view kDot = "\xc2\xb7";
|
||||
|
||||
// Escape Markdown punctuation in dynamic text (track titles, etc.) so it
|
||||
// cannot break an enclosing [text](url) link or apply stray formatting.
|
||||
inline std::string escapeMarkdown(std::string_view text)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(text.size() + 8);
|
||||
for (char c : text) {
|
||||
switch (c) {
|
||||
case '\\':
|
||||
case '`':
|
||||
case '*':
|
||||
case '_':
|
||||
case '[':
|
||||
case ']':
|
||||
case '(':
|
||||
case ')':
|
||||
case '~':
|
||||
case '|':
|
||||
out += '\\';
|
||||
[[fallthrough]];
|
||||
default:
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Render `text` as a Markdown link to `url` (escaping the text). When `url`
|
||||
// is empty/absent the escaped text is returned without a link.
|
||||
inline std::string markdownLink(std::string_view text,
|
||||
const std::optional<std::string>& url)
|
||||
{
|
||||
if (url.has_value() && !url->empty()) {
|
||||
return std::format("[{}]({})", escapeMarkdown(text), *url);
|
||||
}
|
||||
return escapeMarkdown(text);
|
||||
}
|
||||
|
||||
// The best public link for a track: the provider-generated short link when
|
||||
// available, otherwise the original source URL (e.g. the YouTube or
|
||||
// Yandex Music page). Used so every list — search, queue, history,
|
||||
// favorites, stats — links to the real track, never the CDN/stream URL.
|
||||
inline std::optional<std::string> trackLinkUrl(const Api::TrackInfo& track)
|
||||
{
|
||||
if (track.shortenedUrl.has_value() && !track.shortenedUrl->empty()) {
|
||||
return track.shortenedUrl;
|
||||
}
|
||||
if (!track.originalUrl.empty()) {
|
||||
return track.originalUrl;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Render "Title by Artist" (or just Title) as a Markdown link to the
|
||||
// track's best public URL.
|
||||
inline std::string trackLink(const Api::TrackInfo& track)
|
||||
{
|
||||
std::string display = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
display = std::format("{} by {}", track.title, track.artist);
|
||||
}
|
||||
return markdownLink(display, trackLinkUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Context passed to every command execution.
|
||||
* Wraps all dependencies required to perform an action.
|
||||
@@ -52,8 +137,12 @@ namespace Echoion::Core
|
||||
// (non-owning; outlives the command). Populated by CommandManager.
|
||||
const Void::Service::ServiceRegistry* services = nullptr;
|
||||
|
||||
// Language the invoking user should be answered in. Resolved by
|
||||
// CommandManager (per-user kv override, else the config default).
|
||||
I18n::Language language = I18n::Language::English;
|
||||
|
||||
// Reply callback - set by CommandManager
|
||||
std::function<void(std::string_view)> replyCallback;
|
||||
std::function<void(std::string_view)> replyCallback = {};
|
||||
|
||||
// Helper to reply to the user
|
||||
void reply(std::string_view message) const
|
||||
@@ -63,6 +152,24 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
// Translate an English source string into the invoker's language.
|
||||
// Missing translations fall back to the English original.
|
||||
[[nodiscard]] std::string_view tr(std::string_view english) const
|
||||
{
|
||||
return I18n::translate(english, language);
|
||||
}
|
||||
|
||||
// Translate a std::format-style English template, then substitute
|
||||
// the arguments. The template is translated at runtime, so callers
|
||||
// use this instead of std::format for user-facing text.
|
||||
template <typename... Args>
|
||||
[[nodiscard]] std::string trf(std::string_view englishFmt,
|
||||
Args&&... args) const
|
||||
{
|
||||
return std::vformat(I18n::translate(englishFmt, language),
|
||||
std::make_format_args(args...));
|
||||
}
|
||||
|
||||
// Resolve a shared service by interface, or nullptr if the
|
||||
// registry is absent / the service was not provided.
|
||||
template <typename I>
|
||||
@@ -72,6 +179,49 @@ namespace Echoion::Core
|
||||
}
|
||||
};
|
||||
|
||||
// Format a duration as m:ss (or h:mm:ss past an hour). Shared by the
|
||||
// track-listing commands (!np, !queue) so their timestamps line up.
|
||||
inline std::string formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
|
||||
// A compact one-line playback status readout (volume / shuffle / repeat /
|
||||
// radio) shared by !help, !np and !list so all three show the same
|
||||
// at-a-glance state. Rendered as a Markdown blockquote line. Returns an
|
||||
// empty string when playback state is unavailable. Radio comes from
|
||||
// autoplayEnabled() since PlaybackState carries no autoplay field.
|
||||
inline std::string playbackStatusLine(const CommandContext& ctx)
|
||||
{
|
||||
auto mm = ctx.musicManager.lock();
|
||||
if (!mm) {
|
||||
return {};
|
||||
}
|
||||
auto st = mm->getPlaybackState();
|
||||
if (!st) {
|
||||
return {};
|
||||
}
|
||||
auto onOff = [&](bool b) -> std::string_view {
|
||||
return b ? ctx.tr("On") : ctx.tr("Off");
|
||||
};
|
||||
return ctx.trf(
|
||||
"> \xf0\x9f\x8e\x9a {} {}% \xc2\xb7 "
|
||||
"\xf0\x9f\x94\x80 {} {} \xc2\xb7 "
|
||||
"\xf0\x9f\x94\x81 {} {} \xc2\xb7 "
|
||||
"\xf0\x9f\x93\xbb {} {}",
|
||||
ctx.tr("Volume"), static_cast<int>(st->volume * 100),
|
||||
ctx.tr("Shuffle"), onOff(st->shuffle),
|
||||
ctx.tr("Repeat"), onOff(st->repeat),
|
||||
ctx.tr("Radio"), onOff(mm->autoplayEnabled()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Interface that all commands must implement.
|
||||
*/
|
||||
@@ -116,6 +266,16 @@ namespace Echoion::Core
|
||||
* @brief Returns whether this command requires admin privileges.
|
||||
*/
|
||||
virtual bool requiresAdmin() const { return false; }
|
||||
|
||||
/**
|
||||
* @brief Whether an over-long reply from this command should be
|
||||
* auto-paginated into a single message with a "!page" footer.
|
||||
*
|
||||
* Defaults to true. Commands that manage their own output shape
|
||||
* (help's collapsible sections, the page navigator itself) return
|
||||
* false so their replies are sent verbatim.
|
||||
*/
|
||||
virtual bool autoPaginate() const { return true; }
|
||||
};
|
||||
|
||||
using CommandPtr = std::shared_ptr<Command>;
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
// New command system - header-only commands
|
||||
#include "AnnounceCommand.hpp"
|
||||
#include "AutoplayCommand.hpp"
|
||||
#include "ClearCommand.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "FavoriteCommand.hpp"
|
||||
#include "HistoryCommand.hpp"
|
||||
#include "LanguageCommand.hpp"
|
||||
#include "LyricsCommand.hpp"
|
||||
#include "MoveCommand.hpp"
|
||||
#include "NowPlayingCommand.hpp"
|
||||
#include "PauseCommand.hpp"
|
||||
@@ -20,6 +26,9 @@
|
||||
#include "SelectCommand.hpp"
|
||||
#include "ShuffleCommand.hpp"
|
||||
#include "SkipCommand.hpp"
|
||||
#include "SoundCloudPlayCommand.hpp"
|
||||
#include "SoundCloudSearchCommand.hpp"
|
||||
#include "StatsCommand.hpp"
|
||||
#include "StopCommand.hpp"
|
||||
#include "SubscribeCommand.hpp"
|
||||
#include "SubscribersCommand.hpp"
|
||||
@@ -27,3 +36,7 @@
|
||||
#include "UnsubscribeCommand.hpp"
|
||||
#include "UnsubscribeIdCommand.hpp"
|
||||
#include "VolumeCommand.hpp"
|
||||
#include "YandexPlayCommand.hpp"
|
||||
#include "YandexSearchCommand.hpp"
|
||||
#include "YoutubePlayCommand.hpp"
|
||||
#include "YoutubeSearchCommand.hpp"
|
||||
@@ -0,0 +1,206 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !fav add | list | play <n> | remove <n> — per-user favorites keyed by
|
||||
// the stable TS3 unique identifier (hashed to the database's uint64
|
||||
// user key with FNV-1a; session client ids are NOT stable).
|
||||
class FavoriteCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto manager = ctx.musicManager.lock();
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!manager || !db) {
|
||||
ctx.reply(ctx.tr("Favorites are unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto uid = manager->clientUid(ctx.clientId);
|
||||
if (!uid) {
|
||||
ctx.reply(ctx.tr("Couldn't identify you on the server."));
|
||||
return;
|
||||
}
|
||||
const uint64_t userKey = fnv1a(*uid);
|
||||
|
||||
const auto [sub, rest] = splitFirstWord(ctx.args);
|
||||
|
||||
if (sub.empty() || sub == "list") {
|
||||
listFavorites(ctx, *db, userKey);
|
||||
} else if (sub == "add") {
|
||||
addCurrent(ctx, *manager, *db, userKey);
|
||||
} else if (sub == "play") {
|
||||
playFavorite(ctx, *manager, *db, userKey, rest);
|
||||
} else if (sub == "remove" || sub == "rm") {
|
||||
removeFavorite(ctx, *db, userKey, rest);
|
||||
} else {
|
||||
ctx.reply(ctx.trf(
|
||||
"Usage: {}fav add | list | play <n> | remove <n>",
|
||||
ctx.prefix));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Manage your favorite tracks";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "add | list | play <n> | remove <n>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"favorite", "favorites"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static uint64_t fnv1a(std::string_view text)
|
||||
{
|
||||
uint64_t hash = 14695981039346656037ull;
|
||||
for (unsigned char c : text) {
|
||||
hash ^= c;
|
||||
hash *= 1099511628211ull;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::pair<std::string, std::string>
|
||||
splitFirstWord(const std::string& text)
|
||||
{
|
||||
const auto start = text.find_first_not_of(' ');
|
||||
if (start == std::string::npos) {
|
||||
return {};
|
||||
}
|
||||
const auto end = text.find(' ', start);
|
||||
if (end == std::string::npos) {
|
||||
return {text.substr(start), {}};
|
||||
}
|
||||
const auto restStart = text.find_first_not_of(' ', end);
|
||||
return {text.substr(start, end - start),
|
||||
restStart == std::string::npos
|
||||
? std::string{}
|
||||
: text.substr(restStart)};
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::optional<size_t>
|
||||
parseIndex(const std::string& text)
|
||||
{
|
||||
unsigned parsed = 0;
|
||||
auto [_, ec] = std::from_chars(
|
||||
text.data(), text.data() + text.size(), parsed);
|
||||
if (ec != std::errc{} || parsed == 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
static void listFavorites(const CommandContext& ctx,
|
||||
Api::Database& db, uint64_t userKey)
|
||||
{
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites) {
|
||||
ctx.reply(ctx.tr("Couldn't read your favorites."));
|
||||
return;
|
||||
}
|
||||
if (favorites->empty()) {
|
||||
ctx.reply(ctx.trf(
|
||||
"You have no favorites yet. Save the current track "
|
||||
"with {}fav add",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
std::string msg = "Your favorites:";
|
||||
size_t index = 1;
|
||||
for (const auto& fav : *favorites) {
|
||||
msg +=
|
||||
std::format("\n{}. {}", index++, trackLink(fav.track));
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
static void addCurrent(const CommandContext& ctx,
|
||||
MusicManager& manager, Api::Database& db,
|
||||
uint64_t userKey)
|
||||
{
|
||||
auto current = manager.getCurrentTrack();
|
||||
if (!current || !current->has_value()) {
|
||||
ctx.reply(ctx.tr("Nothing is playing right now."));
|
||||
return;
|
||||
}
|
||||
const auto& track = (*current)->track;
|
||||
if (db.addFavorite(userKey, track)) {
|
||||
ctx.reply(ctx.trf("Added to favorites: {}", track.title));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("Couldn't save the favorite."));
|
||||
}
|
||||
}
|
||||
|
||||
static void playFavorite(const CommandContext& ctx,
|
||||
MusicManager& manager, Api::Database& db,
|
||||
uint64_t userKey, const std::string& arg)
|
||||
{
|
||||
auto index = parseIndex(arg);
|
||||
if (!index) {
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: fav play <number> (see fav list)"));
|
||||
return;
|
||||
}
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites || *index > favorites->size()) {
|
||||
ctx.reply(ctx.tr("No favorite with that number."));
|
||||
return;
|
||||
}
|
||||
const auto& track = (*favorites)[*index - 1].track;
|
||||
auto result = manager.play(track.originalUrl, ctx.clientId);
|
||||
if (result) {
|
||||
ctx.reply(*result);
|
||||
} else {
|
||||
ctx.reply(ctx.trf("Couldn't play it: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
|
||||
static void removeFavorite(const CommandContext& ctx,
|
||||
Api::Database& db, uint64_t userKey,
|
||||
const std::string& arg)
|
||||
{
|
||||
auto index = parseIndex(arg);
|
||||
if (!index) {
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: fav remove <number> (see fav list)"));
|
||||
return;
|
||||
}
|
||||
auto favorites = db.getFavorites(userKey);
|
||||
if (!favorites || *index > favorites->size()) {
|
||||
ctx.reply(ctx.tr("No favorite with that number."));
|
||||
return;
|
||||
}
|
||||
const auto& fav = (*favorites)[*index - 1];
|
||||
if (db.removeFavorite(userKey, fav.track.originalUrl)) {
|
||||
ctx.reply(
|
||||
ctx.trf("Removed from favorites: {}", fav.track.title));
|
||||
} else {
|
||||
ctx.reply(ctx.tr("Couldn't remove the favorite."));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !history [n] — recently played tracks (global, deduplicated).
|
||||
class HistoryCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!db) {
|
||||
ctx.reply(ctx.tr("History is unavailable (no database)."));
|
||||
return;
|
||||
}
|
||||
|
||||
size_t limit = 10;
|
||||
if (!ctx.args.empty()) {
|
||||
unsigned parsed = 0;
|
||||
auto [_, ec] = std::from_chars(
|
||||
ctx.args.data(), ctx.args.data() + ctx.args.size(),
|
||||
parsed);
|
||||
if (ec == std::errc{} && parsed > 0) {
|
||||
limit = std::min<size_t>(parsed, 25);
|
||||
}
|
||||
}
|
||||
|
||||
auto recent = db->getRecentlyPlayed(0, limit);
|
||||
if (!recent) {
|
||||
ctx.reply(ctx.tr("Couldn't read the playback history."));
|
||||
return;
|
||||
}
|
||||
if (recent->empty()) {
|
||||
ctx.reply(ctx.tr("Nothing has been played yet."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string msg = "Recently played:";
|
||||
size_t index = 1;
|
||||
for (const auto& track : *recent) {
|
||||
msg += std::format("\n{}. {}", index++, trackLink(track));
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Show recently played tracks";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[count]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"recent"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,111 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "../i18n/Localization.hpp"
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !language [en|ru] — show or set the caller's reply language. The choice
|
||||
// is stored per user (keyed by the stable TS3 unique identifier) in
|
||||
// kv_store so it survives reconnects and restarts. With no argument it
|
||||
// reports the current language and the available options.
|
||||
class LanguageCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
std::string arg = trimmedLower(ctx.args);
|
||||
|
||||
if (arg.empty()) {
|
||||
ctx.reply(
|
||||
ctx.trf("Current language: {}. Available: en, ru. Use "
|
||||
"{}language <en|ru>.",
|
||||
I18n::languageName(ctx.language), ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const bool isEn =
|
||||
arg == "en" || arg == "eng" || arg == "english";
|
||||
const bool isRu = arg == "ru" || arg == "rus" ||
|
||||
arg == "russian" ||
|
||||
arg == "\xd1\x80\xd1\x83\xd1\x81\xd1\x81"
|
||||
"\xd0\xba\xd0\xb8\xd0\xb9";
|
||||
if (!isEn && !isRu) {
|
||||
ctx.reply(ctx.tr("Unknown language. Choose 'en' or 'ru'."));
|
||||
return;
|
||||
}
|
||||
const I18n::Language newLang =
|
||||
isRu ? I18n::Language::Russian : I18n::Language::English;
|
||||
|
||||
auto manager = ctx.musicManager.lock();
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!manager || !db) {
|
||||
ctx.reply(
|
||||
ctx.tr("Language settings are unavailable right now."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto uid = manager->clientUid(ctx.clientId);
|
||||
if (!uid || uid->empty()) {
|
||||
ctx.reply(ctx.tr("Couldn't identify you on the server."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto saved = db->setKv(
|
||||
"lang:" + *uid, std::string(I18n::languageCode(newLang)));
|
||||
if (!saved) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't save your language. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirm in the newly selected language.
|
||||
std::string name(I18n::languageName(newLang));
|
||||
ctx.reply(std::vformat(
|
||||
I18n::translate("\xe2\x9c\x85 Language set to {}.",
|
||||
newLang),
|
||||
std::make_format_args(name)));
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Sets your reply language (English or Russian).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "[en|ru]"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"lang"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string trimmedLower(std::string_view in)
|
||||
{
|
||||
size_t b = in.find_first_not_of(" \t");
|
||||
if (b == std::string_view::npos) {
|
||||
return {};
|
||||
}
|
||||
size_t e = in.find_last_not_of(" \t");
|
||||
std::string out(in.substr(b, e - b + 1));
|
||||
std::transform(out.begin(), out.end(), out.begin(),
|
||||
[](unsigned char c) { return std::tolower(c); });
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/LyricsService.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !lyrics — show the lyrics of the currently playing track (via lrclib).
|
||||
class LyricsCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
if (!current || !current->has_value()) {
|
||||
ctx.reply(ctx.trf("Nothing is currently playing. "
|
||||
"Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& track = current->value().track;
|
||||
|
||||
auto lyrics = ctx.service<LyricsService>();
|
||||
if (!lyrics) {
|
||||
ctx.reply(ctx.tr("Lyrics are unavailable right now."));
|
||||
return;
|
||||
}
|
||||
|
||||
long long durationSec =
|
||||
track.duration.has_value()
|
||||
? track.duration->count() / 1000
|
||||
: 0;
|
||||
auto result = lyrics->fetch(track.title, track.artist,
|
||||
track.album, durationSec);
|
||||
|
||||
if (!result.found || result.plain.empty()) {
|
||||
ctx.reply(ctx.trf("No lyrics found for {}.",
|
||||
trackLink(track)));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x8e\xa4 {}\n\n{}", trackLink(track),
|
||||
result.plain);
|
||||
ctx.reply(msg);
|
||||
} catch (const std::exception& e) {
|
||||
Void::Log::error(
|
||||
"LyricsCommand", "{}",
|
||||
std::format("Lyrics command exception: {}", e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows the lyrics of the current track.";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"ly"};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
@@ -17,14 +17,15 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: move <from> <to>\nExample: move 5 1 "
|
||||
"(moves track 5 to position 1)");
|
||||
ctx.reply(
|
||||
ctx.tr("Usage: move <from> <to>\nExample: move 5 1 "
|
||||
"(moves track 5 to position 1)"));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -33,7 +34,8 @@ namespace Echoion::Core
|
||||
|
||||
auto spacePos = ctx.args.find(' ');
|
||||
if (spacePos == std::string::npos) {
|
||||
ctx.reply("Please provide both from and to positions.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide both from and to positions."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -46,35 +48,40 @@ namespace Echoion::Core
|
||||
|
||||
if (result1.ec != std::errc() ||
|
||||
result2.ec != std::errc() || from == 0 || to == 0) {
|
||||
ctx.reply("Please provide valid position numbers "
|
||||
"(starting from 1).");
|
||||
ctx.reply(
|
||||
ctx.tr("Please provide valid position numbers "
|
||||
"(starting from 1)."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto moveResult = manager->moveInQueue(
|
||||
from - 1, to - 1); // Convert to 0-based
|
||||
if (!moveResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"MoveCommand", "{}",
|
||||
std::format("Move command failed: {}",
|
||||
moveResult.error().message));
|
||||
|
||||
if (moveResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply("One of those positions doesn't exist in "
|
||||
"the queue.");
|
||||
ctx.reply(ctx.tr(
|
||||
"One of those positions doesn't exist in "
|
||||
"the queue."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
"Couldn't move that track. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't move that track. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format(
|
||||
"Moved track from position {} to {}.", from, to));
|
||||
ctx.reply(ctx.trf("Moved track from position {} to {}.",
|
||||
from, to));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"MoveCommand", "{}",
|
||||
std::format("Move command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,24 +16,26 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto current = manager->getCurrentTrack();
|
||||
if (!current) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"NowPlayingCommand", "{}",
|
||||
std::format("NowPlaying command failed: {}",
|
||||
current.error().message));
|
||||
ctx.reply("Couldn't get current track information.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't get current track information."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!current->has_value()) {
|
||||
ctx.reply(std::format("Nothing is currently playing. "
|
||||
"Add something with {}play !",
|
||||
ctx.prefix));
|
||||
ctx.reply(ctx.trf("Nothing is currently playing. "
|
||||
"Add something with {}play !",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,40 +46,47 @@ namespace Echoion::Core
|
||||
displayText = std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*trackInfo.shortenedUrl)
|
||||
: displayText;
|
||||
std::string msg =
|
||||
std::format("\xf0\x9f\x8e\xb5 {}", linkText);
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x8e\xb5 {}",
|
||||
markdownLink(displayText, trackLinkUrl(trackInfo)));
|
||||
|
||||
// Show current position / total duration
|
||||
// Show current position / total duration after a middot
|
||||
// (no [] — TeamSpeak parses it as a link reference).
|
||||
auto playbackState = manager->getPlaybackState();
|
||||
if (playbackState &&
|
||||
playbackState->currentTrack.has_value() &&
|
||||
trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
auto position = playbackState->position;
|
||||
msg += std::format(" [{}/{}]",
|
||||
msg += std::format(" {} {}/{}", kDot,
|
||||
formatDuration(position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
msg += std::format(" [{}]",
|
||||
msg += std::format(" {} {}", kDot,
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
|
||||
if (!track.addedBy.empty()) {
|
||||
msg += std::format(" (requested by {})", track.addedBy);
|
||||
msg += std::format(" (requested by {})",
|
||||
escapeMarkdown(track.addedBy));
|
||||
}
|
||||
|
||||
// Same at-a-glance status footer as !help and !list.
|
||||
if (std::string status = playbackStatusLine(ctx);
|
||||
!status.empty()) {
|
||||
msg += "\n\n";
|
||||
msg += status;
|
||||
}
|
||||
|
||||
ctx.reply(msg);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"NowPlaying command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"NowPlayingCommand", "{}",
|
||||
std::format("NowPlaying command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,22 +104,6 @@ namespace Echoion::Core
|
||||
{
|
||||
return {"np", "current", "playing"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,32 +16,34 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->pause();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("Pause command failed: {}",
|
||||
result.error().message));
|
||||
Void::Log::error("PauseCommand", "{}",
|
||||
std::format("Pause command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
ctx.reply(ctx.tr("Nothing is playing right now."));
|
||||
} else {
|
||||
ctx.reply(
|
||||
"Couldn't pause playback. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't pause playback. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Playback paused.");
|
||||
ctx.reply(ctx.tr("Playback paused."));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PauseCommand", "{}",
|
||||
std::format("Pause command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class PlayCommand : public Command
|
||||
// Shared play rendering. Concrete commands pick the catalog scope:
|
||||
// !play (both), !pyt (YouTube), !pya (Yandex). A bare URL always plays
|
||||
// directly regardless of scope; free text searches the chosen catalog(s)
|
||||
// and, when there is more than one hit, shows a !select list — the same
|
||||
// flow as the search commands.
|
||||
class PlayCommandBase : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -16,80 +22,90 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply("The music service is currently unavailable. "
|
||||
"Please try again later.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable. "
|
||||
"Please try again later."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: play <url or search query>\nExample: "
|
||||
"play never gonna give you up");
|
||||
ctx.reply(ctx.trf("Usage: {} <url or search "
|
||||
"query>\nExample: {} never "
|
||||
"gonna give you up",
|
||||
label(), label()));
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a direct URL
|
||||
// Direct URL: hand straight to the player.
|
||||
if (ctx.args.find("http") == 0) {
|
||||
auto result = manager->play(ctx.args, ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Play URL failed '{}': {}",
|
||||
ctx.args, result.error().message));
|
||||
|
||||
switch (result.error().code) {
|
||||
case Api::ErrorCode::NetworkError:
|
||||
ctx.reply("Couldn't connect to that URL. "
|
||||
"Please check and try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't connect to that URL. "
|
||||
"Please check and try again."));
|
||||
break;
|
||||
case Api::ErrorCode::InvalidUrl:
|
||||
ctx.reply(
|
||||
"That doesn't look like a valid URL.");
|
||||
ctx.reply(ctx.tr(
|
||||
"That doesn't look like a valid URL."));
|
||||
break;
|
||||
default:
|
||||
ctx.reply("Couldn't play that URL. Please "
|
||||
"try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't play that URL. Please "
|
||||
"try again."));
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// result contains the track title
|
||||
ctx.reply(std::format("Added to queue: {}", *result));
|
||||
ctx.reply(ctx.trf("Added to queue: {}", *result));
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, treat as search query
|
||||
auto searchResult = manager->search(ctx.args);
|
||||
// Otherwise, search the chosen catalog(s).
|
||||
auto searchResult = manager->search(ctx.args, scope());
|
||||
if (!searchResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
searchResult.error().message));
|
||||
|
||||
if (searchResult.error().code ==
|
||||
Api::ErrorCode::NetworkError) {
|
||||
ctx.reply("Couldn't connect to search service. "
|
||||
"Please check your connection.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't connect to search service. "
|
||||
"Please check your connection."));
|
||||
} else {
|
||||
ctx.reply("Search failed. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Search failed. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (searchResult->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
ctx.reply(ctx.tr(
|
||||
"No results found. Try different keywords."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Single result - play immediately
|
||||
// Single result - queue immediately.
|
||||
if (searchResult->tracks.size() == 1) {
|
||||
const auto& track = searchResult->tracks[0];
|
||||
auto playResult =
|
||||
manager->queueTrack(track, ctx.clientId);
|
||||
if (!playResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Queue failed: {}",
|
||||
playResult.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't add that track. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't add that track. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -98,23 +114,19 @@ namespace Echoion::Core
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
ctx.reply(std::format("Added to queue: {}", linkText));
|
||||
ctx.reply(ctx.trf(
|
||||
"Added to queue: {}",
|
||||
markdownLink(displayText, trackLinkUrl(track))));
|
||||
return;
|
||||
}
|
||||
|
||||
// Multiple results - store and show list
|
||||
// Multiple results - store and show list.
|
||||
manager->storePendingSearch(ctx.clientId,
|
||||
searchResult->tracks);
|
||||
|
||||
std::string msg =
|
||||
std::format("\xf0\x9f\x94\x8d Multiple results "
|
||||
"found. Use {}select <number>:\n",
|
||||
std::format("Multiple results \xe2\x80\x94 use "
|
||||
"{}select <number>:\n\n",
|
||||
ctx.prefix);
|
||||
for (size_t i = 0; i < searchResult->tracks.size() && i < 5;
|
||||
++i) {
|
||||
@@ -124,15 +136,11 @@ namespace Echoion::Core
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg += std::format("{}. {}", i + 1, linkText);
|
||||
msg += std::format(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText, trackLinkUrl(track)));
|
||||
if (track.duration.has_value()) {
|
||||
msg += std::format(" [{}]",
|
||||
msg += std::format(" {} {}", kDot,
|
||||
formatDuration(*track.duration));
|
||||
}
|
||||
msg += "\n";
|
||||
@@ -141,33 +149,26 @@ namespace Echoion::Core
|
||||
ctx.reply(msg);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PlayCommand", "{}",
|
||||
std::format("Play command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong while trying to play. "
|
||||
"Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong while trying to play. "
|
||||
"Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a track from URL or searches and lets you "
|
||||
"select.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
return CommandCategory::Play;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
protected:
|
||||
|
||||
// The catalog(s) this command searches, and the command name used
|
||||
// in usage text.
|
||||
[[nodiscard]] virtual MusicManager::SearchScope scope() const = 0;
|
||||
[[nodiscard]] virtual std::string_view label() const = 0;
|
||||
|
||||
private:
|
||||
|
||||
@@ -186,4 +187,32 @@ namespace Echoion::Core
|
||||
}
|
||||
};
|
||||
|
||||
// !play — both YouTube and Yandex Music.
|
||||
class PlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays a track from URL, or searches YouTube and Yandex "
|
||||
"Music and lets you select.";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"p", "add"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::All;
|
||||
}
|
||||
std::string_view label() const override { return "play"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
@@ -17,8 +17,8 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -26,23 +26,25 @@ namespace Echoion::Core
|
||||
// List playlists
|
||||
auto playlists = manager->getPlaylists();
|
||||
if (!playlists) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PlaylistCommand", "{}",
|
||||
std::format("Playlist list failed: {}",
|
||||
playlists.error().message));
|
||||
ctx.reply("Couldn't retrieve playlists.");
|
||||
ctx.reply(ctx.tr("Couldn't retrieve playlists."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (playlists->empty()) {
|
||||
ctx.reply("No playlists available.");
|
||||
ctx.reply(ctx.tr("No playlists available."));
|
||||
return;
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x81 Available playlists:\n";
|
||||
msg << ctx.tr(
|
||||
"\xf0\x9f\x93\x81 Available playlists:\n");
|
||||
for (const auto& pl : *playlists) {
|
||||
msg << std::format("- {} ({} tracks)\n", pl.name,
|
||||
pl.tracks.size());
|
||||
msg << ctx.trf("- {} ({} tracks)\n", pl.name,
|
||||
pl.tracks.size());
|
||||
}
|
||||
|
||||
ctx.reply(msg.str());
|
||||
@@ -51,29 +53,35 @@ namespace Echoion::Core
|
||||
auto result = manager->loadPlaylist(
|
||||
std::string(ctx.args), ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"PlaylistCommand", "{}",
|
||||
std::format("Playlist load failed: {}",
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply("That playlist doesn't exist.");
|
||||
ctx.reply(
|
||||
ctx.tr("That playlist doesn't exist."));
|
||||
} else {
|
||||
ctx.reply("Couldn't load the playlist. Please "
|
||||
"try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't load the playlist. Please "
|
||||
"try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(std::format(
|
||||
ctx.reply(ctx.trf(
|
||||
"Loading playlist '{}'... Tracks will be added to "
|
||||
"the queue as they are resolved.",
|
||||
ctx.args));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Playlist command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"PlaylistCommand", "{}",
|
||||
std::format("Playlist command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
@@ -17,8 +17,8 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -27,9 +27,10 @@ namespace Echoion::Core
|
||||
auto state = manager->getPlaybackState();
|
||||
|
||||
if (!queue) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Queue command failed: {}", queue.error().message));
|
||||
ctx.reply("Couldn't get queue information.");
|
||||
Void::Log::error("QueueCommand", "{}",
|
||||
std::format("Queue command failed: {}",
|
||||
queue.error().message));
|
||||
ctx.reply(ctx.tr("Couldn't get queue information."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -41,7 +42,7 @@ namespace Echoion::Core
|
||||
if (page < 1) {
|
||||
page = 1;
|
||||
}
|
||||
} catch (...) {
|
||||
} catch (const std::exception&) {
|
||||
page = 1;
|
||||
}
|
||||
}
|
||||
@@ -64,26 +65,34 @@ namespace Echoion::Core
|
||||
static_cast<int>(queue->size()));
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x9c **Queue** (Page " << page << "/"
|
||||
<< totalPages << ")\n";
|
||||
|
||||
// Same at-a-glance status footer as !help and !np. A
|
||||
// "Paused" marker is prepended since the queue view is
|
||||
// where a stopped playhead is most relevant.
|
||||
if (std::string status = playbackStatusLine(ctx);
|
||||
!status.empty()) {
|
||||
if (state && state->isPaused) {
|
||||
msg << ctx.tr("\xe2\x8f\xb8 Paused\n");
|
||||
}
|
||||
msg << status;
|
||||
}
|
||||
// Current track
|
||||
if (current && current->has_value()) {
|
||||
const auto& track = current->value();
|
||||
const auto& trackInfo = track.track;
|
||||
|
||||
// Build time display: [current/total] or [total]
|
||||
// Build time display: · current/total or · total
|
||||
// (no [] — TeamSpeak parses it as a link reference).
|
||||
std::string timeStr;
|
||||
if (trackInfo.duration.has_value() &&
|
||||
trackInfo.duration->count() > 0) {
|
||||
if (state) {
|
||||
timeStr = std::format(
|
||||
" [{}/{}]",
|
||||
" {} {}/{}", kDot,
|
||||
formatDuration(state->position),
|
||||
formatDuration(*trackInfo.duration));
|
||||
} else {
|
||||
timeStr = std::format(
|
||||
" [{}]",
|
||||
" {} {}", kDot,
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
}
|
||||
@@ -93,23 +102,20 @@ namespace Echoion::Core
|
||||
displayText = std::format(
|
||||
"{} by {}", trackInfo.title, trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format("[{}]({}){}", displayText,
|
||||
*trackInfo.shortenedUrl, timeStr)
|
||||
: displayText + timeStr;
|
||||
msg << std::format("\n**Now Playing:** {}\n", linkText);
|
||||
msg << ctx.trf(
|
||||
"\n**Now Playing:** {}{}\n",
|
||||
markdownLink(displayText, trackLinkUrl(trackInfo)),
|
||||
timeStr);
|
||||
}
|
||||
|
||||
// Queue
|
||||
if (queue->empty()) {
|
||||
msg << std::format(
|
||||
msg << ctx.trf(
|
||||
"\nThe queue is empty. Add songs with {}play !",
|
||||
ctx.prefix);
|
||||
} else {
|
||||
msg << std::format("\n**Up Next ({} tracks):**\n",
|
||||
queue->size());
|
||||
msg << ctx.trf("\n**Up Next ({} tracks):**\n",
|
||||
queue->size());
|
||||
for (int i = startIdx; i < endIdx; ++i) {
|
||||
const auto& entry = (*queue)[i];
|
||||
const auto& trackInfo = entry.track;
|
||||
@@ -119,51 +125,38 @@ namespace Echoion::Core
|
||||
std::format("{} by {}", trackInfo.title,
|
||||
trackInfo.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
trackInfo.shortenedUrl.has_value() &&
|
||||
!trackInfo.shortenedUrl->empty()
|
||||
? std::format(
|
||||
"[{}]({}) [{}]", displayText,
|
||||
*trackInfo.shortenedUrl,
|
||||
formatDuration(*trackInfo.duration))
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << std::format(" (by {})", entry.addedBy);
|
||||
msg << ctx.trf(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText,
|
||||
trackLinkUrl(trackInfo)));
|
||||
if (trackInfo.duration.has_value()) {
|
||||
msg << ctx.trf(
|
||||
" {} {}", kDot,
|
||||
formatDuration(*trackInfo.duration));
|
||||
}
|
||||
msg << "\n";
|
||||
if (!entry.addedBy.empty()) {
|
||||
msg << ctx.trf(" (by {})",
|
||||
escapeMarkdown(entry.addedBy));
|
||||
}
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
if (totalPages > 1) {
|
||||
msg << std::format(
|
||||
"\nUse {}queue <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
msg << ctx.trf("\nUse {}queue <page> to see more "
|
||||
"(page {} of {})",
|
||||
ctx.prefix, page, totalPages);
|
||||
}
|
||||
}
|
||||
|
||||
// State indicators
|
||||
if (state) {
|
||||
msg << "\n\n";
|
||||
if (state->isPaused) {
|
||||
msg << "\xe2\x8f\xb8 Paused | ";
|
||||
}
|
||||
if (state->shuffle) {
|
||||
msg << "\xf0\x9f\x94\x80 Shuffle | ";
|
||||
}
|
||||
if (state->repeat) {
|
||||
msg << "\xf0\x9f\x94\x81 Repeat | ";
|
||||
}
|
||||
msg << std::format(
|
||||
"Volume: {}%",
|
||||
static_cast<int>(state->volume * 100));
|
||||
}
|
||||
|
||||
msg << ctx.tr("\xf0\x9f\x93\x9c **Queue** (Page ") << page
|
||||
<< "/" << totalPages << ctx.tr(")\n");
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"QueueCommand", "{}",
|
||||
std::format("Queue command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,22 +176,6 @@ namespace Echoion::Core
|
||||
{
|
||||
return {"q", "list"};
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static std::string
|
||||
formatDuration(std::chrono::milliseconds duration)
|
||||
{
|
||||
auto totalSeconds = duration.count() / 1000;
|
||||
auto hours = totalSeconds / 3600;
|
||||
auto mins = (totalSeconds % 3600) / 60;
|
||||
auto secs = totalSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return std::format("{}:{:02}:{:02}", hours, mins, secs);
|
||||
}
|
||||
return std::format("{}:{:02}", mins, secs);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -13,11 +14,26 @@ namespace Echoion::Core
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
// This is a placeholder - actual reload is handled by the
|
||||
// plugin
|
||||
ECHOION_LOG_INFO("Reload requested by user");
|
||||
ctx.reply("Reload is handled automatically by the plugin. Use "
|
||||
"the TS3 plugin menu to reload the core.");
|
||||
Void::Log::info("ReloadCommand", "{}",
|
||||
"Reload requested by user");
|
||||
|
||||
// Reload configuration from disk. A full core/plugin reload is
|
||||
// driven from the TS plugin menu (that lives in the plugin).
|
||||
if (auto core = ctx.service<Api::ICoreInterface>()) {
|
||||
auto result = core->reloadConfig();
|
||||
if (result) {
|
||||
ctx.reply(
|
||||
ctx.tr("✅ Configuration reloaded. For a full core "
|
||||
"reload, use the TS plugin menu."));
|
||||
} else {
|
||||
ctx.reply(std::string("❌ Config reload failed: ") +
|
||||
result.error().message);
|
||||
}
|
||||
} else {
|
||||
ctx.reply(
|
||||
ctx.tr("Reload is handled by the plugin. Use the TS "
|
||||
"plugin menu to reload the core."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Core.hpp" // For Core::reloadConfig
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <CoreInterface.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -15,19 +15,29 @@ namespace Echoion::Core
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
try {
|
||||
// Note: ctx.core is not directly accessible, we need to use
|
||||
// the MusicManager's core reference For now, reply with
|
||||
// instructions
|
||||
ctx.reply(
|
||||
"Config reload: Please use !reload command or restart "
|
||||
"the bot for config changes to take effect.");
|
||||
auto core = ctx.service<Api::ICoreInterface>();
|
||||
if (!core) {
|
||||
ctx.reply(
|
||||
ctx.tr("Config reload is unavailable right now."));
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: Add core reference to CommandContext so commands
|
||||
// can call Core methods
|
||||
auto result = core->reloadConfig();
|
||||
if (result) {
|
||||
ctx.reply(
|
||||
ctx.tr("✅ Configuration reloaded from disk."));
|
||||
} else {
|
||||
ctx.reply(std::string("❌ Failed to reload config: ") +
|
||||
result.error().message);
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"ReloadConfig command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"ReloadConfigCommand",
|
||||
"{}",
|
||||
std::format("ReloadConfig command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
@@ -17,16 +17,16 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
std::format("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
ctx.trf("Usage: remove <position>\nUse {}queue "
|
||||
"to see track positions.",
|
||||
ctx.prefix));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -36,35 +36,40 @@ namespace Echoion::Core
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
position);
|
||||
if (result.ec != std::errc() || position == 0) {
|
||||
ctx.reply("Please provide a valid position number "
|
||||
"(starting from 1).");
|
||||
ctx.reply(
|
||||
ctx.tr("Please provide a valid position number "
|
||||
"(starting from 1)."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto remResult = manager->removeFromQueue(
|
||||
position - 1); // Convert to 0-based
|
||||
if (!remResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"RemoveCommand", "{}",
|
||||
std::format("Remove command failed: {}",
|
||||
remResult.error().message));
|
||||
|
||||
if (remResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(
|
||||
"That position doesn't exist in the queue.");
|
||||
ctx.reply(ctx.tr(
|
||||
"That position doesn't exist in the queue."));
|
||||
} else {
|
||||
ctx.reply("Couldn't remove that track. Please try "
|
||||
"again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't remove that track. Please try "
|
||||
"again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(
|
||||
std::format("Removed track at position {}.", position));
|
||||
ctx.trf("Removed track at position {}.", position));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"RemoveCommand", "{}",
|
||||
std::format("Remove command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,26 +16,31 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->toggleRepeat();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"RepeatCommand", "{}",
|
||||
std::format("Repeat command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply("Couldn't toggle repeat. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't toggle repeat. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result ? "\xf0\x9f\x94\x81 Repeat is now ON."
|
||||
: "Repeat is now OFF.");
|
||||
ctx.reply(*result
|
||||
? ctx.tr("\xf0\x9f\x94\x81 Repeat is now ON.")
|
||||
: ctx.tr("Repeat is now OFF."));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"RepeatCommand", "{}",
|
||||
std::format("Repeat command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,32 +16,36 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->resume();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"ResumeCommand", "{}",
|
||||
std::format("Resume command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Playback isn't paused right now.");
|
||||
} else {
|
||||
ctx.reply(
|
||||
"Couldn't resume playback. Please try again.");
|
||||
ctx.tr("Playback isn't paused right now."));
|
||||
} else {
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't resume playback. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Playback resumed.");
|
||||
ctx.reply(ctx.tr("Playback resumed."));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"ResumeCommand", "{}",
|
||||
std::format("Resume command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "../MusicManager.hpp"
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
class SearchCommand : public Command
|
||||
// Shared search rendering. Concrete commands pick the catalog scope:
|
||||
// !search (both), !youtube/!yb (YouTube), !ya/!yandex (Yandex).
|
||||
class SearchCommandBase : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -17,35 +20,38 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: search <query>\nExample: search "
|
||||
"never gonna give you up");
|
||||
ctx.reply(ctx.trf("Usage: {} <query>", label()));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->search(ctx.args);
|
||||
auto result = manager->search(ctx.args, scope());
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"SearchCommand", "{}",
|
||||
std::format("Search failed for '{}': {}", ctx.args,
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::NetworkError) {
|
||||
ctx.reply("Couldn't connect to search service. "
|
||||
"Please check your connection.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't connect to search service. "
|
||||
"Please check your connection."));
|
||||
} else {
|
||||
ctx.reply("Search failed. Please try again later.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Search failed. Please try again later."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (result->tracks.empty()) {
|
||||
ctx.reply("No results found. Try different keywords.");
|
||||
ctx.reply(ctx.tr(
|
||||
"No results found. Try different keywords."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,62 +59,54 @@ namespace Echoion::Core
|
||||
manager->storePendingSearch(ctx.clientId, result->tracks);
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x94\x8d Search results for \"" << ctx.args
|
||||
<< "\":\n\n";
|
||||
msg << ctx.tr("Search results for \"") << ctx.args
|
||||
<< ctx.tr("\":\n\n");
|
||||
|
||||
for (size_t i = 0; i < result->tracks.size() && i < 5;
|
||||
++i) {
|
||||
const auto& track = result->tracks[i];
|
||||
// Format as [Title by Artist](shortenedUrl) with
|
||||
// duration
|
||||
std::string displayText = track.title;
|
||||
if (!track.artist.empty()) {
|
||||
displayText = std::format("{} by {}", track.title,
|
||||
track.artist);
|
||||
}
|
||||
std::string linkText =
|
||||
track.shortenedUrl.has_value() &&
|
||||
!track.shortenedUrl->empty()
|
||||
? std::format("[{}]({})", displayText,
|
||||
*track.shortenedUrl)
|
||||
: displayText;
|
||||
msg << std::format("{}. {}", i + 1, linkText);
|
||||
// [escaped title](url) · duration (no [] around the
|
||||
// duration: TeamSpeak parses [..] as a link reference).
|
||||
msg << ctx.trf(
|
||||
"{}. {}", i + 1,
|
||||
markdownLink(displayText, trackLinkUrl(track)));
|
||||
if (track.duration.has_value()) {
|
||||
msg << std::format(" [{}]",
|
||||
formatDuration(*track.duration));
|
||||
msg << " " << kDot << " "
|
||||
<< formatDuration(*track.duration);
|
||||
}
|
||||
msg << "\n";
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
msg << std::format(
|
||||
"\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
msg << ctx.trf("\nUse {}select <number> to play a result.",
|
||||
ctx.prefix);
|
||||
|
||||
ctx.reply(msg.str());
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"SearchCommand", "{}",
|
||||
std::format("Search command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Searches for tracks and shows results.";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Music;
|
||||
return CommandCategory::Search;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"find", "s"};
|
||||
}
|
||||
protected:
|
||||
|
||||
// The catalog(s) this command searches, and the command name
|
||||
// used in usage text.
|
||||
[[nodiscard]] virtual MusicManager::SearchScope scope() const = 0;
|
||||
[[nodiscard]] virtual std::string_view label() const = 0;
|
||||
|
||||
private:
|
||||
|
||||
@@ -127,4 +125,28 @@ namespace Echoion::Core
|
||||
}
|
||||
};
|
||||
|
||||
// !search — both YouTube and Yandex Music.
|
||||
class SearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search YouTube and Yandex Music for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"find", "s"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::All;
|
||||
}
|
||||
std::string_view label() const override { return "search"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
@@ -18,16 +18,16 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply(
|
||||
ctx.reply(ctx.tr(
|
||||
"Usage: seek <+/-seconds>\nExamples:\n seek +30 "
|
||||
"(skip forward 30s)\n seek -10 (skip back 10s)\n "
|
||||
"seek 60 (jump to 1 minute mark)");
|
||||
"seek 60 (jump to 1 minute mark)"));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -51,9 +51,9 @@ namespace Echoion::Core
|
||||
auto parseResult = std::from_chars(
|
||||
arg.data(), arg.data() + arg.size(), seconds);
|
||||
if (parseResult.ec != std::errc() || seconds < 0) {
|
||||
ctx.reply(
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide a valid number of "
|
||||
"seconds.\nExamples: seek +30, seek -10, seek 60");
|
||||
"seconds.\nExamples: seek +30, seek -10, seek 60"));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -64,8 +64,8 @@ namespace Echoion::Core
|
||||
// Get current position from playback state
|
||||
auto state = manager->getPlaybackState();
|
||||
if (!state) {
|
||||
ctx.reply(
|
||||
"Unable to get current playback position.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Unable to get current playback position."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -94,32 +94,37 @@ namespace Echoion::Core
|
||||
|
||||
auto result = manager->seek(targetPosition);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Seek command failed: {}",
|
||||
result.error().message));
|
||||
Void::Log::error("SeekCommand", "{}",
|
||||
std::format("Seek command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code ==
|
||||
Api::ErrorCode::InvalidArgument) {
|
||||
ctx.reply("Nothing is playing right now.");
|
||||
ctx.reply(ctx.tr("Nothing is playing right now."));
|
||||
} else if (result.error().code ==
|
||||
Api::ErrorCode::NotSupported) {
|
||||
ctx.reply("This track doesn't support seeking.");
|
||||
ctx.reply(
|
||||
ctx.tr("This track doesn't support seeking."));
|
||||
} else {
|
||||
ctx.reply("Couldn't seek. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't seek. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (relative) {
|
||||
ctx.reply(std::format(
|
||||
"Seeked {} from current position.", positionStr));
|
||||
ctx.reply(ctx.trf("Seeked {} from current position.",
|
||||
positionStr));
|
||||
} else {
|
||||
ctx.reply(
|
||||
std::format("Seeked to position {}.", positionStr));
|
||||
ctx.trf("Seeked to position {}.", positionStr));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"SeekCommand", "{}",
|
||||
std::format("Seek command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
@@ -17,14 +17,15 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Usage: select <number>\nSelect a track from "
|
||||
"your last search results.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Usage: select <number>\nSelect a track from "
|
||||
"your last search results."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -35,8 +36,8 @@ namespace Echoion::Core
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
index);
|
||||
if (result.ec != std::errc() || index == 0) {
|
||||
ctx.reply(
|
||||
"Please provide a valid number (1, 2, 3, etc.).");
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide a valid number (1, 2, 3, etc.)."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -45,19 +46,23 @@ namespace Echoion::Core
|
||||
ctx.clientId, index, invokerName);
|
||||
|
||||
if (!selectResult) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Select failed for client {} index {}: {}",
|
||||
ctx.clientId, index, selectResult.error().message));
|
||||
Void::Log::error(
|
||||
"SelectCommand", "{}",
|
||||
std::format(
|
||||
"Select failed for client {} index {}: {}",
|
||||
ctx.clientId, index,
|
||||
selectResult.error().message));
|
||||
|
||||
if (selectResult.error().code ==
|
||||
Api::ErrorCode::NotFound) {
|
||||
ctx.reply(std::format(
|
||||
"No search results found. Use {}play "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
ctx.reply(
|
||||
ctx.trf("No search results found. Use {}play "
|
||||
"<query> to search first.",
|
||||
ctx.prefix));
|
||||
} else {
|
||||
ctx.reply("Couldn't select that track. Please try "
|
||||
"again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't select that track. Please try "
|
||||
"again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -65,9 +70,11 @@ namespace Echoion::Core
|
||||
ctx.reply(*selectResult);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"SelectCommand", "{}",
|
||||
std::format("Select command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,19 +16,29 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Actually shuffle the queue (not just toggle mode)
|
||||
manager->shuffleQueue();
|
||||
if (auto result = manager->shuffleQueue(); !result) {
|
||||
Void::Log::warn(
|
||||
"ShuffleCommand", "{}",
|
||||
std::format("Shuffle failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Something went wrong. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("\xf0\x9f\x94\x80 Queue shuffled!");
|
||||
ctx.reply(ctx.tr("\xf0\x9f\x94\x80 Queue shuffled!"));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"ShuffleCommand", "{}",
|
||||
std::format("Shuffle command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
@@ -17,8 +17,8 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -29,35 +29,39 @@ namespace Echoion::Core
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
count);
|
||||
if (result.ec != std::errc() || count == 0) {
|
||||
ctx.reply(
|
||||
"Please provide a valid number (1 or more).");
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide a valid number (1 or more)."));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
auto result = manager->skip(count);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Skip command failed: {}",
|
||||
result.error().message));
|
||||
Void::Log::error("SkipCommand", "{}",
|
||||
std::format("Skip command failed: {}",
|
||||
result.error().message));
|
||||
|
||||
if (result.error().code == Api::ErrorCode::NotFound) {
|
||||
ctx.reply(
|
||||
"No more tracks in the queue to skip to.");
|
||||
ctx.reply(ctx.tr(
|
||||
"No more tracks in the queue to skip to."));
|
||||
} else {
|
||||
ctx.reply("Couldn't skip. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't skip. Please try again."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (count == 1) {
|
||||
ctx.reply("Skipped to next track.");
|
||||
ctx.reply(ctx.tr("Skipped to next track."));
|
||||
} else {
|
||||
ctx.reply(std::format("Skipped {} tracks.", count));
|
||||
ctx.reply(ctx.trf("Skipped {} tracks.", count));
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"SkipCommand", "{}",
|
||||
std::format("Skip command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !psc / !playsc — play from SoundCloud only (URL or search).
|
||||
class SoundCloudPlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from SoundCloud only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playsc"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::SoundCloud;
|
||||
}
|
||||
std::string_view label() const override { return "psc"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !soundcloud / !sc — search SoundCloud only.
|
||||
class SoundCloudSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search SoundCloud only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"sc", "scloud"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::SoundCloud;
|
||||
}
|
||||
std::string_view label() const override { return "soundcloud"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !stats — global playback statistics.
|
||||
class StatsCommand : public Command
|
||||
{
|
||||
public:
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
auto db = ctx.service<Api::Database>();
|
||||
if (!db) {
|
||||
ctx.reply(
|
||||
ctx.tr("Statistics are unavailable (no database)."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto stats = db->getStatistics(0);
|
||||
if (!stats) {
|
||||
ctx.reply(ctx.tr("Couldn't read playback statistics."));
|
||||
return;
|
||||
}
|
||||
|
||||
const auto totalMinutes = stats->totalPlaytimeMs / 1000 / 60;
|
||||
std::string msg = std::format(
|
||||
"\xf0\x9f\x93\x8a Plays: {} {} Unique tracks: {} {} "
|
||||
"Playtime: {}h {}m",
|
||||
stats->totalPlays, kDot, stats->totalTracks, kDot,
|
||||
totalMinutes / 60, totalMinutes % 60);
|
||||
if (stats->mostPlayedTrack) {
|
||||
msg += std::format("\nMost played: {} ({}x)",
|
||||
trackLink(*stats->mostPlayedTrack),
|
||||
stats->mostPlayedCount);
|
||||
}
|
||||
ctx.reply(msg);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Show playback statistics";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,24 +16,28 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->stop();
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Stop command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply("Couldn't stop playback. Please try again.");
|
||||
Void::Log::error("StopCommand", "{}",
|
||||
std::format("Stop command failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't stop playback. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply("Playback stopped and queue cleared.");
|
||||
ctx.reply(ctx.tr("Playback stopped and queue cleared."));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"StopCommand", "{}",
|
||||
std::format("Stop command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,24 +16,31 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->subscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Subscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply("Couldn't subscribe you. Please try again.");
|
||||
Void::Log::error("SubscribeCommand",
|
||||
"{}",
|
||||
std::format("Subscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't subscribe you. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Subscribe command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"SubscribeCommand",
|
||||
"{}",
|
||||
std::format("Subscribe command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
@@ -19,8 +19,8 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ namespace Echoion::Core
|
||||
auto onlineUids = manager->getOnlineSubscriberUids();
|
||||
|
||||
if (subscribers.empty()) {
|
||||
ctx.reply(
|
||||
"No subscribers. Use !subscribe to receive audio.");
|
||||
ctx.reply(ctx.tr("No subscribers. Use !subscribe to "
|
||||
"receive audio."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -46,45 +46,48 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
std::stringstream msg;
|
||||
msg << "\xf0\x9f\x93\x8b **Subscribed Users** ("
|
||||
<< subscribers.size() << " total)\n";
|
||||
msg << "\xf0\x9f\x9f\xa2 Online: " << online.size()
|
||||
<< " | \xe2\x9a\xaa Offline: " << offline.size()
|
||||
<< "\n\n";
|
||||
msg << ctx.tr("\xf0\x9f\x93\x8b **Subscribed Users** (")
|
||||
<< subscribers.size() << ctx.tr(" total)\n");
|
||||
msg << ctx.tr("\xf0\x9f\x9f\xa2 Online: ") << online.size()
|
||||
<< ctx.tr(" | \xe2\x9a\xaa Offline: ") << offline.size()
|
||||
<< ctx.tr("\n\n");
|
||||
|
||||
// Online subscribers
|
||||
if (!online.empty()) {
|
||||
msg << "**\xf0\x9f\x9f\xa2 Online:**\n";
|
||||
msg << ctx.tr("**\xf0\x9f\x9f\xa2 Online:**\n");
|
||||
for (size_t i = 0; i < online.size(); ++i) {
|
||||
const auto& sub = online[i];
|
||||
msg << std::format("{}. **{}**\n", i + 1,
|
||||
sub.nickname);
|
||||
msg << std::format(" UID: `{}`\n", sub.uid);
|
||||
msg << ctx.trf("{}. **{}**\n", i + 1, sub.nickname);
|
||||
msg << ctx.trf(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << "\n";
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
// Offline subscribers
|
||||
if (!offline.empty()) {
|
||||
msg << "**\xe2\x9a\xaa Offline:**\n";
|
||||
msg << ctx.tr("**\xe2\x9a\xaa Offline:**\n");
|
||||
for (size_t i = 0; i < offline.size(); ++i) {
|
||||
const auto& sub = offline[i];
|
||||
msg << std::format("{}. **{}**\n", i + 1,
|
||||
sub.nickname);
|
||||
msg << std::format(" UID: `{}`\n", sub.uid);
|
||||
msg << ctx.trf("{}. **{}**\n", i + 1, sub.nickname);
|
||||
msg << ctx.trf(" UID: `{}`\n", sub.uid);
|
||||
}
|
||||
msg << "\n";
|
||||
msg << ctx.tr("\n");
|
||||
}
|
||||
|
||||
msg << "Use `!unsubscribeid <uid>` to remove a specific "
|
||||
"subscriber.\n";
|
||||
msg << "Use `!unsubscribeall` to remove all subscribers.";
|
||||
msg << ctx.tr(
|
||||
"Use `!unsubscribeid <uid>` to remove a specific "
|
||||
"subscriber.\n");
|
||||
msg << ctx.tr(
|
||||
"Use `!unsubscribeall` to remove all subscribers.");
|
||||
|
||||
ctx.reply(msg.str());
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Subscribers command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"SubscribersCommand", "{}",
|
||||
std::format("Subscribers command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -17,27 +17,31 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->clearAllSubscriptions();
|
||||
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"UnsubscribeAllCommand", "{}",
|
||||
std::format("Unsubscribe all failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't clear subscriptions. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't clear subscriptions. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribeall command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"UnsubscribeAllCommand", "{}",
|
||||
std::format("Unsubscribeall command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -16,25 +16,31 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
auto result = manager->unsubscribe(ctx.clientId);
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(std::format("Unsubscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't unsubscribe you. Please try again.");
|
||||
Void::Log::error("UnsubscribeCommand",
|
||||
"{}",
|
||||
std::format("Unsubscribe failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't unsubscribe you. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribe command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"UnsubscribeCommand",
|
||||
"{}",
|
||||
std::format("Unsubscribe command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -17,14 +17,15 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.args.empty()) {
|
||||
ctx.reply("Please provide a user UID. Use !subscribers "
|
||||
"to see UIDs.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Please provide a user UID. Use !subscribers "
|
||||
"to see UIDs."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -32,19 +33,23 @@ namespace Echoion::Core
|
||||
auto result = manager->unsubscribeByUid(uid);
|
||||
|
||||
if (!result) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"UnsubscribeIdCommand", "{}",
|
||||
std::format("Unsubscribe by ID failed: {}",
|
||||
result.error().message));
|
||||
ctx.reply(
|
||||
"Couldn't unsubscribe user. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't unsubscribe user. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reply(*result);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Unsubscribeid command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
Void::Log::error(
|
||||
"UnsubscribeIdCommand", "{}",
|
||||
std::format("Unsubscribeid command exception: {}",
|
||||
e.what()));
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Command.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
|
||||
@@ -17,8 +17,8 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto manager = ctx.musicManager.lock();
|
||||
if (!manager) {
|
||||
ctx.reply(
|
||||
"The music service is currently unavailable.");
|
||||
ctx.reply(ctx.tr(
|
||||
"The music service is currently unavailable."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -26,11 +26,11 @@ namespace Echoion::Core
|
||||
// Show current volume
|
||||
auto state = manager->getPlaybackState();
|
||||
if (state) {
|
||||
ctx.reply(std::format(
|
||||
"Current volume: {}%",
|
||||
static_cast<int>(state->volume * 100)));
|
||||
ctx.reply(
|
||||
ctx.trf("Current volume: {}%",
|
||||
static_cast<int>(state->volume * 100)));
|
||||
} else {
|
||||
ctx.reply("Unable to get current volume.");
|
||||
ctx.reply(ctx.tr("Unable to get current volume."));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -42,22 +42,25 @@ namespace Echoion::Core
|
||||
ctx.args.data() + ctx.args.size(),
|
||||
volumePercent);
|
||||
if (result.ec != std::errc()) {
|
||||
ctx.reply("Please provide a valid number (0-100).");
|
||||
ctx.reply(
|
||||
ctx.tr("Please provide a valid number (0-100)."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (volumePercent < 0 || volumePercent > 100) {
|
||||
ctx.reply("Volume must be between 0 and 100.");
|
||||
ctx.reply(ctx.tr("Volume must be between 0 and 100."));
|
||||
return;
|
||||
}
|
||||
|
||||
float volume = volumePercent / 100.0f;
|
||||
auto volResult = manager->setVolume(volume);
|
||||
if (!volResult) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"VolumeCommand", "{}",
|
||||
std::format("Volume command failed: {}",
|
||||
volResult.error().message));
|
||||
ctx.reply("Couldn't change volume. Please try again.");
|
||||
ctx.reply(ctx.tr(
|
||||
"Couldn't change volume. Please try again."));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -71,12 +74,14 @@ namespace Echoion::Core
|
||||
: "\xe2\x96\x91"; // Full block / Light shade
|
||||
}
|
||||
|
||||
ctx.reply(std::format(
|
||||
"Volume: {}% {}", volumePercent, indicator));
|
||||
ctx.reply(
|
||||
ctx.trf("Volume: {}% {}", volumePercent, indicator));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"VolumeCommand", "{}",
|
||||
std::format("Volume command exception: {}", e.what()));
|
||||
ctx.reply("Something went wrong. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Something went wrong. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !pya / !playya — play from Yandex Music only.
|
||||
class YandexPlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from Yandex Music only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playya"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::Yandex;
|
||||
}
|
||||
std::string_view label() const override { return "pya"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !yandex / !ya — search Yandex Music only.
|
||||
class YandexSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search Yandex Music only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"ya"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::Yandex;
|
||||
}
|
||||
std::string_view label() const override { return "yandex"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "PlayCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !pyt / !playyt — play from YouTube only.
|
||||
class YoutubePlayCommand : public PlayCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Plays from YouTube only (URL or search).";
|
||||
}
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "<url or search query>";
|
||||
}
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"playyt"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::YouTube;
|
||||
}
|
||||
std::string_view label() const override { return "pyt"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include "SearchCommand.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// !youtube / !yb — search YouTube only.
|
||||
class YoutubeSearchCommand : public SearchCommandBase
|
||||
{
|
||||
public:
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Search YouTube only for tracks.";
|
||||
}
|
||||
std::string_view getUsage() const override { return "<query>"; }
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
return {"yb", "yt"};
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
MusicManager::SearchScope scope() const override
|
||||
{
|
||||
return MusicManager::SearchScope::YouTube;
|
||||
}
|
||||
std::string_view label() const override { return "youtube"; }
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
[[nodiscard]] inline std::optional<std::uint64_t>
|
||||
uintField(const Void::Json::Value& object, std::string_view key)
|
||||
{
|
||||
const auto* value = object.find(key);
|
||||
if (!value || !value->is_number()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const auto number = value->as_number();
|
||||
// A double equal to 2^64 is what uint64_t::max() rounds to, so use
|
||||
// an exclusive 2^64 bound before converting. Floating-to-integer
|
||||
// conversion outside the destination range is undefined behavior.
|
||||
constexpr double kUint64Limit = 18446744073709551616.0;
|
||||
if (!std::isfinite(number) || number < 0.0 ||
|
||||
std::trunc(number) != number || number >= kUint64Limit) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<std::uint64_t>(number);
|
||||
}
|
||||
} // namespace Echoion::Core::Detail
|
||||
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core::I18n
|
||||
{
|
||||
|
||||
// Languages the bot can reply in. English is the source language: every
|
||||
// English string in the code is a valid translation key, so English never
|
||||
// needs a table entry.
|
||||
enum class Language { English, Russian };
|
||||
|
||||
// Parse a language code ("en"/"ru", case-insensitive). Unknown codes fall
|
||||
// back to English so a bad config/kv value never breaks replies.
|
||||
Language parseLanguage(std::string_view code);
|
||||
|
||||
// The canonical code ("en"/"ru") — used as the kv_store / config value.
|
||||
std::string_view languageCode(Language lang);
|
||||
|
||||
// Human-readable, self-referential name ("English" / "Русский").
|
||||
std::string_view languageName(Language lang);
|
||||
|
||||
// Translate an English source string to `lang`. Returns the original string
|
||||
// unchanged when `lang` is English or no translation is registered, so a
|
||||
// missing entry degrades gracefully to English rather than to an empty
|
||||
// message.
|
||||
std::string_view translate(std::string_view english, Language lang);
|
||||
|
||||
} // namespace Echoion::Core::I18n
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Fixed-capacity ring buffer of audio samples for the playback thread.
|
||||
//
|
||||
// A std::vector<short> drained with erase(begin(), begin()+n) every 20ms
|
||||
// is an O(n) shift of the whole remaining buffer on the real-time audio
|
||||
// path. This ring buffer drains by advancing a head index (O(1)) and
|
||||
// reuses one contiguous allocation, so steady-state playback performs
|
||||
// zero per-frame allocations and no element shuffling. Capacity grows
|
||||
// only if a decoder hands back an unusually large chunk (rare); steady
|
||||
// state never reallocates.
|
||||
//
|
||||
// Single-threaded by design: owned and touched only by the playback
|
||||
// engine thread.
|
||||
class AudioRingBuffer
|
||||
{
|
||||
public:
|
||||
|
||||
void reserve(std::size_t capacity)
|
||||
{
|
||||
if (capacity > storage_.size()) {
|
||||
grow(capacity);
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t size() const { return count_; }
|
||||
[[nodiscard]] bool empty() const { return count_ == 0; }
|
||||
|
||||
// Read the i-th sample counting from the current head.
|
||||
short operator[](std::size_t i) const
|
||||
{
|
||||
return storage_[(head_ + i) % storage_.size()];
|
||||
}
|
||||
|
||||
void append(std::span<const short> data)
|
||||
{
|
||||
if (count_ + data.size() > storage_.size()) {
|
||||
grow(count_ + data.size());
|
||||
}
|
||||
const std::size_t cap = storage_.size();
|
||||
std::size_t tail = (head_ + count_) % cap;
|
||||
for (short sample : data) {
|
||||
storage_[tail] = sample;
|
||||
tail = (tail + 1) % cap;
|
||||
}
|
||||
count_ += data.size();
|
||||
}
|
||||
|
||||
// Drop the first n samples (advance head). O(1).
|
||||
void popFront(std::size_t n)
|
||||
{
|
||||
n = std::min(n, count_);
|
||||
head_ = (head_ + n) % storage_.size();
|
||||
count_ -= n;
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
head_ = 0;
|
||||
count_ = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void grow(std::size_t needed)
|
||||
{
|
||||
// Linearise existing samples into a fresh, larger buffer.
|
||||
std::size_t newCap = storage_.empty() ? 1 : storage_.size();
|
||||
while (newCap < needed) {
|
||||
newCap *= 2;
|
||||
}
|
||||
std::vector<short> next(newCap);
|
||||
for (std::size_t i = 0; i < count_; ++i) {
|
||||
next[i] = storage_[(head_ + i) % storage_.size()];
|
||||
}
|
||||
storage_ = std::move(next);
|
||||
head_ = 0;
|
||||
}
|
||||
|
||||
std::vector<short> storage_;
|
||||
std::size_t head_ = 0;
|
||||
std::size_t count_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,348 @@
|
||||
#pragma once
|
||||
|
||||
#include "../AudioDecoder.hpp"
|
||||
#include "AudioRingBuffer.hpp"
|
||||
#include "PositionClock.hpp"
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <thread>
|
||||
#include <variant>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Everything the engine needs from the outside world. Implemented by
|
||||
// MusicManager; keeps queue policy, source resolution and event
|
||||
// publication out of the real-time loop.
|
||||
class IPlaybackHost
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~IPlaybackHost() = default;
|
||||
|
||||
// Emit one 20ms PCM chunk to the audio sink (TeamSpeak).
|
||||
virtual void emitAudio(std::span<const short> samples) = 0;
|
||||
|
||||
// Resolve a playable URL / local file path for the entry.
|
||||
// Blocking; the engine calls it on a detached async, never on the
|
||||
// audio thread. preferDownload retries via the proxy-download
|
||||
// path after a direct open failed.
|
||||
virtual Api::Result<std::string>
|
||||
resolveStream(const Api::QueueEntry& entry,
|
||||
bool preferDownload) = 0;
|
||||
|
||||
// Queue access: peek what would play next / pop it if unchanged.
|
||||
virtual std::optional<Api::QueueEntry> peekNextTrack() = 0;
|
||||
virtual std::optional<Api::QueueEntry>
|
||||
takeNextTrack(uint64_t expectedQueueId) = 0;
|
||||
// Unconditional pop (fallback when the peeked entry vanished).
|
||||
virtual std::optional<Api::QueueEntry> takeAnyNextTrack() = 0;
|
||||
|
||||
virtual bool repeatEnabled() const = 0;
|
||||
|
||||
// Lifecycle notifications (called on the engine thread).
|
||||
virtual void onTrackStarted(const Api::QueueEntry& entry) = 0;
|
||||
virtual void
|
||||
onTrackFinished(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds finalPosition) = 0;
|
||||
virtual void onPositionTick(const Api::QueueEntry& entry,
|
||||
std::chrono::milliseconds position,
|
||||
std::chrono::milliseconds duration) = 0;
|
||||
// Queue ran dry; engine went idle.
|
||||
virtual void onEngineIdle() = 0;
|
||||
// A resolved local temp file finished playing and can be deleted.
|
||||
virtual void onLocalFileDone(const std::string& path) = 0;
|
||||
// A track failed to resolve or open (before the engine advanced
|
||||
// past it). Called on the engine thread.
|
||||
virtual void onPlaybackError(
|
||||
const Api::Error& error,
|
||||
const std::optional<Api::QueueEntry>& entry) = 0;
|
||||
};
|
||||
|
||||
// Real-time playback engine with gapless track transitions.
|
||||
//
|
||||
// One fixed-cadence (20ms) loop owns BOTH AudioDecoder instances, the
|
||||
// ring buffer and the position clock; no other thread ever touches them.
|
||||
// Control arrives through a small command mailbox; state is published
|
||||
// through atomics. While the current track plays, the next one is
|
||||
// resolved asynchronously and its decoder pre-opened ("warm"), so at EOF
|
||||
// the engine swaps slots and PCM flows without interruption.
|
||||
class PlaybackEngine
|
||||
{
|
||||
public:
|
||||
|
||||
// Sample layout must match the TS3 custom device registration.
|
||||
static constexpr uint32_t SAMPLE_RATE = 192000;
|
||||
static constexpr uint32_t CHANNELS = 2;
|
||||
static constexpr int CHUNK_MS = 20;
|
||||
static constexpr size_t SHORTS_PER_CHUNK =
|
||||
(SAMPLE_RATE * CHANNELS * CHUNK_MS) / 1000;
|
||||
static constexpr auto PREFETCH_THRESHOLD = std::chrono::seconds(15);
|
||||
static constexpr int MAX_CONSECUTIVE_FAILURES = 5;
|
||||
// Grace while a download-to-file retry is in flight. Must cover
|
||||
// YouTubeClient::downloadAudioToFile's 180s wait — the normal
|
||||
// resolve grace (bot.trackTimeout, ~10s) would skip the track
|
||||
// long before the download lands.
|
||||
static constexpr int64_t DOWNLOAD_GRACE_MS = 200'000;
|
||||
|
||||
// How long the engine emits silence waiting for a late resolve
|
||||
// before it gives up on the track and advances. Configurable via
|
||||
// bot.trackTimeout.
|
||||
void setResolveGrace(std::chrono::milliseconds grace)
|
||||
{
|
||||
if (grace.count() > 0) {
|
||||
resolveGraceMs_.store(grace.count());
|
||||
}
|
||||
}
|
||||
|
||||
// Crossfade duration between tracks (bot.crossfadeMs);
|
||||
// 0 = plain gapless handoff.
|
||||
void setCrossfade(std::chrono::milliseconds duration)
|
||||
{
|
||||
crossfadeMs_.store(std::max<int64_t>(duration.count(), 0));
|
||||
}
|
||||
|
||||
// Loudness normalization (features.normalizeLoudness /
|
||||
// targetLoudnessDb): slow AGC toward the target RMS level,
|
||||
// applied before the user volume.
|
||||
void setNormalization(bool enabled, float targetDb)
|
||||
{
|
||||
normalizeTargetDb_.store(targetDb);
|
||||
normalizeEnabled_.store(enabled);
|
||||
}
|
||||
|
||||
explicit PlaybackEngine(IPlaybackHost& host);
|
||||
~PlaybackEngine();
|
||||
|
||||
Api::Result<void>
|
||||
initialize(const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
void shutdown();
|
||||
|
||||
void setProxyConfig(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy);
|
||||
|
||||
// ---- control (thread-safe, non-blocking) ---------------------
|
||||
|
||||
// Play this entry now, replacing whatever is playing. The URL was
|
||||
// already resolved by the caller (so resolution errors could be
|
||||
// reported to the user synchronously).
|
||||
void playNow(Api::QueueEntry entry, std::string streamUrl,
|
||||
bool isLocalFile);
|
||||
|
||||
// Wake the engine so it pulls from the queue if it is idle.
|
||||
void start();
|
||||
|
||||
void pause();
|
||||
void resume();
|
||||
void stopPlayback(); // stop + drop current track (engine idles)
|
||||
void skip(uint32_t count);
|
||||
void seekTo(std::chrono::milliseconds position);
|
||||
|
||||
// Restore after hot reload: open url, seek, optionally stay
|
||||
// paused.
|
||||
void restore(Api::QueueEntry entry, std::string streamUrl,
|
||||
std::chrono::milliseconds position, bool paused);
|
||||
|
||||
void setVolume(float volume) { volume_.store(volume); }
|
||||
[[nodiscard]] float volume() const { return volume_.load(); }
|
||||
|
||||
// ---- state (thread-safe reads) --------------------------------
|
||||
|
||||
[[nodiscard]] bool isPlaying() const { return playing_.load(); }
|
||||
[[nodiscard]] bool isPaused() const { return paused_.load(); }
|
||||
[[nodiscard]] std::chrono::milliseconds position() const
|
||||
{
|
||||
return clock_.position();
|
||||
}
|
||||
[[nodiscard]] std::optional<Api::QueueEntry> currentEntry() const;
|
||||
[[nodiscard]] std::chrono::milliseconds currentDuration() const;
|
||||
|
||||
private:
|
||||
|
||||
// ---- mailbox ---------------------------------------------------
|
||||
|
||||
struct CmdPlayNow {
|
||||
Api::QueueEntry entry;
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
};
|
||||
struct CmdStart {
|
||||
};
|
||||
struct CmdPause {
|
||||
};
|
||||
struct CmdResume {
|
||||
};
|
||||
struct CmdStop {
|
||||
};
|
||||
struct CmdSkip {
|
||||
uint32_t count = 1;
|
||||
};
|
||||
struct CmdSeek {
|
||||
std::chrono::milliseconds position;
|
||||
};
|
||||
struct CmdRestore {
|
||||
Api::QueueEntry entry;
|
||||
std::string url;
|
||||
std::chrono::milliseconds position;
|
||||
bool paused = false;
|
||||
};
|
||||
using Command =
|
||||
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume, CmdStop,
|
||||
CmdSkip, CmdSeek, CmdRestore>;
|
||||
|
||||
void post(Command cmd);
|
||||
|
||||
// ---- decoder slots --------------------------------------------
|
||||
|
||||
struct ResolvedStream {
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
};
|
||||
|
||||
struct DecoderSlot {
|
||||
enum class State {
|
||||
Idle, // nothing assigned
|
||||
Resolving, // resolveFuture in flight
|
||||
Warming, // decoder open, pre-filling its queue
|
||||
Active, // currently feeding the ring buffer
|
||||
};
|
||||
|
||||
State state = State::Idle;
|
||||
std::unique_ptr<AudioDecoder> decoder;
|
||||
std::optional<Api::QueueEntry> entry;
|
||||
std::future<Api::Result<std::string>> resolveFuture;
|
||||
std::chrono::steady_clock::time_point resolveStartedAt{};
|
||||
std::string openUrl;
|
||||
bool isLocalFile = false;
|
||||
// Whether the download-to-file fallback was already tried
|
||||
// for this entry (bounds the retry to one attempt).
|
||||
bool triedDownload = false;
|
||||
|
||||
void closeAndReset()
|
||||
{
|
||||
if (decoder) {
|
||||
decoder->closeSource();
|
||||
}
|
||||
state = State::Idle;
|
||||
entry.reset();
|
||||
resolveFuture = {};
|
||||
openUrl.clear();
|
||||
isLocalFile = false;
|
||||
triedDownload = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Kick off an async download-to-file retry for the slot's entry
|
||||
// (preferDownload=true). Returns false when no retry is possible
|
||||
// (already tried, or no entry).
|
||||
bool retryViaDownload(DecoderSlot& slot);
|
||||
|
||||
// ---- engine thread --------------------------------------------
|
||||
|
||||
void run(std::stop_token st);
|
||||
void drainMailbox();
|
||||
void handle(CmdPlayNow&& cmd);
|
||||
void handle(CmdStart&&);
|
||||
void handle(CmdPause&&);
|
||||
void handle(CmdResume&&);
|
||||
void handle(CmdStop&&);
|
||||
void handle(CmdSkip&& cmd);
|
||||
void handle(CmdSeek&& cmd);
|
||||
void handle(CmdRestore&& cmd);
|
||||
|
||||
// Try to begin playing the next queued track in the current slot
|
||||
// (used when idle). Returns true when a track started resolving
|
||||
// or playing.
|
||||
bool beginNextFromQueue();
|
||||
|
||||
// Kick off async resolution of the upcoming track into next_.
|
||||
void maybeStartPrefetch();
|
||||
// Move a finished resolve into an open, warming decoder.
|
||||
void pollNextResolve();
|
||||
// Current track hit EOF and drained: hand off or advance.
|
||||
void handleTrackEnd();
|
||||
// Crossfade: drain the current track's tail and swap to the warm
|
||||
// slot early so emitChunk can mix the two.
|
||||
void beginCrossfade();
|
||||
void clearFade()
|
||||
{
|
||||
fadeTail_.clear();
|
||||
fadeTailPos_ = 0;
|
||||
fadeEnvPos_ = 0;
|
||||
fadeIncomingStarved_ = false;
|
||||
}
|
||||
// AGC gain for one chunk (updates the internal RMS/gain state).
|
||||
[[nodiscard]] float agcGainFor(std::size_t samples);
|
||||
// Open `slot`'s decoder for `url`; false on failure.
|
||||
bool openSlot(DecoderSlot& slot, const std::string& url,
|
||||
bool isLocalFile);
|
||||
void activateSlot(DecoderSlot& slot,
|
||||
std::chrono::milliseconds startAt =
|
||||
std::chrono::milliseconds(0));
|
||||
void publishCurrent(const std::optional<Api::QueueEntry>& entry);
|
||||
void emitChunk(bool fromRing);
|
||||
void positionTick();
|
||||
|
||||
IPlaybackHost& host_;
|
||||
|
||||
// Mailbox
|
||||
std::mutex mailboxMutex_;
|
||||
std::deque<Command> mailbox_;
|
||||
std::condition_variable mailboxCv_;
|
||||
|
||||
// Engine-thread-only state
|
||||
DecoderSlot current_;
|
||||
DecoderSlot next_;
|
||||
AudioRingBuffer ring_;
|
||||
std::vector<short> outChunk_;
|
||||
std::vector<int16_t> incomingChunk_;
|
||||
std::chrono::steady_clock::time_point nextTick_{};
|
||||
std::chrono::steady_clock::time_point lastPositionTick_{};
|
||||
std::chrono::steady_clock::time_point silenceSince_{};
|
||||
int consecutiveFailures_ = 0;
|
||||
|
||||
// Crossfade state (engine thread only): the outgoing track's
|
||||
// remaining PCM, mixed into the incoming track equal-power.
|
||||
// The tail cursor and the envelope advance independently: the
|
||||
// tail plays continuously, while the envelope only progresses as
|
||||
// incoming audio is actually delivered — so a network-starved
|
||||
// incoming stream stretches the fade instead of being chopped
|
||||
// against a racing envelope.
|
||||
std::vector<short> fadeTail_;
|
||||
std::size_t fadeTailPos_ = 0;
|
||||
std::size_t fadeEnvPos_ = 0;
|
||||
bool fadeIncomingStarved_ = false;
|
||||
|
||||
// AGC state (engine thread only): EMA of mean-square level and
|
||||
// the current smoothed gain in dB.
|
||||
double agcMeanSquare_ = 0.0;
|
||||
float agcGainDb_ = 0.0f;
|
||||
|
||||
// Published state
|
||||
std::atomic<bool> playing_{false};
|
||||
std::atomic<bool> paused_{false};
|
||||
std::atomic<float> volume_{0.5f};
|
||||
std::atomic<int64_t> resolveGraceMs_{10000};
|
||||
std::atomic<int64_t> crossfadeMs_{0};
|
||||
std::atomic<bool> normalizeEnabled_{false};
|
||||
std::atomic<float> normalizeTargetDb_{-14.0f};
|
||||
PositionClock clock_;
|
||||
mutable std::mutex currentEntryMutex_;
|
||||
std::optional<Api::QueueEntry> publishedEntry_;
|
||||
std::atomic<int64_t> currentDurationMs_{0};
|
||||
|
||||
std::optional<Void::Net::ProxyConfig> proxy_;
|
||||
std::jthread thread_;
|
||||
std::atomic<bool> initialized_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Wall-clock based playback position. Replaces the playbackPosition_ /
|
||||
// playbackBasePosition_ / playbackStartTime_ triple whose reset logic was
|
||||
// duplicated across play/resume/skip/seek/track-finished/restore.
|
||||
//
|
||||
// Lock-free: the engine thread writes, any thread reads a consistent
|
||||
// position (worst case one field is a few ns stale, irrelevant at ms
|
||||
// granularity for UI display).
|
||||
class PositionClock
|
||||
{
|
||||
public:
|
||||
|
||||
using ms = std::chrono::milliseconds;
|
||||
|
||||
// Track started from zero (or restarted); clock runs.
|
||||
void restart()
|
||||
{
|
||||
seekTo(ms{0});
|
||||
running_.store(true);
|
||||
}
|
||||
|
||||
// Jump to a position and keep running/paused state.
|
||||
void seekTo(ms position)
|
||||
{
|
||||
baseMs_.store(position.count());
|
||||
startedAtNs_.store(nowNs());
|
||||
}
|
||||
|
||||
void pause()
|
||||
{
|
||||
if (!running_.exchange(false)) {
|
||||
return;
|
||||
}
|
||||
baseMs_.store(currentMs());
|
||||
}
|
||||
|
||||
void resume()
|
||||
{
|
||||
if (running_.load()) {
|
||||
return; // already running; resetting startedAt would
|
||||
// rewind the position
|
||||
}
|
||||
startedAtNs_.store(nowNs());
|
||||
running_.store(true);
|
||||
}
|
||||
|
||||
void stop()
|
||||
{
|
||||
running_.store(false);
|
||||
baseMs_.store(0);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool running() const { return running_.load(); }
|
||||
|
||||
[[nodiscard]] ms position() const { return ms{currentMs()}; }
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] static int64_t nowNs()
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] int64_t currentMs() const
|
||||
{
|
||||
const int64_t base = baseMs_.load();
|
||||
if (!running_.load()) {
|
||||
return base;
|
||||
}
|
||||
const int64_t elapsedNs = nowNs() - startedAtNs_.load();
|
||||
return base + elapsedNs / 1'000'000;
|
||||
}
|
||||
|
||||
std::atomic<int64_t> baseMs_{0};
|
||||
std::atomic<int64_t> startedAtNs_{0};
|
||||
std::atomic<bool> running_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Owns the playback queue, shuffle order and repeat flag. Self-locking:
|
||||
// every public method takes the internal mutex, so callers never manage
|
||||
// queue locks (the old QueueManager exposed raw references and relied on
|
||||
// MusicManager's shared_mutex, which several writers acquired shared).
|
||||
//
|
||||
// Shuffle model: shuffledIndices_ is a permutation of positions into
|
||||
// entries_; shuffleIndex_ is the cursor of the next shuffled pick.
|
||||
// Removing/moving/adding entries fixes the permutation up in place, so
|
||||
// already-played order is preserved.
|
||||
class QueueService
|
||||
{
|
||||
public:
|
||||
|
||||
using Entry = Api::QueueEntry;
|
||||
|
||||
// ---- mutation -------------------------------------------------
|
||||
|
||||
// Appends a track. Fails when the queue is at maxSize.
|
||||
Api::Result<uint64_t> enqueue(const Api::TrackInfo& track,
|
||||
std::string addedBy,
|
||||
std::size_t maxSize);
|
||||
|
||||
// Removes the entry at `position`; returns it for event payloads.
|
||||
Api::Result<Entry> removeAt(uint32_t position);
|
||||
|
||||
// Returns the number of entries removed.
|
||||
uint32_t clear();
|
||||
|
||||
// Moves an entry; returns its queueId for event payloads.
|
||||
Api::Result<uint64_t> move(uint32_t from, uint32_t to);
|
||||
|
||||
// Pops the next entry honouring shuffle order.
|
||||
std::optional<Entry> popNext();
|
||||
|
||||
// Pops the next entry only if it is still the given one — the
|
||||
// gapless engine peeks, warms a decoder, and commits at the swap;
|
||||
// queue edits in between invalidate the warm slot.
|
||||
std::optional<Entry> popIfNext(uint64_t queueId);
|
||||
|
||||
// Replace the whole queue (hot-reload restore).
|
||||
void replaceAll(std::vector<Entry> entries);
|
||||
|
||||
// In-place random shuffle of the raw order (legacy !shufflequeue).
|
||||
void shuffleInPlace();
|
||||
|
||||
// ---- shuffle / repeat -----------------------------------------
|
||||
|
||||
bool toggleShuffle();
|
||||
void setShuffle(bool enabled);
|
||||
[[nodiscard]] bool shuffleEnabled() const;
|
||||
|
||||
bool toggleRepeat();
|
||||
void setRepeat(bool enabled);
|
||||
[[nodiscard]] bool repeatEnabled() const;
|
||||
|
||||
// ---- inspection -----------------------------------------------
|
||||
|
||||
[[nodiscard]] std::optional<Entry> peekNext() const;
|
||||
[[nodiscard]] std::vector<Entry> snapshot() const;
|
||||
[[nodiscard]] std::size_t size() const;
|
||||
[[nodiscard]] bool empty() const;
|
||||
|
||||
// Allocate a queue id for entries created outside the queue (the
|
||||
// immediately-played track in play()).
|
||||
[[nodiscard]] uint64_t allocateQueueId();
|
||||
|
||||
private:
|
||||
|
||||
// All *Locked helpers assume mutex_ is held.
|
||||
void rebuildShuffledIndicesLocked();
|
||||
[[nodiscard]] std::optional<std::size_t> nextPositionLocked() const;
|
||||
std::optional<Entry> popNextLocked();
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<Entry> entries_;
|
||||
std::vector<std::size_t> shuffledIndices_;
|
||||
std::size_t shuffleIndex_ = 0;
|
||||
uint64_t nextQueueId_ = 1;
|
||||
bool shuffle_ = false;
|
||||
bool repeat_ = false;
|
||||
std::mt19937 rng_{std::random_device{}()};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackSource.hpp"
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Pass-through for URLs that already point at an audio stream (radio
|
||||
// streams, .mp3/.ogg/.opus/.m3u8 files, icecast mounts). No network work
|
||||
// at resolve time — ffmpeg opens the URL directly.
|
||||
class DirectUrlSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "direct-url";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override { return true; }
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,86 @@
|
||||
#pragma once
|
||||
|
||||
#include "../NetworkClient.hpp"
|
||||
#include "../SignatureCipher.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Native YouTube resolution through the innertube player API — one HTTP
|
||||
// POST instead of a yt-dlp subprocess, so it is by far the fastest
|
||||
// YouTube path. Requests go through the configured proxy (NetworkClient
|
||||
// applies it); youtubei is ISP-blocked here, so with requireProxy=true
|
||||
// (default) the source reports unavailable when no proxy is set and the
|
||||
// router skips it.
|
||||
//
|
||||
// Client strategy: the IOS client historically returns direct
|
||||
// adaptiveFormats[].url with no signature deciphering. When it yields
|
||||
// nothing playable, the WEB client + SignatureCipher (quickjs solver)
|
||||
// deciphers signatureCipher/n-param challenges.
|
||||
class InnertubeSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
// endpointOverride points tests at a StubHttpServer; production
|
||||
// passes nothing and talks to https://www.youtube.com.
|
||||
explicit InnertubeSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride = "");
|
||||
|
||||
void configure(bool enabled, bool requireProxy);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "innertube";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false; // text search runs through the yt-dlp sources
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
private:
|
||||
|
||||
struct PlayerResponse {
|
||||
std::string title;
|
||||
std::string author;
|
||||
int64_t lengthSeconds = 0;
|
||||
std::string thumbnailUrl;
|
||||
std::string streamUrl; // direct url when present
|
||||
std::string signatureCipher; // needs deciphering
|
||||
};
|
||||
|
||||
// POST youtubei/v1/player with the given client context; parses
|
||||
// the best audio format out of the response.
|
||||
Api::Result<PlayerResponse> callPlayer(const std::string& videoId,
|
||||
bool webClient);
|
||||
|
||||
// WEB fallback: fetch the watch page + player JS, feed the
|
||||
// cipher, decipher the signatureCipher/n-param challenge.
|
||||
Api::Result<std::string>
|
||||
decipherWithWebPlayer(const std::string& videoId,
|
||||
const std::string& signatureCipher);
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::string endpoint_;
|
||||
std::atomic<bool> enabled_{true};
|
||||
std::atomic<bool> requireProxy_{true};
|
||||
|
||||
// Lazy cipher state (only the WEB fallback needs it).
|
||||
std::mutex cipherMutex_;
|
||||
std::unique_ptr<SignatureCipher> cipher_;
|
||||
std::string loadedPlayerJsUrl_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,75 @@
|
||||
#pragma once
|
||||
|
||||
#include "TrackSource.hpp"
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Ordered chain of track sources with per-source failure cooldown and a
|
||||
// stream-URL cache. Resolution walks the configured order and takes the
|
||||
// first source that canHandle() the query, is available, and succeeds;
|
||||
// failures put a source on cooldown (skipped unless it is the last
|
||||
// candidate) and fall through to the next.
|
||||
class SourceRouter
|
||||
{
|
||||
public:
|
||||
|
||||
void setSources(std::vector<std::shared_ptr<ITrackSource>> sources);
|
||||
void addSource(std::shared_ptr<ITrackSource> source);
|
||||
|
||||
// Reorder/enable per config; names not found are ignored, sources
|
||||
// not named are dropped from the chain.
|
||||
void setOrder(const std::vector<std::string>& order);
|
||||
void setFailureCooldown(std::chrono::milliseconds cooldown);
|
||||
// Hedged getStream: when the first candidate hasn't answered
|
||||
// within this delay, race the second one (first success wins).
|
||||
// 0 disables hedging.
|
||||
void setHedgeDelay(std::chrono::milliseconds delay);
|
||||
|
||||
// Text search across the first searching source that succeeds.
|
||||
[[nodiscard]] Api::Result<Api::SearchResult>
|
||||
search(std::string_view query);
|
||||
|
||||
// URL/id/text -> track metadata.
|
||||
[[nodiscard]] Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& query);
|
||||
|
||||
// Track -> playable stream handle (cached).
|
||||
[[nodiscard]] Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track);
|
||||
|
||||
// A cached/served handle failed to open: evict it and demote the
|
||||
// producing source so the next resolve tries elsewhere.
|
||||
void invalidate(const std::string& trackId);
|
||||
|
||||
private:
|
||||
|
||||
struct CachedStream {
|
||||
StreamHandle handle;
|
||||
std::chrono::steady_clock::time_point expiry;
|
||||
};
|
||||
|
||||
struct SourceState {
|
||||
std::shared_ptr<ITrackSource> source;
|
||||
std::chrono::steady_clock::time_point cooldownUntil{};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::vector<std::shared_ptr<ITrackSource>>
|
||||
candidatesFor(const std::string& query, bool needSearch);
|
||||
void reportFailure(const std::shared_ptr<ITrackSource>& source);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<std::shared_ptr<ITrackSource>> allSources_;
|
||||
std::vector<SourceState> chain_;
|
||||
std::chrono::milliseconds cooldown_{std::chrono::minutes(5)};
|
||||
std::chrono::milliseconds hedgeDelay_{std::chrono::milliseconds(300)};
|
||||
std::unordered_map<std::string, CachedStream> streamCache_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <TrackTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// A playable handle produced by a source: either an http(s) URL the
|
||||
// decoder can stream, or a local file path (downloaded audio) the caller
|
||||
// must delete after playback.
|
||||
struct StreamHandle {
|
||||
std::string url;
|
||||
bool isLocalFile = false;
|
||||
std::string sourceName; // for logging / failure attribution
|
||||
};
|
||||
|
||||
// One catalog/stream backend in the resolution chain. Implementations:
|
||||
// InnertubeSource (native YouTube player API), YandexMusicSource (native
|
||||
// Yandex Music), DirectUrlSource (raw audio URLs), YtDlpSource (direct
|
||||
// and proxied yt-dlp).
|
||||
class ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~ITrackSource() = default;
|
||||
|
||||
[[nodiscard]] virtual std::string_view name() const = 0;
|
||||
|
||||
// Can this source resolve the query at all? URLs are matched by
|
||||
// host/scheme; bare text search is handled only by
|
||||
// YouTube-catalog sources.
|
||||
[[nodiscard]] virtual bool
|
||||
canHandle(const std::string& query) const = 0;
|
||||
|
||||
// Health gate — sources with no healthy instances report false
|
||||
// and are skipped by the router.
|
||||
[[nodiscard]] virtual bool isAvailable() const = 0;
|
||||
|
||||
// Does this source implement text search?
|
||||
[[nodiscard]] virtual bool supportsSearch() const = 0;
|
||||
|
||||
virtual Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) = 0;
|
||||
|
||||
// Resolve metadata for a URL or id this source canHandle().
|
||||
virtual Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) = 0;
|
||||
|
||||
// Produce a playable handle for a resolved track.
|
||||
virtual Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
|
||||
#include "../NetworkClient.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// Native Yandex Music source (unofficial api.music.yandex.net). Full
|
||||
// tracks require a Yandex OAuth token (sources.yandexToken) from an
|
||||
// account with Plus; without one this source reports unavailable and
|
||||
// yandex URLs keep routing to ytdlp-direct.
|
||||
//
|
||||
// Yandex is reachable directly in this deployment's region and may
|
||||
// geo-block foreign proxy exits, so every request deliberately bypasses
|
||||
// the configured proxy (NetworkClient::getDirect).
|
||||
class YandexMusicSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
// endpointOverride points tests at a StubHttpServer (it replaces
|
||||
// both the API base and the download-info hosts).
|
||||
explicit YandexMusicSource(std::shared_ptr<NetworkClient> network,
|
||||
std::string endpointOverride = "");
|
||||
|
||||
void configure(bool enabled, std::string token);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return "yandex";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
// Album/playlist track listing for queue imports.
|
||||
[[nodiscard]] bool isCollectionUrl(const std::string& url) const;
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
playlistTracks(const std::string& url);
|
||||
|
||||
// Related/similar tracks for radio autoplay. trackId is the bare
|
||||
// Yandex numeric id (no "yandex:" prefix).
|
||||
Api::Result<std::vector<Api::TrackInfo>>
|
||||
related(const std::string& trackId, size_t limit = 10);
|
||||
|
||||
// Extract the bare Yandex track id from a music.yandex.* URL, if it
|
||||
// is a single-track URL. Used to seed radio from history.
|
||||
[[nodiscard]] std::optional<std::string>
|
||||
trackIdFromUrl(const std::string& url) const;
|
||||
|
||||
private:
|
||||
|
||||
Api::Result<std::string> apiGet(const std::string& path);
|
||||
[[nodiscard]] std::string tokenSnapshot() const;
|
||||
|
||||
std::shared_ptr<NetworkClient> network_;
|
||||
std::string endpoint_;
|
||||
std::atomic<bool> enabled_{true};
|
||||
mutable std::mutex tokenMutex_;
|
||||
std::string token_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "../YouTubeClient.hpp"
|
||||
#include "TrackSource.hpp"
|
||||
#include <memory>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
// yt-dlp-backed source, in two router entries over the same
|
||||
// YouTubeClient:
|
||||
// - Direct ("ytdlp-direct", useProxy=false): non-YouTube extractor URLs
|
||||
// (SoundCloud, Bandcamp, VK, Yandex, radio pages) reachable without a
|
||||
// proxy. Never handles bare text search.
|
||||
// - Proxied ("ytdlp-proxied", useProxy=true): last-resort YouTube
|
||||
// resolution + text search through the configured proxy; also owns
|
||||
// the SOCKS5 download-to-file path.
|
||||
class YtDlpSource : public ITrackSource
|
||||
{
|
||||
public:
|
||||
|
||||
enum class Mode { Direct, Proxied };
|
||||
|
||||
YtDlpSource(std::shared_ptr<YouTubeClient> client, Mode mode,
|
||||
std::string tempDir);
|
||||
|
||||
[[nodiscard]] std::string_view name() const override
|
||||
{
|
||||
return mode_ == Mode::Direct ? "ytdlp-direct"
|
||||
: "ytdlp-proxied";
|
||||
}
|
||||
[[nodiscard]] bool canHandle(const std::string& query) const override;
|
||||
[[nodiscard]] bool isAvailable() const override;
|
||||
[[nodiscard]] bool supportsSearch() const override
|
||||
{
|
||||
return mode_ == Mode::Proxied;
|
||||
}
|
||||
|
||||
Api::Result<Api::SearchResult>
|
||||
search(std::string_view query) override;
|
||||
Api::Result<Api::TrackInfo>
|
||||
resolve(const std::string& urlOrId) override;
|
||||
Api::Result<StreamHandle>
|
||||
getStream(const Api::TrackInfo& track) override;
|
||||
|
||||
// Force the download-to-file path on the next getStream (set by
|
||||
// the router's preferDownload retry).
|
||||
Api::Result<StreamHandle>
|
||||
getStreamViaDownload(const Api::TrackInfo& track);
|
||||
|
||||
private:
|
||||
|
||||
std::shared_ptr<YouTubeClient> client_;
|
||||
Mode mode_;
|
||||
std::string tempDir_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
#include "TrackTypes.hpp"
|
||||
#include "RpcTypes.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
@@ -45,12 +46,20 @@ namespace Echoion::Core
|
||||
std::string lastActivity; // ISO 8601
|
||||
};
|
||||
|
||||
struct ExtensionPluginState {
|
||||
std::string name;
|
||||
std::string json;
|
||||
std::uint32_t version = 0;
|
||||
};
|
||||
|
||||
// Main state
|
||||
PlaybackState playback;
|
||||
bool hasPlayback =
|
||||
false; // Flag to indicate if playback state is valid
|
||||
bool autoplay = false; // Radio mode on/off (persisted for restart)
|
||||
std::vector<QueueEntryState> queue;
|
||||
std::vector<SessionState> sessions;
|
||||
std::vector<ExtensionPluginState> extensionPlugins;
|
||||
|
||||
// Version info
|
||||
uint32_t version = 1;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core::Util
|
||||
{
|
||||
|
||||
// Split `text` into pages no larger than `limit` bytes each, breaking on
|
||||
// line boundaries where possible and hard-splitting over-long lines on a
|
||||
// UTF-8 code-point boundary. Every returned page is <= `limit` bytes, so a
|
||||
// caller can append a short footer and still stay under the transport's
|
||||
// single-message cap. Returns a single element when `text` already fits.
|
||||
std::vector<std::string> paginate(std::string_view text, std::size_t limit);
|
||||
|
||||
} // namespace Echoion::Core::Util
|
||||
+309
-341
@@ -1,10 +1,9 @@
|
||||
#include "LoggerInterface.hpp"
|
||||
#include "echoion/core/AudioDecoder.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/dict.h>
|
||||
#include <libavutil/hwcontext.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libavutil/samplefmt.h>
|
||||
#include <libswresample/swresample.h>
|
||||
@@ -23,73 +22,19 @@ namespace Echoion::Core
|
||||
{
|
||||
shutdown();
|
||||
cleanupFfmpeg();
|
||||
cleanupHardwareAccel();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
AudioDecoder::initialize(const Api::HwAccelConfig& hwConfig)
|
||||
Api::Result<void> AudioDecoder::initialize()
|
||||
{
|
||||
if (initialized_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (zeroCopyEnabled_) {
|
||||
Api::AudioBufferPool::instance().initialize(
|
||||
outputSampleRate_ / 50 * outputChannels_, 256);
|
||||
}
|
||||
|
||||
if (hwConfig.isEnabled()) {
|
||||
auto result = initializeHardwareAccel(hwConfig);
|
||||
if (!result) {
|
||||
ECHOION_LOG_WARNING(
|
||||
std::format("Hardware acceleration init failed: {}, "
|
||||
"falling back to software",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
av_log_set_level(AV_LOG_DEBUG);
|
||||
// Errors only: AV_LOG_DEBUG makes FFmpeg log every packet, which is
|
||||
// both noisy and measurably slow on the decode thread.
|
||||
av_log_set_level(AV_LOG_ERROR);
|
||||
initialized_ = true;
|
||||
ECHOION_LOG_INFO("AudioDecoder initialized");
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
AudioDecoder::initializeHardwareAccel(const Api::HwAccelConfig& config)
|
||||
{
|
||||
enum AVHWDeviceType hwType = AV_HWDEVICE_TYPE_NONE;
|
||||
|
||||
switch (config.type) {
|
||||
case Api::HwAccelType::CUDA:
|
||||
hwType = AV_HWDEVICE_TYPE_CUDA;
|
||||
break;
|
||||
case Api::HwAccelType::VAAPI:
|
||||
hwType = AV_HWDEVICE_TYPE_VAAPI;
|
||||
break;
|
||||
case Api::HwAccelType::DXVA2:
|
||||
hwType = AV_HWDEVICE_TYPE_DXVA2;
|
||||
break;
|
||||
case Api::HwAccelType::D3D11VA:
|
||||
hwType = AV_HWDEVICE_TYPE_D3D11VA;
|
||||
break;
|
||||
case Api::HwAccelType::VideoToolbox:
|
||||
hwType = AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
|
||||
break;
|
||||
default:
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Unsupported hardware acceleration type");
|
||||
}
|
||||
|
||||
if (av_hwdevice_find_type_by_name(av_hwdevice_get_type_name(hwType)) ==
|
||||
AV_HWDEVICE_TYPE_NONE) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotSupported,
|
||||
"Hardware acceleration not available on this system");
|
||||
}
|
||||
|
||||
hwAccelType_ = config.type;
|
||||
ECHOION_LOG_INFO(std::format("Hardware acceleration configured: {}",
|
||||
av_hwdevice_get_type_name(hwType)));
|
||||
|
||||
Void::Log::info("AudioDecoder", "{}", "AudioDecoder initialized");
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -107,27 +52,20 @@ namespace Echoion::Core
|
||||
initialized_ = false;
|
||||
}
|
||||
|
||||
void AudioDecoder::cleanupHardwareAccel()
|
||||
{
|
||||
if (hwFramesContext_) {
|
||||
av_buffer_unref(&hwFramesContext_);
|
||||
}
|
||||
if (hwDeviceContext_) {
|
||||
av_buffer_unref(&hwDeviceContext_);
|
||||
}
|
||||
hwAccelEnabled_ = false;
|
||||
}
|
||||
|
||||
Api::Result<void> AudioDecoder::openSource(const std::string& url)
|
||||
{
|
||||
if (!initialized_) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ServiceUnavailable, "Decoder not initialized");
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"Decoder not initialized");
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
// Close the previous source BEFORE taking mutex_: closeSource()
|
||||
// joins the decode thread, and that thread may be parked in a
|
||||
// cv_.wait on mutex_ (backpressure or EOF park) — it needs the
|
||||
// mutex to wake up and exit, so joining while holding it deadlocks.
|
||||
closeSource();
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
currentUrl_ = url;
|
||||
AVDictionary* options = nullptr;
|
||||
|
||||
@@ -149,25 +87,31 @@ namespace Echoion::Core
|
||||
av_dict_set(&options, "reconnect", "1", 0);
|
||||
av_dict_set(&options, "reconnect_streamed", "1", 0);
|
||||
av_dict_set(&options, "reconnect_delay_max", "5", 0);
|
||||
av_dict_set(&options, "analyzeduration", "20000000", 0);
|
||||
av_dict_set(&options, "probesize", "10240000", 0);
|
||||
// Keep the open cheap: find_stream_info reads min(analyzeduration,
|
||||
// EOF) of media before returning, and openSource runs on the
|
||||
// engine thread — large values froze playback for seconds when a
|
||||
// proxied stream was opened for prefetch. Every source the bot
|
||||
// plays (webm/opus, m4a, mp3, wav) carries codec parameters in its
|
||||
// header, so 1s of analysis is plenty.
|
||||
av_dict_set(&options, "analyzeduration", "1000000", 0);
|
||||
av_dict_set(&options, "probesize", "1048576", 0);
|
||||
|
||||
if (proxyConfig_.has_value() && proxyConfig_->enabled()) {
|
||||
std::string proxyUrl;
|
||||
if ((proxyConfig_->kind == Void::Net::ProxyConfig::Kind::Socks5)) {
|
||||
// Use standard socks5:// scheme. FFmpeg http protocol handles
|
||||
// this correctly. socks5h:// is often rejected by the http
|
||||
// protocol handler, causing proxy bypass.
|
||||
if (proxyConfig_->has_auth()) {
|
||||
proxyUrl = std::format(
|
||||
"socks5://{}:{}@{}:{}", *proxyConfig_->username,
|
||||
*proxyConfig_->password, proxyConfig_->host,
|
||||
proxyConfig_->port);
|
||||
} else {
|
||||
proxyUrl = std::format("socks5://{}:{}", proxyConfig_->host,
|
||||
proxyConfig_->port);
|
||||
}
|
||||
if (proxyConfig_->kind == Void::Net::ProxyConfig::Kind::Socks5) {
|
||||
// FFmpeg has no SOCKS5 support (its http protocol only knows
|
||||
// http_proxy / HTTP CONNECT). MusicManager rewrites SOCKS5
|
||||
// configs to the local Socks5HttpBridge before they reach the
|
||||
// decoder; anything still arriving here would be silently
|
||||
// ignored by FFmpeg, so skip it loudly instead.
|
||||
Void::Log::warn(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("SOCKS5 proxy {}:{} not usable by FFmpeg; "
|
||||
"connecting directly",
|
||||
proxyConfig_->host, proxyConfig_->port));
|
||||
} else {
|
||||
// The option is named http_proxy; FFmpeg drops unknown dict
|
||||
// keys silently, so a wrong name means a direct connection.
|
||||
std::string proxyUrl;
|
||||
if (proxyConfig_->has_auth()) {
|
||||
proxyUrl = std::format(
|
||||
"http://{}:{}@{}:{}", *proxyConfig_->username,
|
||||
@@ -177,22 +121,25 @@ namespace Echoion::Core
|
||||
proxyUrl = std::format("http://{}:{}", proxyConfig_->host,
|
||||
proxyConfig_->port);
|
||||
}
|
||||
av_dict_set(&options, "http_proxy", proxyUrl.c_str(), 0);
|
||||
Void::Log::info("AudioDecoder", "{}",
|
||||
std::format("Using proxy for ffmpeg: {}:{}",
|
||||
proxyConfig_->host,
|
||||
proxyConfig_->port));
|
||||
}
|
||||
|
||||
av_dict_set(&options, "proxy", proxyUrl.c_str(), 0);
|
||||
ECHOION_LOG_INFO(std::format("Using proxy for ffmpeg: {}:{}",
|
||||
proxyConfig_->host,
|
||||
proxyConfig_->port));
|
||||
}
|
||||
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("Opening audio source: {}", url.substr(0, 80)));
|
||||
// Log the URL truncated (googlevideo URLs run to ~1 KB); the "…"
|
||||
// makes clear the full URL is what actually reaches FFmpeg.
|
||||
Void::Log::debug(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("Opening audio source: {}…", url.substr(0, 80)));
|
||||
|
||||
// Allocate format context first (needed for interrupt callback)
|
||||
formatContext_ = avformat_alloc_context();
|
||||
if (!formatContext_) {
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"Failed to allocate format context");
|
||||
"Failed to allocate format context");
|
||||
}
|
||||
|
||||
// Set up interrupt callback to allow graceful shutdown during blocking
|
||||
@@ -214,21 +161,24 @@ namespace Echoion::Core
|
||||
if (ret < 0) {
|
||||
char errbuf[256];
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"FFmpeg failed to open input (error {}): {}", ret, errbuf));
|
||||
Void::Log::error(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("FFmpeg failed to open input (error {}): {}", ret,
|
||||
errbuf));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::AudioError,
|
||||
std::format(
|
||||
"Failed to open audio source: {} (FFmpeg error {}: {})",
|
||||
"Failed to open audio source: {}… (FFmpeg error {}: {})",
|
||||
url.substr(0, 80), ret, errbuf));
|
||||
}
|
||||
ECHOION_LOG_DEBUG("avformat_open_input succeeded");
|
||||
Void::Log::debug("AudioDecoder", "{}", "avformat_open_input succeeded");
|
||||
|
||||
ret = avformat_find_stream_info(formatContext_, nullptr);
|
||||
if (ret < 0) {
|
||||
char errbuf[256];
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("FFmpeg failed to find stream info (error {}): {}",
|
||||
ret, errbuf));
|
||||
avformat_close_input(&formatContext_);
|
||||
@@ -245,14 +195,14 @@ namespace Echoion::Core
|
||||
if (audioStreamIndex_ == -1) {
|
||||
avformat_close_input(&formatContext_);
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"No audio stream found");
|
||||
"No audio stream found");
|
||||
}
|
||||
|
||||
codecContext_ = avcodec_alloc_context3(decoder);
|
||||
if (!codecContext_) {
|
||||
avformat_close_input(&formatContext_);
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"Failed to allocate codec context");
|
||||
"Failed to allocate codec context");
|
||||
}
|
||||
codecContext_->thread_count = 0; // Auto-detect CPU cores
|
||||
codecContext_->thread_type = FF_THREAD_FRAME | FF_THREAD_SLICE;
|
||||
@@ -262,15 +212,16 @@ namespace Echoion::Core
|
||||
if (ret < 0) {
|
||||
avcodec_free_context(&codecContext_);
|
||||
avformat_close_input(&formatContext_);
|
||||
return Api::fail(
|
||||
Api::ErrorCode::AudioError, "Failed to copy codec parameters");
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"Failed to copy codec parameters");
|
||||
}
|
||||
|
||||
ret = avcodec_open2(codecContext_, decoder, nullptr);
|
||||
if (ret < 0) {
|
||||
avcodec_free_context(&codecContext_);
|
||||
avformat_close_input(&formatContext_);
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Failed to open codec");
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"Failed to open codec");
|
||||
}
|
||||
|
||||
frame_ = av_frame_alloc();
|
||||
@@ -278,46 +229,50 @@ namespace Echoion::Core
|
||||
|
||||
if (!frame_ || !packet_) {
|
||||
cleanupFfmpeg();
|
||||
return Api::fail(
|
||||
Api::ErrorCode::AudioError, "Failed to allocate frame/packet");
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"Failed to allocate frame/packet");
|
||||
}
|
||||
|
||||
streamInfo_.sampleRate = codecContext_->sample_rate;
|
||||
streamInfo_.channels = codecContext_->ch_layout.nb_channels;
|
||||
streamInfo_.bitrate = static_cast<uint32_t>(codecContext_->bit_rate);
|
||||
streamInfo_.hwAccelerated = hwAccelEnabled_;
|
||||
streamInfo_.hwAccelType = hwAccelType_;
|
||||
{
|
||||
// streamInfo_ is read from other threads via getStreamInfo();
|
||||
// mutex_ is already held for the whole of openSource() (acquired
|
||||
// at the top), which is what makes these writes safe.
|
||||
streamInfo_.sampleRate = codecContext_->sample_rate;
|
||||
streamInfo_.channels = codecContext_->ch_layout.nb_channels;
|
||||
streamInfo_.bitrate =
|
||||
static_cast<uint32_t>(codecContext_->bit_rate);
|
||||
|
||||
if (formatContext_->duration != AV_NOPTS_VALUE) {
|
||||
streamInfo_.duration = std::chrono::milliseconds(
|
||||
formatContext_->duration * 1000 / AV_TIME_BASE);
|
||||
}
|
||||
|
||||
switch (codecContext_->codec_id) {
|
||||
case AV_CODEC_ID_MP3:
|
||||
streamInfo_.format = Api::AudioFormat::MP3;
|
||||
break;
|
||||
case AV_CODEC_ID_AAC:
|
||||
streamInfo_.format = Api::AudioFormat::AAC;
|
||||
break;
|
||||
case AV_CODEC_ID_OPUS:
|
||||
streamInfo_.format = Api::AudioFormat::Opus;
|
||||
break;
|
||||
case AV_CODEC_ID_VORBIS:
|
||||
streamInfo_.format = Api::AudioFormat::Vorbis;
|
||||
break;
|
||||
case AV_CODEC_ID_FLAC:
|
||||
streamInfo_.format = Api::AudioFormat::FLAC;
|
||||
break;
|
||||
default:
|
||||
streamInfo_.format = Api::AudioFormat::Unknown;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
streamSampleRate_ = static_cast<uint32_t>(
|
||||
codecContext_->sample_rate > 0 ? codecContext_->sample_rate
|
||||
: 48000);
|
||||
|
||||
if (formatContext_->duration != AV_NOPTS_VALUE) {
|
||||
streamInfo_.duration = std::chrono::milliseconds(
|
||||
formatContext_->duration * 1000 / AV_TIME_BASE);
|
||||
}
|
||||
|
||||
switch (codecContext_->codec_id) {
|
||||
case AV_CODEC_ID_MP3:
|
||||
streamInfo_.format = Api::AudioFormat::MP3;
|
||||
break;
|
||||
case AV_CODEC_ID_AAC:
|
||||
streamInfo_.format = Api::AudioFormat::AAC;
|
||||
break;
|
||||
case AV_CODEC_ID_OPUS:
|
||||
streamInfo_.format = Api::AudioFormat::Opus;
|
||||
break;
|
||||
case AV_CODEC_ID_VORBIS:
|
||||
streamInfo_.format = Api::AudioFormat::Vorbis;
|
||||
break;
|
||||
case AV_CODEC_ID_FLAC:
|
||||
streamInfo_.format = Api::AudioFormat::FLAC;
|
||||
break;
|
||||
default:
|
||||
streamInfo_.format = Api::AudioFormat::Unknown;
|
||||
break;
|
||||
}
|
||||
|
||||
// Setup resampler to output S16 (int16) like reference - avoids
|
||||
// float->int conversion
|
||||
AVChannelLayout outLayout;
|
||||
@@ -328,30 +283,32 @@ namespace Echoion::Core
|
||||
&swrContext_, &outLayout, AV_SAMPLE_FMT_S16,
|
||||
static_cast<int>(outputSampleRate_), &codecContext_->ch_layout,
|
||||
codecContext_->sample_fmt, codecContext_->sample_rate, 0, nullptr);
|
||||
if (codecContext_->sample_rate != outputSampleRate_) {
|
||||
if (codecContext_->sample_rate != static_cast<int>(outputSampleRate_)) {
|
||||
av_opt_set_int(swrContext_, "linear_interp", 1, 0);
|
||||
av_opt_set_int(swrContext_, "filter_size", 256, 0);
|
||||
}
|
||||
if (ret < 0 || swr_init(swrContext_) < 0) {
|
||||
cleanupFfmpeg();
|
||||
return Api::fail(
|
||||
Api::ErrorCode::AudioError, "Failed to initialize resampler");
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
"Failed to initialize resampler");
|
||||
}
|
||||
|
||||
// Allocate output buffer for S16 samples (like reference)
|
||||
constexpr int maxSamples = 4096;
|
||||
av_samples_alloc(&outputBuffer_, nullptr,
|
||||
static_cast<int>(outputChannels_), maxSamples,
|
||||
static_cast<int>(outputChannels_), MAX_OUT_SAMPLES,
|
||||
AV_SAMPLE_FMT_S16, 0);
|
||||
|
||||
decoding_ = true;
|
||||
shouldExit_ = false;
|
||||
seekRequestMs_ = -1;
|
||||
decodeThread_ = std::jthread(&AudioDecoder::decodeThread, this);
|
||||
|
||||
ECHOION_LOG_INFO(std::format(
|
||||
"Audio source opened: {} -> {} Hz, {} ch, in={} out=S16", url,
|
||||
outputSampleRate_, outputChannels_,
|
||||
av_get_sample_fmt_name(codecContext_->sample_fmt)));
|
||||
Void::Log::info(
|
||||
"AudioDecoder", "{}",
|
||||
std::format(
|
||||
"Audio source opened: {} -> {} Hz, {} ch, in={} out=S16", url,
|
||||
outputSampleRate_, outputChannels_,
|
||||
av_get_sample_fmt_name(codecContext_->sample_fmt)));
|
||||
|
||||
return {};
|
||||
}
|
||||
@@ -368,48 +325,17 @@ namespace Echoion::Core
|
||||
|
||||
cleanupFfmpeg();
|
||||
currentUrl_.clear();
|
||||
currentPosition_ = std::chrono::milliseconds(0);
|
||||
currentPositionMs_ = 0;
|
||||
eof_ = false;
|
||||
seekRequestMs_ = -1;
|
||||
shouldExit_ = false; // Reset for next use
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> AudioDecoder::decodeFrame()
|
||||
bool AudioDecoder::getNextChunk(std::vector<int16_t>& outChunk,
|
||||
bool blocking)
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
cv_.wait(lock, [this] {
|
||||
return !decodedQueue_.empty() || eof_ || !decoding_;
|
||||
});
|
||||
|
||||
if (!decodedQueue_.empty()) {
|
||||
auto audio = std::move(decodedQueue_.front());
|
||||
decodedQueue_.pop();
|
||||
cv_.notify_one();
|
||||
|
||||
std::lock_guard<std::mutex> statsLock(statsMutex_);
|
||||
stats_.framesDecoded++;
|
||||
|
||||
ECHOION_LOG_DEBUG(std::format("Frame consumed: {} samples, {} ms",
|
||||
audio.view.samplesPerChannel() * 2,
|
||||
audio.timestamp.count()));
|
||||
|
||||
return audio;
|
||||
}
|
||||
|
||||
if (eof_) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "End of stream");
|
||||
}
|
||||
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Decoder stopped");
|
||||
}
|
||||
static int callCount = 0;
|
||||
|
||||
bool AudioDecoder::getNextChunk(std::vector<short>& outChunk, bool blocking)
|
||||
{
|
||||
callCount++;
|
||||
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
|
||||
if (blocking) {
|
||||
cv_.wait(lock,
|
||||
[this] { return !int16Queue_.empty() || eof_.load(); });
|
||||
@@ -419,46 +345,95 @@ namespace Echoion::Core
|
||||
return false;
|
||||
}
|
||||
|
||||
outChunk = std::move(int16Queue_.front());
|
||||
// Swap instead of copy: the caller receives the decoded chunk and
|
||||
// their previous buffer's storage goes to the recycle free-list for
|
||||
// decodeThread() to reuse. Zero copies, zero allocations per chunk.
|
||||
std::vector<int16_t>& front = int16Queue_.front();
|
||||
outChunk.swap(front);
|
||||
front.clear(); // keep capacity, drop stale samples
|
||||
if (recycledChunks_.size() < MAX_INT16_QUEUE_SIZE) {
|
||||
recycledChunks_.push_back(std::move(front));
|
||||
}
|
||||
int16Queue_.pop_front();
|
||||
cv_.notify_one();
|
||||
|
||||
if (callCount <= 10 || callCount % 1000 == 0) {
|
||||
ECHOION_LOG_DEBUG(std::format(
|
||||
"getNextChunk {}: returned {} samples, queue left: {}",
|
||||
callCount, outChunk.size(), int16Queue_.size()));
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> statsLock(statsMutex_);
|
||||
stats_.framesDecoded++;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t AudioDecoder::queuedSamples() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
std::size_t total = 0;
|
||||
for (const auto& chunk : int16Queue_) {
|
||||
total += chunk.size();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
bool AudioDecoder::queueSaturated() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return int16Queue_.size() >= MAX_INT16_QUEUE_SIZE;
|
||||
}
|
||||
|
||||
Api::Result<void> AudioDecoder::seek(std::chrono::milliseconds position)
|
||||
{
|
||||
if (!formatContext_ || audioStreamIndex_ < 0) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "No source open");
|
||||
}
|
||||
|
||||
// No FFmpeg calls here: av_seek_frame() must not race the decode
|
||||
// thread's av_read_frame(). Publish a request instead; the decode
|
||||
// thread performs it in consumePendingSeek().
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
seekRequestMs_ = position.count();
|
||||
// Stop feeding stale pre-seek audio immediately (the decode thread
|
||||
// clears again, authoritatively, once the seek is performed).
|
||||
int16Queue_.clear();
|
||||
// Under mutex_ together with the request: the playback engine must
|
||||
// never observe isFinished() while a seek is pending, and a decode
|
||||
// thread parked at EOF must resume.
|
||||
eof_ = false;
|
||||
currentPositionMs_ = position.count();
|
||||
cv_.notify_all();
|
||||
return {};
|
||||
}
|
||||
|
||||
int64_t targetPts = position.count() * AV_TIME_BASE / 1000;
|
||||
int ret =
|
||||
av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
|
||||
|
||||
if (ret < 0) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Seek failed");
|
||||
bool AudioDecoder::consumePendingSeek()
|
||||
{
|
||||
const int64_t targetMs = seekRequestMs_.exchange(-1);
|
||||
if (targetMs < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const int64_t targetPts = targetMs * AV_TIME_BASE / 1000;
|
||||
int ret =
|
||||
av_seek_frame(formatContext_, -1, targetPts, AVSEEK_FLAG_BACKWARD);
|
||||
if (ret < 0) {
|
||||
char errbuf[256];
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
Void::Log::error(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("Seek to {}ms failed: {}", targetMs, errbuf));
|
||||
return true; // consumed; keep decoding from the current position
|
||||
}
|
||||
|
||||
// Also exits codec drain mode, so decoding can resume after EOF.
|
||||
avcodec_flush_buffers(codecContext_);
|
||||
currentPosition_ = position;
|
||||
|
||||
// Clear pending audio data
|
||||
int16Queue_.clear();
|
||||
std::queue<Api::DecodedAudio> empty;
|
||||
std::swap(decodedQueue_, empty);
|
||||
// Discard samples still buffered inside swresample from before the
|
||||
// seek.
|
||||
while (swr_convert(swrContext_, &outputBuffer_, MAX_OUT_SAMPLES,
|
||||
nullptr, 0) > 0) {
|
||||
}
|
||||
|
||||
return {};
|
||||
{
|
||||
// Authoritative clear: drops any pre-seek chunk pushed between
|
||||
// seek()'s clear and this point.
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
int16Queue_.clear();
|
||||
}
|
||||
currentPositionMs_ = targetMs;
|
||||
return true;
|
||||
}
|
||||
|
||||
Api::Result<Api::AudioStreamInfo> AudioDecoder::getStreamInfo() const
|
||||
@@ -466,6 +441,7 @@ namespace Echoion::Core
|
||||
if (!initialized_ || !formatContext_) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "No source open");
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return streamInfo_;
|
||||
}
|
||||
|
||||
@@ -475,13 +451,7 @@ namespace Echoion::Core
|
||||
// Note: This is updated when frames are decoded, not when played
|
||||
// For accurate playback position, use
|
||||
// MusicManager::getPlaybackPosition()
|
||||
return currentPosition_;
|
||||
}
|
||||
|
||||
bool AudioDecoder::hasMoreData() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return !decodedQueue_.empty() || (!eof_ && decoding_);
|
||||
return std::chrono::milliseconds(currentPositionMs_.load());
|
||||
}
|
||||
|
||||
void AudioDecoder::setOutputFormat(uint32_t sampleRate, uint32_t channels)
|
||||
@@ -496,31 +466,83 @@ namespace Echoion::Core
|
||||
proxyConfig_ = proxy;
|
||||
}
|
||||
|
||||
AudioDecoder::Stats AudioDecoder::getStats() const
|
||||
std::vector<int16_t> AudioDecoder::acquireChunkBuffer(size_t samples)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(statsMutex_);
|
||||
return stats_;
|
||||
std::vector<int16_t> chunk;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!recycledChunks_.empty()) {
|
||||
chunk = std::move(recycledChunks_.back());
|
||||
recycledChunks_.pop_back();
|
||||
}
|
||||
}
|
||||
// resize() reuses the recycled buffer's capacity (no allocation when it
|
||||
// is already large enough); allocates only on first use or growth.
|
||||
chunk.resize(samples);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
void AudioDecoder::decodeThread()
|
||||
{
|
||||
ECHOION_LOG_DEBUG("Decode thread started");
|
||||
constexpr int maxSamples = 4096;
|
||||
Void::Log::debug("AudioDecoder", "{}", "Decode thread started");
|
||||
|
||||
// Session loop: a session ends at EOF (or shutdown). Instead of
|
||||
// exiting at EOF, park and wait for a seek request so a post-EOF
|
||||
// seek can resume decoding on this same thread.
|
||||
while (decoding_.load()) {
|
||||
decodeSession();
|
||||
if (!decoding_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
// EOF park. eof_ and seekRequestMs_ are written together under
|
||||
// mutex_ (here and in seek()), so the playback engine can never
|
||||
// observe a stale isFinished() while a seek is pending.
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
if (seekRequestMs_.load() < 0) {
|
||||
eof_ = true; // real end of track: no seek raced the flush
|
||||
cv_.notify_all();
|
||||
}
|
||||
cv_.wait(lock, [this] {
|
||||
return seekRequestMs_.load() >= 0 || !decoding_;
|
||||
});
|
||||
if (!decoding_) {
|
||||
break;
|
||||
}
|
||||
eof_ = false; // resuming after a post-EOF seek
|
||||
}
|
||||
|
||||
// Unblock any blocking getNextChunk() callers on shutdown.
|
||||
eof_ = true;
|
||||
cv_.notify_all();
|
||||
Void::Log::debug("AudioDecoder", "{}", "Decode thread exiting");
|
||||
}
|
||||
|
||||
void AudioDecoder::decodeSession()
|
||||
{
|
||||
constexpr int maxSamples = MAX_OUT_SAMPLES;
|
||||
int packetsRead = 0;
|
||||
int framesProduced = 0;
|
||||
|
||||
while (decoding_.load()) {
|
||||
// A pending seek is performed here, on the decode thread — the
|
||||
// only thread allowed to touch the FFmpeg contexts.
|
||||
consumePendingSeek();
|
||||
|
||||
// Check queue size limit
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
if (int16Queue_.size() >= MAX_INT16_QUEUE_SIZE) {
|
||||
cv_.wait(lock, [this] {
|
||||
return int16Queue_.size() < MAX_INT16_QUEUE_SIZE ||
|
||||
!decoding_;
|
||||
!decoding_ || seekRequestMs_.load() >= 0;
|
||||
});
|
||||
if (!decoding_) {
|
||||
break;
|
||||
}
|
||||
if (seekRequestMs_.load() >= 0) {
|
||||
continue; // perform the seek at the loop top
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -552,16 +574,40 @@ namespace Echoion::Core
|
||||
break; // Error - continue to next packet
|
||||
}
|
||||
|
||||
// Convert to S16 and queue (like reference)
|
||||
int outSamples =
|
||||
swr_convert(swrContext_, &outputBuffer_, maxSamples,
|
||||
const_cast<const uint8_t**>(frame_->data),
|
||||
frame_->nb_samples);
|
||||
// Track decode position from frame timestamps. Without this
|
||||
// getPosition() stays at 0 forever, which silently disabled
|
||||
// the near-end prefetch (it never saw the track approaching
|
||||
// its end) — every transition took the slow synchronous
|
||||
// resolve path.
|
||||
if (frame_->pts != AV_NOPTS_VALUE) {
|
||||
AVRational tb =
|
||||
formatContext_->streams[audioStreamIndex_]->time_base;
|
||||
currentPositionMs_ = frame_->pts * 1000 * tb.num / tb.den;
|
||||
}
|
||||
|
||||
if (outSamples > 0) {
|
||||
std::vector<int16_t> chunk(outSamples * outputChannels_);
|
||||
// Convert to S16 and queue. One output buffer holds at most
|
||||
// maxSamples per call; anything beyond that stays in
|
||||
// swresample's internal FIFO, so keep draining (input =
|
||||
// nullptr) until it is empty — otherwise large input frames
|
||||
// (WAV blocks, high upsampling ratios) silently lose the
|
||||
// remainder and playback runs short.
|
||||
const uint8_t** inData =
|
||||
const_cast<const uint8_t**>(frame_->data);
|
||||
int inSamples = frame_->nb_samples;
|
||||
while (true) {
|
||||
int outSamples = swr_convert(swrContext_, &outputBuffer_,
|
||||
maxSamples, inData, inSamples);
|
||||
inData = nullptr; // input consumed on the first call
|
||||
inSamples = 0;
|
||||
if (outSamples <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const size_t chunkSamples = outSamples * outputChannels_;
|
||||
std::vector<int16_t> chunk =
|
||||
acquireChunkBuffer(chunkSamples);
|
||||
std::memcpy(chunk.data(), outputBuffer_,
|
||||
outSamples * outputChannels_ * sizeof(int16_t));
|
||||
chunkSamples * sizeof(int16_t));
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -569,17 +615,12 @@ namespace Echoion::Core
|
||||
}
|
||||
cv_.notify_one();
|
||||
framesProduced++;
|
||||
|
||||
if (framesProduced <= 5) {
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("Decode produced frame {}: {} samples",
|
||||
framesProduced, chunk.size()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Final flush (CRITICAL - like reference)
|
||||
// Final flush (CRITICAL - like reference): drain the codec, then the
|
||||
// resampler FIFO.
|
||||
avcodec_send_packet(codecContext_, nullptr);
|
||||
while (decoding_.load()) {
|
||||
int ret = avcodec_receive_frame(codecContext_, frame_);
|
||||
@@ -590,14 +631,21 @@ namespace Echoion::Core
|
||||
break;
|
||||
}
|
||||
|
||||
int outSamples = swr_convert(
|
||||
swrContext_, &outputBuffer_, 4096,
|
||||
const_cast<const uint8_t**>(frame_->data), frame_->nb_samples);
|
||||
const uint8_t** inData = const_cast<const uint8_t**>(frame_->data);
|
||||
int inSamples = frame_->nb_samples;
|
||||
while (true) {
|
||||
int outSamples = swr_convert(swrContext_, &outputBuffer_,
|
||||
maxSamples, inData, inSamples);
|
||||
inData = nullptr;
|
||||
inSamples = 0;
|
||||
if (outSamples <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (outSamples > 0) {
|
||||
std::vector<int16_t> chunk(outSamples * outputChannels_);
|
||||
const size_t chunkSamples = outSamples * outputChannels_;
|
||||
std::vector<int16_t> chunk = acquireChunkBuffer(chunkSamples);
|
||||
std::memcpy(chunk.data(), outputBuffer_,
|
||||
outSamples * outputChannels_ * sizeof(int16_t));
|
||||
chunkSamples * sizeof(int16_t));
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -608,111 +656,31 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
eof_ = true;
|
||||
cv_.notify_all();
|
||||
|
||||
ECHOION_LOG_INFO(std::format("Decode finished. Packets: {}, Frames: {}",
|
||||
packetsRead, framesProduced));
|
||||
}
|
||||
|
||||
Api::Result<void> AudioDecoder::readPacket()
|
||||
{
|
||||
int ret = av_read_frame(formatContext_, packet_);
|
||||
if (ret < 0) {
|
||||
if (ret == AVERROR_EOF) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "End of file");
|
||||
}
|
||||
if (ret == AVERROR_EXIT) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Interrupted");
|
||||
}
|
||||
char errbuf[256];
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
return Api::fail(Api::ErrorCode::AudioError,
|
||||
std::format("Error reading frame: {}", errbuf));
|
||||
}
|
||||
|
||||
if (packet_->stream_index != audioStreamIndex_) {
|
||||
av_packet_unref(packet_);
|
||||
return {};
|
||||
}
|
||||
|
||||
// Send packet to decoder - don't check error, just like reference code
|
||||
// Some packets may be corrupt but we continue to next
|
||||
avcodec_send_packet(codecContext_, packet_);
|
||||
av_packet_unref(packet_);
|
||||
|
||||
// Receive all available frames from the decoder
|
||||
while (true) {
|
||||
ret = avcodec_receive_frame(codecContext_, frame_);
|
||||
if (ret == AVERROR(EAGAIN)) {
|
||||
// Need more packets to produce a frame
|
||||
// Resampler delay tail (samples still buffered for the filter).
|
||||
while (decoding_.load()) {
|
||||
int outSamples = swr_convert(swrContext_, &outputBuffer_,
|
||||
maxSamples, nullptr, 0);
|
||||
if (outSamples <= 0) {
|
||||
break;
|
||||
}
|
||||
if (ret < 0) {
|
||||
// Error receiving frame - log but continue to next packet
|
||||
// Don't treat as fatal - Opus may have bad packets that are
|
||||
// safe to skip
|
||||
break;
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> audio;
|
||||
|
||||
if (zeroCopyEnabled_) {
|
||||
audio = convertFramePooled();
|
||||
} else {
|
||||
audio = convertFrame();
|
||||
}
|
||||
|
||||
if (audio) {
|
||||
const size_t chunkSamples = outSamples * outputChannels_;
|
||||
std::vector<int16_t> chunk = acquireChunkBuffer(chunkSamples);
|
||||
std::memcpy(chunk.data(), outputBuffer_,
|
||||
chunkSamples * sizeof(int16_t));
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
decodedQueue_.push(std::move(*audio));
|
||||
cv_.notify_one();
|
||||
int16Queue_.push_back(std::move(chunk));
|
||||
}
|
||||
cv_.notify_one();
|
||||
framesProduced++;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> AudioDecoder::convertFrame()
|
||||
{
|
||||
int outSamples = swr_get_out_samples(swrContext_, frame_->nb_samples);
|
||||
// Use int16_t for direct output (no float conversion)
|
||||
std::vector<int16_t> outputBuffer(outSamples * outputChannels_);
|
||||
|
||||
uint8_t* outData = reinterpret_cast<uint8_t*>(outputBuffer.data());
|
||||
const uint8_t** inData =
|
||||
const_cast<const uint8_t**>(frame_->extended_data);
|
||||
|
||||
int converted = swr_convert(swrContext_, &outData, outSamples, inData,
|
||||
frame_->nb_samples);
|
||||
if (converted < 0) {
|
||||
return Api::fail(Api::ErrorCode::AudioError, "Resampling failed");
|
||||
}
|
||||
|
||||
outputBuffer.resize(converted * outputChannels_);
|
||||
|
||||
if (frame_->pts != AV_NOPTS_VALUE) {
|
||||
AVRational timeBase =
|
||||
formatContext_->streams[audioStreamIndex_]->time_base;
|
||||
currentPosition_ = std::chrono::milliseconds(
|
||||
frame_->pts * 1000 * timeBase.num / timeBase.den);
|
||||
}
|
||||
|
||||
Api::DecodedAudio audio;
|
||||
audio.samples = std::move(outputBuffer);
|
||||
audio.view = Api::Int16AudioView(audio.samples.data(),
|
||||
audio.samples.size(), outputChannels_);
|
||||
audio.sampleRate = outputSampleRate_;
|
||||
audio.channels = outputChannels_;
|
||||
audio.timestamp = currentPosition_;
|
||||
return audio;
|
||||
}
|
||||
|
||||
Api::Result<Api::DecodedAudio> AudioDecoder::convertFramePooled()
|
||||
{
|
||||
// Using int16_t (short) for direct TeamSpeak compatibility
|
||||
// Both pooled and non-pooled versions now use the same int16 format
|
||||
return convertFrame();
|
||||
// eof_ is set by decodeThread()'s EOF park (not here) so that a seek
|
||||
// racing the final flush cannot leave a stale finished state.
|
||||
Void::Log::info(
|
||||
"AudioDecoder", "{}",
|
||||
std::format("Decode session finished. Packets: {}, Frames: {}",
|
||||
packetsRead, framesProduced));
|
||||
}
|
||||
|
||||
void AudioDecoder::cleanupFfmpeg()
|
||||
|
||||
+383
-38
@@ -1,11 +1,16 @@
|
||||
#include "echoion/core/CommandManager.hpp"
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include "echoion/core/MusicManager.hpp"
|
||||
#include "echoion/core/commands/Command.hpp"
|
||||
#include "echoion/core/i18n/Localization.hpp"
|
||||
#include "echoion/core/util/Paginate.hpp"
|
||||
#include <ConfigTypes.hpp>
|
||||
#include <Database.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <echoion/core/commands/Commands.hpp>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
@@ -25,9 +30,36 @@ namespace Echoion::Core
|
||||
try {
|
||||
auto prefix = manager_.getPrefix();
|
||||
|
||||
std::string helpMsg = std::format(
|
||||
"\xf0\x9f\x8e\xb5 **Echoion Bot Help**\n\n");
|
||||
helpMsg += std::format("Prefix: `{}`\n\n", prefix);
|
||||
std::string helpMsg =
|
||||
std::string(ctx.tr("# \xf0\x9f\x8e\xb5 Echoion Bot "
|
||||
"Help")) +
|
||||
"\n\n";
|
||||
|
||||
// Playback status header so !help doubles as a quick
|
||||
// readout of volume / shuffle / repeat / radio state.
|
||||
// Shared with !np and !list via playbackStatusLine().
|
||||
if (std::string status = playbackStatusLine(ctx);
|
||||
!status.empty()) {
|
||||
helpMsg += status;
|
||||
helpMsg += "\n\n";
|
||||
}
|
||||
|
||||
helpMsg +=
|
||||
ctx.trf("> [!TIP]\n> Prefix is `{}` \xe2\x80\x94 e.g. "
|
||||
"`{}play lofi`\n\n",
|
||||
prefix, prefix);
|
||||
|
||||
// Link the browser UI when it is enabled and has a public
|
||||
// address (web.publicUrl).
|
||||
if (manager_.serverConfig_ &&
|
||||
manager_.serverConfig_->web.enabled &&
|
||||
!manager_.serverConfig_->web.publicUrl.empty()) {
|
||||
helpMsg += ctx.trf(
|
||||
"> \xf0\x9f\x8c\x90 {}\n\n",
|
||||
markdownLink(ctx.tr("Open the web interface"),
|
||||
manager_.serverConfig_->web
|
||||
.publicUrl));
|
||||
}
|
||||
|
||||
// Get commands visible to this client
|
||||
auto visibleCommands =
|
||||
@@ -42,35 +74,58 @@ namespace Echoion::Core
|
||||
grouped[cmd->getCategory()].push_back({name, cmd});
|
||||
}
|
||||
|
||||
// Per-category icon for the collapsible section header.
|
||||
auto categoryEmoji =
|
||||
[](CommandCategory c) -> std::string_view {
|
||||
switch (c) {
|
||||
case CommandCategory::Play:
|
||||
return "\xe2\x96\xb6"; // play triangle
|
||||
case CommandCategory::Search:
|
||||
return "\xf0\x9f\x94\x8d"; // magnifier
|
||||
case CommandCategory::Music:
|
||||
return "\xf0\x9f\x8e\xb5"; // music note
|
||||
case CommandCategory::Queue:
|
||||
return "\xf0\x9f\x93\x9c"; // scroll
|
||||
case CommandCategory::Playback:
|
||||
return "\xe2\x8f\xaf"; // play/pause
|
||||
case CommandCategory::Utility:
|
||||
return "\xf0\x9f\x94\xa7"; // wrench
|
||||
case CommandCategory::Admin:
|
||||
return "\xf0\x9f\x9b\xa0"; // tools
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
for (const auto& [cat, cmds] : grouped) {
|
||||
helpMsg +=
|
||||
std::format("**{} Commands**\n", toString(cat));
|
||||
// Collapsible section per category. TeamSpeak uses the
|
||||
// markdown-it container syntax ":::details <title>" …
|
||||
// ":::" (not HTML <details>).
|
||||
helpMsg += ctx.trf(":::details {} {} Commands\n\n",
|
||||
categoryEmoji(cat),
|
||||
ctx.tr(toString(cat)));
|
||||
|
||||
for (const auto& [name, cmd] : cmds) {
|
||||
// Format: prefix!command usage
|
||||
if (!cmd->getUsage().empty()) {
|
||||
helpMsg += std::format("`{}{}` {}\n",
|
||||
prefix,
|
||||
name,
|
||||
cmd->getUsage());
|
||||
helpMsg +=
|
||||
std::format("`{}{}` {}\n", prefix, name,
|
||||
ctx.tr(cmd->getUsage()));
|
||||
} else {
|
||||
helpMsg +=
|
||||
std::format("`{}{}`\n", prefix, name);
|
||||
}
|
||||
|
||||
// Description
|
||||
helpMsg +=
|
||||
std::format("> {}\n", cmd->getDescription());
|
||||
helpMsg += std::format(
|
||||
"> {}\n", ctx.tr(cmd->getDescription()));
|
||||
|
||||
// Aliases
|
||||
auto aliases = cmd->getAliases();
|
||||
if (!aliases.empty()) {
|
||||
helpMsg += "> Aliases: ";
|
||||
helpMsg +=
|
||||
std::format("> {} ", ctx.tr("Aliases:"));
|
||||
for (size_t i = 0; i < aliases.size(); ++i) {
|
||||
helpMsg += std::format(
|
||||
"`{}{}`", prefix, aliases[i]);
|
||||
if (i < aliases.size() - 1) {
|
||||
helpMsg += ", ";
|
||||
helpMsg += std::format("`{}{}`", prefix,
|
||||
aliases[i]);
|
||||
if (i + 1 < aliases.size()) {
|
||||
helpMsg += " \xc2\xb7 "; // middot
|
||||
}
|
||||
}
|
||||
helpMsg += "\n";
|
||||
@@ -78,13 +133,17 @@ namespace Echoion::Core
|
||||
|
||||
helpMsg += "\n";
|
||||
}
|
||||
|
||||
helpMsg += ":::\n\n";
|
||||
}
|
||||
|
||||
ctx.reply(helpMsg);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"CommandManager", "{}",
|
||||
std::format("Help command exception: {}", e.what()));
|
||||
ctx.reply("Couldn't generate help. Please try again.");
|
||||
ctx.reply(
|
||||
ctx.tr("Couldn't generate help. Please try again."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +163,94 @@ namespace Echoion::Core
|
||||
{
|
||||
return {"h", "?", "commands"};
|
||||
}
|
||||
|
||||
// Help builds its own collapsible layout and is intentionally
|
||||
// multi-message; never auto-paginate it.
|
||||
bool autoPaginate() const override { return false; }
|
||||
};
|
||||
|
||||
// --- Internal Page Navigator (!page / !next / !prev) ---
|
||||
// mode 0 => "!page [n|next|prev]" (argument-driven); +1 => "!next";
|
||||
// -1 => "!prev". Re-sends a page of the caller's last long reply.
|
||||
class CommandManager::PageNavCommand : public Command
|
||||
{
|
||||
CommandManager& manager_;
|
||||
int mode_;
|
||||
|
||||
public:
|
||||
|
||||
PageNavCommand(CommandManager& mgr, int mode)
|
||||
: manager_(mgr), mode_(mode)
|
||||
{
|
||||
}
|
||||
|
||||
void execute(const CommandContext& ctx) override
|
||||
{
|
||||
std::optional<long> absolute;
|
||||
int delta = mode_;
|
||||
|
||||
if (mode_ == 0) {
|
||||
std::string arg = ctx.args;
|
||||
size_t b = arg.find_first_not_of(" \t");
|
||||
size_t e = arg.find_last_not_of(" \t");
|
||||
arg = (b == std::string::npos) ? std::string()
|
||||
: arg.substr(b, e - b + 1);
|
||||
|
||||
if (arg.empty() || arg == "next" || arg == "+") {
|
||||
delta = 1;
|
||||
} else if (arg == "prev" || arg == "back" || arg == "-") {
|
||||
delta = -1;
|
||||
} else {
|
||||
try {
|
||||
absolute = std::stol(arg);
|
||||
delta = 0;
|
||||
} catch (const std::exception&) {
|
||||
ctx.reply(ctx.trf(
|
||||
"Usage: {}page <n>, or {}next / {}prev.",
|
||||
ctx.prefix, ctx.prefix, ctx.prefix));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto page = manager_.renderCachedPage(ctx.clientId, absolute,
|
||||
delta, ctx.language);
|
||||
if (!page) {
|
||||
ctx.reply(ctx.tr(
|
||||
"Nothing to page through \xe2\x80\x94 run a command "
|
||||
"that lists results first."));
|
||||
return;
|
||||
}
|
||||
ctx.reply(*page);
|
||||
}
|
||||
|
||||
std::string_view getDescription() const override
|
||||
{
|
||||
return "Shows another page of the last long reply (also "
|
||||
"!next / !prev).";
|
||||
}
|
||||
|
||||
std::string_view getUsage() const override
|
||||
{
|
||||
return "[n|next|prev]";
|
||||
}
|
||||
|
||||
CommandCategory getCategory() const override
|
||||
{
|
||||
return CommandCategory::Utility;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> getAliases() const override
|
||||
{
|
||||
// Only the argument-driven "page" instance exposes an alias;
|
||||
// the dedicated next/prev instances are registered by name.
|
||||
return mode_ == 0 ? std::vector<std::string_view>{"p"}
|
||||
: std::vector<std::string_view>{};
|
||||
}
|
||||
|
||||
// Each cached page already fits one message; sending it verbatim
|
||||
// avoids a pointless second round of pagination.
|
||||
bool autoPaginate() const override { return false; }
|
||||
};
|
||||
|
||||
// --- Manager Implementation ---
|
||||
@@ -112,6 +259,7 @@ namespace Echoion::Core
|
||||
{
|
||||
registerBuiltinCommands();
|
||||
registerHelpCommand();
|
||||
registerPageCommands();
|
||||
startThreadPool();
|
||||
}
|
||||
|
||||
@@ -128,7 +276,8 @@ namespace Echoion::Core
|
||||
{
|
||||
pool_ =
|
||||
std::make_unique<Void::Concurrency::ThreadPool>(THREAD_POOL_SIZE);
|
||||
ECHOION_LOG_INFO(
|
||||
Void::Log::info(
|
||||
"CommandManager", "{}",
|
||||
std::format("CommandManager thread pool started with {} workers",
|
||||
THREAD_POOL_SIZE));
|
||||
}
|
||||
@@ -165,8 +314,8 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
std::string cmdKey(cmdName);
|
||||
std::transform(
|
||||
cmdKey.begin(), cmdKey.end(), cmdKey.begin(), ::tolower);
|
||||
std::transform(cmdKey.begin(), cmdKey.end(), cmdKey.begin(),
|
||||
::tolower);
|
||||
|
||||
CommandPtr command;
|
||||
{
|
||||
@@ -178,26 +327,43 @@ namespace Echoion::Core
|
||||
command = it->second;
|
||||
}
|
||||
|
||||
// Resolve the invoker's language up front so even the permission /
|
||||
// error fallbacks below are localized.
|
||||
const I18n::Language lang =
|
||||
resolveLanguage(task.clientId, task.musicManager);
|
||||
|
||||
// Check permissions
|
||||
if (!canExecuteCommand(task.clientId, command)) {
|
||||
task.replyFunc(
|
||||
"You don't have permission to use this command.");
|
||||
task.replyFunc(std::string(I18n::translate(
|
||||
"You don't have permission to use this command.", lang)));
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute command
|
||||
CommandContext ctx{.clientId = task.clientId,
|
||||
.prefix = prefix_,
|
||||
.args = std::move(argsStr),
|
||||
.invokerName = task.invokerName,
|
||||
.musicManager = task.musicManager,
|
||||
.services = services_,
|
||||
.replyCallback = std::move(task.replyFunc)};
|
||||
.language = lang};
|
||||
|
||||
if (command->autoPaginate()) {
|
||||
// Copy (not move) the sink so the catch-block fallback below
|
||||
// can still reach the user if execute() throws.
|
||||
ctx.replyCallback = [this, cid = task.clientId, lang,
|
||||
sink =
|
||||
task.replyFunc](std::string_view msg) {
|
||||
sink(paginateReply(cid, std::string(msg), lang));
|
||||
};
|
||||
} else {
|
||||
ctx.replyCallback = task.replyFunc;
|
||||
}
|
||||
|
||||
command->execute(ctx);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error(
|
||||
"CommandManager", "{}",
|
||||
std::format("Async command execution error: {}", e.what()));
|
||||
try {
|
||||
task.replyFunc(
|
||||
@@ -251,7 +417,9 @@ namespace Echoion::Core
|
||||
|
||||
// Check permissions synchronously (fast check)
|
||||
if (!canExecuteCommand(clientId, command)) {
|
||||
replyFunc("You don't have permission to use this command.");
|
||||
replyFunc(std::string(I18n::translate(
|
||||
"You don't have permission to use this command.",
|
||||
resolveLanguage(clientId, musicManager))));
|
||||
return true; // Command was found but not allowed
|
||||
}
|
||||
|
||||
@@ -323,25 +491,40 @@ namespace Echoion::Core
|
||||
|
||||
// Check permissions
|
||||
if (!canExecuteCommand(clientId, command)) {
|
||||
replyFunc("You don't have permission to use this command.");
|
||||
replyFunc(std::string(I18n::translate(
|
||||
"You don't have permission to use this command.",
|
||||
resolveLanguage(clientId, musicManager))));
|
||||
return true;
|
||||
}
|
||||
|
||||
const I18n::Language lang = resolveLanguage(clientId, musicManager);
|
||||
|
||||
CommandContext ctx{.clientId = clientId,
|
||||
.prefix = prefix_,
|
||||
.args = std::move(argsStr),
|
||||
.invokerName = invokerName,
|
||||
.musicManager = musicManager,
|
||||
.services = services_,
|
||||
.replyCallback = std::move(replyFunc)};
|
||||
.language = lang};
|
||||
|
||||
if (command->autoPaginate()) {
|
||||
ctx.replyCallback =
|
||||
[this, clientId, lang,
|
||||
sink = std::move(replyFunc)](std::string_view msg) {
|
||||
sink(paginateReply(clientId, std::string(msg), lang));
|
||||
};
|
||||
} else {
|
||||
ctx.replyCallback = std::move(replyFunc);
|
||||
}
|
||||
|
||||
try {
|
||||
command->execute(ctx);
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format(
|
||||
"Command execution error [{}]: {}", cmdKey, e.what()));
|
||||
ctx.reply(
|
||||
"An unexpected error occurred. Our team has been notified.");
|
||||
Void::Log::error("CommandManager", "{}",
|
||||
std::format("Command execution error [{}]: {}",
|
||||
cmdKey, e.what()));
|
||||
ctx.reply(ctx.tr(
|
||||
"An unexpected error occurred. Our team has been notified."));
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -431,6 +614,35 @@ namespace Echoion::Core
|
||||
permissionCheck_ = std::move(func);
|
||||
}
|
||||
|
||||
bool CommandManager::registerExternalCommand(
|
||||
std::string owner, std::string primaryName, CommandPtr command)
|
||||
{
|
||||
if (owner.empty() || primaryName.empty() || !command) return false;
|
||||
std::lock_guard lock(mutex_);
|
||||
if (commands_.contains(primaryName)) return false;
|
||||
commands_[primaryName] = command;
|
||||
uniqueCommands_.push_back({std::move(primaryName), command});
|
||||
for (auto alias : command->getAliases()) {
|
||||
if (!commands_.contains(alias)) commands_[std::string(alias)] = command;
|
||||
}
|
||||
externalCommands_[std::move(owner)].push_back(std::move(command));
|
||||
return true;
|
||||
}
|
||||
|
||||
void CommandManager::unregisterExternalCommands(std::string_view owner)
|
||||
{
|
||||
std::lock_guard lock(mutex_);
|
||||
auto found = externalCommands_.find(owner);
|
||||
if (found == externalCommands_.end()) return;
|
||||
const auto owns = [&](const CommandPtr& command) {
|
||||
return std::ranges::find(found->second, command) != found->second.end();
|
||||
};
|
||||
std::erase_if(commands_, [&](const auto& entry) { return owns(entry.second); });
|
||||
std::erase_if(uniqueCommands_,
|
||||
[&](const CommandEntry& entry) { return owns(entry.instance); });
|
||||
externalCommands_.erase(found);
|
||||
}
|
||||
|
||||
void CommandManager::setServerConfig(const Api::AppConfig& config)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
@@ -440,22 +652,30 @@ namespace Echoion::Core
|
||||
void CommandManager::registerBuiltinCommands()
|
||||
{
|
||||
registerCommand<PlayCommand>("play");
|
||||
registerCommand<YoutubePlayCommand>("pyt");
|
||||
registerCommand<YandexPlayCommand>("pya");
|
||||
registerCommand<SoundCloudPlayCommand>("psc");
|
||||
registerCommand<SelectCommand>("select");
|
||||
registerCommand<PauseCommand>("pause");
|
||||
registerCommand<ResumeCommand>("resume");
|
||||
registerCommand<StopCommand>("stop");
|
||||
registerCommand<SkipCommand>("skip");
|
||||
// registerCommand<SeekCommand>("seek");
|
||||
registerCommand<SeekCommand>("seek");
|
||||
registerCommand<VolumeCommand>("volume");
|
||||
registerCommand<QueueCommand>("queue");
|
||||
registerCommand<RemoveCommand>("remove");
|
||||
registerCommand<ClearCommand>("clear");
|
||||
registerCommand<MoveCommand>("move");
|
||||
registerCommand<ShuffleCommand>("shuffle");
|
||||
registerCommand<AutoplayCommand>("autoplay");
|
||||
registerCommand<RepeatCommand>("repeat");
|
||||
registerCommand<PlaylistCommand>("playlist");
|
||||
registerCommand<NowPlayingCommand>("np");
|
||||
registerCommand<LyricsCommand>("lyrics");
|
||||
registerCommand<SearchCommand>("search");
|
||||
registerCommand<YoutubeSearchCommand>("youtube");
|
||||
registerCommand<YandexSearchCommand>("yandex");
|
||||
registerCommand<SoundCloudSearchCommand>("soundcloud");
|
||||
registerCommand<ReloadCommand>("reload");
|
||||
registerCommand<ReloadConfigCommand>("reloadconfig");
|
||||
registerCommand<SubscribeCommand>("subscribe");
|
||||
@@ -464,6 +684,11 @@ namespace Echoion::Core
|
||||
registerCommand<UnsubscribeIdCommand>("unsubscribeid");
|
||||
registerCommand<UnsubscribeAllCommand>("unsubscribeall");
|
||||
registerCommand<RpcInfoCommand>("rpc");
|
||||
registerCommand<HistoryCommand>("history");
|
||||
registerCommand<StatsCommand>("stats");
|
||||
registerCommand<FavoriteCommand>("fav");
|
||||
registerCommand<AnnounceCommand>("announce");
|
||||
registerCommand<LanguageCommand>("language");
|
||||
}
|
||||
|
||||
void CommandManager::registerHelpCommand()
|
||||
@@ -480,4 +705,124 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
void CommandManager::registerPageCommands()
|
||||
{
|
||||
auto pageCmd = std::make_shared<PageNavCommand>(*this, 0);
|
||||
auto nextCmd = std::make_shared<PageNavCommand>(*this, 1);
|
||||
auto prevCmd = std::make_shared<PageNavCommand>(*this, -1);
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
// Only "page" is listed in help; next/prev are convenience shortcuts.
|
||||
commands_["page"] = pageCmd;
|
||||
uniqueCommands_.push_back({"page", pageCmd});
|
||||
for (auto alias : pageCmd->getAliases()) {
|
||||
commands_[std::string(alias)] = pageCmd;
|
||||
}
|
||||
commands_["next"] = nextCmd;
|
||||
commands_["prev"] = prevCmd;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
// Append a localized "Page X/Y · nav" footer to a page. Single-page
|
||||
// replies get no footer.
|
||||
std::string withPageFooter(const std::string& page, std::size_t index,
|
||||
std::size_t total, std::string_view prefix,
|
||||
I18n::Language lang)
|
||||
{
|
||||
if (total <= 1) {
|
||||
return page;
|
||||
}
|
||||
std::string tmpl(I18n::translate(
|
||||
"\n\n\xe2\x80\x94 Page {}/{} \xc2\xb7 {}next \xc2\xb7 "
|
||||
"{}prev \xc2\xb7 {}page <n>",
|
||||
lang));
|
||||
std::size_t human = index + 1;
|
||||
std::string pfx(prefix);
|
||||
return page + std::vformat(tmpl, std::make_format_args(
|
||||
human, total, pfx, pfx, pfx));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
I18n::Language CommandManager::resolveLanguage(
|
||||
uint64_t clientId,
|
||||
const std::weak_ptr<MusicManager>& musicManager) const
|
||||
{
|
||||
I18n::Language lang = I18n::Language::English;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (serverConfig_) {
|
||||
lang = I18n::parseLanguage(serverConfig_->bot.language);
|
||||
}
|
||||
}
|
||||
|
||||
auto manager = musicManager.lock();
|
||||
if (!manager || !services_) {
|
||||
return lang;
|
||||
}
|
||||
auto uid = manager->clientUid(clientId);
|
||||
if (!uid || uid->empty()) {
|
||||
return lang;
|
||||
}
|
||||
auto db = services_->get<Api::Database>();
|
||||
if (!db) {
|
||||
return lang;
|
||||
}
|
||||
auto stored = db->getKv("lang:" + *uid);
|
||||
if (stored && *stored) {
|
||||
lang = I18n::parseLanguage(**stored);
|
||||
}
|
||||
return lang;
|
||||
}
|
||||
|
||||
std::string CommandManager::paginateReply(uint64_t clientId,
|
||||
std::string text,
|
||||
I18n::Language lang)
|
||||
{
|
||||
if (text.size() <= kPageLimitBytes) {
|
||||
return text;
|
||||
}
|
||||
|
||||
auto pages = Util::paginate(text, kPageLimitBytes);
|
||||
if (pages.size() <= 1) {
|
||||
return pages.empty() ? text : std::move(pages.front());
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(pagedMutex_);
|
||||
PagedReply& entry = pagedReplies_[clientId];
|
||||
entry.pages = std::move(pages);
|
||||
entry.current = 0;
|
||||
entry.ts = std::chrono::steady_clock::now();
|
||||
return withPageFooter(entry.pages.front(), 0, entry.pages.size(),
|
||||
prefix_, lang);
|
||||
}
|
||||
|
||||
std::optional<std::string>
|
||||
CommandManager::renderCachedPage(uint64_t clientId,
|
||||
std::optional<long> absolute,
|
||||
int delta, I18n::Language lang)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pagedMutex_);
|
||||
auto it = pagedReplies_.find(clientId);
|
||||
if (it == pagedReplies_.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
PagedReply& pr = it->second;
|
||||
if (pr.pages.empty() ||
|
||||
std::chrono::steady_clock::now() - pr.ts > kPageTtl) {
|
||||
pagedReplies_.erase(it);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
const long count = static_cast<long>(pr.pages.size());
|
||||
long target =
|
||||
absolute ? (*absolute - 1) : static_cast<long>(pr.current) + delta;
|
||||
target = std::clamp(target, 0L, count - 1);
|
||||
pr.current = static_cast<std::size_t>(target);
|
||||
pr.ts = std::chrono::steady_clock::now();
|
||||
return withPageFooter(pr.pages[pr.current], pr.current, pr.pages.size(),
|
||||
prefix_, lang);
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
+124
-27
@@ -1,12 +1,17 @@
|
||||
#include "LoggerInterface.hpp"
|
||||
#include "Types.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include <AudioTypes.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <ranges>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
@@ -16,29 +21,121 @@ namespace Echoion::Core
|
||||
// yt-dlp concurrency is hard-capped regardless of what the file says.
|
||||
config.youtube.ytDlpMaxConcurrent =
|
||||
std::min(config.youtube.ytDlpMaxConcurrent, size_t(8));
|
||||
|
||||
// Bot language: only "en"/"ru" are understood; anything else (including
|
||||
// an empty field) falls back to English so replies never break.
|
||||
if (config.bot.language != "en" && config.bot.language != "ru") {
|
||||
config.bot.language = "en";
|
||||
}
|
||||
|
||||
const std::filesystem::path logFile{config.logging.fileName};
|
||||
if (config.logging.fileName.empty() || logFile.is_absolute() ||
|
||||
logFile.has_parent_path() || logFile.filename() != logFile ||
|
||||
logFile == "." || logFile == "..") {
|
||||
config.logging.fileName = "echoion.log";
|
||||
}
|
||||
config.logging.maxFileSizeBytes = std::clamp<uint64_t>(
|
||||
config.logging.maxFileSizeBytes, 64 * 1024, 1024ULL * 1024 * 1024);
|
||||
config.logging.maxFiles =
|
||||
std::clamp<uint32_t>(config.logging.maxFiles, 1, 1000);
|
||||
static constexpr std::array<std::string_view, 8> kLogLevels = {
|
||||
"trace", "debug", "info", "warning",
|
||||
"warn", "error", "critical", "fatal"};
|
||||
if (std::ranges::find(kLogLevels, config.logging.level) ==
|
||||
kLogLevels.end()) {
|
||||
config.logging.level = "debug";
|
||||
}
|
||||
|
||||
// Keep partially specified updater sections usable. Security-sensitive
|
||||
// URL/key validation happens in the host updater before the policy is
|
||||
// persisted or used; normalization here only supplies structural
|
||||
// defaults for older configuration files.
|
||||
if (!config.updates.sources.contains("official")) {
|
||||
config.updates.sources.emplace("official",
|
||||
Api::UpdateSourceConfig{});
|
||||
}
|
||||
auto normalizeComponent = [](Api::UpdateComponentConfig& component) {
|
||||
if (component.source.empty()) {
|
||||
component.source = "official";
|
||||
}
|
||||
if (component.channel.empty()) {
|
||||
component.channel = "stable";
|
||||
}
|
||||
};
|
||||
normalizeComponent(config.updates.runtime);
|
||||
normalizeComponent(config.updates.core);
|
||||
if (config.updates.plugins.source.empty()) {
|
||||
config.updates.plugins.source = "official";
|
||||
}
|
||||
if (config.updates.plugins.channel.empty()) {
|
||||
config.updates.plugins.channel = "stable";
|
||||
}
|
||||
|
||||
if (config.urlShortening.provider.empty()) {
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
}
|
||||
if (config.urlShortening.enabled &&
|
||||
config.urlShortening.provider == "url-shortener-internal" &&
|
||||
config.web.publicUrl.empty()) {
|
||||
config.urlShortening.enabled = false;
|
||||
Void::Log::warn(
|
||||
"ConfigLoader", "{}",
|
||||
"Internal URL shortening was disabled because web.publicUrl is "
|
||||
"empty; configure the bot's public URL before enabling "
|
||||
"url-shortener-internal");
|
||||
}
|
||||
config.urlShortening.timeout = std::clamp(
|
||||
config.urlShortening.timeout, std::chrono::milliseconds(100),
|
||||
std::chrono::milliseconds(30000));
|
||||
const auto validSource = [](std::string_view source) {
|
||||
static constexpr std::array<std::string_view, 6> kSources = {
|
||||
"youtube", "yandex", "url", "soundcloud", "spotify", "plugin"};
|
||||
return std::ranges::find(kSources, source) != kSources.end();
|
||||
};
|
||||
std::erase_if(
|
||||
config.urlShortening.sources,
|
||||
[&](const std::string& source) { return !validSource(source); });
|
||||
std::ranges::sort(config.urlShortening.sources);
|
||||
auto unique = std::ranges::unique(config.urlShortening.sources);
|
||||
config.urlShortening.sources.erase(unique.begin(), unique.end());
|
||||
}
|
||||
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromFile(const std::filesystem::path& path)
|
||||
{
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return Api::fail(Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}",
|
||||
path.string()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::NotFound,
|
||||
std::format("Configuration file not found: {}", path.string()));
|
||||
}
|
||||
|
||||
std::ifstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to open configuration file: {}",
|
||||
path.string()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to open configuration file: {}",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
std::string content((std::istreambuf_iterator<char>(file)),
|
||||
std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
|
||||
auto parsed = Void::Json::parse(content);
|
||||
auto config = loadFromJson(content);
|
||||
if (!config) {
|
||||
return std::unexpected(config.error());
|
||||
}
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< '\n';
|
||||
return config;
|
||||
}
|
||||
|
||||
Api::Result<Api::AppConfig>
|
||||
ConfigLoader::loadFromJson(std::string_view json)
|
||||
{
|
||||
auto parsed = Void::Json::parse(json);
|
||||
if (!parsed) {
|
||||
return Api::fail(
|
||||
Api::ErrorCode::ParseError,
|
||||
@@ -59,11 +156,15 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
Api::AppConfig config = std::move(*result);
|
||||
// Legacy files only had youtube.enableUrlShortening. An explicitly
|
||||
// present new section always wins, including enabled=false.
|
||||
if (parsed->find("urlShortening") == nullptr) {
|
||||
config.urlShortening.enabled = config.youtube.enableUrlShortening;
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
config.urlShortening.sources = {"youtube"};
|
||||
}
|
||||
normalize(config);
|
||||
|
||||
std::cout << std::format("[INFO] Configuration loaded from {}",
|
||||
path.string())
|
||||
<< std::endl;
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -75,15 +176,17 @@ namespace Echoion::Core
|
||||
Void::Json::to_json(config), {.pretty = true});
|
||||
std::ofstream file(path);
|
||||
if (!file.is_open()) {
|
||||
return Api::fail(Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}",
|
||||
path.string()));
|
||||
return Api::fail(
|
||||
Api::ErrorCode::PermissionDenied,
|
||||
std::format("Failed to write configuration file: {}",
|
||||
path.string()));
|
||||
}
|
||||
|
||||
file << json;
|
||||
file.close();
|
||||
|
||||
ECHOION_LOG_INFO(
|
||||
Void::Log::info(
|
||||
"ConfigLoader", "{}",
|
||||
std::format("Configuration saved to {}", path.string()));
|
||||
return {};
|
||||
}
|
||||
@@ -116,17 +219,17 @@ namespace Echoion::Core
|
||||
config.bot.commandPrefix = "!";
|
||||
config.bot.defaultVolume = 0.5f;
|
||||
config.bot.maxQueueSize = 100;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(30000);
|
||||
config.bot.autoReconnect = true;
|
||||
config.bot.reconnectDelay = std::chrono::milliseconds(5000);
|
||||
config.bot.maxReconnectAttempts = 5;
|
||||
config.bot.preferredQuality = Api::AudioQuality::High;
|
||||
config.bot.trackTimeout = std::chrono::milliseconds(10000);
|
||||
config.bot.allowPlaylistImports = true;
|
||||
|
||||
// Default YouTube config
|
||||
config.youtube.ytDlpMaxConcurrent = 4;
|
||||
config.youtube.ytDlpAsyncEnabled = true;
|
||||
config.youtube.enableUrlShortening = true;
|
||||
config.urlShortening.enabled = false;
|
||||
config.urlShortening.provider = "url-shortener-internal";
|
||||
config.urlShortening.sources = {"youtube"};
|
||||
config.urlShortening.timeout = std::chrono::milliseconds(3000);
|
||||
|
||||
// Default network config
|
||||
config.network.rpcEnabled = true;
|
||||
@@ -153,17 +256,11 @@ namespace Echoion::Core
|
||||
config.features.autoStartOnSubscribe = true;
|
||||
config.features.pauseOnEmptySubscribers = true;
|
||||
config.features.resumeOnSubscriberReturn = true;
|
||||
config.features.shuffleMode = "random";
|
||||
config.features.shuffleMode = "off";
|
||||
config.features.repeatMode = "off";
|
||||
config.features.maxHistorySize = 50;
|
||||
|
||||
// Default advanced config
|
||||
config.advanced.sampleRate = 192000;
|
||||
config.advanced.channels = 2;
|
||||
config.advanced.bufferSize = 7680;
|
||||
config.advanced.commandThreadPoolSize = 4;
|
||||
config.advanced.networkThreadPoolSize = 4;
|
||||
config.advanced.decoderThreads = 2;
|
||||
config.advanced.cacheEnabled = true;
|
||||
config.advanced.cacheMaxSize = "1GB";
|
||||
config.advanced.cacheTTL = 86400;
|
||||
|
||||
+10
-1
@@ -2,6 +2,7 @@
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <tuple>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
@@ -44,6 +45,12 @@ namespace Echoion::Api
|
||||
return config_.network;
|
||||
}
|
||||
|
||||
const SourcesConfig& ConfigManager::getSources() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
return config_.sources;
|
||||
}
|
||||
|
||||
const TeamSpeakConfig& ConfigManager::getTeamSpeak() const
|
||||
{
|
||||
std::shared_lock lock(mutex_);
|
||||
@@ -88,7 +95,9 @@ namespace Echoion::Api
|
||||
}
|
||||
|
||||
if (saveToFile) {
|
||||
save();
|
||||
// save() already reports failures (saveToFileInternal); the
|
||||
// in-memory update stands either way.
|
||||
std::ignore = save();
|
||||
}
|
||||
|
||||
notifyCallbacks();
|
||||
|
||||
+1196
-883
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,301 @@
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include "echoion/core/RpcDtos.hpp"
|
||||
#include <Database.hpp>
|
||||
#include <Events.hpp>
|
||||
#include <RpcTypes.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
void Core::setupEventBusSubscriptions() noexcept
|
||||
{
|
||||
using namespace Api::Events;
|
||||
|
||||
// Subscribe to playback events for RPC broadcasting and database
|
||||
// persistence
|
||||
eventBus_.subscribe<PlaybackStarted>(
|
||||
[this](const PlaybackStarted& evt) mutable {
|
||||
// Broadcast to RPC/WebSocket clients
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.started",
|
||||
toJson(Dto::PlaybackStarted{
|
||||
.track = {.id = evt.track.id,
|
||||
.title = evt.track.title,
|
||||
.artist = evt.track.artist},
|
||||
.position = evt.position.count()}));
|
||||
}
|
||||
|
||||
// Record playback start in database
|
||||
if (database_) {
|
||||
if (auto result = database_->recordPlayback(
|
||||
evt.track, evt.clientId,
|
||||
std::chrono::milliseconds(0), false);
|
||||
!result) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to record playback start: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackPaused>(
|
||||
[this](const PlaybackPaused& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.paused",
|
||||
toJson(Dto::Position{.position = evt.position.count()}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackResumed>(
|
||||
[this](const PlaybackResumed& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.resumed",
|
||||
toJson(Dto::Position{.position = evt.position.count()}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackStopped>(
|
||||
[this](const PlaybackStopped&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("playback.stopped", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackPositionChanged>(
|
||||
[this](const PlaybackPositionChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.position",
|
||||
toJson(Dto::PositionProgress{
|
||||
.position = evt.position.count(),
|
||||
.duration = evt.duration.count(),
|
||||
.progress = evt.progressPercent}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<TrackFinished>(
|
||||
[this](const TrackFinished& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("playback.finished", "{}");
|
||||
}
|
||||
|
||||
// Update playback record as completed, keeping the history
|
||||
// bounded per features.maxHistorySize.
|
||||
if (database_) {
|
||||
if (auto result = database_->recordPlayback(
|
||||
evt.track, 0, evt.finalPosition, true);
|
||||
!result) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to record playback: {}",
|
||||
result.error().message));
|
||||
}
|
||||
if (auto result = database_->trimHistory(
|
||||
config_.features.maxHistorySize);
|
||||
!result) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to trim history: {}",
|
||||
result.error().message));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Volume and playback mode changes
|
||||
eventBus_.subscribe<VolumeChanged>(
|
||||
[this](const VolumeChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.volumeChanged",
|
||||
toJson(Dto::Volume{.volume = evt.newVolume}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<ShuffleChanged>(
|
||||
[this](const ShuffleChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.shuffleChanged",
|
||||
toJson(Dto::Shuffle{.shuffle = evt.enabled}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<RepeatChanged>(
|
||||
[this](const RepeatChanged& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.repeatChanged",
|
||||
toJson(Dto::Repeat{.repeat = evt.enabled}));
|
||||
}
|
||||
});
|
||||
|
||||
// Queue events
|
||||
eventBus_.subscribe<TrackQueued>(
|
||||
[this](const TrackQueued& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"queue.trackAdded",
|
||||
toJson(Dto::TrackQueued{
|
||||
.queueId = evt.queueId,
|
||||
.title = evt.track.title,
|
||||
.artist = evt.track.artist,
|
||||
.position = evt.position,
|
||||
.queueLength = evt.queueLength}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<TrackRemoved>(
|
||||
[this](const TrackRemoved& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"queue.trackRemoved",
|
||||
toJson(Dto::TrackRemoved{
|
||||
.queueId = evt.queueId,
|
||||
.queueLength = evt.queueLength}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueCleared>(
|
||||
[this](const QueueCleared&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("queue.cleared", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueReordered>(
|
||||
[this](const QueueReordered& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"queue.reordered",
|
||||
toJson(Dto::QueueReordered{
|
||||
.queueId = evt.queueId,
|
||||
.oldPosition = evt.oldPosition,
|
||||
.newPosition = evt.newPosition}));
|
||||
}
|
||||
});
|
||||
|
||||
// Playlist events - save to database via event bus using external ID
|
||||
eventBus_.subscribe<PlaylistLoadStarted>(
|
||||
[this](const PlaylistLoadStarted& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playlist.loadStarted",
|
||||
toJson(Dto::PlaylistId{.playlistId = evt.playlistId}));
|
||||
}
|
||||
|
||||
if (database_) {
|
||||
auto result = database_->getOrCreatePlaylistByExternalId(
|
||||
evt.playlistId, evt.playlistId, "Loaded from YouTube",
|
||||
evt.requestedByClientId, true);
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaylistTrackLoaded>(
|
||||
[this](const PlaylistTrackLoaded& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playlist.trackLoaded",
|
||||
toJson(Dto::PlaylistTrackLoaded{
|
||||
.playlistId = evt.playlistId,
|
||||
.loaded = evt.loadedCount,
|
||||
.total = evt.totalCount}));
|
||||
}
|
||||
|
||||
// Add track to playlist in database - lookup by external ID
|
||||
if (database_) {
|
||||
auto result = database_->getOrCreatePlaylistByExternalId(
|
||||
evt.playlistId, evt.playlistId, "Loaded from YouTube",
|
||||
0, true);
|
||||
if (result) {
|
||||
if (auto added = database_->addTrackToPlaylist(
|
||||
result.value(), evt.track,
|
||||
evt.loadedCount - 1);
|
||||
!added) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format(
|
||||
"Failed to add track to playlist: {}",
|
||||
added.error().message));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaylistLoadCompleted>(
|
||||
[this](const PlaylistLoadCompleted& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"playlist.loadCompleted",
|
||||
toJson(Dto::PlaylistLoadCompleted{
|
||||
.playlistId = evt.playlistId,
|
||||
.totalTracks = evt.totalTracksLoaded,
|
||||
.success = evt.success}));
|
||||
}
|
||||
});
|
||||
|
||||
// Subscription events
|
||||
eventBus_.subscribe<UserSubscribed>(
|
||||
[this](const UserSubscribed& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"subscription.subscribed",
|
||||
toJson(Dto::User{.uid = evt.uid,
|
||||
.nickname = evt.nickname}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<UserUnsubscribed>(
|
||||
[this](const UserUnsubscribed& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent(
|
||||
"subscription.unsubscribed",
|
||||
toJson(Dto::User{.uid = evt.uid,
|
||||
.nickname = evt.nickname}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<QueueShuffled>(
|
||||
[this](const QueueShuffled&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("queue.shuffled", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<PlaybackError>(
|
||||
[this](const PlaybackError& evt) mutable {
|
||||
if (rpcServer_) {
|
||||
// Build via the JSON model: the error message may
|
||||
// contain quotes/newlines that must be escaped.
|
||||
Void::Json::Value payload = Void::Json::object();
|
||||
auto& obj = payload.as_object();
|
||||
obj.emplace_back("message",
|
||||
Void::Json::Value{evt.message});
|
||||
obj.emplace_back(
|
||||
"track", evt.track
|
||||
? Void::Json::Value{evt.track->title}
|
||||
: Void::Json::Value{nullptr});
|
||||
rpcServer_->broadcastEvent(
|
||||
"playback.error", Void::Json::serialize(payload, {}));
|
||||
}
|
||||
});
|
||||
|
||||
eventBus_.subscribe<ConfigReloaded>(
|
||||
[this](const ConfigReloaded&) mutable {
|
||||
if (rpcServer_) {
|
||||
rpcServer_->broadcastEvent("config.reloaded", "{}");
|
||||
}
|
||||
});
|
||||
|
||||
Void::Log::info("Core", "{}", "EventBus subscriptions set up");
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
File diff suppressed because it is too large.
Load diff
+943
-425
File diff suppressed because it is too large.
Load diff
+67
-21
@@ -3,8 +3,11 @@
|
||||
#include <Void/Plugin/Plugin.hpp>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
@@ -37,16 +40,52 @@ namespace Echoion::Core
|
||||
return "Echoion";
|
||||
}
|
||||
|
||||
// Void::Plugin::PluginLoader calls on_load() once after create
|
||||
// (first load and after a reload swap). Self-initialize from the
|
||||
// default config path so the plugin is ready without host-provided
|
||||
// wiring; idempotent via isInitialized().
|
||||
void configure(std::filesystem::path path)
|
||||
{
|
||||
configPath_ = std::move(path);
|
||||
}
|
||||
|
||||
void stageState(std::string state)
|
||||
{
|
||||
pendingState_ = std::move(state);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool ready() const noexcept { return ready_; }
|
||||
|
||||
// Configuration and state are supplied before on_load(). Keep all
|
||||
// fallible activation work here so void_plugin_ready can make the
|
||||
// manager's eventual swap transactional.
|
||||
void on_load() override
|
||||
{
|
||||
if (!isInitialized()) {
|
||||
(void)initialize(ConfigLoader::getDefaultConfigPath());
|
||||
ready_ = false;
|
||||
const auto path = configPath_.empty()
|
||||
? ConfigLoader::getDefaultConfigPath()
|
||||
: configPath_;
|
||||
if (auto result = initialize(path); !result) {
|
||||
return;
|
||||
}
|
||||
if (pendingState_.has_value()) {
|
||||
if (auto result = restoreAfterHotReload(*pendingState_); !result) {
|
||||
(void)shutdown();
|
||||
return;
|
||||
}
|
||||
pendingState_.reset();
|
||||
}
|
||||
ready_ = true;
|
||||
}
|
||||
|
||||
void on_unload() override
|
||||
{
|
||||
ready_ = false;
|
||||
if (isInitialized()) {
|
||||
(void)shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::filesystem::path configPath_;
|
||||
std::optional<std::string> pendingState_;
|
||||
bool ready_{false};
|
||||
};
|
||||
} // namespace Echoion::Core
|
||||
|
||||
@@ -76,10 +115,27 @@ extern "C"
|
||||
return Void::Plugin::PluginInfo{
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "Echoion",
|
||||
.plugin_version = Echoion::Api::VERSION_STRING,
|
||||
.plugin_version = ECHOION_CORE_VERSION,
|
||||
.description = "Echoion TeamSpeak music bot core"};
|
||||
}
|
||||
|
||||
void void_plugin_configure(void* instance, const char* config)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (plugin != nullptr) {
|
||||
plugin->configure(config != nullptr ? std::filesystem::path{config}
|
||||
: std::filesystem::path{});
|
||||
}
|
||||
}
|
||||
|
||||
int void_plugin_ready(void* instance)
|
||||
{
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
return plugin != nullptr && plugin->ready() ? 0 : -1;
|
||||
}
|
||||
|
||||
// v2 state protocol — survives layout changes across plugin versions.
|
||||
std::uint32_t void_plugin_state_version()
|
||||
{
|
||||
@@ -109,22 +165,12 @@ extern "C"
|
||||
int void_plugin_deserialize_state(void* instance, const char* json,
|
||||
std::uint32_t /*from_version*/)
|
||||
{
|
||||
auto* core = dynamic_cast<Echoion::Api::ICoreInterface*>(
|
||||
auto* plugin = dynamic_cast<Echoion::Core::CorePlugin*>(
|
||||
static_cast<Void::Plugin::IPlugin*>(instance));
|
||||
if (!core || !json) {
|
||||
if (!plugin || !json) {
|
||||
return -1;
|
||||
}
|
||||
// reload() transfers state before on_load(), so the freshly-created
|
||||
// instance is not yet initialized — bring it up first, then restore.
|
||||
// Idempotent: a no-op once initialized.
|
||||
if (!core->isInitialized()) {
|
||||
auto initResult =
|
||||
core->initialize(Echoion::Core::ConfigLoader::getDefaultConfigPath());
|
||||
if (!initResult) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
auto result = core->restoreAfterHotReload(std::string(json));
|
||||
return result ? 0 : -1;
|
||||
plugin->stageState(json);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] std::string archiveTimestamp()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now();
|
||||
const auto secondsPart = floor<seconds>(now);
|
||||
const auto micros = duration_cast<microseconds>(now - secondsPart);
|
||||
const std::time_t raw = system_clock::to_time_t(now);
|
||||
std::tm utc{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&utc, &raw);
|
||||
#else
|
||||
gmtime_r(&raw, &utc);
|
||||
#endif
|
||||
return std::format("{:04}{:02}{:02}-{:02}{:02}{:02}-{:06}",
|
||||
utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
|
||||
utc.tm_hour, utc.tm_min, utc.tm_sec,
|
||||
micros.count());
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isArchiveFor(const std::filesystem::path& path,
|
||||
const std::filesystem::path& active)
|
||||
{
|
||||
const auto name = path.filename().string();
|
||||
const auto prefix = active.stem().string() + "-";
|
||||
return name.starts_with(prefix) &&
|
||||
path.extension() == active.extension();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::error_code rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(activeLog, error);
|
||||
if (error && error != std::errc::no_such_file_or_directory) {
|
||||
return error;
|
||||
}
|
||||
error.clear();
|
||||
|
||||
const bool exists = std::filesystem::exists(status);
|
||||
if (exists && std::filesystem::is_symlink(status)) {
|
||||
return std::make_error_code(
|
||||
std::errc::too_many_symbolic_link_levels);
|
||||
}
|
||||
|
||||
const auto history = activeLog.parent_path() / "history";
|
||||
std::filesystem::create_directories(activeLog.parent_path(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
if (!std::filesystem::is_regular_file(status)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
const auto size = std::filesystem::file_size(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (size == 0 || maxFiles == 0) {
|
||||
std::filesystem::remove(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
} else {
|
||||
std::filesystem::create_directories(history, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
const auto timestamp = archiveTimestamp();
|
||||
auto archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp +
|
||||
activeLog.extension().string());
|
||||
for (std::size_t suffix = 1;
|
||||
std::filesystem::exists(archived, error) && !error;
|
||||
++suffix) {
|
||||
archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp + "-" +
|
||||
std::to_string(suffix) +
|
||||
activeLog.extension().string());
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::filesystem::rename(activeLog, archived, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto historyStatus =
|
||||
std::filesystem::symlink_status(history, error);
|
||||
if (error == std::errc::no_such_file_or_directory ||
|
||||
historyStatus.type() == std::filesystem::file_type::not_found) {
|
||||
return {};
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (!std::filesystem::is_directory(historyStatus) ||
|
||||
std::filesystem::is_symlink(historyStatus)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
std::vector<std::filesystem::path> archives;
|
||||
for (std::filesystem::directory_iterator iterator(history, error), end;
|
||||
!error && iterator != end; iterator.increment(error)) {
|
||||
const auto entryStatus = iterator->symlink_status(error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (std::filesystem::is_regular_file(entryStatus) &&
|
||||
isArchiveFor(iterator->path(), activeLog)) {
|
||||
archives.push_back(iterator->path());
|
||||
}
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::ranges::sort(archives);
|
||||
while (archives.size() > maxFiles) {
|
||||
std::filesystem::remove(archives.front(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
archives.erase(archives.begin());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace Echoion::Core
|
||||
-213
@@ -1,213 +0,0 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/SplitFileLogger.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] Void::Logging::Level toVoidLevel(Echoion::Api::LogLevel level)
|
||||
{
|
||||
using A = Echoion::Api::LogLevel;
|
||||
using V = Void::Logging::Level;
|
||||
switch (level) {
|
||||
case A::Debug:
|
||||
return V::Debug;
|
||||
case A::Info:
|
||||
return V::Info;
|
||||
case A::Warning:
|
||||
return V::Warning;
|
||||
case A::Error:
|
||||
return V::Error;
|
||||
case A::Critical:
|
||||
return V::Fatal;
|
||||
}
|
||||
return V::Info;
|
||||
}
|
||||
|
||||
[[nodiscard]] Echoion::Api::LogLevel fromVoidLevel(Void::Logging::Level level)
|
||||
{
|
||||
using A = Echoion::Api::LogLevel;
|
||||
using V = Void::Logging::Level;
|
||||
switch (level) {
|
||||
case V::Trace:
|
||||
case V::Debug:
|
||||
return A::Debug;
|
||||
case V::Info:
|
||||
return A::Info;
|
||||
case V::Warning:
|
||||
return A::Warning;
|
||||
case V::Error:
|
||||
return A::Error;
|
||||
case V::Fatal:
|
||||
return A::Critical;
|
||||
case V::Disabled:
|
||||
return A::Debug;
|
||||
}
|
||||
return A::Info;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
Logger::Logger(std::string_view logDir, std::string_view baseName)
|
||||
: logDir_(logDir), baseName_(baseName)
|
||||
{
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(logDir_, ec);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
Logger::~Logger()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
if (sink_) {
|
||||
sink_->flush();
|
||||
sink_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::rebuildSinks()
|
||||
{
|
||||
namespace VL = Void::Logging;
|
||||
|
||||
auto multi = std::make_shared<VL::MultiLogger>();
|
||||
|
||||
// Shared layout approximating the previous Logger output:
|
||||
// [2024-01-01 12:00:00.123] [INFO] [thread] file.cpp - message
|
||||
auto formatter = std::make_shared<const VL::PatternFormatter>(
|
||||
"[{time}] [{level}] [{thread}] {file} - {message}");
|
||||
|
||||
if (consoleOutput_.load()) {
|
||||
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
|
||||
console->set_formatter(formatter);
|
||||
multi->add(std::move(console));
|
||||
}
|
||||
|
||||
if (fileOutput_.load()) {
|
||||
VL::SplitFileOptions opts;
|
||||
opts.combined = true; // also write <dir>/all.log
|
||||
opts.max_bytes = static_cast<std::size_t>(maxFileSize_.load());
|
||||
opts.max_files = static_cast<std::size_t>(maxFiles_.load());
|
||||
if (auto fileSink = VL::SplitFileLogger::open(logDir_, opts)) {
|
||||
(*fileSink)->set_formatter(formatter);
|
||||
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
|
||||
}
|
||||
}
|
||||
|
||||
// Bridge Void entries back to the registered ILogger callbacks so
|
||||
// existing log subscribers (e.g. RPC log streaming) keep receiving
|
||||
// Api::LogEntry records, asynchronously as before.
|
||||
multi->add(std::make_shared<VL::CallbackLogger>(
|
||||
[this](const VL::Entry& entry) {
|
||||
dispatchToCallbacks(fromVoidLevel(entry.level), entry.message,
|
||||
entry.location.file_name(),
|
||||
entry.location.line(),
|
||||
entry.location.function_name());
|
||||
}));
|
||||
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
sink_ = std::move(multi);
|
||||
}
|
||||
|
||||
void Logger::dispatchToCallbacks(Api::LogLevel level,
|
||||
const std::string& message,
|
||||
const std::string& file, uint32_t line,
|
||||
const std::string& function)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
if (callbacks_.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Api::LogEntry entry;
|
||||
entry.level = level;
|
||||
entry.message = message;
|
||||
entry.sourceFile = file;
|
||||
entry.sourceLine = line;
|
||||
entry.function = function;
|
||||
entry.threadId = std::this_thread::get_id();
|
||||
entry.timestamp = std::chrono::system_clock::now();
|
||||
|
||||
for (const auto& callback : callbacks_) {
|
||||
callback(entry);
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::log(Api::LogLevel level, std::string_view message,
|
||||
std::source_location location)
|
||||
{
|
||||
if (level < minLevel_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::shared_ptr<Void::Logging::MultiLogger> sink;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
sink = sink_;
|
||||
}
|
||||
if (sink) {
|
||||
sink->log(toVoidLevel(level), message, location);
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::setMinLevel(Api::LogLevel level) { minLevel_.store(level); }
|
||||
|
||||
Api::LogLevel Logger::getMinLevel() const { return minLevel_.load(); }
|
||||
|
||||
void Logger::registerCallback(const LogCallback& callback)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
callbacks_.push_back(callback);
|
||||
}
|
||||
|
||||
void Logger::unregisterCallback(const LogCallback& callback)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(callbackMutex_);
|
||||
callbacks_.erase(std::remove_if(callbacks_.begin(), callbacks_.end(),
|
||||
[&callback](const auto& cb) {
|
||||
return &cb == &callback;
|
||||
}),
|
||||
callbacks_.end());
|
||||
}
|
||||
|
||||
void Logger::flush()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(sinkMutex_);
|
||||
if (sink_) {
|
||||
sink_->flush();
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::setConsoleOutput(bool enabled)
|
||||
{
|
||||
consoleOutput_.store(enabled);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::setFileOutput(bool enabled)
|
||||
{
|
||||
fileOutput_.store(enabled);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::setMaxFileSize(uint64_t bytes)
|
||||
{
|
||||
maxFileSize_.store(bytes);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
void Logger::setMaxFiles(uint32_t count)
|
||||
{
|
||||
maxFiles_.store(count);
|
||||
rebuildSinks();
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,225 @@
|
||||
#include "echoion/core/LyricsService.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
// Read an optional string field from a JSON object value.
|
||||
std::string strField(const Void::Json::Value& obj, std::string_view key)
|
||||
{
|
||||
const auto* v = obj.find(key);
|
||||
if (v && v->is_string()) {
|
||||
return v->as_string();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool boolField(const Void::Json::Value& obj, std::string_view key)
|
||||
{
|
||||
const auto* v = obj.find(key);
|
||||
return v && v->is_bool() && v->as_bool();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
LyricsService::LyricsService(std::shared_ptr<NetworkClient> net)
|
||||
: net_(std::move(net))
|
||||
{
|
||||
}
|
||||
|
||||
LyricsService::Lyrics LyricsService::fetch(const std::string& title,
|
||||
const std::string& artist,
|
||||
const std::string& album,
|
||||
long long durationSec)
|
||||
{
|
||||
if (title.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::string key =
|
||||
std::format("{}|{}|{}", artist, title, durationSec);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = cache_.find(key);
|
||||
if (it != cache_.end() &&
|
||||
std::chrono::steady_clock::now() - it->second.at < kCacheTtl) {
|
||||
return it->second.value;
|
||||
}
|
||||
}
|
||||
|
||||
Lyrics result = fetchUncached(title, artist, album, durationSec);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
cache_[key] = Entry{result, std::chrono::steady_clock::now()};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
LyricsService::Lyrics
|
||||
LyricsService::fetchUncached(const std::string& title,
|
||||
const std::string& artist,
|
||||
const std::string& album,
|
||||
long long durationSec) const
|
||||
{
|
||||
if (!net_) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// Turn one lrclib track object into our Lyrics shape.
|
||||
auto fromObject = [&](const Void::Json::Value& obj) -> Lyrics {
|
||||
Lyrics out;
|
||||
if (boolField(obj, "instrumental")) {
|
||||
out.found = true;
|
||||
out.plain = "[Instrumental]";
|
||||
out.source = "lrclib";
|
||||
out.title = strField(obj, "trackName");
|
||||
out.artist = strField(obj, "artistName");
|
||||
return out;
|
||||
}
|
||||
const std::string plain = strField(obj, "plainLyrics");
|
||||
const std::string synced = strField(obj, "syncedLyrics");
|
||||
if (plain.empty() && synced.empty()) {
|
||||
return {};
|
||||
}
|
||||
out.found = true;
|
||||
out.plain = plain;
|
||||
out.synced = parseLrc(synced);
|
||||
out.source = "lrclib";
|
||||
out.title = strField(obj, "trackName");
|
||||
out.artist = strField(obj, "artistName");
|
||||
// Fall back to the synced text when only synced lyrics exist.
|
||||
if (out.plain.empty() && !out.synced.empty()) {
|
||||
std::string joined;
|
||||
for (const auto& line : out.synced) {
|
||||
joined += line.text;
|
||||
joined += '\n';
|
||||
}
|
||||
out.plain = joined;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// 1) Exact match by artist/title/album/duration.
|
||||
if (durationSec > 0 && !artist.empty()) {
|
||||
std::string url = std::format(
|
||||
"https://lrclib.net/api/get?artist_name={}&track_name={}"
|
||||
"&duration={}",
|
||||
Void::Encoding::Url::encode(artist),
|
||||
Void::Encoding::Url::encode(title), durationSec);
|
||||
if (!album.empty()) {
|
||||
url += std::format("&album_name={}",
|
||||
Void::Encoding::Url::encode(album));
|
||||
}
|
||||
if (auto resp = net_->get(url);
|
||||
resp && resp->status == 200 && !resp->body.empty()) {
|
||||
if (auto parsed = Void::Json::parse(resp->body);
|
||||
parsed && parsed->is_object()) {
|
||||
Lyrics out = fromObject(*parsed);
|
||||
if (out.found) {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Search fallback — take the first result that carries lyrics.
|
||||
std::string searchUrl =
|
||||
std::format("https://lrclib.net/api/search?track_name={}",
|
||||
Void::Encoding::Url::encode(title));
|
||||
if (!artist.empty()) {
|
||||
searchUrl += std::format("&artist_name={}",
|
||||
Void::Encoding::Url::encode(artist));
|
||||
}
|
||||
if (auto resp = net_->get(searchUrl);
|
||||
resp && resp->status == 200 && !resp->body.empty()) {
|
||||
if (auto parsed = Void::Json::parse(resp->body);
|
||||
parsed && parsed->is_array()) {
|
||||
for (const auto& entry : parsed->as_array()) {
|
||||
if (!entry.is_object()) {
|
||||
continue;
|
||||
}
|
||||
Lyrics out = fromObject(entry);
|
||||
if (out.found) {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<LyricsService::Line>
|
||||
LyricsService::parseLrc(const std::string& lrc)
|
||||
{
|
||||
std::vector<Line> lines;
|
||||
if (lrc.empty()) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
std::istringstream stream(lrc);
|
||||
std::string raw;
|
||||
while (std::getline(stream, raw)) {
|
||||
if (!raw.empty() && raw.back() == '\r') {
|
||||
raw.pop_back();
|
||||
}
|
||||
// Collect every [..] timestamp prefix on this line.
|
||||
std::vector<std::int64_t> stamps;
|
||||
std::size_t pos = 0;
|
||||
while (pos < raw.size() && raw[pos] == '[') {
|
||||
std::size_t close = raw.find(']', pos);
|
||||
if (close == std::string::npos) {
|
||||
break;
|
||||
}
|
||||
std::string_view tag(raw.data() + pos + 1, close - pos - 1);
|
||||
// A timestamp starts with a digit; [ar:], [ti:] etc. don't.
|
||||
if (!tag.empty() &&
|
||||
std::isdigit(static_cast<unsigned char>(tag.front()))) {
|
||||
auto colon = tag.find(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
int minutes = 0;
|
||||
double seconds = 0.0;
|
||||
std::from_chars(tag.data(), tag.data() + colon,
|
||||
minutes);
|
||||
// Parse the seconds part (may be fractional).
|
||||
std::string sec(tag.substr(colon + 1));
|
||||
try {
|
||||
seconds = std::stod(sec);
|
||||
} catch (const std::exception&) {
|
||||
seconds = 0.0;
|
||||
}
|
||||
stamps.push_back(static_cast<std::int64_t>(
|
||||
minutes * 60000LL +
|
||||
static_cast<std::int64_t>(seconds * 1000.0)));
|
||||
}
|
||||
}
|
||||
pos = close + 1;
|
||||
}
|
||||
if (stamps.empty()) {
|
||||
continue;
|
||||
}
|
||||
std::string text = raw.substr(pos);
|
||||
// Trim leading spaces on the lyric text.
|
||||
auto start = text.find_first_not_of(" \t");
|
||||
text = (start == std::string::npos) ? std::string{}
|
||||
: text.substr(start);
|
||||
for (auto ms : stamps) {
|
||||
lines.push_back(Line{ms, text});
|
||||
}
|
||||
}
|
||||
|
||||
std::sort(lines.begin(), lines.end(),
|
||||
[](const Line& a, const Line& b) { return a.ms < b.ms; });
|
||||
return lines;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -1,60 +0,0 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <MemoryPool.hpp>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Api
|
||||
{
|
||||
|
||||
AudioBufferPool& AudioBufferPool::instance()
|
||||
{
|
||||
static AudioBufferPool instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void AudioBufferPool::initialize(size_t bufferSize, size_t poolSize)
|
||||
{
|
||||
bufferSize_ = bufferSize;
|
||||
pool_ = std::make_unique<Void::BufferPool::BufferPool<int16_t>>();
|
||||
|
||||
// Pre-warm the size-class bucket: acquire then immediately drop
|
||||
// `poolSize` buffers so subsequent acquireBuffer() calls reuse storage.
|
||||
{
|
||||
std::vector<AudioSampleBuffer> warm;
|
||||
warm.reserve(poolSize);
|
||||
for (size_t i = 0; i < poolSize; ++i) {
|
||||
warm.push_back(pool_->acquire(bufferSize));
|
||||
}
|
||||
} // buffers returned to the pool here
|
||||
|
||||
ECHOION_LOG_INFO(std::format(
|
||||
"AudioBufferPool initialized: {} buffers of {} samples (~{} KB)",
|
||||
poolSize, bufferSize,
|
||||
(bufferSize * poolSize * sizeof(int16_t)) / 1024));
|
||||
}
|
||||
|
||||
void AudioBufferPool::shutdown()
|
||||
{
|
||||
pool_.reset();
|
||||
ECHOION_LOG_INFO("AudioBufferPool shutdown");
|
||||
}
|
||||
|
||||
AudioSampleBuffer AudioBufferPool::acquireBuffer()
|
||||
{
|
||||
if (!pool_) {
|
||||
return AudioSampleBuffer{};
|
||||
}
|
||||
return pool_->acquire(bufferSize_);
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getAvailableBuffers() const
|
||||
{
|
||||
return pool_ ? pool_->stats().pooled : 0;
|
||||
}
|
||||
|
||||
size_t AudioBufferPool::getTotalBuffers() const
|
||||
{
|
||||
return pool_ ? static_cast<size_t>(pool_->stats().allocations) : 0;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Api
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#include <echoion/api/module/LegacyModuleAbi.hpp>
|
||||
|
||||
#include "ModuleContracts.hpp"
|
||||
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::CoreModule
|
||||
{
|
||||
namespace
|
||||
{
|
||||
class LifecycleModule final : public Void::Plugin::IModule
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] std::string_view name() const noexcept override
|
||||
{
|
||||
return "EchoionCore";
|
||||
}
|
||||
};
|
||||
|
||||
std::unique_ptr<Void::Plugin::IModule> createCoreModule()
|
||||
{
|
||||
return std::make_unique<LifecycleModule>();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
const Void::Plugin::ModuleDescriptor& coreModuleDescriptor()
|
||||
{
|
||||
static const Void::Plugin::ModuleDescriptor descriptor{
|
||||
.module_id = "EchoionCore",
|
||||
.component_version =
|
||||
{
|
||||
.major = ECHOION_COMPONENT_VERSION_MAJOR,
|
||||
.minor = ECHOION_COMPONENT_VERSION_MINOR,
|
||||
.patch = ECHOION_COMPONENT_VERSION_PATCH,
|
||||
.pre_release = {},
|
||||
.build = {},
|
||||
},
|
||||
.abi_hash = coreAbiHash,
|
||||
.abi_contract = Void::Json::object({
|
||||
{"schemaVersion", 1},
|
||||
{"contractId", "echoion.module.core"},
|
||||
{"descriptor", "echoion_module_descriptor_v1"},
|
||||
}),
|
||||
.dependencies =
|
||||
{
|
||||
{
|
||||
.module_id = "EchoionApi",
|
||||
.version_range = "^2.0.0",
|
||||
.abi_hash = apiAbiHash,
|
||||
},
|
||||
},
|
||||
.activation_policy = Void::Plugin::ActivationPolicy::Reloadable,
|
||||
.create = createCoreModule,
|
||||
};
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
const echoion_module_descriptor_v1& coreModuleAbiDescriptor()
|
||||
{
|
||||
using Bridge = Api::Module::LegacyModuleAbi<createCoreModule>;
|
||||
static const echoion_module_dependency_v1 dependencies[]{
|
||||
{
|
||||
.struct_size = sizeof(echoion_module_dependency_v1),
|
||||
.component_id = Api::Module::Detail::stringView("EchoionApi"),
|
||||
.version_range =
|
||||
Api::Module::Detail::stringView(">=2.0.0 <3.0.0"),
|
||||
.abi_hash = Api::Module::Detail::stringView(apiAbiHash),
|
||||
.optional = 0,
|
||||
.reserved_bytes = {},
|
||||
},
|
||||
};
|
||||
static const echoion_module_descriptor_v1 descriptor{
|
||||
.struct_size = sizeof(echoion_module_descriptor_v1),
|
||||
.abi_version = ECHOION_MODULE_ABI_VERSION,
|
||||
.component_id = Api::Module::Detail::stringView("EchoionCore"),
|
||||
.version_major = ECHOION_COMPONENT_VERSION_MAJOR,
|
||||
.version_minor = ECHOION_COMPONENT_VERSION_MINOR,
|
||||
.version_patch = ECHOION_COMPONENT_VERSION_PATCH,
|
||||
.version_prerelease = {},
|
||||
.abi_hash = Api::Module::Detail::stringView(coreAbiHash),
|
||||
.dependencies = dependencies,
|
||||
.dependency_count = std::size(dependencies),
|
||||
.activation_policy = ECHOION_ACTIVATION_RELOADABLE_V1,
|
||||
.api = &Bridge::api,
|
||||
.reserved = {},
|
||||
};
|
||||
return descriptor;
|
||||
}
|
||||
} // namespace Echoion::CoreModule
|
||||
|
||||
extern "C" ECHOION_MODULE_EXPORT const Void::Plugin::ModuleDescriptor*
|
||||
echoion_module_query()
|
||||
{
|
||||
return &Echoion::CoreModule::coreModuleDescriptor();
|
||||
}
|
||||
|
||||
extern "C" ECHOION_MODULE_ABI_EXPORT const echoion_module_descriptor_v1*
|
||||
echoion_module_abi_query()
|
||||
{
|
||||
return &Echoion::CoreModule::coreModuleAbiDescriptor();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
namespace Echoion::CoreModule
|
||||
{
|
||||
inline constexpr auto apiAbiHash =
|
||||
"sha256:"
|
||||
"d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113";
|
||||
inline constexpr auto coreAbiHash =
|
||||
"sha256:"
|
||||
"9cb668e2a502dcfe02d145ed63635d63619732d77ff5749685834382705e8d21";
|
||||
} // namespace Echoion::CoreModule
|
||||
+1459
-1861
File diff suppressed because it is too large.
Load diff
+36
-46
@@ -1,4 +1,4 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/NetworkClient.hpp"
|
||||
#include <Void/Functional/Retry.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
@@ -13,9 +13,12 @@ namespace Echoion::Core
|
||||
Api::Result<void> NetworkClient::initialize(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy)
|
||||
{
|
||||
proxy_ = proxy;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
proxy_ = proxy;
|
||||
}
|
||||
initialized_ = true;
|
||||
ECHOION_LOG_INFO(std::format("NetworkClient initialized (proxy: {})",
|
||||
Void::Log::info("NetworkClient", "{}", std::format("NetworkClient initialized (proxy: {})",
|
||||
proxy.has_value() ? "enabled" : "disabled"));
|
||||
return {};
|
||||
}
|
||||
@@ -26,7 +29,15 @@ namespace Echoion::Core
|
||||
NetworkClient::executeRequest(const Void::Net::Request& req)
|
||||
{
|
||||
Void::Net::HttpClient client;
|
||||
const auto active = proxy_;
|
||||
// Snapshot the proxy under the lock. setProxy()/initialize() can run on
|
||||
// other threads (config reload, init), and a torn read of the
|
||||
// optional<ProxyConfig> (it holds std::string host/user/pass) could
|
||||
// yield an empty host -> enabled()==false -> a silent direct connection.
|
||||
std::optional<Void::Net::ProxyConfig> active;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
active = proxy_;
|
||||
}
|
||||
if (active && active->enabled()) {
|
||||
client.set_proxy(*active);
|
||||
}
|
||||
@@ -46,7 +57,7 @@ namespace Echoion::Core
|
||||
retryPolicy_, [&] { return executeRequest(req); },
|
||||
[this](const Api::Result<Void::Net::Response>& result) {
|
||||
if (!result) {
|
||||
ECHOION_LOG_WARNING(std::format(
|
||||
Void::Log::warn("NetworkClient", "{}", std::format(
|
||||
"Request error: {}, retrying", result.error().message));
|
||||
return true;
|
||||
}
|
||||
@@ -54,7 +65,7 @@ namespace Echoion::Core
|
||||
const auto& codes = retryableStatusCodes_;
|
||||
if (std::find(codes.begin(), codes.end(), result->status) !=
|
||||
codes.end()) {
|
||||
ECHOION_LOG_WARNING(
|
||||
Void::Log::warn("NetworkClient", "{}",
|
||||
std::format("Request failed with status {}, retrying",
|
||||
result->status));
|
||||
return true;
|
||||
@@ -69,6 +80,25 @@ namespace Echoion::Core
|
||||
return executeWithRetry(req);
|
||||
}
|
||||
|
||||
Api::Result<Void::Net::Response>
|
||||
NetworkClient::getDirect(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
{
|
||||
Void::Net::Request req;
|
||||
req.url = std::string(url);
|
||||
req.method = Void::Net::Method::Get;
|
||||
req.headers = headers;
|
||||
|
||||
// Deliberately no proxy and no retry (see header).
|
||||
Void::Net::HttpClient client;
|
||||
auto result = client.send(req);
|
||||
if (!result) {
|
||||
return Api::fail(Api::ErrorCode::NetworkError,
|
||||
result.error().message());
|
||||
}
|
||||
return std::move(*result);
|
||||
}
|
||||
|
||||
Api::Result<Void::Net::Response>
|
||||
NetworkClient::get(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
@@ -92,46 +122,6 @@ namespace Echoion::Core
|
||||
return request(req);
|
||||
}
|
||||
|
||||
std::future<Api::Result<Void::Net::Response>>
|
||||
NetworkClient::getAsync(std::string_view url,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
{
|
||||
return pool_.submit([this, u = std::string(url), headers] {
|
||||
return get(u, headers);
|
||||
});
|
||||
}
|
||||
|
||||
std::future<Api::Result<Void::Net::Response>>
|
||||
NetworkClient::postAsync(std::string_view url, std::string_view body,
|
||||
const std::vector<Void::Net::Header>& headers)
|
||||
{
|
||||
return pool_.submit([this, u = std::string(url), b = std::string(body),
|
||||
headers] { return post(u, b, headers); });
|
||||
}
|
||||
|
||||
std::future<Api::Result<Void::Net::Response>>
|
||||
NetworkClient::requestAsync(const Void::Net::Request& req)
|
||||
{
|
||||
return pool_.submit([this, req] { return request(req); });
|
||||
}
|
||||
|
||||
std::vector<Api::Result<Void::Net::Response>>
|
||||
NetworkClient::requestBatch(
|
||||
const std::vector<Void::Net::Request>& requests)
|
||||
{
|
||||
std::vector<std::future<Api::Result<Void::Net::Response>>> futures;
|
||||
futures.reserve(requests.size());
|
||||
for (const auto& req : requests) {
|
||||
futures.push_back(requestAsync(req));
|
||||
}
|
||||
std::vector<Api::Result<Void::Net::Response>> results;
|
||||
results.reserve(requests.size());
|
||||
for (auto& f : futures) {
|
||||
results.push_back(f.get());
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
void NetworkClient::setProxy(
|
||||
const std::optional<Void::Net::ProxyConfig>& proxy)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#include "echoion/core/PlaylistLoader.hpp"
|
||||
#include "echoion/core/YouTubeClient.hpp"
|
||||
#include <Events.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <format>
|
||||
#include <mutex>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
|
||||
Api::Result<void> PlaylistLoader::load(const std::string& playlistIdOrUrl,
|
||||
uint64_t clientId)
|
||||
{
|
||||
if (!yt_) {
|
||||
return Api::fail(Api::ErrorCode::ServiceUnavailable,
|
||||
"YouTube client not available");
|
||||
}
|
||||
|
||||
if (loading_.load()) {
|
||||
return Api::fail(Api::ErrorCode::AlreadyExists,
|
||||
"Already loading a playlist, please wait");
|
||||
}
|
||||
|
||||
// Extract playlist ID if a full URL was provided
|
||||
std::string playlistId = playlistIdOrUrl;
|
||||
if (YouTubeClient::isYouTubeUrl(playlistIdOrUrl)) {
|
||||
auto extractedId = yt_->extractPlaylistId(playlistIdOrUrl);
|
||||
if (extractedId) {
|
||||
playlistId = *extractedId;
|
||||
Void::Log::debug(
|
||||
"PlaylistLoader", "{}",
|
||||
std::format("Extracted playlist ID '{}' from URL",
|
||||
playlistId));
|
||||
} else {
|
||||
return Api::fail(Api::ErrorCode::InvalidArgument,
|
||||
"Could not extract playlist ID from URL");
|
||||
}
|
||||
}
|
||||
|
||||
// Join previous load thread if any (don't detach - unsafe)
|
||||
if (loadThread_.joinable()) {
|
||||
loadThread_.join();
|
||||
}
|
||||
|
||||
loading_ = true;
|
||||
loadedCount_ = 0;
|
||||
totalCount_ = 0;
|
||||
|
||||
Void::Log::info("PlaylistLoader", "{}",
|
||||
std::format("Starting async playlist load: {}",
|
||||
playlistId));
|
||||
|
||||
emit(Api::Events::PlaylistLoadStarted{.playlistId = playlistId,
|
||||
.requestedByClientId = clientId});
|
||||
|
||||
loadThread_ = std::thread([this, playlistId, clientId]() {
|
||||
std::atomic<uint32_t> added{0};
|
||||
std::atomic<bool> firstTrackAdded{false};
|
||||
std::mutex firstMutex;
|
||||
|
||||
yt_->getPlaylistStreaming(
|
||||
playlistId,
|
||||
// Track callback — called for each track as it resolves.
|
||||
[this, &added, &firstTrackAdded, &firstMutex, clientId,
|
||||
playlistId](Api::TrackInfo&& track) {
|
||||
loadedCount_.fetch_add(1);
|
||||
|
||||
bool isFirst = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(firstMutex);
|
||||
isFirst = !firstTrackAdded.load();
|
||||
if (isFirst) {
|
||||
firstTrackAdded = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (enqueue_(track, clientId)) {
|
||||
added.fetch_add(1);
|
||||
|
||||
emit(Api::Events::PlaylistTrackLoaded{
|
||||
.playlistId = playlistId,
|
||||
.track = track,
|
||||
.loadedCount =
|
||||
static_cast<uint32_t>(loadedCount_.load()),
|
||||
.totalCount =
|
||||
static_cast<uint32_t>(totalCount_.load())});
|
||||
|
||||
// Start playback immediately on the first track.
|
||||
if (isFirst) {
|
||||
Void::Log::info(
|
||||
"PlaylistLoader", "{}",
|
||||
std::format("First track resolved: {} - {}. "
|
||||
"Starting playback...",
|
||||
track.title, track.artist));
|
||||
if (requestStart_) {
|
||||
requestStart_();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
// Total-track-count callback.
|
||||
[this, playlistId](size_t totalTracks) {
|
||||
totalCount_ = totalTracks;
|
||||
Void::Log::info(
|
||||
"PlaylistLoader", "{}",
|
||||
std::format("Playlist '{}' has {} tracks, resolving...",
|
||||
playlistId, totalTracks));
|
||||
},
|
||||
// Completion callback.
|
||||
[this, &added, playlistId]() {
|
||||
Void::Log::info(
|
||||
"PlaylistLoader", "{}",
|
||||
std::format(
|
||||
"Playlist streaming complete. Added {} tracks",
|
||||
added.load()));
|
||||
loading_ = false;
|
||||
|
||||
emit(Api::Events::PlaylistLoadCompleted{
|
||||
.playlistId = playlistId,
|
||||
.totalTracksLoaded = added.load(),
|
||||
.success = true,
|
||||
.error = std::nullopt});
|
||||
});
|
||||
});
|
||||
|
||||
return {}; // Loading continues in the background.
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
@@ -0,0 +1,116 @@
|
||||
#include "PluginCompatibility.hpp"
|
||||
|
||||
#include "ModuleContracts.hpp"
|
||||
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr std::size_t maximumDescriptorText = 1024;
|
||||
constexpr std::size_t maximumDependencies = 64;
|
||||
|
||||
[[nodiscard]] PluginCompatibility reject(std::string reason)
|
||||
{
|
||||
return {.compatible = false, .reason = std::move(reason)};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid(const echoion_string_view_v1 value) noexcept
|
||||
{
|
||||
return value.size <= maximumDescriptorText &&
|
||||
(value.size == 0U || value.data != nullptr);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string_view
|
||||
view(const echoion_string_view_v1 value) noexcept
|
||||
{
|
||||
return value.data == nullptr
|
||||
? std::string_view{}
|
||||
: std::string_view{value.data, value.size};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
PluginCompatibility
|
||||
checkExtensionDescriptor(const echoion_module_descriptor_v1* descriptor)
|
||||
{
|
||||
if (descriptor == nullptr) {
|
||||
return reject("stable module descriptor is null");
|
||||
}
|
||||
if (descriptor->struct_size < sizeof(echoion_module_descriptor_v1) ||
|
||||
descriptor->abi_version != ECHOION_MODULE_ABI_VERSION) {
|
||||
return reject("stable module descriptor version is incompatible");
|
||||
}
|
||||
if (!valid(descriptor->component_id) ||
|
||||
view(descriptor->component_id).empty() ||
|
||||
descriptor->version_major != ECHOION_COMPONENT_VERSION_MAJOR) {
|
||||
return reject(
|
||||
"component identity or major version is incompatible");
|
||||
}
|
||||
if (descriptor->api == nullptr ||
|
||||
descriptor->api->struct_size < sizeof(echoion_module_api_v1) ||
|
||||
descriptor->api->abi_version != ECHOION_MODULE_ABI_VERSION ||
|
||||
descriptor->api->create == nullptr ||
|
||||
descriptor->api->destroy == nullptr ||
|
||||
descriptor->api->activate == nullptr ||
|
||||
descriptor->api->quiesce == nullptr ||
|
||||
descriptor->api->checkpoint == nullptr ||
|
||||
descriptor->api->restore == nullptr ||
|
||||
descriptor->api->readiness == nullptr ||
|
||||
descriptor->api->deactivate == nullptr) {
|
||||
return reject("stable module function table is incomplete");
|
||||
}
|
||||
if (descriptor->dependency_count > maximumDependencies ||
|
||||
(descriptor->dependency_count != 0U &&
|
||||
descriptor->dependencies == nullptr)) {
|
||||
return reject("stable module dependency table is invalid");
|
||||
}
|
||||
|
||||
bool apiCompatible = false;
|
||||
bool coreCompatible = false;
|
||||
for (std::size_t index = 0; index < descriptor->dependency_count;
|
||||
++index) {
|
||||
const auto& dependency = descriptor->dependencies[index];
|
||||
if (dependency.struct_size < sizeof(echoion_module_dependency_v1) ||
|
||||
!valid(dependency.component_id) ||
|
||||
!valid(dependency.abi_hash)) {
|
||||
return reject("stable module dependency entry is invalid");
|
||||
}
|
||||
const auto component = view(dependency.component_id);
|
||||
const auto abiHash = view(dependency.abi_hash);
|
||||
if (component == "EchoionApi" && dependency.optional == 0U) {
|
||||
apiCompatible = abiHash == CoreModule::apiAbiHash;
|
||||
}
|
||||
if (component == "EchoionCore" && dependency.optional == 0U) {
|
||||
coreCompatible = abiHash == CoreModule::coreAbiHash;
|
||||
}
|
||||
}
|
||||
if (!apiCompatible || !coreCompatible) {
|
||||
return reject("plugin was built for incompatible Echoion APIs");
|
||||
}
|
||||
return {.compatible = true, .reason = {}};
|
||||
}
|
||||
|
||||
PluginCompatibility
|
||||
checkExtensionCandidate(const Void::Plugin::PluginHandle& candidate)
|
||||
{
|
||||
const auto symbol =
|
||||
candidate.raw_symbol(ECHOION_MODULE_ABI_QUERY_SYMBOL);
|
||||
if (symbol == nullptr) {
|
||||
return reject("stable module query symbol is missing");
|
||||
}
|
||||
const auto query =
|
||||
reinterpret_cast<echoion_module_abi_query_fn_v1>(symbol);
|
||||
try {
|
||||
return checkExtensionDescriptor(query());
|
||||
} catch (const std::exception& error) {
|
||||
return reject(std::string{"stable module query threw: "} +
|
||||
error.what());
|
||||
} catch (...) {
|
||||
return reject("stable module query threw");
|
||||
}
|
||||
}
|
||||
} // namespace Echoion::Core::Detail
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <echoion/api/module/ModuleAbi.h>
|
||||
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Core::Detail
|
||||
{
|
||||
struct PluginCompatibility {
|
||||
bool compatible{};
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
[[nodiscard]] PluginCompatibility checkExtensionDescriptor(
|
||||
const echoion_module_descriptor_v1* descriptor);
|
||||
[[nodiscard]] PluginCompatibility
|
||||
checkExtensionCandidate(const Void::Plugin::PluginHandle& candidate);
|
||||
} // namespace Echoion::Core::Detail
|
||||
+1141
File diff suppressed because it is too large.
Load diff
+219
-111
@@ -1,4 +1,4 @@
|
||||
#include "echoion/core/Logger.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include "echoion/core/RpcServer.hpp"
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Data/Reflect.hpp>
|
||||
@@ -22,6 +22,10 @@ namespace Echoion::Core
|
||||
port_ = port;
|
||||
|
||||
try {
|
||||
// A prior stop() left the io_context in the stopped state; reset
|
||||
// it so acceptLoop()'s run() actually processes work.
|
||||
ioContext_.restart();
|
||||
|
||||
asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
|
||||
acceptor_.emplace(ioContext_);
|
||||
acceptor_->open(endpoint.protocol());
|
||||
@@ -33,7 +37,7 @@ namespace Echoion::Core
|
||||
CLIENT_POOL_SIZE);
|
||||
serverThread_ = std::thread(&RpcServer::acceptLoop, this);
|
||||
|
||||
ECHOION_LOG_INFO(
|
||||
Void::Log::info("RpcServer", "{}",
|
||||
std::format("RPC server started on port {}", port));
|
||||
return {};
|
||||
} catch (const std::exception& e) {
|
||||
@@ -76,18 +80,12 @@ namespace Echoion::Core
|
||||
// ~ThreadPool then joins every worker.
|
||||
clientPool_.reset();
|
||||
|
||||
// Wait for server thread with timeout
|
||||
// The acceptor was cancelled and ioContext_ stopped above, so the
|
||||
// accept loop exits promptly. Join unconditionally: detaching
|
||||
// here let the thread outlive ioContext_ (use-after-free when the
|
||||
// core library unloads).
|
||||
if (serverThread_.joinable()) {
|
||||
// Give it a moment to clean up
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
while (serverThread_.joinable() &&
|
||||
std::chrono::steady_clock::now() - start <
|
||||
std::chrono::seconds(2)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
if (serverThread_.joinable()) {
|
||||
serverThread_.detach(); // Force detach if still running
|
||||
}
|
||||
serverThread_.join();
|
||||
}
|
||||
|
||||
if (acceptor_.has_value()) {
|
||||
@@ -95,101 +93,150 @@ namespace Echoion::Core
|
||||
acceptor_->close(ec);
|
||||
}
|
||||
|
||||
ECHOION_LOG_INFO("RPC server stopped");
|
||||
Void::Log::info("RpcServer", "{}", "RPC server stopped");
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("Error stopping RPC server: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::acceptLoop()
|
||||
{
|
||||
ECHOION_LOG_INFO("RPC server accept loop started");
|
||||
while (running_.load()) {
|
||||
Void::Log::info("RpcServer", "{}", "RPC server accept loop started");
|
||||
|
||||
// Arm the first async accept, then let the io_context drive re-arming
|
||||
// from the completion handler. This model is cleanly interruptible:
|
||||
// stop() cancels the acceptor (the pending accept completes with
|
||||
// operation_aborted and does not re-arm) and calls ioContext_.stop(),
|
||||
// so run() returns promptly. A blocking synchronous accept, by
|
||||
// contrast, cannot be reliably woken from another thread on Linux.
|
||||
doAccept();
|
||||
|
||||
for (;;) {
|
||||
try {
|
||||
asio::ip::tcp::socket socket(ioContext_);
|
||||
ECHOION_LOG_DEBUG("RPC server waiting for connection...");
|
||||
|
||||
// Use async accept with cancellation support
|
||||
std::atomic<bool> acceptComplete{false};
|
||||
boost::system::error_code acceptEc;
|
||||
|
||||
acceptor_->async_accept(
|
||||
socket, [&](const boost::system::error_code& ec) {
|
||||
acceptEc = ec;
|
||||
acceptComplete = true;
|
||||
});
|
||||
|
||||
// Poll until accept completes or we're stopped
|
||||
while (!acceptComplete.load() && running_.load()) {
|
||||
ioContext_.poll_one();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
|
||||
// Cancel pending operation if we're stopping
|
||||
if (!running_.load()) {
|
||||
acceptor_->cancel();
|
||||
break;
|
||||
}
|
||||
|
||||
if (acceptEc) {
|
||||
throw std::runtime_error(acceptEc.message());
|
||||
}
|
||||
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC server accepted TCP connection from {}:{}",
|
||||
socket.remote_endpoint().address().to_string(),
|
||||
socket.remote_endpoint().port()));
|
||||
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(socket));
|
||||
ws->accept();
|
||||
ECHOION_LOG_DEBUG("RPC server WebSocket handshake completed");
|
||||
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
}
|
||||
|
||||
ECHOION_LOG_DEBUG(
|
||||
std::format("RPC client {} connected", clientId));
|
||||
|
||||
// Handle the client on the worker pool (drained/joined by
|
||||
// ~ThreadPool on stop).
|
||||
if (clientPool_) {
|
||||
clientPool_->submit([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
// Cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_.erase(clientId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
ECHOION_LOG_DEBUG(std::format(
|
||||
"RPC client {} disconnected", clientId));
|
||||
});
|
||||
}
|
||||
|
||||
ioContext_.run();
|
||||
break; // returned normally: acceptor cancelled, no more work
|
||||
} catch (const std::exception& e) {
|
||||
// If we're shutting down, exit gracefully
|
||||
// A handler threw (should not happen: the accept path uses
|
||||
// error_code overloads). Never re-arm into a tight spin --
|
||||
// bail if we're stopping, otherwise resume the event loop.
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("RPC accept loop error: {}", e.what()));
|
||||
if (!running_.load()) {
|
||||
break;
|
||||
}
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("RPC accept error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
ECHOION_LOG_INFO("RPC server accept loop stopped");
|
||||
Void::Log::info("RpcServer", "{}", "RPC server accept loop stopped");
|
||||
}
|
||||
|
||||
void RpcServer::doAccept()
|
||||
{
|
||||
auto socket = std::make_shared<asio::ip::tcp::socket>(ioContext_);
|
||||
acceptor_->async_accept(
|
||||
*socket,
|
||||
[this, socket](const boost::system::error_code& ec) {
|
||||
// Cancelled by stop(): tear-down, do not re-arm.
|
||||
if (ec == asio::error::operation_aborted ||
|
||||
!running_.load()) {
|
||||
return;
|
||||
}
|
||||
if (ec) {
|
||||
// Transient accept error (peer vanished mid-handshake,
|
||||
// fd pressure, ...). Log once and re-arm -- the loop is
|
||||
// event-driven, so this cannot busy-spin the way the old
|
||||
// run_one() loop did.
|
||||
Void::Log::warn("RpcServer", "{}",
|
||||
std::format("RPC accept failed: {}", ec.message()));
|
||||
} else {
|
||||
onAccept(std::move(*socket));
|
||||
}
|
||||
if (running_.load()) {
|
||||
doAccept();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void RpcServer::onAccept(asio::ip::tcp::socket socket)
|
||||
{
|
||||
// Non-throwing remote_endpoint: on a torn-down socket this would
|
||||
// otherwise throw "Bad file descriptor" -- the original spam source.
|
||||
boost::system::error_code epc;
|
||||
std::string peerAddress;
|
||||
bool peerIsLoopback = false;
|
||||
if (auto ep = socket.remote_endpoint(epc); !epc) {
|
||||
peerAddress = ep.address().to_string();
|
||||
peerIsLoopback = ep.address().is_loopback();
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("RPC server accepted TCP connection from {}:{}",
|
||||
peerAddress, ep.port()));
|
||||
}
|
||||
|
||||
auto ws =
|
||||
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
|
||||
std::move(socket));
|
||||
|
||||
// Read the upgrade request explicitly so handshake headers are
|
||||
// visible: the web server's /rpc bridge forwards the browser's real
|
||||
// address in X-Echoion-Client-Ip (trusted from loopback only).
|
||||
beast::error_code wsEc;
|
||||
beast::flat_buffer handshakeBuffer;
|
||||
beast::http::request<beast::http::string_body> upgradeReq;
|
||||
beast::http::read(ws->next_layer(), handshakeBuffer, upgradeReq, wsEc);
|
||||
if (wsEc || !websocket::is_upgrade(upgradeReq)) {
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("WebSocket handshake failed: {}",
|
||||
wsEc ? wsEc.message() : "not an upgrade"));
|
||||
return;
|
||||
}
|
||||
std::string clientAddress = peerAddress;
|
||||
if (peerIsLoopback) {
|
||||
if (auto fwd = upgradeReq.find("X-Echoion-Client-Ip");
|
||||
fwd != upgradeReq.end() && !fwd->value().empty()) {
|
||||
clientAddress = std::string(fwd->value());
|
||||
}
|
||||
}
|
||||
|
||||
// error_code overload: a failed handshake is a normal client-side
|
||||
// event, not an "RPC accept error".
|
||||
ws->accept(upgradeReq, wsEc);
|
||||
if (wsEc) {
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("WebSocket handshake failed: {}", wsEc.message()));
|
||||
return;
|
||||
}
|
||||
Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed");
|
||||
|
||||
uint64_t clientId = nextClientId_++;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_[clientId] = ws;
|
||||
clientAddresses_[clientId] = clientAddress;
|
||||
}
|
||||
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("RPC client {} connected", clientId));
|
||||
|
||||
// Handle the client on the worker pool (drained/joined by ~ThreadPool
|
||||
// on stop).
|
||||
if (clientPool_) {
|
||||
clientPool_->submit([this, clientId, ws]() {
|
||||
handleClient(ws);
|
||||
|
||||
// Cleanup
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
clients_.erase(clientId);
|
||||
clientAddresses_.erase(clientId);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
authenticatedClients_.erase(clientId);
|
||||
}
|
||||
Void::Log::debug("RpcServer", "{}", std::format(
|
||||
"RPC client {} disconnected", clientId));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void RpcServer::handleClient(
|
||||
@@ -202,12 +249,26 @@ namespace Echoion::Core
|
||||
beast::error_code ec;
|
||||
ws->read(buffer, ec);
|
||||
|
||||
if (ec == websocket::error::closed) {
|
||||
break;
|
||||
}
|
||||
if (ec) {
|
||||
ECHOION_LOG_ERROR(
|
||||
std::format("WebSocket read error: {}", ec.message()));
|
||||
// Browsers reach us through the HttpServer /rpc TCP tunnel;
|
||||
// closing a tab tears the upstream socket down abruptly, so
|
||||
// the read fails with ENOTCONN/eof/reset rather than a clean
|
||||
// WebSocket close frame. These are all normal disconnects —
|
||||
// log them at debug so routine tab churn doesn't spam errors.
|
||||
const bool cleanDisconnect =
|
||||
ec == websocket::error::closed ||
|
||||
ec == asio::error::eof ||
|
||||
ec == asio::error::connection_reset ||
|
||||
ec == asio::error::not_connected ||
|
||||
ec == asio::error::broken_pipe ||
|
||||
ec == asio::error::operation_aborted;
|
||||
if (cleanDisconnect) {
|
||||
Void::Log::debug("RpcServer", "{}",
|
||||
std::format("WebSocket closed: {}", ec.message()));
|
||||
} else {
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("WebSocket read error: {}", ec.message()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -231,7 +292,7 @@ namespace Echoion::Core
|
||||
}
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("Client handling error: {}", e.what()));
|
||||
break;
|
||||
}
|
||||
@@ -261,8 +322,9 @@ namespace Echoion::Core
|
||||
return;
|
||||
}
|
||||
|
||||
// Check authentication (except for Authenticate method)
|
||||
if (request.method != Api::RpcMethod::Authenticate) {
|
||||
// Check authentication (except for the sign-in methods)
|
||||
if (request.method != Api::RpcMethod::Authenticate &&
|
||||
request.method != Api::RpcMethod::AuthenticateByAddress) {
|
||||
if (!isClientAuthenticated(clientId)) {
|
||||
Api::RpcResponse response;
|
||||
response.requestId = request.id;
|
||||
@@ -276,6 +338,18 @@ namespace Echoion::Core
|
||||
}
|
||||
}
|
||||
|
||||
// Record the (authorized) invocation in the bounded audit ring.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(auditMutex_);
|
||||
auditLog_.push_back(AuditEntry{
|
||||
.clientId = clientId,
|
||||
.method = static_cast<int>(request.method),
|
||||
.timestamp = std::chrono::system_clock::now()});
|
||||
if (auditLog_.size() > MAX_AUDIT_ENTRIES) {
|
||||
auditLog_.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
// Find handler
|
||||
std::string methodName =
|
||||
std::to_string(static_cast<int>(request.method));
|
||||
@@ -299,11 +373,16 @@ namespace Echoion::Core
|
||||
response.result = *result;
|
||||
} else {
|
||||
response.success = false;
|
||||
response.error = std::format(
|
||||
"{{\"code\":{},\"message\":\"{}\",\"source\":\"{}\"}}",
|
||||
static_cast<uint32_t>(result.error().code),
|
||||
result.error().message,
|
||||
result.error().source);
|
||||
// Error text can include quoted TeamSpeak permission names
|
||||
// or other protocol detail. Serialize it as JSON instead of
|
||||
// interpolating it into JSON syntax so the browser always
|
||||
// receives a decodable error.
|
||||
response.error = Void::Json::serialize(Void::Json::object(
|
||||
{{"code", Void::Json::Value{static_cast<long long>(
|
||||
result.error().code)}},
|
||||
{"message", Void::Json::Value{result.error().message}},
|
||||
{"source",
|
||||
Void::Json::Value{result.error().source}}}));
|
||||
}
|
||||
} else {
|
||||
response.success = false;
|
||||
@@ -314,7 +393,7 @@ namespace Echoion::Core
|
||||
sendResponse(clientId, response);
|
||||
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("Message processing error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
@@ -333,7 +412,7 @@ namespace Echoion::Core
|
||||
Void::Json::serialize(Void::Json::to_json(response));
|
||||
it->second->write(asio::buffer(json));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(std::format("Send response error: {}", e.what()));
|
||||
Void::Log::error("RpcServer", "{}", std::format("Send response error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,7 +430,7 @@ namespace Echoion::Core
|
||||
Void::Json::serialize(Void::Json::to_json(notification));
|
||||
it->second->write(asio::buffer(json));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("Send notification error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
@@ -372,7 +451,7 @@ namespace Echoion::Core
|
||||
Void::Json::to_json(notification));
|
||||
ws->write(asio::buffer(json));
|
||||
} catch (const std::exception& e) {
|
||||
ECHOION_LOG_ERROR(
|
||||
Void::Log::error("RpcServer", "{}",
|
||||
std::format("Broadcast error: {}", e.what()));
|
||||
}
|
||||
}
|
||||
@@ -402,6 +481,24 @@ namespace Echoion::Core
|
||||
handlers_.erase(method);
|
||||
}
|
||||
|
||||
std::vector<RpcServer::AuditEntry> RpcServer::getAuditLog() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(auditMutex_);
|
||||
return {auditLog_.begin(), auditLog_.end()};
|
||||
}
|
||||
|
||||
size_t RpcServer::getClientCount() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
return clients_.size();
|
||||
}
|
||||
|
||||
std::chrono::seconds RpcServer::getUptime() const
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::seconds>(
|
||||
std::chrono::steady_clock::now() - startTime_);
|
||||
}
|
||||
|
||||
void RpcServer::setAuthToken(const std::string& token)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(authMutex_);
|
||||
@@ -432,4 +529,15 @@ namespace Echoion::Core
|
||||
return authenticatedClients_.contains(clientId);
|
||||
}
|
||||
|
||||
std::optional<std::string>
|
||||
RpcServer::getClientAddress(uint64_t clientId) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(clientsMutex_);
|
||||
auto it = clientAddresses_.find(clientId);
|
||||
if (it == clientAddresses_.end() || it->second.empty()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user