63 Commits
Author SHA1 Message Date
faumaray 9e6e6ca97b Verify debug info for first-party release binaries
Modular container CI / release-build (push) Successful in 29m50s
Signed modular release / publish (push) Successful in 25m42s
2026-08-01 21:49:53 +03:00
faumaray ebb1040a71 Initialize reproducible release compiler flags
Modular container CI / release-build (push) Failing after 23m7s
2026-08-01 21:23:27 +03:00
faumaray b217d79a2b Apply release prefix maps to nested targets
Modular container CI / release-build (push) Failing after 22m59s
2026-08-01 20:54:10 +03:00
faumaray 71fb612d99 Map component paths in release debug info
Modular container CI / release-build (push) Failing after 23m36s
2026-08-01 20:22:48 +03:00
faumaray 1e83b28e1e Fix subject-only signed release tags
Modular container CI / release-build (push) Failing after 23m53s
2026-08-01 19:48:48 +03:00
faumaray d2e057988f Keep manifest fixtures on RelWithDebInfo
Modular container CI / release-build (push) Failing after 2s
2026-08-01 18:37:46 +03:00
faumaray 63c5444586 Pin RelWithDebInfo SDK release revisions
Modular container CI / release-build (push) Failing after 23m4s
2026-08-01 18:08:05 +03:00
faumaray 8212f13a19 Verify debug information in SDK release artifacts
Modular container CI / release-build (push) Has been cancelled
2026-08-01 18:07:06 +03:00
faumaray 8ac39621fd Harden signed feeds and RelWithDebInfo releases
Modular container CI / release-build (push) Has been cancelled
2026-08-01 18:02:55 +03:00
faumaray 5b2d27a1e8 Release: make RelWithDebInfo instead of Release
Signed modular release / publish (push) Failing after 22m50s
2026-07-31 19:05:45 +03:00
faumaray 3a1dc78a6b Release: make RelWithDebInfo instead of Release
Signed modular release / publish (push) Failing after 22m49s
2026-07-31 18:32:42 +03:00
faumaray 9236dc844b Release: retry transient asset verification failures
Signed modular release / publish (push) Successful in 18m32s
Nightly product integration / publish-nightly (push) Successful in 20m47s
Modular container CI / release-build (push) Successful in 20m45s
2026-07-30 04:14:52 +03:00
faumaray 4f8a46b0c4 Release: exclude pinned tools checkout from source dirtiness
Modular container CI / release-build (push) Has been cancelled
2026-07-30 04:06:27 +03:00
faumaray 697db046d3 Release: harden multiline secret handling
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:58:21 +03:00
faumaray ebb751f22c Release: pin checksum-corrected dependencies
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:43:48 +03:00
faumaray 9ab17418b5 Release: verify assets after draft publication
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:38:53 +03:00
faumaray cfcca4e616 Release: finalize dependency release locks
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:35:02 +03:00
faumaray 99f418fbc1 Release: update dependency release locks
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:32:03 +03:00
faumaray 4b2008bc2b Release: restore annotated component tags
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:25:55 +03:00
faumaray 43d655dc58 Release: include OpenSSH client in builder
Modular container CI / release-build (push) Has been cancelled
2026-07-30 03:13:49 +03:00
faumaray 6331fce118 Release: peel signed component tags
Modular container CI / release-build (push) Has been cancelled
2026-07-30 02:52:23 +03:00
faumaray 0a5323aea7 Release: centralize component feed signing
Modular container CI / release-build (push) Failing after 12s
2026-07-30 02:38:57 +03:00
faumaray 91ed8ac405 Release: update VoidLibrary lock
Modular container CI / release-build (push) Has been cancelled
2026-07-30 02:28:46 +03:00
faumaray f418b2f498 Lock release-container ABI test fix
Modular container CI / release-build (push) Successful in 20m5s
2026-07-30 00:05:16 +03:00
faumaray 2c8164584b Publish components through Gitea packages
Modular container CI / release-build (push) Failing after 17m56s
2026-07-29 23:45:09 +03:00
faumaray 0650d837d3 Lock CMake-compatible EchoionCore
Modular container CI / release-build (push) Has been cancelled
2026-07-29 23:32:07 +03:00
faumaray 267fe8c743 Add independent feed signing key
Modular container CI / release-build (push) Failing after 32s
2026-07-29 23:29:29 +03:00
faumaray b14ad5d000 Lock CI-safe component revisions
Modular container CI / release-build (push) Failing after 14m57s
2026-07-29 23:14:25 +03:00
faumaray 29e257de51 Prevent interactive SSH in release CI 2026-07-29 23:14:25 +03:00
faumaray 1ec7125a6e Lock updated component revisions
Modular container CI / release-build (push) Has been cancelled
2026-07-29 22:56:32 +03:00
faumaray b6ba851e05 Remove assistant-only repository artifacts 2026-07-29 22:56:32 +03:00
faumaray 2a533a27f8 Add independent component release architecture
Modular container CI / release-build (push) Failing after 12s
2026-07-29 22:40:35 +03:00
faumaray 458dde05a6 Release: cut over Echoion 2.0 components
Modular container CI / release-build (push) Has been cancelled
2026-07-29 20:35:27 +03:00
faumaray 1305d37fae Release: enforce root version across component feeds 2026-07-28 21:41:55 +03:00
faumaray f78004e822 Release: use independent component repositories
Container CI / release-build (push) Successful in 16m22s
Nightly release / publish-nightly (push) Successful in 16m6s
2026-07-28 21:24:30 +03:00
faumaray 8c69efc56f FIX: update VoidTeamspeak rev and framepointer 2026-07-27 19:26:03 +03:00
faumaray 870a803bd2 Release: change api version
Container CI / release-build (push) Successful in 33m59s
Signed release / publish (push) Successful in 34m1s
Nightly release / publish-nightly (push) Successful in 16m4s
2026-07-26 18:11:44 +03:00
faumaray a2c6dd4c2c Runtime: reset stale Core baseline on upgrade 2026-07-26 18:11:28 +03:00
faumaray fb8fb69532 Release: fix portable runtime and updater
Container CI / release-build (push) Successful in 34m0s
Signed release / publish (push) Successful in 34m10s
2026-07-26 16:48:53 +03:00
faumaray 1ff935b727 Release version
Container CI / release-build (push) Has been cancelled
Signed release / publish (push) Successful in 17m39s
2026-07-26 05:25:43 +03:00
faumaray d5db7f2d2a Nightly: derive version from releases
Container CI / release-build (push) Has been cancelled
2026-07-26 05:23:18 +03:00
faumaray 9401f19ad5 Nightly: materialize tag on publication
Container CI / release-build (push) Has been cancelled
Nightly release / publish-nightly (push) Has started running
2026-07-26 04:57:15 +03:00
faumaray 30e669359a Release: clarify lightweight tag rejection
Signed release / publish (push) Failing after 21s
Container CI / release-build (push) Successful in 46m58s
2026-07-26 04:03:52 +03:00
faumaray 523355a128 CI: map nested Docker workspace
Container CI / release-build (push) Successful in 16m18s
Signed release / publish (push) Failing after 11s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 03:41:17 +03:00
faumaray 2e8e1fc0ba Tests: run installer suite unprivileged
Container CI / release-build (push) Failing after 16m21s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 03:13:54 +03:00
faumaray 7dca9db7dc Release: fix missing target and remove dist
Container CI / release-build (push) Failing after 15m5s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 02:45:07 +03:00
faumaray 5547621cfa Release: resolve containerized runner workspace
Container CI / release-build (push) Failing after 25s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 02:38:31 +03:00
faumaray c08ff6ca68 remove docs
Container CI / release-build (push) Failing after 12s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 01:05:11 +03:00
faumaray ff25742659 remove docs
Container CI / release-build (push) Failing after 9s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 01:04:10 +03:00
faumaray 6b5b182c33 CI: use Gitea SSH user
Container CI / release-build (push) Failing after 10s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 01:00:54 +03:00
faumaray dbddb80b82 CI: pin Gitea SSH host key
Container CI / release-build (push) Failing after 3s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 00:32:11 +03:00
faumaray ecb4cda800 update
Container CI / release-build (push) Failing after 41s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-26 00:22:14 +03:00
faumaray 41937b2987 update
Container CI / release-build (push) Has been cancelled
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:54:51 +03:00
Aleksey Selihov 0b7af2e96a Merge pull request 'feat/retire-plugin-path' (#2) from feat/retire-plugin-path into main
Container CI / release-build (push) Has been cancelled
Reviewed-on: https://git.faumaray.ru/Void/Echoion/pulls/2
2026-07-25 20:45:44 +00:00
faumaray bdd69f0aad update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:44:48 +03:00
faumaray 639362fbf5 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-16 19:59:57 +03:00
faumaray 818d391022 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:50:44 +03:00
faumaray ef3139ca64 Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-12 02:57:35 +03:00
faumaray 2d1d03db1e New arch
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 16:30:05 +03:00
Aleksey Selihov c9a52b73ac Merge pull request 'feat/standalone-ts-client' (#1) from feat/standalone-ts-client into main
Reviewed-on: https://git.faumaray.ru/Void/Echoion/pulls/1
2026-07-11 12:10:04 +00:00
faumaray 3b3dd2be4f New arch
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 15:07:20 +03:00
faumaray 206c92e3ea New arch
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 15:06:50 +03:00
faumaray 000663b422 New arch
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-11 15:06:22 +03:00
178 changed files with 15990 additions and 18879 deletions

No files matched your search

-86
View File
@@ -1,86 +0,0 @@
---
name: cpp-pro
description: Use when building C++ applications requiring modern C++20/23 features, template metaprogramming, or high-performance systems. Invoke for concepts, ranges, coroutines, SIMD optimization, memory management.
license: MIT
metadata:
author: https://github.com/Jeffallan
version: "1.0.0"
domain: language
triggers: C++, C++20, C++23, modern C++, template metaprogramming, systems programming, performance optimization, SIMD, memory management, CMake
role: specialist
scope: implementation
output-format: code
related-skills: rust-engineer, embedded-systems
---
# C++ Pro
Senior C++ developer with deep expertise in modern C++20/23, systems programming, high-performance computing, and zero-overhead abstractions.
## Role Definition
You are a senior C++ engineer with 15+ years of systems programming experience. You specialize in modern C++20/23, template metaprogramming, performance optimization, and building production-grade systems with emphasis on safety, efficiency, and maintainability. You follow C++ Core Guidelines and leverage cutting-edge language features.
## When to Use This Skill
- Building high-performance C++ applications
- Implementing template metaprogramming solutions
- Optimizing memory-critical systems
- Developing concurrent and parallel algorithms
- Creating custom allocators and memory pools
- Systems programming and embedded development
## Core Workflow
1. **Analyze architecture** - Review build system, compiler flags, performance requirements
2. **Design with concepts** - Create type-safe interfaces using C++20 concepts
3. **Implement zero-cost** - Apply RAII, constexpr, and zero-overhead abstractions
4. **Verify quality** - Run sanitizers, static analysis, and performance benchmarks
5. **Optimize** - Profile, measure, and apply targeted optimizations
## Reference Guide
Load detailed guidance based on context:
| Topic | Reference | Load When |
|-------|-----------|-----------|
| Modern C++ Features | `references/modern-cpp.md` | C++20/23 features, concepts, ranges, coroutines |
| Template Metaprogramming | `references/templates.md` | Variadic templates, SFINAE, type traits, CRTP |
| Memory & Performance | `references/memory-performance.md` | Allocators, SIMD, cache optimization, move semantics |
| Concurrency | `references/concurrency.md` | Atomics, lock-free structures, thread pools, coroutines |
| Build & Tooling | `references/build-tooling.md` | CMake, sanitizers, static analysis, testing |
## Constraints
### MUST DO
- Follow C++ Core Guidelines
- Use concepts for template constraints
- Apply RAII universally
- Use `auto` with type deduction
- Prefer `std::unique_ptr` and `std::shared_ptr`
- Enable all compiler warnings (-Wall -Wextra -Wpedantic)
- Run AddressSanitizer and UndefinedBehaviorSanitizer
- Write const-correct code
### MUST NOT DO
- Use raw `new`/`delete` (prefer smart pointers)
- Ignore compiler warnings
- Use C-style casts (use static_cast, etc.)
- Mix exception and error code patterns inconsistently
- Write non-const-correct code
- Use `using namespace std` in headers
- Ignore undefined behavior
- Skip move semantics for expensive types
## Output Templates
When implementing C++ features, provide:
1. Header file with interfaces and templates
2. Implementation file (when needed)
3. CMakeLists.txt updates (if applicable)
4. Test file demonstrating usage
5. Brief explanation of design decisions and performance characteristics
## Knowledge Reference
C++20/23, concepts, ranges, coroutines, modules, template metaprogramming, SFINAE, type traits, CRTP, smart pointers, custom allocators, move semantics, RAII, SIMD, atomics, lock-free programming, CMake, Conan, sanitizers, clang-tidy, cppcheck, Catch2, GoogleTest
@@ -1,437 +0,0 @@
# Concurrency and Parallel Programming
## Atomics and Memory Ordering
```cpp
#include <atomic>
#include <thread>
// Basic atomics
std::atomic<int> counter{0};
std::atomic<bool> flag{false};
// Memory ordering
void producer(std::atomic<int>& data, std::atomic<bool>& ready) {
data.store(42, std::memory_order_relaxed);
ready.store(true, std::memory_order_release); // Release barrier
}
void consumer(std::atomic<int>& data, std::atomic<bool>& ready) {
while (!ready.load(std::memory_order_acquire)) { // Acquire barrier
std::this_thread::yield();
}
int value = data.load(std::memory_order_relaxed);
}
// Compare-and-swap
bool try_acquire_lock(std::atomic<bool>& lock) {
bool expected = false;
return lock.compare_exchange_strong(expected, true,
std::memory_order_acquire,
std::memory_order_relaxed);
}
// Fetch-and-add
int increment_counter(std::atomic<int>& counter) {
return counter.fetch_add(1, std::memory_order_relaxed);
}
```
## Lock-Free Data Structures
```cpp
#include <atomic>
#include <memory>
// Lock-free stack
template<typename T>
class LockFreeStack {
struct Node {
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
std::atomic<Node*> head_{nullptr};
public:
void push(const T& value) {
Node* new_node = new Node(value);
new_node->next = head_.load(std::memory_order_relaxed);
while (!head_.compare_exchange_weak(new_node->next, new_node,
std::memory_order_release,
std::memory_order_relaxed)) {
// Retry with updated head
}
}
bool pop(T& result) {
Node* old_head = head_.load(std::memory_order_relaxed);
while (old_head &&
!head_.compare_exchange_weak(old_head, old_head->next,
std::memory_order_acquire,
std::memory_order_relaxed)) {
// Retry
}
if (old_head) {
result = old_head->data;
delete old_head; // Note: ABA problem exists
return true;
}
return false;
}
};
// Lock-free queue (single producer, single consumer)
template<typename T, size_t Size>
class SPSCQueue {
std::array<T, Size> buffer_;
alignas(64) std::atomic<size_t> head_{0};
alignas(64) std::atomic<size_t> tail_{0};
public:
bool push(const T& item) {
size_t head = head_.load(std::memory_order_relaxed);
size_t next_head = (head + 1) % Size;
if (next_head == tail_.load(std::memory_order_acquire)) {
return false; // Queue full
}
buffer_[head] = item;
head_.store(next_head, std::memory_order_release);
return true;
}
bool pop(T& item) {
size_t tail = tail_.load(std::memory_order_relaxed);
if (tail == head_.load(std::memory_order_acquire)) {
return false; // Queue empty
}
item = buffer_[tail];
tail_.store((tail + 1) % Size, std::memory_order_release);
return true;
}
};
```
## Thread Pool
```cpp
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
class ThreadPool {
std::vector<std::thread> workers_;
std::queue<std::function<void()>> tasks_;
std::mutex queue_mutex_;
std::condition_variable condition_;
bool stop_ = false;
public:
ThreadPool(size_t num_threads) {
for (size_t i = 0; i < num_threads; ++i) {
workers_.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex_);
condition_.wait(lock, [this] {
return stop_ || !tasks_.empty();
});
if (stop_ && tasks_.empty()) {
return;
}
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex_);
stop_ = true;
}
condition_.notify_all();
for (auto& worker : workers_) {
worker.join();
}
}
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::invoke_result_t<F, Args...>> {
using return_type = typename std::invoke_result_t<F, Args...>;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> result = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (stop_) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks_.emplace([task]() { (*task)(); });
}
condition_.notify_one();
return result;
}
};
```
## Parallel STL Algorithms
```cpp
#include <algorithm>
#include <execution>
#include <vector>
#include <numeric>
void parallel_algorithms_demo() {
std::vector<int> vec(1'000'000);
std::iota(vec.begin(), vec.end(), 0);
// Parallel sort
std::sort(std::execution::par, vec.begin(), vec.end());
// Parallel for_each
std::for_each(std::execution::par_unseq, vec.begin(), vec.end(),
[](int& x) { x *= 2; });
// Parallel transform
std::vector<int> result(vec.size());
std::transform(std::execution::par, vec.begin(), vec.end(),
result.begin(), [](int x) { return x * x; });
// Parallel reduce
int sum = std::reduce(std::execution::par, vec.begin(), vec.end());
// Parallel transform_reduce (map-reduce)
int sum_of_squares = std::transform_reduce(
std::execution::par,
vec.begin(), vec.end(),
0,
std::plus<>(),
[](int x) { return x * x; }
);
}
```
## Synchronization Primitives
```cpp
#include <mutex>
#include <shared_mutex>
#include <condition_variable>
// Mutex types
std::mutex mtx;
std::recursive_mutex rec_mtx;
std::timed_mutex timed_mtx;
std::shared_mutex shared_mtx;
// RAII locks
void exclusive_access() {
std::lock_guard<std::mutex> lock(mtx);
// Critical section
}
void unique_lock_example() {
std::unique_lock<std::mutex> lock(mtx);
// Can unlock and relock
lock.unlock();
// Do some work
lock.lock();
}
// Reader-writer lock
class SharedData {
mutable std::shared_mutex mutex_;
std::string data_;
public:
std::string read() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return data_;
}
void write(std::string new_data) {
std::unique_lock<std::shared_mutex> lock(mutex_);
data_ = std::move(new_data);
}
};
// Condition variable
class Queue {
std::queue<int> queue_;
std::mutex mutex_;
std::condition_variable cv_;
public:
void push(int value) {
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(value);
}
cv_.notify_one();
}
int pop() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this] { return !queue_.empty(); });
int value = queue_.front();
queue_.pop();
return value;
}
};
// std::scoped_lock - multiple mutexes
std::mutex mtx1, mtx2;
void transfer(Account& from, Account& to, int amount) {
std::scoped_lock lock(from.mutex, to.mutex); // Deadlock-free
from.balance -= amount;
to.balance += amount;
}
```
## Async and Futures
```cpp
#include <future>
// std::async
auto future = std::async(std::launch::async, []() {
return expensive_computation();
});
// Get result (blocks until ready)
auto result = future.get();
// Promise and future
void producer(std::promise<int> promise) {
int value = compute_value();
promise.set_value(value);
}
void consumer(std::future<int> future) {
int value = future.get();
}
std::promise<int> promise;
std::future<int> future = promise.get_future();
std::thread producer_thread(producer, std::move(promise));
std::thread consumer_thread(consumer, std::move(future));
// Packaged task
std::packaged_task<int(int, int)> task([](int a, int b) {
return a + b;
});
std::future<int> task_future = task.get_future();
std::thread task_thread(std::move(task), 5, 3);
int sum = task_future.get(); // 8
task_thread.join();
```
## Coroutine-Based Concurrency
```cpp
#include <coroutine>
#include <optional>
// Async task coroutine
template<typename T>
struct AsyncTask {
struct promise_type {
std::optional<T> value;
std::exception_ptr exception;
AsyncTask get_return_object() {
return AsyncTask{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_value(T v) {
value = std::move(v);
}
void unhandled_exception() {
exception = std::current_exception();
}
};
std::coroutine_handle<promise_type> handle;
AsyncTask(std::coroutine_handle<promise_type> h) : handle(h) {}
~AsyncTask() { if (handle) handle.destroy(); }
T get() {
if (!handle.done()) {
handle.resume();
}
if (handle.promise().exception) {
std::rethrow_exception(handle.promise().exception);
}
return *handle.promise().value;
}
};
// Usage
AsyncTask<int> async_compute() {
co_return 42;
}
```
## Quick Reference
| Primitive | Use Case | Performance |
|-----------|----------|-------------|
| std::atomic | Simple shared state | Lock-free |
| std::mutex | Exclusive access | Kernel call |
| std::shared_mutex | Read-heavy workload | Better than mutex |
| Lock-free structures | High contention | Best throughput |
| Thread pool | Task parallelism | Avoid thread overhead |
| Parallel STL | Data parallelism | Automatic scaling |
| std::async | Simple async tasks | Thread pool |
| Coroutines | Async I/O | Minimal overhead |
## Memory Ordering Guide
| Ordering | Guarantees | Use Case |
|----------|-----------|----------|
| relaxed | No synchronization | Counters |
| acquire | Load barrier | Consumer |
| release | Store barrier | Producer |
| acq_rel | Both | RMW operations |
| seq_cst | Total order | Default |
@@ -1,397 +0,0 @@
# Memory Management & Performance
## Smart Pointers
```cpp
#include <memory>
// unique_ptr - exclusive ownership
auto create_resource() {
return std::make_unique<Resource>("data");
}
// shared_ptr - reference counting
std::shared_ptr<Data> shared = std::make_shared<Data>(42);
std::weak_ptr<Data> weak = shared; // Non-owning reference
// Custom deleters
auto file_deleter = [](FILE* fp) { if (fp) fclose(fp); };
std::unique_ptr<FILE, decltype(file_deleter)> file(
fopen("data.txt", "r"),
file_deleter
);
// enable_shared_from_this
class Node : public std::enable_shared_from_this<Node> {
public:
std::shared_ptr<Node> get_shared() {
return shared_from_this();
}
};
```
## Custom Allocators
```cpp
#include <memory>
#include <vector>
// Pool allocator for fixed-size objects
template<typename T, size_t PoolSize = 1024>
class PoolAllocator {
struct Block {
alignas(T) std::byte data[sizeof(T)];
Block* next;
};
Block pool_[PoolSize];
Block* free_list_ = nullptr;
public:
using value_type = T;
PoolAllocator() {
// Initialize free list
for (size_t i = 0; i < PoolSize - 1; ++i) {
pool_[i].next = &pool_[i + 1];
}
pool_[PoolSize - 1].next = nullptr;
free_list_ = &pool_[0];
}
T* allocate(size_t n) {
if (n != 1 || !free_list_) {
throw std::bad_alloc();
}
Block* block = free_list_;
free_list_ = free_list_->next;
return reinterpret_cast<T*>(block->data);
}
void deallocate(T* p, size_t n) {
if (n != 1) return;
Block* block = reinterpret_cast<Block*>(p);
block->next = free_list_;
free_list_ = block;
}
};
// Usage
std::vector<int, PoolAllocator<int>> vec;
// Arena allocator - bump allocator
class Arena {
std::byte* buffer_;
size_t size_;
size_t offset_ = 0;
public:
Arena(size_t size) : size_(size) {
buffer_ = new std::byte[size];
}
~Arena() {
delete[] buffer_;
}
template<typename T>
T* allocate(size_t n = 1) {
size_t alignment = alignof(T);
size_t space = size_ - offset_;
void* ptr = buffer_ + offset_;
if (std::align(alignment, sizeof(T) * n, ptr, space)) {
offset_ = size_ - space + sizeof(T) * n;
return static_cast<T*>(ptr);
}
throw std::bad_alloc();
}
void reset() {
offset_ = 0;
}
};
```
## Move Semantics
```cpp
#include <utility>
#include <algorithm>
class Buffer {
size_t size_;
char* data_;
public:
// Constructor
Buffer(size_t size) : size_(size), data_(new char[size]) {}
// Destructor
~Buffer() { delete[] data_; }
// Copy constructor
Buffer(const Buffer& other) : size_(other.size_), data_(new char[size_]) {
std::copy(other.data_, other.data_ + size_, data_);
}
// Copy assignment
Buffer& operator=(const Buffer& other) {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = new char[size_];
std::copy(other.data_, other.data_ + size_, data_);
}
return *this;
}
// Move constructor
Buffer(Buffer&& other) noexcept
: size_(other.size_), data_(other.data_) {
other.size_ = 0;
other.data_ = nullptr;
}
// Move assignment
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = other.data_;
other.size_ = 0;
other.data_ = nullptr;
}
return *this;
}
};
// Perfect forwarding
template<typename T>
void wrapper(T&& arg) {
process(std::forward<T>(arg)); // Preserves lvalue/rvalue
}
```
## SIMD Optimization
```cpp
#include <immintrin.h> // AVX/AVX2
#include <cstring>
// Vectorized sum using AVX2
float simd_sum(const float* data, size_t size) {
__m256 sum_vec = _mm256_setzero_ps();
size_t i = 0;
// Process 8 floats at a time
for (; i + 8 <= size; i += 8) {
__m256 vec = _mm256_loadu_ps(&data[i]);
sum_vec = _mm256_add_ps(sum_vec, vec);
}
// Horizontal sum
alignas(32) float temp[8];
_mm256_store_ps(temp, sum_vec);
float result = 0.0f;
for (int j = 0; j < 8; ++j) {
result += temp[j];
}
// Handle remaining elements
for (; i < size; ++i) {
result += data[i];
}
return result;
}
// Vectorized multiply-add
void fma_operation(float* result, const float* a, const float* b,
const float* c, size_t size) {
for (size_t i = 0; i + 8 <= size; i += 8) {
__m256 va = _mm256_loadu_ps(&a[i]);
__m256 vb = _mm256_loadu_ps(&b[i]);
__m256 vc = _mm256_loadu_ps(&c[i]);
// result[i] = a[i] * b[i] + c[i]
__m256 vr = _mm256_fmadd_ps(va, vb, vc);
_mm256_storeu_ps(&result[i], vr);
}
}
```
## Cache-Friendly Design
```cpp
// Structure of Arrays (SoA) - better cache locality
struct ParticlesAoS {
struct Particle {
float x, y, z;
float vx, vy, vz;
};
std::vector<Particle> particles;
};
struct ParticlesSoA {
std::vector<float> x, y, z;
std::vector<float> vx, vy, vz;
void update_positions(float dt) {
// All x coordinates are contiguous - better cache usage
for (size_t i = 0; i < x.size(); ++i) {
x[i] += vx[i] * dt;
y[i] += vy[i] * dt;
z[i] += vz[i] * dt;
}
}
};
// Cache line padding to avoid false sharing
struct alignas(64) CacheLinePadded {
std::atomic<int> counter;
char padding[64 - sizeof(std::atomic<int>)];
};
// Prefetching
void process_with_prefetch(const int* data, size_t size) {
for (size_t i = 0; i < size; ++i) {
// Prefetch data for next iteration
if (i + 8 < size) {
__builtin_prefetch(&data[i + 8], 0, 1);
}
// Process current data
process(data[i]);
}
}
```
## Memory Pool
```cpp
#include <vector>
#include <memory>
template<typename T, size_t ChunkSize = 256>
class MemoryPool {
struct Chunk {
alignas(T) std::byte data[sizeof(T) * ChunkSize];
};
std::vector<std::unique_ptr<Chunk>> chunks_;
std::vector<T*> free_list_;
size_t current_chunk_offset_ = ChunkSize;
public:
T* allocate() {
if (!free_list_.empty()) {
T* ptr = free_list_.back();
free_list_.pop_back();
return ptr;
}
if (current_chunk_offset_ >= ChunkSize) {
chunks_.push_back(std::make_unique<Chunk>());
current_chunk_offset_ = 0;
}
Chunk* chunk = chunks_.back().get();
T* ptr = reinterpret_cast<T*>(
&chunk->data[sizeof(T) * current_chunk_offset_++]
);
return ptr;
}
void deallocate(T* ptr) {
free_list_.push_back(ptr);
}
template<typename... Args>
T* construct(Args&&... args) {
T* ptr = allocate();
new (ptr) T(std::forward<Args>(args)...);
return ptr;
}
void destroy(T* ptr) {
ptr->~T();
deallocate(ptr);
}
};
```
## Copy Elision and RVO
```cpp
// Return Value Optimization (RVO)
std::vector<int> create_vector() {
std::vector<int> vec{1, 2, 3, 4, 5};
return vec; // RVO applies, no copy/move
}
// Named Return Value Optimization (NRVO)
std::string build_string(bool condition) {
std::string result;
if (condition) {
result = "condition true";
} else {
result = "condition false";
}
return result; // NRVO may apply
}
// Guaranteed copy elision (C++17)
struct NonMovable {
NonMovable() = default;
NonMovable(const NonMovable&) = delete;
NonMovable(NonMovable&&) = delete;
};
NonMovable create() {
return NonMovable{}; // Guaranteed no copy/move in C++17
}
auto obj = create(); // OK in C++17
```
## Alignment and Memory Layout
```cpp
#include <cstddef>
// Control alignment
struct alignas(64) CacheAligned {
int data[16];
};
// Check alignment
static_assert(alignof(CacheAligned) == 64);
// Aligned allocation
void* aligned_alloc_wrapper(size_t alignment, size_t size) {
void* ptr = nullptr;
if (posix_memalign(&ptr, alignment, size) != 0) {
throw std::bad_alloc();
}
return ptr;
}
// Placement new with alignment
alignas(32) std::byte buffer[sizeof(Data)];
Data* obj = new (buffer) Data();
obj->~Data(); // Manual destruction needed
```
## Quick Reference
| Technique | Use Case | Benefit |
|-----------|----------|---------|
| Smart Pointers | Ownership management | Memory safety |
| Move Semantics | Avoid copies | Performance |
| Custom Allocators | Specialized allocation | Speed + control |
| SIMD | Parallel computation | 4-8x speedup |
| SoA Layout | Sequential access | Cache efficiency |
| Memory Pools | Frequent alloc/dealloc | Reduced fragmentation |
| Alignment | SIMD/cache optimization | Performance |
| RVO/NRVO | Return objects | Zero-copy |
@@ -1,304 +0,0 @@
# Modern C++20/23 Features
## Concepts and Constraints
```cpp
#include <concepts>
// Define custom concepts
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template<typename T>
concept Hashable = requires(T a) {
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
template<typename T>
concept Container = requires(T c) {
typename T::value_type;
typename T::iterator;
{ c.begin() } -> std::same_as<typename T::iterator>;
{ c.end() } -> std::same_as<typename T::iterator>;
{ c.size() } -> std::convertible_to<std::size_t>;
};
// Use concepts for function constraints
template<Numeric T>
T add(T a, T b) {
return a + b;
}
// Concept-based overloading
template<std::integral T>
void process(T value) {
std::cout << "Processing integer: " << value << '\n';
}
template<std::floating_point T>
void process(T value) {
std::cout << "Processing float: " << value << '\n';
}
```
## Ranges and Views
```cpp
#include <ranges>
#include <vector>
#include <algorithm>
// Ranges-based algorithms
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Filter, transform, take - all lazy evaluation
auto result = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; })
| std::views::take(3);
// Copy to vector only when needed
std::vector<int> materialized(result.begin(), result.end());
// Custom range adaptor
auto is_even = [](int n) { return n % 2 == 0; };
auto square = [](int n) { return n * n; };
auto pipeline = std::views::filter(is_even)
| std::views::transform(square);
auto processed = numbers | pipeline;
```
## Coroutines
```cpp
#include <coroutine>
#include <iostream>
#include <memory>
// Generator coroutine
template<typename T>
struct Generator {
struct promise_type {
T current_value;
auto get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
std::suspend_always yield_value(T value) {
current_value = value;
return {};
}
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle;
Generator(std::coroutine_handle<promise_type> h) : handle(h) {}
~Generator() { if (handle) handle.destroy(); }
bool move_next() {
handle.resume();
return !handle.done();
}
T current_value() {
return handle.promise().current_value;
}
};
// Usage
Generator<int> fibonacci() {
int a = 0, b = 1;
while (true) {
co_yield a;
auto next = a + b;
a = b;
b = next;
}
}
// Async coroutine
#include <future>
struct Task {
struct promise_type {
Task get_return_object() {
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
std::coroutine_handle<promise_type> handle;
};
Task async_operation() {
std::cout << "Starting async work\n";
co_await std::suspend_always{};
std::cout << "Resuming async work\n";
}
```
## Three-Way Comparison (Spaceship)
```cpp
#include <compare>
struct Point {
int x, y;
// Auto-generate all comparison operators
auto operator<=>(const Point&) const = default;
};
// Custom spaceship operator
struct Version {
int major, minor, patch;
std::strong_ordering operator<=>(const Version& other) const {
if (auto cmp = major <=> other.major; cmp != 0) return cmp;
if (auto cmp = minor <=> other.minor; cmp != 0) return cmp;
return patch <=> other.patch;
}
bool operator==(const Version& other) const = default;
};
```
## Designated Initializers
```cpp
struct Config {
std::string host = "localhost";
int port = 8080;
bool ssl_enabled = false;
int timeout_ms = 5000;
};
// C++20 designated initializers
Config cfg {
.host = "example.com",
.port = 443,
.ssl_enabled = true
// timeout_ms uses default
};
```
## Modules (C++20)
```cpp
// math.cppm - module interface
export module math;
export namespace math {
template<typename T>
T add(T a, T b) {
return a + b;
}
class Calculator {
public:
int multiply(int a, int b);
};
}
// Implementation
module math;
int math::Calculator::multiply(int a, int b) {
return a * b;
}
// Usage in other files
import math;
int main() {
auto result = math::add(5, 3);
math::Calculator calc;
auto product = calc.multiply(4, 7);
}
```
## constexpr Enhancements
```cpp
#include <string>
#include <vector>
#include <algorithm>
// C++20: constexpr std::string and std::vector
constexpr auto compute_at_compile_time() {
std::vector<int> vec{1, 2, 3, 4, 5};
std::ranges::reverse(vec);
return vec[0]; // Returns 5
}
constexpr int value = compute_at_compile_time();
// constexpr virtual functions (C++20)
struct Base {
constexpr virtual int get_value() const { return 42; }
constexpr virtual ~Base() = default;
};
struct Derived : Base {
constexpr int get_value() const override { return 100; }
};
```
## std::format (C++20)
```cpp
#include <format>
#include <iostream>
int main() {
std::string msg = std::format("Hello, {}!", "World");
// Positional arguments
auto text = std::format("{1} {0}", "World", "Hello");
// Formatting options
double pi = 3.14159265;
auto formatted = std::format("Pi: {:.2f}", pi); // "Pi: 3.14"
// Custom types
struct Point { int x, y; };
}
// Custom formatter
template<>
struct std::formatter<Point> {
constexpr auto parse(format_parse_context& ctx) {
return ctx.begin();
}
auto format(const Point& p, format_context& ctx) const {
return std::format_to(ctx.out(), "({}, {})", p.x, p.y);
}
};
```
## Quick Reference
| Feature | C++17 | C++20 | C++23 |
|---------|-------|-------|-------|
| Concepts | - | ✓ | ✓ |
| Ranges | - | ✓ | ✓ |
| Coroutines | - | ✓ | ✓ |
| Modules | - | ✓ | ✓ |
| Spaceship | - | ✓ | ✓ |
| std::format | - | ✓ | ✓ |
| std::expected | - | - | ✓ |
| std::print | - | - | ✓ |
| Deducing this | - | - | ✓ |
@@ -1,357 +0,0 @@
# Template Metaprogramming
## Variadic Templates
```cpp
#include <iostream>
#include <utility>
// Fold expressions (C++17)
template<typename... Args>
auto sum(Args... args) {
return (args + ...); // Unary right fold
}
template<typename... Args>
void print(Args&&... args) {
((std::cout << args << ' '), ...); // Binary left fold
std::cout << '\n';
}
// Recursive variadic template
template<typename T>
void log(T&& value) {
std::cout << value << '\n';
}
template<typename T, typename... Args>
void log(T&& first, Args&&... rest) {
std::cout << first << ", ";
log(std::forward<Args>(rest)...);
}
// Parameter pack expansion
template<typename... Types>
struct TypeList {
static constexpr size_t size = sizeof...(Types);
};
template<typename... Args>
auto make_tuple_advanced(Args&&... args) {
return std::tuple<std::decay_t<Args>...>(std::forward<Args>(args)...);
}
```
## SFINAE and if constexpr
```cpp
#include <type_traits>
// SFINAE with std::enable_if (older style)
template<typename T>
std::enable_if_t<std::is_integral_v<T>, T>
double_value(T value) {
return value * 2;
}
template<typename T>
std::enable_if_t<std::is_floating_point_v<T>, T>
double_value(T value) {
return value * 2.0;
}
// Modern: if constexpr (C++17)
template<typename T>
auto process(T value) {
if constexpr (std::is_integral_v<T>) {
return value * 2;
} else if constexpr (std::is_floating_point_v<T>) {
return value * 2.0;
} else {
return value;
}
}
// Detection idiom
template<typename T, typename = void>
struct has_serialize : std::false_type {};
template<typename T>
struct has_serialize<T, std::void_t<decltype(std::declval<T>().serialize())>>
: std::true_type {};
template<typename T>
constexpr bool has_serialize_v = has_serialize<T>::value;
// Use with if constexpr
template<typename T>
void save(const T& obj) {
if constexpr (has_serialize_v<T>) {
obj.serialize();
} else {
// Default serialization
}
}
```
## Type Traits
```cpp
#include <type_traits>
// Custom type traits
template<typename T>
struct remove_all_pointers {
using type = T;
};
template<typename T>
struct remove_all_pointers<T*> {
using type = typename remove_all_pointers<T>::type;
};
template<typename T>
using remove_all_pointers_t = typename remove_all_pointers<T>::type;
// Conditional types
template<bool Condition, typename T, typename F>
struct conditional_type {
using type = T;
};
template<typename T, typename F>
struct conditional_type<false, T, F> {
using type = F;
};
// Compile-time type selection
template<size_t N>
struct best_integral_type {
using type = std::conditional_t<N <= 8, uint8_t,
std::conditional_t<N <= 16, uint16_t,
std::conditional_t<N <= 32, uint32_t, uint64_t>>>;
};
// Check for member functions
template<typename T, typename = void>
struct has_reserve : std::false_type {};
template<typename T>
struct has_reserve<T, std::void_t<decltype(std::declval<T>().reserve(size_t{}))>>
: std::true_type {};
```
## CRTP (Curiously Recurring Template Pattern)
```cpp
// Static polymorphism with CRTP
template<typename Derived>
class Shape {
public:
double area() const {
return static_cast<const Derived*>(this)->area_impl();
}
void draw() const {
static_cast<const Derived*>(this)->draw_impl();
}
};
class Circle : public Shape<Circle> {
double radius_;
public:
Circle(double r) : radius_(r) {}
double area_impl() const {
return 3.14159 * radius_ * radius_;
}
void draw_impl() const {
std::cout << "Drawing circle\n";
}
};
class Rectangle : public Shape<Rectangle> {
double width_, height_;
public:
Rectangle(double w, double h) : width_(w), height_(h) {}
double area_impl() const {
return width_ * height_;
}
void draw_impl() const {
std::cout << "Drawing rectangle\n";
}
};
// CRTP for mixin capabilities
template<typename Derived>
class Printable {
public:
void print() const {
std::cout << static_cast<const Derived*>(this)->to_string() << '\n';
}
};
class User : public Printable<User> {
std::string name_;
public:
User(std::string name) : name_(std::move(name)) {}
std::string to_string() const {
return "User: " + name_;
}
};
```
## Template Template Parameters
```cpp
#include <vector>
#include <list>
#include <deque>
// Template template parameter
template<typename T, template<typename, typename> class Container>
class Stack {
Container<T, std::allocator<T>> data_;
public:
void push(const T& value) {
data_.push_back(value);
}
T pop() {
T value = data_.back();
data_.pop_back();
return value;
}
size_t size() const {
return data_.size();
}
};
// Usage with different containers
Stack<int, std::vector> vector_stack;
Stack<int, std::deque> deque_stack;
Stack<int, std::list> list_stack;
```
## Compile-Time Computation
```cpp
#include <array>
// Compile-time factorial
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
constexpr int fact_5 = factorial(5); // Computed at compile time
// Compile-time prime checking
constexpr bool is_prime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) return false;
}
return true;
}
// Generate compile-time array of primes
template<size_t N>
constexpr auto generate_primes() {
std::array<int, N> primes{};
int count = 0;
int candidate = 2;
while (count < N) {
if (is_prime(candidate)) {
primes[count++] = candidate;
}
++candidate;
}
return primes;
}
constexpr auto first_10_primes = generate_primes<10>();
```
## Expression Templates
```cpp
// Lazy evaluation with expression templates
template<typename E>
class VecExpression {
public:
double operator[](size_t i) const {
return static_cast<const E&>(*this)[i];
}
size_t size() const {
return static_cast<const E&>(*this).size();
}
};
class Vec : public VecExpression<Vec> {
std::vector<double> data_;
public:
Vec(size_t n) : data_(n) {}
double operator[](size_t i) const { return data_[i]; }
double& operator[](size_t i) { return data_[i]; }
size_t size() const { return data_.size(); }
// Evaluate expression template
template<typename E>
Vec& operator=(const VecExpression<E>& expr) {
for (size_t i = 0; i < size(); ++i) {
data_[i] = expr[i];
}
return *this;
}
};
// Binary operation expression
template<typename E1, typename E2>
class VecSum : public VecExpression<VecSum<E1, E2>> {
const E1& lhs_;
const E2& rhs_;
public:
VecSum(const E1& lhs, const E2& rhs) : lhs_(lhs), rhs_(rhs) {}
double operator[](size_t i) const {
return lhs_[i] + rhs_[i];
}
size_t size() const { return lhs_.size(); }
};
// Operator overload
template<typename E1, typename E2>
VecSum<E1, E2> operator+(const VecExpression<E1>& lhs,
const VecExpression<E2>& rhs) {
return VecSum<E1, E2>(static_cast<const E1&>(lhs),
static_cast<const E2&>(rhs));
}
// Usage: a = b + c + d (no temporaries created!)
```
## Quick Reference
| Technique | Use Case | Performance |
|-----------|----------|-------------|
| Variadic Templates | Variable arguments | Zero overhead |
| SFINAE | Conditional compilation | Compile-time |
| if constexpr | Type-based branching | Zero overhead |
| CRTP | Static polymorphism | No vtable cost |
| Expression Templates | Lazy evaluation | Eliminates temps |
| Type Traits | Type introspection | Compile-time |
| Fold Expressions | Parameter pack ops | Optimal |
| Template Specialization | Type-specific impl | Zero overhead |
+8
View File
@@ -0,0 +1,8 @@
.git
build*
dist
release
EchoionWeb/frontend/node_modules
EchoionWeb/frontend/web-dist
components
docs
+280
View File
@@ -0,0 +1,280 @@
# Echoion releases on Gitea
Echoion release builds run only through `scripts/release.sh`, whose default
mode builds, tests, validates, and packages inside
`containers/release.Dockerfile`. The runner host only checks out sources and
controls Docker; the workflow never starts `echoiond`.
## One-time Gitea setup
The workflows target the standard `ubuntu-24.04` label advertised by a default
Gitea runner. No custom runner label is required. Use one trusted Linux AMD64
runner with capacity set to one so release and feed writes remain serialized
on Gitea versions that do not implement workflow `concurrency`. The job image
needs Bash, Git with SSH-signature support, OpenSSH client tools, Python 3.10
or newer, OpenSSL with Ed25519 support, coreutils, the Docker CLI, and access
to a Docker daemon. The release builder itself remains containerized.
Every workflow starts by running `docker version` and `docker info`. These
commands verify both the Docker client in the `ubuntu-24.04` job image and
access to the daemon before checkout, secrets, or a long release build are
used. A runner installed as a container must have the host socket mounted:
```yaml
services:
runner:
volumes:
- ./data:/data
- /var/run/docker.sock:/var/run/docker.sock
```
Leave `container.docker_host` at its generated default (`""`) so `act_runner`
passes the detected Docker endpoint to job containers. Do not set it to `-`,
which explicitly prevents that endpoint from being mounted. Restart the runner
after changing its configuration. `scripts/lib/docker-daemon-path.sh` detects
when commands run inside the job container and translates checked-out paths
through that container's Docker mount table. The release wrapper and
control-plane tests both use it because bind mount paths passed to the socket
are resolved by the runner host daemon, not inside the Actions job container.
The shared `scripts/lib/component-ssh.sh` helper pins the current
`git.faumaray.ru` RSA host key. Its verified fingerprint is
`SHA256:fugBYnqAnqmTLsGpafVgQF9gPQzJqps7uHvs48blg2A`. If the Gitea SSH host key
is intentionally rotated, verify the new fingerprint through an independent
administrator channel and update the shared helper. Component Git commands use
`BatchMode=yes` and strict host
checking, so missing credentials or a changed host key fail instead of waiting
for interactive runner input. Never work around a rotation by disabling strict
host-key checking.
The Docker-capable runner executes only protected `main` pushes, manual runs,
scheduled nightlies, and signed release tags. The container CI workflow does
not run for pull requests because contributor-controlled scripts must not
receive a privileged Docker socket or release checkout credentials. If
pre-merge CI is required, register a separate ephemeral `echoion-pr` runner
without release secrets or host-level Docker access and give it a dedicated
workflow. A global runner such as the default installation shown in Gitea must
only serve repositories you trust: a workflow with Docker-daemon access can
control the runner host.
Enable Actions and configure these secrets:
| Secret | Scope | Purpose |
| --- | --- | --- |
| `RELEASE_CHECKOUT_SSH_KEY` | `Void` organization | Single-line base64 of the release-bot OpenSSH private key used to read every private component/dependency repository and to fast-forward the protected Echoion `release-feed` branch. |
| `RELEASE_BOT_TOKEN` | `Void` organization | PAT owned by a dedicated bot. It needs repository write scope for component releases and package write scope for the public organization registry. It does not need `release-feed` write access. |
| `RELEASE_TAG_ALLOWED_SIGNERS` | `Void` organization | Complete OpenSSH `allowed_signers` lines for maintainers allowed to publish `v*` tags. |
| `RELEASE_FEED_ED25519_PRIVATE_KEY` | `Void` organization | Single-line base64 of the Ed25519 PEM private key that signs component feeds. |
| `RELEASE_FEED_GIT_SIGNING_KEY` | `Void` organization | Single-line base64 of the OpenSSH private key that signs `release-feed` commits. |
| `RELEASE_FEED_ED25519_PUBLIC_KEY` | Echoion repository | PEM public key matching the component-feed signing key. It verifies independently published components without exposing signing authority to the product workflow. |
Encode multiline private keys with `base64 -w0` before storing them. This is a
security requirement: the release scripts reject raw multiline private keys so
runner environment diagnostics cannot disclose them. Keep the public
`RELEASE_TAG_ALLOWED_SIGNERS` and `RELEASE_FEED_ED25519_PUBLIC_KEY` values in
their documented text formats.
Root product checkouts use the public repository over HTTPS with
`persist-credentials: false`.
Independent workflows check out their current repository with Gitea's job
token and the public Echoion release tools over HTTPS; their private
component/dependency reads and `release-feed` push use the pinned SSH helper.
Release API operations use the bot PAT. The component-feed private signing key
must not be present in the Echoion product repository, Git, runner images,
Actions variables, or release assets.
## Independent component repositories
Echoion does not use Git submodules. `components.json` describes the nine
independent repositories: `EchoionApi`, `EchoionHost`, `EchoionCore`,
`EchoionWeb`, `EchoionStandalone`, `EchoionUpdater`, `EchoionDesktop`,
`EchoionPluginUrlShortenerInternal`, and
`EchoionPluginUrlShortenerExternal`. `components.lock.json` is the immutable
release checkout manifest. All Gitea workflows check out the locked revisions
as ordinary SSH repositories before entering Docker.
For a new developer checkout:
```bash
scripts/prepare-release.sh --workspace ..
```
For ordinary development CMake follows each component's `main` branch unless a
`CPM_<Component>_SOURCE` override is supplied. Release builds use the exact
lock. After changing a component, make a signed commit and push it over SSH
first, then refresh and commit the root lock:
```bash
scripts/prepare-release.sh --workspace ..
git add components.lock.json cmake/DependencyLock.cmake
git commit -S -m 'Release: lock Echoion 2.0.0 components'
```
The preparer refuses dirty, inaccessible, missing, non-fast-forward, or
version/tag-inconsistent component repositories, so a lock can never point at
unpublished source. Product version changes are separate: edit only
`project(Echoion VERSION ...)` in root `CMakeLists.txt`; orchestrated component
builds and release overrides inherit that value. A stable or beta release tag
must have the same numeric base as this CMake version, so `v2.0.0` and
`v2.0.0-rc.1` both require `project(Echoion VERSION 2.0.0 ...)`. The release
workflow rejects mismatches before building.
`scripts/prepare-release.sh` regenerates `components.lock.json`. When
VoidLibrary or VoidTeamspeak advances, update its exact pushed commit in
`cmake/DependencyLock.cmake` in the same lock commit.
Nightlies use the newer of the root CMake version and the next patch after the
latest published release. This prevents a stale CMake value from producing a
version rollback while still allowing a single CMake edit to move nightlies to
a newer minor or major release line.
Create an orphan `release-feed` branch containing a tracked `feeds/`
directory, then protect it so only the release bot can push. Protect the `v*`
tag pattern so only the release maintainers represented by
`RELEASE_TAG_ALLOWED_SIGNERS` can create, update, or delete matching tags. The
workflow requires the exact `v*` rule to have an explicit non-empty user or
team allowlist. Configure it under repository **Settings → Tags → Protected
tags**; a similar pattern such as `v*.*` does not satisfy the release check.
Gitea uses the same allowlist for tag creation and later tag changes; when
immutable release tags are required, add a server-side pre-receive policy that
rejects updates and deletion after creation. Protect `main` in the normal way.
The updater source can use the feed base:
```text
https://<gitea>/<owner>/<repo>/raw/branch/release-feed
```
or an exact channel catalog:
```text
https://<gitea>/<owner>/<repo>/raw/branch/release-feed/feeds/stable/catalog.json
```
The catalog resolves immutable component documents under
`feeds/<channel>/<component>/<version>.json` and plugin documents under
`feeds/<channel>/plugins/<plugin-id>/<version>.json`. The embedded updater
accepts legacy signed envelopes but new component and product publications use
envelope schema 3:
the signed document is rendered as indented JSON in `document`, while
`signedPayload` preserves the exact bytes covered by the Ed25519 signature.
Verification rejects any semantic difference between those two representations.
Component and product manifests, plus their corresponding
feeds, attest `buildType: "RelWithDebInfo"`; release tooling rejects any other
build type.
The embedded updater trust configuration is represented by
`.gitea/release-keys/official-update-keys.json`. `scripts/release.sh` validates and
embeds that JSON automatically. Release workflows also pass the HTTPS
channel catalog through `--official-update-feed-url`, so a fresh installation
has a signed official source without operator-side duplication. The v1
`feeds/echoion-runtime.json` feed is not published at the 2.0 cutover; v1
operators must stop their service and run the signed v2 installer manually.
## Stable and beta releases
Create an annotated SSH-signed tag. A version without a prerelease suffix goes
to `stable`; any strict SemVer prerelease goes to `beta`. First set the product
version in the root `CMakeLists.txt`, commit it, and use the same numeric base
for the tag:
```bash
git config gpg.format ssh
git config user.signingkey ~/.ssh/echoion-release-maintainer
git tag -s -a v2.0.0 -m 'Echoion 2.0.0'
test "$(git cat-file -t refs/tags/v2.0.0)" = tag
git push origin v2.0.0
```
The private-key path works without an SSH agent. A `.pub` path may be used
instead when its matching private key is already loaded in `ssh-agent`.
`.gitea/workflows/release.yml` rejects a lightweight tag, a non-SSH
signature, an untrusted signer, a repository without the exact `v*` protected
tag rule and explicit allowlist, a non-SemVer name, an event object unrelated
to the tag, or a checkout whose commit differs from the signed tag target.
Release notes contain the signed tag subject and body but not its SSH signature
armor.
The workflow creates or resumes a draft, replaces incomplete draft assets,
uploads every file in `dist/`, downloads every asset through Gitea, checks
its size and SHA-256, and only then publishes. A rerun against an already
published release is read-only and succeeds only when all remote assets still
match. The signed catalog and all component feeds are committed together after
release publication; a feed failure can therefore be retried without replacing
a published release.
## Nightly releases
`.gitea/workflows/nightly.yml` runs at 02:17 UTC and can also be dispatched
manually. The highest published `vMAJOR.MINOR.PATCH` release supplies the next
patch as `MAJOR.MINOR.(PATCH+1)-nightly.YYYYMMDD.RUN_NUMBER`. With no published
semantic release, nightlies use the root CMake
`project(Echoion VERSION x.y.z)` value without incrementing it. Drafts, failed
publications, and `nightly-*` releases do not affect the base. Nightlies use the
`nightly` channel, publish as prereleases, and keep the newest 14 Gitea
releases. Channel catalogs remain separate, and nightly publication never
advances stable component state. Gitea materializes a missing
`nightly-*` Git tag only when the download-verified draft is published; the
publisher then verifies its commit immediately and never moves an existing tag
whose target differs. Stable and beta publishing require their signed tag to
exist before creating a draft. If `nightly-*` is protected separately, allow
the release bot to create and delete it.
Every rolling catalog and `latest.json` envelope expires 45 days after
generation. Scheduled
nightlies normally refresh it daily. Alert when the feed branch has not
advanced for more than seven days, and treat 30 days without a successful
signing run as urgent.
## Feed key custody and rotation
The active component-feed public key id is
`echoion-component-release-2026-07-30-r2`. The superseded
`echoion-component-release-2026-07-30` key is intentionally absent because its
private material was revoked before any feed publication. The older
`echoion-component-release-2026-07` and `echoion-release-2026-07` keys remain
embedded for compatibility. To rotate,
generate the private key on a trusted operator machine:
```bash
umask 077
openssl genpkey -algorithm ED25519 -out echoion-release-YYYY-MM.pem
openssl pkey -in echoion-release-YYYY-MM.pem -pubout \
-out echoion-release-YYYY-MM.pub.pem
```
The PEM public key contains an RFC 8410 SubjectPublicKeyInfo wrapper. The
`ed25519` field in `release-keys/official-update-keys.json` must instead contain
the standard Base64 encoding of only the raw 32-byte public key. Derive that
value with:
```bash
openssl pkey -pubin -in echoion-release-YYYY-MM.pub.pem -outform DER |
tail -c 32 |
base64 -w0
printf '\n'
```
Add the new public key to official builds before signing any feed with it and
keep the old public key embedded for at least one full update lifetime. Update
the signing key id in component release workflows and replace their private-key
secret only after the build containing both trust roots is installed broadly.
Replace the product workflow's public-key secret at the same cutover.
Immutable version feeds are never rewritten during rotation. Never print the
private key or pass it as a command-line argument.
## Recovery rules
- A failed build creates no Gitea release.
- A failed upload leaves a draft. Rerun the same workflow to replace the
partial draft assets.
- A failed verification never publishes the draft.
- A published release with mismatched assets is immutable; investigate and
create a new version instead of replacing it.
- A failed feed push leaves the published release available but undiscoverable
to auto-update. Rerun the workflow; publication verification is idempotent
and the feed step will run again.
- Never edit `release-feed` manually. The publisher validates immutable
version feeds, replay sequences, and component state before committing the
complete transaction.
@@ -0,0 +1,3 @@
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAqD97/GZ6BJaeQpg6shajRcNhwMzvNZ3SvkQtAu6pxEw=
-----END PUBLIC KEY-----
@@ -0,0 +1,14 @@
[
{
"id": "echoion-release-2026-07",
"ed25519": "qD97/GZ6BJaeQpg6shajRcNhwMzvNZ3SvkQtAu6pxEw="
},
{
"id": "echoion-component-release-2026-07",
"ed25519": "vUZXQXNkY/f/D42z6/dYK8SNxCvXjxYQ8ZCpjecIclk="
},
{
"id": "echoion-component-release-2026-07-30-r2",
"ed25519": "0ioZyP3v38st9qShLG9+gvdM8xd8AgO7UNaP5eeHflk="
}
]
+81
View File
@@ -0,0 +1,81 @@
name: Modular container CI
on:
push:
branches:
- main
workflow_dispatch:
permissions:
contents: read
jobs:
release-build:
runs-on: ubuntu-24.04
steps:
- name: Verify the Docker-capable Gitea runner
shell: bash
run: |
set -euo pipefail
test "$(uname -s)" = Linux
command -v docker
docker version
docker info
- name: Check out public root
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
fetch-depth: 0
persist-credentials: false
- name: Verify source-free root and resolve every lock over SSH
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: |
set -euo pipefail
test ! -e .gitmodules
if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }'
then
echo "root release contains a gitlink" >&2
exit 1
fi
scripts/ci-checkout-components.sh \
"$PWD/components" \
"$PWD/dependencies"
scripts/prepare-release.sh \
--workspace "$PWD/components" \
--check
- name: Build, test, and package without starting Echoion
env:
CI_VERSION: 2.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }}
run: |
set -euo pipefail
scripts/release.sh \
--version "$CI_VERSION" \
--component-workspace "$PWD/components" \
--void-source "$PWD/dependencies/VoidLibrary" \
--void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \
--update-channel beta \
--update-sequence "${{ gitea.run_number }}"
- name: Test release control-plane scripts offline
shell: bash
run: |
set -euo pipefail
bash scripts/tests/test-gitea-tag-verification.sh
bash scripts/tests/test-component-ssh-secrets.sh
. scripts/lib/docker-daemon-path.sh
docker_workspace=$(docker_daemon_path "$PWD")
for test_script in \
scripts/tests/test_package_components.py \
scripts/tests/test_publish_component_feeds.py \
scripts/tests/test_gitea_release.py
do
docker run --rm --network none \
--volume "$docker_workspace:/workspace:ro" \
--workdir /workspace \
echoion-release-builder:gcc-16.1.0 \
python3 "$test_script"
done
+103
View File
@@ -0,0 +1,103 @@
name: Nightly product integration
on:
schedule:
- cron: '17 2 * * *'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: echoion-release-feed
cancel-in-progress: false
jobs:
publish-nightly:
runs-on: ubuntu-24.04
steps:
- name: Verify the Docker-capable Gitea runner
shell: bash
run: |
set -euo pipefail
test "$(uname -s)" = Linux
command -v docker
docker version
docker info
- name: Check out public signed main
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
ref: main
fetch-depth: 0
persist-credentials: false
- name: Verify root cutover and check out locked components over SSH
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: |
set -euo pipefail
test ! -e .gitmodules
if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }'
then
echo "root release contains a gitlink" >&2
exit 1
fi
scripts/ci-checkout-components.sh \
"$PWD/components" \
"$PWD/dependencies"
scripts/prepare-release.sh \
--workspace "$PWD/components" \
--check
- name: Derive nightly identity and URLs
shell: bash
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
API_URL: ${{ gitea.api_url }}
SERVER_URL: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
RUN_NUMBER: ${{ gitea.run_number }}
run: |
set -euo pipefail
date_id=$(date -u +%Y%m%d)
owner=${REPOSITORY%%/*}
repo=${REPOSITORY#*/}
version=$(
python3 scripts/gitea_release.py \
--api-url "$API_URL" \
derive-nightly-version \
--owner "$owner" \
--repo "$repo" \
--cmake-file CMakeLists.txt \
--date-id "$date_id" \
--run-number "$RUN_NUMBER"
)
tag="nightly-${date_id}-${RUN_NUMBER}"
python3 scripts/validate-semver.py "$version"
{
printf 'RELEASE_TAG=%s\n' "$tag"
printf 'RELEASE_VERSION=%s\n' "$version"
printf 'RELEASE_CHANNEL=nightly\n'
printf 'RELEASE_SEQUENCE=%s\n' "$RUN_NUMBER"
printf 'RELEASE_ARTIFACT_BASE_URL=%s\n' \
"${SERVER_URL}/${REPOSITORY}/releases/download/${tag}"
printf 'RELEASE_FEED_URL=%s\n' \
"${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/nightly/catalog.json"
printf 'RELEASE_TARGET=%s\n' "$(git rev-parse HEAD)"
} >>"$GITHUB_ENV"
- name: Build and test all locked repositories in Docker
shell: bash
run: |
set -euo pipefail
scripts/release.sh \
--version "$RELEASE_VERSION" \
--skip-component-packages \
--component-workspace "$PWD/components" \
--void-source "$PWD/dependencies/VoidLibrary" \
--void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \
--official-update-feed-url "$RELEASE_FEED_URL" \
--update-channel nightly \
--update-sequence "$RELEASE_SEQUENCE"
+224
View File
@@ -0,0 +1,224 @@
name: Signed modular release
on:
push:
tags:
- v*
permissions:
contents: read
concurrency:
group: echoion-release-feed
cancel-in-progress: false
jobs:
publish:
runs-on: ubuntu-24.04
steps:
- name: Verify the Docker-capable Gitea runner
shell: bash
run: |
set -euo pipefail
test "$(uname -s)" = Linux
command -v docker
docker version
docker info
- name: Check out the public signed root tag
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
ref: ${{ gitea.ref }}
fetch-depth: 0
persist-credentials: false
- name: Reject embedded component sources and gitlinks
shell: bash
run: |
set -euo pipefail
test ! -e .gitmodules
if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }'
then
echo "root release contains a gitlink" >&2
exit 1
fi
python3 - <<'PY'
import json
import pathlib
components = json.loads(pathlib.Path("components.json").read_text())
embedded = [
name for name in components["components"]
if pathlib.Path(name).exists()
]
if embedded:
raise SystemExit(f"embedded component sources: {embedded}")
PY
- name: Check out every locked component and dependency over SSH
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: >-
scripts/ci-checkout-components.sh
"$PWD/components"
"$PWD/dependencies"
- name: Verify protected annotated SSH tag and release lock
shell: bash
env:
TAG: ${{ gitea.ref_name }}
EXPECTED_EVENT_SHA: ${{ gitea.sha }}
EXPECTED_REF: ${{ gitea.ref }}
EXPECTED_REF_TYPE: ${{ gitea.ref_type }}
TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }}
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
API_URL: ${{ gitea.api_url }}
REPOSITORY: ${{ gitea.repository }}
run: |
set -euo pipefail
test "$EXPECTED_REF_TYPE" = tag
test "$EXPECTED_REF" = "refs/tags/$TAG"
allowed_signers="$RUNNER_TEMP/echoion-release-allowed-signers"
tag_credentials="$RUNNER_TEMP/echoion-release-tag-ssh"
trap 'rm -rf -- "$tag_credentials"; rm -f -- "$allowed_signers"' EXIT
umask 077
printf '%s\n' "$TAG_ALLOWED_SIGNERS" >"$allowed_signers"
test -s "$allowed_signers"
. scripts/lib/component-ssh.sh
echoion_configure_component_ssh \
"$tag_credentials" "$ECHOION_COMPONENT_SSH_KEY"
scripts/restore-gitea-release-tag.sh \
--repository "ssh://gitea@git.faumaray.ru/$REPOSITORY.git" \
--tag "$TAG"
target_commit=$(
scripts/verify-gitea-release-tag.sh \
--tag "$TAG" \
--event-sha "$EXPECTED_EVENT_SHA" \
--allowed-signers "$allowed_signers" \
--notes-output "$RUNNER_TEMP/release-notes.md"
)
printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV"
scripts/prepare-release.sh \
--workspace "$PWD/components" \
--check
owner=${REPOSITORY%%/*}
repo=${REPOSITORY#*/}
python3 scripts/gitea_release.py \
--api-url "$API_URL" \
verify-tag-protection \
--owner "$owner" \
--repo "$repo" \
--required-pattern 'v*'
- name: Derive release channel and URLs
shell: bash
env:
TAG: ${{ gitea.ref_name }}
API_URL: ${{ gitea.api_url }}
SERVER_URL: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
RUN_NUMBER: ${{ gitea.run_number }}
run: |
set -euo pipefail
version=${TAG#v}
test "$version" != "$TAG"
python3 scripts/validate-semver.py "$version"
project_version=$(
python3 scripts/gitea_release.py \
--api-url "$API_URL" \
cmake-project-version \
--cmake-file CMakeLists.txt
)
tag_base=${version%%[-+]*}
test "$tag_base" = "$project_version"
channel=stable
prerelease=false
if [[ "$version" == *-* ]]; then
channel=beta
prerelease=true
fi
feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/${channel}/catalog.json"
artifact_url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}"
{
printf 'RELEASE_TAG=%s\n' "$TAG"
printf 'RELEASE_VERSION=%s\n' "$version"
printf 'RELEASE_CHANNEL=%s\n' "$channel"
printf 'RELEASE_PRERELEASE=%s\n' "$prerelease"
printf 'RELEASE_SEQUENCE=%s\n' "$RUN_NUMBER"
printf 'RELEASE_ARTIFACT_BASE_URL=%s\n' "$artifact_url"
printf 'RELEASE_FEED_URL=%s\n' "$feed_url"
} >>"$GITHUB_ENV"
- name: Check out the protected release-feed branch
shell: bash
env:
ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }}
run: |
set -euo pipefail
feed_credentials="$RUNNER_TEMP/echoion-release-feed-ssh"
trap 'rm -rf -- "$feed_credentials"' EXIT
. scripts/lib/component-ssh.sh
echoion_configure_component_ssh \
"$feed_credentials" "$ECHOION_COMPONENT_SSH_KEY"
git clone --filter=blob:none --branch release-feed --single-branch \
ssh://gitea@git.faumaray.ru/Void/Echoion.git feed-state
- name: Verify every locked component was independently published
shell: bash
env:
FEED_PUBLIC_KEY: ${{ secrets.RELEASE_FEED_ED25519_PUBLIC_KEY }}
run: |
set -euo pipefail
feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pub.pem"
trap 'rm -f -- "$feed_key"' EXIT
printf '%s\n' "$FEED_PUBLIC_KEY" >"$feed_key"
chmod 0644 "$feed_key"
openssl pkey -pubin -in "$feed_key" -noout
python3 scripts/verify-locked-component-feeds.py \
--registry components.json \
--lock components.lock.json \
--feed-root feed-state \
--channel "$RELEASE_CHANNEL" \
--key-id "${{ vars.ECHOION_FEED_SIGNING_KEY_ID }}" \
--public-key "$feed_key"
- name: Build, test, and package all locked repositories in Docker
shell: bash
run: |
set -euo pipefail
scripts/release.sh \
--version "$RELEASE_VERSION" \
--skip-component-packages \
--component-workspace "$PWD/components" \
--void-source "$PWD/dependencies/VoidLibrary" \
--void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \
--official-update-feed-url "$RELEASE_FEED_URL" \
--update-channel "$RELEASE_CHANNEL" \
--update-sequence "$RELEASE_SEQUENCE"
- name: Create draft, upload, download-verify, and publish
shell: bash
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }}
API_URL: ${{ gitea.api_url }}
REPOSITORY: ${{ gitea.repository }}
run: |
set -euo pipefail
owner=${REPOSITORY%%/*}
repo=${REPOSITORY#*/}
prerelease=()
if [[ "$RELEASE_PRERELEASE" = true ]]; then
prerelease+=(--prerelease)
fi
python3 scripts/gitea_release.py \
--api-url "$API_URL" \
publish \
--owner "$owner" \
--repo "$repo" \
--tag "$RELEASE_TAG" \
--target "$RELEASE_TARGET" \
--name "Echoion $RELEASE_VERSION" \
--body-file "$RUNNER_TEMP/release-notes.md" \
--artifacts dist \
"${prerelease[@]}"
+18 -2
View File
@@ -1,6 +1,22 @@
*build*
!EchoionStandalone/tests/test_update_build_defaults.cpp
release
/dist/
__pycache__/
*.py[cod]
.cache
.idea
AGENTS.md
.vscode
.opencode/
# Independently cloned component repositories. Their immutable release
# revisions are recorded in components.lock.json.
/EchoionApi/
/EchoionCore/
/EchoionDesktop/
/EchoionHost/
/EchoionStandalone/
/EchoionUpdater/
/EchoionWeb/
/EchoionPluginUrlShortenerInternal/
/EchoionPluginUrlShortenerExternal/
/components/
-15
View File
@@ -1,15 +0,0 @@
[submodule "EchoionApi"]
path = EchoionApi
url = ssh://gitea@git.faumaray.ru/void/echoionapi.git
[submodule "EchoionCore"]
path = EchoionCore
url = ssh://gitea@git.faumaray.ru/void/echoioncore.git
[submodule "EchoionPlugin"]
path = EchoionPlugin
url = ssh://gitea@git.faumaray.ru/void/echoionplugin.git
[submodule "EchoionDesktop"]
path = EchoionDesktop
url = ssh://gitea@git.faumaray.ru/void/echoiondesktop.git
[submodule "docs"]
path = docs
url = ssh://gitea@git.faumaray.ru/void/echoion.wiki.git
-646
View File
@@ -1,646 +0,0 @@
# Phase 0: Decoupled State Management Foundation - Implementation Plan
## Overview
Build the foundation for decoupled state management where:
- **Plugin** never knows Core's internal state structure
- **Core** handles all serialization/deserialization internally
- **State format can change** without Plugin rebuilds
- **10 versions backward compatibility** with graceful degradation
## Architecture
```
EchoionApi (stable interface)
├── ICoreInterface.hpp - Add state management methods
└── SerializedState.hpp - Opaque blob type
EchoionCore (internal implementation)
├── StateSerializer.hpp/cpp - Versioned serialization using glaze
├── StateMigration.hpp/cpp - Migration between versions
├── StateV0.hpp, StateV1.hpp, ... - Version-specific state structures
└── Core.cpp - Implement state capture/restore
EchoionPlugin (unchanged except CoreLoader)
└── CoreLoader.cpp - Use opaque blobs, no state parsing
```
## Files to Create/Modify
### 1. EchoionApi Changes
**File**: `EchoionApi/include/echoion/api/interfaces/CoreInterface.hpp`
Add to `ICoreInterface`:
```cpp
// State management - opaque to caller
virtual Api::SerializedState saveState() = 0;
virtual Api::Result<void> restoreState(const Api::SerializedState& state) = 0;
// Version info
virtual uint32_t getStateFormatVersion() const = 0;
virtual bool canRestoreStateVersion(uint32_t version) const = 0;
```
**File**: `EchoionApi/include/echoion/api/base/SerializedState.hpp` (NEW)
```cpp
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace Echoion::Api {
// Opaque state blob - contents are internal to Core
struct SerializedState {
std::vector<uint8_t> data; // Serialized state data (JSON using glaze)
uint32_t version = 0; // Format version (for logging/debugging only)
std::string timestamp; // ISO 8601 timestamp when saved
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
};
// Constants
constexpr uint32_t MAX_SUPPORTED_STATE_VERSION_AGE = 10; // Support 10 versions back
constexpr uint32_t STATE_VERSION_NONE = 0;
} // namespace Echoion::Api
```
### 2. EchoionCore Changes
**File**: `EchoionCore/include/echoion/core/state/StateSerializer.hpp` (NEW)
```cpp
#pragma once
#include "echoion/core/state/StateVersions.hpp"
#include <SerializedState.hpp>
#include <Types.hpp>
#include <glaze/glaze.hpp>
#include <cstdint>
#include <string>
namespace Echoion::Core {
class StateSerializer {
public:
// Current version being used
static constexpr uint32_t CURRENT_VERSION = 1;
// Serialize current state to opaque blob
static Api::SerializedState serialize(const StateV1& state);
// Deserialize blob to current version (handles migration)
static Api::Result<StateV1> deserialize(const Api::SerializedState& blob);
// Check if version is supported
static bool isVersionSupported(uint32_t version);
// Get supported version range
static uint32_t getMinimumSupportedVersion();
static uint32_t getCurrentVersion();
private:
// Migration functions
static Api::Result<StateV1> migrateToV1(const StateV0& old);
// Extract version from JSON blob
static uint32_t extractVersion(const std::string& jsonStr);
};
} // namespace Echoion::Core
```
**File**: `EchoionCore/include/echoion/core/state/StateVersions.hpp` (NEW)
```cpp
#pragma once
#include <TrackTypes.hpp>
#include <vector>
#include <optional>
#include <cstdint>
#include <string>
namespace Echoion::Core {
// State V0 - Initial version (placeholder for future)
struct StateV0 {
// Minimal state for testing migration
std::vector<std::string> trackIds;
float volume = 0.5f;
};
// State V1 - Current version
struct StateV1 {
// Playback state
struct PlaybackState {
Api::TrackInfo currentTrack;
std::chrono::milliseconds position{0};
bool isPlaying = false;
bool isPaused = false;
float volume = 0.5f;
bool shuffle = false;
bool repeat = false;
};
// Queue entry with metadata
struct QueueEntryState {
Api::TrackInfo track;
uint64_t queueId = 0;
std::string addedBy; // Nickname or UID
std::string addedAt; // ISO 8601
};
// Session state for RPC clients
struct SessionState {
uint64_t clientId = 0;
std::string authToken;
std::string lastActivity; // ISO 8601
};
// Main state
std::optional<PlaybackState> playback;
std::vector<QueueEntryState> queue;
std::vector<SessionState> sessions;
// Version info
uint32_t version = 1;
std::string savedAt; // ISO 8601
};
} // namespace Echoion::Core
// Glaze JSON reflection for StateV1
// (Add in StateVersions.cpp or at end of header)
template <>
struct glz::meta<Echoion::Core::StateV1> {
using T = Echoion::Core::StateV1;
static constexpr auto value = object(
"playback", &T::playback,
"queue", &T::queue,
"sessions", &T::sessions,
"version", &T::version,
"savedAt", &T::savedAt
);
};
```
**File**: `EchoionCore/include/echoion/core/state/StateMigration.hpp` (NEW)
```cpp
#pragma once
#include "echoion/core/state/StateVersions.hpp"
#include <Types.hpp>
#include <cstdint>
namespace Echoion::Core {
// Handles migration between state versions
class StateMigration {
public:
// Migrate from any old version to current
static Api::Result<StateV1> migrate(uint32_t fromVersion, const std::string& jsonData);
// Specific migrations
static StateV1 fromV0(const StateV0& v0);
// Check if migration path exists
static bool canMigrate(uint32_t fromVersion);
private:
// Migration chain: V0 -> V1 -> V2 -> ...
// Each version only knows how to migrate from previous
};
} // namespace Echoion::Core
```
**File**: `EchoionCore/src/state/StateSerializer.cpp` (NEW)
```cpp
#include "echoion/core/state/StateSerializer.hpp"
#include "echoion/core/Logger.hpp"
#include <format>
namespace Echoion::Core {
Api::SerializedState StateSerializer::serialize(const StateV1& state) {
// Serialize to JSON using glaze
std::string jsonStr;
auto ec = glz::write_json(state, jsonStr);
if (ec) {
ECHOION_LOG_ERROR(std::format("Failed to serialize state: {}",
glz::format_error(ec, jsonStr)));
return Api::SerializedState{};
}
// Convert to binary blob
std::vector<uint8_t> data(jsonStr.begin(), jsonStr.end());
return Api::SerializedState{
.data = std::move(data),
.version = CURRENT_VERSION,
.timestamp = getCurrentTimestampISO8601()
};
}
Api::Result<StateV1> StateSerializer::deserialize(const Api::SerializedState& blob) {
if (blob.data.empty()) {
return std::unexpected(Api::Error(
Api::ErrorCode::InvalidArgument,
"Empty state blob"
));
}
// Convert blob to string
std::string jsonStr(blob.data.begin(), blob.data.end());
// Extract version
uint32_t dataVersion = extractVersion(jsonStr);
ECHOION_LOG_INFO(std::format("Deserializing state version {}", dataVersion));
// Check if version is supported
if (!isVersionSupported(dataVersion)) {
if (dataVersion > CURRENT_VERSION) {
return std::unexpected(Api::Error(
Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is from a newer Core. "
"Please update/restart to load this state.",
dataVersion)
));
} else {
return std::unexpected(Api::Error(
Api::ErrorCode::IncompatibleVersion,
std::format("State version {} is too old. "
"Maximum supported age is {} versions.",
dataVersion, Api::MAX_SUPPORTED_STATE_VERSION_AGE)
));
}
}
// If current version, parse directly
if (dataVersion == CURRENT_VERSION) {
StateV1 state;
auto ec = glz::read_json(state, jsonStr);
if (ec) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
std::format("Failed to parse state: {}",
glz::format_error(ec, jsonStr))
));
}
return state;
}
// Otherwise, migrate
return StateMigration::migrate(dataVersion, jsonStr);
}
bool StateSerializer::isVersionSupported(uint32_t version) {
if (version > CURRENT_VERSION) {
return false; // Future version
}
uint32_t minVersion = getMinimumSupportedVersion();
return version >= minVersion && version <= CURRENT_VERSION;
}
uint32_t StateSerializer::getMinimumSupportedVersion() {
// Support 10 versions back, but not below 1
return (CURRENT_VERSION > Api::MAX_SUPPORTED_STATE_VERSION_AGE)
? CURRENT_VERSION - Api::MAX_SUPPORTED_STATE_VERSION_AGE
: 1;
}
uint32_t StateSerializer::getCurrentVersion() {
return CURRENT_VERSION;
}
uint32_t StateSerializer::extractVersion(const std::string& jsonStr) {
// Quick extraction without full parse
// Look for "version": N pattern
size_t pos = jsonStr.find("\"version\"");
if (pos != std::string::npos) {
pos = jsonStr.find(':', pos);
if (pos != std::string::npos) {
// Skip whitespace
pos++;
while (pos < jsonStr.size() && std::isspace(jsonStr[pos])) {
pos++;
}
// Parse number
if (pos < jsonStr.size() && std::isdigit(jsonStr[pos])) {
return static_cast<uint32_t>(std::stoul(jsonStr.substr(pos)));
}
}
}
// Default to 0 (unknown/legacy)
return 0;
}
} // namespace Echoion::Core
```
**File**: `EchoionCore/src/state/StateMigration.cpp` (NEW)
```cpp
#include "echoion/core/state/StateMigration.hpp"
#include "echoion/core/Logger.hpp"
#include <glaze/glaze.hpp>
#include <format>
namespace Echoion::Core {
Api::Result<StateV1> StateMigration::migrate(uint32_t fromVersion, const std::string& jsonData) {
ECHOION_LOG_INFO(std::format("Migrating state from version {} to {}",
fromVersion, StateSerializer::CURRENT_VERSION));
// Migration chain: fromVersion -> ... -> CURRENT_VERSION
// For now, only V0 -> V1 is implemented
// Future: V1 -> V2, V2 -> V3, etc.
if (fromVersion == 0) {
StateV0 v0;
auto ec = glz::read_json(v0, jsonData);
if (ec) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
"Failed to parse V0 state"
));
}
return fromV0(v0);
}
// Add more migrations here as versions evolve
// if (fromVersion == 1) { return fromV1(...); }
return std::unexpected(Api::Error(
Api::ErrorCode::IncompatibleVersion,
std::format("No migration path from version {}", fromVersion)
));
}
StateV1 StateMigration::fromV0(const StateV0& v0) {
StateV1 v1;
// Migrate queue
for (const auto& trackId : v0.trackIds) {
StateV1::QueueEntryState entry;
entry.track.id = trackId;
entry.track.title = "Unknown";
entry.track.artist = "Unknown";
v1.queue.push_back(std::move(entry));
}
// Migrate playback state
if (!v1.queue.empty()) {
StateV1::PlaybackState playback;
playback.currentTrack = v1.queue[0].track;
playback.volume = v0.volume;
v1.playback = std::move(playback);
}
v1.version = 1;
v1.savedAt = getCurrentTimestampISO8601();
return v1;
}
bool StateMigration::canMigrate(uint32_t fromVersion) {
return fromVersion >= StateSerializer::getMinimumSupportedVersion() &&
fromVersion < StateSerializer::CURRENT_VERSION;
}
} // namespace Echoion::Core
```
### 3. Core.cpp Modifications
**File**: `EchoionCore/src/Core.cpp`
Add state management implementation:
```cpp
// Add includes
#include "echoion/core/state/StateSerializer.hpp"
#include "echoion/core/state/StateVersions.hpp"
// Add to Core class implementation:
Api::SerializedState Core::saveState() {
ECHOION_LOG_INFO("Saving Core state...");
StateV1 state;
// Capture current playback state
if (currentTrack_.has_value()) {
StateV1::PlaybackState playback;
playback.currentTrack = currentTrack_->track;
playback.position = currentTrack_->position;
playback.isPlaying = isPlaying_;
playback.isPaused = isPaused_;
playback.volume = volume_;
playback.shuffle = shuffle_;
playback.repeat = repeat_;
state.playback = std::move(playback);
}
// Capture queue
auto queueResult = musicManager_->getQueue();
if (queueResult) {
for (const auto& entry : *queueResult) {
StateV1::QueueEntryState entryState;
entryState.track = entry.track;
entryState.queueId = entry.queueId;
entryState.addedBy = entry.addedBy;
entryState.addedAt = formatTimestamp(entry.addedAt);
state.queue.push_back(std::move(entryState));
}
}
// Capture sessions (from session manager)
// ... session capture code ...
// Serialize
auto blob = StateSerializer::serialize(state);
ECHOION_LOG_INFO(std::format("State saved: version={}, size={} bytes",
blob.version, blob.size()));
return blob;
}
Api::Result<void> Core::restoreState(const Api::SerializedState& state) {
ECHOION_LOG_INFO(std::format("Restoring Core state: version={}", state.version));
auto result = StateSerializer::deserialize(state);
if (!result) {
return std::unexpected(result.error());
}
const StateV1& stateData = *result;
// Restore playback
if (stateData.playback.has_value()) {
// Restore track, position, volume, etc.
// ... restoration code ...
}
// Restore queue
for (const auto& entry : stateData.queue) {
// Add to music manager queue
// ... queue restoration ...
}
// Restore sessions
// ... session restoration ...
ECHOION_LOG_INFO("State restored successfully");
return {};
}
uint32_t Core::getStateFormatVersion() const {
return StateSerializer::CURRENT_VERSION;
}
bool Core::canRestoreStateVersion(uint32_t version) const {
return StateSerializer::isVersionSupported(version);
}
```
### 4. CoreLoader.cpp Modifications
**File**: `EchoionPlugin/src/CoreLoader.cpp`
Update hot reload to use opaque blobs:
```cpp
Api::Result<void> CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) {
std::lock_guard<std::mutex> lock(mutex_);
if (!loaded_) {
return std::unexpected(Api::Error(Api::ErrorCode::NotFound,
"No core loaded to reload"));
}
hotReloading_ = true;
ECHOION_LOG_INFO("Starting hot reload with decoupled state...");
// Step 1: Save state as opaque blob (Plugin doesn't know contents)
Api::SerializedState stateBlob;
if (core_) {
stateBlob = core_->saveState();
ECHOION_LOG_INFO(std::format("Saved state: version={}, size={} bytes",
stateBlob.version, stateBlob.size()));
}
// Step 2: Unload old Core
auto unloadResult = unloadLibraryInternal();
if (!unloadResult) {
hotReloading_ = false;
return unloadResult;
}
// Step 3: Load new Core
auto targetPath = newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath;
if (!std::filesystem::exists(targetPath)) {
hotReloading_ = false;
return std::unexpected(Api::Error(
Api::ErrorCode::NotFound,
std::format("New library not found: {}", targetPath.string())));
}
// ... (existing temp file copying code) ...
auto loadResult = loadLibraryInternal(tempLibraryPath_);
if (!loadResult) {
hotReloading_ = false;
return loadResult;
}
// Step 4: Restore state (Core handles migration internally)
if (!stateBlob.empty()) {
auto coreVersion = core_->getStateFormatVersion();
auto stateVersion = stateBlob.version;
ECHOION_LOG_INFO(std::format("Restoring state v{} to Core v{}",
stateVersion, coreVersion));
if (core_->canRestoreStateVersion(stateVersion)) {
auto restoreResult = core_->restoreState(stateBlob);
if (!restoreResult) {
ECHOION_LOG_ERROR(std::format("Failed to restore state: {}",
restoreResult.error().message));
// Check if it's a version issue
if (restoreResult.error().code == Api::ErrorCode::IncompatibleVersion) {
// Signal user to update/restart
ECHOION_LOG_WARNING("State version incompatible. "
"User needs to update/restart.");
// Optionally: notify through plugin interface
}
// Continue with empty state - graceful degradation
} else {
ECHOION_LOG_INFO("State restored successfully");
}
} else {
ECHOION_LOG_WARNING(std::format(
"Cannot restore state v{} in Core v{}. "
"Version age exceeds maximum supported ({} versions).",
stateVersion, coreVersion, Api::MAX_SUPPORTED_STATE_VERSION_AGE));
// Continue with empty state
}
}
currentLibraryPath_ = targetPath;
hotReloading_ = false;
ECHOION_LOG_INFO("Hot reload complete");
return {};
}
```
## Implementation Order
1. **Create Api types** (SerializedState.hpp)
2. **Update ICoreInterface** (add state methods)
3. **Create StateVersions.hpp** (StateV0, StateV1 structures)
4. **Create StateSerializer** (serialize/deserialize)
5. **Create StateMigration** (V0 -> V1 migration)
6. **Update Core.cpp** (implement saveState/restoreState)
7. **Update CoreLoader.cpp** (use opaque blobs)
8. **Test** (save/restore, migration, version limits)
## Testing Checklist
- [ ] Save state creates valid JSON blob
- [ ] Restore state works for current version
- [ ] Migration V0 -> V1 works correctly
- [ ] Version 11 versions old is rejected with clear message
- [ ] Version from future signals user to update/restart
- [ ] Empty state blob handled gracefully
- [ ] Corrupted state handled gracefully (don't crash)
- [ ] Hot reload preserves state across Core reload
- [ ] State survives 100 hot reloads without corruption
## Success Criteria
1. ✅ Plugin never inspects state blob contents
2. ✅ State format can change without Plugin rebuild
3. ✅ 10 versions backward compatibility
4. ✅ Clear signal to user when version > 10 versions old
5. ✅ Clear signal when state is from future version
6. ✅ Graceful degradation on errors
7. ✅ Uses only glaze (no new dependencies)
Ready to start implementation?
-513
View File
@@ -1,513 +0,0 @@
# Echoion Robustness Improvement Plan
## Executive Summary
This plan addresses robustness for 100+ concurrent users on 4core/8GB hardware while maintaining the TeamSpeak plugin architecture with weekly hot-reload capability.
**Key Architectural Principle**: Plugin and Core are completely decoupled. Core manages its own state serialization/deserialization internally. Plugin only handles opaque state blobs.
**Dependencies**: Uses only existing dependencies (glaze, Boost, TBB, etc.). No new dependencies required.
## Current Pain Points
### 1. Connection Handling (Critical)
- **Issue**: Thread-per-client model creates unlimited threads (RpcServer.cpp:167-196)
- **Risk**: Resource exhaustion with 100+ users
- **Impact**: System instability, crashes
### 2. No Resource Limits
- **Issue**: No memory/CPU limits, unbounded queue growth
- **Risk**: OOM kills, audio dropouts
- **Impact**: Service degradation for all users
### 3. Missing Circuit Breakers
- **Issue**: yt-dlp failures cascade (no failure isolation)
- **Risk**: Repeated failed requests consume resources
- **Impact**: Bot becomes unresponsive
### 4. Race Conditions
- **Issue**: Queue modifications lack proper synchronization
- **Risk**: Data corruption, crashes
- **Impact**: Inconsistent state
### 5. No Health Monitoring
- **Issue**: No self-diagnostics or automatic recovery
- **Risk**: Silent failures accumulate
- **Impact**: Extended downtime
## Decoupled State Management Architecture
The key insight: **Plugin should never know what state Core needs to save**. Core handles all serialization internally using versioned formats.
```
┌─────────────────────────────────────────────────────────────────────┐
│ TeamSpeak Client │
│ ┌───────────────────────────────────────────────────────────────┐ │
│ │ EchoionPlugin (.ts plugin) │ │
│ │ │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ Plugin │ │ Health │ │ StateManager │ │ │
│ │ │ Interface │ │ Monitor │ │ (Opaque Blob) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │
│ │ │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ CoreLoader │ │ Connection │ │ Watchdog │ │ │
│ │ │ (Hot Reload) │ │ Pool │ │ (Heartbeat) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │
│ │ │ │
│ │ Plugin ONLY knows: │ │
│ │ - Core exports: saveState() -> opaque blob │ │
│ │ - Core exports: restoreState(blob) -> success/failure │ │
│ │ - Plugin stores blob temporarily, passes it back │ │
│ │ - Plugin NEVER parses or inspects blob contents │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
│
│ dylib::library (hot reloadable)
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ EchoionCore (.ts library) │
│ ┌───────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Core Internally Manages: │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │ │
│ │ │ StateVersion │ │ Migration │ │ StateSerializer │ │ │
│ │ │ (v1, v2) │ │ Engine │ │ (glaze JSON) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────────────┘ │ │
│ │ │ │
│ │ State Format can change without Plugin rebuild: │ │
│ │ - Old Core saves state v1 │ │
│ │ - New Core loads state v1, migrates to v2 internally │ │
│ │ - Plugin just passes the blob through │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Core │ │ RPC │ │ Resource │ │
│ │ (Main) │◄─┤ Server │ │ Manager │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ MusicManager │ │ YtDlpMgr │ │ Session │ │
│ │ │ │ (Circuit │ │ Manager │ │
│ │ │ │ Breaker) │ │ │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
```
## Decoupled State Management Design
### Core Interface (Stable API)
```cpp
// EchoionApi - Stable interface, never changes
class ICoreInterface {
public:
// State management - opaque to Plugin
virtual Api::SerializedState saveState() = 0;
virtual Api::Result<void> restoreState(const Api::SerializedState& state) = 0;
// Version info for compatibility
virtual uint32_t getStateFormatVersion() = 0;
virtual bool canRestoreStateVersion(uint32_t version) = 0;
};
// SerializedState is just an opaque blob
namespace Api {
struct SerializedState {
std::vector<uint8_t> data; // Plugin never inspects this
uint32_t version; // Format version for logging only
std::string timestamp; // ISO 8601 for debugging
};
}
```
### Core Internal State Management (Can Change Freely)
Uses **glaze** (already available) for JSON serialization:
```cpp
// EchoionCore - Internal implementation, can change anytime
class Core : public ICoreInterface {
private:
// Current state format version
static constexpr uint32_t CURRENT_STATE_VERSION = 2;
// Internal state structure - can change without affecting Plugin
struct StateV2 {
std::vector<QueueEntry> queue;
std::optional<PlaybackState> currentTrack;
float volume;
// ... new fields can be added anytime
};
// Migration support for backward compatibility
class StateMigration {
public:
static StateV2 migrateFromV1(const glz::json_t& v1Data);
static StateV2 migrateFromV0(const glz::json_t& v0Data);
};
public:
Api::SerializedState saveState() override {
StateV2 currentState = captureCurrentState();
// Serialize to JSON using glaze (already available)
std::string jsonState;
auto ec = glz::write_json(currentState, jsonState);
if (ec) {
// Handle error
return Api::SerializedState{};
}
// Convert to binary blob
std::vector<uint8_t> data(jsonState.begin(), jsonState.end());
return Api::SerializedState{
.data = std::move(data),
.version = CURRENT_STATE_VERSION,
.timestamp = getCurrentTimestamp()
};
}
Api::Result<void> restoreState(const Api::SerializedState& state) override {
// Convert blob back to string
std::string jsonStr(state.data.begin(), state.data.end());
// Parse version from JSON using glaze
uint32_t dataVersion = extractVersion(jsonStr);
// Migrate if needed (all handled internally)
if (dataVersion == CURRENT_STATE_VERSION) {
// Direct parse
StateV2 restoredState;
auto ec = glz::read_json(restoredState, jsonStr);
if (ec) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
"Failed to parse state"
));
}
applyState(restoredState);
} else if (dataVersion == 1) {
// Parse as V1, then migrate
StateV1 v1State;
auto ec = glz::read_json(v1State, jsonStr);
if (ec) {
return std::unexpected(Api::Error(
Api::ErrorCode::ParseError,
"Failed to parse V1 state"
));
}
StateV2 migrated = StateMigration::migrateFromV1(v1State);
applyState(migrated);
} else {
return std::unexpected(Api::Error(
Api::ErrorCode::IncompatibleVersion,
std::format("Cannot restore state version {} (current: {})",
dataVersion, CURRENT_STATE_VERSION)
));
}
return {};
}
};
```
### Plugin State Management (Simple Pass-Through)
```cpp
// EchoionPlugin - Never touches state internals
class CoreLoader {
public:
Api::Result<void> hotReload(const std::filesystem::path& newLibraryPath) {
// 1. Ask Core to save its state (opaque blob)
Api::SerializedState state;
if (core_) {
state = core_->saveState();
logInfo(std::format("Saved state: version={}, size={} bytes",
state.version, state.data.size()));
}
// 2. Unload old Core
auto unloadResult = unloadLibraryInternal();
if (!unloadResult) return unloadResult;
// 3. Load new Core
auto loadResult = loadLibraryInternal(newLibraryPath);
if (!loadResult) return loadResult;
// 4. Ask new Core to restore state (it handles migration internally)
if (!state.data.empty()) {
auto coreVersion = core_->getStateFormatVersion();
auto stateVersion = state.version;
if (core_->canRestoreStateVersion(stateVersion)) {
auto restoreResult = core_->restoreState(state);
if (!restoreResult) {
logError(std::format("Failed to restore state v{} to Core v{}",
stateVersion, coreVersion));
// Continue with empty state - graceful degradation
} else {
logInfo("State restored successfully");
}
} else {
logWarning(std::format("Cannot restore state v{} in Core v{}",
stateVersion, coreVersion));
// Continue with empty state
}
}
return {};
}
};
```
### State Format Evolution Example
```cpp
// Week 1: StateV1
struct StateV1 {
std::vector<QueueEntry> queue;
float volume;
};
// Week 2: StateV2 (added new field)
struct StateV2 {
std::vector<QueueEntry> queue;
float volume;
bool shuffleMode; // NEW FIELD
static V2 migrateFromV1(const V1& v1) {
return V2{
.queue = v1.queue,
.volume = v1.volume,
.shuffleMode = false // Default for migrated states
};
}
};
// Week 3: StateV3 (changed structure)
struct StateV3 {
struct Playlist {
std::vector<QueueEntry> tracks;
uint32_t currentIndex;
};
Playlist playlist; // Changed from flat queue
PlaybackSettings settings; // Grouped settings
static V3 migrateFromV2(const V2& v2) {
return V3{
.playlist = {.tracks = v2.queue, .currentIndex = 0},
.settings = {.volume = v2.volume, .shuffle = v2.shuffleMode}
};
}
};
// Plugin never needs to know about these changes!
```
## Implementation Phases
### Phase 0: Decoupled State Management Foundation (Week 0)
**Goal**: Establish the decoupled architecture before other improvements
**New Components**:
1. **StateSerializer.hpp/cpp** (Core) - Versioned state serialization using glaze
2. **StateMigration.hpp/cpp** (Core) - Migration between versions
3. Update **ICoreInterface.hpp** (Api) - Add state management methods
4. Refactor **Core.cpp** - Implement internal state management
5. Refactor **CoreLoader.cpp** - Use opaque state blobs
**Key Design Decisions**:
- State format uses glaze JSON (already available, high performance)
- Version stored in JSON for easy inspection
- Migration chain: V0 -> V1 -> V2 -> V3 (each version only knows previous)
- Graceful degradation: if migration fails, start fresh (don't crash)
### Phase 1: Connection Pool & Rate Limiting (Week 1)
**Goal**: Handle 100+ concurrent RPC connections safely
**Components**:
1. **ConnectionPool.hpp/cpp** - Fixed-size worker thread pool (16 workers)
2. **RateLimiter.hpp/cpp** - Token bucket per client IP (30 req/min, burst 10)
3. Update **RpcServer.cpp** - Integrate connection pool
**Dependencies**: Uses Boost.Asio (already available)
### Phase 2: Resource Management (Week 1-2)
**Goal**: Prevent resource exhaustion on 4core/8GB
**Components**:
1. **ResourceMonitor.hpp/cpp** - Track memory/CPU usage
2. Update **MusicManager.cpp** - Queue limits (500 tracks), memory caps
3. Update **YtDlpManager.cpp** - Limit concurrent operations (4 max)
**Dependencies**: Uses standard library + TBB (already available)
### Phase 3: Circuit Breakers & Fault Isolation (Week 2)
**Goal**: Prevent cascading failures
**Components**:
1. **CircuitBreaker.hpp/cpp** - Generic circuit breaker pattern
2. Update **YtDlpManager.cpp** - Add circuit breaker (5 failures = 60s cooldown)
3. Update **NetworkClient.cpp** - Circuit breaker for HTTP calls
**Dependencies**: Uses standard library only (chrono, atomic)
### Phase 4: Session Management (Week 2-3)
**Goal**: Support 100+ users with proper session handling
**Components**:
1. **SessionManager.hpp/cpp** - Track authenticated sessions (max 150)
2. Update **RpcServer.cpp** - Integrate session management
3. Sessions automatically included in Core's state blob (no Plugin changes!)
**Dependencies**: Uses glaze (already available) + standard library
### Phase 5: Health Monitoring & Self-Healing (Week 3)
**Goal**: Automatic recovery from failures
**Components**:
1. **HealthMonitor.hpp/cpp** - System health checks (every 5s)
2. **Watchdog.hpp/cpp** - Detect hangs (15s timeout)
3. Update **Plugin.cpp** - Integrate health monitoring
**Dependencies**: Uses standard library + Boost.Asio (already available)
### Phase 6: Enhanced yt-dlp Management (Week 3-4)
**Goal**: Reliable auto-updates with fallback
**Components**:
1. Update **YtDlpManager.cpp** - Background updates, atomic swap
2. **UpdateScheduler.hpp/cpp** - Weekly update scheduling (configurable window)
**Dependencies**: Uses standard library only
## Configuration Summary
```json
{
"robustness": {
"stateManagement": {
"format": "glaze_json",
"maxStateSizeMB": 10,
"migration": {
"maxVersionsBackward": 5,
"gracefulDegradation": true
}
},
"rpc": {
"maxConnections": 150,
"workerThreads": 16,
"rateLimitRequestsPerMinute": 30,
"rateLimitBurst": 10,
"connectionTimeoutMs": 30000,
"sessionTimeoutMs": 3600000
},
"resourceLimits": {
"maxQueueSize": 500,
"maxMemoryMB": 1024,
"maxYtDlpConcurrent": 4,
"maxAudioBufferMB": 256,
"enableMemoryPressureHandling": true,
"memoryPressureThresholdMB": 768
},
"circuitBreaker": {
"ytDlpFailureThreshold": 5,
"ytDlpResetTimeoutMs": 60000,
"networkFailureThreshold": 3,
"networkResetTimeoutMs": 30000
},
"healthMonitor": {
"checkIntervalMs": 5000,
"unhealthyThresholdMs": 30000,
"enableAutoRecovery": true,
"maxConsecutiveRecoveries": 3
},
"watchdog": {
"heartbeatIntervalMs": 5000,
"timeoutMs": 15000,
"enableAutoReload": true
},
"ytDlp": {
"autoUpdate": true,
"updateIntervalDays": 7,
"updateTimeWindow": "02:00-04:00",
"enableFallbackMirrors": true,
"requestTimeoutMs": 30000,
"enableRequestDeduplication": true
}
}
}
```
## Dependencies Used
All dependencies are already in your project:
1. **glaze** - JSON serialization for state management
2. **Boost.Asio/Beast** - Connection pool, RPC server
3. **Boost.UUID** - Session IDs
4. **TBB** - Parallel algorithms for resource monitoring
5. **standard library** - Circuit breakers, rate limiters, health monitoring
**No new dependencies required!**
## Benefits of Decoupled State Management
1. **Plugin Stability**: Plugin code never changes when Core state format changes
2. **Rapid Iteration**: Modify Core state structure without rebuilding Plugin
3. **Backward Compatibility**: Old states automatically migrate to new format
4. **Forward Compatibility**: Can detect if state is from future version
5. **Debugging**: State blobs can be saved to disk and inspected manually (JSON)
6. **Testing**: Easy to create test states for specific scenarios
7. **Performance**: Uses glaze (high-performance JSON library you already have)
## Hot-Reload Flow with Decoupled State
```
1. Core V1 running, users connected, music playing
│
▼
2. Developer builds Core V2 (new state format)
│
▼
3. File watcher detects new .ts library
│
▼
4. Plugin asks Core V1: saveState()
Core V1 serializes internal state to blob (format V1)
│
▼
5. Plugin unloads Core V1, loads Core V2
│
▼
6. Plugin asks Core V2: restoreState(blob V1)
Core V2 internally migrates V1 -> V2
Users stay connected, queue preserved
│
▼
7. Core V2 running with migrated state
Zero downtime, zero Plugin changes
```
## Success Metrics
- **Uptime**: >99.9%
- **Concurrent Users**: 100+ without degradation
- **Memory**: Stable <1GB under load
- **Recovery Time**: <5s from failure
- **Hot-Reload**: Zero user impact, zero Plugin rebuilds
- **State Migration**: 100% success rate for versions within 5 releases
## Next Steps
1. **Review this updated plan** - Does the decoupled state approach meet your needs?
2. **State format preferences** - glaze JSON OK, or prefer binary (using std::vector<uint8_t> with custom format)?
3. **Migration depth** - Support 5 versions back, or more/less?
4. **Start implementation** - Begin with Phase 0 (state management foundation)?
The decoupled architecture means you can iterate on Core weekly without ever touching Plugin code again, and we're only using dependencies you already have!
+407 -55
View File
@@ -1,17 +1,27 @@
cmake_minimum_required(VERSION 4.0.0)
project(Echoion VERSION 1.0.0 LANGUAGES CXX)
project(Echoion VERSION 2.0.0 LANGUAGES CXX)
# Default to a Release build when the developer/CI did not pick a config.
include(GNUInstallDirs)
include(cmake/DependencyLock.cmake)
# The root product version is the only manually edited version. Every
# component project consumes this value when orchestrated by Echoion; their
# standalone fallback is intentionally 0.0.0 and is never used for a product
# release.
set(ECHOION_PRODUCT_VERSION "${PROJECT_VERSION}")
set(ECHOION_COMPONENT_VERSION "${PROJECT_VERSION}")
# Default to a RelWithDebInfo build when the developer/CI did not pick a config.
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
# compiled with the same optimisation level as Echoion itself.
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Build type" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
Debug Release RelWithDebInfo MinSizeRel)
message(STATUS "No CMAKE_BUILD_TYPE set; defaulting to Release")
message(STATUS "No CMAKE_BUILD_TYPE set; defaulting to RelWithDebInfo")
endif()
# Use ccache (or sccache) as a compiler launcher when available to speed up
@@ -26,6 +36,75 @@ if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER)
endif()
endif()
# Decide linkage before configuring CPM dependencies. Protocol and VoidLibrary
# must be part of the validated echoiond artifact in production, otherwise a
# release could pair a new daemon with an old/incompatible shared library.
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF)
if(ECHOION_STATIC_LINK)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
message(STATUS "Static GCC runtime linking enabled")
endif()
# Release artifacts should not expose checkout, dependency, or build-machine
# paths through __FILE__, std::source_location, or optional DWARF data. Keep
# developer builds unchanged so local diagnostics can still use absolute paths;
# scripts/release.sh enables this option for production builds.
option(ECHOION_REPRODUCIBLE_BUILD
"Replace local source/build prefixes in compiler-generated paths" OFF)
if(ECHOION_REPRODUCIBLE_BUILD)
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
set(_echoionPrefixMaps
"${CMAKE_SOURCE_DIR}=Echoion"
"${CMAKE_BINARY_DIR}=EchoionBuild")
if(DEFINED CPM_Void_SOURCE AND NOT CPM_Void_SOURCE STREQUAL "")
list(APPEND _echoionPrefixMaps
"${CPM_Void_SOURCE}=VoidLibrary")
endif()
if(DEFINED CPM_VoidTeamspeak_SOURCE AND
NOT CPM_VoidTeamspeak_SOURCE STREQUAL "")
list(APPEND _echoionPrefixMaps
"${CPM_VoidTeamspeak_SOURCE}=VoidTeamspeak")
endif()
if(DEFINED ECHOION_COMPONENT_WORKSPACE AND
NOT ECHOION_COMPONENT_WORKSPACE STREQUAL "")
list(APPEND _echoionPrefixMaps
"${ECHOION_COMPONENT_WORKSPACE}=EchoionComponents")
endif()
foreach(_echoionPrefixMap IN LISTS _echoionPrefixMaps)
list(APPEND _echoionReproducibleCompilerOptions
"$<$<COMPILE_LANGUAGE:C,CXX>:-ffile-prefix-map=${_echoionPrefixMap}>"
"$<$<COMPILE_LANGUAGE:C,CXX>:-fmacro-prefix-map=${_echoionPrefixMap}>"
"$<$<COMPILE_LANGUAGE:C,CXX>:-fdebug-prefix-map=${_echoionPrefixMap}>")
endforeach()
function(echoion_apply_reproducible_build_options directory)
get_property(_echoionDirectoryTargets
DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS)
foreach(_echoionTarget IN LISTS _echoionDirectoryTargets)
get_target_property(_echoionTargetType
"${_echoionTarget}" TYPE)
if(_echoionTargetType MATCHES
"^(EXECUTABLE|STATIC_LIBRARY|SHARED_LIBRARY|MODULE_LIBRARY|OBJECT_LIBRARY)$")
target_compile_options("${_echoionTarget}" PRIVATE
${_echoionReproducibleCompilerOptions})
endif()
endforeach()
get_property(_echoionSubdirectories
DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES)
foreach(_echoionSubdirectory IN LISTS _echoionSubdirectories)
echoion_apply_reproducible_build_options(
"${_echoionSubdirectory}")
endforeach()
endfunction()
message(STATUS "Reproducible compiler path mapping enabled")
else()
message(WARNING
"ECHOION_REPRODUCIBLE_BUILD is not supported by this compiler")
endif()
endif()
# Include CPM
file(
DOWNLOAD
@@ -34,6 +113,7 @@ file(
EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791
)
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)
include(cmake/EchoionComponents.cmake)
# Include PackageProject.cmake
CPMAddPackage(
@@ -50,12 +130,27 @@ CPMAddPackage(
# which CPM honours over the git checkout below.
CPMAddPackage(
NAME Void
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
GIT_TAG main
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
# Keep clean/container releases reproducible. CPM_Void_SOURCE still
# overrides this revision for local dependency development.
GIT_TAG ${ECHOION_VOID_REVISION}
OPTIONS
"VOID_ENABLE_TESTING OFF"
)
# Modern native TeamSpeak client library. Local development can point at the
# adjacent history-preserving extraction with:
# -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak
CPMAddPackage(
NAME VoidTeamspeak
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidteamspeak.git
# This revision supplies the typed administration API used by Standalone.
GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION}
OPTIONS
"VOID_TEAMSPEAK_BUILD_TESTS OFF"
"VOID_ENABLE_TESTING OFF"
)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
@@ -68,6 +163,8 @@ set(CXX_SCAN_FOR_MODULES OFF)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16)
# Guard to C++ only — vendored C dependencies (quickjs) must not see it.
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-freflection>)
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>)
endif()
# Link-time optimisation for Release configs only (keeps Debug builds fast).
@@ -102,87 +199,247 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# Options
option(BUILD_API "Build EchoionApi" ON)
option(BUILD_HOST "Build EchoionHost module loader" ON)
option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_PLUGIN "Build EchoionPlugin" ON)
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON)
option(BUILD_WEB "Build EchoionWeb browser dashboard" ON)
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
option(BUILD_UPDATER "Build EchoionUpdater lifecycle helper" ON)
option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON)
option(BUILD_TESTS "Build tests" OFF)
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)
set(ECHOION_COMPONENT_WORKSPACE
"${CMAKE_CURRENT_SOURCE_DIR}/.."
CACHE PATH "Directory containing permanent Echoion component repositories")
# Static linking configuration
if(ECHOION_STATIC_LINK)
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE)
set(BUILD_SHARED_LIBS OFF)
message(STATUS "Static linking enabled - building standalone distribution")
if(BUILD_TESTS)
enable_testing()
endif()
# Find packages
find_package(Threads REQUIRED)
# Add subdirectories
# All component source directories come from CPM. Local development can set
# CPM_<Component>_SOURCE; normal development follows main; release builds use
# exact components.lock.json revisions.
set(ECHOION_ORCHESTRATOR_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
if(BUILD_API)
add_subdirectory(EchoionApi)
echoion_add_component(EchoionApi)
endif()
if(BUILD_FIRST_PARTY_PLUGINS)
echoion_add_component(EchoionPluginUrlShortenerInternal)
echoion_add_component(EchoionPluginUrlShortenerExternal)
endif()
if(BUILD_HOST OR BUILD_STANDALONE)
echoion_add_component(EchoionHost)
endif()
if(BUILD_CORE)
add_subdirectory(EchoionCore)
echoion_add_component(EchoionCore)
endif()
# EchoionWeb is added after Core so it can reuse the single Boost header
# targets Core discovers. Core owns and starts the web server, so link them
# here (both targets now exist) and flag Core so the wiring compiles in.
if(BUILD_WEB AND BUILD_CORE)
add_subdirectory(EchoionWeb)
echoion_add_component(EchoionWeb)
if(TARGET EchoionCore AND TARGET EchoionWeb)
target_link_libraries(EchoionCore PRIVATE EchoionWeb)
target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
endif()
endif()
if(BUILD_PLUGIN)
add_subdirectory(EchoionPlugin)
# VoidTeamspeak is resolved above as a regular reusable package. The legacy
# TeamSpeak client plugin and in-tree protocol directories are no longer built.
# The updater is a deliberately small, dynamically linked lifecycle helper.
# It validates and journals local operations but leaves network/feed work to
# the daemon through typed request files. Define it before Standalone so the
# Linux release-staging test can use the real helper binary.
if(BUILD_UPDATER AND UNIX AND NOT APPLE)
echoion_add_component(EchoionUpdater)
endif()
# EchoionStandalone links the host-common loader and native protocol client.
if(BUILD_STANDALONE)
echoion_add_component(EchoionStandalone)
endif()
if(BUILD_DESKTOP)
add_subdirectory(EchoionDesktop)
echoion_add_component(EchoionDesktop)
endif()
# Tests
if(BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
# The release install component is deliberately runtime-only. Nested projects
# keep their normal SDK/development install rules, while scripts/release.sh uses
# this component as the single input to dependency collection and packaging.
option(ECHOION_INSTALL_RUNTIME_BUNDLE
"Provide the relocatable Echoion Runtime install component" ON)
if(ECHOION_INSTALL_RUNTIME_BUNDLE)
if(TARGET EchoionStandalone)
if(UNIX AND NOT APPLE)
set_target_properties(EchoionStandalone PROPERTIES
INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}"
INSTALL_RPATH_USE_LINK_PATH FALSE)
endif()
install(TARGETS EchoionStandalone
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
COMPONENT Runtime)
endif()
if(TARGET EchoionCore)
if(UNIX AND NOT APPLE)
set_target_properties(EchoionCore PROPERTIES
INSTALL_RPATH "$ORIGIN"
INSTALL_RPATH_USE_LINK_PATH FALSE)
endif()
install(TARGETS EchoionCore
RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
COMPONENT Runtime)
endif()
if(TARGET EchoionWeb)
install(DIRECTORY "${EchoionWeb_SOURCE_DIR}/frontend/web-dist/"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web"
COMPONENT Runtime)
endif()
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
COMPONENT Runtime)
install(FILES
"${CMAKE_CURRENT_SOURCE_DIR}/components.json"
"${CMAKE_CURRENT_SOURCE_DIR}/components.lock.json"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion"
COMPONENT Runtime)
install(FILES
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in"
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.service.in"
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.timer.in"
DESTINATION service
COMPONENT Runtime)
install(PROGRAMS
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate-release-manifest.py"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/tools"
COMPONENT Runtime)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses"
RENAME Echoion-LICENSE
COMPONENT Runtime)
endif()
endif()
# Packaging configuration
include(CPack)
set(CPACK_PACKAGE_NAME "Echoion")
set(CPACK_PACKAGE_VENDOR "Echoion")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
# Independent component package staging. Each named install component contains
# only that component's first-party payload; release tooling adds its private
# runtime dependency closure and a signed-feed manifest afterwards.
option(ECHOION_INSTALL_COMPONENT_PACKAGES
"Provide one install component for every independently released component"
ON)
if(ECHOION_INSTALL_COMPONENT_PACKAGES)
if(TARGET EchoionApiPluginSdk)
install(TARGETS EchoionApiPluginSdk
ARCHIVE DESTINATION lib
COMPONENT PackageEchoionApi)
install(DIRECTORY "${EchoionApi_SOURCE_DIR}/include/"
DESTINATION include
COMPONENT PackageEchoionApi)
install(FILES
"${EchoionApi_SOURCE_DIR}/abi/echoion-module-v1.json"
DESTINATION abi
COMPONENT PackageEchoionApi)
endif()
# Platform-specific packaging
if(WIN32)
set(CPACK_GENERATOR "ZIP;NSIS")
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion")
set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion")
elseif(APPLE)
set(CPACK_GENERATOR "DragNDMGZ")
set(CPACK_DMG_VOLUME_NAME "Echoion")
else()
set(CPACK_GENERATOR "TGZ;DEB;RPM")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0")
set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite")
if(TARGET EchoionHost)
install(TARGETS EchoionHost
LIBRARY DESTINATION lib
COMPONENT PackageEchoionHost
RUNTIME DESTINATION bin
COMPONENT PackageEchoionHost)
install(FILES "${EchoionHost_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionHost)
endif()
if(TARGET EchoionCore)
install(TARGETS EchoionCore
LIBRARY DESTINATION lib
COMPONENT PackageEchoionCore
RUNTIME DESTINATION bin
COMPONENT PackageEchoionCore)
install(FILES "${EchoionCore_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionCore)
endif()
if(TARGET EchoionWeb)
install(TARGETS EchoionWeb
LIBRARY DESTINATION lib
COMPONENT PackageEchoionWeb
RUNTIME DESTINATION bin
COMPONENT PackageEchoionWeb)
install(FILES "${EchoionWeb_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionWeb)
install(DIRECTORY "${EchoionWeb_SOURCE_DIR}/frontend/web-dist/"
DESTINATION share/echoion/web
COMPONENT PackageEchoionWeb)
endif()
if(TARGET EchoionStandalone)
install(TARGETS EchoionStandalone
RUNTIME DESTINATION bin
COMPONENT PackageEchoionStandalone)
endif()
if(TARGET EchoionUpdater)
install(TARGETS EchoionUpdater
RUNTIME DESTINATION bin
COMPONENT PackageEchoionUpdater)
endif()
if(TARGET EchoionDesktop)
install(TARGETS EchoionDesktop
RUNTIME DESTINATION bin
COMPONENT PackageEchoionDesktop
BUNDLE DESTINATION bin
COMPONENT PackageEchoionDesktop)
if(TARGET Qt6::QXcbIntegrationPlugin)
install(IMPORTED_RUNTIME_ARTIFACTS Qt6::QXcbIntegrationPlugin
LIBRARY DESTINATION plugins/platforms
COMPONENT PackageEchoionDesktop)
endif()
endif()
if(TARGET EchoionUrlShortenerInternalPlugin)
install(TARGETS EchoionUrlShortenerInternalPlugin
LIBRARY DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerInternal
RUNTIME DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerInternal)
install(FILES
"${EchoionPluginUrlShortenerInternal_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionPluginUrlShortenerInternal)
endif()
if(TARGET EchoionUrlShortenerExternalPlugin)
install(TARGETS EchoionUrlShortenerExternalPlugin
LIBRARY DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerExternal
RUNTIME DESTINATION lib
COMPONENT PackageEchoionPluginUrlShortenerExternal)
install(FILES
"${EchoionPluginUrlShortenerExternal_SOURCE_DIR}/abi/module.json"
DESTINATION abi
COMPONENT PackageEchoionPluginUrlShortenerExternal)
endif()
endif()
# Bundling and deployment helpers
include(GNUInstallDirs)
# Function to bundle Qt dependencies
function(bundle_qt_dependencies target)
if(NOT TARGET ${target})
@@ -256,24 +513,119 @@ if(BUILD_CORE AND TARGET EchoionCore)
install_with_dependencies(EchoionCore)
endif()
if(BUILD_PLUGIN AND TARGET EchoionPlugin)
install_with_dependencies(EchoionPlugin)
if(BUILD_TESTS AND UNIX)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
add_test(NAME echoion_prepare_release_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_prepare_release.py")
add_test(NAME echoion_component_package_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_package_components.py")
add_test(NAME echoion_component_feed_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_publish_component_feeds.py")
add_test(NAME echoion_independent_component_release_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_independent_component_release.py")
add_test(NAME echoion_prepare_component_release_tests
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_prepare_component_release.py")
if(NOT COMMAND void_add_tests AND DEFINED Void_SOURCE_DIR)
include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake")
endif()
if(COMMAND void_add_tests AND
TARGET EchoionHost AND TARGET EchoionCore AND TARGET EchoionWeb AND
TARGET EchoionUrlShortenerInternalPlugin AND
TARGET EchoionUrlShortenerExternalPlugin)
add_executable(EchoionModuleTests tests/ModuleDescriptors.cpp)
target_compile_features(EchoionModuleTests PRIVATE cxx_std_26)
target_link_libraries(EchoionModuleTests PRIVATE
Echoion::ApiModuleAbi
Void::Testing
${CMAKE_DL_LIBS})
target_compile_definitions(EchoionModuleTests PRIVATE
"ECHOION_TEST_HOST=\"$<TARGET_FILE:EchoionHost>\""
"ECHOION_TEST_CORE=\"$<TARGET_FILE:EchoionCore>\""
"ECHOION_TEST_WEB=\"$<TARGET_FILE:EchoionWeb>\""
"ECHOION_TEST_PLUGIN_INTERNAL=\"$<TARGET_FILE:EchoionUrlShortenerInternalPlugin>\""
"ECHOION_TEST_PLUGIN_EXTERNAL=\"$<TARGET_FILE:EchoionUrlShortenerExternalPlugin>\"")
void_add_tests(EchoionModuleTests)
add_test(NAME echoion_module_descriptor_tests
COMMAND EchoionModuleTests)
endif()
add_test(NAME echoion_release_manifest_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh"
"${CMAKE_CURRENT_SOURCE_DIR}"
"${ECHOION_COMPONENT_WORKSPACE}")
add_test(NAME echoion_runtime_dependency_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_release_archive_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_frontend_license_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh"
"${CMAKE_CURRENT_SOURCE_DIR}")
add_test(NAME echoion_installer_packaging_tests
COMMAND bash
"${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh")
endif()
# The universal .tar.zst/.run workflow is the supported Linux distribution
# format. Keep legacy CPack available for local Windows/macOS experiments,
# without publishing inaccurate DEB/RPM host-dependency metadata.
option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF)
if(ECHOION_ENABLE_LEGACY_CPACK)
set(CPACK_PACKAGE_NAME "Echoion")
set(CPACK_PACKAGE_VENDOR "Echoion")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
if(WIN32)
set(CPACK_GENERATOR "ZIP;NSIS")
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
elseif(APPLE)
set(CPACK_GENERATOR "DragNDrop")
set(CPACK_DMG_VOLUME_NAME "Echoion")
else()
set(CPACK_GENERATOR "TGZ")
endif()
include(CPack)
endif()
if(ECHOION_REPRODUCIBLE_BUILD AND
COMMAND echoion_apply_reproducible_build_options)
echoion_apply_reproducible_build_options("${CMAKE_CURRENT_SOURCE_DIR}")
endif()
# Print configuration summary
message(STATUS "")
message(STATUS "Echoion Configuration:")
message(STATUS " Version: ${PROJECT_VERSION}")
if(DEFINED ECHOION_RUNTIME_VERSION)
message(STATUS " Runtime release version: ${ECHOION_RUNTIME_VERSION}")
endif()
message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS " Build API: ${BUILD_API}")
message(STATUS " Build Host: ${BUILD_HOST}")
message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}")
message(STATUS " Build Core: ${BUILD_CORE}")
message(STATUS " Build Plugin: ${BUILD_PLUGIN}")
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
message(STATUS " Build Web: ${BUILD_WEB}")
message(STATUS " Build Standalone: ${BUILD_STANDALONE}")
message(STATUS " Build Updater: ${BUILD_UPDATER}")
message(STATUS " Build Tests: ${BUILD_TESTS}")
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
message(STATUS "")
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
message(STATUS "To build: cmake --build build")
message(STATUS "To install: cmake --install build --prefix <install_dir>")
message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)")
message(STATUS "To release: scripts/release.sh --version <version>")
message(STATUS "")
+54
View File
@@ -0,0 +1,54 @@
{
"version": 9,
"cmakeMinimumRequired": {
"major": 4,
"minor": 0,
"patch": 0
},
"configurePresets": [
{
"name": "linux-release",
"displayName": "Linux dynamic runtime release",
"description": "Bot, Core, web dashboard, tests, and a runtime-only install component",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build-relwithdebinfo",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "RelWithDebInfo",
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build-relwithdebinfo/stage",
"BUILD_SHARED_LIBS": "ON",
"ECHOION_STATIC_LINK": "OFF",
"ECHOION_INSTALL_RUNTIME_BUNDLE": "ON",
"ECHOION_ENABLE_LEGACY_CPACK": "OFF",
"ECHOION_ENABLE_LTO": "ON",
"BUILD_API": "ON",
"BUILD_CORE": "ON",
"BUILD_WEB": "ON",
"ECHOION_BUILD_WEB": "ON",
"BUILD_STANDALONE": "ON",
"BUILD_FIRST_PARTY_PLUGINS": "ON",
"BUILD_DESKTOP": "ON",
"BUILD_TESTS": "ON"
}
}
],
"buildPresets": [
{
"name": "linux-release",
"configurePreset": "linux-release",
"configuration": "RelWithDebInfo"
}
],
"testPresets": [
{
"name": "linux-release",
"configurePreset": "linux-release",
"configuration": "RelWithDebInfo",
"output": {
"outputOnFailure": true
},
"execution": {
"noTestsAction": "error"
}
}
]
}
Submodule EchoionApi deleted from e7573fbcd0.
Submodule EchoionCore deleted from 5c036d91fb.
Submodule EchoionDesktop deleted from 2aa44fae9e.
Submodule EchoionPlugin deleted from 470ab507e1.
-115
View File
@@ -1,115 +0,0 @@
cmake_minimum_required(VERSION 4.0.0)
project(EchoionWeb VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp")
add_library(EchoionWeb STATIC ${WEB_SOURCES})
add_library(Echoion::Web ALIAS EchoionWeb)
target_include_directories(EchoionWeb PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
# EchoionCore is configured before this module and creates the header-only
# Boost:: targets from the single system Boost. Fall back to discovering them
# only if this module is ever built without Core.
if(NOT TARGET Boost::beast)
find_package(Boost 1.87 CONFIG QUIET)
foreach(_hdr asio beast system)
if(NOT TARGET Boost::${_hdr})
add_library(_web_boost_${_hdr}_hdr INTERFACE)
add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
"${Boost_INCLUDE_DIRS}")
endif()
endforeach()
endif()
find_package(Threads REQUIRED)
target_link_libraries(EchoionWeb
PUBLIC
Echoion::ApiConfig
Void::Data
Void::Log
Void::Async
Void::Net
PRIVATE
Threads::Threads
Boost::beast
Boost::asio
Boost::system
)
if(MSVC)
target_compile_options(EchoionWeb PRIVATE /W4 /WX-)
else()
target_compile_options(EchoionWeb PRIVATE -Wall -Wextra -Wpedantic)
endif()
# ── Browser frontend (Vite + React + TypeScript) ─────────────────────────────
# The UI lives in frontend/ and is built with npm/vite into frontend/web-dist.
# That build output is what ships next to the runtime binary (default webRoot
# "./web", relative to the working directory) and is installed. Opt out with
# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job).
option(ECHOION_BUILD_WEB "Build the React web frontend with npm/vite" ON)
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
set(_web_dist "${_web_frontend}/web-dist")
if(ECHOION_BUILD_WEB)
find_program(NPM_EXECUTABLE NAMES npm npm.cmd)
if(NOT NPM_EXECUTABLE)
message(FATAL_ERROR
"npm was not found but ECHOION_BUILD_WEB is ON. Install Node.js/npm, "
"or configure with -DECHOION_BUILD_WEB=OFF to skip the web frontend.")
endif()
# Rebuild web-dist whenever any source/config under frontend/ (excluding
# node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at
# build time so new files are picked up without re-running CMake.
file(GLOB_RECURSE _web_srcs CONFIGURE_DEPENDS
"${_web_frontend}/src/*"
"${_web_frontend}/public/*"
"${_web_frontend}/index.html"
"${_web_frontend}/package.json"
"${_web_frontend}/package-lock.json"
"${_web_frontend}/tsconfig.json"
"${_web_frontend}/vite.config.ts")
add_custom_command(
OUTPUT "${_web_dist}/index.html"
# `npm ci` when the lockfile is newer than node_modules keeps installs
# reproducible; the stamp check avoids reinstalling on every build.
COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund
COMMAND ${NPM_EXECUTABLE} run build
WORKING_DIRECTORY "${_web_frontend}"
DEPENDS ${_web_srcs}
COMMENT "Building Echoion web frontend (vite)"
VERBATIM)
add_custom_target(EchoionWebFrontend ALL
DEPENDS "${_web_dist}/index.html")
add_dependencies(EchoionWeb EchoionWebFrontend)
set(_web_assets "${_web_dist}")
else()
# Frontend build skipped: ship whatever is already in web-dist (a prior
# build or a committed snapshot). Falls back to nothing if absent.
set(_web_assets "${_web_dist}")
endif()
# Ship the built browser assets next to the runtime binary. Remove the target
# first so stale files (e.g. an earlier vanilla-JS build) never linger.
add_custom_command(TARGET EchoionWeb POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rm -rf "${CMAKE_BINARY_DIR}/bin/web"
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${_web_assets}"
"${CMAKE_BINARY_DIR}/bin/web"
COMMENT "Copying EchoionWeb static assets to bin/web"
)
install(DIRECTORY "${_web_dist}/" DESTINATION share/echoion/web)
-3
View File
@@ -1,3 +0,0 @@
node_modules/
web-dist/
*.tsbuildinfo
-19
View File
@@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Echoion — Music Bot</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="manifest" href="/manifest.webmanifest">
<meta name="theme-color" content="#151522">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Echoion">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="stylesheet" href="/fonts.css">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
-26
View File
@@ -1,26 +0,0 @@
{
"name": "echoion-web",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"test": "vitest run",
"i18n:check": "node scripts/i18n-check.mjs"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@types/youtube": "^0.1.2",
"@vitejs/plugin-react": "^4.5.0",
"typescript": "^5.8.0",
"vite": "^6.3.0",
"vitest": "^3.1.0"
}
}
-6
View File
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<rect width="24" height="24" rx="5" fill="#151522"/>
<rect x="4" y="9" width="3.4" height="10" rx="1.6" fill="#a970ff"/>
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" fill="#ff8080"/>
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" fill="#ffd977"/>
</svg>

Before

Width:  |  Height:  |  Size: 335 B

-480
View File
@@ -1,480 +0,0 @@
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Full-bleed background for the maskable safe area; bars inset ~20%. -->
<rect width="512" height="512" fill="#151522"/>
<rect x="150" y="232" width="52" height="150" rx="24" fill="#a970ff"/>
<rect x="238" y="160" width="52" height="222" rx="24" fill="#ff8080"/>
<rect x="326" y="278" width="52" height="104" rx="24" fill="#ffd977"/>
</svg>

Before

Width:  |  Height:  |  Size: 412 B

-6
View File
@@ -1,6 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" fill="#151522"/>
<rect x="96" y="200" width="72" height="212" rx="34" fill="#a970ff"/>
<rect x="220" y="100" width="72" height="312" rx="34" fill="#ff8080"/>
<rect x="344" y="264" width="72" height="148" rx="34" fill="#ffd977"/>
</svg>

Before

Width:  |  Height:  |  Size: 343 B

@@ -1,25 +0,0 @@
{
"name": "Echoion Music Bot",
"short_name": "Echoion",
"description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "any",
"background_color": "#0d0d1f",
"theme_color": "#151522",
"icons": [
{
"src": "/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "/icon-maskable.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "maskable"
}
]
}
-83
View File
@@ -1,83 +0,0 @@
// Minimal, dependency-free service worker: makes the panel installable and
// keeps the app shell available offline. It deliberately does NOT touch the
// live surfaces — /rpc and /ws (WebSockets aren't interceptable anyway),
// /config.json, /avatar/*, /emoji/* all fall through to the network so the UI
// never shows stale identity/config.
// Bump when the player shell changes materially so installed/PWA clients do
// not retain an index that references a removed hashed bundle.
const CACHE = 'echoion-shell-v2';
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
)
.then(() => self.clients.claim())
);
});
// Only same-origin GETs are cacheable; everything else passes through.
function isStaticAsset(url) {
return (
url.pathname.startsWith('/assets/') ||
url.pathname === '/manifest.webmanifest' ||
url.pathname.startsWith('/icon') ||
url.pathname.startsWith('/fonts') ||
url.pathname.endsWith('.css') ||
url.pathname.endsWith('.woff2') ||
url.pathname.endsWith('.svg')
);
}
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
// Never intercept the live control/config/media surfaces.
if (
url.pathname === '/config.json' ||
url.pathname.startsWith('/rpc') ||
url.pathname.startsWith('/ws') ||
url.pathname.startsWith('/avatar') ||
url.pathname.startsWith('/emoji')
) {
return;
}
// SPA navigations: network-first, fall back to the cached shell offline.
if (req.mode === 'navigate') {
event.respondWith(
fetch(req).catch(() => caches.match('/').then((r) => r || fetch(req)))
);
return;
}
// Hashed static assets: cache-first, populate on first hit.
if (isStaticAsset(url)) {
event.respondWith(
caches.match(req).then(
(hit) =>
hit ||
fetch(req).then((resp) => {
if (resp.ok) {
const copy = resp.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
}
return resp;
})
)
);
}
});
-117
View File
@@ -1,117 +0,0 @@
#!/usr/bin/env node
// Diffs the Russian catalog (src/i18n/ru.ts) against every t('…') / tf('…')
// literal in src/**/*.ts{,x}, both ways:
// - missing: used in code but absent from ru.ts (falls back to English)
// - orphaned: present in ru.ts but never used as a literal key
//
// Dynamic keys can't be found by this scan and must be checked by hand:
// - watch.ts state strings rendered via t(w.playerEmpty)
// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label)
// - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub)
// - server-sent watch.denied reasons (grep sendDenied in
// EchoionWeb/src/WatchSession.cpp) rendered via t(msg.reason)
// Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC
// list below suppresses the ones we know about.
//
// Usage: npm run i18n:check (exits 1 when keys are missing)
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const srcDir = join(root, 'src');
const ruFile = join(srcDir, 'i18n', 'ru.ts');
// Keys reached through variables (see header); keep in sync by hand.
const KNOWN_DYNAMIC = new Set([
// watch.ts playerEmpty / state strings
'Nothing loaded — paste a URL above',
'Twitch embeds require HTTPS — open the site via its https:// domain',
// server-sent watch.denied reasons (grep sendDenied in WatchSession.cpp)
'Sign in to control playback',
'Only the host controls playback',
'Watch queue is full',
'Watch queue is empty',
'Live stream — cannot seek',
'That viewer is no longer here',
'Only signed-in viewers can host',
// connection state rendered via t(s.connection) in Sidebar.tsx
'connected',
'disconnected',
'error',
// SHORTCUTS labels (lib/shortcuts.ts)
'Play / pause',
'Seek 5s',
'Volume',
'Skip / vote skip',
'Focus search',
'This help',
// HEADS view titles/subtitles (App.tsx)
'Now Playing',
'What Echoion is streaming to the channel',
'Queue',
'Reorder and manage upcoming tracks',
'Search',
'Find tracks across YouTube and Yandex Music',
'Library',
'Your favorites and saved playlists',
'History & Stats',
'Playback history and server insights',
'Watch Together',
'Synced viewing room — everyone in step',
'Server & Admin',
'Manage subscribers and broadcast',
'RPC / API',
'Connect to Echoion programmatically',
// Sidebar NAV labels rendered via t(item.label) — same strings as HEADS
// titles, listed above.
]);
const unescape = (s) => s.replace(/\\(.)/g, '$1');
function walk(dir, out = []) {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) walk(p, out);
else if (/\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name)) {
out.push(p);
}
}
return out;
}
// Catalog keys: top-level `'key': '…'` entries of the ru object literal.
const ruKeys = new Set();
for (const m of readFileSync(ruFile, 'utf8').matchAll(
/^\s*'((?:[^'\\]|\\.)*)':/gm
)) {
ruKeys.add(unescape(m[1]));
}
// Used keys: every t('…') / tf('…', …) string literal.
const used = new Set();
for (const file of walk(srcDir)) {
if (file === ruFile) continue;
const text = readFileSync(file, 'utf8');
for (const m of text.matchAll(/\btf?\(\s*'((?:[^'\\]|\\.)*)'/g)) {
used.add(unescape(m[1]));
}
}
const missing = [...used].filter((k) => !ruKeys.has(k)).sort();
const orphaned = [...ruKeys]
.filter((k) => !used.has(k) && !KNOWN_DYNAMIC.has(k))
.sort();
if (missing.length) {
console.log(`Missing from ru.ts (${missing.length}):`);
for (const k of missing) console.log(`\t'${k.replace(/'/g, "\\'")}':`);
}
if (orphaned.length) {
console.log(`\nIn ru.ts but never used as a literal (${orphaned.length}):`);
for (const k of orphaned) console.log(`\t'${k.replace(/'/g, "\\'")}'`);
console.log('(may be dynamic keys — verify before deleting)');
}
if (!missing.length && !orphaned.length) console.log('i18n: OK');
process.exit(missing.length ? 1 : 0);
-121
View File
@@ -1,121 +0,0 @@
import { useEffect } from 'react';
import { appStore, boot, getStoredToken, toast } from './lib/app';
import { initWatch } from './lib/watch';
import { initRouter } from './lib/router';
import { initShortcuts } from './lib/shortcuts';
import { initMediaSession } from './lib/mediaSession';
import { useStore } from './lib/store';
import { useLanguage, t } from './i18n';
import { HelpIcon, MenuIcon } from './components/icons';
import { Sidebar } from './components/Sidebar';
import { MiniPlayer } from './components/MiniPlayer';
import { DialogHost } from './components/DialogHost';
import { ShortcutsHelp } from './components/ShortcutsHelp';
import { NowView } from './views/NowView';
import { QueueView } from './views/QueueView';
import { SearchView } from './views/SearchView';
import { LibraryView } from './views/LibraryView';
import { StatsView } from './views/StatsView';
import { WatchView } from './views/WatchView';
import { ServerView } from './views/ServerView';
import { RpcView } from './views/RpcView';
const HEADS: Record<string, [string, string]> = {
now: ['Now Playing', 'What Echoion is streaming to the channel'],
queue: ['Queue', 'Reorder and manage upcoming tracks'],
search: ['Search', 'Find tracks across YouTube and Yandex Music'],
library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'],
watch: ['Watch Together', 'Synced viewing room — everyone in step'],
server: ['Server & Admin', 'Manage subscribers and broadcast'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
};
export function App() {
const s = useStore(appStore);
useLanguage(); // re-render everything on language switch
useEffect(() => {
boot();
initWatch({
getName: () =>
(appStore.get().identity &&
appStore.get().identity!.nickname) ||
null,
getToken: getStoredToken,
toast,
});
initRouter();
initShortcuts();
initMediaSession();
}, []);
const [title, sub] = HEADS[s.view] || HEADS.now;
return (
<div id="app">
<Sidebar />
{s.sidebarOpen && (
<div
className="drawer-backdrop"
onClick={() => appStore.set({ sidebarOpen: false })}
/>
)}
<main className="main">
<header className="header">
<div className="header-title">
<button
className="icon-btn hamburger"
title={t('Menu')}
aria-label={t('Menu')}
onClick={() =>
appStore.set({ sidebarOpen: !s.sidebarOpen })
}
>
<MenuIcon />
</button>
<div>
<h1>{t(title)}</h1>
<div className="header-sub">{t(sub)}</div>
</div>
</div>
<div className="header-right">
<span className="pill">
<span className="dot dot-green" />
{s.onlineCount}&nbsp;{t('listening')}
</span>
<button
className="icon-btn"
title={t('Keyboard shortcuts')}
aria-label={t('Keyboard shortcuts')}
onClick={() =>
appStore.set({ shortcutsOpen: true })
}
>
<HelpIcon />
</button>
</div>
</header>
{s.view === 'now' && <NowView />}
{s.view === 'queue' && <QueueView />}
{s.view === 'search' && <SearchView />}
{s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />}
{/* The watch view stays mounted so the embedded player and
room connection survive view switches (the old UI only
toggled `hidden`). */}
<div hidden={s.view !== 'watch'}>
<WatchView />
</div>
{s.view === 'server' && <ServerView />}
{s.view === 'rpc' && <RpcView />}
<MiniPlayer />
</main>
{s.toast && <div className="toast">{s.toast}</div>}
<DialogHost />
<ShortcutsHelp />
</div>
);
}
@@ -1,114 +0,0 @@
import { useState } from 'react';
import { safeCall, toast } from '../lib/app';
import { renderTsMarkup } from '../lib/tsMarkup';
import { Modal } from './Modal';
import { t } from '../i18n';
// Announce composer with a live TS6-markdown/BBCode preview (item 14).
// Replaces the old prompt(). A small toolbar wraps the selection in common
// formatting tags; the preview renders exactly what subscribers will see.
const TOOLBAR: Array<{ label: string; before: string; after: string }> = [
{ label: 'B', before: '**', after: '**' },
{ label: 'I', before: '*', after: '*' },
{ label: 'U', before: '[u]', after: '[/u]' },
{ label: 'S', before: '~~', after: '~~' },
{ label: '</>', before: '`', after: '`' },
{ label: '🔗', before: '[', after: '](https://)' },
{ label: 'H', before: '# ', after: '' },
{ label: '❝', before: '> ', after: '' },
];
export function AnnounceModal({ onClose }: { onClose: () => void }) {
const [text, setText] = useState('');
const [sending, setSending] = useState(false);
let ref: HTMLTextAreaElement | null = null;
const wrap = (before: string, after: string) => {
const el = ref;
if (!el) return;
const start = el.selectionStart;
const end = el.selectionEnd;
const selected = text.slice(start, end);
const next =
text.slice(0, start) + before + selected + after + text.slice(end);
setText(next);
// Restore focus with the caret after the inserted opening tag.
queueMicrotask(() => {
el.focus();
const pos = start + before.length + selected.length;
el.setSelectionRange(pos, pos);
});
};
return (
<Modal
title={t('Compose announcement')}
onClose={onClose}
wide
footer={
<>
<button className="btn btn-ghost" onClick={onClose}>
{t('Cancel')}
</button>
<button
className="btn btn-accent"
disabled={!text.trim() || sending}
onClick={async () => {
setSending(true);
const res = await safeCall<{ message?: string }>(
'Announce',
{ text: text.trim() }
);
setSending(false);
if (res) {
toast(res.message || t('Announcement sent'));
onClose();
}
}}
>
{t('Send announcement')}
</button>
</>
}
>
<div className="announce-toolbar">
{TOOLBAR.map((b) => (
<button
key={b.label}
className="btn btn-ghost"
type="button"
onClick={() => wrap(b.before, b.after)}
>
{b.label}
</button>
))}
</div>
<div className="announce-grid">
<textarea
ref={(el) => {
ref = el;
}}
className="announce-input"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t('Announcement to all subscribers:')}
rows={10}
/>
<div className="announce-preview">
<div className="announce-preview-label">
{t('Preview')}
</div>
<div className="ts-markup">
{text.trim() ? (
renderTsMarkup(text)
) : (
<span className="muted">
{t('Nothing to preview yet')}
</span>
)}
</div>
</div>
</div>
</Modal>
);
}
@@ -1,72 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { avatarColor } from '../lib/format';
// User avatar: tries the TeamSpeak avatar served at /avatar/<uid>, falling
// back to the initial-letter-on-gradient avatar when the image is missing.
// `uid` is the stable TeamSpeak unique id.
//
// The server fetches avatars from TeamSpeak lazily (it must first sync the
// client's avatar hash, then download the file), so the first few requests can
// 404 while that completes. We retry a handful of times with a growing delay,
// bypassing the browser's negative cache with a ?v=N buster, before giving up
// and showing initials.
const RETRY_DELAYS_MS = [2500, 4000, 6000, 9000];
export function Avatar(props: {
name: string;
uid?: string | null;
size?: number;
className?: string;
}) {
const { name, uid, size, className } = props;
const [attempt, setAttempt] = useState(0);
const [failed, setFailed] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Reset retry state whenever the target uid changes.
useEffect(() => {
setAttempt(0);
setFailed(false);
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, [uid]);
const style: React.CSSProperties = size
? { width: `${size}px`, height: `${size}px` }
: {};
if (uid && !failed) {
const src =
`/avatar/${encodeURIComponent(uid)}` +
(attempt > 0 ? `?v=${attempt}` : '');
return (
<img
className={'avatar avatar-img' + (className ? ` ${className}` : '')}
style={style}
src={src}
alt={name}
onError={() => {
if (attempt < RETRY_DELAYS_MS.length) {
const delay = RETRY_DELAYS_MS[attempt];
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(
() => setAttempt((a) => a + 1),
delay
);
} else {
setFailed(true);
}
}}
/>
);
}
return (
<span
className={'avatar' + (className ? ` ${className}` : '')}
style={{ ...style, background: avatarColor(name || '?') }}
>
{(name || '?').charAt(0).toUpperCase()}
</span>
);
}
@@ -1,82 +0,0 @@
import { useRef, useState } from 'react';
// Pointer-drag on a bar: the fill tracks the pointer while dragging and
// onCommit fires once on release (a plain click is a zero-length drag).
// Port of app.js makeDraggableBar.
//
// When `formatValue` is given, a tooltip bubble follows the pointer on hover
// and drag showing the value at that position (item 14) — e.g. a seek time or
// a volume percentage.
export function Bar(props: {
pct: number; // 0..100, authoritative fill when not dragging
bufferPct?: number; // 0..100, second fill layer behind the progress
slim?: boolean;
className?: string;
onCommit?: (fraction: number) => void;
onDragStart?: () => boolean; // return false to refuse the drag
live?: boolean; // live drag feedback: onCommit also fires on move
formatValue?: (fraction: number) => string; // tooltip text at a fraction
}) {
const el = useRef<HTMLDivElement>(null);
const [dragPct, setDragPct] = useState<number | null>(null);
// Pointer position (0..100) for the tooltip; null when the pointer is away.
const [hoverPct, setHoverPct] = useState<number | null>(null);
const fraction = (e: React.PointerEvent) => {
const r = el.current!.getBoundingClientRect();
return Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
};
const tipPct = dragPct ?? hoverPct;
const showTip = props.formatValue && tipPct != null;
return (
<div
ref={el}
className={
'bar' +
(props.slim ? ' bar-slim' : '') +
(props.className ? ` ${props.className}` : '')
}
onPointerDown={(e) => {
if (props.onDragStart && !props.onDragStart()) return;
e.currentTarget.setPointerCapture(e.pointerId);
const f = fraction(e);
setDragPct(f * 100);
if (props.live) props.onCommit?.(f);
}}
onPointerMove={(e) => {
const f = fraction(e);
setHoverPct(f * 100);
if (dragPct == null) return;
setDragPct(f * 100);
if (props.live) props.onCommit?.(f);
}}
onPointerLeave={() => setHoverPct(null)}
onPointerUp={(e) => {
if (dragPct == null) return;
setDragPct(null);
if (!props.live) props.onCommit?.(fraction(e));
}}
>
{props.bufferPct != null && (
<div
className="bar-buffer"
style={{ width: `${Math.min(100, props.bufferPct)}%` }}
/>
)}
<div
className="bar-fill"
style={{ width: `${dragPct ?? props.pct}%` }}
/>
{showTip && (
<div
className="bar-tip"
style={{ left: `${tipPct}%` }}
>
{props.formatValue!((tipPct as number) / 100)}
</div>
)}
</div>
);
}
@@ -1,94 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { Modal } from './Modal';
import { useStore } from '../lib/store';
import { dialogStore, resolveConfirm, resolvePrompt } from '../lib/dialog';
import { t } from '../i18n';
// Renders the active custom dialog (confirm/prompt). Mounted once at the app
// root; see lib/dialog.ts for the confirmDialog/promptDialog helpers.
export function DialogHost() {
const { current } = useStore(dialogStore);
const [text, setText] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
// Seed the prompt field with its initial value and focus it each time a
// new prompt opens.
useEffect(() => {
if (current && current.kind === 'prompt') {
setText(current.initial || '');
// Focus after the modal mounts.
setTimeout(() => inputRef.current?.focus(), 0);
}
}, [current]);
if (!current) return null;
if (current.kind === 'confirm') {
return (
<Modal
title={current.title}
onClose={() => resolveConfirm(false)}
footer={
<>
<button
className="btn btn-ghost"
onClick={() => resolveConfirm(false)}
>
{current.cancelLabel || t('Cancel')}
</button>
<button
className={
'btn ' +
(current.danger ? 'btn-danger' : 'btn-accent')
}
onClick={() => resolveConfirm(true)}
>
{current.confirmLabel || t('Confirm')}
</button>
</>
}
>
<p>{current.message}</p>
</Modal>
);
}
return (
<Modal
title={current.title}
onClose={() => resolvePrompt(null)}
footer={
<>
<button
className="btn btn-ghost"
onClick={() => resolvePrompt(null)}
>
{current.cancelLabel || t('Cancel')}
</button>
<button
className="btn btn-accent"
onClick={() => resolvePrompt(text.trim() || null)}
>
{current.confirmLabel || t('OK')}
</button>
</>
}
>
<form
onSubmit={(e) => {
e.preventDefault();
resolvePrompt(text.trim() || null);
}}
>
{current.message && <p>{current.message}</p>}
<input
ref={inputRef}
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={current.placeholder}
autoComplete="off"
/>
</form>
</Modal>
);
}
@@ -1,112 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { useStore } from '../lib/store';
import { emojiStore, loadCustomEmojis } from '../lib/emoji';
import { safeCall, toast } from '../lib/app';
import { CloseIcon } from './icons';
import { t } from '../i18n';
// Admin custom-emoji manager (item 16): upload an image (≤64KB) under a
// shortcode name, list existing ones, and remove them. The image is sent as
// base64 to AddCustomEmoji and served back at /emoji/<name>.
export function EmojiManager() {
const { custom } = useStore(emojiStore);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
loadCustomEmojis();
}, []);
const upload = async () => {
const file = fileRef.current?.files?.[0];
const clean = name.trim().toLowerCase();
if (!/^[a-z0-9_]{1,32}$/.test(clean)) {
toast(t('Emoji name must be 1-32 chars of a-z, 0-9, _'));
return;
}
if (!file) {
toast(t('Choose an image file'));
return;
}
if (file.size > 64 * 1024) {
toast(t('Emoji image too large (max ~64KB)'));
return;
}
setBusy(true);
const dataBase64 = await new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onload = () => {
const res = String(reader.result);
resolve(res.slice(res.indexOf(',') + 1)); // strip data: prefix
};
reader.readAsDataURL(file);
});
const res = await safeCall('AddCustomEmoji', {
name: clean,
mime: file.type,
dataBase64,
});
setBusy(false);
if (res) {
toast(t('Emoji added'));
setName('');
if (fileRef.current) fileRef.current.value = '';
loadCustomEmojis();
}
};
return (
<div className="card">
<div className="card-head">
<h2>
{t('Custom emojis')}{' '}
<span className="muted">
{custom.length ? `· ${custom.length}` : ''}
</span>
</h2>
</div>
<div className="emoji-manage-row">
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t('shortcode (a-z0-9_)')}
maxLength={32}
/>
<input ref={fileRef} type="file" accept="image/*" />
<button
className="btn btn-accent"
disabled={busy}
onClick={upload}
>
{t('Add emoji')}
</button>
</div>
<div className="emoji-manage-grid">
{custom.map((c) => (
<div key={c.name} className="emoji-manage-item">
<img
className="emoji-img-lg"
src={`/emoji/${c.name}`}
alt={c.name}
/>
<span className="mono">:{c.name}:</span>
<button
className="icon-btn danger"
title={t('Remove')}
onClick={async () => {
await safeCall('RemoveCustomEmoji', {
name: c.name,
});
toast(t('Emoji removed'));
loadCustomEmojis();
}}
>
<CloseIcon />
</button>
</div>
))}
</div>
</div>
);
}
@@ -1,113 +0,0 @@
import { useEffect, useRef } from 'react';
import { useStore } from '../lib/store';
import {
EMOJI_CATEGORIES,
emojiStore,
rememberEmoji,
} from '../lib/emoji';
import { t } from '../i18n';
// A popover emoji picker: recently-used, curated Unicode categories, and the
// server's custom image emojis. `onPick` receives either a unicode char or a
// :shortcode: for a custom emoji.
export function EmojiPicker(props: {
onPick: (token: string) => void;
onClose: () => void;
}) {
const { custom, recent } = useStore(emojiStore);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
props.onClose();
}
};
// Defer so the opening click doesn't immediately close it.
const id = setTimeout(
() => document.addEventListener('mousedown', onDoc),
0
);
return () => {
clearTimeout(id);
document.removeEventListener('mousedown', onDoc);
};
}, [props]);
const pick = (token: string) => {
rememberEmoji(token);
props.onPick(token);
};
return (
<div className="emoji-picker" ref={ref}>
{recent.length > 0 && (
<div className="emoji-section">
<div className="emoji-section-label">{t('Recent')}</div>
<div className="emoji-grid">
{recent.map((token, i) =>
token.startsWith(':') ? (
<button
key={i}
className="emoji-btn"
onClick={() => pick(token)}
>
<img
src={`/emoji/${token.slice(1, -1)}`}
alt={token}
className="emoji-img"
/>
</button>
) : (
<button
key={i}
className="emoji-btn"
onClick={() => pick(token)}
>
{token}
</button>
)
)}
</div>
</div>
)}
{custom.length > 0 && (
<div className="emoji-section">
<div className="emoji-section-label">{t('Custom')}</div>
<div className="emoji-grid">
{custom.map((c) => (
<button
key={c.name}
className="emoji-btn"
title={`:${c.name}:`}
onClick={() => pick(`:${c.name}:`)}
>
<img
src={`/emoji/${c.name}`}
alt={c.name}
className="emoji-img"
/>
</button>
))}
</div>
</div>
)}
{EMOJI_CATEGORIES.map((cat) => (
<div key={cat.label} className="emoji-section">
<div className="emoji-section-label">{cat.label}</div>
<div className="emoji-grid">
{cat.emoji.map((e) => (
<button
key={e}
className="emoji-btn"
onClick={() => pick(e)}
>
{e}
</button>
))}
</div>
</div>
))}
</div>
);
}
@@ -1,108 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { appStore, safeCall } from '../lib/app';
import { useStore } from '../lib/store';
import type { LyricsResult } from '../lib/types';
import { t } from '../i18n';
// Lyrics for the current track (via the bot's GetLyrics → lrclib). When the
// provider returns time-synced lines we highlight the active one against the
// shared playback clock (appStore.positionMs) and keep it scrolled into view;
// otherwise we show plain scrollable text. Collapsed by default so we only
// fetch when the listener asks for it.
export function LyricsPanel() {
const s = useStore(appStore);
const [open, setOpen] = useState(false);
const [lyrics, setLyrics] = useState<LyricsResult | null>(null);
const [loading, setLoading] = useState(false);
const activeRef = useRef<HTMLDivElement>(null);
const track = s.current;
// Refetch when the track identity changes (url is stable per track).
const key = track ? track.url || track.title || '' : '';
useEffect(() => {
if (!open || !key) {
return;
}
let cancelled = false;
setLoading(true);
setLyrics(null);
safeCall<LyricsResult>('GetLyrics').then((res) => {
if (!cancelled) {
setLyrics(res);
setLoading(false);
}
});
return () => {
cancelled = true;
};
}, [key, open]);
const synced = lyrics?.synced ?? [];
// Index of the last line whose timestamp has passed.
const activeIdx = useMemo(() => {
if (!synced.length) return -1;
let idx = -1;
for (let i = 0; i < synced.length; i++) {
if (synced[i].ms <= s.positionMs) idx = i;
else break;
}
return idx;
}, [synced, s.positionMs]);
useEffect(() => {
activeRef.current?.scrollIntoView({ block: 'nearest' });
}, [activeIdx]);
return (
<div className="card">
<div className="card-head">
<h3>{t('Lyrics')}</h3>
<button
className="link"
onClick={() => setOpen((v) => !v)}
disabled={!track}
>
{open ? t('Hide') : t('Show')}
</button>
</div>
{open && (
<div className="lyrics-body">
{!track ? (
<div className="lyrics-empty">
{t('Nothing playing')}
</div>
) : loading ? (
<div className="lyrics-empty">{t('Loading…')}</div>
) : !lyrics || !lyrics.found ? (
<div className="lyrics-empty">
{t('No lyrics found')}
</div>
) : synced.length ? (
<div className="lyrics-synced">
{synced.map((line, i) => (
<div
key={i}
ref={i === activeIdx ? activeRef : null}
className={
'lyrics-line' +
(i === activeIdx ? ' active' : '')
}
>
{line.text || '♪'}
</div>
))}
</div>
) : (
<pre className="lyrics-plain">{lyrics.plain}</pre>
)}
{lyrics && lyrics.found && lyrics.source && (
<div className="lyrics-source muted">
{t('Lyrics via')} {lyrics.source}
</div>
)}
</div>
)}
</div>
);
}
@@ -1,68 +0,0 @@
import { appStore, safeCall } from '../lib/app';
import { useStore } from '../lib/store';
import { Bar } from './Bar';
import { coverStyle, fmtMs } from '../lib/format';
import { PauseIcon, PlayIcon, SkipNextIcon } from './icons';
import { t } from '../i18n';
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
// Mini player mirrors the current track on views other than Now Playing.
export function MiniPlayer() {
const s = useStore(appStore);
if (s.view === 'now' || !s.current) return null;
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
const canForceSkip = !!(
s.identity &&
(s.identity.isAdmin || s.identity.isDj)
);
const durationMs = s.durationMs || s.current.duration || 0;
const pct =
durationMs > 0 ? Math.min(100, (s.positionMs / durationMs) * 100) : 0;
return (
<div className="miniplayer">
<div
className="mini-cover"
style={{ background: coverStyle(s.current) }}
/>
<div className="mini-info">
<div className="mini-title">{s.current.title}</div>
<div className="mini-artist">{s.current.artist || ''}</div>
</div>
<button
className="ctrl"
title={t('Play/Pause')}
onClick={togglePlay}
>
{playing ? <PauseIcon /> : <PlayIcon />}
</button>
{canForceSkip && (
<button
className="ctrl"
title={t('Force skip')}
onClick={() => safeCall('Skip', { count: 1 })}
>
<SkipNextIcon />
</button>
)}
<Bar
slim
className="mini-bar"
pct={pct}
formatValue={(f) =>
durationMs ? fmtMs(Math.round(f * durationMs)) : ''
}
onDragStart={() => durationMs > 0}
onCommit={(f) =>
safeCall('Seek', {
position: Math.round(f * durationMs),
})
}
/>
</div>
);
}
@@ -1,30 +0,0 @@
import type { ReactNode } from 'react';
import { CloseIcon } from './icons';
export function Modal(props: {
title: string;
onClose: () => void;
children: ReactNode;
footer?: ReactNode;
wide?: boolean;
}) {
return (
<div className="modal-backdrop" onClick={props.onClose}>
<div
className={'modal' + (props.wide ? ' modal-wide' : '')}
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<h2>{props.title}</h2>
<button className="icon-btn" onClick={props.onClose}>
<CloseIcon />
</button>
</div>
<div className="modal-body">{props.children}</div>
{props.footer && (
<div className="modal-foot">{props.footer}</div>
)}
</div>
</div>
);
}
@@ -1,16 +0,0 @@
import { describe, expect, it } from 'vitest';
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
describe('NowPlayingVideo drift correction', () => {
it('never seeks while unstarted, cued, or buffering', () => {
for (const state of [-1, 3, 5]) {
expect(shouldCorrectVideoDrift(state, 0, 30, 10_000)).toBe(false);
}
});
it('waits for cooldown and ignores small playing drift', () => {
expect(shouldCorrectVideoDrift(1, 0, 30, 1000)).toBe(false);
expect(shouldCorrectVideoDrift(1, 28, 30, 10_000)).toBe(false);
expect(shouldCorrectVideoDrift(1, 10, 30, 10_000)).toBe(true);
});
});
@@ -1,133 +0,0 @@
import { useEffect, useRef } from 'react';
import { appStore } from '../lib/app';
import {
loadYouTubeApi,
YOUTUBE_EMBED_HOST,
youtubeEmbedVars,
} from '../lib/youtube';
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
// The muted YouTube video of the current track, shown in Now Playing when the
// user enables it (item 11). The bot's audio is the source of truth, so the
// video is always muted and only follows the server position — it resyncs
// with a hard seek when it drifts past the threshold, and pauses/plays to
// match. Purely a local visual aid; it sends nothing to the server.
const SEEK_LEAD_SECONDS = 0.75;
export function NowPlayingVideo({ videoId }: { videoId: string }) {
const mountRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<YT.Player | null>(null);
const currentVideo = useRef<string>('');
const pendingVideo = useRef(videoId);
const lastSeekAt = useRef(0);
const playIntent = useRef<boolean | null>(null);
useEffect(() => {
let cancelled = false;
loadYouTubeApi().then(() => {
if (cancelled || !mountRef.current) return;
const el = document.createElement('div');
mountRef.current.appendChild(el);
playerRef.current = new YT.Player(el, {
width: '100%',
height: '100%',
videoId,
host: YOUTUBE_EMBED_HOST,
playerVars: youtubeEmbedVars({ mute: 1 }),
events: {
onReady: () => {
const p = playerRef.current;
if (!p) return;
const requested = pendingVideo.current;
const startSeconds = appStore.get().positionMs / 1000;
if (requested !== videoId) {
p.loadVideoById({ videoId: requested, startSeconds });
} else if (startSeconds > 0) {
p.seekTo(startSeconds, true);
}
p.mute();
currentVideo.current = requested;
lastSeekAt.current = performance.now();
playIntent.current = null;
},
},
});
});
return () => {
cancelled = true;
playerRef.current?.destroy();
playerRef.current = null;
if (mountRef.current) mountRef.current.innerHTML = '';
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Load a new video id in place without recreating the player.
useEffect(() => {
pendingVideo.current = videoId;
const p = playerRef.current;
if (!p || !p.loadVideoById || currentVideo.current === videoId) return;
p.loadVideoById({
videoId,
startSeconds: appStore.get().positionMs / 1000,
});
p.mute();
currentVideo.current = videoId;
lastSeekAt.current = performance.now();
playIntent.current = null;
}, [videoId]);
// Follow the server position: resync on drift, match play/pause state.
useEffect(() => {
const id = setInterval(() => {
const p = playerRef.current;
if (!p || !p.getCurrentTime || !p.seekTo) return;
const s = appStore.get();
const targetSec = s.positionMs / 1000;
const playing = !!(
s.status &&
s.status.isPlaying &&
!s.status.isPaused
);
try {
const st = p.getPlayerState();
const now = performance.now();
// Seeking while CUED/BUFFERING repeatedly restarts YouTube's
// buffer. Drift is meaningful only once the playback clock moves.
if (shouldCorrectVideoDrift(
st,
p.getCurrentTime(),
targetSec,
now - lastSeekAt.current
)) {
p.seekTo(targetSec + SEEK_LEAD_SECONDS, true);
lastSeekAt.current = now;
}
if (
playing &&
playIntent.current !== true &&
(st === YT.PlayerState.CUED ||
st === YT.PlayerState.PAUSED ||
st === YT.PlayerState.ENDED)
) {
p.playVideo();
playIntent.current = true;
}
else if (
!playing &&
playIntent.current !== false &&
(st === YT.PlayerState.PLAYING || st === YT.PlayerState.BUFFERING)
) {
p.pauseVideo();
playIntent.current = false;
}
p.mute(); // guard against unmute on state changes
} catch {
/* player not ready yet */
}
}, 1000);
return () => clearInterval(id);
}, []);
return <div className="np-video" ref={mountRef} />;
}
@@ -1,31 +0,0 @@
import type { ReactNode } from 'react';
import { Avatar } from './Avatar';
export function PersonRow(props: {
name: string;
uid?: string | null;
sub?: string;
status?: string;
statusColor?: string;
children?: ReactNode;
}) {
const { name, uid, sub, status, statusColor, children } = props;
return (
<div className="person">
<Avatar name={name} uid={uid} />
<div className="person-main">
<div className="person-name">{name}</div>
{sub && <div className="person-sub">{sub}</div>}
</div>
{status && (
<span
className="person-status"
style={statusColor ? { color: statusColor } : undefined}
>
{status}
</span>
)}
{children}
</div>
);
}
@@ -1,62 +0,0 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { PlayerControls } from './PlayerControls';
const noop = () => {};
function render(over: Partial<Parameters<typeof PlayerControls>[0]> = {}) {
return renderToStaticMarkup(
<PlayerControls
playing={false}
positionMs={30_000}
durationMs={120_000}
canControl
volumePct={50}
onTogglePlay={noop}
onSeekMs={noop}
onSeekBy={noop}
onVolume={noop}
{...over}
/>
);
}
describe('PlayerControls', () => {
it('shows transport, times and volume when controllable', () => {
const html = render();
expect(html).toContain('0:30');
expect(html).toContain('2:00');
expect(html).toContain('Back 10 seconds');
expect(html).toContain('Forward 10 seconds');
expect(html).not.toContain('disabled');
});
it('disables transport when canControl is false', () => {
const html = render({ canControl: false });
// Play/pause + the two ±10s buttons are disabled…
expect(html.match(/disabled/g)?.length).toBe(3);
// …but the volume bar (local) is still rendered.
expect(html).toContain('50%');
});
it('hides seek buttons and shows LIVE for live sources', () => {
const html = render({ live: true });
expect(html).not.toContain('Back 10 seconds');
expect(html).toContain('LIVE');
});
it('renders skip only when onSkip is given', () => {
expect(render()).not.toContain('Play next');
expect(render({ onSkip: noop })).toContain('Play next');
});
it('hides the local row when showLocal is false', () => {
expect(render({ showLocal: false })).not.toContain('Vol');
});
it('renders the unified settings slot in the local row', () => {
expect(render({ settings: <button>Settings gear</button> })).toContain(
'Settings gear'
);
});
});
@@ -1,130 +0,0 @@
import type { ReactNode } from 'react';
import { Bar } from './Bar';
import { fmtMs } from '../lib/format';
import {
ForwardIcon,
FullscreenIcon,
PauseIcon,
PlayIcon,
RewindIcon,
SkipNextIcon,
} from './icons';
import { t } from '../i18n';
// The one custom player control bar, shared by Watch Together (room /ws
// protocol) and Now Playing (bot RPC). Purely presentational: the two sync
// channels differ only in the callbacks the views pass in. Embedded players
// (YouTube/Twitch/HTML5) always run with native controls hidden; this bar is
// the only playback UI.
export function PlayerControls(props: {
playing: boolean;
positionMs: number;
durationMs: number; // 0 = unknown
live?: boolean; // no seekable timeline (Twitch / generic embeds)
canControl: boolean; // transport disabled when false; volume stays local
bufferedPct?: number; // 0..100 second fill on the seek bar
volumePct: number; // 0..100
volumeLive?: boolean; // apply volume while dragging (local volume)
onTogglePlay: () => void;
onSeekMs: (ms: number) => void;
onSeekBy?: (deltaSec: number) => void; // renders ±10s when present
onVolume: (pct: number) => void;
onSkip?: () => void; // renders next-track button when present
skipDisabled?: boolean;
onFullscreen?: () => void;
settings?: ReactNode;
showLocal?: boolean; // hide the volume/quality row (default shown)
extra?: ReactNode; // view-specific buttons after the seek bar
extraLocal?: ReactNode; // view-specific controls in the volume row
}) {
const { live, durationMs, positionMs, canControl } = props;
const progressPct = live
? 100
: durationMs > 0
? Math.min(100, (positionMs / durationMs) * 100)
: 0;
return (
<div className="player-controls">
<div className="watch-controls">
<button
className="ctrl ctrl-main"
title={t('Play/Pause')}
disabled={!canControl}
onClick={props.onTogglePlay}
>
{props.playing ? <PauseIcon /> : <PlayIcon />}
</button>
{!live && props.onSeekBy && (
<>
<button
className="ctrl"
title={t('Back 10 seconds')}
disabled={!canControl}
onClick={() => props.onSeekBy!(-10)}
>
<RewindIcon />
</button>
<button
className="ctrl"
title={t('Forward 10 seconds')}
disabled={!canControl}
onClick={() => props.onSeekBy!(10)}
>
<ForwardIcon />
</button>
</>
)}
{props.onSkip && (
<button
className="ctrl"
title={t('Play next')}
disabled={!canControl || props.skipDisabled}
onClick={props.onSkip}
>
<SkipNextIcon />
</button>
)}
<span className="mono">{live ? '—' : fmtMs(positionMs)}</span>
<Bar
pct={progressPct}
bufferPct={live ? undefined : props.bufferedPct}
formatValue={(f) =>
live || !durationMs
? t('LIVE')
: fmtMs(Math.round(f * durationMs))
}
onDragStart={() => !live && durationMs > 0}
onCommit={(f) => props.onSeekMs(Math.round(f * durationMs))}
/>
<span className="mono">
{live ? t('LIVE') : fmtMs(durationMs)}
</span>
{props.extra}
</div>
{(props.showLocal ?? true) && (
<div className="watch-controls watch-local">
<span className="muted">{t('Vol')}</span>
<Bar
slim
live={props.volumeLive}
pct={props.volumePct}
formatValue={(f) => `${Math.round(f * 100)}%`}
onCommit={(f) => props.onVolume(Math.round(f * 100))}
/>
<span className="mono">{Math.round(props.volumePct)}%</span>
{props.settings}
{props.onFullscreen && (
<button
className="ctrl"
title={t('Fullscreen')}
onClick={props.onFullscreen}
>
<FullscreenIcon />
</button>
)}
{props.extraLocal}
</div>
)}
</div>
);
}
@@ -1,99 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import type { PlayerExtraControl } from '../lib/embedProtocols';
import { t } from '../i18n';
import { GearIcon } from './icons';
export function PlayerSettingsMenu(props: {
extras: PlayerExtraControl[];
rate: number;
rateOptions?: number[];
canControl: boolean;
onExtra: (id: string, value: string) => void;
onRate: (rate: number) => void;
}) {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const local = props.extras.filter((control) => control.scope === 'local');
const room = props.extras.filter(
(control) => control.scope === 'synced' && control.id !== 'speed'
);
const hasRoom = room.length > 0 || !!props.rateOptions?.length;
useEffect(() => {
if (!open) return;
const close = (event: MouseEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', close);
return () => document.removeEventListener('mousedown', close);
}, [open]);
if (local.length === 0 && !hasRoom) return null;
const renderControl = (control: PlayerExtraControl) => (
<label className="player-setting" key={control.id}>
<span>{t(control.label)}</span>
<select
value={control.current ?? ''}
disabled={control.scope === 'synced' && !props.canControl}
title={
control.scope === 'synced' && !props.canControl
? t('Only the host can change this')
: undefined
}
onChange={(event) => props.onExtra(control.id, event.target.value)}
>
{control.current == null && <option value="">{t('Choose')}</option>}
{control.options.map((option) => (
<option key={option.value} value={option.value}>
{t(option.label)}
</option>
))}
</select>
</label>
);
return (
<div className="player-settings" ref={rootRef}>
<button
className="ctrl"
title={t('Settings')}
aria-expanded={open}
onClick={() => setOpen((value) => !value)}
>
<GearIcon />
</button>
{open && (
<div className="player-settings-popover">
{local.length > 0 && (
<section>
<div className="player-settings-heading">{t('Local')}</div>
{local.map(renderControl)}
</section>
)}
{hasRoom && (
<section>
<div className="player-settings-heading">{t('Room')}</div>
{props.rateOptions && (
<label className="player-setting">
<span>{t('Speed')}</span>
<select
value={String(props.rate)}
disabled={!props.canControl}
onChange={(event) =>
props.onRate(Number(event.target.value))
}
>
{props.rateOptions.map((rate) => (
<option key={rate} value={rate}>{rate}×</option>
))}
</select>
</label>
)}
{room.map(renderControl)}
</section>
)}
</div>
)}
</div>
);
}
@@ -1,34 +0,0 @@
import { appStore } from '../lib/app';
import { useStore } from '../lib/store';
import { SHORTCUTS } from '../lib/shortcuts';
import { t } from '../i18n';
// Cheat-sheet overlay for keyboard shortcuts, toggled with "?".
export function ShortcutsHelp() {
const s = useStore(appStore);
if (!s.shortcutsOpen) return null;
return (
<div
className="modal-backdrop"
onClick={() => appStore.set({ shortcutsOpen: false })}
>
<div className="modal shortcuts-modal" onClick={(e) => e.stopPropagation()}>
<h2>{t('Keyboard shortcuts')}</h2>
<div className="shortcuts-list">
{SHORTCUTS.map((sc) => (
<div key={sc.keys} className="shortcut-row">
<kbd>{sc.keys}</kbd>
<span>{t(sc.label)}</span>
</div>
))}
</div>
<button
className="btn btn-ghost"
onClick={() => appStore.set({ shortcutsOpen: false })}
>
{t('Close')}
</button>
</div>
</div>
);
}
@@ -1,178 +0,0 @@
import { useState, type ReactNode } from 'react';
import {
appStore,
changeLanguage,
connectWithToken,
getStoredToken,
logout,
requestToken,
showView,
type ViewName,
} from '../lib/app';
import { useStore } from '../lib/store';
import { promptDialog } from '../lib/dialog';
import { Avatar } from './Avatar';
import {
CodeIcon,
GearIcon,
HeartIcon,
PlayIcon,
QueueIcon,
SearchIcon,
StatsIcon,
WatchIcon,
} from './icons';
import { t, useLanguage } from '../i18n';
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'now', icon: <PlayIcon />, label: 'Now Playing' },
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' },
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
];
export function Sidebar() {
const s = useStore(appStore);
const language = useLanguage();
const [token, setToken] = useState(getStoredToken() || '');
const isAdmin = !!(s.identity && s.identity.isAdmin);
const playing = !!(
s.status &&
s.status.isPlaying &&
!s.status.isPaused
);
const name = s.identity
? s.identity.nickname || s.identity.uid || t('user')
: '';
return (
<aside className={'sidebar' + (s.sidebarOpen ? ' open' : '')}>
<div className="brand">
<div className="brand-icon">
<svg viewBox="0 0 24 24" width="22" height="22" fill="#fff">
<rect x="4" y="9" width="3.4" height="10" rx="1.6" />
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" />
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" />
</svg>
</div>
<div>
<div className="brand-name">Echoion</div>
<div className="brand-sub">{t('MUSIC BOT · TS3')}</div>
</div>
</div>
<nav className="nav">
{NAV.filter(
(item) => item.view !== 'server' || isAdmin
).map((item) => (
<button
key={item.view}
className={
'nav-item' + (s.view === item.view ? ' active' : '')
}
onClick={() => showView(item.view)}
>
<span className="nav-ico">{item.icon}</span>
{t(item.label)}
{item.view === 'now' && playing && (
<span className="live-dot" />
)}
{item.view === 'queue' && s.queue.length > 0 && (
<span className="nav-badge">{s.queue.length}</span>
)}
</button>
))}
</nav>
<div className="sidebar-foot">
<div className="conn-row">
<span
className={
'conn-dot' +
(s.connection === 'connected'
? ' on'
: s.connection === 'error'
? ' err'
: '')
}
/>
<span>{t(s.connection)}</span>
<select
className="lang-select"
value={language}
title={t('Language')}
onChange={(e) =>
changeLanguage(e.target.value as 'en' | 'ru')
}
>
<option value="en">EN</option>
<option value="ru">RU</option>
</select>
</div>
{!s.identity ? (
<div>
<input
type="password"
placeholder={t('RPC token')}
autoComplete="off"
value={token}
onChange={(e) => setToken(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
connectWithToken(token);
}
}}
/>
<button
className="btn btn-accent"
onClick={() => connectWithToken(token)}
>
{t('Connect')}
</button>
<button
className="btn btn-ghost"
title={t('Send my token via TeamSpeak PM')}
onClick={async () => {
const nickname = await promptDialog({
title: t('Get token by nickname'),
message: t(
'Your TeamSpeak nickname (must be subscribed):'
),
placeholder: t('Nickname'),
confirmLabel: t('Send'),
});
if (nickname) requestToken(nickname);
}}
>
{t('Get token by nickname…')}
</button>
</div>
) : (
<div className="whoami">
<Avatar name={name} uid={s.identity.uid} />
<span>{name}</span>
{isAdmin && (
<span className="admin-chip">{t('ADMIN')}</span>
)}
{!isAdmin && s.identity.isDj && (
<span className="admin-chip">{t('DJ')}</span>
)}
<button
className="btn btn-ghost"
onClick={() => {
logout();
setToken('');
}}
>
{t('Logout')}
</button>
</div>
)}
</div>
</aside>
);
}
@@ -1,79 +0,0 @@
import type { ReactNode } from 'react';
import type { Track } from '../lib/types';
import { coverStyle, fmtMs, sourceInfo } from '../lib/format';
import { t } from '../i18n';
export interface TrackAction {
icon: ReactNode;
title: string;
cls?: string;
onClick: () => void;
}
export function TrackRow(props: {
track: Track;
num?: number;
playing?: boolean;
sub?: string;
actions?: Array<TrackAction | null | false>;
rowProps?: React.HTMLAttributes<HTMLDivElement> & { draggable?: boolean };
children?: ReactNode;
}) {
const { track, num, playing, sub, rowProps, children } = props;
const actions = (props.actions || []).filter(Boolean) as TrackAction[];
const src = sourceInfo(track);
return (
<div
{...rowProps}
className={
'track-row' +
(playing ? ' playing' : '') +
(rowProps?.className ? ` ${rowProps.className}` : '')
}
>
{num != null && (
<span className="track-num">
{String(num).padStart(2, '0')}
</span>
)}
<div
className="track-cover"
style={{ background: coverStyle(track) }}
/>
<div className="track-main">
<div className="track-title">
{track.title || t('(untitled)')}
</div>
<div className="track-sub">
{[track.artist, sub].filter(Boolean).join(' · ')}
</div>
</div>
{src && <span className={src.cls}>{src.label}</span>}
{!!track.duration && (
<span className="track-dur">{fmtMs(track.duration)}</span>
)}
{actions.length > 0 && (
<div className="track-actions">
{actions.map((a, i) => (
<button
key={i}
className={'icon-btn' + (a.cls ? ` ${a.cls}` : '')}
title={a.title}
onClick={(e) => {
e.stopPropagation();
a.onClick();
}}
>
{a.icon}
</button>
))}
</div>
)}
{children}
</div>
);
}
export function EmptyRow({ text }: { text: string }) {
return <div className="empty">{text}</div>;
}
@@ -1,145 +0,0 @@
import { useState } from 'react';
import { rpc } from '../lib/rpc';
import { send, watchStore } from '../lib/watch';
import { toast } from '../lib/app';
import { useStore } from '../lib/store';
import { thumbFor } from '../lib/format';
import type { Track } from '../lib/types';
import { t, tf } from '../i18n';
// Normalize a Twitch channel entry: accept a bare login name, an @handle, or a
// full twitch.tv URL, and reduce it to the channel login the embed player
// expects. Numeric ids pass through (best effort — resolving them to a login
// would need the Helix API, which isn't wired up).
function normalizeTwitchChannel(input: string): string {
let s = input.trim();
const m = s.match(/twitch\.tv\/([^/?#]+)/i);
if (m) s = m[1];
s = s.replace(/^@/, '');
return s.toLowerCase().replace(/[^a-z0-9_]/g, '');
}
// Add tracks to a watch room from inside it. YouTube uses the unauthenticated
// SearchTracks RPC (results added by title + thumbnail); Twitch has no search
// backend, so it offers an add-by-channel-name/id field instead.
export function WatchSearch({ disabled }: { disabled: boolean }) {
const w = useStore(watchStore);
const [query, setQuery] = useState('');
const [channel, setChannel] = useState('');
const [results, setResults] = useState<Track[]>([]);
const [open, setOpen] = useState(false);
if (w.sourceChoice === 'twitch') {
return (
<div className="watch-search">
<form
className="search-row"
onSubmit={(e) => {
e.preventDefault();
const ch = normalizeTwitchChannel(channel);
if (!ch) return;
send({
type: 'watch.queue.add',
source: 'twitch',
url: ch,
title: ch,
});
toast(tf('Added “{0}” to queue', ch));
setChannel('');
}}
>
<input
value={channel}
onChange={(e) => setChannel(e.target.value)}
placeholder={t(
'Twitch channel name or id to queue…'
)}
autoComplete="off"
disabled={disabled}
/>
<button
className="btn btn-accent"
type="submit"
disabled={disabled}
>
{t('Add channel')}
</button>
</form>
</div>
);
}
return (
<div className="watch-search">
<form
className="search-row"
onSubmit={async (e) => {
e.preventDefault();
const q = query.trim();
if (!q) return;
try {
const res = await rpc.call<{ tracks?: Track[] }>(
'SearchTracks',
{ query: q }
);
setResults((res && res.tracks) || []);
setOpen(true);
} catch (err) {
toast((err as { message?: string }).message || 'error');
}
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('Search YouTube to queue…')}
autoComplete="off"
disabled={disabled}
/>
<button className="btn btn-accent" type="submit" disabled={disabled}>
{t('Search')}
</button>
</form>
{open && results.length > 0 && (
<div className="watch-search-results">
{results.slice(0, 8).map((tr, i) => (
<button
key={tr.url || tr.id || i}
className="watch-search-item"
onClick={() => {
send({
type: 'watch.queue.add',
source: 'youtube',
url: tr.url || tr.id,
title: tr.title || '',
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
setOpen(false);
setQuery('');
}}
>
<div
className="track-cover"
style={
thumbFor(tr)
? {
background: `url("${thumbFor(tr)}") center/cover`,
}
: undefined
}
/>
<span className="watch-search-title">
{tr.title}
</span>
</button>
))}
</div>
)}
</div>
);
}
@@ -1,91 +0,0 @@
import type { SVGProps } from 'react';
// Inline SVG icon set replacing the raw unicode glyphs (✕ ▶ ⏸ ⚙ …), which
// rendered inconsistently across platforms and fonts. Sized in em so icons
// scale with the button font-size; color follows currentColor.
type IconProps = SVGProps<SVGSVGElement>;
function makeIcon(d: string) {
return function Icon(props: IconProps) {
return (
<svg
viewBox="0 0 24 24"
width="1em"
height="1em"
fill="currentColor"
aria-hidden="true"
focusable="false"
{...props}
>
<path d={d} />
</svg>
);
};
}
export const PlayIcon = makeIcon('M8 5v14l11-7z');
export const PauseIcon = makeIcon('M6 19h4V5H6v14zm8-14v14h4V5h-4z');
export const SkipNextIcon = makeIcon('M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z');
export const SkipPrevIcon = makeIcon('M6 6h2v12H6zm3.5 6l8.5 6V6l-8.5 6z');
export const RewindIcon = makeIcon(
'M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z'
);
export const ForwardIcon = makeIcon(
'M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z'
);
export const ShuffleIcon = makeIcon(
'M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z'
);
export const RepeatIcon = makeIcon(
'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z'
);
export const HeartIcon = makeIcon(
'M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z'
);
export const CloseIcon = makeIcon(
'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'
);
export const SearchIcon = makeIcon(
'M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'
);
export const QueueIcon = makeIcon(
'M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zm14-10v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z'
);
export const StatsIcon = makeIcon(
'M5 9.2h3V19H5V9.2zM10.6 5h2.8v14h-2.8V5zm5.6 8H19v6h-2.8v-6z'
);
export const WatchIcon = makeIcon(
'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM9.5 8.5l7 3.5-7 3.5v-7z'
);
export const GearIcon = makeIcon(
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
);
export const CodeIcon = makeIcon(
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
);
export const FullscreenIcon = makeIcon(
'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z'
);
export const PowerIcon = makeIcon(
'M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z'
);
export const CrownIcon = makeIcon(
'M5 16L3 6l5.5 4L12 4l3.5 6L21 6l-2 10H5zm14 3c0 .55-.45 1-1 1H6c-.55 0-1-.45-1-1v-1h14v1z'
);
export const RefreshIcon = makeIcon(
'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z'
);
export const PlusIcon = makeIcon('M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z');
export const VolumeIcon = makeIcon(
'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z'
);
export const VolumeMuteIcon = makeIcon(
'M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z'
);
export const HelpIcon = makeIcon(
'M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z'
);
export const MenuIcon = makeIcon('M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z');
export const ExternalLinkIcon = makeIcon(
'M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'
);
-58
View File
@@ -1,58 +0,0 @@
// Web UI localization, mirroring the bot's approach (EchoionCore i18n):
// English source strings are the keys; a missing entry falls back to the
// English original. Language resolution order matches the bot's
// CommandManager::resolveLanguage: the authenticated user's server-side
// preference (kv "lang:<uid>", shared with !lang) → local override →
// browser language → English.
import { Store, useStore } from '../lib/store';
import { ru } from './ru';
export type Language = 'en' | 'ru';
const LS_KEY = 'echoion.lang';
function initialLanguage(): Language {
// Not a browser (node test runner): no stored preference, use English.
if (typeof localStorage === 'undefined') return 'en';
const stored = localStorage.getItem(LS_KEY);
if (stored === 'en' || stored === 'ru') return stored;
return (navigator.language || '').toLowerCase().startsWith('ru')
? 'ru'
: 'en';
}
export const languageStore = new Store<{ language: Language }>({
language: initialLanguage(),
});
export function getLanguage(): Language {
return languageStore.get().language;
}
// `persist` distinguishes a user choice (saved locally, pushed to the
// server by the caller) from applying the server-side preference.
export function setLanguage(language: Language, persist = true) {
if (persist) localStorage.setItem(LS_KEY, language);
languageStore.set({ language });
document.documentElement.lang = language;
}
export function t(english: string): string {
if (getLanguage() === 'ru') return ru[english] ?? english;
return english;
}
// Translate a template, then substitute {0}, {1}, … arguments.
export function tf(english: string, ...args: Array<string | number>): string {
const template = t(english);
return template.replace(/\{(\d+)\}/g, (m, i) => {
const v = args[Number(i)];
return v === undefined ? m : String(v);
});
}
// Components subscribe so a language switch re-renders everything.
export function useLanguage(): Language {
return useStore(languageStore).language;
}
-302
View File
@@ -1,302 +0,0 @@
// Russian catalog for the web UI. Same philosophy as the bot's compiled-in
// RussianCatalog.inc: English source strings are the keys; a missing entry
// falls back to English. Placeholders are {0}, {1}, … (see tf()).
export const ru: Record<string, string> = {
// Sidebar / navigation
'Now Playing': 'Сейчас играет',
'Queue': 'Очередь',
'Search': 'Поиск',
'Library': 'Библиотека',
'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр',
'Server & Admin': 'Сервер и админ',
'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
'Connect': 'Подключиться',
'Get token by nickname…': 'Получить токен по нику…',
'Send my token via TeamSpeak PM': 'Прислать мой токен личным сообщением в TeamSpeak',
'RPC token': 'RPC-токен',
'Logout': 'Выйти',
'ADMIN': 'АДМИН',
'DJ': 'DJ',
'connected': 'подключено',
'disconnected': 'отключено',
'error': 'ошибка',
'listening': 'слушают',
// View headers
'What Echoion is streaming to the channel': 'Что Echoion стримит в канал',
'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков',
'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке',
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
'Playback history and server insights': 'История воспроизведения и статистика сервера',
'Synced viewing room — everyone in step': 'Синхронный просмотр — все в ногу',
'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
// Now playing
'Nothing playing': 'Ничего не играет',
'Up Next': 'Далее',
'Open queue →': 'Открыть очередь →',
'Listening now': 'Сейчас слушают',
'Queue is empty': 'Очередь пуста',
'Vol': 'Гром.',
'Radio': 'Радио',
'Vote skip': 'Голос за пропуск',
'Vote skip {0}/{1}': 'Пропуск {0}/{1}',
'Shuffle': 'Перемешать',
'Restart track': 'Сначала',
'Play/Pause': 'Играть/Пауза',
'Repeat': 'Повтор',
'Favorite': 'В избранное',
'Vote to skip': 'Голосовать за пропуск',
'Force skip': 'Принудительный пропуск',
'Radio mode is admin-only — ask an admin or use !autoplay':
'Режим радио доступен только админам — попросите админа или используйте !autoplay',
'Radio mode on': 'Режим радио включён',
'Radio mode off': 'Режим радио выключен',
'Vote passed — track skipped': 'Голосование прошло — трек пропущен',
'Added to favorites': 'Добавлено в избранное',
'Removed from favorites': 'Удалено из избранного',
'Playing now': 'Играет сейчас',
'Lyrics': 'Текст песни',
'Show': 'Показать',
'Hide': 'Скрыть',
'Loading…': 'Загрузка…',
'No lyrics found': 'Текст не найден',
'Lyrics via': 'Текст из',
// Queue view
'Queue is empty — add something from Search': 'Очередь пуста — добавьте что-нибудь из Поиска',
'Shuffle queue': 'Перемешать очередь',
'Clear': 'Очистить',
'Clear the whole queue?': 'Очистить всю очередь?',
'Queue cleared': 'Очередь очищена',
'Play now': 'Играть сейчас',
'Remove': 'Удалить',
'{0} tracks': '{0} треков',
// Search
'Search YouTube and Yandex Music… or paste a URL': 'Ищите на YouTube и в Яндекс Музыке… или вставьте ссылку',
'All': 'Все',
'No results yet — search for something': 'Пока нет результатов — поищите что-нибудь',
'Searching “{0}”…': 'Ищем «{0}»…',
'Add to queue': 'Добавить в очередь',
'Added “{0}” to queue': '«{0}» добавлен в очередь',
'Save to favorites': 'Сохранить в избранное',
'Saved to favorites': 'Сохранено в избранное',
// Library
'Your favorites': 'Ваше избранное',
'Playlists': 'Плейлисты',
'Save queue as playlist': 'Сохранить очередь как плейлист',
'Authenticate to use favorites': 'Войдите, чтобы пользоваться избранным',
'No favorites yet — ♥ a track anywhere': 'Пока нет избранного — нажмите ♥ на любом треке',
'No playlists saved yet': 'Плейлистов пока нет',
'Playlist name (saves the current queue):': 'Название плейлиста (сохранит текущую очередь):',
'Playlist “{0}” saved': 'Плейлист «{0}» сохранён',
'Loading playlist “{0}”…': 'Загружаем плейлист «{0}»…',
'Saved from web UI': 'Сохранено из веб-интерфейса',
'Delete': 'Удалить',
'Delete playlist': 'Удалить плейлист',
'Delete playlist “{0}”? This cannot be undone.':
'Удалить плейлист «{0}»? Это нельзя отменить.',
'Playlist “{0}” deleted': 'Плейлист «{0}» удалён',
'Close': 'Закрыть',
'This playlist is empty': 'Плейлист пуст',
// Stats
'Recently played': 'Недавно игравшие',
'Top requesters': 'Топ заказчиков',
'Source split': 'Источники',
'Nothing played yet': 'Пока ничего не игралось',
'No requests logged yet': 'Запросов пока нет',
'Queue again': 'Заказать снова',
'Tracks played today': 'Треков за сегодня',
'Listening hours': 'Часов прослушивания',
'Queue additions': 'Добавлений в очередь',
'Skips': 'Пропусков',
'{0} all-time': '{0} за всё время',
'today': 'сегодня',
'{0}% skip rate': '{0}% пропусков',
'{0} requests': '{0} запросов',
// Watch together
'Nothing loaded — paste a URL above': 'Ничего не загружено — вставьте ссылку выше',
'Twitch embeds require HTTPS — open the site via its https:// domain':
'Встраивание Twitch требует HTTPS — откройте сайт по его https:// адресу',
'YouTube URL to watch together': 'Ссылка YouTube для совместного просмотра',
'Twitch channel or URL to watch together': 'Канал или ссылка Twitch для совместного просмотра',
'Video URL': 'Видео по ссылке',
'Embed': 'Встраивание',
'Direct video or .m3u8 URL to watch together':
'Прямая ссылка на видео или .m3u8 для совместного просмотра',
'Embed URL (Kodik, etc.) to watch together':
'Ссылка для встраивания (Kodik и др.) для совместного просмотра',
'Load': 'Загрузить',
'+ Queue': '+ В очередь',
'Add to the watch queue': 'Добавить в очередь просмотра',
'Guest — sign in to control': 'Гость — войдите, чтобы управлять',
'You are hosting': 'Вы ведущий',
'Viewer': 'Зритель',
'Synced': 'Синхронно',
'Resync': 'Синхронизировать',
'Resynced to room': 'Синхронизировано с комнатой',
'Live stream — cannot seek': 'Прямой эфир — перемотка недоступна',
'LIVE': 'ЭФИР',
'In the room': 'В комнате',
'Room chat': 'Чат комнаты',
'Say something…': 'Скажите что-нибудь…',
'Send': 'Отправить',
'Host': 'Ведущий',
'Host only': 'Только ведущий',
'Play next': 'Следующее',
'(you)': '(вы)',
'Buffering…': 'Буферизация…',
'In sync': 'Синхронно',
'Nothing queued — paste a URL and hit “+ Queue”': 'Очередь пуста — вставьте ссылку и нажмите «+ В очередь»',
'Remove from queue': 'Убрать из очереди',
'added by {0}': 'добавил {0}',
'Fullscreen': 'Во весь экран',
'Fullscreen unavailable': 'Полноэкранный режим недоступен',
'Playback quality (best effort — YouTube may keep auto)':
'Качество (по возможности — YouTube может оставить авто)',
'Auto': 'Авто',
'Not allowed': 'Недостаточно прав',
// Watch Together protocol extensions (items 3, 4, 5)
'New room name…': 'Название новой комнаты…',
'Create / join': 'Создать / войти',
'Make host': 'Назначить ведущим',
'That viewer is no longer here': 'Этого зрителя уже нет',
'Only signed-in viewers can host': 'Вести может только вошедший зритель',
// Watch player & UX (items 7, 8, 16, 20)
'Playback speed': 'Скорость воспроизведения',
'Search YouTube to queue…': 'Найти на YouTube для очереди…',
'Recent': 'Недавние',
'Custom': 'Свои',
'Custom emojis': 'Свои эмодзи',
'Add emoji': 'Добавить эмодзи',
'Emoji added': 'Эмодзи добавлено',
'Emoji removed': 'Эмодзи удалено',
'shortcode (a-z0-9_)': 'код (a-z0-9_)',
'Choose an image file': 'Выберите файл изображения',
'Emoji name must be 1-32 chars of a-z, 0-9, _': 'Имя: 1–32 символа a-z, 0-9, _',
'Emoji image too large (max ~64KB)': 'Изображение слишком большое (макс ~64КБ)',
// Server & admin
'Subscribers': 'Подписчики',
'Announce…': 'Объявление…',
'Reload config': 'Перезагрузить конфиг',
'Restart web UI': 'Перезапустить веб-интерфейс',
'Stop and start the web server without touching the bot':
'Остановить и запустить веб-сервер, не трогая бота',
'Unsub all': 'Отписать всех',
'No subscribers': 'Нет подписчиков',
'Nobody online right now': 'Сейчас никого нет в сети',
'Online': 'В сети',
'Offline': 'Не в сети',
'Unsub': 'Отписать',
'Unsubscribe {0}?': 'Отписать {0}?',
'Unsubscribed {0}': '{0} отписан',
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
'Announcement sent': 'Объявление отправлено',
'Configuration reloaded': 'Конфигурация перезагружена',
'Restart the web interface? Everyone disconnects briefly.':
'Перезапустить веб-интерфейс? Все ненадолго отключатся.',
'Web interface restarting — this page will reconnect':
'Веб-интерфейс перезапускается — страница переподключится',
'Remove ALL subscriptions? This cannot be undone.':
'Удалить ВСЕ подписки? Это нельзя отменить.',
'All subscriptions removed': 'Все подписки удалены',
'Listening': 'Слушает',
'Audit log': 'Журнал аудита',
'Refresh': 'Обновить',
'No audit entries yet': 'Записей аудита пока нет',
'client #{0}': 'клиент №{0}',
// RPC view
'Connect programmatically': 'Программное подключение',
'Copy snippet': 'Скопировать пример',
'Snippet copied': 'Пример скопирован',
'Copy': 'Копировать',
'{0} copied': '{0} — скопировано',
'(authenticate first)': '(сначала войдите)',
// Auth / connection
'Signed in as {0}': 'Вы вошли как {0}',
'Welcome, {0}!': 'Добро пожаловать, {0}!',
'subscriber': 'подписчик',
'friend': 'друг',
'user': 'пользователь',
'Connection failed': 'Не удалось подключиться',
'Reconnected': 'Переподключено',
'Logged out': 'Вы вышли',
'Your TeamSpeak nickname (must be subscribed):': 'Ваш ник в TeamSpeak (нужна подписка):',
'Token sent via TeamSpeak PM': 'Токен отправлен личным сообщением в TeamSpeak',
'Request failed': 'Запрос не удался',
'Language': 'Язык',
'(untitled)': '(без названия)',
// Main-UI feature additions (items 9, 11, 14, 15, 18)
'Open original link': 'Открыть оригинальную ссылку',
'Watch video': 'Смотреть видео',
'Hide video': 'Скрыть видео',
'Compose announcement': 'Составить объявление',
'Send announcement': 'Отправить объявление',
'Cancel': 'Отмена',
'Preview': 'Предпросмотр',
'Nothing to preview yet': 'Пока нечего показать',
// Keyboard shortcuts
'Keyboard shortcuts': 'Горячие клавиши',
'Play / pause': 'Играть / пауза',
'Seek 5s': 'Перемотка 5с',
'Volume': 'Громкость',
'Skip / vote skip': 'Пропустить / голос за пропуск',
'Focus search': 'Перейти к поиску',
'This help': 'Эта справка',
// Mobile / unified player / cleanup update
'Menu': 'Меню',
'Back 10 seconds': 'Назад на 10 секунд',
'Forward 10 seconds': 'Вперёд на 10 секунд',
'Leave room': 'Покинуть комнату',
'Leave this room': 'Покинуть эту комнату',
'Room': 'Комната',
'Watch together': 'Смотреть вместе',
'Refresh rooms': 'Обновить список комнат',
'Join a room to watch in sync, or create your own.':
'Войдите в комнату для синхронного просмотра или создайте свою.',
'No active rooms yet — create one below.':
'Активных комнат пока нет — создайте свою ниже.',
'{0} watching': '{0} смотрят',
'Tap to unmute': 'Нажмите, чтобы включить звук',
'Add channel': 'Добавить канал',
'Twitch channel name or id to queue…': 'Имя или ID Twitch-канала для очереди…',
'Clear queue': 'Очистить очередь',
'Watch queue is full': 'Очередь просмотра заполнена',
'Watch queue is empty': 'Очередь просмотра пуста',
'Confirm': 'Подтвердить',
'OK': 'ОК',
'Save': 'Сохранить',
'Restart': 'Перезапустить',
'Remove all': 'Удалить все',
'Unsubscribe': 'Отписаться',
'Get token by nickname': 'Получить токен по нику',
'Nickname': 'Ник',
'Playlist name': 'Название плейлиста',
'Save playlist': 'Сохранить плейлист',
// Controllable embeds (Kodik / Playerjs)
'Embed synced': 'Встраиваемый плеер синхронизирован',
'Embed is view-only': 'Встраиваемый плеер — только просмотр',
'Settings': 'Настройки',
'Local': 'Локально',
'Quality': 'Качество',
'Speed': 'Скорость',
'Voiceover': 'Озвучка',
'Episode': 'Серия',
'Subtitles': 'Субтитры',
'Off': 'Выкл.',
'Choose': 'Выбрать',
'Only the host can change this': 'Изменять может только ведущий',
};
-365
View File
@@ -1,365 +0,0 @@
// App-level state + orchestration — the controller half of the old app.js.
// Views render from `appStore`; server push and the refresh helpers below
// mutate it.
import { rpc, type RpcMethodName } from './rpc';
import { Store } from './store';
import { t, tf, setLanguage, getLanguage } from '../i18n';
import { setWatchName } from './watch';
import { loadCustomEmojis } from './emoji';
import type {
Identity,
QueueEntry,
ServerInfo,
Status,
Subscriber,
Track,
} from './types';
export type ViewName =
| 'now'
| 'queue'
| 'search'
| 'library'
| 'stats'
| 'watch'
| 'server'
| 'rpc';
export interface AppState {
view: ViewName;
connection: 'connected' | 'disconnected' | 'error';
identity: Identity | null;
status: Status | null;
current: Track | null;
queue: QueueEntry[];
favorites: Track[];
favUrls: Set<string>;
searchResults: Track[];
searchTab: 'all' | 'youtube' | 'yandex';
positionMs: number;
durationMs: number;
onlineCount: number;
listeners: Subscriber[];
toast: string | null;
// Server-wide switch for the Now Playing video preview (item 11), from
// /config.json; users can still disable it locally.
nowPlayingVideoAllowed: boolean;
// Keyboard-shortcut cheat-sheet overlay (toggled with "?").
shortcutsOpen: boolean;
// Sidebar drawer on small screens (hamburger in the header); ignored by
// CSS on desktop widths where the sidebar is always visible.
sidebarOpen: boolean;
}
export const appStore = new Store<AppState>({
view: 'now',
connection: 'disconnected',
identity: null,
status: null,
current: null,
queue: [],
favorites: [],
favUrls: new Set(),
searchResults: [],
searchTab: 'all',
positionMs: 0,
durationMs: 0,
onlineCount: 0,
listeners: [],
toast: null,
nowPlayingVideoAllowed: true,
shortcutsOpen: false,
sidebarOpen: false,
});
// ── toast ────────────────────────────────────────────────────────────────────
let toastTimer: ReturnType<typeof setTimeout> | null = null;
export function toast(msg: string) {
appStore.set({ toast: msg });
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(() => appStore.set({ toast: null }), 2400);
}
export async function safeCall<T = unknown>(
method: RpcMethodName,
params?: Record<string, unknown>
): Promise<T | null> {
try {
return await rpc.call<T>(method, params);
} catch (e) {
const err = e as { message?: string };
if (err && err.message) toast(err.message);
console.warn(method, 'failed', e);
return null;
}
}
// ── auth ─────────────────────────────────────────────────────────────────────
export function getStoredToken(): string | null {
return localStorage.getItem('echoion.token');
}
async function loadUserPrefs() {
const prefs = await safeCall<{ language?: string }>('GetUserPrefs');
if (prefs && (prefs.language === 'en' || prefs.language === 'ru')) {
// Server-side preference (set here or via !lang) wins over the
// browser default but is not written to the local override.
if (!localStorage.getItem('echoion.lang')) {
setLanguage(prefs.language, false);
}
}
}
export async function changeLanguage(language: 'en' | 'ru') {
setLanguage(language);
if (appStore.get().identity) {
await safeCall('SetUserPrefs', { language });
}
}
export function applyIdentity(auth: Identity | null) {
appStore.set({ identity: auth });
if (auth) {
setWatchName(auth.nickname || null);
void loadUserPrefs();
void loadCustomEmojis();
}
}
// Autologin: the bot matches this browser's IP against online subscribers'
// TeamSpeak addresses and hands back the user's persistent token, so people
// on their usual machine never type anything.
export async function tryAutologin(): Promise<boolean> {
try {
const auth = await rpc.call<Identity>('AuthenticateByAddress');
if (auth && auth.token) {
localStorage.setItem('echoion.token', auth.token);
rpc.token = auth.token;
applyIdentity(auth);
toast(tf('Signed in as {0}', auth.nickname || t('subscriber')));
return true;
}
} catch {
/* no address match — the manual auth box stays available */
}
return false;
}
// Restore the authenticated session: use the stored token, and if it's
// missing or rejected (expired/revoked), clear it and fall back to address
// autologin. Never throws — a failure just leaves the user as a guest with the
// auth box available, so callers can always proceed to refresh state.
async function restoreSession(): Promise<void> {
const token = getStoredToken();
if (token) {
try {
applyIdentity((await rpc.authenticate(token)) as Identity);
return;
} catch {
// Stale token — drop it so it doesn't wedge every reconnect.
localStorage.removeItem('echoion.token');
rpc.token = null;
}
}
await tryAutologin();
}
export async function connectWithToken(tokenInput: string) {
const token = tokenInput.trim() || getStoredToken() || '';
try {
if (!rpc.connected) await rpc.connect();
if (token) {
const auth = (await rpc.authenticate(token)) as Identity;
localStorage.setItem('echoion.token', token);
applyIdentity(auth);
toast(tf('Welcome, {0}!', auth.nickname || t('friend')));
}
refreshAll();
} catch (e) {
const err = e as { message?: string };
toast((err && err.message) || t('Connection failed'));
}
}
export async function requestToken(nickname: string) {
try {
if (!rpc.connected) await rpc.connect();
const res = (await rpc.requestToken(nickname.trim())) as Identity;
toast((res && res.message) || t('Token sent via TeamSpeak PM'));
} catch (e) {
const err = e as { message?: string };
toast((err && err.message) || t('Request failed'));
}
}
export async function logout() {
await safeCall('Logout');
localStorage.removeItem('echoion.token');
rpc.token = null;
applyIdentity(null);
toast(t('Logged out'));
}
// ── view routing ─────────────────────────────────────────────────────────────
export function showView(view: ViewName) {
// Navigation closes the mobile drawer.
appStore.set({ view, sidebarOpen: false });
// Reflect the selection in the URL for back/forward + shareable links.
// The watch view owns its own #watch/<room> hash (see watch.ts), so a
// re-selection never clobbers an existing room deep link.
if (view === 'watch' && location.hash.startsWith('#watch')) return;
const target = `#${view}`;
if (location.hash !== target) location.hash = target;
}
// ── refresh orchestration ────────────────────────────────────────────────────
export async function refreshCore() {
if (!rpc.connected) return;
const [status, current, queue, info] = await Promise.all([
safeCall<Status>('GetStatus'),
safeCall<{ track?: Track }>('GetCurrentTrack'),
safeCall<{ queue?: QueueEntry[] }>('GetQueue'),
safeCall<ServerInfo>('GetServerInfo'),
]);
const state = appStore.get();
const next: Partial<AppState> = {
status,
current: (current && current.track) || null,
queue: (queue && queue.queue) || [],
};
if (info && typeof info.onlineSubscribers === 'number') {
next.onlineCount = info.onlineSubscribers;
}
// The nicknames + uids on GetServerInfo feed the "Listening now" card for
// everyone. Admins get a richer list from the server view's loadSubscribers,
// but that only runs once they open that view — so populate here
// unconditionally (previously admins saw an empty card on the Now tab).
if (info) {
const names = info.onlineSubscriberNames || [];
const uids = info.onlineSubscriberUids || [];
next.listeners = names.map((n, i) => ({
uid: uids[i] || n,
nickname: n,
online: true,
}));
}
const track = next.current;
if (track && track.duration && !state.durationMs) {
next.durationMs = track.duration;
}
appStore.set(next);
}
export async function refreshAll() {
await refreshCore();
}
export async function loadFavorites() {
if (!appStore.get().identity) return;
const res = await safeCall<{ tracks?: Track[] }>('GetFavorites');
const favorites = (res && res.tracks) || [];
appStore.set({
favorites,
favUrls: new Set(
favorites.map((tr) => tr.url).filter(Boolean) as string[]
),
});
}
// ── boot ─────────────────────────────────────────────────────────────────────
let booted = false;
export function boot() {
if (booted) return;
booted = true;
// Apply the persisted language before anything renders text.
setLanguage(getLanguage(), false);
// Server config: the Now Playing video preview can be disabled globally.
fetch('/config.json')
.then((r) => r.json())
.then((cfg) => {
if (cfg && cfg.nowPlayingVideo === false) {
appStore.set({ nowPlayingVideoAllowed: false });
}
})
.catch(() => {
/* keep the default (allowed) */
});
rpc.onState = (s) => appStore.set({ connection: s });
// After an automatic reconnect, restore the authenticated session from
// the stored token (or autologin) and pull fresh state.
rpc.onReconnected = async () => {
await restoreSession();
refreshAll();
toast(t('Reconnected'));
};
// Server push: any event nudges a debounced refresh; position updates
// are applied directly so the progress bar stays smooth.
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
rpc.on('*', (event) => {
if (event === 'playback.position') return;
if (refreshTimer) clearTimeout(refreshTimer);
refreshTimer = setTimeout(refreshAll, 150);
});
rpc.on('playback.position', (d) => {
const data = d as { position?: number; duration?: number } | null;
if (!data) return;
appStore.set({
positionMs: data.position || 0,
durationMs: data.duration || 0,
});
});
rpc.on('voteskip.updated', (d) => {
const data = d as { votes?: number; needed?: number } | null;
if (!data) return;
const status = appStore.get().status;
if (status) {
appStore.set({
status: {
...status,
skipVotes: data.votes,
skipVotesNeeded: data.needed,
},
});
}
});
// Local 1s ticker keeps the progress bar moving between server updates.
setInterval(() => {
const s = appStore.get();
if (
s.status &&
s.status.isPlaying &&
!s.status.isPaused &&
s.durationMs > 0
) {
appStore.set({
positionMs: Math.min(s.durationMs, s.positionMs + 1000),
});
}
}, 1000);
(async () => {
try {
await rpc.connect();
} catch {
/* connection failed — stay on the auth box */
return;
}
// Session restore is independent of the connection: even if auth fails
// we still refresh so guests see live state instead of a blank app.
await restoreSession();
refreshAll();
})();
}
@@ -1,65 +0,0 @@
// Maps the numeric RpcMethod enum value carried by audit-log entries to a
// human name. This mirrors the declaration order of `enum class RpcMethod`
// in EchoionApi/include/echoion/api/rpc/RpcTypes.hpp, which is explicitly
// append-only ("numeric values are server-internal and only need to stay
// self-consistent") — so index == enum value. When you append a method to
// that enum, append it here too.
const RPC_METHOD_BY_INDEX: readonly string[] = [
'Play', // 0
'Pause',
'Resume',
'Stop',
'Skip',
'Seek',
'SetVolume',
'QueueTrack',
'RemoveFromQueue',
'ClearQueue',
'GetQueue', // 10
'MoveInQueue',
'GetCurrentTrack',
'GetTrackInfo',
'SearchTracks',
'LoadPlaylist',
'SavePlaylist',
'GetPlaylists',
'DeletePlaylist',
'GetConfig',
'SetConfig', // 20
'ReloadConfig',
'GetStatus',
'HotReload',
'Shutdown',
'Authenticate',
'Logout',
'GetAuditLog',
'ManageUsers',
'GetServerInfo',
'RequestLoginToken', // 30
'ValidateLoginToken',
'ToggleShuffle',
'ToggleRepeat',
'ShuffleQueue',
'GetPlaylist',
'GetHistory',
'GetStats',
'GetFavorites',
'AddFavorite',
'RemoveFavorite', // 40
'VoteSkip',
'Announce',
'GetAggregateStats',
'AuthenticateByAddress',
'RestartWebInterface',
'ToggleAutoplay',
'GetUserPrefs',
'SetUserPrefs',
'GetCustomEmojis',
'AddCustomEmoji', // 50
'RemoveCustomEmoji',
'GetLyrics',
];
export function auditMethodName(method: number): string {
return RPC_METHOD_BY_INDEX[method] ?? `Method #${method}`;
}
-84
View File
@@ -1,84 +0,0 @@
// Imperative custom dialogs (item 10) replacing the browser's native
// confirm()/prompt(), which can't be styled and look out of place. A single
// <DialogHost/> mounted at the app root renders the active request; the
// confirmDialog/promptDialog helpers return a promise that resolves when the
// user answers, so call sites read like `if (await confirmDialog(...))`.
import { Store } from './store';
export interface ConfirmRequest {
kind: 'confirm';
title: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
danger?: boolean;
resolve: (ok: boolean) => void;
}
export interface PromptRequest {
kind: 'prompt';
title: string;
message?: string;
placeholder?: string;
initial?: string;
confirmLabel?: string;
cancelLabel?: string;
resolve: (value: string | null) => void;
}
export type DialogRequest = ConfirmRequest | PromptRequest;
interface DialogState {
current: DialogRequest | null;
}
export const dialogStore = new Store<DialogState>({ current: null });
// Resolve the active dialog and clear it. Guards against double-resolve (e.g.
// clicking confirm and the backdrop in quick succession).
function settle(value: boolean | string | null) {
const req = dialogStore.get().current;
if (!req) return;
dialogStore.set({ current: null });
if (req.kind === 'confirm') {
req.resolve(value === true);
} else {
req.resolve(typeof value === 'string' ? value : null);
}
}
export function resolveConfirm(ok: boolean) {
settle(ok);
}
export function resolvePrompt(value: string | null) {
settle(value);
}
export function confirmDialog(
opts: Omit<ConfirmRequest, 'kind' | 'resolve'>
): Promise<boolean> {
// A pending dialog is cancelled if a new one opens (shouldn't overlap).
const pending = dialogStore.get().current;
if (pending) {
if (pending.kind === 'confirm') pending.resolve(false);
else pending.resolve(null);
}
return new Promise<boolean>((resolve) => {
dialogStore.set({ current: { kind: 'confirm', ...opts, resolve } });
});
}
export function promptDialog(
opts: Omit<PromptRequest, 'kind' | 'resolve'>
): Promise<string | null> {
const pending = dialogStore.get().current;
if (pending) {
if (pending.kind === 'confirm') pending.resolve(false);
else pending.resolve(null);
}
return new Promise<string | null>((resolve) => {
dialogStore.set({ current: { kind: 'prompt', ...opts, resolve } });
});
}
@@ -1,254 +0,0 @@
import { describe, expect, it } from 'vitest';
import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols';
const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!;
const kodik = byName('kodik');
const playerjs = byName('playerjs');
const alloha = byName('alloha');
const vimeo = byName('vimeo');
const playerjsSpec = byName('player.js');
const rutube = byName('rutube');
const dailymotion = byName('dailymotion');
const vk = byName('vk');
describe('kodik parse', () => {
it('parses JSON-string time updates', () => {
expect(
kodik.parse(
JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 })
)
).toEqual({ kind: 'time', seconds: 42.5 });
});
it('parses duration and play/pause/ended state', () => {
expect(
kodik.parse({ key: 'kodik_player_duration_update', value: 1440 })
).toEqual({ kind: 'duration', seconds: 1440 });
expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' });
expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({
kind: 'pause',
});
expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({
kind: 'ended',
});
});
it('rejects everything else', () => {
expect(kodik.parse('garbage')).toBeNull();
expect(kodik.parse('{"broken json')).toBeNull();
expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull();
expect(kodik.parse(null)).toBeNull();
expect(kodik.parse(42)).toBeNull();
});
it('is hostname-pinned and seeks by reloading with start_from', () => {
expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe(
true
);
expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true);
expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false);
// start_from is set (overwritten) while signed params are preserved.
const seeked = kodik.reloadSeek!(
'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5',
42.9
);
expect(seeked).toContain('start_from=42');
expect(seeked).toContain('d_sign=abc');
expect(seeked).not.toContain('start_from=5');
});
});
describe('playerjs.com parse', () => {
it('parses object and JSON-string events', () => {
expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({
kind: 'time',
seconds: 12,
});
expect(
playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 }))
).toEqual({ kind: 'duration', seconds: 600 });
expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' });
});
it('does not lock on player.js-spec or unknown shapes', () => {
expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull();
expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull();
expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull();
});
it('normalizes quality, voiceover and subtitle capabilities', () => {
expect(
playerjs.parse({
event: 'qualities',
answer: [{ id: '720', name: '720p' }, '1080p'],
})
).toMatchObject({
kind: 'extraList',
control: { id: 'quality', scope: 'local' },
});
expect(
playerjs.parse({
event: 'audiotracks',
answer: { ru: 'Russian', en: 'English' },
})
).toMatchObject({
kind: 'extraList',
control: { id: 'audiotrack', scope: 'synced' },
});
expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({
kind: 'extraCurrent',
id: 'subtitle',
value: '1',
});
});
});
describe('alloha detection', () => {
it('pins known Alloha player hosts', () => {
expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true);
expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true);
expect(alloha.matchUrl!('https://example.com/player')).toBe(false);
});
});
describe('vimeo parse', () => {
it('parses timeupdate with bundled duration and the getDuration reply', () => {
expect(
vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } })
).toEqual({ kind: 'time', seconds: 10, duration: 200 });
expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({
kind: 'duration',
seconds: 200,
});
expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' });
});
it('does not lock on a playerjs.com message (has `answer`) or garbage', () => {
expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull();
expect(vimeo.parse('garbage')).toBeNull();
expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull();
});
it('matchUrl selects vimeo hosts only', () => {
expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true);
expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true);
expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false);
});
it('prepareUrl hides native chrome', () => {
const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123');
expect(p).toContain('controls=0');
expect(p).toContain('title=0');
});
});
describe('player.js (embedly spec) parse', () => {
it('parses context-tagged events', () => {
expect(
playerjsSpec.parse({
context: 'player.js',
event: 'timeupdate',
value: { seconds: 5, duration: 100 },
})
).toEqual({ kind: 'time', seconds: 5, duration: 100 });
expect(
playerjsSpec.parse({ context: 'player.js', event: 'pause' })
).toEqual({ kind: 'pause' });
expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual(
{ kind: 'hello' }
);
});
it('rejects messages without the player.js context', () => {
expect(playerjsSpec.parse({ event: 'play' })).toBeNull();
expect(playerjsSpec.parse('garbage')).toBeNull();
});
});
describe('rutube parse + matchUrl', () => {
it('parses player:* events', () => {
expect(
rutube.parse(
JSON.stringify({ type: 'player:currentTime', data: { time: 30 } })
)
).toEqual({ kind: 'time', seconds: 30 });
expect(
rutube.parse({ type: 'player:changeState', data: { state: 'playing' } })
).toEqual({ kind: 'play' });
expect(
rutube.parse({ type: 'player:durationChange', data: { duration: 90 } })
).toEqual({ kind: 'duration', seconds: 90 });
});
it('ignores foreign messages', () => {
expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull();
expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull();
expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true);
expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false);
});
});
describe('dailymotion parse + prepareUrl', () => {
it('parses classic querystring events', () => {
expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual(
{ kind: 'time', seconds: 12, duration: 240 }
);
expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' });
expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' });
expect(dailymotion.parse({ event: 'play' })).toBeNull();
});
it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => {
expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x'))
.toBe(true);
expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true);
const prepared = dailymotion.prepareUrl!(
'https://www.dailymotion.com/embed/video/x?foo=1'
);
expect(prepared).toContain('api=postMessage');
expect(prepared).toContain('controls=0');
expect(prepared).toContain('foo=1');
// idempotent
expect(dailymotion.prepareUrl!(prepared)).toBe(prepared);
});
});
describe('vk parse + prepareUrl', () => {
it('parses player_api events', () => {
expect(
vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 })
).toEqual({ kind: 'time', seconds: 8, duration: 60 });
expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({
kind: 'play',
});
expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({
kind: 'pause',
});
});
it('ignores foreign messages and injects js_api=1', () => {
expect(vk.parse({ event: 'play', answer: 1 })).toBeNull();
expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true);
expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true);
expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain(
'js_api=1'
);
});
});
describe('registry order + prepareEmbedUrl', () => {
it('generic (content-detected) set is player.js then playerjs', () => {
expect(
EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name)
).toEqual(['player.js', 'playerjs']);
});
it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => {
expect(
prepareEmbedUrl('https://www.dailymotion.com/embed/video/x')
).toContain('api=postMessage');
expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe(
'https://kodik.info/seria/1/hash/720p'
);
});
});
@@ -1,972 +0,0 @@
// Adapters for postMessage-controllable embed players in the Watch view.
//
// A generic iframe can only be driven if the player inside exposes a
// postMessage API — everything else stays view-only by browser design.
// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS):
// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec};
// commands {key:'kodik_player_api', value:{method}}.
// - vimeo: {method:'play'|...} strings; events {event:'timeupdate',
// data:{seconds,duration}}. Hostname-selected (player.vimeo.com).
// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL
// params (prepareUrl) and their command/event shapes are community-
// documented — flagged VERIFY, one-line fixes if a live embed differs.
// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co.
// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands,
// {event, answer} events.
// Shapes marked VERIFY are community-documented, not official; dev builds
// console.debug every unrecognized frame message to reverse-engineer them.
//
// Detection: for a hostname-matched player only that protocol is probed;
// otherwise the generic set is probed until one `parse` recognizes a message
// and locks the adapter. On timeout the embed is uncontrollable and the
// caller keeps today's host-driven view-only behavior.
export interface EmbedAdapter {
protocol: string;
// True for players (Kodik) driven by reloading the iframe rather than
// postMessage commands: the caller should avoid drift-reconcile churn and
// not expect pause to work.
reloadBased: boolean;
play(): void;
pause(): void;
seekMs(ms: number): void;
setVolume(v01: number): void; // 0..1
positionMs(): number;
durationMs(): number;
paused(): boolean;
extras(): PlayerExtraControl[];
setExtra(id: string, value: string): void;
destroy(): void;
}
export interface ExtraControlOption {
value: string;
label: string;
}
export interface PlayerExtraControl {
id: string;
label: string;
kind: 'select' | 'button';
options: ExtraControlOption[];
current: string | null;
scope: 'local' | 'synced';
}
// Fired only for events NOT caused by our own commands (see suppression
// below) — i.e. gestures made inside the embed UI, which the host must relay
// to the room.
export interface EmbedCallbacks {
onPlay(positionMs: number): void;
onPause(positionMs: number): void;
onSeek(positionMs: number): void;
onDurationChange(durationMs: number): void;
onEnded(): void;
onExtraControls(controls: PlayerExtraControl[]): void;
}
export type EmbedEvent =
// `duration` piggybacks on time events for players (Vimeo, player.js, DM,
// VK) that bundle it into their timeupdate payload.
| { kind: 'time'; seconds: number; duration?: number }
| { kind: 'duration'; seconds: number }
| { kind: 'play' }
| { kind: 'pause' }
| { kind: 'ended' }
| { kind: 'extraList'; control: PlayerExtraControl }
| { kind: 'extraCurrent'; id: string; value: string }
// Recognized the protocol but the event carries no state we track; enough
// to lock detection.
| { kind: 'hello' };
export interface ProtocolDef {
name: string;
// Hostname-based selection: when a URL matches, only this protocol is
// probed (skips content-based detection). Left undefined for generic
// protocols detected purely by the messages they emit (kodik, player.js).
matchUrl?(url: string): boolean;
// Inject opt-in query params the player needs before the iframe loads
// (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`).
prepareUrl?(url: string): string;
// Some players (Kodik) expose no postMessage command API — the only way to
// seek is to reload the iframe at a start offset. When present, the adapter
// seeks by setting frame.src to this URL instead of posting a command.
reloadSeek?(currentSrc: string, seconds: number): string;
probe(win: Window): void;
parse(data: unknown): EmbedEvent | null;
play(win: Window): void;
pause(win: Window): void;
seek(win: Window, seconds: number): void;
volume(win: Window, v01: number): void;
probeExtras?(win: Window): void;
setExtra?(win: Window, id: string, value: string): void;
staticExtras?(url: string): PlayerExtraControl[];
}
// Embeds are served from many mirror domains (esp. Kodik), so the target
// origin can't be pinned; we never trust incoming data beyond parsing known
// shapes into numbers.
function post(win: Window, msg: unknown) {
try {
win.postMessage(msg, '*');
} catch {
/* frame navigating/gone */
}
}
const asNumber = (v: unknown): number =>
typeof v === 'number' ? v : Number(v);
// Embed URLs are absolute, so no base is needed; guard `location` so the
// helpers also work under the node test runner.
const baseHref = (): string | undefined =>
typeof location !== 'undefined' ? location.href : undefined;
function hostOf(url: string): string {
try {
return new URL(url, baseHref()).hostname.toLowerCase();
} catch {
return '';
}
}
function isHostOrSubdomain(host: string, domain: string): boolean {
return host === domain || host.endsWith(`.${domain}`);
}
function withParams(url: string, params: Record<string, string>): string {
try {
const u = new URL(url, baseHref());
for (const [k, v] of Object.entries(params)) {
if (!u.searchParams.has(k)) u.searchParams.set(k, v);
}
return u.toString();
} catch {
return url;
}
}
// Overwrite a single query param (preserves the rest, incl. Kodik's signed
// d_sign/ref_sign params).
function setParam(url: string, key: string, value: string): string {
try {
const u = new URL(url, baseHref());
u.searchParams.set(key, value);
return u.toString();
} catch {
return url;
}
}
// Normalize an object-or-JSON-string payload into a plain object, or null.
function asObj(data: unknown): Record<string, unknown> | null {
let obj: unknown = data;
if (typeof data === 'string') {
const s = data.trim();
if (!s.startsWith('{') && !s.startsWith('[')) return null;
try {
obj = JSON.parse(s);
} catch {
return null;
}
}
return obj && typeof obj === 'object'
? (obj as Record<string, unknown>)
: null;
}
function toOptions(value: unknown): ExtraControlOption[] {
const entries = Array.isArray(value)
? value.map((item, index) => [String(index), item] as const)
: value && typeof value === 'object'
? Object.entries(value as Record<string, unknown>)
: [];
return entries.flatMap(([fallback, item]) => {
if (item && typeof item === 'object') {
const option = item as Record<string, unknown>;
const raw = option.value ?? option.id ?? option.index ?? fallback;
const label = option.label ?? option.name ?? option.title ?? raw;
return [{ value: String(raw), label: String(label) }];
}
return item == null
? []
: [{ value: fallback, label: String(item) }];
});
}
function extraControl(
id: string,
label: string,
scope: PlayerExtraControl['scope'],
options: ExtraControlOption[],
current: string | null = null
): PlayerExtraControl {
return { id, label, scope, options, current, kind: 'select' };
}
const kodik: ProtocolDef = {
name: 'kodik',
// Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always
// locks as `kodik` and never falls back to view-only.
matchUrl: (url) => {
const host = hostOf(url);
return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com']
.some((domain) => isHostOrSubdomain(host, domain));
},
// Kodik has NO postMessage command API — the only way to seek is to reload
// the iframe at a start offset (preserving its signed params). start_from
// auto-resumes playback from that second.
reloadSeek: (src, seconds) =>
setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))),
probe(win) {
// Community-documented; harmless if ignored by the player.
post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } });
post(win, { key: 'kodik_player_api', value: { method: 'get_time' } });
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.includes('kodik_player')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as { key?: unknown; value?: unknown } | null;
if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) {
return null;
}
const n = asNumber(m.value);
switch (m.key) {
case 'kodik_player_time_update':
case 'kodik_player_current_time':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'kodik_player_duration_update':
case 'kodik_player_duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'kodik_player_play':
return { kind: 'play' };
case 'kodik_player_pause':
return { kind: 'pause' };
case 'kodik_player_video_ended':
return { kind: 'ended' };
default:
// Unmapped kodik_player_* event — still unambiguously Kodik.
return { kind: 'hello' };
}
},
play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }),
pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }),
seek: (win, seconds) =>
post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }),
volume: (win, v01) =>
post(win, {
key: 'kodik_player_api',
value: { method: 'change_volume', volume: v01 },
}),
};
const playerjs: ProtocolDef = {
name: 'playerjs',
probe(win) {
post(win, { api: 'duration' });
post(win, { api: 'time' });
},
probeExtras(win) {
for (const api of ['qualities', 'audiotracks', 'subtitles']) {
post(win, { api });
}
},
staticExtras() {
return [
extraControl(
'speed',
'Speed',
'synced',
[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({
value: String(speed),
label: `${speed}×`,
})),
'1'
),
];
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.startsWith('{')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as
| { event?: unknown; answer?: unknown; context?: unknown }
| null;
if (!m || typeof m.event !== 'string') return null;
// A {context:'player.js'} message belongs to the embedly spec adapter,
// not this one.
if (m.context === 'player.js') return null;
const n = asNumber(m.answer);
// Only lock on events Playerjs actually emits — a bare {event:...}
// could belong to some other player's protocol.
switch (m.event) {
case 'qualities':
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.answer)
),
};
case 'audiotracks':
return {
kind: 'extraList',
control: extraControl(
'audiotrack',
'Voiceover',
'synced',
toOptions(m.answer)
),
};
case 'subtitles':
return {
kind: 'extraList',
control: extraControl(
'subtitle',
'Subtitles',
'local',
[
{ value: '-1', label: 'Off' },
...toOptions(m.answer),
]
),
};
case 'episodes':
return {
kind: 'extraList',
control: extraControl(
'episode',
'Episode',
'synced',
toOptions(m.answer)
),
};
case 'quality':
case 'audiotrack':
case 'subtitle':
case 'speed':
case 'episode':
return {
kind: 'extraCurrent',
id: m.event,
value: String(m.answer ?? ''),
};
case 'time':
case 'updatetime':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'end':
case 'ended':
return { kind: 'ended' };
case 'init':
case 'inited':
case 'ready':
case 'volume':
return { kind: 'hello' };
default:
return null;
}
},
play: (win) => post(win, { api: 'play' }),
pause: (win) => post(win, { api: 'pause' }),
seek: (win, seconds) => post(win, { api: 'seek', set: seconds }),
volume: (win, v01) => post(win, { api: 'volume', set: v01 }),
setExtra: (win, id, value) => {
if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) {
return;
}
post(win, { api: id, set: value });
},
};
const alloha: ProtocolDef = {
...playerjs,
name: 'alloha',
matchUrl: (url) =>
['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some(
(domain) => isHostOrSubdomain(hostOf(url), domain)
),
};
// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated
// from playerjs.com by carrying `data`, not `answer`.
const vimeo: ProtocolDef = {
name: 'vimeo',
matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)),
// Our overlay bar is the only control surface, so hide Vimeo's native chrome.
prepareUrl: (url) =>
withParams(url, {
controls: '0',
title: '0',
byline: '0',
portrait: '0',
}),
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, JSON.stringify({ method: 'addEventListener', value: ev }));
}
post(win, JSON.stringify({ method: 'getDuration' }));
},
probeExtras(win) {
post(win, JSON.stringify({ method: 'getQualities' }));
},
parse(data) {
const m = asObj(data);
if (!m) return null;
if (m.method === 'getDuration') {
const n = asNumber(m.value);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
if (m.method === 'getQualities') {
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.value)
),
};
}
if (typeof m.event !== 'string') return null;
if ('answer' in m) return null; // that's a playerjs.com message
const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(d.seconds);
const dur = asNumber(d.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
case 'finish':
return { kind: 'ended' };
case 'ready':
case 'loaded':
return { kind: 'hello' };
default:
return null; // bare {event} without vimeo markers → not ours
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) =>
post(w, JSON.stringify({ method: 'setCurrentTime', value: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })),
setExtra: (w, id, value) => {
if (id === 'quality') {
post(w, JSON.stringify({ method: 'setQuality', value }));
}
},
};
// embedly player.js SPEC (github.com/embedly/player.js): the `context` field
// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc.
const PJS = { context: 'player.js', version: '0.0.11' } as const;
const playerjsSpec: ProtocolDef = {
name: 'player.js',
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, {
...PJS,
method: 'addEventListener',
listener: `ec_${ev}`,
value: ev,
});
}
},
parse(data) {
const m = asObj(data);
if (!m || m.context !== 'player.js' || typeof m.event !== 'string') {
return null;
}
const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(v.seconds);
const dur = asNumber(v.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // any context:'player.js' event is ours
}
},
play: (w) => post(w, { ...PJS, method: 'play' }),
pause: (w) => post(w, { ...PJS, method: 'pause' }),
seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }),
volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }),
};
// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed.
const rutube: ProtocolDef = {
name: 'rutube',
matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)),
probe(win) {
// Rutube emits events only after an explicit subscribe. VERIFY payload.
post(win, JSON.stringify({ type: 'player:subscribe', data: {} }));
},
parse(data) {
const m = asObj(data);
if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) {
return null;
}
const d = (m.data ?? {}) as {
time?: unknown;
duration?: unknown;
state?: unknown;
};
switch (m.type) {
case 'player:currentTime': {
const n = asNumber(d.time);
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
}
case 'player:durationChange': {
const n = asNumber(d.duration);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
case 'player:changeState': {
const st = String(d.state);
if (st === 'playing') return { kind: 'play' };
if (st === 'paused' || st === 'stopped') return { kind: 'pause' };
if (st === 'ended') return { kind: 'ended' };
return { kind: 'hello' };
}
default:
return { kind: 'hello' }; // player:* is unambiguously Rutube
}
},
play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })),
pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })),
seek: (w, s) =>
post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })),
volume: (w, v) =>
post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })),
};
// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY;
// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed.
const dailymotion: ProtocolDef = {
name: 'dailymotion',
matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)),
// api=postMessage enables control; controls=0 + ui-* hide the native chrome
// (our overlay bar drives playback instead).
prepareUrl: (url) =>
withParams(url, {
api: 'postMessage',
controls: '0',
'ui-start-screen-info': 'false',
'ui-logo': 'false',
}),
probe() {
/* classic embed auto-emits once api=postMessage is set */
},
parse(data) {
if (typeof data !== 'string' || !data.includes('event=')) return null;
const p = new URLSearchParams(data);
const ev = p.get('event');
if (!ev) return null;
const sec = Number(p.get('time'));
const dur = Number(p.get('duration'));
switch (ev) {
case 'timeupdate':
case 'progress':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'durationchange':
return isFinite(dur) && dur > 0
? { kind: 'duration', seconds: dur }
: { kind: 'hello' };
case 'play':
case 'playing':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'video_end':
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' };
}
},
play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })),
pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })),
seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })),
volume: (w, v) =>
post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })),
};
// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes.
const vk: ProtocolDef = {
name: 'vk',
matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)),
prepareUrl: (url) => withParams(url, { js_api: '1' }),
probe(win) {
post(win, JSON.stringify({ method: 'addEventListener', event: '*' }));
},
parse(data) {
const m = asObj(data);
if (!m || m.type !== 'player_api' || typeof m.event !== 'string') {
return null;
}
const sec = asNumber(m.time ?? m.position);
const dur = asNumber(m.duration);
switch (m.event) {
case 'timeupdate':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'started':
case 'resumed':
return { kind: 'play' };
case 'paused':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // type:'player_api' is unambiguously VK
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })),
};
// Hostname-selected protocols first (they're picked by URL, never by content);
// then the generic set probed by the messages they emit — kodik first (its
// keys are unambiguous), the embedly spec before the looser playerjs.com.
// Exported for the parse unit tests.
export const EMBED_PROTOCOLS: ProtocolDef[] = [
kodik,
alloha,
vimeo,
rutube,
dailymotion,
vk,
playerjsSpec,
playerjs,
];
// Inject any opt-in params a hostname-matched player needs, before iframe.src.
export function prepareEmbedUrl(url: string): string {
const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url));
// Signed players such as Kodik depend on their own origin for scripts,
// AJAX, cookies and anti-abuse checks. Keep them on the provider origin;
// Echoion controls them only through their postMessage surface.
return p?.prepareUrl ? p.prepareUrl(url) : url;
}
const PROBE_INTERVAL_MS = 750;
// Commands are echoed back as events by the player; ignore relay callbacks
// for this long after each command we send.
const SUPPRESS_MS = 800;
// A time event this far off the extrapolated position counts as a user seek.
const SEEK_JUMP_SEC = 2.5;
// Minimum gap between reload-based (Kodik) iframe reloads.
const RELOAD_DEBOUNCE_MS = 4000;
export function detectEmbedAdapter(
frame: HTMLIFrameElement,
cb: EmbedCallbacks,
timeoutMs = 5000
): Promise<EmbedAdapter | null> {
return new Promise((resolve) => {
let locked: ProtocolDef | null = null;
// A hostname-matched player is probed alone; otherwise probe the
// generic (content-detected) set. frame.src is the prepared URL.
const matched =
EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null;
const probeSet = matched
? [matched]
: EMBED_PROTOCOLS.filter((p) => !p.matchUrl);
// Normalized player state. Embeds push time updates rather than expose
// getters, so position is the last event extrapolated by wall clock.
let lastTimeSec = 0;
let lastTimeAt = performance.now();
let durationSec = 0;
let playing = false;
let suppressUntil = 0;
const extraControls = new Map<string, PlayerExtraControl>();
const positionMs = () =>
Math.floor(
(lastTimeSec +
(playing ? (performance.now() - lastTimeAt) / 1000 : 0)) *
1000
);
const suppressed = () => performance.now() < suppressUntil;
const applyEvent = (ev: EmbedEvent) => {
switch (ev.kind) {
case 'time': {
const jumped =
Math.abs(ev.seconds - positionMs() / 1000) >
SEEK_JUMP_SEC;
// Advancing time implies playing even when the protocol
// never sends an explicit play event.
const advancing = ev.seconds > lastTimeSec + 0.05;
lastTimeSec = ev.seconds;
lastTimeAt = performance.now();
// Some protocols bundle duration into the time event.
if (
ev.duration != null &&
Math.abs(ev.duration - durationSec) > 0.5
) {
durationSec = ev.duration;
cb.onDurationChange(Math.floor(ev.duration * 1000));
}
if (jumped && !suppressed()) {
cb.onSeek(Math.floor(ev.seconds * 1000));
}
if (!playing && advancing) {
playing = true;
if (!suppressed()) cb.onPlay(positionMs());
}
break;
}
case 'duration':
if (Math.abs(ev.seconds - durationSec) > 0.5) {
durationSec = ev.seconds;
cb.onDurationChange(Math.floor(ev.seconds * 1000));
}
break;
case 'play':
if (!playing) {
playing = true;
lastTimeAt = performance.now();
if (!suppressed()) cb.onPlay(positionMs());
}
break;
case 'pause':
if (playing) {
lastTimeSec = positionMs() / 1000;
playing = false;
if (!suppressed()) cb.onPause(positionMs());
}
break;
case 'ended':
playing = false;
cb.onEnded();
break;
case 'extraList':
if (ev.control.options.length > 0) {
extraControls.set(ev.control.id, ev.control);
cb.onExtraControls([...extraControls.values()]);
}
break;
case 'extraCurrent': {
const control = extraControls.get(ev.id);
if (control && control.current !== ev.value) {
extraControls.set(ev.id, { ...control, current: ev.value });
cb.onExtraControls([...extraControls.values()]);
}
break;
}
case 'hello':
break;
}
};
// contentWindow is read live on every use: it changes when the frame
// navigates, while ev.source comparison below stays valid because the
// browsing context object is stable for the life of the element.
const win = () => frame.contentWindow;
const makeAdapter = (p: ProtocolDef): EmbedAdapter => {
for (const control of p.staticExtras?.(frame.src) ?? []) {
extraControls.set(control.id, control);
}
if (extraControls.size > 0) {
cb.onExtraControls([...extraControls.values()]);
}
const probeExtras = () => {
const current = win();
if (current) p.probeExtras?.(current);
};
probeExtras();
const extraProbeTimers = [1500, 3000].map((delay) =>
window.setTimeout(probeExtras, delay)
);
// Reload-based (Kodik) seeking: replace frame.src at a start offset,
// debounced so drift-reconcile can't spam reloads (each reload
// re-buffers and may replay an ad).
let lastReloadAt = 0;
const reloadTo = (sec: number) => {
const now = performance.now();
if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return;
lastReloadAt = now;
suppressUntil = now + SUPPRESS_MS;
lastTimeSec = Math.max(0, sec);
lastTimeAt = now;
playing = true; // start_from auto-resumes
frame.src = p.reloadSeek!(frame.src, sec);
};
return {
protocol: p.name,
reloadBased: !!p.reloadSeek,
play() {
// Commands update state optimistically so positionMs()/paused()
// reflect intent immediately — otherwise the 3s sync heartbeat
// would fight the slow embed acknowledgement.
suppressUntil = performance.now() + SUPPRESS_MS;
playing = true;
lastTimeAt = performance.now();
if (p.reloadSeek) {
// No play command — resume by reloading at the current spot.
reloadTo(lastTimeSec);
return;
}
const w = win();
if (w) p.play(w);
},
pause() {
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = positionMs() / 1000;
playing = false;
// Reload-based players (Kodik) have no pause — best-effort no-op.
if (p.reloadSeek) return;
const w = win();
if (w) p.pause(w);
},
seekMs(ms: number) {
if (p.reloadSeek) {
reloadTo(ms / 1000);
return;
}
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = ms / 1000;
lastTimeAt = performance.now();
const w = win();
if (w) p.seek(w, ms / 1000);
},
setVolume(v01: number) {
const w = win();
if (w) p.volume(w, Math.max(0, Math.min(1, v01)));
},
extras: () => [...extraControls.values()],
setExtra(id, value) {
const control = extraControls.get(id);
if (!control || !p.setExtra) return;
suppressUntil = performance.now() + 1500;
extraControls.set(id, { ...control, current: value });
cb.onExtraControls([...extraControls.values()]);
const current = win();
if (current) p.setExtra(current, id, value);
},
positionMs,
durationMs: () => Math.floor(durationSec * 1000),
paused: () => !playing,
destroy() {
window.removeEventListener('message', handler);
clearInterval(probeTimer);
clearTimeout(giveUp);
for (const timer of extraProbeTimers) clearTimeout(timer);
},
};
};
const handler = (ev: MessageEvent) => {
if (ev.source !== frame.contentWindow) return;
if (locked) {
const e = locked.parse(ev.data);
if (e) applyEvent(e);
else if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
return;
}
for (const p of probeSet) {
const e = p.parse(ev.data);
if (e) {
locked = p;
clearInterval(probeTimer);
clearTimeout(giveUp);
applyEvent(e);
resolve(makeAdapter(p));
return;
}
}
if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
};
window.addEventListener('message', handler);
const sendProbes = () => {
const w = win();
if (!w || locked) return;
for (const p of probeSet) p.probe(w);
};
// The inner player may boot slowly; keep probing until lock or timeout.
const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS);
frame.addEventListener('load', sendProbes);
sendProbes();
const giveUp = setTimeout(() => {
if (locked) return;
window.removeEventListener('message', handler);
clearInterval(probeTimer);
resolve(null);
}, timeoutMs);
});
}
-96
View File
@@ -1,96 +0,0 @@
// Emoji support for watch chat and reactions (item 16). A curated Unicode set
// across categories (dependency-free — no multi-MB emoji-data bundle), plus
// admin-managed custom image emojis served at /emoji/<name> and referenced by
// :name: shortcodes. Recently-used emoji are remembered locally.
import { Store } from './store';
import { rpc } from './rpc';
export interface CustomEmoji {
name: string;
mime: string;
}
export const emojiStore = new Store<{
custom: CustomEmoji[];
recent: string[]; // unicode chars or :shortcode:
}>({
custom: [],
recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'),
});
export async function loadCustomEmojis() {
try {
const res = await rpc.call<{ emojis?: CustomEmoji[] }>(
'GetCustomEmojis'
);
emojiStore.set({ custom: (res && res.emojis) || [] });
} catch {
/* not connected / not authed — leave empty */
}
}
export function rememberEmoji(token: string) {
const recent = [
token,
...emojiStore.get().recent.filter((r) => r !== token),
].slice(0, 24);
emojiStore.set({ recent });
localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent));
}
// Curated categories of common Unicode emoji.
export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [
{
label: 'Smileys',
emoji: [
'😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰',
'😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞',
'😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶',
'😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒',
],
},
{
label: 'Gestures',
emoji: [
'👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌',
'👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝',
],
},
{
label: 'Hearts',
emoji: [
'❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️',
'💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥',
],
},
{
label: 'Fun',
emoji: [
'🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸',
'⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️',
],
},
];
// Render a chat message: plain text with :name: custom-emoji shortcodes
// replaced by <img> tags. Returns React nodes (text is auto-escaped by React).
export function renderChatText(text: string): (string | EmojiToken)[] {
const out: (string | EmojiToken)[] = [];
const re = /:([a-z0-9_]{1,32}):/g;
const custom = new Set(emojiStore.get().custom.map((c) => c.name));
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (!custom.has(m[1])) continue;
if (m.index > last) out.push(text.slice(last, m.index));
out.push({ emojiName: m[1] });
last = m.index + m[0].length;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
export interface EmojiToken {
emojiName: string;
}
-64
View File
@@ -1,64 +0,0 @@
// Presentation helpers shared across views — ported from web/app.js.
import type { Track } from './types';
export function fmtMs(ms: number | undefined | null): string {
const s = Math.max(0, Math.floor((ms || 0) / 1000));
const m = Math.floor(s / 60);
return `${m}:${String(s % 60).padStart(2, '0')}`;
}
export function cover(seed: number): string {
const h = (seed * 47) % 360;
const h2 = (h + 40) % 360;
return `linear-gradient(135deg, hsl(${h} 55% 42%), hsl(${h2} 60% 26%))`;
}
export function seedOf(t: Track | null | undefined): number {
const s = (t && (t.id || t.title)) || '?';
let n = 0;
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
return n;
}
// Prefer source-provided artwork; otherwise derive the YouTube thumbnail from
// the video id (covers tracks stored before thumbnails were persisted).
export function thumbFor(t: Track | null | undefined): string | null {
if (!t) return null;
if (t.thumbnailUrl) return t.thumbnailUrl;
const m = (t.url || '').match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
if (m) return `https://i.ytimg.com/vi/${m[1]}/mqdefault.jpg`;
if (t.source === 1 && /^[\w-]{11}$/.test(t.id || '')) {
return `https://i.ytimg.com/vi/${t.id}/mqdefault.jpg`;
}
return null;
}
// TrackSource enum: 1 = YouTube, 6 = Yandex (see EchoionApi TrackTypes.hpp).
export function sourceInfo(
t: Track | null | undefined
): { label: string; cls: string } | null {
const url = (t && t.url) || '';
if ((t && t.source === 6) || url.includes('yandex')) {
return { label: 'YANDEX', cls: 'src-badge yandex' };
}
if ((t && t.source === 1) || url.includes('youtu')) {
return { label: 'YOUTUBE', cls: 'src-badge' };
}
return null;
}
export function avatarColor(name: string | undefined | null): string {
let n = 0;
const s = name || '';
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
const h = n % 360;
return `linear-gradient(135deg, hsl(${h} 60% 55%), hsl(${(h + 45) % 360} 55% 40%))`;
}
export function coverStyle(t: Track | null | undefined): string {
const thumb = thumbFor(t);
if (thumb) return `url("${thumb}") center/cover`;
if (t) return cover(seedOf(t));
return 'linear-gradient(135deg, #2a1a4a, #0d0d1f)';
}
-31
View File
@@ -1,31 +0,0 @@
// "Open original link" (item 18): a per-row external-link button that opens
// the track's real source page in a new tab. Prefers the canonical original
// URL (the long, expanded source page) over the shortened faumaray.ru link,
// so users land on the real source rather than a redirector. Never the
// CDN/stream URL (the DTO doesn't expose it).
import type { TrackAction } from '../components/TrackRow';
import type { Track } from './types';
import { ExternalLinkIcon } from '../components/icons';
import { t } from '../i18n';
export function originalLinkUrl(track: Track): string | null {
return track.url || track.shortenedUrl || null;
}
export function openOriginal(track: Track) {
const url = originalLinkUrl(track);
if (url) window.open(url, '_blank', 'noopener');
}
// A TrackRow action for the link, or null when the track has no openable URL.
// Rendered as a dedicated icon button (not a whole-row click, which would
// fight drag-and-drop and the other row actions).
export function originalLinkAction(track: Track): TrackAction | null {
if (!originalLinkUrl(track)) return null;
return {
icon: <ExternalLinkIcon />,
title: t('Open original link'),
onClick: () => openOriginal(track),
};
}
@@ -1,85 +0,0 @@
// Bridges playback state to the OS via the Media Session API, so hardware
// media keys and the lockscreen/notification controls (phone especially)
// drive the bot. Metadata + position follow appStore; the action handlers
// map straight onto the RPC calls the UI already uses.
import { appStore, safeCall } from './app';
import { thumbFor } from './format';
function skip() {
const id = appStore.get().identity;
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
else safeCall('VoteSkip');
}
export function initMediaSession() {
if (!('mediaSession' in navigator)) return;
const ms = navigator.mediaSession;
ms.setActionHandler('play', () => void safeCall('Resume'));
ms.setActionHandler('pause', () => void safeCall('Pause'));
ms.setActionHandler('previoustrack', () =>
void safeCall('Seek', { position: 0 })
);
ms.setActionHandler('nexttrack', () => skip());
ms.setActionHandler('seekto', (d) => {
if (typeof d.seekTime === 'number') {
safeCall('Seek', { position: Math.round(d.seekTime * 1000) });
}
});
ms.setActionHandler('seekbackward', (d) => {
const by = (d.seekOffset || 10) * 1000;
const s = appStore.get();
safeCall('Seek', { position: Math.max(0, s.positionMs - by) });
});
ms.setActionHandler('seekforward', (d) => {
const by = (d.seekOffset || 10) * 1000;
const s = appStore.get();
const dur = s.durationMs || s.positionMs + by;
safeCall('Seek', { position: Math.min(dur, s.positionMs + by) });
});
let lastKey = '';
appStore.subscribe(() => {
const s = appStore.get();
const track = s.current;
const st = s.status;
ms.playbackState = !track
? 'none'
: st && st.isPlaying && !st.isPaused
? 'playing'
: 'paused';
// Rebuild metadata only when the track changes.
const key = track ? track.url || track.title || '' : '';
if (track && key !== lastKey) {
lastKey = key;
const artwork = thumbFor(track);
ms.metadata = new MediaMetadata({
title: track.title || 'Echoion',
artist: track.artist || '',
album: 'Echoion',
artwork: artwork
? [{ src: artwork, sizes: '512x512', type: 'image/jpeg' }]
: [],
});
} else if (!track) {
lastKey = '';
ms.metadata = null;
}
// Keep the scrubber in sync where supported.
if (typeof ms.setPositionState === 'function' && s.durationMs > 0) {
try {
ms.setPositionState({
duration: s.durationMs / 1000,
position: Math.min(s.positionMs, s.durationMs) / 1000,
playbackRate: 1,
});
} catch {
/* invalid position state (e.g. position > duration) — ignore */
}
}
});
}
@@ -1,15 +0,0 @@
const DRIFT_THRESHOLD_SECONDS = 3;
const SEEK_COOLDOWN_MS = 5000;
export function shouldCorrectVideoDrift(
playerState: number,
currentSeconds: number,
targetSeconds: number,
millisSinceSeek: number
): boolean {
return (
playerState === 1 &&
millisSinceSeek >= SEEK_COOLDOWN_MS &&
Math.abs(currentSeconds - targetSeconds) > DRIFT_THRESHOLD_SECONDS
);
}
-50
View File
@@ -1,50 +0,0 @@
// Tiny hash router: keeps the active view in the URL so views are
// bookmarkable and the browser back/forward buttons work. No dependency —
// the app has a single flat set of views. The Watch view owns its own
// `#watch/<room>` hash (see watch.ts joinRoom/leaveRoom); this router only
// reads the room from it to auto-join a deep-linked room.
import { appStore, type ViewName } from './app';
import { joinRoom, watchStore } from './watch';
const VIEWS: readonly ViewName[] = [
'now',
'queue',
'search',
'library',
'stats',
'watch',
'server',
'rpc',
];
// The view named by the current hash, defaulting to `now`. Handles both
// `#queue` and the watch form `#watch/<room>`.
export function viewFromHash(): ViewName {
const raw = location.hash.replace(/^#\/?/, '');
const base = raw.split(/[/?]/)[0];
return (VIEWS as readonly string[]).includes(base)
? (base as ViewName)
: 'now';
}
function roomFromHash(): string | null {
const m = location.hash.match(/^#watch\/([\w-]{1,48})/);
return m ? m[1] : null;
}
export function initRouter() {
// Initial view comes from the hash (refresh / shared link).
appStore.set({ view: viewFromHash() });
window.addEventListener('hashchange', () => {
const view = viewFromHash();
appStore.set({ view });
// Auto-join a room that appears in the hash (pasted link, or
// back/forward onto a different room). Leaving is always explicit.
if (view === 'watch') {
const room = roomFromHash();
if (room && room !== watchStore.get().room) joinRoom(room);
}
});
}
-142
View File
@@ -1,142 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { RpcClient } from './rpc';
// A minimal fake WebSocket that records sent frames and lets the test push
// server frames back. Installed as the global before each RpcClient is made.
class FakeWebSocket {
static OPEN = 1;
static instances: FakeWebSocket[] = [];
readyState = FakeWebSocket.OPEN;
sent: string[] = [];
onopen: (() => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null;
constructor(public url: string) {
FakeWebSocket.instances.push(this);
queueMicrotask(() => this.onopen && this.onopen());
}
send(data: string) {
this.sent.push(data);
}
close() {
this.readyState = 3;
this.onclose && this.onclose();
}
receive(obj: unknown) {
this.onmessage && this.onmessage({ data: JSON.stringify(obj) });
}
}
function installFakes() {
FakeWebSocket.instances = [];
vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);
// /config.json → same-origin /rpc bridge.
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ json: async () => ({ rpcUrl: '/rpc' }) }))
);
vi.stubGlobal('location', {
protocol: 'http:',
host: 'bot.local',
hostname: 'bot.local',
});
}
afterEach(() => vi.unstubAllGlobals());
describe('RpcClient wire contract', () => {
it('encodes method as the enum name and params as a JSON string', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.call('Seek', { position: 4200 });
expect(ws.sent).toHaveLength(1);
const frame = JSON.parse(ws.sent[0]);
expect(frame.method).toBe('Seek');
// params must be a JSON-encoded *string*, not a nested object.
expect(typeof frame.params).toBe('string');
expect(JSON.parse(frame.params)).toEqual({ position: 4200 });
expect(frame.id).toBe(1);
});
it('attaches the auth token once set', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.token = 'tok-abc';
rpc.call('GetStatus');
const frame = JSON.parse(ws.sent[0]);
expect(frame.authToken).toBe('tok-abc');
});
it('resolves a call by requestId and JSON-decodes the result string', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const p = rpc.call('GetStatus');
const frame = JSON.parse(ws.sent[0]);
ws.receive({
requestId: frame.id,
success: true,
result: JSON.stringify({ isPlaying: true, volume: 0.5 }),
});
await expect(p).resolves.toEqual({ isPlaying: true, volume: 0.5 });
});
it('rejects with the decoded error payload', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const p = rpc.call('Skip');
const frame = JSON.parse(ws.sent[0]);
ws.receive({
requestId: frame.id,
success: false,
error: JSON.stringify({ code: 7, message: 'DJ required' }),
});
await expect(p).rejects.toMatchObject({
code: 7,
message: 'DJ required',
});
});
it('dispatches notifications with the data string decoded', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
rpc.on('playback.position', (d) => seen.push(d));
ws.receive({
event: 'playback.position',
data: JSON.stringify({ position: 1000, duration: 200000 }),
});
expect(seen).toEqual([{ position: 1000, duration: 200000 }]);
});
it('fires the wildcard listener with event name and data', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: Array<[unknown, unknown]> = [];
rpc.on('*', (event, data) => seen.push([event, data]));
ws.receive({
event: 'queue.updated',
data: JSON.stringify({ size: 3 }),
});
expect(seen).toEqual([['queue.updated', { size: 3 }]]);
});
});
-242
View File
@@ -1,242 +0,0 @@
// Browser RPC client for the Echoion RPC server — TypeScript port of the
// original web/rpc.js. The web UI is a desktop-style client: it connects
// straight to the RPC WebSocket and speaks the exact same JSON protocol the
// Qt desktop client uses.
//
// Wire contract (must match the server — do not "clean up"):
// - request.method is the RpcMethod enum *name* (e.g. "Play").
// - request.params is a JSON-encoded *string*, not a nested object.
// - responses are correlated by requestId; result/error are JSON strings.
// - notifications carry { event, data } where data is a JSON string.
export type RpcConnectionState = 'connected' | 'disconnected' | 'error';
export interface RpcError {
code?: number;
message: string;
source?: string;
}
// Method names mirroring EchoionApi RpcTypes.hpp; the wire carries the name.
export type RpcMethodName =
| 'Authenticate'
| 'AuthenticateByAddress'
| 'Logout'
| 'Play'
| 'Pause'
| 'Resume'
| 'Stop'
| 'Skip'
| 'Seek'
| 'SetVolume'
| 'ToggleShuffle'
| 'ToggleRepeat'
| 'ToggleAutoplay'
| 'ShuffleQueue'
| 'QueueTrack'
| 'RemoveFromQueue'
| 'ClearQueue'
| 'GetQueue'
| 'MoveInQueue'
| 'SearchTracks'
| 'GetCurrentTrack'
| 'GetStatus'
| 'GetServerInfo'
| 'GetPlaylist'
| 'GetPlaylists'
| 'SavePlaylist'
| 'LoadPlaylist'
| 'DeletePlaylist'
| 'GetHistory'
| 'GetStats'
| 'GetLyrics'
| 'GetFavorites'
| 'AddFavorite'
| 'RemoveFavorite'
| 'VoteSkip'
| 'Announce'
| 'GetAggregateStats'
| 'ReloadConfig'
| 'RestartWebInterface'
| 'ManageUsers'
| 'GetAuditLog'
| 'GetUserPrefs'
| 'SetUserPrefs'
| 'GetCustomEmojis'
| 'AddCustomEmoji'
| 'RemoveCustomEmoji';
type Pending = {
resolve: (value: unknown) => void;
reject: (err: RpcError) => void;
};
export class RpcClient {
private ws: WebSocket | null = null;
private nextId = 1;
private pending = new Map<number, Pending>();
private listeners = new Map<string, Array<(...args: unknown[]) => void>>();
token: string | null = null;
onState: (s: RpcConnectionState) => void = () => {};
// Fired after an automatic reconnect succeeds so the app can
// re-authenticate and refresh its state.
onReconnected: () => void = () => {};
private wantReconnect = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelay = 2000;
async connect(): Promise<void> {
let cfg: { rpcUrl?: string; rpcPort?: number } = {};
try {
cfg = await fetch('/config.json').then((r) => r.json());
} catch {
/* fall back to derived URL below */
}
// A path-only rpcUrl (default "/rpc") means the same-origin bridge on
// the web server; absolute URLs and the bare-port fallback still work.
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
let url: string;
if (cfg.rpcUrl && cfg.rpcUrl.startsWith('/')) {
url = `${wsProto}://${location.host}${cfg.rpcUrl}`;
} else if (cfg.rpcUrl && cfg.rpcUrl.length) {
url = cfg.rpcUrl;
} else {
url = `ws://${location.hostname}:${cfg.rpcPort || 8765}`;
}
return new Promise((resolve, reject) => {
this.ws = new WebSocket(url);
this.ws.onopen = () => {
this.wantReconnect = true;
this.reconnectDelay = 2000;
this.onState('connected');
resolve();
};
this.ws.onclose = () => {
this.onState('disconnected');
this.failAll('Connection closed');
this.scheduleReconnect();
};
this.ws.onerror = () => {
this.onState('error');
reject(new Error('WebSocket error'));
};
this.ws.onmessage = (ev) => this.onMessage(String(ev.data));
});
}
// Reconnect with backoff after an unexpected close. Only armed once a
// connection has succeeded; an explicit disconnect() disarms it.
private scheduleReconnect() {
if (!this.wantReconnect || this.reconnectTimer) return;
const delay = this.reconnectDelay;
this.reconnectDelay = Math.min(this.reconnectDelay * 2, 15000);
this.reconnectTimer = setTimeout(async () => {
this.reconnectTimer = null;
try {
await this.connect();
this.onReconnected();
} catch {
this.scheduleReconnect();
}
}, delay);
}
disconnect() {
this.wantReconnect = false;
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
get connected(): boolean {
return !!this.ws && this.ws.readyState === WebSocket.OPEN;
}
private decode(s: unknown): unknown {
if (s == null) return null;
if (typeof s !== 'string') return s;
try {
return JSON.parse(s);
} catch {
return s;
}
}
private onMessage(raw: string) {
let msg: Record<string, unknown>;
try {
msg = JSON.parse(raw);
} catch {
return;
}
if ('requestId' in msg) {
const p = this.pending.get(msg.requestId as number);
if (!p) return;
this.pending.delete(msg.requestId as number);
if (msg.success) {
p.resolve(this.decode(msg.result));
} else {
p.reject(
(this.decode(msg.error) as RpcError) || {
message: 'RPC error',
}
);
}
} else if ('event' in msg) {
const data = this.decode(msg.data);
const event = msg.event as string;
(this.listeners.get(event) || []).forEach((cb) => cb(data));
(this.listeners.get('*') || []).forEach((cb) => cb(event, data));
}
}
private failAll(message: string) {
for (const [, p] of this.pending) p.reject({ message });
this.pending.clear();
}
call<T = unknown>(
method: RpcMethodName,
params: Record<string, unknown> = {}
): Promise<T> {
return new Promise((resolve, reject) => {
if (!this.connected || !this.ws) {
reject({ message: 'Not connected' });
return;
}
const id = this.nextId++;
const req: Record<string, unknown> = {
id,
method,
params: JSON.stringify(params),
};
if (this.token) req.authToken = this.token;
this.pending.set(id, {
resolve: resolve as (v: unknown) => void,
reject,
});
this.ws.send(JSON.stringify(req));
});
}
on(event: string, cb: (...args: unknown[]) => void) {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event)!.push(cb);
}
authenticate(token: string) {
this.token = token;
return this.call('Authenticate', { token });
}
requestToken(nickname: string) {
return this.call('Authenticate', { nickname });
}
}
// Singleton shared by the whole app (mirrors the vanilla `const rpc`).
export const rpc = new RpcClient();
-111
View File
@@ -1,111 +0,0 @@
// Global keyboard shortcuts for desktop control. Ignored while typing in a
// field, and while any modifier is held (so browser/OS chords still work).
import { appStore, safeCall, showView } from './app';
// List shown in the "?" cheat-sheet overlay. English source strings; the
// overlay translates the labels.
export const SHORTCUTS: Array<{ keys: string; label: string }> = [
{ keys: 'Space', label: 'Play / pause' },
{ keys: '← / →', label: 'Seek 5s' },
{ keys: '↑ / ↓', label: 'Volume' },
{ keys: 'N', label: 'Skip / vote skip' },
{ keys: '/', label: 'Focus search' },
{ keys: '?', label: 'This help' },
];
function isTyping(): boolean {
const el = document.activeElement as HTMLElement | null;
if (!el) return false;
const tag = el.tagName;
return (
tag === 'INPUT' ||
tag === 'TEXTAREA' ||
tag === 'SELECT' ||
el.isContentEditable
);
}
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
function seekBy(deltaSec: number) {
const s = appStore.get();
const dur = s.durationMs || 0;
if (!dur) return;
const pos = Math.max(0, Math.min(dur, s.positionMs + deltaSec * 1000));
safeCall('Seek', { position: Math.round(pos) });
}
function volumeBy(deltaPct: number) {
const st = appStore.get().status || {};
const cur = Math.round((st.volume ?? 0.5) * 100);
const next = Math.max(0, Math.min(100, cur + deltaPct));
safeCall('SetVolume', { volume: next / 100 });
}
function skip() {
const id = appStore.get().identity;
// Mirror the Now view: DJ/admin force-skip, everyone else votes.
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
else safeCall('VoteSkip');
}
export function initShortcuts() {
window.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (isTyping()) {
if (e.key === 'Escape') {
(document.activeElement as HTMLElement | null)?.blur();
}
return;
}
switch (e.key) {
case ' ':
e.preventDefault();
void togglePlay();
break;
case 'ArrowLeft':
seekBy(-5);
break;
case 'ArrowRight':
seekBy(5);
break;
case 'ArrowUp':
e.preventDefault();
volumeBy(5);
break;
case 'ArrowDown':
e.preventDefault();
volumeBy(-5);
break;
case 'n':
case 'N':
skip();
break;
case '/':
e.preventDefault();
showView('search');
setTimeout(() => {
document
.querySelector<HTMLInputElement>('#view-search input')
?.focus();
}, 50);
break;
case '?':
appStore.set({ shortcutsOpen: !appStore.get().shortcutsOpen });
break;
case 'Escape': {
const s = appStore.get();
if (s.shortcutsOpen) appStore.set({ shortcutsOpen: false });
else if (s.sidebarOpen) appStore.set({ sidebarOpen: false });
break;
}
default:
break;
}
});
}
-32
View File
@@ -1,32 +0,0 @@
// Minimal external store + useSyncExternalStore hook. One immutable snapshot
// for the whole app state (the vanilla UI re-rendered everything on any
// refresh anyway, so per-field granularity buys nothing at this scale).
import { useSyncExternalStore } from 'react';
export class Store<T> {
private state: T;
private listeners = new Set<() => void>();
constructor(initial: T) {
this.state = initial;
}
get(): T {
return this.state;
}
set(partial: Partial<T>) {
this.state = { ...this.state, ...partial };
this.listeners.forEach((l) => l());
}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
}
export function useStore<T>(store: Store<T>): T {
return useSyncExternalStore(store.subscribe, () => store.get());
}
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { renderTsMarkup } from './tsMarkup';
const html = (src: string) => renderToStaticMarkup(<>{renderTsMarkup(src)}</>);
describe('renderTsMarkup', () => {
it('renders markdown bold/italic/code', () => {
expect(html('**bold** and *italic* and `code`')).toBe(
'<p><strong>bold</strong> and <em>italic</em> and <code>code</code></p>'
);
});
it('renders BBCode bold/underline/color', () => {
expect(html('[b]x[/b] [u]y[/u] [color=#f00]z[/color]')).toBe(
'<p><strong>x</strong> <u>y</u> <span style="color:#f00">z</span></p>'
);
});
it('renders markdown and BBCode links with safe attributes', () => {
expect(html('[site](https://example.com)')).toBe(
'<p><a href="https://example.com" target="_blank" rel="noopener noreferrer">site</a></p>'
);
expect(html('[url]https://example.com[/url]')).toBe(
'<p><a href="https://example.com" target="_blank" rel="noopener noreferrer">https://example.com</a></p>'
);
});
it('escapes raw HTML (no injection)', () => {
// React escapes text nodes; the <img> is rendered as literal text.
const out = html('<img src=x onerror=alert(1)>');
expect(out).not.toContain('<img');
expect(out).toContain('&lt;img');
});
it('renders headers and blockquotes', () => {
expect(html('# Title')).toBe('<h3>Title</h3>');
expect(html('> quoted')).toBe(
'<blockquote><p>quoted</p></blockquote>'
);
});
it('renders the TS6 collapsible details container', () => {
const out = html(':::details Info\nbody\n:::');
expect(out).toContain('<details open="">');
expect(out).toContain('<summary>Info</summary>');
expect(out).toContain('<p>body</p>');
});
});
-176
View File
@@ -1,176 +0,0 @@
// Renders the TeamSpeak-6 markdown + BBCode subset the bot's replies use so
// the announce composer (item 14) can preview exactly what subscribers see.
// Security: text is escaped first (React escapes by default since we return
// elements, never dangerouslySetInnerHTML), so untrusted markup can't inject
// HTML — only the recognized tags below produce formatting.
import type { ReactNode } from 'react';
// Inline pass: **bold**, *italic* / _italic_, ~~strike~~, `code`, [text](url),
// and the BBCode equivalents [b] [i] [u] [s] [url] [color=…]. Applied to one
// line's worth of text.
function renderInline(text: string, keyBase: string): ReactNode[] {
// Ordered so the first matching rule wins at each position.
const rules: Array<{
re: RegExp;
render: (m: RegExpExecArray, key: string) => ReactNode;
}> = [
{
re: /\*\*([^*]+)\*\*/,
render: (m, k) => <strong key={k}>{renderInline(m[1], k)}</strong>,
},
{
re: /\[b\]([\s\S]*?)\[\/b\]/i,
render: (m, k) => <strong key={k}>{renderInline(m[1], k)}</strong>,
},
{
re: /(?:\*([^*]+)\*|_([^_]+)_)/,
render: (m, k) => (
<em key={k}>{renderInline(m[1] ?? m[2], k)}</em>
),
},
{
re: /\[i\]([\s\S]*?)\[\/i\]/i,
render: (m, k) => <em key={k}>{renderInline(m[1], k)}</em>,
},
{
re: /\[u\]([\s\S]*?)\[\/u\]/i,
render: (m, k) => <u key={k}>{renderInline(m[1], k)}</u>,
},
{
re: /(?:~~([^~]+)~~|\[s\]([\s\S]*?)\[\/s\])/i,
render: (m, k) => <s key={k}>{renderInline(m[1] ?? m[2], k)}</s>,
},
{
re: /`([^`]+)`/,
render: (m, k) => <code key={k}>{m[1]}</code>,
},
{
re: /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/,
render: (m, k) => (
<a key={k} href={m[2]} target="_blank" rel="noopener noreferrer">
{m[1]}
</a>
),
},
{
re: /\[url\]([\s\S]*?)\[\/url\]/i,
render: (m, k) => (
<a key={k} href={m[1]} target="_blank" rel="noopener noreferrer">
{m[1]}
</a>
),
},
{
re: /\[url=([^\]]+)\]([\s\S]*?)\[\/url\]/i,
render: (m, k) => (
<a key={k} href={m[1]} target="_blank" rel="noopener noreferrer">
{renderInline(m[2], k)}
</a>
),
},
{
re: /\[color=([#\w]+)\]([\s\S]*?)\[\/color\]/i,
render: (m, k) => (
<span key={k} style={{ color: m[1] }}>
{renderInline(m[2], k)}
</span>
),
},
];
// Find the earliest match across all rules, emit the text before it, the
// rendered node, then recurse on the remainder.
let best: { index: number; length: number; node: ReactNode } | null = null;
let counter = 0;
for (const rule of rules) {
const m = rule.re.exec(text);
if (m && (best === null || m.index < best.index)) {
best = {
index: m.index,
length: m[0].length,
node: rule.render(m, `${keyBase}-${counter++}`),
};
}
}
if (!best) return [text];
const before = text.slice(0, best.index);
const after = text.slice(best.index + best.length);
return [
...(before ? [before] : []),
best.node,
...renderInline(after, `${keyBase}-r`),
];
}
// Block pass: headers (#, ##, ###), blockquotes (>), and the TS6 collapsible
// container (:::details Title … :::). Everything else is a paragraph line.
export function renderTsMarkup(source: string): ReactNode {
const lines = source.split('\n');
const blocks: ReactNode[] = [];
let i = 0;
let key = 0;
while (i < lines.length) {
const line = lines[i];
const details = /^:::details\s+(.*)$/.exec(line.trim());
if (details) {
const inner: string[] = [];
i++;
while (i < lines.length && lines[i].trim() !== ':::') {
inner.push(lines[i]);
i++;
}
i++; // skip closing :::
blocks.push(
<details key={key++} open>
<summary>{renderInline(details[1], `s${key}`)}</summary>
{renderTsMarkup(inner.join('\n'))}
</details>
);
continue;
}
const header = /^(#{1,3})\s+(.*)$/.exec(line);
if (header) {
const level = header[1].length;
const content = renderInline(header[2], `h${key}`);
blocks.push(
level === 1 ? (
<h3 key={key++}>{content}</h3>
) : level === 2 ? (
<h4 key={key++}>{content}</h4>
) : (
<h5 key={key++}>{content}</h5>
)
);
i++;
continue;
}
if (/^>\s?/.test(line)) {
const quote: string[] = [];
while (i < lines.length && /^>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^>\s?/, ''));
i++;
}
blocks.push(
<blockquote key={key++}>
{renderTsMarkup(quote.join('\n'))}
</blockquote>
);
continue;
}
if (line.trim() === '') {
i++;
continue;
}
blocks.push(<p key={key++}>{renderInline(line, `p${key}`)}</p>);
i++;
}
return <>{blocks}</>;
}
-107
View File
@@ -1,107 +0,0 @@
// Shapes of the RPC payloads the UI consumes (subset of the server DTOs;
// fields the UI does not read are omitted).
export interface Track {
id?: string;
title?: string;
artist?: string;
url?: string; // originalUrl (play-by-url)
shortenedUrl?: string; // faumaray.ru short link, preferred for opening
thumbnailUrl?: string;
duration?: number; // ms
source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex
}
export interface QueueEntry {
queueId: number;
track: Track;
isPlaying?: boolean;
addedBy?: string;
}
export interface Status {
isPlaying?: boolean;
isPaused?: boolean;
shuffle?: boolean;
repeat?: boolean;
autoplay?: boolean;
volume?: number;
skipVotes?: number;
skipVotesNeeded?: number;
skipVoted?: boolean;
}
export interface Identity {
uid?: string;
nickname?: string;
isAdmin?: boolean;
isDj?: boolean;
token?: string;
message?: string;
}
export interface ServerInfo {
version?: string;
uptimeSeconds?: number;
onlineSubscribers?: number;
onlineSubscriberNames?: string[];
// Parallel to onlineSubscriberNames (same order): TeamSpeak uids so the
// "Listening now" card can fetch each listener's avatar.
onlineSubscriberUids?: string[];
}
export interface AggregateStats {
tracksToday: number;
playsTotal: number;
listeningMsToday: number;
queueAdditionsToday: number;
skipsToday: number;
skipsTotal: number;
topRequesters: Array<{ uid?: string; nickname: string; count: number }>;
youtubeCount: number;
yandexCount: number;
otherCount: number;
}
export interface Subscriber {
uid: string;
nickname?: string;
online?: boolean;
}
export interface Playlist {
id: string;
name: string;
trackCount: number;
}
// GetPlaylist response — a playlist's full track list (Dto::PlaylistContents).
export interface PlaylistContents {
id: string;
name: string;
description?: string;
tracks: Track[];
}
// GetAuditLog response entry (Dto::AuditEntryDto). `method` is the numeric
// RpcMethod enum value; map it to a name with lib/auditMethods.
export interface AuditEntry {
clientId: number;
method: number;
timestamp: number; // unix seconds
}
// GetLyrics response (Dto::LyricsResponse).
export interface LyricsLine {
ms: number; // offset from track start
text: string;
}
export interface LyricsResult {
found: boolean;
plain: string;
synced: LyricsLine[];
source?: string;
title?: string;
artist?: string;
}
@@ -1,53 +0,0 @@
import { useEffect, useState, type RefObject } from 'react';
// Auto-hides the Watch player's overlay controls (and the mouse cursor) after
// `idleMs` of no input while a video is PLAYING, and reveals them instantly on
// any input — like a regular video player, in both windowed and fullscreen.
// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is
// open) is left to CSS (:hover / :focus-within); this hook only owns the idle
// timeout and the "always visible while paused" rule. Returns the hidden flag.
export function useControlsAutoHide(
shellRef: RefObject<HTMLElement | null>,
opts: { playing: boolean; enabled?: boolean; idleMs?: number }
): boolean {
const { playing, enabled = true, idleMs = 3000 } = opts;
const [hidden, setHidden] = useState(false);
useEffect(() => {
const shell = shellRef.current;
// Paused, disabled, or no element: always show, no timer.
if (!shell || !enabled || !playing) {
setHidden(false);
return;
}
let timer: number | undefined;
const arm = () => {
if (timer) window.clearTimeout(timer);
timer = window.setTimeout(() => setHidden(true), idleMs);
};
const reveal = () => {
setHidden(false); // React bails when already false → no churn
arm();
};
const events = [
'mousemove',
'pointerdown',
'touchstart',
'keydown',
'focusin',
] as const;
for (const e of events) {
shell.addEventListener(e, reveal, { passive: true });
}
// Entering/leaving fullscreen counts as activity.
document.addEventListener('fullscreenchange', reveal);
arm();
return () => {
if (timer) window.clearTimeout(timer);
for (const e of events) shell.removeEventListener(e, reveal);
document.removeEventListener('fullscreenchange', reveal);
};
}, [shellRef, playing, enabled, idleMs]);
return hidden;
}
File diff suppressed because it is too large. Load diff
-75
View File
@@ -1,75 +0,0 @@
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
// Playing video preview use it; the script is injected once and callers await
// the same readiness promise.
//
// Console-error triage for the YouTube embeds (as seen in production behind
// the reverse proxy):
// - "Failed to execute 'postMessage' … target origin ('https://www.youtube.com')
// does not match the recipient window's origin" — the IFrame API guesses the
// embedder when no explicit origin is passed; fixed by youtubeEmbedVars().
// - "__Secure-YEC has been rejected … SameSite" — YouTube setting its own
// third-party cookie inside the iframe; the youtube-nocookie.com host
// reduces this noise but cannot eliminate it.
// - "Attempt to postMessage on disconnected port" — fires when an iframe is
// torn down mid-message (source switch, room leave); harmless.
// Privacy-enhanced embed host (see cookie note above). Pass as the
// (undeclared in @types/youtube) top-level `host` option of YT.Player.
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
// playerVars every embed must pass: native controls stay hidden (the custom
// bar / sync logic owns playback), and enablejsapi + origin keep the API's
// postMessage channel bound to this page's real origin.
export function youtubeEmbedVars(
extra?: Record<string, string | number>
): YT.PlayerVars {
return {
rel: 0,
modestbranding: 1,
controls: 0,
disablekb: 1,
iv_load_policy: 3,
enablejsapi: 1,
origin: location.origin,
widget_referrer: location.origin,
...extra,
} as YT.PlayerVars;
}
let promise: Promise<void> | null = null;
export function loadYouTubeApi(): Promise<void> {
if (promise) return promise;
promise = new Promise((resolve) => {
const w = window as unknown as {
YT?: typeof YT;
onYouTubeIframeAPIReady?: () => void;
};
if (w.YT && w.YT.Player) {
resolve();
return;
}
const prev = w.onYouTubeIframeAPIReady;
w.onYouTubeIframeAPIReady = () => {
prev?.();
resolve();
};
if (!document.querySelector('script[data-yt-iframe-api]')) {
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
tag.dataset.ytIframeApi = '1';
document.head.appendChild(tag);
}
});
return promise;
}
// Extract an 11-char YouTube video id from a watch/share/embed URL or a bare
// id, or null when the URL is not YouTube.
export function youtubeIdFromUrl(url: string | undefined | null): string | null {
if (!url) return null;
const m = url.match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
if (m) return m[1];
if (/^[\w-]{11}$/.test(url)) return url;
return null;
}
-22
View File
@@ -1,22 +0,0 @@
import { createRoot } from 'react-dom/client';
import { App } from './App';
import './styles/style.css';
// Human-readable fingerprint for deployment/debugging. Vite's filename hash
// can legitimately match an older backup when the emitted code becomes
// byte-identical after a revert, so expose an explicit release identity too.
export const WEB_BUILD_ID = '2026.07.10-player-fix.3';
document.documentElement.dataset.echoionBuild = WEB_BUILD_ID;
console.info(`[Echoion] web build ${WEB_BUILD_ID}`);
createRoot(document.getElementById('root')!).render(<App />);
// Register the PWA service worker in production (installable + offline shell).
// Skipped on the vite dev server so hot-reload isn't shadowed by the cache.
if ('serviceWorker' in navigator && import.meta.env.PROD) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').catch(() => {
/* SW is a progressive enhancement — ignore failures */
});
});
}
-786
View File
@@ -1,786 +0,0 @@
/* Echoion web UI — dark violet design (see Echoion.html mockup). */
:root {
--bg: #0a0a0e;
--panel: rgba(255, 255, 255, 0.03);
--panel-2: rgba(255, 255, 255, 0.05);
--line: rgba(255, 255, 255, 0.07);
--text: #f3f3f6;
--text-2: #e8e8ee;
--muted: #9a9aa8;
--muted-2: #8a8a98;
--faint: #6a6a78;
--accent: #7c5cff;
--accent-soft: rgba(124, 92, 255, 0.16);
--accent-text: #b5a3ff;
--accent-2: #8f72ff;
--green: #3fd07a;
--green-text: #5fe094;
--red: #ff5c5c;
--red-text: #ff8080;
--yellow: #ffcf4a;
--yellow-text: #ffd977;
--pink: #ff6b9d;
--radius: 14px;
--font-head: 'Space Grotesk', sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, monospace;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
min-height: 100vh;
}
button { font-family: inherit; color: inherit; }
input {
font-family: inherit;
color: var(--text);
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 14px;
outline: none;
font-size: 13.5px;
}
input:focus { border-color: rgba(124, 92, 255, 0.45); }
.mono { font-family: var(--font-mono); font-size: 12.5px; }
.muted { color: var(--muted-2); font-weight: 500; }
h1, h2, h3 { font-family: var(--font-head); }
h2 { font-size: 17px; font-weight: 600; }
h3 { font-size: 15px; font-weight: 600; }
#app { display: flex; min-height: 100vh; }
/* ── Sidebar ──────────────────────────────────────────────────────────── */
.sidebar {
width: 236px;
flex: none;
display: flex;
flex-direction: column;
gap: 18px;
padding: 22px 14px;
border-right: 1px solid var(--line);
position: sticky;
top: 0;
height: 100vh;
}
.brand { display: flex; align-items: center; gap: 12px; padding: 0 6px; }
.brand-icon {
width: 42px; height: 42px; border-radius: 13px;
background: linear-gradient(135deg, #7c5cff, #5b3fd6);
display: flex; align-items: center; justify-content: center;
box-shadow: 0 4px 18px rgba(124, 92, 255, 0.35);
}
.brand-name { font-family: var(--font-head); font-size: 19px; font-weight: 700; letter-spacing: -0.02em; }
.brand-sub { font-size: 10px; font-weight: 600; letter-spacing: 2.4px; color: var(--faint); }
.nav { display: flex; flex-direction: column; gap: 3px; flex: 1; }
.nav-item {
display: flex; align-items: center; gap: 12px;
padding: 10px 12px;
border: none; border-radius: 10px;
background: transparent; color: var(--muted);
font-weight: 600; font-size: 13.5px;
cursor: pointer; width: 100%;
transition: background 0.12s;
text-align: left;
}
.nav-item:hover { background: rgba(255, 255, 255, 0.04); }
.nav-item.active {
background: var(--accent-soft);
color: #fff;
box-shadow: inset 3px 0 0 var(--accent);
}
.nav-ico {
width: 18px; color: inherit; opacity: 0.9;
display: inline-flex; align-items: center; justify-content: center;
font-size: 15px; flex: none;
}
.nav-badge {
margin-left: auto;
font-family: var(--font-mono); font-size: 11px; font-weight: 700;
color: var(--accent-text); background: var(--accent-soft);
padding: 2px 8px; border-radius: 8px;
}
.live-dot, .dot {
width: 8px; height: 8px; border-radius: 50%;
display: inline-block; flex: none;
}
.live-dot { margin-left: auto; background: var(--red); animation: ech-pulse 1.6s infinite; }
.dot-green { background: var(--green); }
@keyframes ech-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
.sidebar-foot { display: flex; flex-direction: column; gap: 10px; font-size: 12.5px; }
.conn-row { display: flex; align-items: center; gap: 8px; color: var(--muted-2); padding: 0 6px; }
.conn-dot { width: 8px; height: 8px; border-radius: 50%; background: #5a5a68; }
.conn-dot.on { background: var(--green); }
.conn-dot.err { background: var(--red); }
#authBox { display: flex; flex-direction: column; gap: 8px; }
#authBox input { width: 100%; }
.whoami { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 0 6px; }
.admin-chip {
font-size: 10px; font-weight: 700; letter-spacing: 0.04em;
color: var(--yellow-text); background: rgba(255, 207, 74, 0.12);
padding: 2px 7px; border-radius: 6px;
}
/* ── Main / header ────────────────────────────────────────────────────── */
.main { flex: 1; padding: 26px 30px 90px; min-width: 0; }
.header { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 22px; }
.header h1 { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; }
.header-sub { color: var(--muted-2); font-size: 13px; margin-top: 3px; }
.header-right { display: flex; gap: 10px; align-items: center; }
.pill {
display: inline-flex; align-items: center; gap: 7px;
padding: 7px 13px; border-radius: 10px;
background: var(--panel-2); font-size: 12.5px; font-weight: 600;
color: var(--text-2);
}
.pill-green { background: rgba(63, 208, 122, 0.12); color: var(--green-text); }
.pill-yellow { background: rgba(255, 207, 74, 0.12); color: var(--yellow-text); }
/* ── Cards / lists ────────────────────────────────────────────────────── */
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 18px;
margin-bottom: 18px;
}
.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; gap: 10px; }
.row-gap { display: flex; gap: 8px; align-items: center; }
.col { display: flex; flex-direction: column; min-width: 0; }
.link { background: none; border: none; color: var(--accent-text); cursor: pointer; font-weight: 600; font-size: 12.5px; }
/* Keyboard focus ring for every interactive control; pointer clicks don't
show it. */
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button:focus:not(:focus-visible),
select:focus:not(:focus-visible) { outline: none; }
/* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons
and never shrink in flex rows. */
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .room-chip svg, .link svg {
vertical-align: -0.125em; flex: none;
}
.btn {
padding: 9px 16px;
border-radius: 10px;
border: 1px solid transparent;
cursor: pointer;
font-weight: 600; font-size: 13px;
background: rgba(255, 255, 255, 0.05);
color: var(--text-2);
}
.btn:hover { background: rgba(255, 255, 255, 0.08); }
.btn-accent { background: var(--accent); color: #fff; }
.btn-accent:hover { background: #8b6dff; }
.btn-ghost { background: transparent; border-color: var(--line); color: var(--muted); }
.btn-ghost:hover { color: var(--text-2); background: rgba(255, 255, 255, 0.04); }
.btn-danger-ghost { background: transparent; border-color: rgba(255, 92, 92, 0.3); color: var(--red-text); }
.btn-danger-ghost:hover { background: rgba(255, 92, 92, 0.1); }
/* Leave-room button: prominent but not alarming; pushed to the right of the
room header so it reads as the primary in-room action. */
.btn-leave {
margin-left: auto;
display: inline-flex; align-items: center; gap: 6px;
background: rgba(255, 92, 92, 0.12);
border-color: rgba(255, 92, 92, 0.35);
color: var(--red-text);
font-weight: 700;
}
.btn-leave:hover {
background: rgba(255, 92, 92, 0.22);
border-color: rgba(255, 92, 92, 0.6);
}
.src-badge {
font-size: 10px; font-weight: 700; letter-spacing: 0.03em;
padding: 3px 8px; border-radius: 6px; flex: none;
color: var(--red-text); background: rgba(255, 107, 107, 0.14);
align-self: flex-start;
}
.src-badge.yandex { color: var(--yellow-text); background: rgba(255, 207, 74, 0.14); }
.tracklist { display: flex; flex-direction: column; }
.track-row {
display: flex; align-items: center; gap: 14px;
padding: 10px 6px;
border-bottom: 1px solid rgba(255, 255, 255, 0.035);
}
.track-row:last-child { border-bottom: none; }
.track-row.playing { background: var(--accent-soft); border-radius: 10px; }
.track-row.dragging { opacity: 0.4; }
.track-num { font-family: var(--font-mono); font-size: 12px; color: var(--faint); width: 22px; flex: none; }
.track-cover { width: 40px; height: 40px; border-radius: 9px; flex: none; }
.track-main { flex: 1; min-width: 0; }
.track-title { font-weight: 600; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.track-sub { color: var(--muted-2); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; }
.track-dur { font-family: var(--font-mono); font-size: 12px; color: var(--muted-2); flex: none; }
.track-actions { display: flex; gap: 4px; flex: none; }
.icon-btn {
background: none; border: none; cursor: pointer;
color: var(--muted-2); font-size: 14px;
width: 30px; height: 30px; border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.icon-btn:hover { background: rgba(255, 255, 255, 0.07); color: var(--text); }
.icon-btn.danger:hover { color: var(--red-text); }
.icon-btn.fav-on { color: var(--pink); }
.drag-handle { cursor: grab; color: var(--faint); }
.empty { padding: 24px; text-align: center; color: var(--faint); }
/* ── Now Playing ──────────────────────────────────────────────────────── */
.now-grid { display: grid; grid-template-columns: 1.25fr 1fr; gap: 18px; align-items: start; }
.np-card { display: flex; flex-direction: column; gap: 18px; }
.np-cover {
width: 100%; aspect-ratio: 1.9;
border-radius: 12px;
background: linear-gradient(135deg, #2a1a4a, #0d0d1f);
background-size: cover; background-position: center;
}
.np-info { display: flex; flex-direction: column; gap: 9px; }
.np-title { font-family: var(--font-head); font-size: 22px; font-weight: 700; letter-spacing: -0.01em; }
.np-artist { color: var(--muted); font-size: 14px; }
.np-added { color: var(--faint); font-size: 12px; }
.progress-row { display: flex; align-items: center; gap: 12px; margin-top: 8px; }
.bar {
flex: 1; height: 7px; border-radius: 5px;
background: rgba(255, 255, 255, 0.08);
cursor: pointer; position: relative;
}
.bar-slim { height: 5px; }
.bar-fill { position: relative; height: 100%; width: 0; border-radius: 5px; background: linear-gradient(90deg, #7c5cff, #a68dff); }
/* Locally buffered range, painted behind the progress fill. */
.bar-buffer {
position: absolute; left: 0; top: 0; height: 100%;
border-radius: 5px; background: rgba(255, 255, 255, 0.14);
}
/* Value tooltip that follows the pointer while hovering/dragging a bar. */
.bar-tip {
position: absolute; bottom: 100%; margin-bottom: 8px;
transform: translateX(-50%); pointer-events: none; white-space: nowrap;
background: #1b1b26; color: #f0f0f5; border: 1px solid rgba(255,255,255,0.12);
padding: 2px 7px; border-radius: 6px; font-size: 12px;
font-variant-numeric: tabular-nums; z-index: 5;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
}
.transport { display: flex; align-items: center; gap: 10px; margin-top: 6px; flex-wrap: wrap; }
.ctrl {
width: 40px; height: 40px;
border: none; border-radius: 11px;
cursor: pointer;
display: flex; align-items: center; justify-content: center;
background: rgba(255, 255, 255, 0.04); color: var(--muted-2);
font-size: 15px;
}
.ctrl:hover { background: rgba(255, 255, 255, 0.08); color: var(--text); }
.ctrl.on { background: rgba(124, 92, 255, 0.2); color: var(--accent-text); }
.ctrl.fav-on { color: var(--pink); }
.ctrl-main {
width: 52px; height: 52px; border-radius: 15px;
background: var(--accent); color: #fff; font-size: 18px;
}
.ctrl-main:hover { background: #8b6dff; color: #fff; }
.voteskip.on { border-color: rgba(124, 92, 255, 0.5); color: var(--accent-text); }
.vol-row { display: flex; align-items: center; gap: 12px; margin-top: 4px; }
.vol-row .bar { max-width: 160px; }
.toggle-row { display: flex; align-items: center; gap: 8px; margin-left: auto; cursor: pointer; }
.toggle {
width: 42px; height: 24px; border-radius: 14px; border: none;
cursor: pointer; padding: 2px; display: flex;
background: rgba(255, 255, 255, 0.12);
justify-content: flex-start; transition: background 0.15s;
}
.toggle.on { background: var(--accent); justify-content: flex-end; }
.knob { width: 20px; height: 20px; border-radius: 50%; background: #fff; display: block; }
/* ── People rows (listeners, subscribers, participants) ──────────────── */
.people { display: flex; flex-direction: column; }
.person {
display: flex; align-items: center; gap: 12px;
padding: 9px 4px;
border-bottom: 1px solid rgba(255, 255, 255, 0.035);
}
.person:last-child { border-bottom: none; }
.avatar {
width: 32px; height: 32px; border-radius: 10px; flex: none;
display: inline-flex; align-items: center; justify-content: center;
font-weight: 700; font-size: 14px; color: #fff;
background: linear-gradient(135deg, #7c5cff, #5b3fd6);
}
.person-main { flex: 1; min-width: 0; }
.person-name { font-weight: 600; font-size: 13.5px; }
.person-sub { color: var(--muted-2); font-size: 11.5px; margin-top: 1px; }
.person-status { font-size: 12px; font-weight: 600; flex: none; }
/* ── Search / tabs ────────────────────────────────────────────────────── */
.search-row { display: flex; gap: 10px; margin-bottom: 14px; }
.search-row input { flex: 1; }
.tabs { display: flex; gap: 8px; margin-bottom: 16px; }
.tab {
padding: 9px 18px; border-radius: 10px;
border: 1px solid var(--line);
cursor: pointer; font-weight: 600; font-size: 13.5px;
background: transparent; color: var(--muted);
}
.tab.active { background: var(--accent-soft); border-color: rgba(124, 92, 255, 0.4); color: #fff; }
/* ── Library ──────────────────────────────────────────────────────────── */
.grid-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
.playlist-card {
border: 1px solid var(--line); border-radius: 12px;
padding: 14px; cursor: pointer;
background: var(--panel-2);
display: flex; flex-direction: column; gap: 10px;
}
.playlist-card:hover { border-color: rgba(124, 92, 255, 0.4); }
.playlist-card.active { border-color: rgba(124, 92, 255, 0.7); }
.playlist-actions { display: flex; gap: 6px; margin-top: 2px; }
.playlist-actions .btn { padding: 4px 10px; font-size: 12px; }
.playlist-cover { width: 100%; aspect-ratio: 1.6; border-radius: 9px; }
.playlist-name { font-weight: 600; font-size: 13.5px; }
.playlist-meta { color: var(--muted-2); font-size: 12px; }
/* ── Audit log ────────────────────────────────────────────────────────── */
.audit-scroll { max-height: 420px; overflow-y: auto; }
.audit-row {
display: grid; grid-template-columns: 1fr auto auto; gap: 12px;
align-items: baseline; padding: 8px 4px;
border-bottom: 1px solid var(--line); font-size: 13px;
}
.audit-row:last-child { border-bottom: none; }
.audit-method { font-weight: 600; }
.audit-time { font-size: 12px; white-space: nowrap; }
.audit-client { font-size: 12px; white-space: nowrap; }
/* ── Keyboard shortcuts overlay ───────────────────────────────────────── */
.shortcuts-modal { width: min(380px, 92vw); }
.shortcuts-list { display: flex; flex-direction: column; gap: 8px; margin: 14px 0 18px; }
.shortcut-row { display: flex; align-items: center; gap: 12px; font-size: 13.5px; }
.shortcut-row kbd {
min-width: 64px; text-align: center; padding: 3px 8px; border-radius: 6px;
background: var(--panel-2); border: 1px solid var(--line);
font-family: var(--font-mono, monospace); font-size: 12px; color: var(--text);
}
/* ── Lyrics ───────────────────────────────────────────────────────────── */
.lyrics-body { padding: 4px 2px; }
.lyrics-empty { color: var(--muted-2); font-size: 13px; padding: 8px 4px; }
.lyrics-synced { max-height: 320px; overflow-y: auto; display: flex; flex-direction: column; gap: 4px; }
.lyrics-line { color: var(--muted-2); font-size: 14px; line-height: 1.5; transition: color .15s, transform .15s; }
.lyrics-line.active { color: var(--text); font-weight: 600; transform: translateX(2px); }
.lyrics-plain { max-height: 320px; overflow-y: auto; white-space: pre-wrap; font-family: inherit; font-size: 14px; line-height: 1.55; color: var(--text-2); margin: 0; }
.lyrics-source { font-size: 11px; margin-top: 8px; text-align: right; }
/* ── Stats ────────────────────────────────────────────────────────────── */
.stat-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 18px; }
.stat-card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }
.stat-label { color: var(--muted-2); font-size: 12px; font-weight: 600; }
.stat-value { font-family: var(--font-head); font-size: 26px; font-weight: 700; margin-top: 6px; }
.stat-delta { font-size: 12px; margin-top: 4px; color: var(--muted-2); }
.stat-delta.up { color: var(--green-text); }
.stats-grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 18px; align-items: start; }
.split-bar { display: flex; height: 12px; border-radius: 7px; overflow: hidden; margin: 8px 0 12px; background: rgba(255,255,255,.06); }
.split-yt { background: #ff8080; }
.split-ya { background: #ffd977; }
.split-legend { display: flex; gap: 18px; font-size: 12.5px; color: var(--muted); }
.split-legend span { display: inline-flex; align-items: center; gap: 6px; }
.split-legend b { color: var(--text-2); margin-left: 2px; }
/* ── Watch Together ───────────────────────────────────────────────────── */
.watch-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 18px; align-items: start; }
.src-yt.active { background: rgba(255, 92, 92, 0.16); border-color: rgba(255, 92, 92, 0.4); color: var(--red-text); }
.src-tw.active { background: rgba(169, 112, 255, 0.18); border-color: rgba(169, 112, 255, 0.4); color: #c3a3ff; }
.src-direct.active { background: rgba(95, 224, 148, 0.16); border-color: rgba(95, 224, 148, 0.4); color: var(--green-text); }
.src-iframe.active { background: rgba(255, 217, 119, 0.16); border-color: rgba(255, 217, 119, 0.4); color: #ffd977; }
/* The direct <video> and generic <iframe> fill the player box like the embeds. */
#watchPlayer video, #watchPlayer iframe { width: 100%; height: 100%; display: block; background: #000; }
.player-box {
position: relative; width: 100%; aspect-ratio: 16 / 9;
border-radius: 12px; overflow: hidden;
background: linear-gradient(135deg, #2a1a4a, #0d0d1f);
margin-bottom: 14px;
}
.player-box iframe, .player-box > div:first-child { position: absolute; inset: 0; width: 100%; height: 100%; }
/* The shell owns the outer spacing; the control bar overlays the video bottom
(windowed and fullscreen) so it can fade out when idle. */
.player-shell { position: relative; margin-bottom: 14px; }
.player-shell .player-box { margin-bottom: 0; }
.player-shell.youtube-native .player-overlay { bottom: 42px; }
.player-overlay {
position: absolute; left: 0; right: 0; bottom: 0; z-index: 5;
padding: 34px 14px 8px;
background: linear-gradient(to top,
rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.45) 46%, rgba(0,0,0,0) 100%);
opacity: 1; transition: opacity 0.25s ease;
}
.player-overlay .watch-controls { margin-bottom: 8px; }
.player-overlay .watch-controls:last-child { margin-bottom: 0; }
/* Lift muted/mono text for legibility over video. */
.player-overlay .muted, .player-overlay .mono { color: #e9e9f2; }
/* Idle-hidden while playing (the hook removes the class when paused). Hover /
keyboard focus (incl. an open quality/speed dropdown) reveals regardless. */
.player-shell.controls-hidden .player-overlay { opacity: 0; pointer-events: none; }
.player-shell.controls-hidden { cursor: none; }
.player-shell.controls-hidden:hover .player-overlay,
.player-shell.controls-hidden:focus-within .player-overlay {
opacity: 1; pointer-events: auto;
}
.player-shell.controls-hidden:hover,
.player-shell.controls-hidden:focus-within { cursor: auto; }
/* Fullscreen targets the shell: the player fills the screen and the overlay
floats at the bottom (controls stay usable while fullscreen). */
.player-shell:fullscreen { background: #000; padding: 0; }
.player-shell:fullscreen .player-box {
width: 100%; height: 100%; aspect-ratio: auto;
border-radius: 0; margin: 0;
}
.player-shell:fullscreen .player-overlay { padding: 46px 24px 18px; }
.player-empty {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
color: var(--faint); font-size: 13.5px;
pointer-events: none;
text-align: center; padding: 0 24px;
}
.player-empty[hidden] { display: none; }
/* Muted-autoplay affordance overlaid on the player until the user unmutes. */
.unmute-btn {
position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%);
z-index: 6; box-shadow: 0 4px 16px rgba(0,0,0,0.5);
}
/* Watch lobby (no room joined). */
.watch-lobby { max-width: 640px; margin: 0 auto; }
.watch-lobby .rooms-list { display: flex; flex-direction: column; gap: 8px; margin: 12px 0; }
.watch-lobby .room-chip { justify-content: flex-start; text-align: left; }
.room-now { font-style: italic; }
.watch-controls { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.watch-controls .ctrl-main { width: 42px; height: 42px; }
.watch-local .bar { flex: 0 0 130px; }
.watch-local[hidden] { display: none; }
.quality-select {
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--line);
color: var(--text-2);
border-radius: 8px;
padding: 6px 8px;
font: inherit;
font-size: 12.5px;
}
.player-settings { position: relative; }
.player-settings-popover {
position: absolute; right: 0; bottom: calc(100% + 10px); z-index: 20;
width: min(290px, 80vw); padding: 10px;
border: 1px solid rgba(255,255,255,0.14); border-radius: 12px;
background: rgba(14, 14, 28, 0.96);
box-shadow: 0 18px 46px rgba(0,0,0,0.5);
backdrop-filter: blur(18px);
}
.player-settings-popover section + section {
margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line);
}
.player-settings-heading {
margin: 0 2px 7px; color: var(--faint); font-size: 10px;
font-weight: 800; letter-spacing: .13em; text-transform: uppercase;
}
.player-setting {
display: grid; grid-template-columns: minmax(80px, 1fr) minmax(110px, 1.35fr);
align-items: center; gap: 10px; padding: 5px 2px;
color: var(--text-2); font-size: 12.5px;
}
.player-setting select {
min-width: 0; width: 100%; padding: 6px 8px;
border: 1px solid var(--line); border-radius: 8px;
background: #1b1b31; color: var(--text-2); font: inherit;
}
.ctrl:disabled, .btn:disabled, .icon-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.reactions { display: flex; gap: 8px; }
.reaction {
padding: 8px 14px; border-radius: 10px;
border: 1px solid var(--line); background: transparent;
cursor: pointer; font-size: 16px;
}
.reaction:hover { background: rgba(255, 255, 255, 0.06); }
.reaction-fly {
position: fixed; font-size: 26px; pointer-events: none;
animation: fly-up 1.6s ease-out forwards; z-index: 60;
}
@keyframes fly-up { to { transform: translateY(-120px); opacity: 0; } }
.chat-card { display: flex; flex-direction: column; }
.chat-log {
display: flex; flex-direction: column; gap: 10px;
max-height: 320px; overflow-y: auto;
margin-bottom: 12px; padding-right: 4px;
}
.chat-msg { display: flex; gap: 10px; align-items: flex-start; }
.chat-body { min-width: 0; }
.chat-name { font-weight: 700; font-size: 12.5px; color: var(--accent-2); }
.chat-time { color: var(--faint); font-size: 11px; margin-left: 6px; }
.chat-text { font-size: 13px; color: var(--text-2); margin-top: 1px; word-break: break-word; }
.chat-row { display: flex; gap: 8px; }
.chat-row input { flex: 1; }
/* ── RPC view ─────────────────────────────────────────────────────────── */
.rpc-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }
.rpc-field { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.rpc-label { min-width: 140px; flex: none; font-size: 10.5px; font-weight: 700; letter-spacing: 0.08em; color: var(--faint); }
.rpc-value {
flex: 1; font-family: var(--font-mono); font-size: 12.5px;
background: rgba(255, 255, 255, 0.04); border: 1px solid var(--line);
border-radius: 9px; padding: 9px 12px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.code-block {
font-family: var(--font-mono); font-size: 12px; line-height: 1.55;
background: rgba(0, 0, 0, 0.35); border: 1px solid var(--line);
border-radius: 10px; padding: 14px; overflow-x: auto;
color: #c8c8d2; margin-bottom: 12px;
}
/* ── Mini player ──────────────────────────────────────────────────────── */
.miniplayer {
position: fixed; left: 256px; right: 20px; bottom: 14px;
display: flex; align-items: center; gap: 14px;
background: rgba(18, 18, 26, 0.92);
backdrop-filter: blur(12px);
border: 1px solid var(--line); border-radius: 14px;
padding: 10px 16px; z-index: 40;
}
.mini-cover { width: 38px; height: 38px; border-radius: 9px; background: linear-gradient(135deg, #2a1a4a, #0d0d1f); flex: none; }
.mini-info { min-width: 0; width: 220px; }
.mini-title { font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mini-artist { color: var(--muted-2); font-size: 11.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mini-bar { flex: 1; }
/* ── Toast ────────────────────────────────────────────────────────────── */
.toast {
position: fixed; bottom: 76px; left: 50%; transform: translateX(-50%);
background: #1d1d2a; border: 1px solid rgba(124, 92, 255, 0.35);
color: var(--text); font-size: 13px; font-weight: 600;
padding: 11px 20px; border-radius: 12px;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.5);
z-index: 80;
}
/* ── Responsive ───────────────────────────────────────────────────────── */
/* Hamburger + drawer backdrop exist only at drawer widths (≤900px). */
.hamburger { display: none; }
.header-title { display: flex; align-items: flex-start; gap: 10px; min-width: 0; }
.drawer-backdrop { display: none; }
@media (max-width: 1080px) {
.now-grid, .stats-grid, .watch-grid { grid-template-columns: 1fr; }
}
/* Tablet and below: the sidebar becomes a slide-in drawer. */
@media (max-width: 900px) {
.sidebar {
position: fixed; left: 0; top: 0; bottom: 0; z-index: 90;
width: min(280px, 84vw); height: 100dvh;
background: var(--bg);
transform: translateX(-100%);
transition: transform 0.2s ease;
overflow-y: auto;
}
.sidebar.open { transform: none; box-shadow: 12px 0 40px rgba(0, 0, 0, 0.5); }
.hamburger { display: flex; margin-top: 3px; }
.drawer-backdrop {
display: block; position: fixed; inset: 0; z-index: 85;
background: rgba(0, 0, 0, 0.5);
}
.main { padding: 16px 14px calc(96px + env(safe-area-inset-bottom)); }
.header { flex-wrap: wrap; gap: 8px; }
.miniplayer {
left: 12px; right: 12px;
bottom: calc(10px + env(safe-area-inset-bottom));
}
}
/* Phone density. */
@media (max-width: 560px) {
.main { padding-left: 12px; padding-right: 12px; }
.header h1 { font-size: 20px; }
.card { padding: 14px; }
.np-title { font-size: 19px; }
.search-row, .chat-row, .rooms-create, .row-gap { flex-wrap: wrap; }
.search-row input, .chat-row input { min-width: 0; flex: 1 1 160px; }
.watch-controls { flex-wrap: wrap; row-gap: 8px; }
.watch-local .bar { flex: 1 1 100px; }
.tabs { overflow-x: auto; }
.audit-row { grid-template-columns: 1fr auto; }
.audit-time { grid-column: 1 / -1; }
.rpc-field { flex-direction: column; align-items: stretch; }
.rpc-label { min-width: 0; }
.miniplayer { gap: 10px; }
.mini-info { width: auto; flex: 1; min-width: 0; }
}
/* Touch: bigger targets, and a taller invisible hit area on drag bars. */
@media (pointer: coarse) {
.icon-btn { width: 38px; height: 38px; }
.ctrl { width: 44px; height: 44px; }
.ctrl-main { width: 54px; height: 54px; }
.bar::before { content: ''; position: absolute; inset: -10px 0; }
}
/* ── React port additions ─────────────────────────────────────────────── */
/* Language switcher in the sidebar connection row. */
.lang-select {
margin-left: auto; background: transparent; color: inherit;
border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 6px;
font: inherit; font-size: 11px; padding: 2px 4px; cursor: pointer;
}
.lang-select option { color: #000; }
/* Reactions rendered inside the player box (the vanilla UI appended them
to <body> at fixed coordinates). */
.reaction-layer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
.reaction-fly-abs { position: absolute; bottom: 50px; }
.player-box { position: relative; }
/* Drop indicator for queue drag-and-drop (item 9). */
.drop-indicator {
height: 3px; margin: 1px 0; border-radius: 2px;
background: linear-gradient(90deg, #7c5cff, #b28dff);
box-shadow: 0 0 8px rgba(124, 92, 255, 0.7);
}
/* Real image avatars from TeamSpeak (item 10). */
.avatar-img { object-fit: cover; }
/* Now Playing video (item 11). */
.np-video {
width: 100%; aspect-ratio: 16 / 9; border-radius: 14px;
overflow: hidden; background: #000;
}
.np-video-toggle { align-self: flex-start; margin-bottom: 8px; }
.np-video-toggle.on { color: #b28dff; }
/* Announce composer modal (item 14). */
.modal-backdrop {
position: fixed; inset: 0; z-index: 100; display: flex;
align-items: center; justify-content: center;
background: rgba(6, 6, 14, 0.62); backdrop-filter: blur(3px);
}
.modal {
width: min(560px, 92vw); max-height: 88vh; overflow: auto;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px; padding: 18px 20px;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.5);
}
.modal-wide { width: min(860px, 94vw); }
.modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
.modal-head h2 { margin: 0; }
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
.announce-toolbar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }
.announce-toolbar .btn { padding: 4px 10px; font-weight: 600; min-width: 34px; }
.announce-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
@media (max-width: 720px) { .announce-grid { grid-template-columns: 1fr; } }
.announce-input {
width: 100%; resize: vertical; min-height: 220px;
font-family: inherit; font-size: 14px; line-height: 1.5;
}
.announce-preview {
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 10px;
padding: 10px 12px; overflow: auto;
}
.announce-preview-label {
font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;
color: #8a8a98; margin-bottom: 6px;
}
.ts-markup { font-size: 14px; line-height: 1.55; word-break: break-word; }
.ts-markup h3, .ts-markup h4, .ts-markup h5 { margin: 0.5em 0 0.3em; }
.ts-markup p { margin: 0.35em 0; }
.ts-markup blockquote {
border-left: 3px solid rgba(124, 92, 255, 0.6);
margin: 0.4em 0; padding-left: 10px; color: #c9c9d6;
}
.ts-markup code {
background: rgba(255, 255, 255, 0.08); padding: 1px 5px;
border-radius: 4px; font-size: 0.9em;
}
.ts-markup details { margin: 0.4em 0; }
.ts-markup summary { cursor: pointer; font-weight: 600; }
/* Watch Together room switcher (item 3). */
.pill-room { cursor: pointer; border: none; font: inherit; }
.rooms-panel {
display: flex; flex-direction: column; gap: 10px;
padding: 12px; margin: 4px 0 2px;
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 12px;
background: rgba(255, 255, 255, 0.03);
}
.rooms-list { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.room-chip {
background: rgba(255, 255, 255, 0.06); border: 1px solid transparent;
border-radius: 8px; padding: 5px 10px; cursor: pointer;
color: inherit; font: inherit; font-size: 13px;
}
.room-chip.active { border-color: #7c5cff; color: #b28dff; }
.rooms-create { display: flex; gap: 8px; }
.rooms-create input { flex: 1; }
/* Watch search (item 20). */
.watch-search { position: relative; margin-bottom: 8px; }
.watch-search-results {
position: absolute; z-index: 30; left: 0; right: 0; top: 100%;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px; margin-top: 4px; max-height: 320px; overflow: auto;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.watch-search-item {
display: flex; align-items: center; gap: 10px; width: 100%;
padding: 6px 10px; background: transparent; border: none; cursor: pointer;
color: inherit; text-align: left; font: inherit;
}
.watch-search-item:hover { background: rgba(255, 255, 255, 0.06); }
.watch-search-item .track-cover { width: 48px; height: 27px; flex: none; border-radius: 4px; }
.watch-search-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Emoji picker + custom emojis (item 16). */
.emoji-anchor { position: relative; display: inline-flex; }
.emoji-trigger { padding: 6px 8px; }
.emoji-picker {
position: absolute; bottom: 100%; left: 0; z-index: 40; width: 300px;
max-height: 320px; overflow-y: auto; margin-bottom: 6px; padding: 8px;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px; box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.emoji-section { margin-bottom: 8px; }
.emoji-section-label {
font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase;
color: #8a8a98; margin: 4px 2px;
}
.emoji-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; }
.emoji-btn {
background: transparent; border: none; cursor: pointer; font-size: 20px;
line-height: 1; padding: 4px; border-radius: 6px;
}
.emoji-btn:hover { background: rgba(255, 255, 255, 0.08); }
.emoji-img { width: 20px; height: 20px; vertical-align: middle; object-fit: contain; }
.emoji-img-lg { width: 30px; height: 30px; object-fit: contain; }
.emoji-manage-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; }
.emoji-manage-grid { display: flex; flex-wrap: wrap; gap: 12px; }
.emoji-manage-item {
display: flex; align-items: center; gap: 6px;
background: rgba(255, 255, 255, 0.05); border-radius: 8px; padding: 6px 10px;
}
@@ -1,254 +0,0 @@
import { useEffect, useState } from 'react';
import { appStore, loadFavorites, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { cover } from '../lib/format';
import type { Playlist, PlaylistContents } from '../lib/types';
import { confirmDialog, promptDialog } from '../lib/dialog';
import { CloseIcon } from '../components/icons';
import { t, tf } from '../i18n';
export function LibraryView() {
const s = useStore(appStore);
const [playlists, setPlaylists] = useState<Playlist[]>([]);
const [selected, setSelected] = useState<PlaylistContents | null>(null);
const loadPlaylists = async () => {
const res = await safeCall<{ playlists?: Playlist[] }>('GetPlaylists');
setPlaylists((res && res.playlists) || []);
};
const openPlaylist = async (id: string) => {
const res = await safeCall<PlaylistContents>('GetPlaylist', {
playlistId: id,
});
if (res) setSelected(res);
};
useEffect(() => {
loadFavorites();
loadPlaylists();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<section className="view" id="view-library">
<div className="card">
<div className="card-head">
<h2>
{t('Your favorites')}{' '}
<span className="muted">
{s.favorites.length
? `· ${s.favorites.length}`
: ''}
</span>
</h2>
</div>
<div className="tracklist">
{!s.identity ? (
<EmptyRow text={t('Authenticate to use favorites')} />
) : !s.favorites.length ? (
<EmptyRow
text={t('No favorites yet — ♥ a track anywhere')}
/>
) : (
s.favorites.map((tr, i) => (
<TrackRow
key={tr.url || i}
track={tr}
num={i + 1}
actions={[
{
icon: '+',
title: t('Add to queue'),
onClick: async () => {
await safeCall('QueueTrack', {
query: tr.url || tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
{
icon: <CloseIcon />,
title: t('Remove'),
cls: 'danger',
onClick: async () => {
await safeCall('RemoveFavorite', {
url: tr.url,
});
toast(
t('Removed from favorites')
);
loadFavorites();
},
},
]}
/>
))
)}
</div>
</div>
<div className="card">
<div className="card-head">
<h2>{t('Playlists')}</h2>
<button
className="btn btn-ghost"
onClick={async () => {
const name = await promptDialog({
title: t('Save playlist'),
message: t(
'Playlist name (saves the current queue):'
),
placeholder: t('Playlist name'),
confirmLabel: t('Save'),
});
if (!name) return;
await safeCall('SavePlaylist', {
name: name.trim(),
description: t('Saved from web UI'),
});
toast(tf('Playlist “{0}” saved', name));
loadPlaylists();
}}
>
{t('Save queue as playlist')}
</button>
</div>
<div className="grid-cards">
{!playlists.length ? (
<EmptyRow text={t('No playlists saved yet')} />
) : (
playlists.map((p, i) => (
<div
key={p.id}
className={
'playlist-card' +
(selected && selected.id === p.id
? ' active'
: '')
}
onClick={() => openPlaylist(p.id)}
>
<div
className="playlist-cover"
style={{ background: cover(i * 17 + 2) }}
/>
<div className="playlist-name">{p.name}</div>
<div className="playlist-meta">
{tf('{0} tracks', p.trackCount)}
</div>
<div className="playlist-actions">
<button
className="btn btn-ghost"
onClick={async (e) => {
e.stopPropagation();
toast(
tf(
'Loading playlist “{0}”…',
p.name
)
);
await safeCall('LoadPlaylist', {
playlistId: p.id,
});
}}
>
{t('Load')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async (e) => {
e.stopPropagation();
if (
!(await confirmDialog({
title: t('Delete playlist'),
message: tf(
'Delete playlist “{0}”? This cannot be undone.',
p.name
),
confirmLabel: t('Delete'),
danger: true,
}))
) {
return;
}
await safeCall('DeletePlaylist', {
playlistId: p.id,
});
toast(
tf(
'Playlist “{0}” deleted',
p.name
)
);
if (selected && selected.id === p.id)
setSelected(null);
loadPlaylists();
}}
>
{t('Delete')}
</button>
</div>
</div>
))
)}
</div>
</div>
{selected && (
<div className="card">
<div className="card-head">
<h2>
{selected.name}{' '}
<span className="muted">
{selected.tracks.length
? `· ${selected.tracks.length}`
: ''}
</span>
</h2>
<button
className="btn btn-ghost"
onClick={() => setSelected(null)}
>
{t('Close')}
</button>
</div>
<div className="tracklist">
{!selected.tracks.length ? (
<EmptyRow text={t('This playlist is empty')} />
) : (
selected.tracks.map((tr, i) => (
<TrackRow
key={tr.url || i}
track={tr}
num={i + 1}
actions={[
{
icon: '+',
title: t('Add to queue'),
onClick: async () => {
await safeCall('QueueTrack', {
query: tr.url || tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
]}
/>
))
)}
</div>
</div>
)}
</section>
);
}
-318
View File
@@ -1,318 +0,0 @@
import { useState } from 'react';
import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { PlayerControls } from '../components/PlayerControls';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { PersonRow } from '../components/PersonRow';
import { NowPlayingVideo } from '../components/NowPlayingVideo';
import { LyricsPanel } from '../components/LyricsPanel';
import { coverStyle, sourceInfo } from '../lib/format';
import { youtubeIdFromUrl } from '../lib/youtube';
import {
HeartIcon,
RepeatIcon,
ShuffleIcon,
SkipPrevIcon,
} from '../components/icons';
import { t, tf } from '../i18n';
const VIDEO_PREF_KEY = 'echoion.npVideo';
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
export function NowView() {
const s = useStore(appStore);
const [videoOn, setVideoOn] = useState(
localStorage.getItem(VIDEO_PREF_KEY) === '1'
);
const track = s.current;
const videoId = youtubeIdFromUrl(track?.url);
const videoAvailable = s.nowPlayingVideoAllowed && !!videoId;
const showVideo = videoAvailable && videoOn;
const st = s.status || {};
const src = track && sourceInfo(track);
const playing = !!st.isPlaying && !st.isPaused;
const volumePct = Math.round((st.volume ?? 0.5) * 100);
const durationMs = s.durationMs || track?.duration || 0;
const isFav = !!(track && track.url && s.favUrls.has(track.url));
const isAdmin = !!(s.identity && s.identity.isAdmin);
// Skipping over RPC is a force-skip (DJ/admin only, server-enforced);
// everyone else uses the vote-skip button. See item 15.
const canForceSkip = !!(
s.identity &&
(s.identity.isAdmin || s.identity.isDj)
);
const votes = st.skipVotes || 0;
const needed = st.skipVotesNeeded || 0;
return (
<section className="view" id="view-now">
<div className="now-grid">
<div className="card np-card">
{showVideo && videoId ? (
<NowPlayingVideo videoId={videoId} />
) : (
<div
className="np-cover"
style={{ background: coverStyle(track) }}
/>
)}
<div className="np-info">
{videoAvailable && (
<button
className={
'btn btn-ghost np-video-toggle' +
(videoOn ? ' on' : '')
}
onClick={() => {
const next = !videoOn;
setVideoOn(next);
localStorage.setItem(
VIDEO_PREF_KEY,
next ? '1' : '0'
);
}}
>
{videoOn
? t('Hide video')
: t('Watch video')}
</button>
)}
{src && <span className={src.cls}>{src.label}</span>}
<div className="np-title">
{track ? track.title : t('Nothing playing')}
</div>
<div className="np-artist">
{track ? track.artist || '' : ''}
</div>
<div className="np-added" />
<PlayerControls
playing={playing}
positionMs={s.positionMs}
durationMs={durationMs}
canControl
volumePct={volumePct}
onTogglePlay={togglePlay}
onSeekMs={(ms) =>
safeCall('Seek', { position: ms })
}
onVolume={(pct) =>
safeCall('SetVolume', { volume: pct / 100 })
}
onSkip={
canForceSkip
? () => safeCall('Skip', { count: 1 })
: undefined
}
extra={
<>
<button
className={
'ctrl' + (st.shuffle ? ' on' : '')
}
title={t('Shuffle')}
onClick={() =>
safeCall('ToggleShuffle')
}
>
<ShuffleIcon />
</button>
<button
className="ctrl"
title={t('Restart track')}
onClick={() =>
safeCall('Seek', { position: 0 })
}
>
<SkipPrevIcon />
</button>
<button
className={
'ctrl' + (st.repeat ? ' on' : '')
}
title={t('Repeat')}
onClick={() => safeCall('ToggleRepeat')}
>
<RepeatIcon />
</button>
<button
className={
'ctrl' + (isFav ? ' fav-on' : '')
}
title={t('Favorite')}
onClick={async () => {
if (!track) return;
if (isFav) {
await safeCall(
'RemoveFavorite',
{ url: track.url }
);
toast(
t('Removed from favorites')
);
} else {
await safeCall('AddFavorite', {
track,
});
toast(t('Added to favorites'));
}
loadFavorites();
}}
>
<HeartIcon />
</button>
<button
className={
'btn btn-ghost voteskip' +
(st.skipVoted ? ' on' : '')
}
title={t('Vote to skip')}
onClick={async () => {
const res = await safeCall<{
skipped?: boolean;
votes?: number;
needed?: number;
voted?: boolean;
}>('VoteSkip');
if (!res) return;
if (res.skipped) {
toast(
t(
'Vote passed — track skipped'
)
);
} else {
appStore.set({
status: {
...(appStore.get()
.status || {}),
skipVotes: res.votes,
skipVotesNeeded:
res.needed,
skipVoted: res.voted,
},
});
}
}}
>
<span>
{votes > 0
? tf(
'Vote skip {0}/{1}',
votes,
needed
)
: t('Vote skip')}
</span>
</button>
</>
}
extraLocal={
<label className="toggle-row">
<span className="muted">{t('Radio')}</span>
<button
type="button"
className={
'toggle' +
(st.autoplay ? ' on' : '')
}
onClick={async () => {
if (!isAdmin) {
toast(
t(
'Radio mode is admin-only — ask an admin or use !autoplay'
)
);
return;
}
const res = await safeCall<{
autoplay?: boolean;
}>('ToggleAutoplay');
if (res) {
appStore.set({
status: {
...(appStore.get()
.status || {}),
autoplay: res.autoplay,
},
});
toast(
res.autoplay
? t('Radio mode on')
: t('Radio mode off')
);
}
}}
>
<span className="knob" />
</button>
</label>
}
/>
</div>
</div>
<div className="col">
<div className="card">
<div className="card-head">
<h2>{t('Up Next')}</h2>
<button
className="link"
onClick={() => showView('queue')}
>
{t('Open queue →')}
</button>
</div>
<div className="tracklist">
{(() => {
const upcoming = s.queue
.filter((q) => !q.isPlaying)
.slice(0, 4);
if (!upcoming.length) {
return (
<EmptyRow text={t('Queue is empty')} />
);
}
return upcoming.map((q, i) => (
<TrackRow
key={q.queueId}
track={q.track}
num={i + 1}
/>
));
})()}
</div>
</div>
<LyricsPanel />
<div className="card">
<div className="card-head">
<h3>{t('Listening now')}</h3>
</div>
<div className="people">
{!s.listeners.filter((u) => u.online).length ? (
<EmptyRow
text={t('Nobody online right now')}
/>
) : (
s.listeners
.filter((u) => u.online)
.slice(0, 6)
.map((u, i) => (
<PersonRow
key={i}
name={u.nickname || u.uid}
uid={u.uid}
sub={t('Listening')}
/>
))
)}
</div>
</div>
</div>
</div>
</section>
);
}
-164
View File
@@ -1,164 +0,0 @@
import { useState } from 'react';
import { appStore, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { originalLinkAction } from '../lib/links';
import { confirmDialog } from '../lib/dialog';
import { CloseIcon, PlayIcon } from '../components/icons';
import { t, tf } from '../i18n';
async function playNow(queueId: number) {
await safeCall('MoveInQueue', { queueId, newPosition: 0 });
await safeCall('Skip', { count: 1 });
toast(t('Playing now'));
}
export function QueueView() {
const s = useStore(appStore);
const [dragQueueId, setDragQueueId] = useState<number | null>(null);
// Index where the dragged row would be inserted; drives the drop-line
// indicator so the user can see the landing spot (item 9).
const [dropIndex, setDropIndex] = useState<number | null>(null);
const commitDrop = () => {
if (dragQueueId != null && dropIndex != null) {
const from = s.queue.findIndex((e) => e.queueId === dragQueueId);
// Dropping below its own slot shifts the target down by one.
let target = dropIndex;
if (from !== -1 && from < dropIndex) target -= 1;
if (from !== target) {
safeCall('MoveInQueue', {
queueId: dragQueueId,
newPosition: target,
});
}
}
setDragQueueId(null);
setDropIndex(null);
};
return (
<section className="view" id="view-queue">
<div className="card">
<div className="card-head">
<h2>
{t('Queue')}{' '}
<span className="muted">
{s.queue.length
? `· ${tf('{0} tracks', s.queue.length)}`
: ''}
</span>
</h2>
<div className="row-gap">
<button
className="btn btn-ghost"
onClick={() => safeCall('ShuffleQueue')}
>
{t('Shuffle queue')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
!(await confirmDialog({
title: t('Clear queue'),
message: t('Clear the whole queue?'),
confirmLabel: t('Clear'),
danger: true,
}))
)
return;
await safeCall('ClearQueue');
toast(t('Queue cleared'));
}}
>
{t('Clear')}
</button>
</div>
</div>
<div
className="tracklist"
onDragLeave={(e) => {
// Only clear when leaving the list entirely.
if (
!e.currentTarget.contains(
e.relatedTarget as Node | null
)
) {
setDropIndex(null);
}
}}
onDrop={commitDrop}
>
{!s.queue.length ? (
<EmptyRow
text={t('Queue is empty — add something from Search')}
/>
) : (
s.queue.map((entry, i) => (
<div key={entry.queueId}>
{dragQueueId != null && dropIndex === i && (
<div className="drop-indicator" />
)}
<TrackRow
track={entry.track}
num={i + 1}
playing={entry.isPlaying}
actions={[
originalLinkAction(entry.track),
{
icon: <PlayIcon />,
title: t('Play now'),
onClick: () =>
playNow(entry.queueId),
},
{
icon: <CloseIcon />,
title: t('Remove'),
cls: 'danger',
onClick: () =>
safeCall('RemoveFromQueue', {
queueId: entry.queueId,
}),
},
]}
rowProps={{
draggable: !entry.isPlaying,
className:
dragQueueId === entry.queueId
? 'dragging'
: undefined,
onDragStart: () =>
setDragQueueId(entry.queueId),
onDragEnd: () => {
setDragQueueId(null);
setDropIndex(null);
},
onDragOver: (e) => {
e.preventDefault();
const r =
e.currentTarget.getBoundingClientRect();
const after =
e.clientY > r.top + r.height / 2;
setDropIndex(after ? i + 1 : i);
},
onDrop: (e) => {
e.preventDefault();
e.stopPropagation();
commitDrop();
},
}}
/>
</div>
))
)}
{dragQueueId != null &&
dropIndex === s.queue.length &&
s.queue.length > 0 && (
<div className="drop-indicator" />
)}
</div>
</div>
</section>
);
}
-93
View File
@@ -1,93 +0,0 @@
import { useEffect, useState } from 'react';
import { getStoredToken, safeCall, toast } from '../lib/app';
import type { ServerInfo } from '../lib/types';
import { t, tf } from '../i18n';
async function resolveWsUrl(): Promise<string> {
let cfg: { rpcUrl?: string; rpcPort?: number } = {};
try {
cfg = await fetch('/config.json').then((r) => r.json());
} catch {
/* ignore */
}
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
if (cfg.rpcUrl && cfg.rpcUrl.startsWith('/')) {
return `${wsProto}://${location.host}${cfg.rpcUrl}`;
}
if (cfg.rpcUrl && cfg.rpcUrl.length) return cfg.rpcUrl;
return `ws://${location.hostname}:${cfg.rpcPort || 8765}`;
}
export function RpcView() {
const [wsUrl, setWsUrl] = useState('');
const [uptime, setUptime] = useState('');
useEffect(() => {
resolveWsUrl().then(setWsUrl);
safeCall<ServerInfo>('GetServerInfo').then((info) => {
if (info && typeof info.uptimeSeconds === 'number') {
const h = Math.floor(info.uptimeSeconds / 3600);
setUptime(`up ${Math.floor(h / 24)}d ${h % 24}h`);
}
});
}, []);
const token = getStoredToken() || t('(authenticate first)');
const fields: Array<[string, string]> = [
['WEBSOCKET ENDPOINT', wsUrl],
['AUTH TOKEN', token],
[
'PROTOCOL',
'JSON over WebSocket · method names, params as JSON string',
],
];
const snippet = [
`const ws = new WebSocket('${wsUrl}');`,
`ws.onopen = () => ws.send(JSON.stringify({`,
` id: 1, method: 'Authenticate',`,
` params: JSON.stringify({ token: '<your token>' })`,
`}));`,
`ws.onmessage = (e) => console.log(JSON.parse(e.data));`,
].join('\n');
return (
<section className="view" id="view-rpc">
<div className="card">
<div className="card-head">
<h2>{t('Connect programmatically')}</h2>
<span className="pill">{uptime}</span>
</div>
<div className="rpc-fields">
{fields.map(([label, value]) => (
<div key={label} className="rpc-field">
<span className="rpc-label">{label}</span>
<span className="rpc-value">{value}</span>
<button
className="icon-btn"
title={t('Copy')}
onClick={() => {
navigator.clipboard
.writeText(value)
.catch(() => {});
toast(tf('{0} copied', label.toLowerCase()));
}}
>
⧉
</button>
</div>
))}
</div>
<pre className="code-block">{snippet}</pre>
<button
className="btn btn-ghost"
onClick={() => {
navigator.clipboard.writeText(snippet).catch(() => {});
toast(t('Snippet copied'));
}}
>
{t('Copy snippet')}
</button>
</div>
</section>
);
}
@@ -1,123 +0,0 @@
import { useState } from 'react';
import { appStore, loadFavorites, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { sourceInfo } from '../lib/format';
import type { Track } from '../lib/types';
import { HeartIcon } from '../components/icons';
import { t, tf } from '../i18n';
export function SearchView() {
const s = useStore(appStore);
const [query, setQuery] = useState('');
let items = s.searchResults;
if (s.searchTab === 'youtube') {
items = items.filter(
(tr) => (sourceInfo(tr) || {}).label === 'YOUTUBE'
);
}
if (s.searchTab === 'yandex') {
items = items.filter((tr) => (sourceInfo(tr) || {}).label === 'YANDEX');
}
return (
<section className="view" id="view-search">
<form
className="search-row"
onSubmit={async (e) => {
e.preventDefault();
const q = query.trim();
if (!q) return;
toast(tf('Searching “{0}”…', q));
const res = await safeCall<{ tracks?: Track[] }>(
'SearchTracks',
{ query: q }
);
appStore.set({ searchResults: (res && res.tracks) || [] });
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t(
'Search YouTube and Yandex Music… or paste a URL'
)}
autoComplete="off"
/>
<button className="btn btn-accent" type="submit">
{t('Search')}
</button>
</form>
<div className="tabs">
{(['all', 'youtube', 'yandex'] as const).map((tab) => (
<button
key={tab}
className={
'tab' + (s.searchTab === tab ? ' active' : '')
}
onClick={() => appStore.set({ searchTab: tab })}
>
{tab === 'all'
? t('All')
: tab === 'youtube'
? 'YouTube'
: 'Yandex'}
</button>
))}
</div>
<div className="card">
<div className="tracklist">
{!items.length ? (
<EmptyRow
text={t('No results yet — search for something')}
/>
) : (
items.map((tr, i) => (
<TrackRow
key={tr.url || tr.id || i}
track={tr}
num={i + 1}
actions={[
{
icon: '+',
title: t('Add to queue'),
onClick: async () => {
await safeCall('QueueTrack', {
query:
tr.url ||
tr.id ||
tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
{
icon: <HeartIcon />,
title: t('Save to favorites'),
cls:
tr.url && s.favUrls.has(tr.url)
? 'fav-on'
: undefined,
onClick: async () => {
await safeCall('AddFavorite', {
track: tr,
});
toast(t('Saved to favorites'));
loadFavorites();
},
},
]}
/>
))
)}
</div>
</div>
</section>
);
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more