Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
feat(omnidisc): native chat, voice and screen share
tonhowtf123fbaf70a64
diff --git a/.gitignore b/.gitignoreindex c21833da..573704d6 100644--- a/.gitignore+++ b/.gitignore@@ -259,3 +259,6 @@ vite.config.ts.timestamp-*.vite/.varredura/remake/shots/++# Sessao autonoma (scratch)+/.sessao/diff --git a/scripts/sync-locales.mjs b/scripts/sync-locales.mjsnew file mode 100644index 00000000..e13c0225--- /dev/null+++ b/scripts/sync-locales.mjs@@ -0,0 +1,42 @@+#!/usr/bin/env node+import { readFileSync, writeFileSync, readdirSync } from "node:fs";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++const dir = join(dirname(fileURLToPath(import.meta.url)), "..", "src", "lib", "i18n");+const checkOnly = process.argv.includes("--check");+const source = JSON.parse(readFileSync(join(dir, "en.json"), "utf8"));++function sync(src, dst, path, stats) {+ const out = {};+ for (const key of Object.keys(src)) {+ const full = path ? `${path}.${key}` : key;+ const s = src[key];+ const d = dst?.[key];+ if (s && typeof s === "object" && !Array.isArray(s)) {+ out[key] = sync(s, d && typeof d === "object" ? d : {}, full, stats);+ } else if (d === undefined) {+ out[key] = s;+ stats.added.push(full);+ } else {+ out[key] = d;+ }+ }+ for (const key of Object.keys(dst ?? {})) {+ if (!(key in src)) stats.removed.push(path ? `${path}.${key}` : key);+ }+ return out;+}++let dirty = false;+for (const file of readdirSync(dir).filter((f) => f.endsWith(".json") && f !== "en.json").sort()) {+ const target = JSON.parse(readFileSync(join(dir, file), "utf8"));+ const stats = { added: [], removed: [] };+ const merged = sync(source, target, "", stats);+ const changed = stats.added.length > 0 || stats.removed.length > 0;+ if (changed) dirty = true;+ console.log(`${file}: +${stats.added.length} missing (filled with English) -${stats.removed.length} stale`);+ if (stats.removed.length) console.log(` stale: ${stats.removed.slice(0, 10).join(", ")}${stats.removed.length > 10 ? ", …" : ""}`);+ if (!checkOnly && changed) writeFileSync(join(dir, file), JSON.stringify(merged, null, 2) + "\n");+}+if (checkOnly && dirty) process.exit(1);diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex c89ad522..cad1d325 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -8,6 +8,16 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common 0.1.7",+ "generic-array 0.14.7",+]+[[package]]name = "aes"version = "0.8.4"@@ -19,6 +29,20 @@ dependencies = ["cpufeatures 0.2.17",]+[[package]]+name = "aes-gcm"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"+dependencies = [+ "aead",+ "aes",+ "cipher",+ "ctr",+ "ghash",+ "subtle",+]+[[package]]name = "ahash"version = "0.8.12"@@ -61,6 +85,28 @@ version = "0.2.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"+[[package]]+name = "alsa"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"+dependencies = [+ "alsa-sys",+ "bitflags 2.11.0",+ "cfg-if",+ "libc",+]++[[package]]+name = "alsa-sys"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"+dependencies = [+ "libc",+ "pkg-config",+]+[[package]]name = "android_system_properties"version = "0.1.5"@@ -126,6 +172,12 @@ version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+[[package]]+name = "anymap3"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"+[[package]]name = "apple-bindgen"version = "0.2.0"@@ -141,6 +193,25 @@ dependencies = ["toml 0.6.0",]+[[package]]+name = "apple-cf"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7fd680cd0f3f02ee717b2014b26d18985c57b784384ba47213fcf8791e8c250"+dependencies = [+ "doom-fish-utils",+]++[[package]]+name = "apple-metal"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b1c24b280fad9eadf6f2bf560d826392020ac6258b4c88c6dd356ae7a24f4e3"+dependencies = [+ "doom-fish-utils",+ "libc",+]+[[package]]name = "apple-sdk"version = "0.4.0"@@ -202,6 +273,27 @@ dependencies = ["rustversion",]+[[package]]+name = "array-init"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading 0.8.9",+]+[[package]]name = "assert_cfg"version = "0.1.0"@@ -233,6 +325,17 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "async-channel"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"+dependencies = [+ "concurrent-queue",+ "event-listener 2.5.3",+ "futures-core",+]+[[package]]name = "async-channel"version = "2.5.0"@@ -247,12 +350,13 @@ dependencies = [[[package]]name = "async-compression"-version = "0.4.40"+version = "0.4.43"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d67d43201f4d20c78bcda740c142ca52482d81da80681533d33bf3f0596c8e2"+checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8"dependencies = ["compression-codecs","compression-core",+ "futures-io","pin-project-lite","tokio",]@@ -283,6 +387,21 @@ dependencies = ["futures-lite 1.13.0",]+[[package]]+name = "async-global-executor"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c"+dependencies = [+ "async-channel 2.5.0",+ "async-executor",+ "async-io 2.6.0",+ "async-lock 3.4.2",+ "blocking",+ "futures-lite 2.6.1",+ "once_cell",+]+[[package]]name = "async-io"version = "1.13.0"@@ -341,6 +460,18 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "async-native-tls"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9343dc5acf07e79ff82d0c37899f079db3534d99f189a1837c8e549c99405bec"+dependencies = [+ "futures-util",+ "native-tls",+ "thiserror 1.0.69",+ "url",+]+[[package]]name = "async-process"version = "1.8.1"@@ -364,7 +495,7 @@ version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"dependencies = [- "async-channel",+ "async-channel 2.5.0","async-io 2.6.0","async-lock 3.4.2","async-signal",@@ -405,6 +536,32 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "async-std"+version = "1.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b"+dependencies = [+ "async-channel 1.9.0",+ "async-global-executor",+ "async-io 2.6.0",+ "async-lock 3.4.2",+ "crossbeam-utils",+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-lite 2.6.1",+ "gloo-timers",+ "kv-log-macro",+ "log",+ "memchr",+ "once_cell",+ "pin-project-lite",+ "pin-utils",+ "slab",+ "wasm-bindgen-futures",+]+[[package]]name = "async-stream"version = "0.3.6"@@ -444,6 +601,24 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "async-tungstenite"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef0f7efedeac57d9b26170f72965ecfd31473ca52ca7a64e925b0b6f5f079886"+dependencies = [+ "async-native-tls",+ "async-std",+ "atomic-waker",+ "futures-core",+ "futures-io",+ "futures-task",+ "futures-util",+ "log",+ "pin-project-lite",+ "tungstenite 0.26.2",+]+[[package]]name = "atk"version = "0.18.2"@@ -549,6 +724,12 @@ dependencies = ["rand 0.8.5",]+[[package]]+name = "base16ct"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"+[[package]]name = "base64"version = "0.21.7"@@ -561,6 +742,12 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]name = "bincode"version = "1.3.3"@@ -612,6 +799,21 @@ dependencies = ["which 4.4.2",]+[[package]]+name = "bit-set"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"+[[package]]name = "bitflags"version = "1.3.2"@@ -681,13 +883,23 @@ version = "1.6.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"dependencies = [- "async-channel",+ "async-channel 2.5.0","async-task","futures-io","futures-lite 2.6.1","piper",]+[[package]]+name = "bmrng"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d54df9073108f1558f90ae6c5bf5ab9c917c4185f5527b280c87a993cbead0ac"+dependencies = [+ "futures-core",+ "tokio",+]+[[package]]name = "brotli"version = "8.0.2"@@ -731,6 +943,20 @@ name = "bytemuck"version = "1.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+][[package]]name = "byteorder"@@ -836,6 +1062,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2"dependencies = ["find-msvc-tools",+ "jobserver",+ "libc","shlex",]@@ -883,9 +1111,20 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"[[package]]name = "cfg_aliases"-version = "0.2.1"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "chacha20"+version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"+dependencies = [+ "cfg-if",+ "cipher",+ "cpufeatures 0.2.17",+][[package]]name = "chacha20"@@ -898,6 +1137,19 @@ dependencies = ["rand_core 0.10.0",]+[[package]]+name = "chacha20poly1305"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"+dependencies = [+ "aead",+ "chacha20 0.9.1",+ "cipher",+ "poly1305",+ "zeroize",+]+[[package]]name = "chrono"version = "0.4.43"@@ -920,6 +1172,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = ["crypto-common 0.1.7","inout",+ "zeroize",][[package]]@@ -982,6 +1235,17 @@ dependencies = ["error-code",]+[[package]]+name = "codespan-reporting"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"+dependencies = [+ "serde",+ "termcolor",+ "unicode-width",+]+[[package]]name = "colorchoice"version = "1.0.5"@@ -1018,9 +1282,9 @@ dependencies = [[[package]]name = "compression-codecs"-version = "0.4.37"+version = "0.4.38"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eb7b51a7d9c967fc26773061ba86150f19c50c0d65c887cb1fbe295fd16619b7"+checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"dependencies = ["brotli","compression-core",@@ -1030,9 +1294,9 @@ dependencies = [[[package]]name = "compression-core"-version = "0.4.31"+version = "0.4.32"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "75984efb6ed102a0d42db99afb6c1948f0380d1d91808d5529916e6c08b49d8d"+checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"[[package]]name = "concurrent-queue"@@ -1056,6 +1320,12 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "const-oid"+version = "0.9.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"+[[package]]name = "const-oid"version = "0.10.2"@@ -1182,6 +1452,61 @@ dependencies = ["libc",]+[[package]]+name = "core-models"+version = "0.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "657f625ff361906f779745d08375ae3cc9fef87a35fba5f22874cf773010daf4"+dependencies = [+ "hax-lib",+ "pastey",+ "rand 0.9.2",+]++[[package]]+name = "coreaudio-rs"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"+dependencies = [+ "bitflags 2.11.0",+ "libc",+ "objc2-audio-toolbox",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+]++[[package]]+name = "cpal"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"+dependencies = [+ "alsa",+ "block2",+ "coreaudio-rs",+ "dasp_sample",+ "jni 0.22.4",+ "js-sys",+ "libc",+ "mach2",+ "ndk",+ "ndk-context",+ "num-derive",+ "num-traits",+ "objc2",+ "objc2-audio-toolbox",+ "objc2-avf-audio",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation",+ "web-sys",+ "windows 0.62.2",+ "windows-core 0.62.2",+]+[[package]]name = "cpufeatures"version = "0.2.17"@@ -1218,6 +1543,34 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-queue"+version = "0.3.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26"+dependencies = [+ "crossbeam-utils",+]+[[package]]name = "crossbeam-utils"version = "0.8.21"@@ -1230,6 +1583,18 @@ version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"+[[package]]+name = "crypto-bigint"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"+dependencies = [+ "generic-array 0.14.7",+ "rand_core 0.6.4",+ "subtle",+ "zeroize",+]+[[package]]name = "crypto-common"version = "0.1.7"@@ -1237,6 +1602,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"dependencies = ["generic-array 0.14.7",+ "rand_core 0.6.4","typenum",]@@ -1298,6 +1664,104 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "ctr"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"+dependencies = [+ "cipher",+]++[[package]]+name = "curve25519-dalek"+version = "4.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "curve25519-dalek-derive",+ "digest 0.10.7",+ "fiat-crypto",+ "rustc_version",+ "subtle",+ "zeroize",+]++[[package]]+name = "curve25519-dalek-derive"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "cxx"+version = "1.0.199"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824894a4a85dca76d4c95c2b9098c036f5a29f627b30c12780774f6654e60974"+dependencies = [+ "cc",+ "cxx-build",+ "cxxbridge-cmd",+ "cxxbridge-flags",+ "cxxbridge-macro",+ "foldhash 0.2.0",+ "link-cplusplus",+]++[[package]]+name = "cxx-build"+version = "1.0.199"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1ae0b651ea5b0000b19513aef5a03f194d7e3486f2d9258b658da8677fe9036"+dependencies = [+ "cc",+ "codespan-reporting",+ "indexmap 2.13.0",+ "proc-macro2",+ "quote",+ "scratch",+ "syn 3.0.3",+]++[[package]]+name = "cxxbridge-cmd"+version = "1.0.199"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb05f91d3fb8435d9bab6ac5ce6ac1868be774325fb7fb2a91be39393b21388e"+dependencies = [+ "clap",+ "codespan-reporting",+ "indexmap 2.13.0",+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]++[[package]]+name = "cxxbridge-flags"+version = "1.0.199"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf293202e0e3e98495785745389e8d0755b217e66f19194a5c695c25e03282ef"++[[package]]+name = "cxxbridge-macro"+version = "1.0.199"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca001d746947c7249ed9d332a10f7a59daedbafeb0ec68c5c18a7db7a93f6ccc"+dependencies = [+ "indexmap 2.13.0",+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]+[[package]]name = "darling"version = "0.14.4"@@ -1383,12 +1847,29 @@ dependencies = ["serde",]+[[package]]+name = "dasp_sample"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"+[[package]]name = "data-encoding"version = "2.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"+[[package]]+name = "der"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"+dependencies = [+ "const-oid 0.9.6",+ "pem-rfc7468",+ "zeroize",+]+[[package]]name = "deranged"version = "0.5.8"@@ -1465,6 +1946,21 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "device-info"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2ca8e71544c1b67dcdbc2699ab258828aff985e5bc8d5f6b486d90d7df2f848"+dependencies = [+ "core-foundation 0.10.1",+ "jni 0.21.1",+ "libc",+ "thiserror 2.0.18",+ "wasm-bindgen",+ "web-sys",+ "windows-sys 0.59.0",+]+[[package]]name = "digest"version = "0.10.7"@@ -1472,6 +1968,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer 0.10.4",+ "const-oid 0.9.6","crypto-common 0.1.7","subtle",]@@ -1483,7 +1980,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"dependencies = ["block-buffer 0.12.1",- "const-oid",+ "const-oid 0.10.2","crypto-common 0.2.2",]@@ -1579,6 +2076,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading 0.8.9",+]+[[package]]name = "dlopen2"version = "0.8.2"@@ -1620,6 +2126,16 @@ dependencies = ["litrs",]+[[package]]+name = "doom-fish-utils"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c801f6c2a0db1a1909d89fc395b9dccc594de9ef599659fbde9bb3b55ef67f9f"+dependencies = [+ "crossbeam-queue",+ "futures-util",+]+[[package]]name = "downcast-rs"version = "1.2.1"@@ -1662,12 +2178,85 @@ version = "1.0.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]+name = "easyfft"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "767e39eef2ad8a3b6f1d733be3ec70364d21d437d06d4f18ea76ce08df20b75f"+dependencies = [+ "array-init",+ "generic_singleton",+ "num-complex 0.4.6",+ "realfft",+ "rustfft",+]++[[package]]+name = "ecdsa"+version = "0.16.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"+dependencies = [+ "der",+ "digest 0.10.7",+ "elliptic-curve",+ "rfc6979",+ "signature",+ "spki",+]++[[package]]+name = "ed25519"+version = "2.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"+dependencies = [+ "pkcs8",+ "signature",+]++[[package]]+name = "ed25519-dalek"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"+dependencies = [+ "curve25519-dalek",+ "ed25519",+ "rand_core 0.6.4",+ "serde",+ "sha2",+ "subtle",+ "zeroize",+]+[[package]]name = "either"version = "1.15.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"+[[package]]+name = "elliptic-curve"+version = "0.13.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"+dependencies = [+ "base16ct",+ "crypto-bigint",+ "digest 0.10.7",+ "ff",+ "generic-array 0.14.7",+ "group",+ "hkdf",+ "pem-rfc7468",+ "pkcs8",+ "rand_core 0.6.4",+ "sec1",+ "subtle",+ "zeroize",+]+[[package]]name = "embed-resource"version = "3.0.6"@@ -1863,6 +2452,22 @@ dependencies = ["simd-adler32",]+[[package]]+name = "ff"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"+dependencies = [+ "rand_core 0.6.4",+ "subtle",+]++[[package]]+name = "fiat-crypto"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"+[[package]]name = "field-offset"version = "0.3.6"@@ -1890,6 +2495,12 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+[[package]]+name = "fixedbitset"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"+[[package]]name = "fixedbitset"version = "0.5.7"@@ -1975,6 +2586,37 @@ dependencies = ["percent-encoding",]+[[package]]+name = "from_variants"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e859c8f2057687618905dbe99fc76e836e0a69738865ef90e46fc214a41bbf2"+dependencies = [+ "from_variants_impl",+]++[[package]]+name = "from_variants_impl"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55a5e644a80e6d96b2b4910fa7993301d7b7926c045b475b62202b20a36ce69e"+dependencies = [+ "darling 0.14.4",+ "proc-macro2",+ "quote",+ "syn 1.0.109",+]++[[package]]+name = "fs2"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"+dependencies = [+ "libc",+ "winapi",+]+[[package]]name = "fs4"version = "1.1.0"@@ -2248,6 +2890,17 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"dependencies = ["typenum","version_check",+ "zeroize",+]++[[package]]+name = "generic_singleton"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab6e923c8e978e57cf63e2e200ca967d1d20f0ea2662b28f6d4e11c44aa6ab16"+dependencies = [+ "anymap3",+ "parking_lot",][[package]]@@ -2312,6 +2965,16 @@ dependencies = ["wasip3",]+[[package]]+name = "ghash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"+dependencies = [+ "opaque-debug",+ "polyval",+]+[[package]]name = "gio"version = "0.18.4"@@ -2344,6 +3007,17 @@ dependencies = ["winapi",]+[[package]]+name = "gl_generator"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"+dependencies = [+ "khronos_api",+ "log",+ "xml-rs",+]+[[package]]name = "glib"version = "0.18.5"@@ -2415,6 +3089,39 @@ dependencies = ["xkeysym",]+[[package]]+name = "gloo-timers"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"+dependencies = [+ "futures-channel",+ "futures-core",+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "glow"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5"+dependencies = [+ "js-sys",+ "slotmap",+ "wasm-bindgen",+ "web-sys",+]++[[package]]+name = "glutin_wgl_sys"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e"+dependencies = [+ "gl_generator",+]+[[package]]name = "gobject-sys"version = "0.18.0"@@ -2449,6 +3156,31 @@ dependencies = ["web-time",]+[[package]]+name = "gpu-allocator"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"+dependencies = [+ "ash",+ "hashbrown 0.16.1",+ "log",+ "presser",+ "thiserror 2.0.18",+ "windows 0.62.2",+]++[[package]]+name = "group"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"+dependencies = [+ "ff",+ "rand_core 0.6.4",+ "subtle",+]+[[package]]name = "gtk"version = "0.18.2"@@ -2528,6 +3260,7 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"dependencies = ["cfg-if","crunchy",+ "num-traits","zerocopy",]@@ -2566,6 +3299,15 @@ dependencies = ["foldhash 0.2.0",]+[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "foldhash 0.2.0",+]+[[package]]name = "hashlink"version = "0.9.1"@@ -2576,13 +3318,50 @@ dependencies = [][[package]]-name = "heck"-version = "0.4.1"+name = "hax-lib"+version = "0.3.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"+checksum = "543f93241d32b3f00569201bfce9d7a93c92c6421b23c77864ac929dc947b9fc"+dependencies = [+ "hax-lib-macros",+ "num-bigint",+ "num-traits",+][[package]]-name = "heck"+name = "hax-lib-macros"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8755751e760b11021765bb04cb4a6c4e24742688d9f3aa14c2079638f537b0f"+dependencies = [+ "hax-lib-macros-types",+ "proc-macro-error2",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "hax-lib-macros-types"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f177c9ae8ea456e2f71ff3c1ea47bf4464f772a05133fcbba56cd5ba169035a2"+dependencies = [+ "proc-macro2",+ "quote",+ "serde",+ "serde_json",+ "uuid 1.21.0",+]++[[package]]+name = "heck"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"++[[package]]+name = "heck"version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"@@ -2611,6 +3390,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac",+]+[[package]]name = "hmac"version = "0.12.1"@@ -2629,6 +3417,75 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "hpke-rs"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6ad6a58eb3e0ee30be8bfc7a9770ae98adcfa1d9bc820a5847732ce84f70837"+dependencies = [+ "hpke-rs-crypto",+ "hpke-rs-libcrux",+ "hpke-rs-rust-crypto",+ "libcrux-sha3",+ "log",+ "rand_core 0.9.5",+ "serde",+ "subtle",+ "tls_codec",+ "zeroize",+]++[[package]]+name = "hpke-rs-crypto"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0a73a99d9008010d73289f41335a3f6e14fb8c04eaf60e9111b450463b1bbc7f"+dependencies = [+ "rand_core 0.9.5",+ "zeroize",+]++[[package]]+name = "hpke-rs-libcrux"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0ce6b7e54aebe540faee869c67ee253bede44ea6cb67c6e72c7847d6c59f1df"+dependencies = [+ "hpke-rs-crypto",+ "libcrux-aead",+ "libcrux-ecdh",+ "libcrux-hkdf",+ "libcrux-kem",+ "libcrux-traits",+ "rand 0.10.2",+ "rand_chacha 0.10.0",+ "rand_core 0.10.0",+ "zeroize",+]++[[package]]+name = "hpke-rs-rust-crypto"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14b28be6cba9081c7feda2651d51c2a900029798e78b4c1e093e792f4571a870"+dependencies = [+ "aes-gcm",+ "chacha20poly1305",+ "hkdf",+ "hpke-rs-crypto",+ "k256",+ "p256",+ "p384",+ "rand 0.8.5",+ "rand_chacha 0.3.1",+ "rand_core 0.10.0",+ "rand_core 0.6.4",+ "sha2",+ "subtle",+ "x25519-dalek",+ "zeroize",+]+[[package]]name = "html5ever"version = "0.29.1"@@ -2734,6 +3591,7 @@ dependencies = ["hyper","hyper-util","rustls",+ "rustls-native-certs","rustls-pki-types","tokio","tokio-rustls",@@ -2940,6 +3798,8 @@ dependencies = ["num-traits","png 0.18.1","tiff",+ "zune-core 0.5.3",+ "zune-jpeg 0.5.15",][[package]]@@ -3067,6 +3927,24 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"+[[package]]+name = "itertools"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"+dependencies = [+ "either",+]++[[package]]+name = "itertools"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"+dependencies = [+ "either",+]+[[package]]name = "itertools"version = "0.14.0"@@ -3114,26 +3992,86 @@ dependencies = ["cesu8","cfg-if","combine",- "jni-sys",+ "jni-sys 0.3.0","log","thiserror 1.0.69","walkdir","windows-sys 0.45.0",]+[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys 0.4.1",+ "log",+ "simd_cesu8",+ "thiserror 2.0.18",+ "walkdir",+ "windows-link 0.2.1",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn 2.0.117",+]+[[package]]name = "jni-sys"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"+[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.1",+ "libc",+]+[[package]]name = "js-sys"-version = "0.3.88"+version = "0.3.104"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c7e709f3e3d22866f9c25b3aff01af289b18422cc8b4262fb19103ee80fe513d"+checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"dependencies = [- "once_cell",+ "cfg-if",+ "futures-util","wasm-bindgen",]@@ -3159,6 +4097,31 @@ dependencies = ["serde_json",]+[[package]]+name = "jsonwebtoken"+version = "10.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc"+dependencies = [+ "base64 0.22.1",+ "getrandom 0.2.17",+ "js-sys",+ "serde",+ "serde_json",+ "signature",+ "zeroize",+]++[[package]]+name = "k256"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b"+dependencies = [+ "cfg-if",+ "elliptic-curve",+]+[[package]]name = "keepawake"version = "0.5.1"@@ -3185,6 +4148,37 @@ dependencies = ["unicode-segmentation",]+[[package]]+name = "keyring"+version = "3.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c"+dependencies = [+ "byteorder",+ "log",+ "security-framework 2.11.1",+ "security-framework 3.7.0",+ "windows-sys 0.60.2",+ "zeroize",+]++[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "libloading 0.8.9",+ "pkg-config",+]++[[package]]+name = "khronos_api"+version = "3.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"+[[package]]name = "kuchikiki"version = "0.8.8-speedreader"@@ -3197,6 +4191,15 @@ dependencies = ["selectors",]+[[package]]+name = "kv-log-macro"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f"+dependencies = [+ "log",+]+[[package]]name = "lazy_static"version = "1.5.0"@@ -3252,104 +4255,326 @@ dependencies = [[[package]]name = "libc"-version = "0.2.182"+version = "0.2.189"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"[[package]]-name = "libloading"-version = "0.7.4"+name = "libcrux-aead"+version = "0.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"+checksum = "13297ce29869a5c0edab0378837b0fc5f88bf99a843712d9201c3b1150b3b476"dependencies = [- "cfg-if",- "winapi",+ "libcrux-aesgcm",+ "libcrux-chacha20poly1305",+ "libcrux-secrets",+ "libcrux-traits",][[package]]-name = "libloading"-version = "0.8.9"+name = "libcrux-aesgcm"+version = "0.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+checksum = "99f2a019dab4097585a7d4f5b9deebe46cd1e628b16a5bc4cb0ce35e1da334e6"dependencies = [- "cfg-if",- "windows-link 0.2.1",+ "libcrux-intrinsics",+ "libcrux-platform",+ "libcrux-secrets",+ "libcrux-traits",][[package]]-name = "libredox"-version = "0.1.12"+name = "libcrux-chacha20poly1305"+version = "0.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616"+checksum = "cc08d044676af21343b32b988411fa98dbb5cf65a03c9df478ced221bbdfdb1b"dependencies = [- "bitflags 2.11.0",- "libc",- "redox_syscall 0.7.1",+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-poly1305",+ "libcrux-secrets",+ "libcrux-traits",][[package]]-name = "librqbit"-version = "8.1.1"+name = "libcrux-curve25519"+version = "0.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dadca8f521242010a4c846ef5f224c217009c92e272709cdc08ba9cdabe62983"+checksum = "bb1e5fd8476a6ed609d24ef42aee5ab6f99f7c65d054f92412da9f499e423299"dependencies = [- "anyhow",- "arc-swap",- "async-compression",- "async-stream",- "async-trait",- "backoff",- "base64 0.22.1",- "bincode 2.0.1",- "bitvec",- "byteorder",- "bytes",- "dashmap",- "futures",- "governor",- "hex 0.4.3",- "http",- "intervaltree",- "itertools",- "librqbit-bencode",- "librqbit-buffers",- "librqbit-clone-to-owned",- "librqbit-core",- "librqbit-dht",- "librqbit-peer-protocol",- "librqbit-sha1-wrapper",- "librqbit-tracker-comms",- "librqbit-upnp",- "memmap2",- "mime_guess",- "parking_lot",- "rand 0.9.2",- "regex",- "reqwest 0.12.28",- "rlimit",- "serde",- "serde_json",- "serde_urlencoded",- "serde_with",- "size_format",- "tokio",- "tokio-socks",- "tokio-stream",- "tokio-util",- "tracing",- "url",- "urlencoding",- "uuid 1.21.0",- "walkdir",+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-secrets",+ "libcrux-traits",][[package]]-name = "librqbit-bencode"-version = "3.1.0"+name = "libcrux-ecdh"+version = "0.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "606dff526ba81e3eca33e2bb28b53afa2bc0b2c41d252333fa44e6c11abb37da"+checksum = "b65f73ce79337c762eb38bbac91e4c9b9e60cf318e8501b812750c640814d45e"dependencies = [- "anyhow",+ "libcrux-curve25519",+ "libcrux-p256",+ "rand 0.9.2",+]++[[package]]+name = "libcrux-hacl-rs"+version = "0.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2637dc87d158e1f1b550fd9b226443e84153fded4de69028d897b534d16d22e6"+dependencies = [+ "libcrux-macros",+]++[[package]]+name = "libcrux-hkdf"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c1a89ca0c89be3a268a921e47105fb7873badf7267f5e3ebf4ea46baedd73ef"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-hmac",+ "libcrux-secrets",+]++[[package]]+name = "libcrux-hmac"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7a242707d65960770bd7e14e4f18a92bdf0b967777dd404887db8d087a643b"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-sha2",+]++[[package]]+name = "libcrux-intrinsics"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1b5db005ff8001e026b73a6842ee81bbef8ec5ff0e1915a67ae65fd2a9fafa5"+dependencies = [+ "core-models",+ "hax-lib",+]++[[package]]+name = "libcrux-kem"+version = "0.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12631592f491d22fd1a176d32b2c6edfb673998fd3987e9d95f8fa79ad2a737b"+dependencies = [+ "libcrux-curve25519",+ "libcrux-ecdh",+ "libcrux-ml-kem",+ "libcrux-p256",+ "libcrux-sha3",+ "libcrux-traits",+ "rand 0.9.2",+]++[[package]]+name = "libcrux-macros"+version = "0.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ffd6aa2dcd5be681662001b81d493f1569c6d49a32361f470b0c955465cd0338"+dependencies = [+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "libcrux-ml-kem"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a14ab3e477de9df6ee1273a114018ff62c4996ca9220070c4e5cb1743f94a67d"+dependencies = [+ "hax-lib",+ "libcrux-intrinsics",+ "libcrux-platform",+ "libcrux-secrets",+ "libcrux-sha3",+ "libcrux-traits",+ "rand 0.9.2",+ "tls_codec",+]++[[package]]+name = "libcrux-p256"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4778ba25cb08bb8a96bd100e19ed9aecf78337198fd176036e21042b2dd99bc"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-secrets",+ "libcrux-sha2",+ "libcrux-traits",+]++[[package]]+name = "libcrux-platform"+version = "0.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d9e21d7ed31a92ac539bd69a8c970b183ee883872d2d19ce27036e24cb8ecc4"+dependencies = [+ "libc",+]++[[package]]+name = "libcrux-poly1305"+version = "0.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02491808ee5b9db8cb65fad64ae0be812db64beef179d945c00c7787dc7dfcf9"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+]++[[package]]+name = "libcrux-secrets"+version = "0.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ce650f3041b44ba40d4263852347d007cd2cd9d1cc856a6f6c8b2e10c3fd40b"+dependencies = [+ "hax-lib",+]++[[package]]+name = "libcrux-sha2"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9d253473f259fc74a280c43f29c464f7e374abdf28b4942234dc707f529d4b7"+dependencies = [+ "libcrux-hacl-rs",+ "libcrux-macros",+ "libcrux-traits",+]++[[package]]+name = "libcrux-sha3"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1ae0b7d0e1cc4793a609fd0ff2ca3b3a3fabae523770c619a3d4bc86417b0d7"+dependencies = [+ "hax-lib",+ "libcrux-intrinsics",+ "libcrux-platform",+ "libcrux-traits",+]++[[package]]+name = "libcrux-traits"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812e4fa89f3f5e34b47f928b22b1b78395a0d4ec23b1f583db635f128159d65f"+dependencies = [+ "libcrux-secrets",+ "rand 0.9.2",+]++[[package]]+name = "libloading"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"+dependencies = [+ "cfg-if",+ "winapi",+]++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link 0.2.1",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "libredox"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616"+dependencies = [+ "bitflags 2.11.0",+ "libc",+ "redox_syscall 0.7.1",+]++[[package]]+name = "librqbit"+version = "8.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dadca8f521242010a4c846ef5f224c217009c92e272709cdc08ba9cdabe62983"+dependencies = [+ "anyhow",+ "arc-swap",+ "async-compression",+ "async-stream",+ "async-trait",+ "backoff",+ "base64 0.22.1",+ "bincode 2.0.1",+ "bitvec",+ "byteorder",+ "bytes",+ "dashmap",+ "futures",+ "governor",+ "hex 0.4.3",+ "http",+ "intervaltree",+ "itertools 0.14.0",+ "librqbit-bencode",+ "librqbit-buffers",+ "librqbit-clone-to-owned",+ "librqbit-core",+ "librqbit-dht",+ "librqbit-peer-protocol",+ "librqbit-sha1-wrapper",+ "librqbit-tracker-comms",+ "librqbit-upnp",+ "memmap2",+ "mime_guess",+ "parking_lot",+ "rand 0.9.2",+ "regex",+ "reqwest 0.12.28",+ "rlimit",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "serde_with",+ "size_format",+ "tokio",+ "tokio-socks",+ "tokio-stream",+ "tokio-util",+ "tracing",+ "url",+ "urlencoding",+ "uuid 1.21.0",+ "walkdir",+]++[[package]]+name = "librqbit-bencode"+version = "3.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "606dff526ba81e3eca33e2bb28b53afa2bc0b2c41d252333fa44e6c11abb37da"+dependencies = [+ "anyhow","bytes","librqbit-buffers","librqbit-clone-to-owned",@@ -3389,7 +4614,7 @@ dependencies = ["data-encoding","directories","hex 0.4.3",- "itertools",+ "itertools 0.14.0","librqbit-bencode","librqbit-buffers","librqbit-clone-to-owned",@@ -3442,7 +4667,7 @@ dependencies = ["bitvec","byteorder","bytes",- "itertools",+ "itertools 0.14.0","librqbit-bencode","librqbit-buffers","librqbit-clone-to-owned",@@ -3514,6 +4739,39 @@ dependencies = ["vcpkg",]+[[package]]+name = "libwebrtc"+version = "0.3.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e222d9f53f1fc61dd2656c4835657d987bd387019e8f6026329c918178044eff"+dependencies = [+ "cxx",+ "jni 0.21.1",+ "js-sys",+ "lazy_static",+ "livekit-runtime",+ "log",+ "parking_lot",+ "rtrb 0.3.5",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "webrtc-sys",+]++[[package]]+name = "link-cplusplus"+version = "1.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"+dependencies = [+ "cc",+]+[[package]]name = "linux-raw-sys"version = "0.3.8"@@ -3533,16 +4791,177 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"[[package]]-name = "litemap"-version = "0.8.1"+name = "litemap"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"++[[package]]+name = "litrs"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"++[[package]]+name = "livekit"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c9a22daebb6058be54653f1f6a02eae6a353f9986f73b4c68dc11365134d198"+dependencies = [+ "base64 0.22.1",+ "bmrng",+ "bytes",+ "chrono",+ "flate2",+ "futures-util",+ "lazy_static",+ "libloading 0.8.9",+ "libwebrtc",+ "livekit-api",+ "livekit-common",+ "livekit-data-stream",+ "livekit-datatrack",+ "livekit-protocol",+ "livekit-runtime",+ "log",+ "parking_lot",+ "prost",+ "semver",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+ "tokio",+ "tokio-stream",+]++[[package]]+name = "livekit-api"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4ed580af1187bd8fad22a981fde55cad03d4f9468d9eb9c6ecce6c753371aae"+dependencies = [+ "base64 0.21.7",+ "bytes",+ "device-info",+ "flate2",+ "hmac",+ "http",+ "jsonwebtoken",+ "livekit-common",+ "livekit-net",+ "livekit-protocol",+ "livekit-runtime",+ "log",+ "os_info",+ "parking_lot",+ "pbjson-types",+ "prost",+ "rand 0.9.2",+ "reqwest 0.12.28",+ "scopeguard",+ "serde",+ "serde_json",+ "sha2",+ "signature",+ "thiserror 2.0.18",+ "tokio",+ "url",+]++[[package]]+name = "livekit-common"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f903bfee33454f21c553dbf14d6f4ffbf062157b23b04fde9821cbb94ff01169"+dependencies = [+ "livekit-protocol",+]++[[package]]+name = "livekit-data-stream"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2dfdf91af5f2dade508e2f81c7f63c79f77461f3d15cabe6b7059fe5f2839d58"+dependencies = [+ "async-compression",+ "bmrng",+ "bytes",+ "chrono",+ "from_variants",+ "futures-util",+ "livekit-common",+ "livekit-protocol",+ "log",+ "parking_lot",+ "prost",+ "thiserror 2.0.18",+ "tokio",+ "tokio-stream",+ "uuid 1.21.0",+]++[[package]]+name = "livekit-datatrack"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "376a22d6dae592bff4068a551343461b8e683ffe70aab92e037fb91cb9237ad2"+dependencies = [+ "anyhow",+ "bytes",+ "from_variants",+ "futures-core",+ "futures-util",+ "indexmap 2.13.0",+ "livekit-protocol",+ "livekit-runtime",+ "log",+ "rand 0.9.2",+ "thiserror 2.0.18",+ "tokio",+ "tokio-stream",+]++[[package]]+name = "livekit-net"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46155c42ad7acccca96a0d8be2bd0f379565f93e85144fb3aa6fa406371fee22"+dependencies = [+ "async-trait",+ "async-tungstenite",+ "base64 0.21.7",+ "bytes",+ "futures-util",+ "http",+ "livekit-runtime",+ "log",+ "reqwest 0.12.28",+ "tokio",+ "tokio-tungstenite 0.29.0",+ "url",+]++[[package]]+name = "livekit-protocol"+version = "0.7.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"+checksum = "526f22bddf409e5f15449d55cf341647d7c16a1f43df9db9b05be106e4208e1c"+dependencies = [+ "pbjson",+ "pbjson-types",+ "prost",+ "serde",+][[package]]-name = "litrs"-version = "1.0.0"+name = "livekit-runtime"+version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"+checksum = "532e84c6cdc5fe774f2b5d9912597b5f3bea561927a48296d03e24549d21c3f6"+dependencies = [+ "tokio",+ "tokio-stream",+][[package]]name = "lock_api"@@ -3558,6 +4977,9 @@ name = "log"version = "0.4.29"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"+dependencies = [+ "value-bag",+][[package]]name = "lru-slab"@@ -3604,6 +5026,12 @@ dependencies = ["time",]+[[package]]+name = "mach2"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"+[[package]]name = "malloc_buf"version = "0.0.6"@@ -3782,12 +5210,56 @@ dependencies = ["windows-sys 0.60.2",]+[[package]]+name = "multimap"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"+[[package]]name = "murmur3"version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9252111cf132ba0929b6f8e030cac2a24b507f3a4d6db6fb2896f27b354c714b"+[[package]]+name = "naga"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags 2.11.0",+ "cfg-if",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.17.1",+ "indexmap 2.13.0",+ "libm",+ "log",+ "naga-types",+ "num-traits",+ "once_cell",+ "rustc-hash 1.1.0",+ "spirv",+ "thiserror 2.0.18",+ "unicode-ident",+]++[[package]]+name = "naga-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"+dependencies = [+ "hashbrown 0.17.1",+ "indexmap 2.13.0",+ "rustc-hash 1.1.0",+ "thiserror 2.0.18",+]+[[package]]name = "native-tls"version = "0.2.18"@@ -3800,7 +5272,7 @@ dependencies = ["openssl-probe","openssl-sys","schannel",- "security-framework",+ "security-framework 3.7.0","security-framework-sys","tempfile",]@@ -3812,7 +5284,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"dependencies = ["bitflags 2.11.0",- "jni-sys",+ "jni-sys 0.3.0","log","ndk-sys","num_enum",@@ -3832,7 +5304,7 @@ version = "0.6.0+11769913"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"dependencies = [- "jni-sys",+ "jni-sys 0.3.0",][[package]]@@ -3865,6 +5337,28 @@ dependencies = ["memoffset 0.7.1",]+[[package]]+name = "nix"+version = "0.31.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"+dependencies = [+ "bitflags 2.11.0",+ "cfg-if",+ "cfg_aliases",+ "libc",+]++[[package]]+name = "nnnoiseless"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "805d5964d1e7a0006a7fdced7dae75084d66d18b35f1dfe81bd76929b1f8da0c"+dependencies = [+ "easyfft",+ "once_cell",+]+[[package]]name = "nodrop"version = "0.1.14"@@ -3934,13 +5428,23 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36"dependencies = [- "num-complex",+ "num-complex 0.2.4","num-integer","num-iter","num-rational","num-traits",]+[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]+[[package]]name = "num-complex"version = "0.2.4"@@ -3951,12 +5455,33 @@ dependencies = ["num-traits",]+[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+ "serde",+]+[[package]]name = "num-conv"version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"+[[package]]+name = "num-derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "num-integer"version = "0.1.46"@@ -3995,6 +5520,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = ["autocfg",+ "libm",][[package]]@@ -4065,6 +5591,32 @@ dependencies = ["objc2-quartz-core",]+[[package]]+name = "objc2-audio-toolbox"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"+dependencies = [+ "bitflags 2.11.0",+ "libc",+ "objc2",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-avf-audio"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"+dependencies = [+ "bitflags 2.11.0",+ "objc2",+ "objc2-foundation",+]+[[package]]name = "objc2-cloud-kit"version = "0.3.2"@@ -4076,6 +5628,29 @@ dependencies = ["objc2-foundation",]+[[package]]+name = "objc2-core-audio"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"+dependencies = [+ "dispatch2",+ "objc2",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-audio-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"+dependencies = [+ "bitflags 2.11.0",+ "objc2",+]+[[package]]name = "objc2-core-data"version = "0.3.2"@@ -4094,7 +5669,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = ["bitflags 2.11.0",+ "block2","dispatch2",+ "libc","objc2",]@@ -4121,6 +5698,32 @@ dependencies = ["objc2-foundation",]+[[package]]+name = "objc2-core-location"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-media"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d"+dependencies = [+ "bitflags 2.11.0",+ "block2",+ "dispatch2",+ "objc2",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-core-video",+]+[[package]]name = "objc2-core-text"version = "0.3.2"@@ -4140,10 +5743,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"dependencies = ["bitflags 2.11.0",+ "block2","objc2","objc2-core-foundation","objc2-core-graphics","objc2-io-surface",+ "objc2-metal",][[package]]@@ -4195,6 +5800,18 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags 2.11.0",+ "block2",+ "objc2",+ "objc2-foundation",+]+[[package]]name = "objc2-osa-kit"version = "0.3.2"@@ -4214,9 +5831,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"dependencies = ["bitflags 2.11.0",+ "block2",+ "libc","objc2","objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-video","objc2-foundation",+ "objc2-metal",][[package]]@@ -4231,31 +5853,133 @@ dependencies = [][[package]]-name = "objc2-ui-kit"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+name = "objc2-ui-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"+dependencies = [+ "bitflags 2.11.0",+ "block2",+ "objc2",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-location",+ "objc2-core-text",+ "objc2-foundation",+ "objc2-quartz-core",+ "objc2-user-notifications",+]++[[package]]+name = "objc2-user-notifications"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-video-toolbox"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05bf9a3c14831a7d9641b0d81d87dd913ee238a012b2fde27db5a84b56f5df3e"+dependencies = [+ "bitflags 2.11.0",+ "block2",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-media",+ "objc2-core-video",+ "objc2-foundation",+ "objc2-metal",+]++[[package]]+name = "objc2-web-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"+dependencies = [+ "bitflags 2.11.0",+ "block2",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-javascript-core",+ "objc2-security",+]++[[package]]+name = "omnidisc-media"+version = "0.1.0"+dependencies = [+ "async-trait",+ "base64 0.22.1",+ "cpal",+ "futures",+ "futures-util",+ "image",+ "livekit",+ "nnnoiseless",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-core-media",+ "objc2-core-video",+ "objc2-foundation",+ "objc2-quartz-core",+ "objc2-video-toolbox",+ "omnidisc-proto",+ "pollster",+ "raw-window-handle",+ "reqwest 0.12.28",+ "rtrb 0.4.0",+ "screencapturekit",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+ "tokio",+ "tokio-tungstenite 0.30.0",+ "tracing",+ "wgpu",+]++[[package]]+name = "omnidisc-mls"+version = "0.1.0"dependencies = [- "bitflags 2.11.0",- "objc2",- "objc2-core-foundation",- "objc2-foundation",+ "chacha20poly1305",+ "data-encoding",+ "ed25519-dalek",+ "hkdf",+ "openmls",+ "openmls_basic_credential",+ "openmls_memory_storage",+ "openmls_rust_crypto",+ "openmls_traits",+ "rand 0.10.2",+ "serde",+ "serde_json",+ "sha2",+ "thiserror 1.0.69",+ "tls_codec",][[package]]-name = "objc2-web-kit"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"+name = "omnidisc-proto"+version = "0.1.0"dependencies = [- "bitflags 2.11.0",- "block2",- "objc2",- "objc2-app-kit",- "objc2-core-foundation",- "objc2-foundation",- "objc2-javascript-core",- "objc2-security",+ "serde",+ "serde_json",+ "serde_repr",+ "thiserror 1.0.69",][[package]]@@ -4279,6 +6003,7 @@ dependencies = ["hex 0.4.3","hmac","keepawake",+ "keyring","libloading 0.8.9","librqbit","m3u8-rs",@@ -4288,6 +6013,9 @@ dependencies = ["objc2","objc2-foundation","objc2-web-kit",+ "omnidisc-media",+ "omnidisc-mls",+ "omnidisc-proto","omniget-core","omniget-plugin-sdk","once_cell",@@ -4319,7 +6047,7 @@ dependencies = ["tauri-plugin-updater","thiserror 1.0.69","tokio",- "tokio-tungstenite",+ "tokio-tungstenite 0.30.0","tokio-util","tower-http","tracing",@@ -4416,6 +6144,12 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "opaque-debug"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"+[[package]]name = "open"version = "5.3.3"@@ -4428,6 +6162,84 @@ dependencies = ["pathdiff",]+[[package]]+name = "openmls"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dcb512bfe6a55777518853ea535c6241f069cb0e8984678c117151d2a1e7e903"+dependencies = [+ "log",+ "openmls_traits",+ "rayon",+ "serde",+ "serde_bytes",+ "thiserror 2.0.18",+ "tls_codec",+ "zeroize",+]++[[package]]+name = "openmls_basic_credential"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "983e8be1457dd6f316f409292cec334af3b57b49a19deadc925c83c3c35e15b6"+dependencies = [+ "ed25519-dalek",+ "openmls_traits",+ "p256",+ "rand 0.8.5",+ "serde",+ "tls_codec",+]++[[package]]+name = "openmls_memory_storage"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a52c927ddb9940acb96d51aebd54b8b9c601c7119e6609622fb3f2cbe16abe3"+dependencies = [+ "log",+ "openmls_traits",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+]++[[package]]+name = "openmls_rust_crypto"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fafcc8a3552b10fbb3ab757cccaf1a34081e826ca819f49aa7e6645b1d95c00f"+dependencies = [+ "aes-gcm",+ "chacha20poly1305",+ "ed25519-dalek",+ "hkdf",+ "hmac",+ "hpke-rs",+ "hpke-rs-crypto",+ "hpke-rs-rust-crypto",+ "openmls_memory_storage",+ "openmls_traits",+ "p256",+ "rand 0.8.5",+ "rand_chacha 0.3.1",+ "serde",+ "sha2",+ "thiserror 2.0.18",+ "tls_codec",+]++[[package]]+name = "openmls_traits"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f88ccdd53448dfdbfa5b8da8ba4e527c418fdb966418172bace2e3b41eedd56"+dependencies = [+ "serde",+ "tls_codec",+]+[[package]]name = "openssl"version = "0.10.75"@@ -4478,6 +6290,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "ordered-float"+version = "5.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0"+dependencies = [+ "num-traits",+]+[[package]]name = "ordered-multimap"version = "0.7.3"@@ -4498,6 +6319,22 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "os_info"+version = "3.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"+dependencies = [+ "android_system_properties",+ "log",+ "nix 0.31.3",+ "objc2",+ "objc2-foundation",+ "objc2-ui-kit",+ "serde",+ "windows-sys 0.61.2",+]+[[package]]name = "os_pipe"version = "1.2.3"@@ -4522,6 +6359,28 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "p256"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"+dependencies = [+ "ecdsa",+ "elliptic-curve",+ "primeorder",+ "sha2",+]++[[package]]+name = "p384"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"+dependencies = [+ "elliptic-curve",+ "primeorder",+]+[[package]]name = "pango"version = "0.18.3"@@ -4576,31 +6435,93 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+[[package]]name = "pathdiff"version = "0.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"+[[package]]+name = "pbjson"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1030c719b0ec2a2d25a5df729d6cff1acf3cc230bf766f4f97833591f7577b90"+dependencies = [+ "base64 0.21.7",+ "serde",+]++[[package]]+name = "pbjson-build"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2580e33f2292d34be285c5bc3dba5259542b083cfad6037b6d70345f24dcb735"+dependencies = [+ "heck 0.4.1",+ "itertools 0.11.0",+ "prost",+ "prost-types",+]++[[package]]+name = "pbjson-types"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18f596653ba4ac51bdecbb4ef6773bc7f56042dc13927910de1684ad3d32aa12"+dependencies = [+ "bytes",+ "chrono",+ "pbjson",+ "pbjson-build",+ "prost",+ "prost-build",+ "serde",+]+[[package]]name = "peeking_take_while"version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"+[[package]]+name = "pem-rfc7468"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"+dependencies = [+ "base64ct",+]+[[package]]name = "percent-encoding"version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "petgraph"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"+dependencies = [+ "fixedbitset 0.4.2",+ "indexmap 2.13.0",+]+[[package]]name = "petgraph"version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"dependencies = [- "fixedbitset",+ "fixedbitset 0.5.7","hashbrown 0.15.5","indexmap 2.13.0",]@@ -4762,6 +6683,16 @@ dependencies = ["futures-io",]+[[package]]+name = "pkcs8"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"+dependencies = [+ "der",+ "spki",+]+[[package]]name = "pkg-config"version = "0.3.32"@@ -4837,12 +6768,50 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"++[[package]]+name = "poly1305"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"+dependencies = [+ "cpufeatures 0.2.17",+ "opaque-debug",+ "universal-hash",+]++[[package]]+name = "polyval"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "opaque-debug",+ "universal-hash",+]+[[package]]name = "portable-atomic"version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"+[[package]]+name = "portable-atomic-util"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"+dependencies = [+ "portable-atomic",+]+[[package]]name = "potential_utf"version = "0.1.4"@@ -4873,6 +6842,12 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"+[[package]]+name = "presser"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"+[[package]]name = "prettyplease"version = "0.2.37"@@ -4883,6 +6858,24 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "primal-check"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"+dependencies = [+ "num-integer",+]++[[package]]+name = "primeorder"+version = "0.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"+dependencies = [+ "elliptic-curve",+]+[[package]]name = "proc-macro-crate"version = "1.3.1"@@ -4926,29 +6919,110 @@ dependencies = [][[package]]-name = "proc-macro-error-attr"-version = "1.0.4"+name = "proc-macro-error-attr"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"+dependencies = [+ "proc-macro2",+ "quote",+ "version_check",+]++[[package]]+name = "proc-macro-error-attr2"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"+dependencies = [+ "proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro-error2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"+dependencies = [+ "proc-macro-error-attr2",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "proc-macro-hack"+version = "0.5.20+deprecated"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "profiling"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"++[[package]]+name = "prost"+version = "0.12.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29"+dependencies = [+ "bytes",+ "prost-derive",+]++[[package]]+name = "prost-build"+version = "0.12.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"+checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"dependencies = [- "proc-macro2",- "quote",- "version_check",+ "bytes",+ "heck 0.5.0",+ "itertools 0.12.1",+ "log",+ "multimap",+ "once_cell",+ "petgraph 0.6.5",+ "prettyplease",+ "prost",+ "prost-types",+ "regex",+ "syn 2.0.117",+ "tempfile",][[package]]-name = "proc-macro-hack"-version = "0.5.20+deprecated"+name = "prost-derive"+version = "0.12.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"+checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"+dependencies = [+ "anyhow",+ "itertools 0.12.1",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+][[package]]-name = "proc-macro2"-version = "1.0.106"+name = "prost-types"+version = "0.12.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0"dependencies = [- "unicode-ident",+ "prost",][[package]]@@ -5139,7 +7213,7 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"dependencies = [- "chacha20",+ "chacha20 0.10.0","getrandom 0.4.1","rand_core 0.10.0",]@@ -5174,6 +7248,16 @@ dependencies = ["rand_core 0.9.5",]+[[package]]+name = "rand_chacha"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e6af7f3e25ded52c41df4e0b1af2d047e45896c2f3281792ed68a1c243daedb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.10.0",+]+[[package]]name = "rand_core"version = "0.5.1"@@ -5225,6 +7309,12 @@ dependencies = ["rand_core 0.5.1",]+[[package]]+name = "range-alloc"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"+[[package]]name = "raw-cpuid"version = "11.6.0"@@ -5240,6 +7330,47 @@ version = "0.6.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"+[[package]]+name = "raw-window-metal"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"+dependencies = [+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "realfft"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677"+dependencies = [+ "rustfft",+]+[[package]]name = "redox_syscall"version = "0.5.18"@@ -5329,6 +7460,12 @@ version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"+[[package]]+name = "renderdoc-sys"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"+[[package]]name = "reqwest"version = "0.12.28"@@ -5339,6 +7476,7 @@ dependencies = ["bytes","cookie","cookie_store",+ "futures-channel","futures-core","futures-util","h2",@@ -5357,6 +7495,7 @@ dependencies = ["pin-project-lite","quinn","rustls",+ "rustls-native-certs","rustls-pki-types","serde","serde_json",@@ -5416,6 +7555,16 @@ dependencies = ["web-sys",]+[[package]]+name = "rfc6979"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"+dependencies = [+ "hmac",+ "subtle",+]+[[package]]name = "rfd"version = "0.16.0"@@ -5463,6 +7612,18 @@ dependencies = ["libc",]+[[package]]+name = "rtrb"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fae8ee26b0371a29a77d2b2d6b3ae13aa81def6f9bf1b1b92a32d279a5e709b7"++[[package]]+name = "rtrb"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9278fb35b3e730abe136e9b395b5b81b96d06b9f5478a50f0c8430a2237b22de"+[[package]]name = "rusqlite"version = "0.32.1"@@ -5508,6 +7669,20 @@ dependencies = ["semver",]+[[package]]+name = "rustfft"+version = "6.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"+dependencies = [+ "num-complex 0.4.6",+ "num-integer",+ "num-traits",+ "primal-check",+ "strength_reduce",+ "transpose",+]+[[package]]name = "rustix"version = "0.37.28"@@ -5571,7 +7746,7 @@ dependencies = ["openssl-probe","rustls-pki-types","schannel",- "security-framework",+ "security-framework 3.7.0",][[package]]@@ -5592,14 +7767,14 @@ checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"dependencies = ["core-foundation 0.10.1","core-foundation-sys",- "jni",+ "jni 0.21.1","log","once_cell","rustls","rustls-native-certs","rustls-platform-verifier-android","rustls-webpki",- "security-framework",+ "security-framework 3.7.0","security-framework-sys","webpki-root-certs","windows-sys 0.61.2",@@ -5718,6 +7893,49 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "scratch"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"++[[package]]+name = "screencapturekit"+version = "8.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ddaa8d6b16a2762c9a97c9a6297f04cb8ded0487e5ef02dc98b4e2bee3a26c7"+dependencies = [+ "apple-cf",+ "apple-metal",+]++[[package]]+name = "sec1"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"+dependencies = [+ "base16ct",+ "der",+ "generic-array 0.14.7",+ "pkcs8",+ "subtle",+ "zeroize",+]++[[package]]+name = "security-framework"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"+dependencies = [+ "bitflags 2.11.0",+ "core-foundation 0.9.4",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]+[[package]]name = "security-framework"version = "3.7.0"@@ -5791,6 +8009,16 @@ dependencies = ["typeid",]+[[package]]+name = "serde_bytes"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"+dependencies = [+ "serde",+ "serde_core",+]+[[package]]name = "serde_core"version = "1.0.228"@@ -6040,12 +8268,38 @@ dependencies = ["libc",]+[[package]]+name = "signature"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"+dependencies = [+ "digest 0.10.7",+ "rand_core 0.6.4",+]+[[package]]name = "simd-adler32"version = "0.3.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"+[[package]]+name = "simd_cesu8"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"+dependencies = [+ "rustc_version",+ "simdutf8",+]++[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"+[[package]]name = "siphasher"version = "0.3.11"@@ -6074,6 +8328,15 @@ version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+[[package]]+name = "slotmap"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"+dependencies = [+ "version_check",+]+[[package]]name = "smallvec"version = "1.15.1"@@ -6157,6 +8420,25 @@ dependencies = ["lock_api",]+[[package]]+name = "spirv"+version = "0.4.0+sdk-1.4.341.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"+dependencies = [+ "bitflags 2.11.0",+]++[[package]]+name = "spki"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"+dependencies = [+ "base64ct",+ "der",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -6169,6 +8451,12 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "strength_reduce"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"+[[package]]name = "string_cache"version = "0.8.9"@@ -6245,6 +8533,17 @@ dependencies = ["unicode-ident",]+[[package]]+name = "syn"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "sync_wrapper"version = "1.0.2"@@ -6295,7 +8594,7 @@ dependencies = ["gdkwayland-sys","gdkx11-sys","gtk",- "jni",+ "jni 0.21.1","lazy_static","libc","log",@@ -6370,7 +8669,7 @@ dependencies = ["heck 0.5.0","http","http-range",- "jni",+ "jni 0.21.1","libc","log","mime",@@ -6713,7 +9012,7 @@ dependencies = ["dpi","gtk","http",- "jni",+ "jni 0.21.1","objc2","objc2-ui-kit","objc2-web-kit",@@ -6736,7 +9035,7 @@ checksum = "5204682391625e867d16584fedc83fc292fb998814c9f7918605c789cd876314"dependencies = ["gtk","http",- "jni",+ "jni 0.21.1","log","objc2","objc2-app-kit",@@ -6840,6 +9139,15 @@ dependencies = ["utf-8",]+[[package]]+name = "termcolor"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+dependencies = [+ "winapi-util",+]+[[package]]name = "thiserror"version = "1.0.69"@@ -6900,7 +9208,7 @@ dependencies = ["half","quick-error","weezl",- "zune-jpeg",+ "zune-jpeg 0.4.21",][[package]]@@ -6968,6 +9276,28 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"+[[package]]+name = "tls_codec"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"+dependencies = [+ "serde",+ "tls_codec_derive",+ "zeroize",+]++[[package]]+name = "tls_codec_derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "tokio"version = "1.49.0"@@ -7040,6 +9370,20 @@ dependencies = ["tokio-util",]+[[package]]+name = "tokio-tungstenite"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"+dependencies = [+ "futures-util",+ "log",+ "native-tls",+ "tokio",+ "tokio-native-tls",+ "tungstenite 0.29.0",+]+[[package]]name = "tokio-tungstenite"version = "0.30.0"@@ -7051,7 +9395,7 @@ dependencies = ["native-tls","tokio","tokio-native-tls",- "tungstenite",+ "tungstenite 0.30.0",][[package]]@@ -7309,6 +9653,16 @@ dependencies = ["tracing-log",]+[[package]]+name = "transpose"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"+dependencies = [+ "num-integer",+ "strength_reduce",+]+[[package]]name = "tray-icon"version = "0.21.3"@@ -7328,26 +9682,63 @@ dependencies = ["png 0.17.16","serde","thiserror 2.0.18",- "windows-sys 0.60.2",+ "windows-sys 0.60.2",+]++[[package]]+name = "tree_magic_mini"+version = "3.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"+dependencies = [+ "memchr",+ "nom 8.0.0",+ "petgraph 0.8.3",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "tungstenite"+version = "0.26.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"+dependencies = [+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "native-tls",+ "rand 0.9.2",+ "sha1 0.10.6",+ "thiserror 2.0.18",+ "url",+ "utf-8",][[package]]-name = "tree_magic_mini"-version = "3.2.2"+name = "tungstenite"+version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"+checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"dependencies = [- "memchr",- "nom 8.0.0",- "petgraph",+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "native-tls",+ "rand 0.9.2",+ "sha1 0.10.6",+ "thiserror 2.0.18",+ "url",]-[[package]]-name = "try-lock"-version = "0.2.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"-[[package]]name = "tungstenite"version = "0.30.0"@@ -7474,6 +9865,16 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+[[package]]+name = "universal-hash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"+dependencies = [+ "crypto-common 0.1.7",+ "subtle",+]+[[package]]name = "untrusted"version = "0.9.0"@@ -7562,6 +9963,12 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"+[[package]]+name = "value-bag"+version = "1.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "068e763e8279de7ab94b6afebded2cb701678af094feb1c12ccb061b4783c1be"+[[package]]name = "vcpkg"version = "0.2.15"@@ -7663,9 +10070,9 @@ dependencies = [[[package]]name = "wasm-bindgen"-version = "0.2.111"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ec1adf1535672f5b7824f817792b1afd731d7e843d2d04ec8f27e8cb51edd8ac"+checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70"dependencies = ["cfg-if","once_cell",@@ -7676,23 +10083,19 @@ dependencies = [[[package]]name = "wasm-bindgen-futures"-version = "0.4.61"+version = "0.4.77"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fe88540d1c934c4ec8e6db0afa536876c5441289d7f9f9123d4f065ac1250a6b"+checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950"dependencies = [- "cfg-if",- "futures-util","js-sys",- "once_cell","wasm-bindgen",- "web-sys",][[package]]name = "wasm-bindgen-macro"-version = "0.2.111"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "19e638317c08b21663aed4d2b9a2091450548954695ff4efa75bff5fa546b3b1"+checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1"dependencies = ["quote","wasm-bindgen-macro-support",@@ -7700,9 +10103,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.111"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2c64760850114d03d5f65457e96fc988f11f01d38fbaa51b254e4ab5809102af"+checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284"dependencies = ["bumpalo","proc-macro2",@@ -7713,9 +10116,9 @@ dependencies = [[[package]]name = "wasm-bindgen-shared"-version = "0.2.111"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "60eecd4fe26177cfa3339eb00b4a36445889ba3ad37080c2429879718e20ca41"+checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf"dependencies = ["unicode-ident",]@@ -7847,14 +10250,17 @@ version = "0.31.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e6dbfc3ac5ef974c92a2235805cc0114033018ae1290a72e474aa8b28cbbdfd"dependencies = [+ "dlib",+ "log",+ "once_cell","pkg-config",][[package]]name = "web-sys"-version = "0.3.88"+version = "0.3.104"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d6bb20ed2d9572df8584f6dc81d68a41a625cadc6f15999d649a70ce7e3597a"+checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30"dependencies = ["js-sys","wasm-bindgen",@@ -7932,6 +10338,36 @@ dependencies = ["rustls-pki-types",]+[[package]]+name = "webrtc-sys"+version = "0.3.42"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bd328126bc3653b10eab635579f74a562a472ff032ff09b5d1681d35e6201fd"+dependencies = [+ "cc",+ "cxx",+ "cxx-build",+ "glob",+ "log",+ "pkg-config",+ "webrtc-sys-build",+]++[[package]]+name = "webrtc-sys-build"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d46da6b5a5cbd091fae0400f77189f4ca4807c0d9442b85838a584f28720570"+dependencies = [+ "anyhow",+ "fs2",+ "regex",+ "reqwest 0.12.28",+ "scratch",+ "semver",+ "zip 0.6.6",+]+[[package]]name = "webview2-com"version = "0.38.2"@@ -7974,6 +10410,179 @@ version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"+[[package]]+name = "wgpu"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"+dependencies = [+ "arrayvec",+ "bitflags 2.11.0",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.1",+ "js-sys",+ "log",+ "naga",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "smallvec",+ "static_assertions",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "wgpu-core",+ "wgpu-hal",+ "wgpu-types",+]++[[package]]+name = "wgpu-core"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"+dependencies = [+ "arrayvec",+ "bit-set",+ "bit-vec",+ "bitflags 2.11.0",+ "bytemuck",+ "cfg_aliases",+ "document-features",+ "hashbrown 0.17.1",+ "indexmap 2.13.0",+ "log",+ "naga",+ "naga-types",+ "once_cell",+ "parking_lot",+ "portable-atomic",+ "profiling",+ "raw-window-handle",+ "rustc-hash 1.1.0",+ "smallvec",+ "thiserror 2.0.18",+ "wgpu-core-deps-apple",+ "wgpu-core-deps-emscripten",+ "wgpu-core-deps-windows-linux-android",+ "wgpu-hal",+ "wgpu-naga-bridge",+ "wgpu-types",+]++[[package]]+name = "wgpu-core-deps-apple"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-emscripten"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-core-deps-windows-linux-android"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"+dependencies = [+ "wgpu-hal",+]++[[package]]+name = "wgpu-hal"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"+dependencies = [+ "android_system_properties",+ "arrayvec",+ "ash",+ "bit-set",+ "bitflags 2.11.0",+ "block2",+ "bytemuck",+ "cfg-if",+ "cfg_aliases",+ "glow",+ "glutin_wgl_sys",+ "gpu-allocator",+ "hashbrown 0.17.1",+ "js-sys",+ "khronos-egl",+ "libc",+ "libloading 0.8.9",+ "log",+ "naga",+ "naga-types",+ "ndk-sys",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "objc2-metal",+ "objc2-quartz-core",+ "once_cell",+ "ordered-float",+ "parking_lot",+ "portable-atomic",+ "portable-atomic-util",+ "profiling",+ "range-alloc",+ "raw-window-handle",+ "raw-window-metal",+ "renderdoc-sys",+ "smallvec",+ "static_assertions",+ "thiserror 2.0.18",+ "wasm-bindgen",+ "wayland-sys",+ "web-sys",+ "wgpu-naga-bridge",+ "wgpu-types",+ "windows 0.62.2",+ "windows-core 0.62.2",+ "windows-result 0.4.1",+]++[[package]]+name = "wgpu-naga-bridge"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"+dependencies = [+ "naga",+ "wgpu-types",+]++[[package]]+name = "wgpu-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"+dependencies = [+ "bitflags 2.11.0",+ "bytemuck",+ "js-sys",+ "log",+ "naga-types",+ "raw-window-handle",+ "static_assertions",+ "web-sys",+]+[[package]]name = "which"version = "4.4.2"@@ -8060,11 +10669,23 @@ version = "0.61.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"dependencies = [- "windows-collections",+ "windows-collections 0.2.0","windows-core 0.61.2",- "windows-future",+ "windows-future 0.2.1","windows-link 0.1.3",- "windows-numerics",+ "windows-numerics 0.2.0",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections 0.3.2",+ "windows-core 0.62.2",+ "windows-future 0.3.2",+ "windows-numerics 0.3.1",][[package]]@@ -8076,6 +10697,15 @@ dependencies = ["windows-core 0.61.2",]+[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core 0.62.2",+]+[[package]]name = "windows-core"version = "0.52.0"@@ -8119,7 +10749,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"dependencies = ["windows-core 0.61.2","windows-link 0.1.3",- "windows-threading",+ "windows-threading 0.1.0",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core 0.62.2",+ "windows-link 0.2.1",+ "windows-threading 0.2.1",][[package]]@@ -8166,6 +10807,16 @@ dependencies = ["windows-link 0.1.3",]+[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core 0.62.2",+ "windows-link 0.2.1",+]+[[package]]name = "windows-registry"version = "0.5.3"@@ -8339,6 +10990,15 @@ dependencies = ["windows-link 0.1.3",]+[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link 0.2.1",+]+[[package]]name = "windows-version"version = "0.1.7"@@ -8701,7 +11361,7 @@ dependencies = ["html5ever","http","javascriptcore-rs",- "jni",+ "jni 0.21.1","kuchikiki","libc","ndk",@@ -8775,6 +11435,18 @@ version = "0.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"+[[package]]+name = "x25519-dalek"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"+dependencies = [+ "curve25519-dalek",+ "rand_core 0.6.4",+ "serde",+ "zeroize",+]+[[package]]name = "xattr"version = "1.6.1"@@ -8801,6 +11473,12 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"+[[package]]+name = "xml-rs"+version = "0.8.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"+[[package]]name = "xz2"version = "0.1.7"@@ -8857,7 +11535,7 @@ dependencies = ["futures-sink","futures-util","hex 0.4.3",- "nix",+ "nix 0.26.4","once_cell","ordered-stream","rand 0.8.5",@@ -9006,6 +11684,20 @@ name = "zeroize"version = "1.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+][[package]]name = "zerotrie"@@ -9040,6 +11732,18 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "zip"+version = "0.6.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"+dependencies = [+ "byteorder",+ "crc32fast",+ "crossbeam-utils",+ "flate2",+]+[[package]]name = "zip"version = "2.4.2"@@ -9093,13 +11797,28 @@ version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"+[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"+[[package]]name = "zune-jpeg"version = "0.4.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"dependencies = [- "zune-core",+ "zune-core 0.4.12",+]++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core 0.5.3",][[package]]diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0d301a2d..feab8e69 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,5 +1,5 @@[workspace]-members = [".", "omniget-core", "omniget-plugin-sdk", "omniget-cli"]+members = [".", "omniget-core", "omniget-plugin-sdk", "omniget-cli", "omnidisc-proto", "omnidisc-media", "omnidisc-mls"]resolver = "2"[package]@@ -17,7 +17,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]tauri-build = { version = "2", features = [] }[dependencies]-tauri = { version = "2", features = ["protocol-asset", "tray-icon"] }+tauri = { version = "2", features = ["protocol-asset", "tray-icon", "macos-private-api"] }tauri-plugin-shell = "2"tauri-plugin-store = "2"tauri-plugin-dialog = "2"@@ -65,6 +65,9 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }open = "5"omniget-core = { path = "omniget-core", features = ["desktop"] }omniget-plugin-sdk = { path = "omniget-plugin-sdk" }+omnidisc-proto = { path = "omnidisc-proto" }+omnidisc-media = { path = "omnidisc-media" }+omnidisc-mls = { path = "omnidisc-mls" }libloading = "0.8"which = "7"librqbit = "8.1.1"@@ -76,6 +79,7 @@ native-tls = "0.2.18"fs4 = "1"[target.'cfg(windows)'.dependencies]+keyring = { version = "3", features = ["windows-native"] }webview2-com = "0.38"windows = { version = "0.61", features = ["Win32_System_Com", "Win32_UI_WindowsAndMessaging"] }@@ -83,6 +87,7 @@ windows = { version = "0.61", features = ["Win32_System_Com", "Win32_UI_WindowsA# HttpOnly cookies, which is the whole point of the auth webview (#287).# Versions track what wry already resolves, so this adds no new build cost.[target.'cfg(target_os = "macos")'.dependencies]+keyring = { version = "3", features = ["apple-native"] }objc2 = "0.6"objc2-foundation = { version = "0.3", features = ["NSHTTPCookie", "NSArray", "NSString"] }objc2-web-kit = { version = "0.3", features = ["WKWebView", "WKWebViewConfiguration", "WKWebsiteDataStore", "WKHTTPCookieStore"] }diff --git a/src-tauri/build.rs b/src-tauri/build.rsindex d860e1e6..b3b193ad 100644--- a/src-tauri/build.rs+++ b/src-tauri/build.rs@@ -1,3 +1,13 @@fn main() {+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {+ println!("cargo:rustc-link-arg=-ObjC");+ println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/lib/swift");+ if let Ok(out) = std::process::Command::new("xcode-select").arg("-p").output() {+ let xcode = String::from_utf8_lossy(&out.stdout).trim().to_string();+ if !xcode.is_empty() {+ println!("cargo:rustc-link-arg=-Wl,-rpath,{xcode}/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/macosx");+ }+ }+ }tauri_build::build()}diff --git a/src-tauri/omnidisc-media/Cargo.toml b/src-tauri/omnidisc-media/Cargo.tomlnew file mode 100644index 00000000..45ede983--- /dev/null+++ b/src-tauri/omnidisc-media/Cargo.toml@@ -0,0 +1,45 @@+[package]+name = "omnidisc-media"+version = "0.1.0"+edition = "2021"+description = "OmniDisc client media engine: capture, audio I/O, SFU connection, E2EE (all native, never in the webview)"+license = "GPL-3.0"++[features]+default = ["rnnoise"]+rnnoise = ["dep:nnnoiseless"]++[dependencies]+omnidisc-proto = { path = "../omnidisc-proto" }+tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+thiserror = "1"+tracing = "0.1"+async-trait = "0.1"+futures = "0.3"+livekit = { version = "0.8.3", features = ["native-tls"] }+cpal = "0.18"+rtrb = "0.4"+nnnoiseless = { version = "0.5", optional = true, default-features = false }+wgpu = "30"+pollster = "0.4"+raw-window-handle = "0.6"+image = { version = "0.25", default-features = false, features = ["jpeg"] }+base64 = "0.22"++[target.'cfg(target_os = "macos")'.dependencies]+screencapturekit = { version = "8.0.1", features = ["macos_14_0"] }+objc2 = "0.6"+objc2-foundation = { version = "0.3", features = ["NSArray", "NSString", "NSGeometry", "NSThread", "NSKeyValueCoding", "NSObject", "NSValue"] }+objc2-app-kit = { version = "0.3", features = ["NSView", "NSWindow", "NSResponder", "NSColor", "NSGraphics"] }+objc2-quartz-core = { version = "0.3", features = ["CALayer", "CAMetalLayer"] }+objc2-core-foundation = { version = "0.3.2", features = ["CFDictionary", "CFNumber", "CFString", "CFArray", "CFData", "CFBase"] }+objc2-core-video = { version = "0.3.2", features = ["CVPixelBuffer", "CVImageBuffer", "CVBuffer", "CVReturn", "CVBase", "CVPixelBufferPool", "CVPixelFormatDescription"] }+objc2-core-media = { version = "0.3.2", features = ["CMSampleBuffer", "CMFormatDescription", "CMTime", "CMBase", "CMBlockBuffer", "CMAttachment", "CMSync"] }+objc2-video-toolbox = { version = "0.3.2", features = ["VTCompressionSession", "VTCompressionProperties", "VTSession", "VTErrors", "VTBase", "VTVideoEncoderList", "VTUtilities"] }++[dev-dependencies]+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }+tokio-tungstenite = { version = "0.30", features = ["native-tls"] }+futures-util = "0.3"diff --git a/src-tauri/omnidisc-media/build.rs b/src-tauri/omnidisc-media/build.rsnew file mode 100644index 00000000..951722df--- /dev/null+++ b/src-tauri/omnidisc-media/build.rs@@ -0,0 +1,12 @@+fn main() {+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {+ println!("cargo:rustc-link-arg=-ObjC");+ println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/lib/swift");+ if let Ok(out) = std::process::Command::new("xcode-select").arg("-p").output() {+ let xcode = String::from_utf8_lossy(&out.stdout).trim().to_string();+ if !xcode.is_empty() {+ println!("cargo:rustc-link-arg=-Wl,-rpath,{xcode}/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.5/macosx");+ }+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/audio/capture.rs b/src-tauri/omnidisc-media/src/audio/capture.rsnew file mode 100644index 00000000..3afea965--- /dev/null+++ b/src-tauri/omnidisc-media/src/audio/capture.rs@@ -0,0 +1,370 @@+use super::resample::LinearResampler;+use livekit::webrtc::audio_frame::AudioFrame;+use livekit::webrtc::audio_source::native::NativeAudioSource;+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+use std::sync::mpsc;+use std::sync::Arc;+use std::time::{Duration, Instant};++pub const SAMPLE_RATE: u32 = 48_000;+pub const FRAME_SAMPLES: usize = 480;+const FRAME: Duration = Duration::from_millis(10);+const LEVEL_EVERY_TICKS: u32 = 10;+const VAD_HANGOVER_TICKS: u32 = 30;+const MAX_BACKLOG_MS: usize = 120;++#[derive(Debug, Clone, Copy, PartialEq)]+pub enum CaptureEvent {+ Level { rms_db: f32, peak: f32 },+ Speaking(bool),+ Underrun,+}++pub struct CaptureFlags {+ pub muted: AtomicBool,+ pub ptt_enabled: AtomicBool,+ pub ptt_pressed: AtomicBool,+ pub denoise: AtomicBool,+ pub monitor: AtomicBool,+ vad_threshold_db: AtomicU32,+}++impl Default for CaptureFlags {+ fn default() -> Self {+ Self {+ muted: AtomicBool::new(false),+ ptt_enabled: AtomicBool::new(false),+ ptt_pressed: AtomicBool::new(false),+ denoise: AtomicBool::new(cfg!(feature = "rnnoise")),+ monitor: AtomicBool::new(false),+ vad_threshold_db: AtomicU32::new((-45.0f32).to_bits()),+ }+ }+}++impl CaptureFlags {+ pub fn vad_threshold_db(&self) -> f32 {+ f32::from_bits(self.vad_threshold_db.load(Ordering::Relaxed))+ }++ pub fn set_vad_threshold_db(&self, db: f32) {+ self.vad_threshold_db.store(db.to_bits(), Ordering::Relaxed);+ }++ pub fn transmitting(&self) -> bool {+ !self.muted.load(Ordering::Relaxed)+ && (!self.ptt_enabled.load(Ordering::Relaxed) || self.ptt_pressed.load(Ordering::Relaxed))+ }+}++pub enum FeederMsg {+ Input { consumer: rtrb::Consumer<f32>, sample_rate: u32 },+ NoInput,+ Source(Option<NativeAudioSource>),+ TestTone(Option<f32>),+ Stop,+}++pub type CaptureSink = Arc<dyn Fn(CaptureEvent) + Send + Sync>;++pub struct Feeder {+ tx: mpsc::Sender<FeederMsg>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl Feeder {+ pub fn spawn(flags: Arc<CaptureFlags>, sink: CaptureSink) -> Result<Self, String> {+ let (tx, rx) = mpsc::channel();+ let thread = std::thread::Builder::new()+ .name("omnidisc-mic".into())+ .spawn(move || run(rx, flags, sink))+ .map_err(|e| format!("could not start the microphone thread: {e}"))?;+ Ok(Self { tx, thread: Some(thread) })+ }++ pub fn send(&self, msg: FeederMsg) {+ let _ = self.tx.send(msg);+ }+}++impl Drop for Feeder {+ fn drop(&mut self) {+ let _ = self.tx.send(FeederMsg::Stop);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++struct Pipeline {+ consumer: rtrb::Consumer<f32>,+ resampler: LinearResampler,+ sample_rate: u32,+ scratch: Vec<f32>,+ frame: Vec<f32>,+ out: AudioFrame<'static>,+ #[cfg(feature = "rnnoise")]+ denoiser: Box<nnnoiseless::DenoiseState<'static>>,+ #[cfg(feature = "rnnoise")]+ denoise_in: Vec<f32>,+ #[cfg(feature = "rnnoise")]+ denoise_out: Vec<f32>,+ speaking: bool,+ hang: u32,+ tick: u32,+ underruns: u64,+ tone: Option<(f32, f32)>,+}++impl Pipeline {+ fn new(consumer: rtrb::Consumer<f32>, sample_rate: u32) -> Self {+ Self {+ consumer,+ resampler: LinearResampler::new(sample_rate, SAMPLE_RATE),+ sample_rate,+ scratch: vec![0.0; 8192],+ frame: vec![0.0; FRAME_SAMPLES],+ out: AudioFrame::new(SAMPLE_RATE, 1, FRAME_SAMPLES as u32),+ #[cfg(feature = "rnnoise")]+ denoiser: nnnoiseless::DenoiseState::new(),+ #[cfg(feature = "rnnoise")]+ denoise_in: vec![0.0; FRAME_SAMPLES],+ #[cfg(feature = "rnnoise")]+ denoise_out: vec![0.0; FRAME_SAMPLES],+ speaking: false,+ hang: 0,+ tick: 0,+ underruns: 0,+ tone: None,+ }+ }++ fn pull(&mut self) {+ loop {+ let avail = self.consumer.slots();+ if avail == 0 {+ break;+ }+ let n = avail.min(self.scratch.len());+ let Ok(chunk) = self.consumer.read_chunk(n) else { break };+ let (a, b) = chunk.as_slices();+ self.scratch[..a.len()].copy_from_slice(a);+ self.scratch[a.len()..a.len() + b.len()].copy_from_slice(b);+ chunk.commit_all();+ self.resampler.push(&self.scratch[..n]);+ if n < self.scratch.len() {+ break;+ }+ }+ let max_backlog = (self.sample_rate as usize * MAX_BACKLOG_MS) / 1000;+ self.resampler.drop_excess(max_backlog);+ }++ fn step(&mut self, flags: &CaptureFlags, source: Option<&NativeAudioSource>, sink: &CaptureSink) {+ self.pull();+ let mut got = self.resampler.produce(&mut self.frame);+ if let Some((hz, phase)) = self.tone.as_mut() {+ let step = 2.0 * std::f32::consts::PI * *hz / SAMPLE_RATE as f32;+ for s in self.frame.iter_mut() {+ *s = phase.sin() * 0.5;+ *phase = (*phase + step) % (2.0 * std::f32::consts::PI);+ }+ got = true;+ }+ if !got {+ self.frame.fill(0.0);+ self.underruns += 1;+ if self.underruns == 50 {+ sink(CaptureEvent::Underrun);+ }+ } else {+ self.underruns = 0;+ }++ #[cfg(feature = "rnnoise")]+ if got && flags.denoise.load(Ordering::Relaxed) {+ for (d, s) in self.denoise_in.iter_mut().zip(self.frame.iter()) {+ *d = s * 32_768.0;+ }+ self.denoiser.process_frame(&mut self.denoise_out, &self.denoise_in);+ for (f, d) in self.frame.iter_mut().zip(self.denoise_out.iter()) {+ *f = (d / 32_768.0).clamp(-1.0, 1.0);+ }+ }++ let transmitting = flags.transmitting();+ let (rms, peak) = level(&self.frame);+ let rms_db = if rms > 0.0 { 20.0 * rms.log10() } else { -100.0 };++ let loud = got && transmitting && rms_db > flags.vad_threshold_db();+ if loud {+ self.hang = VAD_HANGOVER_TICKS;+ } else if self.hang > 0 {+ self.hang -= 1;+ }+ let speaking_now = self.hang > 0 && transmitting;+ if speaking_now != self.speaking {+ self.speaking = speaking_now;+ sink(CaptureEvent::Speaking(speaking_now));+ }++ self.tick = self.tick.wrapping_add(1);+ if flags.monitor.load(Ordering::Relaxed) && self.tick % LEVEL_EVERY_TICKS == 0 {+ sink(CaptureEvent::Level { rms_db, peak });+ }++ if let Some(src) = source {+ {+ let data = self.out.data.to_mut();+ if transmitting {+ for (o, s) in data.iter_mut().zip(self.frame.iter()) {+ *o = (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;+ }+ } else {+ data.fill(0);+ }+ }+ if let Err(e) = futures::executor::block_on(src.capture_frame(&self.out)) {+ tracing::debug!("[omnidisc-media] capture_frame: {e}");+ }+ }+ }+}++fn level(frame: &[f32]) -> (f32, f32) {+ let mut sum = 0.0f32;+ let mut peak = 0.0f32;+ for s in frame {+ sum += s * s;+ peak = peak.max(s.abs());+ }+ ((sum / frame.len().max(1) as f32).sqrt(), peak)+}++fn run(rx: mpsc::Receiver<FeederMsg>, flags: Arc<CaptureFlags>, sink: CaptureSink) {+ let mut pipeline: Option<Pipeline> = None;+ let mut source: Option<NativeAudioSource> = None;+ let mut next = Instant::now();+ loop {+ let msg = if pipeline.is_some() {+ match rx.try_recv() {+ Ok(m) => Some(m),+ Err(mpsc::TryRecvError::Empty) => None,+ Err(mpsc::TryRecvError::Disconnected) => return,+ }+ } else {+ match rx.recv() {+ Ok(m) => Some(m),+ Err(_) => return,+ }+ };+ match msg {+ Some(FeederMsg::Stop) => return,+ Some(FeederMsg::Input { consumer, sample_rate }) => {+ pipeline = Some(Pipeline::new(consumer, sample_rate));+ next = Instant::now();+ continue;+ }+ Some(FeederMsg::NoInput) => {+ if pipeline.take().is_some() {+ sink(CaptureEvent::Speaking(false));+ }+ continue;+ }+ Some(FeederMsg::Source(s)) => {+ source = s;+ continue;+ }+ Some(FeederMsg::TestTone(hz)) => {+ if pipeline.is_none() {+ let (_keep, consumer) = rtrb::RingBuffer::<f32>::new(SAMPLE_RATE as usize);+ std::mem::forget(_keep);+ pipeline = Some(Pipeline::new(consumer, SAMPLE_RATE));+ next = Instant::now();+ }+ if let Some(p) = pipeline.as_mut() {+ p.tone = hz.map(|h| (h, 0.0));+ }+ continue;+ }+ None => {}+ }+ let Some(p) = pipeline.as_mut() else { continue };+ p.step(&flags, source.as_ref(), &sink);+ next += FRAME;+ let now = Instant::now();+ if next > now {+ std::thread::sleep(next - now);+ } else if now - next > Duration::from_millis(100) {+ next = now;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn level_of_silence_and_full_scale() {+ assert_eq!(level(&[0.0; 480]), (0.0, 0.0));+ let (rms, peak) = level(&[1.0; 480]);+ assert!((rms - 1.0).abs() < 1e-6);+ assert_eq!(peak, 1.0);+ }++ #[test]+ fn transmit_gate_respects_mute_and_ptt() {+ let f = CaptureFlags::default();+ assert!(f.transmitting());+ f.muted.store(true, Ordering::Relaxed);+ assert!(!f.transmitting());+ f.muted.store(false, Ordering::Relaxed);+ f.ptt_enabled.store(true, Ordering::Relaxed);+ assert!(!f.transmitting());+ f.ptt_pressed.store(true, Ordering::Relaxed);+ assert!(f.transmitting());+ }++ #[test]+ fn feeder_emits_speaking_on_loud_input_and_silence_when_gated() {+ let flags = Arc::new(CaptureFlags::default());+ let (etx, erx) = mpsc::channel();+ let sink: CaptureSink = Arc::new(move |e| {+ let _ = etx.send(e);+ });+ let feeder = Feeder::spawn(flags.clone(), sink).expect("feeder");+ let (mut prod, cons) = rtrb::RingBuffer::<f32>::new(48_000);+ feeder.send(FeederMsg::Input { consumer: cons, sample_rate: 48_000 });+ let mut phase = 0.0f32;+ for _ in 0..40 {+ let mut buf = [0.0f32; 480];+ for s in buf.iter_mut() {+ *s = (phase).sin() * 0.5;+ phase += 2.0 * std::f32::consts::PI * 440.0 / 48_000.0;+ }+ let _ = prod.push_partial_slice(&buf);+ std::thread::sleep(Duration::from_millis(10));+ }+ let deadline = Instant::now() + Duration::from_secs(2);+ let mut spoke = false;+ while Instant::now() < deadline {+ if let Ok(CaptureEvent::Speaking(true)) = erx.recv_timeout(Duration::from_millis(100)) {+ spoke = true;+ break;+ }+ }+ assert!(spoke, "loud sine never flagged as speaking");+ flags.muted.store(true, Ordering::Relaxed);+ let deadline = Instant::now() + Duration::from_secs(2);+ let mut quiet = false;+ while Instant::now() < deadline {+ if let Ok(CaptureEvent::Speaking(false)) = erx.recv_timeout(Duration::from_millis(100)) {+ quiet = true;+ break;+ }+ }+ assert!(quiet, "mute never cleared the speaking flag");+ drop(feeder);+ }+}diff --git a/src-tauri/omnidisc-media/src/audio/devices.rs b/src-tauri/omnidisc-media/src/audio/devices.rsnew file mode 100644index 00000000..1c742740--- /dev/null+++ b/src-tauri/omnidisc-media/src/audio/devices.rs@@ -0,0 +1,79 @@+use cpal::traits::{DeviceTrait, HostTrait};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct AudioDevice {+ pub id: String,+ pub name: String,+ pub default: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct AudioDevices {+ pub inputs: Vec<AudioDevice>,+ pub outputs: Vec<AudioDevice>,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum DeviceKind {+ Input,+ Output,+}++fn describe(device: &cpal::Device, default_id: Option<&str>) -> Option<AudioDevice> {+ let id = device.id().ok()?.to_string();+ let name = device+ .description()+ .map(|d| d.name().to_string())+ .unwrap_or_else(|_| id.clone());+ let default = default_id == Some(id.as_str());+ Some(AudioDevice { id, name, default })+}++pub fn enumerate() -> AudioDevices {+ let host = cpal::default_host();+ let default_in = host.default_input_device().and_then(|d| d.id().ok()).map(|i| i.to_string());+ let default_out = host.default_output_device().and_then(|d| d.id().ok()).map(|i| i.to_string());+ let inputs = host+ .input_devices()+ .map(|it| it.filter_map(|d| describe(&d, default_in.as_deref())).collect())+ .unwrap_or_default();+ let outputs = host+ .output_devices()+ .map(|it| it.filter_map(|d| describe(&d, default_out.as_deref())).collect())+ .unwrap_or_default();+ AudioDevices { inputs, outputs }+}++/// Is this exact device still listed by the OS? Used to tell "unplugged" from+/// "there but refusing to open".+pub fn exists(kind: DeviceKind, id: &str) -> bool {+ let host = cpal::default_host();+ let listed = match kind {+ DeviceKind::Input => host.input_devices().ok().map(|it| it.collect::<Vec<_>>()),+ DeviceKind::Output => host.output_devices().ok().map(|it| it.collect::<Vec<_>>()),+ };+ listed+ .map(|devices| devices.iter().any(|d| d.id().map(|i| i.to_string() == id).unwrap_or(false)))+ .unwrap_or(false)+}++pub fn find(kind: DeviceKind, id: Option<&str>) -> Option<cpal::Device> {+ let host = cpal::default_host();+ let wanted = id.map(str::trim).filter(|s| !s.is_empty());+ match (kind, wanted) {+ (DeviceKind::Input, None) => host.default_input_device(),+ (DeviceKind::Output, None) => host.default_output_device(),+ (DeviceKind::Input, Some(w)) => host+ .input_devices()+ .ok()+ .and_then(|mut it| it.find(|d| d.id().map(|i| i.to_string() == w).unwrap_or(false)))+ .or_else(|| host.default_input_device()),+ (DeviceKind::Output, Some(w)) => host+ .output_devices()+ .ok()+ .and_then(|mut it| it.find(|d| d.id().map(|i| i.to_string() == w).unwrap_or(false)))+ .or_else(|| host.default_output_device()),+ }+}diff --git a/src-tauri/omnidisc-media/src/audio/io.rs b/src-tauri/omnidisc-media/src/audio/io.rsnew file mode 100644index 00000000..ecc8dfa7--- /dev/null+++ b/src-tauri/omnidisc-media/src/audio/io.rs@@ -0,0 +1,331 @@+use super::capture::{Feeder, FeederMsg};+use super::devices::{self, DeviceKind};+use super::playback::{Mixer, OutputRenderer};+use cpal::traits::{DeviceTrait, StreamTrait};+use cpal::{SampleFormat, StreamConfig};+use std::sync::mpsc;+use std::sync::Arc;+use std::time::Duration;++const INPUT_RING_SECONDS: usize = 1;++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum AudioIoError {+ NoDevice,+ PermissionDenied,+ DeviceBusy,+ Unsupported(String),+ Other(String),+}++impl AudioIoError {+ pub fn code(&self) -> &'static str {+ match self {+ Self::NoDevice => "no_device",+ Self::PermissionDenied => "permission_denied",+ Self::DeviceBusy => "device_busy",+ Self::Unsupported(_) => "unsupported",+ Self::Other(_) => "other",+ }+ }+}++impl std::fmt::Display for AudioIoError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::NoDevice => write!(f, "no audio device"),+ Self::PermissionDenied => write!(f, "audio permission denied"),+ Self::DeviceBusy => write!(f, "audio device busy"),+ Self::Unsupported(s) => write!(f, "unsupported audio config: {s}"),+ Self::Other(s) => write!(f, "{s}"),+ }+ }+}++fn classify(e: cpal::Error) -> AudioIoError {+ match e.kind() {+ cpal::ErrorKind::PermissionDenied => AudioIoError::PermissionDenied,+ cpal::ErrorKind::DeviceNotAvailable => AudioIoError::NoDevice,+ cpal::ErrorKind::DeviceBusy => AudioIoError::DeviceBusy,+ cpal::ErrorKind::UnsupportedConfig => AudioIoError::Unsupported(e.to_string()),+ _ => AudioIoError::Other(e.to_string()),+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum StreamFault {+ Input,+ Output,+}++/// Why a device stopped working. Told apart by re-opening it: the OS answers+/// "gone" and "not allowed" with different errors, and the two need different+/// help text — one is "plug it back in", the other is "grant the permission".+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DeviceLoss {+ Unplugged,+ PermissionRevoked,+ Busy,+ Failed,+}++pub fn classify_loss(still_listed: bool, probe: &AudioIoError) -> DeviceLoss {+ match probe {+ AudioIoError::PermissionDenied => DeviceLoss::PermissionRevoked,+ AudioIoError::NoDevice => DeviceLoss::Unplugged,+ AudioIoError::DeviceBusy => DeviceLoss::Busy,+ _ if !still_listed => DeviceLoss::Unplugged,+ _ => DeviceLoss::Failed,+ }+}++pub type FaultSink = Arc<dyn Fn(StreamFault, String) + Send + Sync>;++enum IoCmd {+ StartInput { device: Option<String>, reply: mpsc::Sender<Result<(), AudioIoError>> },+ StopInput,+ StartOutput { device: Option<String>, reply: mpsc::Sender<Result<(), AudioIoError>> },+ StopOutput,+ Shutdown,+}++pub struct AudioIo {+ tx: mpsc::Sender<IoCmd>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl AudioIo {+ pub fn spawn(feeder: Arc<Feeder>, mixer: Arc<Mixer>, faults: FaultSink) -> Result<Self, String> {+ let (tx, rx) = mpsc::channel();+ let thread = std::thread::Builder::new()+ .name("omnidisc-audio-io".into())+ .spawn(move || run(rx, feeder, mixer, faults))+ .map_err(|e| format!("could not start the audio thread: {e}"))?;+ Ok(Self { tx, thread: Some(thread) })+ }++ fn ask(&self, make: impl FnOnce(mpsc::Sender<Result<(), AudioIoError>>) -> IoCmd) -> Result<(), AudioIoError> {+ let (reply_tx, reply_rx) = mpsc::channel();+ self.tx+ .send(make(reply_tx))+ .map_err(|_| AudioIoError::Other("audio thread is gone".into()))?;+ reply_rx+ .recv_timeout(Duration::from_secs(10))+ .map_err(|_| AudioIoError::Other("audio thread did not answer".into()))?+ }++ pub fn start_input(&self, device: Option<String>) -> Result<(), AudioIoError> {+ self.ask(|reply| IoCmd::StartInput { device, reply })+ }++ pub fn stop_input(&self) {+ let _ = self.tx.send(IoCmd::StopInput);+ }++ pub fn start_output(&self, device: Option<String>) -> Result<(), AudioIoError> {+ self.ask(|reply| IoCmd::StartOutput { device, reply })+ }++ pub fn stop_output(&self) {+ let _ = self.tx.send(IoCmd::StopOutput);+ }+}++impl Drop for AudioIo {+ fn drop(&mut self) {+ let _ = self.tx.send(IoCmd::Shutdown);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++fn run(rx: mpsc::Receiver<IoCmd>, feeder: Arc<Feeder>, mixer: Arc<Mixer>, faults: FaultSink) {+ let mut input: Option<cpal::Stream> = None;+ let mut output: Option<cpal::Stream> = None;+ while let Ok(cmd) = rx.recv() {+ match cmd {+ IoCmd::StartInput { device, reply } => {+ input = None;+ feeder.send(FeederMsg::NoInput);+ let res = build_input(device.as_deref(), &feeder, faults.clone());+ let _ = reply.send(res.map(|s| {+ input = Some(s);+ }));+ }+ IoCmd::StopInput => {+ input = None;+ feeder.send(FeederMsg::NoInput);+ }+ IoCmd::StartOutput { device, reply } => {+ output = None;+ let res = build_output(device.as_deref(), mixer.clone(), faults.clone());+ let _ = reply.send(res.map(|s| {+ output = Some(s);+ }));+ }+ IoCmd::StopOutput => {+ output = None;+ }+ IoCmd::Shutdown => break,+ }+ }+ drop(input);+ drop(output);+}++fn build_input(device_id: Option<&str>, feeder: &Feeder, faults: FaultSink) -> Result<cpal::Stream, AudioIoError> {+ let device = devices::find(DeviceKind::Input, device_id).ok_or(AudioIoError::NoDevice)?;+ let supported = device.default_input_config().map_err(classify)?;+ let config: StreamConfig = supported.config();+ let channels = config.channels.max(1) as usize;+ let sample_rate = config.sample_rate;+ let (producer, consumer) = rtrb::RingBuffer::<f32>::new(sample_rate as usize * INPUT_RING_SECONDS);+ let err_cb = move |e: cpal::Error| {+ faults(StreamFault::Input, e.to_string());+ };+ let stream = match supported.sample_format() {+ SampleFormat::F32 => device.build_input_stream(+ config,+ input_callback::<f32>(producer, channels, |s| s),+ err_cb,+ None,+ ),+ SampleFormat::I16 => device.build_input_stream(+ config,+ input_callback::<i16>(producer, channels, |s| s as f32 / 32_768.0),+ err_cb,+ None,+ ),+ SampleFormat::I32 => device.build_input_stream(+ config,+ input_callback::<i32>(producer, channels, |s| s as f32 / 2_147_483_648.0),+ err_cb,+ None,+ ),+ SampleFormat::U16 => device.build_input_stream(+ config,+ input_callback::<u16>(producer, channels, |s| (s as f32 - 32_768.0) / 32_768.0),+ err_cb,+ None,+ ),+ other => return Err(AudioIoError::Unsupported(format!("{other:?}"))),+ }+ .map_err(classify)?;+ stream.play().map_err(classify)?;+ feeder.send(FeederMsg::Input { consumer, sample_rate });+ Ok(stream)+}++fn input_callback<T: Copy + Send + 'static>(+ mut producer: rtrb::Producer<f32>,+ channels: usize,+ convert: impl Fn(T) -> f32 + Send + 'static,+) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static {+ let mut mono: Vec<f32> = Vec::with_capacity(8192);+ move |data: &[T], _| {+ mono.clear();+ let inv = 1.0 / channels as f32;+ for frame in data.chunks(channels) {+ let mut acc = 0.0f32;+ for s in frame {+ acc += convert(*s);+ }+ if mono.len() < mono.capacity() {+ mono.push(acc * inv);+ }+ }+ let _ = producer.push_partial_slice(&mono);+ }+}++fn build_output(device_id: Option<&str>, mixer: Arc<Mixer>, faults: FaultSink) -> Result<cpal::Stream, AudioIoError> {+ let device = devices::find(DeviceKind::Output, device_id).ok_or(AudioIoError::NoDevice)?;+ let supported = device.default_output_config().map_err(classify)?;+ let config: StreamConfig = supported.config();+ let channels = config.channels.max(1);+ let sample_rate = config.sample_rate;+ let err_cb = move |e: cpal::Error| {+ faults(StreamFault::Output, e.to_string());+ };+ let stream = match supported.sample_format() {+ SampleFormat::F32 => device.build_output_stream(+ config,+ output_callback::<f32>(mixer, sample_rate, channels, |s| s),+ err_cb,+ None,+ ),+ SampleFormat::I16 => device.build_output_stream(+ config,+ output_callback::<i16>(mixer, sample_rate, channels, |s| (s * 32_767.0) as i16),+ err_cb,+ None,+ ),+ SampleFormat::I32 => device.build_output_stream(+ config,+ output_callback::<i32>(mixer, sample_rate, channels, |s| (s * 2_147_483_647.0) as i32),+ err_cb,+ None,+ ),+ SampleFormat::U16 => device.build_output_stream(+ config,+ output_callback::<u16>(mixer, sample_rate, channels, |s| ((s + 1.0) * 32_767.5) as u16),+ err_cb,+ None,+ ),+ other => return Err(AudioIoError::Unsupported(format!("{other:?}"))),+ }+ .map_err(classify)?;+ stream.play().map_err(classify)?;+ Ok(stream)+}++fn output_callback<T: Copy + Send + 'static>(+ mixer: Arc<Mixer>,+ sample_rate: u32,+ channels: u16,+ convert: impl Fn(f32) -> T + Send + 'static,+) -> impl FnMut(&mut [T], &cpal::OutputCallbackInfo) + Send + 'static {+ let mut renderer = OutputRenderer::new(sample_rate, channels);+ let mut scratch: Vec<f32> = vec![0.0; 16_384];+ move |data: &mut [T], _| {+ let n = data.len().min(scratch.len());+ renderer.render(&mixer, &mut scratch[..n]);+ for (d, s) in data.iter_mut().zip(scratch[..n].iter()) {+ *d = convert(*s);+ }+ for d in data.iter_mut().skip(n) {+ *d = convert(0.0);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn permission_beats_everything_else() {+ assert_eq!(+ classify_loss(true, &AudioIoError::PermissionDenied),+ DeviceLoss::PermissionRevoked+ );+ assert_eq!(+ classify_loss(false, &AudioIoError::PermissionDenied),+ DeviceLoss::PermissionRevoked+ );+ }++ #[test]+ fn a_device_the_os_no_longer_lists_counts_as_unplugged() {+ assert_eq!(classify_loss(false, &AudioIoError::Other("gone".into())), DeviceLoss::Unplugged);+ assert_eq!(classify_loss(true, &AudioIoError::NoDevice), DeviceLoss::Unplugged);+ }++ #[test]+ fn a_listed_device_that_will_not_open_is_a_plain_failure() {+ assert_eq!(classify_loss(true, &AudioIoError::Other("boom".into())), DeviceLoss::Failed);+ assert_eq!(classify_loss(true, &AudioIoError::DeviceBusy), DeviceLoss::Busy);+ }+}diff --git a/src-tauri/omnidisc-media/src/audio/mod.rs b/src-tauri/omnidisc-media/src/audio/mod.rsnew file mode 100644index 00000000..3121e8a9--- /dev/null+++ b/src-tauri/omnidisc-media/src/audio/mod.rs@@ -0,0 +1,10 @@+pub mod capture;+pub mod devices;+pub mod io;+pub mod playback;+pub mod resample;++pub use capture::{CaptureEvent, CaptureFlags, Feeder, FeederMsg};+pub use devices::{AudioDevice, AudioDevices, DeviceKind};+pub use io::{classify_loss, AudioIo, AudioIoError, DeviceLoss, StreamFault};+pub use playback::Mixer;diff --git a/src-tauri/omnidisc-media/src/audio/playback.rs b/src-tauri/omnidisc-media/src/audio/playback.rsnew file mode 100644index 00000000..0b200d29--- /dev/null+++ b/src-tauri/omnidisc-media/src/audio/playback.rs@@ -0,0 +1,322 @@+use std::collections::VecDeque;+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};+use std::sync::Mutex;++pub const MIX_RATE: u32 = 48_000;+const MAX_SOURCES: usize = 64;+const SCRATCH: usize = 16_384;+/// Ducking ramps instead of stepping: a hard gain jump on a voice track is an+/// audible click, and the click is worse than the thing ducking fixes.+const DUCK_RAMP_SECONDS: f32 = 0.08;++pub struct MixSource {+ pub key: String,+ pub user_id: String,+ pub consumer: rtrb::Consumer<f32>,+ pub gain: f32,+}++pub struct Mixer {+ sources: Mutex<Vec<MixSource>>,+ master: AtomicU32,+ deafened: AtomicBool,+ duck_amount: AtomicU32,+ ducking: AtomicBool,+ duck_gain: AtomicU32,+ pub underruns: AtomicU64,+ pub lock_misses: AtomicU64,+}++impl Default for Mixer {+ fn default() -> Self {+ Self {+ sources: Mutex::new(Vec::with_capacity(MAX_SOURCES)),+ master: AtomicU32::new(1.0f32.to_bits()),+ deafened: AtomicBool::new(false),+ duck_amount: AtomicU32::new(0.0f32.to_bits()),+ ducking: AtomicBool::new(false),+ duck_gain: AtomicU32::new(1.0f32.to_bits()),+ underruns: AtomicU64::new(0),+ lock_misses: AtomicU64::new(0),+ }+ }+}++impl Mixer {+ pub fn add_source(&self, key: String, user_id: String, consumer: rtrb::Consumer<f32>, gain: f32) {+ if let Ok(mut s) = self.sources.lock() {+ s.retain(|x| x.key != key);+ if s.len() < MAX_SOURCES {+ s.push(MixSource { key, user_id, consumer, gain: gain.clamp(0.0, 2.0) });+ }+ }+ }++ pub fn remove_source(&self, key: &str) {+ if let Ok(mut s) = self.sources.lock() {+ s.retain(|x| x.key != key);+ }+ }++ pub fn clear(&self) {+ if let Ok(mut s) = self.sources.lock() {+ s.clear();+ }+ }++ pub fn set_user_gain(&self, user_id: &str, gain: f32) {+ if let Ok(mut s) = self.sources.lock() {+ for x in s.iter_mut().filter(|x| x.user_id == user_id) {+ x.gain = gain.clamp(0.0, 2.0);+ }+ }+ }++ pub fn set_master(&self, gain: f32) {+ self.master.store(gain.clamp(0.0, 2.0).to_bits(), Ordering::Relaxed);+ }++ pub fn master(&self) -> f32 {+ f32::from_bits(self.master.load(Ordering::Relaxed))+ }++ pub fn set_deafened(&self, on: bool) {+ self.deafened.store(on, Ordering::Relaxed);+ }++ pub fn is_deafened(&self) -> bool {+ self.deafened.load(Ordering::Relaxed)+ }++ /// How much of everyone else to take away while the local user speaks,+ /// 0–100 %. 0 turns ducking off.+ pub fn set_duck_percent(&self, percent: u8) {+ let amount = (percent.min(100) as f32) / 100.0;+ self.duck_amount.store(amount.to_bits(), Ordering::Relaxed);+ }++ pub fn duck_percent(&self) -> u8 {+ (f32::from_bits(self.duck_amount.load(Ordering::Relaxed)) * 100.0).round() as u8+ }++ pub fn set_ducking(&self, on: bool) {+ self.ducking.store(on, Ordering::Relaxed);+ }++ fn duck_target(&self) -> f32 {+ if self.ducking.load(Ordering::Relaxed) {+ 1.0 - f32::from_bits(self.duck_amount.load(Ordering::Relaxed)).clamp(0.0, 1.0)+ } else {+ 1.0+ }+ }++ pub fn source_count(&self) -> usize {+ self.sources.lock().map(|s| s.len()).unwrap_or(0)+ }++ pub fn mix_into(&self, out: &mut [f32], scratch: &mut [f32]) {+ out.fill(0.0);+ if self.is_deafened() {+ return;+ }+ let Ok(mut sources) = self.sources.try_lock() else {+ self.lock_misses.fetch_add(1, Ordering::Relaxed);+ return;+ };+ let master = self.master();+ let n = out.len().min(scratch.len());+ for src in sources.iter_mut() {+ let avail = src.consumer.slots().min(n);+ if avail < n {+ self.underruns.fetch_add(1, Ordering::Relaxed);+ }+ if avail == 0 {+ continue;+ }+ let Ok(chunk) = src.consumer.read_chunk(avail) else { continue };+ let (a, b) = chunk.as_slices();+ scratch[..a.len()].copy_from_slice(a);+ scratch[a.len()..a.len() + b.len()].copy_from_slice(b);+ chunk.commit_all();+ let g = src.gain * master;+ for (o, s) in out[..avail].iter_mut().zip(scratch[..avail].iter()) {+ *o += s * g;+ }+ }+ drop(sources);+ let target = self.duck_target();+ let mut g = f32::from_bits(self.duck_gain.load(Ordering::Relaxed));+ let step = 1.0 / (MIX_RATE as f32 * DUCK_RAMP_SECONDS);+ for o in out.iter_mut() {+ if g < target {+ g = (g + step).min(target);+ } else if g > target {+ g = (g - step).max(target);+ }+ *o = (*o * g).clamp(-1.0, 1.0);+ }+ self.duck_gain.store(g.to_bits(), Ordering::Relaxed);+ }+}++pub struct OutputRenderer {+ step: f64,+ pos: f64,+ channels: usize,+ buf48: VecDeque<f32>,+ mix: Vec<f32>,+ scratch: Vec<f32>,+}++impl OutputRenderer {+ pub fn new(out_rate: u32, channels: u16) -> Self {+ Self {+ step: MIX_RATE as f64 / out_rate.max(1) as f64,+ pos: 0.0,+ channels: channels.max(1) as usize,+ buf48: VecDeque::with_capacity(SCRATCH),+ mix: vec![0.0; SCRATCH],+ scratch: vec![0.0; SCRATCH],+ }+ }++ pub fn render(&mut self, mixer: &Mixer, data: &mut [f32]) {+ let frames = data.len() / self.channels;+ if frames == 0 {+ return;+ }+ if (self.step - 1.0).abs() < f64::EPSILON {+ let n = frames.min(self.mix.len());+ let (mix, scratch) = (&mut self.mix[..n], &mut self.scratch[..n]);+ mixer.mix_into(mix, scratch);+ for (i, frame) in data.chunks_mut(self.channels).enumerate() {+ let s = if i < n { mix[i] } else { 0.0 };+ frame.fill(s);+ }+ return;+ }+ let needed = (self.pos + frames as f64 * self.step).floor() as usize + 2;+ if self.buf48.len() < needed {+ let n = (needed - self.buf48.len()).min(self.mix.len());+ let (mix, scratch) = (&mut self.mix[..n], &mut self.scratch[..n]);+ mixer.mix_into(mix, scratch);+ for s in mix.iter() {+ if self.buf48.len() < self.buf48.capacity() {+ self.buf48.push_back(*s);+ }+ }+ }+ let mut p = self.pos;+ for frame in data.chunks_mut(self.channels) {+ let idx = p.floor() as usize;+ let frac = (p - idx as f64) as f32;+ let a = self.buf48.get(idx).copied().unwrap_or(0.0);+ let b = self.buf48.get(idx + 1).copied().unwrap_or(a);+ frame.fill(a + (b - a) * frac);+ p += self.step;+ }+ let consumed = (p.floor() as usize).min(self.buf48.len());+ self.pos = p - p.floor();+ self.buf48.drain(..consumed);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn mixes_two_sources_with_gain_and_master() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(1024);+ let (mut p2, c2) = rtrb::RingBuffer::<f32>::new(1024);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ mixer.add_source("t2".into(), "u2".into(), c2, 0.5);+ let _ = p1.push_partial_slice(&[0.2; 480]);+ let _ = p2.push_partial_slice(&[0.4; 480]);+ let mut out = vec![0.0; 480];+ let mut scratch = vec![0.0; 480];+ mixer.mix_into(&mut out, &mut scratch);+ assert!((out[0] - 0.4).abs() < 1e-6);+ mixer.set_user_gain("u2", 2.0);+ mixer.set_master(0.5);+ let _ = p1.push_partial_slice(&[0.2; 480]);+ let _ = p2.push_partial_slice(&[0.4; 480]);+ mixer.mix_into(&mut out, &mut scratch);+ assert!((out[0] - 0.5).abs() < 1e-6);+ }++ #[test]+ fn deafen_outputs_silence_and_underrun_fills_zero() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(1024);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ let _ = p1.push_partial_slice(&[0.9; 100]);+ let mut out = vec![1.0; 480];+ let mut scratch = vec![0.0; 480];+ mixer.mix_into(&mut out, &mut scratch);+ assert!((out[0] - 0.9).abs() < 1e-6);+ assert_eq!(out[200], 0.0);+ mixer.set_deafened(true);+ let _ = p1.push_partial_slice(&[0.9; 100]);+ mixer.mix_into(&mut out, &mut scratch);+ assert!(out.iter().all(|s| *s == 0.0));+ }++ #[test]+ fn ducking_ramps_other_people_down_and_back_up() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(48_000);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ mixer.set_duck_percent(60);+ assert_eq!(mixer.duck_percent(), 60);+ let mut out = vec![0.0; 4800];+ let mut scratch = vec![0.0; 4800];++ let _ = p1.push_partial_slice(&vec![0.5; 4800]);+ mixer.mix_into(&mut out, &mut scratch);+ assert!((out[4799] - 0.5).abs() < 1e-6, "no ducking while nobody speaks");++ mixer.set_ducking(true);+ for _ in 0..2 {+ let _ = p1.push_partial_slice(&vec![0.5; 4800]);+ mixer.mix_into(&mut out, &mut scratch);+ }+ assert!((out[4799] - 0.2).abs() < 1e-3, "ducked sample was {}", out[4799]);++ mixer.set_ducking(false);+ for _ in 0..2 {+ let _ = p1.push_partial_slice(&vec![0.5; 4800]);+ mixer.mix_into(&mut out, &mut scratch);+ }+ assert!((out[4799] - 0.5).abs() < 1e-3, "restored sample was {}", out[4799]);+ }++ #[test]+ fn ducking_off_by_default_leaves_the_mix_alone() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(4096);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ mixer.set_ducking(true);+ let _ = p1.push_partial_slice(&[0.5; 480]);+ let mut out = vec![0.0; 480];+ let mut scratch = vec![0.0; 480];+ mixer.mix_into(&mut out, &mut scratch);+ assert!((out[479] - 0.5).abs() < 1e-6);+ }++ #[test]+ fn renderer_resamples_to_device_rate_and_channels() {+ let mixer = Mixer::default();+ let (mut p1, c1) = rtrb::RingBuffer::<f32>::new(48_000);+ mixer.add_source("t1".into(), "u1".into(), c1, 1.0);+ let _ = p1.push_partial_slice(&vec![0.5; 4800]);+ let mut r = OutputRenderer::new(44_100, 2);+ let mut data = vec![0.0; 441 * 2];+ r.render(&mixer, &mut data);+ assert!((data[0] - 0.5).abs() < 1e-6);+ assert!((data[1] - 0.5).abs() < 1e-6);+ assert!((data[880] - 0.5).abs() < 1e-6);+ }+}diff --git a/src-tauri/omnidisc-media/src/audio/resample.rs b/src-tauri/omnidisc-media/src/audio/resample.rsnew file mode 100644index 00000000..69f1f57e--- /dev/null+++ b/src-tauri/omnidisc-media/src/audio/resample.rs@@ -0,0 +1,111 @@+pub struct LinearResampler {+ step: f64,+ pos: f64,+ pending: Vec<f32>,+}++impl LinearResampler {+ pub fn new(from_rate: u32, to_rate: u32) -> Self {+ let step = if to_rate == 0 { 1.0 } else { from_rate as f64 / to_rate as f64 };+ Self { step, pos: 0.0, pending: Vec::with_capacity(16_384) }+ }++ pub fn is_identity(&self) -> bool {+ (self.step - 1.0).abs() < f64::EPSILON+ }++ pub fn push(&mut self, input: &[f32]) {+ self.pending.extend_from_slice(input);+ }++ pub fn pending_len(&self) -> usize {+ self.pending.len()+ }++ pub fn needed_for(&self, out_len: usize) -> usize {+ (self.pos + out_len as f64 * self.step).floor() as usize + 2+ }++ pub fn drop_excess(&mut self, keep_at_most: usize) {+ if self.pending.len() > keep_at_most {+ let drop = self.pending.len() - keep_at_most;+ self.pending.drain(..drop);+ }+ }++ pub fn produce(&mut self, out: &mut [f32]) -> bool {+ if self.is_identity() {+ if self.pending.len() < out.len() {+ return false;+ }+ out.copy_from_slice(&self.pending[..out.len()]);+ self.pending.drain(..out.len());+ return true;+ }+ if self.pending.len() < self.needed_for(out.len()) {+ return false;+ }+ let mut p = self.pos;+ for o in out.iter_mut() {+ let idx = p.floor() as usize;+ let frac = (p - idx as f64) as f32;+ let a = self.pending[idx];+ let b = self.pending[idx + 1];+ *o = a + (b - a) * frac;+ p += self.step;+ }+ let consumed = p.floor() as usize;+ self.pos = p - consumed as f64;+ self.pending.drain(..consumed);+ true+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn identity_passes_through() {+ let mut r = LinearResampler::new(48_000, 48_000);+ r.push(&[1.0, 2.0, 3.0, 4.0]);+ let mut out = [0.0; 4];+ assert!(r.produce(&mut out));+ assert_eq!(out, [1.0, 2.0, 3.0, 4.0]);+ assert_eq!(r.pending_len(), 0);+ }++ #[test]+ fn upsamples_ramp_smoothly() {+ let mut r = LinearResampler::new(24_000, 48_000);+ let input: Vec<f32> = (0..100).map(|i| i as f32).collect();+ r.push(&input);+ let mut out = vec![0.0; 100];+ assert!(r.produce(&mut out));+ for (i, v) in out.iter().enumerate() {+ assert!((v - i as f32 * 0.5).abs() < 1e-4, "index {i}: {v}");+ }+ }++ #[test]+ fn reports_underrun_without_consuming() {+ let mut r = LinearResampler::new(44_100, 48_000);+ r.push(&[0.0; 10]);+ let mut out = [0.0; 480];+ assert!(!r.produce(&mut out));+ assert_eq!(r.pending_len(), 10);+ }++ #[test]+ fn downsample_keeps_fractional_position_across_calls() {+ let mut r = LinearResampler::new(44_100, 48_000);+ let input: Vec<f32> = (0..2000).map(|i| (i as f32 * 0.01).sin()).collect();+ r.push(&input);+ let mut a = vec![0.0; 480];+ let mut b = vec![0.0; 480];+ assert!(r.produce(&mut a));+ assert!(r.produce(&mut b));+ let expected = ((480.0 * 44_100.0 / 48_000.0) as f32 * 0.01).sin();+ assert!((b[0] - expected).abs() < 0.01);+ }+}diff --git a/src-tauri/omnidisc-media/src/capture/macos.rs b/src-tauri/omnidisc-media/src/capture/macos.rsnew file mode 100644index 00000000..e5528c6d--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/macos.rs@@ -0,0 +1,467 @@+use super::{unix_micros, AudioSink, CaptureApi, CaptureGeometry, CaptureOptions, VideoSink, VideoTick};+use crate::stream::{resolve_geometry, AudioApp, AudioMode, SourceId, StreamError, StreamSource, StreamSources};+use base64::Engine;+use screencapturekit::prelude::*;+use screencapturekit::screenshot_manager::{CGImageExt, SCScreenshotManager};+use screencapturekit::shareable_content::SCShareableContentInfo;+use screencapturekit::CVPixelBuffer;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++pub const FOURCC_420V: u32 = 0x3432_3076;++pub struct CapturedFrame {+ pub pixel_buffer: CVPixelBuffer,+ pub width: u32,+ pub height: u32,+ pub capture_us: i64,+}++impl CapturedFrame {+ pub fn width(&self) -> u32 {+ self.width+ }++ pub fn height(&self) -> u32 {+ self.height+ }++ pub fn capture_us(&self) -> i64 {+ self.capture_us+ }++ pub fn as_raw(&self) -> *mut std::ffi::c_void {+ self.pixel_buffer.as_ptr()+ }+}++type CFRef = *const std::ffi::c_void;++extern "C" {+ fn CMSampleBufferGetSampleAttachmentsArray(sbuf: CFRef, create: u8) -> CFRef;+ fn CFArrayGetCount(arr: CFRef) -> isize;+ fn CFArrayGetValueAtIndex(arr: CFRef, idx: isize) -> CFRef;+ fn CFStringCreateWithCString(alloc: CFRef, s: *const u8, encoding: u32) -> CFRef;+ fn CFDictionaryGetValue(dict: CFRef, key: CFRef) -> CFRef;+ fn CFNumberGetValue(num: CFRef, ty: isize, out: *mut std::ffi::c_void) -> u8;+ fn CFRelease(cf: CFRef);+}++// The crate's `frame_status()` always returns None (it casts an NSNumber to an+// enum), so the attachment is read by hand: 0 = Complete, 1 = Idle.+fn frame_status(sample: &CMSampleBuffer) -> Option<i64> {+ unsafe {+ let arr = CMSampleBufferGetSampleAttachmentsArray(sample.as_ptr(), 0);+ if arr.is_null() || CFArrayGetCount(arr) == 0 {+ return None;+ }+ let dict = CFArrayGetValueAtIndex(arr, 0);+ let key = CFStringCreateWithCString(std::ptr::null(), b"SCStreamUpdateFrameStatus\0".as_ptr(), 0x0800_0100);+ let val = CFDictionaryGetValue(dict, key);+ CFRelease(key);+ if val.is_null() {+ return None;+ }+ let mut out: i64 = 0;+ if CFNumberGetValue(val, 4, (&mut out as *mut i64).cast()) != 0 {+ Some(out)+ } else {+ None+ }+ }+}++fn map_sc_error(e: SCError) -> StreamError {+ let text = e.to_string();+ let lower = text.to_lowercase();+ if matches!(e, SCError::PermissionDenied(_))+ || e.stream_error_code() == Some(screencapturekit::utils::error::SCStreamErrorCode::UserDeclined)+ || lower.contains("declined")+ || lower.contains("permission")+ || lower.contains("-3801")+ {+ StreamError::Permission+ } else {+ StreamError::Capture(text)+ }+}++fn shareable() -> Result<SCShareableContent, StreamError> {+ SCShareableContent::create()+ .with_on_screen_windows_only(true)+ .with_exclude_desktop_windows(true)+ .get()+ .map_err(map_sc_error)+}++fn own_app(content: &SCShareableContent) -> Option<SCRunningApplication> {+ let pid = std::process::id() as i32;+ content.applications().into_iter().find(|a| a.process_id() == pid)+}++fn thumbnail(filter: &SCContentFilter, src_w: u32, src_h: u32) -> Option<String> {+ let w = 320u32;+ let h = ((src_h as u64 * w as u64) / src_w.max(1) as u64).clamp(2, 320) as u32;+ let config = SCStreamConfiguration::new().with_width(w).with_height(h).with_shows_cursor(false);+ let image = SCScreenshotManager::capture_image(filter, &config).ok()?;+ let rgba = image.rgba_data().ok()?;+ let (iw, ih) = (image.width() as u32, image.height() as u32);+ if rgba.len() < (iw * ih * 4) as usize {+ return None;+ }+ let mut rgb = Vec::with_capacity((iw * ih * 3) as usize);+ for px in rgba.chunks_exact(4).take((iw * ih) as usize) {+ rgb.extend_from_slice(&px[..3]);+ }+ let mut jpeg = Vec::new();+ let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 60);+ enc.encode(&rgb, iw, ih, image::ExtendedColorType::Rgb8).ok()?;+ Some(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(jpeg)))+}++fn display_source(content: &SCShareableContent, d: &SCDisplay, index: usize, thumbs: bool) -> StreamSource {+ let (w, h) = (d.width(), d.height());+ let thumb = if thumbs {+ let filter = match own_app(content) {+ Some(me) => SCContentFilter::create().with_display(d).with_excluding_applications(&[&me], &[]).build(),+ None => SCContentFilter::create().with_display(d).with_excluding_windows(&[]).build(),+ };+ thumbnail(&filter, w, h)+ } else {+ None+ };+ StreamSource {+ id: SourceId::Display { id: d.display_id() },+ title: format!("Display {} ({}×{})", index + 1, w, h),+ app_name: None,+ width: w,+ height: h,+ thumbnail: thumb,+ }+}++fn window_source(w: &SCWindow, thumbs: bool) -> Option<StreamSource> {+ if !w.is_on_screen() || w.window_layer() != 0 {+ return None;+ }+ let frame = w.frame();+ if frame.size.width < 64.0 || frame.size.height < 64.0 {+ return None;+ }+ let title = w.title().unwrap_or_default();+ let app = w.owning_application();+ if app.as_ref().map(|a| a.process_id() == std::process::id() as i32).unwrap_or(false) {+ return None;+ }+ let app_name = app.map(|a| a.application_name()).filter(|n| !n.is_empty());+ if title.trim().is_empty() && app_name.is_none() {+ return None;+ }+ let (pw, ph) = (frame.size.width as u32, frame.size.height as u32);+ let thumb = if thumbs {+ let filter = SCContentFilter::create().with_window(w).build();+ thumbnail(&filter, pw, ph)+ } else {+ None+ };+ Some(StreamSource {+ id: SourceId::Window { id: w.window_id() },+ title: if title.trim().is_empty() { app_name.clone().unwrap_or_default() } else { title },+ app_name,+ width: pw,+ height: ph,+ thumbnail: thumb,+ })+}++pub struct VideoCapture {+ stream: Option<SCStream>,+ _synthetic: Option<SyntheticSource>,+}++impl VideoCapture {+ pub fn stop(self) {+ if let Some(s) = self.stream {+ if let Err(e) = s.stop_capture() {+ tracing::debug!("[omnidisc-media] stop_capture: {e}");+ }+ }+ }+}++pub struct AudioCapture {+ stream: Option<SCStream>,+}++impl AudioCapture {+ pub fn stop(self) {+ if let Some(s) = self.stream {+ if let Err(e) = s.stop_capture() {+ tracing::debug!("[omnidisc-media] audio stop_capture: {e}");+ }+ }+ }+}++fn video_handler(sink: VideoSink) -> impl Fn(CMSampleBuffer, SCStreamOutputType) + Send + Sync + 'static {+ move |sample: CMSampleBuffer, of_type: SCStreamOutputType| {+ if of_type != SCStreamOutputType::Screen {+ return;+ }+ let status = frame_status(&sample);+ if matches!(status, Some(0) | None) {+ if let Some(pb) = sample.image_buffer() {+ let (w, h) = (pb.width() as u32, pb.height() as u32);+ sink(VideoTick::Frame(CapturedFrame { pixel_buffer: pb, width: w, height: h, capture_us: unix_micros() }));+ return;+ }+ }+ sink(VideoTick::Idle);+ }+}++fn audio_handler(sink: AudioSink) -> impl Fn(CMSampleBuffer, SCStreamOutputType) + Send + Sync + 'static {+ let scratch: std::sync::Mutex<Vec<f32>> = std::sync::Mutex::new(Vec::with_capacity(4096));+ move |sample: CMSampleBuffer, of_type: SCStreamOutputType| {+ if of_type != SCStreamOutputType::Audio {+ return;+ }+ let Some(list) = sample.audio_buffer_list() else { return };+ let n = list.num_buffers();+ if n == 0 {+ return;+ }+ let Ok(mut out) = scratch.lock() else { return };+ out.clear();+ let bufs: Vec<&[f32]> = (0..n)+ .filter_map(|i| list.buffer(i))+ .map(|b| {+ let d = b.data();+ let (_, f, _) = unsafe { d.align_to::<f32>() };+ f+ })+ .collect();+ let frames = bufs.iter().map(|b| b.len()).min().unwrap_or(0);+ if frames == 0 {+ return;+ }+ match bufs.len() {+ 1 => {+ for f in 0..frames {+ out.push(bufs[0][f]);+ out.push(bufs[0][f]);+ }+ }+ _ => {+ for f in 0..frames {+ out.push(bufs[0][f]);+ out.push(bufs[1][f]);+ }+ }+ }+ sink(&out);+ }+}++struct SyntheticSource {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+}++impl Drop for SyntheticSource {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Relaxed);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++fn start_synthetic(width: u32, height: u32, fps: u16, sink: VideoSink) -> Result<(VideoCapture, CaptureGeometry), StreamError> {+ let (width, height) = ((width.max(2)) & !1, (height.max(2)) & !1);+ let stop = Arc::new(AtomicBool::new(false));+ let stop2 = stop.clone();+ let thread = std::thread::Builder::new()+ .name("omnidisc-synthetic".into())+ .spawn(move || {+ let interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);+ let w = width as usize;+ let h = height as usize;+ let mut pattern = vec![0u8; w + 256];+ for (i, p) in pattern.iter_mut().enumerate() {+ *p = (16 + (i % 220)) as u8;+ }+ let mut next = Instant::now();+ let mut n: u64 = 0;+ while !stop2.load(Ordering::Relaxed) {+ match CVPixelBuffer::create(w, h, FOURCC_420V) {+ Ok(pb) => {+ if let Ok(mut guard) = pb.lock_read_write() {+ let y_stride = guard.bytes_per_row_of_plane(0);+ let uv_stride = guard.bytes_per_row_of_plane(1);+ if let (Some(y_base), Some(uv_base)) = (guard.base_address_of_plane_mut(0), guard.base_address_of_plane_mut(1)) {+ let shift = (n % 220) as usize;+ for row in 0..h {+ let off = (shift + row / 4) % 220;+ unsafe {+ std::ptr::copy_nonoverlapping(pattern.as_ptr().add(off), y_base.add(row * y_stride), w);+ }+ }+ let u_val = (128 + ((n / 2) % 64) as i32 - 32) as u8;+ let v_val = (128 + ((n / 3) % 64) as i32 - 32) as u8;+ for row in 0..h / 2 {+ let dst = unsafe { std::slice::from_raw_parts_mut(uv_base.add(row * uv_stride), w) };+ for (i, p) in dst.iter_mut().enumerate() {+ *p = if i % 2 == 0 { u_val } else { v_val };+ }+ }+ }+ }+ sink(VideoTick::Frame(CapturedFrame { pixel_buffer: pb, width, height, capture_us: unix_micros() }));+ }+ Err(e) => tracing::warn!("[omnidisc-media] synthetic CVPixelBufferCreate failed: {e}"),+ }+ n += 1;+ next += interval;+ let now = Instant::now();+ if next > now {+ std::thread::sleep(next - now);+ } else if now - next > Duration::from_millis(200) {+ next = now;+ }+ }+ })+ .map_err(|e| StreamError::Capture(format!("synthetic thread: {e}")))?;+ Ok((+ VideoCapture { stream: None, _synthetic: Some(SyntheticSource { stop, thread: Some(thread) }) },+ CaptureGeometry { width, height, fps },+ ))+}++pub struct Platform;++impl CaptureApi for Platform {+ fn list_sources(thumbnails: bool) -> Result<StreamSources, StreamError> {+ let content = shareable()?;+ let displays: Vec<StreamSource> =+ content.displays().iter().enumerate().map(|(i, d)| display_source(&content, d, i, thumbnails)).collect();+ if displays.is_empty() {+ return Err(StreamError::Permission);+ }+ let mut windows: Vec<StreamSource> = Vec::new();+ for w in content.windows() {+ let thumbs = thumbnails && windows.len() < 16;+ if let Some(src) = window_source(&w, thumbs) {+ windows.push(src);+ }+ if windows.len() >= 40 {+ break;+ }+ }+ let own_pid = std::process::id() as i32;+ let mut app_pids: Vec<i32> = content+ .windows()+ .iter()+ .filter(|w| w.is_on_screen() && w.window_layer() == 0)+ .filter_map(|w| w.owning_application().map(|a| a.process_id()))+ .collect();+ app_pids.sort_unstable();+ app_pids.dedup();+ let apps: Vec<AudioApp> = content+ .applications()+ .into_iter()+ .filter(|a| a.process_id() != own_pid && !a.bundle_identifier().is_empty() && app_pids.contains(&a.process_id()))+ .map(|a| AudioApp { pid: a.process_id(), name: a.application_name(), bundle_id: a.bundle_identifier() })+ .collect();+ Ok(StreamSources { displays, windows, apps, app_audio_supported: true, system_audio_supported: true })+ }++ fn start_video(opts: &CaptureOptions, sink: VideoSink) -> Result<(VideoCapture, CaptureGeometry), StreamError> {+ if let SourceId::Synthetic { width, height } = opts.source {+ return start_synthetic(width, height, opts.fps, sink);+ }+ let content = shareable()?;+ let me = own_app(&content);+ let (filter, native_w, native_h) = match opts.source {+ SourceId::Display { id } => {+ let d = content.displays().into_iter().find(|d| d.display_id() == id).ok_or(StreamError::SourceGone)?;+ let filter = match &me {+ Some(app) => SCContentFilter::create().with_display(&d).with_excluding_applications(&[app], &[]).build(),+ None => SCContentFilter::create().with_display(&d).with_excluding_windows(&[]).build(),+ };+ (filter, d.width(), d.height())+ }+ SourceId::Window { id } => {+ let w = content.windows().into_iter().find(|w| w.window_id() == id).ok_or(StreamError::SourceGone)?;+ let filter = SCContentFilter::create().with_window(&w).build();+ let frame = w.frame();+ let (pw, ph) = SCShareableContentInfo::for_filter(&filter)+ .map(|i| i.pixel_size())+ .filter(|(a, b)| *a > 0 && *b > 0)+ .unwrap_or((frame.size.width as u32 * 2, frame.size.height as u32 * 2));+ (filter, pw, ph)+ }+ SourceId::Synthetic { .. } => return Err(StreamError::Unsupported),+ };+ let (width, height) = resolve_geometry(native_w, native_h, opts.height);+ let config = SCStreamConfiguration::new()+ .with_width(width)+ .with_height(height)+ .with_pixel_format(PixelFormat::YCbCr_420v)+ .with_shows_cursor(opts.cursor)+ .with_queue_depth(6)+ .with_minimum_frame_interval(&CMTime::new(1, opts.fps.max(1) as i32));+ let mut stream = SCStream::new(&filter, &config);+ stream.add_output_handler(video_handler(sink), SCStreamOutputType::Screen);+ stream.start_capture().map_err(map_sc_error)?;+ Ok((VideoCapture { stream: Some(stream), _synthetic: None }, CaptureGeometry { width, height, fps: opts.fps }))+ }++ fn start_audio(mode: AudioMode, sink: AudioSink) -> Result<(AudioCapture, AudioMode), StreamError> {+ if mode == AudioMode::None {+ return Ok((AudioCapture { stream: None }, AudioMode::None));+ }+ let content = shareable()?;+ let Some(display) = content.displays().into_iter().next() else {+ return Err(StreamError::Permission);+ };+ let mut attempt = mode;+ loop {+ let (filter, exclude_self) = match attempt {+ AudioMode::App { pid } => match content.applications().into_iter().find(|a| a.process_id() == pid) {+ Some(app) => {+ (SCContentFilter::create().with_display(&display).with_including_applications(&[&app], &[]).build(), false)+ }+ None => {+ tracing::warn!("[omnidisc-media] audio app pid {pid} is not shareable; falling back to system audio");+ attempt = AudioMode::System;+ continue;+ }+ },+ AudioMode::System => (SCContentFilter::create().with_display(&display).with_excluding_windows(&[]).build(), true),+ AudioMode::None => return Ok((AudioCapture { stream: None }, AudioMode::None)),+ };+ let config = SCStreamConfiguration::new()+ .with_width(2)+ .with_height(2)+ .with_minimum_frame_interval(&CMTime::new(1, 1))+ .with_captures_audio(true)+ .with_sample_rate(super::AUDIO_SAMPLE_RATE as i32)+ .with_channel_count(super::AUDIO_CHANNELS as i32)+ .with_excludes_current_process_audio(exclude_self);+ let mut stream = SCStream::new(&filter, &config);+ stream.add_output_handler(audio_handler(sink.clone()), SCStreamOutputType::Audio);+ match stream.start_capture() {+ Ok(()) => return Ok((AudioCapture { stream: Some(stream) }, attempt)),+ Err(e) => {+ tracing::warn!("[omnidisc-media] audio capture {:?} failed: {e}", attempt);+ attempt = match attempt {+ AudioMode::App { .. } => AudioMode::System,+ _ => return Ok((AudioCapture { stream: None }, AudioMode::None)),+ };+ }+ }+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/capture/mod.rs b/src-tauri/omnidisc-media/src/capture/mod.rsnew file mode 100644index 00000000..077ca244--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/mod.rs@@ -0,0 +1,63 @@+use crate::stream::{AudioMode, SourceId, StreamError, StreamSources};+use std::sync::Arc;++#[cfg(target_os = "macos")]+mod macos;+#[cfg(target_os = "macos")]+pub use macos::*;++#[cfg(not(target_os = "macos"))]+mod stub;+#[cfg(not(target_os = "macos"))]+pub use stub::*;++#[derive(Debug, Clone)]+pub struct CaptureOptions {+ pub source: SourceId,+ pub fps: u16,+ pub height: Option<u16>,+ pub cursor: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct CaptureGeometry {+ pub width: u32,+ pub height: u32,+ pub fps: u16,+}++pub enum VideoTick {+ Frame(CapturedFrame),+ Idle,+}++pub type VideoSink = Arc<dyn Fn(VideoTick) + Send + Sync>;+pub type AudioSink = Arc<dyn Fn(&[f32]) + Send + Sync>;++pub const AUDIO_SAMPLE_RATE: u32 = 48_000;+pub const AUDIO_CHANNELS: u32 = 2;++pub fn unix_micros() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_micros() as i64)+ .unwrap_or(0)+}++pub trait CaptureApi {+ fn list_sources(thumbnails: bool) -> Result<StreamSources, StreamError>;+ fn start_video(opts: &CaptureOptions, sink: VideoSink) -> Result<(VideoCapture, CaptureGeometry), StreamError>;+ fn start_audio(mode: AudioMode, sink: AudioSink) -> Result<(AudioCapture, AudioMode), StreamError>;+}++pub fn list_sources(thumbnails: bool) -> Result<StreamSources, StreamError> {+ Platform::list_sources(thumbnails)+}++pub fn start_video(opts: &CaptureOptions, sink: VideoSink) -> Result<(VideoCapture, CaptureGeometry), StreamError> {+ Platform::start_video(opts, sink)+}++pub fn start_audio(mode: AudioMode, sink: AudioSink) -> Result<(AudioCapture, AudioMode), StreamError> {+ Platform::start_audio(mode, sink)+}diff --git a/src-tauri/omnidisc-media/src/capture/stub.rs b/src-tauri/omnidisc-media/src/capture/stub.rsnew file mode 100644index 00000000..51a4fbd3--- /dev/null+++ b/src-tauri/omnidisc-media/src/capture/stub.rs@@ -0,0 +1,53 @@+use super::{AudioSink, CaptureApi, CaptureGeometry, CaptureOptions, VideoSink};+use crate::stream::{AudioMode, StreamError, StreamSources};++pub struct CapturedFrame {+ pub width: u32,+ pub height: u32,+ pub capture_us: i64,+}++impl CapturedFrame {+ pub fn width(&self) -> u32 {+ self.width+ }++ pub fn height(&self) -> u32 {+ self.height+ }++ pub fn capture_us(&self) -> i64 {+ self.capture_us+ }+}++pub struct VideoCapture;++impl VideoCapture {+ pub fn stop(self) {}+}+pub struct AudioCapture;++impl AudioCapture {+ pub fn stop(self) {}+}++pub struct Platform;++impl CaptureApi for Platform {+ fn list_sources(_thumbnails: bool) -> Result<StreamSources, StreamError> {+ Err(StreamError::Unsupported)+ }++ fn start_video(_opts: &CaptureOptions, _sink: VideoSink) -> Result<(VideoCapture, CaptureGeometry), StreamError> {+ Err(StreamError::Unsupported)+ }++ fn start_audio(mode: AudioMode, _sink: AudioSink) -> Result<(AudioCapture, AudioMode), StreamError> {+ if mode == AudioMode::None {+ Ok((AudioCapture, AudioMode::None))+ } else {+ Err(StreamError::Unsupported)+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/e2ee.rs b/src-tauri/omnidisc-media/src/e2ee.rsnew file mode 100644index 00000000..6d09f28d--- /dev/null+++ b/src-tauri/omnidisc-media/src/e2ee.rs@@ -0,0 +1,178 @@+//! Room key plumbing for voice E2EE (ADR 0014, spike S-05).+//!+//! The key itself is derived by the MLS layer — this module only carries it to+//! the SFU's frame cryptor and keeps the key-ring index in sync with the MLS+//! epoch. It is deliberately transport-free so the epoch → `set_shared_key`+//! step can be tested without a LiveKit room.++use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex as StdMutex};++/// LiveKit's default key ring holds 16 keys; the index travels in the SFrame+/// trailer, so a receiver that has not merged the newest MLS commit yet still+/// decodes the previous epoch's frames.+pub const KEY_RING_SIZE: u64 = 16;++/// The room key for one MLS epoch. `Debug` is hand-written so key material can+/// never reach a log line.+#[derive(Clone, Copy, PartialEq, Eq)]+pub struct RoomKey {+ pub epoch: u64,+ pub key: [u8; 32],+}++impl RoomKey {+ pub fn new(epoch: u64, key: [u8; 32]) -> Self {+ Self { epoch, key }+ }++ pub fn ring_index(&self) -> i32 {+ (self.epoch % KEY_RING_SIZE) as i32+ }+}++impl std::fmt::Debug for RoomKey {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("RoomKey").field("epoch", &self.epoch).finish_non_exhaustive()+ }+}++/// Whatever holds the shared key for the media path. LiveKit's `KeyProvider` is+/// the real one; tests use a recorder.+pub trait KeyRing: Send + Sync {+ fn set_shared_key(&self, key: &[u8], index: i32);+}++/// Applies MLS epochs to a key ring, exactly once per epoch.+#[derive(Default)]+pub struct KeyRotation {+ ring: StdMutex<Option<Arc<dyn KeyRing>>>,+ epoch: AtomicU64,+ armed: AtomicBool,+}++impl KeyRotation {+ pub fn new() -> Self {+ Self::default()+ }++ /// Bind a ring and push the first key. Called once per connection.+ pub fn arm(&self, ring: Arc<dyn KeyRing>, first: RoomKey) {+ if let Ok(mut slot) = self.ring.lock() {+ *slot = Some(ring.clone());+ }+ self.epoch.store(first.epoch, Ordering::Release);+ self.armed.store(true, Ordering::Release);+ ring.set_shared_key(&first.key, first.ring_index());+ }++ pub fn disarm(&self) {+ self.armed.store(false, Ordering::Release);+ if let Ok(mut slot) = self.ring.lock() {+ *slot = None;+ }+ }++ pub fn is_armed(&self) -> bool {+ self.armed.load(Ordering::Acquire)+ }++ pub fn epoch(&self) -> Option<u64> {+ self.is_armed().then(|| self.epoch.load(Ordering::Acquire))+ }++ /// Push a new epoch's key. Returns `true` when the ring was actually+ /// written — a repeated epoch is a no-op, and an unarmed rotation (no E2EE+ /// on this room) never writes.+ pub fn apply(&self, next: RoomKey) -> bool {+ if !self.is_armed() {+ return false;+ }+ if self.epoch.load(Ordering::Acquire) == next.epoch {+ return false;+ }+ let ring = match self.ring.lock() {+ Ok(slot) => slot.clone(),+ Err(_) => None,+ };+ let Some(ring) = ring else { return false };+ self.epoch.store(next.epoch, Ordering::Release);+ ring.set_shared_key(&next.key, next.ring_index());+ true+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[derive(Default)]+ struct Recorder {+ calls: StdMutex<Vec<(i32, [u8; 32])>>,+ }++ impl Recorder {+ fn calls(&self) -> Vec<(i32, [u8; 32])> {+ self.calls.lock().map(|c| c.clone()).unwrap_or_default()+ }+ }++ impl KeyRing for Recorder {+ fn set_shared_key(&self, key: &[u8], index: i32) {+ let mut fixed = [0u8; 32];+ fixed[..key.len().min(32)].copy_from_slice(&key[..key.len().min(32)]);+ if let Ok(mut c) = self.calls.lock() {+ c.push((index, fixed));+ }+ }+ }++ fn key(byte: u8) -> [u8; 32] {+ [byte; 32]+ }++ #[test]+ fn arming_pushes_the_first_key_at_the_epochs_ring_index() {+ let recorder = Arc::new(Recorder::default());+ let rotation = KeyRotation::new();+ rotation.arm(recorder.clone(), RoomKey::new(3, key(1)));+ assert_eq!(recorder.calls(), vec![(3, key(1))]);+ assert_eq!(rotation.epoch(), Some(3));+ }++ #[test]+ fn every_epoch_change_writes_once_and_wraps_the_ring() {+ let recorder = Arc::new(Recorder::default());+ let rotation = KeyRotation::new();+ rotation.arm(recorder.clone(), RoomKey::new(15, key(1)));+ assert!(rotation.apply(RoomKey::new(16, key(2))));+ assert!(!rotation.apply(RoomKey::new(16, key(2))), "the same epoch must not rewrite the ring");+ assert!(rotation.apply(RoomKey::new(17, key(3))));+ assert_eq!(recorder.calls(), vec![(15, key(1)), (0, key(2)), (1, key(3))]);+ }++ #[test]+ fn an_unarmed_rotation_never_touches_the_ring() {+ let rotation = KeyRotation::new();+ assert!(!rotation.is_armed());+ assert!(!rotation.apply(RoomKey::new(1, key(9))));+ assert_eq!(rotation.epoch(), None);+ }++ #[test]+ fn disarming_stops_further_writes() {+ let recorder = Arc::new(Recorder::default());+ let rotation = KeyRotation::new();+ rotation.arm(recorder.clone(), RoomKey::new(0, key(1)));+ rotation.disarm();+ assert!(!rotation.apply(RoomKey::new(1, key(2))));+ assert_eq!(recorder.calls().len(), 1);+ }++ #[test]+ fn the_debug_output_never_carries_key_material() {+ let printed = format!("{:?}", RoomKey::new(7, key(0xAB)));+ assert!(printed.contains('7'));+ assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab"), "{printed}");+ }+}diff --git a/src-tauri/omnidisc-media/src/encode/mod.rs b/src-tauri/omnidisc-media/src/encode/mod.rsnew file mode 100644index 00000000..420ce2a9--- /dev/null+++ b/src-tauri/omnidisc-media/src/encode/mod.rs@@ -0,0 +1,45 @@+use crate::stream::{StreamCodec, StreamMode};+use std::sync::atomic::{AtomicU64, Ordering};++#[cfg(target_os = "macos")]+mod videotoolbox;+#[cfg(target_os = "macos")]+pub use videotoolbox::VideoEncoder;++#[cfg(not(target_os = "macos"))]+mod stub;+#[cfg(not(target_os = "macos"))]+pub use stub::VideoEncoder;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct EncoderConfig {+ pub width: u32,+ pub height: u32,+ pub fps: u16,+ pub codec: StreamCodec,+ pub bitrate_kbps: u32,+ pub mode: StreamMode,+}++#[derive(Default, Debug)]+pub struct EncoderCounters {+ pub submitted: AtomicU64,+ pub encoded: AtomicU64,+ pub keyframes: AtomicU64,+ pub dropped: AtomicU64,+ pub errors: AtomicU64,+ pub bytes: AtomicU64,+ pub latency_ns_sum: AtomicU64,+ pub latency_ns_max: AtomicU64,+ pub applied_bps: AtomicU64,+ pub rate_requests: AtomicU64,+ pub keyframe_requests: AtomicU64,+ pub captured_ok: AtomicU64,+ pub captured_rejected: AtomicU64,+}++impl EncoderCounters {+ pub fn applied_kbps(&self) -> f64 {+ self.applied_bps.load(Ordering::Relaxed) as f64 / 1000.0+ }+}diff --git a/src-tauri/omnidisc-media/src/encode/stub.rs b/src-tauri/omnidisc-media/src/encode/stub.rsnew file mode 100644index 00000000..b9ffc5d4--- /dev/null+++ b/src-tauri/omnidisc-media/src/encode/stub.rs@@ -0,0 +1,31 @@+use super::{EncoderConfig, EncoderCounters};+use crate::capture::CapturedFrame;+use crate::stream::StreamError;+use livekit::webrtc::video_source::native::NativeVideoSource;+use std::sync::Arc;++pub struct VideoEncoder;++impl VideoEncoder {+ pub fn new(_cfg: EncoderConfig, _source: NativeVideoSource, _counters: Arc<EncoderCounters>) -> Result<Self, StreamError> {+ Err(StreamError::Unsupported)+ }++ pub fn encode(&self, _frame: &CapturedFrame, _force_key: bool) -> Result<(), StreamError> {+ Err(StreamError::Unsupported)+ }++ pub fn set_bitrate(&self, _bps: u64) {}++ pub fn set_framerate(&self, _fps: u16) {}++ pub fn hardware(&self) -> Option<bool> {+ None+ }++ pub fn name(&self) -> &'static str {+ "none"+ }++ pub fn finish(&self) {}+}diff --git a/src-tauri/omnidisc-media/src/encode/videotoolbox.rs b/src-tauri/omnidisc-media/src/encode/videotoolbox.rsnew file mode 100644index 00000000..cf68df01--- /dev/null+++ b/src-tauri/omnidisc-media/src/encode/videotoolbox.rs@@ -0,0 +1,382 @@+use super::{EncoderConfig, EncoderCounters};+use crate::capture::CapturedFrame;+use crate::stream::{StreamCodec, StreamError, StreamMode};+use livekit::webrtc::video_frame::{EncodedFrameType, EncodedVideoCodec, EncodedVideoFrame};+use livekit::webrtc::video_source::{native::NativeVideoSource, VideoResolution};+use objc2_core_foundation::{CFArray, CFBoolean, CFDictionary, CFNumber, CFRetained, CFString, CFType};+use objc2_core_media::{+ kCMSampleAttachmentKey_NotSync, kCMVideoCodecType_H264, kCMVideoCodecType_HEVC, CMSampleBuffer, CMTime, CMTimeFlags,+ CMVideoFormatDescriptionGetH264ParameterSetAtIndex, CMVideoFormatDescriptionGetHEVCParameterSetAtIndex,+};+use objc2_core_video::{+ kCVPixelBufferHeightKey, kCVPixelBufferIOSurfacePropertiesKey, kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey,+ kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, CVPixelBuffer,+};+use objc2_video_toolbox::{+ kVTCompressionPropertyKey_AllowFrameReordering, kVTCompressionPropertyKey_AverageBitRate,+ kVTCompressionPropertyKey_DataRateLimits, kVTCompressionPropertyKey_ExpectedFrameRate,+ kVTCompressionPropertyKey_H264EntropyMode, kVTCompressionPropertyKey_MaxKeyFrameInterval,+ kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality, kVTCompressionPropertyKey_ProfileLevel,+ kVTCompressionPropertyKey_RealTime, kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,+ kVTEncodeFrameOptionKey_ForceKeyFrame, kVTH264EntropyMode_CABAC, kVTProfileLevel_H264_High_AutoLevel,+ kVTProfileLevel_HEVC_Main_AutoLevel, kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,+ VTCompressionSession, VTEncodeInfoFlags, VTSessionCopyProperty, VTSessionSetProperty,+};+use std::ffi::c_void;+use std::ptr::{null_mut, NonNull};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Instant;++const KEYFRAME_INTERVAL: i32 = 240;++struct FrameCtx {+ submit: Instant,+ capture_us: i64,+}++struct Shared {+ codec: StreamCodec,+ width: u32,+ height: u32,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ param_sets: Mutex<Vec<Vec<u8>>>,+}++fn keyframe_of(sample: &CMSampleBuffer) -> bool {+ unsafe {+ let Some(attachments) = sample.sample_attachments_array(false) else { return true };+ let arr: &CFArray = &attachments;+ if arr.len() == 0 {+ return true;+ }+ let dict_ptr = arr.value_at_index(0) as *const CFDictionary;+ if dict_ptr.is_null() {+ return true;+ }+ let dict: &CFDictionary = &*dict_ptr;+ let key: &CFString = kCMSampleAttachmentKey_NotSync;+ let v = dict.value(key as *const CFString as *const c_void);+ if v.is_null() {+ return true;+ }+ let b: &CFBoolean = &*(v as *const CFBoolean);+ !b.value()+ }+}++unsafe fn parameter_sets(shared: &Shared, sample: &CMSampleBuffer) -> (Vec<Vec<u8>>, usize) {+ let mut sets: Vec<Vec<u8>> = Vec::new();+ let mut nal_len_size = 4usize;+ let Some(fd) = sample.format_description() else { return (sets, nal_len_size) };+ let mut count: usize = 0;+ let mut idx = 0usize;+ loop {+ let mut ptr: *const u8 = std::ptr::null();+ let mut size: usize = 0;+ let mut hdr_len: std::ffi::c_int = 4;+ let st = match shared.codec {+ StreamCodec::H264 => CMVideoFormatDescriptionGetH264ParameterSetAtIndex(&fd, idx, &mut ptr, &mut size, &mut count, &mut hdr_len),+ StreamCodec::H265 => CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(&fd, idx, &mut ptr, &mut size, &mut count, &mut hdr_len),+ };+ if st != 0 || ptr.is_null() {+ break;+ }+ nal_len_size = hdr_len as usize;+ sets.push(std::slice::from_raw_parts(ptr, size).to_vec());+ idx += 1;+ if idx >= count {+ break;+ }+ }+ (sets, nal_len_size)+}++unsafe extern "C-unwind" fn vt_output_callback(+ refcon: *mut c_void,+ frame_refcon: *mut c_void,+ status: i32,+ flags: VTEncodeInfoFlags,+ sample: *mut CMSampleBuffer,+) {+ if refcon.is_null() {+ return;+ }+ let shared: &Shared = &*(refcon as *const Shared);+ let ctx: Option<Box<FrameCtx>> = if frame_refcon.is_null() { None } else { Some(Box::from_raw(frame_refcon as *mut FrameCtx)) };+ let now = Instant::now();+ if status != 0 {+ shared.counters.errors.fetch_add(1, Ordering::Relaxed);+ return;+ }+ if flags.contains(VTEncodeInfoFlags::FrameDropped) || sample.is_null() {+ shared.counters.dropped.fetch_add(1, Ordering::Relaxed);+ return;+ }+ let sample: &CMSampleBuffer = &*sample;+ let capture_us = ctx.as_ref().map(|c| c.capture_us).unwrap_or(0);+ if let Some(c) = ctx.as_ref() {+ let latency = now.duration_since(c.submit).as_nanos() as u64;+ shared.counters.latency_ns_sum.fetch_add(latency, Ordering::Relaxed);+ shared.counters.latency_ns_max.fetch_max(latency, Ordering::Relaxed);+ }++ let keyframe = keyframe_of(sample);+ let Some(block) = sample.data_buffer() else {+ shared.counters.errors.fetch_add(1, Ordering::Relaxed);+ return;+ };+ let total = block.data_length();+ let mut avcc = vec![0u8; total];+ let Some(dst) = NonNull::new(avcc.as_mut_ptr() as *mut c_void) else { return };+ if block.copy_data_bytes(0, total, dst) != 0 {+ shared.counters.errors.fetch_add(1, Ordering::Relaxed);+ return;+ }++ let mut nal_len_size = 4usize;+ if keyframe {+ let (sets, len) = parameter_sets(shared, sample);+ nal_len_size = len;+ if !sets.is_empty() {+ if let Ok(mut ps) = shared.param_sets.lock() {+ *ps = sets;+ }+ }+ }++ let mut annexb: Vec<u8> = Vec::with_capacity(total + 128);+ if keyframe {+ if let Ok(ps) = shared.param_sets.lock() {+ for s in ps.iter() {+ annexb.extend_from_slice(&[0, 0, 0, 1]);+ annexb.extend_from_slice(s);+ }+ }+ }+ let mut off = 0usize;+ while off + nal_len_size <= avcc.len() {+ let mut len = 0usize;+ for i in 0..nal_len_size {+ len = (len << 8) | avcc[off + i] as usize;+ }+ off += nal_len_size;+ if off + len > avcc.len() {+ shared.counters.errors.fetch_add(1, Ordering::Relaxed);+ return;+ }+ annexb.extend_from_slice(&[0, 0, 0, 1]);+ annexb.extend_from_slice(&avcc[off..off + len]);+ off += len;+ }++ shared.counters.encoded.fetch_add(1, Ordering::Relaxed);+ shared.counters.bytes.fetch_add(annexb.len() as u64, Ordering::Relaxed);+ if keyframe {+ shared.counters.keyframes.fetch_add(1, Ordering::Relaxed);+ }+ let frame = EncodedVideoFrame {+ codec: match shared.codec {+ StreamCodec::H264 => EncodedVideoCodec::H264,+ StreamCodec::H265 => EncodedVideoCodec::H265,+ },+ payload: &annexb,+ timestamp_us: capture_us,+ frame_type: if keyframe { EncodedFrameType::Key } else { EncodedFrameType::Delta },+ resolution: VideoResolution { width: shared.width, height: shared.height },+ frame_metadata: None,+ };+ if shared.source.capture_encoded_frame(&frame) {+ shared.counters.captured_ok.fetch_add(1, Ordering::Relaxed);+ } else {+ shared.counters.captured_rejected.fetch_add(1, Ordering::Relaxed);+ }+}++pub struct VideoEncoder {+ session: CFRetained<VTCompressionSession>,+ shared: Arc<Shared>,+ hw: Option<bool>,+ start: Instant,+ counters: Arc<EncoderCounters>,+ finished: AtomicBool,+}++unsafe impl Send for VideoEncoder {}+unsafe impl Sync for VideoEncoder {}++fn set_prop(session: &VTCompressionSession, key: &CFString, value: &CFType) -> i32 {+ unsafe { VTSessionSetProperty(session, key, Some(value)) }+}++fn data_rate_limits(bps: u64) -> CFRetained<CFArray<CFNumber>> {+ let bytes_per_sec = CFNumber::new_i64((bps / 8 * 3 / 2) as i64);+ let one_sec = CFNumber::new_f64(1.0);+ CFArray::<CFNumber>::from_retained_objects(&[bytes_per_sec, one_sec])+}++impl VideoEncoder {+ pub fn new(cfg: EncoderConfig, source: NativeVideoSource, counters: Arc<EncoderCounters>) -> Result<Self, StreamError> {+ let shared = Arc::new(Shared {+ codec: cfg.codec,+ width: cfg.width,+ height: cfg.height,+ source,+ counters: counters.clone(),+ param_sets: Mutex::new(Vec::new()),+ });+ let truthy: &CFType = CFBoolean::new(true);+ let falsy: &CFType = CFBoolean::new(false);+ let spec_keys: [&CFString; 1] = [unsafe { kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder }];+ let spec = CFDictionary::<CFString, CFType>::from_slices(&spec_keys, &[truthy]);+ let fmt = CFNumber::new_i32(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange as i32);+ let w = CFNumber::new_i32(cfg.width as i32);+ let h = CFNumber::new_i32(cfg.height as i32);+ let iosurface = CFDictionary::<CFString, CFType>::from_slices(&[], &[]);+ let iosurface_ref: &CFType = iosurface.as_opaque();+ let src_keys: [&CFString; 4] =+ unsafe { [kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey, kCVPixelBufferHeightKey, kCVPixelBufferIOSurfacePropertiesKey] };+ let src_vals: [&CFType; 4] = [&fmt, &w, &h, iosurface_ref];+ let src_attrs = CFDictionary::<CFString, CFType>::from_slices(&src_keys, &src_vals);++ let shared_ptr = Arc::as_ptr(&shared) as *mut c_void;+ let mut raw: *mut VTCompressionSession = null_mut();+ let status = unsafe {+ VTCompressionSession::create(+ None,+ cfg.width as i32,+ cfg.height as i32,+ match cfg.codec {+ StreamCodec::H264 => kCMVideoCodecType_H264,+ StreamCodec::H265 => kCMVideoCodecType_HEVC,+ },+ Some(spec.as_opaque()),+ Some(src_attrs.as_opaque()),+ None,+ Some(vt_output_callback),+ shared_ptr,+ NonNull::from(&mut raw),+ )+ };+ if status != 0 || raw.is_null() {+ return Err(StreamError::Encoder(format!("VTCompressionSessionCreate failed ({status}); the hardware encoder may be unavailable")));+ }+ let session = unsafe { CFRetained::from_raw(NonNull::new_unchecked(raw)) };+ let bps = cfg.bitrate_kbps as u64 * 1000;+ unsafe {+ set_prop(&session, kVTCompressionPropertyKey_RealTime, truthy);+ set_prop(+ &session,+ kVTCompressionPropertyKey_ProfileLevel,+ match cfg.codec {+ StreamCodec::H264 => kVTProfileLevel_H264_High_AutoLevel,+ StreamCodec::H265 => kVTProfileLevel_HEVC_Main_AutoLevel,+ },+ );+ set_prop(&session, kVTCompressionPropertyKey_AllowFrameReordering, falsy);+ let fps = CFNumber::new_f64(cfg.fps as f64);+ set_prop(&session, kVTCompressionPropertyKey_ExpectedFrameRate, &fps);+ let br = CFNumber::new_i64(bps as i64);+ set_prop(&session, kVTCompressionPropertyKey_AverageBitRate, &br);+ set_prop(&session, kVTCompressionPropertyKey_DataRateLimits, data_rate_limits(bps).as_opaque());+ let keyint = CFNumber::new_i32(KEYFRAME_INTERVAL);+ set_prop(&session, kVTCompressionPropertyKey_MaxKeyFrameInterval, &keyint);+ if cfg.codec == StreamCodec::H264 {+ set_prop(&session, kVTCompressionPropertyKey_H264EntropyMode, kVTH264EntropyMode_CABAC);+ }+ if cfg.mode == StreamMode::Game {+ set_prop(&session, kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality, truthy);+ }+ }+ let st = unsafe { session.prepare_to_encode_frames() };+ if st != 0 {+ return Err(StreamError::Encoder(format!("VTCompressionSessionPrepareToEncodeFrames failed ({st})")));+ }+ let mut hw = None;+ unsafe {+ let mut out: *const CFType = std::ptr::null();+ let st = VTSessionCopyProperty(+ &session,+ kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,+ None,+ &mut out as *mut *const CFType as *mut c_void,+ );+ if st == 0 && !out.is_null() {+ let v = CFRetained::from_raw(NonNull::new_unchecked(out as *mut CFType));+ if let Some(b) = v.downcast_ref::<CFBoolean>() {+ hw = Some(b.value());+ }+ }+ }+ counters.applied_bps.store(bps, Ordering::Relaxed);+ Ok(Self { session, shared, hw, start: Instant::now(), counters, finished: AtomicBool::new(false) })+ }++ pub fn encode(&self, frame: &CapturedFrame, force_key: bool) -> Result<(), StreamError> {+ let pb_ptr = frame.as_raw() as *const CVPixelBuffer;+ if pb_ptr.is_null() {+ return Err(StreamError::Encoder("null pixel buffer".into()));+ }+ let pb: &CVPixelBuffer = unsafe { &*pb_ptr };+ let pts_us = self.start.elapsed().as_micros() as i64;+ let pts = CMTime { value: pts_us, timescale: 1_000_000, flags: CMTimeFlags::Valid, epoch: 0 };+ let dur = CMTime { value: 0, timescale: 1_000_000, flags: CMTimeFlags::empty(), epoch: 0 };+ let props = if force_key {+ let keys: [&CFString; 1] = [unsafe { kVTEncodeFrameOptionKey_ForceKeyFrame }];+ let truthy: &CFType = CFBoolean::new(true);+ Some(CFDictionary::<CFString, CFType>::from_slices(&keys, &[truthy]))+ } else {+ None+ };+ let ctx = Box::new(FrameCtx { submit: Instant::now(), capture_us: frame.capture_us() });+ let mut flags = VTEncodeInfoFlags::empty();+ let st = unsafe {+ self.session.encode_frame(pb, pts, dur, props.as_ref().map(|d| d.as_opaque()), Box::into_raw(ctx) as *mut c_void, &mut flags)+ };+ if st == 0 {+ self.counters.submitted.fetch_add(1, Ordering::Relaxed);+ Ok(())+ } else {+ self.counters.errors.fetch_add(1, Ordering::Relaxed);+ Err(StreamError::Encoder(format!("VTCompressionSessionEncodeFrame failed ({st})")))+ }+ }++ pub fn set_bitrate(&self, bps: u64) {+ let br = CFNumber::new_i64(bps as i64);+ set_prop(&self.session, unsafe { kVTCompressionPropertyKey_AverageBitRate }, &br);+ set_prop(&self.session, unsafe { kVTCompressionPropertyKey_DataRateLimits }, data_rate_limits(bps).as_opaque());+ self.counters.applied_bps.store(bps, Ordering::Relaxed);+ }++ pub fn set_framerate(&self, fps: u16) {+ let v = CFNumber::new_f64(fps as f64);+ set_prop(&self.session, unsafe { kVTCompressionPropertyKey_ExpectedFrameRate }, &v);+ }++ pub fn hardware(&self) -> Option<bool> {+ self.hw+ }++ pub fn name(&self) -> &'static str {+ "VideoToolbox"+ }++ pub fn finish(&self) {+ if self.finished.swap(true, Ordering::AcqRel) {+ return;+ }+ unsafe {+ self.session.complete_frames(CMTime { value: 0, timescale: 1, flags: CMTimeFlags::empty(), epoch: 0 });+ self.session.invalidate();+ }+ }+}++impl Drop for VideoEncoder {+ fn drop(&mut self) {+ self.finish();+ let _ = &self.shared;+ }+}diff --git a/src-tauri/omnidisc-media/src/engine.rs b/src-tauri/omnidisc-media/src/engine.rsnew file mode 100644index 00000000..59fc8834--- /dev/null+++ b/src-tauri/omnidisc-media/src/engine.rs@@ -0,0 +1,451 @@+use crate::audio::io::DeviceLoss;+use crate::audio::{AudioDevices, DeviceKind};+use crate::e2ee::RoomKey;+use crate::state::{VoiceEvent, VoiceState, VoiceStateMachine};+use async_trait::async_trait;+use futures::FutureExt;+use omnidisc_proto::gateway::VoiceServerUpdate;+use serde::{Deserialize, Serialize};+use std::future::Future;+use std::sync::Arc;+use tokio::sync::{broadcast, mpsc, Mutex};++#[derive(Debug, thiserror::Error)]+pub enum MediaError {+ #[error("backend unavailable: {0}")]+ Unavailable(String),+ #[error("connection failed: {0}")]+ Connection(String),+ #[error("device error: {0}")]+ Device(String),+ #[error("not connected")]+ NotConnected,+ #[error("media engine panicked")]+ Panicked,+}++impl MediaError {+ pub fn code(&self) -> &'static str {+ match self {+ Self::Unavailable(_) => "ERR_VOICE_UNAVAILABLE",+ Self::Connection(_) => "ERR_VOICE_UNREACHABLE",+ Self::Device(_) => "ERR_VOICE_NO_AUDIO_DEVICE",+ Self::NotConnected => "ERR_VOICE_NOT_CONNECTED",+ Self::Panicked => "ERR_VOICE_ENGINE_CRASHED",+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Quality {+ Excellent,+ Good,+ Poor,+ Lost,+}++/// Where an audio device ended up after it disappeared mid-call. The UI needs+/// the distinction: a device that came back on its own deserves a quiet note,+/// a mic that ended in `ListenOnly` deserves a loud one.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DeviceStatus {+ Lost,+ Recovered,+ SwitchedToDefault,+ ListenOnly,+ Silent,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum EngineNotification {+ State {+ state: VoiceState,+ #[serde(skip_serializing_if = "Option::is_none")]+ reason: Option<String>,+ },+ Speaking { user_id: String, speaking: bool },+ ParticipantJoined { user_id: String },+ ParticipantLeft { user_id: String },+ Quality { user_id: String, quality: Quality },+ Level { rms_db: f32, peak: f32 },+ Device {+ kind: DeviceKind,+ status: DeviceStatus,+ #[serde(skip_serializing_if = "Option::is_none")]+ cause: Option<DeviceLoss>,+ },+ Error { code: String, message: String },+}++#[derive(Debug)]+pub enum BackendEvent {+ Transport(VoiceEvent),+ Notify(EngineNotification),+}++#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]+pub struct VoiceStats {+ pub rtt_ms: Option<f64>,+ pub packet_loss: Option<f64>,+ pub jitter_ms: Option<f64>,+ pub bitrate_out_kbps: f64,+ pub bitrate_in_kbps: f64,+ pub participants: usize,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct AudioPrefs {+ pub input_device: Option<String>,+ pub output_device: Option<String>,+ pub noise_suppression: bool,+ pub ptt_enabled: bool,+ pub vad_threshold_db: Option<f32>,+ /// How much of everyone else's audio to duck while the local user speaks,+ /// 0–100 %. 0 is off, which is the default.+ #[serde(default)]+ pub ducking_percent: u8,+}++/// Everything about a connection that is not audio: the MLS room key when the+/// channel has a group, and the ICE policy.+#[derive(Debug, Clone, Default)]+pub struct ConnectOptions {+ pub room_key: Option<RoomKey>,+ /// Force every candidate through a TURN relay so peers never see the local+ /// IP. Useless without a TURN server in `VoiceServerUpdate.ice_servers`.+ pub relay_only: bool,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct ConnectOutcome {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mic_error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub output_error: Option<String>,+}++#[async_trait]+pub trait MediaBackend: Send + Sync {+ fn set_events(&self, tx: mpsc::UnboundedSender<BackendEvent>);+ async fn connect(+ &self,+ target: &VoiceServerUpdate,+ prefs: &AudioPrefs,+ options: &ConnectOptions,+ ) -> Result<ConnectOutcome, MediaError>;+ async fn disconnect(&self) -> Result<(), MediaError>;+ async fn set_muted(&self, muted: bool) -> Result<(), MediaError>;+ async fn set_deafened(&self, deafened: bool) -> Result<(), MediaError>;+ async fn set_participant_volume(&self, user_id: &str, gain: f32) -> Result<(), MediaError>;+ async fn set_master_volume(&self, gain: f32) -> Result<(), MediaError>;+ async fn set_device(&self, kind: DeviceKind, id: Option<String>) -> Result<(), MediaError>;+ async fn set_noise_suppression(&self, on: bool) -> Result<(), MediaError>;+ async fn set_ptt(&self, enabled: bool, pressed: bool) -> Result<(), MediaError>;+ async fn set_mic_monitor(&self, on: bool) -> Result<(), MediaError>;+ async fn set_ducking(&self, percent: u8) -> Result<(), MediaError>;+ /// Push the key of a new MLS epoch. A no-op when the room is not encrypted.+ async fn set_room_key(&self, key: RoomKey) -> Result<(), MediaError>;+ fn e2ee_epoch(&self) -> Option<u64>;+ async fn stats(&self) -> Result<VoiceStats, MediaError>;+ fn devices(&self) -> AudioDevices;+}++pub struct MediaEngine {+ backend: Arc<dyn MediaBackend>,+ machine: Mutex<VoiceStateMachine>,+ notify: broadcast::Sender<EngineNotification>,+ backend_rx: Mutex<Option<mpsc::UnboundedReceiver<BackendEvent>>>,+}++async fn guard<T>(fut: impl Future<Output = Result<T, MediaError>>) -> Result<T, MediaError> {+ match std::panic::AssertUnwindSafe(fut).catch_unwind().await {+ Ok(r) => r,+ Err(_) => {+ tracing::error!("[omnidisc-media] backend panicked");+ Err(MediaError::Panicked)+ }+ }+}++impl MediaEngine {+ pub fn new(backend: Arc<dyn MediaBackend>) -> Self {+ let (notify, _) = broadcast::channel(256);+ let (tx, rx) = mpsc::unbounded_channel();+ backend.set_events(tx);+ Self {+ backend,+ machine: Mutex::new(VoiceStateMachine::default()),+ notify,+ backend_rx: Mutex::new(Some(rx)),+ }+ }++ pub fn backend(&self) -> &Arc<dyn MediaBackend> {+ &self.backend+ }++ pub fn subscribe(&self) -> broadcast::Receiver<EngineNotification> {+ self.notify.subscribe()+ }++ pub async fn state(&self) -> VoiceState {+ self.machine.lock().await.state()+ }++ pub async fn pump(&self) {+ let rx = self.backend_rx.lock().await.take();+ let Some(mut rx) = rx else { return };+ while let Some(ev) = rx.recv().await {+ match ev {+ BackendEvent::Transport(t) => {+ let before = self.state().await;+ let after = self.transition(&t, None).await;+ if after == VoiceState::Failed && before != VoiceState::Failed {+ let _ = guard(self.backend.disconnect()).await;+ }+ }+ BackendEvent::Notify(n) => {+ let _ = self.notify.send(n);+ }+ }+ }+ }++ pub async fn join(+ &self,+ target: &VoiceServerUpdate,+ prefs: &AudioPrefs,+ options: &ConnectOptions,+ ) -> Result<ConnectOutcome, MediaError> {+ self.transition(&VoiceEvent::Join, None).await;+ match guard(self.backend.connect(target, prefs, options)).await {+ Ok(outcome) => {+ self.transition(&VoiceEvent::Connected, None).await;+ Ok(outcome)+ }+ Err(e) => {+ self.transition(&VoiceEvent::Disconnected { recoverable: false }, Some(e.code())).await;+ let _ = self.notify.send(EngineNotification::Error { code: e.code().into(), message: e.to_string() });+ let _ = guard(self.backend.disconnect()).await;+ Err(e)+ }+ }+ }++ pub async fn leave(&self) -> Result<VoiceState, MediaError> {+ let r = guard(self.backend.disconnect()).await;+ let s = self.transition(&VoiceEvent::Leave, None).await;+ r.map(|_| s)+ }++ pub async fn set_muted(&self, muted: bool) -> Result<(), MediaError> {+ guard(self.backend.set_muted(muted)).await+ }++ pub async fn set_deafened(&self, deafened: bool) -> Result<(), MediaError> {+ guard(self.backend.set_deafened(deafened)).await+ }++ pub async fn set_participant_volume(&self, user_id: &str, gain: f32) -> Result<(), MediaError> {+ guard(self.backend.set_participant_volume(user_id, gain)).await+ }++ pub async fn set_master_volume(&self, gain: f32) -> Result<(), MediaError> {+ guard(self.backend.set_master_volume(gain)).await+ }++ pub async fn set_device(&self, kind: DeviceKind, id: Option<String>) -> Result<(), MediaError> {+ guard(self.backend.set_device(kind, id)).await+ }++ pub async fn set_noise_suppression(&self, on: bool) -> Result<(), MediaError> {+ guard(self.backend.set_noise_suppression(on)).await+ }++ pub async fn set_ptt(&self, enabled: bool, pressed: bool) -> Result<(), MediaError> {+ guard(self.backend.set_ptt(enabled, pressed)).await+ }++ pub async fn set_mic_monitor(&self, on: bool) -> Result<(), MediaError> {+ guard(self.backend.set_mic_monitor(on)).await+ }++ pub async fn set_ducking(&self, percent: u8) -> Result<(), MediaError> {+ guard(self.backend.set_ducking(percent)).await+ }++ pub async fn set_room_key(&self, key: RoomKey) -> Result<(), MediaError> {+ guard(self.backend.set_room_key(key)).await+ }++ pub fn e2ee_epoch(&self) -> Option<u64> {+ self.backend.e2ee_epoch()+ }++ pub async fn stats(&self) -> Result<VoiceStats, MediaError> {+ guard(self.backend.stats()).await+ }++ pub fn devices(&self) -> AudioDevices {+ self.backend.devices()+ }++ async fn transition(&self, ev: &VoiceEvent, reason: Option<&str>) -> VoiceState {+ let s = self.machine.lock().await.apply(ev);+ let _ = self.notify.send(EngineNotification::State { state: s, reason: reason.map(str::to_string) });+ s+ }+}++pub struct NullBackend;++#[async_trait]+impl MediaBackend for NullBackend {+ fn set_events(&self, _: mpsc::UnboundedSender<BackendEvent>) {}+ async fn connect(+ &self,+ _: &VoiceServerUpdate,+ _: &AudioPrefs,+ _: &ConnectOptions,+ ) -> Result<ConnectOutcome, MediaError> {+ Err(MediaError::Unavailable("no media backend compiled in".into()))+ }+ async fn disconnect(&self) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_muted(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_deafened(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_participant_volume(&self, _: &str, _: f32) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_master_volume(&self, _: f32) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_device(&self, _: DeviceKind, _: Option<String>) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_noise_suppression(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_ptt(&self, _: bool, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_mic_monitor(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_ducking(&self, _: u8) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_room_key(&self, _: RoomKey) -> Result<(), MediaError> {+ Ok(())+ }+ fn e2ee_epoch(&self) -> Option<u64> {+ None+ }+ async fn stats(&self) -> Result<VoiceStats, MediaError> {+ Err(MediaError::NotConnected)+ }+ fn devices(&self) -> AudioDevices {+ AudioDevices::default()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use omnidisc_proto::Snowflake;++ struct PanickyBackend;++ #[async_trait]+ impl MediaBackend for PanickyBackend {+ fn set_events(&self, _: mpsc::UnboundedSender<BackendEvent>) {}+ async fn connect(+ &self,+ _: &VoiceServerUpdate,+ _: &AudioPrefs,+ _: &ConnectOptions,+ ) -> Result<ConnectOutcome, MediaError> {+ panic!("boom");+ }+ async fn disconnect(&self) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_muted(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_deafened(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_participant_volume(&self, _: &str, _: f32) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_master_volume(&self, _: f32) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_device(&self, _: DeviceKind, _: Option<String>) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_noise_suppression(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_ptt(&self, _: bool, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_mic_monitor(&self, _: bool) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_ducking(&self, _: u8) -> Result<(), MediaError> {+ Ok(())+ }+ async fn set_room_key(&self, _: RoomKey) -> Result<(), MediaError> {+ Ok(())+ }+ fn e2ee_epoch(&self) -> Option<u64> {+ None+ }+ async fn stats(&self) -> Result<VoiceStats, MediaError> {+ Err(MediaError::NotConnected)+ }+ fn devices(&self) -> AudioDevices {+ AudioDevices::default()+ }+ }++ fn target() -> VoiceServerUpdate {+ VoiceServerUpdate {+ guild_id: None,+ channel_id: Snowflake(1),+ endpoint: "ws://127.0.0.1:1".into(),+ token: "t".into(),+ room: "r".into(),+ ice_servers: vec![],+ }+ }++ #[tokio::test]+ async fn null_backend_join_fails_into_failed_state() {+ let engine = MediaEngine::new(Arc::new(NullBackend));+ let mut rx = engine.subscribe();+ assert!(engine.join(&target(), &AudioPrefs::default(), &ConnectOptions::default()).await.is_err());+ assert_eq!(engine.state().await, VoiceState::Failed);+ let first = rx.recv().await.unwrap();+ assert_eq!(first, EngineNotification::State { state: VoiceState::Connecting, reason: None });+ assert_eq!(engine.leave().await.unwrap(), VoiceState::Idle);+ }++ #[tokio::test]+ async fn panic_in_backend_is_contained() {+ let engine = MediaEngine::new(Arc::new(PanickyBackend));+ let err = engine.join(&target(), &AudioPrefs::default(), &ConnectOptions::default()).await.unwrap_err();+ assert!(matches!(err, MediaError::Panicked));+ assert_eq!(engine.state().await, VoiceState::Failed);+ }+}diff --git a/src-tauri/omnidisc-media/src/lib.rs b/src-tauri/omnidisc-media/src/lib.rsnew file mode 100644index 00000000..89db3583--- /dev/null+++ b/src-tauri/omnidisc-media/src/lib.rs@@ -0,0 +1,26 @@+pub mod audio;+pub mod capture;+pub mod e2ee;+pub mod encode;+pub mod engine;+pub mod livekit_backend;+pub mod state;+pub mod stream;+pub mod streaming;+pub mod tone;+pub mod viewer;++pub use audio::{AudioDevice, AudioDevices, DeviceKind};+pub use e2ee::{KeyRing, KeyRotation, RoomKey, KEY_RING_SIZE};+pub use engine::{+ AudioPrefs, BackendEvent, ConnectOptions, ConnectOutcome, DeviceStatus, EngineNotification, MediaBackend,+ MediaEngine, MediaError, NullBackend, Quality, VoiceStats,+};+pub use livekit_backend::{LiveKitBackend, RemoteVideo};+pub use state::{VoiceEvent, VoiceState, VoiceStateMachine};+pub use stream::{+ AudioApp, AudioMode, PublishStats, ResolvedStream, SourceId, StreamBadge, StreamCodec, StreamError, StreamMode,+ StreamRequest, StreamSource, StreamSources, StreamStats, Viewport, WatchStats,+};+pub use streaming::{start_stream, ActiveStream};+pub use viewer::Viewer;diff --git a/src-tauri/omnidisc-media/src/livekit_backend.rs b/src-tauri/omnidisc-media/src/livekit_backend.rsnew file mode 100644index 00000000..81c0a0b2--- /dev/null+++ b/src-tauri/omnidisc-media/src/livekit_backend.rs@@ -0,0 +1,968 @@+use crate::audio::{+ capture::{CaptureEvent, CaptureFlags, Feeder, FeederMsg, FRAME_SAMPLES, SAMPLE_RATE},+ devices,+ io::{classify_loss, AudioIo, AudioIoError, DeviceLoss, StreamFault},+ playback::{Mixer, MIX_RATE},+ AudioDevices, DeviceKind,+};+use crate::e2ee::{KeyRing, KeyRotation, RoomKey};+use crate::engine::{+ AudioPrefs, BackendEvent, ConnectOptions, ConnectOutcome, DeviceStatus, EngineNotification, MediaBackend,+ MediaError, Quality, VoiceStats,+};+use crate::state::VoiceEvent;+use crate::tone::ToneMeter;+use async_trait::async_trait;+use futures::StreamExt;+use livekit::e2ee::key_provider::{KeyProvider, KeyProviderOptions};+use livekit::e2ee::{E2eeOptions, EncryptionType};+use livekit::prelude::*;+use livekit::webrtc::audio_source::{native::NativeAudioSource, AudioSourceOptions, RtcAudioSource};+use livekit::webrtc::audio_stream::native::NativeAudioStream;+use livekit::webrtc::peer_connection_factory::{IceServer, IceTransportsType};+use livekit::webrtc::stats::RtcStats;+use livekit::options::TrackPublishOptions;+use livekit::{DisconnectReason, RoomEvent, RoomOptions};+use omnidisc_proto::gateway::VoiceServerUpdate;+use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex as StdMutex};+use std::time::{Duration, Instant};+use tokio::sync::{mpsc, Mutex};++const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);+const PTT_RELEASE_DELAY: Duration = Duration::from_millis(200);+const REMOTE_RING_SAMPLES: usize = MIX_RATE as usize;++struct Session {+ room: Arc<Room>,+ audio_track: LocalAudioTrack,+ remote_audio: Arc<StdMutex<HashMap<String, RemoteAudioTrack>>>,+ tasks: Vec<tokio::task::JoinHandle<()>>,+}++pub const SCREEN_AUDIO_SUFFIX: &str = "#screen";++#[derive(Clone)]+pub struct RemoteVideo {+ pub user_id: String,+ pub sid: String,+ pub track: RemoteVideoTrack,+}++struct Shared {+ events: StdMutex<Option<mpsc::UnboundedSender<BackendEvent>>>,+ flags: Arc<CaptureFlags>,+ mixer: Arc<Mixer>,+ feeder: Arc<Feeder>,+ io: AudioIo,+ session: Mutex<Option<Session>>,+ local_identity: StdMutex<Option<String>>,+ volumes: StdMutex<HashMap<String, f32>>,+ input_device: StdMutex<Option<String>>,+ output_device: StdMutex<Option<String>>,+ input_running: AtomicBool,+ output_running: AtomicBool,+ monitor: AtomicBool,+ ptt_generation: AtomicU64,+ last_stats: StdMutex<Option<(Instant, u64, u64)>>,+ remote_nonsilent_frames: AtomicU64,+ remote_tone: StdMutex<ToneMeter>,+ video_publications: StdMutex<HashMap<String, RemoteTrackPublication>>,+ remote_video: StdMutex<HashMap<String, RemoteVideo>>,+ rotation: KeyRotation,+ recovering_input: AtomicBool,+ recovering_output: AtomicBool,+}++/// LiveKit's frame cryptor behind the crate's transport-free `KeyRing` trait.+struct LiveKitRing(KeyProvider);++impl KeyRing for LiveKitRing {+ fn set_shared_key(&self, key: &[u8], index: i32) {+ self.0.set_shared_key(key.to_vec(), index);+ }+}++impl Shared {+ fn emit(&self, n: EngineNotification) {+ if let Ok(guard) = self.events.lock() {+ if let Some(tx) = guard.as_ref() {+ let _ = tx.send(BackendEvent::Notify(n));+ }+ }+ }++ fn transport(&self, ev: VoiceEvent) {+ if let Ok(guard) = self.events.lock() {+ if let Some(tx) = guard.as_ref() {+ let _ = tx.send(BackendEvent::Transport(ev));+ }+ }+ }++ fn local_identity(&self) -> Option<String> {+ self.local_identity.lock().ok().and_then(|g| g.clone())+ }++ fn volume_for(&self, user_id: &str) -> f32 {+ self.volumes.lock().ok().and_then(|v| v.get(user_id).copied()).unwrap_or(1.0)+ }++ fn input_device(&self) -> Option<String> {+ self.input_device.lock().ok().and_then(|d| d.clone())+ }++ fn output_device(&self) -> Option<String> {+ self.output_device.lock().ok().and_then(|d| d.clone())+ }++ fn ensure_input(&self) -> Result<(), AudioIoError> {+ if self.input_running.load(Ordering::Acquire) {+ return Ok(());+ }+ self.io.start_input(self.input_device())?;+ self.input_running.store(true, Ordering::Release);+ Ok(())+ }++ fn stop_input_if_idle(&self) {+ let in_call = self.session.try_lock().map(|s| s.is_some()).unwrap_or(true);+ if !in_call && !self.monitor.load(Ordering::Acquire) {+ self.io.stop_input();+ self.input_running.store(false, Ordering::Release);+ }+ }++ fn recovering(&self, kind: DeviceKind) -> &AtomicBool {+ match kind {+ DeviceKind::Input => &self.recovering_input,+ DeviceKind::Output => &self.recovering_output,+ }+ }++ fn in_call(&self) -> bool {+ self.session.try_lock().map(|s| s.is_some()).unwrap_or(true)+ }++ /// Is this device still worth re-opening? A mic is, while the call is up or+ /// the mic test is running; an output only while the call is up.+ fn still_wanted(&self, kind: DeviceKind) -> bool {+ match kind {+ DeviceKind::Input => self.in_call() || self.monitor.load(Ordering::Acquire),+ DeviceKind::Output => self.in_call(),+ }+ }++ fn ensure_output(&self) -> Result<(), AudioIoError> {+ if self.output_running.load(Ordering::Acquire) {+ return Ok(());+ }+ self.io.start_output(self.output_device())?;+ self.output_running.store(true, Ordering::Release);+ Ok(())+ }+}++pub struct LiveKitBackend {+ rt: Option<tokio::runtime::Runtime>,+ shared: Arc<Shared>,+}++impl Drop for LiveKitBackend {+ fn drop(&mut self) {+ if let Some(rt) = self.rt.take() {+ rt.shutdown_background();+ }+ }+}++fn map_io_error(e: &AudioIoError, kind: DeviceKind) -> String {+ match (e, kind) {+ (AudioIoError::PermissionDenied, DeviceKind::Input) => "ERR_VOICE_MIC_PERMISSION".into(),+ (AudioIoError::NoDevice, DeviceKind::Input) => "ERR_VOICE_NO_INPUT_DEVICE".into(),+ (AudioIoError::NoDevice, DeviceKind::Output) => "ERR_VOICE_NO_OUTPUT_DEVICE".into(),+ (AudioIoError::DeviceBusy, _) => "ERR_VOICE_DEVICE_BUSY".into(),+ (_, DeviceKind::Input) => "ERR_VOICE_MIC_FAILED".into(),+ (_, DeviceKind::Output) => "ERR_VOICE_OUTPUT_FAILED".into(),+ }+}++/// One device disappeared mid-call. Re-open the same device first, then the+/// system default, and only then give up — a USB mic that was yanked and put+/// back must not need a rejoin, and a permission the user revoked must not look+/// like a broken app.+fn recover(shared: &Arc<Shared>, kind: DeviceKind) {+ const BACKOFF_MS: [u64; 3] = [250, 1_000, 3_000];+ let wanted = match kind {+ DeviceKind::Input => shared.input_device(),+ DeviceKind::Output => shared.output_device(),+ };+ for (attempt, wait) in BACKOFF_MS.iter().enumerate() {+ std::thread::sleep(Duration::from_millis(*wait));+ if !shared.still_wanted(kind) {+ return;+ }+ let probe = match kind {+ DeviceKind::Input => shared.io.start_input(wanted.clone()),+ DeviceKind::Output => shared.io.start_output(wanted.clone()),+ };+ let error = match probe {+ Ok(()) => {+ match kind {+ DeviceKind::Input => shared.input_running.store(true, Ordering::Release),+ DeviceKind::Output => shared.output_running.store(true, Ordering::Release),+ }+ shared.emit(EngineNotification::Device { kind, status: DeviceStatus::Recovered, cause: None });+ return;+ }+ Err(e) => e,+ };+ let still_listed = wanted.as_deref().map(|id| devices::exists(kind, id)).unwrap_or(true);+ let cause = classify_loss(still_listed, &error);+ if cause == DeviceLoss::PermissionRevoked {+ give_up(shared, kind, cause);+ return;+ }+ if wanted.is_some() && cause == DeviceLoss::Unplugged {+ let fallback = match kind {+ DeviceKind::Input => shared.io.start_input(None),+ DeviceKind::Output => shared.io.start_output(None),+ };+ if fallback.is_ok() {+ match kind {+ DeviceKind::Input => {+ if let Ok(mut d) = shared.input_device.lock() {+ *d = None;+ }+ shared.input_running.store(true, Ordering::Release);+ }+ DeviceKind::Output => {+ if let Ok(mut d) = shared.output_device.lock() {+ *d = None;+ }+ shared.output_running.store(true, Ordering::Release);+ }+ }+ shared.emit(EngineNotification::Device {+ kind,+ status: DeviceStatus::SwitchedToDefault,+ cause: Some(cause),+ });+ return;+ }+ }+ if attempt + 1 == BACKOFF_MS.len() {+ give_up(shared, kind, cause);+ }+ }+}++fn give_up(shared: &Arc<Shared>, kind: DeviceKind, cause: DeviceLoss) {+ let status = match kind {+ DeviceKind::Input => {+ shared.io.stop_input();+ shared.input_running.store(false, Ordering::Release);+ DeviceStatus::ListenOnly+ }+ DeviceKind::Output => {+ shared.io.stop_output();+ shared.output_running.store(false, Ordering::Release);+ DeviceStatus::Silent+ }+ };+ tracing::warn!("[omnidisc-media] giving up on the {:?} device: {:?}", kind, cause);+ shared.emit(EngineNotification::Device { kind, status, cause: Some(cause) });+}++impl LiveKitBackend {+ pub fn new() -> Result<Self, MediaError> {+ let rt = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(2)+ .thread_name("omnidisc-media")+ .enable_all()+ .build()+ .map_err(|e| MediaError::Unavailable(format!("media runtime: {e}")))?;+ let flags = Arc::new(CaptureFlags::default());+ let mixer = Arc::new(Mixer::default());+ let events: StdMutex<Option<mpsc::UnboundedSender<BackendEvent>>> = StdMutex::new(None);+ let shared_slot: Arc<StdMutex<Option<std::sync::Weak<Shared>>>> = Arc::new(StdMutex::new(None));+ let capture_slot = shared_slot.clone();+ let capture_sink: crate::audio::capture::CaptureSink = Arc::new(move |ev| {+ let Some(shared) = capture_slot.lock().ok().and_then(|s| s.as_ref().and_then(|w| w.upgrade())) else {+ return;+ };+ match ev {+ CaptureEvent::Level { rms_db, peak } => shared.emit(EngineNotification::Level { rms_db, peak }),+ CaptureEvent::Speaking(speaking) => {+ shared.mixer.set_ducking(speaking);+ if let Some(id) = shared.local_identity() {+ shared.emit(EngineNotification::Speaking { user_id: id, speaking });+ }+ }+ CaptureEvent::Underrun => tracing::debug!("[omnidisc-media] microphone underrun"),+ }+ });+ let feeder = Arc::new(Feeder::spawn(flags.clone(), capture_sink).map_err(MediaError::Device)?);+ let fault_slot = shared_slot.clone();+ let fault_sink: crate::audio::io::FaultSink = Arc::new(move |fault, message| {+ let Some(shared) = fault_slot.lock().ok().and_then(|s| s.as_ref().and_then(|w| w.upgrade())) else {+ return;+ };+ tracing::warn!("[omnidisc-media] audio stream fault {:?}: {}", fault, message);+ let kind = match fault {+ StreamFault::Input => {+ shared.input_running.store(false, Ordering::Release);+ shared.emit(EngineNotification::Error { code: "ERR_VOICE_MIC_LOST".into(), message });+ DeviceKind::Input+ }+ StreamFault::Output => {+ shared.output_running.store(false, Ordering::Release);+ shared.emit(EngineNotification::Error { code: "ERR_VOICE_OUTPUT_LOST".into(), message });+ DeviceKind::Output+ }+ };+ shared.emit(EngineNotification::Device { kind, status: DeviceStatus::Lost, cause: None });+ // The cpal error callback runs on the device thread: re-opening a+ // device from here would deadlock the very thread that has to answer.+ if shared.recovering(kind).swap(true, Ordering::AcqRel) {+ return;+ }+ let worker = shared.clone();+ if std::thread::Builder::new()+ .name("omnidisc-audio-recovery".into())+ .spawn(move || {+ recover(&worker, kind);+ worker.recovering(kind).store(false, Ordering::Release);+ })+ .is_err()+ {+ shared.recovering(kind).store(false, Ordering::Release);+ }+ });+ let io = AudioIo::spawn(feeder.clone(), mixer.clone(), fault_sink).map_err(MediaError::Device)?;+ let shared = Arc::new(Shared {+ events,+ flags,+ mixer,+ feeder,+ io,+ session: Mutex::new(None),+ local_identity: StdMutex::new(None),+ volumes: StdMutex::new(HashMap::new()),+ input_device: StdMutex::new(None),+ output_device: StdMutex::new(None),+ input_running: AtomicBool::new(false),+ output_running: AtomicBool::new(false),+ monitor: AtomicBool::new(false),+ ptt_generation: AtomicU64::new(0),+ last_stats: StdMutex::new(None),+ remote_nonsilent_frames: AtomicU64::new(0),+ remote_tone: StdMutex::new(ToneMeter::new(440.0, MIX_RATE as f64)),+ video_publications: StdMutex::new(HashMap::new()),+ remote_video: StdMutex::new(HashMap::new()),+ rotation: KeyRotation::new(),+ recovering_input: AtomicBool::new(false),+ recovering_output: AtomicBool::new(false),+ });+ if let Ok(mut slot) = shared_slot.lock() {+ *slot = Some(Arc::downgrade(&shared));+ }+ Ok(Self { rt: Some(rt), shared })+ }++ pub fn remote_nonsilent_frames(&self) -> u64 {+ self.shared.remote_nonsilent_frames.load(Ordering::Relaxed)+ }++ /// Share of the received remote energy sitting at 440 Hz — the test tone.+ /// Amplitude alone cannot distinguish delivered audio from the comfort noise+ /// Opus invents when frames fail to decrypt, so the e2e tests assert on this.+ pub fn remote_tone_ratio(&self) -> f64 {+ self.shared.remote_tone.lock().map(|m| m.ratio()).unwrap_or(0.0)+ }++ pub fn set_test_tone(&self, hz: Option<f32>) {+ self.shared.feeder.send(FeederMsg::TestTone(hz));+ }++ pub fn runtime_handle(&self) -> Option<tokio::runtime::Handle> {+ self.rt.as_ref().map(|rt| rt.handle().clone())+ }++ pub async fn current_room(&self) -> Option<Arc<Room>> {+ self.shared.session.lock().await.as_ref().map(|s| s.room.clone())+ }++ pub async fn is_connected(&self) -> bool {+ self.shared.session.lock().await.is_some()+ }++ pub fn set_screen_audio_gain(&self, user_id: &str, gain: f32) {+ let key = format!("{user_id}{SCREEN_AUDIO_SUFFIX}");+ if let Ok(mut v) = self.shared.volumes.lock() {+ v.insert(key.clone(), gain.clamp(0.0, 2.0));+ }+ self.shared.mixer.set_user_gain(&key, gain.clamp(0.0, 2.0));+ }++ pub fn remote_video_for(&self, user_id: &str) -> Option<RemoteVideo> {+ self.shared.remote_video.lock().ok().and_then(|m| m.get(user_id).cloned())+ }++ pub fn video_publication_for(&self, user_id: &str) -> Option<RemoteTrackPublication> {+ self.shared.video_publications.lock().ok().and_then(|m| m.get(user_id).cloned())+ }++ pub fn streaming_user_ids(&self) -> Vec<String> {+ self.shared.video_publications.lock().map(|m| m.keys().cloned().collect()).unwrap_or_default()+ }++ async fn on_runtime<T: Send + 'static>(+ &self,+ fut: impl std::future::Future<Output = Result<T, MediaError>> + Send + 'static,+ ) -> Result<T, MediaError> {+ let Some(rt) = self.rt.as_ref() else { return Err(MediaError::Unavailable("media runtime stopped".into())) };+ match rt.spawn(fut).await {+ Ok(r) => r,+ Err(e) if e.is_panic() => Err(MediaError::Panicked),+ Err(e) => Err(MediaError::Unavailable(e.to_string())),+ }+ }+}++fn quality_of(q: ConnectionQuality) -> Quality {+ match q {+ ConnectionQuality::Excellent => Quality::Excellent,+ ConnectionQuality::Good => Quality::Good,+ ConnectionQuality::Poor => Quality::Poor,+ ConnectionQuality::Lost => Quality::Lost,+ }+}++fn subscribe_audio(publication: &RemoteTrackPublication) {+ if publication.kind() == TrackKind::Audio && !publication.is_subscribed() {+ publication.set_subscribed(true);+ }+}++fn spawn_remote_audio(+ shared: Arc<Shared>,+ remote_audio: Arc<StdMutex<HashMap<String, RemoteAudioTrack>>>,+ track: RemoteAudioTrack,+ _user_id: String,+ gain_key: String,+) -> tokio::task::JoinHandle<()> {+ let key = track.sid().to_string();+ if let Ok(mut m) = remote_audio.lock() {+ m.insert(key.clone(), track.clone());+ }+ tokio::spawn(async move {+ let (mut producer, consumer) = rtrb::RingBuffer::<f32>::new(REMOTE_RING_SAMPLES);+ shared.mixer.add_source(key.clone(), gain_key.clone(), consumer, shared.volume_for(&gain_key));+ let mut stream = NativeAudioStream::new(track.rtc_track(), MIX_RATE as i32, 1);+ let mut scratch: Vec<f32> = Vec::with_capacity(FRAME_SAMPLES * 4);+ while let Some(frame) = stream.next().await {+ scratch.clear();+ scratch.extend(frame.data.iter().map(|s| *s as f32 / 32_768.0));+ if scratch.iter().any(|s| s.abs() > 0.01) {+ shared.remote_nonsilent_frames.fetch_add(1, Ordering::Relaxed);+ }+ if let Ok(mut meter) = shared.remote_tone.lock() {+ meter.push(&scratch);+ }+ let _ = producer.push_partial_slice(&scratch);+ }+ shared.mixer.remove_source(&key);+ if let Ok(mut m) = remote_audio.lock() {+ m.remove(&key);+ }+ })+}++async fn run_room_events(+ shared: Arc<Shared>,+ remote_audio: Arc<StdMutex<HashMap<String, RemoteAudioTrack>>>,+ local_identity: String,+ mut events: mpsc::UnboundedReceiver<RoomEvent>,+) {+ let mut speakers: HashSet<String> = HashSet::new();+ let mut feeders: HashMap<String, tokio::task::JoinHandle<()>> = HashMap::new();+ while let Some(ev) = events.recv().await {+ match ev {+ RoomEvent::ParticipantConnected(p) => {+ shared.emit(EngineNotification::ParticipantJoined { user_id: p.identity().0 });+ }+ RoomEvent::ParticipantDisconnected(p) => {+ let id = p.identity().0;+ if speakers.remove(&id) {+ shared.emit(EngineNotification::Speaking { user_id: id.clone(), speaking: false });+ }+ shared.emit(EngineNotification::ParticipantLeft { user_id: id });+ }+ RoomEvent::TrackPublished { publication, participant } => {+ if publication.kind() == TrackKind::Video {+ if let Ok(mut m) = shared.video_publications.lock() {+ m.insert(participant.identity().0, publication.clone());+ }+ } else {+ subscribe_audio(&publication);+ }+ }+ RoomEvent::TrackUnpublished { publication, participant } => {+ if publication.kind() == TrackKind::Video {+ if let Ok(mut m) = shared.video_publications.lock() {+ m.remove(&participant.identity().0);+ }+ if let Ok(mut m) = shared.remote_video.lock() {+ m.remove(&participant.identity().0);+ }+ }+ }+ RoomEvent::TrackSubscribed { track, participant, publication } => match track {+ RemoteTrack::Audio(audio) => {+ let sid = audio.sid().to_string();+ let user = participant.identity().0;+ let gain_key = if publication.source() == TrackSource::ScreenshareAudio {+ format!("{user}{SCREEN_AUDIO_SUFFIX}")+ } else {+ user+ };+ let handle = spawn_remote_audio(shared.clone(), remote_audio.clone(), audio, participant.identity().0, gain_key);+ if let Some(old) = feeders.insert(sid, handle) {+ old.abort();+ }+ }+ RemoteTrack::Video(video) => {+ if let Ok(mut m) = shared.remote_video.lock() {+ m.insert(+ participant.identity().0.clone(),+ RemoteVideo { user_id: participant.identity().0, sid: video.sid().to_string(), track: video },+ );+ }+ }+ },+ RoomEvent::TrackUnsubscribed { track, participant, .. } => match track {+ RemoteTrack::Audio(audio) => {+ let sid = audio.sid().to_string();+ if let Some(h) = feeders.remove(&sid) {+ h.abort();+ }+ shared.mixer.remove_source(&sid);+ if let Ok(mut m) = remote_audio.lock() {+ m.remove(&sid);+ }+ }+ RemoteTrack::Video(_) => {+ if let Ok(mut m) = shared.remote_video.lock() {+ m.remove(&participant.identity().0);+ }+ }+ },+ RoomEvent::ActiveSpeakersChanged { speakers: now } => {+ let next: HashSet<String> = now+ .iter()+ .map(|p| p.identity().0)+ .filter(|id| *id != local_identity)+ .collect();+ for id in speakers.difference(&next) {+ shared.emit(EngineNotification::Speaking { user_id: id.clone(), speaking: false });+ }+ for id in next.difference(&speakers) {+ shared.emit(EngineNotification::Speaking { user_id: id.clone(), speaking: true });+ }+ speakers = next;+ }+ RoomEvent::ConnectionQualityChanged { quality, participant } => {+ shared.emit(EngineNotification::Quality { user_id: participant.identity().0, quality: quality_of(quality) });+ }+ RoomEvent::Reconnecting => shared.transport(VoiceEvent::Disconnected { recoverable: true }),+ RoomEvent::Reconnected => shared.transport(VoiceEvent::Reconnected),+ RoomEvent::Disconnected { reason } => {+ if reason != DisconnectReason::ClientInitiated {+ tracing::warn!("[omnidisc-media] room disconnected: {:?}", reason);+ shared.emit(EngineNotification::Error {+ code: "ERR_VOICE_DISCONNECTED".into(),+ message: format!("{reason:?}"),+ });+ shared.transport(VoiceEvent::Disconnected { recoverable: false });+ }+ break;+ }+ _ => {}+ }+ }+ for (_, h) in feeders.drain() {+ h.abort();+ }+}++async fn teardown(shared: &Arc<Shared>) {+ let session = shared.session.lock().await.take();+ shared.feeder.send(FeederMsg::Source(None));+ if let Ok(mut id) = shared.local_identity.lock() {+ *id = None;+ }+ if let Some(s) = session {+ for t in s.tasks {+ t.abort();+ }+ if let Err(e) = tokio::time::timeout(Duration::from_secs(5), s.room.close()).await {+ tracing::debug!("[omnidisc-media] room close timed out: {e}");+ }+ }+ if let Ok(mut m) = shared.video_publications.lock() {+ m.clear();+ }+ if let Ok(mut m) = shared.remote_video.lock() {+ m.clear();+ }+ shared.rotation.disarm();+ shared.mixer.set_ducking(false);+ shared.mixer.clear();+ shared.io.stop_output();+ shared.output_running.store(false, Ordering::Release);+ shared.stop_input_if_idle();+ if let Ok(mut l) = shared.last_stats.lock() {+ *l = None;+ }+}++#[async_trait]+impl MediaBackend for LiveKitBackend {+ fn set_events(&self, tx: mpsc::UnboundedSender<BackendEvent>) {+ if let Ok(mut g) = self.shared.events.lock() {+ *g = Some(tx);+ }+ }++ async fn connect(+ &self,+ target: &VoiceServerUpdate,+ prefs: &AudioPrefs,+ options: &ConnectOptions,+ ) -> Result<ConnectOutcome, MediaError> {+ let shared = self.shared.clone();+ let target = target.clone();+ let prefs = prefs.clone();+ let connect_options = options.clone();+ self.on_runtime(async move {+ teardown(&shared).await;+ if let Ok(mut d) = shared.input_device.lock() {+ *d = prefs.input_device.clone();+ }+ if let Ok(mut d) = shared.output_device.lock() {+ *d = prefs.output_device.clone();+ }+ shared.flags.denoise.store(prefs.noise_suppression && cfg!(feature = "rnnoise"), Ordering::Relaxed);+ shared.flags.ptt_enabled.store(prefs.ptt_enabled, Ordering::Relaxed);+ if let Some(db) = prefs.vad_threshold_db {+ shared.flags.set_vad_threshold_db(db);+ }+ shared.mixer.set_duck_percent(prefs.ducking_percent);+ shared.mixer.set_ducking(false);++ let mut options = RoomOptions::default();+ options.auto_subscribe = false;+ options.adaptive_stream = true;+ options.dynacast = true;+ options.connect_timeout = CONNECT_TIMEOUT;+ if !target.ice_servers.is_empty() {+ options.rtc_config.ice_servers = target+ .ice_servers+ .iter()+ .map(|s| IceServer {+ urls: s.urls.clone(),+ username: s.username.clone().unwrap_or_default(),+ password: s.credential.clone().unwrap_or_default(),+ })+ .collect();+ }+ if connect_options.relay_only {+ options.rtc_config.ice_transport_type = IceTransportsType::Relay;+ }+ // Shared-key mode: every member derives the same key from the MLS+ // group, so nothing about it is negotiated over the wire. The ring+ // index is the epoch, which is what lets a member who has not merged+ // the newest commit yet still decode the previous epoch's frames.+ if let Some(room_key) = connect_options.room_key {+ let provider =+ KeyProvider::with_shared_key(KeyProviderOptions::default(), room_key.key.to_vec());+ options.encryption = Some(E2eeOptions {+ encryption_type: EncryptionType::Gcm,+ key_provider: provider.clone(),+ });+ shared.rotation.arm(Arc::new(LiveKitRing(provider)), room_key);+ tracing::info!("[omnidisc-media] room {} is end-to-end encrypted", target.room);+ }+ let connect = Room::connect(&target.endpoint, &target.token, options);+ let (room, events) = match tokio::time::timeout(CONNECT_TIMEOUT, connect).await {+ Ok(Ok(r)) => r,+ Ok(Err(e)) => {+ tracing::warn!("[omnidisc-media] livekit connect to {} failed: {}", target.endpoint, e);+ return Err(MediaError::Connection(e.to_string()));+ }+ Err(_) => return Err(MediaError::Connection("timed out".into())),+ };+ let room = Arc::new(room);+ let local_identity = room.local_participant().identity().0;+ if let Ok(mut id) = shared.local_identity.lock() {+ *id = Some(local_identity.clone());+ }++ let source = NativeAudioSource::new(+ AudioSourceOptions {+ echo_cancellation: true,+ noise_suppression: !(prefs.noise_suppression && cfg!(feature = "rnnoise")),+ auto_gain_control: true,+ },+ SAMPLE_RATE,+ 1,+ 0,+ );+ let audio_track = LocalAudioTrack::create_audio_track("microphone", RtcAudioSource::Native(source.clone()));+ room.local_participant()+ .publish_track(+ LocalTrack::Audio(audio_track.clone()),+ TrackPublishOptions { source: TrackSource::Microphone, dtx: true, ..Default::default() },+ )+ .await+ .map_err(|e| MediaError::Connection(format!("publish microphone: {e}")))?;+ shared.feeder.send(FeederMsg::Source(Some(source)));+ if shared.flags.muted.load(Ordering::Relaxed) {+ audio_track.mute();+ }++ let remote_audio: Arc<StdMutex<HashMap<String, RemoteAudioTrack>>> = Arc::new(StdMutex::new(HashMap::new()));+ for (_, participant) in room.remote_participants() {+ shared.emit(EngineNotification::ParticipantJoined { user_id: participant.identity().0 });+ for (_, publication) in participant.track_publications() {+ if publication.kind() == TrackKind::Video {+ if let Ok(mut m) = shared.video_publications.lock() {+ m.insert(participant.identity().0, publication.clone());+ }+ } else {+ subscribe_audio(&publication);+ }+ }+ }+ let events_task = tokio::spawn(run_room_events(shared.clone(), remote_audio.clone(), local_identity.clone(), events));++ let mut outcome = ConnectOutcome::default();+ if let Err(e) = shared.ensure_output() {+ tracing::warn!("[omnidisc-media] output device: {}", e);+ outcome.output_error = Some(map_io_error(&e, DeviceKind::Output));+ }+ if let Err(e) = shared.ensure_input() {+ tracing::warn!("[omnidisc-media] input device: {}", e);+ outcome.mic_error = Some(map_io_error(&e, DeviceKind::Input));+ }++ *shared.session.lock().await = Some(Session {+ room,+ audio_track,+ remote_audio,+ tasks: vec![events_task],+ });+ Ok(outcome)+ })+ .await+ }++ async fn disconnect(&self) -> Result<(), MediaError> {+ let shared = self.shared.clone();+ self.on_runtime(async move {+ teardown(&shared).await;+ Ok(())+ })+ .await+ }++ async fn set_muted(&self, muted: bool) -> Result<(), MediaError> {+ self.shared.flags.muted.store(muted, Ordering::Relaxed);+ let shared = self.shared.clone();+ self.on_runtime(async move {+ if let Some(s) = shared.session.lock().await.as_ref() {+ if muted {+ s.audio_track.mute();+ } else {+ s.audio_track.unmute();+ }+ }+ Ok(())+ })+ .await+ }++ async fn set_deafened(&self, deafened: bool) -> Result<(), MediaError> {+ self.shared.mixer.set_deafened(deafened);+ Ok(())+ }++ async fn set_participant_volume(&self, user_id: &str, gain: f32) -> Result<(), MediaError> {+ let gain = gain.clamp(0.0, 2.0);+ if let Ok(mut v) = self.shared.volumes.lock() {+ v.insert(user_id.to_string(), gain);+ }+ self.shared.mixer.set_user_gain(user_id, gain);+ Ok(())+ }++ async fn set_master_volume(&self, gain: f32) -> Result<(), MediaError> {+ self.shared.mixer.set_master(gain);+ Ok(())+ }++ async fn set_device(&self, kind: DeviceKind, id: Option<String>) -> Result<(), MediaError> {+ let shared = self.shared.clone();+ self.on_runtime(async move {+ let id = id.map(|s| s.trim().to_string()).filter(|s| !s.is_empty());+ match kind {+ DeviceKind::Input => {+ if let Ok(mut d) = shared.input_device.lock() {+ *d = id;+ }+ if shared.input_running.load(Ordering::Acquire) {+ shared.input_running.store(false, Ordering::Release);+ shared.ensure_input().map_err(|e| MediaError::Device(map_io_error(&e, DeviceKind::Input)))?;+ }+ }+ DeviceKind::Output => {+ if let Ok(mut d) = shared.output_device.lock() {+ *d = id;+ }+ if shared.output_running.load(Ordering::Acquire) {+ shared.output_running.store(false, Ordering::Release);+ shared.ensure_output().map_err(|e| MediaError::Device(map_io_error(&e, DeviceKind::Output)))?;+ }+ }+ }+ Ok(())+ })+ .await+ }++ async fn set_noise_suppression(&self, on: bool) -> Result<(), MediaError> {+ self.shared.flags.denoise.store(on && cfg!(feature = "rnnoise"), Ordering::Relaxed);+ Ok(())+ }++ async fn set_ptt(&self, enabled: bool, pressed: bool) -> Result<(), MediaError> {+ let flags = self.shared.flags.clone();+ flags.ptt_enabled.store(enabled, Ordering::Relaxed);+ let generation = self.shared.ptt_generation.fetch_add(1, Ordering::AcqRel) + 1;+ if pressed || !enabled {+ flags.ptt_pressed.store(pressed, Ordering::Relaxed);+ return Ok(());+ }+ let shared = self.shared.clone();+ let Some(rt) = self.rt.as_ref() else { return Ok(()) };+ rt.spawn(async move {+ tokio::time::sleep(PTT_RELEASE_DELAY).await;+ if shared.ptt_generation.load(Ordering::Acquire) == generation {+ shared.flags.ptt_pressed.store(false, Ordering::Relaxed);+ }+ });+ Ok(())+ }++ async fn set_mic_monitor(&self, on: bool) -> Result<(), MediaError> {+ let shared = self.shared.clone();+ self.on_runtime(async move {+ shared.monitor.store(on, Ordering::Release);+ shared.flags.monitor.store(on, Ordering::Relaxed);+ if on {+ shared.ensure_input().map_err(|e| MediaError::Device(map_io_error(&e, DeviceKind::Input)))?;+ } else {+ shared.stop_input_if_idle();+ }+ Ok(())+ })+ .await+ }++ async fn set_ducking(&self, percent: u8) -> Result<(), MediaError> {+ self.shared.mixer.set_duck_percent(percent);+ Ok(())+ }++ async fn set_room_key(&self, key: RoomKey) -> Result<(), MediaError> {+ if self.shared.rotation.apply(key) {+ tracing::debug!("[omnidisc-media] voice key rotated to epoch {}", key.epoch);+ }+ Ok(())+ }++ fn e2ee_epoch(&self) -> Option<u64> {+ self.shared.rotation.epoch()+ }++ async fn stats(&self) -> Result<VoiceStats, MediaError> {+ let shared = self.shared.clone();+ self.on_runtime(async move {+ let (track, remotes, participants) = {+ let guard = shared.session.lock().await;+ let Some(s) = guard.as_ref() else { return Err(MediaError::NotConnected) };+ let remotes: Vec<RemoteAudioTrack> =+ s.remote_audio.lock().map(|m| m.values().cloned().collect()).unwrap_or_default();+ (s.audio_track.clone(), remotes, s.room.remote_participants().len())+ };+ let mut out = VoiceStats { participants, ..Default::default() };+ let mut bytes_out = 0u64;+ let mut bytes_in = 0u64;+ if let Ok(stats) = track.get_stats().await {+ for s in stats {+ match s {+ RtcStats::OutboundRtp(o) => bytes_out += o.sent.bytes_sent,+ RtcStats::RemoteInboundRtp(r) => {+ if r.remote_inbound.round_trip_time > 0.0 {+ out.rtt_ms = Some(r.remote_inbound.round_trip_time * 1000.0);+ }+ out.packet_loss = Some(r.remote_inbound.fraction_lost.clamp(0.0, 1.0));+ out.jitter_ms = Some(r.received.jitter * 1000.0);+ }+ RtcStats::CandidatePair(p) if p.candidate_pair.nominated => {+ if out.rtt_ms.is_none() && p.candidate_pair.current_round_trip_time > 0.0 {+ out.rtt_ms = Some(p.candidate_pair.current_round_trip_time * 1000.0);+ }+ }+ _ => {}+ }+ }+ }+ let mut lost = 0i64;+ let mut received = 0u64;+ for r in remotes {+ if let Ok(stats) = r.get_stats().await {+ for s in stats {+ if let RtcStats::InboundRtp(i) = s {+ bytes_in += i.inbound.bytes_received;+ lost += i.received.packets_lost;+ received += i.received.packets_received;+ }+ }+ }+ }+ if out.packet_loss.is_none() && received > 0 {+ out.packet_loss = Some((lost.max(0) as f64 / (received as f64 + lost.max(0) as f64)).clamp(0.0, 1.0));+ }+ let now = Instant::now();+ if let Ok(mut last) = shared.last_stats.lock() {+ if let Some((t, o, i)) = *last {+ let dt = now.duration_since(t).as_secs_f64();+ if dt > 0.2 {+ out.bitrate_out_kbps = (bytes_out.saturating_sub(o) as f64 * 8.0 / 1000.0) / dt;+ out.bitrate_in_kbps = (bytes_in.saturating_sub(i) as f64 * 8.0 / 1000.0) / dt;+ }+ }+ *last = Some((now, bytes_out, bytes_in));+ }+ Ok(out)+ })+ .await+ }++ fn devices(&self) -> AudioDevices {+ devices::enumerate()+ }+}diff --git a/src-tauri/omnidisc-media/src/state.rs b/src-tauri/omnidisc-media/src/state.rsnew file mode 100644index 00000000..2dffebd4--- /dev/null+++ b/src-tauri/omnidisc-media/src/state.rs@@ -0,0 +1,103 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum VoiceState {+ #[default]+ Idle,+ Connecting,+ Connected,+ Reconnecting,+ Failed,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum VoiceEvent {+ Join,+ Connected,+ Disconnected { recoverable: bool },+ Reconnected,+ Leave,+ GiveUp,+}++#[derive(Debug, Default, Clone)]+pub struct VoiceStateMachine {+ state: VoiceState,+ retries: u8,+}++impl VoiceStateMachine {+ pub const MAX_RETRIES: u8 = 5;++ pub fn state(&self) -> VoiceState {+ self.state+ }++ pub fn apply(&mut self, ev: &VoiceEvent) -> VoiceState {+ use VoiceEvent as E;+ use VoiceState as S;+ self.state = match (self.state, ev) {+ (S::Idle, E::Join) => S::Connecting,+ (S::Connecting, E::Connected) => {+ self.retries = 0;+ S::Connected+ }+ (S::Connecting, E::Disconnected { recoverable: true }) | (S::Connected, E::Disconnected { recoverable: true }) => {+ self.retries += 1;+ if self.retries > Self::MAX_RETRIES { S::Failed } else { S::Reconnecting }+ }+ (S::Connecting, E::Disconnected { recoverable: false }) | (S::Connected, E::Disconnected { recoverable: false }) => S::Failed,+ (S::Reconnecting, E::Reconnected) | (S::Reconnecting, E::Connected) => {+ self.retries = 0;+ S::Connected+ }+ (S::Reconnecting, E::Disconnected { recoverable: true }) => {+ self.retries += 1;+ if self.retries > Self::MAX_RETRIES { S::Failed } else { S::Reconnecting }+ }+ (S::Reconnecting, E::Disconnected { recoverable: false }) | (S::Reconnecting, E::GiveUp) => S::Failed,+ (_, E::Leave) => {+ self.retries = 0;+ S::Idle+ }+ (S::Failed, E::Join) => S::Connecting,+ (s, _) => s,+ };+ self.state+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn happy_path() {+ let mut m = VoiceStateMachine::default();+ assert_eq!(m.apply(&VoiceEvent::Join), VoiceState::Connecting);+ assert_eq!(m.apply(&VoiceEvent::Connected), VoiceState::Connected);+ assert_eq!(m.apply(&VoiceEvent::Leave), VoiceState::Idle);+ }++ #[test]+ fn gives_up_after_max_retries() {+ let mut m = VoiceStateMachine::default();+ m.apply(&VoiceEvent::Join);+ m.apply(&VoiceEvent::Connected);+ for _ in 0..VoiceStateMachine::MAX_RETRIES {+ assert_eq!(m.apply(&VoiceEvent::Disconnected { recoverable: true }), VoiceState::Reconnecting);+ }+ assert_eq!(m.apply(&VoiceEvent::Disconnected { recoverable: true }), VoiceState::Failed);+ assert_eq!(m.apply(&VoiceEvent::Join), VoiceState::Connecting);+ }++ #[test]+ fn leave_always_returns_to_idle() {+ let mut m = VoiceStateMachine::default();+ m.apply(&VoiceEvent::Join);+ m.apply(&VoiceEvent::Disconnected { recoverable: true });+ assert_eq!(m.apply(&VoiceEvent::Leave), VoiceState::Idle);+ }+}diff --git a/src-tauri/omnidisc-media/src/stream.rs b/src-tauri/omnidisc-media/src/stream.rsnew file mode 100644index 00000000..bbd89a37--- /dev/null+++ b/src-tauri/omnidisc-media/src/stream.rs@@ -0,0 +1,264 @@+use omnidisc_proto::bitrate::{Codec, StreamingPolicy};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum SourceId {+ Display { id: u32 },+ Window { id: u32 },+ Synthetic { width: u32, height: u32 },+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct StreamSource {+ pub id: SourceId,+ pub title: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub app_name: Option<String>,+ pub width: u32,+ pub height: u32,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub thumbnail: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AudioApp {+ pub pid: i32,+ pub name: String,+ pub bundle_id: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct StreamSources {+ pub displays: Vec<StreamSource>,+ pub windows: Vec<StreamSource>,+ pub apps: Vec<AudioApp>,+ pub app_audio_supported: bool,+ pub system_audio_supported: bool,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(tag = "mode", rename_all = "snake_case")]+pub enum AudioMode {+ #[default]+ None,+ App {+ pid: i32,+ },+ System,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(rename_all = "snake_case")]+pub enum StreamMode {+ #[default]+ Text,+ Game,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum StreamCodec {+ H264,+ H265,+}++impl From<Codec> for StreamCodec {+ fn from(c: Codec) -> Self {+ match c {+ Codec::H265 => StreamCodec::H265,+ _ => StreamCodec::H264,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct StreamRequest {+ pub source: SourceId,+ pub fps: u16,+ #[serde(default)]+ pub height: Option<u16>,+ #[serde(default)]+ pub audio: AudioMode,+ #[serde(default)]+ pub bitrate_kbps: Option<u32>,+ #[serde(default)]+ pub mode: StreamMode,+ #[serde(default = "default_cursor")]+ pub cursor: bool,+ #[serde(default)]+ pub policy: StreamingPolicy,+}++fn default_cursor() -> bool {+ true+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct ResolvedStream {+ pub width: u32,+ pub height: u32,+ pub fps: u16,+ pub bitrate_kbps: u32,+ pub codec: StreamCodec,+ pub mode: StreamMode,+ pub audio: AudioMode,+}++pub fn resolve_geometry(native_w: u32, native_h: u32, requested_height: Option<u16>) -> (u32, u32) {+ let native_h = native_h.max(2);+ let native_w = native_w.max(2);+ let target_h = match requested_height {+ Some(h) if (h as u32) < native_h => h as u32,+ _ => native_h,+ };+ let target_w = (native_w as u64 * target_h as u64 / native_h as u64) as u32;+ ((target_w.max(2)) & !1, (target_h.max(2)) & !1)+}++pub fn resolve_bitrate(policy: &StreamingPolicy, width: u32, height: u32, fps: u16, requested_height: Option<u16>, custom_kbps: Option<u32>) -> u32 {+ if let Some(custom) = custom_kbps {+ return policy.clamp_custom(custom);+ }+ match requested_height {+ Some(h) if h as u32 >= height => policy.kbps_for(h, fps),+ _ => policy.native_kbps(width, height, fps),+ }+}++#[derive(Debug, thiserror::Error)]+pub enum StreamError {+ #[error("screen recording permission is missing")]+ Permission,+ #[error("screen share is not supported on this platform yet")]+ Unsupported,+ #[error("capture source is gone")]+ SourceGone,+ #[error("capture failed: {0}")]+ Capture(String),+ #[error("encoder failed: {0}")]+ Encoder(String),+ #[error("not streaming")]+ NotStreaming,+ #[error("no such stream")]+ NoSuchStream,+ #[error("viewer failed: {0}")]+ Viewer(String),+ #[error("not connected to a voice channel")]+ NotConnected,+}++impl StreamError {+ pub fn code(&self) -> &'static str {+ match self {+ Self::Permission => "ERR_SCREEN_PERMISSION",+ Self::Unsupported => "ERR_STREAM_UNSUPPORTED",+ Self::SourceGone => "ERR_STREAM_SOURCE_GONE",+ Self::Capture(_) => "ERR_STREAM_CAPTURE_FAILED",+ Self::Encoder(_) => "ERR_STREAM_ENCODER_FAILED",+ Self::NotStreaming => "ERR_STREAM_NOT_STREAMING",+ Self::NoSuchStream => "ERR_STREAM_NOT_FOUND",+ Self::Viewer(_) => "ERR_STREAM_VIEWER_FAILED",+ Self::NotConnected => "ERR_VOICE_NOT_CONNECTED",+ }+ }+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum WatchState {+ Connecting,+ Playing,+ Ended,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]+pub struct Viewport {+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+ pub scale: f64,+ pub surface_width: u32,+ pub surface_height: u32,+ pub background: [f32; 3],+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]+pub struct PublishStats {+ pub width: u32,+ pub height: u32,+ pub fps_captured: f64,+ pub fps_encoded: f64,+ pub fps_sent: f64,+ pub bitrate_kbps: f64,+ pub target_kbps: f64,+ pub configured_kbps: u32,+ pub codec: Option<StreamCodec>,+ pub encoder: String,+ pub hardware: Option<bool>,+ pub encode_ms: f64,+ pub keyframes: u64,+ pub keyframe_requests: u64,+ pub frames_dropped: u64,+ pub rtt_ms: Option<f64>,+ pub packet_loss: Option<f64>,+ pub quality_limitation: String,+ pub audio: AudioMode,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]+pub struct WatchStats {+ pub user_id: String,+ pub width: u32,+ pub height: u32,+ pub fps_received: f64,+ pub fps_rendered: f64,+ pub bitrate_kbps: f64,+ pub codec: String,+ pub decoder: String,+ pub packet_loss: Option<f64>,+ pub jitter_ms: Option<f64>,+ pub frames_dropped: u64,+ pub freeze_count: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]+pub struct StreamStats {+ pub publishing: Option<PublishStats>,+ pub watching: Vec<WatchStats>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct StreamBadge {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub user_id: Option<String>,+ pub width: u32,+ pub height: u32,+ pub fps: f64,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub codec: Option<String>,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn geometry_keeps_aspect_and_never_upscales() {+ assert_eq!(resolve_geometry(3420, 2214, Some(1080)), (1668, 1080));+ assert_eq!(resolve_geometry(1920, 1080, Some(2160)), (1920, 1080));+ assert_eq!(resolve_geometry(3440, 1440, None), (3440, 1440));+ let (w, h) = resolve_geometry(1365, 767, Some(720));+ assert_eq!(w % 2, 0);+ assert_eq!(h % 2, 0);+ }++ #[test]+ fn bitrate_uses_matrix_for_presets_and_native_otherwise() {+ let p = StreamingPolicy::default();+ assert_eq!(resolve_bitrate(&p, 1920, 1080, 60, Some(1080), None), p.kbps_for(1080, 60));+ assert_eq!(resolve_bitrate(&p, 3440, 1440, 60, None, None), p.native_kbps(3440, 1440, 60));+ assert_eq!(resolve_bitrate(&p, 1920, 1080, 60, Some(1080), Some(7_777)), p.clamp_custom(7_777));+ }+}diff --git a/src-tauri/omnidisc-media/src/streaming.rs b/src-tauri/omnidisc-media/src/streaming.rsnew file mode 100644index 00000000..eeede514--- /dev/null+++ b/src-tauri/omnidisc-media/src/streaming.rs@@ -0,0 +1,391 @@+use crate::capture::{self, AudioSink, CaptureOptions, CapturedFrame, VideoSink, VideoTick};+use crate::encode::{EncoderConfig, EncoderCounters, VideoEncoder};+use crate::livekit_backend::LiveKitBackend;+use crate::stream::{+ resolve_bitrate, AudioMode, PublishStats, ResolvedStream, StreamCodec, StreamError, StreamMode, StreamRequest,+};+use livekit::options::{TrackPublishOptions, VideoCodec, VideoEncoderBackend, VideoEncoding};+use livekit::prelude::*;+use livekit::webrtc::audio_frame::AudioFrame;+use livekit::webrtc::audio_source::{native::NativeAudioSource, AudioSourceOptions, RtcAudioSource};+use livekit::webrtc::stats::RtcStats;+use livekit::webrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};+use livekit::webrtc::video_source::{native::NativeVideoSource, RtcVideoSource, VideoResolution};+use omnidisc_proto::bitrate::{Codec, StreamingPolicy};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex as StdMutex};+use std::time::{Duration, Instant};++const PRIMER_FRAMES: u32 = 6;+const PRIMER_INTERVAL_MS: u64 = 100;+const RATE_FLOOR_PCT: u64 = 25;++fn codec_from_policy(policy: &StreamingPolicy, height: u32, fps: u16) -> StreamCodec {+ match policy.codec_for(height.min(u16::MAX as u32) as u16, fps) {+ Codec::H265 => StreamCodec::H265,+ _ => StreamCodec::H264,+ }+}++fn to_video_codec(c: StreamCodec) -> VideoCodec {+ match c {+ StreamCodec::H264 => VideoCodec::H264,+ StreamCodec::H265 => VideoCodec::H265,+ }+}++struct EncodeLoop {+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+ latest: Arc<StdMutex<Option<CapturedFrame>>>,+ fps_captured: Arc<AtomicU64>,+}++impl EncodeLoop {+ fn video_sink(&self) -> VideoSink {+ let latest = self.latest.clone();+ let counter = self.fps_captured.clone();+ Arc::new(move |tick: VideoTick| {+ if let VideoTick::Frame(frame) = tick {+ counter.fetch_add(1, Ordering::Relaxed);+ if let Ok(mut slot) = latest.lock() {+ *slot = Some(frame);+ }+ }+ })+ }++ fn spawn(+ encoder: Arc<VideoEncoder>,+ source: NativeVideoSource,+ counters: Arc<EncoderCounters>,+ fps: u16,+ configured_bps: u64,+ ) -> Self {+ let stop = Arc::new(AtomicBool::new(false));+ let latest: Arc<StdMutex<Option<CapturedFrame>>> = Arc::new(StdMutex::new(None));+ let fps_captured = Arc::new(AtomicU64::new(0));+ let stop2 = stop.clone();+ let latest2 = latest.clone();+ let floor = configured_bps * RATE_FLOOR_PCT / 100;+ let thread = std::thread::Builder::new()+ .name("omnidisc-encode".into())+ .spawn(move || {+ let interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);+ let mut next = Instant::now();+ let mut have_first = false;+ let mut last_applied = configured_bps;+ while !stop2.load(Ordering::Relaxed) {+ let frame = latest2.lock().ok().and_then(|mut s| s.take());+ let mut force_key = !have_first;+ if source.take_keyframe_request() {+ force_key = true;+ counters.keyframe_requests.fetch_add(1, Ordering::Relaxed);+ }+ if let Some(rc) = source.take_rate_control_request() {+ counters.rate_requests.fetch_add(1, Ordering::Relaxed);+ if rc.target_bitrate_bps > 0 {+ let target = rc.target_bitrate_bps.max(floor).min(configured_bps);+ let changed = (last_applied as f64 - target as f64).abs() / last_applied.max(1) as f64 > 0.05;+ if changed {+ encoder.set_bitrate(target);+ last_applied = target;+ }+ }+ }+ if let Some(frame) = frame {+ if let Err(e) = encoder.encode(&frame, force_key) {+ tracing::debug!("[omnidisc-media] encode: {e}");+ } else {+ have_first = true;+ }+ if let Ok(mut slot) = latest2.lock() {+ if slot.is_none() {+ *slot = Some(frame);+ }+ }+ }+ next += interval;+ let now = Instant::now();+ if next > now {+ std::thread::sleep(next - now);+ } else if now - next > Duration::from_millis(200) {+ next = now;+ }+ }+ })+ .expect("spawn encode loop");+ Self { stop, thread: Some(thread), latest, fps_captured }+ }++}++impl Drop for EncodeLoop {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Relaxed);+ if let Some(t) = self.thread.take() {+ let _ = t.join();+ }+ }+}++struct AudioPublish {+ capture: capture::AudioCapture,+ _track: LocalAudioTrack,+ publication: LocalTrackPublication,+}++pub struct ActiveStream {+ pub resolved: ResolvedStream,+ video_track: LocalVideoTrack,+ video_pub: LocalTrackPublication,+ _source: NativeVideoSource,+ encoder: Arc<VideoEncoder>,+ capture: Option<capture::VideoCapture>,+ encode_loop: Option<EncodeLoop>,+ counters: Arc<EncoderCounters>,+ audio: Option<AudioPublish>,+ configured_kbps: u32,+ started: Instant,+ last_sample: StdMutex<Option<(Instant, u64, u64)>>,+}++impl ActiveStream {+ pub async fn stop(mut self, room: &Arc<Room>) {+ self.encoder.finish();+ self.encode_loop.take();+ if let Some(c) = self.capture.take() {+ c.stop();+ }+ let _ = room.local_participant().unpublish_track(&self.video_pub.sid()).await;+ if let Some(a) = self.audio.take() {+ let _ = room.local_participant().unpublish_track(&a.publication.sid()).await;+ a.capture.stop();+ }+ }+}++pub async fn start_stream(backend: Arc<LiveKitBackend>, req: StreamRequest) -> Result<ActiveStream, StreamError> {+ let room = backend.current_room().await.ok_or(StreamError::NotConnected)?;++ let cap_sink_slot: Arc<StdMutex<Option<VideoSink>>> = Arc::new(StdMutex::new(None));+ let slot = cap_sink_slot.clone();+ let vsink: VideoSink = Arc::new(move |tick| {+ if let Some(s) = slot.lock().ok().and_then(|g| g.clone()) {+ s(tick);+ }+ });+ let opts = CaptureOptions { source: req.source.clone(), fps: req.fps, height: req.height, cursor: req.cursor };+ let (video_capture, geometry) = capture::start_video(&opts, vsink)?;+ let (width, height) = (geometry.width, geometry.height);++ let codec = codec_from_policy(&req.policy, height, req.fps);+ let bitrate = resolve_bitrate(&req.policy, width, height, req.fps, req.height, req.bitrate_kbps);+ let configured_bps = bitrate as u64 * 1000;+ let resolved = ResolvedStream { width, height, fps: req.fps, bitrate_kbps: bitrate, codec, mode: req.mode, audio: req.audio };++ let source = NativeVideoSource::new_encoded(VideoResolution { width, height });+ let track = LocalVideoTrack::create_video_track("omnidisc-screen", RtcVideoSource::Native(source.clone()));+ let degradation = Some(match req.mode {+ StreamMode::Text => livekit::options::DegradationPreference::MaintainResolution,+ StreamMode::Game => livekit::options::DegradationPreference::Balanced,+ });+ let publication = room+ .local_participant()+ .publish_track(+ LocalTrack::Video(track.clone()),+ TrackPublishOptions {+ source: TrackSource::Screenshare,+ video_codec: to_video_codec(codec),+ simulcast: false,+ video_encoder: VideoEncoderBackend::PreEncoded,+ video_encoding: Some(VideoEncoding { max_bitrate: configured_bps, max_framerate: req.fps as f64 }),+ degradation_preference: degradation,+ ..Default::default()+ },+ )+ .await+ .map_err(|e| StreamError::Encoder(format!("publish screenshare: {e}")))?;+ let video_pub = publication;++ // S-07 §5.1: prime the sender with raw frames so the pass-through selector+ // switches before the first encoded frame (otherwise it segfaults on macOS).+ for _ in 0..PRIMER_FRAMES {+ let black = VideoFrame {+ rotation: VideoRotation::VideoRotation0,+ timestamp_us: 0,+ frame_metadata: None,+ buffer: I420Buffer::new_black(width, height),+ };+ source.capture_frame(&black);+ tokio::time::sleep(Duration::from_millis(PRIMER_INTERVAL_MS)).await;+ }+ tokio::time::sleep(Duration::from_millis(PRIMER_INTERVAL_MS * 2)).await;++ let counters = Arc::new(EncoderCounters::default());+ let cfg = EncoderConfig { width, height, fps: req.fps, codec, bitrate_kbps: bitrate, mode: req.mode };+ let encoder = Arc::new(VideoEncoder::new(cfg, source.clone(), counters.clone())?);+ let encode_loop = EncodeLoop::spawn(encoder.clone(), source.clone(), counters.clone(), req.fps, configured_bps);+ if let Ok(mut g) = cap_sink_slot.lock() {+ *g = Some(encode_loop.video_sink());+ }++ let audio = start_screenshare_audio(&room, req.audio).await;++ Ok(ActiveStream {+ resolved,+ video_track: track,+ video_pub,+ _source: source,+ encoder,+ capture: Some(video_capture),+ encode_loop: Some(encode_loop),+ counters,+ audio,+ configured_kbps: bitrate,+ started: Instant::now(),+ last_sample: StdMutex::new(None),+ })+}++async fn start_screenshare_audio(room: &Arc<Room>, mode: AudioMode) -> Option<AudioPublish> {+ if mode == AudioMode::None {+ return None;+ }+ let source = NativeAudioSource::new(+ AudioSourceOptions { echo_cancellation: false, noise_suppression: false, auto_gain_control: false },+ capture::AUDIO_SAMPLE_RATE,+ capture::AUDIO_CHANNELS,+ 0,+ );+ let src2 = source.clone();+ // SCK delivers 20 ms interleaved-stereo buffers; split into 10 ms frames.+ let asink: AudioSink = Arc::new(move |samples: &[f32]| {+ let per_frame = (capture::AUDIO_SAMPLE_RATE / 100 * capture::AUDIO_CHANNELS) as usize;+ for chunk in samples.chunks(per_frame) {+ if chunk.len() < per_frame {+ break;+ }+ let mut frame = AudioFrame::new(capture::AUDIO_SAMPLE_RATE, capture::AUDIO_CHANNELS, (chunk.len() / capture::AUDIO_CHANNELS as usize) as u32);+ {+ let data = frame.data.to_mut();+ for (i, s) in chunk.iter().enumerate() {+ data[i] = (*s * i16::MAX as f32).clamp(i16::MIN as f32, i16::MAX as f32) as i16;+ }+ }+ let _ = futures::executor::block_on(src2.capture_frame(&frame));+ }+ });+ let (capture_handle, obtained) = match capture::start_audio(mode, asink) {+ Ok(v) => v,+ Err(e) => {+ tracing::warn!("[omnidisc-media] screenshare audio unavailable: {e}");+ return None;+ }+ };+ if obtained == AudioMode::None {+ return None;+ }+ let track = LocalAudioTrack::create_audio_track("omnidisc-screen-audio", RtcAudioSource::Native(source));+ match room+ .local_participant()+ .publish_track(LocalTrack::Audio(track.clone()), TrackPublishOptions { source: TrackSource::ScreenshareAudio, ..Default::default() })+ .await+ {+ Ok(pub_) => Some(AudioPublish { capture: capture_handle, _track: track, publication: pub_ }),+ Err(e) => {+ tracing::warn!("[omnidisc-media] publish screenshare audio: {e}");+ capture_handle.stop();+ None+ }+ }+}++impl ActiveStream {+ pub fn audio_mode(&self) -> AudioMode {+ self.resolved.audio+ }++ pub fn overdrive(&self) {+ self.encoder.set_bitrate(self.configured_kbps as u64 * 1000);+ self.encoder.set_framerate(self.resolved.fps);+ }++ pub async fn stats(&self) -> PublishStats {+ let mut stats = PublishStats {+ width: self.resolved.width,+ height: self.resolved.height,+ configured_kbps: self.configured_kbps,+ codec: Some(self.resolved.codec),+ encoder: self.encoder.name().to_string(),+ hardware: self.encoder.hardware(),+ audio: self.resolved.audio,+ ..Default::default()+ };+ let encoded = self.counters.encoded.load(Ordering::Relaxed);+ let bytes = self.counters.bytes.load(Ordering::Relaxed);+ let lat_sum = self.counters.latency_ns_sum.load(Ordering::Relaxed);+ let now = Instant::now();+ if let Ok(mut last) = self.last_sample.lock() {+ if let Some((t, e, b)) = *last {+ let dt = now.duration_since(t).as_secs_f64();+ if dt > 0.2 {+ stats.fps_encoded = (encoded.saturating_sub(e)) as f64 / dt;+ stats.bitrate_kbps = (bytes.saturating_sub(b)) as f64 * 8.0 / 1000.0 / dt;+ }+ }+ *last = Some((now, encoded, bytes));+ }+ if encoded > 0 {+ stats.encode_ms = lat_sum as f64 / encoded as f64 / 1e6;+ }+ stats.keyframes = self.counters.keyframes.load(Ordering::Relaxed);+ stats.keyframe_requests = self.counters.keyframe_requests.load(Ordering::Relaxed);+ stats.frames_dropped = self.counters.dropped.load(Ordering::Relaxed);+ if let Some(el) = self.encode_loop.as_ref() {+ stats.fps_captured = el.fps_captured.load(Ordering::Relaxed) as f64 / self.started.elapsed().as_secs_f64().max(1.0);+ }+ if let Ok(rtc) = self.video_track.get_stats().await {+ apply_outbound(&mut stats, &rtc);+ }+ stats+ }+}++fn apply_outbound(stats: &mut PublishStats, rtc: &[RtcStats]) {+ let mut mimes = std::collections::HashMap::new();+ for s in rtc {+ if let RtcStats::Codec(c) = s {+ mimes.insert(c.rtc.id.clone(), c.codec.mime_type.clone());+ }+ }+ for s in rtc {+ match s {+ RtcStats::OutboundRtp(o) if o.stream.kind == "video" => {+ stats.fps_sent = o.outbound.frames_per_second;+ stats.target_kbps = o.outbound.target_bitrate / 1000.0;+ stats.encoder = o.outbound.encoder_implementation.clone();+ stats.quality_limitation = format!("{:?}", o.outbound.quality_limitation_reason);+ if let Some(m) = mimes.get(&o.stream.codec_id) {+ if m.contains("265") || m.to_lowercase().contains("hevc") {+ stats.codec = Some(StreamCodec::H265);+ } else if m.contains("264") {+ stats.codec = Some(StreamCodec::H264);+ }+ }+ }+ RtcStats::CandidatePair(p) if p.candidate_pair.nominated => {+ if p.candidate_pair.current_round_trip_time > 0.0 {+ stats.rtt_ms = Some(p.candidate_pair.current_round_trip_time * 1000.0);+ }+ }+ RtcStats::RemoteInboundRtp(r) if r.stream.kind == "video" => {+ stats.packet_loss = Some(r.remote_inbound.fraction_lost.clamp(0.0, 1.0));+ if r.remote_inbound.round_trip_time > 0.0 {+ stats.rtt_ms = Some(r.remote_inbound.round_trip_time * 1000.0);+ }+ }+ _ => {}+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/tone.rs b/src-tauri/omnidisc-media/src/tone.rsnew file mode 100644index 00000000..86f2f6cb--- /dev/null+++ b/src-tauri/omnidisc-media/src/tone.rs@@ -0,0 +1,111 @@+//! Goertzel meter over the mixed remote audio.+//!+//! The voice e2e tests used to assert "B received N non-silent frames", which a+//! stream of pure garbage also satisfies: when a frame fails to decrypt, Opus+//! packet-loss concealment invents comfort noise, so amplitude alone cannot tell+//! "the tone arrived" from "the decryptor rejected everything". This measures+//! how much of the received energy actually sits at the published tone, which is+//! what the tests mean to prove in both directions.++const BLOCK: usize = 1200;++#[derive(Debug)]+pub struct ToneMeter {+ coeff: f64,+ q1: f64,+ q2: f64,+ filled: usize,+ tone_energy: f64,+ total_energy: f64,+}++impl ToneMeter {+ /// `hz` must divide the sample rate into `BLOCK` evenly to land on a bin+ /// centre; 440 Hz at 48 kHz gives k = 11 exactly.+ pub fn new(hz: f64, sample_rate: f64) -> Self {+ let k = (BLOCK as f64 * hz / sample_rate).round();+ Self {+ coeff: 2.0 * (2.0 * std::f64::consts::PI * k / BLOCK as f64).cos(),+ q1: 0.0,+ q2: 0.0,+ filled: 0,+ tone_energy: 0.0,+ total_energy: 0.0,+ }+ }++ pub fn push(&mut self, samples: &[f32]) {+ for s in samples {+ let x = *s as f64;+ self.total_energy += x * x;+ let q0 = self.coeff * self.q1 - self.q2 + x;+ self.q2 = std::mem::replace(&mut self.q1, q0);+ self.filled += 1;+ if self.filled == BLOCK {+ let magnitude = self.q1 * self.q1 + self.q2 * self.q2 - self.coeff * self.q1 * self.q2;+ self.tone_energy += magnitude / (BLOCK as f64 / 2.0);+ self.q1 = 0.0;+ self.q2 = 0.0;+ self.filled = 0;+ }+ }+ }++ /// Share of the received energy sitting at the measured tone, 0.0 when+ /// nothing arrived. A clean 440 Hz sine lands near 1.0; comfort noise and+ /// undecryptable frames stay near 0.+ pub fn ratio(&self) -> f64 {+ if self.total_energy <= f64::EPSILON {+ return 0.0;+ }+ (self.tone_energy / self.total_energy).clamp(0.0, 1.0)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sine(hz: f64, samples: usize) -> Vec<f32> {+ (0..samples)+ .map(|i| (2.0 * std::f64::consts::PI * hz * i as f64 / 48_000.0).sin() as f32)+ .collect()+ }++ #[test]+ fn a_pure_tone_dominates_the_ratio() {+ let mut m = ToneMeter::new(440.0, 48_000.0);+ m.push(&sine(440.0, BLOCK * 8));+ assert!(m.ratio() > 0.9, "ratio was {}", m.ratio());+ }++ #[test]+ fn another_tone_does_not_register() {+ let mut m = ToneMeter::new(440.0, 48_000.0);+ m.push(&sine(1_000.0, BLOCK * 8));+ assert!(m.ratio() < 0.1, "ratio was {}", m.ratio());+ }++ #[test]+ fn noise_does_not_register() {+ let mut m = ToneMeter::new(440.0, 48_000.0);+ let mut seed = 0x9e3779b97f4a7c15u64;+ let noise: Vec<f32> = (0..BLOCK * 8)+ .map(|_| {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ (seed as i32 as f64 / i32::MAX as f64) as f32+ })+ .collect();+ m.push(&noise);+ assert!(m.ratio() < 0.1, "ratio was {}", m.ratio());+ }++ #[test]+ fn silence_reports_nothing() {+ let mut m = ToneMeter::new(440.0, 48_000.0);+ m.push(&vec![0.0; BLOCK * 2]);+ assert_eq!(m.ratio(), 0.0);+ }+}diff --git a/src-tauri/omnidisc-media/src/viewer/mod.rs b/src-tauri/omnidisc-media/src/viewer/mod.rsnew file mode 100644index 00000000..ccb66c05--- /dev/null+++ b/src-tauri/omnidisc-media/src/viewer/mod.rs@@ -0,0 +1,195 @@+mod wgpu_surface;++pub use wgpu_surface::{FrameSlot, Planes, WgpuViewer};++use crate::stream::{StreamError, Viewport, WatchStats};+use futures::StreamExt;+use livekit::track::RemoteVideoTrack;+use livekit::webrtc::stats::RtcStats;+use livekit::webrtc::video_frame::native::VideoFrameBufferExt;+use livekit::webrtc::video_frame::{I420Buffer, VideoBuffer};+use livekit::webrtc::video_stream::native::NativeVideoStream;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++#[cfg(target_os = "macos")]+pub unsafe fn create_appkit_surface(ns_view: *mut std::ffi::c_void, width: u32, height: u32) -> Result<Arc<WgpuViewer>, StreamError> {+ use objc2::runtime::NSObjectProtocol;+ use objc2::ClassType;+ use objc2_app_kit::NSView;+ use objc2_quartz_core::CAMetalLayer;+ use raw_window_handle::{AppKitDisplayHandle, AppKitWindowHandle, RawDisplayHandle, RawWindowHandle};++ if ns_view.is_null() {+ return Err(StreamError::Viewer("null ns_view".into()));+ }+ let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();+ desc.backends = wgpu::Backends::PRIMARY;+ let instance = wgpu::Instance::new(desc);+ let handle = AppKitWindowHandle::new(std::ptr::NonNull::new(ns_view).ok_or_else(|| StreamError::Viewer("null ns_view".into()))?);+ let surface = instance+ .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {+ raw_display_handle: Some(RawDisplayHandle::AppKit(AppKitDisplayHandle::new())),+ raw_window_handle: RawWindowHandle::AppKit(handle),+ })+ .map_err(|e| StreamError::Viewer(format!("create_surface: {e}")))?;++ let view: &NSView = &*(ns_view as *const NSView);+ if let Some(root) = view.layer() {+ for l in root.sublayers().into_iter().flatten() {+ if l.isKindOfClass(CAMetalLayer::class()) {+ l.setZPosition(-1.0);+ }+ }+ }+ WgpuViewer::from_surface(instance, surface, width, height)+}++fn pack_i420(buf: &I420Buffer, full_range: bool) -> Planes {+ let (w, h) = (buf.width(), buf.height());+ let (cw, ch) = (buf.chroma_width(), buf.chroma_height());+ let (sy, su, sv) = buf.strides();+ let (dy, du, dv) = buf.data();+ let pack = |data: &[u8], stride: u32, width: u32, height: u32| {+ let stride = stride as usize;+ let width = width as usize;+ let mut out = Vec::with_capacity(width * height as usize);+ for row in 0..height as usize {+ let start = row * stride;+ if start + width <= data.len() {+ out.extend_from_slice(&data[start..start + width]);+ } else {+ out.resize(width * (row + 1), 16);+ }+ }+ out+ };+ Planes {+ y: pack(dy, sy, w, h),+ u: pack(du, su, cw, ch),+ v: pack(dv, sv, cw, ch),+ width: w,+ height: h,+ full_range,+ }+}++struct DecodeStats {+ received: AtomicU64,+ width: AtomicU64,+ height: AtomicU64,+}++pub struct Viewer {+ renderer: Arc<WgpuViewer>,+ track: RemoteVideoTrack,+ user_id: String,+ stop: Arc<AtomicBool>,+ decode_stats: Arc<DecodeStats>,+ started: Instant,+ render_thread: Option<std::thread::JoinHandle<()>>,+ decode_task: Option<tokio::task::JoinHandle<()>>,+}++impl Viewer {+ pub fn new(renderer: Arc<WgpuViewer>, track: RemoteVideoTrack, user_id: String, rt: tokio::runtime::Handle) -> Self {+ let stop = Arc::new(AtomicBool::new(false));+ let decode_stats = Arc::new(DecodeStats { received: AtomicU64::new(0), width: AtomicU64::new(0), height: AtomicU64::new(0) });+ let slot = renderer.frame_slot();+ let stats2 = decode_stats.clone();+ let stop_dec = stop.clone();+ let rtc = track.rtc_track();+ let decode_task = rt.spawn(async move {+ let mut stream = NativeVideoStream::new(rtc);+ while let Some(frame) = stream.next().await {+ if stop_dec.load(Ordering::Relaxed) {+ break;+ }+ let planes = if let Some(native) = frame.buffer.as_native() {+ pack_i420(&native.to_i420(), false)+ } else if let Some(i) = frame.buffer.as_i420() {+ pack_i420(i, false)+ } else {+ continue;+ };+ stats2.received.fetch_add(1, Ordering::Relaxed);+ stats2.width.store(planes.width as u64, Ordering::Relaxed);+ stats2.height.store(planes.height as u64, Ordering::Relaxed);+ if let Ok(mut s) = slot.planes.lock() {+ *s = Some(planes);+ }+ }+ });++ let renderer_r = renderer.clone();+ let stop_render = stop.clone();+ let render_thread = std::thread::Builder::new()+ .name("omnidisc-viewer-render".into())+ .spawn(move || {+ while !stop_render.load(Ordering::Relaxed) {+ let painted = renderer_r.render_once();+ if !painted {+ std::thread::sleep(Duration::from_millis(16));+ }+ }+ })+ .expect("spawn viewer render thread");++ Self { renderer, track, user_id, stop, decode_stats, started: Instant::now(), render_thread: Some(render_thread), decode_task: Some(decode_task) }+ }++ pub fn set_viewport(&self, viewport: Option<Viewport>) {+ self.renderer.set_viewport(viewport);+ }++ pub fn user_id(&self) -> &str {+ &self.user_id+ }++ pub async fn stats(&self) -> WatchStats {+ let mut stats = WatchStats {+ user_id: self.user_id.clone(),+ width: self.decode_stats.width.load(Ordering::Relaxed) as u32,+ height: self.decode_stats.height.load(Ordering::Relaxed) as u32,+ fps_received: self.decode_stats.received.load(Ordering::Relaxed) as f64 / self.started.elapsed().as_secs_f64().max(1.0),+ fps_rendered: self.renderer.rendered_frames() as f64 / self.started.elapsed().as_secs_f64().max(1.0),+ ..Default::default()+ };+ if let Ok(rtc) = self.track.get_stats().await {+ for s in &rtc {+ if let RtcStats::InboundRtp(i) = s {+ if i.stream.kind == "video" {+ stats.fps_received = i.inbound.frames_per_second;+ stats.decoder = i.inbound.decoder_implementation.clone();+ stats.width = i.inbound.frame_width;+ stats.height = i.inbound.frame_height;+ stats.frames_dropped = i.inbound.frames_dropped as u64;+ stats.freeze_count = i.inbound.freeze_count as u64;+ stats.jitter_ms = Some(i.received.jitter * 1000.0);+ stats.packet_loss = Some(i.received.packets_lost.max(0) as f64);+ }+ }+ if let RtcStats::Codec(c) = s {+ if c.codec.mime_type.to_lowercase().contains("video") {+ stats.codec = c.codec.mime_type.clone();+ }+ }+ }+ }+ stats+ }+}++impl Drop for Viewer {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Relaxed);+ self.renderer.stop();+ if let Some(t) = self.decode_task.take() {+ t.abort();+ }+ if let Some(t) = self.render_thread.take() {+ let _ = t.join();+ }+ }+}diff --git a/src-tauri/omnidisc-media/src/viewer/shader.wgsl b/src-tauri/omnidisc-media/src/viewer/shader.wgslnew file mode 100644index 00000000..c466c8cb--- /dev/null+++ b/src-tauri/omnidisc-media/src/viewer/shader.wgsl@@ -0,0 +1,62 @@+struct Uniforms {+ surface: vec4<f32>,+ rect: vec4<f32>,+ video: vec4<f32>,+ bg: vec4<f32>,+ mode: vec4<f32>,+};++@group(0) @binding(0) var<uniform> u: Uniforms;+@group(0) @binding(1) var samp: sampler;+@group(0) @binding(2) var tex0: texture_2d<f32>;+@group(0) @binding(3) var tex1: texture_2d<f32>;+@group(0) @binding(4) var tex2: texture_2d<f32>;++struct VsOut {+ @builtin(position) pos: vec4<f32>,+ @location(0) uv: vec2<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {+ var p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));+ var o: VsOut;+ o.pos = vec4<f32>(p[vi], 0.0, 1.0);+ o.uv = vec2<f32>(p[vi].x * 0.5 + 0.5, 1.0 - (p[vi].y * 0.5 + 0.5));+ return o;+}++fn yuv_to_rgb(y: f32, cb: f32, cr: f32, full: f32) -> vec3<f32> {+ let yy = mix((y - 16.0 / 255.0) * (255.0 / 219.0), y, full);+ let u2 = mix((cb - 128.0 / 255.0) * (255.0 / 224.0), cb - 128.0 / 255.0, full);+ let v2 = mix((cr - 128.0 / 255.0) * (255.0 / 224.0), cr - 128.0 / 255.0, full);+ let r = yy + 1.5748 * v2;+ let g = yy - 0.1873 * u2 - 0.4681 * v2;+ let b = yy + 1.8556 * u2;+ return clamp(vec3<f32>(r, g, b), vec3<f32>(0.0), vec3<f32>(1.0));+}++@fragment+fn fs_main(i: VsOut) -> @location(0) vec4<f32> {+ let px = i.uv * u.surface.xy;+ if (px.x < u.rect.x || px.y < u.rect.y || px.x >= u.rect.z || px.y >= u.rect.w) {+ return vec4<f32>(u.bg.rgb, 1.0);+ }+ if (px.x < u.video.x || px.y < u.video.y || px.x >= u.video.z || px.y >= u.video.w) {+ return vec4<f32>(0.0, 0.0, 0.0, 1.0);+ }+ let vuv = (px - u.video.xy) / (u.video.zw - u.video.xy);+ let m = u32(u.mode.x + 0.5);+ let full = u.mode.y;+ if (m == 2u) {+ let y = textureSample(tex0, samp, vuv).r;+ let uv = textureSample(tex1, samp, vuv).rg;+ return vec4<f32>(yuv_to_rgb(y, uv.x, uv.y, full), 1.0);+ } else if (m == 3u) {+ let y = textureSample(tex0, samp, vuv).r;+ let cb = textureSample(tex1, samp, vuv).r;+ let cr = textureSample(tex2, samp, vuv).r;+ return vec4<f32>(yuv_to_rgb(y, cb, cr, full), 1.0);+ }+ return vec4<f32>(0.0, 0.0, 0.0, 1.0);+}diff --git a/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rs b/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rsnew file mode 100644index 00000000..bdf03997--- /dev/null+++ b/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rs@@ -0,0 +1,343 @@+use crate::stream::{StreamError, Viewport};+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+use std::sync::{Arc, Mutex};++pub struct Planes {+ pub y: Vec<u8>,+ pub u: Vec<u8>,+ pub v: Vec<u8>,+ pub width: u32,+ pub height: u32,+ pub full_range: bool,+}++#[derive(Default)]+pub struct FrameSlot {+ pub planes: Mutex<Option<Planes>>,+ pub width: AtomicU32,+ pub height: AtomicU32,+}++struct Gpu {+ device: wgpu::Device,+ queue: wgpu::Queue,+ surface: wgpu::Surface<'static>,+ config: wgpu::SurfaceConfiguration,+ pipeline: wgpu::RenderPipeline,+ bgl: wgpu::BindGroupLayout,+ sampler: wgpu::Sampler,+ uniform: wgpu::Buffer,+ textures: Option<[wgpu::Texture; 3]>,+ tex_w: u32,+ tex_h: u32,+ format: wgpu::TextureFormat,+}++pub struct WgpuViewer {+ gpu: Mutex<Gpu>,+ frame: Arc<FrameSlot>,+ viewport: Mutex<Option<Viewport>>,+ stop: Arc<AtomicBool>,+ rendered: Arc<std::sync::atomic::AtomicU64>,+}++fn build_pipeline(device: &wgpu::Device, format: wgpu::TextureFormat) -> (wgpu::RenderPipeline, wgpu::BindGroupLayout) {+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("omnidisc-viewer"),+ source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),+ });+ let tex_entry = |binding: u32| wgpu::BindGroupLayoutEntry {+ binding,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ view_dimension: wgpu::TextureViewDimension::D2,+ multisampled: false,+ },+ count: None,+ };+ let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("omnidisc-viewer"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ tex_entry(2),+ tex_entry(3),+ tex_entry(4),+ ],+ });+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("omnidisc-viewer"),+ bind_group_layouts: &[Some(&bgl)],+ immediate_size: 0,+ });+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("omnidisc-viewer"),+ layout: Some(&layout),+ vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), compilation_options: Default::default(), buffers: &[] },+ primitive: wgpu::PrimitiveState::default(),+ depth_stencil: None,+ multisample: wgpu::MultisampleState::default(),+ fragment: Some(wgpu::FragmentState {+ module: &shader,+ entry_point: Some("fs_main"),+ compilation_options: Default::default(),+ targets: &[Some(wgpu::ColorTargetState { format, blend: Some(wgpu::BlendState::REPLACE), write_mask: wgpu::ColorWrites::ALL })],+ }),+ multiview_mask: None,+ cache: None,+ });+ (pipeline, bgl)+}++impl WgpuViewer {+ pub fn from_surface(instance: wgpu::Instance, surface: wgpu::Surface<'static>, width: u32, height: u32) -> Result<Arc<Self>, StreamError> {+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {+ power_preference: wgpu::PowerPreference::HighPerformance,+ compatible_surface: Some(&surface),+ force_fallback_adapter: false,+ apply_limit_buckets: false,+ }))+ .map_err(|e| StreamError::Viewer(format!("no gpu adapter: {e}")))?;+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("omnidisc-viewer"), ..Default::default() }))+ .map_err(|e| StreamError::Viewer(format!("no gpu device: {e}")))?;+ let caps = surface.get_capabilities(&adapter);+ let format = caps.formats.iter().copied().find(|f| !f.is_srgb()).unwrap_or(caps.formats[0]);+ let config = wgpu::SurfaceConfiguration {+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,+ format,+ color_space: wgpu::SurfaceColorSpace::Auto,+ width: width.max(1),+ height: height.max(1),+ present_mode: wgpu::PresentMode::Fifo,+ desired_maximum_frame_latency: 2,+ alpha_mode: caps.alpha_modes[0],+ view_formats: vec![],+ };+ surface.configure(&device, &config);+ let (pipeline, bgl) = build_pipeline(&device, format);+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ ..Default::default()+ });+ let uniform = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("omnidisc-viewer-uniform"),+ size: 80,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ let gpu = Gpu {+ device,+ queue,+ surface,+ config,+ pipeline,+ bgl,+ sampler,+ uniform,+ textures: None,+ tex_w: 0,+ tex_h: 0,+ format,+ };+ Ok(Arc::new(Self {+ gpu: Mutex::new(gpu),+ frame: Arc::new(FrameSlot::default()),+ viewport: Mutex::new(None),+ stop: Arc::new(AtomicBool::new(false)),+ rendered: Arc::new(std::sync::atomic::AtomicU64::new(0)),+ }))+ }++ pub fn frame_slot(&self) -> Arc<FrameSlot> {+ self.frame.clone()+ }++ pub fn rendered_frames(&self) -> u64 {+ self.rendered.load(Ordering::Relaxed)+ }++ pub fn set_viewport(&self, viewport: Option<Viewport>) {+ if let Ok(mut v) = self.viewport.lock() {+ *v = viewport;+ }+ }++ pub fn resize(&self, width: u32, height: u32) {+ if let Ok(mut gpu) = self.gpu.lock() {+ gpu.config.width = width.max(1);+ gpu.config.height = height.max(1);+ let (device, config) = (&gpu.device, gpu.config.clone());+ gpu.surface.configure(device, &config);+ }+ }++ pub fn stop(&self) {+ self.stop.store(true, Ordering::Relaxed);+ }++ fn ensure_textures(gpu: &mut Gpu, w: u32, h: u32) {+ if gpu.textures.is_some() && gpu.tex_w == w && gpu.tex_h == h {+ return;+ }+ let make = |tw: u32, th: u32| {+ gpu.device.create_texture(&wgpu::TextureDescriptor {+ label: Some("omnidisc-plane"),+ size: wgpu::Extent3d { width: tw.max(1), height: th.max(1), depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: wgpu::TextureDimension::D2,+ format: wgpu::TextureFormat::R8Unorm,+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ view_formats: &[],+ })+ };+ gpu.textures = Some([make(w, h), make(w / 2, h / 2), make(w / 2, h / 2)]);+ gpu.tex_w = w;+ gpu.tex_h = h;+ }++ // Renders one frame; returns false when nothing was presented (no viewport).+ pub fn render_once(&self) -> bool {+ let viewport = match self.viewport.lock().ok().and_then(|v| *v) {+ Some(v) if v.width > 0.0 && v.height > 0.0 => v,+ _ => return false,+ };+ let mut gpu = match self.gpu.lock() {+ Ok(g) => g,+ Err(_) => return false,+ };+ let surf_w = (viewport.surface_width.max(1)) as u32;+ let surf_h = (viewport.surface_height.max(1)) as u32;+ if gpu.config.width != surf_w || gpu.config.height != surf_h {+ gpu.config.width = surf_w;+ gpu.config.height = surf_h;+ let (device, config) = (&gpu.device, gpu.config.clone());+ gpu.surface.configure(device, &config);+ }++ let mut full = 0.0f32;+ if let Ok(mut slot) = self.frame.planes.lock() {+ if let Some(p) = slot.take() {+ Self::ensure_textures(&mut gpu, p.width, p.height);+ if let Some(tex) = &gpu.textures {+ let write = |q: &wgpu::Queue, t: &wgpu::Texture, data: &[u8], w: u32, h: u32| {+ q.write_texture(+ wgpu::TexelCopyTextureInfo { texture: t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },+ data,+ wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w), rows_per_image: Some(h) },+ wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },+ );+ };+ write(&gpu.queue, &tex[0], &p.y, p.width, p.height);+ write(&gpu.queue, &tex[1], &p.u, p.width / 2, p.height / 2);+ write(&gpu.queue, &tex[2], &p.v, p.width / 2, p.height / 2);+ self.frame.width.store(p.width, Ordering::Relaxed);+ self.frame.height.store(p.height, Ordering::Relaxed);+ }+ full = if p.full_range { 1.0 } else { 0.0 };+ }+ }+ let vw = self.frame.width.load(Ordering::Relaxed);+ let vh = self.frame.height.load(Ordering::Relaxed);+ if gpu.textures.is_none() || vw == 0 {+ return false;+ }+ let mode = 3u32; // I420++ // fit video into viewport rect preserving aspect ratio (letterbox)+ let rx = viewport.x as f32 * viewport.scale as f32;+ let ry = viewport.y as f32 * viewport.scale as f32;+ let rw = viewport.width as f32 * viewport.scale as f32;+ let rh = viewport.height as f32 * viewport.scale as f32;+ let src_aspect = vw as f32 / vh.max(1) as f32;+ let dst_aspect = rw / rh.max(1.0);+ let (fw, fh) = if src_aspect > dst_aspect { (rw, rw / src_aspect) } else { (rh * src_aspect, rh) };+ let fx = rx + (rw - fw) / 2.0;+ let fy = ry + (rh - fh) / 2.0;+ let vid = [fx, fy, fx + fw, fy + fh];++ let bg = viewport.background;+ let mut ub = [0u8; 80];+ let write_f = |ub: &mut [u8], off: usize, v: f32| ub[off..off + 4].copy_from_slice(&v.to_ne_bytes());+ write_f(&mut ub, 0, gpu.config.width as f32);+ write_f(&mut ub, 4, gpu.config.height as f32);+ write_f(&mut ub, 16, rx);+ write_f(&mut ub, 20, ry);+ write_f(&mut ub, 24, rx + rw);+ write_f(&mut ub, 28, ry + rh);+ write_f(&mut ub, 32, vid[0]);+ write_f(&mut ub, 36, vid[1]);+ write_f(&mut ub, 40, vid[2]);+ write_f(&mut ub, 44, vid[3]);+ write_f(&mut ub, 48, bg[0]);+ write_f(&mut ub, 52, bg[1]);+ write_f(&mut ub, 56, bg[2]);+ write_f(&mut ub, 64, mode as f32);+ write_f(&mut ub, 68, full);+ gpu.queue.write_buffer(&gpu.uniform, 0, &ub);++ let tex = gpu.textures.as_ref().unwrap();+ let views: Vec<wgpu::TextureView> = tex.iter().map(|t| t.create_view(&Default::default())).collect();+ let bind = gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("omnidisc-viewer"),+ layout: &gpu.bgl,+ entries: &[+ wgpu::BindGroupEntry { binding: 0, resource: gpu.uniform.as_entire_binding() },+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&gpu.sampler) },+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&views[0]) },+ wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&views[1]) },+ wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&views[2]) },+ ],+ });+ let surface_tex = match gpu.surface.get_current_texture() {+ wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t,+ wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {+ let (device, config) = (&gpu.device, gpu.config.clone());+ gpu.surface.configure(device, &config);+ return false;+ }+ _ => return false,+ };+ let view = surface_tex.texture.create_view(&Default::default());+ let mut enc = gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("omnidisc-viewer") });+ {+ let mut rp = enc.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("omnidisc-viewer"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &view,+ resolve_target: None,+ depth_slice: None,+ ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },+ })],+ depth_stencil_attachment: None,+ timestamp_writes: None,+ occlusion_query_set: None,+ multiview_mask: None,+ });+ rp.set_pipeline(&gpu.pipeline);+ rp.set_bind_group(0, &bind, &[]);+ rp.draw(0..3, 0..1);+ }+ gpu.queue.submit([enc.finish()]);+ gpu.queue.present(surface_tex);+ self.rendered.fetch_add(1, Ordering::Relaxed);+ let _ = gpu.format;+ true+ }++ pub fn stopped(&self) -> bool {+ self.stop.load(Ordering::Relaxed)+ }+}diff --git a/src-tauri/omnidisc-media/tests/stream_e2e.rs b/src-tauri/omnidisc-media/tests/stream_e2e.rsnew file mode 100644index 00000000..e8cc6661--- /dev/null+++ b/src-tauri/omnidisc-media/tests/stream_e2e.rs@@ -0,0 +1,233 @@+//! Live screen-share e2e against a real omnidisc-server + LiveKit. A publishes a+//! synthetic NV12 1080p60 stream through the real encoder path (generator -> our+//! VideoToolbox session -> PreEncoded pass-through); B subscribes to the remote+//! screenshare video and must receive >= 30 fps within 60 s with a decoder+//! reported. Needs `OMNIDISC_TEST_URL`, e.g.+//! `OMNIDISC_TEST_URL=http://72.62.136.3:8080 cargo test -p omnidisc-media --test stream_e2e -- --ignored --nocapture`.++use futures_util::{SinkExt, StreamExt};+use omnidisc_media::{start_stream, AudioMode, AudioPrefs, ConnectOptions, LiveKitBackend, MediaEngine, SourceId, StreamMode, StreamRequest, VoiceState};+use omnidisc_proto::gateway::VoiceServerUpdate;+use serde_json::{json, Value};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio_tungstenite::tungstenite::Message;++fn unique(prefix: &str) -> String {+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);+ format!("{}{}{}", prefix, std::process::id() % 10_000, nanos % 100_000)+}++async fn register(http: &reqwest::Client, base: &str, name: &str) -> (String, String) {+ let res: Value = http+ .post(format!("{base}/api/auth/register"))+ .json(&json!({ "username": name, "password": "correct horse battery" }))+ .send()+ .await+ .expect("register request")+ .json()+ .await+ .expect("register json");+ (res["token"].as_str().expect("token").to_string(), res["user"]["id"].as_str().expect("user id").to_string())+}++struct Gateway {+ ws: tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,+}++impl Gateway {+ async fn connect(base: &str, token: &str) -> Self {+ let ws_url = format!("{}/gateway", base.replacen("http", "ws", 1));+ let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.expect("gateway ws");+ let _hello = ws.next().await.expect("hello").expect("hello frame");+ let identify = json!({ "op": 2, "d": { "token": token, "protocol_version": omnidisc_proto::PROTOCOL_VERSION, "compress": "none", "properties": { "os": "test", "client": "omnidisc-media-test", "version": "0" } } });+ ws.send(Message::Text(identify.to_string().into())).await.expect("identify");+ let mut g = Self { ws };+ g.wait_dispatch("READY").await;+ g+ }++ async fn send(&mut self, frame: Value) {+ self.ws.send(Message::Text(frame.to_string().into())).await.expect("send frame");+ }++ async fn try_dispatch(&mut self, name: &str, budget: Duration) -> Option<Value> {+ let deadline = Instant::now() + budget;+ while Instant::now() < deadline {+ let remaining = deadline.saturating_duration_since(Instant::now());+ let Ok(Some(Ok(msg))) = tokio::time::timeout(remaining, self.ws.next()).await else { return None };+ let Message::Text(text) = msg else { continue };+ let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };+ if v["op"] == 0 && v["t"] == name {+ return Some(v["d"].clone());+ }+ }+ None+ }++ async fn wait_dispatch(&mut self, name: &str) -> Value {+ let deadline = Instant::now() + Duration::from_secs(15);+ while Instant::now() < deadline {+ let remaining = deadline.saturating_duration_since(Instant::now());+ let msg = tokio::time::timeout(remaining, self.ws.next())+ .await+ .unwrap_or_else(|_| panic!("timed out waiting for {name}"))+ .expect("gateway closed")+ .expect("gateway frame");+ let Message::Text(text) = msg else { continue };+ let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };+ if v["op"] == 0 && v["t"] == name {+ return v["d"].clone();+ }+ if v["op"] == 12 {+ panic!("gateway error waiting for {name}: {v}");+ }+ }+ panic!("timed out waiting for {name}");+ }+}++fn cpu_percent() -> String {+ let pid = std::process::id().to_string();+ std::process::Command::new("ps").args(["-o", "%cpu=", "-p", &pid]).output().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).unwrap_or_else(|_| "?".into())+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+#[ignore]+async fn stream_publish_and_watch() {+ let Ok(url) = std::env::var("OMNIDISC_TEST_URL") else {+ eprintln!("OMNIDISC_TEST_URL not set; skipping");+ return;+ };+ let base = url.trim().trim_end_matches('/').to_string();+ let http = reqwest::Client::builder().timeout(Duration::from_secs(15)).build().expect("http");++ let (token_a, id_a) = register(&http, &base, &unique("streama")).await;+ let (token_b, _id_b) = register(&http, &base, &unique("streamb")).await;++ let guild: Value = http.post(format!("{base}/api/guilds")).bearer_auth(&token_a).json(&json!({ "name": "Stream E2E" })).send().await.expect("guild").json().await.expect("guild json");+ let guild_id = guild["id"].as_str().expect("guild id").to_string();+ let channel: Value = http.post(format!("{base}/api/guilds/{guild_id}/channels")).bearer_auth(&token_a).json(&json!({ "name": "stage", "type": 2 })).send().await.expect("channel").json().await.expect("channel json");+ let channel_id = channel["id"].as_str().expect("channel id").to_string();+ let invite: Value = http.post(format!("{base}/api/invites")).bearer_auth(&token_a).json(&json!({ "guild_id": guild_id })).send().await.expect("invite").json().await.expect("invite json");+ let code = invite["code"].as_str().expect("code");+ let joined = http.post(format!("{base}/api/invites/{code}")).bearer_auth(&token_b).json(&json!({})).send().await.expect("join");+ assert!(joined.status().is_success(), "invite join: {}", joined.status());++ let mut gw_a = Gateway::connect(&base, &token_a).await;+ let mut gw_b = Gateway::connect(&base, &token_b).await;+ gw_a.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": channel_id, "self_mute": false, "self_deaf": false, "self_stream": true } })).await;+ let vsu_a: VoiceServerUpdate = serde_json::from_value(gw_a.wait_dispatch("VOICE_SERVER_UPDATE").await).expect("vsu a");+ gw_b.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": channel_id, "self_mute": false, "self_deaf": false } })).await;+ let vsu_b: VoiceServerUpdate = serde_json::from_value(gw_b.wait_dispatch("VOICE_SERVER_UPDATE").await).expect("vsu b");+ assert_eq!(vsu_a.room, vsu_b.room);++ // A streaming=true propagation is best-effort: only servers built with the+ // self_stream change fan it out; the deployed VPS may predate it.+ if let Some(vs) = gw_b.try_dispatch("VOICE_STATE_UPDATE", Duration::from_secs(3)).await {+ eprintln!("[e2e] B saw voice state: streaming={:?} user={:?}", vs["streaming"], vs["user_id"]);+ } else {+ eprintln!("[e2e] no VOICE_STATE_UPDATE seen (older server or timing) — continuing");+ }++ let backend_a = Arc::new(LiveKitBackend::new().expect("backend a"));+ let backend_b = Arc::new(LiveKitBackend::new().expect("backend b"));+ let engine_a = Arc::new(MediaEngine::new(backend_a.clone()));+ let engine_b = Arc::new(MediaEngine::new(backend_b.clone()));+ let pa = { let e = engine_a.clone(); tokio::spawn(async move { e.pump().await }) };+ let pb = { let e = engine_b.clone(); tokio::spawn(async move { e.pump().await }) };++ let prefs = AudioPrefs { noise_suppression: false, ..Default::default() };+ engine_a.join(&vsu_a, &prefs, &ConnectOptions::default()).await.expect("A joins");+ assert_eq!(engine_a.state().await, VoiceState::Connected);+ engine_b.join(&vsu_b, &prefs, &ConnectOptions::default()).await.expect("B joins");++ let req = StreamRequest {+ source: SourceId::Synthetic { width: 1920, height: 1080 },+ fps: 60,+ height: Some(1080),+ audio: AudioMode::None,+ bitrate_kbps: None,+ mode: StreamMode::Text,+ cursor: false,+ policy: Default::default(),+ };+ let stream = start_stream(backend_a.clone(), req).await.expect("start stream");+ eprintln!("[e2e] A publishing {}x{}@{} {:?} {} kbps", stream.resolved.width, stream.resolved.height, stream.resolved.fps, stream.resolved.codec, stream.resolved.bitrate_kbps);++ // B subscribes to A's screenshare video and counts decoded frames.+ let start = Instant::now();+ let track = {+ let mut found = None;+ while start.elapsed() < Duration::from_secs(20) {+ if let Some(p) = backend_b.video_publication_for(&id_a) {+ p.set_subscribed(true);+ }+ if let Some(rv) = backend_b.remote_video_for(&id_a) {+ found = Some(rv.track);+ break;+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+ found.expect("B never received A's video track")+ };++ let frames = Arc::new(std::sync::atomic::AtomicU64::new(0));+ let frames2 = frames.clone();+ let rtc = track.rtc_track();+ let pump = tokio::spawn(async move {+ let mut stream = livekit::webrtc::video_stream::native::NativeVideoStream::new(rtc);+ while let Some(_f) = stream.next().await {+ frames2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ }+ });++ let mut fps = 0.0;+ let deadline = Instant::now() + Duration::from_secs(60);+ let mut last = (Instant::now(), 0u64);+ while Instant::now() < deadline {+ tokio::time::sleep(Duration::from_secs(3)).await;+ let n = frames.load(std::sync::atomic::Ordering::Relaxed);+ let dt = last.0.elapsed().as_secs_f64();+ fps = (n.saturating_sub(last.1)) as f64 / dt;+ last = (Instant::now(), n);+ let mut decoder = String::new();+ if let Ok(st) = track.get_stats().await {+ for s in &st {+ if let livekit::webrtc::stats::RtcStats::InboundRtp(i) = s {+ if i.stream.kind == "video" {+ decoder = i.inbound.decoder_implementation.clone();+ eprintln!("[e2e] B recv fps={:.1} {}x{} decoder='{}' key={} dropped={}", i.inbound.frames_per_second, i.inbound.frame_width, i.inbound.frame_height, decoder, i.inbound.key_frames_decoded, i.inbound.frames_dropped);+ }+ }+ }+ }+ if fps >= 30.0 && !decoder.is_empty() {+ eprintln!("[e2e] reached {:.1} fps with decoder '{}' at t+{:.0}s", fps, decoder, start.elapsed().as_secs_f64());+ break;+ }+ }++ let mut decoder = String::new();+ if let Ok(st) = track.get_stats().await {+ for s in &st {+ if let livekit::webrtc::stats::RtcStats::InboundRtp(i) = s {+ if i.stream.kind == "video" {+ decoder = i.inbound.decoder_implementation.clone();+ }+ }+ }+ }+ eprintln!("[e2e] final fps={:.1} decoder='{}' cpu(ps lifetime)={}%", fps, decoder, cpu_percent());++ let room_a = backend_a.current_room().await.expect("room a");+ stream.stop(&room_a).await;+ engine_a.leave().await.ok();+ engine_b.leave().await.ok();+ pump.abort();+ pa.abort();+ pb.abort();++ assert!(fps >= 30.0, "B received only {fps:.1} fps within 60 s");+ assert!(!decoder.is_empty(), "no decoder implementation reported for B");+}diff --git a/src-tauri/omnidisc-media/tests/voice_e2e.rs b/src-tauri/omnidisc-media/tests/voice_e2e.rsnew file mode 100644index 00000000..dac32ea0--- /dev/null+++ b/src-tauri/omnidisc-media/tests/voice_e2e.rs@@ -0,0 +1,324 @@+//! Two participants on a live omnidisc-server + LiveKit: A publishes a 440 Hz+//! tone through the real capture pipeline (test-tone hook), B must receive+//! non-silent audio. Runs three times: in the clear, with the SFrame cryptor+//! keyed by a shared room key (what an MLS epoch hands us), and once with+//! mismatched keys, where nothing may be decoded.+//! Needs `OMNIDISC_TEST_URL`, e.g.+//! `OMNIDISC_TEST_URL=https://72-62-136-3.sslip.io cargo test -p omnidisc-media --test voice_e2e -- --ignored --nocapture`.++use futures_util::{SinkExt, StreamExt};+use omnidisc_media::{AudioPrefs, ConnectOptions, LiveKitBackend, MediaEngine, RoomKey, VoiceState};+use omnidisc_proto::gateway::VoiceServerUpdate;+use serde_json::{json, Value};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio_tungstenite::tungstenite::Message;++fn unique(prefix: &str) -> String {+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.subsec_nanos())+ .unwrap_or(0);+ format!("{}{}{}", prefix, std::process::id() % 10_000, nanos % 100_000)+}++async fn register(http: &reqwest::Client, base: &str, name: &str) -> (String, String) {+ let res: Value = http+ .post(format!("{base}/api/auth/register"))+ .json(&json!({ "username": name, "password": "correct horse battery" }))+ .send()+ .await+ .expect("register request")+ .json()+ .await+ .expect("register json");+ let token = res["token"].as_str().expect("token").to_string();+ let id = res["user"]["id"].as_str().expect("user id").to_string();+ (token, id)+}++struct Gateway {+ ws: tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,+}++impl Gateway {+ async fn connect(base: &str, token: &str) -> Self {+ let ws_url = format!("{}/gateway", base.replacen("http", "ws", 1));+ let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.expect("gateway ws");+ let hello = ws.next().await.expect("hello").expect("hello frame");+ assert!(matches!(hello, Message::Text(_)));+ let identify = json!({ "op": 2, "d": { "token": token, "protocol_version": omnidisc_proto::PROTOCOL_VERSION, "compress": "none", "properties": { "os": "test", "client": "omnidisc-media-test", "version": "0" } } });+ ws.send(Message::Text(identify.to_string().into())).await.expect("identify");+ let mut g = Self { ws };+ g.wait_dispatch("READY").await;+ g+ }++ async fn send(&mut self, frame: Value) {+ self.ws.send(Message::Text(frame.to_string().into())).await.expect("send frame");+ }++ async fn wait_dispatch(&mut self, name: &str) -> Value {+ let deadline = Instant::now() + Duration::from_secs(15);+ while Instant::now() < deadline {+ let remaining = deadline.saturating_duration_since(Instant::now());+ let msg = tokio::time::timeout(remaining, self.ws.next())+ .await+ .unwrap_or_else(|_| panic!("timed out waiting for {name}"))+ .expect("gateway closed")+ .expect("gateway frame");+ let Message::Text(text) = msg else { continue };+ let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };+ if v["op"] == 0 && v["t"] == name {+ return v["d"].clone();+ }+ if v["op"] == 12 {+ panic!("gateway error while waiting for {name}: {v}");+ }+ }+ panic!("timed out waiting for {name}");+ }+}++fn cpu_percent() -> String {+ let pid = std::process::id().to_string();+ std::process::Command::new("ps")+ .args(["-o", "%cpu=", "-p", &pid])+ .output()+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())+ .unwrap_or_else(|_| "?".into())+}++struct Room {+ guild_id: String,+ channel_id: String,+ gw_a: Gateway,+ gw_b: Gateway,+ vsu_a: VoiceServerUpdate,+ vsu_b: VoiceServerUpdate,+}++async fn two_in_a_voice_channel(base: &str, label: &str) -> Room {+ let http = reqwest::Client::builder().timeout(Duration::from_secs(15)).build().expect("http");+ let (token_a, _id_a) = register(&http, base, &unique(&format!("{label}a"))).await;+ let (token_b, _id_b) = register(&http, base, &unique(&format!("{label}b"))).await;++ let guild: Value = http+ .post(format!("{base}/api/guilds"))+ .bearer_auth(&token_a)+ .json(&json!({ "name": "Voice E2E" }))+ .send()+ .await+ .expect("create guild")+ .json()+ .await+ .expect("guild json");+ let guild_id = guild["id"].as_str().expect("guild id").to_string();+ let channel: Value = http+ .post(format!("{base}/api/guilds/{guild_id}/channels"))+ .bearer_auth(&token_a)+ .json(&json!({ "name": "voice", "type": 2 }))+ .send()+ .await+ .expect("create channel")+ .json()+ .await+ .expect("channel json");+ let channel_id = channel["id"].as_str().expect("channel id").to_string();+ let invite: Value = http+ .post(format!("{base}/api/invites"))+ .bearer_auth(&token_a)+ .json(&json!({ "guild_id": guild_id }))+ .send()+ .await+ .expect("invite")+ .json()+ .await+ .expect("invite json");+ let code = invite["code"].as_str().expect("code");+ let joined = http+ .post(format!("{base}/api/invites/{code}"))+ .bearer_auth(&token_b)+ .json(&json!({}))+ .send()+ .await+ .expect("join invite");+ assert!(joined.status().is_success(), "invite join failed: {}", joined.status());++ let mut gw_a = Gateway::connect(base, &token_a).await;+ let mut gw_b = Gateway::connect(base, &token_b).await;+ gw_a.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": channel_id, "self_mute": false, "self_deaf": false } })).await;+ let vsu_a: VoiceServerUpdate = serde_json::from_value(gw_a.wait_dispatch("VOICE_SERVER_UPDATE").await).expect("vsu a");+ gw_b.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": channel_id, "self_mute": false, "self_deaf": false } })).await;+ let vsu_b: VoiceServerUpdate = serde_json::from_value(gw_b.wait_dispatch("VOICE_SERVER_UPDATE").await).expect("vsu b");+ assert_eq!(vsu_a.room, vsu_b.room);+ eprintln!(+ "[e2e/{label}] room {} endpoint {} ice_servers={}",+ vsu_a.room,+ vsu_a.endpoint,+ vsu_a.ice_servers.len()+ );+ Room { guild_id, channel_id, gw_a, gw_b, vsu_a, vsu_b }+}++/// A publishes a tone, B must hear it. `room_key` present means both sides run+/// the SFrame cryptor in shared-key mode, exactly as an MLS epoch would set it.+async fn tone_reaches_the_other_side(base: &str, label: &str, room_key: Option<RoomKey>) {+ let mut room = two_in_a_voice_channel(base, label).await;++ let backend_a = Arc::new(LiveKitBackend::new().expect("backend a"));+ let backend_b = Arc::new(LiveKitBackend::new().expect("backend b"));+ let engine_a = Arc::new(MediaEngine::new(backend_a.clone()));+ let engine_b = Arc::new(MediaEngine::new(backend_b.clone()));+ let pump_a = { let e = engine_a.clone(); tokio::spawn(async move { e.pump().await }) };+ let pump_b = { let e = engine_b.clone(); tokio::spawn(async move { e.pump().await }) };+ let mut notes_b = engine_b.subscribe();++ let prefs = AudioPrefs { noise_suppression: false, ..Default::default() };+ let options = ConnectOptions { room_key, relay_only: false };+ let outcome_a = engine_a.join(&room.vsu_a, &prefs, &options).await.expect("A joins");+ eprintln!("[e2e/{label}] A connected (mic_error={:?}, output_error={:?})", outcome_a.mic_error, outcome_a.output_error);+ assert_eq!(engine_a.state().await, VoiceState::Connected);+ backend_a.set_test_tone(Some(440.0));+ let outcome_b = engine_b.join(&room.vsu_b, &prefs, &options).await.expect("B joins");+ eprintln!("[e2e/{label}] B connected (mic_error={:?}, output_error={:?})", outcome_b.mic_error, outcome_b.output_error);+ backend_b.set_test_tone(Some(440.0));++ assert_eq!(engine_a.e2ee_epoch(), room_key.map(|k| k.epoch), "A's key ring state");+ assert_eq!(engine_b.e2ee_epoch(), room_key.map(|k| k.epoch), "B's key ring state");++ let start = Instant::now();+ let deadline = start + Duration::from_secs(20);+ let mut frames = 0;+ while Instant::now() < deadline {+ frames = backend_b.remote_nonsilent_frames();+ if frames >= 50 {+ break;+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+ let tone = backend_b.remote_tone_ratio();+ eprintln!(+ "[e2e/{label}] B received {frames} non-silent frames after {:?}, {:.0}% of the energy at 440 Hz",+ start.elapsed(),+ tone * 100.0+ );+ assert!(frames >= 50, "B received only {frames} non-silent audio frames within 20 s");+ // Frame count alone would also pass on the comfort noise Opus invents for+ // frames it could not decrypt; the tone is what proves A's audio arrived.+ assert!(tone > 0.5, "only {:.0}% of B's received energy was A's 440 Hz tone", tone * 100.0);++ let mut saw_speaking = false;+ let mut saw_participant = false;+ while let Ok(Ok(n)) = tokio::time::timeout(Duration::from_millis(50), notes_b.recv()).await {+ match n {+ omnidisc_media::EngineNotification::Speaking { speaking: true, .. } => saw_speaking = true,+ omnidisc_media::EngineNotification::ParticipantJoined { .. } => saw_participant = true,+ _ => {}+ }+ }+ eprintln!("[e2e/{label}] B events: speaking={saw_speaking} participant_joined={saw_participant}");++ if room_key.is_some() {+ // A commit on the group bumps the epoch; the ring index has to follow it+ // without dropping the call.+ let next = RoomKey::new(room_key.expect("key").epoch + 1, [0x5A; 32]);+ engine_a.set_room_key(next).await.expect("A rotates");+ engine_b.set_room_key(next).await.expect("B rotates");+ assert_eq!(engine_a.e2ee_epoch(), Some(next.epoch));+ let before = backend_b.remote_nonsilent_frames();+ tokio::time::sleep(Duration::from_secs(3)).await;+ let after = backend_b.remote_nonsilent_frames();+ eprintln!("[e2e/{label}] frames across the epoch bump: {before} -> {after}");+ assert!(after > before, "audio stopped after the key rotated ({before} -> {after})");+ }++ let _ = engine_b.stats().await.expect("stats b (first sample)");+ tokio::time::sleep(Duration::from_secs(5)).await;+ let stats_b = engine_b.stats().await.expect("stats b");+ eprintln!("[e2e/{label}] B stats: {:?}", stats_b);+ eprintln!("[e2e/{label}] process cpu (ps lifetime avg) = {}%", cpu_percent());+ assert!(stats_b.bitrate_in_kbps > 0.0, "B reports no inbound bitrate");++ engine_a.leave().await.expect("A leaves");+ engine_b.leave().await.expect("B leaves");+ assert_eq!(engine_b.state().await, VoiceState::Idle);+ let guild_id = room.guild_id.clone();+ room.gw_a.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": null } })).await;+ room.gw_b.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": null } })).await;+ let _ = room.channel_id;+ pump_a.abort();+ pump_b.abort();+}++fn test_url() -> Option<String> {+ match std::env::var("OMNIDISC_TEST_URL") {+ Ok(url) => Some(url.trim().trim_end_matches('/').to_string()),+ Err(_) => {+ eprintln!("OMNIDISC_TEST_URL not set; skipping");+ None+ }+ }+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+#[ignore]+async fn voice_two_participants_exchange_audio() {+ let Some(base) = test_url() else { return };+ tone_reaches_the_other_side(&base, "clear", None).await;+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+#[ignore]+async fn voice_two_participants_exchange_encrypted_audio() {+ let Some(base) = test_url() else { return };+ tone_reaches_the_other_side(&base, "e2ee", Some(RoomKey::new(3, [0xA7; 32]))).await;+}++/// The proof that the cryptor is really in the path: same room, different keys,+/// no audio. Without this the encrypted test above would still pass if E2EE+/// were silently ignored.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+#[ignore]+async fn voice_with_the_wrong_key_hears_nothing() {+ let Some(base) = test_url() else { return };+ let mut room = two_in_a_voice_channel(&base, "badkey").await;++ let backend_a = Arc::new(LiveKitBackend::new().expect("backend a"));+ let backend_b = Arc::new(LiveKitBackend::new().expect("backend b"));+ let engine_a = Arc::new(MediaEngine::new(backend_a.clone()));+ let engine_b = Arc::new(MediaEngine::new(backend_b.clone()));+ let pump_a = { let e = engine_a.clone(); tokio::spawn(async move { e.pump().await }) };+ let pump_b = { let e = engine_b.clone(); tokio::spawn(async move { e.pump().await }) };++ let prefs = AudioPrefs { noise_suppression: false, ..Default::default() };+ engine_a+ .join(&room.vsu_a, &prefs, &ConnectOptions { room_key: Some(RoomKey::new(1, [0x11; 32])), relay_only: false })+ .await+ .expect("A joins");+ backend_a.set_test_tone(Some(440.0));+ engine_b+ .join(&room.vsu_b, &prefs, &ConnectOptions { room_key: Some(RoomKey::new(1, [0x22; 32])), relay_only: false })+ .await+ .expect("B joins");++ tokio::time::sleep(Duration::from_secs(12)).await;+ let frames = backend_b.remote_nonsilent_frames();+ let tone = backend_b.remote_tone_ratio();+ eprintln!(+ "[e2e/badkey] B received {frames} non-silent frames with the wrong key, {:.1}% of the energy at 440 Hz",+ tone * 100.0+ );+ // A handful of non-silent frames is Opus concealment noise for packets the+ // cryptor rejected, not audio: what must be absent is the tone itself.+ assert!(tone < 0.1, "B recovered A's tone with the wrong key ({:.0}% of the energy at 440 Hz)", tone * 100.0);+ assert!(frames < 200, "B decoded {frames} frames it should not have been able to decrypt");++ engine_a.leave().await.expect("A leaves");+ engine_b.leave().await.expect("B leaves");+ let guild_id = room.guild_id.clone();+ room.gw_a.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": null } })).await;+ room.gw_b.send(json!({ "op": 4, "d": { "guild_id": guild_id, "channel_id": null } })).await;+ pump_a.abort();+ pump_b.abort();+}diff --git a/src-tauri/omnidisc-mls/Cargo.toml b/src-tauri/omnidisc-mls/Cargo.tomlnew file mode 100644index 00000000..a88833eb--- /dev/null+++ b/src-tauri/omnidisc-mls/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "omnidisc-mls"+version = "0.1.0"+edition = "2021"+description = "OmniDisc client MLS engine (RFC 9420 via openmls): device identity, groups, message and file encryption"+license = "GPL-3.0"++[dependencies]+openmls = "0.8.1"+openmls_rust_crypto = "0.5.1"+openmls_basic_credential = "0.5.0"+openmls_traits = "0.5.0"+openmls_memory_storage = "0.5.0"+tls_codec = "0.4"+chacha20poly1305 = "0.10"+hkdf = "0.12"+sha2 = "0.10"+ed25519-dalek = "2"+rand = "0.10.0"+data-encoding = "2"+thiserror = "1"+serde = { version = "1", features = ["derive"] }+serde_json = "1"diff --git a/src-tauri/omnidisc-mls/src/client.rs b/src-tauri/omnidisc-mls/src/client.rsnew file mode 100644index 00000000..6eda070c--- /dev/null+++ b/src-tauri/omnidisc-mls/src/client.rs@@ -0,0 +1,892 @@+use crate::provider::Provider;+use crate::{MlsError, Result};+use data_encoding::BASE32_NOPAD;+use hkdf::Hkdf;+use openmls::prelude::*;+use openmls_basic_credential::SignatureKeyPair;+use openmls_traits::OpenMlsProvider;+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use tls_codec::{Deserialize as TlsDeserialize, Serialize as TlsSerialize};++const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;++/// Numeric ciphersuite the server stores alongside every key package.+pub const CIPHERSUITE_ID: u16 = 0x0001;+pub const VOICE_EXPORTER_LABEL: &str = "omnidisc-voice";+pub const VOICE_EXPORTER_INFO: &[u8] = b"omnidisc-voice-v1 livekit-shared-key";++/// Out-of-band verification string: base32 of SHA-256(pubkey)[..20], in groups+/// of four, e.g. `EYES-OGGZ-JXJN-6ENS-3VW3-KVPN-NHDO-SJ3V`.+pub fn fingerprint(public_key: &[u8]) -> String {+ let digest = Sha256::digest(public_key);+ let encoded = BASE32_NOPAD.encode(&digest[..20]);+ encoded+ .as_bytes()+ .chunks(4)+ .map(|c| std::str::from_utf8(c).unwrap_or("????"))+ .collect::<Vec<_>>()+ .join("-")+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MemberInfo {+ pub user_id: String,+ pub device_id: String,+ pub fingerprint: String,+ pub is_me: bool,+}++/// A device the caller has confirmed out of the MLS band: the identity it was+/// asked about and the signature key that device published on the server.+/// Everything the server hands us is checked against one of these, because a+/// hostile server can otherwise swap in a device of its own.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DeviceRef {+ pub user_id: String,+ pub device_id: String,+ pub signature_key: Vec<u8>,+}++impl DeviceRef {+ pub fn new(user_id: impl Into<String>, device_id: impl Into<String>, key: Vec<u8>) -> Self {+ Self { user_id: user_id.into(), device_id: device_id.into(), signature_key: key }+ }++ fn matches(&self, user_id: &str, device_id: &str, key: &[u8]) -> bool {+ self.user_id == user_id && self.device_id == device_id && self.signature_key == key+ }+}++/// A key package claimed from the server, bound to the device it must belong to.+#[derive(Debug, Clone)]+pub struct ClaimedDevice {+ pub device: DeviceRef,+ pub key_package: Vec<u8>,+}++#[derive(Debug, Clone)]+pub struct CommitOutput {+ pub commit: Vec<u8>,+ pub welcome: Option<Vec<u8>>,+ /// Epoch the group reaches once the server accepts this commit.+ pub epoch: u64,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Incoming {+ Application {+ user_id: String,+ device_id: String,+ /// The signature key of the leaf that sent this. MLS authenticates the+ /// leaf, never the identity string inside it, so the caller still has+ /// to match this against the device roster it fetched itself.+ signature_key: Vec<u8>,+ plaintext: Vec<u8>,+ },+ Commit { epoch: u64, removed_me: bool },+ Proposal,+}++pub struct MlsClient {+ user_id: String,+ device_id: String,+ provider: Provider,+ signer: SignatureKeyPair,+ credential: CredentialWithKey,+ public_key: [u8; 32],+ groups: HashMap<String, MlsGroup>,+}++fn mls<E: std::fmt::Debug>(what: &str) -> impl FnOnce(E) -> MlsError + '_ {+ move |e| {+ let text = format!("{e:?}");+ if text.contains("UseAfterEviction") {+ MlsError::Evicted+ } else {+ MlsError::Mls(format!("{what}: {text}"))+ }+ }+}++fn identity_parts(credential: &Credential) -> (String, String) {+ let raw = BasicCredential::try_from(credential.clone())+ .map(|b| String::from_utf8_lossy(b.identity()).into_owned())+ .unwrap_or_default();+ match raw.split_once(':') {+ Some((user, device)) => (user.to_string(), device.to_string()),+ None => (raw, String::new()),+ }+}++impl MlsClient {+ pub fn new(user_id: &str, device_id: &str, seed: &[u8; 32]) -> Result<Self> {+ Self::build(user_id, device_id, seed, Provider::fresh(), false, &[])+ }++ /// Rebuild from a blob produced by [`MlsClient::export_state`].+ pub fn restore(user_id: &str, device_id: &str, seed: &[u8; 32], blob: &[u8]) -> Result<Self> {+ let (group_ids, storage) = split_state(blob)?;+ let provider = Provider::from_blob(storage)?;+ Self::build(user_id, device_id, seed, provider, true, &group_ids)+ }++ fn build(+ user_id: &str,+ device_id: &str,+ seed: &[u8; 32],+ provider: Provider,+ restored: bool,+ group_ids: &[String],+ ) -> Result<Self> {+ let signing = ed25519_dalek::SigningKey::from_bytes(seed);+ let public_key = signing.verifying_key().to_bytes();+ let signer = if restored {+ SignatureKeyPair::read(provider.storage(), &public_key, SignatureScheme::ED25519)+ .ok_or_else(|| MlsError::State("device key missing from stored state".into()))?+ } else {+ let pair = SignatureKeyPair::from_raw(+ SignatureScheme::ED25519,+ signing.to_bytes().to_vec(),+ public_key.to_vec(),+ );+ pair.store(provider.storage()).map_err(mls("store signer"))?;+ pair+ };+ let credential = CredentialWithKey {+ credential: BasicCredential::new(format!("{user_id}:{device_id}").into_bytes()).into(),+ signature_key: public_key.to_vec().into(),+ };+ let mut groups = HashMap::new();+ for id in group_ids {+ let gid = GroupId::from_slice(id.as_bytes());+ match MlsGroup::load(provider.storage(), &gid).map_err(mls("load group"))? {+ Some(group) => {+ groups.insert(id.clone(), group);+ }+ // A group listed in the snapshot but missing from storage means a+ // partial write; dropping it is safer than refusing to start.+ None => {}+ }+ }+ Ok(Self {+ user_id: user_id.to_string(),+ device_id: device_id.to_string(),+ provider,+ signer,+ credential,+ public_key,+ groups,+ })+ }++ pub fn user_id(&self) -> &str {+ &self.user_id+ }++ pub fn device_id(&self) -> &str {+ &self.device_id+ }++ pub fn public_key(&self) -> [u8; 32] {+ self.public_key+ }++ pub fn fingerprint(&self) -> String {+ fingerprint(&self.public_key)+ }++ pub fn export_state(&self) -> Vec<u8> {+ let mut ids: Vec<&String> = self.groups.keys().collect();+ ids.sort();+ let mut out = Vec::new();+ out.extend_from_slice(&(ids.len() as u32).to_be_bytes());+ for id in ids {+ let bytes = id.as_bytes();+ out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());+ out.extend_from_slice(bytes);+ }+ out.extend_from_slice(&self.provider.to_blob());+ out+ }++ pub fn group_ids(&self) -> Vec<String> {+ let mut ids: Vec<String> = self.groups.keys().cloned().collect();+ ids.sort();+ ids+ }++ pub fn has_group(&self, group_id: &str) -> bool {+ self.groups.contains_key(group_id)+ }++ pub fn epoch(&self, group_id: &str) -> Option<u64> {+ self.groups.get(group_id).map(|g| g.epoch().as_u64())+ }++ /// Fresh key packages to publish. The last one is marked `last_resort` when+ /// asked, so a claim never fails just because the stock ran out.+ pub fn key_packages(&mut self, count: usize, last_resort: bool) -> Result<Vec<Vec<u8>>> {+ let mut out = Vec::with_capacity(count + usize::from(last_resort));+ for _ in 0..count {+ out.push(self.build_key_package(false)?);+ }+ if last_resort {+ out.push(self.build_key_package(true)?);+ }+ Ok(out)+ }++ fn build_key_package(&mut self, last_resort: bool) -> Result<Vec<u8>> {+ let builder = KeyPackage::builder();+ let builder = if last_resort { builder.mark_as_last_resort() } else { builder };+ let bundle = builder+ .build(CIPHERSUITE, &self.provider, &self.signer, self.credential.clone())+ .map_err(mls("key package"))?;+ let out: MlsMessageOut = bundle.into();+ out.tls_serialize_detached().map_err(mls("serialise key package"))+ }++ pub fn create_group(&mut self, group_id: &str) -> Result<()> {+ if self.groups.contains_key(group_id) {+ return Ok(());+ }+ let config = MlsGroupCreateConfig::builder()+ .ciphersuite(CIPHERSUITE)+ .use_ratchet_tree_extension(true)+ .build();+ let group = MlsGroup::new_with_group_id(+ &self.provider,+ &self.signer,+ &config,+ GroupId::from_slice(group_id.as_bytes()),+ self.credential.clone(),+ )+ .map_err(mls("create group"))?;+ self.groups.insert(group_id.to_string(), group);+ Ok(())+ }++ /// Parse a claimed key package and bind it to the device it must belong to.+ /// `validate` only proves the package is self-consistent; without the two+ /// checks below the server could hand us a package of its own and an honest+ /// client would add the server's device to the group.+ fn parse_key_package(&self, bytes: &[u8], expected: &DeviceRef) -> Result<KeyPackage> {+ let msg = MlsMessageIn::tls_deserialize(&mut &bytes[..])+ .map_err(|e| MlsError::Malformed(format!("key package: {e}")))?;+ let kp = match msg.extract() {+ MlsMessageBodyIn::KeyPackage(kp) => kp+ .validate(self.provider.crypto(), ProtocolVersion::Mls10)+ .map_err(mls("validate key package"))?,+ _ => return Err(MlsError::Malformed("not a key package".into())),+ };+ let leaf = kp.leaf_node();+ let (user_id, device_id) = identity_parts(leaf.credential());+ if user_id != expected.user_id || device_id != expected.device_id {+ return Err(MlsError::Untrusted(format!(+ "a key package claimed for {}:{} carries the identity {}:{}",+ expected.user_id, expected.device_id, user_id, device_id+ )));+ }+ if leaf.signature_key().as_slice() != expected.signature_key.as_slice() {+ return Err(MlsError::Untrusted(format!(+ "the key package for {}:{} is signed by a key that device never published",+ expected.user_id, expected.device_id+ )));+ }+ Ok(kp)+ }++ /// Stage a commit adding devices. The commit is NOT merged: the caller must+ /// call [`MlsClient::merge_pending`] only after the server accepted it, and+ /// [`MlsClient::clear_pending`] on a 409 — merging a commit the server+ /// rejected would fork the group for this device.+ pub fn add_members(&mut self, group_id: &str, devices: &[ClaimedDevice]) -> Result<CommitOutput> {+ let parsed = devices+ .iter()+ .map(|d| self.parse_key_package(&d.key_package, &d.device))+ .collect::<Result<Vec<_>>>()?;+ let Self { groups, provider, signer, .. } = self;+ let group = groups+ .get_mut(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ let (commit, welcome, _info) = group+ .add_members(provider, signer, &parsed)+ .map_err(mls("add_members"))?;+ Ok(CommitOutput {+ commit: commit.tls_serialize_detached().map_err(mls("serialise commit"))?,+ welcome: Some(welcome.tls_serialize_detached().map_err(mls("serialise welcome"))?),+ epoch: group.epoch().as_u64() + 1,+ })+ }++ pub fn remove_devices(&mut self, group_id: &str, device_ids: &[String]) -> Result<CommitOutput> {+ let leaves: Vec<LeafNodeIndex> = {+ let group = self+ .groups+ .get(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ group+ .members()+ .filter(|m| {+ let (_, device) = identity_parts(&m.credential);+ device_ids.iter().any(|d| *d == device)+ })+ .map(|m| m.index)+ .collect()+ };+ if leaves.is_empty() {+ return Err(MlsError::Malformed("none of those devices are in the group".into()));+ }+ let Self { groups, provider, signer, .. } = self;+ let group = groups+ .get_mut(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ let (commit, welcome, _info) = group+ .remove_members(provider, signer, &leaves)+ .map_err(mls("remove_members"))?;+ Ok(CommitOutput {+ commit: commit.tls_serialize_detached().map_err(mls("serialise commit"))?,+ welcome: welcome+ .map(|w| w.tls_serialize_detached().map_err(mls("serialise welcome")))+ .transpose()?,+ epoch: group.epoch().as_u64() + 1,+ })+ }++ pub fn merge_pending(&mut self, group_id: &str) -> Result<u64> {+ let Self { groups, provider, .. } = self;+ let group = groups+ .get_mut(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ group.merge_pending_commit(provider).map_err(mls("merge_pending_commit"))?;+ Ok(group.epoch().as_u64())+ }++ pub fn clear_pending(&mut self, group_id: &str) -> Result<()> {+ let Self { groups, provider, .. } = self;+ let group = groups+ .get_mut(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ group+ .clear_pending_commit(provider.storage())+ .map_err(mls("clear_pending_commit"))+ }++ /// Join a group we were welcomed into.+ ///+ /// A Welcome is the one MLS message that creates state out of nothing, so+ /// it is the one the server can forge a whole group with. Three refusals+ /// keep it honest: the group id has to be the one the caller expected, we+ /// must not already have that group (joining again would silently re-key+ /// the channel onto whoever sent the second Welcome), and the member that+ /// added us has to be a device the caller already knows is a recipient of+ /// that channel.+ pub fn join_welcome(+ &mut self,+ bytes: &[u8],+ expected_group_id: &str,+ allowed_senders: &[DeviceRef],+ ) -> Result<String> {+ if self.groups.contains_key(expected_group_id) {+ return Err(MlsError::GroupExists(expected_group_id.to_string()));+ }+ let msg = MlsMessageIn::tls_deserialize(&mut &bytes[..])+ .map_err(|e| MlsError::Malformed(format!("welcome: {e}")))?;+ let welcome = match msg.extract() {+ MlsMessageBodyIn::Welcome(w) => w,+ _ => return Err(MlsError::Malformed("not a welcome".into())),+ };+ let staged = StagedWelcome::new_from_welcome(+ &self.provider,+ &MlsGroupJoinConfig::default(),+ welcome,+ None,+ )+ .map_err(mls("staged welcome"))?;+ let id =+ String::from_utf8_lossy(staged.group_context().group_id().as_slice()).into_owned();+ if id != expected_group_id {+ return Err(MlsError::Untrusted(format!(+ "a Welcome announced as {expected_group_id} is really for {id}"+ )));+ }+ if self.groups.contains_key(&id) {+ return Err(MlsError::GroupExists(id));+ }+ let sender = staged.welcome_sender().map_err(mls("welcome sender"))?;+ let (sender_user, sender_device) = identity_parts(sender.credential());+ let sender_key = sender.signature_key().as_slice().to_vec();+ if !allowed_senders+ .iter()+ .any(|d| d.matches(&sender_user, &sender_device, &sender_key))+ {+ return Err(MlsError::Untrusted(format!(+ "{sender_user}:{sender_device} is not a known device of anyone in {id}"+ )));+ }+ let group = staged.into_group(&self.provider).map_err(mls("into_group"))?;+ self.groups.insert(id.clone(), group);+ Ok(id)+ }++ pub fn encrypt(&mut self, group_id: &str, plaintext: &[u8]) -> Result<(Vec<u8>, u64)> {+ let Self { groups, provider, signer, .. } = self;+ let group = groups+ .get_mut(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ let out = group+ .create_message(provider, signer, plaintext)+ .map_err(mls("create_message"))?;+ Ok((+ out.tls_serialize_detached().map_err(mls("serialise message"))?,+ group.epoch().as_u64(),+ ))+ }++ pub fn process(&mut self, group_id: &str, bytes: &[u8]) -> Result<Incoming> {+ let msg = MlsMessageIn::tls_deserialize(&mut &bytes[..])+ .map_err(|e| MlsError::Malformed(format!("envelope: {e}")))?;+ let protocol = msg+ .try_into_protocol_message()+ .map_err(|e| MlsError::Malformed(format!("not a protocol message: {e:?}")))?;+ let Self { groups, provider, .. } = self;+ let group = groups+ .get_mut(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ let processed = group+ .process_message(provider, protocol)+ .map_err(mls("process_message"))?;+ let (user_id, device_id) = identity_parts(processed.credential());+ let signature_key = match processed.sender() {+ Sender::Member(index) => {+ let index = *index;+ group+ .members()+ .find(|m| m.index == index)+ .map(|m| m.signature_key)+ .unwrap_or_default()+ }+ _ => Vec::new(),+ };+ match processed.into_content() {+ ProcessedMessageContent::ApplicationMessage(app) => Ok(Incoming::Application {+ user_id,+ device_id,+ signature_key,+ plaintext: app.into_bytes(),+ }),+ ProcessedMessageContent::StagedCommitMessage(staged) => {+ let removed_me = staged.self_removed();+ group+ .merge_staged_commit(provider, *staged)+ .map_err(mls("merge_staged_commit"))?;+ Ok(Incoming::Commit { epoch: group.epoch().as_u64(), removed_me })+ }+ ProcessedMessageContent::ProposalMessage(p) => {+ group+ .store_pending_proposal(provider.storage(), *p)+ .map_err(mls("store_pending_proposal"))?;+ Ok(Incoming::Proposal)+ }+ ProcessedMessageContent::ExternalJoinProposalMessage(_) => Ok(Incoming::Proposal),+ }+ }++ /// A removed member's group stays around and errors on every later call, so+ /// the client has to drop it itself (S-05 gotcha 6).+ pub fn drop_group(&mut self, group_id: &str) -> Result<()> {+ if let Some(mut group) = self.groups.remove(group_id) {+ let _ = group.delete(self.provider.storage());+ }+ Ok(())+ }++ pub fn members(&self, group_id: &str) -> Vec<MemberInfo> {+ let Some(group) = self.groups.get(group_id) else { return vec![] };+ group+ .members()+ .map(|m| {+ let (user_id, device_id) = identity_parts(&m.credential);+ let is_me = user_id == self.user_id && device_id == self.device_id;+ MemberInfo {+ user_id,+ device_id,+ fingerprint: fingerprint(&m.signature_key),+ is_me,+ }+ })+ .collect()+ }++ pub fn member_device_ids(&self, group_id: &str) -> Vec<String> {+ self.members(group_id).into_iter().map(|m| m.device_id).collect()+ }++ /// Room key for LiveKit's shared-key E2EE mode. Same on every member, new on+ /// every epoch, undefined for a device that was removed.+ pub fn voice_key(&self, group_id: &str, room_id: &[u8]) -> Result<[u8; 32]> {+ let group = self+ .groups+ .get(group_id)+ .ok_or_else(|| MlsError::UnknownGroup(group_id.to_string()))?;+ let exported = group+ .export_secret(self.provider.crypto(), VOICE_EXPORTER_LABEL, room_id, 32)+ .map_err(mls("export_secret"))?;+ let hk = Hkdf::<Sha256>::new(Some(room_id), &exported);+ let mut key = [0u8; 32];+ hk.expand(VOICE_EXPORTER_INFO, &mut key)+ .map_err(|_| MlsError::Mls("hkdf expand".into()))?;+ Ok(key)+ }+}++fn split_state(blob: &[u8]) -> Result<(Vec<String>, &[u8])> {+ if blob.len() < 4 {+ return Err(MlsError::State("truncated state".into()));+ }+ let mut cursor = 0usize;+ let count = u32::from_be_bytes([blob[0], blob[1], blob[2], blob[3]]) as usize;+ cursor += 4;+ let mut ids = Vec::with_capacity(count.min(1024));+ for _ in 0..count {+ if blob.len() < cursor + 4 {+ return Err(MlsError::State("truncated group list".into()));+ }+ let len = u32::from_be_bytes([+ blob[cursor],+ blob[cursor + 1],+ blob[cursor + 2],+ blob[cursor + 3],+ ]) as usize;+ cursor += 4;+ if blob.len() < cursor + len {+ return Err(MlsError::State("truncated group id".into()));+ }+ ids.push(String::from_utf8_lossy(&blob[cursor..cursor + len]).into_owned());+ cursor += len;+ }+ Ok((ids, &blob[cursor..]))+}++#[cfg(test)]+mod tests {+ use super::*;++ const GROUP: &str = "od-group-000000001";+ const ROOM: &[u8] = b"voice-room-1";++ fn client(user: &str, device: &str, seed: u8) -> MlsClient {+ MlsClient::new(user, device, &[seed; 32]).expect("client")+ }++ fn device_ref(c: &MlsClient) -> DeviceRef {+ DeviceRef::new(c.user_id(), c.device_id(), c.public_key().to_vec())+ }++ /// One claimed key package, correctly bound to the device that made it.+ fn claim(c: &mut MlsClient) -> ClaimedDevice {+ ClaimedDevice {+ device: device_ref(c),+ key_package: c.key_packages(1, false).expect("kp").remove(0),+ }+ }++ /// Add `joiners` to `owner`'s group and hand each of them the welcome.+ fn add_all(owner: &mut MlsClient, joiners: &mut [&mut MlsClient]) -> CommitOutput {+ let claimed: Vec<ClaimedDevice> = joiners.iter_mut().map(|c| claim(c)).collect();+ let out = owner.add_members(GROUP, &claimed).expect("add");+ owner.merge_pending(GROUP).expect("merge");+ let welcome = out.welcome.clone().expect("welcome");+ let allowed = [device_ref(owner)];+ for joiner in joiners.iter_mut() {+ let id = joiner.join_welcome(&welcome, GROUP, &allowed).expect("join");+ assert_eq!(id, GROUP);+ }+ out+ }++ #[test]+ fn three_devices_exchange_messages_and_rotate_epochs() {+ let mut alice = client("1001", "desktop-a", 1);+ let mut bob = client("2002", "phone-bbb", 2);+ let mut carol = client("3003", "tablet-cc", 3);+ alice.create_group(GROUP).expect("create");+ assert_eq!(alice.epoch(GROUP), Some(0));++ let out = add_all(&mut alice, &mut [&mut bob]);+ assert_eq!(out.epoch, 1);+ assert_eq!(alice.epoch(GROUP), Some(1));+ assert_eq!(bob.epoch(GROUP), Some(1));++ let (ct, epoch) = alice.encrypt(GROUP, b"hello bob").expect("encrypt");+ assert_eq!(epoch, 1);+ assert!(!ct.windows(9).any(|w| w == b"hello bob"), "ciphertext leaked the plaintext");+ match bob.process(GROUP, &ct).expect("decrypt") {+ Incoming::Application { user_id, device_id, plaintext, .. } => {+ assert_eq!(user_id, "1001");+ assert_eq!(device_id, "desktop-a");+ assert_eq!(plaintext, b"hello bob");+ }+ other => panic!("expected an application message, got {other:?}"),+ }++ // Carol joins: epoch advances for everyone, and the existing member has+ // to process the commit to keep up.+ let carol_kp = claim(&mut carol);+ let commit = alice.add_members(GROUP, &[carol_kp]).expect("add carol");+ alice.merge_pending(GROUP).expect("merge");+ assert!(matches!(+ bob.process(GROUP, &commit.commit).expect("bob commit"),+ Incoming::Commit { epoch: 2, removed_me: false }+ ));+ carol+ .join_welcome(&commit.welcome.clone().expect("welcome"), GROUP, &[device_ref(&alice)])+ .expect("carol join");+ assert_eq!(carol.epoch(GROUP), Some(2));+ assert_eq!(alice.members(GROUP).len(), 3);++ let (ct, _) = carol.encrypt(GROUP, b"carol here").expect("encrypt");+ for member in [&mut alice, &mut bob] {+ match member.process(GROUP, &ct).expect("decrypt") {+ Incoming::Application { plaintext, .. } => assert_eq!(plaintext, b"carol here"),+ other => panic!("expected an application message, got {other:?}"),+ }+ }+ }++ #[test]+ fn a_removed_device_cannot_read_what_comes_next() {+ let mut alice = client("1001", "desktop-a", 11);+ let mut bob = client("2002", "phone-bbb", 12);+ let mut carol = client("3003", "tablet-cc", 13);+ alice.create_group(GROUP).expect("create");+ add_all(&mut alice, &mut [&mut bob, &mut carol]);++ let out = alice.remove_devices(GROUP, &["tablet-cc".to_string()]).expect("remove");+ alice.merge_pending(GROUP).expect("merge");+ assert!(matches!(+ bob.process(GROUP, &out.commit).expect("bob"),+ Incoming::Commit { removed_me: false, .. }+ ));+ assert!(matches!(+ carol.process(GROUP, &out.commit).expect("carol"),+ Incoming::Commit { removed_me: true, .. }+ ));++ let (ct, _) = alice.encrypt(GROUP, b"after the removal").expect("encrypt");+ assert!(matches!(+ bob.process(GROUP, &ct).expect("bob decrypt"),+ Incoming::Application { .. }+ ));+ assert!(carol.process(GROUP, &ct).is_err(), "a removed device decrypted a new message");+ carol.drop_group(GROUP).expect("drop");+ assert!(!carol.has_group(GROUP));+ }++ #[test]+ fn a_rejected_commit_can_be_cleared_and_retried() {+ let mut alice = client("1001", "desktop-a", 21);+ let mut bob = client("2002", "phone-bbb", 22);+ let mut carol = client("3003", "tablet-cc", 23);+ alice.create_group(GROUP).expect("create");+ add_all(&mut alice, &mut [&mut bob]);++ // Alice stages a commit adding Carol, the server rejects it (409), and+ // Bob's commit lands instead.+ let carol_kp = claim(&mut carol);+ alice.add_members(GROUP, &[carol_kp]).expect("stage");+ alice.clear_pending(GROUP).expect("clear");+ let bob_commit = bob.remove_devices(GROUP, &["desktop-a".to_string()]);+ assert!(bob_commit.is_ok(), "bob can still commit after alice cleared hers");+ }++ #[test]+ fn voice_key_agrees_per_epoch_and_changes_with_membership() {+ let mut alice = client("1001", "desktop-a", 31);+ let mut bob = client("2002", "phone-bbb", 32);+ let mut carol = client("3003", "tablet-cc", 33);+ alice.create_group(GROUP).expect("create");+ add_all(&mut alice, &mut [&mut bob]);+ let k1 = alice.voice_key(GROUP, ROOM).expect("key");+ assert_eq!(k1, bob.voice_key(GROUP, ROOM).expect("key"));++ let carol_kp = claim(&mut carol);+ let commit = alice.add_members(GROUP, &[carol_kp]).expect("add");+ alice.merge_pending(GROUP).expect("merge");+ bob.process(GROUP, &commit.commit).expect("bob");+ carol+ .join_welcome(&commit.welcome.clone().expect("welcome"), GROUP, &[device_ref(&alice)])+ .expect("join");+ let k2 = alice.voice_key(GROUP, ROOM).expect("key");+ assert_ne!(k1, k2, "the voice key must rotate on a membership change");+ assert_eq!(k2, bob.voice_key(GROUP, ROOM).expect("key"));+ assert_eq!(k2, carol.voice_key(GROUP, ROOM).expect("key"));+ assert_ne!(k2, alice.voice_key(GROUP, b"another-room").expect("key"));+ }++ #[test]+ fn state_survives_a_restart() {+ let seed = [41u8; 32];+ let mut alice = MlsClient::new("1001", "desktop-a", &seed).expect("client");+ let mut bob = client("2002", "phone-bbb", 42);+ alice.create_group(GROUP).expect("create");+ add_all(&mut alice, &mut [&mut bob]);++ let blob = alice.export_state();+ let mut restored = MlsClient::restore("1001", "desktop-a", &seed, &blob).expect("restore");+ assert_eq!(restored.group_ids(), vec![GROUP.to_string()]);+ assert_eq!(restored.epoch(GROUP), alice.epoch(GROUP));+ assert_eq!(restored.fingerprint(), alice.fingerprint());++ let (ct, _) = restored.encrypt(GROUP, b"after the restart").expect("encrypt");+ match bob.process(GROUP, &ct).expect("decrypt") {+ Incoming::Application { plaintext, .. } => assert_eq!(plaintext, b"after the restart"),+ other => panic!("expected an application message, got {other:?}"),+ }+ let (back, _) = bob.encrypt(GROUP, b"and back").expect("encrypt");+ match restored.process(GROUP, &back).expect("decrypt") {+ Incoming::Application { plaintext, .. } => assert_eq!(plaintext, b"and back"),+ other => panic!("expected an application message, got {other:?}"),+ }+ assert!(MlsClient::restore("1001", "desktop-a", &seed, &blob[..2]).is_err());+ }++ /// C1: a hostile server fabricates a second group under the id of a channel+ /// the victim already has, welcomes them into it, and every later message+ /// goes to whoever owns that group. The second Welcome must bounce.+ #[test]+ fn a_second_welcome_for_a_group_we_already_have_is_refused() {+ let mut alice = client("1001", "desktop-a", 51);+ let mut bob = client("2002", "phone-bbb", 52);+ let mut attacker = client("6006", "evil-0001", 53);+ alice.create_group(GROUP).expect("create");+ add_all(&mut alice, &mut [&mut bob]);+ let before = bob.epoch(GROUP).expect("epoch");++ // The attacker builds their own group under the very same id.+ attacker.create_group(GROUP).expect("create");+ let bob_kp = claim(&mut bob);+ let hijack = attacker.add_members(GROUP, &[bob_kp]).expect("add");+ attacker.merge_pending(GROUP).expect("merge");+ let welcome = hijack.welcome.clone().expect("welcome");++ let err = bob+ .join_welcome(&welcome, GROUP, &[device_ref(&attacker)])+ .expect_err("the second welcome must be refused");+ assert!(matches!(err, MlsError::GroupExists(_)), "{err:?}");+ assert_eq!(bob.epoch(GROUP), Some(before), "the group was re-keyed anyway");++ let (ct, _) = alice.encrypt(GROUP, b"still ours").expect("encrypt");+ match bob.process(GROUP, &ct).expect("decrypt") {+ Incoming::Application { plaintext, .. } => assert_eq!(plaintext, b"still ours"),+ other => panic!("expected an application message, got {other:?}"),+ }+ }++ /// C1: the same attack against a channel the victim has no group for yet.+ /// Nothing local contradicts it, so the only defence is the sender: the+ /// attacker is not a recipient of that channel.+ #[test]+ fn a_welcome_from_someone_outside_the_channel_is_refused() {+ let mut alice = client("1001", "desktop-a", 61);+ let mut attacker = client("6006", "evil-0001", 62);+ let mut bob = client("2002", "phone-bbb", 63);+ attacker.create_group(GROUP).expect("create");+ let bob_kp = claim(&mut bob);+ let out = attacker.add_members(GROUP, &[bob_kp]).expect("add");+ attacker.merge_pending(GROUP).expect("merge");+ let welcome = out.welcome.clone().expect("welcome");++ // Only Alice is a recipient of this channel, so only her devices may add us.+ let allowed = [device_ref(&alice)];+ let err = bob+ .join_welcome(&welcome, GROUP, &allowed)+ .expect_err("a stranger must not be able to welcome us");+ assert!(matches!(err, MlsError::Untrusted(_)), "{err:?}");+ assert!(!bob.has_group(GROUP));++ // Staging a welcome consumes the key package it was addressed to, so the+ // group-id check gets its own victim and its own welcome.+ let mut carol = client("3003", "tablet-cc", 64);+ let carol_kp = claim(&mut carol);+ let out = attacker.add_members(GROUP, &[carol_kp]).expect("add");+ attacker.merge_pending(GROUP).expect("merge");+ let err = carol+ .join_welcome(+ &out.welcome.clone().expect("welcome"),+ "od-other-channel",+ &[device_ref(&attacker)],+ )+ .expect_err("the announced group id must match the welcome");+ assert!(matches!(err, MlsError::Untrusted(_)), "{err:?}");+ assert!(!carol.has_group("od-other-channel"));+ assert!(!carol.has_group(GROUP));+ }++ /// C2: the server hands back a key package of its own under the device id it+ /// was asked for. Binding to the published signature key is what catches it.+ #[test]+ fn a_key_package_that_is_not_the_claimed_device_is_refused() {+ let mut alice = client("1001", "desktop-a", 71);+ let mut bob = client("2002", "phone-bbb", 72);+ let mut attacker = client("6006", "evil-0001", 73);+ alice.create_group(GROUP).expect("create");++ // Right identity string, wrong key: the server minted the package itself.+ let substituted = ClaimedDevice {+ device: device_ref(&bob),+ key_package: attacker.key_packages(1, false).expect("kp").remove(0),+ };+ let err = alice+ .add_members(GROUP, &[substituted])+ .expect_err("a substituted key package must be refused");+ assert!(matches!(err, MlsError::Untrusted(_)), "{err:?}");++ // Right key, but claimed for a device id we never asked about.+ let mut renamed = claim(&mut bob);+ renamed.device.device_id = "phone-zzz".into();+ let err = alice+ .add_members(GROUP, &[renamed])+ .expect_err("a key package for another device must be refused");+ assert!(matches!(err, MlsError::Untrusted(_)), "{err:?}");++ // And the honest one still goes through.+ let honest = claim(&mut bob);+ alice.add_members(GROUP, &[honest]).expect("add");+ assert_eq!(alice.members(GROUP).len(), 1, "a refused commit must not be staged");+ }++ /// C2: attribution. The identity string in a leaf is whatever its owner+ /// typed, so the caller has to match the signature key against the roster.+ #[test]+ fn application_messages_carry_the_senders_signature_key() {+ let mut alice = client("1001", "desktop-a", 81);+ let mut bob = client("2002", "phone-bbb", 82);+ alice.create_group(GROUP).expect("create");+ add_all(&mut alice, &mut [&mut bob]);++ let (ct, _) = alice.encrypt(GROUP, b"from alice").expect("encrypt");+ match bob.process(GROUP, &ct).expect("decrypt") {+ Incoming::Application { user_id, device_id, signature_key, .. } => {+ assert_eq!(user_id, "1001");+ assert_eq!(device_id, "desktop-a");+ assert_eq!(signature_key, alice.public_key().to_vec());+ assert!(device_ref(&alice).matches(&user_id, &device_id, &signature_key));+ // A roster that does not list this key must not vouch for it.+ let impostor = DeviceRef::new("1001", "desktop-a", vec![0u8; 32]);+ assert!(!impostor.matches(&user_id, &device_id, &signature_key));+ }+ other => panic!("expected an application message, got {other:?}"),+ }+ }++ #[test]+ fn fingerprints_are_stable_grouped_base32() {+ let fp = fingerprint(&[0u8; 32]);+ assert_eq!(fp.len(), 32 + 7);+ assert!(fp.split('-').all(|c| c.len() == 4));+ assert_eq!(fp, fingerprint(&[0u8; 32]));+ assert_ne!(fp, fingerprint(&[1u8; 32]));+ }+}diff --git a/src-tauri/omnidisc-mls/src/file.rs b/src-tauri/omnidisc-mls/src/file.rsnew file mode 100644index 00000000..55ba5198--- /dev/null+++ b/src-tauri/omnidisc-mls/src/file.rs@@ -0,0 +1,244 @@+//! Per-file XChaCha20-Poly1305, one AEAD per 1 MiB chunk (ADR 0014 §3).+//!+//! Nonce = `file_nonce(16) ‖ chunk_index u64 BE`, AAD =+//! `"omnidisc-file-v1|" ‖ file_id ‖ index ‖ total_chunks`. Putting the index and+//! the total in both nonce and AAD is what makes a reordered, duplicated or+//! truncated file fail loudly instead of decoding into garbage.++use crate::{MlsError, Result};+use chacha20poly1305::aead::{AeadInPlace, KeyInit};+use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};+use rand::Rng;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::fs::File;+use std::io::{BufReader, BufWriter, Read, Write};+use std::path::Path;++pub const CHUNK_SIZE: usize = 1024 * 1024;+pub const TAG_SIZE: usize = 16;++/// The key material that travels inside the MLS message, never near the server.+/// `Debug` is deliberately not derived so a key cannot be logged by accident.+#[derive(Clone, Serialize, Deserialize)]+pub struct FileSecret {+ pub key: [u8; 32],+ pub nonce: [u8; 16],+}++pub fn new_file_secret() -> FileSecret {+ let mut rng = rand::rng();+ let mut key = [0u8; 32];+ let mut nonce = [0u8; 16];+ rng.fill_bytes(&mut key);+ rng.fill_bytes(&mut nonce);+ FileSecret { key, nonce }+}++pub fn chunk_count(size: u64) -> u64 {+ if size == 0 {+ 1+ } else {+ size.div_ceil(CHUNK_SIZE as u64)+ }+}++pub fn encrypted_size(size: u64) -> u64 {+ size + chunk_count(size) * TAG_SIZE as u64+}++fn chunk_nonce(file_nonce: &[u8; 16], index: u64) -> XNonce {+ let mut n = [0u8; 24];+ n[..16].copy_from_slice(file_nonce);+ n[16..].copy_from_slice(&index.to_be_bytes());+ *XNonce::from_slice(&n)+}++fn chunk_aad(file_id: &str, index: u64, total: u64) -> Vec<u8> {+ let mut aad = Vec::with_capacity(64);+ aad.extend_from_slice(b"omnidisc-file-v1|");+ aad.extend_from_slice(file_id.as_bytes());+ aad.extend_from_slice(&index.to_be_bytes());+ aad.extend_from_slice(&total.to_be_bytes());+ aad+}++/// Streams `src` into `dst`, one chunk at a time. Memory stays at one chunk+/// regardless of file size, which is the whole point (a 2 GB upload must not+/// mean 2 GB of RAM). Returns the plaintext size and its SHA-256, both of which+/// go in the manifest so the receiver can verify what it got.+pub fn encrypt_file(+ src: &Path,+ dst: &Path,+ secret: &FileSecret,+ file_id: &str,+) -> Result<(u64, String)> {+ let size = std::fs::metadata(src)?.len();+ let total = chunk_count(size);+ let cipher = XChaCha20Poly1305::new(Key::from_slice(&secret.key));+ let mut reader = BufReader::with_capacity(CHUNK_SIZE, File::open(src)?);+ let mut writer = BufWriter::with_capacity(CHUNK_SIZE, File::create(dst)?);+ let mut hasher = Sha256::new();+ let mut buf: Vec<u8> = Vec::with_capacity(CHUNK_SIZE + TAG_SIZE);+ let mut index = 0u64;+ loop {+ buf.clear();+ buf.resize(CHUNK_SIZE, 0);+ let mut filled = 0usize;+ while filled < CHUNK_SIZE {+ let n = reader.read(&mut buf[filled..])?;+ if n == 0 {+ break;+ }+ filled += n;+ }+ if filled == 0 && index > 0 {+ break;+ }+ buf.truncate(filled);+ hasher.update(&buf);+ cipher+ .encrypt_in_place(&chunk_nonce(&secret.nonce, index), &chunk_aad(file_id, index, total), &mut buf)+ .map_err(|_| MlsError::File(format!("chunk {index}: could not be encrypted")))?;+ writer.write_all(&buf)?;+ index += 1;+ if filled < CHUNK_SIZE {+ break;+ }+ }+ writer.flush()?;+ Ok((size, hex(&hasher.finalize())))+}++/// Reverse of [`encrypt_file`]; returns the SHA-256 of the plaintext it wrote so+/// the caller can compare it with the manifest.+pub fn decrypt_file(+ src: &Path,+ dst: &Path,+ secret: &FileSecret,+ file_id: &str,+ size: u64,+) -> Result<String> {+ let total = chunk_count(size);+ let cipher = XChaCha20Poly1305::new(Key::from_slice(&secret.key));+ let mut reader = BufReader::with_capacity(CHUNK_SIZE, File::open(src)?);+ let mut writer = BufWriter::with_capacity(CHUNK_SIZE, File::create(dst)?);+ let mut hasher = Sha256::new();+ let mut buf: Vec<u8> = Vec::with_capacity(CHUNK_SIZE + TAG_SIZE);+ let mut remaining = size;+ for index in 0..total {+ let plain_len = remaining.min(CHUNK_SIZE as u64) as usize;+ buf.clear();+ buf.resize(plain_len + TAG_SIZE, 0);+ reader+ .read_exact(&mut buf)+ .map_err(|_| MlsError::File(format!("chunk {index}: the file ends too early")))?;+ cipher+ .decrypt_in_place(&chunk_nonce(&secret.nonce, index), &chunk_aad(file_id, index, total), &mut buf)+ .map_err(|_| MlsError::File(format!("chunk {index}: authentication failed")))?;+ hasher.update(&buf);+ writer.write_all(&buf)?;+ remaining -= plain_len as u64;+ }+ writer.flush()?;+ Ok(hex(&hasher.finalize()))+}++fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp(name: &str) -> std::path::PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "omnidisc-mls-file-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ std::fs::create_dir_all(&dir).expect("temp dir");+ dir.join(name)+ }++ fn write(path: &Path, bytes: &[u8]) {+ std::fs::write(path, bytes).expect("write");+ }++ #[test]+ fn round_trips_a_multi_chunk_file_and_keeps_the_hash() {+ let plain = temp("plain.bin");+ let enc = temp("enc.bin");+ let out = temp("out.bin");+ let data: Vec<u8> = (0..(CHUNK_SIZE * 2 + 4096)).map(|i| (i % 251) as u8).collect();+ write(&plain, &data);+ let secret = new_file_secret();+ let (size, sha) = encrypt_file(&plain, &enc, &secret, "file-1").expect("encrypt");+ assert_eq!(size, data.len() as u64);+ assert_eq!(std::fs::metadata(&enc).expect("meta").len(), encrypted_size(size));+ let back = decrypt_file(&enc, &out, &secret, "file-1", size).expect("decrypt");+ assert_eq!(back, sha);+ assert_eq!(std::fs::read(&out).expect("read"), data);+ }++ #[test]+ fn an_empty_file_is_still_one_authenticated_chunk() {+ let plain = temp("empty.bin");+ let enc = temp("empty.enc");+ let out = temp("empty.out");+ write(&plain, b"");+ let secret = new_file_secret();+ let (size, _) = encrypt_file(&plain, &enc, &secret, "file-e").expect("encrypt");+ assert_eq!(size, 0);+ assert_eq!(std::fs::metadata(&enc).expect("meta").len(), TAG_SIZE as u64);+ decrypt_file(&enc, &out, &secret, "file-e", 0).expect("decrypt");+ assert!(std::fs::read(&out).expect("read").is_empty());+ }++ #[test]+ fn tampering_dropping_and_swapping_chunks_are_all_rejected() {+ let plain = temp("t.bin");+ let enc = temp("t.enc");+ let out = temp("t.out");+ let data: Vec<u8> = (0..(CHUNK_SIZE * 2 + 10)).map(|i| (i % 97) as u8).collect();+ write(&plain, &data);+ let secret = new_file_secret();+ let (size, _) = encrypt_file(&plain, &enc, &secret, "file-2").expect("encrypt");+ let good = std::fs::read(&enc).expect("read");++ let mut tampered = good.clone();+ tampered[CHUNK_SIZE + 32] ^= 0xff;+ write(&enc, &tampered);+ assert!(decrypt_file(&enc, &out, &secret, "file-2", size).is_err());++ let cut = &good[..good.len() - (10 + TAG_SIZE)];+ write(&enc, cut);+ assert!(decrypt_file(&enc, &out, &secret, "file-2", size).is_err());++ let stride = CHUNK_SIZE + TAG_SIZE;+ let mut swapped = Vec::with_capacity(good.len());+ swapped.extend_from_slice(&good[stride..stride * 2]);+ swapped.extend_from_slice(&good[..stride]);+ swapped.extend_from_slice(&good[stride * 2..]);+ write(&enc, &swapped);+ assert!(decrypt_file(&enc, &out, &secret, "file-2", size).is_err());++ write(&enc, &good);+ assert!(decrypt_file(&enc, &out, &secret, "file-other", size).is_err());+ let other = new_file_secret();+ assert!(decrypt_file(&enc, &out, &other, "file-2", size).is_err());+ }++ #[test]+ fn chunk_counts_cover_the_edges() {+ assert_eq!(chunk_count(0), 1);+ assert_eq!(chunk_count(1), 1);+ assert_eq!(chunk_count(CHUNK_SIZE as u64), 1);+ assert_eq!(chunk_count(CHUNK_SIZE as u64 + 1), 2);+ assert_eq!(encrypted_size(CHUNK_SIZE as u64 + 1), CHUNK_SIZE as u64 + 1 + 32);+ }+}diff --git a/src-tauri/omnidisc-mls/src/lib.rs b/src-tauri/omnidisc-mls/src/lib.rsnew file mode 100644index 00000000..8f38c41d--- /dev/null+++ b/src-tauri/omnidisc-mls/src/lib.rs@@ -0,0 +1,47 @@+//! MLS (RFC 9420) engine for the OmniDisc client, per ADR 0014 and spike S-05.+//!+//! Everything here is deliberately transport-free: it turns bytes into bytes.+//! The Tauri layer owns the HTTP calls, the gateway and the persistence path;+//! this crate owns the cryptography and the group state machine so it can be+//! unit-tested without a server.++mod client;+mod file;+mod provider;+mod state;++pub use client::{+ fingerprint, ClaimedDevice, CommitOutput, DeviceRef, Incoming, MemberInfo, MlsClient,+ CIPHERSUITE_ID, VOICE_EXPORTER_INFO, VOICE_EXPORTER_LABEL,+};+pub use file::{+ chunk_count, decrypt_file, encrypt_file, encrypted_size, new_file_secret, FileSecret,+ CHUNK_SIZE, TAG_SIZE,+};+pub use state::{decrypt_state, encrypt_state, new_state_key, FORMAT_VERSION};++use thiserror::Error;++#[derive(Debug, Error)]+pub enum MlsError {+ #[error("openmls: {0}")]+ Mls(String),+ #[error("no MLS group {0}")]+ UnknownGroup(String),+ #[error("this device was removed from the group")]+ Evicted,+ #[error("malformed MLS payload: {0}")]+ Malformed(String),+ #[error("this device is already in MLS group {0}")]+ GroupExists(String),+ #[error("refused, the server cannot be trusted for this: {0}")]+ Untrusted(String),+ #[error("stored MLS state is unreadable: {0}")]+ State(String),+ #[error("file crypto: {0}")]+ File(String),+ #[error("io: {0}")]+ Io(#[from] std::io::Error),+}++pub type Result<T> = std::result::Result<T, MlsError>;diff --git a/src-tauri/omnidisc-mls/src/provider.rs b/src-tauri/omnidisc-mls/src/provider.rsnew file mode 100644index 00000000..2d78d812--- /dev/null+++ b/src-tauri/omnidisc-mls/src/provider.rs@@ -0,0 +1,114 @@+use crate::{MlsError, Result};+use openmls_memory_storage::MemoryStorage;+use openmls_rust_crypto::RustCrypto;+use openmls_traits::OpenMlsProvider;+use std::collections::HashMap;++// OpenMlsRustCrypto keeps its storage private, so a restart could never hand it+// back. Our own provider is the only way to serialise and restore group state.+pub struct Provider {+ crypto: RustCrypto,+ storage: MemoryStorage,+}++impl Provider {+ pub fn fresh() -> Self {+ Self { crypto: RustCrypto::default(), storage: MemoryStorage::default() }+ }++ pub fn from_blob(blob: &[u8]) -> Result<Self> {+ Ok(Self { crypto: RustCrypto::default(), storage: storage_from_blob(blob)? })+ }++ pub fn to_blob(&self) -> Vec<u8> {+ storage_to_blob(&self.storage)+ }+}++impl OpenMlsProvider for Provider {+ type CryptoProvider = RustCrypto;+ type RandProvider = RustCrypto;+ type StorageProvider = MemoryStorage;++ fn storage(&self) -> &MemoryStorage {+ &self.storage+ }++ fn crypto(&self) -> &RustCrypto {+ &self.crypto+ }++ fn rand(&self) -> &RustCrypto {+ &self.crypto+ }+}++fn storage_to_blob(storage: &MemoryStorage) -> Vec<u8> {+ let Ok(values) = storage.values.read() else {+ return (0u64).to_be_bytes().to_vec();+ };+ let mut out = Vec::new();+ out.extend_from_slice(&(values.len() as u64).to_be_bytes());+ // The map has no order of its own; sort so an unchanged state produces an+ // unchanged blob and a redundant disk write can be skipped.+ let mut entries: Vec<_> = values.iter().collect();+ entries.sort_by(|a, b| a.0.cmp(b.0));+ for (k, v) in entries {+ out.extend_from_slice(&(k.len() as u64).to_be_bytes());+ out.extend_from_slice(&(v.len() as u64).to_be_bytes());+ out.extend_from_slice(k);+ out.extend_from_slice(v);+ }+ out+}++fn storage_from_blob(mut blob: &[u8]) -> Result<MemoryStorage> {+ fn take_u64(b: &mut &[u8]) -> Result<usize> {+ if b.len() < 8 {+ return Err(MlsError::State("truncated storage blob".into()));+ }+ let mut a = [0u8; 8];+ a.copy_from_slice(&b[..8]);+ *b = &b[8..];+ Ok(u64::from_be_bytes(a) as usize)+ }+ fn take(b: &mut &[u8], n: usize) -> Result<Vec<u8>> {+ if b.len() < n {+ return Err(MlsError::State("truncated storage blob".into()));+ }+ let v = b[..n].to_vec();+ *b = &b[n..];+ Ok(v)+ }+ let count = take_u64(&mut blob)?;+ let mut map = HashMap::with_capacity(count.min(4096));+ for _ in 0..count {+ let kl = take_u64(&mut blob)?;+ let vl = take_u64(&mut blob)?;+ let k = take(&mut blob, kl)?;+ let v = take(&mut blob, vl)?;+ map.insert(k, v);+ }+ Ok(MemoryStorage { values: std::sync::RwLock::new(map) })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn storage_blob_round_trips_and_rejects_truncation() {+ let provider = Provider::fresh();+ {+ let mut values = provider.storage.values.write().expect("lock");+ values.insert(b"a".to_vec(), b"one".to_vec());+ values.insert(b"bb".to_vec(), b"two".to_vec());+ }+ let blob = provider.to_blob();+ let restored = Provider::from_blob(&blob).expect("restore");+ let values = restored.storage.values.read().expect("lock");+ assert_eq!(values.get(b"a".as_slice()).map(Vec::as_slice), Some(b"one".as_slice()));+ assert_eq!(values.len(), 2);+ assert!(Provider::from_blob(&blob[..blob.len() - 1]).is_err());+ }+}diff --git a/src-tauri/omnidisc-mls/src/state.rs b/src-tauri/omnidisc-mls/src/state.rsnew file mode 100644index 00000000..353fc484--- /dev/null+++ b/src-tauri/omnidisc-mls/src/state.rs@@ -0,0 +1,94 @@+//! MLS state at rest: XChaCha20-Poly1305 under a key the caller keeps in the OS+//! keyring, behind a version header. openmls 0.9 changes the storage encoding+//! (S-05 condition 1), so the version is written now to make that migration an+//! import rather than a data loss.++use crate::{MlsError, Result};+use chacha20poly1305::aead::{Aead, KeyInit, Payload};+use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};+use rand::Rng;++pub const FORMAT_VERSION: u32 = 1;+const MAGIC: &[u8; 6] = b"ODMLS\0";+const NONCE_LEN: usize = 24;++pub fn new_state_key() -> [u8; 32] {+ let mut key = [0u8; 32];+ rand::rng().fill_bytes(&mut key);+ key+}++fn header(version: u32) -> Vec<u8> {+ let mut out = Vec::with_capacity(MAGIC.len() + 4);+ out.extend_from_slice(MAGIC);+ out.extend_from_slice(&version.to_be_bytes());+ out+}++pub fn encrypt_state(key: &[u8; 32], plaintext: &[u8]) -> Result<Vec<u8>> {+ let aad = header(FORMAT_VERSION);+ let mut nonce = [0u8; NONCE_LEN];+ rand::rng().fill_bytes(&mut nonce);+ let cipher = XChaCha20Poly1305::new(Key::from_slice(key));+ let ciphertext = cipher+ .encrypt(XNonce::from_slice(&nonce), Payload { msg: plaintext, aad: &aad })+ .map_err(|_| MlsError::State("could not encrypt the MLS state".into()))?;+ let mut out = aad;+ out.extend_from_slice(&nonce);+ out.extend_from_slice(&ciphertext);+ Ok(out)+}++pub fn decrypt_state(key: &[u8; 32], blob: &[u8]) -> Result<Vec<u8>> {+ let head = MAGIC.len() + 4;+ if blob.len() < head + NONCE_LEN {+ return Err(MlsError::State("the stored MLS state is truncated".into()));+ }+ if &blob[..MAGIC.len()] != MAGIC {+ return Err(MlsError::State("this file is not an MLS state blob".into()));+ }+ let version = u32::from_be_bytes([blob[6], blob[7], blob[8], blob[9]]);+ if version != FORMAT_VERSION {+ return Err(MlsError::State(format!(+ "the stored MLS state is version {version}, this build reads {FORMAT_VERSION}"+ )));+ }+ let nonce = &blob[head..head + NONCE_LEN];+ let cipher = XChaCha20Poly1305::new(Key::from_slice(key));+ cipher+ .decrypt(+ XNonce::from_slice(nonce),+ Payload { msg: &blob[head + NONCE_LEN..], aad: &blob[..head] },+ )+ .map_err(|_| MlsError::State("the stored MLS state failed its integrity check".into()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn round_trips_and_refuses_tampering() {+ let key = new_state_key();+ let blob = encrypt_state(&key, b"group state").expect("encrypt");+ assert_eq!(&blob[..6], MAGIC);+ assert_eq!(decrypt_state(&key, &blob).expect("decrypt"), b"group state");++ let mut bad = blob.clone();+ let last = bad.len() - 1;+ bad[last] ^= 0xff;+ assert!(decrypt_state(&key, &bad).is_err());++ assert!(decrypt_state(&new_state_key(), &blob).is_err());+ assert!(decrypt_state(&key, &blob[..8]).is_err());+ }++ #[test]+ fn a_future_version_is_named_not_guessed() {+ let key = new_state_key();+ let mut blob = encrypt_state(&key, b"x").expect("encrypt");+ blob[9] = 2;+ let err = decrypt_state(&key, &blob).expect_err("version mismatch");+ assert!(err.to_string().contains("version 2"), "{err}");+ }+}diff --git a/src-tauri/omnidisc-proto/Cargo.toml b/src-tauri/omnidisc-proto/Cargo.tomlnew file mode 100644index 00000000..b81ade07--- /dev/null+++ b/src-tauri/omnidisc-proto/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "omnidisc-proto"+version = "0.1.0"+edition = "2021"+description = "Shared wire types, IDs and permission model for OmniDisc (client and server)"+license = "GPL-3.0"++[dependencies]+serde = { version = "1", features = ["derive"] }+serde_json = "1"+serde_repr = "0.1"+thiserror = "1"++[dev-dependencies]diff --git a/src-tauri/omnidisc-proto/src/bitrate.rs b/src-tauri/omnidisc-proto/src/bitrate.rsnew file mode 100644index 00000000..2fa6be96--- /dev/null+++ b/src-tauri/omnidisc-proto/src/bitrate.rs@@ -0,0 +1,184 @@+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;++pub const RESOLUTIONS: [u16; 5] = [540, 720, 1080, 1440, 2160];+pub const FRAMERATES: [u16; 6] = [15, 30, 60, 90, 120, 144];++pub fn width_for_height(height: u16) -> u16 {+ match height {+ 540 => 960,+ 720 => 1280,+ 1080 => 1920,+ 1440 => 2560,+ 2160 => 3840,+ h => ((h as u32 * 16 / 9) & !1) as u16,+ }+}++pub fn default_kbps(height: u16, fps: u16) -> u32 {+ let base = match height {+ 540 => 1_500u32,+ 720 => 2_500,+ 1080 => 5_000,+ 1440 => 9_000,+ 2160 => 16_000,+ _ => {+ let px = width_for_height(height) as u64 * height as u64;+ ((px as f64 / (1920.0 * 1080.0)) * 5_000.0) as u32+ }+ };+ let scale = match fps {+ 15 => 0.65,+ 30 => 1.0,+ 60 => 1.6,+ 90 => 2.1,+ 120 => 2.6,+ 144 => 2.9,+ f => (f as f64 / 30.0).powf(0.7),+ };+ ((base as f64 * scale) as u32).max(300)+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct StreamingPolicy {+ pub max_height: u16,+ pub max_fps: u16,+ pub min_kbps: u32,+ pub max_kbps: u32,+ pub step_kbps: u32,+ pub allow_custom_bitrate: bool,+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]+ pub overrides: BTreeMap<String, u32>,+ #[serde(default)]+ pub preferred_codec: Codec,+ #[serde(default = "default_true")]+ pub allow_h265: bool,+}++fn default_true() -> bool {+ true+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]+#[serde(rename_all = "lowercase")]+pub enum Codec {+ #[default]+ H264,+ H265,+ Vp8,+ Vp9,+ Av1,+}++impl Default for StreamingPolicy {+ fn default() -> Self {+ Self {+ max_height: 2160,+ max_fps: 120,+ min_kbps: 500,+ max_kbps: 20_000,+ step_kbps: 500,+ allow_custom_bitrate: true,+ overrides: BTreeMap::new(),+ preferred_codec: Codec::H264,+ allow_h265: true,+ }+ }+}++impl StreamingPolicy {+ pub fn kbps_for(&self, height: u16, fps: u16) -> u32 {+ let key = format!("{height}p{fps}");+ let raw = self.overrides.get(&key).copied().unwrap_or_else(|| default_kbps(height, fps));+ raw.clamp(self.min_kbps, self.max_kbps)+ }++ pub fn clamp_custom(&self, requested_kbps: u32) -> u32 {+ if !self.allow_custom_bitrate {+ return self.max_kbps.min(requested_kbps).max(self.min_kbps);+ }+ let stepped = (requested_kbps / self.step_kbps.max(1)) * self.step_kbps.max(1);+ stepped.clamp(self.min_kbps, self.max_kbps)+ }++ pub fn allowed_resolutions(&self) -> Vec<u16> {+ RESOLUTIONS.iter().copied().filter(|h| *h <= self.max_height).collect()+ }++ pub fn allowed_framerates(&self) -> Vec<u16> {+ FRAMERATES.iter().copied().filter(|f| *f <= self.max_fps).collect()+ }++ pub fn codec_for(&self, height: u16, fps: u16) -> Codec {+ if self.allow_h265 && height >= 2160 && fps > 60 {+ Codec::H265+ } else {+ self.preferred_codec+ }+ }++ pub fn native_kbps(&self, width: u32, height: u32, fps: u16) -> u32 {+ let px = width as u64 * height as u64;+ let nearest = RESOLUTIONS+ .iter()+ .copied()+ .min_by_key(|h| {+ let hp = width_for_height(*h) as u64 * *h as u64;+ hp.abs_diff(px)+ })+ .unwrap_or(1080);+ let nearest_fps = FRAMERATES+ .iter()+ .copied()+ .min_by_key(|f| f.abs_diff(fps))+ .unwrap_or(30);+ let base = self.kbps_for(nearest, nearest_fps) as f64;+ let nearest_px = (width_for_height(nearest) as u64 * nearest as u64) as f64;+ let scaled = base * (px as f64 / nearest_px) * (fps as f64 / nearest_fps as f64);+ (scaled as u32).clamp(self.min_kbps, self.max_kbps)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn matrix_is_monotonic() {+ for w in RESOLUTIONS.windows(2) {+ assert!(default_kbps(w[1], 30) > default_kbps(w[0], 30));+ }+ for f in FRAMERATES.windows(2) {+ assert!(default_kbps(1080, f[1]) > default_kbps(1080, f[0]));+ }+ }++ #[test]+ fn policy_clamps_and_overrides() {+ let mut p = StreamingPolicy { max_kbps: 8_000, ..Default::default() };+ assert_eq!(p.kbps_for(2160, 120), 8_000);+ p.overrides.insert("720p30".into(), 1_000);+ assert_eq!(p.kbps_for(720, 30), 1_000);+ assert_eq!(p.clamp_custom(12_345), 8_000);+ p.allow_custom_bitrate = false;+ assert_eq!(p.clamp_custom(100), 500);+ }++ #[test]+ fn hevc_only_for_4k_above_60() {+ let p = StreamingPolicy::default();+ assert_eq!(p.codec_for(2160, 120), Codec::H265);+ assert_eq!(p.codec_for(2160, 60), Codec::H264);+ assert_eq!(p.codec_for(1440, 120), Codec::H264);+ let off = StreamingPolicy { allow_h265: false, ..Default::default() };+ assert_eq!(off.codec_for(2160, 120), Codec::H264);+ }++ #[test]+ fn native_handles_ultrawide() {+ let p = StreamingPolicy { max_kbps: 50_000, ..Default::default() };+ let uw = p.native_kbps(3440, 1440, 60);+ let std = p.kbps_for(1440, 60);+ assert!(uw > std);+ }+}diff --git a/src-tauri/omnidisc-proto/src/channel.rs b/src-tauri/omnidisc-proto/src/channel.rsnew file mode 100644index 00000000..2765fa65--- /dev/null+++ b/src-tauri/omnidisc-proto/src/channel.rs@@ -0,0 +1,180 @@+use crate::{Permissions, Snowflake};+use serde::{Deserialize, Serialize};+use serde_repr::{Deserialize_repr, Serialize_repr};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]+#[repr(u8)]+pub enum ChannelType {+ GuildText = 0,+ Dm = 1,+ GuildVoice = 2,+ GroupDm = 3,+ GuildCategory = 4,+ GuildLink = 5,+ PersonalNotes = 6,+}++impl ChannelType {+ pub fn is_text_capable(self) -> bool {+ matches!(+ self,+ Self::GuildText | Self::Dm | Self::GroupDm | Self::GuildVoice | Self::PersonalNotes+ )+ }++ pub fn is_guild(self) -> bool {+ matches!(self, Self::GuildText | Self::GuildVoice | Self::GuildCategory | Self::GuildLink)+ }++ pub fn is_voice(self) -> bool {+ matches!(self, Self::GuildVoice)+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ChannelOverwrite {+ pub target_id: Snowflake,+ pub target_kind: OverwriteTarget,+ pub allow: Permissions,+ pub deny: Permissions,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum OverwriteTarget {+ Role,+ Member,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Channel {+ pub id: Snowflake,+ #[serde(rename = "type")]+ pub kind: ChannelType,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub topic: Option<String>,+ #[serde(default)]+ pub position: i32,+ #[serde(default)]+ pub nsfw: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub slowmode_seconds: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bitrate: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub user_limit: Option<u16>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub url: Option<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub overwrites: Vec<ChannelOverwrite>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub recipient_ids: Vec<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub owner_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub icon: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub last_message_id: Option<Snowflake>,+ #[serde(default)]+ pub e2ee: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Guild {+ pub id: Snowflake,+ pub name: String,+ pub owner_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub icon: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub banner: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ #[serde(default)]+ pub roles: Vec<Role>,+ #[serde(default)]+ pub channels: Vec<Channel>,+ #[serde(default)]+ pub member_count: u32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub afk_channel_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub system_channel_id: Option<Snowflake>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Role {+ pub id: Snowflake,+ pub guild_id: Snowflake,+ pub name: String,+ pub permissions: Permissions,+ pub position: i32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub color: Option<u32>,+ #[serde(default)]+ pub hoist: bool,+ #[serde(default)]+ pub mentionable: bool,+ #[serde(default)]+ pub is_everyone: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Member {+ pub guild_id: Snowflake,+ pub user_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nick: Option<String>,+ #[serde(default)]+ pub role_ids: Vec<Snowflake>,+ pub joined_at: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub muted_until: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Invite {+ pub code: String,+ pub guild_id: Option<Snowflake>,+ pub channel_id: Option<Snowflake>,+ pub inviter_id: Snowflake,+ pub created_at: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub expires_at: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_uses: Option<u32>,+ #[serde(default)]+ pub uses: u32,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Ban {+ pub guild_id: Snowflake,+ pub user_id: Snowflake,+ pub banned_by: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+ pub created_at: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct AuditLogEntry {+ pub id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ pub actor_id: Snowflake,+ pub action: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub target_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+ #[serde(default)]+ pub changes: serde_json::Value,+ pub created_at: String,+}diff --git a/src-tauri/omnidisc-proto/src/gateway.rs b/src-tauri/omnidisc-proto/src/gateway.rsnew file mode 100644index 00000000..3dc8ffd0--- /dev/null+++ b/src-tauri/omnidisc-proto/src/gateway.rs@@ -0,0 +1,420 @@+use crate::channel::{Channel, Guild, Member, Role};+use crate::message::{Message, ReadState};+use crate::user::{PresenceUpdate, Relationship, User, VoiceState};+use crate::Snowflake;+use serde::{Deserialize, Serialize};+use serde_repr::{Deserialize_repr, Serialize_repr};++pub const HEARTBEAT_INTERVAL_MS: u64 = 30_000;+pub const IDENTIFY_TIMEOUT_MS: u64 = 10_000;+pub const MAX_FRAME_BYTES: usize = 10 * 1024 * 1024;+pub const LARGE_GUILD_THRESHOLD: u32 = 250;+pub const MEMBER_LIST_WINDOW: u32 = 100;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]+#[repr(u8)]+pub enum Opcode {+ Dispatch = 0,+ Heartbeat = 1,+ Identify = 2,+ PresenceUpdate = 3,+ VoiceStateUpdate = 4,+ Resume = 6,+ Reconnect = 7,+ RequestGuildMembers = 8,+ InvalidSession = 9,+ Hello = 10,+ HeartbeatAck = 11,+ GatewayError = 12,+ LazyRequest = 14,+ Typing = 20,+ MlsEnvelope = 30,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]+#[repr(u16)]+pub enum CloseCode {+ UnknownError = 4000,+ UnknownOpcode = 4001,+ DecodeError = 4002,+ NotAuthenticated = 4003,+ AuthenticationFailed = 4004,+ AlreadyAuthenticated = 4005,+ InvalidSeq = 4007,+ RateLimited = 4008,+ SessionTimedOut = 4009,+ InvalidVersion = 4012,+ ServerRestarting = 4013,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Frame {+ pub op: Opcode,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub s: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub t: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub d: Option<serde_json::Value>,+}++impl Frame {+ pub fn new(op: Opcode, d: impl Serialize) -> Self {+ Self { op, s: None, t: None, d: serde_json::to_value(d).ok() }+ }++ pub fn dispatch(seq: u64, event: &DispatchEvent) -> Self {+ let d = serde_json::to_value(event).ok().and_then(|v| match v {+ serde_json::Value::Object(mut m) => m.remove("d"),+ other => Some(other),+ });+ Self { op: Opcode::Dispatch, s: Some(seq), t: Some(event.name().to_string()), d }+ }++ pub fn event(&self) -> Option<DispatchEvent> {+ if self.op != Opcode::Dispatch {+ return None;+ }+ let mut obj = serde_json::Map::new();+ obj.insert("t".into(), serde_json::Value::String(self.t.clone()?));+ if let Some(d) = &self.d {+ obj.insert("d".into(), d.clone());+ }+ serde_json::from_value(serde_json::Value::Object(obj)).ok()+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Hello {+ pub heartbeat_interval: u64,+ pub protocol_version: u16,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Identify {+ pub token: String,+ pub protocol_version: u16,+ #[serde(default)]+ pub compress: Compression,+ #[serde(default)]+ pub properties: ClientProperties,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub presence: Option<PresenceUpdate>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum Compression {+ #[default]+ None,+ Zstd,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct ClientProperties {+ #[serde(default)]+ pub os: String,+ #[serde(default)]+ pub client: String,+ #[serde(default)]+ pub version: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub device_name: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Resume {+ pub token: String,+ pub session_id: String,+ pub seq: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct VoiceStateUpdateRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_id: Option<Snowflake>,+ #[serde(default)]+ pub self_mute: bool,+ #[serde(default)]+ pub self_deaf: bool,+ #[serde(default)]+ pub self_stream: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LazyRequest {+ pub guild_id: Snowflake,+ pub channel_id: Snowflake,+ pub ranges: Vec<(u32, u32)>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TypingRequest {+ pub channel_id: Snowflake,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MlsEnvelope {+ pub id: Snowflake,+ pub group_id: String,+ pub epoch: u64,+ pub sender_device_id: String,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub recipient_device_ids: Vec<String>,+ pub kind: MlsEnvelopeKind,+ pub payload: String,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum MlsEnvelopeKind {+ Welcome,+ Commit,+ Proposal,+ Application,+}++impl MlsEnvelopeKind {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Welcome => "welcome",+ Self::Commit => "commit",+ Self::Proposal => "proposal",+ Self::Application => "application",+ }+ }++ pub fn parse(s: &str) -> Option<Self> {+ Some(match s {+ "welcome" => Self::Welcome,+ "commit" => Self::Commit,+ "proposal" => Self::Proposal,+ "application" => Self::Application,+ _ => return None,+ })+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Ready {+ pub session_id: String,+ pub user: User,+ pub guilds: Vec<Guild>,+ pub private_channels: Vec<Channel>,+ pub relationships: Vec<Relationship>,+ pub read_states: Vec<ReadState>,+ pub voice_states: Vec<VoiceState>,+ pub presences: Vec<PresenceUpdate>,+ pub instance: InstanceInfo,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct InstanceInfo {+ pub name: String,+ pub version: String,+ pub media_url: String,+ pub sfu_url: String,+ pub max_upload_bytes: u64,+ pub streaming: crate::bitrate::StreamingPolicy,+ #[serde(default)]+ pub limits: crate::limits::Limits,+ #[serde(default)]+ pub registration_open: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct VoiceServerUpdate {+ pub guild_id: Option<Snowflake>,+ pub channel_id: Snowflake,+ pub endpoint: String,+ pub token: String,+ pub room: String,+ #[serde(default)]+ pub ice_servers: Vec<IceServer>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct IceServer {+ pub urls: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub username: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub credential: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TypingStart {+ pub channel_id: Snowflake,+ pub user_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MemberListUpdate {+ pub guild_id: Snowflake,+ pub channel_id: Snowflake,+ pub total: u32,+ pub online: u32,+ pub ops: Vec<MemberListOp>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "op", rename_all = "snake_case")]+pub enum MemberListOp {+ Sync { range: (u32, u32), items: Vec<MemberListItem> },+ Insert { index: u32, item: MemberListItem },+ Update { index: u32, item: MemberListItem },+ Delete { index: u32 },+ Invalidate { range: (u32, u32) },+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum MemberListItem {+ Group { id: String, count: u32 },+ Member { member: Member, user: User, presence: Option<PresenceUpdate> },+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "t", content = "d")]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum DispatchEvent {+ Ready(Ready),+ Resumed,+ GuildCreate(Guild),+ GuildUpdate(Guild),+ GuildDelete { id: Snowflake },+ GuildMemberAdd(Member),+ GuildMemberUpdate(Member),+ GuildMemberRemove { guild_id: Snowflake, user_id: Snowflake },+ GuildMemberListUpdate(MemberListUpdate),+ GuildRoleCreate(Role),+ GuildRoleUpdate(Role),+ GuildRoleDelete { guild_id: Snowflake, id: Snowflake },+ ChannelCreate(Channel),+ ChannelUpdate(Channel),+ ChannelDelete { id: Snowflake },+ ChannelPinsUpdate { channel_id: Snowflake },+ MessageCreate(Message),+ MessageUpdate(Message),+ MessageDelete { id: Snowflake, channel_id: Snowflake },+ MessageDeleteBulk { ids: Vec<Snowflake>, channel_id: Snowflake },+ MessageReactionAdd { channel_id: Snowflake, message_id: Snowflake, user_id: Snowflake, emoji: crate::message::Emoji },+ MessageReactionRemove { channel_id: Snowflake, message_id: Snowflake, user_id: Snowflake, emoji: crate::message::Emoji },+ MessageAck(ReadState),+ TypingStart(TypingStart),+ PresenceUpdate(PresenceUpdate),+ PresenceUpdateBulk(Vec<PresenceUpdate>),+ UserUpdate(User),+ RelationshipAdd(Relationship),+ RelationshipRemove { user_id: Snowflake },+ VoiceStateUpdate(VoiceState),+ VoiceServerUpdate(VoiceServerUpdate),+ CallRing { channel_id: Snowflake, from_user_id: Snowflake },+ MlsEnvelope(MlsEnvelope),+ DeviceRevoked { user_id: Snowflake, device_id: String },+ InviteCreate(crate::channel::Invite),+ InviteDelete { code: String },+ SessionsReplace(Vec<SessionInfo>),+}++impl DispatchEvent {+ pub fn name(&self) -> &'static str {+ match self {+ Self::Ready(_) => "READY",+ Self::Resumed => "RESUMED",+ Self::GuildCreate(_) => "GUILD_CREATE",+ Self::GuildUpdate(_) => "GUILD_UPDATE",+ Self::GuildDelete { .. } => "GUILD_DELETE",+ Self::GuildMemberAdd(_) => "GUILD_MEMBER_ADD",+ Self::GuildMemberUpdate(_) => "GUILD_MEMBER_UPDATE",+ Self::GuildMemberRemove { .. } => "GUILD_MEMBER_REMOVE",+ Self::GuildMemberListUpdate(_) => "GUILD_MEMBER_LIST_UPDATE",+ Self::GuildRoleCreate(_) => "GUILD_ROLE_CREATE",+ Self::GuildRoleUpdate(_) => "GUILD_ROLE_UPDATE",+ Self::GuildRoleDelete { .. } => "GUILD_ROLE_DELETE",+ Self::ChannelCreate(_) => "CHANNEL_CREATE",+ Self::ChannelUpdate(_) => "CHANNEL_UPDATE",+ Self::ChannelDelete { .. } => "CHANNEL_DELETE",+ Self::ChannelPinsUpdate { .. } => "CHANNEL_PINS_UPDATE",+ Self::MessageCreate(_) => "MESSAGE_CREATE",+ Self::MessageUpdate(_) => "MESSAGE_UPDATE",+ Self::MessageDelete { .. } => "MESSAGE_DELETE",+ Self::MessageDeleteBulk { .. } => "MESSAGE_DELETE_BULK",+ Self::MessageReactionAdd { .. } => "MESSAGE_REACTION_ADD",+ Self::MessageReactionRemove { .. } => "MESSAGE_REACTION_REMOVE",+ Self::MessageAck(_) => "MESSAGE_ACK",+ Self::TypingStart(_) => "TYPING_START",+ Self::PresenceUpdate(_) => "PRESENCE_UPDATE",+ Self::PresenceUpdateBulk(_) => "PRESENCE_UPDATE_BULK",+ Self::UserUpdate(_) => "USER_UPDATE",+ Self::RelationshipAdd(_) => "RELATIONSHIP_ADD",+ Self::RelationshipRemove { .. } => "RELATIONSHIP_REMOVE",+ Self::VoiceStateUpdate(_) => "VOICE_STATE_UPDATE",+ Self::VoiceServerUpdate(_) => "VOICE_SERVER_UPDATE",+ Self::CallRing { .. } => "CALL_RING",+ Self::MlsEnvelope(_) => "MLS_ENVELOPE",+ Self::DeviceRevoked { .. } => "DEVICE_REVOKED",+ Self::InviteCreate(_) => "INVITE_CREATE",+ Self::InviteDelete { .. } => "INVITE_DELETE",+ Self::SessionsReplace(_) => "SESSIONS_REPLACE",+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SessionInfo {+ pub session_id: String,+ pub client: ClientProperties,+ pub last_seen: String,+ pub current: bool,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dispatch_frame_carries_payload_in_d() {+ let ev = DispatchEvent::ChannelDelete { id: Snowflake(42) };+ let f = Frame::dispatch(3, &ev);+ assert_eq!(f.t.as_deref(), Some("CHANNEL_DELETE"));+ assert_eq!(f.s, Some(3));+ assert_eq!(f.d.as_ref().and_then(|d| d.get("id")).and_then(|v| v.as_str()), Some("42"));+ assert!(matches!(f.event(), Some(DispatchEvent::ChannelDelete { id }) if id == Snowflake(42)));+ }++ #[test]+ fn mls_envelope_dispatch_roundtrips() {+ let env = MlsEnvelope {+ id: Snowflake(7),+ group_id: "g1".into(),+ epoch: 3,+ sender_device_id: "dev-a".into(),+ recipient_device_ids: vec!["dev-b".into()],+ kind: MlsEnvelopeKind::Commit,+ payload: "AAEC".into(),+ };+ let f = Frame::dispatch(9, &DispatchEvent::MlsEnvelope(env.clone()));+ assert_eq!(f.t.as_deref(), Some("MLS_ENVELOPE"));+ assert_eq!(f.d.as_ref().and_then(|d| d.get("kind")).and_then(|v| v.as_str()), Some("commit"));+ assert!(matches!(f.event(), Some(DispatchEvent::MlsEnvelope(e)) if e == env));+ let f = Frame::dispatch(10, &DispatchEvent::DeviceRevoked { user_id: Snowflake(1), device_id: "dev-a".into() });+ assert_eq!(f.t.as_deref(), Some("DEVICE_REVOKED"));+ assert_eq!(MlsEnvelopeKind::parse("welcome"), Some(MlsEnvelopeKind::Welcome));+ assert_eq!(MlsEnvelopeKind::Application.as_str(), "application");+ }++ #[test]+ fn unit_event_roundtrips() {+ let f = Frame::dispatch(1, &DispatchEvent::Resumed);+ assert!(f.d.is_none());+ assert!(matches!(f.event(), Some(DispatchEvent::Resumed)));+ let json = serde_json::to_string(&f).unwrap();+ let back: Frame = serde_json::from_str(&json).unwrap();+ assert!(matches!(back.event(), Some(DispatchEvent::Resumed)));+ }+}diff --git a/src-tauri/omnidisc-proto/src/lib.rs b/src-tauri/omnidisc-proto/src/lib.rsnew file mode 100644index 00000000..5ae98b29--- /dev/null+++ b/src-tauri/omnidisc-proto/src/lib.rs@@ -0,0 +1,14 @@+pub mod bitrate;+pub mod channel;+pub mod gateway;+pub mod limits;+pub mod message;+pub mod permissions;+pub mod rest;+pub mod snowflake;+pub mod user;++pub use permissions::Permissions;+pub use snowflake::{Snowflake, SnowflakeGenerator};++pub const PROTOCOL_VERSION: u16 = 1;diff --git a/src-tauri/omnidisc-proto/src/limits.rs b/src-tauri/omnidisc-proto/src/limits.rsnew file mode 100644index 00000000..204d6d13--- /dev/null+++ b/src-tauri/omnidisc-proto/src/limits.rs@@ -0,0 +1,40 @@+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Limits {+ pub max_message_chars: u32,+ pub max_upload_bytes: u64,+ pub max_attachments: u8,+ pub max_guilds_per_user: u32,+ pub max_channels_per_guild: u32,+ pub max_roles_per_guild: u32,+ pub max_group_dm_members: u8,+ pub max_custom_emoji: u32,+ pub max_bio_chars: u32,+ pub max_reactions_per_message: u8,+ pub max_pins_per_channel: u32,+ pub max_voice_bitrate_kbps: u32,+ pub max_avatar_bytes: u64,+ pub max_banner_bytes: u64,+}++impl Default for Limits {+ fn default() -> Self {+ Self {+ max_message_chars: 4_000,+ max_upload_bytes: 100 * 1024 * 1024,+ max_attachments: 10,+ max_guilds_per_user: 200,+ max_channels_per_guild: 500,+ max_roles_per_guild: 250,+ max_group_dm_members: 10,+ max_custom_emoji: 250,+ max_bio_chars: 320,+ max_reactions_per_message: 30,+ max_pins_per_channel: 250,+ max_voice_bitrate_kbps: 384,+ max_avatar_bytes: 8 * 1024 * 1024,+ max_banner_bytes: 16 * 1024 * 1024,+ }+ }+}diff --git a/src-tauri/omnidisc-proto/src/message.rs b/src-tauri/omnidisc-proto/src/message.rsnew file mode 100644index 00000000..ff551f4d--- /dev/null+++ b/src-tauri/omnidisc-proto/src/message.rs@@ -0,0 +1,165 @@+use crate::Snowflake;+use serde::{Deserialize, Serialize};+use serde_repr::{Deserialize_repr, Serialize_repr};++pub const MAX_ATTACHMENTS: usize = 10;+pub const MAX_EMBEDS: usize = 10;+pub const MAX_DISTINCT_REACTIONS: usize = 30;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]+#[repr(u8)]+pub enum MessageType {+ Default = 0,+ Reply = 1,+ Forward = 2,+ MemberJoin = 10,+ MemberLeave = 11,+ ChannelPinned = 12,+ CallStarted = 13,+ CallEnded = 14,+ GroupNameChanged = 15,+ GroupIconChanged = 16,+ GroupRecipientAdded = 17,+ GroupRecipientRemoved = 18,+ E2eeKeyRotated = 30,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Message {+ pub id: Snowflake,+ pub channel_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ pub author_id: Snowflake,+ #[serde(rename = "type")]+ pub kind: MessageType,+ #[serde(default)]+ pub content: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub edited_at: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reference: Option<MessageReference>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub attachments: Vec<Attachment>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub embeds: Vec<Embed>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub reactions: Vec<ReactionCount>,+ #[serde(default)]+ pub mentions: Mentions,+ #[serde(default)]+ pub pinned: bool,+ #[serde(default)]+ pub flags: u32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub e2ee: Option<EncryptedPayload>,+}++pub mod flags {+ pub const SUPPRESS_EMBEDS: u32 = 1 << 0;+ pub const SUPPRESS_NOTIFICATIONS: u32 = 1 << 1;+ pub const VOICE_MESSAGE: u32 = 1 << 2;+ pub const EPHEMERAL: u32 = 1 << 3;+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MessageReference {+ pub message_id: Snowflake,+ pub channel_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub snapshot: Option<Box<Message>>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]+pub struct Mentions {+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub users: Vec<Snowflake>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub roles: Vec<Snowflake>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub channels: Vec<Snowflake>,+ #[serde(default)]+ pub everyone: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Attachment {+ pub id: Snowflake,+ pub filename: String,+ pub size: u64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub content_type: Option<String>,+ pub url: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub thumbnail_url: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub thumbhash: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub width: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub height: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub duration_ms: Option<u64>,+ #[serde(default)]+ pub encrypted: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]+pub struct Embed {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub url: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub site_name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub image: Option<EmbedMedia>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub video: Option<EmbedMedia>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub color: Option<u32>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct EmbedMedia {+ pub url: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub width: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub height: Option<u32>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ReactionCount {+ pub emoji: Emoji,+ pub count: u32,+ #[serde(default)]+ pub me: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(untagged)]+pub enum Emoji {+ Unicode { name: String },+ Custom { id: Snowflake, name: String, animated: bool },+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct EncryptedPayload {+ pub group_id: String,+ pub epoch: u64,+ pub ciphertext: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ReadState {+ pub channel_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub last_read_id: Option<Snowflake>,+ #[serde(default)]+ pub mention_count: u32,+}diff --git a/src-tauri/omnidisc-proto/src/permissions.rs b/src-tauri/omnidisc-proto/src/permissions.rsnew file mode 100644index 00000000..59f9c1c6--- /dev/null+++ b/src-tauri/omnidisc-proto/src/permissions.rs@@ -0,0 +1,289 @@+use serde::{Deserialize, Serialize};+use std::fmt;+use std::ops::{BitAnd, BitOr, BitOrAssign, Not};++#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]+pub struct Permissions(pub u64);++macro_rules! perms {+ ($( $name:ident = $bit:expr ),* $(,)?) => {+ impl Permissions {+ $( pub const $name: Permissions = Permissions(1 << $bit); )*+ pub const ALL_NAMED: &'static [(&'static str, Permissions)] = &[ $( (stringify!($name), Permissions::$name) ),* ];+ }+ };+}++perms! {+ VIEW_CHANNEL = 0,+ SEND_MESSAGES = 1,+ EMBED_LINKS = 2,+ ATTACH_FILES = 3,+ ADD_REACTIONS = 4,+ USE_EXTERNAL_EMOJI = 5,+ MENTION_EVERYONE = 6,+ READ_HISTORY = 7,+ SEND_TTS = 8,+ BYPASS_SLOWMODE = 9,++ MANAGE_MESSAGES = 16,+ PIN_MESSAGES = 17,+ MANAGE_CHANNELS = 18,+ MANAGE_ROLES = 19,+ MANAGE_EMOJI = 20,+ MANAGE_WEBHOOKS = 21,+ MANAGE_GUILD = 22,+ VIEW_AUDIT_LOG = 23,+ CREATE_INVITES = 24,+ CHANGE_NICKNAME = 25,+ MANAGE_NICKNAMES = 26,+ VIEW_CHANNEL_MEMBERS = 27,++ KICK_MEMBERS = 32,+ BAN_MEMBERS = 33,+ MODERATE_MEMBERS = 34,++ CONNECT = 40,+ SPEAK = 41,+ STREAM = 42,+ VIDEO = 43,+ USE_VAD = 44,+ PRIORITY_SPEAKER = 45,+ MUTE_MEMBERS = 46,+ DEAFEN_MEMBERS = 47,+ MOVE_MEMBERS = 48,+ USE_SOUNDBOARD = 49,++ ADMINISTRATOR = 63,+}++impl Permissions {+ pub const NONE: Permissions = Permissions(0);++ pub const fn bits(self) -> u64 {+ self.0+ }++ pub const fn contains(self, other: Permissions) -> bool {+ self.0 & other.0 == other.0+ }++ pub const fn intersects(self, other: Permissions) -> bool {+ self.0 & other.0 != 0+ }++ pub const fn union(self, other: Permissions) -> Permissions {+ Permissions(self.0 | other.0)+ }++ pub const fn difference(self, other: Permissions) -> Permissions {+ Permissions(self.0 & !other.0)+ }++ pub fn is_admin(self) -> bool {+ self.contains(Self::ADMINISTRATOR)+ }++ pub fn default_everyone() -> Permissions {+ Self::VIEW_CHANNEL+ | Self::SEND_MESSAGES+ | Self::EMBED_LINKS+ | Self::ATTACH_FILES+ | Self::ADD_REACTIONS+ | Self::USE_EXTERNAL_EMOJI+ | Self::READ_HISTORY+ | Self::CREATE_INVITES+ | Self::CHANGE_NICKNAME+ | Self::VIEW_CHANNEL_MEMBERS+ | Self::CONNECT+ | Self::SPEAK+ | Self::STREAM+ | Self::VIDEO+ | Self::USE_VAD+ | Self::USE_SOUNDBOARD+ }++ pub fn names(self) -> Vec<&'static str> {+ Self::ALL_NAMED+ .iter()+ .filter(|(_, p)| self.contains(*p))+ .map(|(n, _)| *n)+ .collect()+ }+}++impl BitOr for Permissions {+ type Output = Permissions;+ fn bitor(self, rhs: Self) -> Self {+ Permissions(self.0 | rhs.0)+ }+}++impl BitOrAssign for Permissions {+ fn bitor_assign(&mut self, rhs: Self) {+ self.0 |= rhs.0;+ }+}++impl BitAnd for Permissions {+ type Output = Permissions;+ fn bitand(self, rhs: Self) -> Self {+ Permissions(self.0 & rhs.0)+ }+}++impl Not for Permissions {+ type Output = Permissions;+ fn not(self) -> Self {+ Permissions(!self.0)+ }+}++impl fmt::Debug for Permissions {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "Permissions({:?})", self.names())+ }+}++impl Serialize for Permissions {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.collect_str(&self.0)+ }+}++impl<'de> Deserialize<'de> for Permissions {+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ s.parse::<u64>().map(Permissions).map_err(serde::de::Error::custom)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct Overwrite {+ pub allow: Permissions,+ pub deny: Permissions,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Membership {+ NotMember,+ Member,+ Owner,+ InstanceAdmin,+}++pub struct PermissionInputs<'a> {+ pub membership: Membership,+ pub everyone: Permissions,+ pub roles: &'a [Permissions],+ pub category_everyone: Option<Overwrite>,+ pub category_roles: &'a [Overwrite],+ pub category_member: Option<Overwrite>,+ pub channel_everyone: Option<Overwrite>,+ pub channel_roles: &'a [Overwrite],+ pub channel_member: Option<Overwrite>,+}++pub fn resolve(inputs: &PermissionInputs<'_>) -> Permissions {+ match inputs.membership {+ Membership::NotMember => return Permissions::NONE,+ Membership::Owner | Membership::InstanceAdmin => return Permissions(u64::MAX),+ Membership::Member => {}+ }+ let mut base = inputs.everyone;+ for r in inputs.roles {+ base |= *r;+ }+ if base.is_admin() {+ return Permissions(u64::MAX);+ }+ let mut p = base;+ p = apply_tier(p, inputs.category_everyone, inputs.category_roles, inputs.category_member);+ p = apply_tier(p, inputs.channel_everyone, inputs.channel_roles, inputs.channel_member);+ p+}++fn apply_tier(+ mut p: Permissions,+ everyone: Option<Overwrite>,+ roles: &[Overwrite],+ member: Option<Overwrite>,+) -> Permissions {+ if let Some(o) = everyone {+ p = p.difference(o.deny).union(o.allow);+ }+ let mut allow = Permissions::NONE;+ let mut deny = Permissions::NONE;+ for o in roles {+ allow |= o.allow;+ deny |= o.deny;+ }+ p = p.difference(deny).union(allow);+ if let Some(o) = member {+ p = p.difference(o.deny).union(o.allow);+ }+ p+}++#[cfg(test)]+mod tests {+ use super::*;++ fn base<'a>(membership: Membership, roles: &'a [Permissions]) -> PermissionInputs<'a> {+ PermissionInputs {+ membership,+ everyone: Permissions::default_everyone(),+ roles,+ category_everyone: None,+ category_roles: &[],+ category_member: None,+ channel_everyone: None,+ channel_roles: &[],+ channel_member: None,+ }+ }++ #[test]+ fn non_member_gets_nothing_even_with_channel_allow() {+ let mut i = base(Membership::NotMember, &[]);+ i.channel_everyone = Some(Overwrite { allow: Permissions::VIEW_CHANNEL, deny: Permissions::NONE });+ assert_eq!(resolve(&i), Permissions::NONE);+ }++ #[test]+ fn owner_has_everything() {+ assert!(resolve(&base(Membership::Owner, &[])).contains(Permissions::MANAGE_GUILD));+ }++ #[test]+ fn channel_member_overwrite_beats_role_deny() {+ let mut i = base(Membership::Member, &[]);+ i.channel_roles = &[Overwrite { allow: Permissions::NONE, deny: Permissions::SEND_MESSAGES }];+ i.channel_member = Some(Overwrite { allow: Permissions::SEND_MESSAGES, deny: Permissions::NONE });+ assert!(resolve(&i).contains(Permissions::SEND_MESSAGES));+ }++ #[test]+ fn channel_tier_overrides_category_tier() {+ let mut i = base(Membership::Member, &[]);+ i.category_everyone = Some(Overwrite { allow: Permissions::NONE, deny: Permissions::VIEW_CHANNEL });+ i.channel_everyone = Some(Overwrite { allow: Permissions::VIEW_CHANNEL, deny: Permissions::NONE });+ assert!(resolve(&i).contains(Permissions::VIEW_CHANNEL));+ }++ #[test]+ fn admin_role_ignores_overwrites() {+ let roles = [Permissions::ADMINISTRATOR];+ let mut i = base(Membership::Member, &roles);+ i.channel_everyone = Some(Overwrite { allow: Permissions::NONE, deny: Permissions::VIEW_CHANNEL });+ assert!(resolve(&i).contains(Permissions::VIEW_CHANNEL));+ }++ #[test]+ fn serializes_as_decimal_string() {+ let p = Permissions::VIEW_CHANNEL | Permissions::SPEAK;+ let s = serde_json::to_string(&p).unwrap();+ let back: Permissions = serde_json::from_str(&s).unwrap();+ assert_eq!(back, p);+ }+}diff --git a/src-tauri/omnidisc-proto/src/rest.rs b/src-tauri/omnidisc-proto/src/rest.rsnew file mode 100644index 00000000..b580dec0--- /dev/null+++ b/src-tauri/omnidisc-proto/src/rest.rs@@ -0,0 +1,525 @@+use crate::channel::{ChannelType, OverwriteTarget};+use crate::message::{Message, MessageReference};+use crate::user::User;+use crate::{Permissions, Snowflake};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApiError {+ pub code: String,+ pub message: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub retry_after_ms: Option<u64>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RegisterRequest {+ pub username: String,+ pub password: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub display_name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub invite_code: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LoginRequest {+ pub username: String,+ pub password: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub device_name: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AuthResponse {+ pub token: String,+ pub user: User,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct UpdateUserRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub display_name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bio: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pronouns: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub accent_color: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateGuildRequest {+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateChannelRequest {+ pub name: String,+ #[serde(rename = "type", default = "default_channel_type")]+ pub kind: ChannelType,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub topic: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub url: Option<String>,+}++fn default_channel_type() -> ChannelType {+ ChannelType::GuildText+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct UpdateChannelRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub topic: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub position: Option<i32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nsfw: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub slowmode_seconds: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent_id: Option<Snowflake>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct MessageQuery {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub before: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub after: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub around: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateMessageRequest {+ #[serde(default)]+ pub content: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nonce: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reference: Option<MessageReference>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub attachment_ids: Vec<Snowflake>,+ #[serde(default)]+ pub flags: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EditMessageRequest {+ pub content: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AckRequest {+ pub message_id: Snowflake,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateInviteRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_age_seconds: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_uses: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateDmRequest {+ pub recipient_ids: Vec<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateRoleRequest {+ pub name: String,+ #[serde(default)]+ pub permissions: Permissions,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub color: Option<u32>,+ #[serde(default)]+ pub hoist: bool,+ #[serde(default)]+ pub mentionable: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct UpdateRoleRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub permissions: Option<Permissions>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub color: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub hoist: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mentionable: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub position: Option<i32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PutOverwriteRequest {+ pub target_kind: OverwriteTarget,+ pub allow: Permissions,+ pub deny: Permissions,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct VoiceTokenRequest {+ pub channel_id: Snowflake,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct HealthResponse {+ pub ok: bool,+ pub version: String,+ pub uptime_seconds: u64,+}++pub mod double_option {+ use serde::{Deserialize, Deserializer};++ pub fn deserialize<'de, T, D>(d: D) -> Result<Option<Option<T>>, D::Error>+ where+ T: Deserialize<'de>,+ D: Deserializer<'de>,+ {+ Option::<T>::deserialize(d).map(Some)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum SearchHas {+ File,+ Image,+ Link,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct SearchQuery {+ #[serde(default)]+ pub q: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub from: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub r#in: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub has: Option<SearchHas>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub before: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub after: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SearchResponse {+ pub messages: Vec<Message>,+ pub total: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct LimitQuery {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BulkDeleteRequest {+ pub message_ids: Vec<Snowflake>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct BanRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct KickRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct UpdateMemberRequest {+ #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "double_option::deserialize")]+ pub nick: Option<Option<String>>,+ #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "double_option::deserialize")]+ pub muted_until: Option<Option<String>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct UpdateGuildRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "double_option::deserialize")]+ pub description: Option<Option<String>>,+ #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "double_option::deserialize")]+ pub afk_channel_id: Option<Option<Snowflake>>,+ #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "double_option::deserialize")]+ pub system_channel_id: Option<Option<Snowflake>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TransferGuildRequest {+ pub user_id: Snowflake,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct AuditLogQuery {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub before: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub action: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub actor_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct CreateRelationshipRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub username: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub user_id: Option<Snowflake>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PutNoteRequest {+ pub note: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct UserNote {+ pub user_id: Snowflake,+ pub note: String,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct AdminInstance {+ pub name: String,+ pub registration_open: bool,+ pub streaming: crate::bitrate::StreamingPolicy,+ pub limits: crate::limits::Limits,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct UpdateInstanceRequest {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub registration_open: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub streaming: Option<crate::bitrate::StreamingPolicy>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub limits: Option<crate::limits::Limits>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct AdminStats {+ pub users: u64,+ pub guilds: u64,+ pub channels: u64,+ pub messages: u64,+ pub gateway_sessions: u64,+ pub uptime_seconds: u64,+ pub version: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RegisterDeviceRequest {+ pub ed25519_pub: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Device {+ pub user_id: Snowflake,+ pub device_id: String,+ pub ed25519_pub: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ pub created_at: String,+ pub last_seen_at: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub revoked_at: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct KeyPackageUpload {+ pub ciphersuite: u16,+ pub blob: String,+ #[serde(default)]+ pub last_resort: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PutKeyPackagesRequest {+ pub key_packages: Vec<KeyPackageUpload>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct KeyPackageCount {+ pub unclaimed: u64,+ pub last_resort: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ClaimedKeyPackage {+ pub device_id: String,+ pub ciphersuite: u16,+ pub blob: String,+ #[serde(default)]+ pub last_resort: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ClaimedKeyPackages {+ pub user_id: Snowflake,+ pub key_packages: Vec<ClaimedKeyPackage>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CreateMlsGroupRequest {+ pub channel_id: Snowflake,+ pub group_id: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MlsGroupMember {+ pub user_id: Snowflake,+ pub device_id: String,+ pub joined_epoch: u64,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MlsGroup {+ pub group_id: String,+ pub channel_id: Snowflake,+ pub creator_device_id: String,+ pub current_epoch: u64,+ pub created_at: String,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub members: Vec<MlsGroupMember>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MlsCommitRequest {+ pub epoch: u64,+ pub commit: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub welcome: Option<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub added_devices: Vec<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub removed_devices: Vec<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct MlsCommitResponse {+ pub group_id: String,+ pub epoch: u64,+ pub commit_envelope_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub welcome_envelope_id: Option<Snowflake>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MlsMessageRequest {+ pub epoch: u64,+ pub blob: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nonce: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct MlsInboxQuery {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub after: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub limit: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MlsInboxResponse {+ pub envelopes: Vec<crate::gateway::MlsEnvelope>,+ #[serde(default)]+ pub has_more: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MlsAckRequest {+ pub envelope_ids: Vec<Snowflake>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct ThumbQuery {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub w: Option<u32>,+ #[serde(default)]+ pub exp: u64,+ #[serde(default)]+ pub sig: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct SignedMediaQuery {+ #[serde(default)]+ pub exp: u64,+ #[serde(default)]+ pub sig: String,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn mls_commit_request_defaults() {+ let r: MlsCommitRequest = serde_json::from_str(r#"{"epoch":1,"commit":"AA=="}"#).unwrap();+ assert!(r.welcome.is_none());+ assert!(r.added_devices.is_empty());+ let c: KeyPackageUpload = serde_json::from_str(r#"{"ciphersuite":1,"blob":"AA=="}"#).unwrap();+ assert!(!c.last_resort);+ }++ #[test]+ fn double_option_distinguishes_null_from_absent() {+ let absent: UpdateMemberRequest = serde_json::from_str("{}").unwrap();+ assert!(absent.muted_until.is_none());+ let cleared: UpdateMemberRequest = serde_json::from_str(r#"{"muted_until":null}"#).unwrap();+ assert_eq!(cleared.muted_until, Some(None));+ let set: UpdateMemberRequest =+ serde_json::from_str(r#"{"muted_until":"2030-01-01T00:00:00Z"}"#).unwrap();+ assert_eq!(set.muted_until.as_ref().and_then(|m| m.as_deref()), Some("2030-01-01T00:00:00Z"));+ }++ #[test]+ fn search_query_parses_in_keyword() {+ let q: SearchQuery = serde_json::from_str(r#"{"q":"hello","in":"42","has":"link"}"#).unwrap();+ assert_eq!(q.r#in, Some(Snowflake(42)));+ assert_eq!(q.has, Some(SearchHas::Link));+ }+}diff --git a/src-tauri/omnidisc-proto/src/snowflake.rs b/src-tauri/omnidisc-proto/src/snowflake.rsnew file mode 100644index 00000000..ebe74b7a--- /dev/null+++ b/src-tauri/omnidisc-proto/src/snowflake.rs@@ -0,0 +1,171 @@+use serde::{Deserialize, Serialize};+use std::fmt;+use std::str::FromStr;+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::{SystemTime, UNIX_EPOCH};++pub const OMNIDISC_EPOCH_MS: u64 = 1_785_542_400_000;+pub const BUCKET_SPAN_MS: u64 = 10 * 24 * 60 * 60 * 1000;++const WORKER_BITS: u64 = 10;+const SEQUENCE_BITS: u64 = 12;+const WORKER_SHIFT: u64 = SEQUENCE_BITS;+const TIMESTAMP_SHIFT: u64 = WORKER_BITS + SEQUENCE_BITS;+const SEQUENCE_MASK: u64 = (1 << SEQUENCE_BITS) - 1;+const WORKER_MASK: u64 = (1 << WORKER_BITS) - 1;++#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]+pub struct Snowflake(pub u64);++impl Snowflake {+ pub const fn from_raw(raw: u64) -> Self {+ Self(raw)+ }++ pub fn timestamp_ms(self) -> u64 {+ (self.0 >> TIMESTAMP_SHIFT) + OMNIDISC_EPOCH_MS+ }++ pub fn worker_id(self) -> u16 {+ ((self.0 >> WORKER_SHIFT) & WORKER_MASK) as u16+ }++ pub fn sequence(self) -> u16 {+ (self.0 & SEQUENCE_MASK) as u16+ }++ pub fn bucket(self) -> u32 {+ ((self.timestamp_ms() - OMNIDISC_EPOCH_MS) / BUCKET_SPAN_MS) as u32+ }++ pub fn bucket_for_timestamp_ms(ts: u64) -> u32 {+ (ts.saturating_sub(OMNIDISC_EPOCH_MS) / BUCKET_SPAN_MS) as u32+ }++ pub fn lower_bound_for_bucket(bucket: u32) -> Self {+ Self((bucket as u64 * BUCKET_SPAN_MS) << TIMESTAMP_SHIFT)+ }++ pub fn is_nil(self) -> bool {+ self.0 == 0+ }+}++impl fmt::Debug for Snowflake {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "Snowflake({})", self.0)+ }+}++impl fmt::Display for Snowflake {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.0)+ }+}++impl FromStr for Snowflake {+ type Err = std::num::ParseIntError;+ fn from_str(s: &str) -> Result<Self, Self::Err> {+ s.parse::<u64>().map(Snowflake)+ }+}++impl Serialize for Snowflake {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.collect_str(&self.0)+ }+}++impl<'de> Deserialize<'de> for Snowflake {+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let s = String::deserialize(d)?;+ s.parse().map_err(serde::de::Error::custom)+ }+}++impl From<u64> for Snowflake {+ fn from(v: u64) -> Self {+ Self(v)+ }+}++pub struct SnowflakeGenerator {+ worker_id: u64,+ state: AtomicU64,+}++impl SnowflakeGenerator {+ pub fn new(worker_id: u16) -> Self {+ Self {+ worker_id: (worker_id as u64) & WORKER_MASK,+ state: AtomicU64::new(0),+ }+ }++ pub fn next(&self) -> Snowflake {+ loop {+ let now = Self::now_ms();+ let prev = self.state.load(Ordering::Acquire);+ let prev_ts = prev >> SEQUENCE_BITS;+ let prev_seq = prev & SEQUENCE_MASK;+ let (ts, seq) = if now > prev_ts {+ (now, 0)+ } else if prev_seq < SEQUENCE_MASK {+ (prev_ts, prev_seq + 1)+ } else {+ std::hint::spin_loop();+ continue;+ };+ let next = (ts << SEQUENCE_BITS) | seq;+ if self+ .state+ .compare_exchange(prev, next, Ordering::AcqRel, Ordering::Acquire)+ .is_ok()+ {+ return Snowflake((ts << TIMESTAMP_SHIFT) | (self.worker_id << WORKER_SHIFT) | seq);+ }+ }+ }++ fn now_ms() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+ .saturating_sub(OMNIDISC_EPOCH_MS)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ids_are_monotonic_and_unique() {+ let g = SnowflakeGenerator::new(3);+ let mut prev = g.next();+ for _ in 0..10_000 {+ let n = g.next();+ assert!(n > prev);+ assert_eq!(n.worker_id(), 3);+ prev = n;+ }+ }++ #[test]+ fn bucket_matches_timestamp_division() {+ let g = SnowflakeGenerator::new(0);+ let id = g.next();+ assert_eq!(id.bucket(), Snowflake::bucket_for_timestamp_ms(id.timestamp_ms()));+ assert!(Snowflake::lower_bound_for_bucket(id.bucket()) <= id);+ assert!(Snowflake::lower_bound_for_bucket(id.bucket() + 1) > id);+ }++ #[test]+ fn serializes_as_string() {+ let id = Snowflake(1234567890123);+ assert_eq!(serde_json::to_string(&id).unwrap(), "\"1234567890123\"");+ let back: Snowflake = serde_json::from_str("\"1234567890123\"").unwrap();+ assert_eq!(back, id);+ }+}diff --git a/src-tauri/omnidisc-proto/src/user.rs b/src-tauri/omnidisc-proto/src/user.rsnew file mode 100644index 00000000..da2b865b--- /dev/null+++ b/src-tauri/omnidisc-proto/src/user.rs@@ -0,0 +1,116 @@+use crate::Snowflake;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum Presence {+ Online,+ Idle,+ Dnd,+ Invisible,+ #[default]+ Offline,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct User {+ pub id: Snowflake,+ pub username: String,+ pub display_name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub avatar: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub banner: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub accent_color: Option<u32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bio: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pronouns: Option<String>,+ #[serde(default)]+ pub flags: u64,+ #[serde(default)]+ pub bot: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub identity_key: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]+pub struct CustomStatus {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub emoji: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub expires_at: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct PresenceUpdate {+ pub user_id: Snowflake,+ pub status: Presence,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub custom_status: Option<CustomStatus>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub activity: Option<Activity>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Activity {+ pub kind: ActivityKind,+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub details: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub started_at: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ActivityKind {+ Playing,+ Listening,+ Watching,+ Streaming,+ Downloading,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum RelationshipKind {+ Friend,+ IncomingRequest,+ OutgoingRequest,+ Blocked,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Relationship {+ pub user_id: Snowflake,+ pub kind: RelationshipKind,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nickname: Option<String>,+ pub since: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct VoiceState {+ pub user_id: Snowflake,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<Snowflake>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub channel_id: Option<Snowflake>,+ pub session_id: String,+ #[serde(default)]+ pub self_mute: bool,+ #[serde(default)]+ pub self_deaf: bool,+ #[serde(default)]+ pub server_mute: bool,+ #[serde(default)]+ pub server_deaf: bool,+ #[serde(default)]+ pub streaming: bool,+ #[serde(default)]+ pub video: bool,+}diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rsindex abcc1edf..45160bf5 100644--- a/src-tauri/omniget-core/src/models/settings.rs+++ b/src-tauri/omniget-core/src/models/settings.rs@@ -33,6 +33,55 @@ pub struct AppSettings {pub league: LeagueSettings,#[serde(default)]pub accessibility: AccessibilitySettings,+ #[serde(default)]+ pub omnidisc: OmnidiscSettings,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct OmnidiscSettings {+ #[serde(default)]+ pub enabled: bool,+ #[serde(default)]+ pub voice: OmnidiscVoiceSettings,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OmnidiscVoiceSettings {+ #[serde(default)]+ pub ptt_key: String,+ #[serde(default = "default_true")]+ pub noise_suppression: bool,+ #[serde(default)]+ pub input_device: Option<String>,+ #[serde(default)]+ pub output_device: Option<String>,+ #[serde(default = "default_vad_threshold_db")]+ pub vad_threshold_db: f32,+ /// How much of everyone else's audio to duck while you speak, 0-100 %.+ #[serde(default)]+ pub ducking_percent: u8,+ /// Force every connection through a TURN relay so the other side never+ /// learns your IP. Needs a TURN server on the instance.+ #[serde(default)]+ pub relay_only: bool,+}++impl Default for OmnidiscVoiceSettings {+ fn default() -> Self {+ Self {+ ptt_key: String::new(),+ noise_suppression: true,+ input_device: None,+ output_device: None,+ vad_threshold_db: default_vad_threshold_db(),+ ducking_percent: 0,+ relay_only: false,+ }+ }+}++fn default_vad_threshold_db() -> f32 {+ -45.0}#[derive(Debug, Clone, Default, Serialize, Deserialize)]@@ -638,6 +687,7 @@ impl Default for AppSettings {bridge: BridgeSettings::default(),league: LeagueSettings::default(),accessibility: AccessibilitySettings::default(),+ omnidisc: OmnidiscSettings::default(),}}}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 7a0722a4..9401106c 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -13,6 +13,7 @@ pub mod host_queue;pub mod integration;pub mod league;pub mod media_history;+pub mod omnidisc;pub mod p2p;pub mod plugins;pub mod reencode;diff --git a/src-tauri/src/commands/omnidisc/api.rs b/src-tauri/src/commands/omnidisc/api.rsnew file mode 100644index 00000000..13822f2f--- /dev/null+++ b/src-tauri/src/commands/omnidisc/api.rs@@ -0,0 +1,877 @@+use super::{normalize_instance_url, store};+use reqwest::{Method, StatusCode};+use serde::de::DeserializeOwned;+use serde_json::{json, Value};+use std::time::Duration;++pub const ERR_UNAUTHORIZED: &str = "ERR_UNAUTHORIZED";+pub const ERR_FORBIDDEN: &str = "ERR_FORBIDDEN";+pub const ERR_NOT_FOUND: &str = "ERR_NOT_FOUND";+pub const ERR_RATE_LIMITED: &str = "ERR_RATE_LIMITED";+pub const ERR_UNREACHABLE: &str = "ERR_UNREACHABLE";+pub const ERR_SERVER: &str = "ERR_SERVER";+pub const ERR_BAD_REQUEST: &str = "ERR_BAD_REQUEST";+pub const ERR_NO_SESSION: &str = "ERR_NO_SESSION";++/// Ids reach `Api` as strings from the frontend and from server payloads, and+/// they end up interpolated into a request path. `Url::parse` resolves `..`, so+/// an id is only ever a snowflake, a device id or a group id: never a way to+/// walk out of the route it was meant for.+pub fn path_id(id: &str) -> Result<&str, String> {+ let ok = !id.is_empty()+ && id.len() <= 128+ && id != "."+ && id != ".."+ && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));+ if ok {+ Ok(id)+ } else {+ tracing::warn!("[omnidisc] refused an id that is not a plain identifier");+ Err(format!("{}:invalid_id", ERR_BAD_REQUEST))+ }+}++/// Last line of defence for every request this module makes: the assembled path+/// must still be the route we wrote, whatever was interpolated into it.+fn safe_path(path: &str) -> bool {+ path.starts_with('/')+ && !path.contains("..")+ && !path.contains("//")+ && path.chars().all(|c| {+ c.is_ascii_alphanumeric() || matches!(c, '/' | '-' | '_' | '.' | '@' | '%' | '~')+ })+}++pub fn http_client(timeout: Duration) -> Result<reqwest::Client, String> {+ crate::core::http_client::apply_global_proxy(+ reqwest::Client::builder()+ .user_agent(format!("OmniGet/{}", env!("CARGO_PKG_VERSION")))+ .timeout(timeout),+ )+ .build()+ .map_err(|e| format!("OmniDisc: could not build HTTP client: {}", e))+}++pub struct Api {+ pub base: String,+ token: Option<String>,+ http: reqwest::Client,+}++impl Api {+ pub fn public(url: &str) -> Result<Self, String> {+ let base = normalize_instance_url(url)?;+ Ok(Self { base, token: None, http: http_client(Duration::from_secs(15))? })+ }++ pub fn authed(url: &str) -> Result<Self, String> {+ let base = normalize_instance_url(url)?;+ let token = store::load_token(&base)?.ok_or_else(|| ERR_NO_SESSION.to_string())?;+ Ok(Self { base, token: Some(token), http: http_client(Duration::from_secs(15))? })+ }++ pub fn with_token(base: String, token: String) -> Result<Self, String> {+ Ok(Self { base, token: Some(token), http: http_client(Duration::from_secs(15))? })+ }++ pub async fn send<T: DeserializeOwned>(+ &self,+ method: Method,+ path: &str,+ query: &[(&str, String)],+ body: Option<Value>,+ ) -> Result<T, String> {+ let text = self.raw(method, path, query, body).await?;+ serde_json::from_str(&text).map_err(|e| {+ tracing::warn!("[omnidisc] {}{} returned unexpected JSON: {}", self.base, path, e);+ ERR_SERVER.to_string()+ })+ }++ pub async fn send_empty(+ &self,+ method: Method,+ path: &str,+ body: Option<Value>,+ ) -> Result<(), String> {+ self.raw(method, path, &[], body).await.map(|_| ())+ }++ async fn raw(+ &self,+ method: Method,+ path: &str,+ query: &[(&str, String)],+ body: Option<Value>,+ ) -> Result<String, String> {+ if !safe_path(path) {+ tracing::warn!("[omnidisc] refused a request path that is not a plain route");+ return Err(format!("{}:invalid_path", ERR_BAD_REQUEST));+ }+ let url = format!("{}{}", self.base, path);+ let mut req = self.http.request(method.clone(), &url);+ if !query.is_empty() {+ req = req.query(query);+ }+ if let Some(token) = &self.token {+ req = req.bearer_auth(token);+ }+ if let Some(body) = body {+ req = req.json(&body);+ }+ let response = req.send().await.map_err(|e| {+ tracing::warn!("[omnidisc] {} {} unreachable: {}", method, url, e);+ ERR_UNREACHABLE.to_string()+ })?;+ let status = response.status();+ let text = response.text().await.unwrap_or_default();+ if status.is_success() {+ return Ok(text);+ }+ let code = serde_json::from_str::<omnidisc_proto::rest::ApiError>(&text)+ .map(|e| e.code)+ .unwrap_or_default();+ tracing::warn!("[omnidisc] {} {} -> {} {}", method, url, status.as_u16(), code);+ Err(map_error(status, &code))+ }+}++pub fn map_error(status: StatusCode, code: &str) -> String {+ match status {+ StatusCode::UNAUTHORIZED => ERR_UNAUTHORIZED.to_string(),+ StatusCode::FORBIDDEN => with_code(ERR_FORBIDDEN, code),+ StatusCode::NOT_FOUND => ERR_NOT_FOUND.to_string(),+ StatusCode::TOO_MANY_REQUESTS => ERR_RATE_LIMITED.to_string(),+ s if s.is_client_error() => with_code(ERR_BAD_REQUEST, code),+ _ => ERR_SERVER.to_string(),+ }+}++fn with_code(base: &str, code: &str) -> String {+ if code.is_empty() {+ base.to_string()+ } else {+ format!("{}:{}", base, code)+ }+}++fn opt(v: Option<String>) -> Option<String> {+ v.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())+}++#[tauri::command]+pub async fn omnidisc_list_messages(+ url: String,+ channel_id: String,+ before: Option<String>,+ after: Option<String>,+ around: Option<String>,+ limit: Option<u32>,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let mut query: Vec<(&str, String)> = Vec::new();+ if let Some(b) = opt(before) {+ query.push(("before", b));+ }+ if let Some(a) = opt(after) {+ query.push(("after", a));+ }+ if let Some(a) = opt(around) {+ query.push(("around", a));+ }+ if let Some(l) = limit {+ query.push(("limit", l.clamp(1, 100).to_string()));+ }+ api.send(Method::GET, &format!("/api/channels/{}/messages", channel_id), &query, None)+ .await+}++/// One entry point for both surfaces. `encrypted` comes from the channel kind:+/// DMs and group DMs go through MLS, guild channels go through the plain REST+/// route the server can read. Uploads are referenced by their local id so the+/// file keys never cross the bridge.+#[tauri::command]+pub async fn omnidisc_send_message(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ channel_id: String,+ content: String,+ reply_to: Option<String>,+ nonce: Option<String>,+ upload_ids: Option<Vec<String>>,+ encrypted: Option<bool>,+ recipient_ids: Option<Vec<String>>,+) -> Result<Value, String> {+ let base = super::normalize_instance_url(&url)?;+ let upload_ids = upload_ids.unwrap_or_default();+ let uploads = state.omnidisc_uploads.peek(&upload_ids).await?;+ if encrypted.unwrap_or(false) {+ let payload = super::mls::E2eePayload {+ v: 1,+ content,+ reply_to: opt(reply_to),+ nonce: opt(nonce),+ files: uploads.iter().filter_map(|u| u.manifest()).collect(),+ };+ let recipients = recipient_ids.unwrap_or_default();+ let handle = state.omnidisc_mls.session(&base).await?;+ let mut session = handle.lock().await;+ let api = Api::authed(&base)?;+ let sent =+ super::mls::send_encrypted(&api, &mut session, &channel_id, &recipients, payload)+ .await?;+ state.omnidisc_uploads.release(&upload_ids).await;+ return Ok(sent);+ }+ let api = Api::authed(&base)?;+ let mut body = json!({ "content": content });+ if let Some(n) = opt(nonce) {+ body["nonce"] = Value::String(n);+ }+ if let Some(r) = opt(reply_to) {+ body["reference"] = json!({ "message_id": r, "channel_id": channel_id });+ }+ let attachment_ids: Vec<String> = uploads.iter().map(|u| u.attachment_id.clone()).collect();+ if !attachment_ids.is_empty() {+ body["attachment_ids"] = json!(attachment_ids);+ }+ let sent = api+ .send(Method::POST, &format!("/api/channels/{}/messages", channel_id), &[], Some(body))+ .await?;+ state.omnidisc_uploads.release(&upload_ids).await;+ Ok(sent)+}++#[tauri::command]+pub async fn omnidisc_edit_message(+ url: String,+ channel_id: String,+ message_id: String,+ content: String,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::PATCH,+ &format!("/api/channels/{}/messages/{}", channel_id, message_id),+ &[],+ Some(json!({ "content": content })),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_delete_message(+ url: String,+ channel_id: String,+ message_id: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(+ Method::DELETE,+ &format!("/api/channels/{}/messages/{}", channel_id, message_id),+ None,+ )+ .await+}++fn reaction_path(channel_id: &str, message_id: &str, emoji: &str) -> String {+ format!(+ "/api/channels/{}/messages/{}/reactions/{}/@me",+ channel_id,+ message_id,+ urlencoding::encode(emoji)+ )+}++#[tauri::command]+pub async fn omnidisc_add_reaction(+ url: String,+ channel_id: String,+ message_id: String,+ emoji: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::PUT, &reaction_path(&channel_id, &message_id, &emoji), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_remove_reaction(+ url: String,+ channel_id: String,+ message_id: String,+ emoji: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &reaction_path(&channel_id, &message_id, &emoji), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_ack(url: String, channel_id: String, message_id: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::POST,+ &format!("/api/channels/{}/ack", channel_id),+ &[],+ Some(json!({ "message_id": message_id })),+ )+ .await+}++pub async fn typing_rest(url: &str, channel_id: &str) -> Result<(), String> {+ let api = Api::authed(url)?;+ api.send_empty(Method::POST, &format!("/api/channels/{}/typing", channel_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_create_guild(url: String, name: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::POST, "/api/guilds", &[], Some(json!({ "name": name }))).await+}++#[tauri::command]+pub async fn omnidisc_create_channel(+ url: String,+ guild_id: String,+ name: String,+ kind: u8,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::POST,+ &format!("/api/guilds/{}/channels", guild_id),+ &[],+ Some(json!({ "name": name, "type": kind })),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_create_invite(+ url: String,+ guild_id: String,+ channel_id: Option<String>,+ max_age_seconds: Option<u64>,+ max_uses: Option<u32>,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let mut body = json!({ "guild_id": guild_id });+ if let Some(c) = opt(channel_id) {+ body["channel_id"] = Value::String(c);+ }+ if let Some(age) = max_age_seconds.filter(|a| *a > 0) {+ body["max_age_seconds"] = json!(age);+ }+ if let Some(uses) = max_uses.filter(|u| *u > 0) {+ body["max_uses"] = json!(uses);+ }+ api.send(Method::POST, "/api/invites", &[], Some(body)).await+}++#[tauri::command]+pub async fn omnidisc_join_invite(url: String, code: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let code = extract_invite_code(&code);+ if code.is_empty() {+ return Err(format!("{}:invalid_invite", ERR_BAD_REQUEST));+ }+ api.send(+ Method::POST,+ &format!("/api/invites/{}", urlencoding::encode(&code)),+ &[],+ Some(json!({})),+ )+ .await+}++pub fn extract_invite_code(raw: &str) -> String {+ let trimmed = raw.trim().trim_end_matches('/');+ match trimmed.rsplit_once("/invite/") {+ Some((_, code)) => code.trim().to_string(),+ None => trimmed.rsplit('/').next().unwrap_or(trimmed).trim().to_string(),+ }+}++#[tauri::command]+pub async fn omnidisc_create_dm(url: String, recipient_ids: Vec<String>) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::POST,+ "/api/users/@me/channels",+ &[],+ Some(json!({ "recipient_ids": recipient_ids })),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_update_me(url: String, patch: Value) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::PATCH, "/api/users/@me", &[], Some(patch)).await+}++#[tauri::command]+pub async fn omnidisc_get_user(url: String, user_id: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, &format!("/api/users/{}", user_id), &[], None).await+}++#[tauri::command]+pub async fn omnidisc_get_guild(url: String, guild_id: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, &format!("/api/guilds/{}", guild_id), &[], None).await+}++#[tauri::command]+pub async fn omnidisc_get_me(url: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, "/api/users/@me", &[], None).await+}++#[tauri::command]+pub async fn omnidisc_search(+ url: String,+ scope: String,+ scope_id: String,+ query: String,+ from: Option<String>,+ channel: Option<String>,+ has: Option<String>,+ before: Option<String>,+ after: Option<String>,+ limit: Option<u32>,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let path = match scope.as_str() {+ "guild" => format!("/api/guilds/{}/messages/search", scope_id),+ "channel" => format!("/api/channels/{}/messages/search", scope_id),+ _ => return Err(format!("{}:invalid_scope", ERR_BAD_REQUEST)),+ };+ let mut q: Vec<(&str, String)> = vec![("q", query)];+ if let Some(v) = opt(from) {+ q.push(("from", v));+ }+ if let Some(v) = opt(channel) {+ q.push(("in", v));+ }+ if let Some(v) = opt(has) {+ q.push(("has", v));+ }+ if let Some(v) = opt(before) {+ q.push(("before", v));+ }+ if let Some(v) = opt(after) {+ q.push(("after", v));+ }+ q.push(("limit", limit.unwrap_or(25).clamp(1, 100).to_string()));+ api.send(Method::GET, &path, &q, None).await+}++#[tauri::command]+pub async fn omnidisc_list_pins(url: String, channel_id: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, &format!("/api/channels/{}/pins", channel_id), &[], None).await+}++#[tauri::command]+pub async fn omnidisc_pin_message(+ url: String,+ channel_id: String,+ message_id: String,+ pinned: bool,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ let method = if pinned { Method::PUT } else { Method::DELETE };+ api.send_empty(method, &format!("/api/channels/{}/pins/{}", channel_id, message_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_list_relationships(url: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, "/api/users/@me/relationships", &[], None).await+}++#[tauri::command]+pub async fn omnidisc_add_relationship(+ url: String,+ username: Option<String>,+ user_id: Option<String>,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ let mut body = json!({});+ if let Some(u) = opt(username) {+ body["username"] = Value::String(u);+ }+ if let Some(u) = opt(user_id) {+ body["user_id"] = Value::String(u);+ }+ if body.get("username").is_none() && body.get("user_id").is_none() {+ return Err(format!("{}:invalid_field", ERR_BAD_REQUEST));+ }+ api.send_empty(Method::POST, "/api/users/@me/relationships", Some(body)).await+}++#[tauri::command]+pub async fn omnidisc_accept_relationship(url: String, user_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::PUT, &format!("/api/users/@me/relationships/{}", user_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_remove_relationship(url: String, user_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/users/@me/relationships/{}", user_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_block_user(url: String, user_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::PUT, &format!("/api/users/@me/relationships/{}/block", user_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_list_notes(url: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, "/api/users/@me/notes", &[], None).await+}++#[tauri::command]+pub async fn omnidisc_put_note(url: String, user_id: String, note: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(+ Method::PUT,+ &format!("/api/users/@me/notes/{}", user_id),+ Some(json!({ "note": note })),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_update_guild(url: String, guild_id: String, patch: Value) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::PATCH, &format!("/api/guilds/{}", guild_id), &[], Some(patch)).await+}++#[tauri::command]+pub async fn omnidisc_delete_guild(url: String, guild_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/guilds/{}", guild_id), None).await+}++#[tauri::command]+pub async fn omnidisc_leave_guild(url: String, guild_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/users/@me/guilds/{}", guild_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_transfer_guild(+ url: String,+ guild_id: String,+ user_id: String,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::POST,+ &format!("/api/guilds/{}/transfer", guild_id),+ &[],+ Some(json!({ "user_id": user_id })),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_create_role(+ url: String,+ guild_id: String,+ name: String,+ permissions: String,+ color: Option<u32>,+ hoist: bool,+ mentionable: bool,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let mut body = json!({+ "name": name,+ "permissions": permissions,+ "hoist": hoist,+ "mentionable": mentionable,+ });+ if let Some(c) = color {+ body["color"] = json!(c);+ }+ api.send(Method::POST, &format!("/api/guilds/{}/roles", guild_id), &[], Some(body)).await+}++#[tauri::command]+pub async fn omnidisc_update_role(+ url: String,+ guild_id: String,+ role_id: String,+ patch: Value,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::PATCH,+ &format!("/api/guilds/{}/roles/{}", guild_id, role_id),+ &[],+ Some(patch),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_delete_role(+ url: String,+ guild_id: String,+ role_id: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/guilds/{}/roles/{}", guild_id, role_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_set_member_role(+ url: String,+ guild_id: String,+ user_id: String,+ role_id: String,+ granted: bool,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ let method = if granted { Method::PUT } else { Method::DELETE };+ api.send_empty(+ method,+ &format!("/api/guilds/{}/members/{}/roles/{}", guild_id, user_id, role_id),+ None,+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_update_member(+ url: String,+ guild_id: String,+ user_id: String,+ patch: Value,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(+ Method::PATCH,+ &format!("/api/guilds/{}/members/{}", guild_id, user_id),+ &[],+ Some(patch),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_kick_member(+ url: String,+ guild_id: String,+ user_id: String,+ reason: Option<String>,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ let mut body = json!({});+ if let Some(r) = opt(reason) {+ body["reason"] = Value::String(r);+ }+ api.send_empty(+ Method::DELETE,+ &format!("/api/guilds/{}/members/{}", guild_id, user_id),+ Some(body),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_ban_member(+ url: String,+ guild_id: String,+ user_id: String,+ reason: Option<String>,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let mut body = json!({});+ if let Some(r) = opt(reason) {+ body["reason"] = Value::String(r);+ }+ api.send(+ Method::PUT,+ &format!("/api/guilds/{}/bans/{}", guild_id, user_id),+ &[],+ Some(body),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_unban_member(+ url: String,+ guild_id: String,+ user_id: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/guilds/{}/bans/{}", guild_id, user_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_list_bans(url: String, guild_id: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, &format!("/api/guilds/{}/bans", guild_id), &[], None).await+}++#[tauri::command]+pub async fn omnidisc_audit_log(+ url: String,+ guild_id: String,+ action: Option<String>,+ actor_id: Option<String>,+ before: Option<String>,+ limit: Option<u32>,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let mut q: Vec<(&str, String)> = Vec::new();+ if let Some(v) = opt(action) {+ q.push(("action", v));+ }+ if let Some(v) = opt(actor_id) {+ q.push(("actor_id", v));+ }+ if let Some(v) = opt(before) {+ q.push(("before", v));+ }+ q.push(("limit", limit.unwrap_or(50).clamp(1, 100).to_string()));+ api.send(Method::GET, &format!("/api/guilds/{}/audit-log", guild_id), &q, None).await+}++#[tauri::command]+pub async fn omnidisc_update_channel(+ url: String,+ channel_id: String,+ patch: Value,+) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::PATCH, &format!("/api/channels/{}", channel_id), &[], Some(patch)).await+}++#[tauri::command]+pub async fn omnidisc_delete_channel(url: String, channel_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/channels/{}", channel_id), None).await+}++#[tauri::command]+pub async fn omnidisc_put_overwrite(+ url: String,+ channel_id: String,+ target_id: String,+ target_kind: String,+ allow: String,+ deny: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(+ Method::PUT,+ &format!("/api/channels/{}/overwrites/{}", channel_id, target_id),+ Some(json!({ "target_kind": target_kind, "allow": allow, "deny": deny })),+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_delete_overwrite(+ url: String,+ channel_id: String,+ target_id: String,+) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(+ Method::DELETE,+ &format!("/api/channels/{}/overwrites/{}", channel_id, target_id),+ None,+ )+ .await+}++#[tauri::command]+pub async fn omnidisc_list_sessions(url: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ api.send(Method::GET, "/api/auth/sessions", &[], None).await+}++#[tauri::command]+pub async fn omnidisc_revoke_session(url: String, session_id: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, &format!("/api/auth/sessions/{}", session_id), None)+ .await+}++#[tauri::command]+pub async fn omnidisc_revoke_other_sessions(url: String) -> Result<(), String> {+ let api = Api::authed(&url)?;+ api.send_empty(Method::DELETE, "/api/auth/sessions", None).await+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn maps_statuses_to_stable_codes() {+ assert_eq!(map_error(StatusCode::UNAUTHORIZED, "unauthorized"), "ERR_UNAUTHORIZED");+ assert_eq!(map_error(StatusCode::FORBIDDEN, "registration_closed"), "ERR_FORBIDDEN:registration_closed");+ assert_eq!(map_error(StatusCode::FORBIDDEN, ""), "ERR_FORBIDDEN");+ assert_eq!(map_error(StatusCode::NOT_FOUND, "not_found"), "ERR_NOT_FOUND");+ assert_eq!(map_error(StatusCode::TOO_MANY_REQUESTS, "rate_limited"), "ERR_RATE_LIMITED");+ assert_eq!(map_error(StatusCode::BAD_REQUEST, "invalid_credentials"), "ERR_BAD_REQUEST:invalid_credentials");+ assert_eq!(map_error(StatusCode::CONFLICT, "username_taken"), "ERR_BAD_REQUEST:username_taken");+ assert_eq!(map_error(StatusCode::INTERNAL_SERVER_ERROR, "internal"), "ERR_SERVER");+ assert_eq!(map_error(StatusCode::BAD_GATEWAY, ""), "ERR_SERVER");+ }++ /// `Url::parse` resolves `..`, so an id that walks up the path would reach a+ /// route the caller never wrote.+ #[test]+ fn ids_are_plain_identifiers_or_nothing() {+ assert_eq!(path_id("1234567890123456789"), Ok("1234567890123456789"));+ assert_eq!(path_id("od-3f2a1b4c-1111-2222-3333-444455556666").is_ok(), true);+ assert!(path_id("../../admin/instance").is_err());+ assert!(path_id("..").is_err());+ assert!(path_id("7/messages").is_err());+ assert!(path_id("7?limit=1").is_err());+ assert!(path_id("7#frag").is_err());+ assert!(path_id("7 8").is_err());+ assert!(path_id("").is_err());+ assert!(path_id(&"9".repeat(129)).is_err());+ }++ #[test]+ fn assembled_paths_stay_inside_the_api() {+ assert!(safe_path("/api/users/@me/devices"));+ assert!(safe_path("/api/channels/17/messages/42/reactions/%F0%9F%91%8D/@me"));+ assert!(!safe_path("/api/channels/../../admin"));+ assert!(!safe_path("/api/channels//messages"));+ assert!(!safe_path("api/instance"));+ assert!(!safe_path("/api/channels/7?x=1"));+ assert!(!safe_path("/api/channels/7\n/x"));+ }++ #[test]+ fn invite_code_is_extracted_from_links() {+ assert_eq!(extract_invite_code("abc123"), "abc123");+ assert_eq!(extract_invite_code("https://chat.example.org/invite/abc123"), "abc123");+ assert_eq!(extract_invite_code("https://chat.example.org/invite/abc123/"), "abc123");+ assert_eq!(extract_invite_code(" abc123 "), "abc123");+ }+}diff --git a/src-tauri/src/commands/omnidisc/auth.rs b/src-tauri/src/commands/omnidisc/auth.rsnew file mode 100644index 00000000..0ff41e16--- /dev/null+++ b/src-tauri/src/commands/omnidisc/auth.rs@@ -0,0 +1,117 @@+use super::api::{Api, ERR_SERVER};+use super::store;+use reqwest::Method;+use serde::Serialize;+use serde_json::{json, Value};++#[derive(Serialize)]+pub struct SessionStatus {+ pub url: String,+ pub has_session: bool,+}++fn device_name() -> String {+ let host = hostname();+ match host {+ Some(h) => format!("OmniGet on {}", h),+ None => "OmniGet".to_string(),+ }+}++fn hostname() -> Option<String> {+ std::env::var("HOSTNAME")+ .ok()+ .or_else(|| std::env::var("COMPUTERNAME").ok())+ .map(|h| h.trim().to_string())+ .filter(|h| !h.is_empty())+}++async fn finish_auth(api: &Api, body: Value) -> Result<Value, String> {+ let token = body+ .get("token")+ .and_then(Value::as_str)+ .filter(|t| !t.is_empty())+ .ok_or_else(|| ERR_SERVER.to_string())?;+ let user = body.get("user").cloned().ok_or_else(|| ERR_SERVER.to_string())?;+ store::save_token(&api.base, token)?;+ let username = user.get("username").and_then(Value::as_str).unwrap_or("?").to_string();+ tracing::info!("[omnidisc] signed in to {} as {}", api.base, username);+ Ok(user)+}++pub async fn register(+ url: &str,+ username: &str,+ password: &str,+ display_name: Option<&str>,+ invite_code: Option<&str>,+) -> Result<Value, String> {+ let api = Api::public(url)?;+ let mut body = json!({ "username": username.trim(), "password": password });+ if let Some(d) = display_name.map(str::trim).filter(|d| !d.is_empty()) {+ body["display_name"] = Value::String(d.to_string());+ }+ if let Some(c) = invite_code.map(str::trim).filter(|c| !c.is_empty()) {+ body["invite_code"] = Value::String(super::api::extract_invite_code(c));+ }+ let res: Value = api.send(Method::POST, "/api/auth/register", &[], Some(body)).await?;+ finish_auth(&api, res).await+}++pub async fn login(url: &str, username: &str, password: &str) -> Result<Value, String> {+ let api = Api::public(url)?;+ let body = json!({+ "username": username.trim(),+ "password": password,+ "device_name": device_name(),+ });+ let res: Value = api.send(Method::POST, "/api/auth/login", &[], Some(body)).await?;+ finish_auth(&api, res).await+}++pub async fn logout(url: &str) -> Result<(), String> {+ let base = super::normalize_instance_url(url)?;+ if let Ok(api) = Api::authed(&base) {+ if let Err(e) = api.send_empty(Method::POST, "/api/auth/logout", None).await {+ tracing::warn!("[omnidisc] logout on {} failed ({}); dropping the local session anyway", base, e);+ }+ }+ store::delete_token(&base)+}++#[tauri::command]+pub async fn omnidisc_register(+ url: String,+ username: String,+ password: String,+ display_name: Option<String>,+ invite_code: Option<String>,+) -> Result<Value, String> {+ register(&url, &username, &password, display_name.as_deref(), invite_code.as_deref()).await+}++#[tauri::command]+pub async fn omnidisc_login(url: String, username: String, password: String) -> Result<Value, String> {+ login(&url, &username, &password).await+}++#[tauri::command]+pub async fn omnidisc_logout(+ state: tauri::State<'_, crate::AppState>,+ url: String,+) -> Result<(), String> {+ let base = super::normalize_instance_url(&url)?;+ super::gateway::stop(&state.omnidisc_gateways, &base).await;+ // The device key and the MLS state stay on disk: signing back in on the same+ // instance keeps this device (and therefore its readable history) instead of+ // silently orphaning every group it belongs to.+ state.omnidisc_mls.forget(&base).await;+ logout(&base).await+}++#[tauri::command]+pub async fn omnidisc_has_session(url: String) -> Result<SessionStatus, String> {+ let base = super::normalize_instance_url(&url)?;+ let has_session = store::load_token(&base)?.is_some();+ Ok(SessionStatus { url: base, has_session })+}diff --git a/src-tauri/src/commands/omnidisc/device.rs b/src-tauri/src/commands/omnidisc/device.rsnew file mode 100644index 00000000..b957285b--- /dev/null+++ b/src-tauri/src/commands/omnidisc/device.rs@@ -0,0 +1,268 @@+//! Per-instance device identity: one Ed25519 key pair and one stable device id.+//!+//! The private key never leaves this module — not to the frontend, not to the+//! logs, not to `settings.json`. It lives in the same store as the session token+//! (OS keyring on macOS/Windows, encrypted file elsewhere, see `store.rs`), so+//! "sign out" and "forget this instance" already drop it.++use super::api::Api;+use super::{normalize_instance_url, store};+use base64::Engine;+use omnidisc_proto::rest::Device;+use reqwest::Method;+use serde::Serialize;+use serde_json::{json, Value};+use std::collections::HashMap;+use std::path::PathBuf;++const DEVICE_KEY: &str = "device-key";+const DEVICES_FILE: &str = "device-ids.json";++#[derive(Clone)]+pub struct DeviceIdentity {+ pub device_id: String,+ pub seed: [u8; 32],+}++impl DeviceIdentity {+ pub fn public_key(&self) -> [u8; 32] {+ omnidisc_mls::MlsClient::new("0", &self.device_id, &self.seed)+ .map(|c| c.public_key())+ .unwrap_or([0u8; 32])+ }++ pub fn fingerprint(&self) -> String {+ omnidisc_mls::fingerprint(&self.public_key())+ }+}++#[derive(Serialize)]+pub struct DeviceFingerprint {+ pub device_id: String,+ pub fingerprint: String,+ pub public_key: String,+}++fn ids_path() -> Result<PathBuf, String> {+ Ok(store::base_dir()?.join(DEVICES_FILE))+}++fn read_ids() -> HashMap<String, String> {+ ids_path()+ .ok()+ .and_then(|p| std::fs::read(p).ok())+ .and_then(|b| serde_json::from_slice(&b).ok())+ .unwrap_or_default()+}++fn write_ids(map: &HashMap<String, String>) -> Result<(), String> {+ let path = ids_path()?;+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)+ .map_err(|e| format!("OmniDisc: could not create the device store: {}", e))?;+ }+ let bytes = serde_json::to_vec(map)+ .map_err(|e| format!("OmniDisc: could not encode the device store: {}", e))?;+ std::fs::write(&path, bytes)+ .map_err(|e| format!("OmniDisc: could not write the device store: {}", e))+}++/// Device ids must match the server's `[A-Za-z0-9_-]{8,64}`, so the UUID keeps+/// its hyphens and gains a prefix that makes it recognisable in a log line.+fn new_device_id() -> String {+ format!("od-{}", uuid::Uuid::new_v4())+}++pub fn hostname() -> Option<String> {+ for key in ["HOSTNAME", "COMPUTERNAME", "HOST"] {+ if let Some(h) = std::env::var(key).ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()) {+ return Some(h);+ }+ }+ #[cfg(unix)]+ if let Ok(raw) = std::fs::read_to_string("/etc/hostname") {+ let trimmed = raw.trim().to_string();+ if !trimmed.is_empty() {+ return Some(trimmed);+ }+ }+ None+}++pub fn device_name() -> String {+ let os = match std::env::consts::OS {+ "macos" => "macOS",+ "windows" => "Windows",+ "linux" => "Linux",+ other => other,+ };+ let name = match hostname() {+ Some(host) => format!("{} · OmniGet on {}", host, os),+ None => format!("OmniGet on {}", os),+ };+ // The server caps device names at 64 characters and rejects longer ones;+ // a long hostname must not turn into a failed device registration.+ name.chars().take(64).collect()+}++/// Load this instance's identity, generating it on first use.+pub fn identity(base: &str) -> Result<DeviceIdentity, String> {+ let mut ids = read_ids();+ let device_id = match ids.get(base) {+ Some(id) if !id.is_empty() => id.clone(),+ _ => {+ let id = new_device_id();+ ids.insert(base.to_string(), id.clone());+ write_ids(&ids)?;+ id+ }+ };+ let account = store::secret_account(base, DEVICE_KEY);+ let seed = match store::load_secret(&account)? {+ Some(encoded) => decode_seed(&encoded)?,+ None => {+ let mut seed = [0u8; 32];+ rand::Rng::fill_bytes(&mut rand::rng(), &mut seed);+ store::save_secret(+ &account,+ &base64::engine::general_purpose::STANDARD.encode(seed),+ )?;+ seed+ }+ };+ Ok(DeviceIdentity { device_id, seed })+}++fn decode_seed(encoded: &str) -> Result<[u8; 32], String> {+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(encoded.trim())+ .map_err(|_| "OmniDisc: the stored device key is unreadable".to_string())?;+ if bytes.len() != 32 {+ return Err("OmniDisc: the stored device key has the wrong size".to_string());+ }+ let mut seed = [0u8; 32];+ seed.copy_from_slice(&bytes);+ Ok(seed)+}++pub fn forget(base: &str) -> Result<(), String> {+ let mut ids = read_ids();+ if ids.remove(base).is_some() {+ write_ids(&ids)?;+ }+ store::delete_secret(&store::secret_account(base, DEVICE_KEY))+}++/// Publish the public half so other devices can add us to their MLS groups.+/// Called on login and on every gateway connect: it is an upsert, and it is what+/// binds the current session to this device on the server side.+pub async fn register(api: &Api, identity: &DeviceIdentity) -> Result<Device, String> {+ let public = base64::engine::general_purpose::STANDARD.encode(identity.public_key());+ let body = json!({ "ed25519_pub": public, "name": device_name() });+ let device: Device = api+ .send(+ Method::PUT,+ &format!("/api/users/@me/devices/{}", identity.device_id),+ &[],+ Some(body),+ )+ .await?;+ tracing::info!(+ "[omnidisc] device {} registered on {}",+ identity.device_id,+ api.base+ );+ Ok(device)+}++pub async fn ensure_registered(base: &str) -> Result<DeviceIdentity, String> {+ let identity = identity(base)?;+ let api = Api::authed(base)?;+ register(&api, &identity).await?;+ Ok(identity)+}++#[tauri::command]+pub async fn omnidisc_device_fingerprint(url: String) -> Result<DeviceFingerprint, String> {+ let base = normalize_instance_url(&url)?;+ let identity = identity(&base)?;+ let public = identity.public_key();+ Ok(DeviceFingerprint {+ device_id: identity.device_id,+ fingerprint: omnidisc_mls::fingerprint(&public),+ public_key: base64::engine::general_purpose::STANDARD.encode(public),+ })+}++#[tauri::command]+pub async fn omnidisc_list_user_devices(url: String, user_id: String) -> Result<Value, String> {+ let api = Api::authed(&url)?;+ let path = if user_id.trim().is_empty() || user_id == "@me" {+ "/api/users/@me/devices".to_string()+ } else {+ format!("/api/users/{}/devices", user_id)+ };+ let devices: Vec<Device> = api.send(Method::GET, &path, &[], None).await?;+ let enriched: Vec<Value> = devices+ .into_iter()+ .map(|d| {+ let fingerprint = base64::engine::general_purpose::STANDARD+ .decode(&d.ed25519_pub)+ .ok()+ .filter(|b| b.len() == 32)+ .map(|b| omnidisc_mls::fingerprint(&b));+ let mut value = serde_json::to_value(&d).unwrap_or(Value::Null);+ if let (Value::Object(map), Some(fp)) = (&mut value, fingerprint) {+ map.insert("fingerprint".into(), Value::String(fp));+ }+ value+ })+ .collect();+ Ok(Value::Array(enriched))+}++#[tauri::command]+pub async fn omnidisc_revoke_device(url: String, device_id: String) -> Result<(), String> {+ let base = normalize_instance_url(&url)?;+ let api = Api::authed(&base)?;+ api.send_empty(+ Method::DELETE,+ &format!("/api/users/@me/devices/{}", device_id),+ None,+ )+ .await?;+ let mine = identity(&base)?;+ if mine.device_id == device_id {+ forget(&base)?;+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn device_ids_fit_the_server_rules() {+ let id = new_device_id();+ assert!(id.len() >= 8 && id.len() <= 64, "{id}");+ assert!(id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'), "{id}");+ assert_ne!(id, new_device_id());+ }++ #[test]+ fn device_names_say_where_they_run() {+ let name = device_name();+ assert!(name.contains("OmniGet"), "{name}");+ assert!(name.len() <= 64, "{name}");+ }++ #[test]+ fn seeds_round_trip_and_bad_ones_are_refused() {+ let seed = [9u8; 32];+ let encoded = base64::engine::general_purpose::STANDARD.encode(seed);+ assert_eq!(decode_seed(&encoded).expect("decode"), seed);+ assert!(decode_seed("not base64!!").is_err());+ assert!(decode_seed(&base64::engine::general_purpose::STANDARD.encode([1u8; 16])).is_err());+ }+}diff --git a/src-tauri/src/commands/omnidisc/e2e_lock.rs b/src-tauri/src/commands/omnidisc/e2e_lock.rsnew file mode 100644index 00000000..2c2f1844--- /dev/null+++ b/src-tauri/src/commands/omnidisc/e2e_lock.rs@@ -0,0 +1,38 @@+//! The live e2e tests drive the real store, which resolves its directory from+//! `OMNIGET_OMNIDISC_SESSION_DIR` on every call. That is a process-global, so+//! two of these tests running on cargo's parallel threads clobber each other's+//! session directory and fail in ways that look like protocol bugs. They take+//! this lock instead of being marked `--test-threads=1`, which nothing enforces.++use std::sync::{Mutex, MutexGuard, OnceLock};++use super::store;++static LOCK: OnceLock<Mutex<()>> = OnceLock::new();++pub struct SessionDirGuard {+ _guard: MutexGuard<'static, ()>,+ previous: Option<String>,+}++impl SessionDirGuard {+ pub fn acquire() -> Self {+ let guard = LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ Self {+ _guard: guard,+ previous: std::env::var(store::SESSION_DIR_ENV).ok(),+ }+ }+}++impl Drop for SessionDirGuard {+ fn drop(&mut self) {+ match &self.previous {+ Some(dir) => std::env::set_var(store::SESSION_DIR_ENV, dir),+ None => std::env::remove_var(store::SESSION_DIR_ENV),+ }+ }+}diff --git a/src-tauri/src/commands/omnidisc/e2e_test.rs b/src-tauri/src/commands/omnidisc/e2e_test.rsnew file mode 100644index 00000000..5056ade5--- /dev/null+++ b/src-tauri/src/commands/omnidisc/e2e_test.rs@@ -0,0 +1,337 @@+//! End-to-end check against a running omnidisc-server, using the same+//! functions the Tauri commands call (no `invoke` layer). Skipped unless+//! `OMNIDISC_TEST_URL` points at a server, e.g.+//! `OMNIDISC_TEST_URL=http://localhost:8080 cargo test --lib omnidisc -- --ignored`.++use super::api::Api;+use super::gateway::{run_gateway, GatewaySink, Status};+use super::{auth, store};+use reqwest::Method;+use serde_json::{json, Value};+use std::sync::Arc;+use std::time::Duration;+use tokio::sync::mpsc;+use tokio_util::sync::CancellationToken;++enum Ev {+ Dispatch(String, Value),+ Status(Status, Option<String>),+}++struct ChanSink(mpsc::UnboundedSender<Ev>);++impl GatewaySink for ChanSink {+ fn dispatch(&self, _url: &str, t: &str, d: Value) {+ let _ = self.0.send(Ev::Dispatch(t.to_string(), d));+ }++ fn status(&self, _url: &str, status: Status, error: Option<&str>) {+ let _ = self.0.send(Ev::Status(status, error.map(str::to_string)));+ }+}++async fn wait_for<F: FnMut(&Ev) -> bool>(rx: &mut mpsc::UnboundedReceiver<Ev>, mut pred: F, what: &str) -> Ev {+ let deadline = tokio::time::Instant::now() + Duration::from_secs(15);+ loop {+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());+ let ev = tokio::time::timeout(remaining, rx.recv())+ .await+ .unwrap_or_else(|_| panic!("timed out waiting for {what}"))+ .unwrap_or_else(|| panic!("gateway channel closed waiting for {what}"));+ if pred(&ev) {+ return ev;+ }+ }+}++fn unique(prefix: &str) -> String {+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.subsec_nanos())+ .unwrap_or(0);+ format!("{}{}{}", prefix, std::process::id() % 10_000, nanos % 100_000)+}++#[tokio::test]+#[ignore]+async fn register_gateway_ready_send_receive() {+ let Ok(url) = std::env::var("OMNIDISC_TEST_URL") else {+ eprintln!("OMNIDISC_TEST_URL not set; skipping");+ return;+ };+ let base = super::normalize_instance_url(&url).expect("valid url");+ let _session_dir = super::e2e_lock::SessionDirGuard::acquire();++ let alice_name = unique("alice");+ let bob_name = unique("bob");+ let password = "correct horse battery";++ let alice = auth::register(&base, &alice_name, password, Some("Alice"), None)+ .await+ .expect("register alice");+ assert_eq!(alice["username"], alice_name);+ let alice_token = store::load_token(&base).expect("store").expect("alice token stored");++ let bob = auth::register(&base, &bob_name, password, None, None)+ .await+ .expect("register bob");+ let bob_token = store::load_token(&base).expect("store").expect("bob token stored");+ assert_ne!(alice_token, bob_token);++ let alice_api = Api::with_token(base.clone(), alice_token.clone()).expect("api");+ let bob_api = Api::with_token(base.clone(), bob_token.clone()).expect("api");++ let guild: Value = alice_api+ .send(Method::POST, "/api/guilds", &[], Some(json!({ "name": "E2E" })))+ .await+ .expect("create guild");+ let guild_id = guild["id"].as_str().expect("guild id").to_string();+ let general = guild["channels"]+ .as_array()+ .expect("channels")+ .iter()+ .find(|c| c["type"] == 0)+ .expect("text channel")["id"]+ .as_str()+ .expect("channel id")+ .to_string();++ let invite: Value = alice_api+ .send(Method::POST, "/api/invites", &[], Some(json!({ "guild_id": guild_id })))+ .await+ .expect("create invite");+ let code = invite["code"].as_str().expect("code").to_string();+ let joined: Value = bob_api+ .send(Method::POST, &format!("/api/invites/{code}"), &[], Some(json!({})))+ .await+ .expect("join invite");+ assert_eq!(joined["id"], guild_id);++ let fetched: Value = bob_api+ .send(Method::GET, &format!("/api/users/{}", alice["id"].as_str().expect("id")), &[], None)+ .await+ .expect("get user");+ assert_eq!(fetched["display_name"], "Alice");++ let (a_tx, mut a_rx) = mpsc::unbounded_channel();+ let (_a_out_tx, a_out_rx) = mpsc::unbounded_channel::<String>();+ let a_cancel = CancellationToken::new();+ let a_task = tokio::spawn(run_gateway(+ base.clone(),+ alice_token.clone(),+ a_out_rx,+ a_cancel.clone(),+ Arc::new(ChanSink(a_tx)),+ ));+ let ready = wait_for(&mut a_rx, |e| matches!(e, Ev::Dispatch(t, _) if t == "READY"), "alice READY").await;+ let Ev::Dispatch(_, ready_d) = ready else { unreachable!() };+ assert_eq!(ready_d["user"]["username"], alice_name);+ assert_eq!(ready_d["guilds"][0]["id"], guild_id);+ let ready_status = wait_for(&mut a_rx, |e| matches!(e, Ev::Status(Status::Ready, _)), "alice ready status").await;+ assert!(matches!(ready_status, Ev::Status(_, None)));++ let (b_tx, mut b_rx) = mpsc::unbounded_channel();+ let (b_out_tx, b_out_rx) = mpsc::unbounded_channel::<String>();+ let b_cancel = CancellationToken::new();+ let b_task = tokio::spawn(run_gateway(+ base.clone(),+ bob_token.clone(),+ b_out_rx,+ b_cancel.clone(),+ Arc::new(ChanSink(b_tx)),+ ));+ wait_for(&mut b_rx, |e| matches!(e, Ev::Dispatch(t, _) if t == "READY"), "bob READY").await;+ wait_for(&mut b_rx, |e| matches!(e, Ev::Status(Status::Ready, _)), "bob ready status").await;++ b_out_tx+ .send(json!({ "op": 20, "d": { "channel_id": general } }).to_string())+ .expect("typing frame");+ let typing = wait_for(&mut a_rx, |e| matches!(e, Ev::Dispatch(t, _) if t == "TYPING_START"), "typing").await;+ let Ev::Dispatch(_, typing_d) = typing else { unreachable!() };+ assert_eq!(typing_d["user_id"], bob["id"]);++ let sent: Value = bob_api+ .send(+ Method::POST,+ &format!("/api/channels/{general}/messages"),+ &[],+ Some(json!({ "content": "hello from bob", "nonce": "n-1" })),+ )+ .await+ .expect("send message");+ let received = wait_for(+ &mut a_rx,+ |e| matches!(e, Ev::Dispatch(t, d) if t == "MESSAGE_CREATE" && d["content"] == "hello from bob"),+ "alice MESSAGE_CREATE",+ )+ .await;+ let Ev::Dispatch(_, msg) = received else { unreachable!() };+ assert_eq!(msg["id"], sent["id"]);+ assert_eq!(msg["author_id"], bob["id"]);++ let history: Value = alice_api+ .send(Method::GET, &format!("/api/channels/{general}/messages"), &[("limit", "10".into())], None)+ .await+ .expect("history");+ assert!(history.as_array().map(|a| a.iter().any(|m| m["id"] == sent["id"])).unwrap_or(false));++ let bob_id = bob["id"].as_str().expect("bob id").to_string();+ let alice_id = alice["id"].as_str().expect("alice id").to_string();++ bob_api+ .send_empty(+ Method::POST,+ "/api/users/@me/relationships",+ Some(json!({ "username": alice_name })),+ )+ .await+ .expect("friend request");+ let requested = wait_for(+ &mut a_rx,+ |e| matches!(e, Ev::Dispatch(t, d) if t == "RELATIONSHIP_ADD" && d["user_id"] == bob_id.as_str()),+ "alice RELATIONSHIP_ADD",+ )+ .await;+ let Ev::Dispatch(_, rel) = requested else { unreachable!() };+ assert_eq!(rel["kind"], "incoming_request");++ alice_api+ .send_empty(Method::PUT, &format!("/api/users/@me/relationships/{bob_id}"), None)+ .await+ .expect("accept friend");+ wait_for(+ &mut b_rx,+ |e| matches!(e, Ev::Dispatch(t, d) if t == "RELATIONSHIP_ADD" && d["kind"] == "friend"),+ "bob friend accepted",+ )+ .await;++ let relationships: Value = alice_api+ .send(Method::GET, "/api/users/@me/relationships", &[], None)+ .await+ .expect("relationships");+ assert!(relationships+ .as_array()+ .map(|a| a.iter().any(|r| r["user_id"] == bob_id.as_str() && r["kind"] == "friend"))+ .unwrap_or(false));++ let dm: Value = alice_api+ .send(+ Method::POST,+ "/api/users/@me/channels",+ &[],+ Some(json!({ "recipient_ids": [bob_id.clone()] })),+ )+ .await+ .expect("create dm");+ let dm_id = dm["id"].as_str().expect("dm id").to_string();+ let dm_sent: Value = alice_api+ .send(+ Method::POST,+ &format!("/api/channels/{dm_id}/messages"),+ &[],+ Some(json!({ "content": "dm from alice" })),+ )+ .await+ .expect("dm message");+ wait_for(+ &mut b_rx,+ |e| matches!(e, Ev::Dispatch(t, d) if t == "MESSAGE_CREATE" && d["id"] == dm_sent["id"]),+ "bob DM MESSAGE_CREATE",+ )+ .await;++ let found: Value = alice_api+ .send(+ Method::GET,+ &format!("/api/channels/{general}/messages/search"),+ &[("q", "hello".into())],+ None,+ )+ .await+ .expect("channel search");+ assert!(found["messages"]+ .as_array()+ .map(|a| a.iter().any(|m| m["id"] == sent["id"]))+ .unwrap_or(false));+ let guild_found: Value = alice_api+ .send(+ Method::GET,+ &format!("/api/guilds/{guild_id}/messages/search"),+ &[("q", "hello".into()), ("from", bob_id.clone())],+ None,+ )+ .await+ .expect("guild search");+ assert!(guild_found["messages"]+ .as_array()+ .map(|a| a.iter().any(|m| m["id"] == sent["id"]))+ .unwrap_or(false));++ let message_id = sent["id"].as_str().expect("message id").to_string();+ alice_api+ .send_empty(Method::PUT, &format!("/api/channels/{general}/pins/{message_id}"), None)+ .await+ .expect("pin message");+ wait_for(+ &mut a_rx,+ |e| matches!(e, Ev::Dispatch(t, d) if t == "CHANNEL_PINS_UPDATE" && d["channel_id"] == general.as_str()),+ "alice CHANNEL_PINS_UPDATE",+ )+ .await;+ let pins: Value = alice_api+ .send(Method::GET, &format!("/api/channels/{general}/pins"), &[], None)+ .await+ .expect("list pins");+ assert!(pins+ .as_array()+ .map(|a| a.iter().any(|m| m["id"] == message_id.as_str()))+ .unwrap_or(false));++ alice_api+ .send_empty(+ Method::DELETE,+ &format!("/api/guilds/{guild_id}/members/{bob_id}"),+ Some(json!({ "reason": "e2e" })),+ )+ .await+ .expect("kick bob");+ wait_for(+ &mut b_rx,+ |e| matches!(e, Ev::Dispatch(t, d) if t == "GUILD_DELETE" && d["id"] == guild_id.as_str()),+ "bob kicked out of the guild",+ )+ .await;++ let audit: Value = alice_api+ .send(+ Method::GET,+ &format!("/api/guilds/{guild_id}/audit-log"),+ &[("limit", "10".into())],+ None,+ )+ .await+ .expect("audit log");+ assert!(audit+ .as_array()+ .map(|a| a.iter().any(|e| e["action"] == "member.kick" && e["actor_id"] == alice_id.as_str()))+ .unwrap_or(false));++ let sessions: Value = alice_api+ .send(Method::GET, "/api/auth/sessions", &[], None)+ .await+ .expect("sessions");+ assert!(sessions+ .as_array()+ .map(|a| a.iter().any(|s| s["current"] == true))+ .unwrap_or(false));++ a_cancel.cancel();+ b_cancel.cancel();+ let _ = tokio::time::timeout(Duration::from_secs(5), a_task).await;+ let _ = tokio::time::timeout(Duration::from_secs(5), b_task).await;+ wait_for(&mut a_rx, |e| matches!(e, Ev::Status(Status::Disconnected, _)), "alice disconnected").await;++ auth::logout(&base).await.expect("logout");+ assert!(store::load_token(&base).expect("store").is_none());+}diff --git a/src-tauri/src/commands/omnidisc/e2ee_e2e_test.rs b/src-tauri/src/commands/omnidisc/e2ee_e2e_test.rsnew file mode 100644index 00000000..7bf2428e--- /dev/null+++ b/src-tauri/src/commands/omnidisc/e2ee_e2e_test.rs@@ -0,0 +1,339 @@+//! Live end-to-end check of milestone M4: device identity, MLS groups,+//! encrypted messages and encrypted attachments, against a real+//! omnidisc-server.+//!+//! ```text+//! OMNIDISC_TEST_URL=http://72.62.136.3:8080 \+//! cargo test --lib omnidisc -- --ignored --nocapture+//! ```+//!+//! Each side gets its own `OMNIGET_OMNIDISC_SESSION_DIR`, because the session+//! store, the device key and the MLS state are all keyed by instance URL — two+//! accounts sharing one directory would share one device identity, which is+//! exactly the bug this test is meant to catch.++use super::api::Api;+use base64::Engine;+use super::e2e_lock::SessionDirGuard;+use super::mls::{Decrypted, E2eePayload, MlsManager};+use super::{auth, device, mls, store, upload};+use reqwest::Method;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::path::PathBuf;++struct Side {+ name: String,+ dir: PathBuf,+ base: String,+ token: String,+ user_id: String,+ manager: MlsManager,+}++impl Side {+ /// Point every store lookup at this side's directory. The env var is read on+ /// each call, so switching sides is enough as long as nothing runs in+ /// parallel — and this test is deliberately sequential.+ fn activate(&self) {+ std::env::set_var(store::SESSION_DIR_ENV, &self.dir);+ }++ fn api(&self) -> Api {+ Api::with_token(self.base.clone(), self.token.clone()).expect("api")+ }+}++fn unique(prefix: &str) -> String {+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ format!("{}{}{}", prefix, std::process::id() % 10_000, nanos % 1_000_000)+}++fn workspace(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("omnidisc-e2ee-{}-{}", std::process::id(), tag));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).expect("workspace");+ dir+}++async fn register_side(base: &str, name_prefix: &str) -> Side {+ let dir = workspace(name_prefix);+ std::env::set_var(store::SESSION_DIR_ENV, &dir);+ let username = unique(name_prefix);+ let user = auth::register(base, &username, "correct horse battery", None, None)+ .await+ .expect("register");+ let token = store::load_token(base).expect("store").expect("token");+ let user_id = user["id"].as_str().expect("user id").to_string();+ Side {+ name: username,+ dir,+ base: base.to_string(),+ token,+ user_id,+ manager: MlsManager::default(),+ }+}++/// Register the device and publish key packages, the way a gateway connect does.+async fn bring_online(side: &Side) {+ side.activate();+ let identity = device::ensure_registered(&side.base).await.expect("device");+ assert!(!identity.device_id.is_empty());+ assert_eq!(identity.fingerprint().split('-').count(), 8);+ let api = side.api();+ let handle = side.manager.session(&side.base).await.expect("session");+ let mut session = handle.lock().await;+ mls::top_up_key_packages(&api, &mut session)+ .await+ .expect("key packages");+}++async fn drain(side: &Side) -> Vec<Decrypted> {+ side.activate();+ let api = side.api();+ let handle = side.manager.session(&side.base).await.expect("session");+ let mut session = handle.lock().await;+ let mut out = Vec::new();+ mls::drain_inbox(&api, &mut session, Some(&mut out))+ .await+ .expect("drain inbox");+ out+}++fn sha256_of(path: &std::path::Path) -> String {+ let bytes = std::fs::read(path).expect("read");+ Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect()+}++#[tokio::test]+#[ignore]+async fn two_devices_exchange_an_encrypted_message_and_an_encrypted_file() {+ let Ok(url) = std::env::var("OMNIDISC_TEST_URL") else {+ eprintln!("OMNIDISC_TEST_URL not set; skipping");+ return;+ };+ let _ = tracing_subscriber::fmt().with_max_level(tracing::Level::WARN).try_init();+ let base = super::normalize_instance_url(&url).expect("valid url");+ let _session_dir = SessionDirGuard::acquire();++ let alice = register_side(&base, "alicee").await;+ let bob = register_side(&base, "bobbbb").await;+ bring_online(&alice).await;+ bring_online(&bob).await;++ // Each side must have its own device identity, or the whole model collapses.+ alice.activate();+ let alice_device = device::identity(&base).expect("alice device");+ bob.activate();+ let bob_device = device::identity(&base).expect("bob device");+ assert_ne!(alice_device.device_id, bob_device.device_id);+ assert_ne!(alice_device.fingerprint(), bob_device.fingerprint());++ // The device roster is gated behind a shared context on the server, so it can+ // only be read once the DM exists — which is also the only moment the client+ // needs it.+ alice.activate();+ let dm: Value = alice+ .api()+ .send(+ Method::POST,+ "/api/users/@me/channels",+ &[],+ Some(json!({ "recipient_ids": [bob.user_id.clone()] })),+ )+ .await+ .expect("create dm");+ let dm_id = dm["id"].as_str().expect("dm id").to_string();++ // The public key the server hands out is the one this device really has.+ // Everything the client refuses in C2 hangs off this being true.+ let listed: Vec<Value> = alice+ .api()+ .send(+ Method::GET,+ &format!("/api/users/{}/devices", bob.user_id),+ &[],+ None,+ )+ .await+ .expect("bob devices");+ let seen = listed+ .iter()+ .find(|d| d["device_id"] == bob_device.device_id.as_str())+ .expect("bob's device is published");+ let published = base64::engine::general_purpose::STANDARD+ .decode(seen["ed25519_pub"].as_str().expect("ed25519_pub"))+ .expect("base64");+ assert_eq!(published, bob_device.public_key().to_vec());++ // ---------------------------------------------------------------- message+ let plaintext = "hello from the other side · 🔐";+ alice.activate();+ let sent = {+ let api = alice.api();+ let handle = alice.manager.session(&base).await.expect("session");+ let mut session = handle.lock().await;+ mls::send_encrypted(+ &api,+ &mut session,+ &dm_id,+ &[bob.user_id.clone()],+ E2eePayload {+ v: 1,+ content: plaintext.to_string(),+ reply_to: None,+ nonce: Some("n-1".into()),+ files: vec![],+ },+ )+ .await+ .expect("send encrypted")+ };++ // What the server stored, and therefore what it dispatches, is ciphertext.+ assert_eq!(sent["content"], "");+ let ciphertext = sent["e2ee"]["ciphertext"]+ .as_str()+ .expect("the message carries an e2ee payload")+ .to_string();+ assert!(!ciphertext.contains("hello from the other side"));+ let raw = serde_json::to_string(&sent).expect("json");+ assert!(!raw.contains("hello from the other side"), "plaintext leaked into the message: {raw}");++ let fetched: Vec<Value> = bob+ .api()+ .send(+ Method::GET,+ &format!("/api/channels/{dm_id}/messages"),+ &[("limit", "10".into())],+ None,+ )+ .await+ .expect("history");+ let stored = fetched+ .iter()+ .find(|m| m["id"] == sent["id"])+ .expect("the message is in the history");+ assert_eq!(stored["content"], "");+ assert_eq!(stored["e2ee"]["ciphertext"], ciphertext.as_str());++ let received = drain(&bob).await;+ let decrypted = received+ .iter()+ .find(|d| d.ciphertext == ciphertext)+ .expect("bob decrypted the message");+ assert_eq!(decrypted.payload.content, plaintext);+ assert_eq!(decrypted.channel_id, dm_id);+ assert_eq!(decrypted.sender_user_id, alice.user_id);+ assert_eq!(decrypted.sender_device_id, alice_device.device_id);++ // ------------------------------------------------------------------- file+ let scratch = workspace("payload");+ let source = scratch.join("five-mib.bin");+ let data: Vec<u8> = (0..(5 * 1024 * 1024)).map(|i| (i % 251) as u8).collect();+ std::fs::write(&source, &data).expect("write source");+ let source_sha = sha256_of(&source);++ alice.activate();+ let seen_progress = std::sync::Mutex::new(Vec::<u64>::new());+ let sink = |p: upload::UploadProgress| {+ if let Ok(mut v) = seen_progress.lock() {+ v.push(p.sent);+ }+ };+ let ready = upload::upload_file(&base, &dm_id, &source, true, &sink)+ .await+ .expect("upload");+ assert_eq!(ready.size, data.len() as u64);+ assert_eq!(ready.sha256, source_sha);+ assert!(+ seen_progress.lock().map(|v| v.len() > 1).unwrap_or(false),+ "the upload reported no progress"+ );+ let manifest = ready.manifest().expect("an encrypted upload has a manifest");++ let sent_file = {+ let api = alice.api();+ let handle = alice.manager.session(&base).await.expect("session");+ let mut session = handle.lock().await;+ mls::send_encrypted(+ &api,+ &mut session,+ &dm_id,+ &[bob.user_id.clone()],+ E2eePayload {+ v: 1,+ content: String::new(),+ reply_to: None,+ nonce: Some("n-2".into()),+ files: vec![manifest.clone()],+ },+ )+ .await+ .expect("send file message")+ };+ let file_ciphertext = sent_file["e2ee"]["ciphertext"].as_str().expect("ciphertext");++ let received = drain(&bob).await;+ let with_file = received+ .iter()+ .find(|d| d.ciphertext == file_ciphertext)+ .expect("bob decrypted the file message");+ let got = with_file.payload.files.first().expect("the manifest survived");+ assert_eq!(got.name, "five-mib.bin");+ assert_eq!(got.size, data.len() as u64);+ assert_eq!(got.sha256, source_sha);+ assert_eq!(got.attachment_id, manifest.attachment_id);+ assert_eq!(got.file_id, manifest.file_id);+ assert_ne!(got.file_id, got.attachment_id, "the AAD id must not be the server's id");++ // The blob the server holds is ciphertext, not the file.+ let http = super::api::http_client(std::time::Duration::from_secs(120)).expect("http");+ let downloaded_raw = http+ .get(&got.url)+ .send()+ .await+ .expect("fetch blob")+ .bytes()+ .await+ .expect("blob bytes");+ assert_ne!(downloaded_raw.len(), data.len(), "the stored blob is not padded ciphertext");+ assert_ne!(&downloaded_raw[..64], &data[..64], "the server stored the file in the clear");++ bob.activate();+ let into = workspace("bob-downloads");+ let saved = upload::fetch_attachment(+ &base,+ None,+ Some(got.clone()),+ &got.attachment_id,+ &got.name,+ Some(into.clone()),+ )+ .await+ .expect("download and decrypt");+ assert_eq!(sha256_of(std::path::Path::new(&saved.path)), source_sha);++ // A tampered manifest must not produce a file at all.+ let mut wrong = got.clone();+ wrong.sha256 = "0".repeat(64);+ assert!(+ upload::fetch_attachment(&base, None, Some(wrong), &got.attachment_id, &got.name, Some(into))+ .await+ .is_err(),+ "a mismatched hash was accepted"+ );++ // ---------------------------------------------------------------- cleanup+ for side in [&alice, &bob] {+ side.activate();+ let _ = auth::logout(&base).await;+ let _ = std::fs::remove_dir_all(&side.dir);+ }+ let _ = std::fs::remove_dir_all(&scratch);+ eprintln!("alice={} bob={} dm={}", alice.name, bob.name, dm_id);+}diff --git a/src-tauri/src/commands/omnidisc/gateway.rs b/src-tauri/src/commands/omnidisc/gateway.rsnew file mode 100644index 00000000..96946dc5--- /dev/null+++ b/src-tauri/src/commands/omnidisc/gateway.rs@@ -0,0 +1,547 @@+use super::api::{ERR_NO_SESSION, ERR_UNAUTHORIZED, ERR_UNREACHABLE};+use super::{normalize_instance_url, store};+use futures::{FutureExt, SinkExt, StreamExt};+use omnidisc_proto::gateway::{Opcode, HEARTBEAT_INTERVAL_MS};+use omnidisc_proto::PROTOCOL_VERSION;+use serde::Serialize;+use serde_json::{json, Value};+use std::collections::HashMap;+use std::sync::Arc;+use std::time::Duration;+use tauri::Emitter;+use tokio::sync::{mpsc, Mutex};+use tokio_tungstenite::tungstenite::Message;+use tokio_util::sync::CancellationToken;++pub const EVENT_DISPATCH: &str = "omnidisc://dispatch";+pub const EVENT_STATUS: &str = "omnidisc://status";+pub const ERR_NOT_CONNECTED: &str = "ERR_NOT_CONNECTED";+pub const ERR_PROTOCOL: &str = "ERR_PROTOCOL";++const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);+const HELLO_TIMEOUT: Duration = Duration::from_secs(10);+const BACKOFF_MIN: Duration = Duration::from_secs(1);+const BACKOFF_MAX: Duration = Duration::from_secs(30);++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum Status {+ Connecting,+ Ready,+ Reconnecting,+ Disconnected,+}++impl Status {+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Connecting => "connecting",+ Self::Ready => "ready",+ Self::Reconnecting => "reconnecting",+ Self::Disconnected => "disconnected",+ }+ }+}++pub trait GatewaySink: Send + Sync {+ fn dispatch(&self, url: &str, t: &str, d: Value);+ fn status(&self, url: &str, status: Status, error: Option<&str>);+}++struct TauriSink(tauri::AppHandle);++impl GatewaySink for TauriSink {+ fn dispatch(&self, url: &str, t: &str, d: Value) {+ super::voice::on_dispatch(&self.0, url, t, &d);+ super::mls::on_dispatch(&self.0, url, t, &d);+ let _ = self.0.emit(EVENT_DISPATCH, json!({ "url": url, "t": t, "d": d }));+ }++ fn status(&self, url: &str, status: Status, error: Option<&str>) {+ let _ = self+ .0+ .emit(EVENT_STATUS, json!({ "url": url, "status": status.as_str(), "error": error }));+ }+}++#[derive(Clone, Serialize)]+pub struct StatusSnapshot {+ pub url: String,+ pub status: Status,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++pub struct GatewayHandle {+ cancel: CancellationToken,+ outbound: mpsc::UnboundedSender<String>,+ shared: Arc<Shared>,+}++pub type Gateways = Arc<Mutex<HashMap<String, GatewayHandle>>>;++pub fn new_gateways() -> Gateways {+ Arc::new(Mutex::new(HashMap::new()))+}++struct Shared {+ url: String,+ sink: Arc<dyn GatewaySink>,+ status: std::sync::Mutex<(Status, Option<String>)>,+ finished: std::sync::atomic::AtomicBool,+}++impl Shared {+ fn set_status(&self, status: Status, error: Option<&str>) {+ if let Ok(mut s) = self.status.lock() {+ *s = (status, error.map(str::to_string));+ }+ self.sink.status(&self.url, status, error);+ }++ fn snapshot(&self) -> StatusSnapshot {+ let (status, error) = self+ .status+ .lock()+ .map(|s| s.clone())+ .unwrap_or((Status::Disconnected, None));+ StatusSnapshot { url: self.url.clone(), status, error }+ }++ fn is_finished(&self) -> bool {+ self.finished.load(std::sync::atomic::Ordering::Acquire)+ }+}++enum Outcome {+ Cancelled,+ Stop(String),+ Retry { resume: bool, error: Option<String> },+}++#[derive(Default)]+struct SessionState {+ session_id: Option<String>,+ seq: u64,+ attempt: u32,+}++pub fn ws_url(base: &str) -> String {+ let ws = if let Some(rest) = base.strip_prefix("https://") {+ format!("wss://{}", rest)+ } else if let Some(rest) = base.strip_prefix("http://") {+ format!("ws://{}", rest)+ } else {+ base.to_string()+ };+ format!("{}/gateway", ws)+}++pub fn backoff(attempt: u32) -> Duration {+ let exp = BACKOFF_MIN.saturating_mul(1u32 << attempt.min(5));+ let capped = exp.min(BACKOFF_MAX);+ let jitter_ms: u64 = rand::RngExt::random_range(&mut rand::rng(), 0..1000);+ capped + Duration::from_millis(jitter_ms)+}++fn frame_text(op: Opcode, d: Value) -> String {+ json!({ "op": op as u8, "d": d }).to_string()+}++pub fn identify_payload(token: &str) -> Value {+ json!({+ "token": token,+ "protocol_version": PROTOCOL_VERSION,+ "compress": "none",+ "properties": {+ "os": std::env::consts::OS,+ "client": "omniget",+ "version": env!("CARGO_PKG_VERSION"),+ }+ })+}++pub async fn run_gateway(+ base: String,+ token: String,+ outbound: mpsc::UnboundedReceiver<String>,+ cancel: CancellationToken,+ sink: Arc<dyn GatewaySink>,+) {+ let shared = Arc::new(Shared {+ url: base.clone(),+ sink,+ status: std::sync::Mutex::new((Status::Connecting, None)),+ finished: std::sync::atomic::AtomicBool::new(false),+ });+ run_with_shared(base, token, outbound, cancel, shared).await;+}++async fn run_with_shared(+ base: String,+ token: String,+ mut outbound: mpsc::UnboundedReceiver<String>,+ cancel: CancellationToken,+ shared: Arc<Shared>,+) {+ let mut state = SessionState::default();+ let url = ws_url(&base);+ loop {+ if cancel.is_cancelled() {+ shared.set_status(Status::Disconnected, None);+ break;+ }+ let status = if state.attempt == 0 && state.session_id.is_none() {+ Status::Connecting+ } else {+ Status::Reconnecting+ };+ shared.set_status(status, None);+ let outcome = connect_once(&url, &token, &mut outbound, &cancel, &shared, &mut state).await;+ match outcome {+ Outcome::Cancelled => {+ shared.set_status(Status::Disconnected, None);+ break;+ }+ Outcome::Stop(error) => {+ tracing::warn!("[omnidisc] gateway {} stopped: {}", base, error);+ shared.set_status(Status::Disconnected, Some(&error));+ break;+ }+ Outcome::Retry { resume, error } => {+ if !resume {+ state.session_id = None;+ state.seq = 0;+ }+ let delay = backoff(state.attempt);+ state.attempt = state.attempt.saturating_add(1);+ tracing::info!(+ "[omnidisc] gateway {} dropped ({}); retry in {:?}",+ base,+ error.as_deref().unwrap_or("closed"),+ delay+ );+ shared.set_status(Status::Reconnecting, error.as_deref());+ tokio::select! {+ _ = cancel.cancelled() => {+ shared.set_status(Status::Disconnected, None);+ break;+ }+ _ = tokio::time::sleep(delay) => {}+ }+ }+ }+ }+ shared.finished.store(true, std::sync::atomic::Ordering::Release);+}++async fn connect_once(+ url: &str,+ token: &str,+ outbound: &mut mpsc::UnboundedReceiver<String>,+ cancel: &CancellationToken,+ shared: &Shared,+ state: &mut SessionState,+) -> Outcome {+ let connect = tokio::time::timeout(CONNECT_TIMEOUT, tokio_tungstenite::connect_async(url));+ let ws = tokio::select! {+ _ = cancel.cancelled() => return Outcome::Cancelled,+ res = connect => match res {+ Ok(Ok((ws, _))) => ws,+ Ok(Err(e)) => {+ tracing::warn!("[omnidisc] gateway connect {} failed: {}", url, e);+ return Outcome::Retry { resume: true, error: Some(ERR_UNREACHABLE.to_string()) };+ }+ Err(_) => return Outcome::Retry { resume: true, error: Some(ERR_UNREACHABLE.to_string()) },+ },+ };+ let (mut tx, mut rx) = ws.split();++ let hello = tokio::select! {+ _ = cancel.cancelled() => return Outcome::Cancelled,+ msg = tokio::time::timeout(HELLO_TIMEOUT, rx.next()) => msg,+ };+ let heartbeat_ms = match hello {+ Ok(Some(Ok(Message::Text(t)))) => match serde_json::from_str::<Value>(&t) {+ Ok(v) if v.get("op").and_then(Value::as_u64) == Some(Opcode::Hello as u64) => v+ .get("d")+ .and_then(|d| d.get("heartbeat_interval"))+ .and_then(Value::as_u64)+ .unwrap_or(HEARTBEAT_INTERVAL_MS),+ _ => return Outcome::Retry { resume: true, error: Some(ERR_PROTOCOL.to_string()) },+ },+ _ => return Outcome::Retry { resume: true, error: Some(ERR_UNREACHABLE.to_string()) },+ };++ let first = match &state.session_id {+ Some(sid) if state.seq > 0 => frame_text(+ Opcode::Resume,+ json!({ "token": token, "session_id": sid, "seq": state.seq }),+ ),+ _ => frame_text(Opcode::Identify, identify_payload(token)),+ };+ if tx.send(Message::Text(first.into())).await.is_err() {+ return Outcome::Retry { resume: true, error: Some(ERR_UNREACHABLE.to_string()) };+ }++ let mut heartbeat = tokio::time::interval(Duration::from_millis(heartbeat_ms.max(1000)));+ heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ heartbeat.tick().await;+ let mut ack_pending = false;++ loop {+ tokio::select! {+ _ = cancel.cancelled() => {+ let _ = tx.send(Message::Close(None)).await;+ return Outcome::Cancelled;+ }+ out = outbound.recv() => {+ match out {+ Some(text) => {+ if tx.send(Message::Text(text.into())).await.is_err() {+ return Outcome::Retry { resume: true, error: None };+ }+ }+ None => return Outcome::Cancelled,+ }+ }+ _ = heartbeat.tick() => {+ if ack_pending {+ return Outcome::Retry { resume: true, error: Some("heartbeat timeout".to_string()) };+ }+ let beat = frame_text(Opcode::Heartbeat, json!(state.seq));+ if tx.send(Message::Text(beat.into())).await.is_err() {+ return Outcome::Retry { resume: true, error: None };+ }+ ack_pending = true;+ }+ msg = rx.next() => {+ let text = match msg {+ None | Some(Err(_)) => return Outcome::Retry { resume: true, error: None },+ Some(Ok(Message::Text(t))) => t.to_string(),+ Some(Ok(Message::Binary(b))) => String::from_utf8_lossy(&b).to_string(),+ Some(Ok(Message::Close(frame))) => {+ let code = frame.as_ref().map(|f| u16::from(f.code)).unwrap_or(1000);+ return close_outcome(code);+ }+ Some(Ok(Message::Ping(p))) => {+ let _ = tx.send(Message::Pong(p)).await;+ continue;+ }+ Some(Ok(_)) => continue,+ };+ let frame: Value = match serde_json::from_str(&text) {+ Ok(v) => v,+ Err(_) => continue,+ };+ let op = frame.get("op").and_then(Value::as_u64).unwrap_or(u64::MAX);+ if op == Opcode::Dispatch as u64 {+ if let Some(s) = frame.get("s").and_then(Value::as_u64) {+ state.seq = s;+ }+ let t = frame.get("t").and_then(Value::as_str).unwrap_or("").to_string();+ let d = frame.get("d").cloned().unwrap_or(Value::Null);+ let became_ready = t == "READY" || t == "RESUMED";+ if t == "READY" {+ state.session_id = d.get("session_id").and_then(Value::as_str).map(str::to_string);+ }+ shared.sink.dispatch(&shared.url, &t, d);+ if became_ready {+ state.attempt = 0;+ shared.set_status(Status::Ready, None);+ }+ } else if op == Opcode::HeartbeatAck as u64 {+ ack_pending = false;+ } else if op == Opcode::Heartbeat as u64 {+ let beat = frame_text(Opcode::Heartbeat, json!(state.seq));+ if tx.send(Message::Text(beat.into())).await.is_err() {+ return Outcome::Retry { resume: true, error: None };+ }+ } else if op == Opcode::Reconnect as u64 {+ return Outcome::Retry { resume: true, error: None };+ } else if op == Opcode::InvalidSession as u64 {+ let resumable = frame.get("d").and_then(Value::as_bool).unwrap_or(false);+ return Outcome::Retry { resume: resumable, error: None };+ } else if op == Opcode::GatewayError as u64 {+ let d = frame.get("d").cloned().unwrap_or(Value::Null);+ shared.sink.dispatch(&shared.url, "GATEWAY_ERROR", d);+ }+ }+ }+ }+}++fn close_outcome(code: u16) -> Outcome {+ match code {+ 4004 => Outcome::Stop(ERR_UNAUTHORIZED.to_string()),+ 4012 => Outcome::Stop(ERR_PROTOCOL.to_string()),+ 4001 | 4002 | 4003 | 4005 | 4007 | 4009 => {+ Outcome::Retry { resume: false, error: Some(format!("gateway closed {}", code)) }+ }+ 4000 => Outcome::Retry { resume: false, error: None },+ _ => Outcome::Retry { resume: true, error: None },+ }+}++pub async fn start(+ gateways: &Gateways,+ base: String,+ token: String,+ sink: Arc<dyn GatewaySink>,+) -> StatusSnapshot {+ let mut map = gateways.lock().await;+ if let Some(existing) = map.get(&base) {+ if !existing.shared.is_finished() {+ let snap = existing.shared.snapshot();+ existing.shared.sink.status(&base, snap.status, snap.error.as_deref());+ return snap;+ }+ map.remove(&base);+ }+ let (tx, rx) = mpsc::unbounded_channel::<String>();+ let cancel = CancellationToken::new();+ let shared = Arc::new(Shared {+ url: base.clone(),+ sink,+ status: std::sync::Mutex::new((Status::Connecting, None)),+ finished: std::sync::atomic::AtomicBool::new(false),+ });+ let handle = GatewayHandle { cancel: cancel.clone(), outbound: tx, shared: shared.clone() };+ map.insert(base.clone(), handle);+ let task_shared = shared.clone();+ let task_base = base.clone();+ tauri::async_runtime::spawn(async move {+ let fut = run_with_shared(task_base.clone(), token, rx, cancel, task_shared.clone());+ if std::panic::AssertUnwindSafe(fut).catch_unwind().await.is_err() {+ tracing::error!("[omnidisc] gateway task for {} panicked", task_base);+ task_shared.set_status(Status::Disconnected, Some(ERR_PROTOCOL));+ task_shared.finished.store(true, std::sync::atomic::Ordering::Release);+ }+ });+ shared.snapshot()+}++pub async fn stop(gateways: &Gateways, base: &str) {+ let removed = gateways.lock().await.remove(base);+ if let Some(handle) = removed {+ handle.cancel.cancel();+ }+}++pub async fn send(gateways: &Gateways, base: &str, op: u8, d: Value) -> Result<(), String> {+ let map = gateways.lock().await;+ let handle = map.get(base).ok_or_else(|| ERR_NOT_CONNECTED.to_string())?;+ if handle.shared.is_finished() || handle.shared.snapshot().status != Status::Ready {+ return Err(ERR_NOT_CONNECTED.to_string());+ }+ handle+ .outbound+ .send(json!({ "op": op, "d": d }).to_string())+ .map_err(|_| ERR_NOT_CONNECTED.to_string())+}++pub async fn is_ready(gateways: &Gateways, base: &str) -> bool {+ let map = gateways.lock().await;+ map.get(base)+ .map(|h| !h.shared.is_finished() && h.shared.snapshot().status == Status::Ready)+ .unwrap_or(false)+}++#[tauri::command]+pub async fn omnidisc_gateway_connect(+ app: tauri::AppHandle,+ state: tauri::State<'_, crate::AppState>,+ url: String,+) -> Result<StatusSnapshot, String> {+ let base = normalize_instance_url(&url)?;+ let token = store::load_token(&base)?.ok_or_else(|| ERR_NO_SESSION.to_string())?;+ Ok(start(&state.omnidisc_gateways, base, token, Arc::new(TauriSink(app))).await)+}++#[tauri::command]+pub async fn omnidisc_gateway_disconnect(+ state: tauri::State<'_, crate::AppState>,+ url: String,+) -> Result<(), String> {+ let base = normalize_instance_url(&url)?;+ stop(&state.omnidisc_gateways, &base).await;+ Ok(())+}++#[tauri::command]+pub async fn omnidisc_gateway_send(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ op: u8,+ d: Value,+) -> Result<(), String> {+ let base = normalize_instance_url(&url)?;+ send(&state.omnidisc_gateways, &base, op, d).await+}++#[tauri::command]+pub async fn omnidisc_gateway_status(+ state: tauri::State<'_, crate::AppState>,+ url: String,+) -> Result<StatusSnapshot, String> {+ let base = normalize_instance_url(&url)?;+ let map = state.omnidisc_gateways.lock().await;+ Ok(map+ .get(&base)+ .filter(|h| !h.shared.is_finished())+ .map(|h| h.shared.snapshot())+ .unwrap_or(StatusSnapshot { url: base, status: Status::Disconnected, error: None }))+}++#[tauri::command]+pub async fn omnidisc_typing(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ channel_id: String,+) -> Result<(), String> {+ let base = normalize_instance_url(&url)?;+ let via_gateway = send(+ &state.omnidisc_gateways,+ &base,+ Opcode::Typing as u8,+ json!({ "channel_id": channel_id }),+ )+ .await;+ match via_gateway {+ Ok(()) => Ok(()),+ Err(_) => super::api::typing_rest(&base, &channel_id).await,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ws_url_swaps_scheme_and_appends_gateway() {+ assert_eq!(ws_url("https://chat.example.org"), "wss://chat.example.org/gateway");+ assert_eq!(ws_url("http://localhost:8080"), "ws://localhost:8080/gateway");+ }++ #[test]+ fn backoff_grows_and_caps() {+ assert!(backoff(0) >= Duration::from_secs(1) && backoff(0) < Duration::from_secs(2));+ assert!(backoff(3) >= Duration::from_secs(8) && backoff(3) < Duration::from_secs(9));+ assert!(backoff(12) >= Duration::from_secs(30) && backoff(12) < Duration::from_secs(31));+ }++ #[test]+ fn close_codes_decide_resume() {+ assert!(matches!(close_outcome(4004), Outcome::Stop(e) if e == ERR_UNAUTHORIZED));+ assert!(matches!(close_outcome(4009), Outcome::Retry { resume: false, .. }));+ assert!(matches!(close_outcome(1006), Outcome::Retry { resume: true, .. }));+ }++ #[test]+ fn identify_has_required_fields() {+ let p = identify_payload("od1.x");+ assert_eq!(p["protocol_version"], PROTOCOL_VERSION);+ assert_eq!(p["compress"], "none");+ assert_eq!(p["properties"]["client"], "omniget");+ }+}diff --git a/src-tauri/src/commands/omnidisc/mls.rs b/src-tauri/src/commands/omnidisc/mls.rsnew file mode 100644index 00000000..78ee84a7--- /dev/null+++ b/src-tauri/src/commands/omnidisc/mls.rs@@ -0,0 +1,1271 @@+//! MLS wiring: key-package stock, group lifecycle, envelope inbox and the+//! encrypted message payload.+//!+//! Everything that touches key material stays here. What crosses to the frontend+//! is decrypted text and file metadata — never a key, never the group state.+//!+//! Two rules from spike S-05 shape the code and are easy to break by accident:+//! state is written **before** a commit or a message goes out (losing the epoch+//! secrets of a commit you already sent bricks the group for you), and a commit+//! is merged **only after** the server accepted it (409 means someone else won+//! the epoch, so we clear, catch up and retry).++use super::api::{Api, ERR_BAD_REQUEST, ERR_NOT_FOUND};+use super::device::{self, DeviceIdentity};+use super::store;+use base64::Engine;+use omnidisc_mls::{ClaimedDevice, CommitOutput, DeviceRef, Incoming, MlsClient, CIPHERSUITE_ID};+use omnidisc_proto::channel::{Channel, ChannelType};+use omnidisc_proto::gateway::{MlsEnvelope, MlsEnvelopeKind};+use omnidisc_proto::rest::{+ ClaimedKeyPackages, Device, KeyPackageCount, MlsCommitResponse, MlsInboxResponse,+};+use reqwest::Method;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::Arc;+use tokio::sync::Mutex;++pub const EVENT_DECRYPTED: &str = "omnidisc://decrypted";+pub const ERR_NO_GROUP_YET: &str = "ERR_E2EE_NOT_READY";+pub const ERR_E2EE: &str = "ERR_E2EE";+/// The server said something about identity that the client could not confirm+/// on its own. It is never retried and never downgraded: MLS exists precisely+/// so a compromised server cannot get past this.+pub const ERR_E2EE_UNTRUSTED: &str = "ERR_E2EE_UNTRUSTED";++const KEY_PACKAGE_FLOOR: u64 = 20;+const COMMIT_RETRIES: u32 = 3;+const INBOX_PAGE: u32 = 100;+const HISTORY_CACHE_MAX: usize = 4_000;+const STATE_KEY_ACCOUNT: &str = "mls-state-key";+const PAYLOAD_VERSION: u32 = 1;+/// How stale a cached device roster may be before an unrecognised sender is+/// worth another request.+const ROSTER_REFRESH: std::time::Duration = std::time::Duration::from_secs(60);++/// What a decrypted OmniDisc message carries. The `files` entries hold the key+/// material of every attachment, which is exactly why the whole struct is+/// re-serialised without them before anything reaches the webview.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct E2eePayload {+ #[serde(default = "one")]+ pub v: u32,+ #[serde(default)]+ pub content: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reply_to: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nonce: Option<String>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub files: Vec<FileManifest>,+}++fn one() -> u32 {+ PAYLOAD_VERSION+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FileManifest {+ pub attachment_id: String,+ /// Identifier bound into the chunk AAD at encryption time. It is NOT the+ /// attachment id: the file is encrypted before the server assigns one, and+ /// binding the AAD to something the server picks would let the server+ /// influence the ciphertext's domain separation.+ #[serde(default)]+ pub file_id: String,+ /// Signed media URL captured at upload time. The server never links an+ /// attachment to an MLS message (it cannot read the message), so this is the+ /// only handle the receiver has — and it carries the server's 24 h signature+ /// TTL with it.+ #[serde(default)]+ pub url: String,+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mime: Option<String>,+ pub size: u64,+ pub sha256: String,+ pub key: String,+ pub nonce: String,+}++impl E2eePayload {+ /// The view the frontend gets: same message, no key material.+ pub fn public_view(&self) -> Value {+ let files: Vec<Value> = self+ .files+ .iter()+ .map(|f| {+ json!({+ "attachment_id": f.attachment_id,+ "name": f.name,+ "mime": f.mime,+ "size": f.size,+ })+ })+ .collect();+ json!({+ "content": self.content,+ "reply_to": self.reply_to,+ "nonce": self.nonce,+ "files": files,+ })+ }+}++pub struct MlsManager {+ sessions: Mutex<HashMap<String, Arc<Mutex<Session>>>>,+}++impl Default for MlsManager {+ fn default() -> Self {+ Self { sessions: Mutex::new(HashMap::new()) }+ }+}++impl MlsManager {+ pub async fn session(&self, base: &str) -> Result<Arc<Mutex<Session>>, String> {+ if let Some(existing) = self.sessions.lock().await.get(base) {+ return Ok(existing.clone());+ }+ let session = Session::open(base).await?;+ let handle = Arc::new(Mutex::new(session));+ self.sessions+ .lock()+ .await+ .insert(base.to_string(), handle.clone());+ Ok(handle)+ }++ pub async fn forget(&self, base: &str) {+ self.sessions.lock().await.remove(base);+ }+}++/// The voice room key for a channel on one instance. `establish` is the list of+/// people to build the group with when the channel is encrypted but nobody has+/// sent a message in it yet; without it we only reuse a group that exists.+/// `None` at any step means the call runs in the clear and the UI says so.+pub async fn voice_key_for(+ manager: &MlsManager,+ base: &str,+ channel_id: &str,+ establish: Option<&[String]>,+) -> Option<(u64, [u8; 32])> {+ let handle = manager.session(base).await.ok()?;+ let mut session = handle.lock().await;+ if !session.client.has_group(&group_id_for(channel_id)) {+ let recipients = establish?;+ let api = Api::authed(base).ok()?;+ if let Err(e) = ensure_group(&api, &mut session, channel_id, recipients).await {+ tracing::warn!("[omnidisc] no MLS group for the call in {}: {}", channel_id, e);+ return None;+ }+ }+ session.voice_key(channel_id)+}++pub struct Session {+ base: String,+ identity: DeviceIdentity,+ state_key: [u8; 32],+ client: MlsClient,+ /// Decrypted payloads keyed by the SHA-256 of their ciphertext. MLS ratchets+ /// forward, so a message can only be decrypted once — without this, scrolling+ /// back through history would show empty bubbles forever.+ history: HashMap<String, String>,+ history_order: Vec<String>,+ last_envelope_id: Option<String>,+ /// Devices each user has published, as fetched from the server, with the+ /// moment they were fetched. Sender attribution is checked against this and+ /// never against the identity string inside the MLS credential, which its+ /// owner writes freely.+ rosters: HashMap<String, (std::time::Instant, Vec<DeviceRef>)>,+}++fn state_path(base: &str) -> Result<PathBuf, String> {+ let digest = Sha256::digest(base.as_bytes());+ let name = digest[..8].iter().map(|b| format!("{b:02x}")).collect::<String>();+ Ok(store::base_dir()?.join("mls").join(format!("{name}.state")))+}++fn history_path(base: &str) -> Result<PathBuf, String> {+ let path = state_path(base)?;+ Ok(path.with_extension("history"))+}++fn e2ee(e: impl std::fmt::Display) -> String {+ tracing::warn!("[omnidisc] e2ee: {}", e);+ ERR_E2EE.to_string()+}++/// A refusal is not a failure to be retried: it means the server said something+/// about identity we could not confirm, and the user has to be told that rather+/// than shown a generic "encryption hiccup".+fn e2ee_mls(e: omnidisc_mls::MlsError) -> String {+ match e {+ omnidisc_mls::MlsError::Untrusted(_) => {+ tracing::warn!("[omnidisc] refused an untrusted identity: {}", e);+ ERR_E2EE_UNTRUSTED.to_string()+ }+ other => e2ee(other),+ }+}++/// One MLS group per private channel, named after the channel so both sides+/// derive the same id without a lookup (S-05 gotcha 10).+pub fn group_id_for(channel_id: &str) -> String {+ format!("od-{}", channel_id)+}++pub fn channel_of_group(group_id: &str) -> Option<String> {+ group_id.strip_prefix("od-").map(str::to_string)+}++fn write_atomic(path: &PathBuf, bytes: &[u8]) -> Result<(), String> {+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)+ .map_err(|e| format!("OmniDisc: could not create the MLS state dir: {}", e))?;+ }+ let tmp = path.with_extension("tmp");+ store::write_private(&tmp, bytes)?;+ std::fs::rename(&tmp, path)+ .map_err(|e| format!("OmniDisc: could not replace the MLS state: {}", e))+}++impl Session {+ async fn open(base: &str) -> Result<Self, String> {+ let identity = device::identity(base)?;+ let account = store::secret_account(base, STATE_KEY_ACCOUNT);+ let state_key = match store::load_secret(&account)? {+ Some(encoded) => decode_key(&encoded)?,+ None => {+ let key = omnidisc_mls::new_state_key();+ store::save_secret(+ &account,+ &base64::engine::general_purpose::STANDARD.encode(key),+ )?;+ key+ }+ };+ let user_id = current_user_id(base).await?;+ let path = state_path(base)?;+ let client = match std::fs::read(&path) {+ Ok(blob) => match omnidisc_mls::decrypt_state(&state_key, &blob)+ .and_then(|plain| MlsClient::restore(&user_id, &identity.device_id, &identity.seed, &plain))+ {+ Ok(client) => client,+ Err(err) => {+ // A state we cannot read is a state we cannot use. Starting+ // over loses the history, which is the honest outcome — the+ // alternative is a client that silently fails every send.+ tracing::warn!("[omnidisc] MLS state unusable, starting fresh: {}", err);+ MlsClient::new(&user_id, &identity.device_id, &identity.seed).map_err(e2ee)?+ }+ },+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ MlsClient::new(&user_id, &identity.device_id, &identity.seed).map_err(e2ee)?+ }+ Err(e) => return Err(format!("OmniDisc: could not read the MLS state: {}", e)),+ };+ let mut session = Self {+ base: base.to_string(),+ identity,+ state_key,+ client,+ history: HashMap::new(),+ history_order: Vec::new(),+ last_envelope_id: None,+ rosters: HashMap::new(),+ };+ session.load_history();+ Ok(session)+ }++ pub fn device_id(&self) -> &str {+ &self.identity.device_id+ }++ fn save(&self) -> Result<(), String> {+ let plain = self.client.export_state();+ let blob = omnidisc_mls::encrypt_state(&self.state_key, &plain).map_err(e2ee)?;+ write_atomic(&state_path(&self.base)?, &blob)+ }++ fn load_history(&mut self) {+ let Ok(path) = history_path(&self.base) else { return };+ let Ok(blob) = std::fs::read(&path) else { return };+ let Ok(plain) = omnidisc_mls::decrypt_state(&self.state_key, &blob) else {+ tracing::warn!("[omnidisc] the decrypted-message cache is unreadable; dropping it");+ return;+ };+ let Ok(entries) = serde_json::from_slice::<Vec<(String, String)>>(&plain) else { return };+ for (hash, payload) in entries {+ self.history_order.push(hash.clone());+ self.history.insert(hash, payload);+ }+ }++ fn save_history(&self) {+ let Ok(path) = history_path(&self.base) else { return };+ let entries: Vec<(&String, &String)> = self+ .history_order+ .iter()+ .filter_map(|h| self.history.get_key_value(h))+ .collect();+ let Ok(plain) = serde_json::to_vec(&entries) else { return };+ let Ok(blob) = omnidisc_mls::encrypt_state(&self.state_key, &plain) else { return };+ if let Err(e) = write_atomic(&path, &blob) {+ tracing::warn!("[omnidisc] could not persist the decrypted-message cache: {}", e);+ }+ }++ /// The cache holds the full payload, manifests included — a download that+ /// happens days later needs the file key, and this file is encrypted at rest+ /// with the same keyring-held key as the group state.+ pub fn remember(&mut self, ciphertext_b64: &str, payload: &E2eePayload) {+ let Ok(encoded) = serde_json::to_string(payload) else { return };+ let hash = hash_ciphertext(ciphertext_b64);+ if self.history.insert(hash.clone(), encoded).is_none() {+ self.history_order.push(hash);+ }+ while self.history_order.len() > HISTORY_CACHE_MAX {+ let oldest = self.history_order.remove(0);+ self.history.remove(&oldest);+ }+ }++ fn payload_of(&self, ciphertext_b64: &str) -> Option<E2eePayload> {+ let raw = self.history.get(&hash_ciphertext(ciphertext_b64))?;+ serde_json::from_str(raw).ok()+ }++ /// The voice room key for a channel, or `None` when this channel has no MLS+ /// group. `None` is not an error: guild channels without the E2EE flag are+ /// deliberately not encrypted, and the UI has to say which one is in effect.+ ///+ /// The exporter context is the channel id this client asked to call in, not+ /// the room name the server answered with: a hostile server that hands each+ /// participant a different room name would otherwise split the call into+ /// people who cannot hear each other.+ pub fn voice_key(&self, channel_id: &str) -> Option<(u64, [u8; 32])> {+ voice_key_of(&self.client, channel_id)+ }++ pub fn recall(&self, ciphertext_b64: &str) -> Option<Value> {+ self.payload_of(ciphertext_b64).map(|p| p.public_view())+ }++ pub fn manifest_for(&self, ciphertext_b64: &str, attachment_id: &str) -> Option<FileManifest> {+ self.payload_of(ciphertext_b64)?+ .files+ .into_iter()+ .find(|f| f.attachment_id == attachment_id)+ }+}++/// The voice key of a channel, derived from the channel id and nothing the+/// server said. Free-standing so the binding itself can be tested without a+/// session, a keyring and an instance behind it.+fn voice_key_of(client: &MlsClient, channel_id: &str) -> Option<(u64, [u8; 32])> {+ let group_id = group_id_for(channel_id);+ if !client.has_group(&group_id) {+ return None;+ }+ let epoch = client.epoch(&group_id)?;+ match client.voice_key(&group_id, channel_id.as_bytes()) {+ Ok(key) => Some((epoch, key)),+ Err(e) => {+ tracing::warn!("[omnidisc] could not derive the voice key for {}: {}", group_id, e);+ None+ }+ }+}++fn hash_ciphertext(ciphertext_b64: &str) -> String {+ let digest = Sha256::digest(ciphertext_b64.as_bytes());+ digest.iter().map(|b| format!("{b:02x}")).collect()+}++fn decode_key(encoded: &str) -> Result<[u8; 32], String> {+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(encoded.trim())+ .map_err(|_| "OmniDisc: the stored MLS key is unreadable".to_string())?;+ if bytes.len() != 32 {+ return Err("OmniDisc: the stored MLS key has the wrong size".to_string());+ }+ let mut key = [0u8; 32];+ key.copy_from_slice(&bytes);+ Ok(key)+}++async fn current_user_id(base: &str) -> Result<String, String> {+ let api = Api::authed(base)?;+ let me: Value = api.send(Method::GET, "/api/users/@me", &[], None).await?;+ me.get("id")+ .and_then(Value::as_str)+ .map(str::to_string)+ .ok_or_else(|| ERR_E2EE.to_string())+}++// ---------------------------------------------------------------------------+// Key packages+// ---------------------------------------------------------------------------++pub async fn top_up_key_packages(api: &Api, session: &mut Session) -> Result<(), String> {+ let count: KeyPackageCount = api+ .send(Method::GET, "/api/mls/key-packages/count", &[], None)+ .await?;+ if count.unclaimed >= KEY_PACKAGE_FLOOR && count.last_resort {+ return Ok(());+ }+ let missing = KEY_PACKAGE_FLOOR.saturating_sub(count.unclaimed) as usize;+ let blobs = session+ .client+ .key_packages(missing, !count.last_resort)+ .map_err(e2ee)?;+ if blobs.is_empty() {+ return Ok(());+ }+ session.save()?;+ let last_resort_index = if count.last_resort { usize::MAX } else { blobs.len() - 1 };+ let packages: Vec<Value> = blobs+ .iter()+ .enumerate()+ .map(|(i, blob)| {+ json!({+ "ciphersuite": CIPHERSUITE_ID,+ "blob": base64::engine::general_purpose::STANDARD.encode(blob),+ "last_resort": i == last_resort_index,+ })+ })+ .collect();+ let _: KeyPackageCount = api+ .send(+ Method::PUT,+ "/api/mls/key-packages",+ &[],+ Some(json!({ "key_packages": packages })),+ )+ .await?;+ tracing::info!("[omnidisc] published {} key packages", packages.len());+ Ok(())+}++// ---------------------------------------------------------------------------+// Groups+// ---------------------------------------------------------------------------++/// The devices a user has published, as the server reports them. This is the+/// only handle the client has on "which key really belongs to that device", so+/// every key package and every sender is checked against it.+async fn device_roster(api: &Api, user_id: &str) -> Result<Vec<DeviceRef>, String> {+ let user_id = super::api::path_id(user_id)?;+ let devices: Vec<Device> = api+ .send(Method::GET, &format!("/api/users/{}/devices", user_id), &[], None)+ .await?;+ Ok(devices+ .into_iter()+ .filter(|d| d.revoked_at.is_none())+ .filter_map(|d| {+ let key = base64::engine::general_purpose::STANDARD+ .decode(&d.ed25519_pub)+ .ok()+ .filter(|b| b.len() == 32)?;+ Some(DeviceRef::new(d.user_id.to_string(), d.device_id, key))+ })+ .collect())+}++/// Claim one key package per device of each user, and bind each one to the+/// device it must belong to. A server that substitutes a package of its own+/// fails the binding inside `add_members`, and the whole commit is dropped:+/// adding an unverifiable device would hand it every later message.+async fn claim_devices(api: &Api, user_ids: &[String]) -> Result<Vec<ClaimedDevice>, String> {+ let mut claimed = Vec::new();+ for user_id in user_ids {+ let packages: ClaimedKeyPackages = match api+ .send(+ Method::GET,+ &format!("/api/mls/key-packages/{}", super::api::path_id(user_id)?),+ &[],+ None,+ )+ .await+ {+ Ok(p) => p,+ Err(e) if e.starts_with(ERR_NOT_FOUND) => continue,+ Err(e) => return Err(e),+ };+ if packages.key_packages.is_empty() {+ continue;+ }+ let roster = device_roster(api, user_id).await?;+ for kp in packages.key_packages {+ let Ok(blob) = base64::engine::general_purpose::STANDARD.decode(&kp.blob) else {+ tracing::warn!("[omnidisc] a claimed key package was not valid base64");+ return Err(ERR_E2EE_UNTRUSTED.to_string());+ };+ let Some(device) = roster.iter().find(|d| d.device_id == kp.device_id).cloned() else {+ tracing::warn!(+ "[omnidisc] a key package was claimed for {}, a device {} never published",+ kp.device_id,+ user_id+ );+ return Err(ERR_E2EE_UNTRUSTED.to_string());+ };+ claimed.push(ClaimedDevice { device, key_package: blob });+ }+ }+ Ok(claimed)+}++/// Post a staged commit, handling the server's one-commit-per-epoch rule. On+/// 409 someone else's commit landed first: drop ours, catch up on the inbox and+/// stage it again against the new epoch.+async fn commit_with_retry(+ api: &Api,+ session: &mut Session,+ group_id: &str,+ mut output: CommitOutput,+ added: &[String],+ removed: &[String],+ key_packages: &[ClaimedDevice],+) -> Result<u64, String> {+ for attempt in 0..COMMIT_RETRIES {+ session.save()?;+ let mut body = json!({+ "epoch": output.epoch,+ "commit": base64::engine::general_purpose::STANDARD.encode(&output.commit),+ "added_devices": added,+ "removed_devices": removed,+ });+ if let Some(welcome) = &output.welcome {+ body["welcome"] =+ Value::String(base64::engine::general_purpose::STANDARD.encode(welcome));+ }+ let result: Result<MlsCommitResponse, String> = api+ .send(+ Method::POST,+ &format!("/api/mls/groups/{}/commit", group_id),+ &[],+ Some(body),+ )+ .await;+ match result {+ Ok(response) => {+ session.client.merge_pending(group_id).map_err(e2ee)?;+ session.save()?;+ return Ok(response.epoch);+ }+ Err(err) if err.contains("epoch_conflict") && attempt + 1 < COMMIT_RETRIES => {+ tracing::info!(+ "[omnidisc] commit for {} lost the epoch race; catching up",+ group_id+ );+ session.client.clear_pending(group_id).map_err(e2ee)?;+ session.save()?;+ drain_inbox(api, session, None).await?;+ if !removed.is_empty() {+ output = session.client.remove_devices(group_id, removed).map_err(e2ee)?;+ } else if !key_packages.is_empty() {+ output = session.client.add_members(group_id, key_packages).map_err(e2ee_mls)?;+ } else {+ return Err(format!("{}:epoch_conflict", ERR_BAD_REQUEST));+ }+ }+ Err(err) => {+ let _ = session.client.clear_pending(group_id);+ session.save()?;+ return Err(err);+ }+ }+ }+ Err(format!("{}:epoch_conflict", ERR_BAD_REQUEST))+}++/// Make sure this channel has a group we are a member of, creating it and adding+/// every recipient's devices when it does not exist yet.+pub async fn ensure_group(+ api: &Api,+ session: &mut Session,+ channel_id: &str,+ recipient_user_ids: &[String],+) -> Result<String, String> {+ let group_id = group_id_for(channel_id);+ if session.client.has_group(&group_id) {+ return Ok(group_id);+ }+ // The server may already know a group we have not been welcomed into yet;+ // draining the inbox is what turns that Welcome into a usable group.+ drain_inbox(api, session, None).await?;+ if session.client.has_group(&group_id) {+ return Ok(group_id);+ }+ let existing: Result<Value, String> = api+ .send(+ Method::GET,+ &format!("/api/mls/groups/{}", group_id),+ &[],+ None,+ )+ .await;+ match existing {+ Ok(_) => {+ return Err(ERR_NO_GROUP_YET.to_string());+ }+ Err(e) if e.starts_with(ERR_NOT_FOUND) => {}+ Err(e) => return Err(e),+ }++ session.client.create_group(&group_id).map_err(e2ee)?;+ session.save()?;+ let created: Result<Value, String> = api+ .send(+ Method::POST,+ "/api/mls/groups",+ &[],+ Some(json!({ "channel_id": channel_id, "group_id": group_id })),+ )+ .await;+ if let Err(err) = created {+ session.client.drop_group(&group_id).map_err(e2ee)?;+ session.save()?;+ if err.contains("group_exists") {+ return Err(ERR_NO_GROUP_YET.to_string());+ }+ return Err(err);+ }++ let claimed = claim_devices(api, recipient_user_ids).await?;+ if claimed.is_empty() {+ // The group is registered and usable; the other side simply has no+ // device online yet, and will be added by the next commit.+ return Ok(group_id);+ }+ let devices: Vec<String> = claimed.iter().map(|c| c.device.device_id.clone()).collect();+ let output = session.client.add_members(&group_id, &claimed).map_err(e2ee_mls)?;+ commit_with_retry(api, session, &group_id, output, &devices, &[], &claimed).await?;+ Ok(group_id)+}++/// Add devices of the given users that are not in the group yet — how a friend's+/// new device (or our own second device) starts receiving messages.+pub async fn sync_members(+ api: &Api,+ session: &mut Session,+ group_id: &str,+ user_ids: &[String],+) -> Result<bool, String> {+ if !session.client.has_group(group_id) {+ return Ok(false);+ }+ let known = session.client.member_device_ids(group_id);+ let claimed: Vec<ClaimedDevice> = claim_devices(api, user_ids)+ .await?+ .into_iter()+ .filter(|c| !known.contains(&c.device.device_id))+ .collect();+ if claimed.is_empty() {+ return Ok(false);+ }+ let devices: Vec<String> = claimed.iter().map(|c| c.device.device_id.clone()).collect();+ let output = session.client.add_members(group_id, &claimed).map_err(e2ee_mls)?;+ commit_with_retry(api, session, group_id, output, &devices, &[], &claimed).await?;+ Ok(true)+}++pub async fn remove_device_everywhere(+ api: &Api,+ session: &mut Session,+ device_id: &str,+) -> Result<(), String> {+ if device_id == session.identity.device_id {+ return Ok(());+ }+ let groups = session.client.group_ids();+ let removed = vec![device_id.to_string()];+ for group_id in groups {+ if !session.client.member_device_ids(&group_id).iter().any(|d| d == device_id) {+ continue;+ }+ let output = match session.client.remove_devices(&group_id, &removed) {+ Ok(o) => o,+ Err(e) => {+ tracing::warn!("[omnidisc] could not stage a removal in {}: {}", group_id, e);+ continue;+ }+ };+ if let Err(e) =+ commit_with_retry(api, session, &group_id, output, &[], &removed, &[]).await+ {+ tracing::warn!("[omnidisc] could not remove {} from {}: {}", device_id, group_id, e);+ }+ }+ Ok(())+}++// ---------------------------------------------------------------------------+// Inbox+// ---------------------------------------------------------------------------++pub struct Decrypted {+ pub channel_id: String,+ pub group_id: String,+ pub ciphertext: String,+ pub sender_user_id: String,+ pub sender_device_id: String,+ /// Whether the sending leaf's signature key is one the claimed device+ /// actually published. False means "someone in this group signed as them",+ /// which the UI has to say out loud instead of putting a name on it.+ pub sender_verified: bool,+ pub payload: E2eePayload,+}++/// Drain every envelope addressed to this device, strictly in id order. Welcome+/// and Commit come before the Application messages of their epoch, so a single+/// ordered pass is enough — out-of-order processing is what produces+/// `WrongEpoch` and a group that never recovers.+pub async fn drain_inbox(+ api: &Api,+ session: &mut Session,+ mut sink: Option<&mut Vec<Decrypted>>,+) -> Result<(), String> {+ loop {+ let mut query: Vec<(&str, String)> = vec![("limit", INBOX_PAGE.to_string())];+ if let Some(after) = &session.last_envelope_id {+ query.push(("after", after.clone()));+ }+ let page: MlsInboxResponse = api.send(Method::GET, "/api/mls/inbox", &query, None).await?;+ if page.envelopes.is_empty() {+ return Ok(());+ }+ let mut envelopes = page.envelopes;+ envelopes.sort_by_key(|e| e.id.0);+ let mut acks: Vec<String> = Vec::with_capacity(envelopes.len());+ for envelope in &envelopes {+ acks.push(envelope.id.to_string());+ session.last_envelope_id = Some(envelope.id.to_string());+ match apply_envelope(api, session, envelope).await {+ Ok(Some(decrypted)) => {+ if let Some(sink) = sink.as_deref_mut() {+ sink.push(decrypted);+ }+ }+ Ok(None) => {}+ Err(err) => {+ // One unreadable envelope must not stall the whole mailbox:+ // it is acked and reported, and the rest still lands.+ tracing::warn!(+ "[omnidisc] envelope {} ({}) could not be processed: {}",+ envelope.id,+ envelope.kind.as_str(),+ err+ );+ }+ }+ }+ session.save()?;+ session.save_history();+ if !acks.is_empty() {+ if let Err(e) = api+ .send_empty(+ Method::POST,+ "/api/mls/inbox/ack",+ Some(json!({ "envelope_ids": acks })),+ )+ .await+ {+ tracing::warn!("[omnidisc] could not ack envelopes: {}", e);+ }+ }+ if !page.has_more {+ return Ok(());+ }+ }+}++/// Who is allowed to have welcomed us into `channel_id`'s group.+///+/// The server picks the group id and the Welcome, so on its own a Welcome+/// proves nothing: it has to name a channel we are really a recipient of, and+/// it has to come from a device one of that channel's recipients published.+/// Anything else is a server trying to seat itself in an encrypted room.+async fn welcome_senders(+ api: &Api,+ session: &mut Session,+ channel_id: &str,+) -> Result<Vec<DeviceRef>, String> {+ let channel: Channel = api+ .send(+ Method::GET,+ &format!("/api/channels/{}", super::api::path_id(channel_id)?),+ &[],+ None,+ )+ .await?;+ if !matches!(channel.kind, ChannelType::Dm | ChannelType::GroupDm) {+ return Err(format!("{} is not an encrypted channel", channel_id));+ }+ let me = session.client.user_id().to_string();+ let recipients: Vec<String> = channel.recipient_ids.iter().map(|r| r.to_string()).collect();+ if !recipients.iter().any(|r| *r == me) {+ return Err(format!("this account is not a recipient of {}", channel_id));+ }+ let mut allowed = Vec::new();+ for user_id in &recipients {+ let roster = device_roster(api, user_id).await?;+ session+ .rosters+ .insert(user_id.clone(), (std::time::Instant::now(), roster.clone()));+ allowed.extend(roster);+ }+ Ok(allowed)+}++/// True when the sending leaf's key is one the claimed device published. A miss+/// refetches the roster, because a peer's new device is a normal event and a+/// stale cache must not be reported as an impersonation — but no more often than+/// `ROSTER_REFRESH`, so a stream of forged senders cannot turn into one request+/// per message.+async fn sender_is_known(+ api: &Api,+ session: &mut Session,+ user_id: &str,+ device_id: &str,+ key: &[u8],+) -> bool {+ let matches = |roster: &Vec<DeviceRef>| {+ roster+ .iter()+ .any(|d| d.user_id == user_id && d.device_id == device_id && d.signature_key == key)+ };+ if let Some((fetched, roster)) = session.rosters.get(user_id) {+ if matches(roster) {+ return true;+ }+ if fetched.elapsed() < ROSTER_REFRESH {+ return false;+ }+ }+ match device_roster(api, user_id).await {+ Ok(roster) => {+ let ok = matches(&roster);+ session+ .rosters+ .insert(user_id.to_string(), (std::time::Instant::now(), roster));+ ok+ }+ Err(e) => {+ tracing::warn!("[omnidisc] could not fetch the devices of {}: {}", user_id, e);+ false+ }+ }+}++async fn apply_envelope(+ api: &Api,+ session: &mut Session,+ envelope: &MlsEnvelope,+) -> Result<Option<Decrypted>, String> {+ let blob = base64::engine::general_purpose::STANDARD+ .decode(&envelope.payload)+ .map_err(|_| "the payload was not valid base64".to_string())?;+ match envelope.kind {+ MlsEnvelopeKind::Welcome => {+ if session.client.has_group(&envelope.group_id) {+ return Err(format!(+ "a Welcome for {}, a group this device is already in",+ envelope.group_id+ ));+ }+ let channel_id = channel_of_group(&envelope.group_id)+ .ok_or_else(|| "unrecognised group id".to_string())?;+ let allowed = welcome_senders(api, session, &channel_id).await?;+ let group_id = session+ .client+ .join_welcome(&blob, &envelope.group_id, &allowed)+ .map_err(|e| e.to_string())?;+ tracing::info!("[omnidisc] joined MLS group {}", group_id);+ Ok(None)+ }+ MlsEnvelopeKind::Commit | MlsEnvelopeKind::Proposal | MlsEnvelopeKind::Application => {+ if !session.client.has_group(&envelope.group_id) {+ return Err("no local group for this envelope".to_string());+ }+ match session+ .client+ .process(&envelope.group_id, &blob)+ .map_err(|e| e.to_string())?+ {+ Incoming::Application { user_id, device_id, signature_key, plaintext } => {+ let payload: E2eePayload = serde_json::from_slice(&plaintext)+ .map_err(|e| format!("the plaintext was not an OmniDisc payload: {e}"))?;+ session.remember(&envelope.payload, &payload);+ let channel_id = channel_of_group(&envelope.group_id)+ .ok_or_else(|| "unrecognised group id".to_string())?;+ let sender_verified =+ sender_is_known(api, session, &user_id, &device_id, &signature_key).await;+ if !sender_verified {+ tracing::warn!(+ "[omnidisc] {} in {} signs as {}:{} with a key that device never published",+ envelope.id,+ envelope.group_id,+ user_id,+ device_id+ );+ }+ Ok(Some(Decrypted {+ channel_id,+ group_id: envelope.group_id.clone(),+ ciphertext: envelope.payload.clone(),+ sender_user_id: user_id,+ sender_device_id: device_id,+ sender_verified,+ payload,+ }))+ }+ Incoming::Commit { removed_me, .. } => {+ if removed_me {+ tracing::info!(+ "[omnidisc] this device was removed from {}",+ envelope.group_id+ );+ session.client.drop_group(&envelope.group_id).map_err(|e| e.to_string())?;+ }+ Ok(None)+ }+ Incoming::Proposal => Ok(None),+ }+ }+ }+}++// ---------------------------------------------------------------------------+// Sending+// ---------------------------------------------------------------------------++pub async fn send_encrypted(+ api: &Api,+ session: &mut Session,+ channel_id: &str,+ recipient_user_ids: &[String],+ payload: E2eePayload,+) -> Result<Value, String> {+ let group_id = ensure_group(api, session, channel_id, recipient_user_ids).await?;+ let _ = sync_members(api, session, &group_id, recipient_user_ids).await;+ let plaintext = serde_json::to_vec(&payload).map_err(e2ee)?;+ let (ciphertext, epoch) = session.client.encrypt(&group_id, &plaintext).map_err(e2ee)?;+ // The ratchet already moved; if the process died here the message would be+ // undecryptable for us, so the state goes to disk before the request.+ session.save()?;+ let encoded = base64::engine::general_purpose::STANDARD.encode(&ciphertext);+ session.remember(&encoded, &payload);+ session.save_history();+ let mut body = json!({ "epoch": epoch, "blob": encoded });+ if let Some(nonce) = &payload.nonce {+ body["nonce"] = Value::String(nonce.clone());+ }+ api.send(+ Method::POST,+ &format!("/api/mls/groups/{}/messages", group_id),+ &[],+ Some(body),+ )+ .await+}++// ---------------------------------------------------------------------------+// Tauri commands+// ---------------------------------------------------------------------------++use tauri::Emitter;++fn emit_decrypted(app: &tauri::AppHandle, base: &str, items: Vec<Decrypted>) {+ for item in items {+ let _ = app.emit(+ EVENT_DECRYPTED,+ json!({+ "url": base,+ "channel_id": item.channel_id,+ "group_id": item.group_id,+ "ciphertext": item.ciphertext,+ "sender_user_id": item.sender_user_id,+ "sender_device_id": item.sender_device_id,+ "sender_verified": item.sender_verified,+ "payload": item.payload.public_view(),+ }),+ );+ }+}++/// Register the device, keep the key-package stock topped up and drain the+/// mailbox. Called on every gateway connect, and again on each `MLS_ENVELOPE`.+pub async fn sync(+ app: &tauri::AppHandle,+ manager: &MlsManager,+ base: &str,+ top_up: bool,+) -> Result<(), String> {+ let identity = device::ensure_registered(base).await?;+ let _ = identity;+ let api = Api::authed(base)?;+ let handle = manager.session(base).await?;+ let mut session = handle.lock().await;+ if top_up {+ if let Err(e) = top_up_key_packages(&api, &mut session).await {+ tracing::warn!("[omnidisc] could not top up key packages: {}", e);+ }+ }+ let mut decrypted = Vec::new();+ drain_inbox(&api, &mut session, Some(&mut decrypted)).await?;+ // A commit in the mailbox may have moved the epoch of the very channel we+ // are talking in. The key ring has to follow it, or the call goes silent+ // for whoever merged first.+ let room_key = match super::voice::channel_in_call_on(app, base).await {+ Some(channel_id) => session.voice_key(&channel_id),+ None => None,+ };+ drop(session);+ if let Some((epoch, key)) = room_key {+ super::voice::push_room_key(app, epoch, key).await;+ }+ emit_decrypted(app, base, decrypted);+ Ok(())+}++/// Gateway hook. READY tops up the key-package stock and drains the backlog;+/// an `MLS_ENVELOPE` only drains; `DEVICE_REVOKED` also has to issue the commit+/// that removes the device from every group, because the server cannot.+pub fn on_dispatch(app: &tauri::AppHandle, url: &str, t: &str, d: &Value) {+ let (top_up, revoked) = match t {+ "READY" | "RESUMED" => (true, None),+ "MLS_ENVELOPE" => (false, None),+ "DEVICE_REVOKED" => (+ false,+ d.get("device_id").and_then(Value::as_str).map(str::to_string),+ ),+ _ => return,+ };+ use tauri::Manager;+ let manager = app.state::<crate::AppState>().omnidisc_mls.clone();+ let handle = app.clone();+ let base = url.to_string();+ tauri::async_runtime::spawn(async move {+ if let Some(device_id) = revoked {+ match (Api::authed(&base), manager.session(&base).await) {+ (Ok(api), Ok(session)) => {+ let mut guard = session.lock().await;+ if let Err(e) = remove_device_everywhere(&api, &mut guard, &device_id).await {+ tracing::warn!("[omnidisc] could not evict a revoked device: {}", e);+ }+ }+ _ => tracing::warn!("[omnidisc] no session to evict a revoked device from"),+ }+ }+ if let Err(e) = sync(&handle, &manager, &base, top_up).await {+ tracing::warn!("[omnidisc] MLS sync failed: {}", e);+ }+ });+}++#[tauri::command]+pub async fn omnidisc_mls_sync(+ app: tauri::AppHandle,+ state: tauri::State<'_, crate::AppState>,+ url: String,+ top_up: Option<bool>,+) -> Result<(), String> {+ let base = super::normalize_instance_url(&url)?;+ sync(&app, &state.omnidisc_mls, &base, top_up.unwrap_or(true)).await+}++#[derive(Serialize)]+pub struct GroupStatus {+ pub ready: bool,+ pub group_id: String,+ pub epoch: Option<u64>,+ pub members: Vec<GroupMemberView>,+}++#[derive(Serialize)]+pub struct GroupMemberView {+ pub user_id: String,+ pub device_id: String,+ pub fingerprint: String,+ pub is_me: bool,+}++/// What the padlock in the UI is allowed to claim. `ready == false` means the+/// group does not exist yet, and the UI must not promise encryption.+#[tauri::command]+pub async fn omnidisc_mls_status(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ channel_id: String,+) -> Result<GroupStatus, String> {+ let base = super::normalize_instance_url(&url)?;+ let group_id = group_id_for(&channel_id);+ let handle = state.omnidisc_mls.session(&base).await?;+ let session = handle.lock().await;+ let members = session+ .client+ .members(&group_id)+ .into_iter()+ .map(|m| GroupMemberView {+ user_id: m.user_id,+ device_id: m.device_id,+ fingerprint: m.fingerprint,+ is_me: m.is_me,+ })+ .collect();+ Ok(GroupStatus {+ ready: session.client.has_group(&group_id),+ epoch: session.client.epoch(&group_id),+ group_id,+ members,+ })+}++/// Scrollback: MLS ratchets forward, so old ciphertext can only come from the+/// local cache. Anything not cached stays honestly blank in the UI.+#[tauri::command]+pub async fn omnidisc_mls_recall(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ ciphertexts: Vec<String>,+) -> Result<HashMap<String, Value>, String> {+ let base = super::normalize_instance_url(&url)?;+ let handle = state.omnidisc_mls.session(&base).await?;+ let session = handle.lock().await;+ let mut out = HashMap::new();+ for ciphertext in ciphertexts {+ if let Some(payload) = session.recall(&ciphertext) {+ out.insert(ciphertext, payload);+ }+ }+ Ok(out)+}++/// A device of ours was revoked: drop it from every group we are in, since the+/// server cannot issue that commit itself.+#[tauri::command]+pub async fn omnidisc_mls_device_revoked(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ device_id: String,+) -> Result<(), String> {+ let base = super::normalize_instance_url(&url)?;+ let api = Api::authed(&base)?;+ let handle = state.omnidisc_mls.session(&base).await?;+ let mut session = handle.lock().await;+ remove_device_everywhere(&api, &mut session, &device_id).await+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn group_ids_round_trip_and_fit_the_server_rules() {+ let id = group_id_for("1234567890123456789");+ assert_eq!(id, "od-1234567890123456789");+ assert!(id.len() >= 8 && id.len() <= 128);+ assert!(id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')));+ assert_eq!(channel_of_group(&id).as_deref(), Some("1234567890123456789"));+ assert_eq!(channel_of_group("nope"), None);+ }++ #[test]+ fn the_public_view_never_carries_key_material() {+ let payload = E2eePayload {+ v: 1,+ content: "here is the file".into(),+ reply_to: None,+ nonce: Some("n-1".into()),+ files: vec![FileManifest {+ attachment_id: "42".into(),+ file_id: "local-1".into(),+ url: "https://media.example/attachments/42/cat.png?sig=x".into(),+ name: "cat.png".into(),+ mime: Some("image/png".into()),+ size: 1234,+ sha256: "abc".into(),+ key: "SUPERSECRETKEY".into(),+ nonce: "SUPERSECRETNONCE".into(),+ }],+ };+ let view = serde_json::to_string(&payload.public_view()).expect("json");+ assert!(view.contains("cat.png"));+ assert!(view.contains("here is the file"));+ assert!(!view.contains("SUPERSECRETKEY"), "{view}");+ assert!(!view.contains("SUPERSECRETNONCE"), "{view}");+ assert!(!view.contains("sha256"), "{view}");+ assert!(!view.contains("sig=x"), "{view}");+ }++ #[test]+ fn payloads_round_trip_through_json() {+ let raw = r#"{"v":1,"content":"hi","files":[]}"#;+ let payload: E2eePayload = serde_json::from_str(raw).expect("parse");+ assert_eq!(payload.content, "hi");+ assert!(payload.files.is_empty());+ assert!(payload.reply_to.is_none());+ let minimal: E2eePayload = serde_json::from_str("{}").expect("parse");+ assert_eq!(minimal.v, PAYLOAD_VERSION);+ }++ #[test]+ fn ciphertext_hashes_are_stable_and_distinct() {+ let a = hash_ciphertext("AAAA");+ assert_eq!(a, hash_ciphertext("AAAA"));+ assert_ne!(a, hash_ciphertext("AAAB"));+ assert_eq!(a.len(), 64);+ }++ /// The server picks the LiveKit room name, so it must not reach the key+ /// derivation: two participants handed different room names would otherwise+ /// derive different keys and hear silence.+ #[test]+ fn the_voice_key_is_bound_to_the_channel_and_not_to_anything_the_server_says() {+ use omnidisc_mls::{ClaimedDevice, DeviceRef, MlsClient};+ let channel = "1234567890123456789";+ let group = group_id_for(channel);+ let mut alice = MlsClient::new("1001", "desktop-a", &[91u8; 32]).expect("alice");+ let mut bob = MlsClient::new("2002", "phone-bbb", &[92u8; 32]).expect("bob");+ alice.create_group(&group).expect("group");+ let bob_kp = ClaimedDevice {+ device: DeviceRef::new(bob.user_id(), bob.device_id(), bob.public_key().to_vec()),+ key_package: bob.key_packages(1, false).expect("kp").remove(0),+ };+ let out = alice.add_members(&group, &[bob_kp]).expect("add");+ alice.merge_pending(&group).expect("merge");+ let alice_ref =+ DeviceRef::new(alice.user_id(), alice.device_id(), alice.public_key().to_vec());+ bob.join_welcome(&out.welcome.clone().expect("welcome"), &group, &[alice_ref])+ .expect("join");++ let (epoch_a, key_a) = voice_key_of(&alice, channel).expect("alice key");+ let (epoch_b, key_b) = voice_key_of(&bob, channel).expect("bob key");+ assert_eq!(epoch_a, epoch_b);+ assert_eq!(key_a, key_b, "both sides must derive the same key from the channel alone");+ assert!(voice_key_of(&alice, "9999999999999999999").is_none());+ assert_ne!(+ key_a,+ alice.voice_key(&group, b"livekit-room-the-server-picked").expect("raw"),+ "the channel id is what the exporter is bound to"+ );+ }++ #[test]+ fn state_keys_are_validated_on_the_way_in() {+ let key = [3u8; 32];+ let encoded = base64::engine::general_purpose::STANDARD.encode(key);+ assert_eq!(decode_key(&encoded).expect("decode"), key);+ assert!(decode_key("...").is_err());+ assert!(decode_key(&base64::engine::general_purpose::STANDARD.encode([1u8; 8])).is_err());+ }+}diff --git a/src-tauri/src/commands/omnidisc/mod.rs b/src-tauri/src/commands/omnidisc/mod.rsnew file mode 100644index 00000000..a18e26c4--- /dev/null+++ b/src-tauri/src/commands/omnidisc/mod.rs@@ -0,0 +1,170 @@+pub mod api;+pub mod auth;+pub mod device;+pub mod gateway;+pub mod mls;+pub mod store;+pub mod stream;+pub mod upload;+pub mod voice;++#[cfg(test)]+mod e2e_lock;+#[cfg(test)]+mod e2e_test;+#[cfg(test)]+mod e2ee_e2e_test;++use serde::Serialize;+use serde_json::Value;+use std::time::Duration;++pub const ERR_INVALID_URL: &str =+ "OmniDisc: invalid instance URL. Use http:// or https:// without a username or password.";+pub const ERR_UNREACHABLE: &str =+ "OmniDisc: the server did not respond. Check the address or ask the owner for a new link.";+pub const ERR_NOT_AN_INSTANCE: &str = "OmniDisc: this address is not an OmniDisc server.";++#[derive(Serialize)]+pub struct ConnectResult {+ pub url: String,+ pub recognized: bool,+ /// The session token and every message travel in the clear on this+ /// instance. Plain `http://` still works — a lot of self-hosting starts on+ /// a LAN — but the UI has to say so instead of showing the same padlock as+ /// everyone else.+ pub insecure: bool,+ pub instance: Value,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub invite: Option<String>,+}++/// Loopback traffic never leaves the machine, so `http://localhost` is not the+/// thing this flag is warning about.+pub fn is_insecure_instance_url(base: &str) -> bool {+ let Ok(parsed) = url::Url::parse(base) else { return true };+ if parsed.scheme() != "http" {+ return false;+ }+ !matches!(+ parsed.host(),+ Some(url::Host::Domain("localhost"))+ | Some(url::Host::Ipv4(std::net::Ipv4Addr::LOCALHOST))+ | Some(url::Host::Ipv6(std::net::Ipv6Addr::LOCALHOST))+ )+}++pub fn normalize_instance_url(raw: &str) -> Result<String, String> {+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return Err(ERR_INVALID_URL.to_string());+ }+ let with_scheme = if trimmed.contains("://") {+ trimmed.to_string()+ } else {+ format!("https://{}", trimmed)+ };+ let parsed = url::Url::parse(&with_scheme).map_err(|_| ERR_INVALID_URL.to_string())?;+ if !matches!(parsed.scheme(), "http" | "https") {+ return Err(ERR_INVALID_URL.to_string());+ }+ if !parsed.username().is_empty() || parsed.password().is_some() {+ return Err(ERR_INVALID_URL.to_string());+ }+ if parsed.host_str().map(str::is_empty).unwrap_or(true) {+ return Err(ERR_INVALID_URL.to_string());+ }+ let mut base = parsed.clone();+ base.set_query(None);+ base.set_fragment(None);+ let mut base = base.to_string();+ while base.ends_with('/') {+ base.pop();+ }+ Ok(base)+}++#[tauri::command]+pub async fn omnidisc_connect(url: String, invite: Option<String>) -> Result<Value, String> {+ let base = normalize_instance_url(&url)?;+ let endpoint = format!("{}/api/instance", base);++ let client = crate::core::http_client::apply_global_proxy(+ reqwest::Client::builder()+ .user_agent("OmniGet")+ .timeout(Duration::from_secs(10)),+ )+ .build()+ .map_err(|e| format!("OmniDisc: could not build HTTP client: {}", e))?;++ let response = client.get(&endpoint).send().await.map_err(|e| {+ tracing::warn!("[omnidisc] {} unreachable: {}", base, e);+ ERR_UNREACHABLE.to_string()+ })?;++ if !response.status().is_success() {+ tracing::warn!("[omnidisc] {} answered {}", endpoint, response.status());+ return Err(ERR_NOT_AN_INSTANCE.to_string());+ }++ let body: Value = response.json().await.map_err(|e| {+ tracing::warn!("[omnidisc] {} returned non-JSON body: {}", endpoint, e);+ ERR_NOT_AN_INSTANCE.to_string()+ })?;++ let (recognized, instance) =+ match serde_json::from_value::<omnidisc_proto::gateway::InstanceInfo>(body.clone()) {+ Ok(info) => (true, serde_json::to_value(info).unwrap_or(body)),+ Err(_) => (false, body),+ };++ let invite = invite.map(|i| i.trim().to_string()).filter(|i| !i.is_empty());++ let insecure = is_insecure_instance_url(&base);+ if insecure {+ tracing::warn!("[omnidisc] {} is plain http; the session token travels in the clear", base);+ }+ serde_json::to_value(ConnectResult { url: base, recognized, insecure, instance, invite })+ .map_err(|e| format!("OmniDisc: could not serialize response: {}", e))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn accepts_plain_host_and_adds_https() {+ assert_eq!(normalize_instance_url("chat.example.org").unwrap(), "https://chat.example.org");+ }++ #[test]+ fn strips_trailing_slash_query_and_fragment() {+ assert_eq!(+ normalize_instance_url("https://chat.example.org/?x=1#frag").unwrap(),+ "https://chat.example.org"+ );+ assert_eq!(+ normalize_instance_url("http://localhost:8080/base/").unwrap(),+ "http://localhost:8080/base"+ );+ }++ #[test]+ fn plain_http_is_flagged_everywhere_but_loopback() {+ assert!(is_insecure_instance_url("http://chat.example.org"));+ assert!(is_insecure_instance_url("http://192.168.0.10:8080"));+ assert!(!is_insecure_instance_url("https://chat.example.org"));+ assert!(!is_insecure_instance_url("http://localhost:8080"));+ assert!(!is_insecure_instance_url("http://127.0.0.1:8080"));+ assert!(!is_insecure_instance_url("http://[::1]:8080"));+ assert!(is_insecure_instance_url("not a url"));+ }++ #[test]+ fn rejects_credentials_and_other_schemes() {+ assert!(normalize_instance_url("https://user:[email protected]").is_err());+ assert!(normalize_instance_url("ftp://chat.example.org").is_err());+ assert!(normalize_instance_url("").is_err());+ assert!(normalize_instance_url(" ").is_err());+ }+}diff --git a/src-tauri/src/commands/omnidisc/store.rs b/src-tauri/src/commands/omnidisc/store.rsnew file mode 100644index 00000000..bd78f233--- /dev/null+++ b/src-tauri/src/commands/omnidisc/store.rs@@ -0,0 +1,411 @@+//! Session tokens, one per instance URL.+//!+//! macOS and Windows keep them in the OS keyring (service+//! `wtf.tonho.omniget.omnidisc`, account = instance URL). Linux, and any+//! machine where the keyring call fails, falls back to an encrypted file under+//! `{data_dir}/omnidisc/`. WHY the fallback instead of the Secret Service on+//! Linux: that backend needs libdbus headers at build time and a running+//! daemon at runtime, and neither the CI image nor a headless box has them —+//! a hard dependency would break the Linux build. The file is AES-256-CBC ++//! HMAC-SHA256 with a random key stored next to it with 0600 permissions, so+//! the tokens never sit in plain text inside a backup or a synced folder. It+//! is a floor, not a keyring: anyone running as the same OS user can read the+//! key. Tokens never leave this module towards the frontend.+//!+//! `OMNIGET_OMNIDISC_SESSION_DIR` forces the file store into that directory+//! and bypasses the keyring: the integration test must not write into the+//! developer's real keychain (and a rebuilt test binary would trigger a+//! keychain access prompt that blocks forever).++use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyIvInit};+use hmac::{Hmac, Mac};+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::path::{Path, PathBuf};++pub const SERVICE: &str = "wtf.tonho.omniget.omnidisc";+const SESSIONS_FILE: &str = "sessions.bin";+const KEY_FILE: &str = "session.key";+const IV_LEN: usize = 16;+const MAC_LEN: usize = 32;++type Enc = cbc::Encryptor<aes::Aes256>;+type Dec = cbc::Decryptor<aes::Aes256>;+type HmacSha256 = Hmac<Sha256>;++pub const SESSION_DIR_ENV: &str = "OMNIGET_OMNIDISC_SESSION_DIR";++fn forced_dir() -> Option<PathBuf> {+ std::env::var(SESSION_DIR_ENV)+ .ok()+ .map(|d| d.trim().to_string())+ .filter(|d| !d.is_empty())+ .map(PathBuf::from)+}++/// Directory the file store writes into. Also where the MLS state blobs live,+/// so the integration test's `OMNIGET_OMNIDISC_SESSION_DIR` moves every OmniDisc+/// secret at once instead of half of them.+pub fn base_dir() -> Result<PathBuf, String> {+ if let Some(dir) = forced_dir() {+ return Ok(dir);+ }+ let base = crate::core::paths::app_data_dir()+ .ok_or_else(|| "OmniDisc: could not resolve the app data directory".to_string())?;+ Ok(base.join("omnidisc"))+}++/// Secrets other than the session token (device key, MLS state key) share the+/// same store under a suffixed account so one instance's material stays together+/// and is dropped together on logout.+pub fn secret_account(url: &str, kind: &str) -> String {+ format!("{}#{}", url, kind)+}++pub fn save_secret(account: &str, value: &str) -> Result<(), String> {+ if let Some(dir) = forced_dir() {+ return FileStore::new(dir).set(account, value);+ }+ match keyring_set(account, value) {+ Some(Ok(())) => return Ok(()),+ Some(Err(e)) => tracing::warn!("[omnidisc] keyring write failed, using file store: {}", e),+ None => {}+ }+ FileStore::default_dir()?.set(account, value)+}++pub fn load_secret(account: &str) -> Result<Option<String>, String> {+ if let Some(dir) = forced_dir() {+ return FileStore::new(dir).get(account);+ }+ match keyring_get(account) {+ Some(Ok(found)) => {+ if found.is_some() {+ return Ok(found);+ }+ }+ Some(Err(e)) => tracing::warn!("[omnidisc] keyring read failed, using file store: {}", e),+ None => {}+ }+ FileStore::default_dir()?.get(account)+}++pub fn delete_secret(account: &str) -> Result<(), String> {+ if let Some(dir) = forced_dir() {+ return FileStore::new(dir).remove(account);+ }+ if let Some(Err(e)) = keyring_delete(account) {+ tracing::warn!("[omnidisc] keyring delete failed: {}", e);+ }+ FileStore::default_dir()?.remove(account)+}++pub fn save_token(url: &str, token: &str) -> Result<(), String> {+ save_secret(url, token)+}++pub fn load_token(url: &str) -> Result<Option<String>, String> {+ load_secret(url)+}++pub fn delete_token(url: &str) -> Result<(), String> {+ delete_secret(url)+}++#[cfg(any(target_os = "macos", windows))]+fn keyring_entry(url: &str) -> Result<keyring::Entry, String> {+ keyring::Entry::new(SERVICE, url).map_err(|e| e.to_string())+}++#[cfg(any(target_os = "macos", windows))]+fn keyring_set(url: &str, token: &str) -> Option<Result<(), String>> {+ Some(keyring_entry(url).and_then(|e| e.set_password(token).map_err(|e| e.to_string())))+}++#[cfg(any(target_os = "macos", windows))]+fn keyring_get(url: &str) -> Option<Result<Option<String>, String>> {+ Some(keyring_entry(url).and_then(|e| match e.get_password() {+ Ok(t) => Ok(Some(t)),+ Err(keyring::Error::NoEntry) => Ok(None),+ Err(err) => Err(err.to_string()),+ }))+}++#[cfg(any(target_os = "macos", windows))]+fn keyring_delete(url: &str) -> Option<Result<(), String>> {+ Some(keyring_entry(url).and_then(|e| match e.delete_credential() {+ Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),+ Err(err) => Err(err.to_string()),+ }))+}++#[cfg(not(any(target_os = "macos", windows)))]+fn keyring_set(_url: &str, _token: &str) -> Option<Result<(), String>> {+ None+}++#[cfg(not(any(target_os = "macos", windows)))]+fn keyring_get(_url: &str) -> Option<Result<Option<String>, String>> {+ None+}++#[cfg(not(any(target_os = "macos", windows)))]+fn keyring_delete(_url: &str) -> Option<Result<(), String>> {+ None+}++pub struct FileStore {+ dir: PathBuf,+}++impl FileStore {+ pub fn new(dir: impl Into<PathBuf>) -> Self {+ Self { dir: dir.into() }+ }++ fn default_dir() -> Result<Self, String> {+ let base = crate::core::paths::app_data_dir()+ .ok_or_else(|| "OmniDisc: could not resolve the app data directory".to_string())?;+ Ok(Self::new(base.join("omnidisc")))+ }++ pub fn get(&self, url: &str) -> Result<Option<String>, String> {+ Ok(self.load()?.remove(url))+ }++ pub fn set(&self, url: &str, token: &str) -> Result<(), String> {+ let mut map = self.load()?;+ map.insert(url.to_string(), token.to_string());+ self.save(&map)+ }++ pub fn remove(&self, url: &str) -> Result<(), String> {+ let mut map = self.load()?;+ if map.remove(url).is_some() {+ self.save(&map)?;+ }+ Ok(())+ }++ fn load(&self) -> Result<HashMap<String, String>, String> {+ let path = self.dir.join(SESSIONS_FILE);+ let blob = match std::fs::read(&path) {+ Ok(b) => b,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),+ Err(e) => return Err(format!("OmniDisc: could not read session store: {}", e)),+ };+ let key = self.key(false)?;+ let Some(key) = key else {+ return Ok(HashMap::new());+ };+ let plain = decrypt(&key, &blob)?;+ serde_json::from_slice(&plain)+ .map_err(|e| format!("OmniDisc: session store is corrupt: {}", e))+ }++ fn save(&self, map: &HashMap<String, String>) -> Result<(), String> {+ std::fs::create_dir_all(&self.dir)+ .map_err(|e| format!("OmniDisc: could not create session store dir: {}", e))?;+ let key = self+ .key(true)?+ .ok_or_else(|| "OmniDisc: could not create session key".to_string())?;+ let plain = serde_json::to_vec(map)+ .map_err(|e| format!("OmniDisc: could not encode session store: {}", e))?;+ let blob = encrypt(&key, &plain);+ write_private(&self.dir.join(SESSIONS_FILE), &blob)+ }++ fn key(&self, create: bool) -> Result<Option<[u8; 32]>, String> {+ let path = self.dir.join(KEY_FILE);+ match std::fs::read(&path) {+ Ok(bytes) if bytes.len() == 32 => {+ let mut key = [0u8; 32];+ key.copy_from_slice(&bytes);+ Ok(Some(key))+ }+ Ok(_) => Err("OmniDisc: session key file has the wrong size".to_string()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ if !create {+ return Ok(None);+ }+ let mut key = [0u8; 32];+ rand::Rng::fill_bytes(&mut rand::rng(), &mut key);+ write_private(&path, &key)?;+ Ok(Some(key))+ }+ Err(e) => Err(format!("OmniDisc: could not read session key: {}", e)),+ }+ }+}++/// Write a file only its owner can read. On unix the mode is part of the+/// `open` call: creating the file first and chmod'ing after leaves a window in+/// which the session key, the device key or the MLS state is world-readable.+pub fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {+ let io = |e: std::io::Error| format!("OmniDisc: could not write {}: {}", path.display(), e);+ #[cfg(unix)]+ {+ use std::io::Write;+ use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};+ if let Some(dir) = path.parent() {+ let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));+ }+ let mut opts = std::fs::OpenOptions::new();+ opts.write(true).mode(0o600);+ let mut file = match opts.clone().create_new(true).open(path) {+ Ok(f) => f,+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {+ // Re-tighten before reopening: an older build may have left it+ // readable, and truncating does not change the mode.+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))+ .map_err(io)?;+ opts.truncate(true).open(path).map_err(io)?+ }+ Err(e) => return Err(io(e)),+ };+ file.write_all(bytes).map_err(io)?;+ return Ok(());+ }+ #[cfg(not(unix))]+ {+ std::fs::write(path, bytes).map_err(io)+ }+}++fn derive(key: &[u8; 32], label: &[u8]) -> [u8; 32] {+ let mut hasher = Sha256::new();+ hasher.update(key);+ hasher.update(label);+ hasher.finalize().into()+}++fn encrypt(key: &[u8; 32], plain: &[u8]) -> Vec<u8> {+ let enc_key = derive(key, b"enc");+ let mac_key = derive(key, b"mac");+ let mut iv = [0u8; IV_LEN];+ rand::Rng::fill_bytes(&mut rand::rng(), &mut iv);+ let mut buf = vec![0u8; plain.len() + 16];+ buf[..plain.len()].copy_from_slice(plain);+ let ct_len = Enc::new(&enc_key.into(), &iv.into())+ .encrypt_padded_mut::<Pkcs7>(&mut buf, plain.len())+ .map(|ct| ct.len())+ .unwrap_or(0);+ buf.truncate(ct_len);+ let mut out = Vec::with_capacity(IV_LEN + buf.len() + MAC_LEN);+ out.extend_from_slice(&iv);+ out.extend_from_slice(&buf);+ let mut mac = HmacSha256::new_from_slice(&mac_key).unwrap_or_else(|_| {+ HmacSha256::new_from_slice(b"omnidisc").expect("hmac accepts any key length")+ });+ mac.update(&out);+ out.extend_from_slice(&mac.finalize().into_bytes());+ out+}++fn decrypt(key: &[u8; 32], blob: &[u8]) -> Result<Vec<u8>, String> {+ if blob.len() < IV_LEN + MAC_LEN {+ return Err("OmniDisc: session store is truncated".to_string());+ }+ let (body, tag) = blob.split_at(blob.len() - MAC_LEN);+ let mac_key = derive(key, b"mac");+ let mut mac = HmacSha256::new_from_slice(&mac_key).unwrap_or_else(|_| {+ HmacSha256::new_from_slice(b"omnidisc").expect("hmac accepts any key length")+ });+ mac.update(body);+ mac.verify_slice(tag)+ .map_err(|_| "OmniDisc: session store failed integrity check".to_string())?;+ let (iv, ct) = body.split_at(IV_LEN);+ let enc_key = derive(key, b"enc");+ let mut iv_arr = [0u8; IV_LEN];+ iv_arr.copy_from_slice(iv);+ let mut buf = ct.to_vec();+ Dec::new(&enc_key.into(), &iv_arr.into())+ .decrypt_padded_mut::<Pkcs7>(&mut buf)+ .map(|pt| pt.to_vec())+ .map_err(|_| "OmniDisc: session store could not be decrypted".to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp_dir(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "omnidisc-store-{}-{}-{}",+ name,+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0)+ ));+ let _ = std::fs::remove_dir_all(&dir);+ dir+ }++ #[test]+ fn file_store_roundtrip() {+ let dir = temp_dir("roundtrip");+ let store = FileStore::new(&dir);+ assert_eq!(store.get("https://a.example").unwrap(), None);+ store.set("https://a.example", "od1.secret-a").unwrap();+ store.set("https://b.example", "od1.secret-b").unwrap();+ assert_eq!(store.get("https://a.example").unwrap().as_deref(), Some("od1.secret-a"));+ assert_eq!(store.get("https://b.example").unwrap().as_deref(), Some("od1.secret-b"));+ store.remove("https://a.example").unwrap();+ assert_eq!(store.get("https://a.example").unwrap(), None);+ assert_eq!(store.get("https://b.example").unwrap().as_deref(), Some("od1.secret-b"));+ let raw = std::fs::read(dir.join(SESSIONS_FILE)).unwrap();+ assert!(!raw.windows(b"od1.secret-b".len()).any(|w| w == b"od1.secret-b"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn tampering_is_rejected() {+ let dir = temp_dir("tamper");+ let store = FileStore::new(&dir);+ store.set("https://a.example", "od1.secret").unwrap();+ let path = dir.join(SESSIONS_FILE);+ let mut raw = std::fs::read(&path).unwrap();+ let idx = IV_LEN + 1;+ raw[idx] ^= 0xff;+ std::fs::write(&path, raw).unwrap();+ assert!(store.get("https://a.example").is_err());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// The session key is the key to every stored token: it must never exist on+ /// disk, not even for an instant, in a mode another local account can read.+ #[cfg(unix)]+ #[test]+ fn private_files_are_never_readable_by_anyone_else() {+ use std::os::unix::fs::PermissionsExt;+ let dir = temp_dir("private");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();+ let path = dir.join("key.bin");+ write_private(&path, b"first").unwrap();+ let mode = |p: &std::path::Path| {+ std::fs::metadata(p).unwrap().permissions().mode() & 0o777+ };+ assert_eq!(mode(&path), 0o600);+ assert_eq!(mode(&dir), 0o700, "the folder around it has to be private too");++ // An overwrite keeps the mode, and a file an older build left open is+ // tightened before it is written again.+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();+ write_private(&path, b"second").unwrap();+ assert_eq!(mode(&path), 0o600);+ assert_eq!(std::fs::read(&path).unwrap(), b"second");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn encrypt_decrypt_roundtrip_and_mac() {+ let key = [7u8; 32];+ let blob = encrypt(&key, b"hello");+ assert_eq!(decrypt(&key, &blob).unwrap(), b"hello");+ let other = [8u8; 32];+ assert!(decrypt(&other, &blob).is_err());+ }+}diff --git a/src-tauri/src/commands/omnidisc/stream.rs b/src-tauri/src/commands/omnidisc/stream.rsnew file mode 100644index 00000000..49387e62--- /dev/null+++ b/src-tauri/src/commands/omnidisc/stream.rs@@ -0,0 +1,281 @@+use super::voice::EVENT_VOICE;+use omnidisc_media::{+ start_stream, ActiveStream, AudioMode, LiveKitBackend, PublishStats, SourceId, StreamError, StreamMode, StreamRequest,+ StreamSources, StreamStats, Viewer, Viewport, WatchStats,+};+use omnidisc_proto::bitrate::StreamingPolicy;+use serde::Deserialize;+use serde_json::json;+use std::collections::HashMap;+use std::sync::Arc;+use tauri::{Emitter, Manager, WebviewUrl, WebviewWindowBuilder};+use tokio::sync::Mutex;++pub struct StreamManager {+ active: Mutex<Option<ActiveStream>>,+ viewers: Mutex<HashMap<String, Viewer>>,+}++impl Default for StreamManager {+ fn default() -> Self {+ Self { active: Mutex::new(None), viewers: Mutex::new(HashMap::new()) }+ }+}++fn err(e: StreamError) -> String {+ e.code().to_string()+}++fn backend(state: &crate::AppState) -> Result<Arc<LiveKitBackend>, String> {+ state.omnidisc_voice.livekit_backend().ok_or_else(|| "ERR_VOICE_UNAVAILABLE".to_string())+}++fn emit_voice(app: &tauri::AppHandle, url: Option<String>, event: &str, mut payload: serde_json::Value) {+ if let serde_json::Value::Object(map) = &mut payload {+ map.insert("type".into(), json!(event));+ map.insert("url".into(), url.map(serde_json::Value::String).unwrap_or(serde_json::Value::Null));+ }+ let _ = app.emit(EVENT_VOICE, payload);+}++#[tauri::command]+pub async fn omnidisc_stream_sources(state: tauri::State<'_, crate::AppState>) -> Result<StreamSources, String> {+ let _ = state;+ tokio::task::spawn_blocking(|| omnidisc_media::capture::list_sources(true).map_err(err))+ .await+ .map_err(|e| format!("OmniDisc: source enumeration failed: {e}"))?+}++#[derive(Deserialize)]+pub struct StartArgs {+ pub source: SourceId,+ pub fps: u16,+ #[serde(default)]+ pub height: Option<u16>,+ #[serde(default)]+ pub audio: AudioMode,+ #[serde(default)]+ pub bitrate_kbps: Option<u32>,+ #[serde(default)]+ pub mode: StreamMode,+ #[serde(default)]+ pub cursor: bool,+ #[serde(default)]+ pub policy: Option<StreamingPolicy>,+}++#[tauri::command]+pub async fn omnidisc_stream_start(+ app: tauri::AppHandle,+ state: tauri::State<'_, crate::AppState>,+ args: StartArgs,+) -> Result<PublishStats, String> {+ let backend = backend(&state)?;+ if !backend.is_connected().await {+ return Err(StreamError::NotConnected.code().to_string());+ }+ let req = StreamRequest {+ source: args.source,+ fps: args.fps,+ height: args.height,+ audio: args.audio,+ bitrate_kbps: args.bitrate_kbps,+ mode: args.mode,+ cursor: args.cursor,+ policy: args.policy.unwrap_or_default(),+ };+ let stream = start_stream(backend, req).await.map_err(err)?;+ let audio_mode = stream.audio_mode();+ let resolved = stream.resolved.clone();+ {+ let mut active = state.omnidisc_stream.active.lock().await;+ if let Some(old) = active.take() {+ if let Some(b) = state.omnidisc_voice.livekit_backend() {+ if let Some(room) = b.current_room().await {+ old.stop(&room).await;+ }+ }+ }+ // schedule the two-stage overdrive re-apply like Backspace (t+2 s, t+5 s)+ *active = Some(stream);+ }+ state.omnidisc_voice.set_streaming(true);+ state.omnidisc_voice.announce_stream(&state.omnidisc_gateways).await;+ let url = state.omnidisc_voice.session_info().await.map(|s| s.url);+ schedule_overdrive(app.clone());+ let stats = current_publish_stats(&state).await.unwrap_or_default();+ emit_voice(&app, url.clone(), "stream_started", serde_json::to_value(&resolved).unwrap_or_default());+ emit_voice(&app, url, "stream_audio_mode", json!({ "audio": audio_mode }));+ Ok(stats)+}++fn schedule_overdrive(app: tauri::AppHandle) {+ tauri::async_runtime::spawn(async move {+ for delay in [2u64, 5] {+ tokio::time::sleep(std::time::Duration::from_secs(delay)).await;+ if let Some(state) = app.try_state::<crate::AppState>() {+ if let Some(s) = state.omnidisc_stream.active.lock().await.as_ref() {+ s.overdrive();+ }+ }+ }+ });+}++async fn current_publish_stats(state: &crate::AppState) -> Option<PublishStats> {+ let active = state.omnidisc_stream.active.lock().await;+ let stream = active.as_ref()?;+ Some(stream.stats().await)+}++#[tauri::command]+pub async fn omnidisc_stream_stop(app: tauri::AppHandle, state: tauri::State<'_, crate::AppState>) -> Result<(), String> {+ let stream = state.omnidisc_stream.active.lock().await.take();+ if let Some(stream) = stream {+ if let Some(b) = state.omnidisc_voice.livekit_backend() {+ if let Some(room) = b.current_room().await {+ stream.stop(&room).await;+ }+ }+ }+ state.omnidisc_voice.set_streaming(false);+ state.omnidisc_voice.announce_stream(&state.omnidisc_gateways).await;+ let url = state.omnidisc_voice.session_info().await.map(|s| s.url);+ emit_voice(&app, url, "stream_stopped", json!({}));+ Ok(())+}++#[tauri::command]+pub async fn omnidisc_stream_stats(state: tauri::State<'_, crate::AppState>) -> Result<StreamStats, String> {+ let publishing = current_publish_stats(&state).await;+ let mut watching: Vec<WatchStats> = Vec::new();+ let viewers = state.omnidisc_stream.viewers.lock().await;+ for v in viewers.values() {+ watching.push(v.stats().await);+ }+ Ok(StreamStats { publishing, watching })+}++#[tauri::command]+pub async fn omnidisc_stream_set_volume(state: tauri::State<'_, crate::AppState>, user_id: String, gain: f32) -> Result<(), String> {+ if !gain.is_finite() {+ return Err("ERR_BAD_REQUEST".into());+ }+ if let Some(b) = state.omnidisc_voice.livekit_backend() {+ b.set_screen_audio_gain(&user_id, gain.clamp(0.0, 2.0));+ }+ Ok(())+}++#[derive(Deserialize)]+pub struct ViewportArgs {+ pub user_id: String,+ pub x: f64,+ pub y: f64,+ pub width: f64,+ pub height: f64,+ pub scale: f64,+ pub surface_width: u32,+ pub surface_height: u32,+ #[serde(default)]+ pub background: Option<[f32; 3]>,+}++#[tauri::command]+pub async fn omnidisc_stream_set_viewport(state: tauri::State<'_, crate::AppState>, args: ViewportArgs) -> Result<(), String> {+ let viewers = state.omnidisc_stream.viewers.lock().await;+ if let Some(v) = viewers.get(&args.user_id) {+ v.set_viewport(Some(Viewport {+ x: args.x,+ y: args.y,+ width: args.width,+ height: args.height,+ scale: if args.scale > 0.0 { args.scale } else { 1.0 },+ surface_width: args.surface_width,+ surface_height: args.surface_height,+ background: args.background.unwrap_or([0.0, 0.0, 0.0]),+ }));+ }+ Ok(())+}++#[tauri::command]+pub async fn omnidisc_stream_watch(app: tauri::AppHandle, state: tauri::State<'_, crate::AppState>, user_id: String) -> Result<(), String> {+ let backend = backend(&state)?;+ if state.omnidisc_stream.viewers.lock().await.contains_key(&user_id) {+ return Ok(());+ }+ let publication = backend.video_publication_for(&user_id).ok_or_else(|| StreamError::NoSuchStream.code().to_string())?;+ publication.set_subscribed(true);++ let track = {+ let mut found = None;+ for _ in 0..50 {+ if let Some(rv) = backend.remote_video_for(&user_id) {+ found = Some(rv.track);+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ found.ok_or_else(|| StreamError::Viewer("stream did not arrive".into()).code().to_string())?+ };++ let label = format!("omnidisc-stream-{}", sanitize(&user_id));+ let win_label = label.clone();+ let uid = user_id.clone();+ let build = WebviewWindowBuilder::new(&app, &win_label, WebviewUrl::App(format!("/omnidisc/stream?user={user_id}").into()))+ .title("OmniDisc — Stream")+ .inner_size(1280.0, 760.0)+ .min_inner_size(480.0, 320.0)+ .transparent(true);+ let window = build.build().map_err(|e| format!("OmniDisc: could not open the stream window: {e}"))?;++ let renderer = create_surface_on_main(&app, &window).await?;+ let rt = backend.runtime_handle().ok_or_else(|| "ERR_VOICE_UNAVAILABLE".to_string())?;+ let viewer = Viewer::new(renderer, track, uid, rt);+ state.omnidisc_stream.viewers.lock().await.insert(user_id, viewer);+ Ok(())+}++fn sanitize(s: &str) -> String {+ s.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()+}++async fn create_surface_on_main(app: &tauri::AppHandle, window: &tauri::WebviewWindow) -> Result<Arc<omnidisc_media::viewer::WgpuViewer>, String> {+ let size = window.inner_size().map_err(|e| format!("OmniDisc: window size: {e}"))?;+ #[cfg(target_os = "macos")]+ {+ let ns_view = window.ns_view().map_err(|e| format!("OmniDisc: ns_view: {e}"))? as *mut std::ffi::c_void;+ let ptr = ns_view as usize;+ let (w, h) = (size.width, size.height);+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.run_on_main_thread(move || {+ let result = unsafe { omnidisc_media::viewer::create_appkit_surface(ptr as *mut std::ffi::c_void, w, h) };+ let _ = tx.send(result.map_err(err));+ })+ .map_err(|e| format!("OmniDisc: main thread dispatch: {e}"))?;+ rx.await.map_err(|_| "OmniDisc: surface creation dropped".to_string())?+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = (app, window, size);+ Err(StreamError::Unsupported.code().to_string())+ }+}++#[tauri::command]+pub async fn omnidisc_stream_unwatch(app: tauri::AppHandle, state: tauri::State<'_, crate::AppState>, user_id: String) -> Result<(), String> {+ let removed = state.omnidisc_stream.viewers.lock().await.remove(&user_id);+ if removed.is_some() {+ if let Some(b) = state.omnidisc_voice.livekit_backend() {+ if let Some(p) = b.video_publication_for(&user_id) {+ p.set_subscribed(false);+ }+ }+ let label = format!("omnidisc-stream-{}", sanitize(&user_id));+ if let Some(win) = app.get_webview_window(&label) {+ let _ = win.close();+ }+ }+ Ok(())+}diff --git a/src-tauri/src/commands/omnidisc/upload.rs b/src-tauri/src/commands/omnidisc/upload.rsnew file mode 100644index 00000000..55c38fa4--- /dev/null+++ b/src-tauri/src/commands/omnidisc/upload.rs@@ -0,0 +1,1021 @@+//! Resumable uploads (tus 1.0.0) and attachment downloads.+//!+//! For an E2EE channel the file is encrypted to a temp file first and the blob+//! that leaves the machine is already ciphertext — the server stores size, id,+//! owner and expiry, nothing else (ADR 0014 §3). The key travels in the MLS+//! message, so it never reaches the frontend or the network in the clear.++use super::api::{http_client, Api, ERR_BAD_REQUEST, ERR_SERVER, ERR_UNREACHABLE};+use super::mls::FileManifest;+use super::{normalize_instance_url, store};+use base64::Engine;+use omnidisc_mls::FileSecret;+use omnidisc_proto::gateway::InstanceInfo;+use omnidisc_proto::message::Attachment;+use reqwest::Method;+use serde::Serialize;+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::Duration;+use tauri::Emitter;+use tokio::sync::Mutex;+use tokio_util::sync::CancellationToken;++pub const EVENT_UPLOAD: &str = "omnidisc://upload";+pub const ERR_TOO_LARGE: &str = "ERR_UPLOAD_TOO_LARGE";+pub const ERR_CANCELLED: &str = "ERR_UPLOAD_CANCELLED";+pub const ERR_UPLOAD: &str = "ERR_UPLOAD";+pub const ERR_UNKNOWN_UPLOAD: &str = "ERR_UNKNOWN_UPLOAD";+pub const ERR_ATTACHMENT_ORIGIN: &str = "ERR_ATTACHMENT_ORIGIN";+pub const ERR_ATTACHMENT_TOO_LARGE: &str = "ERR_ATTACHMENT_TOO_LARGE";++/// Room for the per-chunk AEAD tags and the manifest header, so an honest file+/// is never cut off by its own budget.+const DOWNLOAD_SLACK: u64 = 1024 * 1024;+/// Ceiling for a plain (non-E2EE) attachment whose size nobody stated.+const DOWNLOAD_FALLBACK_CAP: u64 = 2 * 1024 * 1024 * 1024;++const PATCH_CHUNK: usize = 4 * 1024 * 1024;+const RESUME_ATTEMPTS: u32 = 4;+const TUS_VERSION: &str = "1.0.0";++#[derive(Clone, Serialize)]+pub struct UploadProgress {+ pub id: String,+ pub url: String,+ pub channel_id: String,+ pub name: String,+ pub sent: u64,+ pub total: u64,+ pub state: &'static str,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub attachment_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mime: Option<String>,+ #[serde(default)]+ pub encrypted: bool,+}++/// A finished upload waiting to be attached to a message. The secret stays on+/// this side of the bridge; the frontend only ever passes the upload id back.+#[derive(Clone)]+pub struct ReadyUpload {+ pub url: String,+ pub channel_id: String,+ pub attachment_id: String,+ pub file_id: String,+ pub url_signed: String,+ pub filename: String,+ pub mime: Option<String>,+ pub size: u64,+ pub sha256: String,+ pub secret: Option<FileSecret>,+}++impl ReadyUpload {+ pub fn manifest(&self) -> Option<FileManifest> {+ let secret = self.secret.as_ref()?;+ Some(FileManifest {+ attachment_id: self.attachment_id.clone(),+ file_id: self.file_id.clone(),+ url: self.url_signed.clone(),+ name: self.filename.clone(),+ mime: self.mime.clone(),+ size: self.size,+ sha256: self.sha256.clone(),+ key: base64::engine::general_purpose::STANDARD.encode(secret.key),+ nonce: base64::engine::general_purpose::STANDARD.encode(secret.nonce),+ })+ }+}++#[derive(Default)]+pub struct UploadManager {+ running: Mutex<HashMap<String, CancellationToken>>,+ ready: Mutex<HashMap<String, ReadyUpload>>,+}++impl UploadManager {+ /// Look up finished uploads without consuming them, so a failed send can be+ /// retried with the same files instead of asking for them again.+ pub async fn peek(&self, ids: &[String]) -> Result<Vec<ReadyUpload>, String> {+ let map = self.ready.lock().await;+ let mut out = Vec::with_capacity(ids.len());+ for id in ids {+ let ready = map+ .get(id)+ .ok_or_else(|| format!("{}:{}", ERR_UNKNOWN_UPLOAD, id))?;+ out.push(ready.clone());+ }+ Ok(out)+ }++ pub async fn release(&self, ids: &[String]) {+ let mut map = self.ready.lock().await;+ for id in ids {+ map.remove(id);+ }+ }++ pub async fn cancel(&self, id: &str) {+ if let Some(token) = self.running.lock().await.remove(id) {+ token.cancel();+ }+ self.ready.lock().await.remove(id);+ }+}++fn tmp_dir() -> Result<PathBuf, String> {+ let dir = store::base_dir()?.join("uploads");+ std::fs::create_dir_all(&dir)+ .map_err(|e| format!("OmniDisc: could not create the upload workspace: {}", e))?;+ Ok(dir)+}++fn guess_mime(path: &Path) -> Option<String> {+ let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();+ let mime = match ext.as_str() {+ "png" => "image/png",+ "jpg" | "jpeg" => "image/jpeg",+ "gif" => "image/gif",+ "webp" => "image/webp",+ "avif" => "image/avif",+ "svg" => "image/svg+xml",+ "mp4" | "m4v" => "video/mp4",+ "webm" => "video/webm",+ "mov" => "video/quicktime",+ "mkv" => "video/x-matroska",+ "mp3" => "audio/mpeg",+ "m4a" => "audio/mp4",+ "ogg" | "opus" => "audio/ogg",+ "wav" => "audio/wav",+ "flac" => "audio/flac",+ "pdf" => "application/pdf",+ "txt" | "md" => "text/plain",+ "zip" => "application/zip",+ _ => return None,+ };+ Some(mime.to_string())+}++fn meta_pair(key: &str, value: &str) -> String {+ format!("{} {}", key, base64::engine::general_purpose::STANDARD.encode(value))+}++pub async fn instance_limits(base: &str) -> Result<InstanceInfo, String> {+ let api = Api::public(base)?;+ api.send(Method::GET, "/api/instance", &[], None).await+}++struct Tus {+ http: reqwest::Client,+ base: String,+ token: String,+}++impl Tus {+ fn new(base: &str) -> Result<Self, String> {+ let token = store::load_token(base)?+ .ok_or_else(|| super::api::ERR_NO_SESSION.to_string())?;+ Ok(Self {+ http: http_client(Duration::from_secs(120))?,+ base: base.to_string(),+ token,+ })+ }++ async fn create(&self, total: u64, meta: &str) -> Result<String, String> {+ let response = self+ .http+ .post(format!("{}/api/uploads", self.base))+ .bearer_auth(&self.token)+ .header("tus-resumable", TUS_VERSION)+ .header("upload-length", total.to_string())+ .header("upload-metadata", meta)+ .send()+ .await+ .map_err(|e| {+ tracing::warn!("[omnidisc] upload create failed: {}", e);+ ERR_UNREACHABLE.to_string()+ })?;+ let status = response.status();+ if status == reqwest::StatusCode::PAYLOAD_TOO_LARGE {+ return Err(ERR_TOO_LARGE.to_string());+ }+ if !status.is_success() {+ let text = response.text().await.unwrap_or_default();+ let code = serde_json::from_str::<omnidisc_proto::rest::ApiError>(&text)+ .map(|e| e.code)+ .unwrap_or_default();+ tracing::warn!("[omnidisc] upload create -> {} {}", status.as_u16(), text);+ return Err(super::api::map_error(status, &code));+ }+ let location = response+ .headers()+ .get("location")+ .and_then(|v| v.to_str().ok())+ .ok_or_else(|| {+ tracing::warn!("[omnidisc] upload create answered without a Location header");+ ERR_SERVER.to_string()+ })?;+ Ok(location.rsplit('/').next().unwrap_or_default().to_string())+ }++ async fn offset(&self, id: &str) -> Result<u64, String> {+ let response = self+ .http+ .head(format!("{}/api/uploads/{}", self.base, id))+ .bearer_auth(&self.token)+ .header("tus-resumable", TUS_VERSION)+ .send()+ .await+ .map_err(|_| ERR_UNREACHABLE.to_string())?;+ if !response.status().is_success() {+ return Err(ERR_UPLOAD.to_string());+ }+ response+ .headers()+ .get("upload-offset")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.parse().ok())+ .ok_or_else(|| ERR_SERVER.to_string())+ }++ /// Returns the new offset, plus the attachment once the last chunk lands.+ async fn patch(+ &self,+ id: &str,+ offset: u64,+ body: Vec<u8>,+ ) -> Result<(u64, Option<Attachment>), String> {+ let response = self+ .http+ .patch(format!("{}/api/uploads/{}", self.base, id))+ .bearer_auth(&self.token)+ .header("tus-resumable", TUS_VERSION)+ .header("upload-offset", offset.to_string())+ .header("content-type", "application/offset+octet-stream")+ .body(body)+ .send()+ .await+ .map_err(|e| {+ tracing::warn!("[omnidisc] upload chunk failed: {}", e);+ ERR_UNREACHABLE.to_string()+ })?;+ let status = response.status();+ if status == reqwest::StatusCode::PAYLOAD_TOO_LARGE {+ return Err(ERR_TOO_LARGE.to_string());+ }+ if !status.is_success() {+ let text = response.text().await.unwrap_or_default();+ let code = serde_json::from_str::<omnidisc_proto::rest::ApiError>(&text)+ .map(|e| e.code)+ .unwrap_or_default();+ tracing::warn!("[omnidisc] upload chunk -> {} {}", status.as_u16(), text);+ return Err(super::api::map_error(status, &code));+ }+ let next = response+ .headers()+ .get("upload-offset")+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.parse::<u64>().ok())+ .unwrap_or(offset + 1);+ if status == reqwest::StatusCode::OK {+ let text = response.text().await.unwrap_or_default();+ let attachment = serde_json::from_str::<Attachment>(&text)+ .map_err(|e| {+ tracing::warn!("[omnidisc] upload finished with an unreadable body: {}", e);+ ERR_SERVER.to_string()+ })?;+ return Ok((next, Some(attachment)));+ }+ Ok((next, None))+ }++ async fn terminate(&self, id: &str) {+ let _ = self+ .http+ .delete(format!("{}/api/uploads/{}", self.base, id))+ .bearer_auth(&self.token)+ .header("tus-resumable", TUS_VERSION)+ .send()+ .await;+ }+}++struct Job {+ id: String,+ base: String,+ channel_id: String,+ name: String,+ mime: Option<String>,+ encrypt: bool,+ source: PathBuf,+}++/// Progress sink. The Tauri command emits an event; the integration test just+/// counts, which is what lets the upload path be exercised without a webview.+pub type Progress<'a> = &'a (dyn Fn(UploadProgress) + Send + Sync);++fn emit(sink: Progress<'_>, progress: UploadProgress) {+ sink(progress);+}++fn progress_of(job: &Job, sent: u64, total: u64, state: &'static str) -> UploadProgress {+ UploadProgress {+ id: job.id.clone(),+ url: job.base.clone(),+ channel_id: job.channel_id.clone(),+ name: job.name.clone(),+ sent,+ total,+ state,+ error: None,+ attachment_id: None,+ mime: job.mime.clone(),+ encrypted: job.encrypt,+ }+}++async fn run_job(+ app: tauri::AppHandle,+ manager: Arc<UploadManager>,+ job: Job,+ cancel: CancellationToken,+) {+ let id = job.id.clone();+ let handle = app.clone();+ let sink = move |p: UploadProgress| {+ let _ = handle.emit(EVENT_UPLOAD, p);+ };+ match upload(&sink, &job, &cancel).await {+ Ok(ready) => {+ let mut done = progress_of(&job, ready.size, ready.size, "done");+ done.attachment_id = Some(ready.attachment_id.clone());+ manager.ready.lock().await.insert(id.clone(), ready);+ emit(&sink, done);+ }+ Err(err) => {+ let state = if cancel.is_cancelled() { "cancelled" } else { "failed" };+ let mut failed = progress_of(&job, 0, 0, state);+ failed.error = Some(err);+ emit(&sink, failed);+ }+ }+ manager.running.lock().await.remove(&id);+}++/// The upload pipeline without Tauri: used by the integration test, which has no+/// app handle to emit into.+pub async fn upload_file(+ base: &str,+ channel_id: &str,+ path: &Path,+ encrypt: bool,+ progress: Progress<'_>,+) -> Result<ReadyUpload, String> {+ let job = Job {+ id: uuid::Uuid::new_v4().to_string(),+ base: base.to_string(),+ channel_id: channel_id.to_string(),+ mime: guess_mime(path),+ name: path+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_else(|| "file".to_string()),+ encrypt,+ source: path.to_path_buf(),+ };+ upload(progress, &job, &CancellationToken::new()).await+}++async fn upload(+ app: Progress<'_>,+ job: &Job,+ cancel: &CancellationToken,+) -> Result<ReadyUpload, String> {+ let meta = std::fs::metadata(&job.source)+ .map_err(|e| format!("{}:{}", ERR_BAD_REQUEST, unreadable(&job.source, e)))?;+ let plain_size = meta.len();+ let limits = instance_limits(&job.base).await?;+ let max = limits.limits.max_upload_bytes.max(limits.max_upload_bytes);++ // Refuse early: encrypting a 3 GB file only to be told it is too large is+ // the kind of wasted wait that makes people distrust the whole feature.+ if plain_size > max {+ return Err(ERR_TOO_LARGE.to_string());+ }+ emit(app, progress_of(job, 0, plain_size, "preparing"));++ let (payload_path, wire_size, sha256, secret) = if job.encrypt {+ let secret = omnidisc_mls::new_file_secret();+ let file_id = job.id.clone();+ let target = tmp_dir()?.join(format!("{}.enc", job.id));+ let source = job.source.clone();+ let target_for_task = target.clone();+ let secret_for_task = secret.clone();+ let (size, sha) = tokio::task::spawn_blocking(move || {+ omnidisc_mls::encrypt_file(&source, &target_for_task, &secret_for_task, &file_id)+ })+ .await+ .map_err(|e| format!("{}:{}", ERR_UPLOAD, e))?+ .map_err(|e| {+ tracing::warn!("[omnidisc] could not encrypt an attachment: {}", e);+ ERR_UPLOAD.to_string()+ })?;+ let wire = omnidisc_mls::encrypted_size(size);+ (target, wire, sha, Some(secret))+ } else {+ (job.source.clone(), plain_size, String::new(), None)+ };++ let cleanup = |path: &PathBuf| {+ if job.encrypt {+ let _ = std::fs::remove_file(path);+ }+ };++ if wire_size > max {+ cleanup(&payload_path);+ return Err(ERR_TOO_LARGE.to_string());+ }++ let mut metadata = vec![+ meta_pair("filename", &job.name),+ meta_pair("channel_id", &job.channel_id),+ ];+ if let Some(mime) = &job.mime {+ metadata.push(meta_pair("filetype", mime));+ }+ if job.encrypt {+ metadata.push(meta_pair("encrypted", "true"));+ }++ let tus = match Tus::new(&job.base) {+ Ok(t) => t,+ Err(e) => {+ cleanup(&payload_path);+ return Err(e);+ }+ };+ let upload_id = match tus.create(wire_size, &metadata.join(",")).await {+ Ok(id) => id,+ Err(e) => {+ cleanup(&payload_path);+ return Err(e);+ }+ };++ let result = push_chunks(app, job, &tus, &upload_id, &payload_path, wire_size, cancel).await;+ cleanup(&payload_path);+ drop_staged(&job.source);+ let attachment = match result {+ Ok(a) => a,+ Err(e) => {+ tus.terminate(&upload_id).await;+ return Err(e);+ }+ };++ Ok(ReadyUpload {+ url: job.base.clone(),+ channel_id: job.channel_id.clone(),+ attachment_id: attachment.id.to_string(),+ file_id: job.id.clone(),+ url_signed: attachment.url.clone(),+ filename: job.name.clone(),+ mime: job.mime.clone(),+ size: plain_size,+ sha256,+ secret,+ })+}++async fn push_chunks(+ app: Progress<'_>,+ job: &Job,+ tus: &Tus,+ upload_id: &str,+ path: &Path,+ total: u64,+ cancel: &CancellationToken,+) -> Result<Attachment, String> {+ use std::io::{Read, Seek, SeekFrom};++ let mut offset = 0u64;+ let mut attempts = 0u32;+ emit(app, progress_of(job, 0, total, "uploading"));+ loop {+ if cancel.is_cancelled() {+ return Err(ERR_CANCELLED.to_string());+ }+ if offset >= total {+ return Err(ERR_SERVER.to_string());+ }+ let want = ((total - offset) as usize).min(PATCH_CHUNK);+ let path = path.to_path_buf();+ let at = offset;+ let chunk = tokio::task::spawn_blocking(move || -> std::io::Result<Vec<u8>> {+ let mut file = std::fs::File::open(&path)?;+ file.seek(SeekFrom::Start(at))?;+ let mut buf = vec![0u8; want];+ file.read_exact(&mut buf)?;+ Ok(buf)+ })+ .await+ .map_err(|e| format!("{}:{}", ERR_UPLOAD, e))?+ .map_err(|e| format!("{}:{}", ERR_UPLOAD, e))?;++ let sent = tokio::select! {+ _ = cancel.cancelled() => return Err(ERR_CANCELLED.to_string()),+ r = tus.patch(upload_id, offset, chunk) => r,+ };+ match sent {+ Ok((_, Some(attachment))) => {+ emit(app, progress_of(job, total, total, "uploading"));+ return Ok(attachment);+ }+ Ok((next, None)) => {+ attempts = 0;+ offset = next;+ emit(app, progress_of(job, offset, total, "uploading"));+ }+ Err(err) if err == ERR_UNREACHABLE && attempts + 1 < RESUME_ATTEMPTS => {+ // A dropped connection is not a failed upload: ask the server+ // where it actually stopped and carry on from there.+ attempts += 1;+ tokio::time::sleep(Duration::from_millis(500 * u64::from(attempts))).await;+ match tus.offset(upload_id).await {+ Ok(server_offset) => {+ offset = server_offset;+ emit(app, progress_of(job, offset, total, "resuming"));+ }+ Err(_) => continue,+ }+ }+ Err(err) => return Err(err),+ }+ }+}++#[tauri::command]+pub async fn omnidisc_instance_limits(url: String) -> Result<InstanceInfo, String> {+ let base = normalize_instance_url(&url)?;+ instance_limits(&base).await+}++/// Pasted or dropped bytes have no path on disk. Staging them under the upload+/// workspace gives the uploader a file to stream, and it is deleted with the+/// rest of the job.+#[tauri::command]+pub async fn omnidisc_stage_file(name: String, bytes: Vec<u8>) -> Result<String, String> {+ let dir = tmp_dir()?.join("staged");+ std::fs::create_dir_all(&dir)+ .map_err(|e| format!("OmniDisc: could not create the upload workspace: {}", e))?;+ let safe = sanitize_filename::sanitize(&name);+ let safe = if safe.trim().is_empty() { "pasted".to_string() } else { safe };+ let path = dir.join(format!("{}-{}", uuid::Uuid::new_v4(), safe));+ std::fs::write(&path, bytes)+ .map_err(|e| format!("OmniDisc: could not stage the file: {}", e))?;+ Ok(path.to_string_lossy().to_string())+}++#[derive(Serialize)]+pub struct StartedUpload {+ pub id: String,+ pub size: u64,+ pub name: String,+}++#[tauri::command]+pub async fn omnidisc_upload_start(+ app: tauri::AppHandle,+ state: tauri::State<'_, crate::AppState>,+ url: String,+ channel_id: String,+ path: String,+ encrypt: bool,+) -> Result<StartedUpload, String> {+ let base = normalize_instance_url(&url)?;+ let source = PathBuf::from(&path);+ if !source.is_file() {+ return Err(format!("{}:file_missing", ERR_BAD_REQUEST));+ }+ // Answer "too big" before the chip ever appears: a limit discovered halfway+ // through an upload reads as a bug, not as a rule.+ let size = std::fs::metadata(&source)+ .map_err(|e| format!("{}:{}", ERR_BAD_REQUEST, unreadable(&source, e)))?+ .len();+ let limits = instance_limits(&base).await?;+ if size > limits.limits.max_upload_bytes.max(limits.max_upload_bytes) {+ return Err(ERR_TOO_LARGE.to_string());+ }+ let name = source+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_else(|| "file".to_string());+ let job = Job {+ id: uuid::Uuid::new_v4().to_string(),+ base,+ channel_id,+ mime: guess_mime(&source),+ name,+ encrypt,+ source,+ };+ let id = job.id.clone();+ let cancel = CancellationToken::new();+ state+ .omnidisc_uploads+ .running+ .lock()+ .await+ .insert(id.clone(), cancel.clone());+ let manager = state.omnidisc_uploads.clone();+ let handle = app.clone();+ let name = job.name.clone();+ tauri::async_runtime::spawn(async move {+ run_job(handle, manager, job, cancel).await;+ });+ Ok(StartedUpload { id, size, name })+}++#[tauri::command]+pub async fn omnidisc_upload_cancel(+ state: tauri::State<'_, crate::AppState>,+ id: String,+) -> Result<(), String> {+ state.omnidisc_uploads.cancel(&id).await;+ Ok(())+}++#[derive(Serialize)]+pub struct DownloadedAttachment {+ pub path: String,+ pub name: String,+}++/// Fetch an attachment to the user's download folder. For an E2EE message the+/// key comes from the local decrypted-message cache, and the SHA-256 written by+/// the sender is checked before the file is handed over.+#[tauri::command]+pub async fn omnidisc_download_attachment(+ state: tauri::State<'_, crate::AppState>,+ url: String,+ attachment_url: Option<String>,+ attachment_id: String,+ filename: String,+ ciphertext: Option<String>,+) -> Result<DownloadedAttachment, String> {+ let base = normalize_instance_url(&url)?;+ let manifest = match &ciphertext {+ Some(ct) => {+ let session = state.omnidisc_mls.session(&base).await?;+ let guard = session.lock().await;+ guard.manifest_for(ct, &attachment_id)+ }+ None => None,+ };+ if ciphertext.is_some() && manifest.is_none() {+ return Err(super::mls::ERR_NO_GROUP_YET.to_string());+ }+ let downloaded =+ fetch_attachment(&base, attachment_url, manifest, &attachment_id, &filename, None).await?;+ let _ = crate::commands::downloads::reveal_file(downloaded.path.clone()).await;+ Ok(downloaded)+}++/// Stream a response straight to disk, aborting the moment it exceeds `budget`.+/// Buffering the body first would let one reply from a hostile server exhaust+/// the app's memory, and the body is attacker-controlled by definition here.+async fn download_to(source: &url::Url, target: &Path, budget: u64) -> Result<(), String> {+ use futures::StreamExt;+ use tokio::io::AsyncWriteExt;++ let http = http_client(Duration::from_secs(300))?;+ let response = http.get(source.clone()).send().await.map_err(|e| {+ tracing::warn!("[omnidisc] attachment download failed: {}", e);+ ERR_UNREACHABLE.to_string()+ })?;+ if !response.status().is_success() {+ return Err(super::api::map_error(response.status(), ""));+ }+ if response.content_length().is_some_and(|len| len > budget) {+ return Err(ERR_ATTACHMENT_TOO_LARGE.to_string());+ }+ let mut file = tokio::fs::File::create(target)+ .await+ .map_err(|e| format!("OmniDisc: could not write the download: {}", e))?;+ let mut stream = response.bytes_stream();+ let mut written: u64 = 0;+ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| {+ tracing::warn!("[omnidisc] attachment download interrupted: {}", e);+ ERR_UNREACHABLE.to_string()+ })?;+ written = written.saturating_add(chunk.len() as u64);+ if written > budget {+ drop(file);+ let _ = tokio::fs::remove_file(target).await;+ tracing::warn!("[omnidisc] an attachment kept sending past its stated size");+ return Err(ERR_ATTACHMENT_TOO_LARGE.to_string());+ }+ file.write_all(&chunk)+ .await+ .map_err(|e| format!("OmniDisc: could not write the download: {}", e))?;+ }+ file.flush()+ .await+ .map_err(|e| format!("OmniDisc: could not write the download: {}", e))?;+ Ok(())+}++/// The origins an attachment may legitimately come from: the instance itself+/// and the media host it advertises. The URL in a manifest is written by+/// whoever sent the message, so without this an attachment is an arbitrary+/// fetch made by this app, with this app's network position.+fn attachment_origins(base: &str, limits: &InstanceInfo) -> Vec<url::Origin> {+ let mut origins = Vec::new();+ if let Ok(parsed) = url::Url::parse(base) {+ origins.push(parsed.origin());+ }+ if let Ok(media) = url::Url::parse(&limits.media_url) {+ origins.push(media.origin());+ }+ origins+}++fn origin_allowed(source: &url::Url, allowed: &[url::Origin]) -> bool {+ matches!(source.scheme(), "http" | "https") && allowed.contains(&source.origin())+}++/// A download is bounded by what the sender said the file is, plus the AEAD+/// overhead — never by whatever the server decides to keep sending.+fn download_budget(manifest: Option<&FileManifest>, instance_max: u64) -> u64 {+ match manifest {+ Some(m) => omnidisc_mls::encrypted_size(m.size).saturating_add(DOWNLOAD_SLACK),+ None => instance_max.max(DOWNLOAD_FALLBACK_CAP),+ }+}++/// Download, decrypt and verify. `into` overrides the destination folder, which+/// the integration test uses to stay out of the developer's Downloads.+pub async fn fetch_attachment(+ base: &str,+ attachment_url: Option<String>,+ manifest: Option<FileManifest>,+ attachment_id: &str,+ filename: &str,+ into: Option<PathBuf>,+) -> Result<DownloadedAttachment, String> {+ let name = sanitize_filename::sanitize(+ manifest.as_ref().map(|m| m.name.as_str()).unwrap_or(filename),+ );+ let name = if name.trim().is_empty() { "download".to_string() } else { name };+ let target_dir = match into {+ Some(dir) => dir,+ None => dirs::download_dir()+ .ok_or_else(|| "OmniDisc: could not find your downloads folder".to_string())?,+ };+ std::fs::create_dir_all(&target_dir)+ .map_err(|e| format!("OmniDisc: could not create the downloads folder: {}", e))?;+ let target = unique_path(&target_dir, &name);++ let source_url = manifest+ .as_ref()+ .map(|m| m.url.clone())+ .filter(|u| !u.is_empty())+ .or(attachment_url)+ .ok_or_else(|| format!("{}:no_attachment_url", ERR_BAD_REQUEST))?;+ let parsed = url::Url::parse(&source_url)+ .map_err(|_| format!("{}:bad_attachment_url", ERR_BAD_REQUEST))?;+ let limits = instance_limits(base).await?;+ if !origin_allowed(&parsed, &attachment_origins(base, &limits)) {+ tracing::warn!("[omnidisc] refused an attachment hosted outside {}", base);+ return Err(ERR_ATTACHMENT_ORIGIN.to_string());+ }+ let budget = download_budget(+ manifest.as_ref(),+ limits.limits.max_upload_bytes.max(limits.max_upload_bytes),+ );+ let tmp = tmp_dir()?.join(format!("{}.dl", attachment_id));+ let _ = std::fs::remove_file(&tmp);+ download_to(&parsed, &tmp, budget).await?;++ match manifest {+ Some(manifest) => {+ let secret = decode_secret(&manifest)?;+ let expected = manifest.sha256.clone();+ let size = manifest.size;+ let file_id = if manifest.file_id.is_empty() {+ manifest.attachment_id.clone()+ } else {+ manifest.file_id.clone()+ };+ let tmp_for_task = tmp.clone();+ let target_for_task = target.clone();+ let got = tokio::task::spawn_blocking(move || {+ omnidisc_mls::decrypt_file(+ &tmp_for_task,+ &target_for_task,+ &secret,+ &file_id,+ size,+ )+ })+ .await+ .map_err(|e| format!("{}:{}", ERR_UPLOAD, e))?;+ let _ = std::fs::remove_file(&tmp);+ let got = got.map_err(|e| {+ tracing::warn!("[omnidisc] attachment failed to decrypt: {}", e);+ let _ = std::fs::remove_file(&target);+ "ERR_ATTACHMENT_CORRUPT".to_string()+ })?;+ if !expected.is_empty() && got != expected {+ let _ = std::fs::remove_file(&target);+ return Err("ERR_ATTACHMENT_CORRUPT".to_string());+ }+ }+ None => {+ std::fs::rename(&tmp, &target)+ .or_else(|_| std::fs::copy(&tmp, &target).map(|_| ()))+ .map_err(|e| format!("OmniDisc: could not write the download: {}", e))?;+ let _ = std::fs::remove_file(&tmp);+ }+ }++ let path = target.to_string_lossy().to_string();+ Ok(DownloadedAttachment { path, name })+}++fn decode_secret(manifest: &FileManifest) -> Result<FileSecret, String> {+ let engine = base64::engine::general_purpose::STANDARD;+ let key = engine+ .decode(&manifest.key)+ .ok()+ .filter(|b| b.len() == 32)+ .ok_or_else(|| "ERR_ATTACHMENT_CORRUPT".to_string())?;+ let nonce = engine+ .decode(&manifest.nonce)+ .ok()+ .filter(|b| b.len() == 16)+ .ok_or_else(|| "ERR_ATTACHMENT_CORRUPT".to_string())?;+ let mut secret = FileSecret { key: [0u8; 32], nonce: [0u8; 16] };+ secret.key.copy_from_slice(&key);+ secret.nonce.copy_from_slice(&nonce);+ Ok(secret)+}++fn unique_path(dir: &Path, name: &str) -> PathBuf {+ let candidate = dir.join(name);+ if !candidate.exists() {+ return candidate;+ }+ let stem = Path::new(name)+ .file_stem()+ .map(|s| s.to_string_lossy().to_string())+ .unwrap_or_else(|| name.to_string());+ let ext = Path::new(name).extension().map(|e| e.to_string_lossy().to_string());+ for n in 2..1000 {+ let candidate = match &ext {+ Some(ext) => dir.join(format!("{stem} ({n}).{ext}")),+ None => dir.join(format!("{stem} ({n})")),+ };+ if !candidate.exists() {+ return candidate;+ }+ }+ dir.join(name)+}++/// A staged (pasted or dropped) source belongs to us, so it goes away with the+/// upload. A file the user picked from disk is theirs and is left alone.+fn drop_staged(source: &Path) {+ let Ok(staged) = tmp_dir().map(|d| d.join("staged")) else { return };+ if source.starts_with(&staged) {+ let _ = std::fs::remove_file(source);+ }+}++fn unreadable(path: &Path, e: std::io::Error) -> String {+ tracing::warn!("[omnidisc] cannot read {}: {}", path.display(), e);+ "file_missing".to_string()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn manifest(size: u64, url: &str) -> FileManifest {+ FileManifest {+ attachment_id: "42".into(),+ file_id: "f".into(),+ url: url.into(),+ name: "cat.png".into(),+ mime: None,+ size,+ sha256: String::new(),+ key: String::new(),+ nonce: String::new(),+ }+ }++ fn limits(media_url: &str) -> InstanceInfo {+ InstanceInfo {+ name: "test".into(),+ version: "0".into(),+ media_url: media_url.into(),+ sfu_url: String::new(),+ max_upload_bytes: 100 * 1024 * 1024,+ streaming: Default::default(),+ limits: Default::default(),+ registration_open: false,+ }+ }++ /// The attachment URL is written by whoever sent the message, so without an+ /// origin check a message is a way to make this app fetch anything at all —+ /// including hosts only this machine can reach.+ #[test]+ fn attachments_only_come_from_the_instance_or_its_media_host() {+ let base = "https://chat.example.org";+ let allowed = attachment_origins(base, &limits("https://media.example.org"));+ let ok = |u: &str| origin_allowed(&url::Url::parse(u).expect("url"), &allowed);+ assert!(ok("https://chat.example.org/api/uploads/42"));+ assert!(ok("https://media.example.org/attachments/42/cat.png?sig=x"));+ assert!(!ok("https://evil.example.net/attachments/42/cat.png"));+ assert!(!ok("http://chat.example.org/api/uploads/42"), "scheme is part of the origin");+ assert!(!ok("https://chat.example.org:8443/api/uploads/42"), "port is part of the origin");+ assert!(!ok("http://127.0.0.1:9200/_search"));+ assert!(!ok("file:///etc/passwd"));+ }++ /// `response.bytes()` used to buffer whatever the server sent; the budget is+ /// what turns "the sender said 4 MB" into a hard stop.+ #[test]+ fn downloads_are_budgeted_by_what_the_sender_declared() {+ let four_mb = 4 * 1024 * 1024;+ let budget = download_budget(Some(&manifest(four_mb, "")), u64::MAX);+ assert!(budget >= omnidisc_mls::encrypted_size(four_mb));+ assert!(budget < four_mb + 2 * DOWNLOAD_SLACK);+ // An empty file still gets its header and tag through.+ assert!(download_budget(Some(&manifest(0, "")), 0) >= omnidisc_mls::encrypted_size(0));+ // Nothing declared: the instance cap, never unbounded.+ assert_eq!(download_budget(None, 0), DOWNLOAD_FALLBACK_CAP);+ assert_eq!(download_budget(None, u64::MAX), u64::MAX);+ }++ #[test]+ fn metadata_is_base64_per_tus() {+ let pair = meta_pair("filename", "cat.png");+ assert_eq!(pair, "filename Y2F0LnBuZw==");+ let (key, value) = pair.split_once(' ').expect("pair");+ assert_eq!(key, "filename");+ let decoded = base64::engine::general_purpose::STANDARD.decode(value).expect("b64");+ assert_eq!(decoded, b"cat.png");+ }++ #[test]+ fn mime_guesses_cover_what_the_ui_renders_inline() {+ assert_eq!(guess_mime(Path::new("a/b/cat.PNG")).as_deref(), Some("image/png"));+ assert_eq!(guess_mime(Path::new("clip.mp4")).as_deref(), Some("video/mp4"));+ assert_eq!(guess_mime(Path::new("song.flac")).as_deref(), Some("audio/flac"));+ assert_eq!(guess_mime(Path::new("archive.7z")), None);+ assert_eq!(guess_mime(Path::new("noext")), None);+ }++ #[test]+ fn downloads_never_overwrite_an_existing_file() {+ let dir = std::env::temp_dir().join(format!("omnidisc-dl-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).expect("dir");+ assert_eq!(unique_path(&dir, "cat.png"), dir.join("cat.png"));+ std::fs::write(dir.join("cat.png"), b"x").expect("write");+ assert_eq!(unique_path(&dir, "cat.png"), dir.join("cat (2).png"));+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn secrets_are_only_accepted_at_the_right_size() {+ let engine = base64::engine::general_purpose::STANDARD;+ let good = FileManifest {+ attachment_id: "1".into(),+ file_id: "1".into(),+ url: String::new(),+ name: "a".into(),+ mime: None,+ size: 1,+ sha256: String::new(),+ key: engine.encode([1u8; 32]),+ nonce: engine.encode([2u8; 16]),+ };+ assert!(decode_secret(&good).is_ok());+ let short = FileManifest { key: engine.encode([1u8; 16]), ..good.clone() };+ assert!(decode_secret(&short).is_err());+ let bad = FileManifest { nonce: "!!!".into(), ..good };+ assert!(decode_secret(&bad).is_err());+ }+}diff --git a/src-tauri/src/commands/omnidisc/voice.rs b/src-tauri/src/commands/omnidisc/voice.rsnew file mode 100644index 00000000..f9aa3792--- /dev/null+++ b/src-tauri/src/commands/omnidisc/voice.rs@@ -0,0 +1,669 @@+use super::gateway::{self, ERR_NOT_CONNECTED};+use super::normalize_instance_url;+use omnidisc_media::{+ AudioDevices, AudioPrefs, ConnectOptions, DeviceKind, LiveKitBackend, MediaEngine, NullBackend, RoomKey,+ VoiceState, VoiceStats,+};+use omnidisc_proto::gateway::{Opcode, VoiceServerUpdate};+use serde::Serialize;+use serde_json::{json, Value};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex as StdMutex};+use std::time::Duration;+use tauri::{Emitter, Manager};+use tokio::sync::{oneshot, Mutex};++pub const EVENT_VOICE: &str = "omnidisc://voice";+pub const ERR_VOICE_TIMEOUT: &str = "ERR_VOICE_TIMEOUT";+pub const ERR_VOICE_DENIED: &str = "ERR_VOICE_DENIED";+pub const ERR_VOICE_DM_UNSUPPORTED: &str = "ERR_VOICE_DM_UNSUPPORTED";+pub const ERR_VOICE_NOT_CONNECTED: &str = "ERR_VOICE_NOT_CONNECTED";++const SERVER_UPDATE_TIMEOUT: Duration = Duration::from_secs(10);++#[derive(Debug, Clone, Serialize)]+pub struct VoiceSessionInfo {+ pub url: String,+ /// `None` for a DM or group-DM call.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub guild_id: Option<String>,+ pub channel_id: String,+ /// The SFU room name. It is also the domain separator the MLS exporter is+ /// bound to, so both ends derive the same voice key without agreeing on+ /// anything extra.+ pub room: String,+ /// Whether frames on this call are end-to-end encrypted. Never guessed:+ /// it is true only when a room key was actually handed to the cryptor.+ pub e2ee: bool,+}++#[derive(Debug, Clone, Copy, Default)]+struct Flags {+ muted: bool,+ deafened: bool,+ muted_before_deafen: bool,+ streaming: bool,+}++struct PendingJoin {+ url: String,+ channel_id: String,+ tx: oneshot::Sender<Result<VoiceServerUpdate, String>>,+}++#[derive(Debug, Clone, Serialize)]+pub struct VoiceStatus {+ pub state: VoiceState,+ pub muted: bool,+ pub deafened: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub session: Option<VoiceSessionInfo>,+ pub backend_available: bool,+}++#[derive(Debug, Clone, Serialize)]+pub struct JoinResult {+ pub state: VoiceState,+ pub session: VoiceSessionInfo,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mic_error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub output_error: Option<String>,+}++pub struct VoiceManager {+ engine: Arc<MediaEngine>,+ backend: Option<Arc<omnidisc_media::LiveKitBackend>>,+ backend_available: bool,+ session: Mutex<Option<VoiceSessionInfo>>,+ pending: StdMutex<Option<PendingJoin>>,+ flags: StdMutex<Flags>,+ started: AtomicBool,+}++impl Default for VoiceManager {+ fn default() -> Self {+ Self::new()+ }+}++impl VoiceManager {+ pub fn new() -> Self {+ let (engine, backend, backend_available) = match LiveKitBackend::new() {+ Ok(backend) => {+ let backend = Arc::new(backend);+ (MediaEngine::new(backend.clone()), Some(backend), true)+ }+ Err(e) => {+ tracing::error!("[omnidisc] voice backend unavailable: {}", e);+ (MediaEngine::new(Arc::new(NullBackend)), None, false)+ }+ };+ Self {+ engine: Arc::new(engine),+ backend,+ backend_available,+ session: Mutex::new(None),+ pending: StdMutex::new(None),+ flags: StdMutex::new(Flags::default()),+ started: AtomicBool::new(false),+ }+ }++ pub fn engine(&self) -> &Arc<MediaEngine> {+ &self.engine+ }++ pub fn livekit_backend(&self) -> Option<Arc<omnidisc_media::LiveKitBackend>> {+ self.backend.clone()+ }++ pub async fn session_info(&self) -> Option<VoiceSessionInfo> {+ self.session.lock().await.clone()+ }++ fn flags(&self) -> Flags {+ self.flags.lock().map(|f| *f).unwrap_or_default()+ }++ fn set_flags(&self, f: Flags) {+ if let Ok(mut g) = self.flags.lock() {+ *g = f;+ }+ }++ async fn session_url(&self) -> Option<String> {+ self.session.lock().await.as_ref().map(|s| s.url.clone())+ }++ fn take_pending_if(&self, url: &str, channel_id: Option<&str>) -> Option<PendingJoin> {+ let mut guard = self.pending.lock().ok()?;+ let matches = guard+ .as_ref()+ .map(|p| p.url == url && channel_id.map(|c| c == p.channel_id).unwrap_or(true))+ .unwrap_or(false);+ if matches {+ guard.take()+ } else {+ None+ }+ }++ pub fn resolve_server_update(&self, url: &str, update: VoiceServerUpdate) {+ if let Some(p) = self.take_pending_if(url, Some(&update.channel_id.to_string())) {+ let _ = p.tx.send(Ok(update));+ }+ }++ pub fn reject_pending(&self, url: &str, reason: String) {+ if let Some(p) = self.take_pending_if(url, None) {+ let _ = p.tx.send(Err(reason));+ }+ }+}++pub fn on_dispatch(app: &tauri::AppHandle, url: &str, t: &str, d: &Value) {+ let Some(state) = app.try_state::<crate::AppState>() else { return };+ match t {+ "READY" | "RESUMED" => {+ let manager = state.omnidisc_voice.clone();+ let gateways = state.omnidisc_gateways.clone();+ let url = url.to_string();+ tauri::async_runtime::spawn(async move {+ let session = manager.session.lock().await.clone();+ let Some(s) = session.filter(|s| s.url == url) else { return };+ if manager.engine.state().await != VoiceState::Connected {+ return;+ }+ tokio::time::sleep(Duration::from_millis(200)).await;+ let flags = manager.flags();+ if let Err(e) = send_voice_state(&gateways, &s.url, s.guild_id.as_deref(), Some(&s.channel_id), flags).await {+ tracing::debug!("[omnidisc] voice state not re-announced after resume: {}", e);+ }+ });+ }+ "VOICE_SERVER_UPDATE" => match serde_json::from_value::<VoiceServerUpdate>(d.clone()) {+ Ok(update) => state.omnidisc_voice.resolve_server_update(url, update),+ Err(e) => tracing::warn!("[omnidisc] malformed VOICE_SERVER_UPDATE from {}: {}", url, e),+ },+ "GATEWAY_ERROR" => {+ if d.get("code").and_then(Value::as_str) == Some("voice") {+ let reason = d.get("message").and_then(Value::as_str).unwrap_or("").to_string();+ tracing::warn!("[omnidisc] voice request rejected by {}: {}", url, reason);+ state.omnidisc_voice.reject_pending(url, ERR_VOICE_DENIED.to_string());+ }+ }+ _ => {}+ }+}++pub fn start(app: &tauri::AppHandle) {+ let Some(state) = app.try_state::<crate::AppState>() else { return };+ let manager = state.omnidisc_voice.clone();+ if manager.started.swap(true, Ordering::AcqRel) {+ return;+ }+ let pump_engine = manager.engine.clone();+ tauri::async_runtime::spawn(async move { pump_engine.pump().await });+ let app = app.clone();+ let forward = manager.clone();+ tauri::async_runtime::spawn(async move {+ let mut rx = forward.engine.subscribe();+ loop {+ match rx.recv().await {+ Ok(n) => {+ let url = forward.session_url().await;+ let mut payload = serde_json::to_value(&n).unwrap_or(Value::Null);+ if let Value::Object(map) = &mut payload {+ map.insert("url".into(), url.map(Value::String).unwrap_or(Value::Null));+ }+ let _ = app.emit(EVENT_VOICE, payload);+ }+ Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {+ tracing::debug!("[omnidisc] voice event forwarder lagged by {}", n);+ }+ Err(tokio::sync::broadcast::error::RecvError::Closed) => break,+ }+ }+ });+}++pub fn ptt_from_hotkey(app: &tauri::AppHandle, pressed: bool) {+ let Some(state) = app.try_state::<crate::AppState>() else { return };+ let manager = state.omnidisc_voice.clone();+ tauri::async_runtime::spawn(async move {+ if let Err(e) = manager.engine.set_ptt(true, pressed).await {+ tracing::debug!("[omnidisc] ptt: {}", e);+ }+ });+}++fn prefs_from_settings(app: &tauri::AppHandle) -> (AudioPrefs, bool) {+ let s = crate::storage::config::load_settings(app).omnidisc.voice;+ let relay_only = s.relay_only;+ (+ AudioPrefs {+ input_device: s.input_device.filter(|d| !d.trim().is_empty()),+ output_device: s.output_device.filter(|d| !d.trim().is_empty()),+ noise_suppression: s.noise_suppression,+ ptt_enabled: !s.ptt_key.trim().is_empty(),+ vad_threshold_db: Some(s.vad_threshold_db),+ ducking_percent: s.ducking_percent.min(100),+ },+ relay_only,+ )+}++async fn send_voice_state(+ gateways: &gateway::Gateways,+ url: &str,+ guild_id: Option<&str>,+ channel_id: Option<&str>,+ flags: Flags,+) -> Result<(), String> {+ gateway::send(+ gateways,+ url,+ Opcode::VoiceStateUpdate as u8,+ json!({+ "guild_id": guild_id,+ "channel_id": channel_id,+ "self_mute": flags.muted,+ "self_deaf": flags.deafened,+ "self_stream": flags.streaming,+ }),+ )+ .await+}++impl VoiceManager {+ pub fn set_streaming(&self, on: bool) {+ if let Ok(mut g) = self.flags.lock() {+ g.streaming = on;+ }+ }++ pub async fn announce_stream(&self, gateways: &gateway::Gateways) {+ push_flags(self, gateways).await;+ }+}++async fn leave_current(manager: &VoiceManager, gateways: &gateway::Gateways) {+ let previous = manager.session.lock().await.take();+ if let Err(e) = manager.engine.leave().await {+ tracing::warn!("[omnidisc] voice leave: {}", e);+ }+ if let Some(s) = previous {+ let flags = manager.flags();+ if let Err(e) = send_voice_state(gateways, &s.url, s.guild_id.as_deref(), None, flags).await {+ tracing::debug!("[omnidisc] voice leave not sent to {}: {}", s.url, e);+ }+ }+}++#[tauri::command]+pub async fn omnidisc_voice_join(+ app: tauri::AppHandle,+ state: tauri::State<'_, crate::AppState>,+ url: String,+ guild_id: Option<String>,+ channel_id: String,+ recipient_ids: Option<Vec<String>>,+) -> Result<JoinResult, String> {+ let base = normalize_instance_url(&url)?;+ let guild_id = guild_id.map(|g| g.trim().to_string()).filter(|g| !g.is_empty());+ let manager = state.omnidisc_voice.clone();+ if !gateway::is_ready(&state.omnidisc_gateways, &base).await {+ return Err(ERR_NOT_CONNECTED.to_string());+ }++ {+ let current = manager.session.lock().await.clone();+ if let Some(s) = current {+ if s.url == base && s.channel_id == channel_id && manager.engine.state().await == VoiceState::Connected {+ return Ok(JoinResult { state: VoiceState::Connected, session: s, mic_error: None, output_error: None });+ }+ leave_current(&manager, &state.omnidisc_gateways).await;+ }+ }++ let (tx, rx) = oneshot::channel();+ if let Ok(mut p) = manager.pending.lock() {+ *p = Some(PendingJoin { url: base.clone(), channel_id: channel_id.clone(), tx });+ }+ let flags = manager.flags();+ if let Err(e) =+ send_voice_state(&state.omnidisc_gateways, &base, guild_id.as_deref(), Some(&channel_id), flags).await+ {+ let _ = manager.take_pending_if(&base, None);+ return Err(e);+ }+ // The gateway was ready before we sent, so silence on a DM means the server+ // predates DM calls and dropped op 4 without a guild — say that instead of+ // a bare timeout.+ let timeout_code = if guild_id.is_some() { ERR_VOICE_TIMEOUT } else { ERR_VOICE_DM_UNSUPPORTED };+ let update = match tokio::time::timeout(SERVER_UPDATE_TIMEOUT, rx).await {+ Ok(Ok(Ok(update))) => update,+ Ok(Ok(Err(reason))) => return Err(reason),+ Ok(Err(_)) => return Err(timeout_code.to_string()),+ Err(_) => {+ let _ = manager.take_pending_if(&base, None);+ return Err(timeout_code.to_string());+ }+ };++ // The key never leaves this process and never touches the server: it is+ // exported from the channel's MLS group, bound to the room name. No group+ // means no key, which means an honest "not encrypted" in the UI.+ let establish = recipient_ids.as_deref().filter(|r| !r.is_empty());+ let room_key = super::mls::voice_key_for(&state.omnidisc_mls, &base, &channel_id, establish)+ .await+ .map(|(epoch, key)| RoomKey::new(epoch, key));+ let session = VoiceSessionInfo {+ url: base.clone(),+ guild_id: guild_id.clone(),+ channel_id: channel_id.clone(),+ room: update.room.clone(),+ e2ee: room_key.is_some(),+ };+ *manager.session.lock().await = Some(session.clone());+ let (prefs, relay_only) = prefs_from_settings(&app);+ let options = ConnectOptions { room_key, relay_only };+ match manager.engine.join(&update, &prefs, &options).await {+ Ok(outcome) => {+ let _ = manager.engine.set_muted(flags.muted).await;+ let _ = manager.engine.set_deafened(flags.deafened).await;+ Ok(JoinResult {+ state: VoiceState::Connected,+ session,+ mic_error: outcome.mic_error,+ output_error: outcome.output_error,+ })+ }+ Err(e) => {+ *manager.session.lock().await = None;+ let _ = send_voice_state(&state.omnidisc_gateways, &base, guild_id.as_deref(), None, flags).await;+ Err(e.code().to_string())+ }+ }+}++/// Which channel this app is talking in on `base`. Used by the MLS layer to+/// rekey an active call; the key is bound to the channel id and not to the+/// room name, which the server chooses.+pub async fn channel_in_call_on(app: &tauri::AppHandle, base: &str) -> Option<String> {+ let state = app.try_state::<crate::AppState>()?;+ let session = state.omnidisc_voice.session_info().await?;+ (session.url == base && session.e2ee).then_some(session.channel_id)+}++/// Push a freshly exported epoch key into the running call.+pub async fn push_room_key(app: &tauri::AppHandle, epoch: u64, key: [u8; 32]) {+ let Some(state) = app.try_state::<crate::AppState>() else { return };+ if let Err(e) = state.omnidisc_voice.engine.set_room_key(RoomKey::new(epoch, key)).await {+ tracing::warn!("[omnidisc] the voice key could not be rotated: {}", e);+ }+}++#[tauri::command]+pub async fn omnidisc_voice_leave(state: tauri::State<'_, crate::AppState>) -> Result<(), String> {+ leave_current(&state.omnidisc_voice, &state.omnidisc_gateways).await;+ Ok(())+}++async fn push_flags(manager: &VoiceManager, gateways: &gateway::Gateways) {+ let flags = manager.flags();+ let session = manager.session.lock().await.clone();+ if let Some(s) = session {+ if let Err(e) = send_voice_state(gateways, &s.url, s.guild_id.as_deref(), Some(&s.channel_id), flags).await {+ tracing::debug!("[omnidisc] voice flags not sent: {}", e);+ }+ }+}++#[tauri::command]+pub async fn omnidisc_voice_set_mute(state: tauri::State<'_, crate::AppState>, muted: bool) -> Result<VoiceStatus, String> {+ let manager = state.omnidisc_voice.clone();+ let mut flags = manager.flags();+ flags.muted = muted;+ if !muted && flags.deafened {+ flags.deafened = false;+ manager.engine.set_deafened(false).await.map_err(|e| e.code().to_string())?;+ }+ manager.set_flags(flags);+ manager.engine.set_muted(muted).await.map_err(|e| e.code().to_string())?;+ push_flags(&manager, &state.omnidisc_gateways).await;+ status_of(&manager).await+}++#[tauri::command]+pub async fn omnidisc_voice_set_deaf(state: tauri::State<'_, crate::AppState>, deafened: bool) -> Result<VoiceStatus, String> {+ let manager = state.omnidisc_voice.clone();+ let mut flags = manager.flags();+ if deafened && !flags.deafened {+ flags.muted_before_deafen = flags.muted;+ flags.muted = true;+ } else if !deafened && flags.deafened {+ flags.muted = flags.muted_before_deafen;+ }+ flags.deafened = deafened;+ manager.set_flags(flags);+ manager.engine.set_deafened(deafened).await.map_err(|e| e.code().to_string())?;+ manager.engine.set_muted(flags.muted).await.map_err(|e| e.code().to_string())?;+ push_flags(&manager, &state.omnidisc_gateways).await;+ status_of(&manager).await+}++#[tauri::command]+pub async fn omnidisc_voice_set_volume(+ state: tauri::State<'_, crate::AppState>,+ user_id: String,+ gain: f32,+) -> Result<(), String> {+ if !gain.is_finite() {+ return Err("ERR_BAD_REQUEST".to_string());+ }+ state+ .omnidisc_voice+ .engine+ .set_participant_volume(&user_id, gain.clamp(0.0, 2.0))+ .await+ .map_err(|e| e.code().to_string())+}++#[tauri::command]+pub async fn omnidisc_voice_devices(state: tauri::State<'_, crate::AppState>) -> Result<AudioDevices, String> {+ let engine = state.omnidisc_voice.engine.clone();+ tokio::task::spawn_blocking(move || engine.devices())+ .await+ .map_err(|e| format!("OmniDisc: device enumeration failed: {}", e))+}++#[tauri::command]+pub async fn omnidisc_voice_set_device(+ state: tauri::State<'_, crate::AppState>,+ kind: DeviceKind,+ id: Option<String>,+) -> Result<(), String> {+ state.omnidisc_voice.engine.set_device(kind, id).await.map_err(|e| e.code().to_string())+}++#[tauri::command]+pub async fn omnidisc_voice_stats(state: tauri::State<'_, crate::AppState>) -> Result<VoiceStats, String> {+ state.omnidisc_voice.engine.stats().await.map_err(|e| e.code().to_string())+}++#[tauri::command]+pub async fn omnidisc_voice_ptt(+ app: tauri::AppHandle,+ state: tauri::State<'_, crate::AppState>,+ pressed: bool,+) -> Result<(), String> {+ let enabled = !crate::storage::config::load_settings(&app).omnidisc.voice.ptt_key.trim().is_empty();+ state.omnidisc_voice.engine.set_ptt(enabled, pressed).await.map_err(|e| e.code().to_string())+}++#[tauri::command]+pub async fn omnidisc_voice_set_noise_suppression(+ state: tauri::State<'_, crate::AppState>,+ enabled: bool,+) -> Result<(), String> {+ state.omnidisc_voice.engine.set_noise_suppression(enabled).await.map_err(|e| e.code().to_string())+}++#[tauri::command]+pub async fn omnidisc_voice_set_ducking(+ state: tauri::State<'_, crate::AppState>,+ percent: u8,+) -> Result<(), String> {+ state+ .omnidisc_voice+ .engine+ .set_ducking(percent.min(100))+ .await+ .map_err(|e| e.code().to_string())+}++#[tauri::command]+pub async fn omnidisc_voice_mic_test(state: tauri::State<'_, crate::AppState>, enabled: bool) -> Result<(), String> {+ state.omnidisc_voice.engine.set_mic_monitor(enabled).await.map_err(|e| e.code().to_string())+}++async fn status_of(manager: &VoiceManager) -> Result<VoiceStatus, String> {+ let flags = manager.flags();+ Ok(VoiceStatus {+ state: manager.engine.state().await,+ muted: flags.muted,+ deafened: flags.deafened,+ session: manager.session.lock().await.clone(),+ backend_available: manager.backend_available,+ })+}++#[tauri::command]+pub async fn omnidisc_voice_status(state: tauri::State<'_, crate::AppState>) -> Result<VoiceStatus, String> {+ status_of(&state.omnidisc_voice).await+}++#[cfg(test)]+mod tests {+ use super::*;+ use omnidisc_proto::Snowflake;++ fn update(channel: u64) -> VoiceServerUpdate {+ VoiceServerUpdate {+ guild_id: Some(Snowflake(1)),+ channel_id: Snowflake(channel),+ endpoint: "ws://sfu".into(),+ token: "t".into(),+ room: "r".into(),+ ice_servers: vec![],+ }+ }++ /// The plumbing that turns an MLS epoch into a `set_shared_key` call. The+ /// MLS derivation itself is tested in `omnidisc-mls`; what matters here is+ /// that two members feed the ring the same bytes and that a commit moves+ /// the index.+ #[test]+ fn an_epoch_change_rotates_the_key_ring_the_same_way_for_both_members() {+ use omnidisc_media::{KeyRing, KeyRotation, RoomKey};+ use omnidisc_mls::{ClaimedDevice, DeviceRef, MlsClient};+ use std::sync::{Arc, Mutex as StdMutex};++ #[derive(Default)]+ struct Recorder(StdMutex<Vec<(i32, Vec<u8>)>>);+ impl KeyRing for Recorder {+ fn set_shared_key(&self, key: &[u8], index: i32) {+ if let Ok(mut c) = self.0.lock() {+ c.push((index, key.to_vec()));+ }+ }+ }++ const GROUP: &str = "od-42";+ const ROOM: &[u8] = b"dm-c42";+ let mut alice = MlsClient::new("1001", "desktop-a", &[71u8; 32]).expect("alice");+ let mut bob = MlsClient::new("2002", "phone-bbb", &[72u8; 32]).expect("bob");+ let mut carol = MlsClient::new("3003", "tablet-cc", &[73u8; 32]).expect("carol");+ alice.create_group(GROUP).expect("group");+ let claim = |c: &mut MlsClient| ClaimedDevice {+ device: DeviceRef::new(c.user_id(), c.device_id(), c.public_key().to_vec()),+ key_package: c.key_packages(1, false).expect("kp").remove(0),+ };+ let alice_ref = DeviceRef::new(alice.user_id(), alice.device_id(), alice.public_key().to_vec());+ let bob_kp = claim(&mut bob);+ let welcome = alice.add_members(GROUP, &[bob_kp]).expect("add");+ alice.merge_pending(GROUP).expect("merge");+ bob.join_welcome(&welcome.welcome.clone().expect("welcome"), GROUP, &[alice_ref])+ .expect("join");++ let epoch = alice.epoch(GROUP).expect("epoch");+ assert_eq!(epoch, bob.epoch(GROUP).expect("epoch"));+ let key_a = alice.voice_key(GROUP, ROOM).expect("key");+ assert_eq!(key_a, bob.voice_key(GROUP, ROOM).expect("key"));++ let ring_a = Arc::new(Recorder::default());+ let ring_b = Arc::new(Recorder::default());+ let rot_a = KeyRotation::new();+ let rot_b = KeyRotation::new();+ rot_a.arm(ring_a.clone(), RoomKey::new(epoch, key_a));+ rot_b.arm(ring_b.clone(), RoomKey::new(epoch, bob.voice_key(GROUP, ROOM).expect("key")));++ let carol_kp = claim(&mut carol);+ let commit = alice.add_members(GROUP, &[carol_kp]).expect("add carol");+ alice.merge_pending(GROUP).expect("merge");+ bob.process(GROUP, &commit.commit).expect("bob processes the commit");++ let next = alice.epoch(GROUP).expect("epoch");+ assert_eq!(next, epoch + 1);+ let key_next = alice.voice_key(GROUP, ROOM).expect("key");+ assert_ne!(key_next, key_a, "the key must change with the epoch");+ assert_eq!(key_next, bob.voice_key(GROUP, ROOM).expect("key"));++ assert!(rot_a.apply(RoomKey::new(next, key_next)));+ assert!(rot_b.apply(RoomKey::new(next, bob.voice_key(GROUP, ROOM).expect("key"))));+ let calls_a = ring_a.0.lock().expect("lock").clone();+ let calls_b = ring_b.0.lock().expect("lock").clone();+ assert_eq!(calls_a, calls_b, "both members key the ring identically");+ assert_eq!(calls_a.len(), 2);+ assert_eq!(calls_a[0].0, (epoch % 16) as i32);+ assert_eq!(calls_a[1].0, (next % 16) as i32);+ assert_ne!(calls_a[0].1, calls_a[1].1);+ }++ #[tokio::test]+ async fn server_update_resolves_only_the_matching_pending_join() {+ let manager = VoiceManager::new();+ let (tx, rx) = oneshot::channel();+ *manager.pending.lock().unwrap() = Some(PendingJoin { url: "https://a".into(), channel_id: "7".into(), tx });+ manager.resolve_server_update("https://b", update(7));+ assert!(manager.pending.lock().unwrap().is_some());+ manager.resolve_server_update("https://a", update(8));+ assert!(manager.pending.lock().unwrap().is_some());+ manager.resolve_server_update("https://a", update(7));+ assert!(manager.pending.lock().unwrap().is_none());+ assert_eq!(rx.await.unwrap().unwrap().channel_id, Snowflake(7));+ }++ #[tokio::test]+ async fn gateway_voice_error_rejects_pending_join() {+ let manager = VoiceManager::new();+ let (tx, rx) = oneshot::channel();+ *manager.pending.lock().unwrap() = Some(PendingJoin { url: "https://a".into(), channel_id: "7".into(), tx });+ manager.reject_pending("https://a", ERR_VOICE_DENIED.into());+ assert_eq!(rx.await.unwrap().unwrap_err(), ERR_VOICE_DENIED);+ }++ #[test]+ fn deafen_implies_mute_and_restores_it() {+ let mut f = Flags::default();+ f.muted_before_deafen = f.muted;+ f.muted = true;+ f.deafened = true;+ assert!(f.muted && f.deafened);+ f.muted = f.muted_before_deafen;+ f.deafened = false;+ assert!(!f.muted && !f.deafened);+ }+}diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rsindex 664426c5..37953ee5 100644--- a/src-tauri/src/commands/settings.rs+++ b/src-tauri/src/commands/settings.rs@@ -1,167 +1,169 @@-use crate::hotkey;-use crate::models::settings::AppSettings;-use crate::storage::config;--#[tauri::command]-pub fn get_settings(app: tauri::AppHandle) -> Result<AppSettings, String> {- Ok(config::load_settings(&app))-}--#[tauri::command]-pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettings, String> {- let mut current = config::load_settings(&app);- let old_hotkey_enabled = current.download.hotkey_enabled;- let old_hotkey_binding = current.download.hotkey_binding.clone();- let old_clip_hotkey_enabled = current.download.clip_hotkey_enabled;- let old_clip_hotkey_binding = current.download.clip_hotkey_binding.clone();- let old_music_hotkey_enabled = current.download.music_hotkey_enabled;- let old_music_hotkey_binding = current.download.music_hotkey_binding.clone();- let old_start_with_system = current.start_with_system;- let old_rpc = current.rpc.clone();-- let patch: serde_json::Value =- serde_json::from_str(&partial).map_err(|e| format!("Invalid JSON: {}", e))?;- let mut current_val =- serde_json::to_value(¤t).map_err(|e| format!("Serialize: {}", e))?;- merge_json(&mut current_val, &patch);- current = serde_json::from_value(current_val).map_err(|e| format!("Deserialize: {}", e))?;- config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;-- crate::core::http_client::init_proxy(current.proxy.clone());- crate::core::http_fetcher::set_global_max_concurrent_segments(- current.advanced.max_concurrent_segments as usize,- );-- if old_hotkey_enabled != current.download.hotkey_enabled- || old_hotkey_binding != current.download.hotkey_binding- || old_clip_hotkey_enabled != current.download.clip_hotkey_enabled- || old_clip_hotkey_binding != current.download.clip_hotkey_binding- || old_music_hotkey_enabled != current.download.music_hotkey_enabled- || old_music_hotkey_binding != current.download.music_hotkey_binding- {- hotkey::reregister(&app);- }-- if old_start_with_system != current.start_with_system {- crate::commands::autostart::apply_autostart(&app, current.start_with_system)?;- }-- if old_rpc.enabled != current.rpc.enabled- || old_rpc.app_id != current.rpc.app_id- || old_rpc.large_image_key != current.rpc.large_image_key- {- let new_rpc = current.rpc.clone();- let prev_app_id = old_rpc.app_id.clone();- tauri::async_runtime::spawn(async move {- crate::core::rpc::handle_settings_changed(new_rpc, prev_app_id).await;- });- }-- Ok(current)-}--#[tauri::command]-pub fn reset_settings(app: tauri::AppHandle) -> Result<AppSettings, String> {- let defaults = AppSettings::default();- config::save_settings(&app, &defaults).map_err(|e| format!("Save: {}", e))?;- hotkey::reregister(&app);- let _ = crate::commands::autostart::apply_autostart(&app, defaults.start_with_system);- Ok(defaults)-}--#[tauri::command]-pub fn mark_onboarding_complete(app: tauri::AppHandle) -> Result<(), String> {- let mut current = config::load_settings(&app);- current.onboarding_completed = true;- config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;- Ok(())-}--#[tauri::command]-pub fn mark_legal_acknowledged(app: tauri::AppHandle) -> Result<(), String> {- let mut current = config::load_settings(&app);- current.legal_acknowledged = true;- config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;- Ok(())-}--#[derive(serde::Serialize)]-pub struct BridgeInfo {- pub enabled: bool,- pub port: u16,- pub token: String,- pub url: String,-}--/// Returns the localhost bridge connection info for the Settings UI.-///-/// `port == 0` means the bridge has not finished binding yet (the user can-/// retry shortly). `token` may be empty until the first run completes.-#[tauri::command]-pub fn get_bridge_info(app: tauri::AppHandle) -> Result<BridgeInfo, String> {- let settings = config::load_settings(&app);- let url = if settings.bridge.port == 0 {- String::new()- } else {- crate::local_bridge::build_pairing_url(settings.bridge.port)- };- Ok(BridgeInfo {- enabled: settings.bridge.enabled,- port: settings.bridge.port,- token: settings.bridge.token,- url,- })-}--/// Forces a fresh token to be generated. Used by the Settings UI when the-/// user wants to revoke a previously-paired browser.-#[tauri::command]-pub fn rotate_bridge_token(app: tauri::AppHandle) -> Result<BridgeInfo, String> {- let mut current = config::load_settings(&app);- current.bridge.token = crate::local_bridge::generate_token();- config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;- get_bridge_info(app)-}--#[derive(serde::Serialize)]-pub struct BridgePairStatus {- pub ok: bool,- pub window_secs: i64,- pub port: u16,- pub enabled: bool,-}--/// Opens a short, single-use, user-consented pairing window so an installed-/// browser extension can fetch the bearer token from `GET /v1/pair` without-/// the user copy-pasting it.-#[tauri::command]-pub fn bridge_open_pairing(app: tauri::AppHandle) -> Result<BridgePairStatus, String> {- let settings = config::load_settings(&app);- if !settings.bridge.enabled {- return Ok(BridgePairStatus {- ok: false,- window_secs: 0,- port: settings.bridge.port,- enabled: false,- });- }- let window_secs = crate::local_bridge::open_pairing_window();- Ok(BridgePairStatus {- ok: true,- window_secs,- port: settings.bridge.port,- enabled: true,- })-}--fn merge_json(base: &mut serde_json::Value, patch: &serde_json::Value) {- if let (Some(base_obj), Some(patch_obj)) = (base.as_object_mut(), patch.as_object()) {- for (key, value) in patch_obj {- if value.is_object() && base_obj.get(key).is_some_and(|v| v.is_object()) {- merge_json(base_obj.get_mut(key).unwrap(), value);- } else {- base_obj.insert(key.clone(), value.clone());- }- }- }-}+use crate::hotkey;+use crate::models::settings::AppSettings;+use crate::storage::config;++#[tauri::command]+pub fn get_settings(app: tauri::AppHandle) -> Result<AppSettings, String> {+ Ok(config::load_settings(&app))+}++#[tauri::command]+pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettings, String> {+ let mut current = config::load_settings(&app);+ let old_hotkey_enabled = current.download.hotkey_enabled;+ let old_hotkey_binding = current.download.hotkey_binding.clone();+ let old_clip_hotkey_enabled = current.download.clip_hotkey_enabled;+ let old_clip_hotkey_binding = current.download.clip_hotkey_binding.clone();+ let old_music_hotkey_enabled = current.download.music_hotkey_enabled;+ let old_music_hotkey_binding = current.download.music_hotkey_binding.clone();+ let old_ptt_key = current.omnidisc.voice.ptt_key.clone();+ let old_start_with_system = current.start_with_system;+ let old_rpc = current.rpc.clone();++ let patch: serde_json::Value =+ serde_json::from_str(&partial).map_err(|e| format!("Invalid JSON: {}", e))?;+ let mut current_val =+ serde_json::to_value(¤t).map_err(|e| format!("Serialize: {}", e))?;+ merge_json(&mut current_val, &patch);+ current = serde_json::from_value(current_val).map_err(|e| format!("Deserialize: {}", e))?;+ config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;++ crate::core::http_client::init_proxy(current.proxy.clone());+ crate::core::http_fetcher::set_global_max_concurrent_segments(+ current.advanced.max_concurrent_segments as usize,+ );++ if old_hotkey_enabled != current.download.hotkey_enabled+ || old_hotkey_binding != current.download.hotkey_binding+ || old_clip_hotkey_enabled != current.download.clip_hotkey_enabled+ || old_clip_hotkey_binding != current.download.clip_hotkey_binding+ || old_music_hotkey_enabled != current.download.music_hotkey_enabled+ || old_music_hotkey_binding != current.download.music_hotkey_binding+ || old_ptt_key != current.omnidisc.voice.ptt_key+ {+ hotkey::reregister(&app);+ }++ if old_start_with_system != current.start_with_system {+ crate::commands::autostart::apply_autostart(&app, current.start_with_system)?;+ }++ if old_rpc.enabled != current.rpc.enabled+ || old_rpc.app_id != current.rpc.app_id+ || old_rpc.large_image_key != current.rpc.large_image_key+ {+ let new_rpc = current.rpc.clone();+ let prev_app_id = old_rpc.app_id.clone();+ tauri::async_runtime::spawn(async move {+ crate::core::rpc::handle_settings_changed(new_rpc, prev_app_id).await;+ });+ }++ Ok(current)+}++#[tauri::command]+pub fn reset_settings(app: tauri::AppHandle) -> Result<AppSettings, String> {+ let defaults = AppSettings::default();+ config::save_settings(&app, &defaults).map_err(|e| format!("Save: {}", e))?;+ hotkey::reregister(&app);+ let _ = crate::commands::autostart::apply_autostart(&app, defaults.start_with_system);+ Ok(defaults)+}++#[tauri::command]+pub fn mark_onboarding_complete(app: tauri::AppHandle) -> Result<(), String> {+ let mut current = config::load_settings(&app);+ current.onboarding_completed = true;+ config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;+ Ok(())+}++#[tauri::command]+pub fn mark_legal_acknowledged(app: tauri::AppHandle) -> Result<(), String> {+ let mut current = config::load_settings(&app);+ current.legal_acknowledged = true;+ config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;+ Ok(())+}++#[derive(serde::Serialize)]+pub struct BridgeInfo {+ pub enabled: bool,+ pub port: u16,+ pub token: String,+ pub url: String,+}++/// Returns the localhost bridge connection info for the Settings UI.+///+/// `port == 0` means the bridge has not finished binding yet (the user can+/// retry shortly). `token` may be empty until the first run completes.+#[tauri::command]+pub fn get_bridge_info(app: tauri::AppHandle) -> Result<BridgeInfo, String> {+ let settings = config::load_settings(&app);+ let url = if settings.bridge.port == 0 {+ String::new()+ } else {+ crate::local_bridge::build_pairing_url(settings.bridge.port)+ };+ Ok(BridgeInfo {+ enabled: settings.bridge.enabled,+ port: settings.bridge.port,+ token: settings.bridge.token,+ url,+ })+}++/// Forces a fresh token to be generated. Used by the Settings UI when the+/// user wants to revoke a previously-paired browser.+#[tauri::command]+pub fn rotate_bridge_token(app: tauri::AppHandle) -> Result<BridgeInfo, String> {+ let mut current = config::load_settings(&app);+ current.bridge.token = crate::local_bridge::generate_token();+ config::save_settings(&app, ¤t).map_err(|e| format!("Save: {}", e))?;+ get_bridge_info(app)+}++#[derive(serde::Serialize)]+pub struct BridgePairStatus {+ pub ok: bool,+ pub window_secs: i64,+ pub port: u16,+ pub enabled: bool,+}++/// Opens a short, single-use, user-consented pairing window so an installed+/// browser extension can fetch the bearer token from `GET /v1/pair` without+/// the user copy-pasting it.+#[tauri::command]+pub fn bridge_open_pairing(app: tauri::AppHandle) -> Result<BridgePairStatus, String> {+ let settings = config::load_settings(&app);+ if !settings.bridge.enabled {+ return Ok(BridgePairStatus {+ ok: false,+ window_secs: 0,+ port: settings.bridge.port,+ enabled: false,+ });+ }+ let window_secs = crate::local_bridge::open_pairing_window();+ Ok(BridgePairStatus {+ ok: true,+ window_secs,+ port: settings.bridge.port,+ enabled: true,+ })+}++fn merge_json(base: &mut serde_json::Value, patch: &serde_json::Value) {+ if let (Some(base_obj), Some(patch_obj)) = (base.as_object_mut(), patch.as_object()) {+ for (key, value) in patch_obj {+ if value.is_object() && base_obj.get(key).is_some_and(|v| v.is_object()) {+ merge_json(base_obj.get_mut(key).unwrap(), value);+ } else {+ base_obj.insert(key.clone(), value.clone());+ }+ }+ }+}diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex 5fd79a20..0a0b0d7a 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -23,6 +23,20 @@ pub fn register_from_settings(app: &tauri::AppHandle) {if settings.download.music_hotkey_enabled {register_one(app, &settings.download.music_hotkey_binding, "music");}+ let ptt = settings.omnidisc.voice.ptt_key.trim();+ if settings.omnidisc.enabled && !ptt.is_empty() {+ register_one(app, ptt, "omnidisc-ptt");+ }+}++pub fn handle_ptt(app: &tauri::AppHandle, shortcut: &Shortcut, pressed: bool) -> bool {+ let settings = config::load_settings(app);+ let ptt = settings.omnidisc.voice.ptt_key.trim();+ if ptt.is_empty() || !matches_binding(shortcut, ptt) {+ return false;+ }+ crate::commands::omnidisc::voice::ptt_from_hotkey(app, pressed);+ true}fn register_one(app: &tauri::AppHandle, binding: &str, label: &str) {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e4fd8143..0952bc4a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -200,6 +200,11 @@ pub struct AppState {pub active_p2p_sends: ActiveP2pSends,pub frontend_ready: Arc<tokio::sync::Mutex<bool>>,pub pending_external_events: Arc<tokio::sync::Mutex<Vec<external_url::ExternalUrlEvent>>>,+ pub omnidisc_gateways: commands::omnidisc::gateway::Gateways,+ pub omnidisc_voice: Arc<commands::omnidisc::voice::VoiceManager>,+ pub omnidisc_stream: Arc<commands::omnidisc::stream::StreamManager>,+ pub omnidisc_mls: Arc<commands::omnidisc::mls::MlsManager>,+ pub omnidisc_uploads: Arc<commands::omnidisc::upload::UploadManager>,}#[cfg_attr(mobile, tauri::mobile_entry_point)]@@ -258,6 +263,11 @@ pub fn run() {active_p2p_sends: Arc::new(tokio::sync::Mutex::new(HashMap::new())),frontend_ready: Arc::new(tokio::sync::Mutex::new(false)),pending_external_events: Arc::new(tokio::sync::Mutex::new(Vec::new())),+ omnidisc_gateways: commands::omnidisc::gateway::new_gateways(),+ omnidisc_voice: Arc::new(commands::omnidisc::voice::VoiceManager::new()),+ omnidisc_stream: Arc::new(commands::omnidisc::stream::StreamManager::default()),+ omnidisc_mls: Arc::new(commands::omnidisc::mls::MlsManager::default()),+ omnidisc_uploads: Arc::new(commands::omnidisc::upload::UploadManager::default()),};tauri::Builder::default()@@ -298,7 +308,11 @@ pub fn run() {.plugin(tauri_plugin_global_shortcut::Builder::new().with_handler(|app, shortcut, event| {- if event.state == tauri_plugin_global_shortcut::ShortcutState::Pressed {+ let pressed = event.state == tauri_plugin_global_shortcut::ShortcutState::Pressed;+ if hotkey::handle_ptt(app, shortcut, pressed) {+ return;+ }+ if pressed {hotkey::on_hotkey_pressed(app, shortcut);}})@@ -645,6 +659,7 @@ pub fn run() {}tray::setup(app.handle())?;hotkey::register_from_settings(app.handle());+ commands::omnidisc::voice::start(app.handle());// Migration: drop the manifests / binary copies the previous// native-messaging code left under `~/.config/...` so Chrome and@@ -807,6 +822,96 @@ pub fn run() {}).invoke_handler(tauri::generate_handler![commands::auth_webview::open_auth_webview,+ commands::omnidisc::omnidisc_connect,+ commands::omnidisc::auth::omnidisc_register,+ commands::omnidisc::auth::omnidisc_login,+ commands::omnidisc::auth::omnidisc_logout,+ commands::omnidisc::auth::omnidisc_has_session,+ commands::omnidisc::api::omnidisc_list_messages,+ commands::omnidisc::api::omnidisc_send_message,+ commands::omnidisc::api::omnidisc_edit_message,+ commands::omnidisc::api::omnidisc_delete_message,+ commands::omnidisc::api::omnidisc_add_reaction,+ commands::omnidisc::api::omnidisc_remove_reaction,+ commands::omnidisc::api::omnidisc_ack,+ commands::omnidisc::gateway::omnidisc_typing,+ commands::omnidisc::api::omnidisc_create_guild,+ commands::omnidisc::api::omnidisc_create_channel,+ commands::omnidisc::api::omnidisc_create_invite,+ commands::omnidisc::api::omnidisc_join_invite,+ commands::omnidisc::api::omnidisc_create_dm,+ commands::omnidisc::api::omnidisc_update_me,+ commands::omnidisc::api::omnidisc_get_user,+ commands::omnidisc::api::omnidisc_get_guild,+ commands::omnidisc::api::omnidisc_get_me,+ commands::omnidisc::api::omnidisc_search,+ commands::omnidisc::api::omnidisc_list_pins,+ commands::omnidisc::api::omnidisc_pin_message,+ commands::omnidisc::api::omnidisc_list_relationships,+ commands::omnidisc::api::omnidisc_add_relationship,+ commands::omnidisc::api::omnidisc_accept_relationship,+ commands::omnidisc::api::omnidisc_remove_relationship,+ commands::omnidisc::api::omnidisc_block_user,+ commands::omnidisc::api::omnidisc_list_notes,+ commands::omnidisc::api::omnidisc_put_note,+ commands::omnidisc::api::omnidisc_update_guild,+ commands::omnidisc::api::omnidisc_delete_guild,+ commands::omnidisc::api::omnidisc_leave_guild,+ commands::omnidisc::api::omnidisc_transfer_guild,+ commands::omnidisc::api::omnidisc_create_role,+ commands::omnidisc::api::omnidisc_update_role,+ commands::omnidisc::api::omnidisc_delete_role,+ commands::omnidisc::api::omnidisc_set_member_role,+ commands::omnidisc::api::omnidisc_update_member,+ commands::omnidisc::api::omnidisc_kick_member,+ commands::omnidisc::api::omnidisc_ban_member,+ commands::omnidisc::api::omnidisc_unban_member,+ commands::omnidisc::api::omnidisc_list_bans,+ commands::omnidisc::api::omnidisc_audit_log,+ commands::omnidisc::api::omnidisc_update_channel,+ commands::omnidisc::api::omnidisc_delete_channel,+ commands::omnidisc::api::omnidisc_put_overwrite,+ commands::omnidisc::api::omnidisc_delete_overwrite,+ commands::omnidisc::api::omnidisc_list_sessions,+ commands::omnidisc::api::omnidisc_revoke_session,+ commands::omnidisc::api::omnidisc_revoke_other_sessions,+ commands::omnidisc::device::omnidisc_device_fingerprint,+ commands::omnidisc::device::omnidisc_list_user_devices,+ commands::omnidisc::device::omnidisc_revoke_device,+ commands::omnidisc::mls::omnidisc_mls_sync,+ commands::omnidisc::mls::omnidisc_mls_status,+ commands::omnidisc::mls::omnidisc_mls_recall,+ commands::omnidisc::mls::omnidisc_mls_device_revoked,+ commands::omnidisc::upload::omnidisc_instance_limits,+ commands::omnidisc::upload::omnidisc_stage_file,+ commands::omnidisc::upload::omnidisc_upload_start,+ commands::omnidisc::upload::omnidisc_upload_cancel,+ commands::omnidisc::upload::omnidisc_download_attachment,+ commands::omnidisc::gateway::omnidisc_gateway_connect,+ commands::omnidisc::gateway::omnidisc_gateway_disconnect,+ commands::omnidisc::gateway::omnidisc_gateway_send,+ commands::omnidisc::gateway::omnidisc_gateway_status,+ commands::omnidisc::voice::omnidisc_voice_join,+ commands::omnidisc::voice::omnidisc_voice_leave,+ commands::omnidisc::voice::omnidisc_voice_set_mute,+ commands::omnidisc::voice::omnidisc_voice_set_deaf,+ commands::omnidisc::voice::omnidisc_voice_set_volume,+ commands::omnidisc::voice::omnidisc_voice_devices,+ commands::omnidisc::voice::omnidisc_voice_set_device,+ commands::omnidisc::voice::omnidisc_voice_stats,+ commands::omnidisc::voice::omnidisc_voice_ptt,+ commands::omnidisc::voice::omnidisc_voice_status,+ commands::omnidisc::voice::omnidisc_voice_set_noise_suppression,+ commands::omnidisc::voice::omnidisc_voice_mic_test,+ commands::omnidisc::voice::omnidisc_voice_set_ducking,+ commands::omnidisc::stream::omnidisc_stream_sources,+ commands::omnidisc::stream::omnidisc_stream_start,+ commands::omnidisc::stream::omnidisc_stream_stop,+ commands::omnidisc::stream::omnidisc_stream_stats,+ commands::omnidisc::stream::omnidisc_stream_set_volume,+ commands::omnidisc::stream::omnidisc_stream_set_viewport,+ commands::omnidisc::stream::omnidisc_stream_watch,+ commands::omnidisc::stream::omnidisc_stream_unwatch,commands::league::league_status,commands::league::league_get,commands::league::league_install_dir,diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex e2aaaf7d..76b36956 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -36,7 +36,8 @@"requireLiteralLeadingDot": false}}- }+ },+ "macOSPrivateApi": true},"plugins": {"updater": {@@ -73,4 +74,4 @@"minimumSystemVersion": "10.15"}}-}+}\ No newline at end of filediff --git a/src/components/omnidisc/AttachmentStrip.svelte b/src/components/omnidisc/AttachmentStrip.sveltenew file mode 100644index 00000000..dc2f1e77--- /dev/null+++ b/src/components/omnidisc/AttachmentStrip.svelte@@ -0,0 +1,207 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { removePendingAttachment, retryAttachment } from "$lib/stores/omnidisc-store.svelte";+ import type { PendingAttachment } from "$lib/omnidisc/types";++ let { channelId, items }: { channelId: string; items: PendingAttachment[] } = $props();++ function sizeLabel(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ const units = ["KB", "MB", "GB"];+ let value = bytes / 1024;+ let unit = 0;+ while (value >= 1024 && unit < units.length - 1) {+ value /= 1024;+ unit += 1;+ }+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;+ }++ function percent(item: PendingAttachment): number {+ if (item.total <= 0) return 0;+ return Math.min(100, Math.round((item.sent / item.total) * 100));+ }++ function status(item: PendingAttachment): string {+ switch (item.state) {+ case "preparing":+ return item.encrypted ? $t("omnidisc.attachments.preparing") : sizeLabel(item.total);+ case "resuming":+ return $t("omnidisc.attachments.resuming");+ case "failed":+ return item.error+ ? translateBackendError(item.error, $t)+ : $t("omnidisc.attachments.failed");+ case "done":+ return `${sizeLabel(item.total)} · ${$t("omnidisc.attachments.ready")}`;+ default:+ return $t("omnidisc.attachments.uploading", { percent: percent(item) });+ }+ }+</script>++{#if items.length > 0}+ <ul class="strip" aria-label={$t("omnidisc.attachments.title")}>+ {#each items as item (item.id)}+ <li class="chip" class:failed={item.state === "failed"} class:ready={item.state === "done"}>+ {#if item.previewUrl}+ <img class="thumb" src={item.previewUrl} alt="" />+ {:else}+ <span class="thumb glyph" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3v5h5" /><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" /></svg>+ </span>+ {/if}+ <span class="detail">+ <span class="name" title={item.name}>{item.name}</span>+ <span class="meta">{status(item)}</span>+ {#if item.state !== "done" && item.state !== "failed"}+ <span+ class="bar"+ role="progressbar"+ aria-valuenow={percent(item)}+ aria-valuemin="0"+ aria-valuemax="100"+ >+ <span class="fill" style:width={`${percent(item)}%`}></span>+ </span>+ {/if}+ </span>+ {#if item.state === "failed"}+ <button type="button" class="mini" onclick={() => void retryAttachment(channelId, item.id)}>+ {$t("omnidisc.attachments.retry")}+ </button>+ {/if}+ <button+ type="button"+ class="close"+ onclick={() => removePendingAttachment(channelId, item.id)}+ aria-label={$t("omnidisc.attachments.remove", { name: item.name })}+ title={$t("omnidisc.attachments.remove", { name: item.name })}+ >×</button>+ </li>+ {/each}+ </ul>+{/if}++<style>+ .strip {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+ }++ .chip {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ max-width: 260px;+ padding: 6px var(--space-2);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ }++ .chip.ready {+ border-color: var(--success);+ }++ .chip.failed {+ border-color: var(--danger);+ }++ .thumb {+ width: 32px;+ height: 32px;+ flex: 0 0 auto;+ border-radius: var(--radius-sm);+ object-fit: cover;+ background: var(--fill-1);+ }++ .glyph {+ display: grid;+ place-items: center;+ color: var(--text-muted);+ }++ .detail {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ flex: 1;+ }++ .name {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .meta {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .chip.failed .meta {+ color: var(--danger);+ }++ .bar {+ display: block;+ height: 3px;+ border-radius: var(--radius-full);+ background: var(--fill-2);+ overflow: hidden;+ }++ .fill {+ display: block;+ height: 100%;+ background: var(--accent);+ transition: width var(--duration-fast) var(--ease-out);+ }++ .mini,+ .close {+ border: none;+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-xs);+ line-height: 1;+ cursor: pointer;+ padding: 2px 4px;+ border-radius: var(--radius-sm);+ }++ .mini {+ color: var(--accent);+ font-weight: 600;+ }++ .mini:hover,+ .close:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .mini:focus-visible,+ .close:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @media (prefers-reduced-motion: reduce) {+ .fill {+ transition: none;+ }+ }+</style>diff --git a/src/components/omnidisc/ChannelList.svelte b/src/components/omnidisc/ChannelList.sveltenew file mode 100644index 00000000..027b8f84--- /dev/null+++ b/src/components/omnidisc/ChannelList.svelte@@ -0,0 +1,785 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ getSelectedInstance,+ getGuilds,+ getGuild,+ getDms,+ getSelectedGuildId,+ getSelectedChannelId,+ canManageGuild,+ canInGuild,+ createChannel,+ createInviteLink,+ isUnread,+ getMentionCount,+ dmTitle,+ getChannel,+ getVoiceMembers,+ getVoiceMemberCount,+ userName,+ } from "$lib/stores/omnidisc-store.svelte";+ import {+ getVoiceSession,+ getVoiceState,+ isVoiceBusy,+ isSpeaking,+ joinVoice,+ } from "$lib/stores/omnidisc-voice-store.svelte";+ import type { ChannelKind, OmnidiscChannel } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "./OmnidiscPrompt.svelte";+ import VoiceBar from "./VoiceBar.svelte";+ import IncomingCallBar from "./IncomingCallBar.svelte";++ let instance = $derived(getSelectedInstance());+ let guilds = $derived(getGuilds(instance?.id ?? null));+ let guild = $derived(getGuild(getSelectedGuildId()) ?? guilds[0] ?? null);+ let dms = $derived(getDms(instance?.id ?? null));+ let selectedChannelId = $derived(getSelectedChannelId());+ let isOwner = $derived(canManageGuild(guild?.id ?? null));+ let canOpenSettings = $derived(!!guild && (isOwner || canInGuild(guild.id, "MANAGE_GUILD") || canInGuild(guild.id, "MANAGE_ROLES") || canInGuild(guild.id, "MANAGE_CHANNELS") || canInGuild(guild.id, "VIEW_AUDIT_LOG")));+ let connected = $derived(instance?.status === "connected" || instance?.id === "demo");+ let voiceSession = $derived(getVoiceSession());+ let voiceState = $derived(getVoiceState());+ let voiceBusy = $derived(isVoiceBusy());+ let currentVoiceName = $derived(getChannel(voiceSession?.channelId ?? null)?.name ?? "");+ let switchTarget = $state<string | null>(null);++ let createOpen = $state(false);+ let createBusy = $state(false);+ let createError = $state<string | null>(null);+ let channelName = $state("");+ let channelKind = $state<ChannelKind>("text");++ let inviteState = $state<"idle" | "busy" | "copied" | "failed">("idle");+ let inviteError = $state<string | null>(null);+ let inviteTimer: ReturnType<typeof setTimeout> | null = null;++ let groups = $derived.by(() => {+ if (!guild) return [] as { category: string; channels: OmnidiscChannel[] }[];+ const map = new Map<string, OmnidiscChannel[]>();+ for (const channel of guild.channels) {+ if (channel.kind === "category") {+ if (!map.has(channel.name)) map.set(channel.name, []);+ continue;+ }+ const key = channel.category ?? "";+ const list = map.get(key) ?? [];+ list.push(channel);+ map.set(key, list);+ }+ return [...map.entries()].map(([category, channels]) => ({ category, channels }));+ });++ function openCreate() {+ createError = null;+ channelName = "";+ channelKind = "text";+ createOpen = true;+ }++ async function submitCreate() {+ if (!guild) return;+ createBusy = true;+ createError = null;+ try {+ const channel = await createChannel(guild.id, channelName.trim(), channelKind);+ createOpen = false;+ if (channel && channel.kind === "text") goto(`/omnidisc/g/${guild.id}/${channel.id}`);+ } catch (e) {+ createError = translateBackendError(typeof e === "string" ? e : String(e), $t);+ } finally {+ createBusy = false;+ }+ }++ function initial(name: string): string {+ return name.trim().charAt(0).toUpperCase() || "?";+ }++ async function clickVoice(channel: OmnidiscChannel) {+ if (!guild) return;+ const inVoice = !!voiceSession && voiceState !== "idle";+ goto(`/omnidisc/g/${guild.id}/${channel.id}`);+ if (inVoice && voiceSession?.channelId !== channel.id) {+ switchTarget = channel.id;+ return;+ }+ if (inVoice) return;+ switchTarget = null;+ await joinVoice(channel.id);+ }++ async function confirmSwitch() {+ const target = switchTarget;+ switchTarget = null;+ if (target) await joinVoice(target);+ }++ async function invite() {+ if (!guild || inviteState === "busy") return;+ inviteState = "busy";+ inviteError = null;+ try {+ const link = await createInviteLink(guild.id, selectedChannelId ?? undefined);+ if (!link) throw new Error("ERR_SERVER");+ await navigator.clipboard.writeText(link);+ inviteState = "copied";+ } catch (e) {+ inviteState = "failed";+ inviteError = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }+ if (inviteTimer) clearTimeout(inviteTimer);+ inviteTimer = setTimeout(() => {+ inviteState = "idle";+ inviteError = null;+ }, 4000);+ }+</script>++<aside class="channel-list" aria-label={$t("omnidisc.channels.title")}>+ <header class="head">+ <div class="head-text">+ <h2 class="title">{guild?.name ?? instance?.name ?? $t("omnidisc.title")}</h2>+ {#if instance && guild}+ <span class="sub">{instance.name}</span>+ {/if}+ </div>+ {#if guild && canOpenSettings}+ <a class="head-action" href={`/omnidisc/g/${guild.id}/settings`} title={$t("omnidisc.guild_settings.title", { guild: guild.name })} aria-label={$t("omnidisc.guild_settings.title", { guild: guild.name })}>+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-1.8-.3 1.6 1.6 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1A1.6 1.6 0 0 0 9 19.4a1.6 1.6 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.6 1.6 0 0 0 .3-1.8 1.6 1.6 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.6 1.6 0 0 0 4.6 9a1.6 1.6 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.6 1.6 0 0 0 1.8.3H9a1.6 1.6 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0-.3 1.8V9a1.6 1.6 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.6 1.6 0 0 0-1.5 1z" /></svg>+ </a>+ {/if}+ {#if guild && connected}+ <button type="button" class="head-action" onclick={invite} disabled={inviteState === "busy"} title={$t("omnidisc.guild.invite")} aria-label={$t("omnidisc.guild.invite")}>+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />+ <circle cx="9" cy="7" r="4" />+ <path d="M19 8v6M22 11h-6" />+ </svg>+ </button>+ {/if}+ </header>++ {#if inviteState === "copied"}+ <p class="toast ok" role="status">{$t("omnidisc.guild.invite_copied")}</p>+ {:else if inviteState === "failed"}+ <p class="toast bad" role="alert">{inviteError ?? $t("omnidisc.guild.invite_failed")}</p>+ {/if}++ <nav class="groups">+ {#if dms.length > 0 || (!guild && instance)}+ <h3 class="category">{$t("omnidisc.channels.dms")}</h3>+ {#if dms.length === 0}+ <p class="empty-body inset">{$t("omnidisc.channels.no_dms")}</p>+ {:else}+ <ul class="channels">+ {#each dms as dm (dm.id)}+ <li>+ <a+ class="channel"+ class:active={dm.id === selectedChannelId}+ class:unread={isUnread(dm.id)}+ href={`/omnidisc/dm/${dm.id}`}+ aria-current={dm.id === selectedChannelId ? "page" : undefined}+ >+ <span class="glyph at" aria-hidden="true">@</span>+ <span class="name">{dmTitle(dm)}</span>+ {#if getMentionCount(dm.id) > 0}+ <span class="pill">{getMentionCount(dm.id)}</span>+ {:else if isUnread(dm.id)}+ <span class="dot" aria-hidden="true"></span>+ {/if}+ </a>+ </li>+ {/each}+ </ul>+ {/if}+ {/if}++ {#if !guild}+ {#if instance && guilds.length === 0}+ <div class="empty">+ <p class="empty-title">{$t("omnidisc.channels.no_guilds")}</p>+ <p class="empty-body">{$t("omnidisc.channels.no_guilds_hint")}</p>+ </div>+ {/if}+ {:else if guild.channels.length === 0}+ <div class="empty">+ <p class="empty-title">{$t("omnidisc.channels.empty")}</p>+ <p class="empty-body">{$t("omnidisc.channels.empty_hint")}</p>+ </div>+ {:else}+ {#each groups as group (group.category)}+ {#if group.category}+ <h3 class="category">{group.category}</h3>+ {/if}+ <ul class="channels">+ {#each group.channels as channel (channel.id)}+ <li>+ {#if channel.kind === "voice"}+ {@const count = getVoiceMemberCount(channel.id)}+ {@const inHere = voiceSession?.channelId === channel.id && voiceState !== "idle"}+ <button+ type="button"+ class="channel voice"+ class:active={channel.id === selectedChannelId}+ class:joined={inHere}+ aria-current={channel.id === selectedChannelId ? "page" : undefined}+ disabled={!connected || voiceBusy}+ title={inHere ? channel.name : $t("omnidisc.voice.join_channel", { channel: channel.name })}+ onclick={() => void clickVoice(channel)}+ >+ <svg class="glyph" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M11 5L6 9H2v6h4l5 4V5z" />+ <path d="M15.5 8.5a5 5 0 0 1 0 7" />+ </svg>+ <span class="name">{channel.name}</span>+ {#if count > 0}+ <span class="count" aria-label={$t("omnidisc.voice.participants", { count })}>{count}</span>+ {/if}+ </button>+ {#if switchTarget === channel.id}+ <div class="switch" role="group" aria-label={$t("omnidisc.voice.switch_title", { channel: channel.name })}>+ <p class="switch-text">+ <strong>{$t("omnidisc.voice.switch_title", { channel: channel.name })}</strong>+ {$t("omnidisc.voice.switch_body", { current: currentVoiceName })}+ </p>+ <div class="switch-actions">+ <button type="button" class="mini primary" onclick={() => void confirmSwitch()} disabled={voiceBusy}>{$t("omnidisc.voice.switch_confirm")}</button>+ <button type="button" class="mini" onclick={() => (switchTarget = null)}>{$t("common.cancel")}</button>+ </div>+ </div>+ {/if}+ {#if count > 0}+ <ul class="voice-members">+ {#each getVoiceMembers(channel.id) as m (m.userId)}+ {@const name = instance ? userName(instance.id, m.userId) : m.userId}+ {@const talking = isSpeaking(m.userId)}+ <li class="voice-member" class:speaking={talking}>+ <span class="mini-avatar" aria-hidden="true">{initial(name)}</span>+ <span class="member-name">{name}</span>+ {#if talking}<span class="sr-only">{$t("omnidisc.voice.speaking")}</span>{/if}+ {#if m.selfDeaf || m.serverDeaf}+ <svg class="flag" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-label={$t("omnidisc.voice.user_deafened", { name })}><path d="M4 14v-2a8 8 0 0 1 16 0v2" /><rect x="3" y="14" width="4" height="6" rx="1" /><rect x="17" y="14" width="4" height="6" rx="1" /><path d="M4 4l16 16" /></svg>+ {:else if m.selfMute || m.serverMute}+ <svg class="flag" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-label={$t("omnidisc.voice.user_muted", { name })}><rect x="9" y="3" width="6" height="11" rx="3" /><path d="M5 11a7 7 0 0 0 14 0M12 18v3" /><path d="M4 4l16 16" /></svg>+ {/if}+ </li>+ {/each}+ </ul>+ {/if}+ {:else}+ <a+ class="channel"+ class:active={channel.id === selectedChannelId}+ class:unread={isUnread(channel.id)}+ href={`/omnidisc/g/${guild.id}/${channel.id}`}+ aria-current={channel.id === selectedChannelId ? "page" : undefined}+ >+ <span class="glyph hash" aria-hidden="true">#</span>+ <span class="name">{channel.name}</span>+ {#if getMentionCount(channel.id) > 0}+ <span class="pill">{getMentionCount(channel.id)}</span>+ {:else if isUnread(channel.id)}+ <span class="dot" aria-hidden="true"></span>+ {/if}+ </a>+ {/if}+ </li>+ {/each}+ </ul>+ {/each}+ {/if}++ {#if guild && isOwner && connected}+ <button type="button" class="create" onclick={openCreate}>+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14" /></svg>+ {$t("omnidisc.guild.create_channel")}+ </button>+ {/if}+ </nav>+ <IncomingCallBar />+ <VoiceBar />+</aside>++<OmnidiscPrompt+ open={createOpen}+ title={$t("omnidisc.guild.create_channel_title", { guild: guild?.name ?? "" })}+ submitLabel={$t("omnidisc.guild.create_channel_submit")}+ busy={createBusy}+ error={createError}+ canSubmit={channelName.trim().length > 0}+ onSubmit={submitCreate}+ onClose={() => (createOpen = false)}+>+ <label class="field">+ <span class="label">{$t("omnidisc.guild.channel_name_label")}</span>+ <input class="input" type="text" bind:value={channelName} placeholder={$t("omnidisc.guild.channel_name_placeholder")} maxlength="100" spellcheck="false" />+ </label>+ <fieldset class="field kind">+ <legend class="label">{$t("omnidisc.guild.channel_kind_label")}</legend>+ <div class="kind-row">+ <label class="kind-opt" class:on={channelKind === "text"}>+ <input type="radio" name="od-channel-kind" value="text" bind:group={channelKind} />+ <span class="hash">#</span>+ {$t("omnidisc.guild.channel_kind_text")}+ </label>+ <label class="kind-opt" class:on={channelKind === "voice"}>+ <input type="radio" name="od-channel-kind" value="voice" bind:group={channelKind} />+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11 5L6 9H2v6h4l5 4V5z" /></svg>+ {$t("omnidisc.guild.channel_kind_voice")}+ </label>+ </div>+ </fieldset>+</OmnidiscPrompt>++<style>+ .channel-list {+ width: 232px;+ flex: 0 0 232px;+ display: flex;+ flex-direction: column;+ min-height: 0;+ background: var(--surface-mut);+ border-right: 1px solid var(--border);+ }++ .head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ padding: var(--space-3) var(--space-3) var(--space-3) var(--space-4);+ border-bottom: 1px solid var(--border);+ min-height: 48px;+ }++ .head-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }++ .title {+ margin: 0;+ font-size: var(--text-base);+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .sub {+ font-size: var(--text-xs);+ color: var(--text-muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .head-action {+ width: 30px;+ height: 30px;+ flex: 0 0 30px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ cursor: pointer;+ }++ .head-action:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .head-action:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .head-action:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .toast {+ margin: var(--space-2) var(--space-2) 0;+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-sm);+ font-size: var(--text-xs);+ line-height: 1.4;+ }++ .toast.ok {+ background: color-mix(in srgb, var(--success) 15%, transparent);+ color: var(--text);+ }++ .toast.bad {+ background: color-mix(in srgb, var(--danger) 15%, transparent);+ color: var(--text);+ }++ .groups {+ flex: 1;+ overflow-y: auto;+ padding: var(--space-2);+ }++ .category {+ margin: var(--space-3) var(--space-2) var(--space-1);+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .channels {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .channel {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: 6px var(--space-2);+ border-radius: var(--radius-sm);+ color: var(--text-muted);+ text-decoration: none;+ font-size: var(--text-sm);+ }++ .channel:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .channel.unread {+ color: var(--text);+ font-weight: 600;+ }++ .channel.active {+ background: var(--fill-2);+ color: var(--text);+ font-weight: 600;+ }++ .channel:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .channel.voice {+ width: 100%;+ border: none;+ background: transparent;+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .channel.voice:disabled {+ cursor: default;+ opacity: 0.6;+ }++ .channel.voice:hover:not(:disabled) {+ background: var(--fill-1);+ color: var(--text);+ }++ .channel.joined {+ color: var(--text);+ }++ .channel.joined .glyph {+ color: var(--success);+ opacity: 1;+ }++ .count {+ min-width: 18px;+ padding: 0 6px;+ border-radius: var(--radius-full);+ background: var(--fill-2);+ color: var(--text-muted);+ font-size: var(--text-xs);+ font-weight: 600;+ text-align: center;+ line-height: 18px;+ font-variant-numeric: tabular-nums;+ }++ .voice-members {+ list-style: none;+ margin: 0 0 var(--space-1);+ padding: 0 0 0 28px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .voice-member {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: 2px var(--space-2);+ border-radius: var(--radius-sm);+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .voice-member.speaking {+ color: var(--text);+ }++ .mini-avatar {+ width: 18px;+ height: 18px;+ flex: 0 0 18px;+ border-radius: var(--radius-full);+ display: grid;+ place-items: center;+ background: var(--accent-soft);+ color: var(--accent);+ font-size: 10px;+ font-weight: 600;+ box-shadow: 0 0 0 2px transparent;+ transition: box-shadow 120ms ease;+ }++ .voice-member.speaking .mini-avatar {+ box-shadow: 0 0 0 2px var(--success);+ }++ .member-name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .flag {+ flex: 0 0 12px;+ color: var(--text-muted);+ }++ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ }++ .switch {+ margin: var(--space-1) 0 var(--space-2) 28px;+ padding: var(--space-2);+ border-radius: var(--radius-sm);+ background: var(--surface);+ border: 1px solid var(--border);+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .switch-text {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.4;+ }++ .switch-text strong {+ display: block;+ color: var(--text);+ }++ .switch-actions {+ display: flex;+ gap: var(--space-1);+ }++ .mini {+ flex: 1;+ padding: 4px var(--space-2);+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface-mut);+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .mini.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ }++ .mini:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .mini:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @media (prefers-reduced-motion: reduce) {+ .mini-avatar {+ transition: none;+ }+ }++ .glyph {+ flex: 0 0 16px;+ width: 16px;+ text-align: center;+ opacity: 0.8;+ }++ .hash,+ .at {+ font-weight: 600;+ }++ .name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .dot {+ width: 8px;+ height: 8px;+ flex: 0 0 8px;+ border-radius: var(--radius-full);+ background: var(--text);+ }++ .pill {+ min-width: 18px;+ padding: 0 6px;+ border-radius: var(--radius-full);+ background: var(--danger);+ color: var(--on-accent);+ font-size: var(--text-xs);+ font-weight: 600;+ text-align: center;+ line-height: 18px;+ }++ .create {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ width: 100%;+ margin-top: var(--space-3);+ padding: 6px var(--space-2);+ border: 1px dashed var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .create:hover {+ color: var(--accent);+ border-color: var(--accent);+ }++ .create:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .empty {+ padding: var(--space-4);+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .empty-title {+ margin: 0;+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .empty-body {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .empty-body.inset {+ padding: 0 var(--space-2) var(--space-2);+ }++ .kind {+ margin: 0;+ padding: 0;+ border: none;+ }++ .kind-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: var(--space-2);+ }++ .kind-opt {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: 8px var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid var(--border);+ color: var(--text-muted);+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .kind-opt.on {+ border-color: var(--accent);+ color: var(--text);+ background: var(--accent-soft);+ }++ .kind-opt input {+ position: absolute;+ opacity: 0;+ width: 0;+ height: 0;+ }++ .kind-opt:focus-within {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/components/omnidisc/ChatView.svelte b/src/components/omnidisc/ChatView.sveltenew file mode 100644index 00000000..9f37c4eb--- /dev/null+++ b/src/components/omnidisc/ChatView.svelte@@ -0,0 +1,597 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ canDeleteMessage,+ canEditMessage,+ canInChannel,+ clearJumpTarget,+ deleteMessage,+ discardMessage,+ editMessage,+ effectiveNotificationLevel,+ getFirstUnreadId,+ getJumpTarget,+ getMessages,+ getNotificationLevel,+ getGroupStatus,+ getTypingNames,+ hostLabel,+ isChannelLoading,+ isEncryptedChannel,+ jumpToMessage,+ loadOlderMessages,+ markUnread,+ messageLink,+ notifyTyping,+ retryMessage,+ sendMessage,+ setNotificationLevel,+ refreshGroupStatus,+ setPinned,+ toggleReaction,+ getChannel,+ getInstance,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { NotificationLevel, OmnidiscMessage } from "$lib/omnidisc/types";+ import MessageList from "./MessageList.svelte";+ import Composer from "./Composer.svelte";+ import SearchPanel from "./SearchPanel.svelte";+ import PinsPanel from "./PinsPanel.svelte";+ import ProfilePopover from "./ProfilePopover.svelte";+ import OmnidiscPrompt from "./OmnidiscPrompt.svelte";++ let {+ instanceId,+ channelId,+ guildId = null,+ title,+ topic = "",+ kind = "text",+ canSend = false,+ membersOpen = false,+ onToggleMembers,+ headerExtra,+ }: {+ instanceId: string;+ channelId: string;+ guildId?: string | null;+ title: string;+ topic?: string;+ kind?: "text" | "dm";+ canSend?: boolean;+ membersOpen?: boolean;+ onToggleMembers?: () => void;+ headerExtra?: import("svelte").Snippet;+ } = $props();++ let panel = $state<"none" | "search" | "pins">("none");+ let notifyOpen = $state(false);+ let notifyEl = $state<HTMLElement | null>(null);+ let replyTo = $state<OmnidiscMessage | null>(null);+ let editingId = $state<string | null>(null);+ let pendingDelete = $state<OmnidiscMessage | null>(null);+ let actionError = $state<string | null>(null);+ let deleteBusy = $state(false);+ let highlightId = $state<string | null>(null);+ let profile = $state<{ userId: string; x: number; y: number } | null>(null);++ let messages = $derived(getMessages(channelId));+ let loading = $derived(isChannelLoading(channelId));+ let typingNames = $derived(getTypingNames(channelId));+ let draftKey = $derived(guildId ? `${guildId}/${channelId}` : `dm/${channelId}`);+ let firstUnreadId = $derived(getFirstUnreadId(channelId));+ let canReact = $derived(canSend && canInChannel(channelId, "ADD_REACTIONS"));+ let canPin = $derived(canInChannel(channelId, "PIN_MESSAGES"));+ let level = $derived(effectiveNotificationLevel(channelId));+ let encrypted = $derived(isEncryptedChannel(channelId));+ let groupStatus = $derived(getGroupStatus(channelId));+ let privacyText = $derived.by(() => {+ if (!encrypted) {+ const url = getInstance(instanceId)?.url ?? "";+ return $t("omnidisc.e2ee.guild_open", { host: url ? hostLabel(url) : "" });+ }+ if (!groupStatus?.ready) return $t("omnidisc.e2ee.preparing");+ const recipients = getChannel(channelId)?.recipientIds ?? [];+ return recipients.length === 1+ ? $t("omnidisc.e2ee.dm_locked", { name: title })+ : $t("omnidisc.e2ee.group_locked");+ });++ $effect(() => {+ if (encrypted) void refreshGroupStatus(channelId);+ });+ let levelExplicit = $derived(getNotificationLevel(channelId));++ $effect(() => {+ const target = getJumpTarget();+ if (!target || target.channelId !== channelId) return;+ highlightId = target.messageId;+ clearJumpTarget();+ });++ $effect(() => {+ channelId;+ replyTo = null;+ editingId = null;+ panel = "none";+ profile = null;+ });++ function fail(e: unknown) {+ actionError = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ function send(text: string) {+ const reference = replyTo?.id;+ replyTo = null;+ void sendMessage(channelId, text, reference);+ }++ function react(message: OmnidiscMessage, emoji: string) {+ toggleReaction(channelId, message.id, emoji).catch(fail);+ }++ function submitEdit(message: OmnidiscMessage, content: string) {+ editingId = null;+ editMessage(channelId, message.id, content).catch(fail);+ }++ function editLast() {+ const mine = [...messages].reverse().find((m) => canEditMessage(m));+ if (mine) editingId = mine.id;+ }++ async function confirmDelete() {+ const message = pendingDelete;+ if (!message) return;+ deleteBusy = true;+ actionError = null;+ try {+ await deleteMessage(channelId, message.id);+ pendingDelete = null;+ } catch (e) {+ fail(e);+ } finally {+ deleteBusy = false;+ }+ }++ async function copy(text: string, failKey: string) {+ try {+ await navigator.clipboard.writeText(text);+ } catch {+ actionError = $t(failKey);+ }+ }++ function openProfile(userId: string, anchor: HTMLElement) {+ const rect = anchor.getBoundingClientRect();+ const width = typeof window !== "undefined" ? window.innerWidth : 1280;+ const height = typeof window !== "undefined" ? window.innerHeight : 800;+ profile = {+ userId,+ x: Math.min(rect.left, width - 320),+ y: Math.min(rect.bottom + 6, height - 420),+ };+ }++ function pickLevel(next: NotificationLevel | null) {+ setNotificationLevel(channelId, next);+ notifyOpen = false;+ }++ function onWindowPointerDown(e: PointerEvent) {+ if (!notifyOpen) return;+ if (notifyEl && e.target instanceof Node && notifyEl.contains(e.target)) return;+ notifyOpen = false;+ }++ function jump(target: string, targetChannel = channelId) {+ if (targetChannel !== channelId) {+ void jumpToMessage(targetChannel, target);+ return;+ }+ void jumpToMessage(channelId, target);+ }+</script>++<svelte:window onpointerdown={onWindowPointerDown} />++<div class="chat-view">+ <header class="bar">+ <h2 class="name">+ <span class="glyph" aria-hidden="true">{kind === "dm" ? "@" : "#"}</span>+ {title}+ </h2>+ {#if topic}+ <p class="topic" title={topic}>{topic}</p>+ {/if}+ <div class="bar-actions">+ {@render headerExtra?.()}+ <button+ type="button"+ class="icon-button"+ class:on={panel === "search"}+ onclick={() => (panel = panel === "search" ? "none" : "search")}+ aria-pressed={panel === "search"}+ title={$t("omnidisc.search.title")}+ aria-label={$t("omnidisc.search.title")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7" /><path d="M20 20l-3.5-3.5" /></svg>+ </button>+ <button+ type="button"+ class="icon-button"+ class:on={panel === "pins"}+ onclick={() => (panel = panel === "pins" ? "none" : "pins")}+ aria-pressed={panel === "pins"}+ title={$t("omnidisc.pins.title")}+ aria-label={$t("omnidisc.pins.title")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 4h6l-1 6 4 3v2H6v-2l4-3z" /><path d="M12 15v5" /></svg>+ </button>+ <div class="notify" bind:this={notifyEl}>+ <button+ type="button"+ class="icon-button"+ class:on={notifyOpen}+ onclick={() => (notifyOpen = !notifyOpen)}+ aria-expanded={notifyOpen}+ title={$t("omnidisc.notify.title")}+ aria-label={$t("omnidisc.notify.title")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" /></svg>+ </button>+ {#if notifyOpen}+ <div class="menu" role="menu" aria-label={$t("omnidisc.notify.title")}>+ <p class="menu-hint">{$t("omnidisc.notify.channel_hint")}</p>+ <button type="button" class="menu-item" class:sel={levelExplicit === null} role="menuitem" onclick={() => pickLevel(null)}>+ {$t("omnidisc.notify.inherit", { level: $t(`omnidisc.notify.level_${level}`) })}+ </button>+ <button type="button" class="menu-item" class:sel={levelExplicit === "all"} role="menuitem" onclick={() => pickLevel("all")}>{$t("omnidisc.notify.level_all")}</button>+ <button type="button" class="menu-item" class:sel={levelExplicit === "mentions"} role="menuitem" onclick={() => pickLevel("mentions")}>{$t("omnidisc.notify.level_mentions")}</button>+ <button type="button" class="menu-item" class:sel={levelExplicit === "nothing"} role="menuitem" onclick={() => pickLevel("nothing")}>{$t("omnidisc.notify.level_nothing")}</button>+ </div>+ {/if}+ </div>+ {#if onToggleMembers}+ <button+ type="button"+ class="icon-button"+ class:on={membersOpen}+ onclick={onToggleMembers}+ aria-pressed={membersOpen}+ aria-label={membersOpen ? $t("omnidisc.members.hide") : $t("omnidisc.members.show")}+ title={membersOpen ? $t("omnidisc.members.hide") : $t("omnidisc.members.show")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />+ <circle cx="9" cy="7" r="4" />+ <path d="M23 21v-2a4 4 0 0 0-3-3.87" />+ <path d="M16 3.13a4 4 0 0 1 0 7.75" />+ </svg>+ </button>+ {/if}+ </div>+ </header>++ {#if actionError}+ <p class="action-error" role="alert">+ {actionError}+ <button type="button" class="dismiss" onclick={() => (actionError = null)}>{$t("common.close")}</button>+ </p>+ {/if}++ <div class="body">+ <div class="stream">+ <MessageList+ {messages}+ {loading}+ {firstUnreadId}+ {highlightId}+ {editingId}+ {canReact}+ canPin={canPin}+ canReply={canSend}+ canEditOf={canEditMessage}+ canDeleteOf={canDeleteMessage}+ onLoadOlder={() => {+ void loadOlderMessages(channelId);+ }}+ onRetry={(m) => {+ void retryMessage(channelId, m.id);+ }}+ onDiscard={(m) => discardMessage(channelId, m.id)}+ onReact={react}+ onReply={(m) => (replyTo = m)}+ onStartEdit={(m) => (editingId = m.id)}+ onSubmitEdit={submitEdit}+ onCancelEdit={() => (editingId = null)}+ onDelete={(m) => {+ actionError = null;+ pendingDelete = m;+ }}+ onTogglePin={(m) => {+ setPinned(channelId, m.id, !m.pinned).catch(fail);+ }}+ onCopyLink={(m) => void copy(messageLink(channelId, m.id), "omnidisc.messages.copy_failed")}+ onCopyId={(m) => void copy(m.id, "omnidisc.messages.copy_failed")}+ onMarkUnread={(m) => markUnread(channelId, m.id)}+ onJumpToMessage={(id) => jump(id)}+ onOpenProfile={openProfile}+ onHighlightShown={() => {+ setTimeout(() => (highlightId = null), 1800);+ }}+ />+ <p class="privacy" class:locked={encrypted}>+ {#if encrypted}+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><rect x="4" y="10" width="16" height="10" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></svg>+ <span>{privacyText}</span>+ {:else}+ <span>{privacyText}</span>+ {/if}+ </p>+ <Composer+ {channelId}+ canAttach={canSend && canInChannel(channelId, "ATTACH_FILES")}+ {draftKey}+ placeholder={kind === "dm"+ ? $t("omnidisc.dm.placeholder", { name: title })+ : $t("omnidisc.composer.placeholder", { channel: title })}+ disabled={!canSend}+ {typingNames}+ {replyTo}+ onSend={send}+ onTyping={() => notifyTyping(channelId)}+ onCancelReply={() => (replyTo = null)}+ onEditLast={editLast}+ />+ </div>++ {#if panel === "search"}+ <SearchPanel+ {instanceId}+ {guildId}+ {channelId}+ onJump={(ch, id) => jump(id, ch)}+ onClose={() => (panel = "none")}+ />+ {:else if panel === "pins"}+ <PinsPanel {instanceId} {channelId} {canPin} onJump={(id) => jump(id)} onClose={() => (panel = "none")} />+ {/if}+ </div>+</div>++{#if profile}+ <ProfilePopover+ {instanceId}+ userId={profile.userId}+ {guildId}+ x={profile.x}+ y={profile.y}+ onClose={() => (profile = null)}+ />+{/if}++<OmnidiscPrompt+ open={pendingDelete !== null}+ title={$t("omnidisc.messages.delete_title")}+ body={$t("omnidisc.messages.delete_body")}+ submitLabel={$t("omnidisc.messages.delete_confirm")}+ busy={deleteBusy}+ error={actionError}+ onSubmit={() => void confirmDelete()}+ onClose={() => {+ pendingDelete = null;+ actionError = null;+ }}+>+ {#if pendingDelete}+ <blockquote class="preview">+ <strong>{pendingDelete.authorName}</strong>+ <span>{pendingDelete.content.slice(0, 240) || $t("omnidisc.messages.delete_no_text")}</span>+ </blockquote>+ {/if}+</OmnidiscPrompt>++<style>+ .privacy {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0;+ padding: var(--space-2) var(--space-4) 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .privacy.locked {+ color: var(--success);+ }++ .chat-view {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .bar {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ min-height: 48px;+ padding: 0 var(--space-4);+ border-bottom: 1px solid var(--border);+ }++ .name {+ margin: 0;+ display: flex;+ align-items: center;+ gap: var(--space-1);+ font-size: var(--text-base);+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ flex: 0 0 auto;+ }++ .glyph {+ color: var(--text-muted);+ }++ .topic {+ flex: 1;+ margin: 0;+ padding-left: var(--space-3);+ border-left: 1px solid var(--border);+ font-size: var(--text-xs);+ color: var(--text-muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .bar-actions {+ margin-left: auto;+ display: flex;+ align-items: center;+ gap: 2px;+ }++ .notify {+ position: relative;+ }++ .icon-button {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ cursor: pointer;+ }++ .icon-button:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .icon-button.on {+ color: var(--accent);+ background: var(--accent-soft);+ }++ .icon-button:focus-visible,+ .menu-item:focus-visible,+ .dismiss:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .menu {+ position: absolute;+ right: 0;+ top: 36px;+ z-index: 40;+ min-width: 210px;+ display: flex;+ flex-direction: column;+ padding: var(--space-1);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ box-shadow: var(--shadow-lg, 0 8px 24px rgba(0, 0, 0, 0.25));+ }++ .menu-hint {+ margin: var(--space-1);+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .menu-item {+ padding: 6px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .menu-item:hover {+ background: var(--fill-1);+ }++ .menu-item.sel {+ color: var(--accent);+ font-weight: 600;+ }++ .action-error {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ margin: 0;+ padding: var(--space-2) var(--space-4);+ background: var(--danger-soft, var(--surface));+ color: var(--danger);+ font-size: var(--text-xs);+ }++ .dismiss {+ border: none;+ background: transparent;+ color: inherit;+ font: inherit;+ text-decoration: underline;+ cursor: pointer;+ }++ .body {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: row;+ }++ .stream {+ flex: 1;+ min-width: 0;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .preview {+ margin: 0;+ padding: var(--space-2) var(--space-3);+ border-left: 2px solid var(--border-hi);+ background: var(--fill-1);+ border-radius: var(--radius-sm);+ display: flex;+ flex-direction: column;+ gap: 2px;+ font-size: var(--text-sm);+ color: var(--text);+ overflow-wrap: anywhere;+ }++ @media (max-width: 1100px) {+ .body :global(.search-panel),+ .body :global(.pins-panel) {+ display: none;+ }+ }+</style>diff --git a/src/components/omnidisc/Composer.svelte b/src/components/omnidisc/Composer.sveltenew file mode 100644index 00000000..ba4e51ea--- /dev/null+++ b/src/components/omnidisc/Composer.svelte@@ -0,0 +1,496 @@+<script lang="ts">+ import { onMount, tick, untrack } from "svelte";+ import { open as openFileDialog } from "@tauri-apps/plugin-dialog";+ import { getCurrentWebview } from "@tauri-apps/api/webview";+ import { invoke } from "@tauri-apps/api/core";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ attachFile,+ getDraft,+ getPendingAttachments,+ hasUploadsInFlight,+ setDraft,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscMessage } from "$lib/omnidisc/types";+ import AttachmentStrip from "./AttachmentStrip.svelte";+ import EmojiPicker from "./EmojiPicker.svelte";++ const MAX_HEIGHT = 220;++ let {+ channelId,+ draftKey,+ placeholder,+ disabled = false,+ canAttach = true,+ typingNames = [],+ replyTo = null,+ onSend,+ onTyping,+ onCancelReply,+ onEditLast,+ }: {+ channelId: string;+ draftKey: string;+ placeholder: string;+ disabled?: boolean;+ canAttach?: boolean;+ typingNames?: string[];+ replyTo?: OmnidiscMessage | null;+ onSend: (text: string) => void;+ onTyping?: () => void;+ onCancelReply?: () => void;+ onEditLast?: () => void;+ } = $props();++ let textarea = $state<HTMLTextAreaElement | null>(null);+ let value = $state("");+ let emojiOpen = $state(false);+ let wrapper = $state<HTMLElement | null>(null);+ let dropActive = $state(false);+ let attachError = $state<string | null>(null);++ let attachments = $derived(getPendingAttachments(channelId));+ let uploading = $derived(hasUploadsInFlight(channelId));++ function fail(e: unknown) {+ const raw = typeof e === "string" ? e : e instanceof Error ? e.message : String(e);+ attachError = translateBackendError(raw, $t);+ }++ async function addPaths(paths: string[]) {+ attachError = null;+ for (const path of paths) {+ const name = path.split(/[\\/]/).pop() ?? "file";+ try {+ await attachFile(channelId, { path, name });+ } catch (e) {+ fail(e);+ return;+ }+ }+ }++ async function pickFiles() {+ if (!canAttach || disabled) return;+ try {+ const picked = await openFileDialog({ multiple: true });+ if (!picked) return;+ await addPaths(Array.isArray(picked) ? picked : [picked]);+ } catch (e) {+ fail(e);+ }+ }++ async function addBlobs(files: File[]) {+ attachError = null;+ for (const file of files) {+ try {+ const bytes = new Uint8Array(await file.arrayBuffer());+ const name = file.name && file.name.length > 0 ? file.name : "pasted";+ const path = await invoke<string>("omnidisc_stage_file", {+ name,+ bytes: Array.from(bytes),+ });+ const previewUrl = file.type.startsWith("image/") ? URL.createObjectURL(file) : undefined;+ await attachFile(channelId, { path, name, previewUrl });+ } catch (e) {+ fail(e);+ return;+ }+ }+ }++ function onPaste(e: ClipboardEvent) {+ if (!canAttach || disabled) return;+ const files = Array.from(e.clipboardData?.files ?? []);+ if (files.length === 0) return;+ e.preventDefault();+ void addBlobs(files);+ }++ function overChat(position: { x: number; y: number } | undefined): boolean {+ const area = wrapper?.closest(".chat-view") ?? wrapper;+ if (!area || !position) return false;+ const rect = area.getBoundingClientRect();+ const scale = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;+ const x = position.x / scale;+ const y = position.y / scale;+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;+ }++ // Tauri delivers file drops on the webview, not on the element, so the drop+ // target is worked out from the pointer position instead of a DOM event.+ onMount(() => {+ let stop: (() => void) | undefined;+ void getCurrentWebview()+ .onDragDropEvent((event) => {+ const payload = event.payload;+ if (!canAttach || disabled) return;+ if (payload.type === "over") {+ dropActive = overChat(payload.position);+ return;+ }+ if (payload.type === "drop") {+ const inside = overChat(payload.position);+ dropActive = false;+ if (inside && payload.paths.length > 0) void addPaths(payload.paths);+ return;+ }+ dropActive = false;+ })+ .then((off) => {+ stop = off;+ })+ .catch(() => {});+ return () => stop?.();+ });++ $effect(() => {+ const key = draftKey;+ value = untrack(() => getDraft(key));+ tick().then(autoGrow);+ });++ function autoGrow() {+ const el = textarea;+ if (!el) return;+ el.style.height = "auto";+ const next = Math.min(el.scrollHeight, MAX_HEIGHT);+ el.style.height = `${next}px`;+ el.style.overflowY = el.scrollHeight > MAX_HEIGHT ? "auto" : "hidden";+ }++ function onInput() {+ setDraft(draftKey, value);+ autoGrow();+ if (value.trim().length > 0) onTyping?.();+ }++ function send() {+ const text = value.trim();+ if (disabled || uploading) return;+ if (!text && attachments.length === 0) return;+ onSend(text);+ value = "";+ setDraft(draftKey, "");+ tick().then(autoGrow);+ }++ function onKeydown(e: KeyboardEvent) {+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {+ e.preventDefault();+ send();+ return;+ }+ if (e.key === "Escape" && replyTo) {+ e.preventDefault();+ onCancelReply?.();+ return;+ }+ if (e.key === "ArrowUp" && value.length === 0 && onEditLast) {+ e.preventDefault();+ onEditLast();+ }+ }++ function insertEmoji(char: string) {+ const el = textarea;+ emojiOpen = false;+ if (!el) {+ value = `${value}${char}`;+ setDraft(draftKey, value);+ return;+ }+ const start = el.selectionStart ?? value.length;+ const end = el.selectionEnd ?? value.length;+ value = `${value.slice(0, start)}${char}${value.slice(end)}`;+ setDraft(draftKey, value);+ tick().then(() => {+ el.focus();+ el.setSelectionRange(start + char.length, start + char.length);+ autoGrow();+ });+ }++ function onWindowPointerDown(e: PointerEvent) {+ if (!emojiOpen) return;+ if (wrapper && e.target instanceof Node && wrapper.contains(e.target)) return;+ emojiOpen = false;+ }++ let canSend = $derived(+ !disabled && !uploading && (value.trim().length > 0 || attachments.length > 0),+ );++ let typingLabel = $derived.by(() => {+ if (typingNames.length === 0) return "";+ if (typingNames.length === 1) return $t("omnidisc.messages.typing_one", { name: typingNames[0] });+ if (typingNames.length === 2) return $t("omnidisc.messages.typing_two", { a: typingNames[0], b: typingNames[1] });+ return $t("omnidisc.messages.typing_many");+ });+</script>++<svelte:window onpointerdown={onWindowPointerDown} />++<form class="composer" class:drop-active={dropActive} bind:this={wrapper} onsubmit={(e) => { e.preventDefault(); send(); }}>+ {#if dropActive}+ <p class="drop-hint" aria-live="polite">{$t("omnidisc.composer.drop_here")}</p>+ {/if}+ {#if attachError}+ <p class="attach-error" role="alert">{attachError}</p>+ {/if}+ <AttachmentStrip {channelId} items={attachments} />+ {#if replyTo}+ <div class="reply-bar">+ <span class="reply-label">{$t("omnidisc.composer.replying_to", { name: replyTo.authorName })}</span>+ <span class="reply-preview">{replyTo.content.slice(0, 80)}</span>+ <button type="button" class="reply-cancel" onclick={() => onCancelReply?.()} aria-label={$t("omnidisc.composer.cancel_reply")}>×</button>+ </div>+ {/if}+ {#if emojiOpen}+ <div class="emoji-pop">+ <EmojiPicker onPick={insertEmoji} onClose={() => (emojiOpen = false)} />+ </div>+ {/if}+ <div class="row">+ <textarea+ bind:this={textarea}+ bind:value+ class="input"+ rows="1"+ {placeholder}+ {disabled}+ aria-label={placeholder}+ oninput={onInput}+ onkeydown={onKeydown}+ onpaste={onPaste}+ ></textarea>+ {#if canAttach}+ <button+ type="button"+ class="emoji-btn attach-btn"+ onclick={() => void pickFiles()}+ disabled={disabled}+ aria-label={$t("omnidisc.composer.attach")}+ title={$t("omnidisc.composer.attach")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21.4 11.05 12.2 20.2a5 5 0 0 1-7.1-7.1l9.2-9.15a3.3 3.3 0 1 1 4.7 4.7l-9.2 9.15a1.7 1.7 0 0 1-2.4-2.4l8.5-8.45" /></svg>+ </button>+ {/if}+ <button+ type="button"+ class="emoji-btn"+ onclick={() => (emojiOpen = !emojiOpen)}+ aria-expanded={emojiOpen}+ disabled={disabled}+ aria-label={$t("omnidisc.emoji.title")}+ title={$t("omnidisc.emoji.title")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9" /><path d="M9 10h.01M15 10h.01M8.5 14.5a4.5 4.5 0 0 0 7 0" /></svg>+ </button>+ <button type="submit" class="send" disabled={!canSend} aria-label={$t("omnidisc.composer.send")}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M22 2L11 13" />+ <path d="M22 2l-7 20-4-9-9-4z" />+ </svg>+ </button>+ </div>+ <p class="hint" aria-live="polite">+ {#if uploading}+ <span class="typing">{$t("omnidisc.composer.uploading_wait")}</span>+ {:else if typingLabel}+ <span class="typing">{typingLabel}</span>+ {:else}+ {$t("omnidisc.composer.hint")}+ {/if}+ </p>+</form>++<style>+ .composer {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-4) var(--space-3);+ border-top: 1px solid var(--border);+ background: var(--bg);+ }++ .row {+ display: grid;+ grid-template-columns: 1fr auto auto auto;+ align-items: end;+ gap: var(--space-2);+ }++ .composer.drop-active {+ outline: 2px dashed var(--accent);+ outline-offset: -4px;+ }++ .drop-hint {+ margin: 0;+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--accent);+ }++ .attach-error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .input {+ grid-column: 1;+ grid-row: 1;+ width: 100%;+ box-sizing: border-box;+ resize: none;+ min-height: 42px;+ max-height: 220px;+ padding: 10px var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-base);+ line-height: 1.45;+ overflow-y: hidden;+ }++ .input:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .input:disabled {+ opacity: 0.6;+ }++ .reply-bar {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: 4px var(--space-2);+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface);+ font-size: var(--text-xs);+ color: var(--text-muted);+ overflow: hidden;+ }++ .reply-label {+ font-weight: 600;+ color: var(--text);+ flex: 0 0 auto;+ }++ .reply-preview {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .reply-cancel {+ border: none;+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-base);+ line-height: 1;+ cursor: pointer;+ }++ .reply-cancel:hover {+ color: var(--text);+ }++ .emoji-pop {+ position: absolute;+ right: var(--space-4);+ bottom: 100%;+ z-index: 40;+ }++ .attach-btn {+ grid-column: 2;+ }++ .emoji-btn {+ grid-column: 3;+ grid-row: 1;+ width: 42px;+ height: 42px;+ display: grid;+ place-items: center;+ border: 1px solid var(--input-border);+ border-radius: var(--radius-md);+ background: transparent;+ color: var(--text-muted);+ cursor: pointer;+ }++ .emoji-btn:hover:not(:disabled) {+ color: var(--text);+ background: var(--fill-1);+ }++ .emoji-btn:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .emoji-btn:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .send {+ grid-column: 4;+ grid-row: 1;+ width: 42px;+ height: 42px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-md);+ background: var(--accent);+ color: var(--on-accent);+ cursor: pointer;+ transition: opacity var(--duration-fast) var(--ease-out);+ }++ .send:disabled {+ opacity: 0.4;+ cursor: default;+ }++ .send:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .hint {+ margin: 0;+ min-height: 1.2em;+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .typing {+ color: var(--text);+ }++ @media (prefers-reduced-motion: reduce) {+ .send {+ transition: none;+ }+ }+</style>diff --git a/src/components/omnidisc/ConnectInstanceForm.svelte b/src/components/omnidisc/ConnectInstanceForm.sveltenew file mode 100644index 00000000..10923bce--- /dev/null+++ b/src/components/omnidisc/ConnectInstanceForm.svelte@@ -0,0 +1,553 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ connectInstance,+ authenticate,+ backToAuth,+ getConnectStep,+ getConnectError,+ getConnectedInstance,+ getPendingConnect,+ resetConnect,+ addDemoInstance,+ getGuilds,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { AuthMode } from "$lib/omnidisc/types";++ let { compact = false, onDone }: { compact?: boolean; onDone?: () => void } = $props();++ let url = $state("");+ let invite = $state("");+ let urlError = $state<string | null>(null);++ let mode = $state<AuthMode>("register");+ let username = $state("");+ let password = $state("");+ let displayName = $state("");+ let authError = $state<string | null>(null);++ const DEV = import.meta.env.DEV;++ let step = $derived(getConnectStep());+ let error = $derived(getConnectError());+ let connected = $derived(getConnectedInstance());+ let pending = $derived(getPendingConnect());+ let busy = $derived(step === "connecting" || step === "authenticating" || step === "syncing");++ const STEPS = ["connecting", "authenticating", "syncing"] as const;++ function stepIndex(s: string): number {+ return STEPS.indexOf(s as (typeof STEPS)[number]);+ }++ $effect(() => {+ if (pending && !pending.registrationOpen && !pending.invite) mode = "login";+ });++ async function submit(e: Event) {+ e.preventDefault();+ const trimmed = url.trim();+ if (!trimmed) {+ urlError = $t("omnidisc.connect.url_required");+ return;+ }+ urlError = null;+ await connectInstance(trimmed, invite);+ }++ async function submitAuth(e: Event) {+ e.preventDefault();+ if (!username.trim() || !password) {+ authError = $t("omnidisc.connect.auth_required");+ return;+ }+ authError = null;+ await authenticate(mode, username.trim(), password, mode === "register" ? displayName : undefined);+ password = "";+ }++ function openConnected() {+ const instance = connected;+ resetConnect();+ onDone?.();+ if (!instance) return;+ const guild = getGuilds(instance.id)[0];+ const channel = guild?.channels.find((c) => c.kind === "text");+ if (guild && channel) {+ goto(`/omnidisc/g/${guild.id}/${channel.id}`);+ } else {+ goto("/omnidisc");+ }+ }++ function retry() {+ if (pending) backToAuth();+ else resetConnect();+ }++ function changeServer() {+ resetConnect();+ username = "";+ password = "";+ displayName = "";+ authError = null;+ }++ function useDemo() {+ addDemoInstance();+ }++ let registrationBlocked = $derived(pending ? !pending.registrationOpen && !pending.invite : false);+</script>++<section class="connect" class:compact>+ {#if step === "done" && connected}+ <div class="state success" role="status">+ <div class="success-icon" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5" /></svg>+ </div>+ <h3>{$t("omnidisc.connect.success_title", { name: connected.name })}</h3>+ <p>{$t("omnidisc.connect.success_body")}</p>+ <button type="button" class="primary" onclick={openConnected}>{$t("omnidisc.connect.open")}</button>+ </div>+ {:else if step === "error"}+ <div class="state error" role="alert">+ <h3>{$t("omnidisc.connect.error_title")}</h3>+ <p>{translateBackendError(error ?? "", $t)}</p>+ <div class="actions">+ <button type="button" class="primary" onclick={retry}>{$t("omnidisc.connect.retry")}</button>+ {#if pending}+ <button type="button" class="ghost" onclick={changeServer}>{$t("omnidisc.connect.change_server")}</button>+ {/if}+ </div>+ </div>+ {:else if step === "auth" && pending}+ <form class="form" onsubmit={submitAuth}>+ <div class="auth-head">+ <h3>{$t("omnidisc.connect.auth_title", { name: pending.name })}</h3>+ <p>{$t("omnidisc.connect.auth_body")}</p>+ {#if pending.invite}+ <p class="note">{$t("omnidisc.connect.invite_noted")}</p>+ {/if}+ {#if pending.insecure}+ <p class="warning" role="status">+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M10.3 3.6 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.6a2 2 0 0 0-3.4 0z" />+ <path d="M12 9v4M12 17h.01" />+ </svg>+ <span>{$t("omnidisc.connect.insecure")}</span>+ </p>+ {/if}+ </div>++ <div class="segmented" role="tablist" aria-label={$t("omnidisc.connect.auth_title", { name: pending.name })}>+ <button+ type="button"+ role="tab"+ class:on={mode === "register"}+ aria-selected={mode === "register"}+ disabled={registrationBlocked}+ onclick={() => { mode = "register"; authError = null; }}+ >{$t("omnidisc.connect.mode_register")}</button>+ <button+ type="button"+ role="tab"+ class:on={mode === "login"}+ aria-selected={mode === "login"}+ onclick={() => { mode = "login"; authError = null; }}+ >{$t("omnidisc.connect.mode_login")}</button>+ </div>++ {#if registrationBlocked}+ <p class="note">{$t("omnidisc.connect.registration_closed")}</p>+ {/if}++ <label class="field">+ <span class="label">{$t("omnidisc.connect.username_label")}</span>+ <input+ class="input"+ type="text"+ autocomplete="username"+ autocapitalize="off"+ spellcheck="false"+ bind:value={username}+ placeholder={$t("omnidisc.connect.username_placeholder")}+ oninput={() => { if (authError) authError = null; }}+ />+ {#if mode === "register"}+ <span class="hint">{$t("omnidisc.connect.username_hint")}</span>+ {/if}+ </label>++ <label class="field">+ <span class="label">{$t("omnidisc.connect.password_label")}</span>+ <input+ class="input"+ type="password"+ autocomplete={mode === "register" ? "new-password" : "current-password"}+ bind:value={password}+ oninput={() => { if (authError) authError = null; }}+ />+ {#if mode === "register"}+ <span class="hint">{$t("omnidisc.connect.password_hint")}</span>+ {/if}+ </label>++ {#if mode === "register"}+ <label class="field">+ <span class="label">{$t("omnidisc.connect.display_name_label")}</span>+ <input+ class="input"+ type="text"+ autocomplete="nickname"+ bind:value={displayName}+ placeholder={$t("omnidisc.connect.display_name_placeholder")}+ />+ </label>+ {/if}++ {#if authError || error}+ <p class="field-error" role="alert">{authError ?? translateBackendError(error ?? "", $t)}</p>+ {/if}++ <div class="actions">+ <button type="submit" class="primary">+ {mode === "register" ? $t("omnidisc.connect.register_submit") : $t("omnidisc.connect.login_submit")}+ </button>+ <button type="button" class="ghost" onclick={changeServer}>{$t("omnidisc.connect.change_server")}</button>+ </div>+ </form>+ {:else}+ <form class="form" onsubmit={submit} aria-busy={busy}>+ <label class="field">+ <span class="label">{$t("omnidisc.connect.url_label")}</span>+ <input+ class="input"+ type="text"+ inputmode="url"+ autocomplete="url"+ spellcheck="false"+ bind:value={url}+ placeholder={$t("omnidisc.connect.url_placeholder")}+ disabled={busy}+ aria-invalid={urlError ? "true" : undefined}+ aria-describedby={urlError ? "omnidisc-url-error" : undefined}+ oninput={() => { if (urlError) urlError = null; }}+ />+ {#if urlError}+ <span id="omnidisc-url-error" class="field-error">{urlError}</span>+ {/if}+ </label>++ <label class="field">+ <span class="label">{$t("omnidisc.connect.invite_label")}</span>+ <input+ class="input"+ type="text"+ autocomplete="off"+ spellcheck="false"+ bind:value={invite}+ placeholder={$t("omnidisc.connect.invite_placeholder")}+ disabled={busy}+ />+ </label>++ {#if busy}+ <ol class="stepper" aria-label={$t("omnidisc.connect.submitting")}>+ {#each STEPS as s, i (s)}+ <li class="step" class:done={stepIndex(step) > i} class:current={step === s} aria-current={step === s ? "step" : undefined}>+ <span class="step-dot" aria-hidden="true"></span>+ <span>{$t(`omnidisc.connect.step_${s}`)}</span>+ </li>+ {/each}+ </ol>+ {/if}++ <div class="actions">+ <button type="submit" class="primary" disabled={busy}>+ {busy ? $t("omnidisc.connect.submitting") : $t("omnidisc.connect.submit")}+ </button>+ {#if DEV && !busy}+ <button type="button" class="ghost" onclick={useDemo}>{$t("omnidisc.connect.demo")}</button>+ {/if}+ </div>+ </form>+ {/if}+</section>++<style>+ .connect {+ width: 100%;+ max-width: 420px;+ }++ .form {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ }++ .auth-head {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .auth-head h3 {+ margin: 0;+ font-size: var(--text-md);+ color: var(--text);+ }++ .auth-head p,+ .note {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .warning {+ display: flex;+ gap: var(--space-2);+ align-items: flex-start;+ margin: var(--space-2) 0 0;+ padding: var(--space-2) var(--space-3);+ border: 1px solid var(--warning);+ border-radius: var(--radius-md);+ font-size: var(--text-sm);+ line-height: 1.5;+ color: var(--text);+ text-align: left;+ }++ .warning svg {+ flex: 0 0 auto;+ margin-top: 2px;+ color: var(--warning);+ }++ .segmented {+ display: grid;+ grid-template-columns: 1fr 1fr;+ padding: 3px;+ border-radius: var(--radius-md);+ background: var(--fill-1);+ }++ .segmented button {+ padding: 8px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 500;+ cursor: pointer;+ }++ .segmented button.on {+ background: var(--surface);+ color: var(--text);+ font-weight: 600;+ }++ .segmented button:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .segmented button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .label {+ font-size: var(--text-sm);+ font-weight: 500;+ color: var(--text);+ }++ .hint {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .input {+ box-sizing: border-box;+ width: 100%;+ padding: 10px var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-base);+ }++ .input:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .input[aria-invalid="true"] {+ border-color: var(--danger);+ }++ .field-error {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--danger);+ line-height: 1.5;+ }++ .actions {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ flex-wrap: wrap;+ }++ .primary {+ padding: 10px var(--space-5);+ border: none;+ border-radius: var(--radius-md);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-base);+ font-weight: 600;+ cursor: pointer;+ }++ .primary:disabled {+ opacity: 0.6;+ cursor: default;+ }++ .primary:focus-visible,+ .ghost:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .ghost {+ padding: 10px var(--space-3);+ border: none;+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .ghost:hover {+ color: var(--text);+ }++ .stepper {+ list-style: none;+ margin: 0;+ padding: var(--space-3);+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ border-radius: var(--radius-md);+ background: var(--surface);+ border: 1px solid var(--border);+ }++ .step {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ font-size: var(--text-sm);+ color: var(--text-muted);+ }++ .step.current {+ color: var(--text);+ font-weight: 600;+ }++ .step.done {+ color: var(--success);+ }++ .step-dot {+ width: 10px;+ height: 10px;+ border-radius: var(--radius-full);+ background: var(--border-hi);+ }++ .step.current .step-dot {+ background: var(--accent);+ animation: blink 1.2s ease-in-out infinite;+ }++ .step.done .step-dot {+ background: var(--success);+ }++ @keyframes blink {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.35; }+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid var(--border);+ background: var(--surface);+ }++ .state h3 {+ margin: 0;+ font-size: var(--text-md);+ color: var(--text);+ }++ .state p {+ margin: 0 0 var(--space-2);+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .state.error {+ border-color: color-mix(in srgb, var(--danger) 40%, var(--border));+ }++ .state.error h3 {+ color: var(--danger);+ }++ .success-icon {+ width: 36px;+ height: 36px;+ border-radius: var(--radius-full);+ display: grid;+ place-items: center;+ background: color-mix(in srgb, var(--success) 18%, transparent);+ color: var(--success);+ }++ @media (prefers-reduced-motion: reduce) {+ .step.current .step-dot {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/EmojiPicker.svelte b/src/components/omnidisc/EmojiPicker.sveltenew file mode 100644index 00000000..64b47de2--- /dev/null+++ b/src/components/omnidisc/EmojiPicker.svelte@@ -0,0 +1,149 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { EMOJI_GROUPS, rememberEmoji, recentEmojis, searchEmojis } from "$lib/omnidisc/emoji";++ let { onPick, onClose }: { onPick: (emoji: string) => void; onClose: () => void } = $props();++ let query = $state("");+ let recent = $state<string[]>(recentEmojis());+ let input = $state<HTMLInputElement | null>(null);++ $effect(() => {+ input?.focus();+ });++ let matches = $derived(searchEmojis(query));+ let grouped = $derived(+ EMOJI_GROUPS.map((group) => ({ group, items: matches.filter((e) => e.group === group) })).filter(+ (g) => g.items.length > 0,+ ),+ );++ function pick(char: string) {+ recent = rememberEmoji(char);+ onPick(char);+ }+</script>++<div+ class="picker"+ role="dialog"+ tabindex="-1"+ aria-label={$t("omnidisc.emoji.title")}+ onkeydown={(e) => {+ if (e.key === "Escape") {+ e.stopPropagation();+ onClose();+ }+ }}+>+ <input+ bind:this={input}+ bind:value={query}+ class="search"+ type="search"+ placeholder={$t("omnidisc.emoji.search")}+ aria-label={$t("omnidisc.emoji.search")}+ spellcheck="false"+ />+ <div class="scroll">+ {#if matches.length === 0}+ <p class="empty">{$t("omnidisc.emoji.no_match", { query })}</p>+ {:else}+ {#if recent.length > 0 && query.trim().length === 0}+ <h4 class="group-title">{$t("omnidisc.emoji.recent")}</h4>+ <div class="grid">+ {#each recent as char (char)}+ <button type="button" class="emoji" onclick={() => pick(char)} title={char}>{char}</button>+ {/each}+ </div>+ {/if}+ {#each grouped as group (group.group)}+ <h4 class="group-title">{$t(`omnidisc.emoji.group_${group.group}`)}</h4>+ <div class="grid">+ {#each group.items as item (item.char)}+ <button type="button" class="emoji" onclick={() => pick(item.char)} title={item.name}>{item.char}</button>+ {/each}+ </div>+ {/each}+ {/if}+ </div>+</div>++<style>+ .picker {+ width: 268px;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-2);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ box-shadow: var(--shadow-lg, 0 8px 24px rgba(0, 0, 0, 0.25));+ }++ .search {+ width: 100%;+ box-sizing: border-box;+ padding: 6px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .search:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .scroll {+ max-height: 240px;+ overflow-y: auto;+ }++ .group-title {+ margin: var(--space-2) 0 var(--space-1);+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .grid {+ display: grid;+ grid-template-columns: repeat(8, 1fr);+ gap: 2px;+ }++ .emoji {+ aspect-ratio: 1;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ font-size: var(--text-base);+ cursor: pointer;+ color: var(--text);+ }++ .emoji:hover {+ background: var(--fill-1);+ }++ .emoji:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .empty {+ margin: var(--space-3) var(--space-1);+ font-size: var(--text-sm);+ color: var(--text-muted);+ }+</style>diff --git a/src/components/omnidisc/IncomingCallBar.svelte b/src/components/omnidisc/IncomingCallBar.sveltenew file mode 100644index 00000000..e0d6945e--- /dev/null+++ b/src/components/omnidisc/IncomingCallBar.svelte@@ -0,0 +1,146 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { getChannel, dmTitle, userName } from "$lib/stores/omnidisc-store.svelte";+ import {+ getIncomingCall,+ ringSecondsLeft,+ acceptIncomingCall,+ dismissIncomingCall,+ isVoiceBusy,+ } from "$lib/stores/omnidisc-voice-store.svelte";++ let call = $derived(getIncomingCall());+ let busy = $derived(isVoiceBusy());+ let seconds = $derived(ringSecondsLeft());+ let channel = $derived(getChannel(call?.channelId ?? null));+ let caller = $derived(call ? userName(call.instanceId, call.fromUserId) : "");+ let group = $derived((channel?.recipientIds?.length ?? 0) > 2);+ let where = $derived(channel ? dmTitle(channel) : "");+</script>++{#if call}+ <section class="ring" aria-label={$t("omnidisc.call.incoming", { name: caller })} aria-live="assertive">+ <div class="who">+ <span class="pulse" aria-hidden="true"></span>+ <div class="lines">+ <span class="headline">+ {group+ ? $t("omnidisc.call.incoming_group", { name: caller, channel: where })+ : $t("omnidisc.call.incoming", { name: caller })}+ </span>+ <span class="countdown">{$t("omnidisc.call.expires_in", { seconds })}</span>+ </div>+ </div>+ <div class="actions">+ <button type="button" class="btn answer" disabled={busy} onclick={() => void acceptIncomingCall()}>+ {busy ? $t("omnidisc.call.joining") : $t("omnidisc.call.accept")}+ </button>+ <button type="button" class="btn" disabled={busy} onclick={dismissIncomingCall}>+ {$t("omnidisc.call.decline")}+ </button>+ </div>+ </section>+{/if}++<style>+ .ring {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-top: 1px solid color-mix(in srgb, var(--accent) 40%, var(--border));+ background: color-mix(in srgb, var(--accent) 10%, var(--surface));+ }++ .who {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ min-width: 0;+ }++ .pulse {+ width: 8px;+ height: 8px;+ flex: 0 0 8px;+ border-radius: var(--radius-full);+ background: var(--accent);+ animation: ring-pulse 1.4s ease-in-out infinite;+ }++ .lines {+ display: flex;+ flex-direction: column;+ gap: 1px;+ min-width: 0;+ }++ .headline {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .countdown {+ font-size: var(--text-xs);+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ }++ .actions {+ display: flex;+ gap: var(--space-2);+ }++ .btn {+ flex: 1;+ height: 30px;+ padding: 0 var(--space-3);+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface-mut);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .btn.answer {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ }++ .btn:hover:not(:disabled) {+ filter: brightness(1.08);+ }++ .btn:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .btn:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @keyframes ring-pulse {+ 0%,+ 100% {+ opacity: 1;+ }+ 50% {+ opacity: 0.35;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ .pulse {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/InstanceRail.svelte b/src/components/omnidisc/InstanceRail.sveltenew file mode 100644index 00000000..4098b282--- /dev/null+++ b/src/components/omnidisc/InstanceRail.svelte@@ -0,0 +1,465 @@+<script lang="ts">+ import { page } from "$app/state";+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ getInstances,+ getSelectedInstance,+ selectInstance,+ getGuilds,+ getSelectedGuildId,+ createGuild,+ joinInvite,+ reconnectInstance,+ resetConnect,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscGuild, OmnidiscInstance } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "./OmnidiscPrompt.svelte";++ let instances = $derived(getInstances());+ let selected = $derived(getSelectedInstance());+ let guilds = $derived(getGuilds(selected?.id ?? null));+ let selectedGuildId = $derived(getSelectedGuildId());+ let isHome = $derived(page.url.pathname === "/omnidisc");+ let isFriends = $derived(page.url.pathname.startsWith("/omnidisc/friends"));++ let menuOpen = $state(false);+ let dialog = $state<"create" | "join" | null>(null);+ let dialogBusy = $state(false);+ let dialogError = $state<string | null>(null);+ let guildName = $state("");+ let inviteCode = $state("");++ function initials(name: string): string {+ const parts = name.trim().split(/\s+/).filter(Boolean);+ if (parts.length === 0) return "?";+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();+ return (parts[0][0] + parts[1][0]).toUpperCase();+ }++ function openInstance(instance: OmnidiscInstance) {+ selectInstance(instance.id);+ goto("/omnidisc");+ }++ function openGuild(guild: OmnidiscGuild) {+ const first = guild.channels.find((c) => c.kind === "text") ?? guild.channels.find((c) => c.kind !== "category");+ if (!first) return;+ goto(`/omnidisc/g/${guild.id}/${first.id}`);+ }++ function statusKey(status: OmnidiscInstance["status"]): string {+ return `omnidisc.rail.status_${status}`;+ }++ function instanceTitle(instance: OmnidiscInstance): string {+ let base = `${instance.name} — ${$t(statusKey(instance.status))}`;+ if ((instance.status === "error" || instance.status === "signed_out") && instance.error) {+ base = `${base}. ${translateBackendError(instance.error, $t)}`;+ }+ if (instance.insecure) {+ base = `${base}. ${$t("omnidisc.connect.insecure_short")}`;+ }+ return base;+ }++ function openDialog(kind: "create" | "join") {+ menuOpen = false;+ dialogError = null;+ dialogBusy = false;+ dialog = kind;+ }++ function closeDialog() {+ dialog = null;+ guildName = "";+ inviteCode = "";+ dialogError = null;+ }++ async function submitCreate() {+ const instance = selected;+ if (!instance) return;+ dialogBusy = true;+ dialogError = null;+ try {+ const guild = await createGuild(instance.id, guildName.trim());+ closeDialog();+ if (guild) openGuild(guild);+ } catch (e) {+ dialogError = translateBackendError(typeof e === "string" ? e : String(e), $t);+ } finally {+ dialogBusy = false;+ }+ }++ async function submitJoin() {+ const instance = selected;+ if (!instance) return;+ dialogBusy = true;+ dialogError = null;+ try {+ const guild = await joinInvite(instance.id, inviteCode.trim());+ closeDialog();+ if (guild) openGuild(guild);+ } catch (e) {+ dialogError = translateBackendError(typeof e === "string" ? e : String(e), $t);+ } finally {+ dialogBusy = false;+ }+ }++ function addInstance() {+ menuOpen = false;+ resetConnect();+ goto("/omnidisc?add=1");+ }++ function onMenuKeydown(e: KeyboardEvent) {+ if (e.key === "Escape") menuOpen = false;+ }++ let canCreate = $derived(selected?.status === "connected");+</script>++<nav class="rail" aria-label={$t("omnidisc.title")}>+ <a class="rail-item home" class:active={isHome} href="/omnidisc" aria-label={$t("omnidisc.rail.home")} title={$t("omnidisc.rail.home")}>+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M21 12a8 8 0 0 1-8 8H7l-4 3V12a8 8 0 0 1 8-8h2a8 8 0 0 1 8 8z" />+ </svg>+ </a>++ <a class="rail-item friends" class:active={isFriends} href="/omnidisc/friends" aria-label={$t("omnidisc.friends.title")} title={$t("omnidisc.friends.title")}>+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />+ <circle cx="9" cy="7" r="4" />+ <path d="M23 21v-2a4 4 0 0 0-3-3.87" />+ <path d="M16 3.13a4 4 0 0 1 0 7.75" />+ </svg>+ </a>++ <div class="rail-divider" role="presentation"></div>++ {#each instances as instance (instance.id)}+ <button+ type="button"+ class="rail-item instance"+ class:active={selected?.id === instance.id}+ class:error={instance.status === "error" || instance.status === "signed_out"}+ onclick={() => openInstance(instance)}+ title={instanceTitle(instance)}+ aria-label={instanceTitle(instance)}+ aria-pressed={selected?.id === instance.id}+ >+ <span class="initials">{initials(instance.name)}</span>+ <span class="status-dot {instance.status}" aria-hidden="true"></span>+ {#if instance.insecure}+ <span class="insecure-dot" title={$t("omnidisc.rail.insecure", { name: instance.name })} aria-hidden="true">+ <svg viewBox="0 0 24 24" width="9" height="9" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">+ <path d="M12 6v7M12 17h.01" />+ </svg>+ </span>+ {/if}+ </button>+ {/each}++ {#if selected && (selected.status === "error" || selected.status === "disconnected" || selected.status === "signed_out")}+ <button+ type="button"+ class="rail-action"+ onclick={() => (selected?.status === "signed_out" ? addInstance() : reconnectInstance(selected.id))}+ title={selected.status === "signed_out" ? $t("omnidisc.rail.sign_in") : $t("omnidisc.rail.reconnect")}+ aria-label={selected.status === "signed_out" ? $t("omnidisc.rail.sign_in") : $t("omnidisc.rail.reconnect")}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M21 12a9 9 0 1 1-2.6-6.4" />+ <path d="M21 3v6h-6" />+ </svg>+ </button>+ {/if}++ {#if guilds.length > 0}+ <div class="rail-divider" role="presentation"></div>+ {#each guilds as guild (guild.id)}+ <button+ type="button"+ class="rail-item guild"+ class:active={selectedGuildId === guild.id}+ onclick={() => openGuild(guild)}+ title={guild.name}+ aria-label={guild.name}+ aria-pressed={selectedGuildId === guild.id}+ >+ <span class="initials">{initials(guild.name)}</span>+ </button>+ {/each}+ {/if}++ <div class="rail-spacer"></div>++ <div class="add-wrap">+ <button+ type="button"+ class="rail-item add"+ aria-label={$t("omnidisc.rail.menu")}+ title={$t("omnidisc.rail.menu")}+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ onclick={() => (menuOpen = !menuOpen)}+ >+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">+ <path d="M12 5v14M5 12h14" />+ </svg>+ </button>+ {#if menuOpen}+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div class="menu" role="menu" tabindex="-1" onkeydown={onMenuKeydown}>+ <button type="button" role="menuitem" onclick={() => openDialog("create")} disabled={!canCreate}>{$t("omnidisc.rail.create_server")}</button>+ <button type="button" role="menuitem" onclick={() => openDialog("join")} disabled={!canCreate}>{$t("omnidisc.rail.join_invite")}</button>+ <button type="button" role="menuitem" onclick={addInstance}>{$t("omnidisc.rail.add_instance")}</button>+ <button type="button" role="menuitem" onclick={() => { menuOpen = false; goto("/omnidisc/settings?view=voice"); }}>{$t("omnidisc.voice.settings")}</button>+ </div>+ {/if}+ </div>+</nav>++<OmnidiscPrompt+ open={dialog === "create"}+ title={$t("omnidisc.guild.create_title")}+ body={$t("omnidisc.guild.create_body")}+ submitLabel={$t("omnidisc.guild.create_submit")}+ busy={dialogBusy}+ error={dialogError}+ canSubmit={guildName.trim().length > 0}+ onSubmit={submitCreate}+ onClose={closeDialog}+>+ <label class="field">+ <span class="label">{$t("omnidisc.guild.name_label")}</span>+ <input class="input" type="text" bind:value={guildName} placeholder={$t("omnidisc.guild.name_placeholder")} maxlength="100" />+ </label>+</OmnidiscPrompt>++<OmnidiscPrompt+ open={dialog === "join"}+ title={$t("omnidisc.guild.join_title")}+ body={$t("omnidisc.guild.join_body")}+ submitLabel={$t("omnidisc.guild.join_submit")}+ busy={dialogBusy}+ error={dialogError}+ canSubmit={inviteCode.trim().length > 0}+ onSubmit={submitJoin}+ onClose={closeDialog}+>+ <label class="field">+ <span class="label">{$t("omnidisc.guild.join_label")}</span>+ <input class="input" type="text" bind:value={inviteCode} placeholder={$t("omnidisc.guild.join_placeholder")} spellcheck="false" autocomplete="off" />+ </label>+</OmnidiscPrompt>++<style>+ .rail {+ width: 64px;+ flex: 0 0 64px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-3) 0;+ background: var(--sidebar-bg);+ border-right: 1px solid var(--border);+ overflow-y: auto;+ overflow-x: hidden;+ }++ .rail-item {+ position: relative;+ width: 44px;+ height: 44px;+ flex: 0 0 44px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-lg);+ background: var(--surface);+ color: var(--text);+ text-decoration: none;+ cursor: pointer;+ transition: border-radius var(--duration-fast) var(--ease-out), background var(--duration-fast) var(--ease-out);+ }++ .rail-item:hover {+ background: var(--surface-hi);+ border-radius: var(--radius-md);+ }++ .rail-item:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .rail-item.active {+ background: var(--accent);+ color: var(--on-accent);+ border-radius: var(--radius-md);+ }++ .rail-item.active::before {+ content: "";+ position: absolute;+ left: -10px;+ top: 50%;+ width: 4px;+ height: 24px;+ transform: translateY(-50%);+ border-radius: var(--radius-full);+ background: var(--accent);+ }++ .rail-item.error {+ box-shadow: inset 0 0 0 1px var(--danger);+ }++ .initials {+ font-size: var(--text-sm);+ font-weight: 600;+ letter-spacing: var(--track-snug);+ }++ .status-dot {+ position: absolute;+ right: -2px;+ bottom: -2px;+ width: 12px;+ height: 12px;+ border-radius: var(--radius-full);+ border: 2px solid var(--sidebar-bg);+ background: var(--text-dim);+ }++ .status-dot.connected {+ background: var(--success);+ }++ .status-dot.connecting,+ .status-dot.reconnecting {+ background: var(--warning);+ }++ .status-dot.error,+ .status-dot.signed_out {+ background: var(--danger);+ }++ /* http instead of https: quiet but permanent, because it is a property of+ the server and not a one-off error the user can retry away. */+ .insecure-dot {+ position: absolute;+ left: -3px;+ bottom: -3px;+ width: 14px;+ height: 14px;+ display: grid;+ place-items: center;+ border-radius: var(--radius-full);+ border: 2px solid var(--sidebar-bg);+ background: var(--warning);+ color: var(--bg);+ }++ .rail-action {+ width: 28px;+ height: 28px;+ display: grid;+ place-items: center;+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-full);+ background: transparent;+ color: var(--text-muted);+ cursor: pointer;+ }++ .rail-action:hover {+ color: var(--accent);+ border-color: var(--accent);+ }++ .rail-action:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .rail-divider {+ width: 28px;+ height: 1px;+ background: var(--border);+ margin: var(--space-1) 0;+ }++ .rail-spacer {+ flex: 1;+ }++ .add-wrap {+ position: relative;+ }++ .rail-item.add {+ background: transparent;+ color: var(--text-muted);+ border: 1px dashed var(--border-hi);+ }++ .rail-item.add:hover {+ color: var(--accent);+ border-color: var(--accent);+ }++ .menu {+ position: absolute;+ left: 52px;+ bottom: 0;+ z-index: 30;+ display: flex;+ flex-direction: column;+ min-width: 200px;+ padding: var(--space-1);+ border-radius: var(--radius-md);+ border: 1px solid var(--border);+ background: var(--surface);+ }++ .menu button {+ padding: 8px var(--space-3);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ white-space: nowrap;+ }++ .menu button:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .menu button:disabled {+ color: var(--text-dim);+ cursor: default;+ }++ .menu button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @media (prefers-reduced-motion: reduce) {+ .rail-item {+ transition: none;+ }+ }+</style>diff --git a/src/components/omnidisc/MemberList.svelte b/src/components/omnidisc/MemberList.sveltenew file mode 100644index 00000000..ce7a7860--- /dev/null+++ b/src/components/omnidisc/MemberList.svelte@@ -0,0 +1,318 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { getMembers, getSelectedGuildId, getGuild, getInstance } from "$lib/stores/omnidisc-store.svelte";+ import { getVolume, setVolume, isSpeaking } from "$lib/stores/omnidisc-voice-store.svelte";+ import type { OmnidiscMember } from "$lib/omnidisc/types";+ import ProfilePopover from "./ProfilePopover.svelte";++ let guildId = $derived(getSelectedGuildId());+ let members = $derived(getMembers(guildId));+ let online = $derived(members.filter((m) => m.online));+ let offline = $derived(members.filter((m) => !m.online));+ let guild = $derived(getGuild(guildId));+ let instance = $derived(getInstance(guild?.instanceId ?? null));+ let me = $derived(instance?.userId ?? null);+ let profile = $state<{ userId: string; x: number; y: number } | null>(null);+ let menu = $state<{ member: OmnidiscMember; x: number; y: number } | null>(null);+ let menuEl = $state<HTMLDivElement | null>(null);+ let menuVolume = $derived(menu ? Math.round(getVolume(menu.member.id) * 100) : 100);++ function openMenu(e: MouseEvent, member: OmnidiscMember) {+ e.preventDefault();+ if (member.id === me) return;+ const x = Math.min(e.clientX, (typeof window !== "undefined" ? window.innerWidth : 9999) - 240);+ const y = Math.min(e.clientY, (typeof window !== "undefined" ? window.innerHeight : 9999) - 140);+ menu = { member, x, y };+ }++ function closeMenuOutside(e: PointerEvent) {+ if (!menu) return;+ if (menuEl && e.target instanceof Node && menuEl.contains(e.target)) return;+ menu = null;+ }++ function onVolumeInput(e: Event) {+ if (!menu) return;+ const v = Number((e.target as HTMLInputElement).value);+ setVolume(menu.member.id, v / 100);+ }++ function initial(name: string): string {+ return name.trim().charAt(0).toUpperCase() || "?";+ }++ function openProfile(member: OmnidiscMember, anchor: HTMLElement) {+ if (!instance) return;+ const rect = anchor.getBoundingClientRect();+ const width = typeof window !== "undefined" ? window.innerWidth : 1280;+ const height = typeof window !== "undefined" ? window.innerHeight : 800;+ profile = {+ userId: member.id,+ x: Math.max(8, Math.min(rect.left - 310, width - 320)),+ y: Math.min(rect.top, height - 420),+ };+ }+</script>++<aside class="member-list" aria-label={$t("omnidisc.members.title")}>+ {#if members.length === 0}+ <div class="empty">+ <p class="empty-title">{$t("omnidisc.members.empty")}</p>+ </div>+ {:else}+ {#if online.length > 0}+ <h3 class="group-title">{$t("omnidisc.members.online", { count: online.length })}</h3>+ <ul class="group">+ {#each online as member (member.id)}+ <li oncontextmenu={(e) => openMenu(e, member)}>+ <button+ type="button"+ class="member"+ title={$t("omnidisc.profile.open", { name: member.name })}+ onclick={(e) => openProfile(member, e.currentTarget)}+ >+ <span class="avatar" class:speaking={isSpeaking(member.id)}><span>{initial(member.name)}</span><span class="dot online" aria-hidden="true"></span></span>+ <span class="name">{member.name}</span>+ {#if member.role}+ <span class="role">{member.role === "owner" ? $t("omnidisc.members.owner") : member.role}</span>+ {/if}+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ {#if offline.length > 0}+ <h3 class="group-title">{$t("omnidisc.members.offline", { count: offline.length })}</h3>+ <ul class="group offline-group">+ {#each offline as member (member.id)}+ <li oncontextmenu={(e) => openMenu(e, member)}>+ <button+ type="button"+ class="member"+ title={$t("omnidisc.profile.open", { name: member.name })}+ onclick={(e) => openProfile(member, e.currentTarget)}+ >+ <span class="avatar"><span>{initial(member.name)}</span><span class="dot" aria-hidden="true"></span></span>+ <span class="name">{member.name}</span>+ {#if member.role}+ <span class="role">{member.role === "owner" ? $t("omnidisc.members.owner") : member.role}</span>+ {/if}+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ {/if}+</aside>++{#if profile && instance}+ <ProfilePopover+ instanceId={instance.id}+ userId={profile.userId}+ guildId={guildId}+ x={profile.x}+ y={profile.y}+ onClose={() => (profile = null)}+ />+{/if}++<svelte:window onpointerdown={closeMenuOutside} onkeydown={(e) => { if (e.key === "Escape") menu = null; }} />++{#if menu}+ <div class="ctx" role="dialog" aria-label={$t("omnidisc.voice.volume_for", { name: menu.member.name })} style:left={`${menu.x}px`} style:top={`${menu.y}px`} bind:this={menuEl}>+ <label class="ctx-label" for="od-member-volume">{$t("omnidisc.voice.volume_for", { name: menu.member.name })}</label>+ <div class="ctx-row">+ <input id="od-member-volume" type="range" min="0" max="200" step="5" value={menuVolume} oninput={onVolumeInput} />+ <span class="ctx-value">{menuVolume}%</span>+ </div>+ <div class="ctx-actions">+ <button type="button" class="ctx-btn" onclick={() => menu && setVolume(menu.member.id, 1)} disabled={menuVolume === 100}>{$t("omnidisc.voice.volume_reset")}</button>+ <button type="button" class="ctx-btn" onclick={() => { const m = menu; menu = null; if (m) openProfile(m.member, document.body); }}>{$t("omnidisc.profile.open", { name: menu.member.name })}</button>+ </div>+ </div>+{/if}++<style>+ .member-list {+ width: 220px;+ flex: 0 0 220px;+ min-height: 0;+ overflow-y: auto;+ padding: var(--space-3) var(--space-2);+ background: var(--surface-mut);+ border-left: 1px solid var(--border);+ }++ .group-title {+ margin: var(--space-2) var(--space-2) var(--space-1);+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .group {+ list-style: none;+ margin: 0 0 var(--space-3);+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .offline-group {+ opacity: 0.55;+ }++ .member {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ width: 100%;+ padding: 4px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .member:hover {+ background: var(--fill-1);+ }++ .member:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .avatar {+ position: relative;+ width: 28px;+ height: 28px;+ flex: 0 0 28px;+ border-radius: var(--radius-full);+ background: var(--accent-soft);+ color: var(--accent);+ display: grid;+ place-items: center;+ font-size: var(--text-xs);+ font-weight: 600;+ }++ .dot {+ position: absolute;+ right: -1px;+ bottom: -1px;+ width: 10px;+ height: 10px;+ border-radius: var(--radius-full);+ border: 2px solid var(--surface-mut);+ background: var(--text-dim);+ }++ .dot.online {+ background: var(--success);+ }++ .avatar.speaking {+ box-shadow: 0 0 0 2px var(--success);+ }++ .ctx {+ position: fixed;+ z-index: 50;+ width: 230px;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid var(--border);+ background: var(--surface);+ box-shadow: var(--shadow-lg, 0 8px 24px rgba(0, 0, 0, 0.25));+ }++ .ctx-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .ctx-row {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ }++ .ctx-row input {+ flex: 1;+ }++ .ctx-value {+ min-width: 40px;+ text-align: right;+ font-size: var(--text-xs);+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ }++ .ctx-actions {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .ctx-btn {+ width: 100%;+ padding: 6px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .ctx-btn:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .ctx-btn:disabled {+ color: var(--text-muted);+ cursor: default;+ }++ .ctx-btn:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .name {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .role {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .empty {+ padding: var(--space-3) var(--space-2);+ }++ .empty-title {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ }+</style>diff --git a/src/components/omnidisc/MessageAttachments.svelte b/src/components/omnidisc/MessageAttachments.sveltenew file mode 100644index 00000000..fda379ef--- /dev/null+++ b/src/components/omnidisc/MessageAttachments.svelte@@ -0,0 +1,303 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { downloadAttachment } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscAttachment, OmnidiscMessage } from "$lib/omnidisc/types";++ let { message }: { message: OmnidiscMessage } = $props();++ let lightbox = $state<OmnidiscAttachment | null>(null);+ let busyId = $state<string | null>(null);+ let savedPath = $state<string | null>(null);+ let error = $state<string | null>(null);++ let items = $derived(message.attachments ?? []);++ function sizeLabel(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ const units = ["KB", "MB", "GB"];+ let value = bytes / 1024;+ let unit = 0;+ while (value >= 1024 && unit < units.length - 1) {+ value /= 1024;+ unit += 1;+ }+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;+ }++ function kindOf(a: OmnidiscAttachment): "image" | "video" | "audio" | "file" {+ // An encrypted attachment is ciphertext at that URL: nothing can play it in+ // place, so it is always offered as a download.+ if (a.encrypted || !a.url) return "file";+ const mime = a.contentType ?? "";+ if (mime.startsWith("image/")) return "image";+ if (mime.startsWith("video/")) return "video";+ if (mime.startsWith("audio/")) return "audio";+ return "file";+ }++ async function save(attachment: OmnidiscAttachment) {+ busyId = attachment.id;+ error = null;+ savedPath = null;+ try {+ savedPath = await downloadAttachment(message.channelId, message, attachment);+ } catch (e) {+ const raw = typeof e === "string" ? e : e instanceof Error ? e.message : String(e);+ error = translateBackendError(raw, $t);+ } finally {+ busyId = null;+ }+ }++ function onKeydown(e: KeyboardEvent) {+ if (e.key === "Escape" && lightbox) {+ e.preventDefault();+ lightbox = null;+ }+ }+</script>++<svelte:window onkeydown={onKeydown} />++{#if items.length > 0}+ <ul class="attachments">+ {#each items as attachment (attachment.id)}+ {@const kind = kindOf(attachment)}+ <li class="item" class:media={kind === "image"}>+ {#if kind === "image"}+ <button+ type="button"+ class="image-button"+ style:aspect-ratio={attachment.width && attachment.height+ ? `${attachment.width} / ${attachment.height}`+ : undefined}+ onclick={() => (lightbox = attachment)}+ aria-label={$t("omnidisc.attachments.open_image", { name: attachment.filename })}+ >+ <img+ src={attachment.thumbnailUrl ?? attachment.url}+ alt={attachment.filename}+ loading="lazy"+ width={attachment.width}+ height={attachment.height}+ />+ </button>+ {:else if kind === "video"}+ <!-- svelte-ignore a11y_media_has_caption -->+ <video class="player" src={attachment.url} controls preload="metadata"></video>+ {:else if kind === "audio"}+ <audio class="player" src={attachment.url} controls preload="metadata"></audio>+ {:else}+ <div class="file">+ <span class="glyph" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3v5h5" /><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" /></svg>+ </span>+ <span class="detail">+ <span class="name" title={attachment.filename}>{attachment.filename}</span>+ <span class="meta">+ {sizeLabel(attachment.size)}{#if attachment.encrypted} · {$t("omnidisc.attachments.encrypted_note")}{/if}+ </span>+ </span>+ <button+ type="button"+ class="save"+ disabled={busyId === attachment.id}+ onclick={() => void save(attachment)}+ >+ {busyId === attachment.id+ ? $t("omnidisc.attachments.downloading")+ : $t("omnidisc.attachments.download")}+ </button>+ </div>+ {/if}+ </li>+ {/each}+ </ul>++ {#if savedPath}+ <p class="note" role="status">{$t("omnidisc.attachments.saved", { path: savedPath })}</p>+ {/if}+ {#if error}+ <p class="note danger" role="alert">{error}</p>+ {/if}+{/if}++{#if lightbox}+ <div+ class="lightbox"+ role="dialog"+ aria-modal="true"+ aria-label={lightbox.filename}+ tabindex="-1"+ >+ <img src={lightbox.url} alt={lightbox.filename} />+ <button+ type="button"+ class="close"+ onclick={() => (lightbox = null)}+ aria-label={$t("omnidisc.attachments.close_image")}+ >×</button>+ </div>+{/if}++<style>+ .attachments {+ list-style: none;+ margin: var(--space-1) 0 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .item {+ max-width: 420px;+ }++ .image-button {+ display: block;+ padding: 0;+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--fill-1);+ overflow: hidden;+ cursor: zoom-in;+ max-width: 100%;+ }++ .image-button img {+ display: block;+ max-width: 100%;+ max-height: 320px;+ width: auto;+ height: auto;+ }++ .image-button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .player {+ display: block;+ max-width: 100%;+ max-height: 320px;+ border-radius: var(--radius-md);+ }++ audio.player {+ width: 320px;+ max-height: none;+ }++ .file {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ }++ .glyph {+ display: grid;+ place-items: center;+ color: var(--text-muted);+ }++ .detail {+ display: flex;+ flex-direction: column;+ min-width: 0;+ flex: 1;+ }++ .name {+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .meta {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .save {+ flex: 0 0 auto;+ padding: 4px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .save:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .save:disabled {+ opacity: 0.6;+ cursor: default;+ }++ .save:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .note {+ margin: var(--space-1) 0 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ overflow-wrap: anywhere;+ }++ .note.danger {+ color: var(--danger);+ }++ .lightbox {+ position: fixed;+ inset: 0;+ z-index: 200;+ display: grid;+ place-items: center;+ padding: var(--space-5);+ background: var(--scrim, rgba(0, 0, 0, 0.72));+ }++ .lightbox img {+ max-width: 100%;+ max-height: 100%;+ border-radius: var(--radius-md);+ }++ .lightbox .close {+ position: absolute;+ top: var(--space-4);+ right: var(--space-4);+ width: 36px;+ height: 36px;+ border: none;+ border-radius: var(--radius-full);+ background: var(--surface);+ color: var(--text);+ font-size: var(--text-lg);+ line-height: 1;+ cursor: pointer;+ }++ .lightbox .close:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/components/omnidisc/MessageItem.svelte b/src/components/omnidisc/MessageItem.sveltenew file mode 100644index 00000000..213d1111--- /dev/null+++ b/src/components/omnidisc/MessageItem.svelte@@ -0,0 +1,793 @@+<script lang="ts">+ import { tick } from "svelte";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import type { OmnidiscMessage } from "$lib/omnidisc/types";+ import EmojiPicker from "./EmojiPicker.svelte";+ import MessageAttachments from "./MessageAttachments.svelte";++ let {+ message,+ showHeader,+ daySeparator,+ unreadDivider = false,+ highlighted = false,+ replyPreview = null,+ canEdit = false,+ canDelete = false,+ canPin = false,+ canReact = false,+ editing = false,+ onRetry,+ onDiscard,+ onReact,+ onReply,+ onStartEdit,+ onSubmitEdit,+ onCancelEdit,+ onDelete,+ onTogglePin,+ onCopyLink,+ onCopyId,+ onMarkUnread,+ onJumpToReply,+ onOpenProfile,+ }: {+ message: OmnidiscMessage;+ showHeader: boolean;+ daySeparator: boolean;+ unreadDivider?: boolean;+ highlighted?: boolean;+ replyPreview?: OmnidiscMessage | null;+ canEdit?: boolean;+ canDelete?: boolean;+ canPin?: boolean;+ canReact?: boolean;+ editing?: boolean;+ onRetry?: (message: OmnidiscMessage) => void;+ onDiscard?: (message: OmnidiscMessage) => void;+ onReact?: (message: OmnidiscMessage, emoji: string) => void;+ onReply?: (message: OmnidiscMessage) => void;+ onStartEdit?: (message: OmnidiscMessage) => void;+ onSubmitEdit?: (message: OmnidiscMessage, content: string) => void;+ onCancelEdit?: () => void;+ onDelete?: (message: OmnidiscMessage) => void;+ onTogglePin?: (message: OmnidiscMessage) => void;+ onCopyLink?: (message: OmnidiscMessage) => void;+ onCopyId?: (message: OmnidiscMessage) => void;+ onMarkUnread?: (message: OmnidiscMessage) => void;+ onJumpToReply?: (messageId: string) => void;+ onOpenProfile?: (userId: string, anchor: HTMLElement) => void;+ } = $props();++ let menuOpen = $state(false);+ let pickerOpen = $state(false);+ let editValue = $state("");+ let editArea = $state<HTMLTextAreaElement | null>(null);+ let root = $state<HTMLElement | null>(null);++ $effect(() => {+ if (!editing) return;+ editValue = message.content;+ tick().then(() => {+ editArea?.focus();+ editArea?.setSelectionRange(editValue.length, editValue.length);+ });+ });++ function dayLabel(ts: number): string {+ const date = new Date(ts);+ const today = new Date();+ const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();+ const startOfDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();+ const diffDays = Math.round((startOfToday - startOfDay) / 86_400_000);+ if (diffDays === 0) return $t("omnidisc.messages.today");+ if (diffDays === 1) return $t("omnidisc.messages.yesterday");+ return date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });+ }++ function timeLabel(ts: number): string {+ return new Date(ts).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });+ }++ function closeOverlays() {+ menuOpen = false;+ pickerOpen = false;+ }++ function onWindowPointerDown(e: PointerEvent) {+ if (!menuOpen && !pickerOpen) return;+ if (root && e.target instanceof Node && root.contains(e.target)) return;+ closeOverlays();+ }++ function react(emoji: string) {+ closeOverlays();+ onReact?.(message, emoji);+ }++ function editKeydown(e: KeyboardEvent) {+ if (e.key === "Escape") {+ e.preventDefault();+ onCancelEdit?.();+ return;+ }+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {+ e.preventDefault();+ submitEdit();+ }+ }++ function submitEdit() {+ const text = editValue.trim();+ if (!text || text === message.content) {+ onCancelEdit?.();+ return;+ }+ onSubmitEdit?.(message, text);+ }++ let initial = $derived(message.authorName.trim().charAt(0).toUpperCase() || "?");+ let pending = $derived(message.delivery === "pending");+ let failed = $derived(message.delivery === "failed");+ // MLS proves a group member sent this; it does not prove the identity string+ // in their credential. Anything the roster does not vouch for is called out.+ let unverified = $derived(message.senderVerified === false);+ let sent = $derived(message.delivery === "sent" || message.delivery === undefined);+ let showActions = $derived(sent && (canReact || canEdit || canDelete || canPin || !!onReply));+</script>++<svelte:window onpointerdown={onWindowPointerDown} />++{#if daySeparator}+ <div class="day-separator" role="separator" aria-label={dayLabel(message.createdAt)}>+ <span>{dayLabel(message.createdAt)}</span>+ </div>+{/if}++{#if unreadDivider}+ <div class="unread-divider" role="separator" aria-label={$t("omnidisc.messages.new_messages")}>+ <span>{$t("omnidisc.messages.new_messages")}</span>+ </div>+{/if}++<article+ bind:this={root}+ class="message"+ class:grouped={!showHeader}+ class:pending+ class:failed+ class:highlighted+ class:editing+ aria-label={message.authorName}+ data-message-id={message.id}+>+ {#if replyPreview || message.replyToId}+ <button+ type="button"+ class="reply-quote"+ onclick={() => message.replyToId && onJumpToReply?.(message.replyToId)}+ disabled={!message.replyToId}+ >+ <span class="reply-mark" aria-hidden="true">↰</span>+ {#if replyPreview}+ <span class="reply-author">{replyPreview.authorName}</span>+ <span class="reply-text">{replyPreview.content.slice(0, 120)}</span>+ {:else}+ <span class="reply-text muted">{$t("omnidisc.messages.reply_unavailable")}</span>+ {/if}+ </button>+ {/if}++ {#if showHeader}+ <button+ type="button"+ class="avatar"+ onclick={(e) => onOpenProfile?.(message.authorId, e.currentTarget)}+ aria-label={$t("omnidisc.profile.open", { name: message.authorName })}+ >{initial}</button>+ <div class="body">+ <header class="meta">+ <button+ type="button"+ class="author"+ onclick={(e) => onOpenProfile?.(message.authorId, e.currentTarget)}+ >{message.authorName}</button>+ <time class="time" datetime={new Date(message.createdAt).toISOString()}>{timeLabel(message.createdAt)}</time>+ {#if message.pinned}+ <span class="tag">{$t("omnidisc.messages.pinned")}</span>+ {/if}+ {#if unverified}+ {@render unverifiedBadge()}+ {/if}+ </header>+ {#if editing}+ <div class="edit">+ <textarea+ bind:this={editArea}+ bind:value={editValue}+ class="edit-input"+ rows="2"+ aria-label={$t("omnidisc.messages.edit_label")}+ onkeydown={editKeydown}+ ></textarea>+ <div class="edit-actions">+ <button type="button" class="mini primary" onclick={submitEdit}>{$t("omnidisc.messages.edit_save")}</button>+ <button type="button" class="mini" onclick={() => onCancelEdit?.()}>{$t("common.cancel")}</button>+ </div>+ </div>+ {:else if message.awaitingDecryption}+ <p class="content locked">{$t("omnidisc.e2ee.unavailable")}</p>+ {:else}+ {#if message.content}+ <p class="content">{message.content}{#if message.editedAt}<span class="edited"> {$t("omnidisc.messages.edited")}</span>{/if}</p>+ {/if}+ <MessageAttachments {message} />+ {/if}+ </div>+ {:else}+ <time class="time gutter" datetime={new Date(message.createdAt).toISOString()}>{timeLabel(message.createdAt)}</time>+ <div class="body">+ {#if unverified}+ <div class="unverified-row">{@render unverifiedBadge()}</div>+ {/if}+ {#if editing}+ <div class="edit">+ <textarea+ bind:this={editArea}+ bind:value={editValue}+ class="edit-input"+ rows="2"+ aria-label={$t("omnidisc.messages.edit_label")}+ onkeydown={editKeydown}+ ></textarea>+ <div class="edit-actions">+ <button type="button" class="mini primary" onclick={submitEdit}>{$t("omnidisc.messages.edit_save")}</button>+ <button type="button" class="mini" onclick={() => onCancelEdit?.()}>{$t("common.cancel")}</button>+ </div>+ </div>+ {:else if message.awaitingDecryption}+ <p class="content locked">{$t("omnidisc.e2ee.unavailable")}</p>+ {:else}+ {#if message.content}+ <p class="content">{message.content}{#if message.editedAt}<span class="edited"> {$t("omnidisc.messages.edited")}</span>{/if}</p>+ {/if}+ <MessageAttachments {message} />+ {/if}+ </div>+ {/if}++ {#if pending}+ <span class="status" role="status">{$t("omnidisc.messages.pending")}</span>+ {:else if failed}+ <div class="status failed-row" role="alert">+ <span>{$t("omnidisc.messages.failed")} {message.error ? translateBackendError(message.error, $t) : ""}</span>+ <button type="button" class="mini" onclick={() => onRetry?.(message)}>{$t("omnidisc.messages.retry")}</button>+ <button type="button" class="mini ghost" onclick={() => onDiscard?.(message)}>{$t("omnidisc.messages.discard")}</button>+ </div>+ {/if}++ {#if message.reactions && message.reactions.length > 0}+ <ul class="reactions">+ {#each message.reactions as r (r.emoji)}+ <li>+ <button+ type="button"+ class="reaction"+ class:me={r.me}+ disabled={!canReact}+ onclick={() => onReact?.(message, r.emoji)}+ aria-pressed={r.me}+ title={r.me ? $t("omnidisc.messages.reaction_remove", { emoji: r.emoji.split(":")[0] }) : $t("omnidisc.messages.reaction_add", { emoji: r.emoji.split(":")[0] })}+ >+ <span>{r.emoji.split(":")[0]}</span>+ <span class="count">{r.count}</span>+ </button>+ </li>+ {/each}+ </ul>+ {/if}++ {#if showActions && !editing}+ <div class="actions" class:open={menuOpen || pickerOpen}>+ {#if canReact}+ <button+ type="button"+ class="action"+ onclick={() => { pickerOpen = !pickerOpen; menuOpen = false; }}+ aria-expanded={pickerOpen}+ title={$t("omnidisc.messages.react")}+ aria-label={$t("omnidisc.messages.react")}+ >+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9" /><path d="M9 10h.01M15 10h.01M8.5 14.5a4.5 4.5 0 0 0 7 0" /></svg>+ </button>+ {/if}+ {#if onReply}+ <button type="button" class="action" onclick={() => onReply?.(message)} title={$t("omnidisc.messages.reply")} aria-label={$t("omnidisc.messages.reply")}>+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14L4 9l5-5" /><path d="M4 9h9a7 7 0 0 1 7 7v4" /></svg>+ </button>+ {/if}+ {#if canEdit}+ <button type="button" class="action" onclick={() => onStartEdit?.(message)} title={$t("omnidisc.messages.edit")} aria-label={$t("omnidisc.messages.edit")}>+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z" /></svg>+ </button>+ {/if}+ <button+ type="button"+ class="action"+ onclick={() => { menuOpen = !menuOpen; pickerOpen = false; }}+ aria-expanded={menuOpen}+ title={$t("omnidisc.messages.more")}+ aria-label={$t("omnidisc.messages.more")}+ >+ <svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="1.6" /><circle cx="12" cy="12" r="1.6" /><circle cx="19" cy="12" r="1.6" /></svg>+ </button>+ </div>++ {#if pickerOpen}+ <div class="overlay picker-anchor">+ <EmojiPicker onPick={react} onClose={() => (pickerOpen = false)} />+ </div>+ {/if}++ {#if menuOpen}+ <div class="overlay menu" role="menu" aria-label={$t("omnidisc.messages.more")}>+ {#if canPin}+ <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(); onTogglePin?.(message); }}>+ {message.pinned ? $t("omnidisc.messages.unpin") : $t("omnidisc.messages.pin")}+ </button>+ {/if}+ <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(); onMarkUnread?.(message); }}>+ {$t("omnidisc.messages.mark_unread")}+ </button>+ <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(); onCopyLink?.(message); }}>+ {$t("omnidisc.messages.copy_link")}+ </button>+ <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(); onCopyId?.(message); }}>+ {$t("omnidisc.messages.copy_id")}+ </button>+ {#if canDelete}+ <button type="button" class="menu-item danger" role="menuitem" onclick={() => { closeOverlays(); onDelete?.(message); }}>+ {$t("omnidisc.messages.delete")}+ </button>+ {/if}+ </div>+ {/if}+ {/if}+</article>++{#snippet unverifiedBadge()}+ <span+ class="unverified"+ role="note"+ title={$t("omnidisc.e2ee.unverified_hint", { name: message.authorName })}+ >+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M10.3 3.6 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.6a2 2 0 0 0-3.4 0z" />+ <path d="M12 9v4M12 17h.01" />+ </svg>+ {$t("omnidisc.e2ee.unverified")}+ </span>+{/snippet}++<style>+ .day-separator,+ .unread-divider {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ padding: var(--space-4) var(--space-4) var(--space-2);+ color: var(--text-muted);+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ }++ .day-separator::before,+ .day-separator::after,+ .unread-divider::before,+ .unread-divider::after {+ content: "";+ flex: 1;+ height: 1px;+ background: var(--border);+ }++ .unread-divider {+ color: var(--accent);+ padding-top: var(--space-2);+ }++ .unread-divider::before,+ .unread-divider::after {+ background: var(--accent);+ }++ .message {+ position: relative;+ display: grid;+ grid-template-columns: 40px 1fr;+ column-gap: var(--space-3);+ padding: var(--space-1) var(--space-4);+ margin-top: var(--space-3);+ }++ .message.grouped {+ margin-top: 0;+ }++ .message:hover {+ background: var(--fill-1);+ }++ .message.highlighted {+ background: var(--accent-soft);+ }++ .message.editing {+ background: var(--fill-1);+ }++ .message.pending .content {+ color: var(--text-muted);+ }++ .reply-quote {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: var(--space-2);+ width: 100%;+ padding: 0 0 2px;+ border: none;+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-xs);+ text-align: left;+ cursor: pointer;+ overflow: hidden;+ }++ .reply-quote:disabled {+ cursor: default;+ }++ .reply-quote:hover:not(:disabled) .reply-text {+ color: var(--text);+ }++ .reply-author {+ font-weight: 600;+ color: var(--text-secondary, var(--text));+ flex: 0 0 auto;+ }++ .reply-text {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .reply-text.muted {+ font-style: italic;+ }++ .avatar {+ width: 40px;+ height: 40px;+ padding: 0;+ border: none;+ border-radius: var(--radius-full);+ background: var(--accent-soft);+ color: var(--accent);+ display: grid;+ place-items: center;+ font: inherit;+ font-weight: 600;+ font-size: var(--text-base);+ cursor: pointer;+ }++ .avatar:focus-visible,+ .author:focus-visible,+ .reply-quote:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .body {+ min-width: 0;+ }++ .meta {+ display: flex;+ align-items: baseline;+ gap: var(--space-2);+ }++ .author {+ padding: 0;+ border: none;+ background: transparent;+ font: inherit;+ font-weight: 600;+ color: var(--text);+ font-size: var(--text-base);+ cursor: pointer;+ }++ .author:hover {+ text-decoration: underline;+ }++ .tag {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ /* Breaks the pattern on purpose: everything else in this header is quiet,+ so the one message whose sender cannot be confirmed is the thing the eye+ lands on. */+ .unverified {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 1px 6px;+ border: 1px solid var(--danger);+ border-radius: var(--radius-full);+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--danger);+ cursor: help;+ }++ .unverified-row {+ margin-bottom: 2px;+ }++ .time {+ color: var(--text-muted);+ font-size: var(--text-xs);+ font-variant-numeric: tabular-nums;+ }++ .time.gutter {+ align-self: start;+ padding-top: 3px;+ text-align: right;+ visibility: hidden;+ }++ .message.grouped:hover .time.gutter {+ visibility: visible;+ }++ .content.locked {+ color: var(--text-muted);+ font-style: italic;+ }++ .content {+ margin: 0;+ color: var(--text);+ font-size: var(--text-base);+ line-height: 1.5;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ }++ .edited {+ color: var(--text-muted);+ font-size: var(--text-xs);+ }++ .edit {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .edit-input {+ width: 100%;+ box-sizing: border-box;+ resize: vertical;+ padding: 8px var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-base);+ line-height: 1.45;+ }++ .edit-input:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .edit-actions {+ display: flex;+ gap: var(--space-2);+ }++ .status {+ grid-column: 2;+ margin-top: 2px;+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .failed-row {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ flex-wrap: wrap;+ color: var(--danger);+ }++ .mini {+ padding: 2px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .mini.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ }++ .mini.ghost {+ border-color: transparent;+ color: var(--text-muted);+ }++ .mini:hover:not(.primary) {+ border-color: var(--accent);+ color: var(--accent);+ }++ .mini:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .reactions {+ grid-column: 2;+ list-style: none;+ margin: var(--space-1) 0 0;+ padding: 0;+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-1);+ }++ .reaction {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 2px var(--space-2);+ border-radius: var(--radius-full);+ border: 1px solid var(--border);+ background: var(--surface);+ font: inherit;+ font-size: var(--text-xs);+ color: var(--text);+ cursor: pointer;+ }++ .reaction:disabled {+ cursor: default;+ }++ .reaction:hover:not(:disabled) {+ border-color: var(--accent);+ }++ .reaction.me {+ border-color: var(--accent);+ background: var(--accent-soft);+ }++ .reaction:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .count {+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ }++ .actions {+ position: absolute;+ top: -12px;+ right: var(--space-4);+ display: none;+ gap: 2px;+ padding: 2px;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface);+ box-shadow: var(--shadow-sm, 0 2px 6px rgba(0, 0, 0, 0.18));+ }++ .message:hover .actions,+ .message:focus-within .actions,+ .actions.open {+ display: flex;+ }++ .action {+ width: 26px;+ height: 26px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ cursor: pointer;+ }++ .action:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .action:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .overlay {+ position: absolute;+ top: 16px;+ right: var(--space-4);+ z-index: 30;+ }++ .menu {+ display: flex;+ flex-direction: column;+ min-width: 180px;+ padding: var(--space-1);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ box-shadow: var(--shadow-lg, 0 8px 24px rgba(0, 0, 0, 0.25));+ }++ .menu-item {+ padding: 6px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .menu-item:hover {+ background: var(--fill-1);+ }++ .menu-item.danger {+ color: var(--danger);+ }++ .menu-item:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/components/omnidisc/MessageList.svelte b/src/components/omnidisc/MessageList.sveltenew file mode 100644index 00000000..096a5194--- /dev/null+++ b/src/components/omnidisc/MessageList.svelte@@ -0,0 +1,278 @@+<script lang="ts">+ import { tick } from "svelte";+ import { t } from "$lib/i18n";+ import type { OmnidiscMessage } from "$lib/omnidisc/types";+ import VirtualList from "./VirtualList.svelte";+ import MessageItem from "./MessageItem.svelte";++ const GROUP_WINDOW_MS = 5 * 60_000;++ let {+ messages,+ loading = false,+ firstUnreadId = null,+ highlightId = null,+ editingId = null,+ canReact = false,+ canPin = false,+ canReply = false,+ canEditOf = () => false,+ canDeleteOf = () => false,+ onLoadOlder,+ onRetry,+ onDiscard,+ onReact,+ onReply,+ onStartEdit,+ onSubmitEdit,+ onCancelEdit,+ onDelete,+ onTogglePin,+ onCopyLink,+ onCopyId,+ onMarkUnread,+ onJumpToMessage,+ onOpenProfile,+ onHighlightShown,+ }: {+ messages: OmnidiscMessage[];+ loading?: boolean;+ firstUnreadId?: string | null;+ highlightId?: string | null;+ editingId?: string | null;+ canReact?: boolean;+ canPin?: boolean;+ canReply?: boolean;+ canEditOf?: (message: OmnidiscMessage) => boolean;+ canDeleteOf?: (message: OmnidiscMessage) => boolean;+ onLoadOlder?: () => void;+ onRetry?: (message: OmnidiscMessage) => void;+ onDiscard?: (message: OmnidiscMessage) => void;+ onReact?: (message: OmnidiscMessage, emoji: string) => void;+ onReply?: (message: OmnidiscMessage) => void;+ onStartEdit?: (message: OmnidiscMessage) => void;+ onSubmitEdit?: (message: OmnidiscMessage, content: string) => void;+ onCancelEdit?: () => void;+ onDelete?: (message: OmnidiscMessage) => void;+ onTogglePin?: (message: OmnidiscMessage) => void;+ onCopyLink?: (message: OmnidiscMessage) => void;+ onCopyId?: (message: OmnidiscMessage) => void;+ onMarkUnread?: (message: OmnidiscMessage) => void;+ onJumpToMessage?: (messageId: string) => void;+ onOpenProfile?: (userId: string, anchor: HTMLElement) => void;+ onHighlightShown?: () => void;+ } = $props();++ type Row = { message: OmnidiscMessage; showHeader: boolean; daySeparator: boolean; unreadDivider: boolean };++ let list = $state<ReturnType<typeof VirtualList> | null>(null);+ let atBottom = $state(true);++ function sameDay(a: number, b: number): boolean {+ const da = new Date(a);+ const db = new Date(b);+ return da.getFullYear() === db.getFullYear() && da.getMonth() === db.getMonth() && da.getDate() === db.getDate();+ }++ let byId = $derived(new Map(messages.map((m) => [m.id, m])));++ let rows = $derived.by<Row[]>(() => {+ const out: Row[] = [];+ let prev: OmnidiscMessage | null = null;+ for (const message of messages) {+ const daySeparator = !prev || !sameDay(prev.createdAt, message.createdAt);+ const showHeader =+ daySeparator ||+ !prev ||+ prev.authorId !== message.authorId ||+ message.createdAt - prev.createdAt > GROUP_WINDOW_MS;+ out.push({ message, showHeader, daySeparator, unreadDivider: message.id === firstUnreadId });+ prev = message;+ }+ return out;+ });++ const rowKey = (row: Row) => row.message.id;++ $effect(() => {+ const target = highlightId;+ if (!target) return;+ tick().then(() => {+ list?.scrollToKey(target);+ onHighlightShown?.();+ });+ });+</script>++<div class="message-list" aria-busy={loading}>+ {#if loading && messages.length === 0}+ <div class="skeleton" aria-label={$t("omnidisc.messages.loading")}>+ {#each Array(8) as _, i (i)}+ <div class="skeleton-row">+ <span class="skeleton-avatar"></span>+ <span class="skeleton-lines">+ <span class="skeleton-line short"></span>+ <span class="skeleton-line"></span>+ </span>+ </div>+ {/each}+ </div>+ {:else}+ <VirtualList+ bind:this={list}+ items={rows}+ getKey={rowKey}+ onReachTop={onLoadOlder}+ onBottomChange={(v) => (atBottom = v)}+ >+ {#snippet row(item)}+ <MessageItem+ message={item.message}+ showHeader={item.showHeader}+ daySeparator={item.daySeparator}+ unreadDivider={item.unreadDivider}+ highlighted={item.message.id === highlightId}+ editing={item.message.id === editingId}+ replyPreview={item.message.replyToId ? (byId.get(item.message.replyToId) ?? null) : null}+ canEdit={canEditOf(item.message)}+ canDelete={canDeleteOf(item.message)}+ {canPin}+ {canReact}+ {onRetry}+ {onDiscard}+ {onReact}+ onReply={canReply ? onReply : undefined}+ {onStartEdit}+ {onSubmitEdit}+ {onCancelEdit}+ {onDelete}+ {onTogglePin}+ {onCopyLink}+ {onCopyId}+ {onMarkUnread}+ onJumpToReply={onJumpToMessage}+ {onOpenProfile}+ />+ {/snippet}+ {#snippet empty()}+ <div class="empty">+ <h3>{$t("omnidisc.messages.empty_title")}</h3>+ <p>{$t("omnidisc.messages.empty_body")}</p>+ </div>+ {/snippet}+ </VirtualList>+ {#if !atBottom && messages.length > 0}+ <button type="button" class="present" onclick={() => list?.scrollToBottom()}>+ {$t("omnidisc.messages.jump_present")}+ <span aria-hidden="true">↓</span>+ </button>+ {/if}+ {/if}+</div>++<style>+ .message-list {+ position: relative;+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .present {+ position: absolute;+ right: var(--space-4);+ bottom: var(--space-3);+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ padding: 6px var(--space-3);+ border: none;+ border-radius: var(--radius-full);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-xs);+ font-weight: 600;+ cursor: pointer;+ box-shadow: var(--shadow-sm, 0 2px 6px rgba(0, 0, 0, 0.2));+ }++ .present:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .empty {+ height: 100%;+ display: flex;+ flex-direction: column;+ justify-content: flex-end;+ padding: var(--space-5) var(--space-4);+ gap: var(--space-1);+ }++ .empty h3 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .empty p {+ margin: 0;+ color: var(--text-muted);+ font-size: var(--text-sm);+ }++ .skeleton {+ display: flex;+ flex-direction: column;+ justify-content: flex-end;+ gap: var(--space-4);+ padding: var(--space-4);+ flex: 1;+ }++ .skeleton-row {+ display: grid;+ grid-template-columns: 40px 1fr;+ gap: var(--space-3);+ }++ .skeleton-avatar {+ width: 40px;+ height: 40px;+ border-radius: var(--radius-full);+ background: var(--fill-2);+ }++ .skeleton-lines {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding-top: var(--space-1);+ }++ .skeleton-line {+ height: 12px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ width: 70%;+ animation: pulse 1.4s ease-in-out infinite;+ }++ .skeleton-line.short {+ width: 30%;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/OmnidiscPrompt.svelte b/src/components/omnidisc/OmnidiscPrompt.sveltenew file mode 100644index 00000000..76bdfd10--- /dev/null+++ b/src/components/omnidisc/OmnidiscPrompt.svelte@@ -0,0 +1,215 @@+<script lang="ts">+ import { tick, type Snippet } from "svelte";+ import { t } from "$lib/i18n";++ let {+ open,+ title,+ body,+ submitLabel,+ busy = false,+ error = null,+ canSubmit = true,+ onSubmit,+ onClose,+ children,+ }: {+ open: boolean;+ title: string;+ body?: string;+ submitLabel: string;+ busy?: boolean;+ error?: string | null;+ canSubmit?: boolean;+ onSubmit: () => void;+ onClose: () => void;+ children: Snippet;+ } = $props();++ let panel = $state<HTMLElement | null>(null);++ $effect(() => {+ if (!open) return;+ tick().then(() => {+ const first = panel?.querySelector<HTMLElement>("input, select, textarea, button");+ first?.focus();+ });+ });++ function onKeydown(e: KeyboardEvent) {+ if (e.key === "Escape" && !busy) {+ e.stopPropagation();+ onClose();+ }+ }++ function submit(e: Event) {+ e.preventDefault();+ if (busy || !canSubmit) return;+ onSubmit();+ }+</script>++{#if open}+ <!-- svelte-ignore a11y_no_static_element_interactions -->+ <div class="backdrop" onkeydown={onKeydown} onclick={(e) => { if (e.target === e.currentTarget && !busy) onClose(); }}>+ <div class="panel" bind:this={panel} role="dialog" aria-modal="true" aria-labelledby="od-prompt-title" aria-busy={busy}>+ <form class="panel-form" onsubmit={submit}>+ <h2 id="od-prompt-title" class="title">{title}</h2>+ {#if body}+ <p class="body">{body}</p>+ {/if}+ <div class="fields">+ {@render children()}+ </div>+ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}+ <div class="actions">+ <button type="button" class="ghost" onclick={onClose} disabled={busy}>{$t("common.cancel")}</button>+ <button type="submit" class="primary" disabled={busy || !canSubmit}>+ {busy ? $t("omnidisc.guild.working") : submitLabel}+ </button>+ </div>+ </form>+ </div>+ </div>+{/if}++<style>+ .backdrop {+ position: fixed;+ inset: 0;+ z-index: 40;+ display: grid;+ place-items: center;+ padding: var(--space-5);+ background: color-mix(in srgb, var(--bg) 70%, transparent);+ }++ .panel {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ width: 100%;+ max-width: 400px;+ padding: var(--space-5);+ border-radius: var(--radius-lg);+ border: 1px solid var(--border);+ background: var(--surface);+ }++ .panel-form {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ }++ .title {+ margin: 0;+ font-size: var(--text-lg);+ font-weight: 600;+ color: var(--text);+ }++ .body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .fields {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ }++ .fields :global(.field) {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .fields :global(.label) {+ font-size: var(--text-sm);+ font-weight: 500;+ color: var(--text);+ }++ .fields :global(.input) {+ box-sizing: border-box;+ width: 100%;+ padding: 10px var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-base);+ }++ .fields :global(.input:focus-visible) {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .fields :global(.hint) {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .error {+ margin: 0;+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-md);+ border: 1px solid color-mix(in srgb, var(--danger) 40%, var(--border));+ color: var(--danger);+ font-size: var(--text-sm);+ line-height: 1.5;+ }++ .actions {+ display: flex;+ justify-content: flex-end;+ gap: var(--space-2);+ margin-top: var(--space-2);+ }++ .primary {+ padding: 10px var(--space-4);+ border: none;+ border-radius: var(--radius-md);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ cursor: pointer;+ }++ .primary:disabled {+ opacity: 0.6;+ cursor: default;+ }++ .ghost {+ padding: 10px var(--space-3);+ border: none;+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .ghost:hover {+ color: var(--text);+ }++ .primary:focus-visible,+ .ghost:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/components/omnidisc/PinsPanel.svelte b/src/components/omnidisc/PinsPanel.sveltenew file mode 100644index 00000000..8efdf934--- /dev/null+++ b/src/components/omnidisc/PinsPanel.svelte@@ -0,0 +1,263 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { getPins, loadPins, setPinned, userName } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscMessage } from "$lib/omnidisc/types";++ let {+ instanceId,+ channelId,+ canPin = false,+ onJump,+ onClose,+ }: {+ instanceId: string;+ channelId: string;+ canPin?: boolean;+ onJump: (messageId: string) => void;+ onClose: () => void;+ } = $props();++ let loading = $state(true);+ let error = $state<string | null>(null);+ let pins = $derived(getPins(channelId));++ $effect(() => {+ const id = channelId;+ loading = true;+ error = null;+ loadPins(id)+ .catch((e) => {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ })+ .finally(() => {+ loading = false;+ });+ });++ function timeLabel(ts: number): string {+ return new Date(ts).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });+ }++ async function unpin(message: OmnidiscMessage) {+ error = null;+ try {+ await setPinned(channelId, message.id, false);+ } catch (e) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }+ }+</script>++<aside class="pins-panel" aria-label={$t("omnidisc.pins.title")}>+ <header class="head">+ <h3>{$t("omnidisc.pins.title")}</h3>+ <button type="button" class="close" onclick={onClose} aria-label={$t("common.close")}>×</button>+ </header>++ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ {#if loading}+ <div class="state" aria-busy="true">+ {#each Array(3) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if pins.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.pins.empty_title")}</p>+ <p class="state-body">{$t("omnidisc.pins.empty_body")}</p>+ </div>+ {:else}+ <ul class="list">+ {#each pins as pin (pin.id)}+ <li class="item">+ <button type="button" class="jump" onclick={() => onJump(pin.id)}>+ <span class="item-head">+ <span class="item-author">{userName(instanceId, pin.authorId)}</span>+ <span class="item-time">{timeLabel(pin.createdAt)}</span>+ </span>+ <span class="item-text">{pin.content.slice(0, 220)}</span>+ </button>+ {#if canPin}+ <button type="button" class="unpin" onclick={() => void unpin(pin)}>{$t("omnidisc.pins.unpin")}</button>+ {/if}+ </li>+ {/each}+ </ul>+ {/if}+</aside>++<style>+ .pins-panel {+ width: 300px;+ flex: 0 0 300px;+ min-height: 0;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3);+ background: var(--surface-mut);+ border-left: 1px solid var(--border);+ }++ .head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }++ .head h3 {+ margin: 0;+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .close {+ width: 24px;+ height: 24px;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font-size: var(--text-base);+ line-height: 1;+ cursor: pointer;+ }++ .close:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3) 0;+ }++ .state-title {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .skeleton-line {+ height: 44px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .item {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding-bottom: var(--space-2);+ border-bottom: 1px solid var(--border);+ }++ .jump {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: var(--space-1);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+ }++ .jump:hover {+ background: var(--fill-1);+ }++ .item-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-2);+ }++ .item-author {+ font-size: var(--text-sm);+ font-weight: 600;+ }++ .item-time {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .item-text {+ font-size: var(--text-sm);+ color: var(--text-secondary, var(--text));+ line-height: 1.4;+ overflow-wrap: anywhere;+ }++ .unpin {+ align-self: flex-start;+ padding: 2px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .unpin:hover {+ color: var(--text);+ border-color: var(--accent);+ }++ .jump:focus-visible,+ .unpin:focus-visible,+ .close:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/ProfilePopover.svelte b/src/components/omnidisc/ProfilePopover.sveltenew file mode 100644index 00000000..165cd5bf--- /dev/null+++ b/src/components/omnidisc/ProfilePopover.svelte@@ -0,0 +1,557 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ acceptFriend,+ addFriend,+ banMember,+ blockUser,+ canInGuild,+ getGuild,+ getInstance,+ getMember,+ getNote,+ getRoles,+ getUser,+ isGuildOwner,+ kickMember,+ loadNotes,+ mutualGuilds,+ openDm,+ relationshipWith,+ removeFriend,+ saveNote,+ updateMember,+ userName,+ } from "$lib/stores/omnidisc-store.svelte";+ import OmnidiscPrompt from "./OmnidiscPrompt.svelte";++ let {+ instanceId,+ userId,+ guildId = null,+ x,+ y,+ onClose,+ }: {+ instanceId: string;+ userId: string;+ guildId?: string | null;+ x: number;+ y: number;+ onClose: () => void;+ } = $props();++ type Action = "kick" | "ban" | "timeout" | "nickname" | null;++ let panel = $state<HTMLElement | null>(null);+ let note = $state("");+ let noteLoaded = $state(false);+ let busy = $state(false);+ let error = $state<string | null>(null);+ let action = $state<Action>(null);+ let reason = $state("");+ let nickname = $state("");+ let timeoutMinutes = $state(60);++ let instance = $derived(getInstance(instanceId));+ let user = $derived(getUser(instanceId, userId));+ let member = $derived(getMember(guildId, userId));+ let guild = $derived(getGuild(guildId));+ let me = $derived(instance?.userId ?? null);+ let isMe = $derived(me === userId);+ let relationship = $derived(relationshipWith(instanceId, userId));+ let mutual = $derived(mutualGuilds(instanceId, userId));+ let roleNames = $derived(+ (member?.roleIds ?? [])+ .map((id) => getRoles(guildId).find((r) => r.id === id))+ .filter((r) => r && !r.isEveryone)+ .map((r) => r?.name ?? ""),+ );+ let displayName = $derived(user?.displayName ?? userName(instanceId, userId));+ let canKick = $derived(!isMe && !!guildId && canInGuild(guildId, "KICK_MEMBERS"));+ let canBan = $derived(!isMe && !!guildId && canInGuild(guildId, "BAN_MEMBERS"));+ let canTimeout = $derived(!isMe && !!guildId && canInGuild(guildId, "MODERATE_MEMBERS"));+ let canNickname = $derived(!isMe && !!guildId && canInGuild(guildId, "MANAGE_NICKNAMES"));+ let targetIsOwner = $derived(!!guild && guild.ownerId === userId);+ let moderationAllowed = $derived(!targetIsOwner || isGuildOwner(guildId));++ $effect(() => {+ if (noteLoaded || !instanceId) return;+ noteLoaded = true;+ loadNotes(instanceId)+ .then(() => {+ note = getNote(instanceId, userId);+ })+ .catch(() => {+ note = "";+ });+ });++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function run(fn: () => Promise<void>) {+ busy = true;+ error = null;+ try {+ await fn();+ action = null;+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ async function message() {+ await run(async () => {+ const channel = await openDm(instanceId, userId);+ if (channel) {+ onClose();+ await goto(`/omnidisc/dm/${channel.id}`);+ }+ });+ }++ function onWindowPointerDown(e: PointerEvent) {+ if (action) return;+ if (panel && e.target instanceof Node && panel.contains(e.target)) return;+ onClose();+ }++ function confirmTitle(): string {+ switch (action) {+ case "kick":+ return $t("omnidisc.profile.kick_title", { name: displayName });+ case "ban":+ return $t("omnidisc.profile.ban_title", { name: displayName });+ case "timeout":+ return $t("omnidisc.profile.timeout_title", { name: displayName });+ case "nickname":+ return $t("omnidisc.profile.nickname_title", { name: displayName });+ default:+ return "";+ }+ }++ function confirmSubmitLabel(): string {+ switch (action) {+ case "kick":+ return $t("omnidisc.profile.kick_confirm", { name: displayName });+ case "ban":+ return $t("omnidisc.profile.ban_confirm", { name: displayName });+ case "timeout":+ return $t("omnidisc.profile.timeout_confirm", { name: displayName });+ case "nickname":+ return $t("omnidisc.profile.nickname_confirm");+ default:+ return "";+ }+ }++ async function submitAction() {+ if (!guildId) return;+ const current = action;+ await run(async () => {+ if (current === "kick") await kickMember(guildId, userId, reason.trim() || undefined);+ else if (current === "ban") await banMember(guildId, userId, reason.trim() || undefined);+ else if (current === "timeout") {+ const until = new Date(Date.now() + timeoutMinutes * 60_000).toISOString();+ await updateMember(guildId, userId, { muted_until: until, reason: reason.trim() || undefined });+ } else if (current === "nickname") {+ await updateMember(guildId, userId, { nick: nickname.trim() || null });+ }+ reason = "";+ onClose();+ });+ }++ async function copyId() {+ try {+ await navigator.clipboard.writeText(userId);+ } catch {+ error = $t("omnidisc.profile.copy_failed");+ }+ }+</script>++<svelte:window onpointerdown={onWindowPointerDown} onkeydown={(e) => { if (e.key === "Escape" && !action) onClose(); }} />++<div+ class="profile"+ role="dialog"+ aria-label={$t("omnidisc.profile.title", { name: displayName })}+ bind:this={panel}+ style:left={`${x}px`}+ style:top={`${y}px`}+>+ <div class="banner" style:background={user?.accentColor !== undefined ? `#${user.accentColor.toString(16).padStart(6, "0")}` : "var(--accent-soft)"}></div>+ <div class="head">+ <span class="avatar" aria-hidden="true">{displayName.trim().charAt(0).toUpperCase() || "?"}</span>+ <div class="names">+ <strong class="display">{member?.nick || displayName}</strong>+ <span class="handle">@{user?.username ?? "…"}</span>+ {#if user?.pronouns}+ <span class="pronouns">{user.pronouns}</span>+ {/if}+ </div>+ </div>++ {#if user?.bio}+ <p class="bio">{user.bio}</p>+ {/if}++ {#if roleNames.length > 0}+ <div class="section">+ <h4>{$t("omnidisc.profile.roles")}</h4>+ <ul class="chips">+ {#each roleNames as name (name)}+ <li class="chip">{name}</li>+ {/each}+ </ul>+ </div>+ {/if}++ {#if mutual.length > 0}+ <div class="section">+ <h4>{$t("omnidisc.profile.mutual_servers", { count: mutual.length })}</h4>+ <ul class="chips">+ {#each mutual.slice(0, 6) as g (g.id)}+ <li class="chip">{g.name}</li>+ {/each}+ </ul>+ </div>+ {/if}++ {#if !isMe}+ <div class="section">+ <label class="note-label" for="od-profile-note">{$t("omnidisc.profile.note")}</label>+ <textarea+ id="od-profile-note"+ class="note"+ rows="2"+ bind:value={note}+ placeholder={$t("omnidisc.profile.note_placeholder")}+ onblur={() => void run(() => saveNote(instanceId, userId, note))}+ ></textarea>+ </div>+ {/if}++ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ {#if !isMe}+ <div class="actions">+ <button type="button" class="btn primary" onclick={() => void message()} disabled={busy}>+ {$t("omnidisc.profile.message")}+ </button>+ {#if relationship?.kind === "incoming_request"}+ <button type="button" class="btn" onclick={() => void run(() => acceptFriend(instanceId, userId))} disabled={busy}>+ {$t("omnidisc.friends.accept")}+ </button>+ {:else if relationship?.kind === "friend"}+ <button type="button" class="btn" onclick={() => void run(() => removeFriend(instanceId, userId))} disabled={busy}>+ {$t("omnidisc.friends.remove")}+ </button>+ {:else if relationship?.kind === "outgoing_request"}+ <span class="pending-note">{$t("omnidisc.friends.request_sent")}</span>+ {:else if relationship?.kind !== "blocked" && user}+ <button type="button" class="btn" onclick={() => void run(() => addFriend(instanceId, user.username))} disabled={busy}>+ {$t("omnidisc.friends.add")}+ </button>+ {/if}+ <button type="button" class="btn" onclick={() => void copyId()}>{$t("omnidisc.profile.copy_id")}</button>+ {#if relationship?.kind === "blocked"}+ <button type="button" class="btn" onclick={() => void run(() => removeFriend(instanceId, userId))} disabled={busy}>+ {$t("omnidisc.friends.unblock")}+ </button>+ {:else}+ <button type="button" class="btn" onclick={() => void run(() => blockUser(instanceId, userId))} disabled={busy}>+ {$t("omnidisc.friends.block")}+ </button>+ {/if}+ </div>+ {/if}++ {#if moderationAllowed && (canNickname || canTimeout || canKick || canBan)}+ <div class="actions moderation">+ <h4>{$t("omnidisc.profile.moderation")}</h4>+ {#if canNickname}+ <button type="button" class="btn" onclick={() => { nickname = member?.nick ?? ""; action = "nickname"; }}>{$t("omnidisc.profile.nickname")}</button>+ {/if}+ {#if canTimeout}+ <button type="button" class="btn" onclick={() => (action = "timeout")}>{$t("omnidisc.profile.timeout")}</button>+ {/if}+ {#if canKick}+ <button type="button" class="btn" onclick={() => (action = "kick")}>{$t("omnidisc.profile.kick")}</button>+ {/if}+ {#if canBan}+ <button type="button" class="btn danger" onclick={() => (action = "ban")}>{$t("omnidisc.profile.ban")}</button>+ {/if}+ </div>+ {/if}+</div>++<OmnidiscPrompt+ open={action !== null}+ title={confirmTitle()}+ body={action === "ban" ? $t("omnidisc.profile.ban_body", { name: displayName }) : action === "kick" ? $t("omnidisc.profile.kick_body", { name: displayName }) : undefined}+ submitLabel={confirmSubmitLabel()}+ busy={busy}+ error={error}+ onSubmit={() => void submitAction()}+ onClose={() => { action = null; error = null; }}+>+ {#if action === "nickname"}+ <label class="field">+ <span class="field-label">{$t("omnidisc.profile.nickname_label")}</span>+ <input class="field-input" type="text" bind:value={nickname} maxlength="32" placeholder={displayName} />+ </label>+ {:else if action === "timeout"}+ <label class="field">+ <span class="field-label">{$t("omnidisc.profile.timeout_label")}</span>+ <select class="field-input" bind:value={timeoutMinutes}>+ <option value={5}>{$t("omnidisc.profile.timeout_5m")}</option>+ <option value={60}>{$t("omnidisc.profile.timeout_1h")}</option>+ <option value={1440}>{$t("omnidisc.profile.timeout_1d")}</option>+ <option value={10080}>{$t("omnidisc.profile.timeout_1w")}</option>+ </select>+ </label>+ <label class="field">+ <span class="field-label">{$t("omnidisc.profile.reason_label")}</span>+ <input class="field-input" type="text" bind:value={reason} maxlength="200" />+ </label>+ {:else}+ <label class="field">+ <span class="field-label">{$t("omnidisc.profile.reason_label")}</span>+ <input class="field-input" type="text" bind:value={reason} maxlength="200" placeholder={$t("omnidisc.profile.reason_placeholder")} />+ </label>+ {/if}+</OmnidiscPrompt>++<style>+ .profile {+ position: fixed;+ z-index: 60;+ width: 300px;+ max-height: 80vh;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ padding-bottom: var(--space-3);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ box-shadow: var(--shadow-lg, 0 8px 24px rgba(0, 0, 0, 0.25));+ }++ .banner {+ height: 56px;+ border-radius: var(--radius-md) var(--radius-md) 0 0;+ }++ .head {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ padding: 0 var(--space-3);+ margin-top: -22px;+ }++ .avatar {+ width: 52px;+ height: 52px;+ flex: 0 0 52px;+ border-radius: var(--radius-full);+ border: 3px solid var(--surface);+ background: var(--accent-soft);+ color: var(--accent);+ display: grid;+ place-items: center;+ font-size: var(--text-lg);+ font-weight: 600;+ }++ .names {+ display: flex;+ flex-direction: column;+ min-width: 0;+ padding-top: 20px;+ }++ .display {+ font-size: var(--text-base);+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .handle,+ .pronouns {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .bio {+ margin: 0 var(--space-3);+ font-size: var(--text-sm);+ color: var(--text-secondary, var(--text));+ line-height: 1.45;+ white-space: pre-wrap;+ }++ .section {+ padding: 0 var(--space-3);+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .section h4,+ .moderation h4 {+ margin: 0;+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .chips {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+ }++ .chip {+ padding: 2px var(--space-2);+ border-radius: var(--radius-full);+ border: 1px solid var(--border);+ font-size: var(--text-xs);+ color: var(--text-secondary, var(--text));+ }++ .note-label {+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .note {+ width: 100%;+ box-sizing: border-box;+ resize: vertical;+ padding: 6px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .note:focus-visible,+ .field-input:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .actions {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-1);+ padding: 0 var(--space-3);+ }++ .moderation {+ flex-direction: column;+ align-items: stretch;+ border-top: 1px solid var(--border);+ padding-top: var(--space-2);+ }++ .btn {+ flex: 1 1 auto;+ padding: 6px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ text-align: center;+ }++ .btn:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .btn:disabled {+ opacity: 0.6;+ cursor: default;+ }++ .btn.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ }++ .btn.danger {+ color: var(--danger);+ border-color: var(--danger);+ }++ .btn:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .pending-note {+ flex: 1 1 auto;+ font-size: var(--text-xs);+ color: var(--text-muted);+ align-self: center;+ }++ .error {+ margin: 0 var(--space-3);+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ width: 100%;+ box-sizing: border-box;+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }+</style>diff --git a/src/components/omnidisc/SearchPanel.svelte b/src/components/omnidisc/SearchPanel.sveltenew file mode 100644index 00000000..e079bcbe--- /dev/null+++ b/src/components/omnidisc/SearchPanel.svelte@@ -0,0 +1,422 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { getMembers, getUser, searchMessages, userName, type SearchFilters } from "$lib/stores/omnidisc-store.svelte";+ import { snowflakeForTime } from "$lib/omnidisc/snowflake";+ import type { OmnidiscMessage } from "$lib/omnidisc/types";+ import VirtualList from "./VirtualList.svelte";++ let {+ instanceId,+ guildId = null,+ channelId,+ onJump,+ onClose,+ }: {+ instanceId: string;+ guildId?: string | null;+ channelId: string;+ onJump: (channelId: string, messageId: string) => void;+ onClose: () => void;+ } = $props();++ let raw = $state("");+ let scope = $state<"channel" | "guild">("channel");+ let scopeSeeded = false;++ $effect(() => {+ if (scopeSeeded) return;+ scopeSeeded = true;+ if (guildId) scope = "guild";+ });+ let results = $state<OmnidiscMessage[]>([]);+ let total = $state(0);+ let ran = $state(false);+ let busy = $state(false);+ let error = $state<string | null>(null);+ let unknownFrom = $state<string | null>(null);+ let input = $state<HTMLInputElement | null>(null);++ $effect(() => {+ input?.focus();+ });++ function resolveUser(name: string): string | null {+ const needle = name.trim().toLowerCase();+ if (!needle) return null;+ for (const member of getMembers(guildId)) {+ if (member.name.toLowerCase() === needle) return member.id;+ const user = getUser(instanceId, member.id);+ if (user && (user.username.toLowerCase() === needle || user.displayName.toLowerCase() === needle)) return member.id;+ }+ return null;+ }++ function parseDate(value: string): string | null {+ const parsed = Date.parse(value);+ return Number.isFinite(parsed) ? snowflakeForTime(parsed) : null;+ }++ function parse(): { query: string; filters: SearchFilters } {+ const filters: SearchFilters = {};+ unknownFrom = null;+ const words: string[] = [];+ for (const token of raw.split(/\s+/)) {+ const [key, ...rest] = token.split(":");+ const value = rest.join(":");+ if (!value) {+ if (token) words.push(token);+ continue;+ }+ if (key === "from") {+ const id = resolveUser(value);+ if (id) filters.from = id;+ else unknownFrom = value;+ } else if (key === "has" && (value === "file" || value === "image" || value === "link")) {+ filters.has = value;+ } else if (key === "before") {+ const snow = parseDate(value);+ if (snow) filters.before = snow;+ } else if (key === "after") {+ const snow = parseDate(value);+ if (snow) filters.after = snow;+ } else {+ words.push(token);+ }+ }+ return { query: words.join(" "), filters };+ }++ async function run() {+ const { query, filters } = parse();+ if (!query.trim()) {+ results = [];+ total = 0;+ ran = false;+ return;+ }+ busy = true;+ error = null;+ try {+ const scopeId = scope === "guild" && guildId ? guildId : channelId;+ const outcome = await searchMessages(instanceId, scope === "guild" && guildId ? "guild" : "channel", scopeId, query, filters);+ results = outcome.messages;+ total = outcome.total;+ ran = true;+ } catch (e) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ results = [];+ total = 0;+ ran = true;+ } finally {+ busy = false;+ }+ }++ function timeLabel(ts: number): string {+ return new Date(ts).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });+ }++ const key = (m: OmnidiscMessage) => m.id;+</script>++<aside class="search-panel" aria-label={$t("omnidisc.search.title")}>+ <header class="head">+ <h3>{$t("omnidisc.search.title")}</h3>+ <button type="button" class="close" onclick={onClose} aria-label={$t("common.close")}>×</button>+ </header>++ <form+ class="form"+ onsubmit={(e) => {+ e.preventDefault();+ void run();+ }}+ >+ <input+ bind:this={input}+ bind:value={raw}+ class="input"+ type="search"+ placeholder={$t("omnidisc.search.placeholder")}+ aria-label={$t("omnidisc.search.placeholder")}+ spellcheck="false"+ />+ {#if guildId}+ <div class="scope" role="radiogroup" aria-label={$t("omnidisc.search.scope")}>+ <label class="scope-opt" class:on={scope === "channel"}>+ <input type="radio" name="od-search-scope" value="channel" bind:group={scope} />+ {$t("omnidisc.search.scope_channel")}+ </label>+ <label class="scope-opt" class:on={scope === "guild"}>+ <input type="radio" name="od-search-scope" value="guild" bind:group={scope} />+ {$t("omnidisc.search.scope_guild")}+ </label>+ </div>+ {/if}+ <button type="submit" class="run" disabled={busy || raw.trim().length === 0}>{$t("omnidisc.search.run")}</button>+ </form>++ <p class="hint">{$t("omnidisc.search.filters_hint")}</p>++ {#if unknownFrom}+ <p class="warn" role="status">{$t("omnidisc.search.unknown_from", { name: unknownFrom })}</p>+ {/if}++ {#if error}+ <p class="warn error" role="alert">{error}</p>+ {:else if busy}+ <div class="state" aria-busy="true">+ {#each Array(4) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if !ran}+ <div class="state">+ <p class="state-title">{$t("omnidisc.search.idle_title")}</p>+ <p class="state-body">{$t("omnidisc.search.idle_body")}</p>+ </div>+ {:else if results.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.search.empty_title")}</p>+ <p class="state-body">{$t("omnidisc.search.empty_body")}</p>+ </div>+ {:else}+ <p class="count">{$t("omnidisc.search.results", { count: total })}</p>+ <div class="results">+ <VirtualList items={results} getKey={key} estimateHeight={72}>+ {#snippet row(item)}+ <button type="button" class="result" onclick={() => onJump(item.channelId, item.id)}>+ <span class="result-head">+ <span class="result-author">{userName(instanceId, item.authorId)}</span>+ <span class="result-time">{timeLabel(item.createdAt)}</span>+ </span>+ <span class="result-text">{item.content.slice(0, 220)}</span>+ </button>+ {/snippet}+ </VirtualList>+ </div>+ {/if}+</aside>++<style>+ .search-panel {+ width: 300px;+ flex: 0 0 300px;+ min-height: 0;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3);+ background: var(--surface-mut);+ border-left: 1px solid var(--border);+ }++ .head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ }++ .head h3 {+ margin: 0;+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .close {+ width: 24px;+ height: 24px;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font-size: var(--text-base);+ line-height: 1;+ cursor: pointer;+ }++ .close:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .form {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .input {+ width: 100%;+ box-sizing: border-box;+ padding: 6px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .input:focus-visible,+ .run:focus-visible,+ .result:focus-visible,+ .close:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .scope {+ display: flex;+ gap: var(--space-1);+ }++ .scope-opt {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 4px;+ padding: 4px;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ font-size: var(--text-xs);+ color: var(--text-muted);+ cursor: pointer;+ }++ .scope-opt.on {+ border-color: var(--accent);+ color: var(--accent);+ background: var(--accent-soft);+ }++ .scope-opt input {+ position: absolute;+ opacity: 0;+ pointer-events: none;+ }++ .run {+ padding: 6px var(--space-3);+ border: none;+ border-radius: var(--radius-sm);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ cursor: pointer;+ }++ .run:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .hint,+ .count {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .warn {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-secondary, var(--text-muted));+ }++ .warn.error {+ color: var(--danger);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3) 0;+ }++ .state-title {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .skeleton-line {+ height: 40px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ .results {+ flex: 1;+ min-height: 0;+ display: flex;+ }++ .result {+ display: flex;+ flex-direction: column;+ gap: 2px;+ width: 100%;+ padding: var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+ }++ .result:hover {+ background: var(--fill-1);+ }++ .result-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-2);+ }++ .result-author {+ font-size: var(--text-sm);+ font-weight: 600;+ }++ .result-time {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .result-text {+ font-size: var(--text-sm);+ color: var(--text-secondary, var(--text));+ line-height: 1.4;+ overflow-wrap: anywhere;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/ShareScreenDialog.svelte b/src/components/omnidisc/ShareScreenDialog.sveltenew file mode 100644index 00000000..86539d68--- /dev/null+++ b/src/components/omnidisc/ShareScreenDialog.svelte@@ -0,0 +1,440 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ refreshSources,+ startStream,+ currentPolicy,+ allowedResolutions,+ allowedFramerates,+ kbpsFor,+ codecFor,+ widthForHeight,+ getStreamError,+ clearStreamError,+ isStreamBusy,+ type StreamSources,+ type StreamSource,+ type SourceId,+ type AudioMode,+ type StreamMode,+ } from "$lib/stores/omnidisc-stream-store.svelte";++ let { onClose }: { onClose: () => void } = $props();++ let sources = $state<StreamSources | null>(null);+ let loading = $state(true);+ let loadError = $state<string | null>(null);+ let selected = $state<SourceId | null>(null);+ let audio = $state<AudioMode>({ mode: "none" });+ let height = $state(1080);+ let fps = $state(60);+ let mode = $state<StreamMode>("text");+ let cursor = $state(true);+ let custom = $state<number | null>(null);++ let policy = $derived(currentPolicy());+ let resolutions = $derived(allowedResolutions(policy));+ let framerates = $derived(allowedFramerates(policy));+ let kbps = $derived(custom ?? kbpsFor(policy, height, fps));+ let codec = $derived(codecFor(policy, height, fps));+ let busy = $derived(isStreamBusy());+ let error = $derived(getStreamError());+ let allowCustom = $derived(policy?.allow_custom_bitrate ?? true);+ let hevcNote = $derived(height >= 2160 && fps > 60);++ $effect(() => {+ void load();+ return () => clearStreamError();+ });++ async function load() {+ loading = true;+ loadError = null;+ const s = await refreshSources();+ loading = false;+ if (!s) {+ loadError = getStreamError() ?? "ERR_STREAM_CAPTURE_FAILED";+ return;+ }+ sources = s;+ if (!selected && s.displays.length > 0) selected = s.displays[0].id;+ if (resolutions.length && !resolutions.includes(height)) height = resolutions[resolutions.length - 1];+ if (framerates.length && !framerates.includes(fps)) fps = framerates.includes(60) ? 60 : framerates[0];+ }++ function pick(src: StreamSource) {+ selected = src.id;+ }++ function isSelected(id: SourceId): boolean {+ return selected?.kind === id.kind && selected?.id === id.id;+ }++ function label(h: number): string {+ return `${h}p`;+ }++ async function share() {+ if (!selected) return;+ const ok = await startStream({+ source: selected,+ fps,+ height,+ audio,+ bitrate_kbps: custom ?? undefined,+ mode,+ cursor,+ });+ if (ok) onClose();+ }++ function onBackdrop(e: MouseEvent) {+ if (e.target === e.currentTarget) onClose();+ }++ function onKey(e: KeyboardEvent) {+ if (e.key === "Escape") onClose();+ }+</script>++<svelte:window onkeydown={onKey} />++<div class="backdrop" role="presentation" onclick={onBackdrop}>+ <div class="dialog" role="dialog" aria-modal="true" aria-label={$t("omnidisc.stream.share_title")}>+ <header>+ <h2>{$t("omnidisc.stream.share_title")}</h2>+ <button type="button" class="close" onclick={onClose} aria-label={$t("common.cancel")}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18" /></svg>+ </button>+ </header>++ <div class="body">+ {#if loading}+ <div class="state">+ <div class="grid" aria-hidden="true">+ {#each Array(4) as _}<div class="skeleton"></div>{/each}+ </div>+ <p class="muted">{$t("omnidisc.stream.loading_sources")}</p>+ </div>+ {:else if loadError}+ <div class="state">+ <p class="err" role="alert">{translateBackendError(loadError, $t)}</p>+ {#if loadError === "ERR_SCREEN_PERMISSION"}+ <button type="button" class="btn" onclick={() => void load()}>{$t("omnidisc.stream.recheck")}</button>+ {:else}+ <button type="button" class="btn" onclick={() => void load()}>{$t("omnidisc.voice.retry")}</button>+ {/if}+ </div>+ {:else if sources}+ <section>+ <h3>{$t("omnidisc.stream.pick_source")}</h3>+ <div class="grid">+ {#each [...sources.displays, ...sources.windows] as src (`${src.id.kind}-${src.id.id}`)}+ <button type="button" class="source" class:on={isSelected(src.id)} onclick={() => pick(src)}>+ <span class="thumb">+ {#if src.thumbnail}<img src={src.thumbnail} alt="" />{:else}<span class="ph" aria-hidden="true"></span>{/if}+ </span>+ <span class="cap">+ <span class="title">{src.title}</span>+ {#if src.app_name}<span class="sub">{src.app_name}</span>{/if}+ </span>+ </button>+ {/each}+ </div>+ </section>++ <section>+ <h3>{$t("omnidisc.stream.audio")}</h3>+ <div class="pills">+ <button type="button" class="pill" class:on={audio.mode === "none"} onclick={() => (audio = { mode: "none" })}>{$t("omnidisc.stream.audio_none")}</button>+ {#if sources.system_audio_supported}+ <button type="button" class="pill" class:on={audio.mode === "system"} onclick={() => (audio = { mode: "system" })}>{$t("omnidisc.stream.audio_system")}</button>+ {/if}+ </div>+ {#if sources.app_audio_supported && sources.apps.length > 0}+ <div class="pills apps">+ {#each sources.apps as app (app.pid)}+ <button type="button" class="pill" class:on={audio.mode === "app" && audio.pid === app.pid} onclick={() => (audio = { mode: "app", pid: app.pid })}>{app.name}</button>+ {/each}+ </div>+ {/if}+ </section>++ <section>+ <h3>{$t("omnidisc.stream.quality")}</h3>+ <div class="rowlabel">{$t("omnidisc.stream.resolution")}</div>+ <div class="pills">+ {#each resolutions as h}+ <button type="button" class="pill" class:on={height === h} onclick={() => { height = h; custom = null; }}>{label(h)}</button>+ {/each}+ </div>+ <div class="rowlabel">{$t("omnidisc.stream.framerate")}</div>+ <div class="pills">+ {#each framerates as f}+ <button type="button" class="pill" class:on={fps === f} onclick={() => { fps = f; custom = null; }}>{f}</button>+ {/each}+ </div>+ <p class="muted implied">{$t("omnidisc.stream.implied_bitrate", { kbps: Math.round(kbps / 100) / 10, codec: codec.toUpperCase() })}</p>+ {#if hevcNote}+ <p class="muted note">{$t("omnidisc.stream.hevc_note")}</p>+ {/if}+ {#if allowCustom}+ <label class="custom">+ <input type="checkbox" checked={custom !== null} onchange={(e) => (custom = e.currentTarget.checked ? kbpsFor(policy, height, fps) : null)} />+ {$t("omnidisc.stream.custom_bitrate")}+ </label>+ {#if custom !== null}+ <input class="range" type="range" min={policy?.min_kbps ?? 500} max={policy?.max_kbps ?? 20000} step={policy?.step_kbps ?? 500} value={custom} oninput={(e) => (custom = Number(e.currentTarget.value))} />+ {/if}+ {/if}+ </section>++ <section>+ <h3>{$t("omnidisc.stream.mode")}</h3>+ <div class="pills">+ <button type="button" class="pill" class:on={mode === "text"} onclick={() => (mode = "text")}>{$t("omnidisc.stream.mode_text")}</button>+ <button type="button" class="pill" class:on={mode === "game"} onclick={() => (mode = "game")}>{$t("omnidisc.stream.mode_game")}</button>+ </div>+ <label class="custom">+ <input type="checkbox" bind:checked={cursor} />+ {$t("omnidisc.stream.cursor")}+ </label>+ </section>++ {#if error}+ <p class="err" role="alert">{translateBackendError(error, $t)}</p>+ {/if}+ {/if}+ </div>++ <footer>+ <button type="button" class="btn" onclick={onClose}>{$t("common.cancel")}</button>+ <button type="button" class="btn primary" disabled={!selected || busy || loading} onclick={share}>+ {busy ? $t("omnidisc.stream.starting") : $t("omnidisc.stream.share_cta", { res: `${height}p${fps}` })}+ </button>+ </footer>+ </div>+</div>++<style>+ .backdrop {+ position: fixed;+ inset: 0;+ z-index: 60;+ display: grid;+ place-items: center;+ background: color-mix(in srgb, var(--bg) 72%, transparent);+ padding: var(--space-4);+ }+ .dialog {+ width: min(680px, 100%);+ max-height: 88vh;+ display: flex;+ flex-direction: column;+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius-lg, 12px);+ box-shadow: 0 24px 60px -12px color-mix(in srgb, var(--bg) 70%, transparent);+ }+ header,+ footer {+ display: flex;+ align-items: center;+ padding: var(--space-3) var(--space-4);+ }+ header {+ justify-content: space-between;+ border-bottom: 1px solid var(--border);+ }+ header h2 {+ font-size: var(--text-lg);+ color: var(--text);+ }+ footer {+ justify-content: flex-end;+ gap: var(--space-2);+ border-top: 1px solid var(--border);+ }+ .close {+ display: grid;+ place-items: center;+ width: 30px;+ height: 30px;+ border: none;+ background: transparent;+ color: var(--text-muted);+ border-radius: var(--radius-sm);+ cursor: pointer;+ }+ .close:hover {+ background: var(--fill-1);+ color: var(--text);+ }+ .body {+ overflow-y: auto;+ padding: var(--space-4);+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ }+ section h3 {+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text-secondary);+ margin-bottom: var(--space-2);+ }+ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: var(--space-2);+ }+ .skeleton {+ aspect-ratio: 16 / 10;+ border-radius: var(--radius-sm);+ background: var(--surface-mut);+ }+ .source {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ padding: 0;+ border: 2px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface-mut);+ cursor: pointer;+ overflow: hidden;+ text-align: left;+ }+ .source.on {+ border-color: var(--accent);+ }+ .thumb {+ aspect-ratio: 16 / 10;+ background: var(--bg);+ display: block;+ }+ .thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ }+ .thumb .ph {+ display: block;+ width: 100%;+ height: 100%;+ background: repeating-linear-gradient(45deg, var(--surface), var(--surface) 8px, var(--surface-mut) 8px, var(--surface-mut) 16px);+ }+ .cap {+ display: flex;+ flex-direction: column;+ padding: var(--space-2);+ min-width: 0;+ }+ .title {+ font-size: var(--text-sm);+ color: var(--text);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .sub {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }+ .pills {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+ }+ .apps {+ margin-top: var(--space-2);+ }+ .pill {+ padding: 6px var(--space-3);+ border: 1px solid var(--border);+ border-radius: var(--radius-full, 999px);+ background: var(--surface-mut);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }+ .pill.on {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ }+ .rowlabel {+ font-size: var(--text-xs);+ color: var(--text-muted);+ margin: var(--space-2) 0 var(--space-1);+ }+ .implied {+ margin-top: var(--space-2);+ }+ .note {+ color: var(--text-secondary);+ }+ .muted {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }+ .custom {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ font-size: var(--text-sm);+ color: var(--text);+ margin-top: var(--space-2);+ }+ .range {+ width: 100%;+ margin-top: var(--space-2);+ accent-color: var(--accent);+ }+ .btn {+ padding: 8px var(--space-4);+ border: 1px solid var(--border-hi, var(--border));+ border-radius: var(--radius-md);+ background: var(--surface-mut);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }+ .btn.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ font-weight: 600;+ }+ .btn:disabled {+ opacity: 0.55;+ cursor: default;+ }+ .btn:focus-visible,+ .pill:focus-visible,+ .source:focus-visible,+ .close:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+ .err {+ margin: 0;+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-sm);+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ color: var(--text);+ font-size: var(--text-sm);+ line-height: 1.5;+ }+ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ align-items: center;+ padding: var(--space-4);+ }+</style>diff --git a/src/components/omnidisc/VirtualList.svelte b/src/components/omnidisc/VirtualList.sveltenew file mode 100644index 00000000..6e1b9c84--- /dev/null+++ b/src/components/omnidisc/VirtualList.svelte@@ -0,0 +1,258 @@+<script lang="ts" generics="T">+ import { onMount, tick, type Snippet } from "svelte";++ let {+ items,+ getKey,+ estimateHeight = 56,+ overscan = 6,+ topThreshold = 120,+ bottomThreshold = 24,+ onReachTop,+ onBottomChange,+ row,+ empty,+ }: {+ items: T[];+ getKey: (item: T) => string;+ estimateHeight?: number;+ overscan?: number;+ topThreshold?: number;+ bottomThreshold?: number;+ onReachTop?: () => void;+ onBottomChange?: (atBottom: boolean) => void;+ row: Snippet<[T, number]>;+ empty?: Snippet;+ } = $props();++ type Anchor = { bottom: true } | { bottom: false; key: string; delta: number };++ let viewport = $state<HTMLDivElement | null>(null);+ let scrollTop = $state(0);+ let viewportHeight = $state(0);+ let heightsVersion = $state(0);+ let stickToBottom = true;+ let pendingAnchor: Anchor | null = null;+ let reachTopArmed = true;+ let lastItemCount = 0;+ let committedKeys: string[] = [];+ let committedOffsets: number[] = [0];++ const heights = new Map<string, number>();+ const elementKeys = new WeakMap<Element, string>();+ let rowObserver: ResizeObserver | null = null;+ let viewportObserver: ResizeObserver | null = null;++ let keys = $derived(items.map(getKey));++ let offsets = $derived.by(() => {+ heightsVersion;+ const out = new Array<number>(keys.length + 1);+ let acc = 0;+ for (let i = 0; i < keys.length; i++) {+ out[i] = acc;+ acc += heights.get(keys[i]) ?? estimateHeight;+ }+ out[keys.length] = acc;+ return out;+ });++ let totalHeight = $derived(offsets[offsets.length - 1] ?? 0);++ function lowerBoundIn(offs: number[], count: number, value: number): number {+ let lo = 0;+ let hi = count;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (offs[mid + 1] <= value) lo = mid + 1;+ else hi = mid;+ }+ return lo;+ }++ function lowerBound(value: number): number {+ return lowerBoundIn(offsets, keys.length, value);+ }++ let range = $derived.by(() => {+ if (keys.length === 0) return { start: 0, end: 0 };+ const start = Math.max(0, lowerBound(scrollTop) - overscan);+ const end = Math.min(keys.length, lowerBound(scrollTop + viewportHeight) + 1 + overscan);+ return { start, end };+ });++ let visible = $derived(items.slice(range.start, range.end));+ let padTop = $derived(offsets[range.start] ?? 0);+ let padBottom = $derived(Math.max(0, totalHeight - (offsets[range.end] ?? totalHeight)));++ function isAtBottom(el: HTMLDivElement): boolean {+ return el.scrollHeight - el.scrollTop - el.clientHeight <= bottomThreshold;+ }++ function captureAnchor(): Anchor {+ const el = viewport;+ if (!el || committedKeys.length === 0 || stickToBottom) return { bottom: true };+ const index = Math.min(committedKeys.length - 1, lowerBoundIn(committedOffsets, committedKeys.length, el.scrollTop));+ return { bottom: false, key: committedKeys[index], delta: committedOffsets[index] - el.scrollTop };+ }++ function commit() {+ committedKeys = keys;+ committedOffsets = offsets;+ }++ function restoreAnchor(anchor: Anchor) {+ commit();+ const el = viewport;+ if (!el) return;+ if (anchor.bottom) {+ el.scrollTop = el.scrollHeight;+ return;+ }+ const index = keys.indexOf(anchor.key);+ if (index < 0) return;+ el.scrollTop = offsets[index] - anchor.delta;+ }++ function handleResizeEntries(entries: ResizeObserverEntry[]) {+ let changed = false;+ for (const entry of entries) {+ const key = elementKeys.get(entry.target);+ if (key === undefined) continue;+ const size = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;+ const height = Math.max(1, Math.round(size));+ if (heights.get(key) !== height) {+ heights.set(key, height);+ changed = true;+ }+ }+ if (!changed) return;+ const anchor = captureAnchor();+ heightsVersion += 1;+ tick().then(() => restoreAnchor(anchor));+ }++ function measure(node: HTMLElement, key: string) {+ elementKeys.set(node, key);+ rowObserver?.observe(node);+ return {+ update(next: string) {+ elementKeys.set(node, next);+ },+ destroy() {+ rowObserver?.unobserve(node);+ },+ };+ }++ function onScroll() {+ const el = viewport;+ if (!el) return;+ scrollTop = el.scrollTop;+ const atBottom = isAtBottom(el);+ if (atBottom !== stickToBottom) onBottomChange?.(atBottom);+ stickToBottom = atBottom;+ if (el.scrollTop <= topThreshold) {+ if (reachTopArmed && onReachTop && items.length > 0) {+ reachTopArmed = false;+ onReachTop();+ }+ } else {+ reachTopArmed = true;+ }+ }++ export function scrollToBottom() {+ const el = viewport;+ if (!el) return;+ stickToBottom = true;+ el.scrollTop = el.scrollHeight;+ onBottomChange?.(true);+ }++ export function scrollToKey(key: string) {+ const el = viewport;+ if (!el) return;+ const index = keys.indexOf(key);+ if (index < 0) return;+ stickToBottom = false;+ el.scrollTop = Math.max(0, (offsets[index] ?? 0) - el.clientHeight / 3);+ scrollTop = el.scrollTop;+ onBottomChange?.(isAtBottom(el));+ }++ onMount(() => {+ rowObserver = new ResizeObserver(handleResizeEntries);+ viewportObserver = new ResizeObserver(() => {+ const el = viewport;+ if (!el) return;+ const anchor = captureAnchor();+ viewportHeight = el.clientHeight;+ tick().then(() => restoreAnchor(anchor));+ });+ if (viewport) {+ viewportObserver.observe(viewport);+ viewportHeight = viewport.clientHeight;+ }+ tick().then(() => scrollToBottom());+ return () => {+ rowObserver?.disconnect();+ viewportObserver?.disconnect();+ };+ });++ $effect.pre(() => {+ items;+ pendingAnchor = captureAnchor();+ });++ $effect(() => {+ items;+ const anchor = pendingAnchor;+ pendingAnchor = null;+ if (!anchor) return;+ tick().then(() => {+ restoreAnchor(anchor);+ if (items.length !== lastItemCount) {+ lastItemCount = items.length;+ reachTopArmed = true;+ }+ });+ });+</script>++<div class="virtual-list" bind:this={viewport} onscroll={onScroll} tabindex="-1">+ {#if items.length === 0}+ {#if empty}+ {@render empty()}+ {/if}+ {:else}+ <div class="virtual-list-inner" style:padding-top="{padTop}px" style:padding-bottom="{padBottom}px">+ {#each visible as item, i (getKey(item))}+ <div class="virtual-list-row" use:measure={getKey(item)}>+ {@render row(item, range.start + i)}+ </div>+ {/each}+ </div>+ {/if}+</div>++<style>+ .virtual-list {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ overflow-anchor: none;+ contain: layout paint;+ outline: none;+ }++ .virtual-list-inner {+ box-sizing: border-box;+ }++ .virtual-list-row {+ contain: layout;+ }+</style>diff --git a/src/components/omnidisc/VoiceBar.svelte b/src/components/omnidisc/VoiceBar.sveltenew file mode 100644index 00000000..702c8725--- /dev/null+++ b/src/components/omnidisc/VoiceBar.svelte@@ -0,0 +1,488 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { isMac, modKey } from "$lib/platform";+ import { getSettings } from "$lib/stores/settings-store.svelte";+ import { getChannel, getGuild } from "$lib/stores/omnidisc-store.svelte";+ import {+ getVoiceSession,+ getVoiceState,+ getVoiceError,+ getMicError,+ getOutputError,+ getVoiceQuality,+ getVoiceStats,+ isMuted,+ isDeafened,+ isVoiceBusy,+ isE2ee,+ toggleMute,+ toggleDeafen,+ leaveVoice,+ retryVoice,+ } from "$lib/stores/omnidisc-voice-store.svelte";+ import { isPublishing, stopStream, isStreamBusy } from "$lib/stores/omnidisc-stream-store.svelte";+ import ShareScreenDialog from "$components/omnidisc/ShareScreenDialog.svelte";++ let shareOpen = $state(false);+ let publishing = $derived(isPublishing());+ let streamBusy = $derived(isStreamBusy());++ let session = $derived(getVoiceSession());+ let connState = $derived(getVoiceState());+ let channel = $derived(getChannel(session?.channelId ?? null));+ let guild = $derived(getGuild(session?.guildId ?? null));+ let muted = $derived(isMuted());+ let deafened = $derived(isDeafened());+ let busy = $derived(isVoiceBusy());+ let quality = $derived(getVoiceQuality());+ let stats = $derived(getVoiceStats());+ let error = $derived(getVoiceError());+ let encrypted = $derived(isE2ee());+ let micError = $derived(getMicError());+ let outputError = $derived(getOutputError());+ let ping = $derived(stats?.rtt_ms != null ? Math.round(stats.rtt_ms) : null);+ let pttKey = $derived(getSettings()?.omnidisc?.voice?.ptt_key ?? "");+ let pttLabel = $derived(+ pttKey+ ? pttKey+ .split("+")+ .map((part) => (part === "CmdOrCtrl" ? modKey() : part))+ .join(isMac() ? "" : "+")+ : "",+ );++ let stateLabel = $derived.by(() => {+ switch (connState) {+ case "connecting":+ return $t("omnidisc.voice.connecting");+ case "reconnecting":+ return $t("omnidisc.voice.reconnecting");+ case "failed":+ return $t("omnidisc.voice.failed");+ default:+ return $t("omnidisc.voice.connected_to");+ }+ });++ let qualityLabel = $derived.by(() => {+ if (connState === "reconnecting") return $t("omnidisc.voice.quality_lost");+ switch (quality) {+ case "excellent":+ return $t("omnidisc.voice.quality_excellent");+ case "good":+ return $t("omnidisc.voice.quality_good");+ case "poor":+ return $t("omnidisc.voice.quality_poor");+ case "lost":+ return $t("omnidisc.voice.quality_lost");+ default:+ return $t("omnidisc.voice.quality_unknown");+ }+ });++ let dotClass = $derived.by(() => {+ if (connState === "failed") return "bad";+ if (connState === "connecting" || connState === "reconnecting") return "wait";+ if (quality === "poor") return "warn";+ if (quality === "lost") return "bad";+ if (quality === "unknown") return "wait";+ return "ok";+ });++ function translate(code: string | null): string {+ return code ? translateBackendError(code, $t) : "";+ }+</script>++{#if session && connState !== "idle"}+ <section class="voice-bar" class:failed={connState === "failed"} aria-label={$t("omnidisc.voice.title")} aria-live="polite">+ <div class="status-row">+ <span class="dot {dotClass}" title={qualityLabel} aria-hidden="true"></span>+ <div class="status-text">+ <span class="state">{stateLabel}</span>+ <span class="where">+ <span+ class="lock"+ class:open={!encrypted}+ title={encrypted ? $t("omnidisc.voice.e2ee_on_desc") : $t("omnidisc.voice.e2ee_off_desc")}+ >+ <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <rect x="5" y="11" width="14" height="9" rx="2" />+ {#if encrypted}+ <path d="M8 11V8a4 4 0 0 1 8 0v3" />+ {:else}+ <path d="M8 11V8a4 4 0 0 1 7.5-2" />+ {/if}+ </svg>+ <span class="sr-only">{encrypted ? $t("omnidisc.voice.e2ee_on") : $t("omnidisc.voice.e2ee_off")}</span>+ </span>+ {#if channel}{channel.name}{/if}{#if guild} · {guild.name}{/if}+ </span>+ {#if pttLabel && connState === "connected" && !muted}+ <span class="where">{$t("omnidisc.voice.ptt_hold", { key: pttLabel })}</span>+ {/if}+ </div>+ {#if ping !== null && connState === "connected"}+ <span class="ping" title={qualityLabel}>{$t("omnidisc.voice.ping", { ms: ping })}</span>+ {/if}+ <button+ type="button"+ class="icon-btn small"+ onclick={() => goto("/omnidisc/settings?view=voice")}+ aria-label={$t("omnidisc.voice.open_settings")}+ title={$t("omnidisc.voice.open_settings")}+ >+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <circle cx="12" cy="12" r="3" />+ <path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z" />+ </svg>+ </button>+ </div>++ {#if connState === "failed"}+ <p class="note bad" role="alert">{translate(error ?? "ERR_VOICE_DISCONNECTED")}</p>+ <div class="actions">+ <button type="button" class="btn primary" onclick={() => void retryVoice()} disabled={busy}>{$t("omnidisc.voice.retry")}</button>+ <button type="button" class="btn" onclick={() => void leaveVoice()} disabled={busy}>{$t("omnidisc.voice.leave_short")}</button>+ </div>+ {:else}+ {#if micError}+ <p class="note warn" role="status">+ {$t("omnidisc.voice.listen_only")}+ <button type="button" class="link" onclick={() => goto("/omnidisc/settings?view=voice")}>{$t("omnidisc.voice.open_settings")}</button>+ </p>+ {/if}+ {#if outputError}+ <p class="note warn" role="status">+ {$t("omnidisc.voice.no_output")}+ <button type="button" class="link" onclick={() => goto("/omnidisc/settings?view=voice")}>{$t("omnidisc.voice.open_settings")}</button>+ </p>+ {/if}+ <div class="share-row">+ {#if publishing}+ <button type="button" class="share stop" onclick={() => void stopStream()} disabled={streamBusy}>+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="13" rx="2" /><path d="M9 10l6 4M15 10l-6 4" /></svg>+ {$t("omnidisc.stream.stop_sharing")}+ </button>+ {:else}+ <button type="button" class="share" onclick={() => (shareOpen = true)} disabled={connState !== "connected"}>+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="13" rx="2" /><path d="M12 8v5M9.5 10.5 12 8l2.5 2.5" /></svg>+ {$t("omnidisc.stream.share_screen")}+ </button>+ {/if}+ </div>++ <div class="actions">+ <button+ type="button"+ class="icon-btn"+ class:on={muted}+ aria-pressed={muted}+ aria-label={muted ? $t("omnidisc.voice.unmute") : $t("omnidisc.voice.mute")}+ title={muted ? $t("omnidisc.voice.unmute") : $t("omnidisc.voice.mute")}+ disabled={busy || !!micError}+ onclick={() => void toggleMute()}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <rect x="9" y="3" width="6" height="11" rx="3" />+ <path d="M5 11a7 7 0 0 0 14 0M12 18v3" />+ {#if muted}<path d="M4 4l16 16" />{/if}+ </svg>+ </button>+ <button+ type="button"+ class="icon-btn"+ class:on={deafened}+ aria-pressed={deafened}+ aria-label={deafened ? $t("omnidisc.voice.undeafen") : $t("omnidisc.voice.deafen")}+ title={deafened ? $t("omnidisc.voice.undeafen") : $t("omnidisc.voice.deafen")}+ disabled={busy}+ onclick={() => void toggleDeafen()}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M4 14v-2a8 8 0 0 1 16 0v2" />+ <rect x="3" y="14" width="4" height="6" rx="1" />+ <rect x="17" y="14" width="4" height="6" rx="1" />+ {#if deafened}<path d="M4 4l16 16" />{/if}+ </svg>+ </button>+ <button+ type="button"+ class="icon-btn leave"+ aria-label={$t("omnidisc.voice.leave")}+ title={$t("omnidisc.voice.leave")}+ disabled={busy}+ onclick={() => void leaveVoice()}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M10.7 13.3a15 15 0 0 1-2-2.6l1.4-1.4a1 1 0 0 0 .2-1L9.5 4.8a1 1 0 0 0-1-.8H5a1 1 0 0 0-1 1c0 3.5 1.3 6.8 3.5 9.4" />+ <path d="M13.3 10.7c.9.8 1.8 1.5 2.7 2l1.4-1.4a1 1 0 0 1 1-.2l3.5.8a1 1 0 0 1 .8 1V16a1 1 0 0 1-1 1 16 16 0 0 1-9.4-3.5" />+ <path d="M4 20L20 4" />+ </svg>+ </button>+ </div>+ {/if}+ </section>+{/if}++{#if shareOpen}+ <ShareScreenDialog onClose={() => (shareOpen = false)} />+{/if}++<style>+ .share-row {+ display: flex;+ }++ .share {+ flex: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: var(--space-2);+ height: 30px;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface-mut);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .share:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .share.stop {+ background: color-mix(in srgb, var(--danger) 16%, transparent);+ border-color: color-mix(in srgb, var(--danger) 45%, var(--border));+ color: var(--danger);+ }++ .share:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .share:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .voice-bar {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-top: 1px solid var(--border);+ background: var(--surface);+ }++ .voice-bar.failed {+ border-top-color: color-mix(in srgb, var(--danger) 40%, var(--border));+ }++ .status-row {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ min-width: 0;+ }++ .dot {+ width: 8px;+ height: 8px;+ flex: 0 0 8px;+ border-radius: var(--radius-full);+ background: var(--text-dim);+ }++ .dot.ok {+ background: var(--success);+ }++ .dot.warn {+ background: var(--warning);+ }++ .dot.bad {+ background: var(--danger);+ }++ .dot.wait {+ background: var(--text-muted);+ }++ .status-text {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 1px;+ }++ .state {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--success);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .failed .state {+ color: var(--danger);+ }++ .where {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ font-size: var(--text-xs);+ color: var(--text-muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .lock {+ display: inline-flex;+ flex: 0 0 auto;+ color: var(--text-secondary);+ }++ .lock.open {+ color: var(--text-muted);+ }++ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+ }++ .ping {+ font-size: var(--text-xs);+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ }++ .actions {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ }++ .icon-btn {+ flex: 1;+ height: 32px;+ display: grid;+ place-items: center;+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface-mut);+ color: var(--text);+ cursor: pointer;+ }++ .icon-btn.small {+ flex: 0 0 26px;+ width: 26px;+ height: 26px;+ border: none;+ background: transparent;+ color: var(--text-muted);+ }++ .icon-btn:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .icon-btn.on {+ background: color-mix(in srgb, var(--danger) 16%, transparent);+ border-color: color-mix(in srgb, var(--danger) 45%, var(--border));+ color: var(--danger);+ }++ .icon-btn.leave {+ color: var(--danger);+ }++ .icon-btn.leave:hover:not(:disabled) {+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ border-color: color-mix(in srgb, var(--danger) 45%, var(--border));+ }++ .icon-btn:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .icon-btn:focus-visible,+ .btn:focus-visible,+ .link:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .note {+ margin: 0;+ font-size: var(--text-xs);+ line-height: 1.45;+ color: var(--text);+ padding: var(--space-2);+ border-radius: var(--radius-sm);+ }++ .note.warn {+ background: color-mix(in srgb, var(--warning) 14%, transparent);+ }++ .note.bad {+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ }++ .link {+ border: none;+ background: transparent;+ padding: 0;+ font: inherit;+ font-size: var(--text-xs);+ color: var(--accent);+ cursor: pointer;+ text-decoration: underline;+ }++ .btn {+ flex: 1;+ height: 30px;+ padding: 0 var(--space-3);+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface-mut);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .btn.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ }++ .btn:disabled {+ opacity: 0.5;+ cursor: default;+ }+</style>diff --git a/src/components/omnidisc/VoiceChannelView.svelte b/src/components/omnidisc/VoiceChannelView.sveltenew file mode 100644index 00000000..eebade1d--- /dev/null+++ b/src/components/omnidisc/VoiceChannelView.svelte@@ -0,0 +1,467 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { getVoiceMembers, getInstance, getGuild, getChannel, userName } from "$lib/stores/omnidisc-store.svelte";+ import {+ getVoiceSession,+ getVoiceState,+ getVoiceError,+ isVoiceBusy,+ isSpeaking,+ joinVoice,+ leaveVoice,+ clearVoiceError,+ } from "$lib/stores/omnidisc-voice-store.svelte";+ import {+ isPublishing,+ isWatching,+ watchStream,+ unwatchStream,+ setStreamVolume,+ isStreamBusy,+ refreshStreamStats,+ getStreamStats,+ } from "$lib/stores/omnidisc-stream-store.svelte";+ import type { OmnidiscChannel } from "$lib/omnidisc/types";++ let { channel }: { channel: OmnidiscChannel } = $props();++ let guild = $derived(getGuild(channel.guildId ?? null));+ let instance = $derived(getInstance(guild?.instanceId ?? null));+ let me = $derived(instance?.userId ?? null);+ let members = $derived(getVoiceMembers(channel.id));+ let session = $derived(getVoiceSession());+ let connState = $derived(getVoiceState());+ let here = $derived(session?.channelId === channel.id && connState !== "idle");+ let elsewhere = $derived(!!session && session.channelId !== channel.id && connState !== "idle");+ let busy = $derived(isVoiceBusy());+ let error = $derived(getVoiceError());+ let canJoin = $derived(instance?.status === "connected");+ let currentName = $derived(getChannel(session?.channelId ?? null)?.name ?? "");+ let confirmSwitch = $state(false);+ let publishing = $derived(isPublishing());+ let streamBusy = $derived(isStreamBusy());+ let inspectorOpen = $state(false);+ let volumes = $state<Record<string, number>>({});++ let stats = $derived(getStreamStats());++ $effect(() => {+ if (!inspectorOpen) return;+ const tick = () => void refreshStreamStats();+ tick();+ const timer = setInterval(tick, 2000);+ return () => clearInterval(timer);+ });++ function initial(name: string): string {+ return name.trim().charAt(0).toUpperCase() || "?";+ }++ function isLive(userId: string): boolean {+ const m = members.find((x) => x.userId === userId);+ if (!m) return false;+ return m.streaming || (userId === me && publishing);+ }++ async function toggleWatch(userId: string) {+ if (isWatching(userId)) await unwatchStream(userId);+ else await watchStream(userId);+ }++ function volumeOf(userId: string): number {+ return volumes[userId] ?? 100;+ }++ function onVolume(userId: string, value: number) {+ volumes = { ...volumes, [userId]: value };+ void setStreamVolume(userId, value / 100);+ }++ function watchStatsFor(userId: string) {+ return stats?.watching.find((w) => w.user_id === userId) ?? null;+ }++ async function join() {+ if (elsewhere && !confirmSwitch) {+ confirmSwitch = true;+ return;+ }+ confirmSwitch = false;+ clearVoiceError();+ await joinVoice(channel.id);+ }+</script>++<div class="voice-view">+ {#if error && !here}+ <p class="error" role="alert">{translateBackendError(error, $t)}</p>+ {/if}++ {#if members.length === 0}+ <div class="empty">+ <h3>{$t("omnidisc.voice.nobody")}</h3>+ <p>{$t("omnidisc.voice.nobody_hint")}</p>+ </div>+ {:else}+ <p class="count">{$t("omnidisc.voice.participants", { count: members.length })}</p>+ <ul class="grid" aria-label={$t("omnidisc.voice.participants", { count: members.length })}>+ {#each members as m (m.userId)}+ {@const name = instance ? userName(instance.id, m.userId) : m.userId}+ {@const talking = isSpeaking(m.userId)}+ {@const live = isLive(m.userId)}+ {@const watching = isWatching(m.userId)}+ {@const ws = watchStatsFor(m.userId)}+ <li class="tile" class:speaking={talking} class:me={m.userId === me} class:live>+ {#if live}<span class="live-badge">{$t("omnidisc.stream.live")}</span>{/if}+ <span class="avatar" aria-hidden="true">{initial(name)}</span>+ <span class="name">{name}{#if m.userId === me} <span class="you">({$t("omnidisc.voice.you")})</span>{/if}</span>+ {#if live && m.userId !== me}+ <div class="watch">+ <button type="button" class="btn small" onclick={() => void toggleWatch(m.userId)} disabled={streamBusy}>+ {watching ? $t("omnidisc.stream.stop_watching") : $t("omnidisc.stream.watch")}+ </button>+ {#if watching}+ {#if ws && ws.width > 0}+ <span class="res-badge">{ws.width}×{ws.height} · {Math.round(ws.fps_received)}fps{#if ws.codec} · {ws.codec.replace("video/", "").toUpperCase()}{/if}</span>+ {/if}+ <label class="vol">+ <span class="sr-only">{$t("omnidisc.stream.volume")}</span>+ <input type="range" min="0" max="200" step="5" value={volumeOf(m.userId)} oninput={(e) => onVolume(m.userId, Number(e.currentTarget.value))} />+ <span class="vol-val">{volumeOf(m.userId)}%</span>+ </label>+ {/if}+ </div>+ {:else if live && m.userId === me}+ <span class="res-badge you-live">{$t("omnidisc.stream.you_live")}</span>+ {/if}+ <span class="badges">+ {#if talking}<span class="sr-only">{$t("omnidisc.voice.speaking")}</span>{/if}+ {#if m.selfDeaf || m.serverDeaf}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-label={$t("omnidisc.voice.user_deafened", { name })}><path d="M4 14v-2a8 8 0 0 1 16 0v2" /><rect x="3" y="14" width="4" height="6" rx="1" /><rect x="17" y="14" width="4" height="6" rx="1" /><path d="M4 4l16 16" /></svg>+ {:else if m.selfMute || m.serverMute}+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-label={$t("omnidisc.voice.user_muted", { name })}><rect x="9" y="3" width="6" height="11" rx="3" /><path d="M5 11a7 7 0 0 0 14 0M12 18v3" /><path d="M4 4l16 16" /></svg>+ {/if}+ </span>+ </li>+ {/each}+ </ul>+ {/if}++ {#if here}+ <details class="inspector" bind:open={inspectorOpen}>+ <summary>{$t("omnidisc.stream.inspector")}</summary>+ <div class="inspector-body">+ {#if stats?.publishing}+ {@const p = stats.publishing}+ <p class="ins-line"><strong>{$t("omnidisc.stream.sending")}</strong> {p.width}×{p.height} · {Math.round(p.fps_sent || p.fps_encoded)}fps · {Math.round(p.bitrate_kbps)}/{p.configured_kbps} kbps · {(p.codec ?? "h264").toUpperCase()} · {p.encoder}{#if p.hardware === false} ({$t("omnidisc.stream.software")}){/if}</p>+ <p class="ins-line muted">{$t("omnidisc.stream.rtt")}: {p.rtt_ms != null ? Math.round(p.rtt_ms) + "ms" : "—"} · {$t("omnidisc.stream.loss")}: {p.packet_loss != null ? Math.round(p.packet_loss * 100) + "%" : "—"} · {$t("omnidisc.stream.encode")}: {p.encode_ms.toFixed(1)}ms</p>+ {#if p.hardware === false}<p class="ins-line warn">{$t("omnidisc.stream.software_warn")}</p>{/if}+ {/if}+ {#each stats?.watching ?? [] as w (w.user_id)}+ <p class="ins-line muted">{$t("omnidisc.stream.receiving")}: {w.width}×{w.height} · {Math.round(w.fps_received)}fps · {w.decoder || "—"} · {$t("omnidisc.stream.loss")} {w.packet_loss != null ? Math.round(w.packet_loss) : 0}</p>+ {/each}+ {#if !stats?.publishing && (stats?.watching?.length ?? 0) === 0}+ <p class="ins-line muted">{$t("omnidisc.stream.no_active")}</p>+ {/if}+ </div>+ </details>+ {/if}++ <div class="cta">+ {#if here}+ <button type="button" class="btn" onclick={() => void leaveVoice()} disabled={busy}>{$t("omnidisc.voice.leave")}</button>+ {:else if confirmSwitch}+ <p class="switch">+ <strong>{$t("omnidisc.voice.switch_title", { channel: channel.name })}</strong>+ {$t("omnidisc.voice.switch_body", { current: currentName })}+ </p>+ <div class="switch-actions">+ <button type="button" class="btn primary" onclick={join} disabled={busy}>{$t("omnidisc.voice.switch_confirm")}</button>+ <button type="button" class="btn" onclick={() => (confirmSwitch = false)}>{$t("common.cancel")}</button>+ </div>+ {:else}+ <button type="button" class="btn primary" onclick={join} disabled={busy || !canJoin} aria-busy={busy && connState === "connecting"}>+ {#if busy && connState === "connecting"}{$t("omnidisc.voice.connecting")}{:else}{$t("omnidisc.voice.join_channel", { channel: channel.name })}{/if}+ </button>+ {/if}+ </div>+</div>++<style>+ .voice-view {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-4);+ padding: var(--space-5);+ overflow-y: auto;+ }++ .empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-1);+ text-align: center;+ max-width: 360px;+ }++ .empty h3 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .empty p,+ .count {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .grid {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: var(--space-3);+ max-width: 640px;+ }++ .tile {+ position: relative;+ width: 140px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-3) var(--space-2);+ border-radius: var(--radius-md);+ background: var(--surface);+ border: 1px solid var(--border);+ }++ .tile.live {+ border-color: color-mix(in srgb, var(--danger) 45%, var(--border));+ }++ .live-badge {+ position: absolute;+ top: var(--space-2);+ right: var(--space-2);+ font-size: var(--text-xs);+ font-weight: 700;+ letter-spacing: 0.04em;+ color: var(--on-accent);+ background: var(--danger);+ padding: 1px 6px;+ border-radius: var(--radius-sm);+ }++ .watch {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-1);+ width: 100%;+ }++ .btn.small {+ padding: 4px var(--space-3);+ font-size: var(--text-xs);+ border-radius: var(--radius-sm);+ }++ .res-badge {+ font-size: var(--text-xs);+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ text-align: center;+ }++ .you-live {+ color: var(--danger);+ }++ .vol {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ width: 100%;+ }++ .vol input {+ flex: 1;+ accent-color: var(--accent);+ min-width: 0;+ }++ .vol-val {+ font-size: var(--text-xs);+ color: var(--text-muted);+ min-width: 34px;+ text-align: right;+ font-variant-numeric: tabular-nums;+ }++ .inspector {+ width: min(560px, 100%);+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ background: var(--surface);+ }++ .inspector summary {+ padding: var(--space-2) var(--space-3);+ font-size: var(--text-sm);+ color: var(--text-secondary);+ cursor: pointer;+ }++ .inspector-body {+ padding: 0 var(--space-3) var(--space-3);+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .ins-line {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text);+ line-height: 1.5;+ font-variant-numeric: tabular-nums;+ }++ .ins-line.muted {+ color: var(--text-muted);+ }++ .ins-line.warn {+ color: var(--warning);+ }++ .avatar {+ width: 56px;+ height: 56px;+ border-radius: var(--radius-full);+ display: grid;+ place-items: center;+ background: var(--accent-soft);+ color: var(--accent);+ font-size: var(--text-lg);+ font-weight: 600;+ box-shadow: 0 0 0 3px transparent;+ transition: box-shadow 120ms ease;+ }++ .tile.speaking .avatar {+ box-shadow: 0 0 0 3px var(--success);+ }++ .name {+ font-size: var(--text-sm);+ color: var(--text);+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .you {+ color: var(--text-muted);+ }++ .badges {+ height: 14px;+ color: var(--text-muted);+ display: flex;+ gap: 4px;+ }++ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ }++ .cta {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-2);+ }++ .switch {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ text-align: center;+ max-width: 320px;+ }++ .switch strong {+ display: block;+ color: var(--text);+ }++ .switch-actions {+ display: flex;+ gap: var(--space-2);+ }++ .btn {+ padding: 8px var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid var(--border-hi);+ background: var(--surface);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .btn.primary {+ background: var(--accent);+ border-color: var(--accent);+ color: var(--on-accent);+ font-weight: 600;+ }++ .btn:disabled {+ opacity: 0.55;+ cursor: default;+ }++ .btn:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .error {+ margin: 0;+ max-width: 420px;+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-sm);+ background: color-mix(in srgb, var(--danger) 14%, transparent);+ color: var(--text);+ font-size: var(--text-sm);+ line-height: 1.5;+ }++ @media (prefers-reduced-motion: reduce) {+ .avatar {+ transition: none;+ }+ }+</style>diff --git a/src/components/omnidisc/VoiceSettings.svelte b/src/components/omnidisc/VoiceSettings.sveltenew file mode 100644index 00000000..5f3bd0be--- /dev/null+++ b/src/components/omnidisc/VoiceSettings.svelte@@ -0,0 +1,386 @@+<script lang="ts">+ import { onDestroy, onMount } from "svelte";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { isMac, modKey } from "$lib/platform";+ import { getSettings } from "$lib/stores/settings-store.svelte";+ import {+ getDevices,+ isDevicesLoading,+ refreshDevices,+ setDevice,+ setNoiseSuppression,+ setPttKey,+ setVadThreshold,+ setDucking,+ setRelayOnly,+ setMicTest,+ isMicTesting,+ getMicLevel,+ micLevelStale,+ } from "$lib/stores/omnidisc-voice-store.svelte";++ let settings = $derived(getSettings());+ let voice = $derived(settings?.omnidisc?.voice ?? {});+ let devices = $derived(getDevices());+ let loading = $derived(isDevicesLoading());+ let testing = $derived(isMicTesting());+ let level = $derived(getMicLevel());+ let now = $state(Date.now());+ let stale = $derived(micLevelStale(now));+ let deviceError = $state<string | null>(null);+ let micError = $state<string | null>(null);+ let recording = $state(false);+ let vadDraft = $state<number | null>(null);+ let vadTimer: ReturnType<typeof setTimeout> | null = null;+ let duckDraft = $state<number | null>(null);+ let duckTimer: ReturnType<typeof setTimeout> | null = null;+ let clock: ReturnType<typeof setInterval> | null = null;++ let levelPercent = $derived(Math.round(Math.min(1, Math.max(0, (level.rmsDb + 60) / 60)) * 100));+ let pttLabel = $derived(formatBinding(voice.ptt_key ?? ""));+ let vadValue = $derived(vadDraft ?? voice.vad_threshold_db ?? -45);+ let duckValue = $derived(duckDraft ?? voice.ducking_percent ?? 0);+ let relayOnly = $derived(voice.relay_only === true);++ function formatBinding(binding: string): string {+ if (!binding) return "";+ return binding+ .split("+")+ .map((part) => (part === "CmdOrCtrl" ? modKey() : part === "Meta" || part === "Super" ? (isMac() ? "⌘" : "Win") : part))+ .join(isMac() ? "" : "+");+ }++ function mapKeyName(key: string): string | null {+ if (key.length === 1 && /[a-zA-Z]/.test(key)) return key.toUpperCase();+ if (key.length === 1 && /[0-9]/.test(key)) return key;+ if (/^F([1-9]|1[0-2])$/.test(key)) return key;+ const map: Record<string, string> = {+ " ": "Space", ArrowUp: "Up", ArrowDown: "Down", ArrowLeft: "Left", ArrowRight: "Right",+ Enter: "Enter", Tab: "Tab", Backspace: "Backspace", Delete: "Delete",+ Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", Insert: "Insert",+ "`": "`", "-": "-", "=": "=", "[": "[", "]": "]", "\\": "\\", ";": ";", "'": "'", ",": ",", ".": ".", "/": "/",+ };+ return map[key] ?? null;+ }++ function startRecording(e: MouseEvent) {+ recording = true;+ (e.currentTarget as HTMLButtonElement | null)?.focus();+ }++ function onRecordKey(e: KeyboardEvent) {+ if (!recording) return;+ e.preventDefault();+ e.stopPropagation();+ if (e.key === "Escape") {+ recording = false;+ return;+ }+ if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return;+ const keyName = mapKeyName(e.key);+ if (!keyName) return;+ const parts: string[] = [];+ if (e.ctrlKey || e.metaKey) parts.push("CmdOrCtrl");+ if (e.shiftKey) parts.push("Shift");+ if (e.altKey) parts.push("Alt");+ parts.push(keyName);+ recording = false;+ void setPttKey(parts.join("+"));+ }++ async function changeDevice(kind: "input" | "output", e: Event) {+ const value = (e.target as HTMLSelectElement).value;+ deviceError = await setDevice(kind, value === "" ? null : value);+ }++ async function toggleTest() {+ micError = null;+ const err = await setMicTest(!testing);+ if (err) micError = err;+ }++ function onVadInput(e: Event) {+ const v = Number((e.target as HTMLInputElement).value);+ vadDraft = v;+ if (vadTimer) clearTimeout(vadTimer);+ vadTimer = setTimeout(() => {+ void setVadThreshold(v);+ vadDraft = null;+ }, 500);+ }++ function onDuckInput(e: Event) {+ const v = Number((e.target as HTMLInputElement).value);+ duckDraft = v;+ if (duckTimer) clearTimeout(duckTimer);+ duckTimer = setTimeout(() => {+ void setDucking(v);+ duckDraft = null;+ }, 400);+ }++ onMount(() => {+ void refreshDevices();+ clock = setInterval(() => (now = Date.now()), 1000);+ });++ onDestroy(() => {+ if (clock) clearInterval(clock);+ if (vadTimer) clearTimeout(vadTimer);+ if (duckTimer) clearTimeout(duckTimer);+ if (testing) void setMicTest(false);+ });+</script>++<div class="voice-settings">+ <div class="card">+ <div class="setting-row">+ <div class="setting-col">+ <label class="setting-label" for="od-voice-input">{$t("omnidisc.voice.input_device")}</label>+ {#if !loading && devices.inputs.length === 0}+ <span class="setting-path">{$t("omnidisc.voice.no_input_devices")}</span>+ {/if}+ </div>+ <select id="od-voice-input" class="select" value={voice.input_device ?? ""} onchange={(e) => void changeDevice("input", e)} disabled={loading}>+ <option value="">{$t("omnidisc.voice.device_default")}</option>+ {#each devices.inputs as d (d.id)}+ <option value={d.id}>{d.name}</option>+ {/each}+ </select>+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <label class="setting-label" for="od-voice-output">{$t("omnidisc.voice.output_device")}</label>+ {#if !loading && devices.outputs.length === 0}+ <span class="setting-path">{$t("omnidisc.voice.no_output_devices")}</span>+ {/if}+ </div>+ <select id="od-voice-output" class="select" value={voice.output_device ?? ""} onchange={(e) => void changeDevice("output", e)} disabled={loading}>+ <option value="">{$t("omnidisc.voice.device_default")}</option>+ {#each devices.outputs as d (d.id)}+ <option value={d.id}>{d.name}</option>+ {/each}+ </select>+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t("omnidisc.voice.mic_test")}</span>+ <span class="setting-path">{$t("omnidisc.voice.mic_test_hint")}</span>+ <div class="meter-wrap">+ <div class="meter" role="meter" aria-label={$t("omnidisc.voice.mic_level")} aria-valuemin="0" aria-valuemax="100" aria-valuenow={testing ? levelPercent : 0}>+ <div class="meter-fill" class:hot={levelPercent > 85} style:width={`${testing ? levelPercent : 0}%`}></div>+ </div>+ {#if testing && stale}+ <span class="meter-note">{$t("omnidisc.voice.mic_silent")}</span>+ {/if}+ {#if micError}+ <span class="meter-note bad">{translateBackendError(micError, $t)}</span>+ {/if}+ </div>+ </div>+ <div class="row-actions">+ <button type="button" class="button" class:active={testing} aria-pressed={testing} onclick={toggleTest}>+ {testing ? $t("omnidisc.voice.mic_test_stop") : $t("omnidisc.voice.mic_test")}+ </button>+ <button type="button" class="button ghost" onclick={() => void refreshDevices()} disabled={loading}>{$t("omnidisc.voice.device_refresh")}</button>+ </div>+ </div>+ {#if deviceError}+ <p class="error" role="alert">{translateBackendError(deviceError, $t)}</p>+ {/if}+ </div>++ <div class="card">+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t("omnidisc.voice.noise_suppression")}</span>+ <span class="setting-path">{$t("omnidisc.voice.noise_suppression_desc")}</span>+ </div>+ <button+ class="toggle"+ class:on={voice.noise_suppression !== false}+ role="switch"+ aria-checked={voice.noise_suppression !== false}+ aria-label={$t("omnidisc.voice.noise_suppression")}+ onclick={() => void setNoiseSuppression(!(voice.noise_suppression !== false))}+ ><span class="toggle-knob"></span></button>+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t("omnidisc.voice.ptt_key")}</span>+ <span class="setting-path">{$t("omnidisc.voice.ptt_key_desc")}</span>+ {#if isMac() && voice.ptt_key}+ <span class="setting-path">{$t("omnidisc.voice.ptt_permission_hint")}</span>+ {/if}+ </div>+ <div class="row-actions">+ <button+ type="button"+ class="button key"+ class:recording+ onclick={startRecording}+ onkeydown={onRecordKey}+ onblur={() => (recording = false)}+ aria-label={$t("omnidisc.voice.ptt_key")}+ >+ {#if recording}{$t("omnidisc.voice.ptt_recording")}{:else if pttLabel}{pttLabel}{:else}{$t("omnidisc.voice.ptt_record")}{/if}+ </button>+ {#if voice.ptt_key}+ <button type="button" class="button ghost" onclick={() => void setPttKey("")}>{$t("omnidisc.voice.ptt_clear")}</button>+ {/if}+ </div>+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <label class="setting-label" for="od-voice-vad">{$t("omnidisc.voice.vad_threshold")}</label>+ <span class="setting-path">{$t("omnidisc.voice.vad_threshold_desc")}</span>+ </div>+ <div class="vad">+ <input id="od-voice-vad" type="range" min="-70" max="-20" step="1" value={vadValue} oninput={onVadInput} />+ <span class="vad-value">{vadValue} dB</span>+ </div>+ </div>+ <div class="divider"></div>+ <div class="setting-row">+ <div class="setting-col">+ <label class="setting-label" for="od-voice-duck">{$t("omnidisc.voice.ducking")}</label>+ <span class="setting-path">{$t("omnidisc.voice.ducking_desc")}</span>+ </div>+ <div class="vad">+ <input id="od-voice-duck" type="range" min="0" max="100" step="5" value={duckValue} oninput={onDuckInput} />+ <span class="vad-value">+ {duckValue === 0 ? $t("omnidisc.voice.ducking_off") : $t("omnidisc.voice.ducking_value", { percent: duckValue })}+ </span>+ </div>+ </div>+ </div>++ <div class="card">+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t("omnidisc.voice.relay_only")}</span>+ <span class="setting-path">{$t("omnidisc.voice.relay_only_desc")}</span>+ </div>+ <button+ class="toggle"+ class:on={relayOnly}+ role="switch"+ aria-checked={relayOnly}+ aria-label={$t("omnidisc.voice.relay_only")}+ onclick={() => void setRelayOnly(!relayOnly)}+ ><span class="toggle-knob"></span></button>+ </div>+ </div>+</div>++<style>+ .voice-settings {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ }++ .select {+ max-width: 240px;+ min-width: 160px;+ }++ .row-actions {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: var(--space-2);+ }++ .button.active {+ background: var(--accent);+ color: var(--on-accent);+ border-color: var(--accent);+ }++ .button.ghost {+ background: transparent;+ }++ .button.key {+ min-width: 140px;+ font-variant-numeric: tabular-nums;+ }++ .button.key.recording {+ border-color: var(--accent);+ color: var(--accent);+ }++ .meter-wrap {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ margin-top: var(--space-2);+ max-width: 320px;+ }++ .meter {+ height: 8px;+ border-radius: var(--radius-full);+ background: var(--fill-2);+ overflow: hidden;+ }++ .meter-fill {+ height: 100%;+ width: 0;+ background: var(--success);+ border-radius: var(--radius-full);+ transition: width 80ms linear;+ }++ .meter-fill.hot {+ background: var(--warning);+ }++ .meter-note {+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.45;+ }++ .meter-note.bad {+ color: var(--danger);+ }++ .error {+ margin: var(--space-2) 0 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .vad {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ }++ .vad input {+ width: 160px;+ }++ .vad-value {+ min-width: 72px;+ text-align: right;+ font-size: var(--text-xs);+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ }++ @media (prefers-reduced-motion: reduce) {+ .meter-fill {+ transition: none;+ }+ }+</style>diff --git a/src/components/omnidisc/settings/DevicesSettings.svelte b/src/components/omnidisc/settings/DevicesSettings.sveltenew file mode 100644index 00000000..d878cf45--- /dev/null+++ b/src/components/omnidisc/settings/DevicesSettings.svelte@@ -0,0 +1,320 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ getDevices,+ getSelectedInstance,+ getThisDeviceId,+ loadDevices,+ revokeDevice,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscDevice } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "../OmnidiscPrompt.svelte";++ let instance = $derived(getSelectedInstance());+ let devices = $derived(getDevices(instance?.id ?? null));+ let thisDeviceId = $derived(getThisDeviceId(instance?.id ?? null));+ let loading = $state(true);+ let error = $state<string | null>(null);+ let busy = $state(false);+ let pending = $state<OmnidiscDevice | null>(null);+ let copied = $state<string | null>(null);+ let loadedFor = $state<string | null>(null);++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function refresh() {+ const id = instance?.id;+ if (!id) return;+ loading = true;+ error = null;+ try {+ await loadDevices(id);+ } catch (e) {+ fail(e);+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ const id = instance?.id;+ if (!id || loadedFor === id) return;+ loadedFor = id;+ void refresh();+ });++ function label(device: OmnidiscDevice): string {+ return device.name?.trim() || $t("omnidisc.devices.unnamed");+ }++ function when(raw: string): string {+ const ms = Date.parse(raw);+ if (!Number.isFinite(ms)) return "";+ return new Date(ms).toLocaleString(undefined, {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ });+ }++ async function copy(device: OmnidiscDevice) {+ if (!device.fingerprint) return;+ try {+ await navigator.clipboard.writeText(device.fingerprint);+ copied = device.deviceId;+ setTimeout(() => (copied = null), 2000);+ } catch {+ error = $t("omnidisc.devices.copy_failed");+ }+ }++ async function confirmRevoke() {+ const id = instance?.id;+ const device = pending;+ if (!id || !device) return;+ busy = true;+ error = null;+ try {+ await revokeDevice(id, device.deviceId);+ pending = null;+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ let isThisDevice = $derived(pending?.deviceId === thisDeviceId);+</script>++{#if !instance}+ <div class="state">+ <p class="state-title">{$t("omnidisc.profile_settings.no_instance_title")}</p>+ <p class="state-body">{$t("omnidisc.profile_settings.no_instance_body")}</p>+ </div>+{:else}+ <section class="devices">+ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ <p class="state-body">{$t("omnidisc.devices.fingerprint_hint")}</p>++ {#if loading}+ <div class="state" aria-busy="true">+ {#each Array(2) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if devices.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.devices.empty_title")}</p>+ <p class="state-body">{$t("omnidisc.devices.empty_body")}</p>+ </div>+ {:else}+ <ul class="list">+ {#each devices as device (device.deviceId)}+ <li class="row">+ <span class="who">+ <span class="name">+ {label(device)}+ {#if device.deviceId === thisDeviceId}+ <span class="tag">{$t("omnidisc.devices.this_device")}</span>+ {/if}+ </span>+ <span class="meta">{$t("omnidisc.devices.last_seen", { when: when(device.lastSeenAt) })}</span>+ {#if device.fingerprint}+ <button+ type="button"+ class="fingerprint"+ onclick={() => void copy(device)}+ title={$t("omnidisc.devices.copy")}+ >+ <code>{device.fingerprint}</code>+ <span class="copy-state">+ {copied === device.deviceId ? $t("omnidisc.devices.copied") : $t("omnidisc.devices.copy")}+ </span>+ </button>+ {/if}+ </span>+ <button type="button" class="ghost" onclick={() => (pending = device)}>+ {$t("omnidisc.devices.revoke")}+ </button>+ </li>+ {/each}+ </ul>+ {/if}+ </section>+{/if}++<OmnidiscPrompt+ open={pending !== null}+ title={isThisDevice+ ? $t("omnidisc.devices.revoke_this_title")+ : $t("omnidisc.devices.revoke_title", { device: pending ? label(pending) : "" })}+ body={isThisDevice ? $t("omnidisc.devices.revoke_this_body") : $t("omnidisc.devices.revoke_body")}+ submitLabel={$t("omnidisc.devices.revoke_confirm", { device: pending ? label(pending) : "" })}+ {busy}+ {error}+ onSubmit={() => void confirmRevoke()}+ onClose={() => {+ pending = null;+ error = null;+ }}+>+ <p class="state-body">{$t("omnidisc.devices.no_history_warning")}</p>+</OmnidiscPrompt>++<style>+ .devices {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ max-width: 560px;+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }++ .row {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: var(--space-3);+ padding: var(--space-3) 0;+ border-bottom: 1px solid var(--border);+ }++ .who {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }++ .name {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .tag {+ padding: 1px var(--space-2);+ border-radius: var(--radius-full);+ background: var(--accent-soft);+ color: var(--accent);+ font-size: var(--text-xs);+ font-weight: 600;+ }++ .meta {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .fingerprint {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: 2px 0;+ border: none;+ background: transparent;+ cursor: pointer;+ text-align: left;+ }++ .fingerprint code {+ font-family: var(--font-mono, monospace);+ font-size: var(--text-xs);+ letter-spacing: 0.04em;+ color: var(--text-secondary);+ overflow-wrap: anywhere;+ }++ .copy-state {+ font-size: var(--text-xs);+ color: var(--accent);+ flex: 0 0 auto;+ }++ .fingerprint:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .ghost {+ flex: 0 0 auto;+ padding: 4px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .ghost:hover {+ background: var(--fill-1);+ }++ .ghost:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .skeleton-line {+ height: 56px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/settings/GuildAuditLog.svelte b/src/components/omnidisc/settings/GuildAuditLog.sveltenew file mode 100644index 00000000..a34bdfe3--- /dev/null+++ b/src/components/omnidisc/settings/GuildAuditLog.svelte@@ -0,0 +1,214 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { loadAuditLog, userName } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscAuditEntry } from "$lib/omnidisc/types";++ let { guildId, instanceId }: { guildId: string; instanceId: string } = $props();++ const ACTIONS = [+ "guild.update",+ "channel.create",+ "channel.update",+ "channel.delete",+ "channel.overwrite",+ "role.create",+ "role.update",+ "role.delete",+ "member.update",+ "member.kick",+ "member.ban",+ "member.unban",+ "member.leave",+ "message.delete",+ "message.bulk_delete",+ "message.pin",+ "message.unpin",+ "guild.transfer",+ ];++ let entries = $state<OmnidiscAuditEntry[]>([]);+ let loading = $state(true);+ let error = $state<string | null>(null);+ let filter = $state("");+ let loadedKey = $state<string | null>(null);++ async function refresh() {+ loading = true;+ error = null;+ try {+ entries = await loadAuditLog(guildId, filter || undefined);+ } catch (e) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ entries = [];+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ const key = `${guildId}:${filter}`;+ if (loadedKey === key) return;+ loadedKey = key;+ void refresh();+ });++ function sentence(entry: OmnidiscAuditEntry): string {+ const actor = userName(instanceId, entry.actorId);+ const target = entry.targetId ? userName(instanceId, entry.targetId) : "";+ const key = `omnidisc.audit.${entry.action.replace(".", "_")}`;+ const translated = $t(key, { actor, target });+ return translated === key ? $t("omnidisc.audit.fallback", { actor, action: entry.action, target }) : translated;+ }++ function when(entry: OmnidiscAuditEntry): string {+ const ms = Date.parse(entry.createdAt);+ if (!Number.isFinite(ms)) return "";+ return new Date(ms).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });+ }+</script>++<section class="audit">+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.audit_filter")}</span>+ <select class="field-input" bind:value={filter}>+ <option value="">{$t("omnidisc.guild_settings.audit_all")}</option>+ {#each ACTIONS as action (action)}+ <option value={action}>{$t(`omnidisc.audit_action.${action.replace(".", "_")}`)}</option>+ {/each}+ </select>+ </label>++ {#if error}+ <p class="error" role="alert">{error}</p>+ {:else if loading}+ <div class="state" aria-busy="true">+ {#each Array(4) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if entries.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.guild_settings.audit_empty_title")}</p>+ <p class="state-body">{$t("omnidisc.guild_settings.audit_empty_body")}</p>+ </div>+ {:else}+ <ul class="list">+ {#each entries as entry (entry.id)}+ <li class="row">+ <span class="text">{sentence(entry)}{#if entry.reason} — {entry.reason}{/if}</span>+ <time class="when">{when(entry)}</time>+ </li>+ {/each}+ </ul>+ {/if}+</section>++<style>+ .audit {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ max-width: 640px;+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ max-width: 260px;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .field-input:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }++ .row {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-3);+ padding: var(--space-2) 0;+ border-bottom: 1px solid var(--border);+ }++ .text {+ font-size: var(--text-sm);+ color: var(--text);+ line-height: 1.4;+ }++ .when {+ flex: 0 0 auto;+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .skeleton-line {+ height: 32px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/settings/GuildBans.svelte b/src/components/omnidisc/settings/GuildBans.sveltenew file mode 100644index 00000000..50b18188--- /dev/null+++ b/src/components/omnidisc/settings/GuildBans.svelte@@ -0,0 +1,209 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { listBans, unbanMember, userName } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscBan } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "../OmnidiscPrompt.svelte";++ let { guildId, instanceId, canBan }: { guildId: string; instanceId: string; canBan: boolean } = $props();++ let bans = $state<OmnidiscBan[]>([]);+ let loading = $state(true);+ let error = $state<string | null>(null);+ let busy = $state(false);+ let pending = $state<OmnidiscBan | null>(null);+ let loadedFor = $state<string | null>(null);++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function refresh() {+ loading = true;+ error = null;+ try {+ bans = await listBans(guildId);+ } catch (e) {+ fail(e);+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ if (loadedFor === guildId) return;+ loadedFor = guildId;+ void refresh();+ });++ async function confirmUnban() {+ const ban = pending;+ if (!ban) return;+ busy = true;+ error = null;+ try {+ await unbanMember(guildId, ban.userId);+ pending = null;+ await refresh();+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }+</script>++<section class="bans">+ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ {#if loading}+ <div class="state" aria-busy="true">+ {#each Array(3) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if bans.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.guild_settings.bans_empty_title")}</p>+ <p class="state-body">{$t("omnidisc.guild_settings.bans_empty_body")}</p>+ </div>+ {:else}+ <ul class="list">+ {#each bans as ban (ban.userId)}+ <li class="row">+ <span class="who">+ <span class="name">{userName(instanceId, ban.userId)}</span>+ <span class="meta">+ {$t("omnidisc.guild_settings.ban_by", { name: userName(instanceId, ban.bannedBy) })}+ {#if ban.reason}— {ban.reason}{/if}+ </span>+ </span>+ {#if canBan}+ <button type="button" class="ghost" onclick={() => (pending = ban)}>{$t("omnidisc.guild_settings.unban")}</button>+ {/if}+ </li>+ {/each}+ </ul>+ {/if}+</section>++<OmnidiscPrompt+ open={pending !== null}+ title={$t("omnidisc.guild_settings.unban_title", { name: pending ? userName(instanceId, pending.userId) : "" })}+ body={$t("omnidisc.guild_settings.unban_body")}+ submitLabel={$t("omnidisc.guild_settings.unban_confirm", { name: pending ? userName(instanceId, pending.userId) : "" })}+ {busy}+ {error}+ onSubmit={() => void confirmUnban()}+ onClose={() => (pending = null)}+>+ <p class="state-body">{$t("omnidisc.guild_settings.unban_hint")}</p>+</OmnidiscPrompt>++<style>+ .bans {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ max-width: 620px;+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }++ .row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-3);+ padding: var(--space-2) 0;+ border-bottom: 1px solid var(--border);+ }++ .who {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ .name {+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .meta {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .ghost {+ padding: 4px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .ghost:hover {+ background: var(--fill-1);+ }++ .ghost:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .skeleton-line {+ height: 40px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/omnidisc/settings/GuildChannels.svelte b/src/components/omnidisc/settings/GuildChannels.sveltenew file mode 100644index 00000000..908af31f--- /dev/null+++ b/src/components/omnidisc/settings/GuildChannels.svelte@@ -0,0 +1,508 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ deleteChannel,+ deleteOverwrite,+ getGuild,+ getRoles,+ putOverwrite,+ updateChannelSettings,+ userName,+ } from "$lib/stores/omnidisc-store.svelte";+ import { PERMISSION_GROUPS, perm, toBits, type PermissionGroup, type PermissionName } from "$lib/omnidisc/permissions";+ import type { OmnidiscChannel } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "../OmnidiscPrompt.svelte";++ let {+ guildId,+ instanceId,+ canManage,+ initialChannelId = null,+ }: { guildId: string; instanceId: string; canManage: boolean; initialChannelId?: string | null } = $props();++ const GROUPS: PermissionGroup[] = ["general", "text", "voice", "moderation"];+ type Tri = "allow" | "inherit" | "deny";++ let guild = $derived(getGuild(guildId));+ let channels = $derived((guild?.channels ?? []).filter((c) => c.kind !== "category"));+ let selectedId = $state<string | null>(null);+ let seeded = false;++ $effect(() => {+ if (seeded) return;+ seeded = true;+ selectedId = initialChannelId;+ });+ let selected = $derived(channels.find((c) => c.id === selectedId) ?? channels[0] ?? null);+ let targetId = $state<string | null>(null);+ let busy = $state(false);+ let error = $state<string | null>(null);+ let pendingDelete = $state<OmnidiscChannel | null>(null);++ let roles = $derived(getRoles(guildId));+ let memberTargets = $derived(+ (selected?.overwrites ?? []).filter((o) => o.targetKind === "member").map((o) => o.targetId),+ );+ let target = $derived(+ targetId ?? roles.find((r) => r.isEveryone)?.id ?? roles[0]?.id ?? null,+ );+ let targetKind = $derived<"role" | "member">(roles.some((r) => r.id === target) ? "role" : "member");+ let overwrite = $derived(selected?.overwrites?.find((o) => o.targetId === target) ?? null);++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function run(fn: () => Promise<void>) {+ busy = true;+ error = null;+ try {+ await fn();+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ function stateOf(name: PermissionName): Tri {+ if (!overwrite) return "inherit";+ const bit = perm(name);+ if ((toBits(overwrite.allow) & bit) === bit) return "allow";+ if ((toBits(overwrite.deny) & bit) === bit) return "deny";+ return "inherit";+ }++ async function setState(name: PermissionName, next: Tri) {+ if (!selected || !target) return;+ const bit = perm(name);+ let allow = toBits(overwrite?.allow);+ let deny = toBits(overwrite?.deny);+ allow &= ~bit;+ deny &= ~bit;+ if (next === "allow") allow |= bit;+ if (next === "deny") deny |= bit;+ const channelId = selected.id;+ const id = target;+ const kind = targetKind;+ if (allow === 0n && deny === 0n) {+ await run(() => deleteOverwrite(channelId, id));+ return;+ }+ await run(() => putOverwrite(channelId, id, kind, allow.toString(), deny.toString()));+ }++ async function save(patch: Record<string, unknown>) {+ if (!selected) return;+ const id = selected.id;+ await run(() => updateChannelSettings(id, patch));+ }++ async function confirmDelete() {+ const channel = pendingDelete;+ if (!channel) return;+ await run(async () => {+ await deleteChannel(channel.id);+ pendingDelete = null;+ if (selectedId === channel.id) selectedId = null;+ });+ }+</script>++<section class="channels">+ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ {#if channels.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.channels.empty")}</p>+ <p class="state-body">{$t("omnidisc.channels.empty_hint")}</p>+ </div>+ {:else}+ <div class="grid">+ <ul class="list">+ {#each channels as channel (channel.id)}+ <li>+ <button type="button" class="row" class:on={selected?.id === channel.id} onclick={() => (selectedId = channel.id)}>+ <span class="glyph" aria-hidden="true">{channel.kind === "voice" ? "🔊" : "#"}</span>+ <span class="row-name">{channel.name}</span>+ </button>+ </li>+ {/each}+ </ul>++ {#if selected}+ <div class="detail">+ <label class="field">+ <span class="field-label">{$t("omnidisc.channel_settings.name")}</span>+ <input+ class="field-input"+ type="text"+ value={selected.name}+ maxlength="100"+ disabled={!canManage || busy}+ onchange={(e) => void save({ name: e.currentTarget.value.trim() })}+ />+ </label>++ {#if selected.kind !== "voice"}+ <label class="field">+ <span class="field-label">{$t("omnidisc.channel_settings.topic")}</span>+ <textarea+ class="field-input"+ rows="2"+ maxlength="1024"+ disabled={!canManage || busy}+ value={selected.topic ?? ""}+ onchange={(e) => void save({ topic: e.currentTarget.value })}+ ></textarea>+ </label>++ <label class="field short">+ <span class="field-label">{$t("omnidisc.channel_settings.slowmode")}</span>+ <select+ class="field-input"+ disabled={!canManage || busy}+ value={String(selected.slowmodeSeconds ?? 0)}+ onchange={(e) => void save({ slowmode_seconds: Number(e.currentTarget.value) })}+ >+ <option value="0">{$t("omnidisc.channel_settings.slowmode_off")}</option>+ <option value="5">5s</option>+ <option value="30">30s</option>+ <option value="60">1min</option>+ <option value="300">5min</option>+ </select>+ </label>++ <label class="toggle">+ <input+ type="checkbox"+ checked={selected.nsfw === true}+ disabled={!canManage || busy}+ onchange={(e) => void save({ nsfw: e.currentTarget.checked })}+ />+ <span>{$t("omnidisc.channel_settings.nsfw")}</span>+ </label>+ {:else}+ <p class="voice-note">{$t("omnidisc.channel_settings.voice_note")}</p>+ {/if}++ <h4 class="group-title">{$t("omnidisc.channel_settings.overwrites")}</h4>+ <p class="hint">{$t("omnidisc.channel_settings.overwrites_hint")}</p>+ <label class="field short">+ <span class="field-label">{$t("omnidisc.channel_settings.overwrite_target")}</span>+ <select class="field-input" value={target ?? ""} onchange={(e) => (targetId = e.currentTarget.value)}>+ {#each roles as role (role.id)}+ <option value={role.id}>{role.isEveryone ? $t("omnidisc.guild_settings.everyone_role") : role.name}</option>+ {/each}+ {#each memberTargets as memberId (memberId)}+ <option value={memberId}>{userName(instanceId, memberId)}</option>+ {/each}+ </select>+ </label>++ {#each GROUPS as group (group)}+ <h5 class="sub-title">{$t(`omnidisc.guild_settings.perm_group_${group}`)}</h5>+ <ul class="perms">+ {#each PERMISSION_GROUPS[group] as name (name)}+ <li class="perm">+ <span class="perm-name">{$t(`omnidisc.perm.${name}`)}</span>+ <div class="tri" role="radiogroup" aria-label={$t(`omnidisc.perm.${name}`)}>+ <button+ type="button"+ class="tri-btn deny"+ class:on={stateOf(name) === "deny"}+ disabled={!canManage || busy}+ onclick={() => void setState(name, "deny")}+ aria-pressed={stateOf(name) === "deny"}+ >{$t("omnidisc.channel_settings.deny")}</button>+ <button+ type="button"+ class="tri-btn"+ class:on={stateOf(name) === "inherit"}+ disabled={!canManage || busy}+ onclick={() => void setState(name, "inherit")}+ aria-pressed={stateOf(name) === "inherit"}+ >{$t("omnidisc.channel_settings.inherit")}</button>+ <button+ type="button"+ class="tri-btn allow"+ class:on={stateOf(name) === "allow"}+ disabled={!canManage || busy}+ onclick={() => void setState(name, "allow")}+ aria-pressed={stateOf(name) === "allow"}+ >{$t("omnidisc.channel_settings.allow")}</button>+ </div>+ </li>+ {/each}+ </ul>+ {/each}++ {#if canManage}+ <button type="button" class="danger" onclick={() => (pendingDelete = selected)}>+ {$t("omnidisc.channel_settings.delete", { name: selected.name })}+ </button>+ {/if}+ </div>+ {/if}+ </div>+ {/if}+</section>++<OmnidiscPrompt+ open={pendingDelete !== null}+ title={$t("omnidisc.channel_settings.delete_title", { name: pendingDelete?.name ?? "" })}+ body={$t("omnidisc.channel_settings.delete_body")}+ submitLabel={$t("omnidisc.channel_settings.delete_confirm", { name: pendingDelete?.name ?? "" })}+ {busy}+ {error}+ onSubmit={() => void confirmDelete()}+ onClose={() => (pendingDelete = null)}+>+ <p class="hint">{$t("omnidisc.channel_settings.delete_hint")}</p>+</OmnidiscPrompt>++<style>+ .channels {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ }++ .grid {+ display: grid;+ grid-template-columns: 200px 1fr;+ gap: var(--space-4);+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .row {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ width: 100%;+ padding: 6px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .row:hover {+ background: var(--fill-1);+ }++ .row.on {+ background: var(--accent-soft);+ color: var(--accent);+ font-weight: 600;+ }++ .glyph {+ color: var(--text-muted);+ }++ .row-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .detail {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ min-width: 0;+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .field.short {+ max-width: 260px;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ width: 100%;+ box-sizing: border-box;+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ resize: vertical;+ }++ .toggle {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ font-size: var(--text-sm);+ color: var(--text);+ }++ .group-title {+ margin: var(--space-3) 0 0;+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .sub-title {+ margin: var(--space-2) 0 0;+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text-muted);+ }++ .hint,+ .voice-note {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .perms {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .perm {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-3);+ padding: 3px 0;+ }++ .perm-name {+ font-size: var(--text-sm);+ color: var(--text);+ }++ .tri {+ display: flex;+ flex: 0 0 auto;+ }++ .tri-btn {+ padding: 3px var(--space-2);+ border: 1px solid var(--border);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .tri-btn:first-child {+ border-radius: var(--radius-sm) 0 0 var(--radius-sm);+ }++ .tri-btn:last-child {+ border-radius: 0 var(--radius-sm) var(--radius-sm) 0;+ }++ .tri-btn.on {+ color: var(--text);+ background: var(--fill-1);+ font-weight: 600;+ }++ .tri-btn.allow.on {+ color: var(--success);+ border-color: var(--success);+ }++ .tri-btn.deny.on {+ color: var(--danger);+ border-color: var(--danger);+ }++ .tri-btn:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .danger {+ align-self: flex-start;+ padding: 6px var(--space-3);+ border: 1px solid var(--danger);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--danger);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ input:focus-visible,+ select:focus-visible,+ textarea:focus-visible,+ button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @media (max-width: 760px) {+ .grid {+ grid-template-columns: 1fr;+ }+ }+</style>diff --git a/src/components/omnidisc/settings/GuildInvites.svelte b/src/components/omnidisc/settings/GuildInvites.sveltenew file mode 100644index 00000000..77d6201f--- /dev/null+++ b/src/components/omnidisc/settings/GuildInvites.svelte@@ -0,0 +1,208 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { createInviteWithOptions, getGuild } from "$lib/stores/omnidisc-store.svelte";++ let { guildId, canInvite }: { guildId: string; canInvite: boolean } = $props();++ let guild = $derived(getGuild(guildId));+ let textChannels = $derived((guild?.channels ?? []).filter((c) => c.kind === "text"));+ let channelId = $state<string>("");+ let maxAge = $state("86400");+ let maxUses = $state("0");+ let busy = $state(false);+ let error = $state<string | null>(null);+ let link = $state<string | null>(null);+ let copied = $state(false);++ async function create() {+ busy = true;+ error = null;+ copied = false;+ try {+ const created = await createInviteWithOptions(+ guildId,+ channelId || undefined,+ Number(maxAge) || null,+ Number(maxUses) || null,+ );+ link = created;+ if (!created) error = $t("omnidisc.guild.invite_failed");+ } catch (e) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ } finally {+ busy = false;+ }+ }++ async function copy() {+ if (!link) return;+ try {+ await navigator.clipboard.writeText(link);+ copied = true;+ } catch {+ error = $t("omnidisc.guild.invite_failed");+ }+ }+</script>++<section class="invites">+ <p class="hint">{$t("omnidisc.guild_settings.invites_hint")}</p>++ <div class="fields">+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.invite_channel")}</span>+ <select class="field-input" bind:value={channelId} disabled={!canInvite || busy}>+ <option value="">{$t("omnidisc.guild_settings.invite_channel_any")}</option>+ {#each textChannels as channel (channel.id)}+ <option value={channel.id}>#{channel.name}</option>+ {/each}+ </select>+ </label>++ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.invite_expiry")}</span>+ <select class="field-input" bind:value={maxAge} disabled={!canInvite || busy}>+ <option value="1800">{$t("omnidisc.guild_settings.expiry_30m")}</option>+ <option value="86400">{$t("omnidisc.guild_settings.expiry_1d")}</option>+ <option value="604800">{$t("omnidisc.guild_settings.expiry_7d")}</option>+ <option value="0">{$t("omnidisc.guild_settings.expiry_never")}</option>+ </select>+ </label>++ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.invite_uses")}</span>+ <select class="field-input" bind:value={maxUses} disabled={!canInvite || busy}>+ <option value="0">{$t("omnidisc.guild_settings.uses_unlimited")}</option>+ <option value="1">1</option>+ <option value="5">5</option>+ <option value="25">25</option>+ </select>+ </label>+ </div>++ <button type="button" class="primary" onclick={() => void create()} disabled={!canInvite || busy}>+ {busy ? $t("omnidisc.guild.working") : $t("omnidisc.guild_settings.invite_create")}+ </button>++ {#if error}+ <p class="error" role="alert">{error}</p>+ {:else if link}+ <div class="result" role="status">+ <code class="link">{link}</code>+ <button type="button" class="ghost" onclick={() => void copy()}>+ {copied ? $t("omnidisc.guild.invite_copied") : $t("omnidisc.guild_settings.invite_copy")}+ </button>+ </div>+ {:else}+ <p class="hint">{$t("omnidisc.guild_settings.invites_empty")}</p>+ {/if}++ <p class="note">{$t("omnidisc.guild_settings.invites_no_list")}</p>+</section>++<style>+ .invites {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ max-width: 560px;+ }++ .fields {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-3);+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ flex: 1 1 160px;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ width: 100%;+ box-sizing: border-box;+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .primary {+ align-self: flex-start;+ padding: 8px var(--space-4);+ border: none;+ border-radius: var(--radius-sm);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ cursor: pointer;+ }++ .primary:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .result {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2);+ border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ background: var(--surface);+ }++ .link {+ flex: 1;+ font-size: var(--text-xs);+ color: var(--text);+ overflow-wrap: anywhere;+ }++ .ghost {+ padding: 4px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .hint,+ .note {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ select:focus-visible,+ button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/components/omnidisc/settings/GuildRoles.svelte b/src/components/omnidisc/settings/GuildRoles.sveltenew file mode 100644index 00000000..c83950cf--- /dev/null+++ b/src/components/omnidisc/settings/GuildRoles.svelte@@ -0,0 +1,446 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { createRole, deleteRole, getRoles, updateRole } from "$lib/stores/omnidisc-store.svelte";+ import { PERMISSION_GROUPS, has, perm, toBits, type PermissionGroup, type PermissionName } from "$lib/omnidisc/permissions";+ import type { OmnidiscRole } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "../OmnidiscPrompt.svelte";++ let { guildId, canManage }: { guildId: string; canManage: boolean } = $props();++ const GROUPS: PermissionGroup[] = ["general", "text", "voice", "moderation"];++ let roles = $derived(getRoles(guildId));+ let selectedId = $state<string | null>(null);+ let selected = $derived(roles.find((r) => r.id === selectedId) ?? roles[0] ?? null);+ let busy = $state(false);+ let error = $state<string | null>(null);+ let createOpen = $state(false);+ let newName = $state("");+ let pendingDelete = $state<OmnidiscRole | null>(null);++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function run(fn: () => Promise<void>) {+ busy = true;+ error = null;+ try {+ await fn();+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ async function togglePermission(role: OmnidiscRole, name: PermissionName) {+ const bits = toBits(role.permissions);+ const next = has(bits, name) ? bits & ~perm(name) : bits | perm(name);+ await run(() => updateRole(guildId, role.id, { permissions: next.toString() }));+ }++ async function rename(role: OmnidiscRole, name: string) {+ const trimmed = name.trim();+ if (!trimmed || trimmed === role.name) return;+ await run(() => updateRole(guildId, role.id, { name: trimmed }));+ }++ async function setColor(role: OmnidiscRole, hex: string) {+ const value = Number.parseInt(hex.replace("#", ""), 16);+ if (!Number.isFinite(value)) return;+ await run(() => updateRole(guildId, role.id, { color: value }));+ }++ async function submitCreate() {+ const name = newName.trim();+ if (!name) return;+ await run(async () => {+ const role = await createRole(guildId, name, "0");+ if (role) selectedId = role.id;+ createOpen = false;+ newName = "";+ });+ }++ async function confirmDelete() {+ const role = pendingDelete;+ if (!role) return;+ await run(async () => {+ await deleteRole(guildId, role.id);+ pendingDelete = null;+ if (selectedId === role.id) selectedId = null;+ });+ }++ function colorHex(role: OmnidiscRole): string {+ return `#${(role.color ?? 0).toString(16).padStart(6, "0")}`;+ }+</script>++<section class="roles">+ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ {#if roles.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.guild_settings.roles_empty_title")}</p>+ <p class="state-body">{$t("omnidisc.guild_settings.roles_empty_body")}</p>+ </div>+ {:else}+ <div class="grid">+ <div class="list-col">+ <ul class="list">+ {#each roles as role (role.id)}+ <li>+ <button type="button" class="role" class:on={selected?.id === role.id} onclick={() => (selectedId = role.id)}>+ <span class="swatch" style:background={role.color ? colorHex(role) : "var(--text-dim)"}></span>+ <span class="role-name">{role.isEveryone ? $t("omnidisc.guild_settings.everyone_role") : role.name}</span>+ </button>+ </li>+ {/each}+ </ul>+ {#if canManage}+ <button type="button" class="add" onclick={() => (createOpen = true)}>{$t("omnidisc.guild_settings.role_create")}</button>+ {/if}+ </div>++ {#if selected}+ <div class="detail">+ <div class="fields">+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.role_name")}</span>+ <input+ class="field-input"+ type="text"+ value={selected.isEveryone ? $t("omnidisc.guild_settings.everyone_role") : selected.name}+ maxlength="60"+ disabled={!canManage || selected.isEveryone || busy}+ onchange={(e) => selected && void rename(selected, e.currentTarget.value)}+ />+ </label>+ {#if !selected.isEveryone}+ <label class="field short">+ <span class="field-label">{$t("omnidisc.guild_settings.role_color")}</span>+ <input+ class="field-color"+ type="color"+ value={colorHex(selected)}+ disabled={!canManage || busy}+ onchange={(e) => selected && void setColor(selected, e.currentTarget.value)}+ />+ </label>+ <label class="toggle">+ <input+ type="checkbox"+ checked={selected.hoist}+ disabled={!canManage || busy}+ onchange={(e) => selected && void run(() => updateRole(guildId, selected.id, { hoist: e.currentTarget.checked }))}+ />+ <span>{$t("omnidisc.guild_settings.role_hoist")}</span>+ </label>+ <label class="toggle">+ <input+ type="checkbox"+ checked={selected.mentionable}+ disabled={!canManage || busy}+ onchange={(e) => selected && void run(() => updateRole(guildId, selected.id, { mentionable: e.currentTarget.checked }))}+ />+ <span>{$t("omnidisc.guild_settings.role_mentionable")}</span>+ </label>+ {/if}+ </div>++ {#each GROUPS as group (group)}+ <h4 class="group-title">{$t(`omnidisc.guild_settings.perm_group_${group}`)}</h4>+ <ul class="perms">+ {#each PERMISSION_GROUPS[group] as name (name)}+ <li class="perm">+ <label class="perm-row">+ <input+ type="checkbox"+ checked={has(toBits(selected.permissions), name)}+ disabled={!canManage || busy}+ onchange={() => selected && void togglePermission(selected, name)}+ />+ <span class="perm-text">+ <span class="perm-name">{$t(`omnidisc.perm.${name}`)}</span>+ <span class="perm-desc">{$t(`omnidisc.perm_desc.${name}`)}</span>+ </span>+ </label>+ </li>+ {/each}+ </ul>+ {/each}++ {#if canManage && !selected.isEveryone}+ <button type="button" class="danger" onclick={() => (pendingDelete = selected)}>+ {$t("omnidisc.guild_settings.role_delete", { name: selected.name })}+ </button>+ {/if}+ </div>+ {/if}+ </div>+ {/if}+</section>++<OmnidiscPrompt+ open={createOpen}+ title={$t("omnidisc.guild_settings.role_create_title")}+ submitLabel={$t("omnidisc.guild_settings.role_create_submit")}+ {busy}+ {error}+ canSubmit={newName.trim().length > 0}+ onSubmit={() => void submitCreate()}+ onClose={() => (createOpen = false)}+>+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.role_name")}</span>+ <input class="field-input" type="text" bind:value={newName} maxlength="60" placeholder={$t("omnidisc.guild_settings.role_name_placeholder")} />+ </label>+</OmnidiscPrompt>++<OmnidiscPrompt+ open={pendingDelete !== null}+ title={$t("omnidisc.guild_settings.role_delete_title", { name: pendingDelete?.name ?? "" })}+ body={$t("omnidisc.guild_settings.role_delete_body")}+ submitLabel={$t("omnidisc.guild_settings.role_delete_confirm", { name: pendingDelete?.name ?? "" })}+ {busy}+ {error}+ onSubmit={() => void confirmDelete()}+ onClose={() => (pendingDelete = null)}+>+ <p class="confirm-text">{$t("omnidisc.guild_settings.role_delete_hint")}</p>+</OmnidiscPrompt>++<style>+ .roles {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ }++ .grid {+ display: grid;+ grid-template-columns: 200px 1fr;+ gap: var(--space-4);+ }++ .list-col {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .role {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ width: 100%;+ padding: 6px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .role:hover {+ background: var(--fill-1);+ }++ .role.on {+ background: var(--accent-soft);+ color: var(--accent);+ font-weight: 600;+ }++ .swatch {+ width: 10px;+ height: 10px;+ flex: 0 0 10px;+ border-radius: var(--radius-full);+ }++ .role-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .add,+ .danger {+ padding: 6px var(--space-3);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .add:hover {+ background: var(--fill-1);+ }++ .danger {+ align-self: flex-start;+ color: var(--danger);+ border-color: var(--danger);+ }++ .detail {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ min-width: 0;+ }++ .fields {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ gap: var(--space-3);+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ flex: 1 1 200px;+ }++ .field.short {+ flex: 0 0 auto;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ width: 100%;+ box-sizing: border-box;+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .field-color {+ width: 48px;+ height: 34px;+ padding: 2px;+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ }++ .toggle {+ display: inline-flex;+ align-items: center;+ gap: var(--space-2);+ font-size: var(--text-sm);+ color: var(--text);+ }++ .group-title {+ margin: var(--space-3) 0 0;+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .perms {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .perm-row {+ display: flex;+ align-items: flex-start;+ gap: var(--space-2);+ padding: 4px 0;+ cursor: pointer;+ }++ .perm-text {+ display: flex;+ flex-direction: column;+ }++ .perm-name {+ font-size: var(--text-sm);+ color: var(--text);+ }++ .perm-desc {+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.4;+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body,+ .confirm-text {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ input:focus-visible,+ button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @media (max-width: 760px) {+ .grid {+ grid-template-columns: 1fr;+ }+ }+</style>diff --git a/src/components/omnidisc/settings/ProfileSettings.svelte b/src/components/omnidisc/settings/ProfileSettings.sveltenew file mode 100644index 00000000..3d9384b8--- /dev/null+++ b/src/components/omnidisc/settings/ProfileSettings.svelte@@ -0,0 +1,389 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ getMe,+ getOwnPresence,+ getSelectedInstance,+ setOwnPresence,+ updateMe,+ } from "$lib/stores/omnidisc-store.svelte";++ const PRESENCES = ["online", "idle", "dnd", "invisible"] as const;+ const BIO_MAX = 320;++ let instance = $derived(getSelectedInstance());+ let me = $derived(getMe(instance?.id ?? null));+ let connected = $derived(instance?.status === "connected");++ let displayName = $state("");+ let pronouns = $state("");+ let bio = $state("");+ let accent = $state("#5865f2");+ let statusText = $state("");+ let statusExpiry = $state("0");+ let seeded = $state<string | null>(null);+ let busy = $state(false);+ let error = $state<string | null>(null);+ let saved = $state(false);++ $effect(() => {+ if (!me || seeded === me.id) return;+ seeded = me.id;+ displayName = me.displayName;+ pronouns = me.pronouns ?? "";+ bio = me.bio ?? "";+ if (me.accentColor !== undefined) accent = `#${me.accentColor.toString(16).padStart(6, "0")}`;+ });++ let presence = $derived(getOwnPresence(instance?.id ?? null));++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function save() {+ const id = instance?.id;+ if (!id) return;+ busy = true;+ error = null;+ saved = false;+ try {+ await updateMe(id, {+ display_name: displayName.trim() || undefined,+ pronouns: pronouns.trim(),+ bio: bio.trim(),+ accent_color: Number.parseInt(accent.replace("#", ""), 16),+ });+ saved = true;+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ async function applyPresence(next: string) {+ const id = instance?.id;+ if (!id) return;+ busy = true;+ error = null;+ try {+ const minutes = Number(statusExpiry);+ await setOwnPresence(id, next, {+ text: statusText.trim() || undefined,+ expiresAt: minutes > 0 ? new Date(Date.now() + minutes * 60_000).toISOString() : undefined,+ });+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }+</script>++{#if !instance}+ <div class="state">+ <p class="state-title">{$t("omnidisc.profile_settings.no_instance_title")}</p>+ <p class="state-body">{$t("omnidisc.profile_settings.no_instance_body")}</p>+ </div>+{:else}+ <section class="profile-settings">+ <div class="preview" aria-label={$t("omnidisc.profile_settings.preview")}>+ <span class="preview-banner" style:background={accent}></span>+ <span class="preview-avatar">{(displayName || me?.username || "?").trim().charAt(0).toUpperCase()}</span>+ <span class="preview-names">+ <strong>{displayName || me?.username}</strong>+ <span class="handle">@{me?.username ?? "…"}</span>+ {#if pronouns}<span class="handle">{pronouns}</span>{/if}+ </span>+ {#if bio}<p class="preview-bio">{bio}</p>{/if}+ </div>++ <label class="field">+ <span class="field-label">{$t("omnidisc.profile_settings.display_name")}</span>+ <input class="field-input" type="text" bind:value={displayName} maxlength="32" disabled={!connected || busy} />+ </label>++ <label class="field">+ <span class="field-label">{$t("omnidisc.profile_settings.pronouns")}</span>+ <input class="field-input" type="text" bind:value={pronouns} maxlength="40" disabled={!connected || busy} placeholder={$t("omnidisc.profile_settings.pronouns_placeholder")} />+ </label>++ <label class="field">+ <span class="field-label">{$t("omnidisc.profile_settings.bio")}</span>+ <textarea class="field-input" rows="3" maxlength={BIO_MAX} bind:value={bio} disabled={!connected || busy}></textarea>+ <span class="counter">{bio.length}/{BIO_MAX}</span>+ </label>++ <label class="field short">+ <span class="field-label">{$t("omnidisc.profile_settings.accent")}</span>+ <input class="field-color" type="color" bind:value={accent} disabled={!connected || busy} />+ </label>++ <button type="button" class="primary" onclick={() => void save()} disabled={!connected || busy}>+ {busy ? $t("omnidisc.guild.working") : $t("omnidisc.profile_settings.save")}+ </button>++ {#if error}+ <p class="error" role="alert">{error}</p>+ {:else if saved}+ <p class="ok" role="status">{$t("omnidisc.profile_settings.saved")}</p>+ {/if}++ <p class="note">{$t("omnidisc.profile_settings.avatar_note")}</p>++ <h4 class="block-title">{$t("omnidisc.profile_settings.presence")}</h4>+ <div class="segmented" role="radiogroup" aria-label={$t("omnidisc.profile_settings.presence")}>+ {#each PRESENCES as option (option)}+ <button+ type="button"+ class="seg"+ class:on={presence === option}+ aria-pressed={presence === option}+ disabled={!connected || busy}+ onclick={() => void applyPresence(option)}+ >+ {$t(`omnidisc.profile_settings.presence_${option}`)}+ </button>+ {/each}+ </div>++ <label class="field">+ <span class="field-label">{$t("omnidisc.profile_settings.custom_status")}</span>+ <input class="field-input" type="text" bind:value={statusText} maxlength="128" disabled={!connected || busy} placeholder={$t("omnidisc.profile_settings.custom_status_placeholder")} />+ </label>++ <label class="field short">+ <span class="field-label">{$t("omnidisc.profile_settings.custom_status_expiry")}</span>+ <select class="field-input" bind:value={statusExpiry} disabled={!connected || busy}>+ <option value="0">{$t("omnidisc.profile_settings.expiry_never")}</option>+ <option value="30">{$t("omnidisc.profile_settings.expiry_30m")}</option>+ <option value="240">{$t("omnidisc.profile_settings.expiry_4h")}</option>+ <option value="1440">{$t("omnidisc.profile_settings.expiry_today")}</option>+ </select>+ </label>++ <button type="button" class="ghost" onclick={() => void applyPresence(presence)} disabled={!connected || busy}>+ {$t("omnidisc.profile_settings.apply_status")}+ </button>+ </section>+{/if}++<style>+ .profile-settings {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ max-width: 520px;+ }++ .preview {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: 0 var(--space-3) var(--space-3);+ border: 1px solid var(--border);+ border-radius: var(--border-radius);+ background: var(--surface);+ overflow: hidden;+ }++ .preview-banner {+ height: 48px;+ margin: 0 calc(-1 * var(--space-3));+ }++ .preview-avatar {+ width: 48px;+ height: 48px;+ margin-top: -24px;+ border: 3px solid var(--surface);+ border-radius: var(--radius-full);+ background: var(--accent-soft);+ color: var(--accent);+ display: grid;+ place-items: center;+ font-weight: 600;+ }++ .preview-names {+ display: flex;+ flex-direction: column;+ }++ .handle {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .preview-bio {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-secondary, var(--text));+ line-height: 1.45;+ white-space: pre-wrap;+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .field.short {+ max-width: 220px;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ width: 100%;+ box-sizing: border-box;+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ resize: vertical;+ }++ .field-color {+ width: 56px;+ height: 34px;+ padding: 2px;+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ }++ .counter {+ align-self: flex-end;+ font-size: var(--text-xs);+ color: var(--text-muted);+ font-variant-numeric: tabular-nums;+ }++ .primary {+ align-self: flex-start;+ padding: 8px var(--space-4);+ border: none;+ border-radius: var(--radius-sm);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ cursor: pointer;+ }++ .ghost {+ align-self: flex-start;+ padding: 6px var(--space-3);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .primary:disabled,+ .ghost:disabled,+ .seg:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .block-title {+ margin: var(--space-2) 0 0;+ font-size: var(--text-xs);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .segmented {+ display: flex;+ }++ .seg {+ padding: 6px var(--space-3);+ border: 1px solid var(--border);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .seg:first-child {+ border-radius: var(--radius-sm) 0 0 var(--radius-sm);+ }++ .seg:last-child {+ border-radius: 0 var(--radius-sm) var(--radius-sm) 0;+ }++ .seg.on {+ background: var(--accent-soft);+ border-color: var(--accent);+ color: var(--accent);+ font-weight: 600;+ }++ .note {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .ok {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--success);+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ input:focus-visible,+ select:focus-visible,+ textarea:focus-visible,+ button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/components/omnidisc/settings/SessionsSettings.svelte b/src/components/omnidisc/settings/SessionsSettings.sveltenew file mode 100644index 00000000..2ff9098f--- /dev/null+++ b/src/components/omnidisc/settings/SessionsSettings.svelte@@ -0,0 +1,278 @@+<script lang="ts">+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import { getSelectedInstance, listSessions, revokeOtherSessions, revokeSession } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscSession } from "$lib/omnidisc/types";+ import OmnidiscPrompt from "../OmnidiscPrompt.svelte";++ let instance = $derived(getSelectedInstance());+ let sessions = $state<OmnidiscSession[]>([]);+ let loading = $state(true);+ let error = $state<string | null>(null);+ let busy = $state(false);+ let pending = $state<OmnidiscSession | null>(null);+ let revokeAll = $state(false);+ let loadedFor = $state<string | null>(null);++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function refresh() {+ const id = instance?.id;+ if (!id) return;+ loading = true;+ error = null;+ try {+ sessions = await listSessions(id);+ } catch (e) {+ fail(e);+ sessions = [];+ } finally {+ loading = false;+ }+ }++ $effect(() => {+ const id = instance?.id;+ if (!id || loadedFor === id) return;+ loadedFor = id;+ void refresh();+ });++ function label(session: OmnidiscSession): string {+ return session.deviceName || session.client || $t("omnidisc.sessions.unknown_device");+ }++ function when(session: OmnidiscSession): string {+ const ms = Date.parse(session.lastSeen);+ if (!Number.isFinite(ms)) return "";+ return new Date(ms).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });+ }++ async function confirmRevoke() {+ const id = instance?.id;+ if (!id) return;+ busy = true;+ error = null;+ try {+ if (revokeAll) await revokeOtherSessions(id);+ else if (pending) await revokeSession(id, pending.sessionId);+ pending = null;+ revokeAll = false;+ await refresh();+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }+</script>++{#if !instance}+ <div class="state">+ <p class="state-title">{$t("omnidisc.profile_settings.no_instance_title")}</p>+ <p class="state-body">{$t("omnidisc.profile_settings.no_instance_body")}</p>+ </div>+{:else}+ <section class="sessions">+ {#if error}+ <p class="error" role="alert">{error}</p>+ {/if}++ {#if loading}+ <div class="state" aria-busy="true">+ {#each Array(3) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if sessions.length === 0}+ <div class="state">+ <p class="state-title">{$t("omnidisc.sessions.empty_title")}</p>+ <p class="state-body">{$t("omnidisc.sessions.empty_body")}</p>+ </div>+ {:else}+ <ul class="list">+ {#each sessions as session (session.sessionId)}+ <li class="row">+ <span class="who">+ <span class="name">+ {label(session)}+ {#if session.current}<span class="tag">{$t("omnidisc.sessions.current")}</span>{/if}+ </span>+ <span class="meta">{$t("omnidisc.sessions.last_seen", { when: when(session) })}</span>+ </span>+ <button+ type="button"+ class="ghost"+ onclick={() => {+ revokeAll = false;+ pending = session;+ }}+ >+ {session.current ? $t("omnidisc.sessions.sign_out_here") : $t("omnidisc.sessions.revoke")}+ </button>+ </li>+ {/each}+ </ul>++ {#if sessions.length > 1}+ <button+ type="button"+ class="ghost danger"+ onclick={() => {+ pending = null;+ revokeAll = true;+ }}+ >+ {$t("omnidisc.sessions.revoke_others", { count: sessions.length - 1 })}+ </button>+ {/if}+ {/if}+ </section>+{/if}++<OmnidiscPrompt+ open={pending !== null || revokeAll}+ title={revokeAll+ ? $t("omnidisc.sessions.revoke_others_title")+ : $t("omnidisc.sessions.revoke_title", { device: pending ? label(pending) : "" })}+ body={revokeAll ? $t("omnidisc.sessions.revoke_others_body") : $t("omnidisc.sessions.revoke_body")}+ submitLabel={revokeAll+ ? $t("omnidisc.sessions.revoke_others_confirm")+ : $t("omnidisc.sessions.revoke_confirm", { device: pending ? label(pending) : "" })}+ {busy}+ {error}+ onSubmit={() => void confirmRevoke()}+ onClose={() => {+ pending = null;+ revokeAll = false;+ error = null;+ }}+>+ <p class="state-body">{$t("omnidisc.sessions.revoke_hint")}</p>+</OmnidiscPrompt>++<style>+ .sessions {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ max-width: 560px;+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }++ .row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-3);+ padding: var(--space-2) 0;+ border-bottom: 1px solid var(--border);+ }++ .who {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ .name {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .tag {+ padding: 1px var(--space-2);+ border-radius: var(--radius-full);+ background: var(--accent-soft);+ color: var(--accent);+ font-size: var(--text-xs);+ font-weight: 600;+ }++ .meta {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .ghost {+ padding: 4px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .ghost:hover {+ background: var(--fill-1);+ }++ .ghost.danger {+ align-self: flex-start;+ color: var(--danger);+ border-color: var(--danger);+ }++ .ghost:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .skeleton-line {+ height: 40px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/components/settings/SettingsAdvanced.svelte b/src/components/settings/SettingsAdvanced.svelteindex c682c6f9..f983e524 100644--- a/src/components/settings/SettingsAdvanced.svelte+++ b/src/components/settings/SettingsAdvanced.svelte@@ -16,7 +16,7 @@searchActive?: boolean;} = $props();- type AdvancedDrill = "performance" | "torrent" | "expert" | "league" | "debug";+ type AdvancedDrill = "performance" | "torrent" | "expert" | "league" | "omnidisc" | "debug";let subView = $state<AdvancedDrill | null>(null);let settings = $derived(getSettings());@@ -26,6 +26,7 @@{ id: "torrent", titleKey: "settings.advanced.section_torrent", hintKey: "settings.advanced.section_torrent_desc" },{ id: "expert", titleKey: "settings.advanced.section_expert", hintKey: "settings.advanced.section_expert_desc" },{ id: "league", titleKey: "league.settings_title", hintKey: "league.settings_desc" },+ { id: "omnidisc", titleKey: "omnidisc.settings_title", hintKey: "omnidisc.settings_desc" },{ id: "debug", titleKey: "settings.advanced.section_debug", hintKey: "settings.advanced.section_debug_desc" },];@@ -321,6 +322,16 @@</div>{/if}</div>+ {:else if subView === "omnidisc"}+ <div class="card">+ <div class="setting-row">+ <div class="setting-col">+ <span class="setting-label">{$t('omnidisc.settings_enable')}</span>+ <span class="setting-path">{$t('omnidisc.settings_enable_desc')}</span>+ </div>+ <button class="toggle" class:on={settings.omnidisc?.enabled} onclick={() => updateSettings({ omnidisc: { enabled: !(settings.omnidisc?.enabled ?? false) } })} role="switch" aria-checked={settings.omnidisc?.enabled ?? false} aria-label={$t('omnidisc.settings_enable') as string}><span class="toggle-knob"></span></button>+ </div>+ </div>{:else if subView === "debug"}<div class="card"><div class="setting-row">diff --git a/src/components/shell/AppSidebar.svelte b/src/components/shell/AppSidebar.svelteindex f1c2640a..f30a51f2 100644--- a/src/components/shell/AppSidebar.svelte+++ b/src/components/shell/AppSidebar.svelte@@ -1,92 +1,98 @@-<script lang="ts">- import { page } from "$app/state";- import { t } from "$lib/i18n";- import NavIcon from "$components/shell/NavIcon.svelte";- import type { NavItem } from "$lib/nav-config";-- interface Props {- primaryNav?: NavItem[];- appNav?: NavItem[];- pluginNav?: NavItem[];- badgeLabel?: string;- badgeCount?: number;- }-- let {- primaryNav = [],- appNav = [],- pluginNav = [],- badgeLabel = "",- badgeCount = 0,- }: Props = $props();-- let pluginsExpanded = $state(true);-- function isActive(href: string): boolean {- if (href === "/") return page.url.pathname === "/";- return page.url.pathname.startsWith(href);- }-- function itemTitle(item: NavItem): string {- return item.label || (item.labelKey ? $t(item.labelKey) : "");- }-</script>--<aside class="mac-source-list">- <div class="mac-nav-section">- <div class="mac-nav-section-header">{$t("nav.section_primary")}</div>- {#each primaryNav as item}- {@const title = itemTitle(item)}- <a href={item.href} class="mac-nav-item" class:active={isActive(item.href)} title={title}>- <NavIcon icon={item.icon} iconSvg={item.iconSvg} />- <span class="mac-nav-label">{title}</span>- {#if item.badge === "downloads" && badgeCount > 0}- <span class="mac-nav-badge">{badgeLabel}</span>- {/if}- </a>- {/each}- </div>-- <div class="mac-nav-section">- <div class="mac-nav-section-header">{$t("nav.section_app")}</div>- {#each appNav as item}- {@const title = itemTitle(item)}- <a href={item.href} class="mac-nav-item" class:active={isActive(item.href)} title={title}>- <NavIcon icon={item.icon} iconSvg={item.iconSvg} />- <span class="mac-nav-label">{title}</span>- </a>- {/each}- </div>-- {#if pluginNav.length > 0}- <div class="mac-nav-section">- <div class="mac-nav-section-header">- <span>{$t("nav.section_plugins")}</span>- <button- type="button"- class="mac-plugins-toggle"- onclick={() => { pluginsExpanded = !pluginsExpanded; }}- aria-expanded={pluginsExpanded}- aria-label={pluginsExpanded ? $t("nav.collapse_plugins") : $t("nav.expand_plugins")}- >- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">- {#if pluginsExpanded}- <path d="M6 9l6 6 6-6" />- {:else}- <path d="M9 6l6 6-6 6" />- {/if}- </svg>- </button>- </div>- {#if pluginsExpanded}- {#each pluginNav as item}- {@const title = itemTitle(item)}- <a href={item.href} class="mac-nav-item" class:active={isActive(item.href)} title={title}>- <NavIcon icon={item.icon} iconSvg={item.iconSvg} />- <span class="mac-nav-label">{title}</span>- </a>- {/each}- {/if}- </div>- {/if}-</aside>+<script lang="ts">+ import { page } from "$app/state";+ import { t } from "$lib/i18n";+ import NavIcon from "$components/shell/NavIcon.svelte";+ import type { NavItem } from "$lib/nav-config";++ interface Props {+ primaryNav?: NavItem[];+ appNav?: NavItem[];+ pluginNav?: NavItem[];+ badgeLabel?: string;+ badgeCount?: number;+ chatBadgeCount?: number;+ }++ let {+ primaryNav = [],+ appNav = [],+ pluginNav = [],+ badgeLabel = "",+ badgeCount = 0,+ chatBadgeCount = 0,+ }: Props = $props();++ let chatBadgeLabel = $derived(chatBadgeCount > 99 ? "99+" : String(chatBadgeCount));++ let pluginsExpanded = $state(true);++ function isActive(href: string): boolean {+ if (href === "/") return page.url.pathname === "/";+ return page.url.pathname.startsWith(href);+ }++ function itemTitle(item: NavItem): string {+ return item.label || (item.labelKey ? $t(item.labelKey) : "");+ }+</script>++<aside class="mac-source-list">+ <div class="mac-nav-section">+ <div class="mac-nav-section-header">{$t("nav.section_primary")}</div>+ {#each primaryNav as item}+ {@const title = itemTitle(item)}+ <a href={item.href} class="mac-nav-item" class:active={isActive(item.href)} title={title}>+ <NavIcon icon={item.icon} iconSvg={item.iconSvg} />+ <span class="mac-nav-label">{title}</span>+ {#if item.badge === "downloads" && badgeCount > 0}+ <span class="mac-nav-badge">{badgeLabel}</span>+ {:else if item.badge === "omnidisc" && chatBadgeCount > 0}+ <span class="mac-nav-badge">{chatBadgeLabel}</span>+ {/if}+ </a>+ {/each}+ </div>++ <div class="mac-nav-section">+ <div class="mac-nav-section-header">{$t("nav.section_app")}</div>+ {#each appNav as item}+ {@const title = itemTitle(item)}+ <a href={item.href} class="mac-nav-item" class:active={isActive(item.href)} title={title}>+ <NavIcon icon={item.icon} iconSvg={item.iconSvg} />+ <span class="mac-nav-label">{title}</span>+ </a>+ {/each}+ </div>++ {#if pluginNav.length > 0}+ <div class="mac-nav-section">+ <div class="mac-nav-section-header">+ <span>{$t("nav.section_plugins")}</span>+ <button+ type="button"+ class="mac-plugins-toggle"+ onclick={() => { pluginsExpanded = !pluginsExpanded; }}+ aria-expanded={pluginsExpanded}+ aria-label={pluginsExpanded ? $t("nav.collapse_plugins") : $t("nav.expand_plugins")}+ >+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">+ {#if pluginsExpanded}+ <path d="M6 9l6 6 6-6" />+ {:else}+ <path d="M9 6l6 6-6 6" />+ {/if}+ </svg>+ </button>+ </div>+ {#if pluginsExpanded}+ {#each pluginNav as item}+ {@const title = itemTitle(item)}+ <a href={item.href} class="mac-nav-item" class:active={isActive(item.href)} title={title}>+ <NavIcon icon={item.icon} iconSvg={item.iconSvg} />+ <span class="mac-nav-label">{title}</span>+ </a>+ {/each}+ {/if}+ </div>+ {/if}+</aside>diff --git a/src/components/shell/NavIcon.svelte b/src/components/shell/NavIcon.svelteindex 15fa684f..69a08019 100644--- a/src/components/shell/NavIcon.svelte+++ b/src/components/shell/NavIcon.svelte@@ -1,47 +1,50 @@-<script lang="ts">- let { icon, iconSvg, size = 18 }: { icon: string; iconSvg?: string; size?: number } = $props();-</script>--<svg- viewBox="0 0 24 24"- width={size}- height={size}- fill="none"- stroke="currentColor"- stroke-width="1.8"- stroke-linecap="round"- stroke-linejoin="round"- aria-hidden="true"->- {#if iconSvg}- {#each iconSvg.split(" M").map((d, i) => (i === 0 ? d : "M" + d)) as pathD}- <path d={pathD} />- {/each}- {:else if icon === "home"}- <path d="M3 12L12 3l9 9" />- <path d="M5 10v9a1 1 0 001 1h3v-5h6v5h3a1 1 0 001-1v-9" />- {:else if icon === "downloads"}- <path d="M12 3v12m0 0l-4-4m4 4l4-4" />- <path d="M4 17v2a1 1 0 001 1h14a1 1 0 001-1v-2" />- {:else if icon === "marketplace"}- <path d="M3 21h18" />- <path d="M3 7v1a3 3 0 0 0 6 0V7" />- <path d="M9 7v1a3 3 0 0 0 6 0V7" />- <path d="M15 7v1a3 3 0 0 0 6 0V7" />- <path d="M3 7h18l-1.5-4H4.5z" />- <path d="M5 21V10" />- <path d="M19 21V10" />- {:else if icon === "settings"}- <path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />- <circle cx="12" cy="12" r="3" />+<script lang="ts">+ let { icon, iconSvg, size = 18 }: { icon: string; iconSvg?: string; size?: number } = $props();+</script>++<svg+ viewBox="0 0 24 24"+ width={size}+ height={size}+ fill="none"+ stroke="currentColor"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+ aria-hidden="true"+>+ {#if iconSvg}+ {#each iconSvg.split(" M").map((d, i) => (i === 0 ? d : "M" + d)) as pathD}+ <path d={pathD} />+ {/each}+ {:else if icon === "home"}+ <path d="M3 12L12 3l9 9" />+ <path d="M5 10v9a1 1 0 001 1h3v-5h6v5h3a1 1 0 001-1v-9" />+ {:else if icon === "downloads"}+ <path d="M12 3v12m0 0l-4-4m4 4l4-4" />+ <path d="M4 17v2a1 1 0 001 1h14a1 1 0 001-1v-2" />+ {:else if icon === "chat"}+ <path d="M21 12a8 8 0 0 1-8 8H7l-4 3V12a8 8 0 0 1 8-8h2a8 8 0 0 1 8 8z" />+ <path d="M8 12h.01M12 12h.01M16 12h.01" />+ {:else if icon === "marketplace"}+ <path d="M3 21h18" />+ <path d="M3 7v1a3 3 0 0 0 6 0V7" />+ <path d="M9 7v1a3 3 0 0 0 6 0V7" />+ <path d="M15 7v1a3 3 0 0 0 6 0V7" />+ <path d="M3 7h18l-1.5-4H4.5z" />+ <path d="M5 21V10" />+ <path d="M19 21V10" />+ {:else if icon === "settings"}+ <path d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />+ <circle cx="12" cy="12" r="3" />{:else if icon === "league"}<path d="M6 14L17 3h4v4L10 18" /><path d="M3 21l5-5" /><path d="M5 14l5 5" />- {:else if icon === "about"}- <circle cx="12" cy="12" r="10" />- <path d="M12 16v-4m0-4h.01" />- {:else}- <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />- {/if}-</svg>+ {:else if icon === "about"}+ <circle cx="12" cy="12" r="10" />+ <path d="M12 16v-4m0-4h.01" />+ {:else}+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />+ {/if}+</svg>diff --git a/src/lib/error-translate.ts b/src/lib/error-translate.tsindex 4737d4ec..be0d95d8 100644--- a/src/lib/error-translate.ts+++ b/src/lib/error-translate.ts@@ -44,6 +44,80 @@ const BACKEND_ERROR_MAP: Record<string, string> = {"errors.drm_protected","Course platforms can't be downloaded from a URL. Open the Courses page (requires the Courses plugin and a logged-in account).":"errors.course_platform_url",+ "OmniDisc: invalid instance URL. Use http:// or https:// without a username or password.":+ "omnidisc.error.invalid_url",+ "OmniDisc: the server did not respond. Check the address or ask the owner for a new link.":+ "omnidisc.error.unreachable",+ "OmniDisc: this address is not an OmniDisc server.": "omnidisc.error.not_an_instance",+ ERR_UNAUTHORIZED: "omnidisc.error.unauthorized",+ ERR_NO_SESSION: "omnidisc.error.no_session",+ ERR_FORBIDDEN: "omnidisc.error.forbidden",+ "ERR_FORBIDDEN:registration_closed": "omnidisc.error.registration_closed",+ "ERR_FORBIDDEN:missing_permissions": "omnidisc.error.missing_permissions",+ "ERR_FORBIDDEN:too_many_guilds": "omnidisc.error.too_many_guilds",+ ERR_NOT_FOUND: "omnidisc.error.not_found",+ ERR_RATE_LIMITED: "omnidisc.error.rate_limited",+ ERR_UNREACHABLE: "omnidisc.error.unreachable",+ ERR_SERVER: "omnidisc.error.server",+ ERR_NOT_CONNECTED: "omnidisc.error.not_connected",+ ERR_PROTOCOL: "omnidisc.error.protocol",+ ERR_BAD_REQUEST: "omnidisc.error.bad_request",+ "ERR_BAD_REQUEST:invalid_credentials": "omnidisc.error.invalid_credentials",+ "ERR_BAD_REQUEST:username_taken": "omnidisc.error.username_taken",+ "ERR_BAD_REQUEST:invalid_username": "omnidisc.error.invalid_username",+ "ERR_BAD_REQUEST:invalid_password": "omnidisc.error.invalid_password",+ "ERR_BAD_REQUEST:invalid_invite": "omnidisc.error.invalid_invite",+ "ERR_BAD_REQUEST:message_too_long": "omnidisc.error.message_too_long",+ "ERR_BAD_REQUEST:empty_message": "omnidisc.error.empty_message",+ ERR_SCREEN_PERMISSION: "omnidisc.error.screen_permission",+ ERR_STREAM_UNSUPPORTED: "omnidisc.error.stream_unsupported",+ ERR_STREAM_SOURCE_GONE: "omnidisc.error.stream_source_gone",+ ERR_STREAM_CAPTURE_FAILED: "omnidisc.error.stream_capture_failed",+ ERR_STREAM_ENCODER_FAILED: "omnidisc.error.stream_encoder_failed",+ ERR_STREAM_NOT_STREAMING: "omnidisc.error.stream_not_streaming",+ ERR_STREAM_NOT_FOUND: "omnidisc.error.stream_not_found",+ ERR_STREAM_VIEWER_FAILED: "omnidisc.error.stream_viewer_failed",+ ERR_VOICE_MIC_PERMISSION: "omnidisc.error.voice_mic_permission",+ ERR_VOICE_NO_INPUT_DEVICE: "omnidisc.error.voice_no_input_device",+ ERR_VOICE_NO_OUTPUT_DEVICE: "omnidisc.error.voice_no_output_device",+ ERR_VOICE_NO_AUDIO_DEVICE: "omnidisc.error.voice_no_input_device",+ ERR_VOICE_DEVICE_BUSY: "omnidisc.error.voice_device_busy",+ ERR_VOICE_MIC_FAILED: "omnidisc.error.voice_mic_failed",+ ERR_VOICE_OUTPUT_FAILED: "omnidisc.error.voice_output_failed",+ ERR_VOICE_MIC_LOST: "omnidisc.error.voice_mic_lost",+ ERR_VOICE_OUTPUT_LOST: "omnidisc.error.voice_output_lost",+ ERR_VOICE_OUTPUT_PERMISSION: "omnidisc.error.voice_output_permission",+ ERR_VOICE_UNREACHABLE: "omnidisc.error.voice_unreachable",+ ERR_VOICE_TIMEOUT: "omnidisc.error.voice_timeout",+ ERR_VOICE_DENIED: "omnidisc.error.voice_denied",+ ERR_VOICE_DM_UNSUPPORTED: "omnidisc.error.voice_dm_unsupported",+ ERR_VOICE_NOT_CONNECTED: "omnidisc.error.voice_not_connected",+ ERR_VOICE_DISCONNECTED: "omnidisc.error.voice_disconnected",+ ERR_VOICE_UNAVAILABLE: "omnidisc.error.voice_unavailable",+ ERR_VOICE_ENGINE_CRASHED: "omnidisc.error.voice_engine_crashed",+ ERR_E2EE: "omnidisc.error.e2ee",+ ERR_E2EE_NOT_READY: "omnidisc.error.e2ee_not_ready",+ ERR_UPLOAD_TOO_LARGE: "omnidisc.error.upload_too_large",+ ERR_UPLOAD: "omnidisc.error.upload_failed",+ ERR_UPLOAD_CANCELLED: "omnidisc.error.upload_cancelled",+ ERR_UNKNOWN_UPLOAD: "omnidisc.error.unknown_upload",+ ERR_ATTACHMENT_CORRUPT: "omnidisc.error.attachment_corrupt",+ ERR_ATTACHMENT_ORIGIN: "omnidisc.error.attachment_origin",+ ERR_ATTACHMENT_TOO_LARGE: "omnidisc.error.attachment_too_large",+ ERR_E2EE_UNTRUSTED: "omnidisc.error.e2ee_untrusted",+ ERR_TOO_MANY_ATTACHMENTS: "omnidisc.error.too_many_attachments",+ "ERR_BAD_REQUEST:file_missing": "omnidisc.error.file_missing",+ "ERR_BAD_REQUEST:epoch_conflict": "omnidisc.error.epoch_conflict",+ "ERR_FORBIDDEN:device_required": "omnidisc.error.device_required",+};++const OMNIDISC_PREFIX_MAP: Record<string, string> = {+ ERR_FORBIDDEN: "omnidisc.error.forbidden",+ ERR_BAD_REQUEST: "omnidisc.error.bad_request",+ ERR_UPLOAD: "omnidisc.error.upload_failed",+ ERR_UNKNOWN_UPLOAD: "omnidisc.error.unknown_upload",+ ERR_UPLOAD_TOO_LARGE: "omnidisc.error.upload_too_large",+ ERR_TOO_MANY_ATTACHMENTS: "omnidisc.error.too_many_attachments",};/**@@ -75,6 +149,12 @@ export function translateBackendError(const key = BACKEND_ERROR_MAP[stripped];if (key) return t(key);+ if (stripped.startsWith("ERR_")) {+ const prefix = stripped.split(":")[0];+ const prefixKey = OMNIDISC_PREFIX_MAP[prefix];+ if (prefixKey) return t(prefixKey);+ }+const lower = stripped.toLowerCase();if (lower.includes("could not copy") && lower.includes("cookie")) return t("errors.cookie_database");if (lower.includes("size mismatch")) return t("errors.size_mismatch");diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.jsonindex 2d5e596d..23f99cda 100644--- a/src/lib/i18n/el.json+++ b/src/lib/i18n/el.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "Λήψεις σε εξέλιξη","message": "Έχετε {{count}} ενεργή(ες) λήψη(εις). Το κλείσιμο τώρα θα τις ακυρώσει.",@@ -348,6 +366,7 @@"marketplace": "Marketplace","settings": "Ρυθμίσεις","about": "Σχετικά",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "Εμφάνιση",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "Θέμα","theme_system": "Σύστημα","more_themes": "More themes",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "Εξ'ορισμού φάκελος",@@ -4134,22 +4153,801 @@"test_body": "Θα βλέπετε τέτοιες ειδοποιήσεις όταν τα δέματά σας αλλάζουν κατάσταση."}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "Αυτός ο διακομιστής προσπελαύνεται με απλό http. Ο κωδικός σας και ό,τι στέλνετε εδώ ταξιδεύουν χωρίς κρυπτογράφηση — όποιος βρίσκεται στο δίκτυο ανάμεσά σας μπορεί να τα διαβάσει.",+ "insecure_short": "Σύνδεση χωρίς κρυπτογράφηση"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — σύνδεση χωρίς κρυπτογράφηση (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "Ο διακομιστής απάντησε με μια συσκευή που αυτό το άτομο δεν δημοσίευσε ποτέ. Το OmniGet σταμάτησε αντί να κρυπτογραφήσει προς αυτήν — δεν στάλθηκε τίποτα. Ενημερώστε όποιον διαχειρίζεται τον διακομιστή.",+ "attachment_origin": "Αυτό το συνημμένο δείχνει εκτός αυτού του διακομιστή. Το OmniGet δεν το κατέβασε.",+ "attachment_too_large": "Αυτό το συνημμένο συνέχισε να στέλνει πέρα από το μέγεθος που δήλωσε, οπότε η λήψη σταμάτησε."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Μη επαληθευμένη συσκευή",+ "unverified_hint": "Αυτό το μήνυμα υπογράφηκε από συσκευή που ο/η {{name}} δεν έχει δημοσιεύσει. Μπορεί να μην είναι όντως αυτός/αυτή — ελέγξτε τα αποτυπώματα πριν το εμπιστευθείτε."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex 36952ef8..9828a290 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -366,6 +366,7 @@"marketplace": "Marketplace","settings": "Settings","about": "About",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -884,12 +885,12 @@"title": "Browser extension","description": "The extension sends cookies and page URLs from your browser to OmniGet. It is not on the official stores yet, so use the buttons below to extract the current version and install it manually.","bundled_version": "Bundled version: v{{version}}",- "extracting": "Extracting\u2026",+ "extracting": "Extracting…","update_install": "Update / Install","open_store": "Open store","unavailable": "Unavailable",- "hint_chrome": "chrome://extensions \u2192 Developer mode \u2192 \"Load unpacked\" \u2192 select the extracted folder.",- "hint_firefox": "about:debugging#/runtime/this-firefox \u2192 \"Load Temporary Add-on\" \u2192 select manifest.json in the extracted folder. Firefox drops temporary add-ons on restart, so this has to be repeated until we publish on AMO.",+ "hint_chrome": "chrome://extensions → Developer mode → \"Load unpacked\" → select the extracted folder.",+ "hint_firefox": "about:debugging#/runtime/this-firefox → \"Load Temporary Add-on\" → select manifest.json in the extracted folder. Firefox drops temporary add-ons on restart, so this has to be repeated until we publish on AMO.","hint_safari": "Safari has required extensions to ship through the Mac App Store since Safari 14. A Safari build of the OmniGet extension is not published yet."},"rules": {@@ -4151,5 +4152,802 @@"test_title": "Tracking notifications are working","test_body": "You will see notifications like this when your packages move."}+ },+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "This server is reached over plain http. Your password and everything you send here travel unencrypted — anyone on the network between you and it can read them.",+ "insecure_short": "Unencrypted connection"+ },+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — unencrypted connection (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channel",+ "voice_soon_hint": "Join from the list on the left, or with the button below.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "This server is too old for calls in direct messages. Ask the owner to update it.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "The server answered with a device this person never published. OmniGet stopped rather than encrypt to it — nothing was sent. Tell whoever runs this server.",+ "attachment_origin": "This attachment points somewhere outside this server. OmniGet did not download it.",+ "attachment_too_large": "This attachment kept sending past the size it declared, so the download was stopped."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}",+ "retry": "Try again",+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Encryption starts with the first message you send here",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Unverified device",+ "unverified_hint": "This message was signed by a device {{name}} has not published. It may not really be them — check their fingerprints before you trust it."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"+ }}}diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.jsonindex 18dfb6c0..9175f576 100644--- a/src/lib/i18n/es.json+++ b/src/lib/i18n/es.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "Descargas en curso","message": "Tienes {{count}} descarga(s) activa(s). Si cierras ahora se cancelarán.",@@ -348,6 +366,7 @@"marketplace": "Marketplace","settings": "Configuración","about": "Acerca de",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "Apariencia",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "Tema","theme_system": "Sistema","more_themes": "Más temas",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "Carpeta por defecto",@@ -4134,22 +4153,801 @@"test_body": "Verás notificaciones así cuando tus paquetes cambien de estado."}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "Este servidor se abre por http simple. Tu contraseña y todo lo que envíes aquí viajan sin cifrar — cualquiera en la red entre tú y él puede leerlo.",+ "insecure_short": "Conexión sin cifrar"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — conexión sin cifrar (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "El servidor respondió con un dispositivo que esta persona nunca publicó. OmniGet se detuvo en vez de cifrar hacia él — no se envió nada. Avisa a quien administra este servidor.",+ "attachment_origin": "Este adjunto apunta fuera de este servidor. OmniGet no lo descargó.",+ "attachment_too_large": "Este adjunto siguió enviando más allá del tamaño que declaró, así que se detuvo la descarga."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Dispositivo sin verificar",+ "unverified_hint": "Este mensaje lo firmó un dispositivo que {{name}} no ha publicado. Puede que no sea esa persona — compara las huellas antes de confiar."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.jsonindex dd947bc1..163ccc6b 100644--- a/src/lib/i18n/fr.json+++ b/src/lib/i18n/fr.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "Téléchargements en cours","message": "Vous avez {{count}} téléchargement(s) actif(s). Fermer maintenant va les annuler.",@@ -348,6 +366,7 @@"marketplace": "Marketplace","settings": "Paramètres","about": "À propos",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "Apparence",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "Thème","theme_system": "Système","more_themes": "More themes",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "Dossier par défaut",@@ -4134,22 +4153,801 @@"test_body": "Vous verrez ce type de notification lorsque vos colis évoluent."}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "Ce serveur est joint en http simple. Votre mot de passe et tout ce que vous envoyez ici circulent sans chiffrement — n'importe qui sur le réseau entre vous et lui peut les lire.",+ "insecure_short": "Connexion non chiffrée"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — connexion non chiffrée (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "Le serveur a répondu avec un appareil que cette personne n'a jamais publié. OmniGet s'est arrêté plutôt que de chiffrer vers lui — rien n'a été envoyé. Prévenez la personne qui gère ce serveur.",+ "attachment_origin": "Cette pièce jointe pointe en dehors de ce serveur. OmniGet ne l'a pas téléchargée.",+ "attachment_too_large": "Cette pièce jointe a continué à envoyer au-delà de la taille annoncée, le téléchargement a donc été arrêté."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Appareil non vérifié",+ "unverified_hint": "Ce message a été signé par un appareil que {{name}} n'a pas publié. Ce n'est peut-être pas cette personne — comparez les empreintes avant de faire confiance."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.jsonindex 6bda8952..6c0a6061 100644--- a/src/lib/i18n/it.json+++ b/src/lib/i18n/it.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "Download in corso","message": "Hai {{count}} download attivi. Chiudere ora li annullerà.",@@ -348,6 +366,7 @@"marketplace": "Marketplace","settings": "Impostazioni","about": "Info",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "Aspetto",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "Tema","theme_system": "Sistema","more_themes": "More themes",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "Cartella predefinita",@@ -4134,22 +4153,801 @@"test_body": "Vedrai notifiche come questa quando i tuoi pacchi cambiano stato."}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "Questo server viene raggiunto in http semplice. La tua password e tutto ciò che invii qui viaggiano non cifrati — chiunque sulla rete fra te e il server può leggerli.",+ "insecure_short": "Connessione non cifrata"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — connessione non cifrata (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "Il server ha risposto con un dispositivo che questa persona non ha mai pubblicato. OmniGet si è fermato invece di cifrare verso di esso — non è stato inviato nulla. Avvisa chi gestisce questo server.",+ "attachment_origin": "Questo allegato punta fuori da questo server. OmniGet non l'ha scaricato.",+ "attachment_too_large": "Questo allegato ha continuato a inviare oltre la dimensione dichiarata, quindi il download è stato interrotto."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Dispositivo non verificato",+ "unverified_hint": "Questo messaggio è stato firmato da un dispositivo che {{name}} non ha pubblicato. Potrebbe non essere davvero questa persona — confronta le impronte prima di fidarti."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.jsonindex 84629b4f..eb0722fd 100644--- a/src/lib/i18n/ja.json+++ b/src/lib/i18n/ja.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "ダウンロード中","message": "{{count}} 件のダウンロードが進行中です。今閉じるとキャンセルされます。",@@ -348,6 +366,7 @@"marketplace": "マーケットプレイス","settings": "設定","about": "このアプリについて",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "外観",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "テーマ","theme_system": "システム","more_themes": "More themes",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "既定のフォルダ",@@ -4134,22 +4153,801 @@"test_body": "荷物のステータスが変わると、このような通知が表示されます。"}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "このサーバーには平文の http で接続しています。パスワードもここで送る内容も暗号化されずに流れ、経路上の誰でも読めます。",+ "insecure_short": "暗号化されていない接続"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — 暗号化されていない接続 (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "サーバーは、この人が公開したことのないデバイスを返しました。OmniGet はそこへ暗号化せずに停止し、何も送信していません。サーバーの管理者に知らせてください。",+ "attachment_origin": "この添付ファイルはこのサーバーの外を指しています。OmniGet はダウンロードしませんでした。",+ "attachment_too_large": "この添付ファイルは申告したサイズを超えて送信を続けたため、ダウンロードを中止しました。"+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "未確認のデバイス",+ "unverified_hint": "このメッセージは {{name}} が公開していないデバイスで署名されています。本人ではない可能性があります。信用する前にフィンガープリントを確認してください。"+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.tsindex c4f9cae7..8382aee3 100644--- a/src/lib/i18n/keys.ts+++ b/src/lib/i18n/keys.ts@@ -769,6 +769,7 @@ export type TranslationKeys =| 'nav.expand_plugins'| 'nav.home'| 'nav.marketplace'+ | 'nav.omnidisc'| 'nav.section_app'| 'nav.section_plugins'| 'nav.section_primary'@@ -915,6 +916,742 @@ export type TranslationKeys =| 'omnibox.unsupported'| 'omnibox.view_formats'+ | 'omnidisc.attachments.close_image'+ | 'omnidisc.attachments.download'+ | 'omnidisc.attachments.downloading'+ | 'omnidisc.attachments.encrypted_note'+ | 'omnidisc.attachments.failed'+ | 'omnidisc.attachments.open_image'+ | 'omnidisc.attachments.preparing'+ | 'omnidisc.attachments.ready'+ | 'omnidisc.attachments.remove'+ | 'omnidisc.attachments.resuming'+ | 'omnidisc.attachments.retry'+ | 'omnidisc.attachments.saved'+ | 'omnidisc.attachments.title'+ | 'omnidisc.attachments.too_large'+ | 'omnidisc.attachments.too_many'+ | 'omnidisc.attachments.unreadable'+ | 'omnidisc.attachments.uploading'+ | 'omnidisc.audit.channel_create'+ | 'omnidisc.audit.channel_delete'+ | 'omnidisc.audit.channel_overwrite'+ | 'omnidisc.audit.channel_update'+ | 'omnidisc.audit.fallback'+ | 'omnidisc.audit.guild_create'+ | 'omnidisc.audit.guild_delete'+ | 'omnidisc.audit.guild_transfer'+ | 'omnidisc.audit.guild_update'+ | 'omnidisc.audit.instance_update'+ | 'omnidisc.audit.member_ban'+ | 'omnidisc.audit.member_kick'+ | 'omnidisc.audit.member_leave'+ | 'omnidisc.audit.member_unban'+ | 'omnidisc.audit.member_update'+ | 'omnidisc.audit.message_bulk_delete'+ | 'omnidisc.audit.message_delete'+ | 'omnidisc.audit.message_pin'+ | 'omnidisc.audit.message_unpin'+ | 'omnidisc.audit.role_create'+ | 'omnidisc.audit.role_delete'+ | 'omnidisc.audit.role_update'+ | 'omnidisc.audit_action.channel_create'+ | 'omnidisc.audit_action.channel_delete'+ | 'omnidisc.audit_action.channel_overwrite'+ | 'omnidisc.audit_action.channel_update'+ | 'omnidisc.audit_action.guild_transfer'+ | 'omnidisc.audit_action.guild_update'+ | 'omnidisc.audit_action.member_ban'+ | 'omnidisc.audit_action.member_kick'+ | 'omnidisc.audit_action.member_leave'+ | 'omnidisc.audit_action.member_unban'+ | 'omnidisc.audit_action.member_update'+ | 'omnidisc.audit_action.message_bulk_delete'+ | 'omnidisc.audit_action.message_delete'+ | 'omnidisc.audit_action.message_pin'+ | 'omnidisc.audit_action.message_unpin'+ | 'omnidisc.audit_action.role_create'+ | 'omnidisc.audit_action.role_delete'+ | 'omnidisc.audit_action.role_update'+ | 'omnidisc.call.accept'+ | 'omnidisc.call.decline'+ | 'omnidisc.call.expires_in'+ | 'omnidisc.call.in_call'+ | 'omnidisc.call.incoming'+ | 'omnidisc.call.incoming_group'+ | 'omnidisc.call.joining'+ | 'omnidisc.call.leave'+ | 'omnidisc.call.start'+ | 'omnidisc.call.start_hint'+ | 'omnidisc.channel_settings.allow'+ | 'omnidisc.channel_settings.delete'+ | 'omnidisc.channel_settings.delete_body'+ | 'omnidisc.channel_settings.delete_confirm'+ | 'omnidisc.channel_settings.delete_hint'+ | 'omnidisc.channel_settings.delete_title'+ | 'omnidisc.channel_settings.deny'+ | 'omnidisc.channel_settings.inherit'+ | 'omnidisc.channel_settings.name'+ | 'omnidisc.channel_settings.nsfw'+ | 'omnidisc.channel_settings.overwrite_target'+ | 'omnidisc.channel_settings.overwrites'+ | 'omnidisc.channel_settings.overwrites_hint'+ | 'omnidisc.channel_settings.slowmode'+ | 'omnidisc.channel_settings.slowmode_off'+ | 'omnidisc.channel_settings.title'+ | 'omnidisc.channel_settings.topic'+ | 'omnidisc.channel_settings.voice_note'+ | 'omnidisc.channels.dms'+ | 'omnidisc.channels.empty'+ | 'omnidisc.channels.empty_hint'+ | 'omnidisc.channels.no_dms'+ | 'omnidisc.channels.no_guilds'+ | 'omnidisc.channels.no_guilds_hint'+ | 'omnidisc.channels.not_found'+ | 'omnidisc.channels.not_found_hint'+ | 'omnidisc.channels.title'+ | 'omnidisc.channels.voice_soon'+ | 'omnidisc.channels.voice_soon_hint'+ | 'omnidisc.composer.attach'+ | 'omnidisc.composer.cancel_reply'+ | 'omnidisc.composer.drop_here'+ | 'omnidisc.composer.hint'+ | 'omnidisc.composer.placeholder'+ | 'omnidisc.composer.replying_to'+ | 'omnidisc.composer.send'+ | 'omnidisc.composer.uploading_wait'+ | 'omnidisc.connect.add_another'+ | 'omnidisc.connect.auth_body'+ | 'omnidisc.connect.auth_required'+ | 'omnidisc.connect.auth_title'+ | 'omnidisc.connect.change_server'+ | 'omnidisc.connect.demo'+ | 'omnidisc.connect.display_name_label'+ | 'omnidisc.connect.display_name_placeholder'+ | 'omnidisc.connect.error_title'+ | 'omnidisc.connect.insecure'+ | 'omnidisc.connect.insecure_short'+ | 'omnidisc.connect.invite_label'+ | 'omnidisc.connect.invite_noted'+ | 'omnidisc.connect.invite_placeholder'+ | 'omnidisc.connect.login_submit'+ | 'omnidisc.connect.mode_login'+ | 'omnidisc.connect.mode_register'+ | 'omnidisc.connect.open'+ | 'omnidisc.connect.password_hint'+ | 'omnidisc.connect.password_label'+ | 'omnidisc.connect.register_submit'+ | 'omnidisc.connect.registration_closed'+ | 'omnidisc.connect.retry'+ | 'omnidisc.connect.step_auth'+ | 'omnidisc.connect.step_authenticating'+ | 'omnidisc.connect.step_connecting'+ | 'omnidisc.connect.step_syncing'+ | 'omnidisc.connect.submit'+ | 'omnidisc.connect.submitting'+ | 'omnidisc.connect.subtitle'+ | 'omnidisc.connect.success_body'+ | 'omnidisc.connect.success_title'+ | 'omnidisc.connect.title'+ | 'omnidisc.connect.url_label'+ | 'omnidisc.connect.url_placeholder'+ | 'omnidisc.connect.url_required'+ | 'omnidisc.connect.username_hint'+ | 'omnidisc.connect.username_label'+ | 'omnidisc.connect.username_placeholder'+ | 'omnidisc.devices.added'+ | 'omnidisc.devices.copied'+ | 'omnidisc.devices.copy'+ | 'omnidisc.devices.copy_failed'+ | 'omnidisc.devices.empty_body'+ | 'omnidisc.devices.empty_title'+ | 'omnidisc.devices.fingerprint'+ | 'omnidisc.devices.fingerprint_hint'+ | 'omnidisc.devices.hint'+ | 'omnidisc.devices.last_seen'+ | 'omnidisc.devices.no_history_warning'+ | 'omnidisc.devices.revoke'+ | 'omnidisc.devices.revoke_body'+ | 'omnidisc.devices.revoke_confirm'+ | 'omnidisc.devices.revoke_this_body'+ | 'omnidisc.devices.revoke_this_title'+ | 'omnidisc.devices.revoke_title'+ | 'omnidisc.devices.this_device'+ | 'omnidisc.devices.title'+ | 'omnidisc.devices.unnamed'+ | 'omnidisc.disabled_body'+ | 'omnidisc.disabled_title'+ | 'omnidisc.dm.not_found'+ | 'omnidisc.dm.not_found_hint'+ | 'omnidisc.dm.placeholder'+ | 'omnidisc.dm.title'+ | 'omnidisc.e2ee.badge'+ | 'omnidisc.e2ee.devices_note'+ | 'omnidisc.e2ee.dm_locked'+ | 'omnidisc.e2ee.group_locked'+ | 'omnidisc.e2ee.guild_open'+ | 'omnidisc.e2ee.not_ready'+ | 'omnidisc.e2ee.preparing'+ | 'omnidisc.e2ee.unavailable'+ | 'omnidisc.e2ee.unverified'+ | 'omnidisc.e2ee.unverified_hint'+ | 'omnidisc.emoji.group_activity'+ | 'omnidisc.emoji.group_food'+ | 'omnidisc.emoji.group_nature'+ | 'omnidisc.emoji.group_objects'+ | 'omnidisc.emoji.group_people'+ | 'omnidisc.emoji.group_reactions'+ | 'omnidisc.emoji.group_symbols'+ | 'omnidisc.emoji.no_match'+ | 'omnidisc.emoji.recent'+ | 'omnidisc.emoji.search'+ | 'omnidisc.emoji.title'+ | 'omnidisc.error.attachment_corrupt'+ | 'omnidisc.error.attachment_origin'+ | 'omnidisc.error.attachment_too_large'+ | 'omnidisc.error.bad_request'+ | 'omnidisc.error.device_required'+ | 'omnidisc.error.e2ee'+ | 'omnidisc.error.e2ee_not_ready'+ | 'omnidisc.error.e2ee_untrusted'+ | 'omnidisc.error.empty_message'+ | 'omnidisc.error.epoch_conflict'+ | 'omnidisc.error.file_missing'+ | 'omnidisc.error.forbidden'+ | 'omnidisc.error.invalid_credentials'+ | 'omnidisc.error.invalid_invite'+ | 'omnidisc.error.invalid_password'+ | 'omnidisc.error.invalid_url'+ | 'omnidisc.error.invalid_username'+ | 'omnidisc.error.message_too_long'+ | 'omnidisc.error.missing_permissions'+ | 'omnidisc.error.no_session'+ | 'omnidisc.error.not_an_instance'+ | 'omnidisc.error.not_connected'+ | 'omnidisc.error.not_found'+ | 'omnidisc.error.protocol'+ | 'omnidisc.error.rate_limited'+ | 'omnidisc.error.registration_closed'+ | 'omnidisc.error.screen_permission'+ | 'omnidisc.error.server'+ | 'omnidisc.error.stream_capture_failed'+ | 'omnidisc.error.stream_encoder_failed'+ | 'omnidisc.error.stream_not_found'+ | 'omnidisc.error.stream_not_streaming'+ | 'omnidisc.error.stream_source_gone'+ | 'omnidisc.error.stream_unsupported'+ | 'omnidisc.error.stream_viewer_failed'+ | 'omnidisc.error.too_many_attachments'+ | 'omnidisc.error.too_many_guilds'+ | 'omnidisc.error.unauthorized'+ | 'omnidisc.error.unknown_upload'+ | 'omnidisc.error.unreachable'+ | 'omnidisc.error.upload_cancelled'+ | 'omnidisc.error.upload_failed'+ | 'omnidisc.error.upload_too_large'+ | 'omnidisc.error.username_taken'+ | 'omnidisc.error.voice_denied'+ | 'omnidisc.error.voice_device_busy'+ | 'omnidisc.error.voice_disconnected'+ | 'omnidisc.error.voice_dm_unsupported'+ | 'omnidisc.error.voice_engine_crashed'+ | 'omnidisc.error.voice_mic_failed'+ | 'omnidisc.error.voice_mic_lost'+ | 'omnidisc.error.voice_mic_permission'+ | 'omnidisc.error.voice_no_input_device'+ | 'omnidisc.error.voice_no_output_device'+ | 'omnidisc.error.voice_not_connected'+ | 'omnidisc.error.voice_output_failed'+ | 'omnidisc.error.voice_output_lost'+ | 'omnidisc.error.voice_output_permission'+ | 'omnidisc.error.voice_timeout'+ | 'omnidisc.error.voice_unavailable'+ | 'omnidisc.error.voice_unreachable'+ | 'omnidisc.friends.accept'+ | 'omnidisc.friends.add'+ | 'omnidisc.friends.add_hint'+ | 'omnidisc.friends.add_label'+ | 'omnidisc.friends.add_placeholder'+ | 'omnidisc.friends.block'+ | 'omnidisc.friends.cancel_request'+ | 'omnidisc.friends.decline'+ | 'omnidisc.friends.empty_all_body'+ | 'omnidisc.friends.empty_all_title'+ | 'omnidisc.friends.empty_blocked_body'+ | 'omnidisc.friends.empty_blocked_title'+ | 'omnidisc.friends.empty_online_body'+ | 'omnidisc.friends.empty_online_title'+ | 'omnidisc.friends.empty_pending_body'+ | 'omnidisc.friends.empty_pending_title'+ | 'omnidisc.friends.pending_out'+ | 'omnidisc.friends.remove'+ | 'omnidisc.friends.request_sent'+ | 'omnidisc.friends.send_request'+ | 'omnidisc.friends.sending'+ | 'omnidisc.friends.tab_all'+ | 'omnidisc.friends.tab_blocked'+ | 'omnidisc.friends.tab_online'+ | 'omnidisc.friends.tab_pending'+ | 'omnidisc.friends.title'+ | 'omnidisc.friends.unblock'+ | 'omnidisc.guild.channel_kind_label'+ | 'omnidisc.guild.channel_kind_text'+ | 'omnidisc.guild.channel_kind_voice'+ | 'omnidisc.guild.channel_name_label'+ | 'omnidisc.guild.channel_name_placeholder'+ | 'omnidisc.guild.create_body'+ | 'omnidisc.guild.create_channel'+ | 'omnidisc.guild.create_channel_submit'+ | 'omnidisc.guild.create_channel_title'+ | 'omnidisc.guild.create_submit'+ | 'omnidisc.guild.create_title'+ | 'omnidisc.guild.invite'+ | 'omnidisc.guild.invite_copied'+ | 'omnidisc.guild.invite_failed'+ | 'omnidisc.guild.join_body'+ | 'omnidisc.guild.join_label'+ | 'omnidisc.guild.join_placeholder'+ | 'omnidisc.guild.join_submit'+ | 'omnidisc.guild.join_title'+ | 'omnidisc.guild.name_label'+ | 'omnidisc.guild.name_placeholder'+ | 'omnidisc.guild.working'+ | 'omnidisc.guild_settings.audit_all'+ | 'omnidisc.guild_settings.audit_empty_body'+ | 'omnidisc.guild_settings.audit_empty_title'+ | 'omnidisc.guild_settings.audit_filter'+ | 'omnidisc.guild_settings.back'+ | 'omnidisc.guild_settings.ban_by'+ | 'omnidisc.guild_settings.bans_empty_body'+ | 'omnidisc.guild_settings.bans_empty_title'+ | 'omnidisc.guild_settings.danger'+ | 'omnidisc.guild_settings.delete'+ | 'omnidisc.guild_settings.delete_body'+ | 'omnidisc.guild_settings.delete_confirm'+ | 'omnidisc.guild_settings.delete_hint'+ | 'omnidisc.guild_settings.delete_title'+ | 'omnidisc.guild_settings.delete_type'+ | 'omnidisc.guild_settings.description'+ | 'omnidisc.guild_settings.everyone_role'+ | 'omnidisc.guild_settings.expiry_1d'+ | 'omnidisc.guild_settings.expiry_30m'+ | 'omnidisc.guild_settings.expiry_7d'+ | 'omnidisc.guild_settings.expiry_never'+ | 'omnidisc.guild_settings.invite_channel'+ | 'omnidisc.guild_settings.invite_channel_any'+ | 'omnidisc.guild_settings.invite_copy'+ | 'omnidisc.guild_settings.invite_create'+ | 'omnidisc.guild_settings.invite_expiry'+ | 'omnidisc.guild_settings.invite_uses'+ | 'omnidisc.guild_settings.invites_empty'+ | 'omnidisc.guild_settings.invites_hint'+ | 'omnidisc.guild_settings.invites_no_list'+ | 'omnidisc.guild_settings.leave'+ | 'omnidisc.guild_settings.leave_body'+ | 'omnidisc.guild_settings.leave_confirm'+ | 'omnidisc.guild_settings.leave_hint'+ | 'omnidisc.guild_settings.leave_owner_hint'+ | 'omnidisc.guild_settings.leave_title'+ | 'omnidisc.guild_settings.not_found_body'+ | 'omnidisc.guild_settings.not_found_title'+ | 'omnidisc.guild_settings.overview'+ | 'omnidisc.guild_settings.perm_group_general'+ | 'omnidisc.guild_settings.perm_group_moderation'+ | 'omnidisc.guild_settings.perm_group_text'+ | 'omnidisc.guild_settings.perm_group_voice'+ | 'omnidisc.guild_settings.read_only'+ | 'omnidisc.guild_settings.role_color'+ | 'omnidisc.guild_settings.role_create'+ | 'omnidisc.guild_settings.role_create_submit'+ | 'omnidisc.guild_settings.role_create_title'+ | 'omnidisc.guild_settings.role_delete'+ | 'omnidisc.guild_settings.role_delete_body'+ | 'omnidisc.guild_settings.role_delete_confirm'+ | 'omnidisc.guild_settings.role_delete_hint'+ | 'omnidisc.guild_settings.role_delete_title'+ | 'omnidisc.guild_settings.role_hoist'+ | 'omnidisc.guild_settings.role_mentionable'+ | 'omnidisc.guild_settings.role_name'+ | 'omnidisc.guild_settings.role_name_placeholder'+ | 'omnidisc.guild_settings.roles_empty_body'+ | 'omnidisc.guild_settings.roles_empty_title'+ | 'omnidisc.guild_settings.save'+ | 'omnidisc.guild_settings.saved'+ | 'omnidisc.guild_settings.tab_audit'+ | 'omnidisc.guild_settings.tab_bans'+ | 'omnidisc.guild_settings.tab_channels'+ | 'omnidisc.guild_settings.tab_invites'+ | 'omnidisc.guild_settings.tab_overview'+ | 'omnidisc.guild_settings.tab_roles'+ | 'omnidisc.guild_settings.title'+ | 'omnidisc.guild_settings.transfer'+ | 'omnidisc.guild_settings.transfer_body'+ | 'omnidisc.guild_settings.transfer_confirm'+ | 'omnidisc.guild_settings.transfer_hint'+ | 'omnidisc.guild_settings.transfer_pick'+ | 'omnidisc.guild_settings.transfer_title'+ | 'omnidisc.guild_settings.transfer_to'+ | 'omnidisc.guild_settings.unban'+ | 'omnidisc.guild_settings.unban_body'+ | 'omnidisc.guild_settings.unban_confirm'+ | 'omnidisc.guild_settings.unban_hint'+ | 'omnidisc.guild_settings.unban_title'+ | 'omnidisc.guild_settings.uses_unlimited'+ | 'omnidisc.home.pick_channel_body'+ | 'omnidisc.home.pick_channel_title'+ | 'omnidisc.members.empty'+ | 'omnidisc.members.hide'+ | 'omnidisc.members.message'+ | 'omnidisc.members.offline'+ | 'omnidisc.members.online'+ | 'omnidisc.members.owner'+ | 'omnidisc.members.show'+ | 'omnidisc.members.title'+ | 'omnidisc.messages.copy_failed'+ | 'omnidisc.messages.copy_id'+ | 'omnidisc.messages.copy_link'+ | 'omnidisc.messages.delete'+ | 'omnidisc.messages.delete_body'+ | 'omnidisc.messages.delete_confirm'+ | 'omnidisc.messages.delete_no_text'+ | 'omnidisc.messages.delete_title'+ | 'omnidisc.messages.discard'+ | 'omnidisc.messages.edit'+ | 'omnidisc.messages.edit_label'+ | 'omnidisc.messages.edit_save'+ | 'omnidisc.messages.edited'+ | 'omnidisc.messages.empty_body'+ | 'omnidisc.messages.empty_title'+ | 'omnidisc.messages.failed'+ | 'omnidisc.messages.jump_present'+ | 'omnidisc.messages.loading'+ | 'omnidisc.messages.mark_unread'+ | 'omnidisc.messages.more'+ | 'omnidisc.messages.new_messages'+ | 'omnidisc.messages.pending'+ | 'omnidisc.messages.pin'+ | 'omnidisc.messages.pinned'+ | 'omnidisc.messages.react'+ | 'omnidisc.messages.reaction_add'+ | 'omnidisc.messages.reaction_remove'+ | 'omnidisc.messages.reply'+ | 'omnidisc.messages.reply_unavailable'+ | 'omnidisc.messages.retry'+ | 'omnidisc.messages.today'+ | 'omnidisc.messages.typing_many'+ | 'omnidisc.messages.typing_one'+ | 'omnidisc.messages.typing_two'+ | 'omnidisc.messages.unknown_user'+ | 'omnidisc.messages.unpin'+ | 'omnidisc.messages.yesterday'+ | 'omnidisc.messages.you'+ | 'omnidisc.notify.channel_hint'+ | 'omnidisc.notify.guild_hint'+ | 'omnidisc.notify.guild_title'+ | 'omnidisc.notify.inherit'+ | 'omnidisc.notify.level_all'+ | 'omnidisc.notify.level_mentions'+ | 'omnidisc.notify.level_nothing'+ | 'omnidisc.notify.title'+ | 'omnidisc.open_settings'+ | 'omnidisc.perm.ADD_REACTIONS'+ | 'omnidisc.perm.ADMINISTRATOR'+ | 'omnidisc.perm.ATTACH_FILES'+ | 'omnidisc.perm.BAN_MEMBERS'+ | 'omnidisc.perm.BYPASS_SLOWMODE'+ | 'omnidisc.perm.CHANGE_NICKNAME'+ | 'omnidisc.perm.CONNECT'+ | 'omnidisc.perm.CREATE_INVITES'+ | 'omnidisc.perm.DEAFEN_MEMBERS'+ | 'omnidisc.perm.EMBED_LINKS'+ | 'omnidisc.perm.KICK_MEMBERS'+ | 'omnidisc.perm.MANAGE_CHANNELS'+ | 'omnidisc.perm.MANAGE_EMOJI'+ | 'omnidisc.perm.MANAGE_GUILD'+ | 'omnidisc.perm.MANAGE_MESSAGES'+ | 'omnidisc.perm.MANAGE_NICKNAMES'+ | 'omnidisc.perm.MANAGE_ROLES'+ | 'omnidisc.perm.MANAGE_WEBHOOKS'+ | 'omnidisc.perm.MENTION_EVERYONE'+ | 'omnidisc.perm.MODERATE_MEMBERS'+ | 'omnidisc.perm.MOVE_MEMBERS'+ | 'omnidisc.perm.MUTE_MEMBERS'+ | 'omnidisc.perm.PIN_MESSAGES'+ | 'omnidisc.perm.PRIORITY_SPEAKER'+ | 'omnidisc.perm.READ_HISTORY'+ | 'omnidisc.perm.SEND_MESSAGES'+ | 'omnidisc.perm.SEND_TTS'+ | 'omnidisc.perm.SPEAK'+ | 'omnidisc.perm.STREAM'+ | 'omnidisc.perm.USE_EXTERNAL_EMOJI'+ | 'omnidisc.perm.USE_SOUNDBOARD'+ | 'omnidisc.perm.USE_VAD'+ | 'omnidisc.perm.VIDEO'+ | 'omnidisc.perm.VIEW_AUDIT_LOG'+ | 'omnidisc.perm.VIEW_CHANNEL'+ | 'omnidisc.perm.VIEW_CHANNEL_MEMBERS'+ | 'omnidisc.perm_desc.ADD_REACTIONS'+ | 'omnidisc.perm_desc.ADMINISTRATOR'+ | 'omnidisc.perm_desc.ATTACH_FILES'+ | 'omnidisc.perm_desc.BAN_MEMBERS'+ | 'omnidisc.perm_desc.BYPASS_SLOWMODE'+ | 'omnidisc.perm_desc.CHANGE_NICKNAME'+ | 'omnidisc.perm_desc.CONNECT'+ | 'omnidisc.perm_desc.CREATE_INVITES'+ | 'omnidisc.perm_desc.DEAFEN_MEMBERS'+ | 'omnidisc.perm_desc.EMBED_LINKS'+ | 'omnidisc.perm_desc.KICK_MEMBERS'+ | 'omnidisc.perm_desc.MANAGE_CHANNELS'+ | 'omnidisc.perm_desc.MANAGE_EMOJI'+ | 'omnidisc.perm_desc.MANAGE_GUILD'+ | 'omnidisc.perm_desc.MANAGE_MESSAGES'+ | 'omnidisc.perm_desc.MANAGE_NICKNAMES'+ | 'omnidisc.perm_desc.MANAGE_ROLES'+ | 'omnidisc.perm_desc.MANAGE_WEBHOOKS'+ | 'omnidisc.perm_desc.MENTION_EVERYONE'+ | 'omnidisc.perm_desc.MODERATE_MEMBERS'+ | 'omnidisc.perm_desc.MOVE_MEMBERS'+ | 'omnidisc.perm_desc.MUTE_MEMBERS'+ | 'omnidisc.perm_desc.PIN_MESSAGES'+ | 'omnidisc.perm_desc.PRIORITY_SPEAKER'+ | 'omnidisc.perm_desc.READ_HISTORY'+ | 'omnidisc.perm_desc.SEND_MESSAGES'+ | 'omnidisc.perm_desc.SEND_TTS'+ | 'omnidisc.perm_desc.SPEAK'+ | 'omnidisc.perm_desc.STREAM'+ | 'omnidisc.perm_desc.USE_EXTERNAL_EMOJI'+ | 'omnidisc.perm_desc.USE_SOUNDBOARD'+ | 'omnidisc.perm_desc.USE_VAD'+ | 'omnidisc.perm_desc.VIDEO'+ | 'omnidisc.perm_desc.VIEW_AUDIT_LOG'+ | 'omnidisc.perm_desc.VIEW_CHANNEL'+ | 'omnidisc.perm_desc.VIEW_CHANNEL_MEMBERS'+ | 'omnidisc.pins.empty_body'+ | 'omnidisc.pins.empty_title'+ | 'omnidisc.pins.title'+ | 'omnidisc.pins.unpin'+ | 'omnidisc.profile.ban'+ | 'omnidisc.profile.ban_body'+ | 'omnidisc.profile.ban_confirm'+ | 'omnidisc.profile.ban_title'+ | 'omnidisc.profile.copy_failed'+ | 'omnidisc.profile.copy_id'+ | 'omnidisc.profile.kick'+ | 'omnidisc.profile.kick_body'+ | 'omnidisc.profile.kick_confirm'+ | 'omnidisc.profile.kick_title'+ | 'omnidisc.profile.message'+ | 'omnidisc.profile.moderation'+ | 'omnidisc.profile.mutual_servers'+ | 'omnidisc.profile.nickname'+ | 'omnidisc.profile.nickname_confirm'+ | 'omnidisc.profile.nickname_label'+ | 'omnidisc.profile.nickname_title'+ | 'omnidisc.profile.note'+ | 'omnidisc.profile.note_placeholder'+ | 'omnidisc.profile.open'+ | 'omnidisc.profile.reason_label'+ | 'omnidisc.profile.reason_placeholder'+ | 'omnidisc.profile.roles'+ | 'omnidisc.profile.timeout'+ | 'omnidisc.profile.timeout_1d'+ | 'omnidisc.profile.timeout_1h'+ | 'omnidisc.profile.timeout_1w'+ | 'omnidisc.profile.timeout_5m'+ | 'omnidisc.profile.timeout_confirm'+ | 'omnidisc.profile.timeout_label'+ | 'omnidisc.profile.timeout_title'+ | 'omnidisc.profile.title'+ | 'omnidisc.profile_settings.accent'+ | 'omnidisc.profile_settings.apply_status'+ | 'omnidisc.profile_settings.avatar_note'+ | 'omnidisc.profile_settings.bio'+ | 'omnidisc.profile_settings.custom_status'+ | 'omnidisc.profile_settings.custom_status_expiry'+ | 'omnidisc.profile_settings.custom_status_placeholder'+ | 'omnidisc.profile_settings.display_name'+ | 'omnidisc.profile_settings.expiry_30m'+ | 'omnidisc.profile_settings.expiry_4h'+ | 'omnidisc.profile_settings.expiry_never'+ | 'omnidisc.profile_settings.expiry_today'+ | 'omnidisc.profile_settings.hint'+ | 'omnidisc.profile_settings.no_instance_body'+ | 'omnidisc.profile_settings.no_instance_title'+ | 'omnidisc.profile_settings.presence'+ | 'omnidisc.profile_settings.presence_dnd'+ | 'omnidisc.profile_settings.presence_idle'+ | 'omnidisc.profile_settings.presence_invisible'+ | 'omnidisc.profile_settings.presence_online'+ | 'omnidisc.profile_settings.preview'+ | 'omnidisc.profile_settings.pronouns'+ | 'omnidisc.profile_settings.pronouns_placeholder'+ | 'omnidisc.profile_settings.save'+ | 'omnidisc.profile_settings.saved'+ | 'omnidisc.profile_settings.title'+ | 'omnidisc.rail.add_instance'+ | 'omnidisc.rail.add_server'+ | 'omnidisc.rail.create_server'+ | 'omnidisc.rail.home'+ | 'omnidisc.rail.insecure'+ | 'omnidisc.rail.join_invite'+ | 'omnidisc.rail.menu'+ | 'omnidisc.rail.reconnect'+ | 'omnidisc.rail.remove'+ | 'omnidisc.rail.sign_in'+ | 'omnidisc.rail.status_connected'+ | 'omnidisc.rail.status_connecting'+ | 'omnidisc.rail.status_disconnected'+ | 'omnidisc.rail.status_error'+ | 'omnidisc.rail.status_reconnecting'+ | 'omnidisc.rail.status_signed_out'+ | 'omnidisc.search.empty_body'+ | 'omnidisc.search.empty_title'+ | 'omnidisc.search.filters_hint'+ | 'omnidisc.search.idle_body'+ | 'omnidisc.search.idle_title'+ | 'omnidisc.search.placeholder'+ | 'omnidisc.search.results'+ | 'omnidisc.search.run'+ | 'omnidisc.search.scope'+ | 'omnidisc.search.scope_channel'+ | 'omnidisc.search.scope_guild'+ | 'omnidisc.search.title'+ | 'omnidisc.search.unknown_from'+ | 'omnidisc.sessions.current'+ | 'omnidisc.sessions.empty_body'+ | 'omnidisc.sessions.empty_title'+ | 'omnidisc.sessions.hint'+ | 'omnidisc.sessions.last_seen'+ | 'omnidisc.sessions.revoke'+ | 'omnidisc.sessions.revoke_body'+ | 'omnidisc.sessions.revoke_confirm'+ | 'omnidisc.sessions.revoke_hint'+ | 'omnidisc.sessions.revoke_others'+ | 'omnidisc.sessions.revoke_others_body'+ | 'omnidisc.sessions.revoke_others_confirm'+ | 'omnidisc.sessions.revoke_others_title'+ | 'omnidisc.sessions.revoke_title'+ | 'omnidisc.sessions.sign_out_here'+ | 'omnidisc.sessions.title'+ | 'omnidisc.sessions.unknown_device'+ | 'omnidisc.settings_desc'+ | 'omnidisc.settings_enable'+ | 'omnidisc.settings_enable_desc'+ | 'omnidisc.settings_title'+ | 'omnidisc.stream.audio'+ | 'omnidisc.stream.audio_none'+ | 'omnidisc.stream.audio_system'+ | 'omnidisc.stream.connecting'+ | 'omnidisc.stream.cursor'+ | 'omnidisc.stream.custom_bitrate'+ | 'omnidisc.stream.encode'+ | 'omnidisc.stream.framerate'+ | 'omnidisc.stream.fullscreen'+ | 'omnidisc.stream.hevc_note'+ | 'omnidisc.stream.implied_bitrate'+ | 'omnidisc.stream.inspector'+ | 'omnidisc.stream.live'+ | 'omnidisc.stream.loading_sources'+ | 'omnidisc.stream.loss'+ | 'omnidisc.stream.mode'+ | 'omnidisc.stream.mode_game'+ | 'omnidisc.stream.mode_text'+ | 'omnidisc.stream.no_active'+ | 'omnidisc.stream.pick_source'+ | 'omnidisc.stream.quality'+ | 'omnidisc.stream.receiving'+ | 'omnidisc.stream.recheck'+ | 'omnidisc.stream.resolution'+ | 'omnidisc.stream.rtt'+ | 'omnidisc.stream.sending'+ | 'omnidisc.stream.share_cta'+ | 'omnidisc.stream.share_screen'+ | 'omnidisc.stream.share_title'+ | 'omnidisc.stream.software'+ | 'omnidisc.stream.software_warn'+ | 'omnidisc.stream.starting'+ | 'omnidisc.stream.stop_sharing'+ | 'omnidisc.stream.stop_watching'+ | 'omnidisc.stream.volume'+ | 'omnidisc.stream.watch'+ | 'omnidisc.stream.you_live'+ | 'omnidisc.title'+ | 'omnidisc.voice.connected_to'+ | 'omnidisc.voice.connecting'+ | 'omnidisc.voice.deafen'+ | 'omnidisc.voice.deafened'+ | 'omnidisc.voice.device_default'+ | 'omnidisc.voice.device_refresh'+ | 'omnidisc.voice.ducking'+ | 'omnidisc.voice.ducking_desc'+ | 'omnidisc.voice.ducking_off'+ | 'omnidisc.voice.ducking_value'+ | 'omnidisc.voice.e2ee_off'+ | 'omnidisc.voice.e2ee_off_desc'+ | 'omnidisc.voice.e2ee_on'+ | 'omnidisc.voice.e2ee_on_desc'+ | 'omnidisc.voice.failed'+ | 'omnidisc.voice.input_device'+ | 'omnidisc.voice.join'+ | 'omnidisc.voice.join_channel'+ | 'omnidisc.voice.leave'+ | 'omnidisc.voice.leave_short'+ | 'omnidisc.voice.listen_only'+ | 'omnidisc.voice.mic_back'+ | 'omnidisc.voice.mic_level'+ | 'omnidisc.voice.mic_silent'+ | 'omnidisc.voice.mic_switched'+ | 'omnidisc.voice.mic_test'+ | 'omnidisc.voice.mic_test_hint'+ | 'omnidisc.voice.mic_test_stop'+ | 'omnidisc.voice.mute'+ | 'omnidisc.voice.muted'+ | 'omnidisc.voice.no_input_devices'+ | 'omnidisc.voice.no_output'+ | 'omnidisc.voice.no_output_devices'+ | 'omnidisc.voice.nobody'+ | 'omnidisc.voice.nobody_hint'+ | 'omnidisc.voice.noise_suppression'+ | 'omnidisc.voice.noise_suppression_desc'+ | 'omnidisc.voice.open_settings'+ | 'omnidisc.voice.output_back'+ | 'omnidisc.voice.output_device'+ | 'omnidisc.voice.output_switched'+ | 'omnidisc.voice.participants'+ | 'omnidisc.voice.ping'+ | 'omnidisc.voice.ptt_clear'+ | 'omnidisc.voice.ptt_hold'+ | 'omnidisc.voice.ptt_key'+ | 'omnidisc.voice.ptt_key_desc'+ | 'omnidisc.voice.ptt_permission_hint'+ | 'omnidisc.voice.ptt_record'+ | 'omnidisc.voice.ptt_recording'+ | 'omnidisc.voice.quality_excellent'+ | 'omnidisc.voice.quality_good'+ | 'omnidisc.voice.quality_lost'+ | 'omnidisc.voice.quality_poor'+ | 'omnidisc.voice.quality_unknown'+ | 'omnidisc.voice.reconnecting'+ | 'omnidisc.voice.relay_only'+ | 'omnidisc.voice.relay_only_desc'+ | 'omnidisc.voice.retry'+ | 'omnidisc.voice.settings'+ | 'omnidisc.voice.settings_hint'+ | 'omnidisc.voice.speaking'+ | 'omnidisc.voice.switch_body'+ | 'omnidisc.voice.switch_confirm'+ | 'omnidisc.voice.switch_title'+ | 'omnidisc.voice.title'+ | 'omnidisc.voice.undeafen'+ | 'omnidisc.voice.unmute'+ | 'omnidisc.voice.user_deafened'+ | 'omnidisc.voice.user_muted'+ | 'omnidisc.voice.vad_threshold'+ | 'omnidisc.voice.vad_threshold_desc'+ | 'omnidisc.voice.volume_for'+ | 'omnidisc.voice.volume_reset'+ | 'omnidisc.voice.you'+| 'onboarding.back'| 'onboarding.deps_desc'| 'onboarding.deps_install_all'diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.jsonindex 39d34fd0..3740c3e6 100644--- a/src/lib/i18n/pt.json+++ b/src/lib/i18n/pt.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "Downloads em andamento","message": "Você tem {{count}} download(s) ativo(s). Fechar agora vai cancelá-los.",@@ -348,6 +366,7 @@"marketplace": "Marketplace","settings": "Configurações","about": "Sobre",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "Aparência",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "Tema","theme_system": "Sistema","more_themes": "Mais temas",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "Pasta padrão",@@ -4134,22 +4153,801 @@"test_body": "Você verá notificações assim quando os pacotes mudarem de status."}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "Este servidor é acessado por http simples. Sua senha e tudo o que você enviar aqui trafegam sem criptografia — qualquer pessoa na rede entre você e ele pode ler.",+ "insecure_short": "Conexão sem criptografia"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — conexão sem criptografia (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "O servidor respondeu com um dispositivo que essa pessoa nunca publicou. O OmniGet parou em vez de criptografar para ele — nada foi enviado. Avise quem administra este servidor.",+ "attachment_origin": "Este anexo aponta para fora deste servidor. O OmniGet não baixou.",+ "attachment_too_large": "Este anexo continuou enviando além do tamanho declarado, então o download foi interrompido."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Dispositivo não verificado",+ "unverified_hint": "Esta mensagem foi assinada por um dispositivo que {{name}} não publicou. Pode não ser essa pessoa — confira as impressões digitais antes de confiar."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.jsonindex 53e6047f..8d3e1e07 100644--- a/src/lib/i18n/ru.json+++ b/src/lib/i18n/ru.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "Загрузки в процессе","message": "Активных загрузок: {{count}}. Если закрыть сейчас, они будут отменены.",@@ -348,6 +366,7 @@"marketplace": "Маркетплейс","settings": "Настройки","about": "О программе",+ "omnidisc": "Chat","section_primary": "Основное","section_app": "Приложение","section_plugins": "Плагины",@@ -706,6 +725,11 @@},"appearance": {"title": "Внешний вид",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "Тема","theme_system": "Системная","more_themes": "Больше тем",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "Папка по умолчанию",@@ -1403,12 +1422,12 @@},"about": {"tab": {+ "overview": "Overview","terms": "условия","project": "проект","roadmap": "план","changelog": "история изменений",- "debug": "отладочная информация",- "overview": "Overview"+ "debug": "отладочная информация"},"debug": {"title": "Отладочная информация",@@ -1419,6 +1438,12 @@"copy_failed": "Не удалось скопировать в буфер обмена"},"debug_disabled_redirect": "Страница отладки скрыта. Включите её в Настройках → Дополнительно → Диагностика.",+ "card_changelog_title": "What's new",+ "card_changelog_desc": "Release notes for every version.",+ "card_project_title": "The project",+ "card_project_desc": "Roadmap, philosophy and how to contribute.",+ "card_terms_title": "Terms & ethics",+ "card_terms_desc": "What OmniGet expects from you, and what you can expect back.","description": "ваш загрузчик медиа. с открытым исходным кодом и бесплатный.","terms_title": "условия использования","terms_text": "OmniGet предоставляется «как есть», и мы не даём никаких гарантий. Приложение упрощает скачивание контента, который общедоступен в интернете, но мы не несём никакой ответственности за то, что вы скачиваете или что с этим делаете. Используя OmniGet, вы соглашаетесь с этим.",@@ -1450,13 +1475,7 @@"roadmap_community_discord": "свяжитесь с нами в Discord:","roadmap_community_issue": "или откройте задачу в репозитории:","tagline": "Скачивайте что угодно, откуда угодно.",- "credit": "Сделано с любовью tonho.wtf",- "card_changelog_title": "What's new",- "card_changelog_desc": "Release notes for every version.",- "card_project_title": "The project",- "card_project_desc": "Roadmap, philosophy and how to contribute.",- "card_terms_title": "Terms & ethics",- "card_terms_desc": "What OmniGet expects from you, and what you can expect back."+ "credit": "Сделано с любовью tonho.wtf"},"marketplace": {"title": "Маркетплейс",@@ -4134,22 +4153,801 @@"test_body": "Вы будете видеть такие уведомления, когда ваши посылки перемещаются."}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "Этот сервер открыт по обычному http. Ваш пароль и всё, что вы здесь отправляете, идут без шифрования — их может прочитать любой в сети между вами и сервером.",+ "insecure_short": "Соединение без шифрования"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — соединение без шифрования (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "Сервер ответил устройством, которое этот человек никогда не публиковал. OmniGet остановился, вместо того чтобы шифровать для него — ничего не отправлено. Сообщите администратору сервера.",+ "attachment_origin": "Это вложение указывает за пределы этого сервера. OmniGet не стал его скачивать.",+ "attachment_too_large": "Это вложение продолжало передавать данные сверх заявленного размера, поэтому загрузка была остановлена."+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "Непроверенное устройство",+ "unverified_hint": "Это сообщение подписано устройством, которое {{name}} не публиковал. Возможно, это не он — сверьте отпечатки, прежде чем доверять."+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.jsonindex 04033568..d6e5afb0 100644--- a/src/lib/i18n/zh-TW.json+++ b/src/lib/i18n/zh-TW.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "下載進行中","message": "您有 {{count}} 個進行中的下載。立即關閉將會取消它們。",@@ -348,6 +366,7 @@"marketplace": "插件市场","settings": "設定","about": "關於",+ "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -706,6 +725,11 @@},"appearance": {"title": "外觀",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "主題","theme_system": "系統預設","more_themes": "More themes",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "預設資料夾",@@ -4134,22 +4153,801 @@"test_body": "包裹狀態變化時,您將看到此類通知。"}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "這個伺服器是以明文 http 連線的。你的密碼和在這裡送出的一切都不加密傳輸,路徑上的任何人都讀得到。",+ "insecure_short": "未加密的連線"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — 未加密的連線 (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "伺服器回傳了一台此人從未公布過的裝置。OmniGet 選擇中止而不是向它加密,什麼都沒有送出。請告知該伺服器的管理員。",+ "attachment_origin": "這個附件指向這個伺服器之外的位置,OmniGet 沒有下載。",+ "attachment_too_large": "這個附件持續傳送超過它宣稱的大小,下載已中止。"+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "未驗證的裝置",+ "unverified_hint": "這則訊息由 {{name}} 未公布過的裝置簽署,可能不是本人。信任之前請先核對指紋。"+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.jsonindex a3710105..5d8627c8 100644--- a/src/lib/i18n/zh.json+++ b/src/lib/i18n/zh.json@@ -1,4 +1,22 @@{+ "error": {+ "cause": {+ "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",+ "sabr_only": "YouTube only offered streams this player cannot save yet.",+ "rate_limited": "The site is rate-limiting downloads from your connection.",+ "disk_full": "There is no space left on the download disk.",+ "needs_login": "The site asked for a login to reach this content.",+ "tls_fingerprint": "The site blocked the connection before sending any content.",+ "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ },+ "remedy": {+ "import_cookies": "Import cookies",+ "retry": "Try again",+ "update_ytdlp": "Update yt-dlp",+ "updated": "yt-dlp updated",+ "pot_guide": "Open the PO token guide"+ }+ },"confirm_close": {"title": "下载进行中","message": "您有 {{count}} 个活动下载。立即关闭将会取消它们。",@@ -348,6 +366,7 @@"marketplace": "插件市场","settings": "设置","about": "关于",+ "omnidisc": "Chat","section_primary": "主菜单","section_app": "应用","section_plugins": "插件",@@ -706,6 +725,11 @@},"appearance": {"title": "外观",+ "accessibility_title": "Accessibility",+ "reduce_motion": "Reduce motion",+ "reduce_motion_desc": "Turns position and scale animations into simple fades.",+ "reduce_transparency": "Reduce transparency",+ "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds.","theme": "主题","theme_system": "跟随系统","more_themes": "更多主题",@@ -718,12 +742,7 @@"lang_it": "Italiano","lang_fr": "Français","lang_es": "Español",- "lang_el": "Ελληνικά",- "accessibility_title": "Accessibility",- "reduce_motion": "Reduce motion",- "reduce_motion_desc": "Turns position and scale animations into simple fades.",- "reduce_transparency": "Reduce transparency",- "reduce_transparency_desc": "Replaces translucent panels with solid backgrounds."+ "lang_el": "Ελληνικά"},"download": {"default_output_dir": "默认文件夹",@@ -4134,22 +4153,801 @@"test_body": "包裹状态变化时,您将看到此类通知。"}},- "error": {- "cause": {- "po_token_required": "YouTube asked for a proof-of-origin token before serving this video.",- "sabr_only": "YouTube only offered streams this player cannot save yet.",- "rate_limited": "The site is rate-limiting downloads from your connection.",- "disk_full": "There is no space left on the download disk.",- "needs_login": "The site asked for a login to reach this content.",- "tls_fingerprint": "The site blocked the connection before sending any content.",- "extractor_outdated": "yt-dlp needs an update to keep up with this site."+ "omnidisc": {+ "title": "Chat",+ "settings_title": "Chat (OmniDisc) — experimental",+ "settings_desc": "Built-in chat for self-hosted OmniDisc servers. Off by default.",+ "settings_enable": "Show the Chat menu",+ "settings_enable_desc": "Adds a Chat entry to the sidebar. Nothing connects until you add a server.",+ "disabled_title": "Chat is off",+ "disabled_body": "Turn it on in Settings → Advanced → Chat (OmniDisc). Nothing runs until you do.",+ "open_settings": "Open Settings",+ "connect": {+ "title": "Connect to a server",+ "subtitle": "Paste the invite link your friend sent you, or the server address.",+ "url_label": "Server address",+ "url_placeholder": "https://chat.example.org",+ "url_required": "Enter the server address to continue.",+ "invite_label": "Invite code (optional)",+ "invite_placeholder": "Paste the code from the link",+ "submit": "Connect",+ "submitting": "Connecting…",+ "step_connecting": "Connecting to the server",+ "step_authenticating": "Signing in",+ "step_syncing": "Syncing channels",+ "error_title": "Could not connect",+ "retry": "Try again",+ "success_title": "Connected to {{name}}",+ "success_body": "Pick a channel on the left to start chatting.",+ "open": "Open chat",+ "add_another": "Add another server",+ "demo": "Use demo data",+ "step_auth": "Signing in",+ "auth_title": "Sign in to {{name}}",+ "auth_body": "Your account lives on this server only. Create one here, or use one you already have.",+ "mode_register": "Create account",+ "mode_login": "I already have one",+ "username_label": "Username",+ "username_placeholder": "e.g. ana",+ "username_hint": "2–32 characters: letters, numbers, _ . -",+ "password_label": "Password",+ "password_hint": "At least 8 characters.",+ "display_name_label": "Display name (optional)",+ "display_name_placeholder": "How others will see you",+ "register_submit": "Create account and join",+ "login_submit": "Sign in",+ "auth_required": "Enter a username and a password to continue.",+ "registration_closed": "This server only accepts new accounts through an invite link. Sign in, or go back and add the invite code.",+ "change_server": "Use another server",+ "invite_noted": "Invite code noted — you will join that server after signing in.",+ "insecure": "该服务器通过明文 http 访问。你的密码和在这里发送的一切都不加密传输,链路上的任何人都能读取。",+ "insecure_short": "未加密的连接"},- "remedy": {- "import_cookies": "Import cookies",+ "home": {+ "pick_channel_title": "Pick a channel",+ "pick_channel_body": "Choose a server on the left, then a channel, to start chatting."+ },+ "rail": {+ "home": "Chat home",+ "add_server": "Add a server",+ "status_connected": "connected",+ "status_connecting": "connecting",+ "status_disconnected": "disconnected",+ "status_error": "connection failed",+ "status_reconnecting": "reconnecting",+ "status_signed_out": "signed out",+ "menu": "Add or create",+ "create_server": "Create a server",+ "join_invite": "Join with invite",+ "add_instance": "Connect another server",+ "sign_in": "Sign in again",+ "reconnect": "Reconnect",+ "remove": "Forget this server",+ "insecure": "{{name}} — 未加密的连接 (http)"+ },+ "channels": {+ "title": "Channels",+ "empty": "No channels yet",+ "empty_hint": "The server has not shared any channels with you yet.",+ "not_found": "Channel not found",+ "not_found_hint": "It may have been deleted, or you no longer have access. Pick another one on the left.",+ "voice_soon": "Voice channels are not ready yet",+ "voice_soon_hint": "Text chat works now; voice and video arrive in a later update.",+ "dms": "Direct messages",+ "no_dms": "No direct messages yet. Pick a member on the right to start one.",+ "no_guilds": "You are not in any server here yet.",+ "no_guilds_hint": "Create one or join with an invite using the + button on the left."+ },+ "members": {+ "title": "Members",+ "online": "Online — {{count}}",+ "offline": "Offline — {{count}}",+ "empty": "No one here yet",+ "show": "Show members",+ "hide": "Hide members",+ "message": "Message {{name}}",+ "owner": "owner"+ },+ "messages": {+ "empty_title": "No messages yet",+ "empty_body": "Say hi — you will be the first one here.",+ "loading": "Loading messages…",+ "today": "Today",+ "yesterday": "Yesterday",+ "you": "You",+ "pending": "Sending…",+ "failed": "Not sent.",+ "retry": "Retry",+ "discard": "Discard",+ "edited": "(edited)",+ "typing_one": "{{name}} is typing…",+ "typing_two": "{{a}} and {{b}} are typing…",+ "typing_many": "Several people are typing…",+ "unknown_user": "Unknown user",+ "new_messages": "New messages",+ "reply_unavailable": "Original message is not loaded",+ "pinned": "Pinned",+ "edit_label": "Edit message",+ "edit_save": "Save",+ "react": "Add reaction",+ "reply": "Reply",+ "edit": "Edit",+ "more": "More actions",+ "pin": "Pin to channel",+ "unpin": "Remove pin",+ "mark_unread": "Mark unread from here",+ "copy_link": "Copy message link",+ "copy_id": "Copy message ID",+ "delete": "Delete message",+ "delete_title": "Delete this message?",+ "delete_body": "It disappears for everyone in the channel. This cannot be undone.",+ "delete_confirm": "Delete message",+ "delete_no_text": "(no text)",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "jump_present": "Jump to present",+ "reaction_add": "React with {{emoji}}",+ "reaction_remove": "Remove your {{emoji}}"+ },+ "composer": {+ "placeholder": "Message #{{channel}}",+ "send": "Send",+ "hint": "Enter to send · Shift+Enter for a new line",+ "replying_to": "Replying to {{name}}",+ "cancel_reply": "Cancel reply",+ "attach": "Attach a file",+ "drop_here": "Drop to attach",+ "uploading_wait": "Wait for the files to finish uploading"+ },+ "dm": {+ "title": "Direct message",+ "placeholder": "Message {{name}}",+ "not_found": "Conversation not found",+ "not_found_hint": "It may have been closed, or this server is not connected right now."+ },+ "error": {+ "unreachable": "The server did not respond. Check the address or ask the owner for a new link.",+ "invalid_url": "That address does not look right. Use http:// or https:// without a username or password.",+ "not_an_instance": "There is no OmniDisc server at this address. Check the link with whoever sent it.",+ "unauthorized": "Your session on this server has expired. Sign in again.",+ "no_session": "You are signed out of this server. Sign in to continue.",+ "forbidden": "This server does not allow you to do that.",+ "missing_permissions": "You do not have permission to do that here. Ask the server owner.",+ "too_many_guilds": "You reached this server's limit of groups per person.",+ "not_found": "That no longer exists on the server. It may have been deleted.",+ "rate_limited": "The server is asking you to slow down. Wait a few seconds and try again.",+ "server": "The server hit an internal error. Try again; if it keeps happening, tell the server owner.",+ "not_connected": "Not connected to this server right now. It reconnects on its own; try again in a moment.",+ "protocol": "This server speaks a version of the chat protocol this OmniGet does not understand. Update OmniGet, or ask the owner to update the server.",+ "bad_request": "The server rejected that. Check what you typed and try again.",+ "invalid_credentials": "Wrong username or password. Check both and try again.",+ "username_taken": "That username is already taken on this server. Pick another one.",+ "invalid_username": "Usernames are 2–32 characters: letters, numbers, _ . -",+ "invalid_password": "Passwords must be 8 to 256 characters.",+ "invalid_invite": "That invite is invalid or has expired. Ask for a new link.",+ "registration_closed": "This server only accepts new accounts through an invite link. Ask a member for one.",+ "message_too_long": "That message is longer than this server allows.",+ "empty_message": "Type something before sending.",+ "voice_mic_permission": "OmniGet is not allowed to use the microphone. Allow it in your system's privacy settings, then rejoin.",+ "voice_no_input_device": "No microphone found. Plug one in or pick another in Voice settings. You can still listen.",+ "voice_no_output_device": "No speakers or headphones found. Connect one and rejoin.",+ "voice_device_busy": "Another app is using the audio device. Close it or pick another device in Voice settings.",+ "voice_mic_failed": "The microphone could not be started. Pick another one in Voice settings. You can still listen.",+ "voice_output_failed": "Audio output could not be started. Pick another device in Voice settings.",+ "voice_mic_lost": "The microphone was disconnected. Plug it back in or pick another in Voice settings.",+ "voice_output_lost": "The audio output was disconnected. Pick another device in Voice settings.",+ "voice_unreachable": "The voice server did not answer. Check your connection and try again; if it keeps failing, tell the server owner.",+ "voice_timeout": "The server took too long to set up voice. Try again in a moment.",+ "voice_denied": "You cannot join this voice channel. Ask the server owner for permission.",+ "voice_dm_unsupported": "Voice calls in direct messages are not available yet. Use a voice channel in a server.",+ "voice_not_connected": "You are not in a voice channel.",+ "voice_disconnected": "Voice dropped. Rejoin when you are ready.",+ "voice_unavailable": "Voice is not available in this build of OmniGet.",+ "voice_engine_crashed": "The voice engine crashed and left the call. Rejoin to try again; if it repeats, send us the log from About → Debug.",+ "screen_permission": "OmniGet needs Screen Recording permission. Open System Settings → Privacy & Security → Screen & System Audio Recording, enable OmniGet, then try again.",+ "stream_unsupported": "Screen sharing isn't available on this platform yet.",+ "stream_source_gone": "That screen or window is no longer available. Pick another one.",+ "stream_capture_failed": "Couldn't capture the screen. Try another source or restart the app.",+ "stream_encoder_failed": "Your machine's video encoder couldn't start. Try a lower resolution or frame rate.",+ "stream_not_streaming": "You aren't sharing your screen right now.",+ "stream_not_found": "That stream isn't available anymore.",+ "stream_viewer_failed": "Couldn't open the stream viewer. Try watching again.",+ "e2ee": "OmniGet could not use encryption for this conversation. Reconnect to the server and try again.",+ "e2ee_not_ready": "Encryption is not set up yet — the other side has to open OmniDisc once. Your message was not sent.",+ "upload_too_large": "That file is bigger than this server accepts.",+ "upload_failed": "The upload did not finish. Check your connection and try again.",+ "upload_cancelled": "Upload cancelled.",+ "unknown_upload": "That attachment is no longer ready. Attach it again.",+ "attachment_corrupt": "This file did not survive the trip — its contents do not match what the sender signed. It was not saved.",+ "too_many_attachments": "You can attach up to 10 files to one message.",+ "file_missing": "OmniGet could not read that file. It may have moved or been deleted.",+ "device_required": "This server needs the app to register a device before encrypting. Reconnect and try again.",+ "epoch_conflict": "Someone changed this conversation while your message was going out. Try sending it again.",+ "voice_output_permission": "OmniGet is not allowed to use the audio output. Allow it in your system's privacy settings, then rejoin.",+ "e2ee_untrusted": "服务器返回了一台此人从未公布过的设备。OmniGet 选择中止而不是向它加密,什么都没有发送。请告知该服务器的管理员。",+ "attachment_origin": "该附件指向此服务器之外的位置,OmniGet 没有下载。",+ "attachment_too_large": "该附件持续发送超过其声明的大小,下载已中止。"+ },+ "guild": {+ "create_title": "Create a server",+ "create_body": "A server is a set of channels for your group. You can invite people right after.",+ "name_label": "Server name",+ "name_placeholder": "e.g. Friday games",+ "create_submit": "Create server",+ "join_title": "Join a server",+ "join_body": "Paste the invite link or code a friend sent you.",+ "join_label": "Invite link or code",+ "join_placeholder": "https://chat.example.org/invite/abc123",+ "join_submit": "Join server",+ "invite": "Invite",+ "invite_copied": "Invite link copied. Send it to whoever you want in.",+ "invite_failed": "Could not create an invite link.",+ "create_channel": "Create channel",+ "create_channel_title": "Create a channel in {{guild}}",+ "channel_name_label": "Channel name",+ "channel_name_placeholder": "e.g. memes",+ "channel_kind_label": "Type",+ "channel_kind_text": "Text",+ "channel_kind_voice": "Voice",+ "create_channel_submit": "Create channel",+ "working": "Working…"+ },+ "voice": {+ "title": "Voice",+ "join": "Join voice",+ "join_channel": "Join {{channel}}",+ "switch_title": "Switch to {{channel}}?",+ "switch_body": "You will leave {{current}}.",+ "switch_confirm": "Switch channel",+ "leave": "Leave voice",+ "leave_short": "Leave",+ "connected_to": "Voice connected",+ "connecting": "Connecting to voice…",+ "reconnecting": "Reconnecting…",+ "failed": "Voice dropped",+ "retry": "Rejoin",+ "mute": "Mute microphone",+ "unmute": "Unmute microphone",+ "deafen": "Deafen (mute everyone)",+ "undeafen": "Undeafen",+ "muted": "Muted",+ "deafened": "Deafened",+ "ptt_hold": "Hold {{key}} to talk",+ "listen_only": "Listening only — your microphone is not working.",+ "no_output": "Your speakers or headphones are not available — others cannot be heard.",+ "quality_excellent": "Connection: excellent",+ "quality_good": "Connection: good",+ "quality_poor": "Connection: poor — audio may cut out",+ "quality_lost": "Connection lost — reconnecting",+ "quality_unknown": "Connection: measuring…",+ "ping": "{{ms}} ms",+ "participants": "{{count}} in voice",+ "nobody": "Nobody here yet",+ "nobody_hint": "Join and invite a friend — voice is lighter than video and works on any connection.",+ "you": "you",+ "speaking": "speaking",+ "user_muted": "{{name}} is muted",+ "user_deafened": "{{name}} is deafened",+ "volume_for": "Volume for {{name}}",+ "volume_reset": "Reset to 100%",+ "settings": "Voice settings",+ "open_settings": "Open voice settings",+ "settings_hint": "Microphone, speakers, noise suppression and push-to-talk.",+ "input_device": "Microphone",+ "output_device": "Speakers / headphones",+ "device_default": "System default",+ "device_refresh": "Refresh devices",+ "no_input_devices": "No microphone found. Plug one in, then refresh.",+ "no_output_devices": "No speakers or headphones found.",+ "mic_test": "Test microphone",+ "mic_test_stop": "Stop test",+ "mic_test_hint": "Speak normally — the bar should move. Nothing is sent anywhere.",+ "mic_level": "Microphone level",+ "mic_silent": "No sound detected. Check the microphone is plugged in and that OmniGet is allowed to use it.",+ "noise_suppression": "Noise suppression",+ "noise_suppression_desc": "Filters fans, keyboards and background hum before your voice is sent. On by default; turn off for music.",+ "ptt_key": "Push-to-talk key",+ "ptt_key_desc": "Leave empty to use voice activity: your mic opens when you speak.",+ "ptt_record": "Record",+ "ptt_recording": "Press a key combination…",+ "ptt_clear": "Use voice activity instead",+ "ptt_permission_hint": "On macOS a global key needs Accessibility permission: System Settings → Privacy & Security → Accessibility → OmniGet.",+ "vad_threshold": "Voice sensitivity",+ "vad_threshold_desc": "Lower opens the mic on quieter sounds; higher needs you to speak up.",+ "e2ee_on": "End-to-end encrypted",+ "e2ee_on_desc": "Only the people in this call can hear it. The key comes from this conversation, never from the server.",+ "e2ee_off": "Not end-to-end encrypted",+ "e2ee_off_desc": "The server can hear this call. Server voice channels are not encrypted unless the owner turns it on.",+ "mic_back": "Your microphone is back.",+ "output_back": "Your audio output is back.",+ "mic_switched": "Your microphone was unplugged — switched to the system default.",+ "output_switched": "Your audio output was unplugged — switched to the system default.",+ "ducking": "Lower others while I talk",+ "ducking_desc": "Turns everyone else down while your microphone is open, so you hear yourself think. Off by default.",+ "ducking_off": "Off",+ "ducking_value": "{{percent}}% quieter",+ "relay_only": "Hide my IP address",+ "relay_only_desc": "Sends all voice through the server's relay instead of straight to the other person. Needs a relay (TURN) on the server; adds a little delay. Applies to your next call."+ },+ "stream": {+ "live": "LIVE",+ "you_live": "You're live",+ "share_screen": "Share screen",+ "stop_sharing": "Stop sharing",+ "share_title": "Share your screen",+ "pick_source": "What to share",+ "loading_sources": "Looking for screens and windows…",+ "recheck": "Check again",+ "audio": "Audio",+ "audio_none": "No audio",+ "audio_system": "System audio",+ "quality": "Quality",+ "resolution": "Resolution",+ "framerate": "Frame rate",+ "implied_bitrate": "About {{kbps}} Mbps · {{codec}}",+ "hevc_note": "Your Mac's H.264 encoder tops out near 60 fps at 4K, so 4K120 uses HEVC. Viewers without HEVC can't watch.",+ "custom_bitrate": "Set the bitrate myself",+ "mode": "Motion",+ "mode_text": "Text & UI",+ "mode_game": "Fast motion",+ "cursor": "Show my cursor",+ "starting": "Starting…",+ "share_cta": "Share {{res}}",+ "watch": "Watch",+ "stop_watching": "Stop watching",+ "volume": "Stream volume",+ "fullscreen": "Fullscreen",+ "connecting": "Connecting…",+ "inspector": "Connection details",+ "sending": "Sending",+ "receiving": "Receiving",+ "software": "software",+ "software_warn": "Encoding in software — this uses more CPU. Close other apps or lower the quality.",+ "rtt": "Ping",+ "loss": "Loss",+ "encode": "Encode",+ "no_active": "No stream running yet."+ },+ "emoji": {+ "title": "Emoji",+ "search": "Search emoji",+ "recent": "Recently used",+ "no_match": "No emoji matches “{{query}}”.",+ "group_reactions": "Quick reactions",+ "group_people": "People",+ "group_nature": "Nature",+ "group_food": "Food",+ "group_activity": "Activity",+ "group_objects": "Objects",+ "group_symbols": "Symbols"+ },+ "search": {+ "title": "Search",+ "placeholder": "Search messages",+ "scope": "Where to search",+ "scope_channel": "This channel",+ "scope_guild": "Whole server",+ "run": "Search",+ "filters_hint": "Filters: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",+ "unknown_from": "No member named “{{name}}” here, so that filter was ignored.",+ "idle_title": "Search this conversation",+ "idle_body": "Type a word and press Search. Filters narrow it down.",+ "empty_title": "Nothing matched",+ "empty_body": "Try fewer words, or drop a filter.",+ "results": "{{count}} matches"+ },+ "pins": {+ "title": "Pinned messages",+ "unpin": "Unpin",+ "empty_title": "No pins yet",+ "empty_body": "Pin a message from its menu to keep it here."+ },+ "notify": {+ "title": "Notifications",+ "channel_hint": "For this channel",+ "inherit": "Use the server setting ({{level}})",+ "level_all": "All messages",+ "level_mentions": "Only mentions",+ "level_nothing": "Nothing",+ "guild_title": "Notifications for this server",+ "guild_hint": "Applies to every channel that has no setting of its own. Stored on this computer."+ },+ "profile": {+ "title": "{{name}}'s profile",+ "open": "Open {{name}}'s profile",+ "roles": "Roles",+ "mutual_servers": "Servers in common — {{count}}",+ "note": "Your note",+ "note_placeholder": "Only you can read this",+ "message": "Message",+ "copy_id": "Copy user ID",+ "copy_failed": "The clipboard is not available. Copy it by hand instead.",+ "moderation": "Moderation",+ "nickname": "Change nickname",+ "nickname_title": "Nickname for {{name}}",+ "nickname_confirm": "Save nickname",+ "nickname_label": "New nickname (empty clears it)",+ "timeout": "Time out",+ "timeout_title": "Time out {{name}}?",+ "timeout_confirm": "Time out {{name}}",+ "timeout_label": "For how long",+ "timeout_5m": "5 minutes",+ "timeout_1h": "1 hour",+ "timeout_1d": "1 day",+ "timeout_1w": "1 week",+ "kick": "Kick",+ "kick_title": "Kick {{name}}?",+ "kick_body": "{{name}} leaves the server and can come back with a new invite.",+ "kick_confirm": "Kick {{name}}",+ "ban": "Ban",+ "ban_title": "Ban {{name}}?",+ "ban_body": "{{name}} leaves the server and cannot rejoin, invite or not, until you unban them.",+ "ban_confirm": "Ban {{name}}",+ "reason_label": "Reason (optional)",+ "reason_placeholder": "Shown in the audit log"+ },+ "friends": {+ "title": "Friends",+ "tab_online": "Online",+ "tab_all": "All — {{count}}",+ "tab_pending": "Pending",+ "tab_blocked": "Blocked",+ "add_label": "Add a friend",+ "add_placeholder": "username",+ "add_hint": "Usernames are exact. Ask the person how theirs is spelled.",+ "send_request": "Send request",+ "sending": "Sending…",+ "request_sent": "Request sent. They see it under Pending.",+ "accept": "Accept",+ "decline": "Decline",+ "remove": "Remove friend",+ "block": "Block",+ "unblock": "Unblock",+ "cancel_request": "Cancel request",+ "pending_out": "Waiting for them",+ "add": "Add friend",+ "empty_online_title": "Nobody online",+ "empty_online_body": "Your friends show up here when they connect.",+ "empty_all_title": "No friends yet",+ "empty_all_body": "Add someone by username above.",+ "empty_pending_title": "No pending requests",+ "empty_pending_body": "Requests you send or receive land here.",+ "empty_blocked_title": "Nobody blocked",+ "empty_blocked_body": "Blocked people cannot DM you."+ },+ "guild_settings": {+ "title": "{{guild}} settings",+ "back": "Back to the server",+ "tab_overview": "Overview",+ "tab_roles": "Roles",+ "tab_channels": "Channels",+ "tab_invites": "Invites",+ "tab_bans": "Bans",+ "tab_audit": "Audit log",+ "overview": "Overview",+ "description": "Description",+ "save": "Save changes",+ "saved": "Saved.",+ "read_only": "You can look, but changing this server needs the Manage server permission.",+ "not_found_title": "Server not found",+ "not_found_body": "It may have been deleted, or you left it.",+ "danger": "Danger zone",+ "leave": "Leave server",+ "leave_hint": "You lose access to its channels until someone invites you again.",+ "leave_owner_hint": "Transfer ownership before leaving — a server cannot be left without an owner.",+ "leave_title": "Leave {{guild}}?",+ "leave_body": "You lose access to its channels until someone invites you again.",+ "leave_confirm": "Leave {{guild}}",+ "transfer": "Transfer ownership",+ "transfer_hint": "The new owner gets every permission. You keep your roles.",+ "transfer_title": "Transfer {{guild}} to someone else?",+ "transfer_body": "They get every permission on this server, including deleting it.",+ "transfer_confirm": "Transfer ownership",+ "transfer_to": "New owner",+ "transfer_pick": "Pick a member",+ "delete": "Delete server",+ "delete_hint": "Channels, messages and roles go with it. This cannot be undone.",+ "delete_title": "Delete {{guild}}?",+ "delete_body": "Every channel, message and role is deleted for everyone. This cannot be undone.",+ "delete_confirm": "Delete {{guild}}",+ "delete_type": "Type {{guild}} to confirm",+ "roles_empty_title": "No roles yet",+ "roles_empty_body": "Create one to hand out permissions.",+ "everyone_role": "everyone",+ "role_create": "New role",+ "role_create_title": "New role",+ "role_create_submit": "Create role",+ "role_name": "Role name",+ "role_name_placeholder": "Moderators",+ "role_color": "Color",+ "role_hoist": "Show separately in the member list",+ "role_mentionable": "Anyone can @mention this role",+ "role_delete": "Delete {{name}}",+ "role_delete_title": "Delete the role {{name}}?",+ "role_delete_body": "Members keep their other roles; the permissions this one granted are gone.",+ "role_delete_confirm": "Delete {{name}}",+ "role_delete_hint": "This cannot be undone.",+ "perm_group_general": "General",+ "perm_group_text": "Text",+ "perm_group_voice": "Voice",+ "perm_group_moderation": "Moderation",+ "invites_hint": "An invite link lets someone join this server.",+ "invite_channel": "Lands in",+ "invite_channel_any": "Server default",+ "invite_expiry": "Expires after",+ "expiry_30m": "30 minutes",+ "expiry_1d": "1 day",+ "expiry_7d": "7 days",+ "expiry_never": "Never",+ "invite_uses": "Max uses",+ "uses_unlimited": "Unlimited",+ "invite_create": "Create invite link",+ "invite_copy": "Copy link",+ "invites_empty": "No link created yet in this session.",+ "invites_no_list": "This server does not keep a list of live invites, so only the link you just created is shown.",+ "bans_empty_title": "Nobody is banned",+ "bans_empty_body": "Bans you hand out show up here so you can lift them.",+ "ban_by": "Banned by {{name}}",+ "unban": "Unban",+ "unban_title": "Unban {{name}}?",+ "unban_body": "They can join again with an invite.",+ "unban_confirm": "Unban {{name}}",+ "unban_hint": "They do not rejoin automatically — they need a new invite.",+ "audit_filter": "Filter by action",+ "audit_all": "Everything",+ "audit_empty_title": "Nothing logged yet",+ "audit_empty_body": "Moderation and setting changes appear here."+ },+ "channel_settings": {+ "title": "Channel settings",+ "name": "Channel name",+ "topic": "Topic",+ "slowmode": "Slowmode",+ "slowmode_off": "Off",+ "nsfw": "Mark as sensitive content",+ "voice_note": "Bitrate and user limit are decided by the instance policy, so they are not editable here.",+ "overwrites": "Permissions in this channel",+ "overwrites_hint": "Inherit follows the role's server permission. Allow and deny only apply here.",+ "overwrite_target": "For",+ "allow": "Allow",+ "inherit": "Inherit",+ "deny": "Deny",+ "delete": "Delete #{{name}}",+ "delete_title": "Delete #{{name}}?",+ "delete_body": "Its messages go with it. This cannot be undone.",+ "delete_confirm": "Delete #{{name}}",+ "delete_hint": "Everyone loses the history in this channel."+ },+ "profile_settings": {+ "title": "Your profile",+ "hint": "Name, pronouns, bio, colour and presence",+ "preview": "What other people see",+ "display_name": "Display name",+ "pronouns": "Pronouns",+ "pronouns_placeholder": "she/her, he/him, they/them…",+ "bio": "About you",+ "accent": "Accent colour",+ "save": "Save profile",+ "saved": "Profile saved.",+ "avatar_note": "Avatar and banner uploads are not available yet — this instance has no file upload endpoint. Your initial and accent colour stand in until then.",+ "presence": "Presence",+ "presence_online": "Online",+ "presence_idle": "Idle",+ "presence_dnd": "Do not disturb",+ "presence_invisible": "Invisible",+ "custom_status": "Custom status",+ "custom_status_placeholder": "Heads down until 5pm",+ "custom_status_expiry": "Clear it after",+ "expiry_never": "Never",+ "expiry_30m": "30 minutes",+ "expiry_4h": "4 hours",+ "expiry_today": "Today",+ "apply_status": "Apply status",+ "no_instance_title": "No server connected",+ "no_instance_body": "Connect to an OmniDisc server first — your profile lives on it."+ },+ "sessions": {+ "title": "Sessions",+ "hint": "Where you are signed in",+ "empty_title": "No other sessions",+ "empty_body": "Only this device is signed in to this server.",+ "current": "This device",+ "last_seen": "Last seen {{when}}",+ "revoke": "Sign out",+ "revoke_title": "Sign {{device}} out?",+ "revoke_body": "That device has to sign in again to use this server.",+ "revoke_confirm": "Sign {{device}} out",+ "revoke_hint": "Do this if you do not recognise the device.",+ "revoke_others": "Sign out the other {{count}} sessions",+ "revoke_others_title": "Sign out every other session?",+ "revoke_others_body": "This device stays signed in. Every other one has to sign in again.",+ "revoke_others_confirm": "Sign the others out",+ "sign_out_here": "Sign out here",+ "unknown_device": "Unknown device"+ },+ "perm": {+ "VIEW_CHANNEL": "View channel",+ "SEND_MESSAGES": "Send messages",+ "EMBED_LINKS": "Embed links",+ "ATTACH_FILES": "Attach files",+ "ADD_REACTIONS": "Add reactions",+ "USE_EXTERNAL_EMOJI": "Use external emoji",+ "MENTION_EVERYONE": "Mention everyone",+ "READ_HISTORY": "Read history",+ "SEND_TTS": "Send text-to-speech",+ "BYPASS_SLOWMODE": "Bypass slowmode",+ "MANAGE_MESSAGES": "Manage messages",+ "PIN_MESSAGES": "Pin messages",+ "MANAGE_CHANNELS": "Manage channels",+ "MANAGE_ROLES": "Manage roles",+ "MANAGE_EMOJI": "Manage emoji",+ "MANAGE_WEBHOOKS": "Manage webhooks",+ "MANAGE_GUILD": "Manage server",+ "VIEW_AUDIT_LOG": "View audit log",+ "CREATE_INVITES": "Create invites",+ "CHANGE_NICKNAME": "Change own nickname",+ "MANAGE_NICKNAMES": "Manage nicknames",+ "VIEW_CHANNEL_MEMBERS": "See the member list",+ "KICK_MEMBERS": "Kick members",+ "BAN_MEMBERS": "Ban members",+ "MODERATE_MEMBERS": "Time out members",+ "CONNECT": "Join voice",+ "SPEAK": "Speak",+ "STREAM": "Share screen",+ "VIDEO": "Turn on camera",+ "USE_VAD": "Use voice activity",+ "PRIORITY_SPEAKER": "Priority speaker",+ "MUTE_MEMBERS": "Mute members",+ "DEAFEN_MEMBERS": "Deafen members",+ "MOVE_MEMBERS": "Move members",+ "USE_SOUNDBOARD": "Use the soundboard",+ "ADMINISTRATOR": "Administrator"+ },+ "perm_desc": {+ "VIEW_CHANNEL": "See the channel and read what is in it.",+ "SEND_MESSAGES": "Write in the channel.",+ "EMBED_LINKS": "Links they post get a preview card.",+ "ATTACH_FILES": "Upload files and images.",+ "ADD_REACTIONS": "React to messages with emoji.",+ "USE_EXTERNAL_EMOJI": "Use emoji from other servers.",+ "MENTION_EVERYONE": "Ping the whole channel at once.",+ "READ_HISTORY": "See messages sent before they arrived.",+ "SEND_TTS": "Send messages that are read out loud.",+ "BYPASS_SLOWMODE": "Send without waiting between messages.",+ "MANAGE_MESSAGES": "Delete other people's messages.",+ "PIN_MESSAGES": "Pin and unpin messages in the channel.",+ "MANAGE_CHANNELS": "Create, rename and delete channels.",+ "MANAGE_ROLES": "Create roles and hand out permissions.",+ "MANAGE_EMOJI": "Add and remove custom emoji.",+ "MANAGE_WEBHOOKS": "Create and remove webhooks.",+ "MANAGE_GUILD": "Change the server name, description and settings.",+ "VIEW_AUDIT_LOG": "See who changed what.",+ "CREATE_INVITES": "Make invite links to this server.",+ "CHANGE_NICKNAME": "Rename themselves in this server.",+ "MANAGE_NICKNAMES": "Rename other members.",+ "VIEW_CHANNEL_MEMBERS": "Open the member list of a channel.",+ "KICK_MEMBERS": "Remove members; they can rejoin with an invite.",+ "BAN_MEMBERS": "Remove members and block them from coming back.",+ "MODERATE_MEMBERS": "Temporarily silence a member.",+ "CONNECT": "Enter voice channels.",+ "SPEAK": "Use the microphone in voice.",+ "STREAM": "Stream a screen or window.",+ "VIDEO": "Send video in voice channels.",+ "USE_VAD": "Talk without holding push-to-talk.",+ "PRIORITY_SPEAKER": "Others get quieter while they talk.",+ "MUTE_MEMBERS": "Server-mute people in voice.",+ "DEAFEN_MEMBERS": "Server-deafen people in voice.",+ "MOVE_MEMBERS": "Drag people between voice channels.",+ "USE_SOUNDBOARD": "Play soundboard clips in voice.",+ "ADMINISTRATOR": "Every permission, everywhere, ignoring channel overrides."+ },+ "audit": {+ "guild_update": "{{actor}} changed the server settings",+ "guild_delete": "{{actor}} deleted the server",+ "guild_transfer": "{{actor}} handed the server to {{target}}",+ "guild_create": "{{actor}} created the server",+ "channel_create": "{{actor}} created a channel",+ "channel_update": "{{actor}} changed a channel",+ "channel_delete": "{{actor}} deleted a channel",+ "channel_overwrite": "{{actor}} changed channel permissions",+ "role_create": "{{actor}} created a role",+ "role_update": "{{actor}} changed a role",+ "role_delete": "{{actor}} deleted a role",+ "member_update": "{{actor}} updated {{target}}",+ "member_kick": "{{actor}} kicked {{target}}",+ "member_ban": "{{actor}} banned {{target}}",+ "member_unban": "{{actor}} unbanned {{target}}",+ "member_leave": "{{target}} left the server",+ "message_delete": "{{actor}} deleted a message",+ "message_bulk_delete": "{{actor}} deleted several messages",+ "message_pin": "{{actor}} pinned a message",+ "message_unpin": "{{actor}} unpinned a message",+ "instance_update": "{{actor}} changed the instance settings",+ "fallback": "{{actor}} — {{action}} {{target}}"+ },+ "audit_action": {+ "guild_update": "Server updated",+ "channel_create": "Channel created",+ "channel_update": "Channel updated",+ "channel_delete": "Channel deleted",+ "channel_overwrite": "Channel permissions",+ "role_create": "Role created",+ "role_update": "Role updated",+ "role_delete": "Role deleted",+ "member_update": "Member updated",+ "member_kick": "Member kicked",+ "member_ban": "Member banned",+ "member_unban": "Member unbanned",+ "member_leave": "Member left",+ "message_delete": "Message deleted",+ "message_bulk_delete": "Messages deleted",+ "message_pin": "Message pinned",+ "message_unpin": "Message unpinned",+ "guild_transfer": "Ownership transferred"+ },+ "attachments": {+ "title": "Attachments",+ "remove": "Remove {{name}}","retry": "Try again",- "update_ytdlp": "Update yt-dlp",- "updated": "yt-dlp updated",- "pot_guide": "Open the PO token guide"+ "preparing": "Encrypting…",+ "uploading": "Sending… {{percent}}%",+ "resuming": "Connection dropped, picking up where it stopped…",+ "ready": "Ready to send",+ "failed": "Did not upload",+ "download": "Save to Downloads",+ "downloading": "Saving…",+ "saved": "Saved to {{path}}",+ "open_image": "Open {{name}}",+ "close_image": "Close the preview",+ "encrypted_note": "Encrypted — save it to open it",+ "too_large": "That file is bigger than this server accepts ({{limit}}).",+ "too_many": "You can attach up to {{count}} files to one message.",+ "unreadable": "OmniGet could not read that file."+ },+ "e2ee": {+ "dm_locked": "Only you and {{name}} can read these messages",+ "group_locked": "Only the people in this conversation can read these messages",+ "guild_open": "Messages in server channels are stored unencrypted — whoever runs {{host}} can read them.",+ "preparing": "Setting up encryption for this conversation…",+ "not_ready": "Waiting for the other device to set up encryption. Your message was not sent.",+ "unavailable": "This message was sent to a device you no longer have. Its text stays on the device that received it.",+ "badge": "End-to-end encrypted",+ "devices_note": "{{count}} devices can read this conversation",+ "unverified": "未验证的设备",+ "unverified_hint": "这条消息由 {{name}} 未公布过的设备签名,可能并非本人。信任之前请先核对指纹。"+ },+ "devices": {+ "title": "Devices",+ "hint": "Which devices can read your encrypted messages",+ "empty_title": "No devices yet",+ "empty_body": "Sign in to a server and this device registers itself so your DMs can be encrypted.",+ "this_device": "This device",+ "added": "Added {{when}}",+ "last_seen": "Last seen {{when}}",+ "fingerprint": "Fingerprint",+ "fingerprint_hint": "Read this out to your friend over a call. If your codes match, nobody is in the middle.",+ "copy": "Copy the fingerprint",+ "copied": "Copied",+ "copy_failed": "OmniGet could not reach the clipboard.",+ "revoke": "Remove",+ "revoke_title": "Remove {{device}}?",+ "revoke_body": "That device stops receiving new encrypted messages. Messages it already has stay on it.",+ "revoke_confirm": "Remove {{device}}",+ "revoke_this_title": "Remove this device?",+ "revoke_this_body": "You will be signed out here and lose the encrypted history stored on this device. There is no backup.",+ "unnamed": "Unnamed device",+ "no_history_warning": "A device only reads messages sent after it joined. Older ones stay on the device that received them."+ },+ "call": {+ "incoming": "{{name}} is calling",+ "incoming_group": "{{name}} is calling {{channel}}",+ "accept": "Answer",+ "decline": "Decline",+ "expires_in": "{{seconds}}s left",+ "start": "Start a call",+ "start_hint": "Voice only — nobody sees your camera.",+ "in_call": "In a call",+ "leave": "Leave the call",+ "joining": "Connecting…"}}}diff --git a/src/lib/nav-config.test.ts b/src/lib/nav-config.test.tsindex 822f1e37..ab01ef8b 100644--- a/src/lib/nav-config.test.ts+++ b/src/lib/nav-config.test.ts@@ -2,8 +2,15 @@ import { describe, it, expect } from "vitest";import { CORE_NAV_ITEMS } from "./nav-config";describe("CORE_NAV_ITEMS", () => {- it("has the expected 5 core entries", () => {- expect(CORE_NAV_ITEMS).toHaveLength(5);+ it("has the expected 6 core entries", () => {+ expect(CORE_NAV_ITEMS).toHaveLength(6);+ });++ it("OmniDisc sits between Downloads and the app group", () => {+ const chat = CORE_NAV_ITEMS.find((i) => i.href === "/omnidisc");+ expect(chat?.group).toBe("primary");+ expect(chat?.icon).toBe("chat");+ expect(chat?.order).toBe(25);});it("Home is first in primary group", () => {diff --git a/src/lib/nav-config.ts b/src/lib/nav-config.tsindex 079f884e..9321d202 100644--- a/src/lib/nav-config.ts+++ b/src/lib/nav-config.ts@@ -5,7 +5,7 @@ export interface NavItem {icon: string;iconSvg?: string;group: "primary" | "app" | "plugins" | "secondary";- badge?: "downloads";+ badge?: "downloads" | "omnidisc";pluginId?: string;order?: number;}@@ -13,6 +13,7 @@ export interface NavItem {export const CORE_NAV_ITEMS: NavItem[] = [{ href: "/", labelKey: "nav.home", icon: "home", group: "primary", order: 10 },{ href: "/downloads", labelKey: "nav.downloads", icon: "downloads", group: "primary", badge: "downloads", order: 20 },+ { href: "/omnidisc", labelKey: "nav.omnidisc", icon: "chat", group: "primary", badge: "omnidisc", order: 25 },{ href: "/marketplace", labelKey: "nav.marketplace", icon: "marketplace", group: "app", order: 30 },{ href: "/settings", labelKey: "nav.settings", icon: "settings", group: "app", order: 40 },{ href: "/about", labelKey: "nav.about", icon: "about", group: "app", order: 50 },diff --git a/src/lib/omnidisc/emoji.ts b/src/lib/omnidisc/emoji.tsnew file mode 100644index 00000000..0d9dd326--- /dev/null+++ b/src/lib/omnidisc/emoji.ts@@ -0,0 +1,110 @@+export interface EmojiEntry {+ char: string;+ name: string;+ group: string;+}++export const EMOJI_GROUPS = ["reactions", "people", "nature", "food", "activity", "objects", "symbols"] as const;++export type EmojiGroup = (typeof EMOJI_GROUPS)[number];++export const EMOJIS: EmojiEntry[] = [+ { char: "👍", name: "thumbs up yes ok", group: "reactions" },+ { char: "👎", name: "thumbs down no", group: "reactions" },+ { char: "❤️", name: "heart love", group: "reactions" },+ { char: "🔥", name: "fire hot", group: "reactions" },+ { char: "🎉", name: "party tada celebrate", group: "reactions" },+ { char: "😂", name: "joy laugh lol", group: "reactions" },+ { char: "😮", name: "wow surprised", group: "reactions" },+ { char: "😢", name: "sad cry", group: "reactions" },+ { char: "🙏", name: "pray thanks please", group: "reactions" },+ { char: "👀", name: "eyes looking", group: "reactions" },+ { char: "✅", name: "check done ok", group: "reactions" },+ { char: "❌", name: "cross no wrong", group: "reactions" },+ { char: "😀", name: "grin smile happy", group: "people" },+ { char: "😅", name: "sweat smile nervous", group: "people" },+ { char: "🙂", name: "slight smile", group: "people" },+ { char: "😉", name: "wink", group: "people" },+ { char: "😍", name: "heart eyes love", group: "people" },+ { char: "🤔", name: "thinking hmm", group: "people" },+ { char: "😴", name: "sleep tired", group: "people" },+ { char: "😎", name: "cool sunglasses", group: "people" },+ { char: "🤝", name: "handshake deal", group: "people" },+ { char: "👋", name: "wave hello bye", group: "people" },+ { char: "💪", name: "muscle strong", group: "people" },+ { char: "🧠", name: "brain smart", group: "people" },+ { char: "🐶", name: "dog puppy", group: "nature" },+ { char: "🐱", name: "cat kitten", group: "nature" },+ { char: "🦊", name: "fox", group: "nature" },+ { char: "🐢", name: "turtle slow", group: "nature" },+ { char: "🌱", name: "seedling plant grow", group: "nature" },+ { char: "🌊", name: "wave water sea", group: "nature" },+ { char: "☀️", name: "sun sunny", group: "nature" },+ { char: "🌙", name: "moon night", group: "nature" },+ { char: "⭐", name: "star", group: "nature" },+ { char: "🍕", name: "pizza food", group: "food" },+ { char: "🍔", name: "burger food", group: "food" },+ { char: "🍟", name: "fries food", group: "food" },+ { char: "🍰", name: "cake dessert", group: "food" },+ { char: "☕", name: "coffee cafe", group: "food" },+ { char: "🍺", name: "beer drink", group: "food" },+ { char: "🥤", name: "soda drink", group: "food" },+ { char: "🎮", name: "game controller play", group: "activity" },+ { char: "🎧", name: "headphones music listen", group: "activity" },+ { char: "🎵", name: "music note song", group: "activity" },+ { char: "🏆", name: "trophy win", group: "activity" },+ { char: "⚽", name: "soccer football", group: "activity" },+ { char: "🎬", name: "clapper movie film", group: "activity" },+ { char: "🚀", name: "rocket ship launch", group: "activity" },+ { char: "💻", name: "laptop computer code", group: "objects" },+ { char: "📱", name: "phone mobile", group: "objects" },+ { char: "🖥️", name: "desktop screen", group: "objects" },+ { char: "🎥", name: "camera video record", group: "objects" },+ { char: "📎", name: "paperclip attach", group: "objects" },+ { char: "📌", name: "pin pinned", group: "objects" },+ { char: "🔒", name: "lock secure private", group: "objects" },+ { char: "🔑", name: "key access", group: "objects" },+ { char: "🐛", name: "bug issue", group: "objects" },+ { char: "⚡", name: "zap fast lightning", group: "symbols" },+ { char: "💡", name: "idea bulb light", group: "symbols" },+ { char: "⚠️", name: "warning caution", group: "symbols" },+ { char: "♻️", name: "recycle repeat", group: "symbols" },+ { char: "➕", name: "plus add", group: "symbols" },+ { char: "➖", name: "minus remove", group: "symbols" },+ { char: "❓", name: "question help", group: "symbols" },+ { char: "❗", name: "exclamation important", group: "symbols" },+ { char: "💯", name: "hundred perfect", group: "symbols" },+];++const RECENT_KEY = "omnidisc.emoji.recent";+const RECENT_MAX = 12;++export function recentEmojis(): string[] {+ if (typeof localStorage === "undefined") return [];+ try {+ const raw = localStorage.getItem(RECENT_KEY);+ if (!raw) return [];+ const parsed: unknown = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed.filter((e): e is string => typeof e === "string").slice(0, RECENT_MAX) : [];+ } catch {+ return [];+ }+}++export function rememberEmoji(char: string): string[] {+ const next = [char, ...recentEmojis().filter((e) => e !== char)].slice(0, RECENT_MAX);+ if (typeof localStorage !== "undefined") {+ try {+ localStorage.setItem(RECENT_KEY, JSON.stringify(next));+ } catch {+ return next;+ }+ }+ return next;+}++export function searchEmojis(query: string): EmojiEntry[] {+ const q = query.trim().toLowerCase();+ if (!q) return EMOJIS;+ return EMOJIS.filter((e) => e.name.includes(q) || e.char === q);+}diff --git a/src/lib/omnidisc/fixtures.ts b/src/lib/omnidisc/fixtures.tsnew file mode 100644index 00000000..202711e4--- /dev/null+++ b/src/lib/omnidisc/fixtures.ts@@ -0,0 +1,82 @@+import type { OmnidiscGuild, OmnidiscMember, OmnidiscMessage } from "./types";++export const DEMO_INSTANCE_ID = "demo";+export const DEMO_INSTANCE_URL = "demo://local";++const AUTHORS = [+ { id: "u1", name: "Loop" },+ { id: "u2", name: "Ana" },+ { id: "u3", name: "Rafael" },+ { id: "u4", name: "Mei" },+ { id: "u5", name: "Kofi" },+];++const LINES = [+ "anyone up for a game later?",+ "just pushed the fix, can you pull and check?",+ "the new build scrolls way smoother on my old laptop",+ "lol",+ "I'll be there in 10",+ "can someone resend the link? I lost it",+ "ok that works",+ "this is a longer message so the list has to deal with rows of different heights, which is exactly what a virtualized list gets wrong if it assumes a fixed size for every item.",+ "gg",+ "brb",+ "what codec are we using for screen share again?",+ "4k120 is wild",+];++export function makeFixtureGuilds(instanceId: string): OmnidiscGuild[] {+ return [+ {+ id: "g-home",+ instanceId,+ name: "Home base",+ ownerId: "u1",+ roles: [],+ channels: [+ { id: "c-general", name: "general", kind: "text", category: "Text", position: 0, guildId: "g-home" },+ { id: "c-downloads", name: "downloads", kind: "text", category: "Text", position: 1, guildId: "g-home" },+ { id: "c-dev", name: "dev", kind: "text", category: "Text", position: 2, guildId: "g-home" },+ { id: "c-lounge", name: "Lounge", kind: "voice", category: "Voice", position: 3, guildId: "g-home" },+ { id: "c-games", name: "Games", kind: "voice", category: "Voice", position: 4, guildId: "g-home" },+ ],+ },+ {+ id: "g-study",+ instanceId,+ name: "Study group",+ ownerId: "u2",+ roles: [],+ channels: [+ { id: "c-notes", name: "notes", kind: "text", category: "Text", position: 0, guildId: "g-study" },+ { id: "c-focus", name: "Focus room", kind: "voice", category: "Voice", position: 1, guildId: "g-study" },+ ],+ },+ ];+}++export function makeFixtureMembers(): OmnidiscMember[] {+ return AUTHORS.map((a, i) => ({ id: a.id, name: a.name, online: i % 2 === 0, role: i === 0 ? "admin" : undefined }));+}++export function makeFixtureMessages(channelId: string, count: number, endAt: number, startSeq: number): OmnidiscMessage[] {+ const out: OmnidiscMessage[] = [];+ let ts = endAt;+ for (let i = count - 1; i >= 0; i--) {+ const seq = startSeq + i;+ const author = AUTHORS[(seq * 7) % AUTHORS.length];+ const gapMin = seq % 9 === 0 ? 8 * 60 : seq % 4 === 0 ? 7 : 1;+ out.unshift({+ id: `${channelId}-${seq}`,+ channelId,+ authorId: author.id,+ authorName: author.name,+ content: LINES[(seq * 5) % LINES.length],+ createdAt: ts,+ delivery: "sent",+ });+ ts -= gapMin * 60_000;+ }+ return out;+}diff --git a/src/lib/omnidisc/permissions.test.ts b/src/lib/omnidisc/permissions.test.tsnew file mode 100644index 00000000..bc9a4950--- /dev/null+++ b/src/lib/omnidisc/permissions.test.ts@@ -0,0 +1,158 @@+import { describe, expect, it } from "vitest";+import {+ ALL_PERMISSIONS,+ canIn,+ has,+ perm,+ resolvePermissions,+ toBits,+ type PermissionContext,+} from "./permissions";+import type { OmnidiscChannel, OmnidiscGuild, OmnidiscMember, OmnidiscRole } from "./types";++const EVERYONE: OmnidiscRole = {+ id: "r-everyone",+ name: "everyone",+ permissions: (perm("VIEW_CHANNEL") | perm("SEND_MESSAGES") | perm("READ_HISTORY")).toString(),+ position: 0,+ hoist: false,+ mentionable: false,+ isEveryone: true,+};++const MOD: OmnidiscRole = {+ id: "r-mod",+ name: "Moderators",+ permissions: perm("MANAGE_MESSAGES").toString(),+ position: 1,+ hoist: true,+ mentionable: true,+ isEveryone: false,+};++const ADMIN: OmnidiscRole = {+ id: "r-admin",+ name: "Admins",+ permissions: perm("ADMINISTRATOR").toString(),+ position: 2,+ hoist: true,+ mentionable: false,+ isEveryone: false,+};++function guild(roles: OmnidiscRole[] = [EVERYONE, MOD, ADMIN], ownerId = "owner"): OmnidiscGuild {+ return { id: "g1", instanceId: "i1", name: "Guild", ownerId, channels: [], roles };+}++function channel(overwrites: OmnidiscChannel["overwrites"] = [], parentId?: string): OmnidiscChannel {+ return { id: "c1", name: "general", kind: "text", position: 0, guildId: "g1", parentId, overwrites };+}++function member(roleIds: string[]): OmnidiscMember {+ return { id: "u1", name: "User", online: true, roleIds };+}++function ctx(over: Partial<PermissionContext> = {}): PermissionContext {+ return {+ guild: guild(),+ channel: channel(),+ parent: null,+ member: member([]),+ userId: "u1",+ ...over,+ };+}++describe("omnidisc permission bits", () => {+ it("parses a decimal string and falls back to zero on junk", () => {+ expect(toBits("3")).toBe(3n);+ expect(toBits(undefined)).toBe(0n);+ expect(toBits("not a number")).toBe(0n);+ });++ it("has() needs every bit of the permission", () => {+ expect(has(perm("SEND_MESSAGES"), "SEND_MESSAGES")).toBe(true);+ expect(has(perm("SEND_MESSAGES"), "MANAGE_MESSAGES")).toBe(false);+ });+});++describe("omnidisc permission resolution", () => {+ it("gives the owner everything, whatever the overwrites say", () => {+ const denied = [{ targetId: "r-everyone", targetKind: "role" as const, allow: "0", deny: perm("VIEW_CHANNEL").toString() }];+ const resolved = resolvePermissions(ctx({ userId: "owner", channel: channel(denied) }));+ expect(resolved).toBe(ALL_PERMISSIONS);+ });++ it("a non-member of any guild gets nothing", () => {+ expect(resolvePermissions(ctx({ guild: null }))).toBe(0n);+ expect(resolvePermissions(ctx({ userId: null }))).toBe(0n);+ });++ it("starts from @everyone and adds the member's roles", () => {+ expect(canIn(ctx(), "SEND_MESSAGES")).toBe(true);+ expect(canIn(ctx(), "MANAGE_MESSAGES")).toBe(false);+ expect(canIn(ctx({ member: member(["r-mod"]) }), "MANAGE_MESSAGES")).toBe(true);+ });++ it("an administrator role ignores channel denials", () => {+ const denied = [{ targetId: "r-everyone", targetKind: "role" as const, allow: "0", deny: perm("VIEW_CHANNEL").toString() }];+ expect(canIn(ctx({ member: member(["r-admin"]), channel: channel(denied) }), "VIEW_CHANNEL")).toBe(true);+ });++ it("a member overwrite beats a role denial in the same channel", () => {+ const overwrites = [+ { targetId: "r-mod", targetKind: "role" as const, allow: "0", deny: perm("SEND_MESSAGES").toString() },+ { targetId: "u1", targetKind: "member" as const, allow: perm("SEND_MESSAGES").toString(), deny: "0" },+ ];+ expect(canIn(ctx({ member: member(["r-mod"]), channel: channel(overwrites) }), "SEND_MESSAGES")).toBe(true);+ });++ it("someone with no membership record gets nothing, like the server", () => {+ expect(resolvePermissions(ctx({ member: null }))).toBe(0n);+ expect(canIn(ctx({ member: null }), "VIEW_CHANNEL")).toBe(false);+ expect(canIn(ctx({ member: null }), "SEND_MESSAGES")).toBe(false);+ expect(canIn(ctx({ member: member([]), isMember: false }), "SEND_MESSAGES")).toBe(false);+ // The owner is still the owner even before their member record arrives.+ expect(resolvePermissions(ctx({ member: null, userId: "owner" }))).toBe(ALL_PERMISSIONS);+ // A member whose paged row has not arrived yet is still a member.+ expect(canIn(ctx({ member: null, isMember: true }), "SEND_MESSAGES")).toBe(true);+ });++ it("a timed-out member loses exactly what the server takes away", () => {+ const timedOut: OmnidiscMember = {+ ...member([]),+ mutedUntil: new Date(Date.now() + 60_000).toISOString(),+ };+ expect(canIn(ctx({ member: timedOut }), "SEND_MESSAGES")).toBe(false);+ expect(canIn(ctx({ member: timedOut }), "ADD_REACTIONS")).toBe(false);+ expect(canIn(ctx({ member: timedOut }), "SPEAK")).toBe(false);+ expect(canIn(ctx({ member: timedOut }), "READ_HISTORY")).toBe(true);+ expect(canIn(ctx({ member: timedOut }), "VIEW_CHANNEL")).toBe(true);+ });++ it("an expired timeout, and an admin's timeout, change nothing", () => {+ const expired: OmnidiscMember = {+ ...member([]),+ mutedUntil: new Date(Date.now() - 60_000).toISOString(),+ };+ expect(canIn(ctx({ member: expired }), "SEND_MESSAGES")).toBe(true);+ const admin: OmnidiscMember = {+ ...member(["r-admin"]),+ mutedUntil: new Date(Date.now() + 60_000).toISOString(),+ };+ expect(canIn(ctx({ member: admin }), "SEND_MESSAGES")).toBe(true);+ const junk: OmnidiscMember = { ...member([]), mutedUntil: "whenever" };+ expect(canIn(ctx({ member: junk }), "SEND_MESSAGES")).toBe(true);+ });++ it("the channel tier overrides the category tier", () => {+ const parent = channel([+ { targetId: "r-everyone", targetKind: "role", allow: "0", deny: perm("VIEW_CHANNEL").toString() },+ ]);+ const child = channel([+ { targetId: "r-everyone", targetKind: "role", allow: perm("VIEW_CHANNEL").toString(), deny: "0" },+ ]);+ expect(canIn(ctx({ parent, channel: child }), "VIEW_CHANNEL")).toBe(true);+ expect(canIn(ctx({ parent, channel: channel() }), "VIEW_CHANNEL")).toBe(false);+ });+});diff --git a/src/lib/omnidisc/permissions.ts b/src/lib/omnidisc/permissions.tsnew file mode 100644index 00000000..1e189d84--- /dev/null+++ b/src/lib/omnidisc/permissions.ts@@ -0,0 +1,194 @@+import type { OmnidiscChannel, OmnidiscGuild, OmnidiscMember, OmnidiscOverwrite } from "./types";++export const PERMISSION_BITS = {+ VIEW_CHANNEL: 0,+ SEND_MESSAGES: 1,+ EMBED_LINKS: 2,+ ATTACH_FILES: 3,+ ADD_REACTIONS: 4,+ USE_EXTERNAL_EMOJI: 5,+ MENTION_EVERYONE: 6,+ READ_HISTORY: 7,+ SEND_TTS: 8,+ BYPASS_SLOWMODE: 9,+ MANAGE_MESSAGES: 16,+ PIN_MESSAGES: 17,+ MANAGE_CHANNELS: 18,+ MANAGE_ROLES: 19,+ MANAGE_EMOJI: 20,+ MANAGE_WEBHOOKS: 21,+ MANAGE_GUILD: 22,+ VIEW_AUDIT_LOG: 23,+ CREATE_INVITES: 24,+ CHANGE_NICKNAME: 25,+ MANAGE_NICKNAMES: 26,+ VIEW_CHANNEL_MEMBERS: 27,+ KICK_MEMBERS: 32,+ BAN_MEMBERS: 33,+ MODERATE_MEMBERS: 34,+ CONNECT: 40,+ SPEAK: 41,+ STREAM: 42,+ VIDEO: 43,+ USE_VAD: 44,+ PRIORITY_SPEAKER: 45,+ MUTE_MEMBERS: 46,+ DEAFEN_MEMBERS: 47,+ MOVE_MEMBERS: 48,+ USE_SOUNDBOARD: 49,+ ADMINISTRATOR: 63,+} as const;++export type PermissionName = keyof typeof PERMISSION_BITS;++export const ALL_PERMISSIONS = ~0n & ((1n << 64n) - 1n);++export function perm(name: PermissionName): bigint {+ return 1n << BigInt(PERMISSION_BITS[name]);+}++export function toBits(raw: string | undefined): bigint {+ if (!raw) return 0n;+ try {+ return BigInt(raw);+ } catch {+ return 0n;+ }+}++export function has(bits: bigint, name: PermissionName): boolean {+ const p = perm(name);+ return (bits & p) === p;+}++export type PermissionGroup = "general" | "text" | "voice" | "moderation";++export const PERMISSION_GROUPS: Record<PermissionGroup, PermissionName[]> = {+ general: [+ "VIEW_CHANNEL",+ "VIEW_CHANNEL_MEMBERS",+ "CREATE_INVITES",+ "CHANGE_NICKNAME",+ "MANAGE_CHANNELS",+ "MANAGE_ROLES",+ "MANAGE_GUILD",+ "VIEW_AUDIT_LOG",+ "ADMINISTRATOR",+ ],+ text: [+ "SEND_MESSAGES",+ "READ_HISTORY",+ "EMBED_LINKS",+ "ATTACH_FILES",+ "ADD_REACTIONS",+ "USE_EXTERNAL_EMOJI",+ "MENTION_EVERYONE",+ "MANAGE_MESSAGES",+ "PIN_MESSAGES",+ "BYPASS_SLOWMODE",+ ],+ voice: [+ "CONNECT",+ "SPEAK",+ "STREAM",+ "VIDEO",+ "USE_VAD",+ "PRIORITY_SPEAKER",+ "USE_SOUNDBOARD",+ "MUTE_MEMBERS",+ "DEAFEN_MEMBERS",+ "MOVE_MEMBERS",+ ],+ moderation: ["KICK_MEMBERS", "BAN_MEMBERS", "MODERATE_MEMBERS", "MANAGE_NICKNAMES"],+};++function overwriteFor(+ overwrites: OmnidiscOverwrite[] | undefined,+ targetId: string,+ kind: "role" | "member",+): { allow: bigint; deny: bigint } | null {+ const found = overwrites?.find((o) => o.targetId === targetId && o.targetKind === kind);+ if (!found) return null;+ return { allow: toBits(found.allow), deny: toBits(found.deny) };+}++function applyTier(+ base: bigint,+ overwrites: OmnidiscOverwrite[] | undefined,+ everyoneRoleId: string | null,+ roleIds: string[],+ userId: string,+): bigint {+ let p = base;+ if (everyoneRoleId) {+ const everyone = overwriteFor(overwrites, everyoneRoleId, "role");+ if (everyone) p = (p & ~everyone.deny) | everyone.allow;+ }+ let allow = 0n;+ let deny = 0n;+ for (const roleId of roleIds) {+ if (roleId === everyoneRoleId) continue;+ const o = overwriteFor(overwrites, roleId, "role");+ if (!o) continue;+ allow |= o.allow;+ deny |= o.deny;+ }+ p = (p & ~deny) | allow;+ const member = overwriteFor(overwrites, userId, "member");+ if (member) p = (p & ~member.deny) | member.allow;+ return p;+}++export interface PermissionContext {+ guild: OmnidiscGuild | null;+ channel: OmnidiscChannel | null;+ parent?: OmnidiscChannel | null;+ member: OmnidiscMember | null;+ userId: string | null;+ /// Whether the user belongs to this guild at all. Defaults to `member !== null`,+ /// which is what a caller with only a member list can know. The store passes it+ /// explicitly because membership and the member *row* arrive from different+ /// places: the row is paged (op 14 asks for ranks 0-99), so a member of a large+ /// guild can be missing from it for a long time and must not be treated as an+ /// outsider.+ isMember?: boolean;+}++/// Mirrors the server's MUTED_DENY: what a timed-out member loses until the+/// timeout expires. Kept in sync by hand with `permissions.rs` on the server.+export const MUTED_DENY =+ perm("SEND_MESSAGES") | perm("ADD_REACTIONS") | perm("SPEAK") | perm("STREAM") | perm("VIDEO");++export function isMuted(member: OmnidiscMember | null, now = Date.now()): boolean {+ if (!member?.mutedUntil) return false;+ const until = Date.parse(member.mutedUntil);+ return Number.isFinite(until) && until > now;+}++export function resolvePermissions(ctx: PermissionContext): bigint {+ const { guild, channel, parent, member, userId } = ctx;+ if (!guild || !userId) return 0n;+ if (guild.ownerId === userId) return ALL_PERMISSIONS;+ // The server answers NONE for someone who is not a member of the guild.+ // Falling through to @everyone here is what makes the UI offer actions that+ // then come back 403.+ if (!(ctx.isMember ?? member !== null)) return 0n;+ const everyoneRole = guild.roles.find((r) => r.isEveryone) ?? null;+ const roleIds = member?.roleIds ?? [];+ let base = toBits(everyoneRole?.permissions);+ for (const roleId of roleIds) {+ const role = guild.roles.find((r) => r.id === roleId);+ if (role) base |= toBits(role.permissions);+ }+ if (has(base, "ADMINISTRATOR")) return ALL_PERMISSIONS;+ const everyoneId = everyoneRole?.id ?? null;+ let p = base;+ if (parent) p = applyTier(p, parent.overwrites, everyoneId, roleIds, userId);+ if (channel) p = applyTier(p, channel.overwrites, everyoneId, roleIds, userId);+ if (!has(p, "ADMINISTRATOR") && isMuted(member)) p &= ~MUTED_DENY;+ return p;+}++export function canIn(ctx: PermissionContext, name: PermissionName): boolean {+ return has(resolvePermissions(ctx), name);+}diff --git a/src/lib/omnidisc/snowflake.ts b/src/lib/omnidisc/snowflake.tsnew file mode 100644index 00000000..b08e6c51--- /dev/null+++ b/src/lib/omnidisc/snowflake.ts@@ -0,0 +1,28 @@+export const OMNIDISC_EPOCH_MS = 1_785_542_400_000;+const TIMESTAMP_SHIFT = 22n;++export function snowflakeTime(id: string): number {+ if (!/^\d+$/.test(id)) return Date.now();+ try {+ return Number(BigInt(id) >> TIMESTAMP_SHIFT) + OMNIDISC_EPOCH_MS;+ } catch {+ return Date.now();+ }+}++export function compareSnowflakes(a: string, b: string): number {+ if (a === b) return 0;+ if (a.length !== b.length) return a.length < b.length ? -1 : 1;+ return a < b ? -1 : 1;+}++export function isAfter(a: string | undefined, b: string | undefined): boolean {+ if (!a) return false;+ if (!b) return true;+ return compareSnowflakes(a, b) > 0;+}++export function snowflakeForTime(ms: number): string {+ const delta = Math.max(0, Math.floor(ms) - OMNIDISC_EPOCH_MS);+ return (BigInt(delta) << TIMESTAMP_SHIFT).toString();+}diff --git a/src/lib/omnidisc/types.ts b/src/lib/omnidisc/types.tsnew file mode 100644index 00000000..bdb6a2db--- /dev/null+++ b/src/lib/omnidisc/types.ts@@ -0,0 +1,255 @@+export type InstanceStatus =+ | "disconnected"+ | "connecting"+ | "connected"+ | "reconnecting"+ | "signed_out"+ | "error";++export interface StreamingPolicy {+ max_height: number;+ max_fps: number;+ min_kbps: number;+ max_kbps: number;+ step_kbps: number;+ allow_custom_bitrate: boolean;+ overrides?: Record<string, number>;+ preferred_codec?: string;+ allow_h265?: boolean;+}++export interface OmnidiscInstance {+ id: string;+ url: string;+ name: string;+ status: InstanceStatus;+ error?: string;+ userId?: string;+ streaming?: StreamingPolicy;+ /// Reached over plain http, so the session token and every message are+ /// readable on the wire. Loopback does not count.+ insecure?: boolean;+}++export type ChannelKind = "text" | "voice" | "category" | "dm" | "group_dm" | "link" | "notes";++export interface OmnidiscOverwrite {+ targetId: string;+ targetKind: "role" | "member";+ allow: string;+ deny: string;+}++export interface OmnidiscChannel {+ id: string;+ name: string;+ kind: ChannelKind;+ e2ee?: boolean;+ category?: string;+ parentId?: string;+ position: number;+ guildId?: string;+ recipientIds?: string[];+ lastMessageId?: string;+ topic?: string;+ nsfw?: boolean;+ slowmodeSeconds?: number;+ bitrate?: number;+ userLimit?: number;+ overwrites?: OmnidiscOverwrite[];+}++export interface OmnidiscRole {+ id: string;+ name: string;+ permissions: string;+ position: number;+ color?: number;+ hoist: boolean;+ mentionable: boolean;+ isEveryone: boolean;+}++export interface OmnidiscGuild {+ id: string;+ instanceId: string;+ name: string;+ ownerId: string;+ description?: string;+ channels: OmnidiscChannel[];+ roles: OmnidiscRole[];+}++export interface OmnidiscMember {+ id: string;+ name: string;+ online: boolean;+ role?: string;+ nick?: string;+ roleIds?: string[];+ mutedUntil?: string;+}++export interface OmnidiscUser {+ id: string;+ username: string;+ displayName: string;+ avatar?: string;+ banner?: string;+ accentColor?: number;+ bio?: string;+ pronouns?: string;+}++export type RelationshipKind = "friend" | "incoming_request" | "outgoing_request" | "blocked";++export interface OmnidiscRelationship {+ userId: string;+ kind: RelationshipKind;+ since: string;+}++export interface OmnidiscSession {+ sessionId: string;+ client: string;+ deviceName?: string;+ lastSeen: string;+ current: boolean;+}++export interface OmnidiscBan {+ userId: string;+ bannedBy: string;+ reason?: string;+ createdAt: string;+}++export interface OmnidiscAuditEntry {+ id: string;+ actorId: string;+ action: string;+ targetId?: string;+ reason?: string;+ createdAt: string;+}++export type NotificationLevel = "all" | "mentions" | "nothing";++export interface OmnidiscReaction {+ emoji: string;+ count: number;+ me: boolean;+}++export type MessageDelivery = "sent" | "pending" | "failed";++export interface OmnidiscAttachment {+ id: string;+ filename: string;+ size: number;+ contentType?: string;+ url?: string;+ thumbnailUrl?: string;+ thumbhash?: string;+ width?: number;+ height?: number;+ durationMs?: number;+ encrypted: boolean;+}++export interface OmnidiscDevice {+ userId: string;+ deviceId: string;+ publicKey: string;+ fingerprint?: string;+ name?: string;+ createdAt: string;+ lastSeenAt: string;+ revokedAt?: string;+}++export interface OmnidiscGroupMember {+ userId: string;+ deviceId: string;+ fingerprint: string;+ isMe: boolean;+}++export interface OmnidiscGroupStatus {+ ready: boolean;+ groupId: string;+ epoch?: number;+ members: OmnidiscGroupMember[];+}++export type UploadState = "preparing" | "uploading" | "resuming" | "done" | "failed" | "cancelled";++export interface PendingAttachment {+ id: string;+ channelId: string;+ name: string;+ path: string;+ sent: number;+ total: number;+ state: UploadState;+ error?: string;+ mime?: string;+ encrypted: boolean;+ previewUrl?: string;+}++export interface OmnidiscMessage {+ id: string;+ channelId: string;+ authorId: string;+ authorName: string;+ content: string;+ createdAt: number;+ editedAt?: number;+ delivery?: MessageDelivery;+ error?: string;+ replyToId?: string;+ reactions?: OmnidiscReaction[];+ pinned?: boolean;+ mentionsMe?: boolean;+ mentionedUserIds?: string[];+ mentionsEveryone?: boolean;+ attachments?: OmnidiscAttachment[];+ encrypted?: boolean;+ ciphertext?: string;+ awaitingDecryption?: boolean;+ /// Set only on decrypted messages: false means the sending device is not one+ /// the claimed author published, so the name on the bubble is not proof.+ senderVerified?: boolean;+}++export type ConnectStep =+ | "idle"+ | "connecting"+ | "auth"+ | "authenticating"+ | "syncing"+ | "error"+ | "done";++export type AuthMode = "login" | "register";++export interface ConnectResult {+ url: string;+ recognized: boolean;+ insecure?: boolean;+ instance: Record<string, unknown>;+ invite?: string;+}++export interface GatewayStatusEvent {+ url: string;+ status: "connecting" | "ready" | "reconnecting" | "disconnected";+ error?: string | null;+}++export interface GatewayDispatchEvent {+ url: string;+ t: string;+ d: unknown;+}diff --git a/src/lib/omnidisc/wire.ts b/src/lib/omnidisc/wire.tsnew file mode 100644index 00000000..dd475b03--- /dev/null+++ b/src/lib/omnidisc/wire.ts@@ -0,0 +1,335 @@+import type {+ ChannelKind,+ OmnidiscAttachment,+ OmnidiscDevice,+ OmnidiscAuditEntry,+ OmnidiscBan,+ OmnidiscChannel,+ OmnidiscGuild,+ OmnidiscMessage,+ OmnidiscOverwrite,+ OmnidiscReaction,+ OmnidiscRelationship,+ OmnidiscRole,+ OmnidiscSession,+ OmnidiscUser,+ RelationshipKind,+} from "./types";+import { snowflakeTime } from "./snowflake";++type Json = Record<string, unknown>;++export function isRecord(v: unknown): v is Json {+ return typeof v === "object" && v !== null && !Array.isArray(v);+}++export function str(v: unknown): string | undefined {+ return typeof v === "string" ? v : undefined;+}++function num(v: unknown): number | undefined {+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;+}++function strList(v: unknown): string[] {+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];+}++const CHANNEL_KINDS: Record<number, ChannelKind> = {+ 0: "text",+ 1: "dm",+ 2: "voice",+ 3: "group_dm",+ 4: "category",+ 5: "link",+ 6: "notes",+};++export function channelKindCode(kind: ChannelKind): number {+ for (const [code, k] of Object.entries(CHANNEL_KINDS)) {+ if (k === kind) return Number(code);+ }+ return 0;+}++function parseOverwrites(raw: unknown): OmnidiscOverwrite[] {+ if (!Array.isArray(raw)) return [];+ const out: OmnidiscOverwrite[] = [];+ for (const o of raw) {+ if (!isRecord(o)) continue;+ const targetId = str(o.target_id);+ const targetKind = o.target_kind === "member" ? "member" : "role";+ if (!targetId) continue;+ out.push({ targetId, targetKind, allow: str(o.allow) ?? "0", deny: str(o.deny) ?? "0" });+ }+ return out;+}++export function parseRole(raw: unknown): OmnidiscRole | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ if (!id) return null;+ return {+ id,+ name: str(raw.name) ?? id,+ permissions: str(raw.permissions) ?? "0",+ position: num(raw.position) ?? 0,+ color: num(raw.color),+ hoist: raw.hoist === true,+ mentionable: raw.mentionable === true,+ isEveryone: raw.is_everyone === true,+ };+}++export function parseChannel(raw: unknown): OmnidiscChannel | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ if (!id) return null;+ const kind = CHANNEL_KINDS[num(raw.type) ?? -1] ?? "text";+ return {+ id,+ name: str(raw.name) ?? "",+ kind,+ parentId: str(raw.parent_id),+ position: num(raw.position) ?? 0,+ guildId: str(raw.guild_id),+ recipientIds: strList(raw.recipient_ids),+ e2ee: raw.e2ee === true,+ lastMessageId: str(raw.last_message_id),+ topic: str(raw.topic),+ nsfw: raw.nsfw === true,+ slowmodeSeconds: num(raw.slowmode_seconds),+ bitrate: num(raw.bitrate),+ userLimit: num(raw.user_limit),+ overwrites: parseOverwrites(raw.overwrites),+ };+}++export function parseGuild(raw: unknown, instanceId: string): OmnidiscGuild | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ if (!id) return null;+ const channels = (Array.isArray(raw.channels) ? raw.channels : [])+ .map(parseChannel)+ .filter((c): c is OmnidiscChannel => c !== null);+ const roles = (Array.isArray(raw.roles) ? raw.roles : [])+ .map(parseRole)+ .filter((r): r is OmnidiscRole => r !== null)+ .sort((a, b) => a.position - b.position);+ return {+ id,+ instanceId,+ name: str(raw.name) ?? id,+ ownerId: str(raw.owner_id) ?? "",+ description: str(raw.description),+ channels: withCategories(channels),+ roles,+ };+}++export function withCategories(channels: OmnidiscChannel[]): OmnidiscChannel[] {+ const categories = new Map<string, OmnidiscChannel>();+ for (const c of channels) {+ if (c.kind === "category") categories.set(c.id, c);+ }+ const sorted = [...channels].sort((a, b) => {+ const ca = a.kind === "category" ? a : a.parentId ? categories.get(a.parentId) : undefined;+ const cb = b.kind === "category" ? b : b.parentId ? categories.get(b.parentId) : undefined;+ const pa = ca ? ca.position : -1;+ const pb = cb ? cb.position : -1;+ if (pa !== pb) return pa - pb;+ if (a.kind === "category" && b.kind !== "category") return -1;+ if (b.kind === "category" && a.kind !== "category") return 1;+ if (a.position !== b.position) return a.position - b.position;+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;+ });+ return sorted.map((c) => ({+ ...c,+ category: c.parentId ? categories.get(c.parentId)?.name : undefined,+ }));+}++export function parseUser(raw: unknown): OmnidiscUser | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ const username = str(raw.username);+ if (!id || !username) return null;+ const displayName = str(raw.display_name);+ return {+ id,+ username,+ displayName: displayName && displayName.trim().length > 0 ? displayName : username,+ avatar: str(raw.avatar),+ banner: str(raw.banner),+ accentColor: num(raw.accent_color),+ bio: str(raw.bio),+ pronouns: str(raw.pronouns),+ };+}++const RELATIONSHIP_KINDS: RelationshipKind[] = ["friend", "incoming_request", "outgoing_request", "blocked"];++export function parseRelationship(raw: unknown): OmnidiscRelationship | null {+ if (!isRecord(raw)) return null;+ const userId = str(raw.user_id);+ const kind = str(raw.kind);+ if (!userId || !kind) return null;+ const known = RELATIONSHIP_KINDS.find((k) => k === kind);+ if (!known) return null;+ return { userId, kind: known, since: str(raw.since) ?? "" };+}++export function parseSession(raw: unknown): OmnidiscSession | null {+ if (!isRecord(raw)) return null;+ const sessionId = str(raw.session_id);+ if (!sessionId) return null;+ const client = isRecord(raw.client) ? raw.client : {};+ return {+ sessionId,+ client: str(client.client) ?? "",+ deviceName: str(client.device_name),+ lastSeen: str(raw.last_seen) ?? "",+ current: raw.current === true,+ };+}++export function parseBan(raw: unknown): OmnidiscBan | null {+ if (!isRecord(raw)) return null;+ const userId = str(raw.user_id);+ if (!userId) return null;+ return {+ userId,+ bannedBy: str(raw.banned_by) ?? "",+ reason: str(raw.reason),+ createdAt: str(raw.created_at) ?? "",+ };+}++export function parseAuditEntry(raw: unknown): OmnidiscAuditEntry | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ const action = str(raw.action);+ if (!id || !action) return null;+ return {+ id,+ actorId: str(raw.actor_id) ?? "",+ action,+ targetId: str(raw.target_id),+ reason: str(raw.reason),+ createdAt: str(raw.created_at) ?? "",+ };+}++export function emojiKey(raw: unknown): string {+ if (!isRecord(raw)) return "";+ const name = str(raw.name) ?? "";+ const id = str(raw.id);+ return id ? `${name}:${id}` : name;+}++function parseReactions(raw: unknown): OmnidiscReaction[] {+ if (!Array.isArray(raw)) return [];+ const out: OmnidiscReaction[] = [];+ for (const r of raw) {+ if (!isRecord(r)) continue;+ const emoji = emojiKey(r.emoji);+ if (!emoji) continue;+ out.push({ emoji, count: num(r.count) ?? 0, me: r.me === true });+ }+ return out;+}++export function parseAttachment(raw: unknown): OmnidiscAttachment | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ const filename = str(raw.filename);+ if (!id || !filename) return null;+ return {+ id,+ filename,+ size: num(raw.size) ?? 0,+ contentType: str(raw.content_type),+ url: str(raw.url),+ thumbnailUrl: str(raw.thumbnail_url),+ thumbhash: str(raw.thumbhash),+ width: num(raw.width),+ height: num(raw.height),+ durationMs: num(raw.duration_ms),+ encrypted: raw.encrypted === true,+ };+}++export function parseDevice(raw: unknown): OmnidiscDevice | null {+ if (!isRecord(raw)) return null;+ const deviceId = str(raw.device_id);+ if (!deviceId) return null;+ return {+ userId: str(raw.user_id) ?? "",+ deviceId,+ publicKey: str(raw.ed25519_pub) ?? "",+ fingerprint: str(raw.fingerprint),+ name: str(raw.name),+ createdAt: str(raw.created_at) ?? "",+ lastSeenAt: str(raw.last_seen_at) ?? "",+ revokedAt: str(raw.revoked_at),+ };+}++export function parseMessage(raw: unknown, resolveName: (authorId: string) => string): OmnidiscMessage | null {+ if (!isRecord(raw)) return null;+ const id = str(raw.id);+ const channelId = str(raw.channel_id);+ const authorId = str(raw.author_id);+ if (!id || !channelId || !authorId) return null;+ const editedRaw = str(raw.edited_at);+ const editedAt = editedRaw ? Date.parse(editedRaw) : NaN;+ const reference = isRecord(raw.reference) ? str(raw.reference.message_id) : undefined;+ const e2ee = isRecord(raw.e2ee) ? str(raw.e2ee.ciphertext) : undefined;+ const attachments = (Array.isArray(raw.attachments) ? raw.attachments : [])+ .map(parseAttachment)+ .filter((a): a is OmnidiscAttachment => a !== null);+ return {+ id,+ channelId,+ authorId,+ authorName: resolveName(authorId),+ content: str(raw.content) ?? "",+ createdAt: snowflakeTime(id),+ editedAt: Number.isFinite(editedAt) ? editedAt : undefined,+ delivery: "sent",+ replyToId: reference,+ reactions: parseReactions(raw.reactions),+ pinned: raw.pinned === true,+ mentionedUserIds: isRecord(raw.mentions) ? strList(raw.mentions.users) : [],+ mentionsEveryone: isRecord(raw.mentions) ? raw.mentions.everyone === true : false,+ attachments,+ encrypted: e2ee !== undefined,+ ciphertext: e2ee,+ awaitingDecryption: e2ee !== undefined,+ };+}++export interface ReadStateWire {+ channelId: string;+ lastReadId?: string;+ mentionCount: number;+}++export function parseReadState(raw: unknown): ReadStateWire | null {+ if (!isRecord(raw)) return null;+ const channelId = str(raw.channel_id);+ if (!channelId) return null;+ return { channelId, lastReadId: str(raw.last_read_id), mentionCount: num(raw.mention_count) ?? 0 };+}++export interface PresenceWire {+ userId: string;+ status: string;+}++export function parsePresence(raw: unknown): PresenceWire | null {+ if (!isRecord(raw)) return null;+ const userId = str(raw.user_id);+ if (!userId) return null;+ return { userId, status: str(raw.status) ?? "offline" };+}diff --git a/src/lib/stores/omnidisc-store.svelte.ts b/src/lib/stores/omnidisc-store.svelte.tsnew file mode 100644index 00000000..17f7987b--- /dev/null+++ b/src/lib/stores/omnidisc-store.svelte.ts@@ -0,0 +1,2650 @@+import { invoke } from "@tauri-apps/api/core";+import { listen, type UnlistenFn } from "@tauri-apps/api/event";+import type {+ AuthMode,+ NotificationLevel,+ OmnidiscAuditEntry,+ OmnidiscBan,+ OmnidiscRelationship,+ OmnidiscRole,+ OmnidiscSession,+ StreamingPolicy,+ ConnectResult,+ ConnectStep,+ GatewayDispatchEvent,+ GatewayStatusEvent,+ InstanceStatus,+ OmnidiscChannel,+ OmnidiscGuild,+ OmnidiscInstance,+ OmnidiscMember,+ OmnidiscMessage,+ OmnidiscUser,+ ChannelKind,+ OmnidiscAttachment,+ OmnidiscDevice,+ OmnidiscGroupStatus,+ PendingAttachment,+} from "$lib/omnidisc/types";+import {+ DEMO_INSTANCE_ID,+ DEMO_INSTANCE_URL,+ makeFixtureGuilds,+ makeFixtureMembers,+ makeFixtureMessages,+} from "$lib/omnidisc/fixtures";+import {+ channelKindCode,+ emojiKey,+ isRecord,+ parseAuditEntry,+ parseBan,+ parseChannel,+ parseDevice,+ parseGuild,+ parseMessage,+ parsePresence,+ parseReadState,+ parseRelationship,+ parseRole,+ parseSession,+ parseUser,+ str,+ withCategories,+} from "$lib/omnidisc/wire";+import { canIn, resolvePermissions, type PermissionName } from "$lib/omnidisc/permissions";+import { compareSnowflakes, isAfter } from "$lib/omnidisc/snowflake";++const STORAGE_KEY = "omnidisc.instances";+const PAGE_SIZE = 50;+const TYPING_TTL_MS = 5_000;+const TYPING_THROTTLE_MS = 8_000;+const READY_TIMEOUT_MS = 20_000;+const ERR_NO_SESSION = "ERR_NO_SESSION";+const ERR_UNAUTHORIZED = "ERR_UNAUTHORIZED";++type PersistedInstance = Pick<OmnidiscInstance, "id" | "url" | "name"> & { insecure?: boolean };++interface ReadState {+ lastReadId?: string;+ mentionCount: number;+}++export interface VoiceMemberState {+ userId: string;+ channelId: string;+ guildId?: string;+ selfMute: boolean;+ selfDeaf: boolean;+ serverMute: boolean;+ serverDeaf: boolean;+ streaming: boolean;+}++interface PendingConnect {+ url: string;+ name: string;+ invite?: string;+ registrationOpen: boolean;+ streaming?: StreamingPolicy;+ insecure: boolean;+}++/// Same rule the backend applies in `omnidisc_connect`: plain http is only+/// harmless on loopback, where the traffic never reaches a network.+export function isInsecureInstanceUrl(url: string): boolean {+ try {+ const parsed = new URL(url);+ if (parsed.protocol !== "http:") return false;+ return !["localhost", "127.0.0.1", "[::1]", "::1"].includes(parsed.hostname);+ } catch {+ return true;+ }+}++let instances = $state<OmnidiscInstance[]>([]);+let loaded = false;+let initialized = false;++let selectedInstanceId = $state<string | null>(null);+let selectedGuildId = $state<string | null>(null);+let selectedChannelId = $state<string | null>(null);+let memberListOpen = $state(true);++let drafts = $state<Record<string, string>>({});+let guildsByInstance = $state<Record<string, OmnidiscGuild[]>>({});+let dmsByInstance = $state<Record<string, OmnidiscChannel[]>>({});+let usersByInstance = $state<Record<string, Record<string, OmnidiscUser>>>({});+let presenceByInstance = $state<Record<string, Record<string, string>>>({});+let membersByGuild = $state<Record<string, OmnidiscMember[]>>({});+let messagesByChannel = $state<Record<string, OmnidiscMessage[]>>({});+let readStateByChannel = $state<Record<string, ReadState>>({});+let lastMessageIdByChannel = $state<Record<string, string>>({});+let typingByChannel = $state<Record<string, Record<string, number>>>({});+let voiceStatesByChannel = $state<Record<string, Record<string, VoiceMemberState>>>({});+let voiceChannelByUser: Record<string, string> = {};+let loadingByChannel = $state<Record<string, boolean>>({});+let hasMoreByChannel: Record<string, boolean> = {};+let loadedChannels = new Set<string>();+let oldestSeqByChannel: Record<string, number> = {};+let channelInstance: Record<string, string> = {};+let channelGuild: Record<string, string> = {};+let userFetchInFlight = new Set<string>();+let typingSentAt: Record<string, number> = {};+let typingTimers: Record<string, ReturnType<typeof setTimeout>> = {};+let ackedByChannel: Record<string, string> = {};+let readyWaiters: Record<string, { resolve: () => void; reject: (e: string) => void }[]> = {};++let relationshipsByInstance = $state<Record<string, OmnidiscRelationship[]>>({});+let notesByInstance = $state<Record<string, Record<string, string>>>({});+let pinsByChannel = $state<Record<string, OmnidiscMessage[]>>({});+let ownPresenceByInstance = $state<Record<string, string>>({});+let notificationLevels = $state<Record<string, NotificationLevel>>({});+let localUnread = $state<Record<string, string>>({});+let notifyPrefsLoaded = false;++let connectStep = $state<ConnectStep>("idle");+let connectError = $state<string | null>(null);+let connectedInstance = $state<OmnidiscInstance | null>(null);+let pendingConnect = $state<PendingConnect | null>(null);++function hasStorage(): boolean {+ return typeof localStorage !== "undefined";+}++function persist() {+ if (!hasStorage()) return;+ const slim: PersistedInstance[] = instances+ .filter((i) => i.id !== DEMO_INSTANCE_ID)+ .map(({ id, url, name, insecure }) => ({ id, url, name, insecure }));+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(slim));+ } catch {+ return;+ }+}++function ensureLoaded() {+ if (loaded) return;+ loaded = true;+ if (!hasStorage()) return;+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (!raw) return;+ const parsed: unknown = JSON.parse(raw);+ if (!Array.isArray(parsed)) return;+ instances = parsed+ .filter(+ (p): p is PersistedInstance =>+ typeof p === "object" && p !== null && typeof p.id === "string" && typeof p.url === "string" && typeof p.name === "string",+ )+ .map((p) => ({+ id: p.id,+ url: p.url,+ name: p.name,+ status: "disconnected" as InstanceStatus,+ insecure: p.insecure ?? isInsecureInstanceUrl(p.url),+ }));+ if (instances.length > 0 && !selectedInstanceId) {+ selectedInstanceId = instances[0].id;+ }+ } catch {+ instances = [];+ }+}++function makeId(): string {+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {+ return crypto.randomUUID();+ }+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+}++function errorText(e: unknown): string {+ return typeof e === "string" ? e : e instanceof Error ? e.message : String(e);+}++function isDemo(instanceId: string | null | undefined): boolean {+ return import.meta.env.DEV && instanceId === DEMO_INSTANCE_ID;+}++function instanceByUrl(url: string): OmnidiscInstance | null {+ return instances.find((i) => i.url === url) ?? null;+}++function instanceForChannel(channelId: string): OmnidiscInstance | null {+ const id = channelInstance[channelId];+ if (!id) return null;+ return instances.find((i) => i.id === id) ?? null;+}++function seedDemoData(instanceId: string) {+ const guilds = makeFixtureGuilds(instanceId);+ guildsByInstance = { ...guildsByInstance, [instanceId]: guilds };+ const members = makeFixtureMembers();+ const nextMembers = { ...membersByGuild };+ const nextMessages = { ...messagesByChannel };+ const now = Date.now();+ for (const guild of guilds) {+ nextMembers[guild.id] = members;+ for (const channel of guild.channels) {+ channelInstance[channel.id] = instanceId;+ channelGuild[channel.id] = guild.id;+ if (channel.kind !== "text") continue;+ const count = channel.id === "c-general" ? 200 : 40;+ nextMessages[channel.id] = makeFixtureMessages(channel.id, count, now, 1000);+ oldestSeqByChannel[channel.id] = 1000;+ loadedChannels.add(channel.id);+ }+ }+ membersByGuild = nextMembers;+ messagesByChannel = nextMessages;+}++export function getInstances(): OmnidiscInstance[] {+ ensureLoaded();+ return instances;+}++export function hasInstances(): boolean {+ ensureLoaded();+ return instances.length > 0;+}++export function getSelectedInstance(): OmnidiscInstance | null {+ ensureLoaded();+ return instances.find((i) => i.id === selectedInstanceId) ?? null;+}++export function getInstanceStreamingPolicy(id: string | null): StreamingPolicy | null {+ return getInstance(id)?.streaming ?? null;+}++export function getInstance(id: string | null): OmnidiscInstance | null {+ if (!id) return null;+ return instances.find((i) => i.id === id) ?? null;+}++export function selectInstance(id: string | null) {+ ensureLoaded();+ selectedInstanceId = id;+ selectedGuildId = null;+ selectedChannelId = null;+}++export function addInstance(input: {+ url: string;+ name: string;+ status?: InstanceStatus;+ id?: string;+ streaming?: StreamingPolicy;+ insecure?: boolean;+}): OmnidiscInstance {+ ensureLoaded();+ const insecure = input.insecure ?? isInsecureInstanceUrl(input.url);+ const existing = instances.find((i) => i.url === input.url);+ if (existing) {+ existing.name = input.name || existing.name;+ existing.status = input.status ?? existing.status;+ if (input.streaming) existing.streaming = input.streaming;+ existing.insecure = insecure;+ persist();+ return existing;+ }+ const instance: OmnidiscInstance = {+ id: input.id ?? makeId(),+ url: input.url,+ name: input.name || input.url,+ status: input.status ?? "disconnected",+ streaming: input.streaming,+ insecure,+ };+ instances = [...instances, instance];+ if (!selectedInstanceId) selectedInstanceId = instance.id;+ persist();+ return instance;+}++function clearInstanceData(instanceId: string) {+ const guilds = guildsByInstance[instanceId] ?? [];+ const nextMessages = { ...messagesByChannel };+ const nextMembers = { ...membersByGuild };+ for (const guild of guilds) {+ delete nextMembers[guild.id];+ for (const channel of guild.channels) {+ delete nextMessages[channel.id];+ delete channelInstance[channel.id];+ delete channelGuild[channel.id];+ loadedChannels.delete(channel.id);+ }+ }+ for (const dm of dmsByInstance[instanceId] ?? []) {+ delete nextMessages[dm.id];+ delete channelInstance[dm.id];+ loadedChannels.delete(dm.id);+ }+ messagesByChannel = nextMessages;+ membersByGuild = nextMembers;+ const nextGuilds = { ...guildsByInstance };+ delete nextGuilds[instanceId];+ guildsByInstance = nextGuilds;+ const nextDms = { ...dmsByInstance };+ delete nextDms[instanceId];+ dmsByInstance = nextDms;+ const nextUsers = { ...usersByInstance };+ delete nextUsers[instanceId];+ usersByInstance = nextUsers;+ const nextPresence = { ...presenceByInstance };+ delete nextPresence[instanceId];+ presenceByInstance = nextPresence;+ clearVoiceStates(instanceId);+}++export function removeInstance(id: string) {+ ensureLoaded();+ const instance = instances.find((i) => i.id === id);+ clearInstanceData(id);+ instances = instances.filter((i) => i.id !== id);+ if (selectedInstanceId === id) {+ selectedInstanceId = instances[0]?.id ?? null;+ selectedGuildId = null;+ selectedChannelId = null;+ }+ persist();+ if (instance && !isDemo(id)) {+ void forgetRemote(instance.url);+ }+}++async function forgetRemote(url: string) {+ try {+ await invoke("omnidisc_gateway_disconnect", { url });+ await invoke("omnidisc_logout", { url });+ } catch (e) {+ console.warn("[omnidisc] could not sign out of", url, errorText(e));+ }+}++export async function signOut(id: string) {+ const instance = instances.find((i) => i.id === id);+ if (!instance || isDemo(id)) return;+ try {+ await invoke("omnidisc_logout", { url: instance.url });+ } catch {+ // token is dropped locally even if the server did not answer+ }+ clearInstanceData(id);+ setInstanceStatus(id, "signed_out");+}++export function setInstanceStatus(id: string, status: InstanceStatus, error?: string) {+ const instance = instances.find((i) => i.id === id);+ if (!instance) return;+ instance.status = status;+ instance.error = status === "error" || status === "signed_out" ? error : undefined;+}++export function getGuilds(instanceId: string | null): OmnidiscGuild[] {+ if (!instanceId) return [];+ return guildsByInstance[instanceId] ?? [];+}++export function getGuild(guildId: string | null): OmnidiscGuild | null {+ if (!guildId) return null;+ for (const list of Object.values(guildsByInstance)) {+ const found = list.find((g) => g.id === guildId);+ if (found) return found;+ }+ return null;+}++export function getDms(instanceId: string | null): OmnidiscChannel[] {+ if (!instanceId) return [];+ return dmsByInstance[instanceId] ?? [];+}++export function getChannel(channelId: string | null): OmnidiscChannel | null {+ if (!channelId) return null;+ const guildId = channelGuild[channelId];+ if (guildId) {+ return getGuild(guildId)?.channels.find((c) => c.id === channelId) ?? null;+ }+ const instanceId = channelInstance[channelId];+ if (!instanceId) return null;+ return (dmsByInstance[instanceId] ?? []).find((c) => c.id === channelId) ?? null;+}++export function getUser(instanceId: string | null, userId: string | null): OmnidiscUser | null {+ if (!instanceId || !userId) return null;+ return usersByInstance[instanceId]?.[userId] ?? null;+}++export function getPresence(instanceId: string | null, userId: string | null): string {+ if (!instanceId || !userId) return "offline";+ return presenceByInstance[instanceId]?.[userId] ?? "offline";+}++export function getMe(instanceId: string | null): OmnidiscUser | null {+ const instance = getInstance(instanceId);+ if (!instance?.userId) return null;+ return getUser(instance.id, instance.userId);+}++export function getChannelInstanceId(channelId: string | null): string | null {+ if (!channelId) return null;+ const guildId = channelGuild[channelId];+ if (guildId) return getGuild(guildId)?.instanceId ?? null;+ return channelInstance[channelId] ?? null;+}++export function userName(instanceId: string, userId: string): string {+ const user = usersByInstance[instanceId]?.[userId];+ if (user) return user.displayName;+ if (!isDemo(instanceId)) void ensureUser(instanceId, userId);+ return "…";+}++export function dmTitle(channel: OmnidiscChannel): string {+ const instanceId = channelInstance[channel.id];+ const instance = getInstance(instanceId ?? null);+ if (!instanceId || !instance) return channel.name || channel.id;+ if (channel.name) return channel.name;+ const others = (channel.recipientIds ?? []).filter((r) => r !== instance.userId);+ if (others.length === 0) return userName(instanceId, instance.userId ?? "");+ return others.map((r) => userName(instanceId, r)).join(", ");+}++async function ensureUser(instanceId: string, userId: string) {+ const key = `${instanceId}:${userId}`;+ if (userFetchInFlight.has(key)) return;+ const instance = getInstance(instanceId);+ if (!instance) return;+ userFetchInFlight.add(key);+ try {+ const raw = await invoke<unknown>("omnidisc_get_user", { url: instance.url, userId });+ const user = parseUser(raw);+ if (user) upsertUser(instanceId, user);+ } catch {+ // name stays as a placeholder; the next render retries when the user reappears+ } finally {+ userFetchInFlight.delete(key);+ }+}++function upsertUser(instanceId: string, user: OmnidiscUser) {+ const current = usersByInstance[instanceId] ?? {};+ usersByInstance = { ...usersByInstance, [instanceId]: { ...current, [user.id]: user } };+}++function setPresence(instanceId: string, userId: string, status: string) {+ const current = presenceByInstance[instanceId] ?? {};+ presenceByInstance = { ...presenceByInstance, [instanceId]: { ...current, [userId]: status } };+}++export function getMembers(guildId: string | null): OmnidiscMember[] {+ if (!guildId) return [];+ const guild = getGuild(guildId);+ const base = membersByGuild[guildId] ?? [];+ if (!guild || isDemo(guild.instanceId)) return base;+ const presence = presenceByInstance[guild.instanceId] ?? {};+ const users = usersByInstance[guild.instanceId] ?? {};+ return base.map((m) => ({+ ...m,+ name: users[m.id]?.displayName ?? m.name,+ online: m.id === getInstance(guild.instanceId)?.userId ? true : (presence[m.id] ?? "offline") !== "offline",+ }));+}++export function getMessages(channelId: string | null): OmnidiscMessage[] {+ if (!channelId) return [];+ const list = messagesByChannel[channelId] ?? [];+ const instanceId = channelInstance[channelId];+ if (!instanceId || isDemo(instanceId)) return list;+ const users = usersByInstance[instanceId] ?? {};+ return list.map((m) => {+ const user = users[m.authorId];+ if (!user) return m.authorName === "…" ? m : { ...m, authorName: m.authorName };+ return user.displayName === m.authorName ? m : { ...m, authorName: user.displayName };+ });+}++export function isChannelLoading(channelId: string | null): boolean {+ return channelId ? (loadingByChannel[channelId] ?? false) : false;+}++export function getTypingNames(channelId: string | null): string[] {+ if (!channelId) return [];+ const instanceId = channelInstance[channelId];+ const instance = getInstance(instanceId ?? null);+ if (!instanceId || !instance) return [];+ const now = Date.now();+ return Object.entries(typingByChannel[channelId] ?? {})+ .filter(([userId, until]) => until > now && userId !== instance.userId)+ .map(([userId]) => userName(instanceId, userId));+}++export function getSelectedGuildId(): string | null {+ return selectedGuildId;+}++export function getSelectedChannelId(): string | null {+ return selectedChannelId;+}++export function selectChannel(guildId: string | null, channelId: string | null) {+ ensureLoaded();+ if (selectedChannelId && selectedChannelId !== channelId) {+ delete suppressAck[selectedChannelId];+ clearUnreadMark(selectedChannelId);+ }+ const guild = getGuild(guildId);+ if (guild && guild.instanceId !== selectedInstanceId) {+ selectedInstanceId = guild.instanceId;+ }+ if (!guild && channelId) {+ const instanceId = channelInstance[channelId];+ if (instanceId && instanceId !== selectedInstanceId) selectedInstanceId = instanceId;+ }+ selectedGuildId = guildId;+ selectedChannelId = channelId;+ if (channelId) {+ void ensureChannelLoaded(channelId);+ void ackChannel(channelId);+ if (guildId) void requestMembers(guildId, channelId);+ }+}++export function isMemberListOpen(): boolean {+ return memberListOpen;+}++export function toggleMemberList() {+ memberListOpen = !memberListOpen;+}++export function getDraft(key: string): string {+ return drafts[key] ?? "";+}++export function setDraft(key: string, text: string) {+ if (text.length === 0) {+ if (key in drafts) {+ const next = { ...drafts };+ delete next[key];+ drafts = next;+ }+ return;+ }+ drafts = { ...drafts, [key]: text };+}++export function isUnread(channelId: string): boolean {+ const last = lastMessageIdByChannel[channelId];+ if (!last) return false;+ return isAfter(last, readStateByChannel[channelId]?.lastReadId);+}++export function getMentionCount(channelId: string): number {+ return readStateByChannel[channelId]?.mentionCount ?? 0;+}++export function getUnreadCount(): number {+ let count = 0;+ for (const channelId of Object.keys(lastMessageIdByChannel)) {+ if (channelId === selectedChannelId) continue;+ const channel = getChannel(channelId);+ if (!channel || channel.kind === "voice" || channel.kind === "category") continue;+ if (isUnread(channelId)) count += 1;+ }+ return count;+}++export function getVoiceMembers(channelId: string | null): VoiceMemberState[] {+ if (!channelId) return [];+ return Object.values(voiceStatesByChannel[channelId] ?? {});+}++export function getVoiceMemberCount(channelId: string): number {+ return Object.keys(voiceStatesByChannel[channelId] ?? {}).length;+}++export function getVoiceChannelOfUser(instanceId: string | null, userId: string | null): string | null {+ if (!instanceId || !userId) return null;+ return voiceChannelByUser[`${instanceId}:${userId}`] ?? null;+}++export function applyVoiceState(instanceId: string, raw: unknown) {+ if (!isRecord(raw)) return;+ const userId = str(raw.user_id);+ if (!userId) return;+ const key = `${instanceId}:${userId}`;+ const channelId = str(raw.channel_id);+ const previous = voiceChannelByUser[key];+ const next = { ...voiceStatesByChannel };+ if (previous && previous !== channelId && next[previous]) {+ const rest = { ...next[previous] };+ delete rest[userId];+ if (Object.keys(rest).length === 0) delete next[previous];+ else next[previous] = rest;+ }+ if (channelId) {+ voiceChannelByUser[key] = channelId;+ next[channelId] = {+ ...(next[channelId] ?? {}),+ [userId]: {+ userId,+ channelId,+ guildId: str(raw.guild_id),+ selfMute: raw.self_mute === true,+ selfDeaf: raw.self_deaf === true,+ serverMute: raw.server_mute === true,+ serverDeaf: raw.server_deaf === true,+ streaming: raw.streaming === true,+ },+ };+ if (!usersByInstance[instanceId]?.[userId] && !isDemo(instanceId)) void ensureUser(instanceId, userId);+ } else {+ delete voiceChannelByUser[key];+ }+ voiceStatesByChannel = next;+}++function clearVoiceStates(instanceId: string) {+ const prefix = `${instanceId}:`;+ const gone = new Set<string>();+ for (const key of Object.keys(voiceChannelByUser)) {+ if (key.startsWith(prefix)) {+ gone.add(key.slice(prefix.length));+ delete voiceChannelByUser[key];+ }+ }+ if (gone.size === 0) return;+ const next: Record<string, Record<string, VoiceMemberState>> = {};+ for (const [channelId, members] of Object.entries(voiceStatesByChannel)) {+ const kept = Object.fromEntries(Object.entries(members).filter(([uid]) => !gone.has(uid)));+ if (Object.keys(kept).length > 0) next[channelId] = kept;+ }+ voiceStatesByChannel = next;+}++function sortMessages(list: OmnidiscMessage[]): OmnidiscMessage[] {+ return [...list].sort((a, b) => {+ if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;+ if (a.delivery !== "sent" && b.delivery === "sent") return 1;+ if (b.delivery !== "sent" && a.delivery === "sent") return -1;+ return compareSnowflakes(a.id, b.id);+ });+}++function upsertMessage(message: OmnidiscMessage) {+ const current = messagesByChannel[message.channelId] ?? [];+ const idx = current.findIndex((m) => m.id === message.id);+ const next = idx >= 0 ? current.map((m, i) => (i === idx ? message : m)) : sortMessages([...current, message]);+ messagesByChannel = { ...messagesByChannel, [message.channelId]: next };+}++function removeMessage(channelId: string, messageId: string) {+ const current = messagesByChannel[channelId];+ if (!current) return;+ messagesByChannel = { ...messagesByChannel, [channelId]: current.filter((m) => m.id !== messageId) };+}++function bumpLastMessage(channelId: string, messageId: string) {+ if (isAfter(messageId, lastMessageIdByChannel[channelId])) {+ lastMessageIdByChannel = { ...lastMessageIdByChannel, [channelId]: messageId };+ }+}++function setReadState(channelId: string, state: ReadState) {+ readStateByChannel = { ...readStateByChannel, [channelId]: state };+}++function nameResolver(instanceId: string): (authorId: string) => string {+ const users = usersByInstance[instanceId] ?? {};+ return (authorId) => users[authorId]?.displayName ?? "…";+}++export async function ensureChannelLoaded(channelId: string) {+ if (loadedChannels.has(channelId)) return;+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ loadedChannels.add(channelId);+ loadingByChannel = { ...loadingByChannel, [channelId]: true };+ try {+ const raw = await invoke<unknown>("omnidisc_list_messages", { url: instance.url, channelId, limit: PAGE_SIZE });+ const list = Array.isArray(raw) ? raw : [];+ const resolve = nameResolver(instance.id);+ const parsed = list+ .map((m) => parseMessage(m, resolve))+ .filter((m): m is OmnidiscMessage => m !== null);+ hasMoreByChannel[channelId] = list.length >= PAGE_SIZE;+ const pending = (messagesByChannel[channelId] ?? []).filter((m) => m.delivery !== "sent");+ messagesByChannel = { ...messagesByChannel, [channelId]: sortMessages([...parsed, ...pending]) };+ for (const m of parsed) {+ bumpLastMessage(channelId, m.id);+ if (!usersByInstance[instance.id]?.[m.authorId]) void ensureUser(instance.id, m.authorId);+ }+ void hydrateEncrypted(channelId);+ void refreshGroupStatus(channelId);+ } catch (e) {+ loadedChannels.delete(channelId);+ console.warn("[omnidisc] could not load messages", errorText(e));+ } finally {+ const next = { ...loadingByChannel };+ delete next[channelId];+ loadingByChannel = next;+ }+}++export async function loadOlderMessages(channelId: string, count = PAGE_SIZE): Promise<number> {+ const current = messagesByChannel[channelId] ?? [];+ const instance = instanceForChannel(channelId);+ if (instance && isDemo(instance.id)) {+ const oldestSeq = oldestSeqByChannel[channelId];+ if (oldestSeq === undefined || oldestSeq <= 0) return 0;+ const endAt = (current[0]?.createdAt ?? Date.now()) - 60_000;+ const startSeq = Math.max(0, oldestSeq - count);+ const older = makeFixtureMessages(channelId, oldestSeq - startSeq, endAt, startSeq);+ oldestSeqByChannel[channelId] = startSeq;+ messagesByChannel = { ...messagesByChannel, [channelId]: [...older, ...current] };+ return older.length;+ }+ if (!instance || hasMoreByChannel[channelId] === false || loadingByChannel[channelId]) return 0;+ const oldest = current.find((m) => m.delivery === "sent");+ if (!oldest) return 0;+ loadingByChannel = { ...loadingByChannel, [channelId]: true };+ try {+ const raw = await invoke<unknown>("omnidisc_list_messages", {+ url: instance.url,+ channelId,+ before: oldest.id,+ limit: count,+ });+ const list = Array.isArray(raw) ? raw : [];+ const resolve = nameResolver(instance.id);+ const parsed = list.map((m) => parseMessage(m, resolve)).filter((m): m is OmnidiscMessage => m !== null);+ hasMoreByChannel[channelId] = list.length >= count;+ const known = new Set((messagesByChannel[channelId] ?? []).map((m) => m.id));+ const fresh = parsed.filter((m) => !known.has(m.id));+ messagesByChannel = {+ ...messagesByChannel,+ [channelId]: sortMessages([...fresh, ...(messagesByChannel[channelId] ?? [])]),+ };+ for (const m of fresh) {+ if (!usersByInstance[instance.id]?.[m.authorId]) void ensureUser(instance.id, m.authorId);+ }+ void hydrateEncrypted(channelId);+ return fresh.length;+ } catch (e) {+ console.warn("[omnidisc] could not load older messages", errorText(e));+ return 0;+ } finally {+ const next = { ...loadingByChannel };+ delete next[channelId];+ loadingByChannel = next;+ }+}++export function hasUploadsInFlight(channelId: string): boolean {+ return (uploadsByChannel[channelId] ?? []).some((u) => u.state !== "done" && u.state !== "failed");+}++export async function sendMessage(channelId: string, content: string, replyTo?: string): Promise<void> {+ const instance = instanceForChannel(channelId);+ const text = content.trim();+ const ready = (uploadsByChannel[channelId] ?? []).filter((u) => u.state === "done");+ if (!text && ready.length === 0) return;+ if (hasUploadsInFlight(channelId)) return;+ if (!instance || isDemo(instance.id)) {+ if (text) appendLocalMessage(channelId, text, { id: instance?.userId ?? "me", name: "You" });+ return;+ }+ const me = instance.userId ?? "me";+ const pendingId = `pending:${makeId()}`;+ const attachments: OmnidiscAttachment[] = ready.map((u) => ({+ id: u.id,+ filename: u.name,+ size: u.total,+ contentType: u.mime,+ url: u.previewUrl,+ encrypted: u.encrypted,+ }));+ const optimistic: OmnidiscMessage = {+ id: pendingId,+ channelId,+ authorId: me,+ authorName: getMe(instance.id)?.displayName ?? "…",+ content: text,+ createdAt: Date.now(),+ delivery: "pending",+ replyToId: replyTo,+ attachments,+ encrypted: isEncryptedChannel(channelId),+ };+ const uploadIds = ready.map((u) => u.id);+ clearUploads(channelId);+ upsertMessage(optimistic);+ await deliver(instance, optimistic, uploadIds);+}++const uploadsOfPending: Record<string, string[]> = {};++async function deliver(instance: OmnidiscInstance, optimistic: OmnidiscMessage, uploadIds: string[]) {+ uploadsOfPending[optimistic.id] = uploadIds;+ const channel = getChannel(optimistic.channelId);+ const encrypted = isEncryptedChannel(optimistic.channelId);+ try {+ const raw = await invoke<unknown>("omnidisc_send_message", {+ url: instance.url,+ channelId: optimistic.channelId,+ content: optimistic.content,+ nonce: optimistic.id,+ replyTo: optimistic.replyToId ?? null,+ uploadIds,+ encrypted,+ recipientIds: (channel?.recipientIds ?? []).filter((id) => id !== instance.userId),+ });+ const sent = parseMessage(raw, nameResolver(instance.id));+ removeMessage(optimistic.channelId, optimistic.id);+ delete uploadsOfPending[optimistic.id];+ if (sent) {+ // We wrote the plaintext, so there is nothing to wait for on our own copy.+ const settled: OmnidiscMessage = sent.encrypted+ ? { ...sent, content: optimistic.content, attachments: optimistic.attachments, awaitingDecryption: false }+ : sent;+ upsertMessage(settled);+ bumpLastMessage(settled.channelId, settled.id);+ ackedByChannel[settled.channelId] = settled.id;+ setReadState(settled.channelId, { lastReadId: settled.id, mentionCount: 0 });+ if (encrypted) void refreshGroupStatus(settled.channelId);+ }+ } catch (e) {+ upsertMessage({ ...optimistic, delivery: "failed", error: errorText(e) });+ }+}++export async function retryMessage(channelId: string, messageId: string) {+ const instance = instanceForChannel(channelId);+ const current = (messagesByChannel[channelId] ?? []).find((m) => m.id === messageId);+ if (!instance || !current || current.delivery !== "failed") return;+ upsertMessage({ ...current, delivery: "pending", error: undefined });+ await deliver(instance, { ...current, delivery: "pending", error: undefined }, uploadsOfPending[messageId] ?? []);+}++export function discardMessage(channelId: string, messageId: string) {+ removeMessage(channelId, messageId);+}++export function appendLocalMessage(channelId: string, content: string, author: { id: string; name: string }) {+ const message: OmnidiscMessage = {+ id: `${channelId}-local-${makeId()}`,+ channelId,+ authorId: author.id,+ authorName: author.name,+ content,+ createdAt: Date.now(),+ delivery: "sent",+ };+ messagesByChannel = { ...messagesByChannel, [channelId]: [...(messagesByChannel[channelId] ?? []), message] };+}++export async function editMessage(channelId: string, messageId: string, content: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ const raw = await invoke<unknown>("omnidisc_edit_message", { url: instance.url, channelId, messageId, content });+ const parsed = parseMessage(raw, nameResolver(instance.id));+ if (parsed) upsertMessage(parsed);+}++export async function deleteMessage(channelId: string, messageId: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) {+ removeMessage(channelId, messageId);+ return;+ }+ await invoke("omnidisc_delete_message", { url: instance.url, channelId, messageId });+ removeMessage(channelId, messageId);+}++export async function toggleReaction(channelId: string, messageId: string, emoji: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ const message = (messagesByChannel[channelId] ?? []).find((m) => m.id === messageId);+ const mine = message?.reactions?.find((r) => r.emoji === emoji)?.me ?? false;+ const command = mine ? "omnidisc_remove_reaction" : "omnidisc_add_reaction";+ await invoke(command, { url: instance.url, channelId, messageId, emoji: emoji.split(":")[0] });+}++export function notifyTyping(channelId: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id) || instance.status !== "connected") return;+ const now = Date.now();+ if (now - (typingSentAt[channelId] ?? 0) < TYPING_THROTTLE_MS) return;+ typingSentAt[channelId] = now;+ invoke("omnidisc_typing", { url: instance.url, channelId }).catch(() => {+ typingSentAt[channelId] = 0;+ });+}++async function ackChannel(channelId: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ if (suppressAck[channelId]) return;+ const last = lastMessageIdByChannel[channelId];+ if (!last) return;+ const read = readStateByChannel[channelId]?.lastReadId;+ if (!isAfter(last, read)) return;+ if (ackedByChannel[channelId] === last) return;+ ackedByChannel[channelId] = last;+ setReadState(channelId, { lastReadId: last, mentionCount: 0 });+ try {+ await invoke("omnidisc_ack", { url: instance.url, channelId, messageId: last });+ } catch {+ delete ackedByChannel[channelId];+ }+}++async function requestMembers(guildId: string, channelId: string) {+ const guild = getGuild(guildId);+ const instance = guild ? getInstance(guild.instanceId) : null;+ if (!guild || !instance || isDemo(instance.id) || instance.status !== "connected") return;+ try {+ await invoke("omnidisc_gateway_send", {+ url: instance.url,+ op: 14,+ d: { guild_id: guildId, channel_id: channelId, ranges: [[0, 99]] },+ });+ } catch {+ // member list stays as it was; nothing to show the user beyond the existing list+ }+}++function registerChannels(instanceId: string, guildId: string | null, channels: OmnidiscChannel[]) {+ for (const channel of channels) {+ channelInstance[channel.id] = instanceId;+ if (guildId) channelGuild[channel.id] = guildId;+ else delete channelGuild[channel.id];+ if (channel.lastMessageId) bumpLastMessage(channel.id, channel.lastMessageId);+ }+}++function upsertGuild(instanceId: string, guild: OmnidiscGuild) {+ const list = guildsByInstance[instanceId] ?? [];+ const idx = list.findIndex((g) => g.id === guild.id);+ const next = idx >= 0 ? list.map((g, i) => (i === idx ? guild : g)) : [...list, guild];+ guildsByInstance = { ...guildsByInstance, [instanceId]: next };+ registerChannels(instanceId, guild.id, guild.channels);+}++function removeGuild(instanceId: string, guildId: string) {+ const list = guildsByInstance[instanceId] ?? [];+ const guild = list.find((g) => g.id === guildId);+ if (guild) {+ for (const c of guild.channels) {+ delete channelInstance[c.id];+ delete channelGuild[c.id];+ }+ }+ guildsByInstance = { ...guildsByInstance, [instanceId]: list.filter((g) => g.id !== guildId) };+ const nextMembers = { ...membersByGuild };+ delete nextMembers[guildId];+ membersByGuild = nextMembers;+ if (selectedGuildId === guildId) {+ selectedGuildId = null;+ selectedChannelId = null;+ }+}++function upsertGuildChannel(instanceId: string, channel: OmnidiscChannel) {+ const guildId = channel.guildId;+ if (!guildId) return;+ const list = guildsByInstance[instanceId] ?? [];+ const guild = list.find((g) => g.id === guildId);+ if (!guild) return;+ const rest = guild.channels.filter((c) => c.id !== channel.id);+ const updated: OmnidiscGuild = { ...guild, channels: withCategories([...rest, channel]) };+ upsertGuild(instanceId, updated);+}++function removeChannel(instanceId: string, channelId: string) {+ const guildId = channelGuild[channelId];+ if (guildId) {+ const guild = (guildsByInstance[instanceId] ?? []).find((g) => g.id === guildId);+ if (guild) {+ upsertGuild(instanceId, { ...guild, channels: guild.channels.filter((c) => c.id !== channelId) });+ }+ } else {+ dmsByInstance = { ...dmsByInstance, [instanceId]: (dmsByInstance[instanceId] ?? []).filter((c) => c.id !== channelId) };+ }+ delete channelInstance[channelId];+ delete channelGuild[channelId];+ if (selectedChannelId === channelId) selectedChannelId = null;+}++function upsertDm(instanceId: string, channel: OmnidiscChannel) {+ const list = dmsByInstance[instanceId] ?? [];+ const idx = list.findIndex((c) => c.id === channel.id);+ const next = idx >= 0 ? list.map((c, i) => (i === idx ? channel : c)) : [channel, ...list];+ dmsByInstance = { ...dmsByInstance, [instanceId]: next };+ registerChannels(instanceId, null, [channel]);+ for (const r of channel.recipientIds ?? []) {+ if (!usersByInstance[instanceId]?.[r]) void ensureUser(instanceId, r);+ }+}++function applyReady(instance: OmnidiscInstance, d: unknown) {+ if (!isRecord(d)) return;+ const me = parseUser(d.user);+ if (me) {+ instance.userId = me.id;+ upsertUser(instance.id, me);+ }+ const guilds = (Array.isArray(d.guilds) ? d.guilds : [])+ .map((g) => parseGuild(g, instance.id))+ .filter((g): g is OmnidiscGuild => g !== null);+ guildsByInstance = { ...guildsByInstance, [instance.id]: guilds };+ for (const g of guilds) registerChannels(instance.id, g.id, g.channels);+ const dms = (Array.isArray(d.private_channels) ? d.private_channels : [])+ .map(parseChannel)+ .filter((c): c is OmnidiscChannel => c !== null);+ dmsByInstance = { ...dmsByInstance, [instance.id]: dms };+ registerChannels(instance.id, null, dms);+ for (const dm of dms) {+ for (const r of dm.recipientIds ?? []) {+ if (!usersByInstance[instance.id]?.[r]) void ensureUser(instance.id, r);+ }+ }+ const relationships = (Array.isArray(d.relationships) ? d.relationships : [])+ .map(parseRelationship)+ .filter((r): r is OmnidiscRelationship => r !== null);+ relationshipsByInstance = { ...relationshipsByInstance, [instance.id]: relationships };+ for (const rel of relationships) {+ if (!usersByInstance[instance.id]?.[rel.userId]) void ensureUser(instance.id, rel.userId);+ }+ for (const rs of Array.isArray(d.read_states) ? d.read_states : []) {+ const parsed = parseReadState(rs);+ if (parsed) setReadState(parsed.channelId, { lastReadId: parsed.lastReadId, mentionCount: parsed.mentionCount });+ }+ const presences: Record<string, string> = {};+ for (const p of Array.isArray(d.presences) ? d.presences : []) {+ const parsed = parsePresence(p);+ if (parsed) presences[parsed.userId] = parsed.status;+ }+ if (me) presences[me.id] = "online";+ presenceByInstance = { ...presenceByInstance, [instance.id]: presences };+ clearVoiceStates(instance.id);+ for (const vs of Array.isArray(d.voice_states) ? d.voice_states : []) applyVoiceState(instance.id, vs);+ loadedChannels = new Set([...loadedChannels].filter((id) => channelInstance[id] !== instance.id));+ if (selectedChannelId && channelInstance[selectedChannelId] === instance.id) {+ void ensureChannelLoaded(selectedChannelId);+ if (selectedGuildId) void requestMembers(selectedGuildId, selectedChannelId);+ }+}++function applyMemberList(instanceId: string, d: unknown) {+ if (!isRecord(d)) return;+ const guildId = str(d.guild_id);+ if (!guildId) return;+ const guild = getGuild(guildId);+ const members: OmnidiscMember[] = [];+ for (const op of Array.isArray(d.ops) ? d.ops : []) {+ if (!isRecord(op) || op.op !== "sync") continue;+ for (const item of Array.isArray(op.items) ? op.items : []) {+ if (!isRecord(item) || item.kind !== "member") continue;+ const user = parseUser(item.user);+ if (!user) continue;+ upsertUser(instanceId, user);+ const presence = parsePresence(item.presence);+ if (presence) setPresence(instanceId, presence.userId, presence.status);+ const memberRaw = isRecord(item.member) ? item.member : {};+ members.push({+ id: user.id,+ name: str(memberRaw.nick) ?? user.displayName,+ online: presence ? presence.status !== "offline" : false,+ role: guild?.ownerId === user.id ? "owner" : undefined,+ nick: str(memberRaw.nick),+ roleIds: Array.isArray(memberRaw.role_ids)+ ? memberRaw.role_ids.filter((r): r is string => typeof r === "string")+ : [],+ mutedUntil: str(memberRaw.muted_until),+ });+ }+ }+ membersByGuild = { ...membersByGuild, [guildId]: members };+}++function handleDispatch(instance: OmnidiscInstance, t: string, d: unknown) {+ switch (t) {+ case "READY":+ applyReady(instance, d);+ return;+ case "RESUMED":+ return;+ case "GUILD_CREATE":+ case "GUILD_UPDATE": {+ const guild = parseGuild(d, instance.id);+ if (guild) upsertGuild(instance.id, guild);+ return;+ }+ case "GUILD_DELETE": {+ if (isRecord(d) && typeof d.id === "string") removeGuild(instance.id, d.id);+ return;+ }+ case "GUILD_MEMBER_ADD":+ case "GUILD_MEMBER_UPDATE":+ case "GUILD_MEMBER_REMOVE": {+ if (!isRecord(d)) return;+ const guildId = str(d.guild_id);+ const userId = str(d.user_id);+ if (userId && t !== "GUILD_MEMBER_REMOVE" && !usersByInstance[instance.id]?.[userId]) void ensureUser(instance.id, userId);+ if (guildId && guildId === selectedGuildId && selectedChannelId) void requestMembers(guildId, selectedChannelId);+ return;+ }+ case "GUILD_MEMBER_LIST_UPDATE":+ applyMemberList(instance.id, d);+ return;+ case "GUILD_ROLE_CREATE":+ case "GUILD_ROLE_UPDATE": {+ const role = parseRole(d);+ const guildId = isRecord(d) ? str(d.guild_id) : undefined;+ const guild = getGuild(guildId ?? null);+ if (!role || !guild) return;+ const rest = guild.roles.filter((r) => r.id !== role.id);+ upsertGuild(instance.id, { ...guild, roles: [...rest, role].sort((a, b) => a.position - b.position) });+ return;+ }+ case "GUILD_ROLE_DELETE": {+ if (!isRecord(d)) return;+ const guild = getGuild(str(d.guild_id) ?? null);+ const roleId = str(d.id);+ if (!guild || !roleId) return;+ upsertGuild(instance.id, { ...guild, roles: guild.roles.filter((r) => r.id !== roleId) });+ return;+ }+ case "RELATIONSHIP_ADD": {+ const rel = parseRelationship(d);+ if (!rel) return;+ const list = (relationshipsByInstance[instance.id] ?? []).filter((r) => r.userId !== rel.userId);+ relationshipsByInstance = { ...relationshipsByInstance, [instance.id]: [...list, rel] };+ if (!usersByInstance[instance.id]?.[rel.userId]) void ensureUser(instance.id, rel.userId);+ return;+ }+ case "RELATIONSHIP_REMOVE": {+ if (!isRecord(d)) return;+ const userId = str(d.user_id);+ if (!userId) return;+ relationshipsByInstance = {+ ...relationshipsByInstance,+ [instance.id]: (relationshipsByInstance[instance.id] ?? []).filter((r) => r.userId !== userId),+ };+ return;+ }+ case "CHANNEL_PINS_UPDATE": {+ if (!isRecord(d)) return;+ const channelId = str(d.channel_id);+ if (channelId && pinsByChannel[channelId]) void loadPins(channelId);+ return;+ }+ case "CHANNEL_CREATE":+ case "CHANNEL_UPDATE": {+ const channel = parseChannel(d);+ if (!channel) return;+ if (channel.guildId) upsertGuildChannel(instance.id, channel);+ else upsertDm(instance.id, channel);+ return;+ }+ case "CHANNEL_DELETE": {+ if (isRecord(d) && typeof d.id === "string") removeChannel(instance.id, d.id);+ return;+ }+ case "MESSAGE_CREATE":+ case "MESSAGE_UPDATE": {+ const parsed = parseMessage(d, nameResolver(instance.id));+ if (!parsed) return;+ const message = fillFromPending(parsed);+ if (!usersByInstance[instance.id]?.[message.authorId]) void ensureUser(instance.id, message.authorId);+ if (t === "MESSAGE_CREATE" || (messagesByChannel[message.channelId] ?? []).some((m) => m.id === message.id)) {+ upsertMessage(message);+ }+ if (t === "MESSAGE_CREATE") {+ bumpLastMessage(message.channelId, message.id);+ const typing = typingByChannel[message.channelId];+ if (typing && message.authorId in typing) {+ const next = { ...typing };+ delete next[message.authorId];+ typingByChannel = { ...typingByChannel, [message.channelId]: next };+ }+ if (message.channelId === selectedChannelId) void ackChannel(message.channelId);+ else void maybeNotify(instance, message);+ }+ return;+ }+ case "MESSAGE_DELETE": {+ if (isRecord(d) && typeof d.id === "string" && typeof d.channel_id === "string") removeMessage(d.channel_id, d.id);+ return;+ }+ case "MESSAGE_DELETE_BULK": {+ if (!isRecord(d) || typeof d.channel_id !== "string" || !Array.isArray(d.ids)) return;+ const ids = new Set(d.ids.filter((x): x is string => typeof x === "string"));+ const current = messagesByChannel[d.channel_id];+ if (current) messagesByChannel = { ...messagesByChannel, [d.channel_id]: current.filter((m) => !ids.has(m.id)) };+ return;+ }+ case "MESSAGE_REACTION_ADD":+ case "MESSAGE_REACTION_REMOVE": {+ if (!isRecord(d)) return;+ const channelId = str(d.channel_id);+ const messageId = str(d.message_id);+ const userId = str(d.user_id);+ const emoji = emojiKey(d.emoji);+ if (!channelId || !messageId || !userId || !emoji) return;+ const current = messagesByChannel[channelId];+ const message = current?.find((m) => m.id === messageId);+ if (!message) return;+ const reactions = [...(message.reactions ?? [])];+ const idx = reactions.findIndex((r) => r.emoji === emoji);+ const delta = t === "MESSAGE_REACTION_ADD" ? 1 : -1;+ const mine = userId === instance.userId;+ if (idx >= 0) {+ const r = reactions[idx];+ const count = Math.max(0, r.count + delta);+ if (count === 0) reactions.splice(idx, 1);+ else reactions[idx] = { ...r, count, me: mine ? delta > 0 : r.me };+ } else if (delta > 0) {+ reactions.push({ emoji, count: 1, me: mine });+ }+ upsertMessage({ ...message, reactions });+ return;+ }+ case "MESSAGE_ACK": {+ const parsed = parseReadState(d);+ if (parsed) setReadState(parsed.channelId, { lastReadId: parsed.lastReadId, mentionCount: parsed.mentionCount });+ return;+ }+ case "TYPING_START": {+ if (!isRecord(d)) return;+ const channelId = str(d.channel_id);+ const userId = str(d.user_id);+ if (!channelId || !userId) return;+ const until = Date.now() + TYPING_TTL_MS;+ typingByChannel = { ...typingByChannel, [channelId]: { ...(typingByChannel[channelId] ?? {}), [userId]: until } };+ const key = `${channelId}:${userId}`;+ if (typingTimers[key]) clearTimeout(typingTimers[key]);+ typingTimers[key] = setTimeout(() => {+ delete typingTimers[key];+ const current = typingByChannel[channelId];+ if (!current || !(userId in current)) return;+ const next = { ...current };+ delete next[userId];+ typingByChannel = { ...typingByChannel, [channelId]: next };+ }, TYPING_TTL_MS);+ return;+ }+ case "PRESENCE_UPDATE": {+ const p = parsePresence(d);+ if (p) setPresence(instance.id, p.userId, p.status);+ return;+ }+ case "PRESENCE_UPDATE_BULK": {+ for (const item of Array.isArray(d) ? d : []) {+ const p = parsePresence(item);+ if (p) setPresence(instance.id, p.userId, p.status);+ }+ return;+ }+ case "USER_UPDATE": {+ const user = parseUser(d);+ if (user) upsertUser(instance.id, user);+ return;+ }+ case "VOICE_STATE_UPDATE":+ applyVoiceState(instance.id, d);+ return;+ case "GATEWAY_ERROR":+ console.warn("[omnidisc] gateway error", instance.url, d);+ return;+ default:+ return;+ }+}++function mapStatus(ev: GatewayStatusEvent): { status: InstanceStatus; error?: string } {+ switch (ev.status) {+ case "ready":+ return { status: "connected" };+ case "connecting":+ return { status: "connecting" };+ case "reconnecting":+ return { status: "reconnecting", error: ev.error ?? undefined };+ case "disconnected":+ default:+ if (ev.error === ERR_UNAUTHORIZED || ev.error === ERR_NO_SESSION) return { status: "signed_out", error: ev.error };+ if (ev.error) return { status: "error", error: ev.error };+ return { status: "disconnected" };+ }+}++function settleReady(url: string, error: string | null) {+ const waiters = readyWaiters[url];+ if (!waiters) return;+ delete readyWaiters[url];+ for (const w of waiters) {+ if (error) w.reject(error);+ else w.resolve();+ }+}++function waitForReady(url: string, timeoutMs = READY_TIMEOUT_MS): Promise<void> {+ const instance = instanceByUrl(url);+ if (instance?.status === "connected") return Promise.resolve();+ return new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => {+ readyWaiters[url] = (readyWaiters[url] ?? []).filter((w) => w.resolve !== wrappedResolve);+ reject("ERR_UNREACHABLE");+ }, timeoutMs);+ const wrappedResolve = () => {+ clearTimeout(timer);+ resolve();+ };+ const wrappedReject = (e: string) => {+ clearTimeout(timer);+ reject(e);+ };+ readyWaiters[url] = [...(readyWaiters[url] ?? []), { resolve: wrappedResolve, reject: wrappedReject }];+ });+}++function handleStatus(ev: GatewayStatusEvent) {+ const instance = instanceByUrl(ev.url);+ if (!instance) return;+ const mapped = mapStatus(ev);+ instance.status = mapped.status;+ instance.error = mapped.status === "error" || mapped.status === "signed_out" ? mapped.error : undefined;+ if (mapped.status === "connected") settleReady(ev.url, null);+ else if (mapped.status === "signed_out" || mapped.status === "error") settleReady(ev.url, mapped.error ?? "ERR_UNREACHABLE");+}++let unlisteners: UnlistenFn[] = [];++export async function initOmnidisc(): Promise<void> {+ ensureLoaded();+ if (initialized) return;+ initialized = true;+ try {+ const offDispatch = await listen<GatewayDispatchEvent>("omnidisc://dispatch", (event) => {+ const payload = event.payload;+ const instance = instanceByUrl(payload.url);+ if (!instance) return;+ try {+ handleDispatch(instance, payload.t, payload.d);+ } catch (e) {+ console.warn("[omnidisc] dispatch handler failed", payload.t, errorText(e));+ }+ });+ const offStatus = await listen<GatewayStatusEvent>("omnidisc://status", (event) => handleStatus(event.payload));+ const offUpload = await listen<unknown>("omnidisc://upload", (event) => handleUploadProgress(event.payload));+ const offDecrypted = await listen<unknown>("omnidisc://decrypted", (event) =>+ handleDecryptedEvent(event.payload),+ );+ unlisteners = [offDispatch, offStatus, offUpload, offDecrypted];+ } catch (e) {+ initialized = false;+ console.warn("[omnidisc] could not subscribe to gateway events", errorText(e));+ return;+ }+ for (const instance of instances) {+ if (isDemo(instance.id)) continue;+ void connectGateway(instance);+ }+}++export function teardownOmnidisc() {+ for (const off of unlisteners) off();+ unlisteners = [];+ initialized = false;+}++export async function connectGateway(instance: OmnidiscInstance): Promise<void> {+ if (isDemo(instance.id)) return;+ instance.status = "connecting";+ instance.error = undefined;+ try {+ const snap = await invoke<{ status: string; error?: string }>("omnidisc_gateway_connect", { url: instance.url });+ handleStatus({ url: instance.url, status: snap.status as GatewayStatusEvent["status"], error: snap.error ?? null });+ } catch (e) {+ const error = errorText(e);+ handleStatus({ url: instance.url, status: "disconnected", error });+ }+}++export async function reconnectInstance(id: string) {+ const instance = getInstance(id);+ if (!instance) return;+ await connectGateway(instance);+}++export function getConnectStep(): ConnectStep {+ return connectStep;+}++export function getConnectError(): string | null {+ return connectError;+}++export function getConnectedInstance(): OmnidiscInstance | null {+ return connectedInstance;+}++export function getPendingConnect(): PendingConnect | null {+ return pendingConnect;+}++export function resetConnect() {+ connectStep = "idle";+ connectError = null;+ connectedInstance = null;+ pendingConnect = null;+}++function failConnect(e: unknown) {+ connectError = errorText(e);+ connectStep = "error";+}++async function finishConnect(pending: PendingConnect, joinInvite: boolean): Promise<OmnidiscInstance | null> {+ const instance = addInstance({+ url: pending.url,+ name: pending.name,+ status: "connecting",+ streaming: pending.streaming,+ insecure: pending.insecure,+ });+ selectedInstanceId = instance.id;+ connectStep = "syncing";+ try {+ await connectGateway(instance);+ if (instance.status !== "connected") await waitForReady(pending.url);+ } catch (e) {+ failConnect(e);+ return null;+ }+ if (joinInvite && pending.invite) {+ try {+ const raw = await invoke<unknown>("omnidisc_join_invite", { url: pending.url, code: pending.invite });+ const guild = parseGuild(raw, instance.id);+ if (guild) upsertGuild(instance.id, guild);+ } catch (e) {+ console.warn("[omnidisc] invite could not be redeemed", errorText(e));+ }+ }+ connectedInstance = instance;+ connectStep = "done";+ return instance;+}++export async function connectInstance(url: string, invite?: string): Promise<OmnidiscInstance | null> {+ ensureLoaded();+ connectStep = "connecting";+ connectError = null;+ connectedInstance = null;+ pendingConnect = null;+ let result: ConnectResult;+ try {+ result = await invoke<ConnectResult>("omnidisc_connect", {+ url,+ invite: invite && invite.trim().length > 0 ? invite.trim() : null,+ });+ } catch (e) {+ failConnect(e);+ return null;+ }+ const rawName = result.instance?.name;+ const name = typeof rawName === "string" && rawName.trim().length > 0 ? rawName.trim() : hostLabel(result.url);+ const registrationOpen = result.instance?.registration_open === true;+ const streaming = (result.instance?.streaming ?? undefined) as StreamingPolicy | undefined;+ const pending: PendingConnect = {+ url: result.url,+ name,+ invite: result.invite,+ registrationOpen,+ streaming,+ insecure: result.insecure ?? isInsecureInstanceUrl(result.url),+ };+ pendingConnect = pending;+ try {+ const session = await invoke<{ has_session: boolean }>("omnidisc_has_session", { url: result.url });+ if (!session.has_session) {+ connectStep = "auth";+ return null;+ }+ } catch (e) {+ failConnect(e);+ return null;+ }+ connectStep = "authenticating";+ const instance = await finishConnect(pending, true);+ const stepAfter = getConnectStep();+ const errorAfter = getConnectError();+ if (!instance && stepAfter === "error" && (errorAfter === ERR_UNAUTHORIZED || errorAfter === ERR_NO_SESSION)) {+ connectError = null;+ connectStep = "auth";+ }+ return instance;+}++export async function authenticate(+ mode: AuthMode,+ username: string,+ password: string,+ displayName?: string,+): Promise<OmnidiscInstance | null> {+ const pending = pendingConnect;+ if (!pending) return null;+ connectStep = "authenticating";+ connectError = null;+ try {+ if (mode === "register") {+ await invoke("omnidisc_register", {+ url: pending.url,+ username,+ password,+ displayName: displayName && displayName.trim().length > 0 ? displayName.trim() : null,+ inviteCode: pending.invite ?? null,+ });+ } else {+ await invoke("omnidisc_login", { url: pending.url, username, password });+ }+ } catch (e) {+ connectError = errorText(e);+ connectStep = "auth";+ return null;+ }+ return finishConnect(pending, mode === "login");+}++export function backToAuth() {+ if (pendingConnect) {+ connectError = null;+ connectStep = "auth";+ } else {+ resetConnect();+ }+}++export async function createGuild(instanceId: string, name: string): Promise<OmnidiscGuild | null> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return null;+ const raw = await invoke<unknown>("omnidisc_create_guild", { url: instance.url, name });+ const guild = parseGuild(raw, instanceId);+ if (guild) upsertGuild(instanceId, guild);+ return guild;+}++export async function createChannel(guildId: string, name: string, kind: ChannelKind): Promise<OmnidiscChannel | null> {+ const guild = getGuild(guildId);+ const instance = guild ? getInstance(guild.instanceId) : null;+ if (!guild || !instance || isDemo(instance.id)) return null;+ const raw = await invoke<unknown>("omnidisc_create_channel", {+ url: instance.url,+ guildId,+ name,+ kind: channelKindCode(kind),+ });+ const channel = parseChannel(raw);+ if (channel) upsertGuildChannel(instance.id, channel);+ return channel;+}++export async function createInviteLink(guildId: string, channelId?: string): Promise<string | null> {+ const guild = getGuild(guildId);+ const instance = guild ? getInstance(guild.instanceId) : null;+ if (!guild || !instance || isDemo(instance.id)) return null;+ const raw = await invoke<unknown>("omnidisc_create_invite", { url: instance.url, guildId, channelId: channelId ?? null });+ const code = isRecord(raw) ? str(raw.code) : undefined;+ if (!code) return null;+ return `${instance.url}/invite/${code}`;+}++export async function joinInvite(instanceId: string, code: string): Promise<OmnidiscGuild | null> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return null;+ const raw = await invoke<unknown>("omnidisc_join_invite", { url: instance.url, code });+ const guild = parseGuild(raw, instanceId);+ if (guild) upsertGuild(instanceId, guild);+ return guild;+}++export async function openDm(instanceId: string, userId: string): Promise<OmnidiscChannel | null> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return null;+ const raw = await invoke<unknown>("omnidisc_create_dm", { url: instance.url, recipientIds: [userId] });+ const channel = parseChannel(raw);+ if (channel) upsertDm(instanceId, channel);+ return channel;+}++export function canManageGuild(guildId: string | null): boolean {+ const guild = getGuild(guildId);+ if (!guild) return false;+ const instance = getInstance(guild.instanceId);+ return !!instance?.userId && instance.userId === guild.ownerId;+}++export function addDemoInstance(): OmnidiscInstance | null {+ if (!import.meta.env.DEV) return null;+ ensureLoaded();+ const instance = addInstance({ id: DEMO_INSTANCE_ID, url: DEMO_INSTANCE_URL, name: "Demo server", status: "connected" });+ instance.userId = "u1";+ selectedInstanceId = instance.id;+ if (!guildsByInstance[instance.id]) seedDemoData(instance.id);+ connectedInstance = instance;+ connectStep = "done";+ return instance;+}++export function hostLabel(url: string): string {+ try {+ return new URL(url).host || url;+ } catch {+ return url;+ }+}++const NOTIFY_KEY = "omnidisc.notifications";+let suppressAck: Record<string, boolean> = {};+let jumpTarget = $state<{ channelId: string; messageId: string } | null>(null);++function loadNotifyPrefs() {+ if (notifyPrefsLoaded) return;+ notifyPrefsLoaded = true;+ if (!hasStorage()) return;+ try {+ const raw = localStorage.getItem(NOTIFY_KEY);+ if (!raw) return;+ const parsed: unknown = JSON.parse(raw);+ if (!isRecord(parsed)) return;+ const out: Record<string, NotificationLevel> = {};+ for (const [key, value] of Object.entries(parsed)) {+ if (value === "all" || value === "mentions" || value === "nothing") out[key] = value;+ }+ notificationLevels = out;+ } catch {+ notificationLevels = {};+ }+}++function persistNotifyPrefs() {+ if (!hasStorage()) return;+ try {+ localStorage.setItem(NOTIFY_KEY, JSON.stringify(notificationLevels));+ } catch {+ return;+ }+}++export function getNotificationLevel(scopeId: string): NotificationLevel | null {+ loadNotifyPrefs();+ return notificationLevels[scopeId] ?? null;+}++export function setNotificationLevel(scopeId: string, level: NotificationLevel | null) {+ loadNotifyPrefs();+ const next = { ...notificationLevels };+ if (level === null) delete next[scopeId];+ else next[scopeId] = level;+ notificationLevels = next;+ persistNotifyPrefs();+}++export function effectiveNotificationLevel(channelId: string): NotificationLevel {+ loadNotifyPrefs();+ const own = notificationLevels[channelId];+ if (own) return own;+ const guildId = channelGuild[channelId];+ if (guildId && notificationLevels[guildId]) return notificationLevels[guildId];+ return getChannel(channelId)?.guildId ? "mentions" : "all";+}++export function mentionsMe(instanceId: string, message: OmnidiscMessage): boolean {+ const me = getInstance(instanceId)?.userId;+ if (!me || message.authorId === me) return false;+ if (message.mentionsEveryone) return true;+ return (message.mentionedUserIds ?? []).includes(me);+}++async function windowFocused(): Promise<boolean> {+ try {+ const { getCurrentWebviewWindow } = await import("@tauri-apps/api/webviewWindow");+ return await getCurrentWebviewWindow().isFocused();+ } catch {+ return false;+ }+}++async function maybeNotify(instance: OmnidiscInstance, message: OmnidiscMessage) {+ if (isDemo(instance.id)) return;+ if (message.authorId === instance.userId) return;+ const level = effectiveNotificationLevel(message.channelId);+ if (level === "nothing") return;+ const mention = mentionsMe(instance.id, message);+ const isDm = !channelGuild[message.channelId];+ if (level === "mentions" && !mention && !isDm) return;+ if (message.channelId === selectedChannelId && (await windowFocused())) return;+ const channel = getChannel(message.channelId);+ const where = channel ? (isDm ? dmTitle(channel) : `#${channel.name}`) : "";+ try {+ const n = await import("@tauri-apps/plugin-notification");+ let granted = await n.isPermissionGranted();+ if (!granted) granted = (await n.requestPermission()) === "granted";+ if (!granted) return;+ n.sendNotification({+ title: where ? `${message.authorName} — ${where}` : message.authorName,+ body: message.content.slice(0, 180),+ });+ } catch {+ // notifications are optional; a missing permission must never break the chat+ }+}++export function getMentionTotal(): number {+ let count = 0;+ for (const [channelId, state] of Object.entries(readStateByChannel)) {+ if (channelId === selectedChannelId) continue;+ count += state.mentionCount;+ }+ return count;+}++export function getGuildUnread(guildId: string): { unread: boolean; mentions: number } {+ const guild = getGuild(guildId);+ if (!guild) return { unread: false, mentions: 0 };+ let unread = false;+ let mentions = 0;+ for (const channel of guild.channels) {+ if (channel.kind === "category" || channel.kind === "voice") continue;+ if (isUnread(channel.id)) unread = true;+ mentions += getMentionCount(channel.id);+ }+ return { unread, mentions };+}++function memberOf(guildId: string | null, userId: string | null): OmnidiscMember | null {+ if (!guildId || !userId) return null;+ return (membersByGuild[guildId] ?? []).find((m) => m.id === userId) ?? null;+}++export function getRoles(guildId: string | null): OmnidiscRole[] {+ return getGuild(guildId)?.roles ?? [];+}++export function getMember(guildId: string | null, userId: string | null): OmnidiscMember | null {+ return memberOf(guildId, userId);+}++function permissionContext(channelId: string | null, guildId?: string | null) {+ const gid = guildId ?? (channelId ? channelGuild[channelId] : null) ?? null;+ const guild = getGuild(gid);+ const channel = channelId ? getChannel(channelId) : null;+ const parent = channel?.parentId ? getChannel(channel.parentId) : null;+ const instance = guild ? getInstance(guild.instanceId) : null;+ const userId = instance?.userId ?? null;+ // Membership comes from READY (the gateway only sends guilds this account is+ // in), not from the paged member list, which may simply not have reached us yet.+ return { guild, channel, parent, member: memberOf(gid, userId), userId, isMember: !!guild };+}++export function canInChannel(channelId: string | null, name: PermissionName): boolean {+ if (!channelId) return false;+ const instanceId = channelInstance[channelId];+ if (isDemo(instanceId)) return true;+ if (!channelGuild[channelId]) return true;+ return canIn(permissionContext(channelId), name);+}++export function canInGuild(guildId: string | null, name: PermissionName): boolean {+ const guild = getGuild(guildId);+ if (!guild) return false;+ if (isDemo(guild.instanceId)) return true;+ return canIn(permissionContext(null, guildId), name);+}++export function permissionBitsIn(channelId: string | null, guildId?: string | null): bigint {+ return resolvePermissions(permissionContext(channelId, guildId));+}++export function isGuildOwner(guildId: string | null): boolean {+ const guild = getGuild(guildId);+ if (!guild) return false;+ return getInstance(guild.instanceId)?.userId === guild.ownerId;+}++export function canEditMessage(message: OmnidiscMessage): boolean {+ const instanceId = channelInstance[message.channelId];+ const me = getInstance(instanceId ?? null)?.userId;+ return !!me && message.authorId === me && message.delivery === "sent";+}++export function canDeleteMessage(message: OmnidiscMessage): boolean {+ const instanceId = channelInstance[message.channelId];+ const me = getInstance(instanceId ?? null)?.userId;+ if (me && message.authorId === me) return true;+ return canInChannel(message.channelId, "MANAGE_MESSAGES");+}++export function getPins(channelId: string | null): OmnidiscMessage[] {+ if (!channelId) return [];+ return pinsByChannel[channelId] ?? [];+}++export async function loadPins(channelId: string): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ const raw = await invoke<unknown>("omnidisc_list_pins", { url: instance.url, channelId });+ const resolve = nameResolver(instance.id);+ const list = (Array.isArray(raw) ? raw : [])+ .map((m) => parseMessage(m, resolve))+ .filter((m): m is OmnidiscMessage => m !== null);+ pinsByChannel = { ...pinsByChannel, [channelId]: list };+ for (const m of list) {+ if (!usersByInstance[instance.id]?.[m.authorId]) void ensureUser(instance.id, m.authorId);+ }+}++export async function setPinned(channelId: string, messageId: string, pinned: boolean): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_pin_message", { url: instance.url, channelId, messageId, pinned });+ const message = (messagesByChannel[channelId] ?? []).find((m) => m.id === messageId);+ if (message) upsertMessage({ ...message, pinned });+ if (pinsByChannel[channelId]) await loadPins(channelId);+}++export interface SearchFilters {+ from?: string;+ has?: string;+ before?: string;+ after?: string;+ channel?: string;+}++export interface SearchOutcome {+ messages: OmnidiscMessage[];+ total: number;+}++export async function searchMessages(+ instanceId: string,+ scope: "guild" | "channel",+ scopeId: string,+ query: string,+ filters: SearchFilters = {},+): Promise<SearchOutcome> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return { messages: [], total: 0 };+ const raw = await invoke<unknown>("omnidisc_search", {+ url: instance.url,+ scope,+ scopeId,+ query,+ from: filters.from ?? null,+ channel: filters.channel ?? null,+ has: filters.has ?? null,+ before: filters.before ?? null,+ after: filters.after ?? null,+ limit: 100,+ });+ if (!isRecord(raw)) return { messages: [], total: 0 };+ const resolve = nameResolver(instanceId);+ const messages = (Array.isArray(raw.messages) ? raw.messages : [])+ .map((m) => parseMessage(m, resolve))+ .filter((m): m is OmnidiscMessage => m !== null)+ .reverse();+ for (const m of messages) {+ if (!usersByInstance[instanceId]?.[m.authorId]) void ensureUser(instanceId, m.authorId);+ }+ const total = typeof raw.total === "number" ? raw.total : messages.length;+ return { messages, total };+}++export function getJumpTarget(): { channelId: string; messageId: string } | null {+ return jumpTarget;+}++export function clearJumpTarget() {+ jumpTarget = null;+}++export async function jumpToMessage(channelId: string, messageId: string): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) {+ jumpTarget = { channelId, messageId };+ return;+ }+ const known = (messagesByChannel[channelId] ?? []).some((m) => m.id === messageId);+ if (!known) {+ loadingByChannel = { ...loadingByChannel, [channelId]: true };+ try {+ const raw = await invoke<unknown>("omnidisc_list_messages", {+ url: instance.url,+ channelId,+ around: messageId,+ limit: PAGE_SIZE,+ });+ const resolve = nameResolver(instance.id);+ const parsed = (Array.isArray(raw) ? raw : [])+ .map((m) => parseMessage(m, resolve))+ .filter((m): m is OmnidiscMessage => m !== null);+ const byId = new Map((messagesByChannel[channelId] ?? []).map((m) => [m.id, m]));+ for (const m of parsed) byId.set(m.id, m);+ messagesByChannel = { ...messagesByChannel, [channelId]: sortMessages([...byId.values()]) };+ loadedChannels.add(channelId);+ for (const m of parsed) {+ if (!usersByInstance[instance.id]?.[m.authorId]) void ensureUser(instance.id, m.authorId);+ }+ } finally {+ const next = { ...loadingByChannel };+ delete next[channelId];+ loadingByChannel = next;+ }+ }+ jumpTarget = { channelId, messageId };+}++export function getFirstUnreadId(channelId: string | null): string | null {+ if (!channelId) return null;+ const marked = localUnread[channelId];+ if (marked) return marked;+ const read = readStateByChannel[channelId]?.lastReadId;+ if (!read) return null;+ const list = messagesByChannel[channelId] ?? [];+ const first = list.find((m) => m.delivery === "sent" && isAfter(m.id, read));+ return first?.id ?? null;+}++export function markUnread(channelId: string, messageId: string) {+ const list = messagesByChannel[channelId] ?? [];+ const index = list.findIndex((m) => m.id === messageId);+ const previous = index > 0 ? list[index - 1].id : undefined;+ setReadState(channelId, { lastReadId: previous, mentionCount: 0 });+ localUnread = { ...localUnread, [channelId]: messageId };+ suppressAck[channelId] = true;+ delete ackedByChannel[channelId];+}++export function clearUnreadMark(channelId: string) {+ if (!(channelId in localUnread)) return;+ const next = { ...localUnread };+ delete next[channelId];+ localUnread = next;+ delete suppressAck[channelId];+}++export function messageLink(channelId: string, messageId: string): string {+ const instance = instanceForChannel(channelId);+ const guildId = channelGuild[channelId];+ const base = instance?.url ?? "";+ return guildId ? `${base}/channels/${guildId}/${channelId}/${messageId}` : `${base}/channels/@me/${channelId}/${messageId}`;+}++export function getRelationships(instanceId: string | null): OmnidiscRelationship[] {+ if (!instanceId) return [];+ return relationshipsByInstance[instanceId] ?? [];+}++export async function loadRelationships(instanceId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ const raw = await invoke<unknown>("omnidisc_list_relationships", { url: instance.url });+ const list = (Array.isArray(raw) ? raw : [])+ .map(parseRelationship)+ .filter((r): r is OmnidiscRelationship => r !== null);+ relationshipsByInstance = { ...relationshipsByInstance, [instanceId]: list };+ for (const rel of list) {+ if (!usersByInstance[instanceId]?.[rel.userId]) void ensureUser(instanceId, rel.userId);+ }+}++export async function addFriend(instanceId: string, username: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_add_relationship", { url: instance.url, username, userId: null });+ await loadRelationships(instanceId);+}++export async function acceptFriend(instanceId: string, userId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_accept_relationship", { url: instance.url, userId });+ await loadRelationships(instanceId);+}++export async function removeFriend(instanceId: string, userId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_remove_relationship", { url: instance.url, userId });+ relationshipsByInstance = {+ ...relationshipsByInstance,+ [instanceId]: (relationshipsByInstance[instanceId] ?? []).filter((r) => r.userId !== userId),+ };+}++export async function blockUser(instanceId: string, userId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_block_user", { url: instance.url, userId });+ await loadRelationships(instanceId);+}++export function relationshipWith(instanceId: string | null, userId: string | null): OmnidiscRelationship | null {+ if (!instanceId || !userId) return null;+ return (relationshipsByInstance[instanceId] ?? []).find((r) => r.userId === userId) ?? null;+}++export function getNote(instanceId: string | null, userId: string | null): string {+ if (!instanceId || !userId) return "";+ return notesByInstance[instanceId]?.[userId] ?? "";+}++export async function loadNotes(instanceId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ const raw = await invoke<unknown>("omnidisc_list_notes", { url: instance.url });+ const notes: Record<string, string> = {};+ for (const n of Array.isArray(raw) ? raw : []) {+ if (!isRecord(n)) continue;+ const userId = str(n.user_id);+ if (userId) notes[userId] = str(n.note) ?? "";+ }+ notesByInstance = { ...notesByInstance, [instanceId]: notes };+}++export async function saveNote(instanceId: string, userId: string, note: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_put_note", { url: instance.url, userId, note });+ const current = notesByInstance[instanceId] ?? {};+ notesByInstance = { ...notesByInstance, [instanceId]: { ...current, [userId]: note } };+}++export function mutualGuilds(instanceId: string | null, userId: string | null): OmnidiscGuild[] {+ if (!instanceId || !userId) return [];+ return (guildsByInstance[instanceId] ?? []).filter((g) =>+ (membersByGuild[g.id] ?? []).some((m) => m.id === userId),+ );+}++export async function updateMe(instanceId: string, patch: Record<string, unknown>): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ const raw = await invoke<unknown>("omnidisc_update_me", { url: instance.url, patch });+ const user = parseUser(raw);+ if (user) upsertUser(instanceId, user);+}++export function getOwnPresence(instanceId: string | null): string {+ if (!instanceId) return "online";+ return ownPresenceByInstance[instanceId] ?? "online";+}++export async function setOwnPresence(+ instanceId: string,+ status: string,+ custom?: { text?: string; expiresAt?: string },+): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ const payload: Record<string, unknown> = { user_id: instance.userId ?? "0", status };+ if (custom?.text) {+ payload.custom_status = { text: custom.text, expires_at: custom.expiresAt ?? null };+ }+ await invoke("omnidisc_gateway_send", { url: instance.url, op: 3, d: payload });+ ownPresenceByInstance = { ...ownPresenceByInstance, [instanceId]: status };+ if (instance.userId) setPresence(instanceId, instance.userId, status);+}++export async function listSessions(instanceId: string): Promise<OmnidiscSession[]> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return [];+ const raw = await invoke<unknown>("omnidisc_list_sessions", { url: instance.url });+ return (Array.isArray(raw) ? raw : [])+ .map(parseSession)+ .filter((s): s is OmnidiscSession => s !== null);+}++export async function revokeSession(instanceId: string, sessionId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_revoke_session", { url: instance.url, sessionId });+}++export async function revokeOtherSessions(instanceId: string): Promise<void> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instanceId)) return;+ await invoke("omnidisc_revoke_other_sessions", { url: instance.url });+}++function guildInstance(guildId: string): OmnidiscInstance | null {+ const guild = getGuild(guildId);+ return guild ? getInstance(guild.instanceId) : null;+}++export async function updateGuild(guildId: string, patch: Record<string, unknown>): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ const raw = await invoke<unknown>("omnidisc_update_guild", { url: instance.url, guildId, patch });+ const guild = parseGuild(raw, instance.id);+ if (guild) upsertGuild(instance.id, guild);+}++export async function deleteGuild(guildId: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_delete_guild", { url: instance.url, guildId });+ removeGuild(instance.id, guildId);+}++export async function leaveGuild(guildId: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_leave_guild", { url: instance.url, guildId });+ removeGuild(instance.id, guildId);+}++export async function transferGuild(guildId: string, userId: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ const raw = await invoke<unknown>("omnidisc_transfer_guild", { url: instance.url, guildId, userId });+ const guild = parseGuild(raw, instance.id);+ if (guild) upsertGuild(instance.id, guild);+}++export async function createRole(guildId: string, name: string, permissions: string): Promise<OmnidiscRole | null> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return null;+ const raw = await invoke<unknown>("omnidisc_create_role", {+ url: instance.url,+ guildId,+ name,+ permissions,+ color: null,+ hoist: false,+ mentionable: false,+ });+ const role = parseRole(raw);+ const guild = getGuild(guildId);+ if (role && guild) {+ upsertGuild(instance.id, { ...guild, roles: [...guild.roles, role].sort((a, b) => a.position - b.position) });+ }+ return role;+}++export async function updateRole(guildId: string, roleId: string, patch: Record<string, unknown>): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ const raw = await invoke<unknown>("omnidisc_update_role", { url: instance.url, guildId, roleId, patch });+ const role = parseRole(raw);+ const guild = getGuild(guildId);+ if (role && guild) {+ const rest = guild.roles.filter((r) => r.id !== role.id);+ upsertGuild(instance.id, { ...guild, roles: [...rest, role].sort((a, b) => a.position - b.position) });+ }+}++export async function deleteRole(guildId: string, roleId: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_delete_role", { url: instance.url, guildId, roleId });+ const guild = getGuild(guildId);+ if (guild) upsertGuild(instance.id, { ...guild, roles: guild.roles.filter((r) => r.id !== roleId) });+}++export async function setMemberRole(guildId: string, userId: string, roleId: string, granted: boolean): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_set_member_role", { url: instance.url, guildId, userId, roleId, granted });+}++export async function updateMember(guildId: string, userId: string, patch: Record<string, unknown>): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_update_member", { url: instance.url, guildId, userId, patch });+}++export async function kickMember(guildId: string, userId: string, reason?: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_kick_member", { url: instance.url, guildId, userId, reason: reason ?? null });+}++export async function banMember(guildId: string, userId: string, reason?: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_ban_member", { url: instance.url, guildId, userId, reason: reason ?? null });+}++export async function unbanMember(guildId: string, userId: string): Promise<void> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_unban_member", { url: instance.url, guildId, userId });+}++export async function listBans(guildId: string): Promise<OmnidiscBan[]> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return [];+ const raw = await invoke<unknown>("omnidisc_list_bans", { url: instance.url, guildId });+ const list = (Array.isArray(raw) ? raw : []).map(parseBan).filter((b): b is OmnidiscBan => b !== null);+ for (const b of list) {+ if (!usersByInstance[instance.id]?.[b.userId]) void ensureUser(instance.id, b.userId);+ }+ return list;+}++export async function loadAuditLog(guildId: string, action?: string): Promise<OmnidiscAuditEntry[]> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return [];+ const raw = await invoke<unknown>("omnidisc_audit_log", {+ url: instance.url,+ guildId,+ action: action ?? null,+ actorId: null,+ before: null,+ limit: 50,+ });+ const list = (Array.isArray(raw) ? raw : [])+ .map(parseAuditEntry)+ .filter((e): e is OmnidiscAuditEntry => e !== null);+ for (const e of list) {+ if (!usersByInstance[instance.id]?.[e.actorId]) void ensureUser(instance.id, e.actorId);+ if (e.targetId && !usersByInstance[instance.id]?.[e.targetId]) void ensureUser(instance.id, e.targetId);+ }+ return list;+}++export async function updateChannelSettings(channelId: string, patch: Record<string, unknown>): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ const raw = await invoke<unknown>("omnidisc_update_channel", { url: instance.url, channelId, patch });+ const channel = parseChannel(raw);+ if (channel?.guildId) upsertGuildChannel(instance.id, channel);+}++export async function deleteChannel(channelId: string): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_delete_channel", { url: instance.url, channelId });+ removeChannel(instance.id, channelId);+}++export async function putOverwrite(+ channelId: string,+ targetId: string,+ targetKind: "role" | "member",+ allow: string,+ deny: string,+): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_put_overwrite", { url: instance.url, channelId, targetId, targetKind, allow, deny });+ const channel = getChannel(channelId);+ if (channel?.guildId) {+ const rest = (channel.overwrites ?? []).filter((o) => o.targetId !== targetId);+ upsertGuildChannel(instance.id, { ...channel, overwrites: [...rest, { targetId, targetKind, allow, deny }] });+ }+}++export async function deleteOverwrite(channelId: string, targetId: string): Promise<void> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_delete_overwrite", { url: instance.url, channelId, targetId });+ const channel = getChannel(channelId);+ if (channel?.guildId) {+ upsertGuildChannel(instance.id, {+ ...channel,+ overwrites: (channel.overwrites ?? []).filter((o) => o.targetId !== targetId),+ });+ }+}++export async function createInviteWithOptions(+ guildId: string,+ channelId: string | undefined,+ maxAgeSeconds: number | null,+ maxUses: number | null,+): Promise<string | null> {+ const instance = guildInstance(guildId);+ if (!instance || isDemo(instance.id)) return null;+ const raw = await invoke<unknown>("omnidisc_create_invite", {+ url: instance.url,+ guildId,+ channelId: channelId ?? null,+ maxAgeSeconds,+ maxUses,+ });+ const code = isRecord(raw) ? str(raw.code) : undefined;+ return code ? `${instance.url}/invite/${code}` : null;+}++// ---------------------------------------------------------------------------+// Attachments, uploads and end-to-end encryption+// ---------------------------------------------------------------------------++let uploadsByChannel = $state<Record<string, PendingAttachment[]>>({});+let devicesByInstance = $state<Record<string, OmnidiscDevice[]>>({});+let thisDeviceByInstance = $state<Record<string, string>>({});+let limitsByInstance: Record<string, { maxUploadBytes: number; maxAttachments: number }> = {};+let groupStatusByChannel = $state<Record<string, OmnidiscGroupStatus>>({});+// Plaintext that arrived before its MESSAGE_CREATE, keyed by ciphertext.+let pendingDecrypts: Record<string, DecryptedPayload> = {};+// Whether that plaintext's sending device matched the published roster.+let unverifiedSenders: Record<string, boolean> = {};++interface DecryptedPayload {+ content: string;+ replyToId?: string;+ attachments: OmnidiscAttachment[];+}++export function isEncryptedChannel(channelId: string | null): boolean {+ const channel = getChannel(channelId);+ return channel?.kind === "dm" || channel?.kind === "group_dm";+}++function readPayload(raw: unknown): DecryptedPayload | null {+ if (!isRecord(raw)) return null;+ const files = Array.isArray(raw.files) ? raw.files : [];+ const attachments: OmnidiscAttachment[] = [];+ for (const f of files) {+ if (!isRecord(f)) continue;+ const id = str(f.attachment_id);+ const filename = str(f.name);+ if (!id || !filename) continue;+ attachments.push({+ id,+ filename,+ size: typeof f.size === "number" ? f.size : 0,+ contentType: str(f.mime),+ encrypted: true,+ });+ }+ return { content: str(raw.content) ?? "", replyToId: str(raw.reply_to), attachments };+}++function applyDecrypted(+ channelId: string,+ ciphertext: string,+ payload: DecryptedPayload,+ senderVerified = true,+) {+ const list = messagesByChannel[channelId] ?? [];+ const target = list.find((m) => m.ciphertext === ciphertext);+ if (!target) {+ pendingDecrypts[ciphertext] = payload;+ unverifiedSenders[ciphertext] = senderVerified;+ return;+ }+ upsertMessage({+ ...target,+ content: payload.content,+ replyToId: payload.replyToId ?? target.replyToId,+ attachments: payload.attachments,+ awaitingDecryption: false,+ senderVerified,+ });+}++function fillFromPending(message: OmnidiscMessage): OmnidiscMessage {+ if (!message.ciphertext) return message;+ const payload = pendingDecrypts[message.ciphertext];+ if (!payload) return message;+ const senderVerified = unverifiedSenders[message.ciphertext] ?? true;+ delete pendingDecrypts[message.ciphertext];+ delete unverifiedSenders[message.ciphertext];+ return {+ ...message,+ content: payload.content,+ replyToId: payload.replyToId ?? message.replyToId,+ attachments: payload.attachments,+ awaitingDecryption: false,+ senderVerified,+ };+}++/// Scrollback: MLS ratchets forward, so old ciphertext can only come from the+/// local cache in Rust. Anything it cannot recall stays honestly blank.+export async function hydrateEncrypted(channelId: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return;+ const waiting = (messagesByChannel[channelId] ?? [])+ .filter((m) => m.awaitingDecryption && m.ciphertext)+ .map((m) => m.ciphertext as string);+ if (waiting.length === 0) return;+ try {+ const found = await invoke<Record<string, unknown>>("omnidisc_mls_recall", {+ url: instance.url,+ ciphertexts: waiting,+ });+ for (const [ciphertext, raw] of Object.entries(found ?? {})) {+ const payload = readPayload(raw);+ if (payload) applyDecrypted(channelId, ciphertext, payload);+ }+ } catch (e) {+ console.warn("[omnidisc] could not read cached plaintext", errorText(e));+ }+}++export function getGroupStatus(channelId: string | null): OmnidiscGroupStatus | null {+ return channelId ? (groupStatusByChannel[channelId] ?? null) : null;+}++export async function refreshGroupStatus(channelId: string) {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id) || !isEncryptedChannel(channelId)) return;+ try {+ const raw = await invoke<unknown>("omnidisc_mls_status", { url: instance.url, channelId });+ if (!isRecord(raw)) return;+ const members = (Array.isArray(raw.members) ? raw.members : [])+ .filter(isRecord)+ .map((m) => ({+ userId: str(m.user_id) ?? "",+ deviceId: str(m.device_id) ?? "",+ fingerprint: str(m.fingerprint) ?? "",+ isMe: m.is_me === true,+ }));+ groupStatusByChannel = {+ ...groupStatusByChannel,+ [channelId]: {+ ready: raw.ready === true,+ groupId: str(raw.group_id) ?? "",+ epoch: typeof raw.epoch === "number" ? raw.epoch : undefined,+ members,+ },+ };+ } catch (e) {+ console.warn("[omnidisc] could not read the group status", errorText(e));+ }+}++export async function getUploadLimits(instanceId: string) {+ const cached = limitsByInstance[instanceId];+ if (cached) return cached;+ const instance = getInstance(instanceId);+ if (!instance) return { maxUploadBytes: 0, maxAttachments: 10 };+ try {+ const raw = await invoke<unknown>("omnidisc_instance_limits", { url: instance.url });+ const limits = isRecord(raw) && isRecord(raw.limits) ? raw.limits : {};+ const value = {+ maxUploadBytes:+ typeof limits.max_upload_bytes === "number"+ ? limits.max_upload_bytes+ : typeof (raw as Record<string, unknown>).max_upload_bytes === "number"+ ? ((raw as Record<string, unknown>).max_upload_bytes as number)+ : 0,+ maxAttachments: typeof limits.max_attachments === "number" ? limits.max_attachments : 10,+ };+ limitsByInstance[instanceId] = value;+ return value;+ } catch {+ return { maxUploadBytes: 0, maxAttachments: 10 };+ }+}++export function getPendingAttachments(channelId: string | null): PendingAttachment[] {+ return channelId ? (uploadsByChannel[channelId] ?? []) : [];+}++function putUpload(next: PendingAttachment) {+ const list = uploadsByChannel[next.channelId] ?? [];+ const index = list.findIndex((u) => u.id === next.id);+ const updated = index >= 0 ? list.map((u) => (u.id === next.id ? next : u)) : [...list, next];+ uploadsByChannel = { ...uploadsByChannel, [next.channelId]: updated };+}++export function removePendingAttachment(channelId: string, id: string) {+ const list = uploadsByChannel[channelId] ?? [];+ const target = list.find((u) => u.id === id);+ if (target?.previewUrl) URL.revokeObjectURL(target.previewUrl);+ uploadsByChannel = { ...uploadsByChannel, [channelId]: list.filter((u) => u.id !== id) };+ void invoke("omnidisc_upload_cancel", { id }).catch(() => {});+}++function clearUploads(channelId: string) {+ for (const upload of uploadsByChannel[channelId] ?? []) {+ if (upload.previewUrl) URL.revokeObjectURL(upload.previewUrl);+ }+ const next = { ...uploadsByChannel };+ delete next[channelId];+ uploadsByChannel = next;+}++export async function attachFile(+ channelId: string,+ file: { path: string; name?: string; previewUrl?: string },+): Promise<string | null> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return null;+ const limits = await getUploadLimits(instance.id);+ const already = uploadsByChannel[channelId] ?? [];+ if (already.length >= limits.maxAttachments) {+ throw new Error(`ERR_TOO_MANY_ATTACHMENTS:${limits.maxAttachments}`);+ }+ const encrypted = isEncryptedChannel(channelId);+ // Rust owns the size check: it reads the file anyway and knows the instance+ // limit, so the answer arrives before the first byte moves.+ const started = await invoke<{ id: string; size: number; name: string }>(+ "omnidisc_upload_start",+ { url: instance.url, channelId, path: file.path, encrypt: encrypted },+ );+ putUpload({+ id: started.id,+ channelId,+ name: file.name ?? started.name,+ path: file.path,+ sent: 0,+ total: started.size,+ state: "preparing",+ encrypted,+ previewUrl: file.previewUrl,+ });+ return started.id;+}++export async function retryAttachment(channelId: string, id: string) {+ const list = uploadsByChannel[channelId] ?? [];+ const target = list.find((u) => u.id === id);+ if (!target) return;+ removePendingAttachment(channelId, id);+ await attachFile(channelId, {+ path: target.path,+ name: target.name,+ previewUrl: target.previewUrl,+ });+}++function handleUploadProgress(raw: unknown) {+ if (!isRecord(raw)) return;+ const id = str(raw.id);+ const channelId = str(raw.channel_id);+ if (!id || !channelId) return;+ const list = uploadsByChannel[channelId] ?? [];+ const current = list.find((u) => u.id === id);+ if (!current) return;+ const state = (str(raw.state) ?? "uploading") as PendingAttachment["state"];+ if (state === "cancelled") {+ removePendingAttachment(channelId, id);+ return;+ }+ putUpload({+ ...current,+ sent: typeof raw.sent === "number" ? raw.sent : current.sent,+ total: typeof raw.total === "number" && raw.total > 0 ? raw.total : current.total,+ state,+ error: str(raw.error),+ mime: str(raw.mime) ?? current.mime,+ });+}++function handleDecryptedEvent(raw: unknown) {+ if (!isRecord(raw)) return;+ const channelId = str(raw.channel_id);+ const ciphertext = str(raw.ciphertext);+ if (!channelId || !ciphertext) return;+ const payload = readPayload(raw.payload);+ if (payload) applyDecrypted(channelId, ciphertext, payload, raw.sender_verified !== false);+}++export async function downloadAttachment(+ channelId: string,+ message: OmnidiscMessage,+ attachment: OmnidiscAttachment,+): Promise<string | null> {+ const instance = instanceForChannel(channelId);+ if (!instance || isDemo(instance.id)) return null;+ const result = await invoke<{ path: string; name: string }>("omnidisc_download_attachment", {+ url: instance.url,+ attachmentUrl: attachment.url ?? null,+ attachmentId: attachment.id,+ filename: attachment.filename,+ ciphertext: attachment.encrypted ? (message.ciphertext ?? null) : null,+ });+ return result?.path ?? null;+}++// ---------------------------------------------------------------------------+// Devices+// ---------------------------------------------------------------------------++export function getDevices(instanceId: string | null): OmnidiscDevice[] {+ return instanceId ? (devicesByInstance[instanceId] ?? []) : [];+}++export function getThisDeviceId(instanceId: string | null): string | null {+ return instanceId ? (thisDeviceByInstance[instanceId] ?? null) : null;+}++export async function loadDevices(instanceId: string, userId?: string): Promise<OmnidiscDevice[]> {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instance.id)) return [];+ const [mine, raw] = await Promise.all([+ invoke<{ device_id: string }>("omnidisc_device_fingerprint", { url: instance.url }).catch(+ () => null,+ ),+ invoke<unknown>("omnidisc_list_user_devices", { url: instance.url, userId: userId ?? "@me" }),+ ]);+ if (mine?.device_id) {+ thisDeviceByInstance = { ...thisDeviceByInstance, [instanceId]: mine.device_id };+ }+ const devices = (Array.isArray(raw) ? raw : [])+ .map(parseDevice)+ .filter((d): d is OmnidiscDevice => d !== null);+ if (!userId || userId === "@me") {+ devicesByInstance = { ...devicesByInstance, [instanceId]: devices };+ }+ return devices;+}++export async function revokeDevice(instanceId: string, deviceId: string) {+ const instance = getInstance(instanceId);+ if (!instance || isDemo(instance.id)) return;+ await invoke("omnidisc_revoke_device", { url: instance.url, deviceId });+ await loadDevices(instanceId);+}diff --git a/src/lib/stores/omnidisc-store.test.ts b/src/lib/stores/omnidisc-store.test.tsnew file mode 100644index 00000000..da5e3c4b--- /dev/null+++ b/src/lib/stores/omnidisc-store.test.ts@@ -0,0 +1,86 @@+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));++type OmnidiscStore = typeof import("./omnidisc-store.svelte");++let store: OmnidiscStore;++beforeAll(async () => {+ vi.stubGlobal("$state", <T>(value: T) => value);+ vi.stubGlobal("$derived", <T>(value: T) => value);+ store = await import("./omnidisc-store.svelte");+});++afterAll(() => {+ vi.unstubAllGlobals();+});++describe("omnidisc instances", () => {+ it("adds an instance once per url and selects the first one", () => {+ const a = store.addInstance({ url: "https://chat.example.org", name: "Example" });+ const again = store.addInstance({ url: "https://chat.example.org", name: "Renamed" });+ expect(again.id).toBe(a.id);+ expect(again.name).toBe("Renamed");+ expect(store.getInstances()).toHaveLength(1);+ expect(store.getSelectedInstance()?.id).toBe(a.id);+ });++ it("removing the selected instance falls back to the next one", () => {+ const first = store.getInstances()[0];+ const second = store.addInstance({ url: "https://other.example.org", name: "Other" });+ store.selectInstance(first.id);+ store.removeInstance(first.id);+ expect(store.getSelectedInstance()?.id).toBe(second.id);+ });++ it("status updates keep the error only while in error", () => {+ const instance = store.getInstances()[0];+ store.setInstanceStatus(instance.id, "error", "boom");+ expect(store.getInstances()[0].error).toBe("boom");+ store.setInstanceStatus(instance.id, "connected");+ expect(store.getInstances()[0].error).toBeUndefined();+ });+});++describe("omnidisc drafts", () => {+ it("keeps one draft per channel key and drops empty ones", () => {+ store.setDraft("g1/c1", "hello");+ store.setDraft("g1/c2", "other");+ expect(store.getDraft("g1/c1")).toBe("hello");+ expect(store.getDraft("g1/c2")).toBe("other");+ store.setDraft("g1/c1", "");+ expect(store.getDraft("g1/c1")).toBe("");+ expect(store.getDraft("g1/c2")).toBe("other");+ });+});++describe("omnidisc url helpers", () => {+ it("hostLabel falls back to the raw string", () => {+ expect(store.hostLabel("https://chat.example.org:8443/x")).toBe("chat.example.org:8443");+ expect(store.hostLabel("not a url")).toBe("not a url");+ });++ it("unread count starts at zero", () => {+ expect(store.getUnreadCount()).toBe(0);+ });+});++describe("omnidisc voice states", () => {+ it("tracks who is in which voice channel and moves users between channels", () => {+ const inst = store.addInstance({ url: "https://voice.example.org", name: "Voice" });+ store.applyVoiceState(inst.id, { user_id: "u1", guild_id: "g1", channel_id: "v1", self_mute: true });+ store.applyVoiceState(inst.id, { user_id: "u2", guild_id: "g1", channel_id: "v1" });+ expect(store.getVoiceMemberCount("v1")).toBe(2);+ expect(store.getVoiceMembers("v1").find((m) => m.userId === "u1")?.selfMute).toBe(true);+ expect(store.getVoiceChannelOfUser(inst.id, "u1")).toBe("v1");+ store.applyVoiceState(inst.id, { user_id: "u1", guild_id: "g1", channel_id: "v2" });+ expect(store.getVoiceMemberCount("v1")).toBe(1);+ expect(store.getVoiceMemberCount("v2")).toBe(1);+ store.applyVoiceState(inst.id, { user_id: "u1", guild_id: "g1", channel_id: null });+ expect(store.getVoiceMemberCount("v2")).toBe(0);+ expect(store.getVoiceChannelOfUser(inst.id, "u1")).toBeNull();+ store.applyVoiceState(inst.id, { channel_id: "v1" });+ expect(store.getVoiceMemberCount("v1")).toBe(1);+ });+});diff --git a/src/lib/stores/omnidisc-stream-store.svelte.ts b/src/lib/stores/omnidisc-stream-store.svelte.tsnew file mode 100644index 00000000..09a93de6--- /dev/null+++ b/src/lib/stores/omnidisc-stream-store.svelte.ts@@ -0,0 +1,298 @@+import { invoke } from "@tauri-apps/api/core";+import { listen, type UnlistenFn } from "@tauri-apps/api/event";+import { getInstanceStreamingPolicy } from "$lib/stores/omnidisc-store.svelte";+import { getVoiceSession } from "$lib/stores/omnidisc-voice-store.svelte";+import type { StreamingPolicy } from "$lib/omnidisc/types";++export type SourceKind = "display" | "window";+export type AudioMode = { mode: "none" } | { mode: "app"; pid: number } | { mode: "system" };+export type StreamMode = "text" | "game";++export interface SourceId {+ kind: SourceKind | "synthetic";+ id?: number;+ width?: number;+ height?: number;+}++export interface StreamSource {+ id: SourceId;+ title: string;+ app_name?: string;+ width: number;+ height: number;+ thumbnail?: string;+}++export interface AudioApp {+ pid: number;+ name: string;+ bundle_id: string;+}++export interface StreamSources {+ displays: StreamSource[];+ windows: StreamSource[];+ apps: AudioApp[];+ app_audio_supported: boolean;+ system_audio_supported: boolean;+}++export interface PublishStats {+ width: number;+ height: number;+ fps_captured: number;+ fps_encoded: number;+ fps_sent: number;+ bitrate_kbps: number;+ target_kbps: number;+ configured_kbps: number;+ codec?: "h264" | "h265";+ encoder: string;+ hardware?: boolean;+ encode_ms: number;+ keyframes: number;+ frames_dropped: number;+ rtt_ms?: number;+ packet_loss?: number;+ quality_limitation: string;+ audio: AudioMode;+}++export interface WatchStats {+ user_id: string;+ width: number;+ height: number;+ fps_received: number;+ fps_rendered: number;+ bitrate_kbps: number;+ codec: string;+ decoder: string;+ packet_loss?: number;+ jitter_ms?: number;+ frames_dropped: number;+ freeze_count: number;+}++export interface StreamStats {+ publishing: PublishStats | null;+ watching: WatchStats[];+}++export interface StartArgs {+ source: SourceId;+ fps: number;+ height?: number;+ audio: AudioMode;+ bitrate_kbps?: number;+ mode: StreamMode;+ cursor: boolean;+ policy?: StreamingPolicy;+}++const RESOLUTIONS = [540, 720, 1080, 1440, 2160];+const FRAMERATES = [15, 30, 60, 90, 120, 144];++let publishing = $state<PublishStats | null>(null);+let watchingIds = $state<string[]>([]);+let stats = $state<StreamStats | null>(null);+let busy = $state(false);+let lastError = $state<string | null>(null);+let streamers = $state<Record<string, boolean>>({});++let unlisten: UnlistenFn | null = null;+let initialized = false;++function errorText(e: unknown): string {+ return typeof e === "string" ? e : e instanceof Error ? e.message : String(e);+}++export function isPublishing(): boolean {+ return publishing !== null;+}++export function getPublishStats(): PublishStats | null {+ return publishing;+}++export function getStreamStats(): StreamStats | null {+ return stats;+}++export function isWatching(userId: string): boolean {+ return watchingIds.includes(userId);+}++export function isStreamBusy(): boolean {+ return busy;+}++export function getStreamError(): string | null {+ return lastError;+}++export function clearStreamError() {+ lastError = null;+}++export function isStreamer(userId: string): boolean {+ return streamers[userId] === true;+}++export function markStreamer(userId: string, on: boolean) {+ if (streamers[userId] === on) return;+ streamers = { ...streamers, [userId]: on };+}++export function allowedResolutions(policy: StreamingPolicy | null): number[] {+ const max = policy?.max_height ?? 2160;+ return RESOLUTIONS.filter((h) => h <= max);+}++export function allowedFramerates(policy: StreamingPolicy | null): number[] {+ const max = policy?.max_fps ?? 120;+ return FRAMERATES.filter((f) => f <= max);+}++export function widthForHeight(height: number): number {+ switch (height) {+ case 540: return 960;+ case 720: return 1280;+ case 1080: return 1920;+ case 1440: return 2560;+ case 2160: return 3840;+ default: return Math.round((height * 16) / 9) & ~1;+ }+}++function defaultKbps(height: number, fps: number): number {+ const base =+ height <= 540 ? 1500 : height <= 720 ? 2500 : height <= 1080 ? 5000 : height <= 1440 ? 9000 : 16000;+ const scale =+ fps <= 15 ? 0.65 : fps <= 30 ? 1.0 : fps <= 60 ? 1.6 : fps <= 90 ? 2.1 : fps <= 120 ? 2.6 : 2.9;+ return Math.max(300, Math.round(base * scale));+}++export function kbpsFor(policy: StreamingPolicy | null, height: number, fps: number): number {+ const key = `${height}p${fps}`;+ const raw = policy?.overrides?.[key] ?? defaultKbps(height, fps);+ const min = policy?.min_kbps ?? 500;+ const max = policy?.max_kbps ?? 20000;+ return Math.min(max, Math.max(min, raw));+}++export function codecFor(policy: StreamingPolicy | null, height: number, fps: number): "h264" | "h265" {+ const allow = policy?.allow_h265 ?? true;+ return allow && height >= 2160 && fps > 60 ? "h265" : "h264";+}++export function currentPolicy(): StreamingPolicy | null {+ const session = getVoiceSession();+ return getInstanceStreamingPolicy(session?.instanceId ?? null);+}++export async function refreshSources(): Promise<StreamSources | null> {+ try {+ return await invoke<StreamSources>("omnidisc_stream_sources");+ } catch (e) {+ lastError = errorText(e);+ return null;+ }+}++export async function startStream(args: StartArgs): Promise<boolean> {+ busy = true;+ lastError = null;+ try {+ const policy = currentPolicy() ?? undefined;+ publishing = await invoke<PublishStats>("omnidisc_stream_start", { args: { ...args, policy } });+ return true;+ } catch (e) {+ lastError = errorText(e);+ return false;+ } finally {+ busy = false;+ }+}++export async function stopStream(): Promise<void> {+ busy = true;+ try {+ await invoke("omnidisc_stream_stop");+ } catch (e) {+ console.warn("[omnidisc] stop stream failed", errorText(e));+ } finally {+ publishing = null;+ busy = false;+ }+}++export async function watchStream(userId: string): Promise<boolean> {+ busy = true;+ lastError = null;+ try {+ await invoke("omnidisc_stream_watch", { userId });+ if (!watchingIds.includes(userId)) watchingIds = [...watchingIds, userId];+ return true;+ } catch (e) {+ lastError = errorText(e);+ return false;+ } finally {+ busy = false;+ }+}++export async function unwatchStream(userId: string): Promise<void> {+ try {+ await invoke("omnidisc_stream_unwatch", { userId });+ } catch (e) {+ console.warn("[omnidisc] unwatch failed", errorText(e));+ } finally {+ watchingIds = watchingIds.filter((id) => id !== userId);+ }+}++export async function setStreamVolume(userId: string, gain: number): Promise<void> {+ try {+ await invoke("omnidisc_stream_set_volume", { userId, gain: Math.min(2, Math.max(0, gain)) });+ } catch (e) {+ console.warn("[omnidisc] stream volume failed", errorText(e));+ }+}++export async function refreshStreamStats(): Promise<StreamStats | null> {+ try {+ stats = await invoke<StreamStats>("omnidisc_stream_stats");+ if (stats.publishing) publishing = stats.publishing;+ return stats;+ } catch {+ return null;+ }+}++interface StreamEventPayload {+ type: string;+ audio?: AudioMode;+}++export async function initStream(): Promise<void> {+ if (initialized) return;+ initialized = true;+ try {+ unlisten = await listen<StreamEventPayload>("omnidisc://voice", (event) => {+ const p = event.payload;+ if (p.type === "stream_stopped") {+ publishing = null;+ }+ });+ } catch (e) {+ initialized = false;+ console.warn("[omnidisc] stream events subscribe failed", errorText(e));+ }+}++export function teardownStream() {+ if (unlisten) unlisten();+ unlisten = null;+ initialized = false;+}diff --git a/src/lib/stores/omnidisc-voice-store.svelte.ts b/src/lib/stores/omnidisc-voice-store.svelte.tsnew file mode 100644index 00000000..22c09e47--- /dev/null+++ b/src/lib/stores/omnidisc-voice-store.svelte.ts@@ -0,0 +1,706 @@+import { invoke } from "@tauri-apps/api/core";+import { listen, type UnlistenFn } from "@tauri-apps/api/event";+import {+ getChannel,+ getChannelInstanceId,+ getGuild,+ getInstance,+ getInstances,+ isEncryptedChannel,+} from "$lib/stores/omnidisc-store.svelte";+import { updateSettings } from "$lib/stores/settings-store.svelte";+import { showToast } from "$lib/stores/toast-store.svelte";+import { translateBackendError } from "$lib/error-translate";+import { t } from "$lib/i18n";+import { get } from "svelte/store";++export type VoiceConnState = "idle" | "connecting" | "connected" | "reconnecting" | "failed";+export type VoiceQuality = "excellent" | "good" | "poor" | "lost" | "unknown";+export type DeviceKind = "input" | "output";+export type DeviceStatus = "lost" | "recovered" | "switched_to_default" | "listen_only" | "silent";+export type DeviceLoss = "unplugged" | "permission_revoked" | "busy" | "failed";++export interface VoiceSession {+ instanceId: string;+ url: string;+ guildId: string | null;+ channelId: string;+ room: string;+ e2ee: boolean;+}++export interface IncomingCall {+ instanceId: string;+ url: string;+ channelId: string;+ fromUserId: string;+ ringingUntil: number;+}++export interface AudioDevice {+ id: string;+ name: string;+ default: boolean;+}++export interface AudioDevices {+ inputs: AudioDevice[];+ outputs: AudioDevice[];+}++export interface VoiceStatsWire {+ rtt_ms: number | null;+ packet_loss: number | null;+ jitter_ms: number | null;+ bitrate_out_kbps: number;+ bitrate_in_kbps: number;+ participants: number;+}++interface VoiceEventPayload {+ url: string | null;+ type: string;+ state?: VoiceConnState;+ reason?: string | null;+ user_id?: string;+ speaking?: boolean;+ quality?: VoiceQuality;+ rms_db?: number;+ peak?: number;+ code?: string;+ message?: string;+ kind?: DeviceKind;+ status?: DeviceStatus;+ cause?: DeviceLoss;+}++interface DispatchPayload {+ url: string;+ t: string;+ d: unknown;+}++interface VoiceSessionWire {+ url: string;+ guild_id?: string;+ channel_id: string;+ room: string;+ e2ee: boolean;+}++interface JoinResultWire {+ state: VoiceConnState;+ session: VoiceSessionWire;+ mic_error?: string;+ output_error?: string;+}++interface VoiceStatusWire {+ state: VoiceConnState;+ muted: boolean;+ deafened: boolean;+ session?: VoiceSessionWire;+ backend_available: boolean;+}++const VOLUMES_KEY = "omnidisc.voice.volumes";+const STATS_INTERVAL_MS = 5_000;+const MIC_SILENCE_AFTER_MS = 4_000;+const RING_TIMEOUT_MS = 60_000;++let session = $state<VoiceSession | null>(null);+let connState = $state<VoiceConnState>("idle");+let lastError = $state<string | null>(null);+let micError = $state<string | null>(null);+let outputError = $state<string | null>(null);+let muted = $state(false);+let deafened = $state(false);+let busy = $state(false);+let backendAvailable = $state(true);+let speaking = $state<Record<string, boolean>>({});+let quality = $state<VoiceQuality>("unknown");+let stats = $state<VoiceStatsWire | null>(null);+let volumes = $state<Record<string, number>>({});+let volumesLoaded = false;+let devices = $state<AudioDevices>({ inputs: [], outputs: [] });+let devicesLoading = $state(false);+let micTesting = $state(false);+let micLevel = $state<{ rmsDb: number; peak: number; at: number }>({ rmsDb: -100, peak: 0, at: 0 });++let incoming = $state<IncomingCall | null>(null);+let ringNow = $state(Date.now());++let unlisten: UnlistenFn | null = null;+let unlistenDispatch: UnlistenFn | null = null;+let initialized = false;+let statsTimer: ReturnType<typeof setInterval> | null = null;+let ringTimer: ReturnType<typeof setInterval> | null = null;++function errorText(e: unknown): string {+ return typeof e === "string" ? e : e instanceof Error ? e.message : String(e);+}++function hasStorage(): boolean {+ return typeof localStorage !== "undefined";+}++function loadVolumes() {+ if (volumesLoaded) return;+ volumesLoaded = true;+ if (!hasStorage()) return;+ try {+ const raw = localStorage.getItem(VOLUMES_KEY);+ if (!raw) return;+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return;+ const clean: Record<string, number> = {};+ for (const [k, v] of Object.entries(parsed)) {+ if (typeof v === "number" && Number.isFinite(v)) clean[k] = Math.min(2, Math.max(0, v));+ }+ volumes = clean;+ } catch {+ volumes = {};+ }+}++function persistVolumes() {+ if (!hasStorage()) return;+ try {+ localStorage.setItem(VOLUMES_KEY, JSON.stringify(volumes));+ } catch {+ return;+ }+}++function instanceByUrl(url: string) {+ return getInstances().find((i) => i.url === url) ?? null;+}++function localUserId(): string | null {+ if (!session) return null;+ return getInstance(session.instanceId)?.userId ?? null;+}++export function getVoiceSession(): VoiceSession | null {+ return session;+}++export function getVoiceState(): VoiceConnState {+ return connState;+}++export function isVoiceBusy(): boolean {+ return busy;+}++export function getVoiceError(): string | null {+ return lastError;+}++export function getMicError(): string | null {+ return micError;+}++export function getOutputError(): string | null {+ return outputError;+}++export function isMuted(): boolean {+ return muted;+}++export function isDeafened(): boolean {+ return deafened;+}++export function isVoiceBackendAvailable(): boolean {+ return backendAvailable;+}++export function isSpeaking(userId: string): boolean {+ return speaking[userId] === true;+}++export function getVoiceQuality(): VoiceQuality {+ return quality;+}++export function getVoiceStats(): VoiceStatsWire | null {+ return stats;+}++export function getVolume(userId: string): number {+ loadVolumes();+ return volumes[userId] ?? 1;+}++export function getDevices(): AudioDevices {+ return devices;+}++export function isDevicesLoading(): boolean {+ return devicesLoading;+}++export function isMicTesting(): boolean {+ return micTesting;+}++export function getMicLevel(): { rmsDb: number; peak: number; at: number } {+ return micLevel;+}++export function micLevelStale(now = Date.now()): boolean {+ return micTesting && micLevel.at > 0 && now - micLevel.at > MIC_SILENCE_AFTER_MS;+}++export function isInVoiceChannel(channelId: string): boolean {+ return session?.channelId === channelId && connState !== "idle";+}++export function clearVoiceError() {+ lastError = null;+}++function toSession(wire: VoiceSessionWire): VoiceSession | null {+ const instance = instanceByUrl(wire.url);+ if (!instance) return null;+ return {+ instanceId: instance.id,+ url: wire.url,+ guildId: wire.guild_id ?? null,+ channelId: wire.channel_id,+ room: wire.room,+ e2ee: wire.e2ee === true,+ };+}++function applyStatus(s: VoiceStatusWire) {+ connState = s.state;+ muted = s.muted;+ deafened = s.deafened;+ backendAvailable = s.backend_available;+ if (s.session && s.state !== "idle") {+ const mapped = toSession(s.session);+ if (mapped) session = mapped;+ } else if (s.state === "idle") {+ session = null;+ }+ syncStatsPolling();+}++function handleEvent(p: VoiceEventPayload) {+ switch (p.type) {+ case "state": {+ if (!p.state) return;+ connState = p.state;+ if (p.state === "idle") {+ session = null;+ speaking = {};+ quality = "unknown";+ stats = null;+ } else if (p.state === "failed") {+ lastError = p.reason ?? "ERR_VOICE_DISCONNECTED";+ speaking = {};+ } else if (p.state === "connected") {+ lastError = null;+ }+ syncStatsPolling();+ return;+ }+ case "speaking": {+ if (!p.user_id) return;+ if (speaking[p.user_id] === (p.speaking === true)) return;+ speaking = { ...speaking, [p.user_id]: p.speaking === true };+ return;+ }+ case "participant_left": {+ if (p.user_id && p.user_id in speaking) {+ const next = { ...speaking };+ delete next[p.user_id];+ speaking = next;+ }+ return;+ }+ case "quality": {+ if (p.quality && p.user_id && p.user_id === localUserId()) quality = p.quality;+ return;+ }+ case "level": {+ micLevel = { rmsDb: p.rms_db ?? -100, peak: p.peak ?? 0, at: Date.now() };+ return;+ }+ case "device": {+ if (!p.kind || !p.status) return;+ handleDeviceEvent(p.kind, p.status, p.cause);+ return;+ }+ case "error": {+ const code = p.code ?? "ERR_VOICE_DISCONNECTED";+ if (code === "ERR_VOICE_MIC_LOST") micError = code;+ else if (code === "ERR_VOICE_OUTPUT_LOST") outputError = code;+ else lastError = code;+ return;+ }+ default:+ return;+ }+}++function deviceErrorCode(kind: DeviceKind, cause: DeviceLoss | undefined): string {+ if (cause === "permission_revoked") {+ return kind === "input" ? "ERR_VOICE_MIC_PERMISSION" : "ERR_VOICE_OUTPUT_PERMISSION";+ }+ if (cause === "busy") return "ERR_VOICE_DEVICE_BUSY";+ return kind === "input" ? "ERR_VOICE_MIC_LOST" : "ERR_VOICE_OUTPUT_LOST";+}++function handleDeviceEvent(kind: DeviceKind, status: DeviceStatus, cause?: DeviceLoss) {+ const translate = get(t);+ switch (status) {+ case "lost":+ if (kind === "input") micError = "ERR_VOICE_MIC_LOST";+ else outputError = "ERR_VOICE_OUTPUT_LOST";+ return;+ case "recovered":+ if (kind === "input") micError = null;+ else outputError = null;+ showToast("success", translate(kind === "input" ? "omnidisc.voice.mic_back" : "omnidisc.voice.output_back"));+ return;+ case "switched_to_default":+ if (kind === "input") micError = null;+ else outputError = null;+ showToast(+ "info",+ translate(kind === "input" ? "omnidisc.voice.mic_switched" : "omnidisc.voice.output_switched"),+ );+ return;+ case "listen_only":+ micError = deviceErrorCode("input", cause);+ showToast("error", `${translate("omnidisc.voice.listen_only")} ${translateBackendError(micError, translate)}`);+ return;+ case "silent":+ outputError = deviceErrorCode("output", cause);+ showToast("error", `${translate("omnidisc.voice.no_output")} ${translateBackendError(outputError, translate)}`);+ return;+ default:+ return;+ }+}++function syncRingClock() {+ if (incoming && !ringTimer) {+ ringNow = Date.now();+ ringTimer = setInterval(() => {+ ringNow = Date.now();+ if (incoming && ringNow >= incoming.ringingUntil) dismissIncomingCall();+ }, 1_000);+ } else if (!incoming && ringTimer) {+ clearInterval(ringTimer);+ ringTimer = null;+ }+}++function handleDispatch(p: DispatchPayload) {+ if (p.t !== "CALL_RING" || typeof p.d !== "object" || p.d === null) return;+ const d = p.d as Record<string, unknown>;+ const channelId = typeof d.channel_id === "string" ? d.channel_id : null;+ const fromUserId = typeof d.from_user_id === "string" ? d.from_user_id : null;+ if (!channelId || !fromUserId) return;+ const instance = instanceByUrl(p.url);+ if (!instance) return;+ if (session?.channelId === channelId && connState !== "idle") return;+ incoming = {+ instanceId: instance.id,+ url: p.url,+ channelId,+ fromUserId,+ ringingUntil: Date.now() + RING_TIMEOUT_MS,+ };+ syncRingClock();+}++export function getIncomingCall(): IncomingCall | null {+ return incoming;+}++export function ringSecondsLeft(): number {+ if (!incoming) return 0;+ return Math.max(0, Math.ceil((incoming.ringingUntil - ringNow) / 1000));+}++export function dismissIncomingCall() {+ incoming = null;+ syncRingClock();+}++export async function acceptIncomingCall(): Promise<boolean> {+ const call = incoming;+ if (!call) return false;+ dismissIncomingCall();+ return joinVoice(call.channelId);+}++function syncStatsPolling() {+ const want = connState === "connected" || connState === "reconnecting";+ if (want && !statsTimer) {+ statsTimer = setInterval(() => {+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;+ void refreshStats();+ }, STATS_INTERVAL_MS);+ void refreshStats();+ } else if (!want && statsTimer) {+ clearInterval(statsTimer);+ statsTimer = null;+ stats = null;+ }+}++async function refreshStats() {+ try {+ stats = await invoke<VoiceStatsWire>("omnidisc_voice_stats");+ } catch {+ stats = null;+ }+}++export async function initVoice(): Promise<void> {+ loadVolumes();+ if (initialized) return;+ initialized = true;+ try {+ unlisten = await listen<VoiceEventPayload>("omnidisc://voice", (event) => {+ try {+ handleEvent(event.payload);+ } catch (e) {+ console.warn("[omnidisc] voice event failed", errorText(e));+ }+ });+ } catch (e) {+ initialized = false;+ console.warn("[omnidisc] could not subscribe to voice events", errorText(e));+ return;+ }+ try {+ unlistenDispatch = await listen<DispatchPayload>("omnidisc://dispatch", (event) => {+ try {+ handleDispatch(event.payload);+ } catch (e) {+ console.warn("[omnidisc] call ring failed", errorText(e));+ }+ });+ } catch (e) {+ console.warn("[omnidisc] could not subscribe to call rings", errorText(e));+ }+ try {+ applyStatus(await invoke<VoiceStatusWire>("omnidisc_voice_status"));+ } catch {+ return;+ }+}++export function teardownVoice() {+ if (unlisten) unlisten();+ unlisten = null;+ if (unlistenDispatch) unlistenDispatch();+ unlistenDispatch = null;+ initialized = false;+ if (statsTimer) clearInterval(statsTimer);+ statsTimer = null;+ if (ringTimer) clearInterval(ringTimer);+ ringTimer = null;+ incoming = null;+}++export async function joinVoice(channelId: string): Promise<boolean> {+ const channel = getChannel(channelId);+ const guild = getGuild(channel?.guildId ?? null);+ const instance = getInstance(guild?.instanceId ?? getChannelInstanceId(channelId));+ if (!channel || !instance) {+ lastError = "ERR_VOICE_NOT_CONNECTED";+ return false;+ }+ if (instance.status !== "connected") {+ lastError = "ERR_NOT_CONNECTED";+ return false;+ }+ busy = true;+ lastError = null;+ micError = null;+ outputError = null;+ connState = "connecting";+ session = {+ instanceId: instance.id,+ url: instance.url,+ guildId: guild?.id ?? null,+ channelId,+ room: "",+ e2ee: false,+ };+ try {+ const result = await invoke<JoinResultWire>("omnidisc_voice_join", {+ url: instance.url,+ guildId: guild?.id ?? null,+ channelId,+ recipientIds: isEncryptedChannel(channelId) ? (channel.recipientIds ?? null) : null,+ });+ connState = result.state;+ session = toSession(result.session) ?? session;+ micError = result.mic_error ?? null;+ outputError = result.output_error ?? null;+ syncStatsPolling();+ return true;+ } catch (e) {+ lastError = errorText(e);+ connState = "failed";+ syncStatsPolling();+ return false;+ } finally {+ busy = false;+ }+}++export async function leaveVoice(): Promise<void> {+ busy = true;+ try {+ await invoke("omnidisc_voice_leave");+ } catch (e) {+ console.warn("[omnidisc] voice leave failed", errorText(e));+ } finally {+ busy = false;+ session = null;+ connState = "idle";+ speaking = {};+ quality = "unknown";+ lastError = null;+ micError = null;+ outputError = null;+ syncStatsPolling();+ }+}++export async function retryVoice(): Promise<boolean> {+ const target = session?.channelId;+ if (!target) return false;+ return joinVoice(target);+}++export async function toggleMute(): Promise<void> {+ const next = !muted;+ muted = next;+ try {+ applyStatus(await invoke<VoiceStatusWire>("omnidisc_voice_set_mute", { muted: next }));+ } catch (e) {+ muted = !next;+ console.warn("[omnidisc] mute failed", errorText(e));+ }+}++export async function toggleDeafen(): Promise<void> {+ const next = !deafened;+ deafened = next;+ try {+ applyStatus(await invoke<VoiceStatusWire>("omnidisc_voice_set_deaf", { deafened: next }));+ } catch (e) {+ deafened = !next;+ console.warn("[omnidisc] deafen failed", errorText(e));+ }+}++export function setVolume(userId: string, gain: number) {+ loadVolumes();+ const clamped = Math.min(2, Math.max(0, Number.isFinite(gain) ? gain : 1));+ if (clamped === 1) {+ const next = { ...volumes };+ delete next[userId];+ volumes = next;+ } else {+ volumes = { ...volumes, [userId]: clamped };+ }+ persistVolumes();+ invoke("omnidisc_voice_set_volume", { userId, gain: clamped }).catch((e: unknown) => {+ console.warn("[omnidisc] volume failed", errorText(e));+ });+}++export async function refreshDevices(): Promise<void> {+ devicesLoading = true;+ try {+ devices = await invoke<AudioDevices>("omnidisc_voice_devices");+ } catch (e) {+ console.warn("[omnidisc] device list failed", errorText(e));+ } finally {+ devicesLoading = false;+ }+}++export async function setDevice(kind: DeviceKind, id: string | null): Promise<string | null> {+ const key = kind === "input" ? "input_device" : "output_device";+ try {+ await invoke("omnidisc_voice_set_device", { kind, id });+ } catch (e) {+ return errorText(e);+ }+ try {+ await updateSettings({ omnidisc: { voice: { [key]: id } } });+ } catch (e) {+ console.warn("[omnidisc] device preference not saved", errorText(e));+ }+ return null;+}++export async function setNoiseSuppression(enabled: boolean): Promise<void> {+ try {+ await invoke("omnidisc_voice_set_noise_suppression", { enabled });+ } catch (e) {+ console.warn("[omnidisc] noise suppression failed", errorText(e));+ }+ await updateSettings({ omnidisc: { voice: { noise_suppression: enabled } } });+}++export async function setPttKey(key: string): Promise<void> {+ await updateSettings({ omnidisc: { voice: { ptt_key: key } } });+ try {+ await invoke("omnidisc_voice_ptt", { pressed: false });+ } catch {+ return;+ }+}++export async function setVadThreshold(db: number): Promise<void> {+ await updateSettings({ omnidisc: { voice: { vad_threshold_db: db } } });+}++export async function setDucking(percent: number): Promise<void> {+ const clamped = Math.min(100, Math.max(0, Math.round(percent)));+ try {+ await invoke("omnidisc_voice_set_ducking", { percent: clamped });+ } catch (e) {+ console.warn("[omnidisc] ducking failed", errorText(e));+ }+ await updateSettings({ omnidisc: { voice: { ducking_percent: clamped } } });+}++export async function setRelayOnly(enabled: boolean): Promise<void> {+ await updateSettings({ omnidisc: { voice: { relay_only: enabled } } });+}++export function isE2ee(): boolean {+ return session?.e2ee === true;+}++export function pushToTalk(pressed: boolean) {+ invoke("omnidisc_voice_ptt", { pressed }).catch(() => undefined);+}++export async function setMicTest(on: boolean): Promise<string | null> {+ try {+ await invoke("omnidisc_voice_mic_test", { enabled: on });+ micTesting = on;+ if (on) micLevel = { rmsDb: -100, peak: 0, at: Date.now() };+ return null;+ } catch (e) {+ micTesting = false;+ return errorText(e);+ }+}diff --git a/src/lib/stores/omnidisc-voice-store.test.ts b/src/lib/stores/omnidisc-voice-store.test.tsnew file mode 100644index 00000000..bbdd6047--- /dev/null+++ b/src/lib/stores/omnidisc-voice-store.test.ts@@ -0,0 +1,47 @@+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(() => Promise.resolve()) }));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(() => Promise.resolve(() => undefined)) }));++type VoiceStore = typeof import("./omnidisc-voice-store.svelte");++let store: VoiceStore;++beforeAll(async () => {+ vi.stubGlobal("$state", <T>(value: T) => value);+ vi.stubGlobal("$derived", <T>(value: T) => value);+ store = await import("./omnidisc-voice-store.svelte");+});++afterAll(() => {+ vi.unstubAllGlobals();+});++describe("omnidisc voice volumes", () => {+ it("defaults to 100%, clamps to 0–200% and forgets the default", () => {+ expect(store.getVolume("u1")).toBe(1);+ store.setVolume("u1", 1.5);+ expect(store.getVolume("u1")).toBe(1.5);+ store.setVolume("u1", 9);+ expect(store.getVolume("u1")).toBe(2);+ store.setVolume("u1", -3);+ expect(store.getVolume("u1")).toBe(0);+ store.setVolume("u1", 1);+ expect(store.getVolume("u1")).toBe(1);+ store.setVolume("u2", Number.NaN);+ expect(store.getVolume("u2")).toBe(1);+ });++ it("starts idle with no session", () => {+ expect(store.getVoiceState()).toBe("idle");+ expect(store.getVoiceSession()).toBeNull();+ expect(store.isInVoiceChannel("v1")).toBe(false);+ expect(store.isSpeaking("u1")).toBe(false);+ });++ it("claims encryption only when the backend says a room key is in use", () => {+ expect(store.isE2ee()).toBe(false);+ expect(store.getIncomingCall()).toBeNull();+ expect(store.ringSecondsLeft()).toBe(0);+ });+});diff --git a/src/lib/stores/settings-store.svelte.ts b/src/lib/stores/settings-store.svelte.tsindex 7d2fc40b..54f0f157 100644--- a/src/lib/stores/settings-store.svelte.ts+++ b/src/lib/stores/settings-store.svelte.ts@@ -90,6 +90,10 @@ export type AppSettings = {app_id: string;large_image_key: string;};+ omnidisc?: {+ enabled?: boolean;+ voice?: OmnidiscVoiceSettings;+ };league?: {enabled?: boolean;auto_accept?: boolean;@@ -127,6 +131,16 @@ export type AppSettings = {typography?: TypographySettings;};+export type OmnidiscVoiceSettings = {+ ptt_key?: string;+ noise_suppression?: boolean;+ input_device?: string | null;+ output_device?: string | null;+ vad_threshold_db?: number;+ ducking_percent?: number;+ relay_only?: boolean;+};+export type TypographySettings = {font_display: string;font_body: string;diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelteindex 74c56a41..af1bcca2 100644--- a/src/routes/+layout.svelte+++ b/src/routes/+layout.svelte@@ -9,6 +9,11 @@import { listen } from "@tauri-apps/api/event";import { initDownloadListener } from "$lib/stores/download-listener";import { getCounts } from "$lib/stores/download-store.svelte";+ import {+ getUnreadCount as getChatUnreadCount,+ getMentionTotal as getChatMentionCount,+ initOmnidisc,+ } from "$lib/stores/omnidisc-store.svelte";import { getSettings } from "$lib/stores/settings-store.svelte";import { queueExternalPrefill, type ExternalUrlEvent } from "$lib/stores/external-url-store.svelte";import Toast from "$components/toast/Toast.svelte";@@ -44,7 +49,11 @@: []);- let allNav = $derived([...CORE_NAV_ITEMS, ...leagueNavItems, ...pluginNavItems].sort((a, b) => (a.order ?? 50) - (b.order ?? 50)));+ let coreNavItems = $derived(+ CORE_NAV_ITEMS.filter((item) => item.href !== "/omnidisc" || (getSettings()?.omnidisc?.enabled ?? false))+ );++ let allNav = $derived([...coreNavItems, ...leagueNavItems, ...pluginNavItems].sort((a, b) => (a.order ?? 50) - (b.order ?? 50)));let primaryNav = $derived(allNav.filter((item) => item.group === "primary"));let appNav = $derived(allNav.filter((item) => item.group === "app"));let pluginNav = $derived(allNav.filter((item) => item.group === "plugins"));@@ -55,9 +64,11 @@let counts = $derived(getCounts());let badgeLabel = $derived(counts.badge > 99 ? "99+" : String(counts.badge));+ let chatBadgeCount = $derived(getChatMentionCount() || getChatUnreadCount());let settings = $derived(getSettings());let isStudyRoute = $derived(page.url.pathname.startsWith("/study"));+ let isStreamPopout = $derived(page.url.pathname === "/omnidisc/stream");let isCoreRoute = $derived(page.url.pathname === "/" ||page.url.pathname.startsWith("/downloads") ||@@ -118,6 +129,13 @@.catch(() => {});}+ let omnidiscStarted = false;+ $effect(() => {+ if (omnidiscStarted || !(getSettings()?.omnidisc?.enabled ?? false)) return;+ omnidiscStarted = true;+ void initOmnidisc();+ });+onMount(() => {initDownloadListener();@@ -287,8 +305,13 @@});</script>+{#if isStreamPopout}+ <div class="stream-popout">+ {@render children()}+ </div>+{:else}<div class="shell" data-reduce-motion={settings?.accessibility?.reduce_motion} data-reduce-transparency={settings?.accessibility?.reduce_transparency}>- <AppSidebar {primaryNav} {appNav} {pluginNav} {badgeLabel} />+ <AppSidebar {primaryNav} {appNav} {pluginNav} {badgeLabel} {chatBadgeCount} /><div class="shell-body"><AppToolbar />@@ -329,6 +352,7 @@</main></div></div>+{/if}<Toast /><CommandPalette />diff --git a/src/routes/omnidisc/+layout.svelte b/src/routes/omnidisc/+layout.sveltenew file mode 100644index 00000000..a240e1df--- /dev/null+++ b/src/routes/omnidisc/+layout.svelte@@ -0,0 +1,139 @@+<script lang="ts">+ import { page } from "$app/state";+ import { goto } from "$app/navigation";+ import { onMount } from "svelte";+ import { t } from "$lib/i18n";+ import { getSettings } from "$lib/stores/settings-store.svelte";+ import { hasInstances, isMemberListOpen, initOmnidisc } from "$lib/stores/omnidisc-store.svelte";+ import { initVoice } from "$lib/stores/omnidisc-voice-store.svelte";+ import { initStream } from "$lib/stores/omnidisc-stream-store.svelte";+ import InstanceRail from "$components/omnidisc/InstanceRail.svelte";+ import ChannelList from "$components/omnidisc/ChannelList.svelte";+ import MemberList from "$components/omnidisc/MemberList.svelte";+ import type { Snippet } from "svelte";++ let { children }: { children: Snippet } = $props();++ let settings = $derived(getSettings());+ let enabled = $derived(settings?.omnidisc?.enabled ?? false);+ let showShell = $derived(hasInstances());+ let inChannel = $derived(page.url.pathname.startsWith("/omnidisc/g/"));+ let isStreamPopout = $derived(page.url.pathname === "/omnidisc/stream");+ let showMembers = $derived(inChannel && isMemberListOpen());++ onMount(() => {+ void initOmnidisc();+ void initVoice();+ void initStream();+ });+</script>++{#if isStreamPopout}+ {@render children()}+{:else}+<div class="od-root">+ {#if !settings}+ <div class="od-blank" aria-busy="true"></div>+ {:else if !enabled}+ <div class="od-guard">+ <div class="guard-card">+ <h2>{$t("omnidisc.disabled_title")}</h2>+ <p>{$t("omnidisc.disabled_body")}</p>+ <button type="button" class="button primary" onclick={() => goto("/settings")}>{$t("omnidisc.open_settings")}</button>+ </div>+ </div>+ {:else if !showShell}+ {@render children()}+ {:else}+ <div class="od-shell">+ <InstanceRail />+ <ChannelList />+ <section class="od-main">+ {@render children()}+ </section>+ {#if showMembers}+ <MemberList />+ {/if}+ </div>+ {/if}+</div>+{/if}++<style>+ .od-root {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ background: var(--bg);+ color: var(--text);+ }++ .od-blank {+ flex: 1;+ }++ .od-guard {+ flex: 1;+ display: flex;+ align-items: flex-start;+ padding: var(--space-5);+ }++ .guard-card {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: var(--space-3);+ max-width: 480px;+ padding: var(--space-5);+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--border-radius);+ }++ .guard-card h2 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .guard-card p {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .guard-card .primary {+ background: var(--accent);+ color: var(--on-accent);+ }++ .od-shell {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: row;+ }++ .od-main {+ flex: 1;+ min-width: 0;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ @media (max-width: 900px) {+ .od-shell :global(.member-list) {+ display: none;+ }+ }++ @media (max-width: 700px) {+ .od-shell :global(.channel-list) {+ display: none;+ }+ }+</style>diff --git a/src/routes/omnidisc/+page.svelte b/src/routes/omnidisc/+page.sveltenew file mode 100644index 00000000..f28e2c44--- /dev/null+++ b/src/routes/omnidisc/+page.svelte@@ -0,0 +1,155 @@+<script lang="ts">+ import { page } from "$app/state";+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { hasInstances, resetConnect } from "$lib/stores/omnidisc-store.svelte";+ import ConnectInstanceForm from "$components/omnidisc/ConnectInstanceForm.svelte";++ let hasAny = $derived(hasInstances());+ let addRequested = $derived(page.url.searchParams.get("add") === "1");+ let showForm = $state(false);+ let onboarding = $derived(!hasAny || addRequested || showForm);++ function done() {+ showForm = false;+ if (addRequested) goto("/omnidisc");+ }++ function startAdd() {+ resetConnect();+ showForm = true;+ }+</script>++<div class="od-home" class:onboarding>+ {#if onboarding}+ <section class="hero">+ <div class="hero-mark" aria-hidden="true">+ <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">+ <path d="M21 12a8 8 0 0 1-8 8H7l-4 3V12a8 8 0 0 1 8-8h2a8 8 0 0 1 8 8z" />+ </svg>+ </div>+ <h1 class="hero-title">{$t("omnidisc.connect.title")}</h1>+ <p class="hero-sub">{$t("omnidisc.connect.subtitle")}</p>+ <ConnectInstanceForm onDone={done} />+ {#if hasAny}+ <button type="button" class="link" onclick={done}>{$t("common.cancel")}</button>+ {/if}+ </section>+ {:else}+ <section class="pick">+ <h2>{$t("omnidisc.home.pick_channel_title")}</h2>+ <p>{$t("omnidisc.home.pick_channel_body")}</p>+ <button type="button" class="secondary" onclick={startAdd}>{$t("omnidisc.connect.add_another")}</button>+ </section>+ {/if}+</div>++<style>+ .od-home {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: var(--space-6) var(--space-5);+ overflow-y: auto;+ }++ .hero {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-3);+ width: 100%;+ max-width: 420px;+ text-align: center;+ }++ .hero-mark {+ width: 56px;+ height: 56px;+ border-radius: var(--radius-lg);+ display: grid;+ place-items: center;+ background: var(--accent-soft);+ color: var(--accent);+ margin-bottom: var(--space-2);+ }++ .hero-title {+ margin: 0;+ font-size: var(--text-xl);+ font-weight: 600;+ color: var(--text);+ }++ .hero-sub {+ margin: 0 0 var(--space-3);+ font-size: var(--text-base);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .hero :global(.connect) {+ text-align: left;+ }++ .link {+ border: none;+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ padding: var(--space-2);+ }++ .link:hover {+ color: var(--text);+ }++ .pick {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-2);+ text-align: center;+ max-width: 360px;+ }++ .pick h2 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .pick p {+ margin: 0 0 var(--space-3);+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .secondary {+ padding: 8px var(--space-4);+ border-radius: var(--radius-md);+ border: 1px solid var(--border-hi);+ background: var(--surface);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .secondary:hover {+ background: var(--surface-hi);+ }++ .secondary:focus-visible,+ .link:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }+</style>diff --git a/src/routes/omnidisc/dm/[id]/+page.svelte b/src/routes/omnidisc/dm/[id]/+page.sveltenew file mode 100644index 00000000..fbf7f35e--- /dev/null+++ b/src/routes/omnidisc/dm/[id]/+page.svelte@@ -0,0 +1,122 @@+<script lang="ts">+ import { page } from "$app/state";+ import { t } from "$lib/i18n";+ import {+ selectChannel,+ getChannel,+ dmTitle,+ getSelectedInstance,+ } from "$lib/stores/omnidisc-store.svelte";+ import ChatView from "$components/omnidisc/ChatView.svelte";+ import {+ getVoiceSession,+ getVoiceState,+ isVoiceBusy,+ joinVoice,+ leaveVoice,+ } from "$lib/stores/omnidisc-voice-store.svelte";++ let channelId = $derived(page.params.id ?? "");+ let channel = $derived(getChannel(channelId));+ let instance = $derived(getSelectedInstance());+ let title = $derived(channel ? dmTitle(channel) : "");+ let canSend = $derived(instance?.status === "connected");+ let session = $derived(getVoiceSession());+ let connState = $derived(getVoiceState());+ let voiceBusy = $derived(isVoiceBusy());+ let inThisCall = $derived(session?.channelId === channelId && connState !== "idle");+ let inAnotherCall = $derived(!!session && session.channelId !== channelId && connState !== "idle");++ $effect(() => {+ selectChannel(null, channelId);+ });+</script>++{#if !channel || !instance}+ <div class="not-found">+ <h3>{$t("omnidisc.dm.not_found")}</h3>+ <p>{$t("omnidisc.dm.not_found_hint")}</p>+ </div>+{:else}+ <ChatView+ instanceId={instance.id}+ {channelId}+ title={title || $t("omnidisc.dm.title")}+ kind="dm"+ {canSend}+ >+ {#snippet headerExtra()}+ <button+ type="button"+ class="icon-button"+ class:leave={inThisCall}+ disabled={!canSend || voiceBusy || inAnotherCall}+ onclick={() => (inThisCall ? void leaveVoice() : void joinVoice(channelId))}+ aria-label={inThisCall ? $t("omnidisc.call.leave") : $t("omnidisc.call.start")}+ title={inThisCall ? $t("omnidisc.call.leave") : $t("omnidisc.call.start_hint")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M10.7 13.3a15 15 0 0 1-2-2.6l1.4-1.4a1 1 0 0 0 .2-1L9.5 4.8a1 1 0 0 0-1-.8H5a1 1 0 0 0-1 1c0 3.5 1.3 6.8 3.5 9.4" />+ <path d="M13.3 10.7c.9.8 1.8 1.5 2.7 2l1.4-1.4a1 1 0 0 1 1-.2l3.5.8a1 1 0 0 1 .8 1V16a1 1 0 0 1-1 1 16 16 0 0 1-9.4-3.5" />+ {#if inThisCall}<path d="M4 20L20 4" />{/if}+ </svg>+ </button>+ {/snippet}+ </ChatView>+{/if}++<style>+ .icon-button {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ cursor: pointer;+ }++ .icon-button:hover:not(:disabled) {+ background: var(--fill-1);+ color: var(--text);+ }++ .icon-button.leave {+ color: var(--danger);+ }++ .icon-button:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .icon-button:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .not-found {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-1);+ padding: var(--space-5);+ text-align: center;+ }++ .not-found h3 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .not-found p {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ }+</style>diff --git a/src/routes/omnidisc/friends/+page.svelte b/src/routes/omnidisc/friends/+page.sveltenew file mode 100644index 00000000..23a9253a--- /dev/null+++ b/src/routes/omnidisc/friends/+page.svelte@@ -0,0 +1,543 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ acceptFriend,+ addFriend,+ blockUser,+ getSelectedInstance,+ getPresence,+ getRelationships,+ getUser,+ loadRelationships,+ openDm,+ removeFriend,+ userName,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { OmnidiscRelationship } from "$lib/omnidisc/types";+ import ProfilePopover from "$components/omnidisc/ProfilePopover.svelte";++ type Tab = "online" | "all" | "pending" | "blocked";++ let instance = $derived(getSelectedInstance());+ let connected = $derived(instance?.status === "connected");+ let tab = $state<Tab>("online");+ let username = $state("");+ let addBusy = $state(false);+ let addError = $state<string | null>(null);+ let addOk = $state(false);+ let listError = $state<string | null>(null);+ let loading = $state(true);+ let busyId = $state<string | null>(null);+ let profile = $state<{ userId: string; x: number; y: number } | null>(null);+ let loadedFor = $state<string | null>(null);++ let relationships = $derived(getRelationships(instance?.id ?? null));+ let friends = $derived(relationships.filter((r) => r.kind === "friend"));+ let incoming = $derived(relationships.filter((r) => r.kind === "incoming_request"));+ let outgoing = $derived(relationships.filter((r) => r.kind === "outgoing_request"));+ let blocked = $derived(relationships.filter((r) => r.kind === "blocked"));+ let onlineFriends = $derived(+ friends.filter((r) => instance && getPresence(instance.id, r.userId) !== "offline"),+ );++ $effect(() => {+ const id = instance?.id;+ if (!id || loadedFor === id) return;+ loadedFor = id;+ loading = true;+ listError = null;+ loadRelationships(id)+ .catch((e) => {+ listError = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ })+ .finally(() => {+ loading = false;+ });+ });++ function fail(e: unknown): string {+ return translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function submitAdd(e: Event) {+ e.preventDefault();+ const id = instance?.id;+ const name = username.trim();+ if (!id || !name) return;+ addBusy = true;+ addError = null;+ addOk = false;+ try {+ await addFriend(id, name);+ addOk = true;+ username = "";+ } catch (err) {+ addError = fail(err);+ } finally {+ addBusy = false;+ }+ }++ async function act(userId: string, fn: () => Promise<void>) {+ busyId = userId;+ listError = null;+ try {+ await fn();+ } catch (e) {+ listError = fail(e);+ } finally {+ busyId = null;+ }+ }++ async function message(userId: string) {+ const id = instance?.id;+ if (!id) return;+ await act(userId, async () => {+ const channel = await openDm(id, userId);+ if (channel) await goto(`/omnidisc/dm/${channel.id}`);+ });+ }++ function openProfile(userId: string, anchor: HTMLElement) {+ const rect = anchor.getBoundingClientRect();+ const width = typeof window !== "undefined" ? window.innerWidth : 1280;+ const height = typeof window !== "undefined" ? window.innerHeight : 800;+ profile = { userId, x: Math.min(rect.left, width - 320), y: Math.min(rect.bottom + 6, height - 420) };+ }++ function initial(name: string): string {+ return name.trim().charAt(0).toUpperCase() || "?";+ }++ let visible = $derived.by<OmnidiscRelationship[]>(() => {+ switch (tab) {+ case "online":+ return onlineFriends;+ case "all":+ return friends;+ case "pending":+ return [...incoming, ...outgoing];+ case "blocked":+ return blocked;+ }+ });+</script>++<div class="friends">+ <header class="bar">+ <h2 class="title">{$t("omnidisc.friends.title")}</h2>+ <nav class="tabs" aria-label={$t("omnidisc.friends.title")}>+ <button type="button" class="tab" class:on={tab === "online"} onclick={() => (tab = "online")}>{$t("omnidisc.friends.tab_online")}</button>+ <button type="button" class="tab" class:on={tab === "all"} onclick={() => (tab = "all")}>{$t("omnidisc.friends.tab_all", { count: friends.length })}</button>+ <button type="button" class="tab" class:on={tab === "pending"} onclick={() => (tab = "pending")}>+ {$t("omnidisc.friends.tab_pending")}+ {#if incoming.length > 0}<span class="pill">{incoming.length}</span>{/if}+ </button>+ <button type="button" class="tab" class:on={tab === "blocked"} onclick={() => (tab = "blocked")}>{$t("omnidisc.friends.tab_blocked")}</button>+ </nav>+ </header>++ <div class="content">+ <form class="add" onsubmit={submitAdd}>+ <label class="add-label" for="od-friend-username">{$t("omnidisc.friends.add_label")}</label>+ <div class="add-row">+ <input+ id="od-friend-username"+ class="input"+ type="text"+ bind:value={username}+ placeholder={$t("omnidisc.friends.add_placeholder")}+ spellcheck="false"+ maxlength="32"+ disabled={!connected || addBusy}+ />+ <button type="submit" class="primary" disabled={!connected || addBusy || username.trim().length === 0}>+ {addBusy ? $t("omnidisc.friends.sending") : $t("omnidisc.friends.send_request")}+ </button>+ </div>+ {#if addError}+ <p class="error" role="alert">{addError}</p>+ {:else if addOk}+ <p class="ok" role="status">{$t("omnidisc.friends.request_sent")}</p>+ {:else}+ <p class="hint">{$t("omnidisc.friends.add_hint")}</p>+ {/if}+ </form>++ {#if listError}+ <p class="error" role="alert">{listError}</p>+ {/if}++ {#if loading}+ <div class="state" aria-busy="true">+ {#each Array(4) as _, i (i)}+ <span class="skeleton-line"></span>+ {/each}+ </div>+ {:else if visible.length === 0}+ <div class="state">+ <p class="state-title">{$t(`omnidisc.friends.empty_${tab}_title`)}</p>+ <p class="state-body">{$t(`omnidisc.friends.empty_${tab}_body`)}</p>+ </div>+ {:else}+ <ul class="list">+ {#each visible as rel (rel.userId)}+ {@const name = instance ? userName(instance.id, rel.userId) : rel.userId}+ {@const user = instance ? getUser(instance.id, rel.userId) : null}+ <li class="row" aria-busy={busyId === rel.userId}>+ <button type="button" class="who" onclick={(e) => openProfile(rel.userId, e.currentTarget)}>+ <span class="avatar" aria-hidden="true">+ {initial(name)}+ <span class="dot" class:online={instance && getPresence(instance.id, rel.userId) !== "offline"}></span>+ </span>+ <span class="names">+ <span class="name">{name}</span>+ <span class="handle">@{user?.username ?? "…"}</span>+ </span>+ </button>+ <div class="row-actions">+ {#if rel.kind === "friend"}+ <button type="button" class="ghost" onclick={() => void message(rel.userId)} disabled={!connected}>{$t("omnidisc.profile.message")}</button>+ <button type="button" class="ghost" onclick={() => instance && void act(rel.userId, () => removeFriend(instance.id, rel.userId))}>{$t("omnidisc.friends.remove")}</button>+ {:else if rel.kind === "incoming_request"}+ <button type="button" class="primary small" onclick={() => instance && void act(rel.userId, () => acceptFriend(instance.id, rel.userId))}>{$t("omnidisc.friends.accept")}</button>+ <button type="button" class="ghost" onclick={() => instance && void act(rel.userId, () => removeFriend(instance.id, rel.userId))}>{$t("omnidisc.friends.decline")}</button>+ {:else if rel.kind === "outgoing_request"}+ <span class="tag">{$t("omnidisc.friends.pending_out")}</span>+ <button type="button" class="ghost" onclick={() => instance && void act(rel.userId, () => removeFriend(instance.id, rel.userId))}>{$t("omnidisc.friends.cancel_request")}</button>+ {:else}+ <button type="button" class="ghost" onclick={() => instance && void act(rel.userId, () => removeFriend(instance.id, rel.userId))}>{$t("omnidisc.friends.unblock")}</button>+ {/if}+ {#if rel.kind !== "blocked"}+ <button type="button" class="ghost danger" onclick={() => instance && void act(rel.userId, () => blockUser(instance.id, rel.userId))}>{$t("omnidisc.friends.block")}</button>+ {/if}+ </div>+ </li>+ {/each}+ </ul>+ {/if}+ </div>+</div>++{#if profile && instance}+ <ProfilePopover+ instanceId={instance.id}+ userId={profile.userId}+ x={profile.x}+ y={profile.y}+ onClose={() => (profile = null)}+ />+{/if}++<style>+ .friends {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .bar {+ display: flex;+ align-items: center;+ gap: var(--space-4);+ min-height: 48px;+ padding: 0 var(--space-4);+ border-bottom: 1px solid var(--border);+ }++ .title {+ margin: 0;+ font-size: var(--text-base);+ font-weight: 600;+ color: var(--text);+ }++ .tabs {+ display: flex;+ gap: var(--space-1);+ }++ .tab {+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ padding: 4px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .tab:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .tab.on {+ background: var(--accent-soft);+ color: var(--accent);+ font-weight: 600;+ }++ .pill {+ min-width: 16px;+ padding: 0 5px;+ border-radius: var(--radius-full);+ background: var(--accent);+ color: var(--on-accent);+ font-size: var(--text-xs);+ font-weight: 600;+ text-align: center;+ }++ .content {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: var(--space-4);+ max-width: 720px;+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ }++ .add {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3);+ border: 1px solid var(--border);+ border-radius: var(--border-radius);+ background: var(--surface);+ }++ .add-label {+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--text);+ }++ .add-row {+ display: flex;+ gap: var(--space-2);+ }++ .input {+ flex: 1;+ min-width: 0;+ padding: 8px var(--space-3);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ }++ .input:focus-visible,+ .primary:focus-visible,+ .ghost:focus-visible,+ .tab:focus-visible,+ .who:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .primary {+ padding: 8px var(--space-4);+ border: none;+ border-radius: var(--radius-sm);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ cursor: pointer;+ }++ .primary.small {+ padding: 4px var(--space-3);+ }++ .primary:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .hint,+ .ok,+ .error {+ margin: 0;+ font-size: var(--text-xs);+ }++ .hint {+ color: var(--text-muted);+ }++ .ok {+ color: var(--success);+ }++ .error {+ color: var(--danger);+ }++ .state {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ }++ .state-title {+ margin: 0;+ font-size: var(--text-base);+ color: var(--text);+ }++ .state-body {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .skeleton-line {+ height: 44px;+ border-radius: var(--radius-sm);+ background: var(--fill-2);+ animation: pulse 1.4s ease-in-out infinite;+ }++ .list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ }++ .row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-3);+ padding: var(--space-2) 0;+ border-bottom: 1px solid var(--border);+ }++ .who {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ border: none;+ background: transparent;+ color: var(--text);+ font: inherit;+ cursor: pointer;+ text-align: left;+ min-width: 0;+ }++ .avatar {+ position: relative;+ width: 32px;+ height: 32px;+ flex: 0 0 32px;+ border-radius: var(--radius-full);+ background: var(--accent-soft);+ color: var(--accent);+ display: grid;+ place-items: center;+ font-size: var(--text-sm);+ font-weight: 600;+ }++ .dot {+ position: absolute;+ right: -1px;+ bottom: -1px;+ width: 10px;+ height: 10px;+ border-radius: var(--radius-full);+ border: 2px solid var(--bg);+ background: var(--text-dim);+ }++ .dot.online {+ background: var(--success);+ }++ .names {+ display: flex;+ flex-direction: column;+ min-width: 0;+ }++ .name {+ font-size: var(--text-sm);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .handle {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ .row-actions {+ display: flex;+ align-items: center;+ gap: var(--space-1);+ flex-wrap: wrap;+ justify-content: flex-end;+ }++ .ghost {+ padding: 4px var(--space-2);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-xs);+ cursor: pointer;+ }++ .ghost:hover:not(:disabled) {+ background: var(--fill-1);+ }++ .ghost:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .ghost.danger {+ color: var(--danger);+ }++ .tag {+ font-size: var(--text-xs);+ color: var(--text-muted);+ }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @media (prefers-reduced-motion: reduce) {+ .skeleton-line {+ animation: none;+ }+ }+</style>diff --git a/src/routes/omnidisc/g/[guild]/[channel]/+page.svelte b/src/routes/omnidisc/g/[guild]/[channel]/+page.sveltenew file mode 100644index 00000000..dc8b4578--- /dev/null+++ b/src/routes/omnidisc/g/[guild]/[channel]/+page.svelte@@ -0,0 +1,134 @@+<script lang="ts">+ import { page } from "$app/state";+ import { t } from "$lib/i18n";+ import {+ selectChannel,+ getGuild,+ canInChannel,+ isMemberListOpen,+ toggleMemberList,+ getInstance,+ } from "$lib/stores/omnidisc-store.svelte";+ import ChatView from "$components/omnidisc/ChatView.svelte";+ import VoiceChannelView from "$components/omnidisc/VoiceChannelView.svelte";++ let guildId = $derived(page.params.guild ?? "");+ let channelId = $derived(page.params.channel ?? "");++ $effect(() => {+ selectChannel(guildId, channelId);+ });++ let guild = $derived(getGuild(guildId));+ let instance = $derived(getInstance(guild?.instanceId ?? null));+ let channel = $derived(guild?.channels.find((c) => c.id === channelId) ?? null);+ let membersOpen = $derived(isMemberListOpen());+ let connected = $derived(instance?.status === "connected" || instance?.id === "demo");+ let canSend = $derived(connected && canInChannel(channelId, "SEND_MESSAGES"));+ let canManageChannel = $derived(canInChannel(channelId, "MANAGE_CHANNELS"));+</script>++{#if !channel || !instance}+ <div class="not-found">+ <h3>{$t("omnidisc.channels.not_found")}</h3>+ <p>{$t("omnidisc.channels.not_found_hint")}</p>+ </div>+{:else if channel.kind === "voice"}+ <div class="voice-wrap">+ <header class="bar">+ <h2 class="name">{channel.name}</h2>+ </header>+ <VoiceChannelView {channel} />+ </div>+{:else}+ <ChatView+ instanceId={instance.id}+ {channelId}+ {guildId}+ title={channel.name}+ topic={channel.topic ?? ""}+ kind="text"+ {canSend}+ {membersOpen}+ onToggleMembers={toggleMemberList}+ >+ {#snippet headerExtra()}+ {#if canManageChannel}+ <a+ class="icon-link"+ href={`/omnidisc/g/${guildId}/settings?channel=${channelId}`}+ title={$t("omnidisc.channel_settings.title")}+ aria-label={$t("omnidisc.channel_settings.title")}+ >+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.6 1.6 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.6 1.6 0 0 0-1.8-.3 1.6 1.6 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1A1.6 1.6 0 0 0 9 19.4a1.6 1.6 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.6 1.6 0 0 0 .3-1.8 1.6 1.6 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.6 1.6 0 0 0 4.6 9a1.6 1.6 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.6 1.6 0 0 0 1.8.3H9a1.6 1.6 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.6 1.6 0 0 0 1 1.5 1.6 1.6 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.6 1.6 0 0 0-.3 1.8V9a1.6 1.6 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.6 1.6 0 0 0-1.5 1z" /></svg>+ </a>+ {/if}+ {/snippet}+ </ChatView>+{/if}++<style>+ .voice-wrap {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .bar {+ display: flex;+ align-items: center;+ min-height: 48px;+ padding: 0 var(--space-4);+ border-bottom: 1px solid var(--border);+ }++ .name {+ margin: 0;+ font-size: var(--text-base);+ font-weight: 600;+ color: var(--text);+ }++ .icon-link {+ width: 32px;+ height: 32px;+ display: grid;+ place-items: center;+ border-radius: var(--radius-sm);+ color: var(--text-muted);+ }++ .icon-link:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .icon-link:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .not-found {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-1);+ padding: var(--space-5);+ text-align: center;+ }++ .not-found h3 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .not-found p {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ }+</style>diff --git a/src/routes/omnidisc/g/[guild]/settings/+page.svelte b/src/routes/omnidisc/g/[guild]/settings/+page.sveltenew file mode 100644index 00000000..b5631fb2--- /dev/null+++ b/src/routes/omnidisc/g/[guild]/settings/+page.svelte@@ -0,0 +1,564 @@+<script lang="ts">+ import { goto } from "$app/navigation";+ import { page } from "$app/state";+ import { t } from "$lib/i18n";+ import { translateBackendError } from "$lib/error-translate";+ import {+ canInGuild,+ deleteGuild,+ getGuild,+ getInstance,+ getMembers,+ getNotificationLevel,+ isGuildOwner,+ leaveGuild,+ setNotificationLevel,+ transferGuild,+ updateGuild,+ } from "$lib/stores/omnidisc-store.svelte";+ import type { NotificationLevel } from "$lib/omnidisc/types";+ import GuildRoles from "$components/omnidisc/settings/GuildRoles.svelte";+ import GuildChannels from "$components/omnidisc/settings/GuildChannels.svelte";+ import GuildInvites from "$components/omnidisc/settings/GuildInvites.svelte";+ import GuildBans from "$components/omnidisc/settings/GuildBans.svelte";+ import GuildAuditLog from "$components/omnidisc/settings/GuildAuditLog.svelte";+ import OmnidiscPrompt from "$components/omnidisc/OmnidiscPrompt.svelte";++ type View = "overview" | "roles" | "channels" | "invites" | "bans" | "audit";+ type Danger = "transfer" | "leave" | "delete" | null;++ let guildId = $derived(page.params.guild ?? "");+ let guild = $derived(getGuild(guildId));+ let instance = $derived(getInstance(guild?.instanceId ?? null));+ let members = $derived(getMembers(guildId));+ let owner = $derived(isGuildOwner(guildId));+ let canManage = $derived(canInGuild(guildId, "MANAGE_GUILD"));+ let canRoles = $derived(canInGuild(guildId, "MANAGE_ROLES"));+ let canChannels = $derived(canInGuild(guildId, "MANAGE_CHANNELS"));+ let canInvite = $derived(canInGuild(guildId, "CREATE_INVITES"));+ let canBan = $derived(canInGuild(guildId, "BAN_MEMBERS"));+ let canAudit = $derived(canInGuild(guildId, "VIEW_AUDIT_LOG"));++ let view = $state<View>((page.url.searchParams.get("channel") ? "channels" : "overview") as View);+ let initialChannelId = page.url.searchParams.get("channel");++ let name = $state("");+ let description = $state("");+ let seeded = $state<string | null>(null);+ let busy = $state(false);+ let error = $state<string | null>(null);+ let saved = $state(false);+ let danger = $state<Danger>(null);+ let typed = $state("");+ let transferTo = $state("");++ $effect(() => {+ if (!guild || seeded === guild.id) return;+ seeded = guild.id;+ name = guild.name;+ description = guild.description ?? "";+ });++ let guildLevel = $derived(getNotificationLevel(guildId) ?? "all");++ function fail(e: unknown) {+ error = translateBackendError(typeof e === "string" ? e : e instanceof Error ? e.message : String(e), $t);+ }++ async function saveOverview() {+ if (!guild) return;+ busy = true;+ error = null;+ saved = false;+ try {+ const patch: Record<string, unknown> = {};+ if (name.trim() && name.trim() !== guild.name) patch.name = name.trim();+ if ((description ?? "") !== (guild.description ?? "")) patch.description = description.trim() || null;+ if (Object.keys(patch).length > 0) await updateGuild(guild.id, patch);+ saved = true;+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ async function runDanger() {+ if (!guild) return;+ busy = true;+ error = null;+ try {+ if (danger === "delete") {+ await deleteGuild(guild.id);+ danger = null;+ await goto("/omnidisc");+ } else if (danger === "leave") {+ await leaveGuild(guild.id);+ danger = null;+ await goto("/omnidisc");+ } else if (danger === "transfer" && transferTo) {+ await transferGuild(guild.id, transferTo);+ danger = null;+ }+ } catch (e) {+ fail(e);+ } finally {+ busy = false;+ }+ }++ const VIEWS: { id: View; allowed: () => boolean }[] = [+ { id: "overview", allowed: () => true },+ { id: "roles", allowed: () => canRoles },+ { id: "channels", allowed: () => canChannels },+ { id: "invites", allowed: () => canInvite },+ { id: "bans", allowed: () => canBan },+ { id: "audit", allowed: () => canAudit },+ ];+</script>++{#if !guild || !instance}+ <div class="not-found">+ <h3>{$t("omnidisc.guild_settings.not_found_title")}</h3>+ <p>{$t("omnidisc.guild_settings.not_found_body")}</p>+ </div>+{:else}+ <div class="settings">+ <header class="bar">+ <a class="back" href={`/omnidisc/g/${guild.id}/${guild.channels.find((c) => c.kind === "text")?.id ?? ""}`}>+ <span aria-hidden="true">‹</span>+ {$t("omnidisc.guild_settings.back")}+ </a>+ <h2 class="title">{$t("omnidisc.guild_settings.title", { guild: guild.name })}</h2>+ </header>++ <div class="layout">+ <nav class="sub-nav" aria-label={$t("omnidisc.guild_settings.title", { guild: guild.name })}>+ {#each VIEWS as item (item.id)}+ {#if item.allowed()}+ <button type="button" class="sub-item" class:on={view === item.id} onclick={() => (view = item.id)}>+ {$t(`omnidisc.guild_settings.tab_${item.id}`)}+ </button>+ {/if}+ {/each}+ </nav>++ <div class="content">+ {#if view === "overview"}+ <section class="block">+ <h3 class="block-title">{$t("omnidisc.guild_settings.overview")}</h3>+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild.name_label")}</span>+ <input class="field-input" type="text" bind:value={name} maxlength="100" disabled={!canManage || busy} />+ </label>+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.description")}</span>+ <textarea class="field-input" rows="2" maxlength="300" bind:value={description} disabled={!canManage || busy}></textarea>+ </label>+ {#if canManage}+ <button type="button" class="primary" onclick={() => void saveOverview()} disabled={busy}>+ {busy ? $t("omnidisc.guild.working") : $t("omnidisc.guild_settings.save")}+ </button>+ {:else}+ <p class="hint">{$t("omnidisc.guild_settings.read_only")}</p>+ {/if}+ {#if error}+ <p class="error" role="alert">{error}</p>+ {:else if saved}+ <p class="ok" role="status">{$t("omnidisc.guild_settings.saved")}</p>+ {/if}+ </section>++ <section class="block">+ <h3 class="block-title">{$t("omnidisc.notify.guild_title")}</h3>+ <p class="hint">{$t("omnidisc.notify.guild_hint")}</p>+ <div class="segmented" role="radiogroup" aria-label={$t("omnidisc.notify.guild_title")}>+ {#each ["all", "mentions", "nothing"] as level (level)}+ <button+ type="button"+ class="seg"+ class:on={guildLevel === level}+ aria-pressed={guildLevel === level}+ onclick={() => setNotificationLevel(guildId, level as NotificationLevel)}+ >+ {$t(`omnidisc.notify.level_${level}`)}+ </button>+ {/each}+ </div>+ </section>++ <section class="block danger-zone">+ <h3 class="block-title">{$t("omnidisc.guild_settings.danger")}</h3>+ <div class="danger-row">+ <div class="danger-text">+ <strong>{$t("omnidisc.guild_settings.leave")}</strong>+ <span>{owner ? $t("omnidisc.guild_settings.leave_owner_hint") : $t("omnidisc.guild_settings.leave_hint")}</span>+ </div>+ <button type="button" class="ghost" onclick={() => (danger = "leave")} disabled={owner}>{$t("omnidisc.guild_settings.leave")}</button>+ </div>+ {#if owner}+ <div class="danger-row">+ <div class="danger-text">+ <strong>{$t("omnidisc.guild_settings.transfer")}</strong>+ <span>{$t("omnidisc.guild_settings.transfer_hint")}</span>+ </div>+ <button type="button" class="ghost" onclick={() => { transferTo = ""; danger = "transfer"; }}>{$t("omnidisc.guild_settings.transfer")}</button>+ </div>+ <div class="danger-row">+ <div class="danger-text">+ <strong>{$t("omnidisc.guild_settings.delete")}</strong>+ <span>{$t("omnidisc.guild_settings.delete_hint")}</span>+ </div>+ <button type="button" class="ghost danger" onclick={() => { typed = ""; danger = "delete"; }}>{$t("omnidisc.guild_settings.delete")}</button>+ </div>+ {/if}+ </section>+ {:else if view === "roles"}+ <GuildRoles {guildId} canManage={canRoles} />+ {:else if view === "channels"}+ <GuildChannels {guildId} instanceId={instance.id} canManage={canChannels} {initialChannelId} />+ {:else if view === "invites"}+ <GuildInvites {guildId} {canInvite} />+ {:else if view === "bans"}+ <GuildBans {guildId} instanceId={instance.id} {canBan} />+ {:else if view === "audit"}+ <GuildAuditLog {guildId} instanceId={instance.id} />+ {/if}+ </div>+ </div>+ </div>++ <OmnidiscPrompt+ open={danger !== null}+ title={danger === "delete"+ ? $t("omnidisc.guild_settings.delete_title", { guild: guild.name })+ : danger === "leave"+ ? $t("omnidisc.guild_settings.leave_title", { guild: guild.name })+ : $t("omnidisc.guild_settings.transfer_title", { guild: guild.name })}+ body={danger === "delete"+ ? $t("omnidisc.guild_settings.delete_body", { guild: guild.name })+ : danger === "leave"+ ? $t("omnidisc.guild_settings.leave_body", { guild: guild.name })+ : $t("omnidisc.guild_settings.transfer_body")}+ submitLabel={danger === "delete"+ ? $t("omnidisc.guild_settings.delete_confirm", { guild: guild.name })+ : danger === "leave"+ ? $t("omnidisc.guild_settings.leave_confirm", { guild: guild.name })+ : $t("omnidisc.guild_settings.transfer_confirm")}+ {busy}+ {error}+ canSubmit={danger === "delete" ? typed.trim() === guild.name : danger === "transfer" ? transferTo.length > 0 : true}+ onSubmit={() => void runDanger()}+ onClose={() => {+ danger = null;+ error = null;+ }}+ >+ {#if danger === "delete"}+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.delete_type", { guild: guild.name })}</span>+ <input class="field-input" type="text" bind:value={typed} placeholder={guild.name} spellcheck="false" />+ </label>+ {:else if danger === "transfer"}+ <label class="field">+ <span class="field-label">{$t("omnidisc.guild_settings.transfer_to")}</span>+ <select class="field-input" bind:value={transferTo}>+ <option value="">{$t("omnidisc.guild_settings.transfer_pick")}</option>+ {#each members.filter((m) => m.id !== instance.userId) as member (member.id)}+ <option value={member.id}>{member.name}</option>+ {/each}+ </select>+ </label>+ {:else}+ <p class="hint">{$t("omnidisc.guild_settings.leave_hint")}</p>+ {/if}+ </OmnidiscPrompt>+{/if}++<style>+ .settings {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .bar {+ display: flex;+ align-items: center;+ gap: var(--space-3);+ min-height: 48px;+ padding: 0 var(--space-4);+ border-bottom: 1px solid var(--border);+ }++ .back {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-size: var(--text-sm);+ color: var(--text-muted);+ }++ .back:hover {+ color: var(--text);+ }++ .title {+ margin: 0;+ font-size: var(--text-base);+ font-weight: 600;+ color: var(--text);+ }++ .layout {+ flex: 1;+ min-height: 0;+ display: grid;+ grid-template-columns: 180px 1fr;+ }++ .sub-nav {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: var(--space-3) var(--space-2);+ border-right: 1px solid var(--border);+ background: var(--surface-mut);+ }++ .sub-item {+ padding: 6px var(--space-2);+ border: none;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ text-align: left;+ cursor: pointer;+ }++ .sub-item:hover {+ background: var(--fill-1);+ color: var(--text);+ }++ .sub-item.on {+ background: var(--accent-soft);+ color: var(--accent);+ font-weight: 600;+ }++ .content {+ min-height: 0;+ overflow-y: auto;+ padding: var(--space-4) var(--space-5);+ display: flex;+ flex-direction: column;+ gap: var(--space-5);+ }++ .block {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ max-width: 560px;+ }++ .block-title {+ margin: 0;+ font-size: var(--text-sm);+ font-weight: 600;+ letter-spacing: var(--track-caps);+ text-transform: uppercase;+ color: var(--text-muted);+ }++ .field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ .field-label {+ font-size: var(--text-xs);+ font-weight: 600;+ color: var(--text);+ }++ .field-input {+ width: 100%;+ box-sizing: border-box;+ padding: 8px var(--space-2);+ border-radius: var(--radius-sm);+ border: 1px solid var(--input-border);+ background: var(--input-bg);+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ resize: vertical;+ }++ .primary {+ align-self: flex-start;+ padding: 8px var(--space-4);+ border: none;+ border-radius: var(--radius-sm);+ background: var(--accent);+ color: var(--on-accent);+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ cursor: pointer;+ }++ .primary:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .segmented {+ display: flex;+ }++ .seg {+ padding: 6px var(--space-3);+ border: 1px solid var(--border);+ background: transparent;+ color: var(--text-muted);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .seg:first-child {+ border-radius: var(--radius-sm) 0 0 var(--radius-sm);+ }++ .seg:last-child {+ border-radius: 0 var(--radius-sm) var(--radius-sm) 0;+ }++ .seg.on {+ background: var(--accent-soft);+ border-color: var(--accent);+ color: var(--accent);+ font-weight: 600;+ }++ .danger-zone {+ border-top: 1px solid var(--border);+ padding-top: var(--space-3);+ }++ .danger-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-3);+ padding: var(--space-2) 0;+ }++ .danger-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }++ .danger-text strong {+ font-size: var(--text-sm);+ color: var(--text);+ }++ .danger-text span {+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.4;+ }++ .ghost {+ padding: 6px var(--space-3);+ border: 1px solid var(--border-hi);+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--text-sm);+ cursor: pointer;+ }++ .ghost:disabled {+ opacity: 0.5;+ cursor: default;+ }++ .ghost.danger {+ color: var(--danger);+ border-color: var(--danger);+ }++ .hint {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--text-muted);+ line-height: 1.5;+ }++ .ok {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--success);+ }++ .error {+ margin: 0;+ font-size: var(--text-xs);+ color: var(--danger);+ }++ .not-found {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: var(--space-1);+ padding: var(--space-5);+ text-align: center;+ }++ .not-found h3 {+ margin: 0;+ font-size: var(--text-lg);+ color: var(--text);+ }++ .not-found p {+ margin: 0;+ font-size: var(--text-sm);+ color: var(--text-muted);+ }++ input:focus-visible,+ select:focus-visible,+ textarea:focus-visible,+ button:focus-visible,+ a:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ @media (max-width: 760px) {+ .layout {+ grid-template-columns: 1fr;+ }++ .sub-nav {+ flex-direction: row;+ overflow-x: auto;+ border-right: none;+ border-bottom: 1px solid var(--border);+ }+ }+</style>diff --git a/src/routes/omnidisc/settings/+page.svelte b/src/routes/omnidisc/settings/+page.sveltenew file mode 100644index 00000000..83288751--- /dev/null+++ b/src/routes/omnidisc/settings/+page.svelte@@ -0,0 +1,97 @@+<script lang="ts">+ import { page } from "$app/state";+ import { t } from "$lib/i18n";+ import SettingsDrillBack from "$components/settings/SettingsDrillBack.svelte";+ import SettingsDrillItem from "$components/settings/SettingsDrillItem.svelte";+ import VoiceSettings from "$components/omnidisc/VoiceSettings.svelte";+ import ProfileSettings from "$components/omnidisc/settings/ProfileSettings.svelte";+ import SessionsSettings from "$components/omnidisc/settings/SessionsSettings.svelte";+ import DevicesSettings from "$components/omnidisc/settings/DevicesSettings.svelte";++ type Drill = "voice" | "profile" | "sessions" | "devices";++ function initial(): Drill | null {+ const view = page.url.searchParams.get("view");+ return view === "voice" || view === "profile" || view === "sessions" || view === "devices"+ ? view+ : null;+ }++ let subView = $state<Drill | null>(initial());+</script>++<div class="od-settings">+ <header class="bar">+ <h2 class="title">{$t("omnidisc.settings_title")}</h2>+ </header>+ <div class="body settings-content">+ {#if subView === null}+ <div class="settings-drill-list">+ <SettingsDrillItem+ title={$t("omnidisc.profile_settings.title")}+ hint={$t("omnidisc.profile_settings.hint")}+ onclick={() => (subView = "profile")}+ />+ <SettingsDrillItem+ title={$t("omnidisc.voice.title")}+ hint={$t("omnidisc.voice.settings_hint")}+ onclick={() => (subView = "voice")}+ />+ <SettingsDrillItem+ title={$t("omnidisc.sessions.title")}+ hint={$t("omnidisc.sessions.hint")}+ onclick={() => (subView = "sessions")}+ />+ <SettingsDrillItem+ title={$t("omnidisc.devices.title")}+ hint={$t("omnidisc.devices.hint")}+ onclick={() => (subView = "devices")}+ />+ </div>+ {:else if subView === "voice"}+ <SettingsDrillBack title={$t("omnidisc.voice.title")} hint={$t("omnidisc.voice.settings_hint")} onBack={() => (subView = null)} />+ <VoiceSettings />+ {:else if subView === "profile"}+ <SettingsDrillBack title={$t("omnidisc.profile_settings.title")} hint={$t("omnidisc.profile_settings.hint")} onBack={() => (subView = null)} />+ <ProfileSettings />+ {:else if subView === "sessions"}+ <SettingsDrillBack title={$t("omnidisc.sessions.title")} hint={$t("omnidisc.sessions.hint")} onBack={() => (subView = null)} />+ <SessionsSettings />+ {:else if subView === "devices"}+ <SettingsDrillBack title={$t("omnidisc.devices.title")} hint={$t("omnidisc.devices.hint")} onBack={() => (subView = null)} />+ <DevicesSettings />+ {/if}+ </div>+</div>++<style>+ .od-settings {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }++ .bar {+ display: flex;+ align-items: center;+ min-height: 48px;+ padding: 0 var(--space-4);+ border-bottom: 1px solid var(--border);+ }++ .title {+ margin: 0;+ font-size: var(--text-base);+ font-weight: 600;+ color: var(--text);+ }++ .body {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: var(--space-4) var(--space-5);+ max-width: 760px;+ }+</style>diff --git a/src/routes/omnidisc/stream/+page.svelte b/src/routes/omnidisc/stream/+page.sveltenew file mode 100644index 00000000..a0286ee0--- /dev/null+++ b/src/routes/omnidisc/stream/+page.svelte@@ -0,0 +1,240 @@+<script lang="ts">+ import { onMount } from "svelte";+ import { page } from "$app/state";+ import { invoke } from "@tauri-apps/api/core";+ import { getCurrentWindow } from "@tauri-apps/api/window";+ import { t } from "$lib/i18n";+ import {+ unwatchStream,+ setStreamVolume,+ refreshStreamStats,+ getStreamStats,+ } from "$lib/stores/omnidisc-stream-store.svelte";++ let userId = $derived(page.url.searchParams.get("user") ?? "");+ let volume = $state(100);+ let fullscreen = $state(false);+ let controlsVisible = $state(true);+ let stats = $derived(getStreamStats());+ let mine = $derived(stats?.watching.find((w) => w.user_id === userId) ?? null);+ let hideTimer: ReturnType<typeof setTimeout> | null = null;++ let viewportEl: HTMLDivElement;++ async function reportViewport() {+ if (!viewportEl || !userId) return;+ const rect = viewportEl.getBoundingClientRect();+ const scale = window.devicePixelRatio || 1;+ try {+ await invoke("omnidisc_stream_set_viewport", {+ args: {+ user_id: userId,+ x: rect.left,+ y: rect.top,+ width: rect.width,+ height: rect.height,+ scale,+ surface_width: Math.round(window.innerWidth * scale),+ surface_height: Math.round(window.innerHeight * scale),+ background: [0, 0, 0],+ },+ });+ } catch {+ /* window may be closing */+ }+ }++ function onVolume(v: number) {+ volume = v;+ void setStreamVolume(userId, v / 100);+ }++ async function toggleFullscreen() {+ const win = getCurrentWindow();+ fullscreen = !fullscreen;+ await win.setFullscreen(fullscreen);+ }++ async function stop() {+ await unwatchStream(userId);+ await getCurrentWindow().close();+ }++ function nudgeControls() {+ controlsVisible = true;+ if (hideTimer) clearTimeout(hideTimer);+ hideTimer = setTimeout(() => (controlsVisible = false), 2600);+ }++ onMount(() => {+ const root = document.documentElement;+ const prevHtml = root.style.background;+ const prevBody = document.body.style.background;+ root.style.background = "transparent";+ document.body.style.background = "transparent";++ void reportViewport();+ const ro = new ResizeObserver(() => void reportViewport());+ if (viewportEl) ro.observe(viewportEl);+ window.addEventListener("resize", reportViewport);++ const statsTimer = setInterval(() => void refreshStreamStats(), 2000);+ nudgeControls();++ return () => {+ ro.disconnect();+ window.removeEventListener("resize", reportViewport);+ clearInterval(statsTimer);+ if (hideTimer) clearTimeout(hideTimer);+ root.style.background = prevHtml;+ document.body.style.background = prevBody;+ void invoke("omnidisc_stream_unwatch", { userId }).catch(() => undefined);+ };+ });+</script>++<div+ class="viewport"+ bind:this={viewportEl}+ role="presentation"+ onmousemove={nudgeControls}+ class:idle={!controlsVisible}+>+ <div class="overlay" class:hidden={!controlsVisible}>+ <div class="badge">+ {#if mine && mine.width > 0}+ {mine.width}×{mine.height} · {Math.round(mine.fps_received)}fps{#if mine.decoder} · {mine.decoder}{/if}+ {:else}+ {$t("omnidisc.stream.connecting")}+ {/if}+ </div>+ <div class="controls">+ <label class="vol">+ <span class="sr-only">{$t("omnidisc.stream.volume")}</span>+ <input type="range" min="0" max="200" step="5" value={volume} oninput={(e) => onVolume(Number(e.currentTarget.value))} />+ <span class="vol-val">{volume}%</span>+ </label>+ <button type="button" class="ctl" onclick={toggleFullscreen} title={$t("omnidisc.stream.fullscreen")}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" /></svg>+ </button>+ <button type="button" class="ctl stop" onclick={stop} title={$t("omnidisc.stream.stop_watching")}>+ <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18" /></svg>+ </button>+ </div>+ </div>+</div>++<style>+ :global(body) {+ background: transparent;+ }++ .viewport {+ position: fixed;+ inset: 0;+ background: transparent;+ cursor: default;+ }++ .viewport.idle {+ cursor: none;+ }++ .overlay {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ pointer-events: none;+ transition: opacity 200ms ease;+ }++ .overlay.hidden {+ opacity: 0;+ }++ .badge {+ align-self: flex-start;+ margin: var(--space-3);+ padding: 4px var(--space-2);+ border-radius: var(--radius-sm);+ background: color-mix(in srgb, black 55%, transparent);+ color: white;+ font-size: var(--text-xs);+ font-variant-numeric: tabular-nums;+ pointer-events: auto;+ }++ .controls {+ align-self: center;+ display: flex;+ align-items: center;+ gap: var(--space-3);+ margin-bottom: var(--space-4);+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-full, 999px);+ background: color-mix(in srgb, black 55%, transparent);+ pointer-events: auto;+ }++ .vol {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ width: 180px;+ }++ .vol input {+ flex: 1;+ accent-color: var(--accent);+ }++ .vol-val {+ color: white;+ font-size: var(--text-xs);+ min-width: 36px;+ text-align: right;+ font-variant-numeric: tabular-nums;+ }++ .ctl {+ display: grid;+ place-items: center;+ width: 34px;+ height: 34px;+ border: none;+ border-radius: var(--radius-full, 999px);+ background: color-mix(in srgb, white 14%, transparent);+ color: white;+ cursor: pointer;+ }++ .ctl:hover {+ background: color-mix(in srgb, white 26%, transparent);+ }++ .ctl.stop:hover {+ background: var(--danger);+ }++ .ctl:focus-visible {+ outline: var(--focus-ring);+ outline-offset: var(--focus-ring-offset);+ }++ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ }++ @media (prefers-reduced-motion: reduce) {+ .overlay {+ transition: none;+ }+ }+</style>