Compare commits
62
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0000c6232f | ||
|
|
884fd2dd19 | ||
|
|
5d06619d66 | ||
|
|
9e6e6ca97b | ||
|
|
ebb1040a71 | ||
|
|
b217d79a2b | ||
|
|
71fb612d99 | ||
|
|
1e83b28e1e | ||
|
|
d2e057988f | ||
|
|
63c5444586 | ||
|
|
8212f13a19 | ||
|
|
8ac39621fd | ||
|
|
5b2d27a1e8 | ||
|
|
3a1dc78a6b | ||
|
|
9236dc844b | ||
|
|
4f8a46b0c4 | ||
|
|
697db046d3 | ||
|
|
ebb751f22c | ||
|
|
9ab17418b5 | ||
|
|
cfcca4e616 | ||
|
|
99f418fbc1 | ||
|
|
4b2008bc2b | ||
|
|
43d655dc58 | ||
|
|
6331fce118 | ||
|
|
0a5323aea7 | ||
|
|
91ed8ac405 | ||
|
|
f418b2f498 | ||
|
|
2c8164584b | ||
|
|
0650d837d3 | ||
|
|
267fe8c743 | ||
|
|
b14ad5d000 | ||
|
|
29e257de51 | ||
|
|
1ec7125a6e | ||
|
|
b6ba851e05 | ||
|
|
2a533a27f8 | ||
|
|
458dde05a6 | ||
|
|
1305d37fae | ||
|
|
f78004e822 | ||
|
|
8c69efc56f | ||
|
|
870a803bd2 | ||
|
|
a2c6dd4c2c | ||
|
|
fb8fb69532 | ||
|
|
1ff935b727 | ||
|
|
d5db7f2d2a | ||
|
|
9401f19ad5 | ||
|
|
30e669359a | ||
|
|
523355a128 | ||
|
|
2e8e1fc0ba | ||
|
|
7dca9db7dc | ||
|
|
5547621cfa | ||
|
|
c08ff6ca68 | ||
|
|
ff25742659 | ||
|
|
6b5b182c33 | ||
|
|
dbddb80b82 | ||
|
|
ecb4cda800 | ||
|
|
41937b2987 | ||
|
|
0b7af2e96a | ||
|
|
bdd69f0aad | ||
|
|
639362fbf5 | ||
|
|
818d391022 | ||
|
|
ef3139ca64 | ||
|
|
2d1d03db1e |
No files matched your search
@@ -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 |
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
.git
|
||||||
|
build*
|
||||||
|
dist
|
||||||
|
release
|
||||||
|
EchoionWeb/frontend/node_modules
|
||||||
|
EchoionWeb/frontend/web-dist
|
||||||
|
components
|
||||||
|
docs
|
||||||
@@ -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="
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -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
|
||||||
@@ -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"
|
||||||
@@ -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
@@ -1,6 +1,22 @@
|
|||||||
*build*
|
*build*
|
||||||
|
!EchoionStandalone/tests/test_update_build_defaults.cpp
|
||||||
|
release
|
||||||
|
/dist/
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
.cache
|
.cache
|
||||||
.idea
|
.idea
|
||||||
AGENTS.md
|
|
||||||
.vscode
|
.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
@@ -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
|
|
||||||
@@ -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?
|
|
||||||
@@ -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!
|
|
||||||
+419
-65
@@ -1,17 +1,27 @@
|
|||||||
cmake_minimum_required(VERSION 4.0.0)
|
cmake_minimum_required(VERSION 4.0.0)
|
||||||
project(Echoion VERSION 1.0.0 LANGUAGES CXX)
|
project(Echoion VERSION 2.0.1 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
|
# Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC
|
||||||
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
|
# falls back to -O0, so "production" builds shipped unoptimised. Set this before
|
||||||
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
|
# any CPMAddPackage() below so fetched dependencies (Void, Boost, quickjs) are
|
||||||
# compiled with the same optimisation level as Echoion itself.
|
# compiled with the same optimisation level as Echoion itself.
|
||||||
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
|
||||||
if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)
|
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
|
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||||
Debug Release RelWithDebInfo MinSizeRel)
|
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()
|
endif()
|
||||||
|
|
||||||
# Use ccache (or sccache) as a compiler launcher when available to speed up
|
# 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()
|
||||||
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
|
# Include CPM
|
||||||
file(
|
file(
|
||||||
DOWNLOAD
|
DOWNLOAD
|
||||||
@@ -34,6 +113,7 @@ file(
|
|||||||
EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791
|
EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791
|
||||||
)
|
)
|
||||||
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)
|
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)
|
||||||
|
include(cmake/EchoionComponents.cmake)
|
||||||
|
|
||||||
# Include PackageProject.cmake
|
# Include PackageProject.cmake
|
||||||
CPMAddPackage(
|
CPMAddPackage(
|
||||||
@@ -50,12 +130,27 @@ CPMAddPackage(
|
|||||||
# which CPM honours over the git checkout below.
|
# which CPM honours over the git checkout below.
|
||||||
CPMAddPackage(
|
CPMAddPackage(
|
||||||
NAME Void
|
NAME Void
|
||||||
GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git
|
GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git
|
||||||
GIT_TAG main
|
# Keep clean/container releases reproducible. CPM_Void_SOURCE still
|
||||||
|
# overrides this revision for local dependency development.
|
||||||
|
GIT_TAG ${ECHOION_VOID_REVISION}
|
||||||
OPTIONS
|
OPTIONS
|
||||||
"VOID_ENABLE_TESTING OFF"
|
"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 26)
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
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)
|
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.
|
# 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>:-freflection>)
|
||||||
|
|
||||||
|
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fno-omit-frame-pointer>)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Link-time optimisation for Release configs only (keeps Debug builds fast).
|
# Link-time optimisation for Release configs only (keeps Debug builds fast).
|
||||||
@@ -102,100 +199,247 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
|
|||||||
|
|
||||||
# Options
|
# Options
|
||||||
option(BUILD_API "Build EchoionApi" ON)
|
option(BUILD_API "Build EchoionApi" ON)
|
||||||
|
option(BUILD_HOST "Build EchoionHost module loader" ON)
|
||||||
option(BUILD_CORE "Build EchoionCore" ON)
|
option(BUILD_CORE "Build EchoionCore" ON)
|
||||||
option(BUILD_PLUGIN "Build EchoionPlugin" ON)
|
|
||||||
option(BUILD_DESKTOP "Build EchoionDesktop" 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_PROTOCOL "Build EchoionProtocol (native TeamSpeak UDP client)" ON)
|
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
|
||||||
option(BUILD_STANDALONE "Build EchoionStandalone (daemon; no 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_TESTS "Build tests" OFF)
|
||||||
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
|
set(ECHOION_COMPONENT_WORKSPACE
|
||||||
option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON)
|
"${CMAKE_CURRENT_SOURCE_DIR}/.."
|
||||||
|
CACHE PATH "Directory containing permanent Echoion component repositories")
|
||||||
|
|
||||||
# Static linking configuration
|
if(BUILD_TESTS)
|
||||||
if(ECHOION_STATIC_LINK)
|
enable_testing()
|
||||||
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")
|
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Find packages
|
# Find packages
|
||||||
find_package(Threads REQUIRED)
|
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)
|
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()
|
endif()
|
||||||
|
|
||||||
if(BUILD_CORE)
|
if(BUILD_CORE)
|
||||||
add_subdirectory(EchoionCore)
|
echoion_add_component(EchoionCore)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# EchoionWeb is added after Core so it can reuse the single Boost header
|
# 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
|
# 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.
|
# here (both targets now exist) and flag Core so the wiring compiles in.
|
||||||
if(BUILD_WEB AND BUILD_CORE)
|
if(BUILD_WEB AND BUILD_CORE)
|
||||||
add_subdirectory(EchoionWeb)
|
echoion_add_component(EchoionWeb)
|
||||||
if(TARGET EchoionCore AND TARGET EchoionWeb)
|
if(TARGET EchoionCore AND TARGET EchoionWeb)
|
||||||
target_link_libraries(EchoionCore PRIVATE EchoionWeb)
|
target_link_libraries(EchoionCore PRIVATE EchoionWeb)
|
||||||
target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
|
target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB)
|
||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(BUILD_PLUGIN)
|
# VoidTeamspeak is resolved above as a regular reusable package. The legacy
|
||||||
add_subdirectory(EchoionPlugin)
|
# 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()
|
endif()
|
||||||
|
|
||||||
# EchoionProtocol: standalone TeamSpeak UDP client library (no Echoion deps).
|
# EchoionStandalone links the host-common loader and native protocol client.
|
||||||
if(BUILD_PROTOCOL OR BUILD_STANDALONE)
|
|
||||||
add_subdirectory(EchoionProtocol)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# EchoionStandalone: reuses the plugin's CoreLoader, so it needs EchoionPlugin's
|
|
||||||
# sources present. It links the Api + EchoionProtocol and loads Core at runtime.
|
|
||||||
if(BUILD_STANDALONE)
|
if(BUILD_STANDALONE)
|
||||||
add_subdirectory(EchoionStandalone)
|
echoion_add_component(EchoionStandalone)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(BUILD_DESKTOP)
|
if(BUILD_DESKTOP)
|
||||||
add_subdirectory(EchoionDesktop)
|
echoion_add_component(EchoionDesktop)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Tests
|
# The release install component is deliberately runtime-only. Nested projects
|
||||||
if(BUILD_TESTS)
|
# keep their normal SDK/development install rules, while scripts/release.sh uses
|
||||||
enable_testing()
|
# this component as the single input to dependency collection and packaging.
|
||||||
add_subdirectory(tests)
|
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()
|
endif()
|
||||||
|
|
||||||
# Packaging configuration
|
# Independent component package staging. Each named install component contains
|
||||||
include(CPack)
|
# only that component's first-party payload; release tooling adds its private
|
||||||
set(CPACK_PACKAGE_NAME "Echoion")
|
# runtime dependency closure and a signed-feed manifest afterwards.
|
||||||
set(CPACK_PACKAGE_VENDOR "Echoion")
|
option(ECHOION_INSTALL_COMPONENT_PACKAGES
|
||||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak")
|
"Provide one install component for every independently released component"
|
||||||
set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
|
ON)
|
||||||
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
|
if(ECHOION_INSTALL_COMPONENT_PACKAGES)
|
||||||
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
|
if(TARGET EchoionApiPluginSdk)
|
||||||
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE")
|
install(TARGETS EchoionApiPluginSdk
|
||||||
set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md")
|
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(TARGET EchoionHost)
|
||||||
if(WIN32)
|
install(TARGETS EchoionHost
|
||||||
set(CPACK_GENERATOR "ZIP;NSIS")
|
LIBRARY DESTINATION lib
|
||||||
set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot")
|
COMPONENT PackageEchoionHost
|
||||||
set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion")
|
RUNTIME DESTINATION bin
|
||||||
set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion")
|
COMPONENT PackageEchoionHost)
|
||||||
elseif(APPLE)
|
install(FILES "${EchoionHost_SOURCE_DIR}/abi/module.json"
|
||||||
set(CPACK_GENERATOR "DragNDMGZ")
|
DESTINATION abi
|
||||||
set(CPACK_DMG_VOLUME_NAME "Echoion")
|
COMPONENT PackageEchoionHost)
|
||||||
else()
|
endif()
|
||||||
set(CPACK_GENERATOR "TGZ;DEB;RPM")
|
|
||||||
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0")
|
if(TARGET EchoionCore)
|
||||||
set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite")
|
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()
|
endif()
|
||||||
|
|
||||||
# Bundling and deployment helpers
|
# Bundling and deployment helpers
|
||||||
include(GNUInstallDirs)
|
|
||||||
|
|
||||||
# Function to bundle Qt dependencies
|
# Function to bundle Qt dependencies
|
||||||
function(bundle_qt_dependencies target)
|
function(bundle_qt_dependencies target)
|
||||||
if(NOT TARGET ${target})
|
if(NOT TARGET ${target})
|
||||||
@@ -269,24 +513,134 @@ if(BUILD_CORE AND TARGET EchoionCore)
|
|||||||
install_with_dependencies(EchoionCore)
|
install_with_dependencies(EchoionCore)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
if(BUILD_PLUGIN AND TARGET EchoionPlugin)
|
if(BUILD_TESTS AND UNIX)
|
||||||
install_with_dependencies(EchoionPlugin)
|
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)
|
||||||
|
foreach(_echoionTestComponent IN ITEMS
|
||||||
|
EchoionHost EchoionCore EchoionWeb
|
||||||
|
EchoionPluginUrlShortenerInternal
|
||||||
|
EchoionPluginUrlShortenerExternal)
|
||||||
|
string(JSON _echoionTestComponentVersion GET
|
||||||
|
"${_echoionComponentLockJson}"
|
||||||
|
components "${_echoionTestComponent}" componentVersion)
|
||||||
|
set("_echoionTestVersion${_echoionTestComponent}"
|
||||||
|
"${_echoionTestComponentVersion}")
|
||||||
|
endforeach()
|
||||||
|
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>\""
|
||||||
|
"ECHOION_TEST_HOST_VERSION=\"${_echoionTestVersionEchoionHost}\""
|
||||||
|
"ECHOION_TEST_CORE_VERSION=\"${_echoionTestVersionEchoionCore}\""
|
||||||
|
"ECHOION_TEST_WEB_VERSION=\"${_echoionTestVersionEchoionWeb}\""
|
||||||
|
"ECHOION_TEST_PLUGIN_INTERNAL_VERSION=\"${_echoionTestVersionEchoionPluginUrlShortenerInternal}\""
|
||||||
|
"ECHOION_TEST_PLUGIN_EXTERNAL_VERSION=\"${_echoionTestVersionEchoionPluginUrlShortenerExternal}\"")
|
||||||
|
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()
|
endif()
|
||||||
|
|
||||||
# Print configuration summary
|
# Print configuration summary
|
||||||
message(STATUS "")
|
message(STATUS "")
|
||||||
message(STATUS "Echoion Configuration:")
|
message(STATUS "Echoion Configuration:")
|
||||||
message(STATUS " Version: ${PROJECT_VERSION}")
|
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 " C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||||
message(STATUS " Build API: ${BUILD_API}")
|
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 Core: ${BUILD_CORE}")
|
||||||
message(STATUS " Build Plugin: ${BUILD_PLUGIN}")
|
|
||||||
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
|
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 " Build Tests: ${BUILD_TESTS}")
|
||||||
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
|
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
|
||||||
|
message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}")
|
||||||
message(STATUS "")
|
message(STATUS "")
|
||||||
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
|
message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}")
|
||||||
message(STATUS "To build: cmake --build build")
|
message(STATUS "To build: cmake --build build")
|
||||||
message(STATUS "To install: cmake --install build --prefix <install_dir>")
|
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 "")
|
message(STATUS "")
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
-1
Submodule EchoionApi deleted from e7573fbcd0.
-1
Submodule EchoionCore deleted from 5c036d91fb.
Submodule EchoionDesktop deleted from 2aa44fae9e.
Submodule EchoionPlugin deleted from 470ab507e1.
@@ -1,49 +0,0 @@
|
|||||||
# EchoionProtocol — reverse-engineered TeamSpeak 3/6 full-client voice protocol.
|
|
||||||
#
|
|
||||||
# Deliberately dependency-isolated: it knows nothing about Echoion::Api, Void or
|
|
||||||
# reflection. It links only OpenSSL (crypto), libopus (voice) and a vendored
|
|
||||||
# QuickLZ. This keeps it independently unit-testable and reusable, and lets it
|
|
||||||
# build with a plain C++20 toolchain even though the rest of Echoion needs
|
|
||||||
# C++26/reflection.
|
|
||||||
|
|
||||||
cmake_minimum_required(VERSION 3.24)
|
|
||||||
|
|
||||||
# Allow standalone configuration (own build) as well as add_subdirectory() from
|
|
||||||
# the Echoion root.
|
|
||||||
if(NOT DEFINED PROJECT_NAME)
|
|
||||||
project(EchoionProtocol LANGUAGES CXX)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
option(ECHOIONPROTOCOL_BUILD_TESTS "Build EchoionProtocol unit tests" OFF)
|
|
||||||
|
|
||||||
find_package(OpenSSL REQUIRED)
|
|
||||||
|
|
||||||
find_package(PkgConfig QUIET)
|
|
||||||
if(PkgConfig_FOUND)
|
|
||||||
pkg_check_modules(OPUS IMPORTED_TARGET opus)
|
|
||||||
# libsodium provides the raw Ed25519 point arithmetic the TS6 license chain
|
|
||||||
# (initivexpand2) needs; OpenSSL cannot do it.
|
|
||||||
pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
file(GLOB ECHOIONPROTOCOL_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
|
|
||||||
|
|
||||||
add_library(EchoionProtocol STATIC ${ECHOIONPROTOCOL_SOURCES})
|
|
||||||
add_library(Echoion::Protocol ALIAS EchoionProtocol)
|
|
||||||
|
|
||||||
target_include_directories(EchoionProtocol
|
|
||||||
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
|
|
||||||
|
|
||||||
# This target is standalone C++20 on purpose — do not inherit the tree's C++26.
|
|
||||||
target_compile_features(EchoionProtocol PUBLIC cxx_std_20)
|
|
||||||
|
|
||||||
target_link_libraries(EchoionProtocol PUBLIC OpenSSL::Crypto PkgConfig::SODIUM)
|
|
||||||
if(TARGET PkgConfig::OPUS)
|
|
||||||
target_link_libraries(EchoionProtocol PUBLIC PkgConfig::OPUS)
|
|
||||||
target_compile_definitions(EchoionProtocol PUBLIC ECHOION_HAVE_OPUS=1)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if(ECHOIONPROTOCOL_BUILD_TESTS OR BUILD_TESTS)
|
|
||||||
enable_testing()
|
|
||||||
add_subdirectory(tests)
|
|
||||||
endif()
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
# EchoionProtocol
|
|
||||||
|
|
||||||
A native C++ implementation of the TeamSpeak 3/6 **full-client voice protocol**,
|
|
||||||
so Echoion can connect to a TeamSpeak server as its own client — no TeamSpeak
|
|
||||||
client and no plugin required. Ported from
|
|
||||||
[ts6-manager](https://github.com/clusterzx/ts6-manager)'s `tslib` (MIT) and
|
|
||||||
cross-checked against ReSpeak's protocol documentation.
|
|
||||||
|
|
||||||
TeamSpeak 6 has **no WebRTC voice** — its voice is still the legacy TS3 UDP
|
|
||||||
protocol on port 9987, which this library speaks.
|
|
||||||
|
|
||||||
## Modules
|
|
||||||
|
|
||||||
| Module | Purpose |
|
|
||||||
|--------|---------|
|
|
||||||
| `Crypto` | AES-128-EAX (composed from AES-CTR + CMAC/OMAC1), per-packet key/nonce derivation, SHA hashes. **Byte-verified against RFC 4493 (CMAC) and the EAX spec test vectors.** |
|
|
||||||
| `Identity` | ECDSA P-256 identity, libtomcrypt public-key export ("omega"), uid, hashcash security-level. OpenSSL. |
|
|
||||||
| `License` | TS6 `initivexpand2` license chain — Ed25519 point arithmetic via libsodium. |
|
|
||||||
| `Command` | TS3 escaped `key=value` command serialization + notify parsing. |
|
|
||||||
| `QuickLz` | QuickLZ level-1 decompression for compressed command packets. |
|
|
||||||
| `TsClient` | UDP socket, handshake (`init0`–`init4` + RSA puzzle, `clientinitiv`, `initivexpand`/`initivexpand2`), per-packet crypto, ack/resend, keepalive, voice/whisper send, event callbacks. |
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
OpenSSL (crypto), libsodium (Ed25519), libopus (only consumed by the host's
|
|
||||||
audio encoder, not this library). No Boost, no Void, no reflection — plain C++20,
|
|
||||||
independently buildable and testable.
|
|
||||||
|
|
||||||
## Build & test standalone
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cmake -S . -B build -DECHOIONPROTOCOL_BUILD_TESTS=ON
|
|
||||||
cmake --build build
|
|
||||||
./build/tests/echoion_protocol_tests
|
|
||||||
```
|
|
||||||
|
|
||||||
## Verified
|
|
||||||
|
|
||||||
- Unit tests: CMAC (RFC 4493), EAX (spec vectors), SHA-1, base64, command
|
|
||||||
escaping, QuickLZ, identity uid/security-level/sign, save/load.
|
|
||||||
- **Live handshake**: connects to a real TeamSpeak 3 server (Docker) through the
|
|
||||||
full handshake and appears in the server's client list.
|
|
||||||
|
|
||||||
## Not yet integration-tested against a live server
|
|
||||||
|
|
||||||
Audio audibility to a second client, whisper targeting, and inbound-command
|
|
||||||
event mapping are implemented but need a full end-to-end run with Core.
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// TS3 command wire format: "commandname key=value key=value|key=value".
|
|
||||||
// Ported from ts6-manager tslib/commands.ts.
|
|
||||||
|
|
||||||
#include <map>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
|
|
||||||
// Escape / unescape a single token per the TS3 rules
|
|
||||||
// (\\ \/ \s \p \f \n \r \t \v).
|
|
||||||
std::string tsEscape(const std::string& str);
|
|
||||||
std::string tsUnescape(const std::string& str);
|
|
||||||
|
|
||||||
// Ordered key/value params for a command. std::map keeps a stable order so
|
|
||||||
// serialization is deterministic (helpful for tests); the server does not
|
|
||||||
// care about ordering.
|
|
||||||
using CommandParams = std::map<std::string, std::string>;
|
|
||||||
|
|
||||||
struct ParsedCommand {
|
|
||||||
std::string name;
|
|
||||||
CommandParams params; // first group
|
|
||||||
std::vector<CommandParams> groups; // all '|'-separated groups
|
|
||||||
};
|
|
||||||
|
|
||||||
// Serialize "name k=v k=v". Empty values are emitted as "k=".
|
|
||||||
std::string buildCommand(const std::string& name,
|
|
||||||
const CommandParams& params);
|
|
||||||
|
|
||||||
// Parse a raw command / notify line into name + params (+ pipe groups).
|
|
||||||
ParsedCommand parseCommand(const std::string& raw);
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Low-level cryptographic primitives for the TeamSpeak 3/6 full-client voice
|
|
||||||
// protocol. Ported byte-for-byte from ts6-manager's tslib/crypto.ts (MIT) so the
|
|
||||||
// on-wire behaviour is identical; implemented over OpenSSL EVP.
|
|
||||||
//
|
|
||||||
// The protocol uses AES-128-EAX for per-packet authenticated encryption. OpenSSL
|
|
||||||
// has no native EAX, so — exactly like the reference — we compose it from
|
|
||||||
// AES-128-CTR (confidentiality) and AES-128-CMAC / OMAC1 (authenticity).
|
|
||||||
|
|
||||||
#include <array>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <optional>
|
|
||||||
#include <span>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol::Crypto
|
|
||||||
{
|
|
||||||
|
|
||||||
using Bytes = std::vector<uint8_t>;
|
|
||||||
using ByteView = std::span<const uint8_t>;
|
|
||||||
|
|
||||||
inline constexpr size_t BLOCK_SIZE = 16;
|
|
||||||
inline constexpr size_t MAC_LEN = 8;
|
|
||||||
|
|
||||||
// "TS3INIT1" — the fake/static MAC stamped on low-level init packets before a
|
|
||||||
// shared secret exists.
|
|
||||||
inline constexpr std::array<uint8_t, 8> INIT_MAC = {'T', 'S', '3', 'I',
|
|
||||||
'N', 'I', 'T', '1'};
|
|
||||||
|
|
||||||
// "c:\\windows\\syste" / "m\\firewall32.cpl" — the fixed key/nonce used to
|
|
||||||
// (de)crypt command packets during the handshake, before key exchange.
|
|
||||||
inline constexpr std::array<uint8_t, 16> DUMMY_KEY = {
|
|
||||||
'c', ':', '\\', 'w', 'i', 'n', 'd', 'o',
|
|
||||||
'w', 's', '\\', 's', 'y', 's', 't', 'e'};
|
|
||||||
inline constexpr std::array<uint8_t, 16> DUMMY_NONCE = {
|
|
||||||
'm', '\\', 'f', 'i', 'r', 'e', 'w', 'a',
|
|
||||||
'l', 'l', '3', '2', '.', 'c', 'p', 'l'};
|
|
||||||
|
|
||||||
// Client version signature used in clientinit (3.5.0 [Stable]).
|
|
||||||
inline constexpr uint32_t INIT_VERSION = 1566914096u;
|
|
||||||
|
|
||||||
// --- Hashes -------------------------------------------------------------
|
|
||||||
std::array<uint8_t, 20> sha1(ByteView data);
|
|
||||||
std::array<uint8_t, 32> sha256(ByteView data);
|
|
||||||
std::array<uint8_t, 64> sha512(ByteView data);
|
|
||||||
|
|
||||||
// --- XOR helpers --------------------------------------------------------
|
|
||||||
// out[i] = a[i] ^ b[i] for i in [0, min(a,b)).
|
|
||||||
Bytes xorBuffers(ByteView a, ByteView b);
|
|
||||||
// a[i] ^= b[i] for i in [0, len). Caller guarantees bounds.
|
|
||||||
void xorInto(std::span<uint8_t> a, ByteView b, size_t len);
|
|
||||||
|
|
||||||
// --- AES-128-CMAC (OMAC1) ----------------------------------------------
|
|
||||||
// 16-byte MAC over `data` under the 16-byte `key`.
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data);
|
|
||||||
|
|
||||||
// --- AES-128-EAX --------------------------------------------------------
|
|
||||||
struct EaxResult {
|
|
||||||
Bytes ciphertext;
|
|
||||||
std::array<uint8_t, MAC_LEN> mac;
|
|
||||||
};
|
|
||||||
// Encrypt `plaintext` with 16-byte `key`, `nonce` and associated `header`.
|
|
||||||
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
|
|
||||||
ByteView plaintext);
|
|
||||||
// Decrypt/verify; returns nullopt on MAC mismatch.
|
|
||||||
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
|
|
||||||
ByteView header, ByteView ciphertext,
|
|
||||||
ByteView mac);
|
|
||||||
|
|
||||||
// --- Per-packet key/nonce derivation -----------------------------------
|
|
||||||
struct KeyNonce {
|
|
||||||
std::array<uint8_t, 16> key;
|
|
||||||
std::array<uint8_t, 16> nonce;
|
|
||||||
};
|
|
||||||
// Derive the packet key+nonce from the connection `ivStruct` (20 bytes for
|
|
||||||
// the SHA1 handshake secret, 64 bytes for the license path), keyed by
|
|
||||||
// direction, packet id, generation and packet type.
|
|
||||||
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
|
|
||||||
uint32_t generationId, uint8_t packetType,
|
|
||||||
ByteView ivStruct);
|
|
||||||
|
|
||||||
// --- Misc ---------------------------------------------------------------
|
|
||||||
// base64(sha1(utf8(password))); empty string for empty password.
|
|
||||||
std::string hashPassword(const std::string& password);
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol::Crypto
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// TeamSpeak client identity: an ECDSA P-256 keypair plus the libtomcrypt-style
|
|
||||||
// public-key export ("omega"), the derived unique-id, and the hashcash
|
|
||||||
// key-offset that raises the identity's "security level".
|
|
||||||
// Ported from ts6-manager tslib/identity.ts.
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <memory>
|
|
||||||
#include <span>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
|
|
||||||
class Identity
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
|
|
||||||
using Bytes = std::vector<uint8_t>;
|
|
||||||
using ByteView = std::span<const uint8_t>;
|
|
||||||
|
|
||||||
// Generate a fresh identity and raise it to at least `securityLevel`
|
|
||||||
// leading-zero bits (hashcash over the public key + offset).
|
|
||||||
static Identity generate(int securityLevel = 8);
|
|
||||||
|
|
||||||
// Load / save the identity to a small text file:
|
|
||||||
// privateKeyPem, publicKeyString, keyOffset (one per line).
|
|
||||||
static Identity load(const std::string& path);
|
|
||||||
void save(const std::string& path) const;
|
|
||||||
|
|
||||||
// libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv).
|
|
||||||
const std::string& publicKeyString() const { return publicKeyString_; }
|
|
||||||
// base64(sha1(ascii(publicKeyString))).
|
|
||||||
const std::string& uid() const { return uid_; }
|
|
||||||
uint64_t keyOffset() const { return keyOffset_; }
|
|
||||||
int securityLevel() const;
|
|
||||||
|
|
||||||
// ECDSA sign `data` with SHA-256; returns the raw signature.
|
|
||||||
Bytes sign(ByteView data) const;
|
|
||||||
|
|
||||||
// ECDH(this private key, server public key) → SHA-1 of the shared
|
|
||||||
// x-coordinate. `serverPublicKeyDer` is the libtomcrypt DER blob
|
|
||||||
// (base64-decoded "omega" from initivexpand).
|
|
||||||
Bytes sharedSecret(ByteView serverPublicKeyDer) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
Identity() = default;
|
|
||||||
|
|
||||||
struct PKeyDeleter {
|
|
||||||
void operator()(void* p) const noexcept;
|
|
||||||
};
|
|
||||||
// EVP_PKEY* held opaquely so this header stays OpenSSL-free.
|
|
||||||
std::shared_ptr<void> pkey_;
|
|
||||||
std::string publicKeyString_;
|
|
||||||
std::string uid_;
|
|
||||||
uint64_t keyOffset_ = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// TeamSpeak license chain handling for the modern handshake (initivexpand2).
|
|
||||||
// The chain is walked with Ed25519 point arithmetic (scalar-mult + point-add),
|
|
||||||
// which OpenSSL does not expose, so this module uses libsodium.
|
|
||||||
// Ported from ts6-manager tslib/license.ts.
|
|
||||||
|
|
||||||
#include <array>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <span>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
|
|
||||||
using Bytes = std::vector<uint8_t>;
|
|
||||||
using ByteView = std::span<const uint8_t>;
|
|
||||||
|
|
||||||
struct LicenseBlock {
|
|
||||||
std::array<uint8_t, 32> key;
|
|
||||||
std::array<uint8_t, 32> hash; // first 32 bytes of SHA-512(content)
|
|
||||||
uint8_t type = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct TempKey {
|
|
||||||
std::array<uint8_t, 32> publicKey;
|
|
||||||
std::array<uint8_t, 32> privateKey;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Parse the server license blob into its chain of blocks.
|
|
||||||
std::vector<LicenseBlock> parseLicense(ByteView data);
|
|
||||||
|
|
||||||
// Walk the chain from the root key to the final server public key (32 bytes).
|
|
||||||
std::array<uint8_t, 32>
|
|
||||||
deriveLicenseKey(const std::vector<LicenseBlock>& blocks);
|
|
||||||
|
|
||||||
// Generate an ephemeral Ed25519 keypair (clamped like the reference).
|
|
||||||
TempKey generateTemporaryKey();
|
|
||||||
|
|
||||||
// initivexpand2 shared secret: SHA-512( tempPriv * serverDerivedKey ),
|
|
||||||
// 64 bytes. Returns the raw digest.
|
|
||||||
std::array<uint8_t, 64>
|
|
||||||
getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey);
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// QuickLZ level-1 decompression, used to inflate compressed command packets.
|
|
||||||
// Clients send commands uncompressed, so only decompression is needed.
|
|
||||||
// Ported from ts6-manager tslib/quicklz.ts (itself from TSLib QuickerLz.cs).
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <span>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
|
|
||||||
using Bytes = std::vector<uint8_t>;
|
|
||||||
using ByteView = std::span<const uint8_t>;
|
|
||||||
|
|
||||||
uint32_t qlzDecompressedSize(ByteView data);
|
|
||||||
uint32_t qlzCompressedSize(ByteView data);
|
|
||||||
|
|
||||||
// Throws std::runtime_error on malformed input or unsupported level.
|
|
||||||
Bytes qlzDecompress(ByteView data);
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Full-client connection to a TeamSpeak 3/6 server over the native UDP voice
|
|
||||||
// protocol. Owns the socket, handshake, per-packet crypto, resend/keepalive and
|
|
||||||
// voice send path. Ported from ts6-manager tslib/client.ts.
|
|
||||||
//
|
|
||||||
// Threading: a single background thread runs the receive + timer loop. Public
|
|
||||||
// send methods are thread-safe (guarded by an internal mutex) so the audio
|
|
||||||
// thread can call sendVoice() directly. Callbacks fire on the loop thread.
|
|
||||||
|
|
||||||
#include "echoion/protocol/Command.hpp"
|
|
||||||
#include "echoion/protocol/Identity.hpp"
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <functional>
|
|
||||||
#include <map>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
#include <span>
|
|
||||||
#include <string>
|
|
||||||
#include <thread>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
|
|
||||||
enum class PacketType : uint8_t {
|
|
||||||
Voice = 0,
|
|
||||||
VoiceWhisper = 1,
|
|
||||||
Command = 2,
|
|
||||||
CommandLow = 3,
|
|
||||||
Ping = 4,
|
|
||||||
Pong = 5,
|
|
||||||
Ack = 6,
|
|
||||||
AckLow = 7,
|
|
||||||
Init1 = 8,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum class ClientState {
|
|
||||||
Disconnected,
|
|
||||||
Init,
|
|
||||||
Handshake,
|
|
||||||
Connected,
|
|
||||||
Disconnecting,
|
|
||||||
};
|
|
||||||
|
|
||||||
struct TsClientOptions {
|
|
||||||
std::string host;
|
|
||||||
uint16_t port = 9987;
|
|
||||||
const Identity* identity = nullptr; // not owned
|
|
||||||
std::string nickname = "EchoionBot";
|
|
||||||
std::string serverPassword;
|
|
||||||
std::string defaultChannel; // channel id or name
|
|
||||||
std::string channelPassword;
|
|
||||||
};
|
|
||||||
|
|
||||||
// All callbacks fire on the internal loop thread.
|
|
||||||
struct TsClientCallbacks {
|
|
||||||
std::function<void()> onConnected;
|
|
||||||
std::function<void()> onDisconnected;
|
|
||||||
std::function<void(const std::string&)> onError;
|
|
||||||
std::function<void(const ParsedCommand&)> onCommand;
|
|
||||||
std::function<void(const CommandParams&)> onTextMessage;
|
|
||||||
std::function<void(std::span<const uint8_t>)> onVoice;
|
|
||||||
std::function<void(const std::string&)> onDebug;
|
|
||||||
};
|
|
||||||
|
|
||||||
class TsClient
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
|
|
||||||
TsClient();
|
|
||||||
~TsClient();
|
|
||||||
|
|
||||||
TsClient(const TsClient&) = delete;
|
|
||||||
TsClient& operator=(const TsClient&) = delete;
|
|
||||||
|
|
||||||
void setCallbacks(TsClientCallbacks cb) { cb_ = std::move(cb); }
|
|
||||||
|
|
||||||
// Begin connecting. Returns immediately; onConnected/onError fire
|
|
||||||
// asynchronously. Throws only on immediate socket setup failure.
|
|
||||||
void connect(const TsClientOptions& opts);
|
|
||||||
// Graceful: send clientdisconnect, then close.
|
|
||||||
void disconnect();
|
|
||||||
// Immediate close, no disconnect command.
|
|
||||||
void forceClose();
|
|
||||||
|
|
||||||
ClientState state() const { return state_.load(); }
|
|
||||||
uint16_t clientId() const { return clientId_.load(); }
|
|
||||||
|
|
||||||
// Send one already-Opus-encoded 20 ms frame to the current channel.
|
|
||||||
void sendVoice(std::span<const uint8_t> opus);
|
|
||||||
// Whisper the frame to the given channel/client targets.
|
|
||||||
void sendWhisper(std::span<const uint8_t> opus,
|
|
||||||
const std::vector<uint64_t>& channelIds,
|
|
||||||
const std::vector<uint16_t>& clientIds);
|
|
||||||
// End-of-voice marker (empty frame).
|
|
||||||
void sendVoiceStop();
|
|
||||||
|
|
||||||
// Send a raw pre-built TS3 command line (fragmented if large).
|
|
||||||
void sendCommand(const std::string& cmd);
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
// ---- packet path ----
|
|
||||||
void loopThread();
|
|
||||||
void handleIncomingPacket(std::span<const uint8_t> raw);
|
|
||||||
void sendOutgoing(std::span<const uint8_t> data, PacketType type,
|
|
||||||
uint8_t extraFlags = 0);
|
|
||||||
std::vector<uint8_t> buildRawPacket(std::span<const uint8_t> data,
|
|
||||||
PacketType type,
|
|
||||||
uint16_t packetId,
|
|
||||||
uint8_t flags);
|
|
||||||
void encryptPacket(std::vector<uint8_t>& raw, PacketType type,
|
|
||||||
uint16_t packetId, uint32_t gen, uint8_t flags,
|
|
||||||
std::span<const uint8_t> data);
|
|
||||||
std::vector<uint8_t> decryptPacket(std::span<const uint8_t> raw,
|
|
||||||
PacketType type,
|
|
||||||
uint16_t packetId, uint32_t gen,
|
|
||||||
uint8_t flags, bool& ok);
|
|
||||||
void sendRawLocked(const std::vector<uint8_t>& raw);
|
|
||||||
void sendInitPacket(const std::vector<uint8_t>& data);
|
|
||||||
|
|
||||||
// ---- handshake / commands ----
|
|
||||||
std::vector<uint8_t> buildInit0();
|
|
||||||
void handleInit(std::span<const uint8_t> data);
|
|
||||||
void handleCommandData(std::span<const uint8_t> data, uint8_t flags);
|
|
||||||
void processCommand(std::span<const uint8_t> data, uint8_t flags);
|
|
||||||
void handleInitIvExpand(const CommandParams& params);
|
|
||||||
void handleInitIvExpand2(const CommandParams& params);
|
|
||||||
void sendClientInit();
|
|
||||||
void handleInitServer(const CommandParams& params);
|
|
||||||
void handleChannelList(const ParsedCommand& parsed);
|
|
||||||
void handleChannelListFinished();
|
|
||||||
|
|
||||||
void sendAck(uint16_t ackId, PacketType ackType);
|
|
||||||
void handlePing(uint16_t packetId);
|
|
||||||
void resendTick();
|
|
||||||
void debug(const std::string& msg);
|
|
||||||
void cleanup();
|
|
||||||
|
|
||||||
// counters / crypto
|
|
||||||
struct Counter {
|
|
||||||
uint16_t id = 0;
|
|
||||||
uint32_t gen = 0;
|
|
||||||
};
|
|
||||||
Counter getCounter(PacketType type);
|
|
||||||
void incCounter(PacketType type);
|
|
||||||
|
|
||||||
TsClientOptions opts_;
|
|
||||||
TsClientCallbacks cb_;
|
|
||||||
|
|
||||||
int sock_ = -1;
|
|
||||||
std::atomic<ClientState> state_{ClientState::Disconnected};
|
|
||||||
std::atomic<uint16_t> clientId_{0};
|
|
||||||
|
|
||||||
std::thread thread_;
|
|
||||||
std::atomic<bool> running_{false};
|
|
||||||
// Recursive: command handlers running under the loop lock call
|
|
||||||
// sendCommand()/sendOutgoing() which re-lock.
|
|
||||||
mutable std::recursive_mutex mu_;
|
|
||||||
int64_t disconnectDeadline_ = 0;
|
|
||||||
|
|
||||||
std::array<uint16_t, 9> packetCounter_{};
|
|
||||||
std::array<uint32_t, 9> generationCounter_{};
|
|
||||||
|
|
||||||
bool cryptoInitComplete_ = false;
|
|
||||||
std::vector<uint8_t> ivStruct_;
|
|
||||||
std::array<uint8_t, 8> fakeSignature_{};
|
|
||||||
std::vector<uint8_t> alphaTmp_;
|
|
||||||
|
|
||||||
// resend tracking
|
|
||||||
struct Resend {
|
|
||||||
std::vector<uint8_t> raw;
|
|
||||||
uint16_t packetId = 0;
|
|
||||||
int64_t firstSend = 0;
|
|
||||||
int64_t lastSend = 0;
|
|
||||||
};
|
|
||||||
std::map<uint16_t, Resend> resendMap_;
|
|
||||||
std::unique_ptr<Resend> initResend_;
|
|
||||||
int64_t lastMessageTime_ = 0;
|
|
||||||
int64_t lastPing_ = 0;
|
|
||||||
int64_t connectStart_ = 0;
|
|
||||||
|
|
||||||
// fragment reassembly
|
|
||||||
std::vector<uint8_t> fragmentBuffer_;
|
|
||||||
bool fragmenting_ = false;
|
|
||||||
uint8_t fragmentFlags_ = 0;
|
|
||||||
|
|
||||||
// channel map for auto-move
|
|
||||||
std::map<std::string, uint64_t> channelMap_;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Small dependency-free encoding helpers shared across the protocol modules.
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <span>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol::Util
|
|
||||||
{
|
|
||||||
|
|
||||||
using Bytes = std::vector<uint8_t>;
|
|
||||||
using ByteView = std::span<const uint8_t>;
|
|
||||||
|
|
||||||
// Standard base64 (RFC 4648) with '+' '/' and '=' padding.
|
|
||||||
std::string base64Encode(ByteView data);
|
|
||||||
Bytes base64Decode(const std::string& text);
|
|
||||||
|
|
||||||
// Lowercase hex, no separators.
|
|
||||||
std::string toHex(ByteView data);
|
|
||||||
Bytes fromHex(const std::string& hex);
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol::Util
|
|
||||||
@@ -1,184 +0,0 @@
|
|||||||
#include "echoion/protocol/Command.hpp"
|
|
||||||
|
|
||||||
#include <sstream>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
|
|
||||||
std::string tsEscape(const std::string& str)
|
|
||||||
{
|
|
||||||
std::string out;
|
|
||||||
out.reserve(str.size());
|
|
||||||
for (char c : str) {
|
|
||||||
switch (c) {
|
|
||||||
case '\\':
|
|
||||||
out += "\\\\";
|
|
||||||
break;
|
|
||||||
case '/':
|
|
||||||
out += "\\/";
|
|
||||||
break;
|
|
||||||
case ' ':
|
|
||||||
out += "\\s";
|
|
||||||
break;
|
|
||||||
case '|':
|
|
||||||
out += "\\p";
|
|
||||||
break;
|
|
||||||
case '\f':
|
|
||||||
out += "\\f";
|
|
||||||
break;
|
|
||||||
case '\n':
|
|
||||||
out += "\\n";
|
|
||||||
break;
|
|
||||||
case '\r':
|
|
||||||
out += "\\r";
|
|
||||||
break;
|
|
||||||
case '\t':
|
|
||||||
out += "\\t";
|
|
||||||
break;
|
|
||||||
case '\v':
|
|
||||||
out += "\\v";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
out.push_back(c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string tsUnescape(const std::string& str)
|
|
||||||
{
|
|
||||||
std::string out;
|
|
||||||
out.reserve(str.size());
|
|
||||||
for (size_t i = 0; i < str.size(); ++i) {
|
|
||||||
if (str[i] == '\\') {
|
|
||||||
if (++i >= str.size()) {
|
|
||||||
throw std::runtime_error("invalid escape sequence");
|
|
||||||
}
|
|
||||||
switch (str[i]) {
|
|
||||||
case '\\':
|
|
||||||
out.push_back('\\');
|
|
||||||
break;
|
|
||||||
case '/':
|
|
||||||
out.push_back('/');
|
|
||||||
break;
|
|
||||||
case 's':
|
|
||||||
out.push_back(' ');
|
|
||||||
break;
|
|
||||||
case 'p':
|
|
||||||
out.push_back('|');
|
|
||||||
break;
|
|
||||||
case 'f':
|
|
||||||
out.push_back('\f');
|
|
||||||
break;
|
|
||||||
case 'n':
|
|
||||||
out.push_back('\n');
|
|
||||||
break;
|
|
||||||
case 'r':
|
|
||||||
out.push_back('\r');
|
|
||||||
break;
|
|
||||||
case 't':
|
|
||||||
out.push_back('\t');
|
|
||||||
break;
|
|
||||||
case 'v':
|
|
||||||
out.push_back('\v');
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw std::runtime_error(std::string("unknown escape: \\") +
|
|
||||||
str[i]);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
out.push_back(str[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string buildCommand(const std::string& name,
|
|
||||||
const CommandParams& params)
|
|
||||||
{
|
|
||||||
std::string cmd = tsEscape(name);
|
|
||||||
for (const auto& [key, value] : params) {
|
|
||||||
cmd += ' ';
|
|
||||||
cmd += key;
|
|
||||||
cmd += '=';
|
|
||||||
cmd += tsEscape(value);
|
|
||||||
}
|
|
||||||
return cmd;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
CommandParams parseGroup(const std::string& part)
|
|
||||||
{
|
|
||||||
CommandParams params;
|
|
||||||
std::istringstream iss(part);
|
|
||||||
std::string token;
|
|
||||||
while (std::getline(iss, token, ' ')) {
|
|
||||||
if (token.empty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
auto eq = token.find('=');
|
|
||||||
if (eq != std::string::npos) {
|
|
||||||
params[token.substr(0, eq)] =
|
|
||||||
tsUnescape(token.substr(eq + 1));
|
|
||||||
} else {
|
|
||||||
params[token] = "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return params;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string trim(const std::string& s)
|
|
||||||
{
|
|
||||||
size_t a = s.find_first_not_of(" \t\r\n");
|
|
||||||
if (a == std::string::npos) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
size_t b = s.find_last_not_of(" \t\r\n");
|
|
||||||
return s.substr(a, b - a + 1);
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
ParsedCommand parseCommand(const std::string& raw)
|
|
||||||
{
|
|
||||||
// Split on '|' into groups.
|
|
||||||
std::vector<std::string> parts;
|
|
||||||
{
|
|
||||||
std::string cur;
|
|
||||||
for (char c : raw) {
|
|
||||||
if (c == '|') {
|
|
||||||
parts.push_back(cur);
|
|
||||||
cur.clear();
|
|
||||||
} else {
|
|
||||||
cur.push_back(c);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
parts.push_back(cur);
|
|
||||||
}
|
|
||||||
|
|
||||||
ParsedCommand out;
|
|
||||||
std::string first = trim(parts[0]);
|
|
||||||
|
|
||||||
// The command name is the first whitespace-delimited token.
|
|
||||||
std::string body;
|
|
||||||
auto sp = first.find(' ');
|
|
||||||
if (sp == std::string::npos) {
|
|
||||||
out.name = tsUnescape(first);
|
|
||||||
body = "";
|
|
||||||
} else {
|
|
||||||
out.name = tsUnescape(first.substr(0, sp));
|
|
||||||
body = first.substr(sp + 1);
|
|
||||||
}
|
|
||||||
out.params = parseGroup(body);
|
|
||||||
|
|
||||||
if (parts.size() > 1) {
|
|
||||||
out.groups.push_back(out.params);
|
|
||||||
for (size_t g = 1; g < parts.size(); ++g) {
|
|
||||||
out.groups.push_back(parseGroup(trim(parts[g])));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,249 +0,0 @@
|
|||||||
#include "echoion/protocol/Crypto.hpp"
|
|
||||||
#include "echoion/protocol/Util.hpp"
|
|
||||||
|
|
||||||
#include <openssl/evp.h>
|
|
||||||
#include <openssl/sha.h>
|
|
||||||
|
|
||||||
#include <cstring>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol::Crypto
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
// Raw single-block AES-128-ECB encryption (no padding). Used to build
|
|
||||||
// CMAC; matches the reference's aesEncryptBlock().
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> aesEncryptBlock(
|
|
||||||
ByteView key, std::span<const uint8_t, BLOCK_SIZE> block)
|
|
||||||
{
|
|
||||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
|
||||||
if (!ctx) {
|
|
||||||
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
|
|
||||||
}
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> out{};
|
|
||||||
int len = 0;
|
|
||||||
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(),
|
|
||||||
nullptr) != 1 ||
|
|
||||||
EVP_CIPHER_CTX_set_padding(ctx, 0) != 1 ||
|
|
||||||
EVP_EncryptUpdate(ctx, out.data(), &len, block.data(),
|
|
||||||
static_cast<int>(BLOCK_SIZE)) != 1) {
|
|
||||||
EVP_CIPHER_CTX_free(ctx);
|
|
||||||
throw std::runtime_error("AES-ECB block encrypt failed");
|
|
||||||
}
|
|
||||||
EVP_CIPHER_CTX_free(ctx);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
// GF(2^128) left-shift-by-one with the 0x87 reduction polynomial.
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> doubleBlock(
|
|
||||||
const std::array<uint8_t, BLOCK_SIZE>& buf)
|
|
||||||
{
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> out{};
|
|
||||||
uint8_t carry = 0;
|
|
||||||
for (int i = BLOCK_SIZE - 1; i >= 0; --i) {
|
|
||||||
uint16_t tmp = static_cast<uint16_t>((buf[i] << 1) | carry);
|
|
||||||
out[i] = static_cast<uint8_t>(tmp & 0xff);
|
|
||||||
carry = (buf[i] >> 7) & 1;
|
|
||||||
}
|
|
||||||
if (carry) {
|
|
||||||
out[BLOCK_SIZE - 1] ^= 0x87;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
// EAX OMAC over a tag byte prepended in a leading block, then `data`.
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> eaxOmac(ByteView key, uint8_t tag,
|
|
||||||
ByteView data)
|
|
||||||
{
|
|
||||||
Bytes input(BLOCK_SIZE + data.size(), 0);
|
|
||||||
input[BLOCK_SIZE - 1] = tag;
|
|
||||||
std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size());
|
|
||||||
return cmac(key, input);
|
|
||||||
}
|
|
||||||
|
|
||||||
// AES-128-CTR keystream applied to `in`, IV = `nonce`.
|
|
||||||
Bytes aesCtr(ByteView key, std::span<const uint8_t, BLOCK_SIZE> nonce,
|
|
||||||
ByteView in)
|
|
||||||
{
|
|
||||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
|
||||||
if (!ctx) {
|
|
||||||
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
|
|
||||||
}
|
|
||||||
Bytes out(in.size(), 0);
|
|
||||||
int len = 0;
|
|
||||||
int total = 0;
|
|
||||||
if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), nullptr, key.data(),
|
|
||||||
nonce.data()) != 1 ||
|
|
||||||
EVP_EncryptUpdate(ctx, out.data(), &len, in.data(),
|
|
||||||
static_cast<int>(in.size())) != 1) {
|
|
||||||
EVP_CIPHER_CTX_free(ctx);
|
|
||||||
throw std::runtime_error("AES-CTR failed");
|
|
||||||
}
|
|
||||||
total = len;
|
|
||||||
if (EVP_EncryptFinal_ex(ctx, out.data() + total, &len) != 1) {
|
|
||||||
EVP_CIPHER_CTX_free(ctx);
|
|
||||||
throw std::runtime_error("AES-CTR final failed");
|
|
||||||
}
|
|
||||||
EVP_CIPHER_CTX_free(ctx);
|
|
||||||
out.resize(static_cast<size_t>(total) + len);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
std::array<uint8_t, 20> sha1(ByteView data)
|
|
||||||
{
|
|
||||||
std::array<uint8_t, 20> out{};
|
|
||||||
::SHA1(data.data(), data.size(), out.data());
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<uint8_t, 32> sha256(ByteView data)
|
|
||||||
{
|
|
||||||
std::array<uint8_t, 32> out{};
|
|
||||||
::SHA256(data.data(), data.size(), out.data());
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<uint8_t, 64> sha512(ByteView data)
|
|
||||||
{
|
|
||||||
std::array<uint8_t, 64> out{};
|
|
||||||
::SHA512(data.data(), data.size(), out.data());
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes xorBuffers(ByteView a, ByteView b)
|
|
||||||
{
|
|
||||||
size_t len = std::min(a.size(), b.size());
|
|
||||||
Bytes out(len, 0);
|
|
||||||
for (size_t i = 0; i < len; ++i) {
|
|
||||||
out[i] = a[i] ^ b[i];
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
void xorInto(std::span<uint8_t> a, ByteView b, size_t len)
|
|
||||||
{
|
|
||||||
for (size_t i = 0; i < len; ++i) {
|
|
||||||
a[i] ^= b[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data)
|
|
||||||
{
|
|
||||||
const std::array<uint8_t, BLOCK_SIZE> zero{};
|
|
||||||
auto L = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
|
||||||
zero.data(), BLOCK_SIZE));
|
|
||||||
auto K1 = doubleBlock(L);
|
|
||||||
auto K2 = doubleBlock(K1);
|
|
||||||
|
|
||||||
const size_t n = data.size();
|
|
||||||
const size_t numBlocks = n == 0 ? 1 : (n + BLOCK_SIZE - 1) / BLOCK_SIZE;
|
|
||||||
const bool lastComplete = n > 0 && n % BLOCK_SIZE == 0;
|
|
||||||
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> x{};
|
|
||||||
for (size_t i = 0; i + 1 < numBlocks; ++i) {
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> block{};
|
|
||||||
std::memcpy(block.data(), data.data() + i * BLOCK_SIZE, BLOCK_SIZE);
|
|
||||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
|
||||||
block[j] ^= x[j];
|
|
||||||
}
|
|
||||||
x = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
|
||||||
block.data(), BLOCK_SIZE));
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<uint8_t, BLOCK_SIZE> last{};
|
|
||||||
const size_t off = (numBlocks - 1) * BLOCK_SIZE;
|
|
||||||
if (lastComplete) {
|
|
||||||
std::memcpy(last.data(), data.data() + off, BLOCK_SIZE);
|
|
||||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
|
||||||
last[j] ^= K1[j];
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const size_t rem = n - off;
|
|
||||||
std::memcpy(last.data(), data.data() + off, rem);
|
|
||||||
last[rem] = 0x80;
|
|
||||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
|
||||||
last[j] ^= K2[j];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (size_t j = 0; j < BLOCK_SIZE; ++j) {
|
|
||||||
last[j] ^= x[j];
|
|
||||||
}
|
|
||||||
return aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
|
||||||
last.data(), BLOCK_SIZE));
|
|
||||||
}
|
|
||||||
|
|
||||||
EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header,
|
|
||||||
ByteView plaintext)
|
|
||||||
{
|
|
||||||
auto N = eaxOmac(key, 0, nonce);
|
|
||||||
auto H = eaxOmac(key, 1, header);
|
|
||||||
Bytes ciphertext = aesCtr(
|
|
||||||
key, std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
|
|
||||||
plaintext);
|
|
||||||
auto C = eaxOmac(key, 2, ciphertext);
|
|
||||||
|
|
||||||
EaxResult res;
|
|
||||||
res.ciphertext = std::move(ciphertext);
|
|
||||||
for (size_t i = 0; i < MAC_LEN; ++i) {
|
|
||||||
res.mac[i] = N[i] ^ H[i] ^ C[i];
|
|
||||||
}
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
|
|
||||||
ByteView header, ByteView ciphertext,
|
|
||||||
ByteView mac)
|
|
||||||
{
|
|
||||||
auto N = eaxOmac(key, 0, nonce);
|
|
||||||
auto H = eaxOmac(key, 1, header);
|
|
||||||
auto C = eaxOmac(key, 2, ciphertext);
|
|
||||||
|
|
||||||
std::array<uint8_t, MAC_LEN> tag{};
|
|
||||||
uint8_t diff = 0;
|
|
||||||
for (size_t i = 0; i < MAC_LEN; ++i) {
|
|
||||||
tag[i] = N[i] ^ H[i] ^ C[i];
|
|
||||||
diff |= static_cast<uint8_t>(tag[i] ^ (i < mac.size() ? mac[i] : 0));
|
|
||||||
}
|
|
||||||
if (diff != 0 || mac.size() < MAC_LEN) {
|
|
||||||
return std::nullopt;
|
|
||||||
}
|
|
||||||
return aesCtr(key,
|
|
||||||
std::span<const uint8_t, BLOCK_SIZE>(N.data(), BLOCK_SIZE),
|
|
||||||
ciphertext);
|
|
||||||
}
|
|
||||||
|
|
||||||
KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId,
|
|
||||||
uint32_t generationId, uint8_t packetType,
|
|
||||||
ByteView ivStruct)
|
|
||||||
{
|
|
||||||
const size_t tmpLen = ivStruct.size() == 20 ? 26 : 70;
|
|
||||||
Bytes tmp(tmpLen, 0);
|
|
||||||
tmp[0] = fromServer ? 0x30 : 0x31;
|
|
||||||
tmp[1] = packetType;
|
|
||||||
tmp[2] = static_cast<uint8_t>((generationId >> 24) & 0xff);
|
|
||||||
tmp[3] = static_cast<uint8_t>((generationId >> 16) & 0xff);
|
|
||||||
tmp[4] = static_cast<uint8_t>((generationId >> 8) & 0xff);
|
|
||||||
tmp[5] = static_cast<uint8_t>(generationId & 0xff);
|
|
||||||
std::memcpy(tmp.data() + 6, ivStruct.data(), ivStruct.size());
|
|
||||||
|
|
||||||
auto kn = sha256(tmp);
|
|
||||||
KeyNonce out;
|
|
||||||
std::memcpy(out.key.data(), kn.data(), 16);
|
|
||||||
std::memcpy(out.nonce.data(), kn.data() + 16, 16);
|
|
||||||
out.key[0] ^= static_cast<uint8_t>((packetId >> 8) & 0xff);
|
|
||||||
out.key[1] ^= static_cast<uint8_t>(packetId & 0xff);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string hashPassword(const std::string& password)
|
|
||||||
{
|
|
||||||
if (password.empty()) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
auto digest = sha1(ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>(password.data()), password.size()));
|
|
||||||
return Util::base64Encode(ByteView(digest.data(), digest.size()));
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol::Crypto
|
|
||||||
@@ -1,426 +0,0 @@
|
|||||||
#include "echoion/protocol/Identity.hpp"
|
|
||||||
#include "echoion/protocol/Crypto.hpp"
|
|
||||||
#include "echoion/protocol/Util.hpp"
|
|
||||||
|
|
||||||
#include <openssl/bn.h>
|
|
||||||
#include <openssl/core_names.h>
|
|
||||||
#include <openssl/evp.h>
|
|
||||||
#include <openssl/param_build.h>
|
|
||||||
#include <openssl/pem.h>
|
|
||||||
|
|
||||||
#include <fstream>
|
|
||||||
#include <stdexcept>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
using Bytes = std::vector<uint8_t>;
|
|
||||||
|
|
||||||
[[noreturn]] void fail(const char* what)
|
|
||||||
{
|
|
||||||
throw std::runtime_error(std::string("Identity: ") + what);
|
|
||||||
}
|
|
||||||
|
|
||||||
EVP_PKEY* asPkey(const std::shared_ptr<void>& p)
|
|
||||||
{
|
|
||||||
return static_cast<EVP_PKEY*>(p.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Minimal big-endian encoding of a BIGNUM (no leading zeros).
|
|
||||||
Bytes bnBytes(const BIGNUM* bn)
|
|
||||||
{
|
|
||||||
int n = BN_num_bytes(bn);
|
|
||||||
Bytes out(static_cast<size_t>(n < 0 ? 0 : n), 0);
|
|
||||||
if (n > 0) {
|
|
||||||
BN_bn2bin(bn, out.data());
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes derLength(size_t len)
|
|
||||||
{
|
|
||||||
if (len < 0x80) {
|
|
||||||
return {static_cast<uint8_t>(len)};
|
|
||||||
}
|
|
||||||
if (len < 0x100) {
|
|
||||||
return {0x81, static_cast<uint8_t>(len)};
|
|
||||||
}
|
|
||||||
return {0x82, static_cast<uint8_t>((len >> 8) & 0xff),
|
|
||||||
static_cast<uint8_t>(len & 0xff)};
|
|
||||||
}
|
|
||||||
|
|
||||||
// DER INTEGER from a non-negative big-endian magnitude.
|
|
||||||
Bytes derInteger(Bytes mag)
|
|
||||||
{
|
|
||||||
if (mag.empty()) {
|
|
||||||
mag.push_back(0);
|
|
||||||
}
|
|
||||||
if (mag[0] & 0x80) {
|
|
||||||
mag.insert(mag.begin(), 0x00);
|
|
||||||
}
|
|
||||||
Bytes out;
|
|
||||||
out.push_back(0x02);
|
|
||||||
Bytes len = derLength(mag.size());
|
|
||||||
out.insert(out.end(), len.begin(), len.end());
|
|
||||||
out.insert(out.end(), mag.begin(), mag.end());
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes derIntegerFromU64(uint64_t v)
|
|
||||||
{
|
|
||||||
BIGNUM* bn = BN_new();
|
|
||||||
BN_set_word(bn, v);
|
|
||||||
Bytes r = derInteger(bnBytes(bn));
|
|
||||||
BN_free(bn);
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
// libtomcrypt public key: SEQ{ BITSTRING(00 07 00), INT(32), INT(x),
|
|
||||||
// INT(y) }. The BITSTRING carries a leading "unused bits" byte (0x00)
|
|
||||||
// plus 0x07 0x00 in the reference; we reproduce it verbatim.
|
|
||||||
std::string buildPublicKeyString(const BIGNUM* x, const BIGNUM* y)
|
|
||||||
{
|
|
||||||
Bytes content;
|
|
||||||
const uint8_t bitStr[] = {0x03, 0x02, 0x07, 0x00};
|
|
||||||
content.insert(content.end(), std::begin(bitStr), std::end(bitStr));
|
|
||||||
Bytes i32 = derIntegerFromU64(32);
|
|
||||||
Bytes ix = derInteger(bnBytes(x));
|
|
||||||
Bytes iy = derInteger(bnBytes(y));
|
|
||||||
content.insert(content.end(), i32.begin(), i32.end());
|
|
||||||
content.insert(content.end(), ix.begin(), ix.end());
|
|
||||||
content.insert(content.end(), iy.begin(), iy.end());
|
|
||||||
|
|
||||||
Bytes der;
|
|
||||||
der.push_back(0x30);
|
|
||||||
Bytes len = derLength(content.size());
|
|
||||||
der.insert(der.end(), len.begin(), len.end());
|
|
||||||
der.insert(der.end(), content.begin(), content.end());
|
|
||||||
return Util::base64Encode(Crypto::ByteView(der.data(), der.size()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Uncompressed EC point (0x04 || x || y) from a public EVP_PKEY.
|
|
||||||
Bytes pubPoint(EVP_PKEY* pkey)
|
|
||||||
{
|
|
||||||
size_t len = 0;
|
|
||||||
if (EVP_PKEY_get_octet_string_param(
|
|
||||||
pkey, OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1) {
|
|
||||||
fail("cannot read public point length");
|
|
||||||
}
|
|
||||||
Bytes buf(len, 0);
|
|
||||||
if (EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY,
|
|
||||||
buf.data(), len, &len) != 1) {
|
|
||||||
fail("cannot read public point");
|
|
||||||
}
|
|
||||||
buf.resize(len);
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
|
|
||||||
int countLeadingZeroBits(Crypto::ByteView data)
|
|
||||||
{
|
|
||||||
int count = 0;
|
|
||||||
for (uint8_t b : data) {
|
|
||||||
if (b == 0) {
|
|
||||||
count += 8;
|
|
||||||
} else {
|
|
||||||
for (int bit = 0; bit < 8; ++bit) {
|
|
||||||
if ((b & (1 << bit)) == 0) {
|
|
||||||
++count;
|
|
||||||
} else {
|
|
||||||
return count;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return count;
|
|
||||||
}
|
|
||||||
|
|
||||||
int securityLevelFor(const std::string& pubKeyString, uint64_t offset)
|
|
||||||
{
|
|
||||||
std::string s = pubKeyString + std::to_string(offset);
|
|
||||||
auto h = Crypto::sha1(Crypto::ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>(s.data()), s.size()));
|
|
||||||
return countLeadingZeroBits(
|
|
||||||
Crypto::ByteView(h.data(), h.size()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// libtomcrypt DER parse → the two public-key INTEGERs (x, y). See
|
|
||||||
// reference parseDerSequence: collected = [bitByte, 32, x, y].
|
|
||||||
void parseServerPub(Crypto::ByteView der, BIGNUM** x, BIGNUM** y)
|
|
||||||
{
|
|
||||||
size_t pos = 0;
|
|
||||||
auto readLen = [&](size_t& p) -> size_t {
|
|
||||||
uint8_t first = der[p++];
|
|
||||||
if (first < 0x80) {
|
|
||||||
return first;
|
|
||||||
}
|
|
||||||
int nb = first & 0x7f;
|
|
||||||
size_t len = 0;
|
|
||||||
for (int i = 0; i < nb; ++i) {
|
|
||||||
len = (len << 8) | der[p++];
|
|
||||||
}
|
|
||||||
return len;
|
|
||||||
};
|
|
||||||
if (der.empty() || der[pos++] != 0x30) {
|
|
||||||
fail("server key: expected SEQUENCE");
|
|
||||||
}
|
|
||||||
readLen(pos);
|
|
||||||
std::vector<BIGNUM*> ints;
|
|
||||||
while (pos < der.size()) {
|
|
||||||
uint8_t tag = der[pos++];
|
|
||||||
size_t len = readLen(pos);
|
|
||||||
if (tag == 0x02) {
|
|
||||||
ints.push_back(
|
|
||||||
BN_bin2bn(der.data() + pos, static_cast<int>(len),
|
|
||||||
nullptr));
|
|
||||||
}
|
|
||||||
pos += len;
|
|
||||||
}
|
|
||||||
// ints = [32, x, y]; guard against short input.
|
|
||||||
if (ints.size() < 3) {
|
|
||||||
for (auto* b : ints) {
|
|
||||||
BN_free(b);
|
|
||||||
}
|
|
||||||
fail("server key: too few integers");
|
|
||||||
}
|
|
||||||
*x = ints[1];
|
|
||||||
*y = ints[2];
|
|
||||||
for (size_t i = 0; i < ints.size(); ++i) {
|
|
||||||
if (i != 1 && i != 2) {
|
|
||||||
BN_free(ints[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
void Identity::PKeyDeleter::operator()(void* p) const noexcept
|
|
||||||
{
|
|
||||||
EVP_PKEY_free(static_cast<EVP_PKEY*>(p));
|
|
||||||
}
|
|
||||||
|
|
||||||
Identity Identity::generate(int securityLevel)
|
|
||||||
{
|
|
||||||
EVP_PKEY* pkey = nullptr;
|
|
||||||
EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
|
|
||||||
if (!ctx) {
|
|
||||||
fail("keygen ctx");
|
|
||||||
}
|
|
||||||
if (EVP_PKEY_keygen_init(ctx) != 1) {
|
|
||||||
EVP_PKEY_CTX_free(ctx);
|
|
||||||
fail("keygen init");
|
|
||||||
}
|
|
||||||
OSSL_PARAM params[2] = {
|
|
||||||
OSSL_PARAM_construct_utf8_string(
|
|
||||||
OSSL_PKEY_PARAM_GROUP_NAME,
|
|
||||||
const_cast<char*>("prime256v1"), 0),
|
|
||||||
OSSL_PARAM_construct_end()};
|
|
||||||
EVP_PKEY_CTX_set_params(ctx, params);
|
|
||||||
if (EVP_PKEY_keygen(ctx, &pkey) != 1) {
|
|
||||||
EVP_PKEY_CTX_free(ctx);
|
|
||||||
fail("keygen");
|
|
||||||
}
|
|
||||||
EVP_PKEY_CTX_free(ctx);
|
|
||||||
|
|
||||||
Identity id;
|
|
||||||
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
|
|
||||||
|
|
||||||
Bytes point = pubPoint(pkey);
|
|
||||||
if (point.size() != 65 || point[0] != 0x04) {
|
|
||||||
fail("unexpected public point format");
|
|
||||||
}
|
|
||||||
BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr);
|
|
||||||
BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr);
|
|
||||||
id.publicKeyString_ = buildPublicKeyString(x, y);
|
|
||||||
BN_free(x);
|
|
||||||
BN_free(y);
|
|
||||||
|
|
||||||
auto uidHash = Crypto::sha1(Crypto::ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
|
|
||||||
id.publicKeyString_.size()));
|
|
||||||
id.uid_ = Util::base64Encode(
|
|
||||||
Crypto::ByteView(uidHash.data(), uidHash.size()));
|
|
||||||
|
|
||||||
// Hashcash: find the offset giving the most leading-zero bits, up to
|
|
||||||
// the requested level.
|
|
||||||
if (securityLevel > 0) {
|
|
||||||
uint64_t offset = 0;
|
|
||||||
int best = securityLevelFor(id.publicKeyString_, offset);
|
|
||||||
uint64_t checked = 0;
|
|
||||||
while (best < securityLevel) {
|
|
||||||
++checked;
|
|
||||||
int curr = securityLevelFor(id.publicKeyString_, checked);
|
|
||||||
if (curr > best) {
|
|
||||||
best = curr;
|
|
||||||
offset = checked;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
id.keyOffset_ = offset;
|
|
||||||
}
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
int Identity::securityLevel() const
|
|
||||||
{
|
|
||||||
return securityLevelFor(publicKeyString_, keyOffset_);
|
|
||||||
}
|
|
||||||
|
|
||||||
Identity::Bytes Identity::sign(ByteView data) const
|
|
||||||
{
|
|
||||||
EVP_PKEY* pkey = asPkey(pkey_);
|
|
||||||
EVP_MD_CTX* md = EVP_MD_CTX_new();
|
|
||||||
if (!md) {
|
|
||||||
fail("sign ctx");
|
|
||||||
}
|
|
||||||
size_t siglen = 0;
|
|
||||||
if (EVP_DigestSignInit(md, nullptr, EVP_sha256(), nullptr, pkey) != 1 ||
|
|
||||||
EVP_DigestSign(md, nullptr, &siglen, data.data(), data.size()) !=
|
|
||||||
1) {
|
|
||||||
EVP_MD_CTX_free(md);
|
|
||||||
fail("sign init");
|
|
||||||
}
|
|
||||||
Bytes sig(siglen, 0);
|
|
||||||
if (EVP_DigestSign(md, sig.data(), &siglen, data.data(), data.size()) !=
|
|
||||||
1) {
|
|
||||||
EVP_MD_CTX_free(md);
|
|
||||||
fail("sign");
|
|
||||||
}
|
|
||||||
sig.resize(siglen);
|
|
||||||
EVP_MD_CTX_free(md);
|
|
||||||
return sig;
|
|
||||||
}
|
|
||||||
|
|
||||||
Identity::Bytes Identity::sharedSecret(ByteView serverPublicKeyDer) const
|
|
||||||
{
|
|
||||||
BIGNUM* x = nullptr;
|
|
||||||
BIGNUM* y = nullptr;
|
|
||||||
parseServerPub(serverPublicKeyDer, &x, &y);
|
|
||||||
|
|
||||||
// Build uncompressed point 0x04 || x(32) || y(32).
|
|
||||||
Bytes point(65, 0);
|
|
||||||
point[0] = 0x04;
|
|
||||||
BN_bn2binpad(x, point.data() + 1, 32);
|
|
||||||
BN_bn2binpad(y, point.data() + 33, 32);
|
|
||||||
BN_free(x);
|
|
||||||
BN_free(y);
|
|
||||||
|
|
||||||
EVP_PKEY* peer = nullptr;
|
|
||||||
{
|
|
||||||
OSSL_PARAM_BLD* bld = OSSL_PARAM_BLD_new();
|
|
||||||
OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
|
|
||||||
"prime256v1", 0);
|
|
||||||
OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY,
|
|
||||||
point.data(), point.size());
|
|
||||||
OSSL_PARAM* p = OSSL_PARAM_BLD_to_param(bld);
|
|
||||||
EVP_PKEY_CTX* pctx =
|
|
||||||
EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr);
|
|
||||||
if (!pctx || EVP_PKEY_fromdata_init(pctx) != 1 ||
|
|
||||||
EVP_PKEY_fromdata(pctx, &peer, EVP_PKEY_PUBLIC_KEY, p) != 1) {
|
|
||||||
if (pctx) {
|
|
||||||
EVP_PKEY_CTX_free(pctx);
|
|
||||||
}
|
|
||||||
OSSL_PARAM_free(p);
|
|
||||||
OSSL_PARAM_BLD_free(bld);
|
|
||||||
fail("build peer key");
|
|
||||||
}
|
|
||||||
EVP_PKEY_CTX_free(pctx);
|
|
||||||
OSSL_PARAM_free(p);
|
|
||||||
OSSL_PARAM_BLD_free(bld);
|
|
||||||
}
|
|
||||||
|
|
||||||
EVP_PKEY_CTX* dctx = EVP_PKEY_CTX_new(asPkey(pkey_), nullptr);
|
|
||||||
size_t secretLen = 0;
|
|
||||||
if (!dctx || EVP_PKEY_derive_init(dctx) != 1 ||
|
|
||||||
EVP_PKEY_derive_set_peer(dctx, peer) != 1 ||
|
|
||||||
EVP_PKEY_derive(dctx, nullptr, &secretLen) != 1) {
|
|
||||||
if (dctx) {
|
|
||||||
EVP_PKEY_CTX_free(dctx);
|
|
||||||
}
|
|
||||||
EVP_PKEY_free(peer);
|
|
||||||
fail("ecdh derive init");
|
|
||||||
}
|
|
||||||
Bytes secret(secretLen, 0);
|
|
||||||
if (EVP_PKEY_derive(dctx, secret.data(), &secretLen) != 1) {
|
|
||||||
EVP_PKEY_CTX_free(dctx);
|
|
||||||
EVP_PKEY_free(peer);
|
|
||||||
fail("ecdh derive");
|
|
||||||
}
|
|
||||||
secret.resize(secretLen);
|
|
||||||
EVP_PKEY_CTX_free(dctx);
|
|
||||||
EVP_PKEY_free(peer);
|
|
||||||
|
|
||||||
// Pad/truncate to 32 bytes, then SHA-1 (matches reference).
|
|
||||||
Bytes keyArr(32, 0);
|
|
||||||
if (secret.size() >= 32) {
|
|
||||||
std::copy(secret.end() - 32, secret.end(), keyArr.begin());
|
|
||||||
} else {
|
|
||||||
std::copy(secret.begin(), secret.end(),
|
|
||||||
keyArr.begin() + (32 - secret.size()));
|
|
||||||
}
|
|
||||||
auto h = Crypto::sha1(Crypto::ByteView(keyArr.data(), keyArr.size()));
|
|
||||||
return Bytes(h.begin(), h.end());
|
|
||||||
}
|
|
||||||
|
|
||||||
void Identity::save(const std::string& path) const
|
|
||||||
{
|
|
||||||
EVP_PKEY* pkey = asPkey(pkey_);
|
|
||||||
BIO* mem = BIO_new(BIO_s_mem());
|
|
||||||
if (!PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr,
|
|
||||||
nullptr)) {
|
|
||||||
BIO_free(mem);
|
|
||||||
fail("serialize private key");
|
|
||||||
}
|
|
||||||
char* data = nullptr;
|
|
||||||
long n = BIO_get_mem_data(mem, &data);
|
|
||||||
std::string pem(data, static_cast<size_t>(n));
|
|
||||||
BIO_free(mem);
|
|
||||||
|
|
||||||
std::ofstream out(path, std::ios::trunc);
|
|
||||||
if (!out) {
|
|
||||||
fail("cannot open identity file for writing");
|
|
||||||
}
|
|
||||||
out << "ECHOION_IDENTITY_V1\n";
|
|
||||||
out << keyOffset_ << "\n";
|
|
||||||
out << publicKeyString_ << "\n";
|
|
||||||
out << "-----PRIVATE-----\n";
|
|
||||||
out << pem;
|
|
||||||
}
|
|
||||||
|
|
||||||
Identity Identity::load(const std::string& path)
|
|
||||||
{
|
|
||||||
std::ifstream in(path);
|
|
||||||
if (!in) {
|
|
||||||
fail("cannot open identity file");
|
|
||||||
}
|
|
||||||
std::string magic;
|
|
||||||
std::getline(in, magic);
|
|
||||||
if (magic != "ECHOION_IDENTITY_V1") {
|
|
||||||
fail("bad identity file magic");
|
|
||||||
}
|
|
||||||
std::string offsetLine;
|
|
||||||
std::getline(in, offsetLine);
|
|
||||||
Identity id;
|
|
||||||
id.keyOffset_ = std::stoull(offsetLine);
|
|
||||||
std::getline(in, id.publicKeyString_);
|
|
||||||
std::string sep;
|
|
||||||
std::getline(in, sep); // -----PRIVATE-----
|
|
||||||
std::string pem((std::istreambuf_iterator<char>(in)),
|
|
||||||
std::istreambuf_iterator<char>());
|
|
||||||
|
|
||||||
BIO* mem = BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size()));
|
|
||||||
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr);
|
|
||||||
BIO_free(mem);
|
|
||||||
if (!pkey) {
|
|
||||||
fail("cannot parse private key");
|
|
||||||
}
|
|
||||||
id.pkey_ = std::shared_ptr<void>(pkey, PKeyDeleter{});
|
|
||||||
|
|
||||||
auto uidHash = Crypto::sha1(Crypto::ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
|
|
||||||
id.publicKeyString_.size()));
|
|
||||||
id.uid_ = Util::base64Encode(
|
|
||||||
Crypto::ByteView(uidHash.data(), uidHash.size()));
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
#include "echoion/protocol/License.hpp"
|
|
||||||
#include "echoion/protocol/Crypto.hpp"
|
|
||||||
|
|
||||||
#include <sodium.h>
|
|
||||||
|
|
||||||
#include <cstring>
|
|
||||||
#include <mutex>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
[[noreturn]] void fail(const char* what)
|
|
||||||
{
|
|
||||||
throw std::runtime_error(std::string("License: ") + what);
|
|
||||||
}
|
|
||||||
|
|
||||||
void ensureSodium()
|
|
||||||
{
|
|
||||||
static std::once_flag once;
|
|
||||||
static bool ok = false;
|
|
||||||
std::call_once(once, [] { ok = sodium_init() >= 0; });
|
|
||||||
if (!ok) {
|
|
||||||
fail("libsodium init failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ed25519 point compressed root key.
|
|
||||||
constexpr std::array<uint8_t, 32> LICENSE_ROOT_KEY = {
|
|
||||||
0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c,
|
|
||||||
0xfd, 0x8f, 0x68, 0xb3, 0xdc, 0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec,
|
|
||||||
0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a};
|
|
||||||
|
|
||||||
size_t findNullTerminator(ByteView data, size_t start)
|
|
||||||
{
|
|
||||||
for (size_t i = start; i < data.size(); ++i) {
|
|
||||||
if (data[i] == 0) {
|
|
||||||
return i - start;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fail("non-null-terminated string in license");
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
std::vector<LicenseBlock> parseLicense(ByteView data)
|
|
||||||
{
|
|
||||||
if (data.size() < 1) {
|
|
||||||
fail("license too short");
|
|
||||||
}
|
|
||||||
if (data[0] != 1) {
|
|
||||||
fail("unsupported license version");
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<LicenseBlock> blocks;
|
|
||||||
size_t pos = 1;
|
|
||||||
while (pos < data.size()) {
|
|
||||||
if (data.size() - pos < 42) {
|
|
||||||
fail("license block too short");
|
|
||||||
}
|
|
||||||
if (data[pos] != 0) {
|
|
||||||
fail("wrong key kind");
|
|
||||||
}
|
|
||||||
|
|
||||||
LicenseBlock block;
|
|
||||||
std::memcpy(block.key.data(), data.data() + pos + 1, 32);
|
|
||||||
const uint8_t blockType = data[pos + 33];
|
|
||||||
block.type = blockType;
|
|
||||||
|
|
||||||
size_t extraLen = 0;
|
|
||||||
switch (blockType) {
|
|
||||||
case 0: // Intermediate
|
|
||||||
extraLen = findNullTerminator(data, pos + 46) + 5;
|
|
||||||
break;
|
|
||||||
case 2: // Server
|
|
||||||
extraLen = findNullTerminator(data, pos + 47) + 6;
|
|
||||||
break;
|
|
||||||
case 8: { // TS5 Server
|
|
||||||
size_t p = pos + 44;
|
|
||||||
const uint8_t propCount = data[pos + 43];
|
|
||||||
for (uint8_t i = 0; i < propCount; ++i) {
|
|
||||||
const uint8_t propLen = data[p];
|
|
||||||
p += 1 + propLen;
|
|
||||||
}
|
|
||||||
extraLen = p - (pos + 42);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 32: // Ephemeral
|
|
||||||
extraLen = 0;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
fail("invalid license block type");
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t blockLen = 42 + extraLen;
|
|
||||||
if (pos + blockLen > data.size()) {
|
|
||||||
fail("license block overruns buffer");
|
|
||||||
}
|
|
||||||
auto content = data.subspan(pos + 1, blockLen - 1);
|
|
||||||
auto h = Crypto::sha512(content);
|
|
||||||
std::memcpy(block.hash.data(), h.data(), 32);
|
|
||||||
|
|
||||||
blocks.push_back(block);
|
|
||||||
pos += blockLen;
|
|
||||||
}
|
|
||||||
return blocks;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<uint8_t, 32>
|
|
||||||
deriveLicenseKey(const std::vector<LicenseBlock>& blocks)
|
|
||||||
{
|
|
||||||
ensureSodium();
|
|
||||||
std::array<uint8_t, 32> parentKey = LICENSE_ROOT_KEY;
|
|
||||||
|
|
||||||
for (const auto& block : blocks) {
|
|
||||||
// Clamp the block hash into an Ed25519 scalar.
|
|
||||||
std::array<uint8_t, 32> scalar = block.hash;
|
|
||||||
scalar[0] &= 0xf8;
|
|
||||||
scalar[31] &= 0x3f;
|
|
||||||
scalar[31] |= 0x40;
|
|
||||||
|
|
||||||
std::array<uint8_t, 32> mul{};
|
|
||||||
if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(),
|
|
||||||
block.key.data()) != 0) {
|
|
||||||
fail("ed25519 scalarmult failed");
|
|
||||||
}
|
|
||||||
std::array<uint8_t, 32> sum{};
|
|
||||||
if (crypto_core_ed25519_add(sum.data(), mul.data(),
|
|
||||||
parentKey.data()) != 0) {
|
|
||||||
fail("ed25519 point add failed");
|
|
||||||
}
|
|
||||||
parentKey = sum;
|
|
||||||
}
|
|
||||||
return parentKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
TempKey generateTemporaryKey()
|
|
||||||
{
|
|
||||||
ensureSodium();
|
|
||||||
TempKey out;
|
|
||||||
randombytes_buf(out.privateKey.data(), out.privateKey.size());
|
|
||||||
out.privateKey[0] &= 248;
|
|
||||||
out.privateKey[31] &= 127;
|
|
||||||
out.privateKey[31] |= 64;
|
|
||||||
if (crypto_scalarmult_ed25519_base_noclamp(out.publicKey.data(),
|
|
||||||
out.privateKey.data()) != 0) {
|
|
||||||
fail("ed25519 base mult failed");
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<uint8_t, 64> getSharedSecret2(ByteView serverDerivedKey,
|
|
||||||
ByteView tempPrivateKey)
|
|
||||||
{
|
|
||||||
ensureSodium();
|
|
||||||
if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) {
|
|
||||||
fail("bad key length for shared secret");
|
|
||||||
}
|
|
||||||
std::array<uint8_t, 32> priv{};
|
|
||||||
std::memcpy(priv.data(), tempPrivateKey.data(), 32);
|
|
||||||
priv[31] &= 0x7f;
|
|
||||||
|
|
||||||
std::array<uint8_t, 32> mul{};
|
|
||||||
if (crypto_scalarmult_ed25519_noclamp(mul.data(), priv.data(),
|
|
||||||
serverDerivedKey.data()) != 0) {
|
|
||||||
fail("ed25519 scalarmult failed");
|
|
||||||
}
|
|
||||||
return Crypto::sha512(ByteView(mul.data(), mul.size()));
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
#include "echoion/protocol/QuickLz.hpp"
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
constexpr int TABLE_SIZE = 4096;
|
|
||||||
constexpr uint32_t MAX_DECOMPRESSED_SIZE = 1024 * 1024;
|
|
||||||
|
|
||||||
uint32_t readU32LE(ByteView b, size_t off)
|
|
||||||
{
|
|
||||||
return static_cast<uint32_t>(b[off]) |
|
|
||||||
(static_cast<uint32_t>(b[off + 1]) << 8) |
|
|
||||||
(static_cast<uint32_t>(b[off + 2]) << 16) |
|
|
||||||
(static_cast<uint32_t>(b[off + 3]) << 24);
|
|
||||||
}
|
|
||||||
|
|
||||||
int32_t readI32LE(ByteView b, size_t off)
|
|
||||||
{
|
|
||||||
return static_cast<int32_t>(readU32LE(b, off));
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t read24(const Bytes& b, size_t off)
|
|
||||||
{
|
|
||||||
return static_cast<uint32_t>(b[off]) |
|
|
||||||
(static_cast<uint32_t>(b[off + 1]) << 8) |
|
|
||||||
(static_cast<uint32_t>(b[off + 2]) << 16);
|
|
||||||
}
|
|
||||||
|
|
||||||
int hashVal(uint32_t value)
|
|
||||||
{
|
|
||||||
return static_cast<int>(((value >> 12) ^ value) & 0xfff);
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
uint32_t qlzDecompressedSize(ByteView data)
|
|
||||||
{
|
|
||||||
return (data[0] & 0x02) != 0
|
|
||||||
? static_cast<uint32_t>(readI32LE(data, 5))
|
|
||||||
: data[2];
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t qlzCompressedSize(ByteView data)
|
|
||||||
{
|
|
||||||
return (data[0] & 0x02) != 0
|
|
||||||
? static_cast<uint32_t>(readI32LE(data, 1))
|
|
||||||
: data[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes qlzDecompress(ByteView data)
|
|
||||||
{
|
|
||||||
if (data.empty()) {
|
|
||||||
throw std::runtime_error("QuickLZ: empty input");
|
|
||||||
}
|
|
||||||
const uint8_t flags = data[0];
|
|
||||||
const int level = (flags >> 2) & 0x03;
|
|
||||||
if (level != 1) {
|
|
||||||
throw std::runtime_error("QuickLZ level not supported");
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t headerLen = (flags & 0x02) != 0 ? 9 : 3;
|
|
||||||
const uint32_t decompressedSize = qlzDecompressedSize(data);
|
|
||||||
if (decompressedSize > MAX_DECOMPRESSED_SIZE) {
|
|
||||||
throw std::runtime_error("QuickLZ: decompressed size exceeds max");
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes dest(decompressedSize, 0);
|
|
||||||
|
|
||||||
if ((flags & 0x01) == 0) {
|
|
||||||
// Stored, not compressed.
|
|
||||||
if (headerLen + decompressedSize > data.size()) {
|
|
||||||
throw std::runtime_error("QuickLZ: truncated stored block");
|
|
||||||
}
|
|
||||||
std::copy_n(data.begin() + headerLen, decompressedSize,
|
|
||||||
dest.begin());
|
|
||||||
return dest;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<int32_t> hashtable(TABLE_SIZE, 0);
|
|
||||||
uint32_t control = 1;
|
|
||||||
size_t sourcePos = headerLen;
|
|
||||||
size_t destPos = 0;
|
|
||||||
size_t nextHashed = 0;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
if (control == 1) {
|
|
||||||
control = readU32LE(data, sourcePos);
|
|
||||||
sourcePos += 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((control & 1) != 0) {
|
|
||||||
control >>= 1;
|
|
||||||
const uint8_t next = data[sourcePos++];
|
|
||||||
const int hashIdx = (next >> 4) | (data[sourcePos++] << 4);
|
|
||||||
|
|
||||||
uint32_t matchLen = next & 0x0f;
|
|
||||||
if (matchLen != 0) {
|
|
||||||
matchLen += 2;
|
|
||||||
} else {
|
|
||||||
matchLen = data[sourcePos++];
|
|
||||||
}
|
|
||||||
|
|
||||||
const int32_t offset = hashtable[hashIdx];
|
|
||||||
|
|
||||||
dest[destPos] = dest[offset];
|
|
||||||
dest[destPos + 1] = dest[offset + 1];
|
|
||||||
dest[destPos + 2] = dest[offset + 2];
|
|
||||||
for (uint32_t i = 3; i < matchLen; ++i) {
|
|
||||||
dest[destPos + i] = dest[offset + i];
|
|
||||||
}
|
|
||||||
destPos += matchLen;
|
|
||||||
|
|
||||||
const size_t end = destPos + 1 - matchLen;
|
|
||||||
if (nextHashed < end) {
|
|
||||||
uint32_t nxt = read24(dest, nextHashed);
|
|
||||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
|
|
||||||
for (size_t i = nextHashed + 1; i < end; ++i) {
|
|
||||||
nxt = (nxt >> 8) |
|
|
||||||
(static_cast<uint32_t>(dest[i + 2]) << 16);
|
|
||||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
nextHashed = destPos;
|
|
||||||
} else if (destPos >=
|
|
||||||
std::max<size_t>(decompressedSize, 10) - 10) {
|
|
||||||
while (destPos < decompressedSize) {
|
|
||||||
if (control == 1) {
|
|
||||||
sourcePos += 4;
|
|
||||||
}
|
|
||||||
control >>= 1;
|
|
||||||
dest[destPos++] = data[sourcePos++];
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
dest[destPos++] = data[sourcePos++];
|
|
||||||
control >>= 1;
|
|
||||||
|
|
||||||
const size_t end = destPos >= 2 ? destPos - 2 : 0;
|
|
||||||
if (nextHashed < end) {
|
|
||||||
uint32_t nxt = read24(dest, nextHashed);
|
|
||||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(nextHashed);
|
|
||||||
for (size_t i = nextHashed + 1; i < end; ++i) {
|
|
||||||
nxt = (nxt >> 8) |
|
|
||||||
(static_cast<uint32_t>(dest[i + 2]) << 16);
|
|
||||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
nextHashed = std::max(nextHashed, end);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return dest;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,980 +0,0 @@
|
|||||||
#include "echoion/protocol/TsClient.hpp"
|
|
||||||
#include "echoion/protocol/Crypto.hpp"
|
|
||||||
#include "echoion/protocol/License.hpp"
|
|
||||||
#include "echoion/protocol/QuickLz.hpp"
|
|
||||||
#include "echoion/protocol/Util.hpp"
|
|
||||||
|
|
||||||
#include <openssl/bn.h>
|
|
||||||
#include <openssl/rand.h>
|
|
||||||
|
|
||||||
#include <arpa/inet.h>
|
|
||||||
#include <netdb.h>
|
|
||||||
#include <poll.h>
|
|
||||||
#include <sys/socket.h>
|
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <cstring>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
constexpr uint8_t FLAG_FRAGMENTED = 0x10;
|
|
||||||
constexpr uint8_t FLAG_NEWPROTOCOL = 0x20;
|
|
||||||
constexpr uint8_t FLAG_COMPRESSED = 0x40;
|
|
||||||
constexpr uint8_t FLAG_UNENCRYPTED = 0x80;
|
|
||||||
|
|
||||||
constexpr size_t MAC_LEN = 8;
|
|
||||||
constexpr size_t C2S_HEADER_LEN = 5; // PId(2) + CId(2) + PT(1)
|
|
||||||
constexpr size_t S2C_HEADER_LEN = 3; // PId(2) + PT(1)
|
|
||||||
constexpr size_t MAX_PACKET_SIZE = 500;
|
|
||||||
constexpr size_t MAX_OUT_CONTENT =
|
|
||||||
MAX_PACKET_SIZE - MAC_LEN - C2S_HEADER_LEN;
|
|
||||||
|
|
||||||
constexpr const char* VS_PLATFORM = "Linux";
|
|
||||||
constexpr const char* VS_VERSION = "3.?.? [Build: 5680278000]";
|
|
||||||
constexpr const char* VS_SIGN =
|
|
||||||
"Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2"
|
|
||||||
"gSwRuZi0R+8Laan5ts5CQ==";
|
|
||||||
|
|
||||||
int64_t nowMs()
|
|
||||||
{
|
|
||||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
||||||
std::chrono::steady_clock::now().time_since_epoch())
|
|
||||||
.count();
|
|
||||||
}
|
|
||||||
|
|
||||||
void putU16BE(std::vector<uint8_t>& b, size_t off, uint16_t v)
|
|
||||||
{
|
|
||||||
b[off] = static_cast<uint8_t>((v >> 8) & 0xff);
|
|
||||||
b[off + 1] = static_cast<uint8_t>(v & 0xff);
|
|
||||||
}
|
|
||||||
uint16_t getU16BE(std::span<const uint8_t> b, size_t off)
|
|
||||||
{
|
|
||||||
return static_cast<uint16_t>((b[off] << 8) | b[off + 1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// y = x^(2^level) mod n, all big-endian 64-byte.
|
|
||||||
std::vector<uint8_t> rsaPuzzle(std::span<const uint8_t> x,
|
|
||||||
std::span<const uint8_t> n, int32_t level)
|
|
||||||
{
|
|
||||||
BN_CTX* ctx = BN_CTX_new();
|
|
||||||
BIGNUM* bx = BN_bin2bn(x.data(), static_cast<int>(x.size()),
|
|
||||||
nullptr);
|
|
||||||
BIGNUM* bn = BN_bin2bn(n.data(), static_cast<int>(n.size()),
|
|
||||||
nullptr);
|
|
||||||
BIGNUM* exp = BN_new();
|
|
||||||
BIGNUM* one = BN_new();
|
|
||||||
BN_one(one);
|
|
||||||
BN_lshift(exp, one, level); // 2^level
|
|
||||||
BIGNUM* y = BN_new();
|
|
||||||
BN_mod_exp(y, bx, exp, bn, ctx);
|
|
||||||
std::vector<uint8_t> out(64, 0);
|
|
||||||
BN_bn2binpad(y, out.data(), 64);
|
|
||||||
BN_free(y);
|
|
||||||
BN_free(exp);
|
|
||||||
BN_free(one);
|
|
||||||
BN_free(bn);
|
|
||||||
BN_free(bx);
|
|
||||||
BN_CTX_free(ctx);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
TsClient::TsClient() = default;
|
|
||||||
|
|
||||||
TsClient::~TsClient()
|
|
||||||
{
|
|
||||||
forceClose();
|
|
||||||
if (thread_.joinable()) {
|
|
||||||
thread_.join();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::debug(const std::string& msg)
|
|
||||||
{
|
|
||||||
if (cb_.onDebug) {
|
|
||||||
cb_.onDebug(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TsClient::Counter TsClient::getCounter(PacketType type)
|
|
||||||
{
|
|
||||||
if (type == PacketType::Init1) {
|
|
||||||
return {101, 0};
|
|
||||||
}
|
|
||||||
auto i = static_cast<size_t>(type);
|
|
||||||
return {packetCounter_[i], generationCounter_[i]};
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::incCounter(PacketType type)
|
|
||||||
{
|
|
||||||
if (type == PacketType::Init1) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto i = static_cast<size_t>(type);
|
|
||||||
if (++packetCounter_[i] == 0) {
|
|
||||||
++generationCounter_[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::connect(const TsClientOptions& opts)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (!opts.identity) {
|
|
||||||
throw std::runtime_error("TsClient: identity is required");
|
|
||||||
}
|
|
||||||
opts_ = opts;
|
|
||||||
|
|
||||||
// Resolve host and open a connected UDP socket.
|
|
||||||
addrinfo hints{};
|
|
||||||
hints.ai_family = AF_INET;
|
|
||||||
hints.ai_socktype = SOCK_DGRAM;
|
|
||||||
hints.ai_protocol = IPPROTO_UDP;
|
|
||||||
addrinfo* res = nullptr;
|
|
||||||
std::string portStr = std::to_string(opts.port);
|
|
||||||
if (getaddrinfo(opts.host.c_str(), portStr.c_str(), &hints, &res) != 0 ||
|
|
||||||
!res) {
|
|
||||||
throw std::runtime_error("TsClient: cannot resolve host " +
|
|
||||||
opts.host);
|
|
||||||
}
|
|
||||||
sock_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
|
||||||
if (sock_ < 0) {
|
|
||||||
freeaddrinfo(res);
|
|
||||||
throw std::runtime_error("TsClient: socket() failed");
|
|
||||||
}
|
|
||||||
if (::connect(sock_, res->ai_addr, res->ai_addrlen) != 0) {
|
|
||||||
freeaddrinfo(res);
|
|
||||||
::close(sock_);
|
|
||||||
sock_ = -1;
|
|
||||||
throw std::runtime_error("TsClient: connect() failed");
|
|
||||||
}
|
|
||||||
freeaddrinfo(res);
|
|
||||||
|
|
||||||
// Reset all per-connection state.
|
|
||||||
state_ = ClientState::Init;
|
|
||||||
clientId_ = 0;
|
|
||||||
cryptoInitComplete_ = false;
|
|
||||||
ivStruct_.clear();
|
|
||||||
fakeSignature_.fill(0);
|
|
||||||
alphaTmp_.clear();
|
|
||||||
packetCounter_.fill(0);
|
|
||||||
generationCounter_.fill(0);
|
|
||||||
resendMap_.clear();
|
|
||||||
initResend_.reset();
|
|
||||||
fragmentBuffer_.clear();
|
|
||||||
fragmenting_ = false;
|
|
||||||
fragmentFlags_ = 0;
|
|
||||||
channelMap_.clear();
|
|
||||||
disconnectDeadline_ = 0;
|
|
||||||
lastMessageTime_ = nowMs();
|
|
||||||
lastPing_ = nowMs();
|
|
||||||
connectStart_ = nowMs();
|
|
||||||
|
|
||||||
// Reserve command counter (old clientinitiv behaviour), then Init0.
|
|
||||||
incCounter(PacketType::Command);
|
|
||||||
sendInitPacket(buildInit0());
|
|
||||||
|
|
||||||
running_ = true;
|
|
||||||
thread_ = std::thread([this] { loopThread(); });
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::loopThread()
|
|
||||||
{
|
|
||||||
while (running_.load()) {
|
|
||||||
pollfd pfd{};
|
|
||||||
pfd.fd = sock_;
|
|
||||||
pfd.events = POLLIN;
|
|
||||||
int rc = ::poll(&pfd, 1, 100);
|
|
||||||
if (!running_.load()) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (rc > 0 && (pfd.revents & POLLIN)) {
|
|
||||||
uint8_t buf[2048];
|
|
||||||
ssize_t n = ::recv(sock_, buf, sizeof(buf), 0);
|
|
||||||
if (n > 0) {
|
|
||||||
handleIncomingPacket(
|
|
||||||
std::span<const uint8_t>(buf, static_cast<size_t>(n)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resendTick();
|
|
||||||
}
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (sock_ >= 0) {
|
|
||||||
::close(sock_);
|
|
||||||
sock_ = -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Outgoing ----------------------------------------------------------
|
|
||||||
|
|
||||||
std::vector<uint8_t> TsClient::buildInit0()
|
|
||||||
{
|
|
||||||
std::vector<uint8_t> buf(4 + 1 + 4 + 4 + 8, 0);
|
|
||||||
putU16BE(buf, 0, static_cast<uint16_t>((Crypto::INIT_VERSION >> 16)));
|
|
||||||
putU16BE(buf, 2, static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
|
||||||
buf[4] = 0x00; // step 0
|
|
||||||
uint32_t ts = static_cast<uint32_t>(
|
|
||||||
std::chrono::duration_cast<std::chrono::seconds>(
|
|
||||||
std::chrono::system_clock::now().time_since_epoch())
|
|
||||||
.count());
|
|
||||||
buf[5] = (ts >> 24) & 0xff;
|
|
||||||
buf[6] = (ts >> 16) & 0xff;
|
|
||||||
buf[7] = (ts >> 8) & 0xff;
|
|
||||||
buf[8] = ts & 0xff;
|
|
||||||
RAND_bytes(buf.data() + 9, 4);
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendInitPacket(const std::vector<uint8_t>& data)
|
|
||||||
{
|
|
||||||
auto raw = buildRawPacket(data, PacketType::Init1, 101,
|
|
||||||
FLAG_UNENCRYPTED);
|
|
||||||
std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN);
|
|
||||||
initResend_ = std::make_unique<Resend>(
|
|
||||||
Resend{raw, 101, nowMs(), nowMs()});
|
|
||||||
sendRawLocked(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<uint8_t> TsClient::buildRawPacket(std::span<const uint8_t> data,
|
|
||||||
PacketType type,
|
|
||||||
uint16_t packetId,
|
|
||||||
uint8_t flags)
|
|
||||||
{
|
|
||||||
std::vector<uint8_t> raw(MAC_LEN + C2S_HEADER_LEN + data.size(), 0);
|
|
||||||
putU16BE(raw, MAC_LEN, packetId);
|
|
||||||
putU16BE(raw, MAC_LEN + 2, clientId_.load());
|
|
||||||
raw[MAC_LEN + 4] =
|
|
||||||
static_cast<uint8_t>((flags & 0xf0) |
|
|
||||||
(static_cast<uint8_t>(type) & 0x0f));
|
|
||||||
std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, data.data(),
|
|
||||||
data.size());
|
|
||||||
return raw;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::encryptPacket(std::vector<uint8_t>& raw, PacketType type,
|
|
||||||
uint16_t packetId, uint32_t gen, uint8_t flags,
|
|
||||||
std::span<const uint8_t> data)
|
|
||||||
{
|
|
||||||
if (type == PacketType::Init1) {
|
|
||||||
std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (flags & FLAG_UNENCRYPTED) {
|
|
||||||
std::memcpy(raw.data(), fakeSignature_.data(), MAC_LEN);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Crypto::KeyNonce kn;
|
|
||||||
if (!cryptoInitComplete_ || ivStruct_.empty()) {
|
|
||||||
std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16);
|
|
||||||
std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16);
|
|
||||||
} else {
|
|
||||||
kn = Crypto::deriveKeyNonce(
|
|
||||||
false, packetId, gen, static_cast<uint8_t>(type),
|
|
||||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
|
||||||
}
|
|
||||||
|
|
||||||
Crypto::ByteView header(raw.data() + MAC_LEN, C2S_HEADER_LEN);
|
|
||||||
auto enc = Crypto::eaxEncrypt(
|
|
||||||
Crypto::ByteView(kn.key.data(), 16),
|
|
||||||
Crypto::ByteView(kn.nonce.data(), 16), header, data);
|
|
||||||
std::memcpy(raw.data(), enc.mac.data(), MAC_LEN);
|
|
||||||
std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, enc.ciphertext.data(),
|
|
||||||
enc.ciphertext.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendOutgoing(std::span<const uint8_t> dataIn, PacketType type,
|
|
||||||
uint8_t extraFlags)
|
|
||||||
{
|
|
||||||
auto ctr = getCounter(type);
|
|
||||||
incCounter(type);
|
|
||||||
|
|
||||||
std::vector<uint8_t> data(dataIn.begin(), dataIn.end());
|
|
||||||
uint8_t flags = extraFlags;
|
|
||||||
switch (type) {
|
|
||||||
case PacketType::Voice:
|
|
||||||
case PacketType::VoiceWhisper:
|
|
||||||
if (data.size() >= 2) {
|
|
||||||
putU16BE(data, 0, ctr.id);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case PacketType::Command:
|
|
||||||
case PacketType::CommandLow:
|
|
||||||
flags |= FLAG_NEWPROTOCOL;
|
|
||||||
break;
|
|
||||||
case PacketType::Ping:
|
|
||||||
case PacketType::Pong:
|
|
||||||
flags |= FLAG_UNENCRYPTED;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto raw = buildRawPacket(data, type, ctr.id, flags);
|
|
||||||
encryptPacket(raw, type, ctr.id, ctr.gen, flags, data);
|
|
||||||
|
|
||||||
if (type == PacketType::Command || type == PacketType::CommandLow) {
|
|
||||||
resendMap_[ctr.id] = Resend{raw, ctr.id, nowMs(), nowMs()};
|
|
||||||
}
|
|
||||||
sendRawLocked(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendRawLocked(const std::vector<uint8_t>& raw)
|
|
||||||
{
|
|
||||||
if (sock_ < 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
::send(sock_, raw.data(), raw.size(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendCommand(const std::string& cmd)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
std::span<const uint8_t> data(
|
|
||||||
reinterpret_cast<const uint8_t*>(cmd.data()), cmd.size());
|
|
||||||
if (data.size() <= MAX_OUT_CONTENT) {
|
|
||||||
sendOutgoing(data, PacketType::Command);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Fragment: FLAG_FRAGMENTED on first and last fragment only.
|
|
||||||
size_t total = data.size();
|
|
||||||
size_t count = (total + MAX_OUT_CONTENT - 1) / MAX_OUT_CONTENT;
|
|
||||||
for (size_t i = 0, idx = 0; i < total; i += MAX_OUT_CONTENT, ++idx) {
|
|
||||||
size_t len = std::min(MAX_OUT_CONTENT, total - i);
|
|
||||||
bool first = idx == 0;
|
|
||||||
bool last = idx == count - 1;
|
|
||||||
uint8_t extra = (first || last) ? FLAG_FRAGMENTED : 0;
|
|
||||||
sendOutgoing(data.subspan(i, len), PacketType::Command, extra);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendVoice(std::span<const uint8_t> opus)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (state_.load() != ClientState::Connected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::vector<uint8_t> buf(3 + opus.size(), 0);
|
|
||||||
buf[2] = 5; // CODEC_OPUS_MUSIC
|
|
||||||
std::memcpy(buf.data() + 3, opus.data(), opus.size());
|
|
||||||
sendOutgoing(buf, PacketType::Voice);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendVoiceStop()
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (state_.load() != ClientState::Connected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::vector<uint8_t> buf(3, 0);
|
|
||||||
buf[2] = 5;
|
|
||||||
sendOutgoing(buf, PacketType::Voice);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendWhisper(std::span<const uint8_t> opus,
|
|
||||||
const std::vector<uint64_t>& channelIds,
|
|
||||||
const std::vector<uint16_t>& clientIds)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (state_.load() != ClientState::Connected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (channelIds.empty() && clientIds.empty()) {
|
|
||||||
sendVoice(opus);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// VoiceWhisper C2S: voiceId(2) + codec(1) + nChan(1) + nClient(1)
|
|
||||||
// + channelIds(u64 BE each) + clientIds(u16 BE each)
|
|
||||||
// + opus. voiceId filled by sendOutgoing.
|
|
||||||
std::vector<uint8_t> buf;
|
|
||||||
buf.resize(3 + 2 + channelIds.size() * 8 + clientIds.size() * 2 +
|
|
||||||
opus.size());
|
|
||||||
size_t p = 0;
|
|
||||||
p += 2; // voiceId placeholder
|
|
||||||
buf[p++] = 5; // codec
|
|
||||||
buf[p++] = static_cast<uint8_t>(channelIds.size());
|
|
||||||
buf[p++] = static_cast<uint8_t>(clientIds.size());
|
|
||||||
for (uint64_t cid : channelIds) {
|
|
||||||
for (int s = 56; s >= 0; s -= 8) {
|
|
||||||
buf[p++] = static_cast<uint8_t>((cid >> s) & 0xff);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (uint16_t clid : clientIds) {
|
|
||||||
buf[p++] = static_cast<uint8_t>((clid >> 8) & 0xff);
|
|
||||||
buf[p++] = static_cast<uint8_t>(clid & 0xff);
|
|
||||||
}
|
|
||||||
std::memcpy(buf.data() + p, opus.data(), opus.size());
|
|
||||||
sendOutgoing(buf, PacketType::VoiceWhisper);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Incoming ----------------------------------------------------------
|
|
||||||
|
|
||||||
std::vector<uint8_t> TsClient::decryptPacket(std::span<const uint8_t> raw,
|
|
||||||
PacketType type,
|
|
||||||
uint16_t packetId,
|
|
||||||
uint32_t gen, uint8_t flags,
|
|
||||||
bool& ok)
|
|
||||||
{
|
|
||||||
ok = false;
|
|
||||||
if (type == PacketType::Init1) {
|
|
||||||
if (std::memcmp(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN) != 0) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
ok = true;
|
|
||||||
return std::vector<uint8_t>(raw.begin() + MAC_LEN + S2C_HEADER_LEN,
|
|
||||||
raw.end());
|
|
||||||
}
|
|
||||||
if (flags & FLAG_UNENCRYPTED) {
|
|
||||||
if (cryptoInitComplete_ &&
|
|
||||||
std::memcmp(raw.data(), fakeSignature_.data(), MAC_LEN) != 0) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
ok = true;
|
|
||||||
return std::vector<uint8_t>(raw.begin() + MAC_LEN + S2C_HEADER_LEN,
|
|
||||||
raw.end());
|
|
||||||
}
|
|
||||||
|
|
||||||
Crypto::ByteView header(raw.data() + MAC_LEN, S2C_HEADER_LEN);
|
|
||||||
Crypto::ByteView mac(raw.data(), MAC_LEN);
|
|
||||||
Crypto::ByteView ct(raw.data() + MAC_LEN + S2C_HEADER_LEN,
|
|
||||||
raw.size() - MAC_LEN - S2C_HEADER_LEN);
|
|
||||||
|
|
||||||
for (bool dummy : {!cryptoInitComplete_, cryptoInitComplete_}) {
|
|
||||||
Crypto::KeyNonce kn;
|
|
||||||
if (dummy || ivStruct_.empty()) {
|
|
||||||
std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16);
|
|
||||||
std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16);
|
|
||||||
} else {
|
|
||||||
kn = Crypto::deriveKeyNonce(
|
|
||||||
true, packetId, gen, static_cast<uint8_t>(type),
|
|
||||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
|
||||||
}
|
|
||||||
auto dec = Crypto::eaxDecrypt(Crypto::ByteView(kn.key.data(), 16),
|
|
||||||
Crypto::ByteView(kn.nonce.data(), 16),
|
|
||||||
header, ct, mac);
|
|
||||||
if (dec) {
|
|
||||||
ok = true;
|
|
||||||
return *dec;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleIncomingPacket(std::span<const uint8_t> raw)
|
|
||||||
{
|
|
||||||
if (raw.size() < MAC_LEN + S2C_HEADER_LEN) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
uint16_t packetId = getU16BE(raw, MAC_LEN);
|
|
||||||
uint8_t ptByte = raw[MAC_LEN + 2];
|
|
||||||
auto type = static_cast<PacketType>(ptByte & 0x0f);
|
|
||||||
uint8_t flags = ptByte & 0xf0;
|
|
||||||
lastMessageTime_ = nowMs();
|
|
||||||
|
|
||||||
bool ok = false;
|
|
||||||
auto data = decryptPacket(raw, type, packetId, 0, flags, ok);
|
|
||||||
if (!ok) {
|
|
||||||
debug("failed to decrypt packet");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::span<const uint8_t> d(data.data(), data.size());
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case PacketType::Init1:
|
|
||||||
handleInit(d);
|
|
||||||
break;
|
|
||||||
case PacketType::Command:
|
|
||||||
case PacketType::CommandLow:
|
|
||||||
sendAck(packetId, type == PacketType::Command ? PacketType::Ack
|
|
||||||
: PacketType::AckLow);
|
|
||||||
handleCommandData(d, flags);
|
|
||||||
break;
|
|
||||||
case PacketType::Ack:
|
|
||||||
if (data.size() >= 2) {
|
|
||||||
resendMap_.erase(getU16BE(d, 0));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case PacketType::Ping:
|
|
||||||
handlePing(packetId);
|
|
||||||
break;
|
|
||||||
case PacketType::Voice:
|
|
||||||
case PacketType::VoiceWhisper:
|
|
||||||
if (cb_.onVoice) {
|
|
||||||
cb_.onVoice(d);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendAck(uint16_t ackId, PacketType ackType)
|
|
||||||
{
|
|
||||||
std::vector<uint8_t> buf(2, 0);
|
|
||||||
putU16BE(buf, 0, ackId);
|
|
||||||
sendOutgoing(buf, ackType);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handlePing(uint16_t packetId)
|
|
||||||
{
|
|
||||||
std::vector<uint8_t> buf(2, 0);
|
|
||||||
putU16BE(buf, 0, packetId);
|
|
||||||
sendOutgoing(buf, PacketType::Pong);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Handshake ---------------------------------------------------------
|
|
||||||
|
|
||||||
void TsClient::handleInit(std::span<const uint8_t> data)
|
|
||||||
{
|
|
||||||
if (data.empty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
uint8_t step = data[0];
|
|
||||||
debug("init step " + std::to_string(step));
|
|
||||||
|
|
||||||
if (step == 1) {
|
|
||||||
if (data.size() < 21) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
std::vector<uint8_t> init2(4 + 1 + 16 + 4, 0);
|
|
||||||
putU16BE(init2, 0,
|
|
||||||
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
|
|
||||||
putU16BE(init2, 2,
|
|
||||||
static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
|
||||||
init2[4] = 0x02;
|
|
||||||
std::memcpy(init2.data() + 5, data.data() + 1, 20);
|
|
||||||
initResend_.reset();
|
|
||||||
sendInitPacket(init2);
|
|
||||||
} else if (step == 3) {
|
|
||||||
if (data.size() < 1 + 64 + 64 + 4 + 100) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
state_ = ClientState::Handshake;
|
|
||||||
initResend_.reset();
|
|
||||||
|
|
||||||
std::span<const uint8_t> x = data.subspan(1, 64);
|
|
||||||
std::span<const uint8_t> n = data.subspan(65, 64);
|
|
||||||
int32_t level = static_cast<int32_t>(
|
|
||||||
(data[129] << 24) | (data[130] << 16) | (data[131] << 8) |
|
|
||||||
data[132]);
|
|
||||||
std::span<const uint8_t> serverData = data.subspan(133, 100);
|
|
||||||
debug("RSA puzzle level=" + std::to_string(level));
|
|
||||||
|
|
||||||
auto y = rsaPuzzle(x, n, level);
|
|
||||||
|
|
||||||
// alpha = 10 random bytes (base64); omega = identity pubkey string.
|
|
||||||
alphaTmp_.assign(10, 0);
|
|
||||||
RAND_bytes(alphaTmp_.data(), 10);
|
|
||||||
std::string alpha = Util::base64Encode(
|
|
||||||
Crypto::ByteView(alphaTmp_.data(), alphaTmp_.size()));
|
|
||||||
|
|
||||||
CommandParams p;
|
|
||||||
p["alpha"] = alpha;
|
|
||||||
p["omega"] = opts_.identity->publicKeyString();
|
|
||||||
p["ot"] = "1";
|
|
||||||
p["ip"] = "";
|
|
||||||
std::string initAdd = buildCommand("clientinitiv", p);
|
|
||||||
std::span<const uint8_t> textBytes(
|
|
||||||
reinterpret_cast<const uint8_t*>(initAdd.data()),
|
|
||||||
initAdd.size());
|
|
||||||
|
|
||||||
std::vector<uint8_t> init4(4 + 1 + 64 + 64 + 4 + 100 + 64 +
|
|
||||||
textBytes.size(),
|
|
||||||
0);
|
|
||||||
putU16BE(init4, 0,
|
|
||||||
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
|
|
||||||
putU16BE(init4, 2,
|
|
||||||
static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
|
||||||
init4[4] = 0x04;
|
|
||||||
std::memcpy(init4.data() + 5, x.data(), 64);
|
|
||||||
std::memcpy(init4.data() + 69, n.data(), 64);
|
|
||||||
init4[133] = (level >> 24) & 0xff;
|
|
||||||
init4[134] = (level >> 16) & 0xff;
|
|
||||||
init4[135] = (level >> 8) & 0xff;
|
|
||||||
init4[136] = level & 0xff;
|
|
||||||
std::memcpy(init4.data() + 137, serverData.data(), 100);
|
|
||||||
std::memcpy(init4.data() + 237, y.data(), 64);
|
|
||||||
std::memcpy(init4.data() + 301, textBytes.data(), textBytes.size());
|
|
||||||
|
|
||||||
sendInitPacket(init4);
|
|
||||||
} else if (step == 0x7f) {
|
|
||||||
debug("server requested restart");
|
|
||||||
initResend_.reset();
|
|
||||||
sendInitPacket(buildInit0());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleCommandData(std::span<const uint8_t> data,
|
|
||||||
uint8_t flags)
|
|
||||||
{
|
|
||||||
if (flags & FLAG_FRAGMENTED) {
|
|
||||||
if (!fragmenting_) {
|
|
||||||
fragmenting_ = true;
|
|
||||||
fragmentFlags_ = flags;
|
|
||||||
fragmentBuffer_.assign(data.begin(), data.end());
|
|
||||||
} else {
|
|
||||||
fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(),
|
|
||||||
data.end());
|
|
||||||
uint8_t saved = fragmentFlags_;
|
|
||||||
fragmenting_ = false;
|
|
||||||
fragmentFlags_ = 0;
|
|
||||||
auto merged = std::move(fragmentBuffer_);
|
|
||||||
fragmentBuffer_.clear();
|
|
||||||
processCommand(
|
|
||||||
std::span<const uint8_t>(merged.data(), merged.size()),
|
|
||||||
saved);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (fragmenting_) {
|
|
||||||
fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(),
|
|
||||||
data.end());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
processCommand(data, flags);
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::processCommand(std::span<const uint8_t> data, uint8_t flags)
|
|
||||||
{
|
|
||||||
std::vector<uint8_t> decompressed;
|
|
||||||
if (flags & FLAG_COMPRESSED) {
|
|
||||||
try {
|
|
||||||
decompressed = qlzDecompress(data);
|
|
||||||
data = std::span<const uint8_t>(decompressed.data(),
|
|
||||||
decompressed.size());
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
debug(std::string("decompression failed: ") + e.what());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string cmdStr(reinterpret_cast<const char*>(data.data()),
|
|
||||||
data.size());
|
|
||||||
auto parsed = parseCommand(cmdStr);
|
|
||||||
if (cb_.onCommand) {
|
|
||||||
cb_.onCommand(parsed);
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::string& name = parsed.name;
|
|
||||||
if (name == "initivexpand") {
|
|
||||||
handleInitIvExpand(parsed.params);
|
|
||||||
} else if (name == "initivexpand2") {
|
|
||||||
handleInitIvExpand2(parsed.params);
|
|
||||||
} else if (name == "initserver") {
|
|
||||||
handleInitServer(parsed.params);
|
|
||||||
} else if (name == "channellist") {
|
|
||||||
handleChannelList(parsed);
|
|
||||||
} else if (name == "channellistfinished") {
|
|
||||||
handleChannelListFinished();
|
|
||||||
} else if (name == "notifyclientleftview") {
|
|
||||||
auto it = parsed.params.find("clid");
|
|
||||||
if (it != parsed.params.end() &&
|
|
||||||
static_cast<uint16_t>(std::stoul(it->second)) ==
|
|
||||||
clientId_.load()) {
|
|
||||||
cleanup();
|
|
||||||
}
|
|
||||||
} else if (name == "notifytextmessage") {
|
|
||||||
if (cb_.onTextMessage) {
|
|
||||||
cb_.onTextMessage(parsed.params);
|
|
||||||
}
|
|
||||||
} else if (name == "error") {
|
|
||||||
int errId = 0;
|
|
||||||
auto it = parsed.params.find("id");
|
|
||||||
if (it != parsed.params.end()) {
|
|
||||||
errId = std::stoi(it->second);
|
|
||||||
}
|
|
||||||
if (errId == 2568 || errId == 3329 || errId == 1796) {
|
|
||||||
std::string msg = "unknown error";
|
|
||||||
auto m = parsed.params.find("msg");
|
|
||||||
if (m != parsed.params.end()) {
|
|
||||||
msg = m->second;
|
|
||||||
}
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError("TS3 error " + std::to_string(errId) + ": " +
|
|
||||||
msg);
|
|
||||||
}
|
|
||||||
disconnect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleInitIvExpand(const CommandParams& params)
|
|
||||||
{
|
|
||||||
initResend_.reset();
|
|
||||||
auto ai = params.find("alpha");
|
|
||||||
auto bi = params.find("beta");
|
|
||||||
auto oi = params.find("omega");
|
|
||||||
if (ai == params.end() || bi == params.end() || oi == params.end()) {
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError("missing initivexpand parameters");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
auto beta = Util::base64Decode(bi->second);
|
|
||||||
auto omega = Util::base64Decode(oi->second);
|
|
||||||
auto sharedKey = opts_.identity->sharedSecret(
|
|
||||||
Crypto::ByteView(omega.data(), omega.size()));
|
|
||||||
|
|
||||||
ivStruct_.assign(10 + beta.size(), 0);
|
|
||||||
for (size_t i = 0; i < 10; ++i) {
|
|
||||||
ivStruct_[i] = sharedKey[i] ^ alphaTmp_[i];
|
|
||||||
}
|
|
||||||
for (size_t i = 0; i < beta.size(); ++i) {
|
|
||||||
ivStruct_[10 + i] = sharedKey[10 + i] ^ beta[i];
|
|
||||||
}
|
|
||||||
auto sig = Crypto::sha1(
|
|
||||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
|
||||||
std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN);
|
|
||||||
cryptoInitComplete_ = true;
|
|
||||||
alphaTmp_.clear();
|
|
||||||
sendClientInit();
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleInitIvExpand2(const CommandParams& params)
|
|
||||||
{
|
|
||||||
if (cryptoInitComplete_ || alphaTmp_.empty()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
initResend_.reset();
|
|
||||||
auto li = params.find("l");
|
|
||||||
auto bi = params.find("beta");
|
|
||||||
auto oi = params.find("omega");
|
|
||||||
if (li == params.end() || bi == params.end() || oi == params.end()) {
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError("missing initivexpand2 parameters");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
auto beta = Util::base64Decode(bi->second);
|
|
||||||
auto license = Util::base64Decode(li->second);
|
|
||||||
auto blocks =
|
|
||||||
parseLicense(ByteView(license.data(), license.size()));
|
|
||||||
auto serverKey = deriveLicenseKey(blocks);
|
|
||||||
auto temp = generateTemporaryKey();
|
|
||||||
|
|
||||||
std::string ek = Util::base64Encode(
|
|
||||||
Crypto::ByteView(temp.publicKey.data(), 32));
|
|
||||||
std::vector<uint8_t> toSign(temp.publicKey.begin(),
|
|
||||||
temp.publicKey.end());
|
|
||||||
toSign.insert(toSign.end(), beta.begin(), beta.end());
|
|
||||||
auto sigBuf = opts_.identity->sign(
|
|
||||||
Crypto::ByteView(toSign.data(), toSign.size()));
|
|
||||||
std::string proof = Util::base64Encode(
|
|
||||||
Crypto::ByteView(sigBuf.data(), sigBuf.size()));
|
|
||||||
|
|
||||||
CommandParams ck;
|
|
||||||
ck["ek"] = ek;
|
|
||||||
ck["proof"] = proof;
|
|
||||||
sendCommand(buildCommand("clientek", ck));
|
|
||||||
|
|
||||||
auto shared = getSharedSecret2(
|
|
||||||
ByteView(serverKey.data(), serverKey.size()),
|
|
||||||
ByteView(temp.privateKey.data(), 32));
|
|
||||||
|
|
||||||
ivStruct_.assign(shared.begin(), shared.end());
|
|
||||||
for (size_t i = 0; i < 10 && i < ivStruct_.size(); ++i) {
|
|
||||||
ivStruct_[i] ^= alphaTmp_[i];
|
|
||||||
}
|
|
||||||
for (size_t i = 0; i < beta.size() && (10 + i) < ivStruct_.size();
|
|
||||||
++i) {
|
|
||||||
ivStruct_[10 + i] ^= beta[i];
|
|
||||||
}
|
|
||||||
auto sig = Crypto::sha1(
|
|
||||||
Crypto::ByteView(ivStruct_.data(), ivStruct_.size()));
|
|
||||||
std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN);
|
|
||||||
cryptoInitComplete_ = true;
|
|
||||||
alphaTmp_.clear();
|
|
||||||
sendClientInit();
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError(std::string("initivexpand2 failed: ") + e.what());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::sendClientInit()
|
|
||||||
{
|
|
||||||
debug("sending clientinit");
|
|
||||||
CommandParams p;
|
|
||||||
p["client_nickname"] = opts_.nickname;
|
|
||||||
p["client_version"] = VS_VERSION;
|
|
||||||
p["client_platform"] = VS_PLATFORM;
|
|
||||||
p["client_input_hardware"] = "1";
|
|
||||||
p["client_output_hardware"] = "1";
|
|
||||||
p["client_default_channel"] = opts_.defaultChannel;
|
|
||||||
p["client_default_channel_password"] =
|
|
||||||
opts_.channelPassword.empty()
|
|
||||||
? ""
|
|
||||||
: Crypto::hashPassword(opts_.channelPassword);
|
|
||||||
p["client_server_password"] =
|
|
||||||
opts_.serverPassword.empty()
|
|
||||||
? ""
|
|
||||||
: Crypto::hashPassword(opts_.serverPassword);
|
|
||||||
p["client_meta_data"] = "";
|
|
||||||
p["client_version_sign"] = VS_SIGN;
|
|
||||||
p["client_key_offset"] = std::to_string(opts_.identity->keyOffset());
|
|
||||||
p["client_nickname_phonetic"] = "";
|
|
||||||
p["client_default_token"] = "";
|
|
||||||
p["hwid"] = "";
|
|
||||||
sendCommand(buildCommand("clientinit", p));
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleInitServer(const CommandParams& params)
|
|
||||||
{
|
|
||||||
auto it = params.find("aclid");
|
|
||||||
uint16_t id = 0;
|
|
||||||
if (it != params.end()) {
|
|
||||||
id = static_cast<uint16_t>(std::stoul(it->second));
|
|
||||||
}
|
|
||||||
clientId_ = id;
|
|
||||||
state_ = ClientState::Connected;
|
|
||||||
lastPing_ = nowMs();
|
|
||||||
debug("connected, clientId=" + std::to_string(id));
|
|
||||||
if (cb_.onConnected) {
|
|
||||||
cb_.onConnected();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleChannelList(const ParsedCommand& parsed)
|
|
||||||
{
|
|
||||||
const auto& entries =
|
|
||||||
parsed.groups.empty()
|
|
||||||
? std::vector<CommandParams>{parsed.params}
|
|
||||||
: parsed.groups;
|
|
||||||
for (const auto& e : entries) {
|
|
||||||
auto ci = e.find("cid");
|
|
||||||
auto ni = e.find("channel_name");
|
|
||||||
if (ci != e.end() && ni != e.end()) {
|
|
||||||
channelMap_[ni->second] =
|
|
||||||
static_cast<uint64_t>(std::stoull(ci->second));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::handleChannelListFinished()
|
|
||||||
{
|
|
||||||
const std::string& target = opts_.defaultChannel;
|
|
||||||
if (target.empty() || clientId_.load() == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
uint64_t cid = 0;
|
|
||||||
bool numeric = !target.empty() &&
|
|
||||||
target.find_first_not_of("0123456789") ==
|
|
||||||
std::string::npos;
|
|
||||||
if (numeric) {
|
|
||||||
cid = std::stoull(target);
|
|
||||||
} else {
|
|
||||||
auto it = channelMap_.find(target);
|
|
||||||
if (it != channelMap_.end()) {
|
|
||||||
cid = it->second;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (cid == 0) {
|
|
||||||
debug("default channel not found: " + target);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
CommandParams p;
|
|
||||||
p["cid"] = std::to_string(cid);
|
|
||||||
p["clid"] = std::to_string(clientId_.load());
|
|
||||||
p["cpw"] = opts_.channelPassword;
|
|
||||||
sendCommand(buildCommand("clientmove", p));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Timers / teardown -------------------------------------------------
|
|
||||||
|
|
||||||
void TsClient::resendTick()
|
|
||||||
{
|
|
||||||
int64_t now = nowMs();
|
|
||||||
|
|
||||||
if (disconnectDeadline_ != 0 && now >= disconnectDeadline_) {
|
|
||||||
cleanup();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (initResend_) {
|
|
||||||
if (now - initResend_->firstSend > 30000) {
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError("init timeout");
|
|
||||||
}
|
|
||||||
cleanup();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (now - initResend_->lastSend > 1000) {
|
|
||||||
initResend_->lastSend = now;
|
|
||||||
sendRawLocked(initResend_->raw);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (auto& [id, pkt] : resendMap_) {
|
|
||||||
if (now - pkt.firstSend > 30000) {
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError("packet " + std::to_string(id) + " timeout");
|
|
||||||
}
|
|
||||||
cleanup();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (now - pkt.lastSend > 1000) {
|
|
||||||
pkt.lastSend = now;
|
|
||||||
sendRawLocked(pkt.raw);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state_.load() == ClientState::Connected &&
|
|
||||||
now - lastPing_ >= 1000) {
|
|
||||||
lastPing_ = now;
|
|
||||||
std::vector<uint8_t> empty;
|
|
||||||
sendOutgoing(empty, PacketType::Ping);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (now - lastMessageTime_ > 30000) {
|
|
||||||
if (cb_.onError) {
|
|
||||||
cb_.onError("connection timeout - no response");
|
|
||||||
}
|
|
||||||
cleanup();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::disconnect()
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (state_.load() == ClientState::Connected) {
|
|
||||||
state_ = ClientState::Disconnecting;
|
|
||||||
CommandParams p;
|
|
||||||
p["reasonid"] = "8";
|
|
||||||
p["reasonmsg"] = "leaving";
|
|
||||||
sendCommand(buildCommand("clientdisconnect", p));
|
|
||||||
}
|
|
||||||
disconnectDeadline_ = nowMs() + 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::forceClose()
|
|
||||||
{
|
|
||||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
|
||||||
if (state_.load() == ClientState::Disconnected && !running_.load()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
state_ = ClientState::Disconnected;
|
|
||||||
running_ = false;
|
|
||||||
if (sock_ >= 0) {
|
|
||||||
::shutdown(sock_, SHUT_RDWR);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void TsClient::cleanup()
|
|
||||||
{
|
|
||||||
if (state_.load() == ClientState::Disconnected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
state_ = ClientState::Disconnected;
|
|
||||||
running_ = false;
|
|
||||||
if (cb_.onDisconnected) {
|
|
||||||
cb_.onDisconnected();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
#include "echoion/protocol/Util.hpp"
|
|
||||||
|
|
||||||
#include <array>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Protocol::Util
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
constexpr char kEnc[] =
|
|
||||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
||||||
|
|
||||||
std::array<int8_t, 256> makeDecodeTable()
|
|
||||||
{
|
|
||||||
std::array<int8_t, 256> t{};
|
|
||||||
t.fill(-1);
|
|
||||||
for (int i = 0; i < 64; ++i) {
|
|
||||||
t[static_cast<uint8_t>(kEnc[i])] = static_cast<int8_t>(i);
|
|
||||||
}
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
const std::array<int8_t, 256> kDec = makeDecodeTable();
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
std::string base64Encode(ByteView data)
|
|
||||||
{
|
|
||||||
std::string out;
|
|
||||||
out.reserve((data.size() + 2) / 3 * 4);
|
|
||||||
size_t i = 0;
|
|
||||||
for (; i + 3 <= data.size(); i += 3) {
|
|
||||||
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
|
|
||||||
(static_cast<uint32_t>(data[i + 1]) << 8) |
|
|
||||||
static_cast<uint32_t>(data[i + 2]);
|
|
||||||
out.push_back(kEnc[(n >> 18) & 0x3f]);
|
|
||||||
out.push_back(kEnc[(n >> 12) & 0x3f]);
|
|
||||||
out.push_back(kEnc[(n >> 6) & 0x3f]);
|
|
||||||
out.push_back(kEnc[n & 0x3f]);
|
|
||||||
}
|
|
||||||
const size_t rem = data.size() - i;
|
|
||||||
if (rem == 1) {
|
|
||||||
uint32_t n = static_cast<uint32_t>(data[i]) << 16;
|
|
||||||
out.push_back(kEnc[(n >> 18) & 0x3f]);
|
|
||||||
out.push_back(kEnc[(n >> 12) & 0x3f]);
|
|
||||||
out.push_back('=');
|
|
||||||
out.push_back('=');
|
|
||||||
} else if (rem == 2) {
|
|
||||||
uint32_t n = (static_cast<uint32_t>(data[i]) << 16) |
|
|
||||||
(static_cast<uint32_t>(data[i + 1]) << 8);
|
|
||||||
out.push_back(kEnc[(n >> 18) & 0x3f]);
|
|
||||||
out.push_back(kEnc[(n >> 12) & 0x3f]);
|
|
||||||
out.push_back(kEnc[(n >> 6) & 0x3f]);
|
|
||||||
out.push_back('=');
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes base64Decode(const std::string& text)
|
|
||||||
{
|
|
||||||
Bytes out;
|
|
||||||
out.reserve(text.size() / 4 * 3);
|
|
||||||
uint32_t buf = 0;
|
|
||||||
int bits = 0;
|
|
||||||
for (char c : text) {
|
|
||||||
if (c == '=' || c == '\n' || c == '\r' || c == ' ') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
int8_t v = kDec[static_cast<uint8_t>(c)];
|
|
||||||
if (v < 0) {
|
|
||||||
throw std::runtime_error("invalid base64 character");
|
|
||||||
}
|
|
||||||
buf = (buf << 6) | static_cast<uint32_t>(v);
|
|
||||||
bits += 6;
|
|
||||||
if (bits >= 8) {
|
|
||||||
bits -= 8;
|
|
||||||
out.push_back(static_cast<uint8_t>((buf >> bits) & 0xff));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string toHex(ByteView data)
|
|
||||||
{
|
|
||||||
static const char* h = "0123456789abcdef";
|
|
||||||
std::string out;
|
|
||||||
out.reserve(data.size() * 2);
|
|
||||||
for (uint8_t b : data) {
|
|
||||||
out.push_back(h[b >> 4]);
|
|
||||||
out.push_back(h[b & 0x0f]);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Bytes fromHex(const std::string& hex)
|
|
||||||
{
|
|
||||||
auto nib = [](char c) -> int {
|
|
||||||
if (c >= '0' && c <= '9')
|
|
||||||
return c - '0';
|
|
||||||
if (c >= 'a' && c <= 'f')
|
|
||||||
return c - 'a' + 10;
|
|
||||||
if (c >= 'A' && c <= 'F')
|
|
||||||
return c - 'A' + 10;
|
|
||||||
throw std::runtime_error("invalid hex character");
|
|
||||||
};
|
|
||||||
if (hex.size() % 2 != 0) {
|
|
||||||
throw std::runtime_error("odd-length hex string");
|
|
||||||
}
|
|
||||||
Bytes out;
|
|
||||||
out.reserve(hex.size() / 2);
|
|
||||||
for (size_t i = 0; i < hex.size(); i += 2) {
|
|
||||||
out.push_back(static_cast<uint8_t>((nib(hex[i]) << 4) |
|
|
||||||
nib(hex[i + 1])));
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Protocol::Util
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
# Unit tests for EchoionProtocol. Uses a tiny header-only harness (check.hpp),
|
|
||||||
# no external test framework required.
|
|
||||||
|
|
||||||
file(GLOB ECHOIONPROTOCOL_TEST_SOURCES CONFIGURE_DEPENDS
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/test_*.cpp")
|
|
||||||
|
|
||||||
add_executable(echoion_protocol_tests ${ECHOIONPROTOCOL_TEST_SOURCES})
|
|
||||||
target_link_libraries(echoion_protocol_tests PRIVATE EchoionProtocol)
|
|
||||||
target_include_directories(echoion_protocol_tests PRIVATE
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}")
|
|
||||||
|
|
||||||
add_test(NAME echoion_protocol_tests COMMAND echoion_protocol_tests)
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Minimal dependency-free test harness. Tests register cases with TEST_CASE and
|
|
||||||
// assert with CHECK / CHECK_EQ; main() runs them and reports a non-zero exit on
|
|
||||||
// any failure so ctest treats it as a failing test.
|
|
||||||
|
|
||||||
#include <cstdio>
|
|
||||||
#include <functional>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace echotest
|
|
||||||
{
|
|
||||||
struct Case {
|
|
||||||
std::string name;
|
|
||||||
std::function<void()> fn;
|
|
||||||
};
|
|
||||||
|
|
||||||
inline std::vector<Case>& registry()
|
|
||||||
{
|
|
||||||
static std::vector<Case> cases;
|
|
||||||
return cases;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int& failures()
|
|
||||||
{
|
|
||||||
static int f = 0;
|
|
||||||
return f;
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Registrar {
|
|
||||||
Registrar(const std::string& name, std::function<void()> fn)
|
|
||||||
{
|
|
||||||
registry().push_back({name, std::move(fn)});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
inline int run()
|
|
||||||
{
|
|
||||||
int failed = 0;
|
|
||||||
for (auto& c : registry()) {
|
|
||||||
int before = failures();
|
|
||||||
try {
|
|
||||||
c.fn();
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
std::printf(" [THROW] %s: %s\n", c.name.c_str(), e.what());
|
|
||||||
++failures();
|
|
||||||
}
|
|
||||||
if (failures() > before) {
|
|
||||||
std::printf("[FAIL] %s\n", c.name.c_str());
|
|
||||||
++failed;
|
|
||||||
} else {
|
|
||||||
std::printf("[ok] %s\n", c.name.c_str());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
std::printf("\n%zu cases, %d failed\n", registry().size(), failed);
|
|
||||||
return failed == 0 ? 0 : 1;
|
|
||||||
}
|
|
||||||
} // namespace echotest
|
|
||||||
|
|
||||||
#define TEST_CASE(name) \
|
|
||||||
static void name(); \
|
|
||||||
static echotest::Registrar reg_##name(#name, name); \
|
|
||||||
static void name()
|
|
||||||
|
|
||||||
#define CHECK(cond) \
|
|
||||||
do { \
|
|
||||||
if (!(cond)) { \
|
|
||||||
std::printf(" CHECK failed: %s (%s:%d)\n", #cond, __FILE__, \
|
|
||||||
__LINE__); \
|
|
||||||
++echotest::failures(); \
|
|
||||||
} \
|
|
||||||
} while (0)
|
|
||||||
|
|
||||||
#define CHECK_EQ(a, b) \
|
|
||||||
do { \
|
|
||||||
if (!((a) == (b))) { \
|
|
||||||
std::printf(" CHECK_EQ failed: %s == %s (%s:%d)\n", #a, #b, \
|
|
||||||
__FILE__, __LINE__); \
|
|
||||||
++echotest::failures(); \
|
|
||||||
} \
|
|
||||||
} while (0)
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
#include "check.hpp"
|
|
||||||
#include "echoion/protocol/Command.hpp"
|
|
||||||
|
|
||||||
using namespace Echoion::Protocol;
|
|
||||||
|
|
||||||
TEST_CASE(escape_roundtrip)
|
|
||||||
{
|
|
||||||
std::string raw = "hello world|pipe/slash\ttab\nnl\\back";
|
|
||||||
auto esc = tsEscape(raw);
|
|
||||||
// Spaces and specials must be escaped (no raw space/pipe left).
|
|
||||||
CHECK(esc.find(' ') == std::string::npos);
|
|
||||||
CHECK(esc.find('|') == std::string::npos);
|
|
||||||
CHECK_EQ(tsUnescape(esc), raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(escape_known)
|
|
||||||
{
|
|
||||||
CHECK_EQ(tsEscape("a b"), std::string("a\\sb"));
|
|
||||||
CHECK_EQ(tsEscape("a|b"), std::string("a\\pb"));
|
|
||||||
CHECK_EQ(tsEscape("a/b"), std::string("a\\/b"));
|
|
||||||
CHECK_EQ(tsUnescape("a\\sb"), std::string("a b"));
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(build_command)
|
|
||||||
{
|
|
||||||
CommandParams p;
|
|
||||||
p["client_nickname"] = "My Bot";
|
|
||||||
p["cid"] = "5";
|
|
||||||
auto cmd = buildCommand("clientmove", p);
|
|
||||||
// Params are ordered by key (map): cid before client_nickname.
|
|
||||||
CHECK_EQ(cmd, std::string("clientmove cid=5 client_nickname=My\\sBot"));
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(parse_notify)
|
|
||||||
{
|
|
||||||
auto pc = parseCommand(
|
|
||||||
"notifytextmessage targetmode=2 msg=hello\\sworld invokerid=7 "
|
|
||||||
"invokername=Alice");
|
|
||||||
CHECK_EQ(pc.name, std::string("notifytextmessage"));
|
|
||||||
CHECK_EQ(pc.params["targetmode"], std::string("2"));
|
|
||||||
CHECK_EQ(pc.params["msg"], std::string("hello world"));
|
|
||||||
CHECK_EQ(pc.params["invokername"], std::string("Alice"));
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(parse_pipe_groups)
|
|
||||||
{
|
|
||||||
auto pc = parseCommand("channellist cid=1 channel_name=Default|cid=2 "
|
|
||||||
"channel_name=Talk");
|
|
||||||
CHECK_EQ(pc.name, std::string("channellist"));
|
|
||||||
CHECK_EQ(pc.groups.size(), size_t(2));
|
|
||||||
CHECK_EQ(pc.groups[0]["cid"], std::string("1"));
|
|
||||||
CHECK_EQ(pc.groups[0]["channel_name"], std::string("Default"));
|
|
||||||
CHECK_EQ(pc.groups[1]["cid"], std::string("2"));
|
|
||||||
CHECK_EQ(pc.groups[1]["channel_name"], std::string("Talk"));
|
|
||||||
}
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
#include "check.hpp"
|
|
||||||
#include "echoion/protocol/Crypto.hpp"
|
|
||||||
#include "echoion/protocol/Util.hpp"
|
|
||||||
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
using namespace Echoion::Protocol;
|
|
||||||
using Crypto::ByteView;
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
Crypto::Bytes hex(const std::string& h) { return Util::fromHex(h); }
|
|
||||||
std::string hx(ByteView b) { return Util::toHex(b); }
|
|
||||||
std::string hx(const std::vector<uint8_t>& b)
|
|
||||||
{
|
|
||||||
return Util::toHex(ByteView(b.data(), b.size()));
|
|
||||||
}
|
|
||||||
template <size_t N> std::string hx(const std::array<uint8_t, N>& b)
|
|
||||||
{
|
|
||||||
return Util::toHex(ByteView(b.data(), b.size()));
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
// RFC 4493 AES-128-CMAC known-answer vectors.
|
|
||||||
TEST_CASE(cmac_rfc4493)
|
|
||||||
{
|
|
||||||
auto key = hex("2b7e151628aed2a6abf7158809cf4f3c");
|
|
||||||
|
|
||||||
// Example 1: empty message.
|
|
||||||
CHECK_EQ(hx(Crypto::cmac(key, {})),
|
|
||||||
std::string("bb1d6929e95937287fa37d129b756746"));
|
|
||||||
|
|
||||||
// Example 2: 16-byte message.
|
|
||||||
auto m2 = hex("6bc1bee22e409f96e93d7e117393172a");
|
|
||||||
CHECK_EQ(hx(Crypto::cmac(key, m2)),
|
|
||||||
std::string("070a16b46b4d4144f79bdd9dd04a287c"));
|
|
||||||
|
|
||||||
// Example 3: 40-byte message.
|
|
||||||
auto m3 = hex("6bc1bee22e409f96e93d7e117393172a"
|
|
||||||
"ae2d8a571e03ac9c9eb76fac45af8e51"
|
|
||||||
"30c81c46a35ce411");
|
|
||||||
CHECK_EQ(hx(Crypto::cmac(key, m3)),
|
|
||||||
std::string("dfa66747de9ae63030ca32611497c827"));
|
|
||||||
|
|
||||||
// Example 4: 64-byte message.
|
|
||||||
auto m4 = hex("6bc1bee22e409f96e93d7e117393172a"
|
|
||||||
"ae2d8a571e03ac9c9eb76fac45af8e51"
|
|
||||||
"30c81c46a35ce411e5fbc1191a0a52ef"
|
|
||||||
"f69f2445df4f9b17ad2b417be66c3710");
|
|
||||||
CHECK_EQ(hx(Crypto::cmac(key, m4)),
|
|
||||||
std::string("51f0bebf7e3b9d92fc49741779363cfe"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// EAX specification test vectors (Bellare/Rogaway/Wagner). The EAX output is
|
|
||||||
// ciphertext||tag where tag is the full 16-byte value; TeamSpeak truncates the
|
|
||||||
// MAC to 8 bytes, so we compare against the first 8 tag bytes.
|
|
||||||
TEST_CASE(eax_spec_vectors)
|
|
||||||
{
|
|
||||||
// Empty message.
|
|
||||||
{
|
|
||||||
auto key = hex("233952dee4d5ed5f9b9c6d6ff80ff478");
|
|
||||||
auto nonce = hex("62ec67f9c3a4a407fcb2a8c49031a8b3");
|
|
||||||
auto hdr = hex("6bfb914fd07eae6b");
|
|
||||||
auto res = Crypto::eaxEncrypt(key, nonce, hdr, {});
|
|
||||||
CHECK(res.ciphertext.empty());
|
|
||||||
CHECK_EQ(hx(res.mac), std::string("e037830e8389f27b"));
|
|
||||||
// Round-trip.
|
|
||||||
auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac);
|
|
||||||
CHECK(dec.has_value());
|
|
||||||
CHECK(dec && dec->empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2-byte message F7FB.
|
|
||||||
{
|
|
||||||
auto key = hex("91945d3f4dcbee0bf45ef52255f095a4");
|
|
||||||
auto nonce = hex("becaf043b0a23d843194ba972c66debd");
|
|
||||||
auto hdr = hex("fa3bfd4806eb53fa");
|
|
||||||
auto msg = hex("f7fb");
|
|
||||||
auto res = Crypto::eaxEncrypt(key, nonce, hdr, msg);
|
|
||||||
CHECK_EQ(hx(res.ciphertext), std::string("19dd"));
|
|
||||||
CHECK_EQ(hx(res.mac), std::string("5c4c9331049d0bda"));
|
|
||||||
auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac);
|
|
||||||
CHECK(dec.has_value());
|
|
||||||
CHECK(dec && hx(*dec) == std::string("f7fb"));
|
|
||||||
// Tamper → reject.
|
|
||||||
auto bad = res.mac;
|
|
||||||
bad[0] ^= 0x01;
|
|
||||||
CHECK(!Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, bad));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(sha_and_base64)
|
|
||||||
{
|
|
||||||
// sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d
|
|
||||||
std::string abc = "abc";
|
|
||||||
auto s1 = Crypto::sha1(
|
|
||||||
ByteView(reinterpret_cast<const uint8_t*>(abc.data()), abc.size()));
|
|
||||||
CHECK_EQ(hx(s1),
|
|
||||||
std::string("a9993e364706816aba3e25717850c26c9cd0d89d"));
|
|
||||||
|
|
||||||
// base64 round-trip + known value.
|
|
||||||
CHECK_EQ(Util::base64Encode(ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>("foobar"), 6)),
|
|
||||||
std::string("Zm9vYmFy"));
|
|
||||||
auto dec = Util::base64Decode("Zm9vYmFy");
|
|
||||||
CHECK_EQ(std::string(dec.begin(), dec.end()), std::string("foobar"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// deriveKeyNonce: verify the packetId XOR into key[0..1] and the deterministic
|
|
||||||
// structure. Uses a fixed 20-byte ivStruct.
|
|
||||||
TEST_CASE(derive_key_nonce)
|
|
||||||
{
|
|
||||||
auto iv = hex("000102030405060708090a0b0c0d0e0f10111213"); // 20 bytes
|
|
||||||
auto a = Crypto::deriveKeyNonce(false, 0, 0, 2, iv);
|
|
||||||
auto b = Crypto::deriveKeyNonce(false, 0x0102, 0, 2, iv);
|
|
||||||
// key[0] ^= pid>>8, key[1] ^= pid&0xff; nonce unchanged.
|
|
||||||
CHECK_EQ(a.key[0] ^ 0x01, b.key[0]);
|
|
||||||
CHECK_EQ(a.key[1] ^ 0x02, b.key[1]);
|
|
||||||
CHECK_EQ(hx(a.nonce), hx(b.nonce));
|
|
||||||
// Direction changes the derivation.
|
|
||||||
auto c = Crypto::deriveKeyNonce(true, 0, 0, 2, iv);
|
|
||||||
CHECK(hx(a.key) != hx(c.key));
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
#include "check.hpp"
|
|
||||||
#include "echoion/protocol/Crypto.hpp"
|
|
||||||
#include "echoion/protocol/Identity.hpp"
|
|
||||||
#include "echoion/protocol/Util.hpp"
|
|
||||||
|
|
||||||
#include <cstdio>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
using namespace Echoion::Protocol;
|
|
||||||
|
|
||||||
TEST_CASE(identity_generate_uid_and_level)
|
|
||||||
{
|
|
||||||
auto id = Identity::generate(8);
|
|
||||||
|
|
||||||
// uid must equal base64(sha1(ascii(publicKeyString))).
|
|
||||||
auto h = Crypto::sha1(Crypto::ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>(id.publicKeyString().data()),
|
|
||||||
id.publicKeyString().size()));
|
|
||||||
CHECK_EQ(id.uid(),
|
|
||||||
Util::base64Encode(Crypto::ByteView(h.data(), h.size())));
|
|
||||||
|
|
||||||
// publicKeyString is valid base64 of a DER SEQUENCE (starts with 0x30).
|
|
||||||
auto der = Util::base64Decode(id.publicKeyString());
|
|
||||||
CHECK(!der.empty());
|
|
||||||
CHECK_EQ(der[0], uint8_t(0x30));
|
|
||||||
|
|
||||||
// Security level actually reached the requested threshold.
|
|
||||||
CHECK(id.securityLevel() >= 8);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(identity_sign_verifiable_length)
|
|
||||||
{
|
|
||||||
auto id = Identity::generate(0);
|
|
||||||
std::string msg = "hello";
|
|
||||||
auto sig = id.sign(Crypto::ByteView(
|
|
||||||
reinterpret_cast<const uint8_t*>(msg.data()), msg.size()));
|
|
||||||
// DER ECDSA signature over P-256 is ~70-72 bytes; never empty.
|
|
||||||
CHECK(!sig.empty());
|
|
||||||
CHECK(sig[0] == 0x30); // DER SEQUENCE
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(identity_save_load_roundtrip)
|
|
||||||
{
|
|
||||||
auto id = Identity::generate(0);
|
|
||||||
std::string path = "/tmp/echoion_identity_test.txt";
|
|
||||||
id.save(path);
|
|
||||||
auto loaded = Identity::load(path);
|
|
||||||
CHECK_EQ(loaded.publicKeyString(), id.publicKeyString());
|
|
||||||
CHECK_EQ(loaded.uid(), id.uid());
|
|
||||||
CHECK_EQ(loaded.keyOffset(), id.keyOffset());
|
|
||||||
std::remove(path.c_str());
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
#include "check.hpp"
|
|
||||||
|
|
||||||
int main()
|
|
||||||
{
|
|
||||||
return echotest::run();
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
#include "check.hpp"
|
|
||||||
#include "echoion/protocol/QuickLz.hpp"
|
|
||||||
|
|
||||||
using namespace Echoion::Protocol;
|
|
||||||
|
|
||||||
// QuickLZ level-1 "stored" (uncompressed) block: header byte with level=1
|
|
||||||
// (bits 2-3 = 01 -> 0x04), compressed bit (bit0) = 0, short size form
|
|
||||||
// (bit1 = 0) -> 3-byte header: [flags, compressedSize, decompressedSize].
|
|
||||||
TEST_CASE(qlz_stored_block)
|
|
||||||
{
|
|
||||||
Bytes payload = {'h', 'e', 'l', 'l', 'o'};
|
|
||||||
Bytes buf;
|
|
||||||
buf.push_back(0x04); // flags: level 1, not compressed, short header
|
|
||||||
buf.push_back(static_cast<uint8_t>(3 + payload.size())); // compressed size
|
|
||||||
buf.push_back(static_cast<uint8_t>(payload.size())); // decompressed size
|
|
||||||
buf.insert(buf.end(), payload.begin(), payload.end());
|
|
||||||
|
|
||||||
CHECK_EQ(qlzDecompressedSize(buf), uint32_t(payload.size()));
|
|
||||||
CHECK_EQ(qlzCompressedSize(buf), uint32_t(3 + payload.size()));
|
|
||||||
|
|
||||||
auto out = qlzDecompress(buf);
|
|
||||||
CHECK_EQ(out.size(), payload.size());
|
|
||||||
CHECK(out == payload);
|
|
||||||
}
|
|
||||||
|
|
||||||
TEST_CASE(qlz_rejects_bad_level)
|
|
||||||
{
|
|
||||||
Bytes buf = {0x00, 0x03, 0x00}; // level 0 -> unsupported
|
|
||||||
bool threw = false;
|
|
||||||
try {
|
|
||||||
qlzDecompress(buf);
|
|
||||||
} catch (const std::exception&) {
|
|
||||||
threw = true;
|
|
||||||
}
|
|
||||||
CHECK(threw);
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
# EchoionStandalone — the daemon that runs Core without a TeamSpeak client.
|
|
||||||
#
|
|
||||||
# It reuses the plugin's (TeamSpeak-independent) CoreLoader/FileWatcher to load
|
|
||||||
# and hot-reload Core, but implements IPluginInterface with EchoionProtocol's
|
|
||||||
# native UDP client. Built with PLUGIN=1 so it shares the plugin's minimal-API
|
|
||||||
# ABI contract with Core (self-contained ServerConfig, no ConfigTypes).
|
|
||||||
|
|
||||||
cmake_minimum_required(VERSION 4.0.0)
|
|
||||||
project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX)
|
|
||||||
|
|
||||||
set(CMAKE_CXX_STANDARD 26)
|
|
||||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
|
||||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
|
||||||
|
|
||||||
# dylib for the Core hot-reload loader (same version the plugin uses).
|
|
||||||
CPMAddPackage(
|
|
||||||
NAME dylib
|
|
||||||
GITHUB_REPOSITORY martin-olivier/dylib
|
|
||||||
GIT_TAG "v3.0.1"
|
|
||||||
)
|
|
||||||
|
|
||||||
find_package(PkgConfig REQUIRED)
|
|
||||||
pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil)
|
|
||||||
pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus)
|
|
||||||
find_package(Threads REQUIRED)
|
|
||||||
|
|
||||||
set(PLUGIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../EchoionPlugin")
|
|
||||||
|
|
||||||
add_executable(EchoionStandalone
|
|
||||||
src/main.cpp
|
|
||||||
src/StandaloneClientInterface.cpp
|
|
||||||
src/AudioEncoder.cpp
|
|
||||||
# Reused, TeamSpeak-independent loader from the plugin (transition shim;
|
|
||||||
# a shared EchoionHostCommon lib can extract these later).
|
|
||||||
"${PLUGIN_DIR}/src/CoreLoader.cpp"
|
|
||||||
"${PLUGIN_DIR}/src/FileWatcher.cpp"
|
|
||||||
)
|
|
||||||
|
|
||||||
# PLUGIN=1 gives the self-contained ServerConfig + minimal API, matching the
|
|
||||||
# ABI Core was built against for the plugin path.
|
|
||||||
target_compile_definitions(EchoionStandalone PRIVATE PLUGIN=1)
|
|
||||||
|
|
||||||
target_include_directories(EchoionStandalone PRIVATE
|
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
|
||||||
"${PLUGIN_DIR}/include"
|
|
||||||
)
|
|
||||||
|
|
||||||
target_link_libraries(EchoionStandalone PRIVATE
|
|
||||||
Echoion::Protocol
|
|
||||||
Echoion::ApiBase
|
|
||||||
Echoion::ApiPlugin
|
|
||||||
Echoion::ApiOpaque
|
|
||||||
Echoion::ApiPluginInterface
|
|
||||||
Echoion::ApiCoreInterface
|
|
||||||
Echoion::ApiLogger
|
|
||||||
Void::Data
|
|
||||||
Void::Log
|
|
||||||
Void::Stacktrace
|
|
||||||
dylib
|
|
||||||
Threads::Threads
|
|
||||||
PkgConfig::SWRESAMPLE
|
|
||||||
PkgConfig::OPUS
|
|
||||||
)
|
|
||||||
|
|
||||||
set_target_properties(EchoionStandalone PROPERTIES
|
|
||||||
OUTPUT_NAME "echoiond"
|
|
||||||
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
|
|
||||||
)
|
|
||||||
|
|
||||||
install(TARGETS EchoionStandalone RUNTIME DESTINATION bin)
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Converts Echoion's internal PCM (192 kHz stereo S16, delivered in 20 ms
|
|
||||||
// chunks) into TeamSpeak-ready Opus frames: resample to 48 kHz stereo, then
|
|
||||||
// Opus-encode in exact 20 ms (960 samples/ch) frames. A small PCM ring absorbs
|
|
||||||
// the resampler's priming latency so every emitted frame is exactly 960/ch.
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <span>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
struct SwrContext;
|
|
||||||
struct OpusEncoder;
|
|
||||||
|
|
||||||
namespace Echoion::Standalone
|
|
||||||
{
|
|
||||||
|
|
||||||
class AudioEncoder
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
|
|
||||||
// inRate defaults to Echoion's 192 kHz internal pipeline.
|
|
||||||
explicit AudioEncoder(int bitrate = 96000, int inRate = 192000);
|
|
||||||
~AudioEncoder();
|
|
||||||
|
|
||||||
AudioEncoder(const AudioEncoder&) = delete;
|
|
||||||
AudioEncoder& operator=(const AudioEncoder&) = delete;
|
|
||||||
|
|
||||||
// Feed one chunk of interleaved stereo S16 at inRate. Returns zero or
|
|
||||||
// more complete Opus frames (each a 20 ms packet).
|
|
||||||
std::vector<std::vector<uint8_t>>
|
|
||||||
encode(std::span<const short> interleaved);
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
SwrContext* swr_ = nullptr;
|
|
||||||
OpusEncoder* enc_ = nullptr;
|
|
||||||
int inRate_ = 192000;
|
|
||||||
std::vector<short> pcm_; // resampled 48 kHz interleaved stereo
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Standalone
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
// Implements Echoion's IPluginInterface against the native TeamSpeak UDP
|
|
||||||
// protocol (EchoionProtocol) instead of the TS3 Client Plugin SDK. This is the
|
|
||||||
// single seam that lets the whole Core run as a standalone application: Core
|
|
||||||
// only ever talks to IPluginInterface, so swapping this implementation in for
|
|
||||||
// the plugin drops the TeamSpeak-client dependency entirely.
|
|
||||||
|
|
||||||
#include <PluginInterface.hpp>
|
|
||||||
|
|
||||||
#include "echoion/protocol/Identity.hpp"
|
|
||||||
#include "echoion/protocol/TsClient.hpp"
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <map>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Echoion::Standalone
|
|
||||||
{
|
|
||||||
|
|
||||||
class AudioEncoder;
|
|
||||||
|
|
||||||
// Runtime knobs the protocol client needs that ServerConfig does not carry.
|
|
||||||
// Sourced from environment / defaults by main(), so no Core changes are
|
|
||||||
// required.
|
|
||||||
struct StandaloneSettings {
|
|
||||||
std::string identityPath; // where to load/persist the TS identity
|
|
||||||
int securityLevel = 8;
|
|
||||||
int opusBitrate = 96000;
|
|
||||||
};
|
|
||||||
|
|
||||||
class StandaloneClientInterface : public Api::IPluginInterface
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
|
|
||||||
explicit StandaloneClientInterface(StandaloneSettings settings);
|
|
||||||
~StandaloneClientInterface() override;
|
|
||||||
|
|
||||||
// Lifecycle
|
|
||||||
Api::Result<void> initialize() override;
|
|
||||||
Api::Result<void> shutdown() override;
|
|
||||||
|
|
||||||
// Clients
|
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::ClientInfo>>
|
|
||||||
getClients() override;
|
|
||||||
[[nodiscard]] Api::Result<std::optional<Api::ClientInfo>>
|
|
||||||
getClient(uint64_t clientId) override;
|
|
||||||
Api::Result<void> moveClient(uint64_t clientId,
|
|
||||||
uint64_t channelId) override;
|
|
||||||
Api::Result<void> kickClient(uint64_t clientId,
|
|
||||||
const std::string& reason) override;
|
|
||||||
|
|
||||||
// Channels
|
|
||||||
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
|
|
||||||
getChannels() const override;
|
|
||||||
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
|
|
||||||
getChannel(uint64_t channelId) const override;
|
|
||||||
|
|
||||||
// Messaging
|
|
||||||
Api::Result<void>
|
|
||||||
sendTextMessage(uint64_t targetId,
|
|
||||||
const std::string& message) override;
|
|
||||||
Api::Result<void>
|
|
||||||
sendChannelMessage(uint64_t channelId,
|
|
||||||
const std::string& message) override;
|
|
||||||
Api::Result<void>
|
|
||||||
sendServerMessage(const std::string& message) override;
|
|
||||||
|
|
||||||
// Audio
|
|
||||||
Api::Result<void>
|
|
||||||
sendAudioData(const std::span<const short>& data) override;
|
|
||||||
Api::Result<void>
|
|
||||||
setWhisperList(const std::vector<uint64_t>& clientIds) override;
|
|
||||||
|
|
||||||
// Connection
|
|
||||||
Api::Result<void>
|
|
||||||
connectToServer(const Api::ServerConfig& config) override;
|
|
||||||
Api::Result<void> disconnectFromServer() override;
|
|
||||||
[[nodiscard]] bool isConnected() const override;
|
|
||||||
Api::Result<void> reconnect() override;
|
|
||||||
|
|
||||||
// Events
|
|
||||||
void
|
|
||||||
registerEventCallback(const Api::EventCallback& cb) override;
|
|
||||||
void
|
|
||||||
unregisterEventCallback(const Api::EventCallback& cb) override;
|
|
||||||
|
|
||||||
private:
|
|
||||||
|
|
||||||
void wireCallbacks();
|
|
||||||
void onCommand(const Protocol::ParsedCommand& parsed);
|
|
||||||
void onTextMessage(const Protocol::CommandParams& params);
|
|
||||||
void broadcast(const Api::PluginEvent& event);
|
|
||||||
void upsertClientGroup(const Protocol::CommandParams& p,
|
|
||||||
bool emitConnected);
|
|
||||||
|
|
||||||
StandaloneSettings settings_;
|
|
||||||
std::unique_ptr<Protocol::Identity> identity_;
|
|
||||||
std::unique_ptr<Protocol::TsClient> client_;
|
|
||||||
std::unique_ptr<AudioEncoder> encoder_;
|
|
||||||
|
|
||||||
Api::ServerConfig currentConfig_{};
|
|
||||||
std::atomic<bool> initialized_{false};
|
|
||||||
|
|
||||||
mutable std::mutex mirrorMutex_;
|
|
||||||
std::map<uint64_t, Api::ClientInfo> clients_;
|
|
||||||
std::map<uint64_t, Api::ChannelInfo> channels_;
|
|
||||||
std::vector<uint64_t> whisperList_;
|
|
||||||
|
|
||||||
std::mutex cbMutex_;
|
|
||||||
std::vector<Api::EventCallback> callbacks_;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Echoion::Standalone
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
#include "echoion/standalone/AudioEncoder.hpp"
|
|
||||||
|
|
||||||
extern "C" {
|
|
||||||
#include <libavutil/channel_layout.h>
|
|
||||||
#include <libavutil/opt.h>
|
|
||||||
#include <libavutil/samplefmt.h>
|
|
||||||
#include <libswresample/swresample.h>
|
|
||||||
#include <opus/opus.h>
|
|
||||||
}
|
|
||||||
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
namespace Echoion::Standalone
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
constexpr int OUT_RATE = 48000;
|
|
||||||
constexpr int CHANNELS = 2;
|
|
||||||
constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel
|
|
||||||
constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS;
|
|
||||||
constexpr int MAX_OPUS = 4000;
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate)
|
|
||||||
{
|
|
||||||
AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO;
|
|
||||||
if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE,
|
|
||||||
&stereo, AV_SAMPLE_FMT_S16, inRate_, 0,
|
|
||||||
nullptr) < 0 ||
|
|
||||||
swr_init(swr_) < 0) {
|
|
||||||
throw std::runtime_error("AudioEncoder: swresample init failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
int err = 0;
|
|
||||||
enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO,
|
|
||||||
&err);
|
|
||||||
if (err != OPUS_OK || !enc_) {
|
|
||||||
throw std::runtime_error("AudioEncoder: opus encoder init failed");
|
|
||||||
}
|
|
||||||
opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate));
|
|
||||||
opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC));
|
|
||||||
}
|
|
||||||
|
|
||||||
AudioEncoder::~AudioEncoder()
|
|
||||||
{
|
|
||||||
if (enc_) {
|
|
||||||
opus_encoder_destroy(enc_);
|
|
||||||
}
|
|
||||||
if (swr_) {
|
|
||||||
swr_free(&swr_);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::vector<uint8_t>>
|
|
||||||
AudioEncoder::encode(std::span<const short> interleaved)
|
|
||||||
{
|
|
||||||
std::vector<std::vector<uint8_t>> out;
|
|
||||||
|
|
||||||
const int inSamplesPerCh =
|
|
||||||
static_cast<int>(interleaved.size() / CHANNELS);
|
|
||||||
if (inSamplesPerCh <= 0) {
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upper bound on resampled samples for this chunk.
|
|
||||||
int maxOut = static_cast<int>(
|
|
||||||
av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh,
|
|
||||||
OUT_RATE, inRate_, AV_ROUND_UP));
|
|
||||||
std::vector<short> resampled(
|
|
||||||
static_cast<size_t>(maxOut) * CHANNELS, 0);
|
|
||||||
|
|
||||||
const uint8_t* inPtr =
|
|
||||||
reinterpret_cast<const uint8_t*>(interleaved.data());
|
|
||||||
uint8_t* outPtr = reinterpret_cast<uint8_t*>(resampled.data());
|
|
||||||
int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr,
|
|
||||||
inSamplesPerCh);
|
|
||||||
if (gotPerCh < 0) {
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
pcm_.insert(pcm_.end(), resampled.begin(),
|
|
||||||
resampled.begin() +
|
|
||||||
static_cast<size_t>(gotPerCh) * CHANNELS);
|
|
||||||
|
|
||||||
// Emit as many full 20 ms frames as we have buffered.
|
|
||||||
size_t consumed = 0;
|
|
||||||
while (pcm_.size() - consumed >= static_cast<size_t>(FRAME_SHORTS)) {
|
|
||||||
uint8_t packet[MAX_OPUS];
|
|
||||||
int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES,
|
|
||||||
packet, MAX_OPUS);
|
|
||||||
if (n > 0) {
|
|
||||||
out.emplace_back(packet, packet + n);
|
|
||||||
}
|
|
||||||
consumed += FRAME_SHORTS;
|
|
||||||
}
|
|
||||||
if (consumed > 0) {
|
|
||||||
pcm_.erase(pcm_.begin(),
|
|
||||||
pcm_.begin() + static_cast<std::ptrdiff_t>(consumed));
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Standalone
|
|
||||||
@@ -1,495 +0,0 @@
|
|||||||
#include "echoion/standalone/StandaloneClientInterface.hpp"
|
|
||||||
#include "echoion/standalone/AudioEncoder.hpp"
|
|
||||||
|
|
||||||
#include "echoion/protocol/Command.hpp"
|
|
||||||
|
|
||||||
#include <Void/Log/Log.hpp>
|
|
||||||
|
|
||||||
#include <chrono>
|
|
||||||
#include <filesystem>
|
|
||||||
|
|
||||||
namespace Echoion::Standalone
|
|
||||||
{
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
constexpr const char* LOG = "Standalone";
|
|
||||||
|
|
||||||
uint64_t toU64(const std::string& s)
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
return std::stoull(s);
|
|
||||||
} catch (...) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string get(const Protocol::CommandParams& p, const char* k)
|
|
||||||
{
|
|
||||||
auto it = p.find(k);
|
|
||||||
return it == p.end() ? std::string{} : it->second;
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
StandaloneClientInterface::StandaloneClientInterface(
|
|
||||||
StandaloneSettings settings)
|
|
||||||
: settings_(std::move(settings))
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
StandaloneClientInterface::~StandaloneClientInterface()
|
|
||||||
{
|
|
||||||
(void)shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> StandaloneClientInterface::initialize()
|
|
||||||
{
|
|
||||||
if (initialized_.exchange(true)) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
encoder_ = std::make_unique<AudioEncoder>(settings_.opusBitrate);
|
|
||||||
client_ = std::make_unique<Protocol::TsClient>();
|
|
||||||
Void::Log::info(LOG, "Standalone client interface initialized");
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> StandaloneClientInterface::shutdown()
|
|
||||||
{
|
|
||||||
if (!initialized_.exchange(false)) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
if (client_) {
|
|
||||||
client_->forceClose();
|
|
||||||
client_.reset();
|
|
||||||
}
|
|
||||||
encoder_.reset();
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Connection --------------------------------------------------------
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::connectToServer(const Api::ServerConfig& config)
|
|
||||||
{
|
|
||||||
if (!client_) {
|
|
||||||
return Api::fail(Api::ErrorCode::NotInitialized,
|
|
||||||
"interface not initialized");
|
|
||||||
}
|
|
||||||
currentConfig_ = config;
|
|
||||||
|
|
||||||
// Load or create the persistent identity.
|
|
||||||
try {
|
|
||||||
std::filesystem::path idPath(settings_.identityPath);
|
|
||||||
if (!idPath.empty() && std::filesystem::exists(idPath)) {
|
|
||||||
identity_ = std::make_unique<Protocol::Identity>(
|
|
||||||
Protocol::Identity::load(idPath.string()));
|
|
||||||
Void::Log::info(LOG, "Loaded identity (uid={})",
|
|
||||||
identity_->uid());
|
|
||||||
} else {
|
|
||||||
Void::Log::info(LOG,
|
|
||||||
"Generating identity (security level {})...",
|
|
||||||
settings_.securityLevel);
|
|
||||||
identity_ = std::make_unique<Protocol::Identity>(
|
|
||||||
Protocol::Identity::generate(settings_.securityLevel));
|
|
||||||
if (!idPath.empty()) {
|
|
||||||
std::filesystem::create_directories(idPath.parent_path());
|
|
||||||
identity_->save(idPath.string());
|
|
||||||
}
|
|
||||||
Void::Log::info(LOG, "Identity ready (uid={})",
|
|
||||||
identity_->uid());
|
|
||||||
}
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
return Api::fail(Api::ErrorCode::PluginError,
|
|
||||||
std::string("identity error: ") + e.what());
|
|
||||||
}
|
|
||||||
|
|
||||||
wireCallbacks();
|
|
||||||
|
|
||||||
Protocol::TsClientOptions opts;
|
|
||||||
opts.host = config.address;
|
|
||||||
opts.port = config.port ? config.port : 9987;
|
|
||||||
opts.identity = identity_.get();
|
|
||||||
opts.nickname = config.nickname.empty() ? "EchoionBot" : config.nickname;
|
|
||||||
opts.serverPassword = config.serverPassword;
|
|
||||||
opts.defaultChannel =
|
|
||||||
config.defaultChannelId.value_or(std::string{});
|
|
||||||
opts.channelPassword = config.channelPassword.value_or(std::string{});
|
|
||||||
|
|
||||||
try {
|
|
||||||
client_->connect(opts);
|
|
||||||
} catch (const std::exception& e) {
|
|
||||||
return Api::fail(Api::ErrorCode::NetworkError,
|
|
||||||
std::string("connect failed: ") + e.what());
|
|
||||||
}
|
|
||||||
Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port,
|
|
||||||
opts.nickname);
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
void StandaloneClientInterface::wireCallbacks()
|
|
||||||
{
|
|
||||||
Protocol::TsClientCallbacks cb;
|
|
||||||
cb.onConnected = [this] {
|
|
||||||
// Ask the server to reveal all clients so the presence mirror fills.
|
|
||||||
client_->sendCommand("channelsubscribeall");
|
|
||||||
Api::PluginEvent ev;
|
|
||||||
ev.type = Api::PluginEventType::ConnectionEstablished;
|
|
||||||
ev.timestamp = std::chrono::system_clock::now();
|
|
||||||
broadcast(ev);
|
|
||||||
};
|
|
||||||
cb.onDisconnected = [this] {
|
|
||||||
Void::Log::warn(LOG, "Disconnected from server");
|
|
||||||
};
|
|
||||||
cb.onError = [](const std::string& msg) {
|
|
||||||
Void::Log::error(LOG, "Protocol error: {}", msg);
|
|
||||||
};
|
|
||||||
cb.onCommand = [this](const Protocol::ParsedCommand& p) {
|
|
||||||
onCommand(p);
|
|
||||||
};
|
|
||||||
cb.onTextMessage = [this](const Protocol::CommandParams& p) {
|
|
||||||
onTextMessage(p);
|
|
||||||
};
|
|
||||||
cb.onDebug = [](const std::string& msg) {
|
|
||||||
Void::Log::debug(LOG, "{}", msg);
|
|
||||||
};
|
|
||||||
client_->setCallbacks(std::move(cb));
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> StandaloneClientInterface::disconnectFromServer()
|
|
||||||
{
|
|
||||||
if (client_) {
|
|
||||||
client_->disconnect();
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
bool StandaloneClientInterface::isConnected() const
|
|
||||||
{
|
|
||||||
return client_ &&
|
|
||||||
client_->state() == Protocol::ClientState::Connected;
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> StandaloneClientInterface::reconnect()
|
|
||||||
{
|
|
||||||
(void)disconnectFromServer();
|
|
||||||
return connectToServer(currentConfig_);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Event mirror ------------------------------------------------------
|
|
||||||
|
|
||||||
void StandaloneClientInterface::upsertClientGroup(
|
|
||||||
const Protocol::CommandParams& p, bool emitConnected)
|
|
||||||
{
|
|
||||||
uint64_t clid = toU64(get(p, "clid"));
|
|
||||||
if (clid == 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Api::ClientInfo info;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
info = clients_[clid];
|
|
||||||
info.id = clid;
|
|
||||||
if (auto n = get(p, "client_nickname"); !n.empty()) {
|
|
||||||
info.nickname = n;
|
|
||||||
}
|
|
||||||
if (auto u = get(p, "client_unique_identifier"); !u.empty()) {
|
|
||||||
info.uniqueIdentifier = u;
|
|
||||||
}
|
|
||||||
if (auto c = get(p, "ctid"); !c.empty()) {
|
|
||||||
info.channelId = toU64(c);
|
|
||||||
} else if (auto cid = get(p, "cid"); !cid.empty()) {
|
|
||||||
info.channelId = toU64(cid);
|
|
||||||
}
|
|
||||||
clients_[clid] = info;
|
|
||||||
}
|
|
||||||
if (emitConnected) {
|
|
||||||
Api::PluginEvent ev;
|
|
||||||
ev.type = Api::PluginEventType::ClientConnected;
|
|
||||||
ev.clientId = clid;
|
|
||||||
ev.clientName = info.nickname;
|
|
||||||
ev.timestamp = std::chrono::system_clock::now();
|
|
||||||
broadcast(ev);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p)
|
|
||||||
{
|
|
||||||
const auto& groups =
|
|
||||||
p.groups.empty()
|
|
||||||
? std::vector<Protocol::CommandParams>{p.params}
|
|
||||||
: p.groups;
|
|
||||||
|
|
||||||
if (p.name == "notifycliententerview") {
|
|
||||||
for (const auto& g : groups) {
|
|
||||||
upsertClientGroup(g, true);
|
|
||||||
}
|
|
||||||
} else if (p.name == "notifyclientleftview") {
|
|
||||||
for (const auto& g : groups) {
|
|
||||||
uint64_t clid = toU64(get(g, "clid"));
|
|
||||||
if (clid == 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
std::string name;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
auto it = clients_.find(clid);
|
|
||||||
if (it != clients_.end()) {
|
|
||||||
name = it->second.nickname;
|
|
||||||
clients_.erase(it);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Api::PluginEvent ev;
|
|
||||||
ev.type = Api::PluginEventType::ClientDisconnected;
|
|
||||||
ev.clientId = clid;
|
|
||||||
ev.clientName = name;
|
|
||||||
ev.timestamp = std::chrono::system_clock::now();
|
|
||||||
broadcast(ev);
|
|
||||||
}
|
|
||||||
} else if (p.name == "notifyclientmoved") {
|
|
||||||
for (const auto& g : groups) {
|
|
||||||
uint64_t clid = toU64(get(g, "clid"));
|
|
||||||
uint64_t ctid = toU64(get(g, "ctid"));
|
|
||||||
if (clid == 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
clients_[clid].id = clid;
|
|
||||||
clients_[clid].channelId = ctid;
|
|
||||||
}
|
|
||||||
Api::PluginEvent ev;
|
|
||||||
ev.type = Api::PluginEventType::ClientMoved;
|
|
||||||
ev.clientId = clid;
|
|
||||||
ev.targetChannelId = ctid;
|
|
||||||
ev.timestamp = std::chrono::system_clock::now();
|
|
||||||
broadcast(ev);
|
|
||||||
}
|
|
||||||
} else if (p.name == "channellist" || p.name == "notifychannellist") {
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
for (const auto& g : groups) {
|
|
||||||
uint64_t cid = toU64(get(g, "cid"));
|
|
||||||
if (cid == 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
Api::ChannelInfo ch = channels_[cid];
|
|
||||||
ch.id = cid;
|
|
||||||
if (auto n = get(g, "channel_name"); !n.empty()) {
|
|
||||||
ch.name = n;
|
|
||||||
}
|
|
||||||
if (auto pid = get(g, "pid"); !pid.empty()) {
|
|
||||||
ch.parentId = toU64(pid);
|
|
||||||
}
|
|
||||||
channels_[cid] = ch;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void StandaloneClientInterface::onTextMessage(
|
|
||||||
const Protocol::CommandParams& params)
|
|
||||||
{
|
|
||||||
uint64_t invoker = toU64(get(params, "invokerid"));
|
|
||||||
if (client_ && invoker == client_->clientId()) {
|
|
||||||
return; // ignore our own messages
|
|
||||||
}
|
|
||||||
Api::PluginEvent ev;
|
|
||||||
ev.type = Api::PluginEventType::TextMessageReceived;
|
|
||||||
ev.clientId = invoker;
|
|
||||||
ev.clientName = get(params, "invokername");
|
|
||||||
ev.message = get(params, "msg");
|
|
||||||
if (auto t = get(params, "target"); !t.empty()) {
|
|
||||||
ev.targetChannelId = toU64(t);
|
|
||||||
}
|
|
||||||
ev.timestamp = std::chrono::system_clock::now();
|
|
||||||
broadcast(ev);
|
|
||||||
}
|
|
||||||
|
|
||||||
void StandaloneClientInterface::broadcast(const Api::PluginEvent& event)
|
|
||||||
{
|
|
||||||
std::vector<Api::EventCallback> cbs;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(cbMutex_);
|
|
||||||
cbs = callbacks_;
|
|
||||||
}
|
|
||||||
for (const auto& cb : cbs) {
|
|
||||||
cb(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Clients / channels ------------------------------------------------
|
|
||||||
|
|
||||||
Api::Result<std::vector<Api::ClientInfo>>
|
|
||||||
StandaloneClientInterface::getClients()
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
std::vector<Api::ClientInfo> out;
|
|
||||||
out.reserve(clients_.size());
|
|
||||||
for (const auto& [id, c] : clients_) {
|
|
||||||
out.push_back(c);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<std::optional<Api::ClientInfo>>
|
|
||||||
StandaloneClientInterface::getClient(uint64_t clientId)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
auto it = clients_.find(clientId);
|
|
||||||
if (it == clients_.end()) {
|
|
||||||
return std::optional<Api::ClientInfo>{};
|
|
||||||
}
|
|
||||||
return std::optional<Api::ClientInfo>{it->second};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<std::vector<Api::ChannelInfo>>
|
|
||||||
StandaloneClientInterface::getChannels() const
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
std::vector<Api::ChannelInfo> out;
|
|
||||||
out.reserve(channels_.size());
|
|
||||||
for (const auto& [id, c] : channels_) {
|
|
||||||
out.push_back(c);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<std::optional<Api::ChannelInfo>>
|
|
||||||
StandaloneClientInterface::getChannel(uint64_t channelId) const
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
auto it = channels_.find(channelId);
|
|
||||||
if (it == channels_.end()) {
|
|
||||||
return std::optional<Api::ChannelInfo>{};
|
|
||||||
}
|
|
||||||
return std::optional<Api::ChannelInfo>{it->second};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::moveClient(uint64_t clientId, uint64_t channelId)
|
|
||||||
{
|
|
||||||
if (!client_) {
|
|
||||||
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
|
|
||||||
}
|
|
||||||
Protocol::CommandParams p;
|
|
||||||
p["clid"] = std::to_string(clientId);
|
|
||||||
p["cid"] = std::to_string(channelId);
|
|
||||||
client_->sendCommand(Protocol::buildCommand("clientmove", p));
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::kickClient(uint64_t clientId,
|
|
||||||
const std::string& reason)
|
|
||||||
{
|
|
||||||
if (!client_) {
|
|
||||||
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
|
|
||||||
}
|
|
||||||
Protocol::CommandParams p;
|
|
||||||
p["clid"] = std::to_string(clientId);
|
|
||||||
p["reasonid"] = "5"; // kick from server
|
|
||||||
p["reasonmsg"] = reason;
|
|
||||||
client_->sendCommand(Protocol::buildCommand("clientkick", p));
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Messaging ---------------------------------------------------------
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::sendTextMessage(uint64_t targetId,
|
|
||||||
const std::string& message)
|
|
||||||
{
|
|
||||||
if (!client_) {
|
|
||||||
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
|
|
||||||
}
|
|
||||||
Protocol::CommandParams p;
|
|
||||||
p["targetmode"] = "1"; // client
|
|
||||||
p["target"] = std::to_string(targetId);
|
|
||||||
p["msg"] = message;
|
|
||||||
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p));
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::sendChannelMessage(uint64_t channelId,
|
|
||||||
const std::string& message)
|
|
||||||
{
|
|
||||||
if (!client_) {
|
|
||||||
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
|
|
||||||
}
|
|
||||||
Protocol::CommandParams p;
|
|
||||||
p["targetmode"] = "2"; // channel
|
|
||||||
p["target"] = std::to_string(channelId);
|
|
||||||
p["msg"] = message;
|
|
||||||
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p));
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::sendServerMessage(const std::string& message)
|
|
||||||
{
|
|
||||||
if (!client_) {
|
|
||||||
return Api::fail(Api::ErrorCode::NotInitialized, "not connected");
|
|
||||||
}
|
|
||||||
Protocol::CommandParams p;
|
|
||||||
p["targetmode"] = "3"; // server
|
|
||||||
p["msg"] = message;
|
|
||||||
client_->sendCommand(Protocol::buildCommand("sendtextmessage", p));
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Audio -------------------------------------------------------------
|
|
||||||
|
|
||||||
Api::Result<void>
|
|
||||||
StandaloneClientInterface::sendAudioData(const std::span<const short>& data)
|
|
||||||
{
|
|
||||||
if (!client_ || !encoder_ ||
|
|
||||||
client_->state() != Protocol::ClientState::Connected) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
std::vector<uint64_t> whisper;
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
whisper = whisperList_;
|
|
||||||
}
|
|
||||||
auto frames = encoder_->encode(data);
|
|
||||||
for (const auto& f : frames) {
|
|
||||||
if (whisper.empty()) {
|
|
||||||
client_->sendVoice(f);
|
|
||||||
} else {
|
|
||||||
std::vector<uint16_t> clients;
|
|
||||||
clients.reserve(whisper.size());
|
|
||||||
for (uint64_t c : whisper) {
|
|
||||||
clients.push_back(static_cast<uint16_t>(c));
|
|
||||||
}
|
|
||||||
client_->sendWhisper(f, {}, clients);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
Api::Result<void> StandaloneClientInterface::setWhisperList(
|
|
||||||
const std::vector<uint64_t>& clientIds)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(mirrorMutex_);
|
|
||||||
whisperList_ = clientIds;
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Events ------------------------------------------------------------
|
|
||||||
|
|
||||||
void StandaloneClientInterface::registerEventCallback(
|
|
||||||
const Api::EventCallback& cb)
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(cbMutex_);
|
|
||||||
callbacks_.push_back(cb);
|
|
||||||
}
|
|
||||||
|
|
||||||
void StandaloneClientInterface::unregisterEventCallback(
|
|
||||||
const Api::EventCallback&)
|
|
||||||
{
|
|
||||||
// Callbacks are not individually comparable (std::function); the host
|
|
||||||
// registers a single Core callback for the process lifetime, so a full
|
|
||||||
// clear on unregister is sufficient and matches usage.
|
|
||||||
std::lock_guard<std::mutex> lock(cbMutex_);
|
|
||||||
callbacks_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Echoion::Standalone
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
// Standalone Echoion host.
|
|
||||||
//
|
|
||||||
// Replaces the TeamSpeak-client + plugin sandwich: loads the same hot-reloadable
|
|
||||||
// Core shared library via the (TeamSpeak-independent) CoreLoader, but backs
|
|
||||||
// IPluginInterface with a native TeamSpeak UDP protocol client instead of the
|
|
||||||
// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no
|
|
||||||
// TeamSpeak client, no Weston/RDP, no plugin directory.
|
|
||||||
|
|
||||||
#include "echoion/plugin/CoreLoader.hpp"
|
|
||||||
#include "echoion/standalone/StandaloneClientInterface.hpp"
|
|
||||||
|
|
||||||
#include <CoreInterface.hpp>
|
|
||||||
#include <Void/Log/Log.hpp>
|
|
||||||
#include <Void/Stacktrace/Stacktrace.hpp>
|
|
||||||
|
|
||||||
#include <atomic>
|
|
||||||
#include <condition_variable>
|
|
||||||
#include <csignal>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <exception>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <iostream>
|
|
||||||
#include <memory>
|
|
||||||
#include <mutex>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
std::atomic<bool> g_stop{false};
|
|
||||||
std::condition_variable g_cv;
|
|
||||||
std::mutex g_mu;
|
|
||||||
|
|
||||||
void onSignal(int)
|
|
||||||
{
|
|
||||||
g_stop = true;
|
|
||||||
g_cv.notify_all();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::filesystem::path configDir()
|
|
||||||
{
|
|
||||||
if (const char* x = std::getenv("XDG_CONFIG_HOME")) {
|
|
||||||
return std::filesystem::path(x) / "echoion";
|
|
||||||
}
|
|
||||||
if (const char* h = std::getenv("HOME")) {
|
|
||||||
return std::filesystem::path(h) / ".config" / "echoion";
|
|
||||||
}
|
|
||||||
return std::filesystem::path(".") / "echoion";
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string envOr(const char* key, const std::string& fallback)
|
|
||||||
{
|
|
||||||
const char* v = std::getenv(key);
|
|
||||||
return v ? std::string(v) : fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
int envInt(const char* key, int fallback)
|
|
||||||
{
|
|
||||||
const char* v = std::getenv(key);
|
|
||||||
if (!v) {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return std::stoi(v);
|
|
||||||
} catch (...) {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Locate the Core shared library ("Echoion.ts").
|
|
||||||
std::filesystem::path corePath()
|
|
||||||
{
|
|
||||||
if (const char* p = std::getenv("ECHOION_CORE_PATH")) {
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
for (const char* c :
|
|
||||||
{"./Echoion.ts", "./bin/Echoion.ts", "./plugins/Echoion.ts"}) {
|
|
||||||
if (std::filesystem::exists(c)) {
|
|
||||||
return c;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "./Echoion.ts";
|
|
||||||
}
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
int main(int argc, char** argv)
|
|
||||||
{
|
|
||||||
std::set_terminate([] {
|
|
||||||
const auto frames = Void::Stacktrace::capture_stacktrace();
|
|
||||||
std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n';
|
|
||||||
std::abort();
|
|
||||||
});
|
|
||||||
|
|
||||||
std::filesystem::path cfgDir = configDir();
|
|
||||||
std::filesystem::path cfgPath = cfgDir / "config.json";
|
|
||||||
// Optional CLI: --config <path>
|
|
||||||
for (int i = 1; i + 1 < argc; ++i) {
|
|
||||||
if (std::string(argv[i]) == "--config") {
|
|
||||||
cfgPath = argv[i + 1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Echoion::Standalone::StandaloneSettings settings;
|
|
||||||
settings.identityPath =
|
|
||||||
envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string());
|
|
||||||
settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8);
|
|
||||||
settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000);
|
|
||||||
|
|
||||||
auto interface = std::make_shared<Echoion::Standalone::StandaloneClientInterface>(
|
|
||||||
settings);
|
|
||||||
if (auto r = interface->initialize(); !r) {
|
|
||||||
Void::Log::error("main", "interface init failed: {}",
|
|
||||||
r.error().message);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
Echoion::Plugin::CoreLoader loader;
|
|
||||||
loader.setConfigPath(cfgPath);
|
|
||||||
|
|
||||||
auto corePathResolved = corePath();
|
|
||||||
Void::Log::info("main", "Loading Core from {}", corePathResolved.string());
|
|
||||||
if (auto r = loader.load(corePathResolved); !r) {
|
|
||||||
Void::Log::error("main", "failed to load Core: {}", r.error().message);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto core = loader.getCore();
|
|
||||||
if (!core) {
|
|
||||||
Void::Log::error("main", "Core not available after load");
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
core->setPluginInterface(interface);
|
|
||||||
interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) {
|
|
||||||
std::ignore = core->onPluginEvent(ev);
|
|
||||||
});
|
|
||||||
// Re-register the Core callback after each hot reload (new Core instance).
|
|
||||||
loader.setHotReloadCallback([&loader, interface] {
|
|
||||||
if (auto c = loader.getCore()) {
|
|
||||||
c->setPluginInterface(interface);
|
|
||||||
interface->registerEventCallback(
|
|
||||||
[c](const Echoion::Api::PluginEvent& ev) {
|
|
||||||
std::ignore = c->onPluginEvent(ev);
|
|
||||||
});
|
|
||||||
c->triggerAutoConnect();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
core->triggerAutoConnect();
|
|
||||||
loader.enableAutoReload();
|
|
||||||
|
|
||||||
std::signal(SIGINT, onSignal);
|
|
||||||
std::signal(SIGTERM, onSignal);
|
|
||||||
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
|
|
||||||
|
|
||||||
{
|
|
||||||
std::unique_lock<std::mutex> lock(g_mu);
|
|
||||||
g_cv.wait(lock, [] { return g_stop.load(); });
|
|
||||||
}
|
|
||||||
|
|
||||||
Void::Log::info("main", "Shutting down...");
|
|
||||||
loader.disableAutoReload();
|
|
||||||
(void)interface->disconnectFromServer();
|
|
||||||
(void)loader.unload();
|
|
||||||
(void)interface->shutdown();
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
node_modules/
|
|
||||||
web-dist/
|
|
||||||
*.tsbuildinfo
|
|
||||||
@@ -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>
|
|
||||||
Generated
-2320
File diff suppressed because it is too large.
Load diff
@@ -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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 |
@@ -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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
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 |
@@ -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"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -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;
|
|
||||||
})
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -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);
|
|
||||||
@@ -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} {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'
|
|
||||||
);
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user