16 Commits
Author SHA1 Message Date
faumaray c2ec314eb9 Reject incompatible managed plugins before activation
Independent component release / publish (push) Failing after 8s
2026-08-01 18:00:04 +03:00
faumaray 16d9a667eb Use shared Gitea artifact registry
Independent component release / publish (push) Failing after 7s
2026-07-29 23:43:44 +03:00
faumaray d456257d0c Support CMake 4.0 SQLite target 2026-07-29 23:31:30 +03:00
faumaray cbb178d83d Avoid interactive SSH during release checkout 2026-07-29 23:11:54 +03:00
faumaray 29c7e60733 Export stable C ABI and add component releases 2026-07-29 22:40:35 +03:00
faumaray 4b6f3165b2 Core: expose component update transactions 2026-07-29 00:33:52 +03:00
faumaray b08f8ad29b Core: publish reloadable module descriptor 2026-07-28 23:32:32 +03:00
faumaray 915e2ab981 Core: build independently at 2.0.0 2026-07-28 23:18:08 +03:00
faumaray 9637f1eef7 Core: add configurable startup log rotation 2026-07-28 21:10:09 +03:00
faumaray a277f2102b Core: finalize plugin services after discovery 2026-07-26 18:11:00 +03:00
faumaray dfbbdaaf01 Sources: use standalone yt-dlp releases 2026-07-26 16:44:25 +03:00
faumaray 7975f2b38e update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:44:42 +03:00
faumaray 9f06af6c80 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-16 19:59:45 +03:00
faumaray 39aff68d8d Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:49:57 +03:00
faumaray 01362d2e51 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-12 02:56:29 +03:00
faumaray 5c036d91fb making WEB
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 00:45:17 +03:00
101 changed files with 10255 additions and 1902 deletions

No files matched your search

+55
View File
@@ -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
+113 -6
View File
@@ -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(
@@ -110,13 +148,19 @@ 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
@@ -131,6 +175,7 @@ target_link_libraries(EchoionCore
Void::Net
Void::Sqlite
Void::Service
Void::ShortUrl
Void::Plugin
PRIVATE
Threads::Threads
@@ -149,6 +194,21 @@ 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.
@@ -199,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(
@@ -219,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)
+15
View File
@@ -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"
}
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"schemaVersion": 1,
"componentId": "EchoionCore",
"productCompatibility": ">=2.0.0 <3.0.0",
"publishNightly": true,
"cmakeOptions": {}
}
+23
View File
@@ -67,9 +67,26 @@ namespace Echoion::Core
// 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();
// 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.
@@ -100,6 +117,9 @@ namespace Echoion::Core
// 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
@@ -116,6 +136,9 @@ namespace Echoion::Core
// 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};
+49 -1
View File
@@ -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_;
+9 -1
View File
@@ -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);
};
+80 -5
View File
@@ -2,23 +2,31 @@
#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
{
@@ -27,6 +35,8 @@ namespace Void::Logging
namespace Echoion::Core
{
class PluginHost;
class TeamSpeakDirectoryService;
// Main Core implementation of ICoreInterface
class Core : public Api::ICoreInterface
@@ -126,6 +136,8 @@ namespace Echoion::Core
void setAudioDataCallback(
const MusicManager::AudioDataCallback& callback);
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);
@@ -154,21 +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();
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
@@ -176,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
+15
View File
@@ -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
+76
View File
@@ -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
+67 -5
View File
@@ -4,6 +4,7 @@
#include "NetworkClient.hpp"
#include "PlaylistLoader.hpp"
#include "RpcTypes.hpp"
#include "Socks5HttpBridge.hpp"
#include "SubscriptionManager.hpp"
#include "SubscriptionService.hpp"
#include "TrackCache.hpp"
@@ -79,7 +80,15 @@ namespace Echoion::Core
// 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.
@@ -100,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);
@@ -134,7 +158,7 @@ namespace Echoion::Core
[[nodiscard]] std::chrono::milliseconds getPlaybackPosition() const;
// Which catalog(s) a text search targets.
enum class SearchScope { All, YouTube, Yandex };
enum class SearchScope { All, YouTube, Yandex, SoundCloud };
[[nodiscard]] Api::Result<Api::SearchResult>
search(const std::string& query,
@@ -158,6 +182,17 @@ namespace Echoion::Core
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;
@@ -278,6 +313,17 @@ namespace Echoion::Core
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;
@@ -309,9 +355,13 @@ namespace Echoion::Core
downloadAudioForPlayback(const Api::TrackInfo& track);
void cleanupTempFile(const std::string& filepath);
// True when a SOCKS5 proxy is configured: ffmpeg cannot route
// IP-locked googlevideo URLs through it, so those are downloaded.
[[nodiscard]] bool socksProxyActive() const;
// 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 -----------------------------------------------------
@@ -342,6 +392,14 @@ namespace Echoion::Core
QueueService queue_;
std::unique_ptr<TrackCache> trackCache_;
// 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;
// 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
@@ -364,6 +422,10 @@ namespace Echoion::Core
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)
+111
View File
@@ -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
+139 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include <TrackTypes.hpp>
#include <ExtensionPlugin.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Data/Reflect.hpp>
#include <cstdint>
@@ -73,10 +74,18 @@ namespace Echoion::Core::Dto
};
struct ManageUsersRequest {
std::string action; // "list" | "remove"
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 {
@@ -88,6 +97,9 @@ namespace Echoion::Core::Dto
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)
@@ -104,7 +116,28 @@ namespace Echoion::Core::Dto
.thumbnailUrl = t.thumbnailUrl,
.url = t.originalUrl.empty()
? std::nullopt
: std::optional(t.originalUrl)};
: 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 {
@@ -127,6 +160,12 @@ namespace Echoion::Core::Dto
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 {
@@ -143,6 +182,32 @@ namespace Echoion::Core::Dto
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;
@@ -192,6 +257,13 @@ namespace Echoion::Core::Dto
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 {
@@ -207,12 +279,77 @@ namespace Echoion::Core::Dto
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 {
+12
View File
@@ -13,6 +13,7 @@
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <set>
#include <thread>
#include <unordered_map>
@@ -53,6 +54,13 @@ 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;
@@ -74,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);
@@ -93,6 +103,8 @@ namespace Echoion::Core
uint64_t,
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
clients_;
// clientId -> effective network address (see getClientAddress).
std::unordered_map<uint64_t, std::string> clientAddresses_;
mutable std::mutex clientsMutex_;
std::atomic<uint64_t> nextClientId_{1};
+90
View File
@@ -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
+9 -3
View File
@@ -81,10 +81,16 @@ namespace Echoion::Core
[[nodiscard]] std::vector<SubscriptionManager::Subscriber>
getSubscribers() const;
// Presence events from the plugin. onClientConnected returns true
// when a subscribed user came online and playback should
// 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.
bool onClientConnected(uint64_t clientId);
struct ClientConnectResult {
std::optional<std::string> subscribedUid;
bool mayAutoStart = false;
};
ClientConnectResult onClientConnected(uint64_t clientId);
void onClientDisconnected(uint64_t clientId);
private:
@@ -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
+23 -36
View File
@@ -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
+30 -6
View File
@@ -49,12 +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);
@@ -89,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>
@@ -106,7 +118,6 @@ 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
@@ -141,6 +152,14 @@ 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().
@@ -156,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,
@@ -189,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
+10 -12
View File
@@ -50,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)
@@ -62,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);
@@ -93,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;
@@ -135,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";
@@ -20,17 +20,18 @@ namespace Echoion::Core
{
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: {}announce <message>", ctx.prefix));
ctx.reply(
ctx.trf("Usage: {}announce <message>", ctx.prefix));
return;
}
const size_t reached = manager->setAnnouncement(ctx.args);
ctx.reply(std::format(
ctx.reply(ctx.trf(
"Announcement saved and delivered to {} online "
"subscriber(s). Offline subscribers get it on their "
"next connect.",
@@ -23,8 +23,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;
}
@@ -32,7 +32,8 @@ namespace Echoion::Core
std::string arg(ctx.args);
std::transform(arg.begin(), arg.end(), arg.begin(),
[](unsigned char c) {
return static_cast<char>(std::tolower(c));
return static_cast<char>(
std::tolower(c));
});
if (arg == "on" || arg == "true" || arg == "1" ||
arg == "enable") {
@@ -45,17 +46,19 @@ namespace Echoion::Core
manager->setAutoplay(enable);
if (enable) {
ctx.reply(
ctx.reply(ctx.tr(
"\xf0\x9f\x93\xbb Autoplay is ON \xe2\x80\x94 I'll "
"keep the music going with related tracks.");
"keep the music going with related tracks."));
} else {
ctx.reply("\xf0\x9f\x93\xbb Autoplay is OFF.");
ctx.reply(ctx.tr("\xf0\x9f\x93\xbb Autoplay is OFF."));
}
} catch (const std::exception& e) {
Void::Log::error("AutoplayCommand", "{}",
Void::Log::error(
"AutoplayCommand", "{}",
std::format("Autoplay command exception: {}",
e.what()));
ctx.reply("Something went wrong. Please try again.");
ctx.reply(
ctx.tr("Something went wrong. Please try again."));
}
}
+12 -10
View File
@@ -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) {
Void::Log::error("ClearCommand", "{}",
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) {
Void::Log::error("ClearCommand", "{}",
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."));
}
}
+78 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "echoion/core/MusicManager.hpp"
#include "echoion/core/i18n/Localization.hpp"
#include <ConfigTypes.hpp>
#include <Types.hpp>
#include <Void/Service/Registry.hpp>
@@ -93,7 +94,7 @@ namespace Echoion::Core
return escapeMarkdown(text);
}
// The best public link for a track: the shortened faumaray link when
// 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.
@@ -136,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
@@ -147,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>
@@ -156,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.
*/
@@ -200,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>;
+10 -6
View File
@@ -5,6 +5,10 @@
#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"
@@ -21,18 +25,18 @@
#include "SeekCommand.hpp"
#include "SelectCommand.hpp"
#include "ShuffleCommand.hpp"
#include "FavoriteCommand.hpp"
#include "HistoryCommand.hpp"
#include "SkipCommand.hpp"
#include "SoundCloudPlayCommand.hpp"
#include "SoundCloudSearchCommand.hpp"
#include "StatsCommand.hpp"
#include "StopCommand.hpp"
#include "YandexPlayCommand.hpp"
#include "YandexSearchCommand.hpp"
#include "YoutubePlayCommand.hpp"
#include "YoutubeSearchCommand.hpp"
#include "SubscribeCommand.hpp"
#include "SubscribersCommand.hpp"
#include "UnsubscribeAllCommand.hpp"
#include "UnsubscribeCommand.hpp"
#include "UnsubscribeIdCommand.hpp"
#include "VolumeCommand.hpp"
#include "YandexPlayCommand.hpp"
#include "YandexSearchCommand.hpp"
#include "YoutubePlayCommand.hpp"
#include "YoutubeSearchCommand.hpp"
@@ -22,13 +22,13 @@ namespace Echoion::Core
auto manager = ctx.musicManager.lock();
auto db = ctx.service<Api::Database>();
if (!manager || !db) {
ctx.reply("Favorites are unavailable.");
ctx.reply(ctx.tr("Favorites are unavailable."));
return;
}
auto uid = manager->clientUid(ctx.clientId);
if (!uid) {
ctx.reply("Couldn't identify you on the server.");
ctx.reply(ctx.tr("Couldn't identify you on the server."));
return;
}
const uint64_t userKey = fnv1a(*uid);
@@ -44,7 +44,7 @@ namespace Echoion::Core
} else if (sub == "remove" || sub == "rm") {
removeFavorite(ctx, *db, userKey, rest);
} else {
ctx.reply(std::format(
ctx.reply(ctx.trf(
"Usage: {}fav add | list | play <n> | remove <n>",
ctx.prefix));
}
@@ -117,11 +117,11 @@ namespace Echoion::Core
{
auto favorites = db.getFavorites(userKey);
if (!favorites) {
ctx.reply("Couldn't read your favorites.");
ctx.reply(ctx.tr("Couldn't read your favorites."));
return;
}
if (favorites->empty()) {
ctx.reply(std::format(
ctx.reply(ctx.trf(
"You have no favorites yet. Save the current track "
"with {}fav add",
ctx.prefix));
@@ -130,8 +130,8 @@ namespace Echoion::Core
std::string msg = "Your favorites:";
size_t index = 1;
for (const auto& fav : *favorites) {
msg += std::format("\n{}. {}", index++,
trackLink(fav.track));
msg +=
std::format("\n{}. {}", index++, trackLink(fav.track));
}
ctx.reply(msg);
}
@@ -142,15 +142,14 @@ namespace Echoion::Core
{
auto current = manager.getCurrentTrack();
if (!current || !current->has_value()) {
ctx.reply("Nothing is playing right now.");
ctx.reply(ctx.tr("Nothing is playing right now."));
return;
}
const auto& track = (*current)->track;
if (db.addFavorite(userKey, track)) {
ctx.reply(std::format("Added to favorites: {}",
track.title));
ctx.reply(ctx.trf("Added to favorites: {}", track.title));
} else {
ctx.reply("Couldn't save the favorite.");
ctx.reply(ctx.tr("Couldn't save the favorite."));
}
}
@@ -160,22 +159,22 @@ namespace Echoion::Core
{
auto index = parseIndex(arg);
if (!index) {
ctx.reply("Usage: fav play <number> (see fav list)");
ctx.reply(
ctx.tr("Usage: fav play <number> (see fav list)"));
return;
}
auto favorites = db.getFavorites(userKey);
if (!favorites || *index > favorites->size()) {
ctx.reply("No favorite with that number.");
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);
auto result = manager.play(track.originalUrl, ctx.clientId);
if (result) {
ctx.reply(*result);
} else {
ctx.reply(std::format("Couldn't play it: {}",
result.error().message));
ctx.reply(ctx.trf("Couldn't play it: {}",
result.error().message));
}
}
@@ -185,20 +184,21 @@ namespace Echoion::Core
{
auto index = parseIndex(arg);
if (!index) {
ctx.reply("Usage: fav remove <number> (see fav list)");
ctx.reply(
ctx.tr("Usage: fav remove <number> (see fav list)"));
return;
}
auto favorites = db.getFavorites(userKey);
if (!favorites || *index > favorites->size()) {
ctx.reply("No favorite with that number.");
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(std::format("Removed from favorites: {}",
fav.track.title));
ctx.reply(
ctx.trf("Removed from favorites: {}", fav.track.title));
} else {
ctx.reply("Couldn't remove the favorite.");
ctx.reply(ctx.tr("Couldn't remove the favorite."));
}
}
};
@@ -18,7 +18,7 @@ namespace Echoion::Core
{
auto db = ctx.service<Api::Database>();
if (!db) {
ctx.reply("History is unavailable (no database).");
ctx.reply(ctx.tr("History is unavailable (no database)."));
return;
}
@@ -35,11 +35,11 @@ namespace Echoion::Core
auto recent = db->getRecentlyPlayed(0, limit);
if (!recent) {
ctx.reply("Couldn't read the playback history.");
ctx.reply(ctx.tr("Couldn't read the playback history."));
return;
}
if (recent->empty()) {
ctx.reply("Nothing has been played yet.");
ctx.reply(ctx.tr("Nothing has been played yet."));
return;
}
@@ -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
+23 -16
View File
@@ -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) {
Void::Log::error("MoveCommand", "{}",
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) {
Void::Log::error("MoveCommand", "{}",
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."));
}
}
@@ -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) {
Void::Log::error("NowPlayingCommand", "{}",
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;
}
@@ -70,11 +72,21 @@ namespace Echoion::Core
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) {
Void::Log::error("NowPlayingCommand", "{}", 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."));
}
}
@@ -92,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
+13 -11
View File
@@ -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) {
Void::Log::error("PauseCommand", "{}",
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) {
Void::Log::error("PauseCommand", "{}",
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."));
}
}
+43 -31
View File
@@ -22,16 +22,17 @@ 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(std::format(
"Usage: {} <url or search query>\nExample: {} never "
"gonna give you up",
label(), label()));
ctx.reply(ctx.trf("Usage: {} <url or search "
"query>\nExample: {} never "
"gonna give you up",
label(), label()));
return;
}
@@ -39,50 +40,57 @@ namespace Echoion::Core
if (ctx.args.find("http") == 0) {
auto result = manager->play(ctx.args, ctx.clientId);
if (!result) {
Void::Log::error("PlayCommand", "{}",
std::format("Play URL failed '{}': {}", ctx.args,
result.error().message));
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;
}
ctx.reply(std::format("Added to queue: {}", *result));
ctx.reply(ctx.trf("Added to queue: {}", *result));
return;
}
// Otherwise, search the chosen catalog(s).
auto searchResult = manager->search(ctx.args, scope());
if (!searchResult) {
Void::Log::error("PlayCommand", "{}",
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;
}
@@ -92,11 +100,12 @@ namespace Echoion::Core
auto playResult =
manager->queueTrack(track, ctx.clientId);
if (!playResult) {
Void::Log::error("PlayCommand", "{}",
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;
}
@@ -105,7 +114,7 @@ namespace Echoion::Core
displayText = std::format("{} by {}", track.title,
track.artist);
}
ctx.reply(std::format(
ctx.reply(ctx.trf(
"Added to queue: {}",
markdownLink(displayText, trackLinkUrl(track))));
return;
@@ -115,9 +124,10 @@ namespace Echoion::Core
manager->storePendingSearch(ctx.clientId,
searchResult->tracks);
std::string msg = std::format(
"Multiple results \xe2\x80\x94 use {}select <number>:\n\n",
ctx.prefix);
std::string msg =
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) {
const auto& track = searchResult->tracks[i];
@@ -139,10 +149,12 @@ namespace Echoion::Core
ctx.reply(msg);
} catch (const std::exception& e) {
Void::Log::error("PlayCommand", "{}",
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."));
}
}
@@ -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) {
Void::Log::error("PlaylistCommand", "{}",
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) {
Void::Log::error("PlaylistCommand", "{}",
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) {
Void::Log::error("PlaylistCommand", "{}", 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."));
}
}
+35 -58
View File
@@ -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) {
Void::Log::error("QueueCommand", "{}", 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;
}
@@ -64,9 +65,16 @@ 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();
@@ -94,21 +102,20 @@ namespace Echoion::Core
displayText = std::format(
"{} by {}", trackInfo.title, trackInfo.artist);
}
msg << std::format(
msg << ctx.trf(
"\n**Now Playing:** {}{}\n",
markdownLink(displayText,
trackLinkUrl(trackInfo)),
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;
@@ -118,52 +125,38 @@ namespace Echoion::Core
std::format("{} by {}", trackInfo.title,
trackInfo.artist);
}
msg << std::format(
msg << ctx.trf(
"{}. {}", i + 1,
markdownLink(displayText,
trackLinkUrl(trackInfo)));
if (trackInfo.duration.has_value()) {
msg << std::format(
msg << ctx.trf(
" {} {}", kDot,
formatDuration(*trackInfo.duration));
}
if (!entry.addedBy.empty()) {
msg << std::format(
" (by {})", escapeMarkdown(entry.addedBy));
msg << ctx.trf(" (by {})",
escapeMarkdown(entry.addedBy));
}
msg << "\n";
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) {
Void::Log::error("QueueCommand", "{}",
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
@@ -22,15 +22,17 @@ namespace Echoion::Core
if (auto core = ctx.service<Api::ICoreInterface>()) {
auto result = core->reloadConfig();
if (result) {
ctx.reply("✅ Configuration reloaded. For a full core "
"reload, use the TS plugin menu.");
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("Reload is handled by the plugin. Use the TS "
"plugin menu to reload the core.");
ctx.reply(
ctx.tr("Reload is handled by the plugin. Use the TS "
"plugin menu to reload the core."));
}
}
@@ -17,21 +17,27 @@ namespace Echoion::Core
try {
auto core = ctx.service<Api::ICoreInterface>();
if (!core) {
ctx.reply("Config reload is unavailable right now.");
ctx.reply(
ctx.tr("Config reload is unavailable right now."));
return;
}
auto result = core->reloadConfig();
if (result) {
ctx.reply("✅ Configuration reloaded from disk.");
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) {
Void::Log::error("ReloadConfigCommand", "{}", 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."));
}
}
+20 -15
View File
@@ -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) {
Void::Log::error("RemoveCommand", "{}",
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) {
Void::Log::error("RemoveCommand", "{}",
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."));
}
}
@@ -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) {
Void::Log::error("RepeatCommand", "{}",
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) {
Void::Log::error("RepeatCommand", "{}",
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."));
}
}
@@ -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) {
Void::Log::error("ResumeCommand", "{}",
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) {
Void::Log::error("ResumeCommand", "{}",
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."));
}
}
+22 -16
View File
@@ -20,34 +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(std::format("Usage: {} <query>", label()));
ctx.reply(ctx.trf("Usage: {} <query>", label()));
return;
}
auto result = manager->search(ctx.args, scope());
if (!result) {
Void::Log::error("SearchCommand", "{}",
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;
}
@@ -55,7 +59,8 @@ namespace Echoion::Core
manager->storePendingSearch(ctx.clientId, result->tracks);
std::stringstream msg;
msg << "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) {
@@ -67,26 +72,27 @@ namespace Echoion::Core
}
// [escaped title](url) · duration (no [] around the
// duration: TeamSpeak parses [..] as a link reference).
msg << std::format(
msg << ctx.trf(
"{}. {}", i + 1,
markdownLink(displayText, trackLinkUrl(track)));
if (track.duration.has_value()) {
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) {
Void::Log::error("SearchCommand", "{}",
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."));
}
}
+23 -18
View File
@@ -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) {
Void::Log::error("SeekCommand", "{}", 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) {
Void::Log::error("SeekCommand", "{}",
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."));
}
}
+24 -17
View File
@@ -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) {
Void::Log::error("SelectCommand", "{}", 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) {
Void::Log::error("SelectCommand", "{}",
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."));
}
}
@@ -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) {
Void::Log::error("ShuffleCommand", "{}",
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."));
}
}
+17 -13
View File
@@ -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) {
Void::Log::error("SkipCommand", "{}", 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) {
Void::Log::error("SkipCommand", "{}",
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
@@ -16,18 +16,18 @@ namespace Echoion::Core
{
auto db = ctx.service<Api::Database>();
if (!db) {
ctx.reply("Statistics are unavailable (no database).");
ctx.reply(
ctx.tr("Statistics are unavailable (no database)."));
return;
}
auto stats = db->getStatistics(0);
if (!stats) {
ctx.reply("Couldn't read playback statistics.");
ctx.reply(ctx.tr("Couldn't read playback statistics."));
return;
}
const auto totalMinutes =
stats->totalPlaytimeMs / 1000 / 60;
const auto totalMinutes = stats->totalPlaytimeMs / 1000 / 60;
std::string msg = std::format(
"\xf0\x9f\x93\x8a Plays: {} {} Unique tracks: {} {} "
"Playtime: {}h {}m",
+12 -8
View File
@@ -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) {
Void::Log::error("StopCommand", "{}", 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) {
Void::Log::error("StopCommand", "{}",
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."));
}
}
@@ -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) {
Void::Log::error("SubscribeCommand", "{}", 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) {
Void::Log::error("SubscribeCommand", "{}", 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 <Void/Log/Log.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) {
Void::Log::error("SubscribersCommand", "{}", 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 <Void/Log/Log.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) {
Void::Log::error("UnsubscribeAllCommand", "{}",
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) {
Void::Log::error("UnsubscribeAllCommand", "{}", 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."));
}
}
@@ -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) {
Void::Log::error("UnsubscribeCommand", "{}", 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) {
Void::Log::error("UnsubscribeCommand", "{}", 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 <Void/Log/Log.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) {
Void::Log::error("UnsubscribeIdCommand", "{}",
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) {
Void::Log::error("UnsubscribeIdCommand", "{}", 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."));
}
}
+19 -14
View File
@@ -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) {
Void::Log::error("VolumeCommand", "{}",
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) {
Void::Log::error("VolumeCommand", "{}",
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,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
@@ -63,9 +63,9 @@ namespace Echoion::Core
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;
virtual void onPlaybackError(
const Api::Error& error,
const std::optional<Api::QueueEntry>& entry) = 0;
};
// Real-time playback engine with gapless track transitions.
@@ -86,9 +86,13 @@ namespace Echoion::Core
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 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
@@ -119,8 +123,8 @@ namespace Echoion::Core
explicit PlaybackEngine(IPlaybackHost& host);
~PlaybackEngine();
Api::Result<void> initialize(
const std::optional<Void::Net::ProxyConfig>& proxy);
Api::Result<void>
initialize(const std::optional<Void::Net::ProxyConfig>& proxy);
void shutdown();
void setProxyConfig(
@@ -171,10 +175,14 @@ namespace Echoion::Core
std::string url;
bool isLocalFile = false;
};
struct CmdStart {};
struct CmdPause {};
struct CmdResume {};
struct CmdStop {};
struct CmdStart {
};
struct CmdPause {
};
struct CmdResume {
};
struct CmdStop {
};
struct CmdSkip {
uint32_t count = 1;
};
@@ -188,8 +196,8 @@ namespace Echoion::Core
bool paused = false;
};
using Command =
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume,
CmdStop, CmdSkip, CmdSeek, CmdRestore>;
std::variant<CmdPlayNow, CmdStart, CmdPause, CmdResume, CmdStop,
CmdSkip, CmdSeek, CmdRestore>;
void post(Command cmd);
@@ -202,10 +210,10 @@ namespace Echoion::Core
struct DecoderSlot {
enum class State {
Idle, // nothing assigned
Idle, // nothing assigned
Resolving, // resolveFuture in flight
Warming, // decoder open, pre-filling its queue
Active, // currently feeding the ring buffer
Active, // currently feeding the ring buffer
};
State state = State::Idle;
@@ -268,7 +276,9 @@ namespace Echoion::Core
void clearFade()
{
fadeTail_.clear();
fadePos_ = 0;
fadeTailPos_ = 0;
fadeEnvPos_ = 0;
fadeIncomingStarved_ = false;
}
// AGC gain for one chunk (updates the internal RMS/gain state).
[[nodiscard]] float agcGainFor(std::size_t samples);
@@ -302,8 +312,15 @@ namespace Echoion::Core
// 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 fadePos_ = 0;
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.
@@ -21,6 +21,7 @@ namespace Echoion::Core
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.
@@ -59,9 +60,9 @@ namespace Echoion::Core
std::chrono::steady_clock::time_point cooldownUntil{};
};
[[nodiscard]] std::vector<SourceState*>
[[nodiscard]] std::vector<std::shared_ptr<ITrackSource>>
candidatesFor(const std::string& query, bool needSearch);
void reportFailure(SourceState& state);
void reportFailure(const std::shared_ptr<ITrackSource>& source);
mutable std::mutex mutex_;
std::vector<std::shared_ptr<ITrackSource>> allSources_;
@@ -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;
+18
View File
@@ -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
+157 -58
View File
@@ -59,9 +59,13 @@ namespace Echoion::Core
"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;
@@ -83,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(
"socks5h://{}:{}@{}:{}", *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,
@@ -111,22 +121,19 @@ 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);
av_dict_set(
&options, "protocol_whitelist",
"file,http,https,tls,tcp,udp,crypto,httpproxy,socks,socks5", 0);
Void::Log::info("AudioDecoder", "{}",
std::format("Using proxy for ffmpeg: {}:{}",
proxyConfig_->host,
proxyConfig_->port));
}
// 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)));
std::format("Opening audio source: {}…", url.substr(0, 80)));
// Allocate format context first (needed for interrupt callback)
formatContext_ = avformat_alloc_context();
@@ -161,7 +168,7 @@ namespace Echoion::Core
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));
}
Void::Log::debug("AudioDecoder", "{}", "avformat_open_input succeeded");
@@ -276,8 +283,7 @@ 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 !=
static_cast<int>(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);
}
@@ -288,13 +294,13 @@ namespace Echoion::Core
}
// 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);
Void::Log::info(
@@ -321,6 +327,7 @@ namespace Echoion::Core
currentUrl_.clear();
currentPositionMs_ = 0;
eof_ = false;
seekRequestMs_ = -1;
shouldExit_ = false; // Reset for next use
}
@@ -352,29 +359,81 @@ namespace Echoion::Core
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_);
currentPositionMs_ = position.count();
// Clear pending audio data
int16Queue_.clear();
// 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
@@ -426,22 +485,64 @@ namespace Echoion::Core
void AudioDecoder::decodeThread()
{
Void::Log::debug("AudioDecoder", "{}", "Decode thread started");
constexpr int maxSamples = 4096;
// 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
}
}
}
@@ -481,8 +582,7 @@ namespace Echoion::Core
if (frame_->pts != AV_NOPTS_VALUE) {
AVRational tb =
formatContext_->streams[audioStreamIndex_]->time_base;
currentPositionMs_ =
frame_->pts * 1000 * tb.num / tb.den;
currentPositionMs_ = frame_->pts * 1000 * tb.num / tb.den;
}
// Convert to S16 and queue. One output buffer holds at most
@@ -496,8 +596,7 @@ namespace Echoion::Core
int inSamples = frame_->nb_samples;
while (true) {
int outSamples = swr_convert(swrContext_, &outputBuffer_,
maxSamples, inData,
inSamples);
maxSamples, inData, inSamples);
inData = nullptr; // input consumed on the first call
inSamples = 0;
if (outSamples <= 0) {
@@ -505,7 +604,8 @@ namespace Echoion::Core
}
const size_t chunkSamples = outSamples * outputChannels_;
std::vector<int16_t> chunk = acquireChunkBuffer(chunkSamples);
std::vector<int16_t> chunk =
acquireChunkBuffer(chunkSamples);
std::memcpy(chunk.data(), outputBuffer_,
chunkSamples * sizeof(int16_t));
@@ -531,8 +631,7 @@ namespace Echoion::Core
break;
}
const uint8_t** inData =
const_cast<const uint8_t**>(frame_->data);
const uint8_t** inData = const_cast<const uint8_t**>(frame_->data);
int inSamples = frame_->nb_samples;
while (true) {
int outSamples = swr_convert(swrContext_, &outputBuffer_,
@@ -576,12 +675,12 @@ namespace Echoion::Core
framesProduced++;
}
eof_ = true;
cv_.notify_all();
Void::Log::info("AudioDecoder", "{}",
std::format("Decode finished. Packets: {}, Frames: {}",
packetsRead, framesProduced));
// 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()
+341 -31
View File
@@ -1,11 +1,16 @@
#include "echoion/core/CommandManager.hpp"
#include <Void/Log/Log.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
@@ -26,11 +31,35 @@ namespace Echoion::Core
auto prefix = manager_.getPrefix();
std::string helpMsg =
"# \xf0\x9f\x8e\xb5 Echoion Bot Help\n\n";
helpMsg += std::format(
"> [!TIP]\n> Prefix is `{}` \xe2\x80\x94 e.g. "
"`{}play lofi`\n\n",
prefix, prefix);
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 =
@@ -71,25 +100,27 @@ namespace Echoion::Core
// Collapsible section per category. TeamSpeak uses the
// markdown-it container syntax ":::details <title>" …
// ":::" (not HTML <details>).
helpMsg += std::format(":::details {} {} Commands\n\n",
categoryEmoji(cat),
toString(cat));
helpMsg += ctx.trf(":::details {} {} Commands\n\n",
categoryEmoji(cat),
ctx.tr(toString(cat)));
for (const auto& [name, cmd] : cmds) {
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);
}
helpMsg +=
std::format("> {}\n", cmd->getDescription());
helpMsg += std::format(
"> {}\n", ctx.tr(cmd->getDescription()));
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]);
@@ -108,9 +139,11 @@ namespace Echoion::Core
ctx.reply(helpMsg);
} catch (const std::exception& e) {
Void::Log::error("CommandManager", "{}",
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."));
}
}
@@ -130,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 ---
@@ -138,6 +259,7 @@ namespace Echoion::Core
{
registerBuiltinCommands();
registerHelpCommand();
registerPageCommands();
startThreadPool();
}
@@ -154,7 +276,8 @@ namespace Echoion::Core
{
pool_ =
std::make_unique<Void::Concurrency::ThreadPool>(THREAD_POOL_SIZE);
Void::Log::info("CommandManager", "{}",
Void::Log::info(
"CommandManager", "{}",
std::format("CommandManager thread pool started with {} workers",
THREAD_POOL_SIZE));
}
@@ -191,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;
{
@@ -204,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) {
Void::Log::error("CommandManager", "{}",
Void::Log::error(
"CommandManager", "{}",
std::format("Async command execution error: {}", e.what()));
try {
task.replyFunc(
@@ -277,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
}
@@ -349,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) {
Void::Log::error("CommandManager", "{}", 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;
@@ -457,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_);
@@ -468,6 +654,7 @@ namespace Echoion::Core
registerCommand<PlayCommand>("play");
registerCommand<YoutubePlayCommand>("pyt");
registerCommand<YandexPlayCommand>("pya");
registerCommand<SoundCloudPlayCommand>("psc");
registerCommand<SelectCommand>("select");
registerCommand<PauseCommand>("pause");
registerCommand<ResumeCommand>("resume");
@@ -484,9 +671,11 @@ namespace Echoion::Core
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");
@@ -499,6 +688,7 @@ namespace Echoion::Core
registerCommand<StatsCommand>("stats");
registerCommand<FavoriteCommand>("fav");
registerCommand<AnnounceCommand>("announce");
registerCommand<LanguageCommand>("language");
}
void CommandManager::registerHelpCommand()
@@ -515,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
+121 -15
View File
@@ -1,13 +1,17 @@
#include <Void/Log/Log.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
{
@@ -17,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,
@@ -60,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())
<< '\n';
return config;
}
@@ -76,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();
Void::Log::info("ConfigLoader", "{}",
Void::Log::info(
"ConfigLoader", "{}",
std::format("Configuration saved to {}", path.string()));
return {};
}
@@ -124,6 +226,10 @@ namespace Echoion::Core
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;
+4 -1
View File
@@ -2,6 +2,7 @@
#include "echoion/core/ConfigLoader.hpp"
#include <format>
#include <iostream>
#include <tuple>
namespace Echoion::Api
{
@@ -94,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();
+1026 -235
View File
File diff suppressed because it is too large. Load diff
+37 -10
View File
@@ -33,9 +33,15 @@ namespace Echoion::Core
// Record playback start in database
if (database_) {
database_->recordPlayback(evt.track, evt.clientId,
std::chrono::milliseconds(0),
false);
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));
}
}
});
@@ -58,7 +64,7 @@ namespace Echoion::Core
});
eventBus_.subscribe<PlaybackStopped>(
[this](const PlaybackStopped& evt) mutable {
[this](const PlaybackStopped&) mutable {
if (rpcServer_) {
rpcServer_->broadcastEvent("playback.stopped", "{}");
}
@@ -85,9 +91,22 @@ namespace Echoion::Core
// Update playback record as completed, keeping the history
// bounded per features.maxHistorySize.
if (database_) {
database_->recordPlayback(evt.track, 0, evt.finalPosition,
true);
database_->trimHistory(config_.features.maxHistorySize);
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));
}
}
});
@@ -146,7 +165,7 @@ namespace Echoion::Core
});
eventBus_.subscribe<QueueCleared>(
[this](const QueueCleared& evt) mutable {
[this](const QueueCleared&) mutable {
if (rpcServer_) {
rpcServer_->broadcastEvent("queue.cleared", "{}");
}
@@ -197,8 +216,16 @@ namespace Echoion::Core
evt.playlistId, evt.playlistId, "Loaded from YouTube",
0, true);
if (result) {
database_->addTrackToPlaylist(result.value(), evt.track,
evt.loadedCount - 1);
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));
}
}
}
});
+1208 -221
View File
File diff suppressed because it is too large. Load diff
+313 -9
View File
@@ -2,6 +2,7 @@
#include <Void/Log/Log.hpp>
#include <Void/Math/Random.hpp>
#include <Void/Sqlite/Sqlite.hpp>
#include <algorithm>
#include <cstring>
#include <format>
#include <shared_mutex>
@@ -312,7 +313,101 @@ namespace Echoion::Api
"Database migration 6 applied: track_short_url columns added");
}
impl_->version = 6;
// Migration 7: aggregate-stats support — skip tracking on history and
// a queue-addition log (daily counters + top requesters for the web
// dashboard).
if (currentVersion < 7) {
const char* migration7 = R"(
ALTER TABLE playback_history ADD COLUMN skipped INTEGER DEFAULT 0;
CREATE TABLE IF NOT EXISTS queue_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid TEXT,
nickname TEXT,
added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_queue_log_date ON queue_log(added_at);
)";
if (auto r = impl_->voidDb.exec(migration7); !r) {
return fail(ErrorCode::DatabaseError, r.error().message());
}
[[maybe_unused]] auto ins = impl_->voidDb.exec(
"INSERT INTO schema_migrations (version) VALUES (7)");
Void::Log::info("Database", "{}",
"Database migration 7 applied: skip tracking and queue log");
}
// Migration 8: persist track thumbnails with history and favorites so
// the web UI can show original artwork for reconstructed tracks
// (playlist_tracks already stores track_thumbnail since v1).
if (currentVersion < 8) {
const char* migration8 = R"(
ALTER TABLE playback_history ADD COLUMN track_thumbnail TEXT;
ALTER TABLE user_favorites ADD COLUMN track_thumbnail TEXT;
)";
if (auto r = impl_->voidDb.exec(migration8); !r) {
return fail(ErrorCode::DatabaseError, r.error().message());
}
[[maybe_unused]] auto ins = impl_->voidDb.exec(
"INSERT INTO schema_migrations (version) VALUES (8)");
Void::Log::info("Database", "{}",
"Database migration 8 applied: track_thumbnail columns added");
}
// Migration 9 belonged to a retired embedded browser feature. Preserve
// its version slot so existing databases and later migrations remain
// compatible, but new Echoion databases no longer create its tables.
if (currentVersion < 9) {
[[maybe_unused]] auto ins = impl_->voidDb.exec(
"INSERT INTO schema_migrations (version) VALUES (9)");
Void::Log::info("Database", "{}", "Database migration 9 retired");
}
// Migration 10: cached TeamSpeak avatars for the web UI, keyed by uid,
// so avatars survive the client going offline/out-of-view.
if (currentVersion < 10) {
const char* migration10 = R"(
CREATE TABLE IF NOT EXISTS cached_avatars (
uid TEXT PRIMARY KEY,
mime TEXT NOT NULL,
data TEXT NOT NULL, -- base64-encoded image bytes
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
)";
if (auto r = impl_->voidDb.exec(migration10); !r) {
return fail(ErrorCode::DatabaseError, r.error().message());
}
[[maybe_unused]] auto ins = impl_->voidDb.exec(
"INSERT INTO schema_migrations (version) VALUES (10)");
Void::Log::info("Database", "{}",
"Database migration 10 applied: cached_avatars table added");
}
// Migration 11: remember the source avatar URL alongside the cached
// bytes, so an offline user's avatar can be re-fetched from it.
if (currentVersion < 11) {
// ADD COLUMN is a no-op-safe schema bump; ignore "duplicate column"
// if a prior partial run already added it.
[[maybe_unused]] auto alt = impl_->voidDb.exec(
"ALTER TABLE cached_avatars ADD COLUMN url TEXT;");
[[maybe_unused]] auto ins = impl_->voidDb.exec(
"INSERT INTO schema_migrations (version) VALUES (11)");
Void::Log::info("Database", "{}",
"Database migration 11 applied: cached_avatars.url added");
}
impl_->version = 11;
return {};
}
@@ -576,8 +671,8 @@ namespace Echoion::Api
const char* sql = R"(
INSERT INTO playback_history
(track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url)
VALUES (?, ?, ?, ?, ?, ?, ?);
(track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url, track_thumbnail)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
)";
auto stmtRes = impl_->voidDb.prepare(sql);
@@ -591,7 +686,53 @@ namespace Echoion::Api
.bind(4, static_cast<std::int64_t>(playedBy))
.bind(5, static_cast<std::int64_t>(duration.count()))
.bind(6, completed ? 1 : 0)
.bind(7, track.shortenedUrl.value_or(""));
.bind(7, track.shortenedUrl.value_or(""))
.bind(8, track.thumbnailUrl.value_or(""));
[[maybe_unused]] auto stepRes = stmt.step();
return {};
}
Result<void> Database::recordSkip(const TrackInfo& track, uint64_t playedBy)
{
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT INTO playback_history
(track_url, track_title, track_artist, played_by, duration_ms, completed, track_short_url, track_thumbnail, skipped)
VALUES (?, ?, ?, ?, 0, 0, ?, ?, 1);
)";
auto stmtRes = impl_->voidDb.prepare(sql);
if (!stmtRes) {
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
}
auto& stmt = *stmtRes;
stmt.bind(1, track.originalUrl)
.bind(2, track.title)
.bind(3, track.artist)
.bind(4, static_cast<std::int64_t>(playedBy))
.bind(5, track.shortenedUrl.value_or(""))
.bind(6, track.thumbnailUrl.value_or(""));
[[maybe_unused]] auto stepRes = stmt.step();
return {};
}
Result<void> Database::logQueueAddition(const std::string& uid,
const std::string& nickname)
{
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql =
"INSERT INTO queue_log (uid, nickname) VALUES (?, ?);";
auto stmtRes = impl_->voidDb.prepare(sql);
if (!stmtRes) {
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
}
auto& stmt = *stmtRes;
stmt.bind(1, uid).bind(2, nickname);
[[maybe_unused]] auto stepRes = stmt.step();
return {};
@@ -606,7 +747,7 @@ namespace Echoion::Api
std::vector<PlaybackHistoryEntry> history;
const char* sql = R"(
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed, track_short_url
SELECT id, track_url, track_title, track_artist, played_at, duration_ms, completed, track_short_url, track_thumbnail
FROM playback_history
WHERE played_by = ?
ORDER BY played_at DESC
@@ -635,6 +776,9 @@ namespace Echoion::Api
if (auto shortUrl = stmt.column_text(7); !shortUrl.empty()) {
entry.track.shortenedUrl = shortUrl;
}
if (auto thumb = stmt.column_text(8); !thumb.empty()) {
entry.track.thumbnailUrl = thumb;
}
history.push_back(entry);
}
@@ -647,8 +791,8 @@ namespace Echoion::Api
std::unique_lock<std::shared_mutex> lock(mutex_);
const char* sql = R"(
INSERT OR REPLACE INTO user_favorites
(user_id, track_url, track_title, track_artist, track_short_url)
VALUES (?, ?, ?, ?, ?);
(user_id, track_url, track_title, track_artist, track_short_url, track_thumbnail)
VALUES (?, ?, ?, ?, ?, ?);
)";
auto stmtRes = impl_->voidDb.prepare(sql);
@@ -662,6 +806,7 @@ namespace Echoion::Api
stmt.bind(3, track.title);
stmt.bind(4, track.artist);
stmt.bind(5, track.shortenedUrl.value_or(""));
stmt.bind(6, track.thumbnailUrl.value_or(""));
[[maybe_unused]] auto stepRes = stmt.step();
@@ -716,7 +861,7 @@ namespace Echoion::Api
std::vector<FavoriteTrack> favorites;
const char* sql = R"(
SELECT track_url, track_title, track_artist, added_at, track_short_url
SELECT track_url, track_title, track_artist, added_at, track_short_url, track_thumbnail
FROM user_favorites
WHERE user_id = ?
ORDER BY added_at DESC;
@@ -741,6 +886,9 @@ namespace Echoion::Api
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
fav.track.shortenedUrl = shortUrl;
}
if (auto thumb = stmt.column_text(5); !thumb.empty()) {
fav.track.thumbnailUrl = thumb;
}
fav.userId = userId;
favorites.push_back(fav);
}
@@ -1052,7 +1200,7 @@ namespace Echoion::Api
// userId 0 = global history. Deduplicate by URL, newest first.
const char* sql = R"(
SELECT track_url, track_title, track_artist, MAX(played_at), MAX(track_short_url)
SELECT track_url, track_title, track_artist, MAX(played_at), MAX(track_short_url), MAX(track_thumbnail)
FROM playback_history
WHERE (?1 = 0 OR played_by = ?1)
GROUP BY track_url
@@ -1076,6 +1224,9 @@ namespace Echoion::Api
if (auto shortUrl = stmt.column_text(4); !shortUrl.empty()) {
track.shortenedUrl = shortUrl;
}
if (auto thumb = stmt.column_text(5); !thumb.empty()) {
track.thumbnailUrl = thumb;
}
tracks.push_back(std::move(track));
}
return tracks;
@@ -1169,6 +1320,90 @@ namespace Echoion::Api
return result;
}
Result<AggregateStats> Database::getAggregateStats()
{
std::shared_lock<std::shared_mutex> lock(mutex_);
AggregateStats stats;
// played_at/added_at are CURRENT_TIMESTAMP (UTC); "today" follows the
// same clock.
{
const char* sql = R"(
SELECT
SUM(CASE WHEN completed = 1 AND date(played_at) = date('now') THEN 1 ELSE 0 END),
SUM(CASE WHEN completed = 1 AND date(played_at) = date('now') THEN duration_ms ELSE 0 END),
SUM(CASE WHEN skipped = 1 AND date(played_at) = date('now') THEN 1 ELSE 0 END),
SUM(CASE WHEN completed = 1 THEN 1 ELSE 0 END),
SUM(CASE WHEN skipped = 1 THEN 1 ELSE 0 END),
SUM(CASE WHEN track_url LIKE '%youtu%' THEN 1 ELSE 0 END),
SUM(CASE WHEN track_url LIKE '%yandex%' THEN 1 ELSE 0 END),
COUNT(*)
FROM playback_history;
)";
auto stmtRes = impl_->voidDb.prepare(sql);
if (!stmtRes) {
return fail(ErrorCode::DatabaseError,
stmtRes.error().message());
}
auto& stmt = *stmtRes;
if (stmt.step().value_or(false)) {
stats.tracksToday = static_cast<uint64_t>(stmt.column_int(0));
stats.listeningMsToday =
static_cast<uint64_t>(stmt.column_int(1));
stats.skipsToday = static_cast<uint64_t>(stmt.column_int(2));
stats.playsTotal = static_cast<uint64_t>(stmt.column_int(3));
stats.skipsTotal = static_cast<uint64_t>(stmt.column_int(4));
stats.youtubeCount = static_cast<uint64_t>(stmt.column_int(5));
stats.yandexCount = static_cast<uint64_t>(stmt.column_int(6));
const auto total = static_cast<uint64_t>(stmt.column_int(7));
stats.otherCount =
total - std::min(total, stats.youtubeCount +
stats.yandexCount);
}
}
{
const char* sql = R"(
SELECT COUNT(*) FROM queue_log WHERE date(added_at) = date('now');
)";
auto stmtRes = impl_->voidDb.prepare(sql);
if (!stmtRes) {
return fail(ErrorCode::DatabaseError,
stmtRes.error().message());
}
auto& stmt = *stmtRes;
if (stmt.step().value_or(false)) {
stats.queueAdditionsToday =
static_cast<uint64_t>(stmt.column_int(0));
}
}
{
const char* sql = R"(
SELECT nickname, COUNT(*) AS adds, MAX(uid) AS uid
FROM queue_log
WHERE nickname IS NOT NULL AND nickname != ''
GROUP BY nickname
ORDER BY adds DESC
LIMIT 5;
)";
auto stmtRes = impl_->voidDb.prepare(sql);
if (!stmtRes) {
return fail(ErrorCode::DatabaseError,
stmtRes.error().message());
}
auto& stmt = *stmtRes;
while (stmt.step().value_or(false)) {
stats.topRequesters.push_back(AggregateStats::TopRequester{
.uid = stmt.column_text(2),
.nickname = stmt.column_text(0),
.count = static_cast<uint64_t>(stmt.column_int(1))});
}
}
return stats;
}
Result<std::optional<std::string>> Database::getKv(const std::string& key)
{
std::shared_lock<std::shared_mutex> lock(mutex_);
@@ -1202,6 +1437,75 @@ namespace Echoion::Api
return {};
}
Result<std::optional<Database::CachedAvatar>>
Database::getCachedAvatar(const std::string& uid)
{
std::shared_lock<std::shared_mutex> lock(mutex_);
auto stmtRes = impl_->voidDb.prepare(
"SELECT uid, mime, data, COALESCE(url, '') FROM cached_avatars "
"WHERE uid = ?;");
if (!stmtRes) {
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
}
auto& stmt = *stmtRes;
stmt.bind(1, uid);
if (stmt.step().value_or(false)) {
return std::optional<CachedAvatar>{
CachedAvatar{.uid = stmt.column_text(0),
.mime = stmt.column_text(1),
.dataBase64 = stmt.column_text(2),
.url = stmt.column_text(3)}};
}
return std::optional<CachedAvatar>{};
}
Result<void> Database::putCachedAvatar(const std::string& uid,
const std::string& mime,
const std::string& dataBase64)
{
std::unique_lock<std::shared_mutex> lock(mutex_);
// Upsert the image but keep any url already recorded for this uid.
auto stmtRes = impl_->voidDb.prepare(R"(
INSERT INTO cached_avatars (uid, mime, data, updated_at)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(uid) DO UPDATE SET
mime = excluded.mime,
data = excluded.data,
updated_at = CURRENT_TIMESTAMP;
)");
if (!stmtRes) {
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
}
auto& stmt = *stmtRes;
stmt.bind(1, uid).bind(2, mime).bind(3, dataBase64);
if (auto stepRes = stmt.step(); !stepRes) {
return fail(ErrorCode::DatabaseError, stepRes.error().message());
}
return {};
}
Result<void> Database::putCachedAvatarUrl(const std::string& uid,
const std::string& url)
{
std::unique_lock<std::shared_mutex> lock(mutex_);
// Insert a url-only row (empty mime/data satisfy NOT NULL) or update the
// url on an existing one, without touching cached bytes.
auto stmtRes = impl_->voidDb.prepare(R"(
INSERT INTO cached_avatars (uid, mime, data, url)
VALUES (?, '', '', ?)
ON CONFLICT(uid) DO UPDATE SET url = excluded.url;
)");
if (!stmtRes) {
return fail(ErrorCode::DatabaseError, stmtRes.error().message());
}
auto& stmt = *stmtRes;
stmt.bind(1, uid).bind(2, url);
if (auto stepRes = stmt.step(); !stepRes) {
return fail(ErrorCode::DatabaseError, stepRes.error().message());
}
return {};
}
Result<void> Database::executeQuery(const std::string& sql,
RowCallback callback)
{
+67 -21
View File
@@ -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;
}
}
+142
View File
@@ -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
+225
View File
@@ -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
+104
View File
@@ -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();
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
namespace Echoion::CoreModule
{
inline constexpr auto apiAbiHash =
"sha256:"
"d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113";
inline constexpr auto coreAbiHash =
"sha256:"
"9cb668e2a502dcfe02d145ed63635d63619732d77ff5749685834382705e8d21";
} // namespace Echoion::CoreModule
+596 -210
View File
File diff suppressed because it is too large. Load diff
+116
View File
@@ -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
+20
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+173 -94
View File
@@ -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());
@@ -99,98 +103,142 @@ namespace Echoion::Core
void RpcServer::acceptLoop()
{
Void::Log::info("RpcServer", "{}", "RPC server accept loop started");
while (running_.load()) {
// 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_);
Void::Log::debug("RpcServer", "{}", "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;
});
// Block until the accept completes or we're stopped. stop()
// clears running_, cancels the acceptor and calls
// ioContext_.stop(), so run_one() returns promptly instead of
// the previous 10ms busy-poll.
while (!acceptComplete.load() && running_.load()) {
if (ioContext_.stopped()) {
break;
}
ioContext_.run_one();
}
// Cancel pending operation if we're stopping
if (!running_.load()) {
acceptor_->cancel();
break;
}
if (acceptEc) {
throw std::runtime_error(acceptEc.message());
}
Void::Log::debug("RpcServer", "{}",
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();
Void::Log::debug("RpcServer", "{}", "RPC server WebSocket handshake completed");
uint64_t clientId = nextClientId_++;
{
std::lock_guard<std::mutex> lock(clientsMutex_);
clients_[clientId] = ws;
}
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);
}
{
std::lock_guard<std::mutex> lock(authMutex_);
authenticatedClients_.erase(clientId);
}
Void::Log::debug("RpcServer", "{}", 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;
}
Void::Log::error("RpcServer", "{}",
std::format("RPC accept error: {}", e.what()));
}
}
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(
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
{
@@ -201,12 +249,26 @@ namespace Echoion::Core
beast::error_code ec;
ws->read(buffer, ec);
if (ec == websocket::error::closed) {
break;
}
if (ec) {
Void::Log::error("RpcServer", "{}",
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;
}
@@ -260,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;
@@ -310,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;
@@ -461,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
+32 -32
View File
@@ -1,12 +1,14 @@
#include <Void/Log/Log.hpp>
#include "echoion/core/SignatureCipher.hpp"
#include <Void/Data/Json.hpp>
#include <quickjs.h>
#include <Void/Log/Log.hpp>
#include <Void/Net/Http.hpp>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <quickjs.h>
#include <regex>
// Minimal embedded fallback - a stub that logs errors
@@ -492,40 +494,38 @@ namespace Echoion::Core
std::optional<std::string>
SignatureCipher::downloadSolverLibrary(std::string_view url)
{
// Simple curl-based download with redirect following
// -s: silent, -L: follow redirects, -f: fail on HTTP error, -m 30:
// timeout 30s
std::string cmd =
std::format("curl -sLf -m 30 '{}' 2>&1", std::string(url));
Void::Log::debug("SignatureCipher", "{}",
std::format("Downloading: {}", url));
Void::Log::debug("SignatureCipher", "{}", std::format("Downloading: {}", url));
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
Void::Log::warn("SignatureCipher", "{}", std::format("Failed to run curl for {}", url));
Void::Net::HttpClient client;
client.set_verify_tls(true);
client.set_max_redirects(5);
client.set_max_body_size(16U * 1024U * 1024U);
Void::Net::Request request;
request.url = std::string(url);
request.method = Void::Net::Method::Get;
request.timeout = std::chrono::seconds{30};
auto response = client.send(request);
if (!response) {
Void::Log::warn("SignatureCipher", "{}",
std::format("Solver download failed for {}: {}",
url, response.error().message()));
return std::nullopt;
}
if (!response->ok()) {
Void::Log::warn(
"SignatureCipher", "{}",
std::format("Solver download returned HTTP {} for {}",
response->status, url));
return std::nullopt;
}
if (response->body.empty()) {
Void::Log::warn("SignatureCipher", "{}",
std::format("Downloaded empty file from {}", url));
return std::nullopt;
}
std::string result;
char buffer[4096];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
int status = pclose(pipe);
if (status != 0) {
Void::Log::warn("SignatureCipher", "{}",
std::format("curl failed with status {} for {}", status, url));
return std::nullopt;
}
if (result.empty()) {
Void::Log::warn("SignatureCipher", "{}",
std::format("Downloaded empty file from {}", url));
return std::nullopt;
}
return result;
return std::move(response->body);
}
void SignatureCipher::initSolver()
+403
View File
@@ -0,0 +1,403 @@
#include "echoion/core/Socks5HttpBridge.hpp"
#include <Void/Log/Log.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/write.hpp>
#include <array>
#include <charconv>
#include <format>
#include <stdexcept>
#include <string>
#include <string_view>
#ifndef _WIN32
#include <sys/socket.h>
#include <sys/time.h>
#endif
namespace Echoion::Core
{
namespace
{
namespace asio = boost::asio;
using tcp = boost::asio::ip::tcp;
// SO_RCVTIMEO/SO_SNDTIMEO for the blocking upstream dial + handshake,
// so a dead SOCKS5 proxy cannot hang a tunnel thread until stop().
// Cleared (0) again for the relay phase — a paused stream may
// legitimately sit idle far longer than any sane handshake timeout.
void setSocketTimeouts(tcp::socket& socket, long seconds)
{
#ifdef _WIN32
DWORD ms = static_cast<DWORD>(seconds * 1000);
setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const char*>(&ms), sizeof(ms));
setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const char*>(&ms), sizeof(ms));
#else
timeval tv{.tv_sec = seconds, .tv_usec = 0};
setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv));
setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv,
sizeof(tv));
#endif
}
// One direction of the tunnel; runs until either side closes.
void pump(tcp::socket& from, tcp::socket& to)
{
std::array<char, 16 * 1024> buf;
boost::system::error_code ec;
while (true) {
const std::size_t n = from.read_some(asio::buffer(buf), ec);
if (ec || n == 0) {
break;
}
asio::write(to, asio::buffer(buf.data(), n), ec);
if (ec) {
break;
}
}
// Half-close so the peer's read loop terminates too.
to.shutdown(tcp::socket::shutdown_send, ec);
}
// "CONNECT host:port HTTP/1.1" -> {host, port}. Handles the bracketed
// IPv6 authority form ("[::1]:443").
std::optional<std::pair<std::string, uint16_t>>
parseConnectTarget(std::string_view requestLine)
{
if (!requestLine.starts_with("CONNECT ")) {
return std::nullopt;
}
requestLine.remove_prefix(8);
const auto space = requestLine.find(' ');
if (space == std::string_view::npos) {
return std::nullopt;
}
std::string_view authority = requestLine.substr(0, space);
std::string_view host;
std::string_view portStr;
if (authority.starts_with('[')) {
const auto close = authority.find(']');
if (close == std::string_view::npos ||
close + 1 >= authority.size() ||
authority[close + 1] != ':') {
return std::nullopt;
}
host = authority.substr(1, close - 1);
portStr = authority.substr(close + 2);
} else {
const auto colon = authority.rfind(':');
if (colon == std::string_view::npos) {
return std::nullopt;
}
host = authority.substr(0, colon);
portStr = authority.substr(colon + 1);
}
uint16_t port = 0;
const auto [ptr, ec] = std::from_chars(
portStr.data(), portStr.data() + portStr.size(), port);
if (ec != std::errc{} || ptr != portStr.data() + portStr.size() ||
host.empty() || port == 0) {
return std::nullopt;
}
return std::make_pair(std::string(host), port);
}
void writeAll(tcp::socket& socket, std::string_view data)
{
boost::system::error_code ec;
asio::write(socket, asio::buffer(data), ec);
}
} // namespace
Socks5HttpBridge::~Socks5HttpBridge() { stop(); }
Api::Result<uint16_t>
Socks5HttpBridge::start(const Void::Net::ProxyConfig& socks5)
{
stop();
try {
acceptor_.emplace(io_,
tcp::endpoint(asio::ip::make_address("127.0.0.1"),
0));
port_ = acceptor_->local_endpoint().port();
} catch (const std::exception& e) {
acceptor_.reset();
return Api::fail(
Api::ErrorCode::NetworkError,
std::format("Failed to bind SOCKS5 bridge: {}", e.what()));
}
{
std::lock_guard<std::mutex> lock(mutex_);
upstream_ = socks5;
}
running_ = true;
acceptThread_ = std::thread([this]() { acceptLoop(); });
Void::Log::info(
"Socks5HttpBridge", "{}",
std::format("HTTP->SOCKS5 bridge on 127.0.0.1:{} (upstream {}:{})",
port_, socks5.host, socks5.port));
return port_;
}
void Socks5HttpBridge::stop()
{
if (!running_.exchange(false)) {
return;
}
boost::system::error_code ec;
if (acceptor_) {
acceptor_->close(ec);
}
if (acceptThread_.joinable()) {
acceptThread_.join();
}
acceptor_.reset();
std::vector<std::unique_ptr<Connection>> connections;
{
std::lock_guard<std::mutex> lock(mutex_);
connections.swap(connections_);
upstream_.reset();
}
for (auto& conn : connections) {
conn->client.close(ec);
conn->upstream.close(ec);
}
for (auto& conn : connections) {
if (conn->worker.joinable()) {
conn->worker.join();
}
}
port_ = 0;
}
std::optional<Void::Net::ProxyConfig> Socks5HttpBridge::upstream() const
{
std::lock_guard<std::mutex> lock(mutex_);
return upstream_;
}
void Socks5HttpBridge::acceptLoop()
{
while (running_.load()) {
auto conn = std::make_unique<Connection>(io_);
boost::system::error_code ec;
acceptor_->accept(conn->client, ec);
if (ec) {
// close() from stop() lands here.
break;
}
Connection* raw = conn.get();
{
std::lock_guard<std::mutex> lock(mutex_);
pruneFinished();
connections_.push_back(std::move(conn));
}
raw->worker = std::thread([this, raw]() {
serve(*raw);
raw->done = true;
});
}
}
void Socks5HttpBridge::pruneFinished()
{
// Caller holds mutex_.
std::erase_if(connections_, [](const std::unique_ptr<Connection>& c) {
if (!c->done.load()) {
return false;
}
if (c->worker.joinable()) {
c->worker.join();
}
return true;
});
}
void Socks5HttpBridge::serve(Connection& conn)
{
boost::system::error_code ec;
// Read the request head; ffmpeg sends a single CONNECT for https
// targets. Bound the handshake so a stuck client can't pin the thread.
setSocketTimeouts(conn.client, 15);
asio::streambuf head;
asio::read_until(conn.client, head, "\r\n\r\n", ec);
if (ec) {
conn.client.close(ec);
return;
}
std::istream stream(&head);
std::string requestLine;
std::getline(stream, requestLine);
if (!requestLine.empty() && requestLine.back() == '\r') {
requestLine.pop_back();
}
const auto target = parseConnectTarget(requestLine);
if (!target) {
Void::Log::warn(
"Socks5HttpBridge", "{}",
std::format("Rejected non-CONNECT request: '{}'", requestLine));
writeAll(conn.client,
"HTTP/1.1 405 Method Not Allowed\r\n\r\n");
conn.client.close(ec);
return;
}
std::optional<Void::Net::ProxyConfig> proxy = upstream();
if (!proxy) {
writeAll(conn.client, "HTTP/1.1 502 Bad Gateway\r\n\r\n");
conn.client.close(ec);
return;
}
try {
setSocketTimeouts(conn.upstream, 15);
tcp::resolver resolver(io_);
asio::connect(conn.upstream,
resolver.resolve(proxy->host,
std::to_string(proxy->port)));
socks5Connect(conn.upstream, target->first, target->second,
*proxy);
} catch (const std::exception& e) {
Void::Log::warn(
"Socks5HttpBridge", "{}",
std::format("Tunnel to {}:{} failed: {}", target->first,
target->second, e.what()));
writeAll(conn.client, "HTTP/1.1 502 Bad Gateway\r\n\r\n");
conn.client.close(ec);
conn.upstream.close(ec);
return;
}
writeAll(conn.client, "HTTP/1.1 200 Connection established\r\n\r\n");
// Relay phase: no timeouts — a paused stream may idle for minutes.
setSocketTimeouts(conn.client, 0);
setSocketTimeouts(conn.upstream, 0);
std::thread downstream(
[&conn]() { pump(conn.upstream, conn.client); });
pump(conn.client, conn.upstream);
downstream.join();
conn.client.close(ec);
conn.upstream.close(ec);
}
void Socks5HttpBridge::socks5Connect(tcp::socket& upstream,
const std::string& host,
uint16_t targetPort,
const Void::Net::ProxyConfig& proxy)
{
// Greeting: no-auth, plus user/pass when credentials are configured.
std::vector<uint8_t> greeting{0x05};
if (proxy.has_auth()) {
greeting.insert(greeting.end(), {0x02, 0x00, 0x02});
} else {
greeting.insert(greeting.end(), {0x01, 0x00});
}
asio::write(upstream, asio::buffer(greeting));
std::array<uint8_t, 2> sel{};
asio::read(upstream, asio::buffer(sel));
if (sel[0] != 0x05) {
throw std::runtime_error("SOCKS5: invalid version");
}
if (sel[1] == 0x02) {
if (!proxy.has_auth()) {
throw std::runtime_error("SOCKS5: auth required");
}
std::vector<uint8_t> auth{0x01};
auth.push_back(static_cast<uint8_t>(proxy.username->size()));
auth.insert(auth.end(), proxy.username->begin(),
proxy.username->end());
auth.push_back(static_cast<uint8_t>(proxy.password->size()));
auth.insert(auth.end(), proxy.password->begin(),
proxy.password->end());
asio::write(upstream, asio::buffer(auth));
std::array<uint8_t, 2> authReply{};
asio::read(upstream, asio::buffer(authReply));
if (authReply[0] != 0x01 || authReply[1] != 0x00) {
throw std::runtime_error("SOCKS5: authentication failed");
}
} else if (sel[1] != 0x00) {
throw std::runtime_error("SOCKS5: no acceptable auth method");
}
// CONNECT request: literal IPs as ATYP 1/4, otherwise the domain form
// (ATYP 3) so the proxy resolves — important when googlevideo DNS is
// poisoned or blocked locally.
std::vector<uint8_t> connectReq{0x05, 0x01, 0x00};
boost::system::error_code addrEc;
const auto addr = asio::ip::make_address(host, addrEc);
if (!addrEc) {
if (addr.is_v4()) {
connectReq.push_back(0x01);
for (auto b : addr.to_v4().to_bytes()) {
connectReq.push_back(b);
}
} else {
connectReq.push_back(0x04);
for (auto b : addr.to_v6().to_bytes()) {
connectReq.push_back(b);
}
}
} else {
connectReq.push_back(0x03);
connectReq.push_back(static_cast<uint8_t>(host.size()));
connectReq.insert(connectReq.end(), host.begin(), host.end());
}
connectReq.push_back(static_cast<uint8_t>((targetPort >> 8) & 0xFF));
connectReq.push_back(static_cast<uint8_t>(targetPort & 0xFF));
asio::write(upstream, asio::buffer(connectReq));
std::array<uint8_t, 4> reply{};
asio::read(upstream, asio::buffer(reply));
if (reply[0] != 0x05) {
throw std::runtime_error("SOCKS5: invalid connect reply");
}
if (reply[1] != 0x00) {
throw std::runtime_error(std::format(
"SOCKS5: connect failed (code {})", int(reply[1])));
}
// Drain the bound address the proxy reports.
switch (reply[3]) {
case 0x01: {
std::array<uint8_t, 6> bound{};
asio::read(upstream, asio::buffer(bound));
break;
}
case 0x03: {
std::array<uint8_t, 1> len{};
asio::read(upstream, asio::buffer(len));
std::vector<uint8_t> bound(len[0] + 2u);
asio::read(upstream, asio::buffer(bound));
break;
}
case 0x04: {
std::array<uint8_t, 18> bound{};
asio::read(upstream, asio::buffer(bound));
break;
}
default:
break;
}
}
} // namespace Echoion::Core
+8 -1
View File
@@ -65,7 +65,14 @@ namespace Echoion::Core
if (subscribedUids_.contains(uid)) {
// Update nickname even if already subscribed
if (database_) {
database_->addSubscriber(uid, nickname);
if (auto result = database_->addSubscriber(uid, nickname);
!result) {
Void::Log::warn(
"SubscriptionManager", "{}",
std::format(
"Failed to refresh subscriber {} nickname: {}",
uid, result.error().message));
}
}
return false; // Already subscribed
}
+12 -8
View File
@@ -40,8 +40,8 @@ namespace Echoion::Core
// A subscriber appeared: if this policy paused playback earlier,
// bring it back.
if (added && pausedForNoSubscribers_.load() &&
resumeOnReturn_.load() && requestResume_) {
if (added && pausedForNoSubscribers_.load() && resumeOnReturn_.load() &&
requestResume_) {
if (requestResume_()) {
pausedForNoSubscribers_ = false;
}
@@ -201,21 +201,24 @@ namespace Echoion::Core
return manager_->getSubscribers();
}
bool SubscriptionService::onClientConnected(uint64_t clientId)
SubscriptionService::ClientConnectResult
SubscriptionService::onClientConnected(uint64_t clientId)
{
ClientConnectResult result;
if (!manager_ || !clientInfo_) {
return false;
return result;
}
auto clientInfo = clientInfo_(clientId);
if (!clientInfo) {
return false;
return result;
}
const auto& [uid, nickname] = *clientInfo;
if (!manager_->isSubscribed(uid)) {
return false;
return result;
}
result.subscribedUid = uid;
Void::Log::info(
"SubscriptionService", "{}",
@@ -233,10 +236,11 @@ namespace Echoion::Core
if (requestResume_()) {
pausedForNoSubscribers_ = false;
}
return false; // resumed; no auto-start needed
return result; // resumed; no auto-start needed
}
return true; // subscribed user online; caller may auto-start playback
result.mayAutoStart = true; // caller may auto-start playback
return result;
}
void SubscriptionService::onClientDisconnected(uint64_t clientId)
+265
View File
@@ -0,0 +1,265 @@
#include "echoion/core/TeamSpeakDirectoryService.hpp"
#include <algorithm>
#include <map>
#include <optional>
#include <set>
#include <utility>
namespace Echoion::Core
{
namespace
{
using Void::Json::Value;
Value optionalId(const std::optional<std::uint64_t>& id)
{
return id ? Value{static_cast<long long>(*id)} : Value{nullptr};
}
Value publicClient(const Api::ClientInfo& client)
{
return Void::Json::object({{"nickname", Value{client.nickname}},
{"talking", Value{client.isTalking}},
{"muted", Value{client.isMuted}},
{"deafened", Value{client.isDeafened}},
{"away", Value{client.isAway}}});
}
Value adminClient(const Api::ClientInfo& client)
{
Value::Array_t groups;
groups.reserve(client.serverGroups.size());
for (const auto group : client.serverGroups) {
groups.emplace_back(static_cast<long long>(group));
}
return Void::Json::object(
{{"id", Value{static_cast<long long>(client.id)}},
{"databaseId", optionalId(client.databaseId)},
{"uid", client.uniqueIdentifier
? Value{*client.uniqueIdentifier}
: Value{nullptr}},
{"nickname", Value{client.nickname}},
{"channelId", Value{static_cast<long long>(client.channelId)}},
{"talking", Value{client.isTalking}},
{"muted", Value{client.isMuted}},
{"deafened", Value{client.isDeafened}},
{"away", Value{client.isAway}},
{"groups", Void::Json::array(std::move(groups))}});
}
Value channelMetadata(const Api::ChannelInfo& channel)
{
return Void::Json::object(
{{"id", Value{static_cast<long long>(channel.id)}},
{"name", Value{channel.name}},
{"parentId", optionalId(channel.parentId)},
{"order", Value{static_cast<long long>(channel.order)}},
{"default", Value{channel.isDefault}},
{"permanent", Value{channel.isPermanent}},
{"semiPermanent", Value{channel.isSemiPermanent}},
{"password", Value{channel.hasPassword}},
{"maxClients",
Value{static_cast<long long>(channel.maxClients)}},
{"currentClients",
Value{static_cast<long long>(channel.currentClients)}}});
}
Value buildChannelTree(const std::vector<Api::ChannelInfo>& channels,
const std::vector<Api::ClientInfo>& clients,
const std::optional<std::uint64_t>
parent,
bool admin)
{
Value::Array_t result;
for (const auto& channel : channels) {
if (channel.parentId != parent) {
continue;
}
auto node = channelMetadata(channel);
Value::Array_t members;
for (const auto& client : clients) {
if (client.channelId != channel.id || client.isQuery) {
continue;
}
members.push_back(admin ? adminClient(client)
: publicClient(client));
}
node.as_object().emplace_back(
"clients", Void::Json::array(std::move(members)));
node.as_object().emplace_back(
"channels",
buildChannelTree(channels, clients, channel.id, admin));
result.push_back(std::move(node));
}
return Void::Json::array(std::move(result));
}
Value serverJson(const TeamSpeakDirectoryService::Snapshot& snapshot)
{
const auto visibleClients =
std::ranges::count_if(snapshot.clients, [](const auto& client) {
return !client.isQuery;
});
return Void::Json::object(
{{"name", Value{snapshot.server.name}},
{"connected", Value{snapshot.connected}},
{"clientCount", Value{static_cast<long long>(visibleClients)}},
{"maxClients",
Value{static_cast<long long>(snapshot.server.maxClients)}},
{"channelCount",
Value{static_cast<long long>(snapshot.channels.size())}},
{"revision",
Value{static_cast<long long>(snapshot.revision)}}});
}
} // namespace
void TeamSpeakDirectoryService::setPluginInterface(
Api::PluginInterfacePtr plugin)
{
{
std::lock_guard lock{mutex_};
plugin_ = std::move(plugin);
}
(void)refresh();
}
Api::Result<void> TeamSpeakDirectoryService::refresh()
{
Api::PluginInterfacePtr plugin;
{
std::lock_guard lock{mutex_};
plugin = plugin_;
}
if (!plugin) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"TeamSpeak interface is unavailable");
}
// Host calls may block or invoke callbacks. Never hold the cache lock
// while crossing that boundary.
auto channelsResult = plugin->getChannels();
if (!channelsResult) {
return std::unexpected(channelsResult.error());
}
auto clientsResult = plugin->getClients();
if (!clientsResult) {
return std::unexpected(clientsResult.error());
}
Snapshot next;
next.connected = plugin->isConnected();
next.channels = orderChannels(std::move(*channelsResult));
for (auto& channel : next.channels) {
// TeamSpeak uses 0 as the root parent while the API model uses an
// absent value. Normalize once so both serializers build one tree.
if (channel.parentId == 0) {
channel.parentId.reset();
}
}
next.clients = std::move(*clientsResult);
if (auto server = plugin->getTeamSpeakServerInfo(); server) {
next.server = std::move(*server);
}
// Counts derived from the same snapshot cannot disagree with the tree,
// even when a host does not expose TeamSpeak's aggregate properties.
for (auto& channel : next.channels) {
channel.currentClients = static_cast<std::uint32_t>(
std::ranges::count_if(next.clients, [&](const auto& client) {
return !client.isQuery && client.channelId == channel.id;
}));
}
next.server.currentClients = static_cast<std::uint32_t>(
std::ranges::count_if(next.clients, [](const auto& client) {
return !client.isQuery;
}));
{
std::lock_guard lock{mutex_};
next.revision = snapshot_.revision + 1;
snapshot_ = std::move(next);
}
return {};
}
void TeamSpeakDirectoryService::handleEvent(Api::PluginEventType type)
{
switch (type) {
case Api::PluginEventType::ConnectionEstablished:
case Api::PluginEventType::ClientConnected:
case Api::PluginEventType::ClientDisconnected:
case Api::PluginEventType::ClientMoved:
case Api::PluginEventType::ClientUpdated:
case Api::PluginEventType::ChannelUpdated:
(void)refresh();
break;
default:
break;
}
}
TeamSpeakDirectoryService::Snapshot
TeamSpeakDirectoryService::snapshot() const
{
std::lock_guard lock{mutex_};
return snapshot_;
}
Value TeamSpeakDirectoryService::publicJson() const
{
const auto current = snapshot();
return Void::Json::object(
{{"server", serverJson(current)},
{"channels", buildChannelTree(current.channels, current.clients,
std::nullopt, false)}});
}
Value TeamSpeakDirectoryService::adminJson() const
{
const auto current = snapshot();
return Void::Json::object(
{{"server", serverJson(current)},
{"channels", buildChannelTree(current.channels, current.clients,
std::nullopt, true)}});
}
std::vector<Api::ChannelInfo> TeamSpeakDirectoryService::orderChannels(
std::vector<Api::ChannelInfo> channels)
{
std::map<std::optional<std::uint64_t>, std::vector<Api::ChannelInfo>>
byParent;
for (auto& channel : channels) {
byParent[channel.parentId].push_back(std::move(channel));
}
std::vector<Api::ChannelInfo> ordered;
ordered.reserve(channels.size());
for (auto& [parent, siblings] : byParent) {
(void)parent;
std::set<std::uint64_t> emitted;
std::uint64_t predecessor = 0;
for (;;) {
auto next =
std::ranges::find_if(siblings, [&](const auto& channel) {
return channel.order == predecessor &&
!emitted.contains(channel.id);
});
if (next == siblings.end()) {
break;
}
predecessor = next->id;
emitted.insert(next->id);
ordered.push_back(*next);
}
std::ranges::sort(siblings, {}, &Api::ChannelInfo::id);
for (const auto& orphan : siblings) {
if (!emitted.contains(orphan.id)) {
ordered.push_back(orphan);
}
}
}
return ordered;
}
} // namespace Echoion::Core
+135 -138
View File
@@ -1,158 +1,155 @@
#include <Void/Log/Log.hpp>
#include "echoion/core/UrlShortener.hpp"
#include <Void/Data/Json.hpp>
#include <format>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <cctype>
#include <exception>
#include <optional>
#include <utility>
namespace Echoion::Core
{
UrlShortener::UrlShortener(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient))
namespace
{
}
UrlShortener::~UrlShortener() = default;
Api::Result<std::string>
UrlShortener::shortenYouTubeUrl(std::string_view videoId)
{
std::string originalUrl =
std::format("https://www.youtube.com/watch?v={}", videoId);
return shortenUrl(originalUrl);
}
Api::Result<std::string>
UrlShortener::shortenUrl(std::string_view originalUrl)
{
// Check cache first
std::string lower(std::string value)
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
Void::Log::debug("UrlShortener", "{}", std::format("URL cache hit: {} -> {}",
originalUrl,
it->second.shortenedUrl));
return it->second.shortenedUrl;
}
// Expired, remove from cache
cache_.erase(it);
std::ranges::transform(value, value.begin(), [](unsigned char ch) {
return static_cast<char>(std::tolower(ch));
});
return value;
}
std::optional<Api::TrackSource> sourceFromName(std::string name)
{
name = lower(std::move(name));
if (name == "youtube") {
return Api::TrackSource::YouTube;
}
if (name == "yandex") {
return Api::TrackSource::Yandex;
}
if (name == "url") {
return Api::TrackSource::URL;
}
if (name == "soundcloud") {
return Api::TrackSource::SoundCloud;
}
if (name == "spotify") {
return Api::TrackSource::Spotify;
}
if (name == "plugin") {
return Api::TrackSource::Plugin;
}
return std::nullopt;
}
Api::ErrorCode apiError(Void::ShortUrl::ErrorCode code)
{
using enum Void::ShortUrl::ErrorCode;
switch (code) {
case invalid_request:
return Api::ErrorCode::InvalidArgument;
case invalid_url:
return Api::ErrorCode::InvalidUrl;
case unsupported:
return Api::ErrorCode::NotSupported;
case not_found:
case expired:
case revoked:
return Api::ErrorCode::NotFound;
case conflict:
return Api::ErrorCode::AlreadyExists;
case unauthorized:
return Api::ErrorCode::Unauthorized;
case unavailable:
case timeout:
case rate_limited:
return Api::ErrorCode::ServiceUnavailable;
case provider_error:
case response_too_large:
return Api::ErrorCode::NetworkError;
case storage:
return Api::ErrorCode::DatabaseError;
default:
return Api::ErrorCode::UnknownError;
}
}
} // namespace
if (!networkClient_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Network client not available");
void UrlShortener::setProvider(ProviderGetter provider)
{
std::lock_guard lock(mutex_);
provider_ = std::move(provider);
}
void UrlShortener::setSources(const std::vector<std::string>& sources)
{
std::unordered_set<Api::TrackSource> parsed;
for (const auto& source : sources) {
if (auto value = sourceFromName(source)) {
parsed.insert(*value);
}
}
std::lock_guard lock(mutex_);
sources_ = std::move(parsed);
}
bool UrlShortener::sourceAllowed(Api::TrackSource source) const
{
std::lock_guard lock(mutex_);
return source != Api::TrackSource::LocalFile &&
sources_.contains(source);
}
Api::Result<std::string>
UrlShortener::shortenUrl(std::string_view originalUrl,
Api::TrackSource source) const
{
if (originalUrl.empty() || !sourceAllowed(source)) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"URL source is not enabled for shortening");
}
// faumaray.ru API endpoint for URL shortening
// POST /shorten with JSON body {"longUrl": "https://..."}
// Response: {"shortUrl": "https://faumaray.ru/xxxxx"}
std::string apiUrl = "https://faumaray.ru/shorten";
// Build JSON request body - API expects "longUrl" field
std::string jsonBody =
std::format(R"({{"longUrl":"{}"}})", originalUrl);
std::vector<Void::Net::Header> headers = {
{"Content-Type", "application/json"},
{"User-Agent", "EchoionBot/1.0"}};
Void::Log::debug("UrlShortener", "{}",
std::format("Shortening URL via faumaray.ru: {}", originalUrl));
auto response = networkClient_->post(apiUrl, jsonBody, headers);
if (!response) {
Void::Log::warn("UrlShortener", "{}", std::format("URL shortening failed: {}",
response.error().message));
return Api::fail(Api::ErrorCode::NetworkError,
"Failed to shorten URL");
ProviderGetter getter;
{
std::lock_guard lock(mutex_);
getter = provider_;
}
if (!response->ok()) {
Void::Log::warn("UrlShortener", "{}", std::format("URL shortening returned HTTP {}",
response->status));
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Shortening service returned HTTP {}",
response->status));
}
try {
// Parse response - expecting {"shortUrl":
// "https://faumaray.ru/xxxxx"}
auto parsed = Void::Json::parse(response->body);
if (!parsed) {
Void::Log::warn("UrlShortener", "{}", "Failed to parse URL shortening response");
return Api::fail(Api::ErrorCode::ParseError,
"Failed to parse shortening response");
auto provider = getter ? getter() : nullptr;
if (!provider || provider->service_version() !=
Void::ShortUrl::kServiceVersion) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"URL shortener provider is unavailable");
}
const auto health = provider->health();
if (health.status == Void::ShortUrl::HealthStatus::unhealthy) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
health.message.empty()
? "URL shortener provider is unhealthy"
: health.message);
}
std::string shortenedUrl;
const Void::Json::Value* shortUrl = parsed->find("shortUrl");
if (shortUrl && shortUrl->is_string()) {
shortenedUrl = shortUrl->as_string();
} else {
Void::Log::warn("UrlShortener", "{}", "No shortUrl field in response");
return Api::fail(Api::ErrorCode::ParseError,
"No shortUrl in response");
}
// Cache the result
{
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_[std::string(originalUrl)] = {
.shortenedUrl = shortenedUrl,
.timestamp = std::chrono::system_clock::now()};
}
Void::Log::debug("UrlShortener", "{}", std::format("URL shortened: {} -> {}",
originalUrl, shortenedUrl));
return shortenedUrl;
} catch (const std::exception& e) {
Void::Log::warn("UrlShortener", "{}", std::format(
"Exception parsing shortening response: {}", e.what()));
return Api::fail(
Api::ErrorCode::ParseError, "Exception during URL shortening");
}
}
std::optional<std::string>
UrlShortener::getCachedUrl(std::string_view originalUrl) const
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto it = cache_.find(std::string(originalUrl));
if (it != cache_.end()) {
auto now = std::chrono::system_clock::now();
if (now - it->second.timestamp < cacheTtl_) {
return it->second.shortenedUrl;
}
}
return std::nullopt;
}
void UrlShortener::clearCache()
{
std::lock_guard<std::mutex> lock(cacheMutex_);
cache_.clear();
}
void UrlShortener::setCacheTtl(std::chrono::hours ttl) { cacheTtl_ = ttl; }
void UrlShortener::cleanExpiredCache()
{
std::lock_guard<std::mutex> lock(cacheMutex_);
auto now = std::chrono::system_clock::now();
for (auto it = cache_.begin(); it != cache_.end();) {
if (now - it->second.timestamp >= cacheTtl_) {
it = cache_.erase(it);
} else {
++it;
auto result =
provider->shorten({.target_url = std::string(originalUrl),
.custom_key = {},
.expires_at_unix_seconds = 0});
if (!result.ok() || result.short_url.empty()) {
return Api::fail(apiError(result.error.code),
result.error.message.empty()
? "URL shortening failed"
: result.error.message);
}
return result.short_url;
} catch (const std::exception& error) {
Void::Log::warn("UrlShortener", "Provider call failed: {}",
error.what());
} catch (...) {
Void::Log::warn("UrlShortener", "Provider call failed");
}
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"URL shortener provider failed");
}
} // namespace Echoion::Core
+216 -87
View File
@@ -5,6 +5,7 @@
#include <Void/Text/Url.hpp>
#include <Void/Time/Format.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <filesystem>
@@ -12,6 +13,7 @@
#include <future>
#include <iomanip>
#include <memory>
#include <random>
#include <regex>
#include <sstream>
#include <thread>
@@ -29,7 +31,7 @@ namespace Echoion::Core
YouTubeClient::YouTubeClient(std::shared_ptr<NetworkClient> networkClient)
: networkClient_(std::move(networkClient)),
ytDlpManager_(std::make_unique<YtDlpManager>(networkClient_)),
urlShortener_(std::make_unique<UrlShortener>(networkClient_))
urlShortener_(std::make_unique<UrlShortener>())
{
}
@@ -155,7 +157,11 @@ namespace Echoion::Core
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"yt-dlp manager not initialized");
}
return ytDlpManager_->update();
auto result = ytDlpManager_->update();
if (!result) {
return std::unexpected(result.error());
}
return {};
}
Api::Result<std::string>
@@ -275,6 +281,7 @@ namespace Echoion::Core
}
std::string url = result.output;
Void::Log::debug("YouTubeClient", "{}", url);
// -g may print multiple lines (video+audio); take the first.
if (auto nl = url.find('\n'); nl != std::string::npos) {
url.resize(nl);
@@ -831,7 +838,23 @@ namespace Echoion::Core
}
Api::Result<Api::SearchResult> YouTubeClient::searchWithYtDlp(
std::string_view query, const std::optional<std::string>& pageToken)
std::string_view query, const std::optional<std::string>& /*pageToken*/)
{
return searchWithYtDlpProvider(query, "ytsearch5",
Api::TrackSource::YouTube);
}
Api::Result<Api::SearchResult>
YouTubeClient::searchSoundCloud(std::string_view query)
{
return searchWithYtDlpProvider(query, "scsearch5",
Api::TrackSource::SoundCloud);
}
Api::Result<Api::SearchResult>
YouTubeClient::searchWithYtDlpProvider(std::string_view query,
std::string_view searchPrefix,
Api::TrackSource source)
{
if (!ytDlpManager_->isAvailable()) {
@@ -842,8 +865,8 @@ namespace Echoion::Core
Void::Log::debug("YouTubeClient", "{}", "Starting yt-dlp search...");
auto searchStart = std::chrono::steady_clock::now();
// yt-dlp search format: ytsearch5:query
std::string searchQuery = std::format("ytsearch5:{}", query);
// yt-dlp search format, e.g. ytsearch5:query or scsearch5:query
std::string searchQuery = std::format("{}:{}", searchPrefix, query);
auto result = ytDlpManager_->executeAsync(
{searchQuery, "-J", "--flat-playlist", "--no-warnings"});
@@ -908,11 +931,16 @@ namespace Echoion::Core
if ((entry).has("thumbnail")) {
track.thumbnailUrl = (entry).get_str("thumbnail");
}
// Set originalUrl so we can extract video ID later for
// streaming
track.originalUrl = std::format(
"https://www.youtube.com/watch?v={}", track.id);
track.source = Api::TrackSource::YouTube;
// Set originalUrl so the track can be resolved later. For
// YouTube it's the watch URL (id is the video id); other
// providers (SoundCloud) carry the permalink in `url`.
if (source == Api::TrackSource::YouTube) {
track.originalUrl = std::format(
"https://www.youtube.com/watch?v={}", track.id);
} else if ((entry).has("url")) {
track.originalUrl = (entry).get_str("url");
}
track.source = source;
searchResult.tracks.push_back(track);
}
@@ -1019,6 +1047,100 @@ namespace Echoion::Core
}
}
Api::Result<std::vector<Api::TrackInfo>>
YouTubeClient::randomMusicVideo(size_t limit)
{
if (!ytDlpManager_->isAvailable()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"yt-dlp not available");
}
// Curated music-oriented queries so a plain ytsearch skews toward
// actual music rather than talk/gaming clips. One is picked at random
// per call; combined with the shuffled results this gives the radio a
// varied backstop when no related/unplayed track is available.
static const std::array<std::string_view, 10> kQueries = {
"popular music", "top hits", "rock music", "electronic music",
"hip hop music", "lofi hip hop", "pop music", "jazz music",
"indie music", "dance music"};
static thread_local std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<size_t> pick(0, kQueries.size() - 1);
const std::string_view query = kQueries[pick(rng)];
// ytsearch<N>: returns the top N results for the query as a flat
// playlist — cheap metadata only, same as radioMix.
const std::string searchUrl =
std::format("ytsearch{}:{}", limit + 10, query);
auto future = ytDlpManager_->executeAsync(
{searchUrl, "-J", "--flat-playlist", "--no-warnings"});
auto waitStatus = future.wait_for(std::chrono::seconds(30));
if (waitStatus == std::future_status::timeout) {
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp random music search timed out");
}
auto ytdlpResult = future.get();
if (!ytdlpResult.success || ytdlpResult.output.empty()) {
return Api::fail(Api::ErrorCode::NetworkError,
"yt-dlp random music search failed");
}
try {
auto parsed = Void::Json::parse(ytdlpResult.output);
if (!parsed) {
return Api::fail(
Api::ErrorCode::ParseError,
"Failed to parse yt-dlp random music search output");
}
const JValue& json = *parsed;
std::vector<Api::TrackInfo> tracks;
if (const JValue* entries = (json).child_array("entries")) {
for (const JValue& entry : entries->as_array()) {
if (!(entry).has("id")) {
continue;
}
Api::TrackInfo track;
track.id = (entry).get_str("id");
if ((entry).has("title")) {
track.title =
Void::Text::html_unescape((entry).get_str("title"));
}
if ((entry).has("uploader")) {
track.artist = Void::Text::html_unescape(
(entry).get_str("uploader"));
}
if ((entry).has("duration")) {
track.duration = std::chrono::seconds(
static_cast<int64_t>((entry).get_num("duration")));
}
if ((entry).has("thumbnail")) {
track.thumbnailUrl = (entry).get_str("thumbnail");
}
track.requestedBy = "radio\\autoplay";
track.addedAt = std::chrono::system_clock::now();
track.originalUrl = std::format(
"https://www.youtube.com/watch?v={}", track.id);
track.source = Api::TrackSource::YouTube;
tracks.push_back(std::move(track));
}
}
// Shuffle so the caller's "take the first acceptable one" pick is
// effectively random across the result set.
std::shuffle(tracks.begin(), tracks.end(), rng);
populateShortenedUrls(tracks);
return tracks;
} catch (const std::exception& e) {
return Api::fail(
Api::ErrorCode::ParseError,
std::format("Exception parsing yt-dlp random music search: {}",
e.what()));
}
}
Api::Result<Api::PlaylistInfo>
YouTubeClient::getPlaylist(std::string_view playlistId)
{
@@ -1486,60 +1608,21 @@ namespace Echoion::Core
{
std::string url_str(url);
// Handle faumaray.ru redirects using NetworkClient
if (url_str.find("faumaray.ru") != std::string::npos &&
networkClient_) {
Void::Log::debug(
"YouTubeClient", "{}",
std::format("Following redirect for: {}", url_str));
std::vector<Void::Net::Header> headers = {
{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36"}};
// Make request without following redirects to get the Location
// header
auto response = networkClient_->get(url_str, headers);
if (response) {
// Check if we got a redirect
if (response->status >= 300 && response->status < 400) {
auto location = response->header("location");
if (location.has_value()) {
Void::Log::debug(
"YouTubeClient", "{}",
std::format("Redirected to: {}", *location));
url_str = std::string(*location);
}
} else if (response->ok()) {
// Some shorteners might return the target in the body or we
// might need to look at the URL after any automatic
// redirect following Try to extract from current URL or
// response
auto finalUrl = response->header(
"x-final-url"); // Some clients add this
if (finalUrl.has_value()) {
url_str = std::string(*finalUrl);
}
}
}
}
// More comprehensive regex patterns for YouTube URLs
static const std::regex watch_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?)",
R"(^(?:https?://)?(?:www\.)?youtube\.com/watch\?[^\s]*v=([a-zA-Z0-9_-]{11})(?:&[^\s]*)?$)",
std::regex::icase);
static const std::regex short_pattern(
R"((?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
R"(^(?:https?://)?(?:www\.)?youtu\.be/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)",
std::regex::icase);
static const std::regex embed_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
R"(^(?:https?://)?(?:www\.)?youtube\.com/embed/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)",
std::regex::icase);
static const std::regex shorts_pattern(
R"((?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?)",
R"(^(?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})(?:\?[^\s]*)?$)",
std::regex::icase);
// Also match just the video ID (11 characters)
@@ -1573,9 +1656,10 @@ namespace Echoion::Core
bool YouTubeClient::isYouTubeUrl(std::string_view url)
{
return url.find("faumaray.ru") != std::string::npos ||
url.find("youtube.com") != std::string::npos ||
url.find("youtu.be") != std::string::npos;
static const std::regex youtubeUrlPattern(
R"(^(?:https?://)?(?:www\.)?(?:youtube\.com(?:/|$)|youtu\.be(?:/|$)))",
std::regex::icase);
return std::regex_search(url.begin(), url.end(), youtubeUrlPattern);
}
void YouTubeClient::setUrlShorteningEnabled(bool enabled)
@@ -1587,6 +1671,25 @@ namespace Echoion::Core
std::format("URL shortening {}", enabled ? "enabled" : "disabled"));
}
void YouTubeClient::setUrlShortenerProvider(
UrlShortener::ProviderGetter provider)
{
urlShortener_->setProvider(std::move(provider));
}
void YouTubeClient::setUrlShorteningSources(
const std::vector<std::string>& sources)
{
urlShortener_->setSources(sources);
}
void YouTubeClient::setUrlShorteningTimeout(
std::chrono::milliseconds timeout)
{
std::lock_guard lock(configMutex_);
urlShorteningTimeout_ = timeout;
}
void YouTubeClient::setAutoUpdateEnabled(bool enabled)
{
if (ytDlpManager_) {
@@ -1603,35 +1706,46 @@ namespace Echoion::Core
void YouTubeClient::populateShortenedUrl(Api::TrackInfo& track)
{
bool enabled;
std::chrono::milliseconds timeout;
{
std::lock_guard<std::mutex> lock(configMutex_);
enabled = urlShorteningEnabled_;
timeout = urlShorteningTimeout_;
}
if (!enabled || !urlShortener_ || track.id.empty()) {
if (!enabled || !urlShortener_ ||
(track.shortenedUrl && !track.shortenedUrl->empty())) {
return;
}
std::string originalUrl = track.originalUrl;
if (originalUrl.empty() && track.source == Api::TrackSource::YouTube &&
!track.id.empty()) {
originalUrl =
std::format("https://www.youtube.com/watch?v={}", track.id);
}
if (originalUrl.empty()) {
return;
}
const auto source = track.source;
// Run URL shortening on the shared pool with a timeout. Best-effort: if
// it times out we keep the track unshortened. The future is only read
// on the ready path (which establishes happens-before), and on timeout
// the task keeps running on the pool with its result discarded — no
// detached thread and no busy-wait poll.
auto trackId = track.id;
auto future =
pool_.submit([this, trackId]() -> std::optional<std::string> {
try {
auto result = urlShortener_->shortenYouTubeUrl(trackId);
if (result) {
return *result;
}
} catch (...) {
// Ignore exceptions - this is best-effort
auto future = pool_.submit([this, originalUrl = std::move(originalUrl),
source]() -> std::optional<std::string> {
try {
auto result = urlShortener_->shortenUrl(originalUrl, source);
if (result) {
return *result;
}
return std::nullopt;
});
} catch (...) {
// Ignore exceptions - this is best-effort
}
return std::nullopt;
});
if (future.wait_for(std::chrono::seconds(3)) ==
std::future_status::ready) {
if (future.wait_for(timeout) == std::future_status::ready) {
if (auto shortened = future.get()) {
track.shortenedUrl = *shortened;
Void::Log::debug("YouTubeClient", "{}",
@@ -1641,7 +1755,8 @@ namespace Echoion::Core
}
} else {
Void::Log::warn("YouTubeClient", "{}",
"URL shortening timed out after 3s");
std::format("URL shortening timed out after {}ms",
timeout.count()));
}
}
@@ -1649,9 +1764,11 @@ namespace Echoion::Core
std::vector<Api::TrackInfo>& tracks)
{
bool enabled;
std::chrono::milliseconds timeout;
{
std::lock_guard<std::mutex> lock(configMutex_);
enabled = urlShorteningEnabled_;
timeout = urlShorteningTimeout_;
}
if (!enabled || !urlShortener_ || tracks.empty()) {
return;
@@ -1674,30 +1791,42 @@ namespace Echoion::Core
slots.reserve(tracks.size());
for (auto& track : tracks) {
if (track.id.empty()) {
if (track.shortenedUrl && !track.shortenedUrl->empty()) {
continue;
}
auto trackId = track.id;
std::string originalUrl = track.originalUrl;
if (originalUrl.empty() &&
track.source == Api::TrackSource::YouTube &&
!track.id.empty()) {
originalUrl =
std::format("https://www.youtube.com/watch?v={}", track.id);
}
if (originalUrl.empty()) {
continue;
}
const auto source = track.source;
auto out = std::make_shared<std::optional<std::string>>();
auto future = pool_.submit([this, trackId, out]() {
try {
auto result = urlShortener_->shortenYouTubeUrl(trackId);
if (result) {
*out = *result;
auto future = pool_.submit(
[this, originalUrl = std::move(originalUrl), source, out]() {
try {
auto result =
urlShortener_->shortenUrl(originalUrl, source);
if (result) {
*out = *result;
}
} catch (...) {
// Ignore exceptions - best-effort
}
} catch (...) {
// Ignore exceptions - best-effort
}
});
});
slots.push_back({&track, std::move(out), std::move(future)});
}
// Wait for all with an overall 5-second timeout.
// Wait for all with the configured overall timeout.
auto start = std::chrono::steady_clock::now();
for (auto& slot : slots) {
auto remaining = std::chrono::seconds(5) -
(std::chrono::steady_clock::now() - start);
if (remaining <= std::chrono::seconds::zero()) {
auto remaining =
timeout - (std::chrono::steady_clock::now() - start);
if (remaining <= std::chrono::milliseconds::zero()) {
break;
}
slot.future.wait_for(remaining);
+171 -116
View File
@@ -1,9 +1,11 @@
#include <Void/Log/Log.hpp>
#include "echoion/core/YtDlpManager.hpp"
#include <Void/Log/Log.hpp>
#include <Void/System/Process.hpp>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <format>
#include <fstream>
#include <future>
@@ -50,6 +52,10 @@ namespace Echoion::Core
}
return homeDir / "echoion" / "yt-dlp";
#else
if (const char* dataHome = std::getenv("XDG_DATA_HOME");
dataHome && *dataHome != '\0') {
return std::filesystem::path{dataHome} / "echoion" / "yt-dlp";
}
const char* home = std::getenv("HOME");
if (home) {
homeDir = home;
@@ -81,8 +87,12 @@ namespace Echoion::Core
return std::string(YTDLP_DOWNLOAD_WINDOWS);
#elif defined(__APPLE__)
return std::string(YTDLP_DOWNLOAD_MACOS);
#elif defined(__x86_64__) || defined(_M_X64)
return std::string(YTDLP_DOWNLOAD_LINUX_X86_64);
#elif defined(__aarch64__) || defined(_M_ARM64)
return std::string(YTDLP_DOWNLOAD_LINUX_AARCH64);
#else
return std::string(YTDLP_DOWNLOAD_LINUX);
return {};
#endif
}
@@ -113,15 +123,18 @@ namespace Echoion::Core
return {};
}
Void::Log::info("YtDlpManager", "{}", "Initializing yt-dlp manager...");
Void::Log::info("YtDlpManager", "{}",
"Initializing yt-dlp manager...");
// Create storage directory if needed
std::filesystem::path storageDir = getStorageDir();
Void::Log::debug("YtDlpManager", "{}",
Void::Log::debug(
"YtDlpManager", "{}",
std::format("yt-dlp storage dir: {}", storageDir.string()));
if (!std::filesystem::exists(storageDir)) {
Void::Log::info("YtDlpManager", "{}", "Creating yt-dlp storage directory...");
Void::Log::info("YtDlpManager", "{}",
"Creating yt-dlp storage directory...");
try {
std::filesystem::create_directories(storageDir);
} catch (const std::exception& e) {
@@ -134,10 +147,11 @@ namespace Echoion::Core
}
executablePath_ = storageDir / getExecutableName();
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp executable path: {}",
executablePath_.string()));
Void::Log::debug("YtDlpManager", "{}",
std::format("yt-dlp executable path: {}",
executablePath_.string()));
} // Release lock; everything below runs off the caller's thread.
} // Release lock; everything below runs off the caller's thread.
// Download/update and the subprocess version check can take seconds
// (10s timeout each) — that used to run inline and stalled every
@@ -147,32 +161,38 @@ namespace Echoion::Core
// preserved: downloadYtDlp()/getVersion() run without mutex_ held
// (getVersion -> execute -> getCookieArgs takes it).
initThread_ = std::jthread([this]() {
// update() already verifies the fresh binary; only probe the
// version ourselves when no (successful) update ran.
std::string version;
const bool exists = std::filesystem::exists(executablePath_);
if (!exists) {
Void::Log::info("YtDlpManager", "{}",
"yt-dlp not found, downloading...");
auto result = downloadYtDlp();
if (!result) {
Void::Log::error(
"YtDlpManager", "{}",
std::format("yt-dlp download failed: {}",
result.error().message));
Void::Log::error("YtDlpManager", "{}",
std::format("yt-dlp download failed: {}",
result.error().message));
return;
}
} else if (autoUpdateEnabled_.load() && shouldUpdate()) {
Void::Log::info("YtDlpManager", "{}",
"yt-dlp may be outdated, updating...");
auto result = update();
if (!result) {
if (result) {
version = *result;
} else {
Void::Log::warn("YtDlpManager", "{}",
std::format("yt-dlp update failed: {}",
result.error().toString()));
std::format("yt-dlp update failed: {}",
result.error().toString()));
}
}
Void::Log::info("YtDlpManager", "{}",
"Checking yt-dlp version...");
const std::string version = getVersion();
if (version.empty()) {
Void::Log::info("YtDlpManager", "{}",
"Checking yt-dlp version...");
version = getVersion();
}
if (version.empty()) {
Void::Log::error("YtDlpManager", "{}",
"yt-dlp executable not working");
@@ -201,15 +221,19 @@ namespace Echoion::Core
unsigned int hardwareThreads = std::thread::hardware_concurrency();
if (hardwareThreads > 0 && threadPoolSize_ > hardwareThreads / 2) {
threadPoolSize_ = std::max(1u, hardwareThreads / 2);
Void::Log::info("YtDlpManager", "{}", std::format(
"Auto-adjusted yt-dlp thread pool to {} threads (hardware: {})",
threadPoolSize_, hardwareThreads));
Void::Log::info("YtDlpManager", "{}",
std::format("Auto-adjusted yt-dlp thread pool to "
"{} threads (hardware: {})",
threadPoolSize_, hardwareThreads));
}
Void::Log::info("YtDlpManager", "{}", std::format(
"Starting yt-dlp thread pool with {} threads", threadPoolSize_));
Void::Log::info(
"YtDlpManager", "{}",
std::format("Starting yt-dlp thread pool with {} threads",
threadPoolSize_));
pool_ = std::make_unique<Void::Concurrency::ThreadPool>(threadPoolSize_);
pool_ =
std::make_unique<Void::Concurrency::ThreadPool>(threadPoolSize_);
}
void YtDlpManager::stopThreadPool()
@@ -250,8 +274,9 @@ namespace Echoion::Core
std::lock_guard<std::mutex> lock(proxyMutex_);
proxyConfig_ = proxy;
if (proxy.has_value() && proxy->enabled()) {
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp proxy configured: {}:{}",
proxy->host, proxy->port));
Void::Log::info("YtDlpManager", "{}",
std::format("yt-dlp proxy configured: {}:{}",
proxy->host, proxy->port));
} else {
Void::Log::info("YtDlpManager", "{}", "yt-dlp proxy cleared");
}
@@ -302,11 +327,17 @@ namespace Echoion::Core
{
if (!networkClient_) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Network client not available");
"Network client not available");
}
std::string downloadUrl = getDownloadUrl();
Void::Log::info("YtDlpManager", "{}",
if (downloadUrl.empty()) {
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
"No standalone yt-dlp release is available for this platform");
}
Void::Log::info(
"YtDlpManager", "{}",
std::format("Downloading yt-dlp from: {}", downloadUrl));
std::vector<Void::Net::Header> headers = {
@@ -322,8 +353,8 @@ namespace Echoion::Core
auto result = networkClient_->get(downloadUrl, headers);
if (!result) {
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: {}",
result.error().message));
std::format("Failed to download yt-dlp: {}",
result.error().message));
}
response = std::move(*result);
@@ -352,8 +383,9 @@ namespace Echoion::Core
}
}
Void::Log::info("YtDlpManager", "{}", std::format("Following redirect (HTTP {}): {}",
response.status, newUrl));
Void::Log::info("YtDlpManager", "{}",
std::format("Following redirect (HTTP {}): {}",
response.status, newUrl));
downloadUrl = newUrl;
redirectCount++;
continue;
@@ -364,23 +396,42 @@ namespace Echoion::Core
if (!response.ok()) {
return Api::fail(Api::ErrorCode::NetworkError,
std::format("Failed to download yt-dlp: HTTP {}",
response.status));
std::format("Failed to download yt-dlp: HTTP {}",
response.status));
}
Void::Log::info("YtDlpManager", "{}",
Void::Log::info(
"YtDlpManager", "{}",
std::format("Downloaded {} bytes", response.body.size()));
// Write to file
// Write to a temp file next to the target, verify it, then atomically
// rename over the real path. Writing the live binary in place fails
// with ETXTBSY while any yt-dlp process is running; rename never
// touches the executing inode, so the swap always succeeds.
const std::filesystem::path tempPath =
executablePath_.string() + ".new";
try {
std::ofstream file(executablePath_, std::ios::binary);
errno = 0;
std::ofstream file(tempPath, std::ios::binary | std::ios::trunc);
if (!file) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Failed to open yt-dlp file for writing");
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format("Failed to open '{}' for writing: {}",
tempPath.string(), std::strerror(errno)));
}
file.write(response.body.data(), response.body.size());
file.write(response.body.data(),
static_cast<std::streamsize>(response.body.size()));
file.close();
if (!file) {
std::filesystem::remove(tempPath);
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format("Failed to write '{}': {}", tempPath.string(),
std::strerror(errno)));
}
} catch (const std::exception& e) {
std::error_code ec;
std::filesystem::remove(tempPath, ec);
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format("Failed to write yt-dlp file: {}", e.what()));
@@ -388,12 +439,50 @@ namespace Echoion::Core
// Make executable on Unix
#ifndef _WIN32
auto execResult = makeExecutable();
auto execResult = makeExecutable(tempPath);
if (!execResult) {
std::error_code ec;
std::filesystem::remove(tempPath, ec);
return execResult;
}
#endif
// Verify the downloaded binary actually runs before swapping it in;
// a truncated/corrupt download must never replace a working one.
auto probe = Void::Process::run(tempPath, {"--version"}, {},
std::chrono::seconds(10));
if (!probe || probe->exit_code != 0) {
std::error_code ec;
std::filesystem::remove(tempPath, ec);
std::string details =
probe ? std::format("exit code {}", probe->exit_code)
: probe.error().message();
if (probe) {
const auto& output =
!probe->err.empty() ? probe->err : probe->out;
if (!output.empty()) {
constexpr std::size_t maxDiagnosticLength = 1024;
details += std::format(
"; output: {}", output.substr(0, maxDiagnosticLength));
}
}
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format("Downloaded yt-dlp failed verification: {}",
details));
}
std::error_code renameEc;
std::filesystem::rename(tempPath, executablePath_, renameEc);
if (renameEc) {
std::error_code ec;
std::filesystem::remove(tempPath, ec);
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format("Failed to move '{}' into place: {}",
tempPath.string(), renameEc.message()));
}
// Write timestamp file for update checking
try {
std::ofstream tsFile(getStorageDir() / ".last_update");
@@ -409,15 +498,19 @@ namespace Echoion::Core
return {};
}
Api::Result<void> YtDlpManager::makeExecutable()
Api::Result<void>
YtDlpManager::makeExecutable(const std::filesystem::path& path)
{
#ifdef _WIN32
(void)path;
return {}; // Windows doesn't need this
#else
if (chmod(executablePath_.c_str(),
if (chmod(path.c_str(),
S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Failed to make yt-dlp executable");
return Api::fail(
Api::ErrorCode::ServiceUnavailable,
std::format("Failed to make '{}' executable: {}",
path.string(), std::strerror(errno)));
}
return {};
#endif
@@ -453,66 +546,42 @@ namespace Echoion::Core
}
}
Api::Result<void> YtDlpManager::update()
Api::Result<std::string> YtDlpManager::update()
{
std::lock_guard<std::mutex> lock(mutex_);
// No mutex_ here: downloadYtDlp() verifies the new binary and swaps
// it in atomically (no backup needed), and getVersion() -> execute()
// -> getCookieArgs() takes mutex_ itself — holding it across the call
// would self-deadlock. Same lock discipline as initialize().
Void::Log::info("YtDlpManager", "{}", "Updating yt-dlp...");
// Backup current version
std::filesystem::path backupPath = executablePath_.string() + ".backup";
try {
if (std::filesystem::exists(executablePath_)) {
std::filesystem::copy_file(
executablePath_, backupPath,
std::filesystem::copy_options::overwrite_existing);
}
} catch (...) {
}
// Download new version
auto result = downloadYtDlp();
if (!result) {
// Restore backup if available
try {
if (std::filesystem::exists(backupPath)) {
std::filesystem::copy_file(
backupPath, executablePath_,
std::filesystem::copy_options::overwrite_existing);
}
} catch (...) {
}
return result;
return std::unexpected(result.error());
}
// Remove backup
try {
std::filesystem::remove(backupPath);
} catch (...) {
}
// Verify new version works
std::string version = getVersion();
const std::string version = getVersion();
if (version.empty()) {
return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Updated yt-dlp not working");
"Updated yt-dlp not working");
}
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp updated to: {}", version));
return {};
Void::Log::info("YtDlpManager", "{}",
std::format("yt-dlp updated to: {}", version));
return version;
}
std::string YtDlpManager::getVersion() const
{
if (!std::filesystem::exists(executablePath_)) {
Void::Log::warn("YtDlpManager", "{}",
"yt-dlp executable not found for version check");
Void::Log::warn("YtDlpManager", "{}",
"yt-dlp executable not found for version check");
return "";
}
Void::Log::debug("YtDlpManager", "{}", "Executing yt-dlp --version...");
std::string result = execute({"--version"});
Void::Log::debug("YtDlpManager", "{}", std::format("yt-dlp --version output: '{}'", result));
Void::Log::debug("YtDlpManager", "{}",
std::format("yt-dlp --version output: '{}'", result));
// Remove trailing newline
if (!result.empty() && result.back() == '\n') {
@@ -526,14 +595,16 @@ namespace Echoion::Core
{
std::lock_guard<std::mutex> lock(mutex_);
cookiesPath_ = path;
Void::Log::info("YtDlpManager", "{}", std::format("yt-dlp cookies path set to: {}", path));
Void::Log::info("YtDlpManager", "{}",
std::format("yt-dlp cookies path set to: {}", path));
}
void YtDlpManager::setCookiesFromBrowser(const std::string& browser)
{
std::lock_guard<std::mutex> lock(mutex_);
cookiesFromBrowser_ = browser;
Void::Log::info("YtDlpManager", "{}",
Void::Log::info(
"YtDlpManager", "{}",
std::format("yt-dlp will use cookies from browser: {}", browser));
}
@@ -574,7 +645,8 @@ namespace Echoion::Core
// Assemble argv: proxy args, then cookie args, then caller args.
// Void::Process::run executes the binary directly (no shell), so no
// manual quoting/escaping is required and arguments are passed verbatim.
// manual quoting/escaping is required and arguments are passed
// verbatim.
std::vector<std::string> processArgs;
const auto proxyArgs = getProxyArgs();
processArgs.insert(processArgs.end(), proxyArgs.begin(),
@@ -589,9 +661,15 @@ namespace Echoion::Core
(args.size() == 1 && args[0] == "--version");
const auto timeout = std::chrono::seconds(isVersionCheck ? 10 : 60);
Void::Log::debug("YtDlpManager", "{}", std::format("Executing yt-dlp: {} ({} args)",
executablePath_.string(),
processArgs.size()));
auto argsStr = std::accumulate(
std::next(processArgs.begin()),
processArgs.end(),
processArgs[0],
[](std::string a, std::string b) { return a + " " + b; });
Void::Log::debug(
"YtDlpManager", "{}",
std::format("Executing yt-dlp: {} ({} args) commandArgs: {}",
executablePath_.string(), processArgs.size(), argsStr));
auto procResult =
Void::Process::run(executablePath_, processArgs, {}, timeout);
@@ -602,8 +680,9 @@ namespace Echoion::Core
startTime);
if (!procResult) {
Void::Log::warn("YtDlpManager", "{}", std::format("Failed to execute yt-dlp: {}",
procResult.error().message()));
Void::Log::warn("YtDlpManager", "{}",
std::format("Failed to execute yt-dlp: {}",
procResult.error().message()));
return result;
}
@@ -614,7 +693,6 @@ namespace Echoion::Core
return result;
}
std::future<YtDlpResult>
YtDlpManager::executeAsync(const std::vector<std::string>& args)
{
@@ -629,27 +707,4 @@ namespace Echoion::Core
return pool_->submit([this, args]() { return executeInternal(args); });
}
std::vector<YtDlpResult> YtDlpManager::executeBatch(
const std::vector<std::vector<std::string>>& argsList)
{
std::vector<std::future<YtDlpResult>> futures;
futures.reserve(argsList.size());
// Launch all tasks
for (const auto& args : argsList) {
futures.push_back(executeAsync(args));
}
// Collect results
std::vector<YtDlpResult> results;
results.reserve(argsList.size());
for (auto& future : futures) {
results.push_back(future.get());
}
return results;
}
} // namespace Echoion::Core
+68
View File
@@ -0,0 +1,68 @@
#include "echoion/core/i18n/Localization.hpp"
#include <algorithm>
#include <cctype>
#include <string>
#include <unordered_map>
namespace Echoion::Core::I18n
{
Language parseLanguage(std::string_view code)
{
std::string lower(code);
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) { return std::tolower(c); });
if (lower == "ru" || lower == "russian" ||
lower == "\xd1\x80\xd1\x83" ||
lower == "\xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0"
"\xb9") {
return Language::Russian;
}
return Language::English;
}
std::string_view languageCode(Language lang)
{
return lang == Language::Russian ? "ru" : "en";
}
std::string_view languageName(Language lang)
{
// Self-referential (shown when a user picks a language).
return lang == Language::Russian ? "\xd0\xa0\xd1\x83\xd1\x81\xd1\x81"
"\xd0\xba\xd0\xb8\xd0\xb9"
: "English";
}
namespace
{
// English source string -> Russian translation. Keys must match the
// English text passed to CommandContext::tr/trf exactly (adjacent
// string literals are already concatenated by the compiler). A missing
// key simply renders the English original, so partial coverage is safe.
const std::unordered_map<std::string_view, std::string_view>&
russianCatalog()
{
static const std::unordered_map<std::string_view, std::string_view>
kMap = {
// Populated in Localization.cpp catalog section.
#include "RussianCatalog.inc"
};
return kMap;
}
} // namespace
std::string_view translate(std::string_view english, Language lang)
{
if (lang == Language::English || english.empty()) {
return english;
}
const auto& map = russianCatalog();
if (auto it = map.find(english); it != map.end()) {
return it->second;
}
return english;
}
} // namespace Echoion::Core::I18n
+200
View File
@@ -0,0 +1,200 @@
// Auto-generated English -> Russian translation entries.
// Consumed by Localization.cpp. Keys must byte-match tr()/trf() sources.
{"\n\n— Page {}/{} · {}next · {}prev · {}page <n>", "\n\n— Страница {}/{} · {}next · {}prev · {}page <n>"},
{"\n**Now Playing:** {}{}\n", "\n**Сейчас играет:** {}{}\n"},
{"\n**Up Next ({} tracks):**\n", "\n**Далее ({} треков):**\n"},
{"\nThe queue is empty. Add songs with {}play !", "\nОчередь пуста. Добавьте треки командой {}play !"},
{"\nUse {}queue <page> to see more (page {} of {})", "\nИспользуйте {}queue <страница>, чтобы увидеть больше (страница {} из {})"},
{"\nUse {}select <number> to play a result.", "\nИспользуйте {}select <номер>, чтобы включить результат."},
{" total)\n", " всего)\n"},
{" | ⚪ Offline: ", " | ⚪ Не в сети: "},
{"# 🎵 Echoion Bot Help", "# 🎵 Справка Echoion"},
{"**⚪ Offline:**\n", "**⚪ Не в сети:**\n"},
{"**🟢 Online:**\n", "**🟢 В сети:**\n"},
{"- {} ({} tracks)\n", "- {} ({} треков)\n"},
{":::details {} {} Commands\n\n", ":::details {} {} — команды\n\n"},
{"> [!TIP]\n> Prefix is `{}` — e.g. `{}play lofi`\n\n", "> [!TIP]\n> Префикс — `{}`, например `{}play lofi`\n\n"},
{"> 🎚 {} {}% · 🔀 {} {} · 🔁 {} {} · 📻 {} {}\n\n", "> 🎚 {} {}% · 🔀 {} {} · 🔁 {} {} · 📻 {} {}\n\n"},
{"Added to favorites: {}", "Добавлено в избранное: {}"},
{"Added to queue: {}", "Добавлено в очередь: {}"},
{"Aliases:", "Псевдонимы:"},
{"An unexpected error occurred. Our team has been notified.", "Произошла непредвиденная ошибка. Мы уже уведомлены."},
{"Announcement saved and delivered to {} online subscriber(s). Offline subscribers get it on their next connect.", "Объявление сохранено и доставлено {} подписчикам в сети. Остальные получат его при следующем подключении."},
{"Config reload is unavailable right now.", "Перезагрузка конфигурации сейчас недоступна."},
{"Couldn't add that track. Please try again.", "Не удалось добавить трек. Попробуйте ещё раз."},
{"Couldn't change volume. Please try again.", "Не удалось изменить громкость. Попробуйте ещё раз."},
{"Couldn't clear subscriptions. Please try again.", "Не удалось очистить подписки. Попробуйте ещё раз."},
{"Couldn't clear the queue. Please try again.", "Не удалось очистить очередь. Попробуйте ещё раз."},
{"Couldn't connect to search service. Please check your connection.", "Не удалось подключиться к поиску. Проверьте соединение."},
{"Couldn't connect to that URL. Please check and try again.", "Не удалось подключиться по этой ссылке. Проверьте её и попробуйте снова."},
{"Couldn't generate help. Please try again.", "Не удалось сформировать справку. Попробуйте ещё раз."},
{"Couldn't get current track information.", "Не удалось получить информацию о текущем треке."},
{"Couldn't get queue information.", "Не удалось получить информацию об очереди."},
{"Couldn't identify you on the server.", "Не удалось определить вас на сервере."},
{"Couldn't load the playlist. Please try again.", "Не удалось загрузить плейлист. Попробуйте ещё раз."},
{"Couldn't move that track. Please try again.", "Не удалось переместить трек. Попробуйте ещё раз."},
{"Couldn't pause playback. Please try again.", "Не удалось поставить на паузу. Попробуйте ещё раз."},
{"Couldn't play it: {}", "Не удалось воспроизвести: {}"},
{"Couldn't play that URL. Please try again.", "Не удалось воспроизвести эту ссылку. Попробуйте ещё раз."},
{"Couldn't read playback statistics.", "Не удалось прочитать статистику воспроизведения."},
{"Couldn't read the playback history.", "Не удалось прочитать историю воспроизведения."},
{"Couldn't read your favorites.", "Не удалось прочитать ваше избранное."},
{"Couldn't remove that track. Please try again.", "Не удалось удалить трек. Попробуйте ещё раз."},
{"Couldn't remove the favorite.", "Не удалось удалить из избранного."},
{"Couldn't resume playback. Please try again.", "Не удалось возобновить воспроизведение. Попробуйте ещё раз."},
{"Couldn't retrieve playlists.", "Не удалось получить плейлисты."},
{"Couldn't save the favorite.", "Не удалось сохранить в избранное."},
{"Couldn't save your language. Please try again.", "Не удалось сохранить язык. Попробуйте ещё раз."},
{"Couldn't seek. Please try again.", "Не удалось перемотать. Попробуйте ещё раз."},
{"Couldn't select that track. Please try again.", "Не удалось выбрать трек. Попробуйте ещё раз."},
{"Couldn't skip. Please try again.", "Не удалось пропустить. Попробуйте ещё раз."},
{"Couldn't stop playback. Please try again.", "Не удалось остановить воспроизведение. Попробуйте ещё раз."},
{"Couldn't subscribe you. Please try again.", "Не удалось оформить подписку. Попробуйте ещё раз."},
{"Couldn't toggle repeat. Please try again.", "Не удалось переключить повтор. Попробуйте ещё раз."},
{"Couldn't unsubscribe user. Please try again.", "Не удалось отписать пользователя. Попробуйте ещё раз."},
{"Couldn't unsubscribe you. Please try again.", "Не удалось отписать вас. Попробуйте ещё раз."},
{"Current language: {}. Available: en, ru. Use {}language <en|ru>.", "Текущий язык: {}. Доступно: en, ru. Используйте {}language <en|ru>."},
{"Current volume: {}%", "Текущая громкость: {}%"},
{"Favorites are unavailable.", "Избранное недоступно."},
{"History is unavailable (no database).", "История недоступна (нет базы данных)."},
{"Language settings are unavailable right now.", "Настройки языка сейчас недоступны."},
{"Loading playlist '{}'... Tracks will be added to the queue as they are resolved.", "Загрузка плейлиста «{}»... Треки будут добавляться в очередь по мере обработки."},
{"Moved track from position {} to {}.", "Трек перемещён с позиции {} на {}."},
{"No favorite with that number.", "Нет избранного с таким номером."},
{"No more tracks in the queue to skip to.", "В очереди больше нет треков для пропуска."},
{"No playlists available.", "Нет доступных плейлистов."},
{"No results found. Try different keywords.", "Ничего не найдено. Попробуйте другие слова."},
{"No search results found. Use {}play <query> to search first.", "Результатов поиска нет. Сначала выполните поиск: {}play <запрос>."},
{"No subscribers. Use !subscribe to receive audio.", "Подписчиков нет. Используйте !subscribe, чтобы получать звук."},
{"Nothing has been played yet.", "Пока ничего не воспроизводилось."},
{"Nothing is currently playing. Add something with {}play !", "Сейчас ничего не играет. Добавьте что-нибудь командой {}play !"},
{"Nothing is playing right now.", "Сейчас ничего не играет."},
{"Nothing to page through — run a command that lists results first.", "Нечего листать — сначала выполните команду со списком результатов."},
{"Off", "выкл"},
{"On", "вкл"},
{"One of those positions doesn't exist in the queue.", "Одной из этих позиций нет в очереди."},
{"Open the web interface", "Открыть веб-интерфейс"},
{"Playback isn't paused right now.", "Воспроизведение сейчас не на паузе."},
{"Playback paused.", "Воспроизведение приостановлено."},
{"Playback resumed.", "Воспроизведение возобновлено."},
{"Playback stopped and queue cleared.", "Воспроизведение остановлено, очередь очищена."},
{"Please provide a user UID. Use !subscribers to see UIDs.", "Укажите UID пользователя. Используйте !subscribers, чтобы увидеть UID."},
{"Please provide a valid number (0-100).", "Укажите корректное число (0-100)."},
{"Please provide a valid number (1 or more).", "Укажите корректное число (1 или больше)."},
{"Please provide a valid number (1, 2, 3, etc.).", "Укажите корректное число (1, 2, 3 и т.д.)."},
{"Please provide a valid number of seconds.\nExamples: seek +30, seek -10, seek 60", "Укажите корректное число секунд.\nПримеры: seek +30, seek -10, seek 60"},
{"Please provide a valid position number (starting from 1).", "Укажите корректный номер позиции (начиная с 1)."},
{"Please provide both from and to positions.", "Укажите позиции «откуда» и «куда»."},
{"Please provide valid position numbers (starting from 1).", "Укажите корректные номера позиций (начиная с 1)."},
{"Queue cleared!", "Очередь очищена!"},
{"Radio", "Радио"},
{"Reload is handled by the plugin. Use the TS plugin menu to reload the core.", "Перезагрузка выполняется плагином. Используйте меню плагина TS, чтобы перезагрузить ядро."},
{"Removed from favorites: {}", "Удалено из избранного: {}"},
{"Removed track at position {}.", "Удалён трек на позиции {}."},
{"Repeat", "Повтор"},
{"Repeat is now OFF.", "Повтор выключен."},
{"Search failed. Please try again later.", "Поиск не удался. Попробуйте позже."},
{"Search failed. Please try again.", "Поиск не удался. Попробуйте ещё раз."},
{"Search results for \"", "Результаты поиска по \""},
{"Seeked to position {}.", "Перемотано на позицию {}."},
{"Seeked {} from current position.", "Перемотано на {} от текущей позиции."},
{"Shuffle", "Перемешивание"},
{"Skipped to next track.", "Пропущено к следующему треку."},
{"Skipped {} tracks.", "Пропущено треков: {}."},
{"Something went wrong while trying to play. Please try again.", "Что-то пошло не так при воспроизведении. Попробуйте ещё раз."},
{"Something went wrong. Please try again.", "Что-то пошло не так. Попробуйте ещё раз."},
{"Statistics are unavailable (no database).", "Статистика недоступна (нет базы данных)."},
{"That doesn't look like a valid URL.", "Это не похоже на корректную ссылку."},
{"That playlist doesn't exist.", "Такого плейлиста не существует."},
{"That position doesn't exist in the queue.", "Такой позиции нет в очереди."},
{"The music service is currently unavailable.", "Музыкальный сервис сейчас недоступен."},
{"The music service is currently unavailable. Please try again later.", "Музыкальный сервис сейчас недоступен. Попробуйте позже."},
{"This track doesn't support seeking.", "Этот трек не поддерживает перемотку."},
{"Unable to get current playback position.", "Не удалось получить текущую позицию воспроизведения."},
{"Unable to get current volume.", "Не удалось получить текущую громкость."},
{"Unknown language. Choose 'en' or 'ru'.", "Неизвестный язык. Выберите «en» или «ru»."},
{"Unknown command. Type {}help for available commands.", "Неизвестная команда. Введите {}help, чтобы увидеть список команд."},
{"Usage: fav play <number> (see fav list)", "Использование: fav play <номер> (см. fav list)"},
{"Usage: fav remove <number> (see fav list)", "Использование: fav remove <номер> (см. fav list)"},
{"Usage: move <from> <to>\nExample: move 5 1 (moves track 5 to position 1)", "Использование: move <откуда> <куда>\nПример: move 5 1 (переместит трек 5 на позицию 1)"},
{"Usage: remove <position>\nUse {}queue to see track positions.", "Использование: remove <позиция>\nИспользуйте {}queue, чтобы увидеть позиции треков."},
{"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 <+/-секунды>\nПримеры:\n seek +30 (вперёд на 30с)\n seek -10 (назад на 10с)\n seek 60 (к отметке 1 минута)"},
{"Usage: select <number>\nSelect a track from your last search results.", "Использование: select <номер>\nВыберите трек из последних результатов поиска."},
{"Usage: {} <query>", "Использование: {} <запрос>"},
{"Usage: {} <url or search query>\nExample: {} never gonna give you up", "Использование: {} <ссылка или поисковый запрос>\nПример: {} never gonna give you up"},
{"Usage: {}announce <message>", "Использование: {}announce <сообщение>"},
{"Usage: {}fav add | list | play <n> | remove <n>", "Использование: {}fav add | list | play <n> | remove <n>"},
{"Usage: {}page <n>, or {}next / {}prev.", "Использование: {}page <n> или {}next / {}prev."},
{"Use `!unsubscribeall` to remove all subscribers.", "Используйте `!unsubscribeall`, чтобы удалить всех подписчиков."},
{"Use `!unsubscribeid <uid>` to remove a specific subscriber.\n", "Используйте `!unsubscribeid <uid>`, чтобы удалить конкретного подписчика.\n"},
{"Volume", "Громкость"},
{"Volume must be between 0 and 100.", "Громкость должна быть от 0 до 100."},
{"Volume: {}%", "Громкость: {}%"},
{"Volume: {}% {}", "Громкость: {}% {}"},
{"You don't have permission to use this command.", "У вас нет прав на использование этой команды."},
{"You have no favorites yet. Save the current track with {}fav add", "У вас пока нет избранного. Сохраните текущий трек командой {}fav add"},
{"⏸ Paused | ", "⏸ Пауза | "},
{"✅ Configuration reloaded from disk.", "✅ Конфигурация перезагружена с диска."},
{"✅ Configuration reloaded. For a full core reload, use the TS plugin menu.", "✅ Конфигурация перезагружена. Для полной перезагрузки ядра используйте меню плагина TS."},
{"✅ Language set to {}.", "✅ Язык установлен: {}."},
{"📁 Available playlists:\n", "📁 Доступные плейлисты:\n"},
{"📋 **Subscribed Users** (", "📋 **Подписчики** ("},
{"📜 **Queue** (Page ", "📜 **Очередь** (страница "},
{"📻 Autoplay is OFF.", "📻 Автовоспроизведение выключено."},
{"📻 Autoplay is ON — I'll keep the music going with related tracks.", "📻 Автовоспроизведение включено — буду добавлять похожие треки."},
{"🔀 Queue shuffled!", "🔀 Очередь перемешана!"},
{"🔀 Shuffle | ", "🔀 Перемешивание | "},
{"🔁 Repeat is now ON.", "🔁 Повтор включён."},
{"🔁 Repeat | ", "🔁 Повтор | "},
{"🟢 Online: ", "🟢 В сети: "},
// --- Command descriptions & usage hints (shown in !help) ---
{"Clears all tracks from the queue.", "Очищает все треки из очереди."},
{"Get RPC server connection information", "Показать данные подключения к RPC-серверу"},
{"Lists all subscribed users (online/offline).", "Показывает всех подписчиков (в сети/не в сети)."},
{"Lists or loads a playlist.", "Показывает или загружает плейлист."},
{"Manage your favorite tracks", "Управление избранными треками"},
{"Moves a track to a different position in the queue.", "Перемещает трек на другую позицию в очереди."},
{"Pauses the current playback.", "Ставит воспроизведение на паузу."},
{"Plays a track from URL, or searches YouTube and Yandex Music and lets you select.", "Воспроизводит трек по ссылке или ищет на YouTube и Yandex Music с выбором."},
{"Plays from Yandex Music only (URL or search).", "Воспроизводит только из Yandex Music (ссылка или поиск)."},
{"Plays from YouTube only (URL or search).", "Воспроизводит только из YouTube (ссылка или поиск)."},
{"Reloads the bot configuration from file.", "Перезагружает конфигурацию бота из файла."},
{"Removes a track from the queue by position.", "Удаляет трек из очереди по позиции."},
{"Removes all subscriptions (admin only).", "Удаляет все подписки (только админ)."},
{"Resumes the paused playback.", "Возобновляет приостановленное воспроизведение."},
{"Search Yandex Music only for tracks.", "Искать треки только в Yandex Music."},
{"Search YouTube and Yandex Music for tracks.", "Искать треки на YouTube и Yandex Music."},
{"Search YouTube only for tracks.", "Искать треки только на YouTube."},
{"Seeks to a position in the current track. Use +seconds to skip forward, -seconds to skip backward.", "Перемотка текущего трека. +секунды — вперёд, -секунды — назад."},
{"Selects a track from your search results.", "Выбирает трек из результатов поиска."},
{"Send an announcement to all subscribers (admin).", "Отправляет объявление всем подписчикам (админ)."},
{"Sets or shows the playback volume.", "Устанавливает или показывает громкость воспроизведения."},
{"Sets your reply language (English or Russian).", "Устанавливает язык ответов (английский или русский)."},
{"Show playback statistics", "Показать статистику воспроизведения"},
{"Show recently played tracks", "Показать недавно проигранные треки"},
{"Shows information about reloading the bot.", "Показывает информацию о перезапуске бота."},
{"Shows the current queue and playback status.", "Показывает текущую очередь и статус воспроизведения."},
{"Shows the currently playing track.", "Показывает текущий трек."},
{"Skips to the next track(s).", "Пропускает к следующему треку(ам)."},
{"Stops playback and clears the queue.", "Останавливает воспроизведение и очищает очередь."},
{"Subscribes to the music bot to receive audio.", "Подписаться на музыкального бота, чтобы получать звук."},
{"Toggles radio mode: auto-queues related tracks when the queue runs out.", "Переключает режим радио: добавляет похожие треки, когда очередь заканчивается."},
{"Toggles repeat mode for the current track.", "Переключает режим повтора текущего трека."},
{"Toggles shuffle mode for the queue.", "Переключает режим перемешивания очереди."},
{"Unsubscribes a user by their UID (admin only).", "Отписывает пользователя по его UID (только админ)."},
{"Unsubscribes from the music bot.", "Отписаться от музыкального бота."},
{"Shows this help message with all available commands.", "Показывает эту справку со всеми доступными командами."},
{"Shows another page of the last long reply (also !next / !prev).", "Показывает другую страницу последнего длинного ответа (также !next / !prev)."},
{"<+/-seconds>", "<+/-секунды>"},
{"<from> <to>", "<откуда> <куда>"},
{"<message>", "<сообщение>"},
{"<number>", "<номер>"},
{"<position>", "<позиция>"},
{"<query>", "<запрос>"},
{"<url or search query>", "<ссылка или поисковый запрос>"},
{"[count]", "[кол-во]"},
{"[playlist name]", "[название плейлиста]"},
{"[command]", "[команда]"},
{"[n|next|prev]", "[n|next|prev]"},
+112 -23
View File
@@ -11,6 +11,18 @@ namespace Echoion::Core
{
constexpr size_t MAX_BUFFER_SHORTS =
PlaybackEngine::SHORTS_PER_CHUNK * 50;
// Crossfade readiness gate cap (1.5s of stereo PCM): never demand
// more buffered incoming audio than the decoder queue can physically
// hold (~2s for Opus/YouTube), or long fades could never start.
constexpr size_t FADE_GATE_CAP_SHORTS =
PlaybackEngine::SAMPLE_RATE * PlaybackEngine::CHANNELS * 3 / 2;
// Micro-ramp (~4ms) applied to the incoming track when it resumes
// after a mid-fade buffer underrun, so it doesn't cut back in with
// an audible step while the outgoing tail is still playing.
constexpr size_t FADE_RAMP_SHORTS =
PlaybackEngine::SAMPLE_RATE * PlaybackEngine::CHANNELS * 4 / 1000;
} // namespace
PlaybackEngine::PlaybackEngine(IPlaybackHost& host) : host_(host) {}
@@ -209,7 +221,23 @@ namespace Echoion::Core
if (duration.count() > 0 &&
duration - position <=
std::chrono::milliseconds(fade)) {
beginCrossfade();
// A proxied network stream may still be filling its
// decode queue. Only start the fade once the incoming
// side has buffered enough audio to survive it —
// otherwise the fade envelope races ahead of the
// starving ring and chops the incoming audio ~50
// times a second (an audible buzz over the outgoing
// tail). If the gate never passes, EOF falls back to
// the plain gapless handoff.
const auto fadeShorts = static_cast<std::size_t>(
fade * SAMPLE_RATE * CHANNELS / 1000);
const std::size_t ready =
std::min(fadeShorts, FADE_GATE_CAP_SHORTS);
if (next_.decoder->isFinished() ||
next_.decoder->queueSaturated() ||
next_.decoder->queuedSamples() >= ready) {
beginCrossfade();
}
}
}
}
@@ -219,7 +247,7 @@ namespace Echoion::Core
// 4) Emit one chunk per 20ms tick.
const bool fading =
!fadeTail_.empty() && fadePos_ < fadeTail_.size();
!fadeTail_.empty() && fadeEnvPos_ < fadeTail_.size();
if (ring_.size() >= SHORTS_PER_CHUNK || fading) {
// Full chunk available, OR a crossfade is in progress (the
// outgoing tail covers a not-yet-full incoming ring so the
@@ -241,8 +269,14 @@ namespace Echoion::Core
if (silenceSince_.time_since_epoch().count() == 0) {
silenceSince_ = std::chrono::steady_clock::now();
}
// A download-to-file retry legitimately takes far longer than
// the normal resolve grace; don't skip a track whose download
// is still in progress.
const int64_t graceMs = current_.triedDownload
? DOWNLOAD_GRACE_MS
: resolveGraceMs_.load();
if (std::chrono::steady_clock::now() - silenceSince_ >
std::chrono::milliseconds(resolveGraceMs_.load())) {
std::chrono::milliseconds(graceMs)) {
Void::Log::warn(
"PlaybackEngine", "{}",
"Track resolve exceeded grace period, skipping");
@@ -321,6 +355,9 @@ namespace Echoion::Core
auto entry = *slot.entry;
slot.state = DecoderSlot::State::Resolving;
slot.resolveStartedAt = std::chrono::steady_clock::now();
// Restart the silence-grace clock: time burnt on the failed direct
// open must not count against the download's (longer) grace window.
silenceSince_ = {};
slot.resolveFuture = std::async(std::launch::async, [this, entry]() {
// preferDownload=true evicts the poisoned cache entry and
// downloads through the proxy (yt-dlp handles SOCKS5).
@@ -434,6 +471,9 @@ namespace Echoion::Core
}
ring_.clear();
clearFade();
// seek() is asynchronous: it publishes a request that the decode
// thread performs. Failure here only means "no source open";
// av_seek_frame errors are logged by the decoder itself.
auto result = current_.decoder->seek(cmd.position);
if (result) {
clock_.seekTo(cmd.position);
@@ -617,7 +657,9 @@ namespace Echoion::Core
crossfadeMs_.load() * SAMPLE_RATE * CHANNELS / 1000);
fadeTail_.clear();
fadePos_ = 0;
fadeTailPos_ = 0;
fadeEnvPos_ = 0;
fadeIncomingStarved_ = false;
fadeTail_.reserve(ring_.size() + maxTailSamples);
for (std::size_t i = 0; i < ring_.size(); ++i) {
fadeTail_.push_back(ring_[i]);
@@ -811,37 +853,84 @@ namespace Echoion::Core
if (fromRing) {
const size_t available = std::min(ring_.size(), SHORTS_PER_CHUNK);
const bool fading =
!fadeTail_.empty() && fadePos_ < fadeTail_.size();
!fadeTail_.empty() && fadeEnvPos_ < fadeTail_.size();
// The number of output samples we actually fill: during a fade
// we emit a FULL chunk even when the incoming ring is still
// short (the outgoing tail covers the gap), so a track handoff
// never leaves the TS3 device starved. Otherwise it's just what
// the ring holds.
const size_t filled = fading ? SHORTS_PER_CHUNK : available;
// The number of output samples we actually fill and how much of
// the ring we consume. During a fade we emit a FULL chunk even
// when the incoming ring is short (the outgoing tail covers the
// gap), so a track handoff never leaves the TS3 device starved.
// Otherwise it's just what the ring holds.
size_t filled = available;
size_t consumed = available;
if (fading) {
// Equal-power blend: incoming (ring, or 0 if not ready yet)
// rises while the outgoing tail falls, across the whole
// chunk.
// Equal-power blend: the incoming (ring) rises while the
// outgoing tail falls. The tail plays continuously; the
// envelope only advances as incoming audio is delivered, so
// an underrun stretches the fade instead of chopping the
// incoming signal against a racing envelope.
filled = SHORTS_PER_CHUNK;
const auto fadeLen = static_cast<float>(fadeTail_.size());
const bool starved = available < SHORTS_PER_CHUNK;
// Starvation boundaries get micro-ramps on the incoming
// signal: the first starved tick ramps it out over the
// samples that remain, and the first tick after recovery
// ramps it back in — the incoming never appears or vanishes
// with an audible step under the still-playing tail. While
// starvation persists nothing is consumed (the ring is left
// to refill to a full chunk).
const size_t rampOut =
(starved && !fadeIncomingStarved_) ? available : 0;
const size_t rampIn =
(!starved && fadeIncomingStarved_) ? FADE_RAMP_SHORTS : 0;
consumed = starved ? rampOut : SHORTS_PER_CHUNK;
for (size_t i = 0; i < SHORTS_PER_CHUNK; ++i) {
const float incoming =
i < available ? static_cast<float>(ring_[i]) : 0.0f;
const bool hasIncoming = i < consumed;
float incoming = 0.0f;
if (hasIncoming) {
incoming = static_cast<float>(ring_[i]);
if (rampOut > 0) {
incoming *= 1.0f -
static_cast<float>(i) /
static_cast<float>(rampOut);
} else if (i < rampIn) {
incoming *= static_cast<float>(i) /
static_cast<float>(rampIn);
}
}
float mixed = incoming;
if (fadePos_ < fadeTail_.size()) {
if (fadeEnvPos_ < fadeTail_.size()) {
const float theta =
(static_cast<float>(fadePos_) / fadeLen) *
(static_cast<float>(fadeEnvPos_) / fadeLen) *
1.57079632679f; // pi/2
const float tail =
fadeTailPos_ < fadeTail_.size()
? static_cast<float>(fadeTail_[fadeTailPos_])
: 0.0f;
mixed = incoming * std::sin(theta) +
static_cast<float>(fadeTail_[fadePos_]) *
std::cos(theta);
++fadePos_;
tail * std::cos(theta);
if (fadeTailPos_ < fadeTail_.size()) {
++fadeTailPos_;
}
// Envelope lockstep: advance with delivered incoming
// samples. Once the tail itself is exhausted there
// is nothing left to hold for — let the envelope
// complete so the incoming finishes its rise (or,
// with both sources dry, the fade ends and normal
// starvation handling resumes).
if (hasIncoming ||
fadeTailPos_ >= fadeTail_.size()) {
++fadeEnvPos_;
}
}
outChunk_[i] = static_cast<short>(std::clamp(
static_cast<int>(mixed), -32768, 32767));
}
if (fadePos_ >= fadeTail_.size()) {
fadeIncomingStarved_ = starved;
if (fadeEnvPos_ >= fadeTail_.size()) {
clearFade();
}
} else {
@@ -868,7 +957,7 @@ namespace Echoion::Core
std::fill(outChunk_.begin() +
static_cast<std::ptrdiff_t>(filled),
outChunk_.end(), 0);
ring_.popFront(available);
ring_.popFront(consumed);
} else {
std::fill(outChunk_.begin(), outChunk_.end(), 0);
}
+42 -32
View File
@@ -38,6 +38,14 @@ namespace Echoion::Core
}
}
void SourceRouter::addSource(std::shared_ptr<ITrackSource> source)
{
if (!source) return;
std::lock_guard lock(mutex_);
allSources_.push_back(source);
chain_.push_back(SourceState{.source = std::move(source)});
}
void SourceRouter::setOrder(const std::vector<std::string>& order)
{
std::lock_guard<std::mutex> lock(mutex_);
@@ -73,13 +81,13 @@ namespace Echoion::Core
hedgeDelay_ = std::max(delay, std::chrono::milliseconds(0));
}
std::vector<SourceRouter::SourceState*>
SourceRouter::candidatesFor(const std::string& query, bool needSearch)
std::vector<std::shared_ptr<ITrackSource>>
SourceRouter::candidatesFor(const std::string& query, bool needSearch)
{
// Callers hold mutex_.
const auto now = std::chrono::steady_clock::now();
std::vector<SourceState*> eligible;
std::vector<SourceState*> coolingDown;
std::vector<std::shared_ptr<ITrackSource>> eligible;
std::vector<std::shared_ptr<ITrackSource>> coolingDown;
for (auto& state : chain_) {
if (needSearch && !state.source->supportsSearch()) {
@@ -89,10 +97,10 @@ namespace Echoion::Core
continue;
}
if (state.cooldownUntil > now) {
coolingDown.push_back(&state);
coolingDown.push_back(state.source);
continue;
}
eligible.push_back(&state);
eligible.push_back(state.source);
}
// A source on cooldown is still tried when nothing else matched —
// better a likely-failing attempt than an immediate error.
@@ -102,13 +110,17 @@ namespace Echoion::Core
return eligible;
}
void SourceRouter::reportFailure(SourceState& state)
void SourceRouter::reportFailure(const std::shared_ptr<ITrackSource>& source)
{
state.cooldownUntil = std::chrono::steady_clock::now() + cooldown_;
auto state = std::ranges::find_if(chain_, [&](const SourceState& candidate) {
return candidate.source == source;
});
if (state == chain_.end()) return;
state->cooldownUntil = std::chrono::steady_clock::now() + cooldown_;
Void::Log::info(
"SourceRouter", "{}",
std::format("Source '{}' on cooldown for {}s",
state.source->name(), cooldown_.count() / 1000));
source->name(), cooldown_.count() / 1000));
}
Api::Result<Api::SearchResult> SourceRouter::search(std::string_view query)
@@ -119,17 +131,17 @@ namespace Echoion::Core
Api::Error lastError{Api::ErrorCode::ServiceUnavailable,
"No source can search"};
for (auto* state : candidates) {
if (!state->source->isAvailable()) {
for (const auto& source : candidates) {
if (!source->isAvailable()) {
continue;
}
auto result = state->source->search(query);
auto result = source->search(query);
if (result) {
return result;
}
lastError = result.error();
std::lock_guard<std::mutex> relock(mutex_);
reportFailure(*state);
reportFailure(source);
}
return std::unexpected(lastError);
}
@@ -142,21 +154,21 @@ namespace Echoion::Core
Api::Error lastError{Api::ErrorCode::NotFound,
"No source can resolve this query"};
for (auto* state : candidates) {
if (!state->source->isAvailable()) {
for (const auto& source : candidates) {
if (!source->isAvailable()) {
continue;
}
Void::Log::debug(
"SourceRouter", "{}",
std::format("Resolving '{}' via {}", query,
state->source->name()));
auto result = state->source->resolve(query);
source->name()));
auto result = source->resolve(query);
if (result) {
return result;
}
lastError = result.error();
std::lock_guard<std::mutex> relock(mutex_);
reportFailure(*state);
reportFailure(source);
}
return std::unexpected(lastError);
}
@@ -191,10 +203,10 @@ namespace Echoion::Core
const auto hedgeDelay = hedgeDelay_;
lock.unlock();
std::vector<SourceState*> eligible;
for (auto* state : candidates) {
if (state->source->isAvailable()) {
eligible.push_back(state);
std::vector<std::shared_ptr<ITrackSource>> eligible;
for (const auto& source : candidates) {
if (source->isAvailable()) {
eligible.push_back(source);
}
}
@@ -253,7 +265,7 @@ namespace Echoion::Core
}).detach();
};
launch(eligible[0]->source, 0);
launch(eligible[0], 0);
int launched = 1;
std::optional<Api::Result<StreamHandle>> winner;
std::array<bool, 2> failed{false, false};
@@ -267,7 +279,7 @@ namespace Echoion::Core
if (!state->winner) {
// A is slow or already failed: bring in B.
lk.unlock();
launch(eligible[1]->source, 1);
launch(eligible[1], 1);
launched = 2;
lk.lock();
state->cv.wait(lk, [&] {
@@ -291,11 +303,9 @@ namespace Echoion::Core
"SourceRouter", "{}",
std::format(
"Source '{}' failed stream for '{}': {}",
eligible[static_cast<size_t>(slot)]
->source->name(),
eligible[static_cast<size_t>(slot)]->name(),
cacheKey, lastError.message));
reportFailure(
*eligible[static_cast<size_t>(slot)]);
reportFailure(eligible[static_cast<size_t>(slot)]);
}
}
}
@@ -308,8 +318,8 @@ namespace Echoion::Core
// Sequential pass over the remaining candidates (or all of them
// when hedging is disabled).
for (; index < eligible.size(); ++index) {
auto* state = eligible[index];
auto handle = state->source->getStream(track);
const auto& source = eligible[index];
auto handle = source->getStream(track);
if (handle) {
return finish(std::move(handle));
}
@@ -317,10 +327,10 @@ namespace Echoion::Core
Void::Log::warn(
"SourceRouter", "{}",
std::format("Source '{}' failed stream for '{}': {}",
state->source->name(), cacheKey,
source->name(), cacheKey,
handle.error().message));
std::lock_guard<std::mutex> relock(mutex_);
reportFailure(*state);
reportFailure(source);
}
return std::unexpected(lastError);
}
+3 -23
View File
@@ -2,6 +2,7 @@
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Text/Url.hpp>
#include <format>
#include <openssl/evp.h>
#include <regex>
@@ -62,27 +63,6 @@ namespace Echoion::Core
return std::regex_search(url, playlist);
}
std::string percentEncode(std::string_view text)
{
static constexpr char hex[] = "0123456789ABCDEF";
std::string out;
out.reserve(text.size() * 3);
for (unsigned char c : text) {
const bool unreserved = (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '-' ||
c == '_' || c == '.' || c == '~';
if (unreserved) {
out.push_back(static_cast<char>(c));
} else {
out.push_back('%');
out.push_back(hex[c >> 4]);
out.push_back(hex[c & 0xF]);
}
}
return out;
}
std::string str(const Void::Json::Value& v, const char* key)
{
const auto* f = v.find(key);
@@ -198,8 +178,8 @@ namespace Echoion::Core
"Yandex Music not configured");
}
auto body =
apiGet("/search?type=track&page=0&text=" + percentEncode(query));
auto body = apiGet("/search?type=track&page=0&text=" +
Void::Encoding::Url::encode(query));
if (!body) {
return std::unexpected(body.error());
}
+16 -1
View File
@@ -78,7 +78,22 @@ namespace Echoion::Core
t.id = urlOrId;
t.title = urlOrId;
t.source = Api::TrackSource::URL;
t.originalUrl = urlOrId;
// If a YouTube video id is still extractable here (e.g. a youtu.be
// short link that skipped the video-info path), expand it to the
// canonical watch URL so originalUrl is never a shortened form —
// mirrors InnertubeSource so "open original link" opens the long URL.
if (client_) {
if (auto videoId = client_->extractVideoId(urlOrId)) {
t.id = *videoId;
t.source = Api::TrackSource::YouTube;
t.originalUrl =
std::format("https://www.youtube.com/watch?v={}", *videoId);
} else {
t.originalUrl = urlOrId;
}
} else {
t.originalUrl = urlOrId;
}
t.addedAt = std::chrono::system_clock::now();
return t;
}
+6 -27
View File
@@ -101,33 +101,12 @@ namespace Echoion::Core
uint32_t StateSerializer::extractVersion(const std::string& jsonStr)
{
// Quick extraction without full parse
// Look for "version": N pattern
size_t pos = jsonStr.find("\"version\"");
if (pos != std::string::npos) {
pos = jsonStr.find(':', pos);
if (pos != std::string::npos) {
// Skip whitespace
pos++;
while (pos < jsonStr.size() &&
std::isspace(static_cast<unsigned char>(jsonStr[pos]))) {
pos++;
}
// Parse number
if (pos < jsonStr.size() &&
std::isdigit(static_cast<unsigned char>(jsonStr[pos]))) {
try {
return static_cast<uint32_t>(
std::stoul(jsonStr.substr(pos)));
} catch (const std::exception&) {
return 0;
}
}
}
}
// Default to 0 (unknown/legacy)
return 0;
// Read only the root field. A textual search can accidentally select a
// nested schema version (for example an extension plugin's state).
auto parsed = Void::Json::parse(jsonStr);
if (!parsed || !parsed->is_object()) return 0;
const auto version = parsed->get_num("version", 0);
return version > 0 ? static_cast<uint32_t>(version) : 0;
}
} // namespace Echoion::Core
+63
View File
@@ -0,0 +1,63 @@
#include "echoion/core/util/Paginate.hpp"
namespace Echoion::Core::Util
{
std::vector<std::string> paginate(std::string_view text, std::size_t limit)
{
std::vector<std::string> pages;
if (limit == 0) {
pages.emplace_back(text);
return pages;
}
if (text.size() <= limit) {
pages.emplace_back(text);
return pages;
}
std::string current;
auto flush = [&] {
if (!current.empty()) {
pages.push_back(current);
current.clear();
}
};
std::size_t pos = 0;
while (pos < text.size()) {
const std::size_t nl = text.find('\n', pos);
std::string line =
(nl == std::string_view::npos)
? std::string(text.substr(pos))
: std::string(text.substr(pos, nl - pos + 1));
pos = (nl == std::string_view::npos) ? text.size() : nl + 1;
// Start a new page when appending this line would overflow.
if (!current.empty() && current.size() + line.size() > limit) {
flush();
}
// Hard-split a single line that is itself longer than the limit,
// cutting on a UTF-8 continuation boundary so multi-byte code
// points are never severed.
while (line.size() > limit) {
std::size_t cut = limit;
while (cut > 0 &&
(static_cast<unsigned char>(line[cut]) & 0xC0) == 0x80) {
--cut;
}
if (cut == 0) {
cut = limit; // pathological line; avoid an infinite loop
}
flush();
pages.push_back(line.substr(0, cut));
line.erase(0, cut);
}
current += line;
}
flush();
return pages;
}
} // namespace Echoion::Core::Util
+138
View File
@@ -0,0 +1,138 @@
#include "echoion/core/ConfigLoader.hpp"
#include <iostream>
#include <string>
#include <string_view>
namespace
{
int failures = 0;
void expect(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
++failures;
}
}
void expectShortening(std::string_view name, std::string_view json,
bool enabled, std::string_view provider)
{
const auto config = Echoion::Core::ConfigLoader::loadFromJson(json);
if (!config) {
std::cerr << "FAILED: " << name
<< " did not parse: " << config.error().message << '\n';
++failures;
return;
}
expect(config->urlShortening.enabled == enabled,
std::string{name} + " enabled state");
expect(config->urlShortening.provider == provider,
std::string{name} + " provider");
}
} // namespace
int main()
{
using Echoion::Core::ConfigLoader;
const auto defaults = ConfigLoader::createDefaultConfig();
expect(!defaults.urlShortening.enabled,
"generated defaults keep URL shortening disabled");
expect(defaults.logging.fileName == "echoion.log" &&
defaults.logging.maxFiles == 10,
"generated defaults configure bounded rolling logs");
const auto logging = ConfigLoader::loadFromJson(R"({
"logging": {
"level": "verbose",
"fileName": "../outside.log",
"maxFileSizeBytes": 1,
"maxFiles": 0
}
})");
expect(logging.has_value(), "logging configuration parses");
if (logging) {
expect(logging->logging.level == "debug",
"invalid log level is normalized");
expect(logging->logging.fileName == "echoion.log",
"log file cannot escape the state log directory");
expect(logging->logging.maxFileSizeBytes == 64 * 1024,
"log size is clamped to a safe minimum");
expect(logging->logging.maxFiles == 1,
"at least one rolled log is retained");
}
const auto parentLog =
ConfigLoader::loadFromJson(R"({"logging":{"fileName":".."}})");
expect(parentLog && parentLog->logging.fileName == "echoion.log",
"parent-directory logging filename is normalized");
expectShortening("legacy disabled",
R"({
"youtube": {"enableUrlShortening": false},
"web": {"publicUrl": "https://bot.example"}
})",
false, "url-shortener-internal");
const auto legacyEnabled = ConfigLoader::loadFromJson(R"({
"youtube": {"enableUrlShortening": true},
"web": {"publicUrl": "https://bot.example"}
})");
if (!legacyEnabled) {
std::cerr << "FAILED: legacy enabled did not parse: "
<< legacyEnabled.error().message << '\n';
++failures;
} else {
expect(legacyEnabled->urlShortening.enabled,
"legacy enabled flag migrates through JSON updates");
expect(legacyEnabled->urlShortening.provider ==
"url-shortener-internal",
"legacy migration selects internal provider");
expect(legacyEnabled->urlShortening.sources.size() == 1 &&
legacyEnabled->urlShortening.sources.front() == "youtube",
"legacy migration limits shortening to YouTube");
}
expectShortening("explicit section wins",
R"({
"youtube": {"enableUrlShortening": true},
"urlShortening": {
"enabled": false,
"provider": "url-shortener-internal"
},
"web": {"publicUrl": "https://bot.example"}
})",
false, "url-shortener-internal");
expectShortening("internal provider without public URL",
R"({
"urlShortening": {
"enabled": true,
"provider": "url-shortener-internal"
}
})",
false, "url-shortener-internal");
expectShortening("internal provider with public URL",
R"({
"urlShortening": {
"enabled": true,
"provider": "url-shortener-internal"
},
"web": {"publicUrl": "https://bot.example"}
})",
true, "url-shortener-internal");
expectShortening("external provider without public URL",
R"({
"urlShortening": {
"enabled": true,
"provider": "url-shortener-external"
}
})",
true, "url-shortener-external");
return failures == 0 ? 0 : 1;
}
+34
View File
@@ -0,0 +1,34 @@
#include "echoion/core/state/StateSerializer.hpp"
#include <iostream>
#include <string>
int main()
{
Echoion::Core::StateV1 state;
state.extensionPlugins.push_back({.name = "example", .json = "{\"v\":1}",
.version = 3});
auto blob = Echoion::Core::StateSerializer::serialize(state);
std::string json{blob.data.begin(), blob.data.end()};
// State written by the removed experimental rooms build must remain safe to
// load during a hot reload. Void reflection intentionally ignores unknown
// root fields, so the obsolete payload is discarded rather than rejected.
json.insert(json.rfind('}'),
R"(,"listeningRooms":[{"name":"legacy","subscribers":["uid"]}])");
blob.data.assign(json.begin(), json.end());
const auto restored = Echoion::Core::StateSerializer::deserialize(blob);
if (!restored) {
std::cerr << "extension state did not deserialize: "
<< restored.error().message << '\n';
return 1;
}
if (restored->extensionPlugins.size() != 1 ||
restored->extensionPlugins.front().name != "example" ||
restored->extensionPlugins.front().version != 3) {
std::cerr << "extension plugin state did not round-trip\n";
return 1;
}
return 0;
}
+82
View File
@@ -0,0 +1,82 @@
#include "echoion/core/LogRotation.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string_view>
namespace
{
int failures = 0;
void expect(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
++failures;
}
}
std::size_t archiveCount(const std::filesystem::path& history)
{
std::size_t count = 0;
std::error_code error;
for (std::filesystem::directory_iterator iterator(history, error), end;
!error && iterator != end; iterator.increment(error)) {
if (iterator->is_regular_file()) {
++count;
}
}
return count;
}
} // namespace
int main()
{
const auto root =
std::filesystem::temp_directory_path() / "echoion-log-rotation-test";
std::error_code error;
std::filesystem::remove_all(root, error);
std::filesystem::create_directories(root, error);
const auto active = root / "echoion.log";
{
std::ofstream file(active);
file << "first run\n";
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(!error, "first startup rotation succeeds");
expect(!std::filesystem::exists(active),
"startup rotation leaves no old active file");
expect(archiveCount(root / "history") == 1, "first run is archived");
for (int run = 0; run < 3; ++run) {
{
std::ofstream file(active);
file << "run " << run << '\n';
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(!error, "subsequent startup rotation succeeds");
}
expect(archiveCount(root / "history") == 2,
"startup rotation prunes to configured history count");
{
std::ofstream file(active);
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(!error && !std::filesystem::exists(active),
"empty active file is removed instead of archived");
std::filesystem::remove_all(root / "history", error);
{
std::ofstream invalidHistory(root / "history");
invalidHistory << "not a directory\n";
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(error == std::errc::invalid_argument,
"non-directory history path was accepted");
std::filesystem::remove_all(root, error);
return failures == 0 ? 0 : 1;
}
+141
View File
@@ -0,0 +1,141 @@
#include "PluginCompatibility.hpp"
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Runner.hpp>
#include <Void/Testing/Test.hpp>
#include <array>
#include <cstddef>
#include <string_view>
namespace
{
echoion_string_view_v1 view(const std::string_view value)
{
return {.data = value.data(), .size = value.size()};
}
echoion_status_v1 create(const echoion_module_host_v1*,
echoion_module_instance_v1*)
{
return ECHOION_STATUS_OK_V1;
}
void destroy(echoion_module_instance_v1) {}
echoion_status_v1 activate(echoion_module_instance_v1)
{
return ECHOION_STATUS_OK_V1;
}
echoion_status_v1 quiesce(echoion_module_instance_v1, std::int64_t)
{
return ECHOION_STATUS_OK_V1;
}
echoion_status_v1 checkpoint(echoion_module_instance_v1,
echoion_write_bytes_fn_v1, void*)
{
return ECHOION_STATUS_OK_V1;
}
echoion_status_v1 restore(echoion_module_instance_v1, echoion_bytes_view_v1)
{
return ECHOION_STATUS_OK_V1;
}
echoion_status_v1 readiness(echoion_module_instance_v1,
echoion_module_readiness_v1*)
{
return ECHOION_STATUS_OK_V1;
}
echoion_status_v1 deactivate(echoion_module_instance_v1)
{
return ECHOION_STATUS_OK_V1;
}
const echoion_module_api_v1 api{
.struct_size = sizeof(echoion_module_api_v1),
.abi_version = ECHOION_MODULE_ABI_VERSION,
.create = create,
.destroy = destroy,
.activate = activate,
.quiesce = quiesce,
.checkpoint = checkpoint,
.restore = restore,
.readiness = readiness,
.deactivate = deactivate,
.reserved = {},
};
std::array<echoion_module_dependency_v1, 2>
dependencies(const std::string_view apiHash,
const std::string_view coreHash)
{
return {{
{
.struct_size = sizeof(echoion_module_dependency_v1),
.component_id = view("EchoionApi"),
.version_range = view(">=2.0.0 <3.0.0"),
.abi_hash = view(apiHash),
.optional = 0,
.reserved_bytes = {},
},
{
.struct_size = sizeof(echoion_module_dependency_v1),
.component_id = view("EchoionCore"),
.version_range = view(">=2.0.0 <3.0.0"),
.abi_hash = view(coreHash),
.optional = 0,
.reserved_bytes = {},
},
}};
}
echoion_module_descriptor_v1
descriptor(const std::array<echoion_module_dependency_v1, 2>& values)
{
return {
.struct_size = sizeof(echoion_module_descriptor_v1),
.abi_version = ECHOION_MODULE_ABI_VERSION,
.component_id = view("EchoionPluginExample"),
.version_major = 2,
.version_minor = 0,
.version_patch = 0,
.version_prerelease = {},
.abi_hash = view("sha256:example"),
.dependencies = values.data(),
.dependency_count = values.size(),
.activation_policy = ECHOION_ACTIVATION_RELOADABLE_V1,
.api = &api,
.reserved = {},
};
}
} // namespace
Void::Testing::Test compatible_v2_extension_descriptor_is_accepted()
{
const auto values = dependencies(
"sha256:"
"d50293d345a97e52f9844088bdd42277f566bc815a21b7636d3e053f06c6c113",
"sha256:"
"9cb668e2a502dcfe02d145ed63635d63619732d77ff5749685834382705e8d21");
const auto candidate = descriptor(values);
const auto result =
Echoion::Core::Detail::checkExtensionDescriptor(&candidate);
Void::Testing::expect(result.compatible);
}
Void::Testing::Test legacy_or_mismatched_extension_descriptor_is_rejected()
{
const auto values = dependencies("sha256:old-api", "sha256:old-core");
auto candidate = descriptor(values);
auto result = Echoion::Core::Detail::checkExtensionDescriptor(&candidate);
Void::Testing::expect(!result.compatible);
candidate.version_major = 1;
result = Echoion::Core::Detail::checkExtensionDescriptor(&candidate);
Void::Testing::expect(!result.compatible);
Void::Testing::expect(
!Echoion::Core::Detail::checkExtensionDescriptor(nullptr).compatible);
}
int main(int argc, char** argv)
{
return Void::Testing::Runner::instance().main(argc, argv);
}
+188
View File
@@ -0,0 +1,188 @@
#include "echoion/core/TeamSpeakDirectoryService.hpp"
#include "echoion/core/detail/RpcValidation.hpp"
#include <Void/Data/Json.hpp>
#include <cassert>
#include <memory>
#include <span>
#include <string>
#include <vector>
namespace
{
class FakePlugin final : public Echoion::Api::IPluginInterface
{
public:
Echoion::Api::Result<void> initialize() override { return {}; }
Echoion::Api::Result<void> shutdown() override { return {}; }
Echoion::Api::Result<std::vector<Echoion::Api::ClientInfo>>
getClients() override
{
return clients;
}
Echoion::Api::Result<std::optional<Echoion::Api::ClientInfo>>
getClient(uint64_t id) override
{
for (const auto& client : clients) {
if (client.id == id) {
return client;
}
}
return std::optional<Echoion::Api::ClientInfo>{};
}
Echoion::Api::Result<void> moveClient(uint64_t, uint64_t) override
{
return {};
}
Echoion::Api::Result<void> kickClient(uint64_t,
const std::string&) override
{
return {};
}
Echoion::Api::Result<std::vector<Echoion::Api::ChannelInfo>>
getChannels() const override
{
return channels;
}
Echoion::Api::Result<std::optional<Echoion::Api::ChannelInfo>>
getChannel(uint64_t id) const override
{
for (const auto& channel : channels) {
if (channel.id == id) {
return channel;
}
}
return std::optional<Echoion::Api::ChannelInfo>{};
}
Echoion::Api::Result<void>
sendTextMessage(uint64_t, const std::string&) override
{
return {};
}
Echoion::Api::Result<void>
sendChannelMessage(uint64_t, const std::string&) override
{
return {};
}
Echoion::Api::Result<void>
sendServerMessage(const std::string&) override
{
return {};
}
Echoion::Api::Result<void>
sendAudioData(const std::span<const short>&) override
{
return {};
}
Echoion::Api::Result<void>
setWhisperList(const std::vector<uint64_t>&) override
{
return {};
}
Echoion::Api::Result<void>
connectToServer(const Echoion::Api::ServerConfig&) override
{
return {};
}
Echoion::Api::Result<void> disconnectFromServer() override
{
return {};
}
bool isConnected() const override { return connected; }
Echoion::Api::Result<void> reconnect() override { return {}; }
void registerEventCallback(
const Echoion::Api::EventCallback&) override
{
}
void unregisterEventCallback(
const Echoion::Api::EventCallback&) override
{
}
Echoion::Api::Result<Echoion::Api::ServerInfo>
getTeamSpeakServerInfo() override
{
return Echoion::Api::ServerInfo{
.name = "Fixture", .welcomeMessage = "", .maxClients = 64};
}
std::vector<Echoion::Api::ClientInfo> clients;
std::vector<Echoion::Api::ChannelInfo> channels;
bool connected = true;
};
} // namespace
int main()
{
using Echoion::Api::ChannelInfo;
using Echoion::Api::ClientInfo;
using Echoion::Core::TeamSpeakDirectoryService;
const auto validId = Void::Json::parse(R"({"id":42})");
const auto fractionalId = Void::Json::parse(R"({"id":1.5})");
const auto negativeId = Void::Json::parse(R"({"id":-1})");
const auto overflowingId =
Void::Json::parse(R"({"id":18446744073709551616})");
const auto enormousId = Void::Json::parse(R"({"id":1e100})");
assert(validId && Echoion::Core::Detail::uintField(*validId, "id") == 42);
assert(fractionalId &&
!Echoion::Core::Detail::uintField(*fractionalId, "id"));
assert(negativeId && !Echoion::Core::Detail::uintField(*negativeId, "id"));
assert(overflowingId &&
!Echoion::Core::Detail::uintField(*overflowingId, "id"));
assert(enormousId && !Echoion::Core::Detail::uintField(*enormousId, "id"));
auto plugin = std::make_shared<FakePlugin>();
plugin->channels = {
ChannelInfo{.id = 2, .name = "Second", .parentId = 0, .order = 1},
ChannelInfo{.id = 1, .name = "First", .parentId = 0, .order = 0},
ChannelInfo{.id = 3, .name = "Child", .parentId = 1, .order = 0}};
plugin->clients = {ClientInfo{.id = 10,
.databaseId = 110,
.nickname = "Visible",
.uniqueIdentifier = "secret-uid",
.channelId = 1,
.isTalking = true,
.serverGroups = {7}},
ClientInfo{.id = 11,
.databaseId = std::nullopt,
.nickname = "Query Client",
.uniqueIdentifier = "query-secret",
.channelId = 1,
.isQuery = true,
.serverGroups = {}}};
TeamSpeakDirectoryService service;
service.setPluginInterface(plugin);
const auto publicJson = Void::Json::serialize(service.publicJson());
assert(publicJson.contains("Visible"));
assert(publicJson.find("First") < publicJson.find("Second"));
assert(!publicJson.contains("Query Client"));
assert(!publicJson.contains("secret-uid"));
assert(!publicJson.contains("databaseId"));
assert(!publicJson.contains("groups"));
const auto adminJson = Void::Json::serialize(service.adminJson());
assert(adminJson.contains("secret-uid"));
assert(adminJson.contains("databaseId"));
assert(!adminJson.contains("Query Client"));
const auto ordered = TeamSpeakDirectoryService::orderChannels(
{ChannelInfo{.id = 2, .name = "", .parentId = std::nullopt, .order = 1},
ChannelInfo{.id = 1, .name = "", .parentId = std::nullopt, .order = 0},
ChannelInfo{
.id = 9, .name = "", .parentId = std::nullopt, .order = 99}});
assert(ordered.size() == 3);
assert(ordered[0].id == 1);
assert(ordered[1].id == 2);
assert(ordered[2].id == 9);
plugin->connected = false;
plugin->clients.clear();
plugin->channels.clear();
service.handleEvent(Echoion::Api::PluginEventType::ChannelUpdated);
const auto disconnected = Void::Json::serialize(service.publicJson());
assert(disconnected.contains("\"connected\":false"));
assert(!disconnected.contains("Visible"));
}
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more