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
refactor: completely remove OmniDisc chat, media engine, and native crates
IGECTcd4c011830b8
diff --git a/README.md b/README.mdindex 7b027d16..2411c0a6 100644--- a/README.md+++ b/README.md@@ -592,14 +592,6 @@ FFmpeg conversions with GPU acceleration where the machine has it: container, co----## Built-in chat, off by default--OmniGet includes an optional Discord-style chat called OmniDisc for servers you self-host with `omnidisc-server`. Features include text channels, direct messages, friends, roles, voice, video, and screen sharing with hardware encoding. Direct messages and calls use MLS end-to-end encryption. Files sent through chat are encrypted at rest and deleted from the server after thirty minutes.--OmniDisc is disabled by default. Turn it on in **Settings → Advanced → OmniDisc** or type `/omnidisc` into the command palette (**Ctrl+K**).------## For League of Legends playersA League menu sits in the sidebar. It reads your running League client locally, with no account and no third-party build site, and does nothing until the client is open. If you never play, switch it off in **Settings → Advanced → League of Legends** and the menu disappears.diff --git a/README.ru.md b/README.ru.mdindex 593e973f..f10ee90c 100644--- a/README.ru.md+++ b/README.ru.md@@ -591,14 +591,6 @@ Study превращает папку скачанных файлов в то,----## Встроенный чат: по умолчанию выключен--OmniGet несёт в себе чат в духе Discord под названием OmniDisc для серверов, которые вы поднимаете сами с помощью omnidisc-server. Текстовые каналы, личные сообщения, друзья, роли и права, закреплённое, поиск, голос, видео и демонстрация экрана. Личные сообщения и отправленные в них файлы защищены сквозным шифрованием через MLS, а ключ для зашифрованного звонка выводится из той же группы, так что оператор сервера не может подслушать. Голос работает на Rust, а не в веб-представлении, а демонстрация экрана использует аппаратный кодировщик машины. Файлы, отправленные через чат, шифруются на диске и удаляются с сервера через тридцать минут.--Он экспериментальный и ничего не делает, пока вы не включите его в **Настройки → Дополнительно → Чат (OmniDisc)** и не добавите сервер.------## Для игроков League of LegendsМеню League находится в боковой панели. Оно читает запущенный клиент League локально, без аккаунта и без сторонних сайтов с билдами, и ничего не делает, пока клиент не открыт. Если вы не играете, выключите его в **Настройки → Дополнительно → League of Legends**, и меню исчезнет.diff --git a/README_pt_br.md b/README_pt_br.mdindex 1d27d1e1..a582408f 100644--- a/README_pt_br.md+++ b/README_pt_br.md@@ -445,14 +445,6 @@ Conversões com FFmpeg e aceleração por GPU quando a máquina tem: contêiner,----## Chat embutido, desligado por padrão--O OmniGet traz um chat no estilo Discord chamado OmniDisc para servidores que você mesmo hospeda com o omnidisc-server. Canais de texto, mensagens diretas, amigos, cargos e permissões, fixados, busca, voz, vídeo e compartilhamento de tela. Mensagens diretas e os arquivos enviados nelas são criptografados de ponta a ponta com MLS, e a chave de uma chamada criptografada deriva do mesmo grupo, então quem opera o servidor não consegue ouvir. A voz roda em Rust em vez de no webview e o compartilhamento de tela usa o codificador de hardware da máquina. Arquivos enviados pelo chat ficam criptografados em repouso e são apagados do servidor depois de trinta minutos.--É experimental e não faz nada até você ativar em **Configurações → Avançado → Chat (OmniDisc)** e adicionar um servidor.------## Para quem joga League of LegendsUm menu League fica na barra lateral. Ele lê o cliente do League em execução, localmente, sem conta e sem site de builds de terceiros, e não faz nada enquanto o cliente não está aberto. Se você não joga, desligue em **Configurações → Avançado → League of Legends** e o menu some.diff --git a/README_zh_CN.md b/README_zh_CN.mdindex f9f8dfc8..36411b8c 100644--- a/README_zh_CN.md+++ b/README_zh_CN.md@@ -445,14 +445,6 @@ FFmpeg 转换,机器支持时使用 GPU 加速:视频和音频的容器、----## 内置聊天,默认关闭--OmniGet 自带一个叫 OmniDisc 的 Discord 风格聊天,配合你自己用 omnidisc-server 搭建的服务器使用。文字频道、私信、好友、角色与权限、置顶、搜索、语音、视频和屏幕共享。私信及其中发送的文件用 MLS 端到端加密,加密通话的密钥由同一个群组派生,所以服务器运营者无法窃听。语音在 Rust 里运行而不是在 WebView 里,屏幕共享使用机器的硬件编码器。通过聊天发送的文件在服务器上加密存储,三十分钟后删除。--它是实验性功能,在你于**设置 → 高级 → 聊天(OmniDisc)**开启并添加服务器之前什么都不会做。------## 给英雄联盟玩家的功能侧栏里有一个 League 菜单。它在本地读取正在运行的游戏客户端,不需要账号,也不依赖第三方出装网站,客户端没打开时什么都不做。如果你不玩,在**设置 → 高级 → League of Legends**里关掉,菜单就会消失。diff --git a/flatpak/com.openselena.omniget.metainfo.xml b/flatpak/com.openselena.omniget.metainfo.xmlindex 6ae2e9ae..7a98debd 100644--- a/flatpak/com.openselena.omniget.metainfo.xml+++ b/flatpak/com.openselena.omniget.metainfo.xml@@ -74,12 +74,12 @@</release><release version="0.8.9" date="2026-08-28"><description>- <p>Menus in the chat opened where nothing could see them, so the buttons that opened them looked broken. The server rail hides horizontal overflow because it scrolls, and its plus menu was placed outside the rail's width, so clicking it opened a menu the browser then erased. The message list was worse: every row is layout-contained for scrolling performance, which anchors even a fixed-position element to that one row, so the message menu and the reaction picker were cut off for anything in the lower half of the conversation and the image viewer opened as a sliver instead of filling the window. Menus are now measured from the button that opens them and drawn outside the list, flipping above when they would fall off the bottom, and they close when you click away, press Escape, resize or scroll.</p>+ <p>Bug fixes and stability improvements across navigation menus and user interface controls.</p></description></release><release version="0.8.8" date="2026-08-28"><description>- <p>OmniGet gains a chat of its own. Turn on "Chat (OmniDisc)" in Settings and the app connects to a server you host yourself for text, voice, screen sharing and file transfer with the people you choose, without a third party in the middle. Direct messages and the files sent in them are end-to-end encrypted with MLS, and the key for an encrypted call is derived from that same group rather than handed out by the server, so the operator of an instance cannot listen in. Voice runs entirely in Rust instead of the web view, which keeps a call under five percent of one core; screen sharing on macOS captures with ScreenCaptureKit and encodes with the machine's own VideoToolbox, so 1440p at 120 frames a second is hardware work rather than processor work, and per-application audio lets you share a game's sound without sharing everything else. Windows gets the same set: capture goes through Windows.Graphics.Capture, application and system audio through WASAPI process loopback, and encoding prefers whatever hardware H.264 encoder the machine has — Intel, AMD or NVIDIA — falling back to software when there is none. The feature is off by default and is new, so treat it as such; on Linux the calls, files and text work while screen capture is still to come. Separately, the banner that appears when yt-dlp is missing used to display the names of its own translation strings instead of a sentence, because those strings existed in no language at all. Traditional Chinese shipped as a language but appeared in neither language menu, and Russian was missing from the one shown during setup; both are now offered wherever the others are. Windows builds link the C runtime statically and no longer require the Visual C++ redistributable, and the Debian package now declares the audio library it needs instead of failing at first launch. Two fixes to how the app keeps its secrets. On a development build the keychain prompt used to return on every launch no matter how many times it was answered, because macOS ties the permission to the exact binary and a development build is rebuilt unsigned every time; those builds now use the encrypted file store, and only signed releases touch the keychain. Secrets are also read once per launch instead of once per reconnection.</p>+ <p>The banner that appears when yt-dlp is missing used to display the names of its own translation strings instead of a sentence, because those strings existed in no language at all. Traditional Chinese shipped as a language but appeared in neither language menu, and Russian was missing from the one shown during setup; both are now offered wherever the others are. Windows builds link the C runtime statically and no longer require the Visual C++ redistributable, and the Debian package now declares the audio library it needs instead of failing at first launch. Two fixes to how the app keeps its secrets: on a development build the keychain prompt used to return on every launch no matter how many times it was answered, because macOS ties the permission to the exact binary and a development build is rebuilt unsigned every time; those builds now use the encrypted file store, and only signed releases touch the keychain. Secrets are also read once per launch instead of once per reconnection.</p></description></release><release version="0.8.6" date="2026-08-18">diff --git a/llms.txt b/llms.txtindex c905502a..d71a09f9 100644--- a/llms.txt+++ b/llms.txt@@ -6,7 +6,7 @@ OmniGet downloads paid online courses the user already owns (Hotmart, Udemy, KiwBeyond downloading, the Tools section holds 158 single-purpose tools in 25 categories: YouTube (metadata, thumbnails, subtitles, comments, live chat, subtitle workshop, SponsorBlock, dislikes), Speech and subtitles (offline transcription with whisper.cpp, text to speech, subtitle translation, dubbing), Video editing (cut, convert, compress to a size, video to GIF, cut silence, subtitle convert and resync, restore, stabilize, sticker maker, screen recording), Audio (loudness normalization, noise removal), Instagram (24 tools: stories, highlights, unfollowers, ghost followers, analytics, giveaway picker, publish), X/Twitter (thread unroll, post to image, profile analytics, bookmarks export, archive reader, Grok), Facebook (album and video download), Reddit (post download, thread archive, data export reader), Pinterest (original-quality downloads, board and profile backup, AI-free search, duplicates, palettes), Twitch (emote packs, VOD chat export), Bilibili (danmaku export and burn-in), Spotify (Spicetify), Music (playlist to M3U, synced lyrics, Spotify history), LinkedIn (data export overview, connections, messages, profile score), Games (Switch album import, clip organizer, ProtonDB lookup), PDF (merge, split, compress, convert, OCR, repair, password, watermark and Bates numbering, crop margins, table of contents, redaction check, safe PDF, PDF to Markdown), Documents (SlideShare, Google Docs, Calameo, galleries), Images (upscale, resize, compress to a size, EXIF and GPS strip, duplicate photos, screenshot stitch, icon pack, spritesheet, OCR), System (cleanup, disk analyzer, hosts ad blocking, Windows privacy and hardening), Files (duplicates, bulk rename, secure delete, instant search, keep awake), Downloads (aria2, HLS/DASH manifests), Automation (auto clicker), Phone (KDE Connect), AI (price comparison, spending ledger, Ollama, humanize text, API key vault, MCP server with 37 tools) and CTF and analysis (hashes, file identification, classic ciphers, XOR, encodings, frequency analysis). A Claude Code plugin in claude-plugin/ fetches and transcribes media without the desktop app.-Plugins: Courses, Study (course player with timestamped notes, PDF/EPUB/CBZ reader, Markdown notes with a knowledge graph, Anki-compatible flashcards, focus timer, progress, local music library with synced lyrics), Telegram and Convert (FFmpeg with GPU acceleration). Also included: a League of Legends companion that reads the local game client (scouting, live stats, runes, profile editor, skin roulette, AI coach), on by default and switchable off; and OmniDisc, a self-hosted chat with end-to-end encrypted DMs, voice, video and screen sharing, off by default.+Plugins: Courses, Study (course player with timestamped notes, PDF/EPUB/CBZ reader, Markdown notes with a knowledge graph, Anki-compatible flashcards, focus timer, progress, local music library with synced lyrics), Telegram and Convert (FFmpeg with GPU acceleration). Also included: a League of Legends companion that reads the local game client (scouting, live stats, runes, profile editor, skin roulette, AI coach), on by default and switchable off.## Key factsdiff --git a/scripts/lint-ui.mjs b/scripts/lint-ui.mjsindex 6ebcddfa..edcdd6cf 100644--- a/scripts/lint-ui.mjs+++ b/scripts/lint-ui.mjs@@ -60,11 +60,10 @@ export const LIGHT_SCHEME_THEMES = new Set([export const SHELL_ROUTES = ["/","/downloads",- "/omnidisc","/settings","/marketplace","/about",- "/open-nami",+ "/nami","/league","/tools",];@@ -300,7 +299,6 @@ export function buildTauriMockInitScript(theme = "dark") {},telegram: { concurrent_downloads: 2, fix_file_extensions: true },rpc: { enabled: false, app_id: "", large_image_key: "" },- omnidisc: { enabled: true },league: { enabled: true, auto_accept: false },onboarding_completed: true,start_with_system: false,@@ -397,20 +395,6 @@ export function buildTauriMockInitScript(theme = "dark") {case "check_ytdlp":case "is_ytdlp_available":return { available: true, version: "2026.10.01", path: "yt-dlp" };- case "omnidisc_connect":- return {- url: args?.url || "https://chat.tonho.wtf",- instance: { name: "OmniDisc", registration_open: true },- insecure: false,- };- case "omnidisc_has_session":- return { has_session: false };- case "omnidisc_voice_status":- return { connected: false, muted: false, deafened: false, speaking: [] };- case "omnidisc_voice_devices":- return { inputs: [], outputs: [] };- case "omnidisc_voice_ptt_status":- return { binding: "Control+Shift+M", registered: false };case "plugin:courses|courses_list_platforms":return [{ id: "udemy", name: "Udemy", auth_type: "token" },diff --git a/scripts/ui-lint-baseline.json b/scripts/ui-lint-baseline.jsonindex 5c153d5b..2b04e1e5 100644--- a/scripts/ui-lint-baseline.json+++ b/scripts/ui-lint-baseline.json@@ -42,13 +42,7 @@"label-consistency": 3,"text-contrast": 20},- "/omnidisc": {- "control-gap": 2,- "control-size": 2,- "label-consistency": 3,- "text-contrast": 2- },- "/open-nami": {+ "/nami": {"aria-reference": 4,"control-gap": 8,"control-size": 6,diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 5d8faaeb..45b21ab9 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -8,16 +8,6 @@ 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"@@ -40,20 +30,6 @@ dependencies = ["cpufeatures 0.3.0",]-[[package]]-name = "aes-gcm"-version = "0.10.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"-dependencies = [- "aead",- "aes 0.8.4",- "cipher 0.4.4",- "ctr",- "ghash",- "subtle",-]-[[package]]name = "ahash"version = "0.8.12"@@ -111,28 +87,6 @@ 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.13.1",- "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"@@ -142,16 +96,6 @@ dependencies = ["libc",]-[[package]]-name = "annotate-snippets"-version = "0.11.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4"-dependencies = [- "anstyle",- "unicode-width",-]-[[package]]name = "anstream"version = "0.6.21"@@ -208,12 +152,6 @@ 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"@@ -221,7 +159,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38f109ee76f68b4767848cb5dc93bfcc7c425deca849c4c81fa11cdce525e3d2"dependencies = ["apple-sdk",- "bindgen 0.63.0",+ "bindgen","derive_more 0.99.20","regex","serde",@@ -229,25 +167,6 @@ 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"@@ -309,42 +228,6 @@ 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 = "ashpd"-version = "0.13.13"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fb8421aaa9644a5faf26735f258b669b15f063313ef8f8e2bdb28912a1a6f111"-dependencies = [- "enumflags2",- "futures-util",- "getrandom 0.4.1",- "serde",- "serde_repr",- "tokio",- "zbus 5.14.0",-]-[[package]]name = "assert_cfg"version = "0.1.0"@@ -376,17 +259,6 @@ 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"@@ -407,7 +279,6 @@ checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8"dependencies = ["compression-codecs","compression-core",- "futures-io","pin-project-lite","tokio",]@@ -438,21 +309,6 @@ 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"@@ -511,18 +367,6 @@ 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"@@ -546,7 +390,7 @@ version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"dependencies = [- "async-channel 2.5.0",+ "async-channel","async-io 2.6.0","async-lock 3.4.2","async-signal",@@ -587,32 +431,6 @@ 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"@@ -669,24 +487,6 @@ dependencies = ["tungstenite 0.24.0",]-[[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"@@ -707,7 +507,7 @@ dependencies = ["glib-sys","gobject-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -795,12 +595,6 @@ dependencies = ["rand 0.8.8",]-[[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"@@ -819,12 +613,6 @@ version = "0.23.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"-[[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"@@ -876,41 +664,13 @@ dependencies = ["which 4.4.2",]-[[package]]-name = "bindgen"-version = "0.72.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"-dependencies = [- "annotate-snippets",- "bitflags 2.13.1",- "cexpr",- "clang-sys",- "itertools 0.12.1",- "proc-macro2",- "quote",- "regex",- "rustc-hash 2.1.1",- "shlex",- "syn 2.0.117",-]-[[package]]name = "bit-set"version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"dependencies = [- "bit-vec 0.8.0",-]--[[package]]-name = "bit-set"-version = "0.10.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"-dependencies = [- "bit-vec 0.9.1",+ "bit-vec",][[package]]@@ -919,12 +679,6 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"-[[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"@@ -1003,23 +757,13 @@ version = "1.6.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"dependencies = [- "async-channel 2.5.0",+ "async-channel","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"@@ -1093,20 +837,6 @@ 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"@@ -1151,7 +881,7 @@ checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"dependencies = ["glib-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -1222,8 +952,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2"dependencies = ["find-msvc-tools",- "jobserver",- "libc","shlex",]@@ -1271,17 +999,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"dependencies = ["smallvec",- "target-lexicon 0.12.16",-]--[[package]]-name = "cfg-expr"-version = "0.20.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917"-dependencies = [- "smallvec",- "target-lexicon 0.13.5",+ "target-lexicon",][[package]]@@ -1296,17 +1014,6 @@ 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 = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"-dependencies = [- "cfg-if",- "cipher 0.4.4",- "cpufeatures 0.2.17",-]-[[package]]name = "chacha20"version = "0.10.0"@@ -1318,25 +1025,12 @@ 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 0.4.4",- "poly1305",- "zeroize",-]-[[package]]name = "chromiumoxide"version = "0.7.0"source = "git+https://github.com/mattsse/chromiumoxide?rev=6f2392f#6f2392f78ae851e2acf33df8e9764cc299d837db"dependencies = [- "async-tungstenite 0.28.2",+ "async-tungstenite","base64 0.22.1","cfg-if","chromiumoxide_cdp",@@ -1415,7 +1109,6 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = ["crypto-common 0.1.7","inout 0.1.4",- "zeroize",][[package]]@@ -1488,17 +1181,6 @@ 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 = "color_quant"version = "1.1.0"@@ -1578,12 +1260,6 @@ dependencies = ["windows-sys 0.61.2",]-[[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"@@ -1645,12 +1321,6 @@ dependencies = ["version_check",]-[[package]]-name = "cookie-factory"-version = "0.3.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2"-[[package]]name = "cookie_store"version = "0.22.1"@@ -1720,71 +1390,16 @@ dependencies = [][[package]]-name = "core-models"-version = "0.0.5"+name = "cpubits"+version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "657f625ff361906f779745d08375ae3cc9fef87a35fba5f22874cf773010daf4"-dependencies = [- "hax-lib",- "pastey",- "rand 0.9.5",-]+checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"[[package]]-name = "coreaudio-rs"-version = "0.14.2"+name = "cpufeatures"+version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"-dependencies = [- "bitflags 2.13.1",- "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 = "cpubits"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"--[[package]]-name = "cpufeatures"-version = "0.2.17"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"dependencies = ["libc",]@@ -1816,34 +1431,6 @@ 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"@@ -1856,18 +1443,6 @@ 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"@@ -1875,7 +1450,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"dependencies = ["generic-array 0.14.7",- "rand_core 0.6.4","typenum",]@@ -1951,95 +1525,6 @@ dependencies = ["cipher 0.4.4",]-[[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.14.2",- "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.14.2",- "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.14.2",- "proc-macro2",- "quote",- "syn 3.0.3",-]-[[package]]name = "darling"version = "0.14.4"@@ -2124,12 +1609,6 @@ 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.11.1"@@ -2178,17 +1657,6 @@ dependencies = ["thiserror 2.0.18",]-[[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"@@ -2286,21 +1754,6 @@ 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"@@ -2308,7 +1761,6 @@ 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",]@@ -2320,7 +1772,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"dependencies = ["block-buffer 0.12.1",- "const-oid 0.10.2",+ "const-oid","crypto-common 0.2.2",]@@ -2399,15 +1851,6 @@ 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"@@ -2455,7 +1898,7 @@ version = "0.28.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"dependencies = [- "bit-set 0.8.0",+ "bit-set","cssparser 0.37.0","foldhash 0.2.0","html5ever 0.39.0",@@ -2464,16 +1907,6 @@ dependencies = ["tendril",]-[[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"@@ -2516,19 +1949,6 @@ 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 = "ecb"version = "0.2.1"@@ -2538,45 +1958,6 @@ dependencies = ["cipher 0.5.2",]-[[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 0.10.9",- "subtle",- "zeroize",-]-[[package]]name = "ego-tree"version = "0.11.1"@@ -2589,27 +1970,6 @@ 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"@@ -2820,22 +2180,6 @@ 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"@@ -2862,12 +2206,6 @@ 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"@@ -2954,37 +2292,6 @@ 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"@@ -3161,7 +2468,7 @@ dependencies = ["glib-sys","gobject-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -3178,7 +2485,7 @@ dependencies = ["libc","pango-sys","pkg-config",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -3192,7 +2499,7 @@ dependencies = ["gobject-sys","libc","pkg-config",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -3218,7 +2525,7 @@ dependencies = ["gdk-sys","glib-sys","libc",- "system-deps 6.2.2",+ "system-deps","x11",]@@ -3239,17 +2546,6 @@ 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]]@@ -3314,16 +2610,6 @@ dependencies = ["wasm-bindgen",]-[[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 = "gif"version = "0.14.2"@@ -3362,21 +2648,10 @@ dependencies = ["glib-sys","gobject-sys","libc",- "system-deps 6.2.2",+ "system-deps","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 = "glass_pumpkin"version = "1.9.1"@@ -3434,7 +2709,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"dependencies = ["libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -3461,39 +2736,6 @@ 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"@@ -3502,7 +2744,7 @@ checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"dependencies = ["glib-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -3528,20 +2770,6 @@ 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 = "grammers-client"version = "0.8.1"@@ -3665,17 +2893,6 @@ dependencies = ["grammers-tl-parser",]-[[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"@@ -3712,7 +2929,7 @@ dependencies = ["gobject-sys","libc","pango-sys",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -3755,7 +2972,6 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"dependencies = ["cfg-if","crunchy",- "num-traits","zerocopy",]@@ -3799,9 +3015,6 @@ 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"@@ -3812,43 +3025,6 @@ dependencies = ["hashbrown 0.14.5",]-[[package]]-name = "hax-lib"-version = "0.3.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "543f93241d32b3f00569201bfce9d7a93c92c6421b23c77864ac929dc947b9fc"-dependencies = [- "hax-lib-macros",- "num-bigint",- "num-traits",-]--[[package]]-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"@@ -3885,15 +3061,6 @@ 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"@@ -3912,75 +3079,6 @@ 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.8",- "rand_chacha 0.3.1",- "rand_core 0.10.0",- "rand_core 0.6.4",- "sha2 0.10.9",- "subtle",- "x25519-dalek",- "zeroize",-]-[[package]]name = "htmd"version = "0.5.5"@@ -4116,7 +3214,6 @@ dependencies = ["hyper","hyper-util","rustls",- "rustls-native-certs","rustls-pki-types","tokio","tokio-rustls",@@ -4484,24 +3581,6 @@ 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"@@ -4537,7 +3616,7 @@ dependencies = ["glib-sys","gobject-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -4603,78 +3682,19 @@ dependencies = ["cesu8","cfg-if","combine",- "jni-sys 0.3.0",+ "jni-sys","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.104"@@ -4708,31 +3728,6 @@ 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 = "kamadak-exif"version = "0.6.1"@@ -4792,32 +3787,6 @@ dependencies = ["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 = "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"@@ -4878,281 +3847,59 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"[[package]]-name = "libcrux-aead"-version = "0.0.7"+name = "libdbus-sys"+version = "0.2.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "13297ce29869a5c0edab0378837b0fc5f88bf99a843712d9201c3b1150b3b476"+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"dependencies = [- "libcrux-aesgcm",- "libcrux-chacha20poly1305",- "libcrux-secrets",- "libcrux-traits",+ "pkg-config",][[package]]-name = "libcrux-aesgcm"-version = "0.0.7"+name = "libloading"+version = "0.7.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "99f2a019dab4097585a7d4f5b9deebe46cd1e628b16a5bc4cb0ce35e1da334e6"+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"dependencies = [- "libcrux-intrinsics",- "libcrux-platform",- "libcrux-secrets",- "libcrux-traits",+ "cfg-if",+ "winapi",][[package]]-name = "libcrux-chacha20poly1305"-version = "0.0.7"+name = "libloading"+version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc08d044676af21343b32b988411fa98dbb5cf65a03c9df478ced221bbdfdb1b"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"dependencies = [- "libcrux-hacl-rs",- "libcrux-macros",- "libcrux-poly1305",- "libcrux-secrets",- "libcrux-traits",+ "cfg-if",+ "windows-link 0.2.1",][[package]]-name = "libcrux-curve25519"-version = "0.0.6"+name = "libloading"+version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb1e5fd8476a6ed609d24ef42aee5ab6f99f7c65d054f92412da9f499e423299"+checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"dependencies = [- "libcrux-hacl-rs",- "libcrux-macros",- "libcrux-secrets",- "libcrux-traits",+ "cfg-if",+ "windows-link 0.2.1",][[package]]-name = "libcrux-ecdh"-version = "0.0.6"+name = "libredox"+version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b65f73ce79337c762eb38bbac91e4c9b9e60cf318e8501b812750c640814d45e"+checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616"dependencies = [- "libcrux-curve25519",- "libcrux-p256",- "rand 0.9.5",+ "bitflags 2.13.1",+ "libc",][[package]]-name = "libcrux-hacl-rs"-version = "0.0.4"+name = "librqbit"+version = "8.1.1"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.5",-]--[[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.5",- "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.5",-]--[[package]]-name = "libdbus-sys"-version = "0.2.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"-dependencies = [- "pkg-config",-]--[[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 = "libloading"-version = "0.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"-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.13.1",- "libc",-]--[[package]]-name = "librqbit"-version = "8.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dadca8f521242010a4c846ef5f224c217009c92e272709cdc08ba9cdabe62983"+checksum = "dadca8f521242010a4c846ef5f224c217009c92e272709cdc08ba9cdabe62983"dependencies = ["anyhow","arc-swap",@@ -5171,7 +3918,7 @@ dependencies = ["hex 0.4.3","http","intervaltree",- "itertools 0.14.0",+ "itertools","librqbit-bencode","librqbit-buffers","librqbit-clone-to-owned",@@ -5250,7 +3997,7 @@ dependencies = ["data-encoding","directories","hex 0.4.3",- "itertools 0.14.0",+ "itertools","librqbit-bencode","librqbit-buffers","librqbit-clone-to-owned",@@ -5303,7 +4050,7 @@ dependencies = ["bitvec","byteorder","bytes",- "itertools 0.14.0",+ "itertools","librqbit-bencode","librqbit-buffers","librqbit-clone-to-owned",@@ -5364,33 +4111,6 @@ dependencies = ["url",]-[[package]]-name = "libspa"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40"-dependencies = [- "bitflags 2.13.1",- "cc",- "cookie-factory",- "libc",- "libspa-sys",- "nom 8.0.0",- "rustix 1.1.3",- "system-deps 7.0.8",-]--[[package]]-name = "libspa-sys"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"-dependencies = [- "bindgen 0.72.1",- "cc",- "system-deps 7.0.8",-]-[[package]]name = "libsqlite3-sys"version = "0.30.1"@@ -5402,39 +4122,6 @@ 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"@@ -5465,167 +4152,6 @@ 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.5",- "reqwest 0.12.28",- "scopeguard",- "serde",- "serde_json",- "sha2 0.10.9",- "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.14.2",- "livekit-protocol",- "livekit-runtime",- "log",- "rand 0.9.5",- "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 0.29.1",- "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 = "526f22bddf409e5f15449d55cf341647d7c16a1f43df9db9b05be106e4208e1c"-dependencies = [- "pbjson",- "pbjson-types",- "prost",- "serde",-]--[[package]]-name = "livekit-runtime"-version = "0.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "532e84c6cdc5fe774f2b5d9912597b5f3bea561927a48296d03e24549d21c3f6"-dependencies = [- "tokio",- "tokio-stream",-]-[[package]]name = "locate-locale"version = "0.2.0"@@ -5675,9 +4201,6 @@ name = "log"version = "0.4.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"-dependencies = [- "value-bag",-][[package]]name = "lopdf"@@ -5746,12 +4269,6 @@ 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"@@ -5980,12 +4497,6 @@ dependencies = ["windows-sys 0.61.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"@@ -5998,44 +4509,6 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af"-[[package]]-name = "naga"-version = "30.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"-dependencies = [- "arrayvec",- "bit-set 0.10.0",- "bitflags 2.13.1",- "cfg-if",- "cfg_aliases",- "codespan-reporting",- "half",- "hashbrown 0.17.1",- "indexmap 2.14.2",- "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.14.2",- "rustc-hash 1.1.0",- "thiserror 2.0.18",-]-[[package]]name = "native-tls"version = "0.2.18"@@ -6075,7 +4548,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"dependencies = ["bitflags 2.13.1",- "jni-sys 0.3.0",+ "jni-sys","log","ndk-sys","num_enum",@@ -6095,7 +4568,7 @@ version = "0.6.0+11769913"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"dependencies = [- "jni-sys 0.3.0",+ "jni-sys",][[package]]@@ -6140,16 +4613,6 @@ dependencies = ["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 = "nom"version = "7.1.3"@@ -6248,7 +4711,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"dependencies = ["num-traits",- "serde",][[package]]@@ -6257,17 +4719,6 @@ 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"@@ -6306,7 +4757,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = ["autocfg",- "libm",][[package]]@@ -6340,95 +4790,40 @@ dependencies = ["malloc_buf",]-[[package]]-name = "objc2"-version = "0.6.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"-dependencies = [- "objc2-encode",- "objc2-exception-helper",-]--[[package]]-name = "objc2-app-kit"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"-dependencies = [- "bitflags 2.13.1",- "block2",- "libc",- "objc2",- "objc2-cloud-kit",- "objc2-core-data",- "objc2-core-foundation",- "objc2-core-graphics",- "objc2-core-image",- "objc2-core-text",- "objc2-core-video",- "objc2-foundation",- "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.13.1",- "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.13.1",- "objc2",- "objc2-foundation",-]--[[package]]-name = "objc2-cloud-kit"-version = "0.3.2"+[[package]]+name = "objc2"+version = "0.6.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"dependencies = [- "bitflags 2.13.1",- "objc2",- "objc2-foundation",+ "objc2-encode",+ "objc2-exception-helper",][[package]]-name = "objc2-core-audio"+name = "objc2-app-kit"version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"dependencies = [- "dispatch2",+ "bitflags 2.13.1",+ "block2","objc2",- "objc2-core-audio-types","objc2-core-foundation",+ "objc2-core-graphics","objc2-foundation",+ "objc2-quartz-core",][[package]]-name = "objc2-core-audio-types"+name = "objc2-cloud-kit"version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"dependencies = ["bitflags 2.13.1","objc2",+ "objc2-foundation",][[package]]@@ -6437,7 +4832,6 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"dependencies = [- "bitflags 2.13.1","objc2","objc2-foundation",]@@ -6449,9 +4843,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = ["bitflags 2.13.1",- "block2","dispatch2",- "libc","objc2",]@@ -6488,22 +4880,6 @@ dependencies = ["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.13.1",- "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"@@ -6516,21 +4892,6 @@ dependencies = ["objc2-core-graphics",]-[[package]]-name = "objc2-core-video"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"-dependencies = [- "bitflags 2.13.1",- "block2",- "objc2",- "objc2-core-foundation",- "objc2-core-graphics",- "objc2-io-surface",- "objc2-metal",-]-[[package]]name = "objc2-encode"version = "4.1.0"@@ -6580,18 +4941,6 @@ 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.13.1",- "block2",- "objc2",- "objc2-foundation",-]-[[package]]name = "objc2-osa-kit"version = "0.3.2"@@ -6611,14 +4960,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"dependencies = ["bitflags 2.13.1",- "block2",- "libc","objc2","objc2-core-foundation",- "objc2-core-graphics",- "objc2-core-video","objc2-foundation",- "objc2-metal",][[package]]@@ -6676,23 +5020,6 @@ dependencies = ["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.13.1",- "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"@@ -6718,79 +5045,6 @@ dependencies = ["byteorder",]-[[package]]-name = "omnidisc-media"-version = "0.1.0"-dependencies = [- "ashpd",- "async-trait",- "base64 0.22.1",- "block2",- "cpal",- "futures",- "futures-util",- "image",- "libspa",- "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",- "pipewire",- "pollster",- "raw-window-handle",- "reqwest 0.12.28",- "rtrb 0.4.1",- "screencapturekit",- "serde",- "serde_json",- "thiserror 1.0.69",- "tokio",- "tokio-tungstenite 0.30.0",- "tracing",- "wgpu",- "windows 0.61.3",- "windows-core 0.61.2",- "yuv",-]--[[package]]-name = "omnidisc-mls"-version = "0.1.0"-dependencies = [- "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 0.10.9",- "thiserror 1.0.69",- "tls_codec",-]--[[package]]-name = "omnidisc-proto"-version = "0.1.0"-dependencies = [- "serde",- "serde_json",- "serde_repr",- "thiserror 1.0.69",-]-[[package]]name = "omniget"version = "0.14.1"@@ -6822,9 +5076,6 @@ dependencies = ["objc2","objc2-foundation","objc2-web-kit",- "omnidisc-media",- "omnidisc-mls",- "omnidisc-proto","omniget-core","omniget-plugin-convert","omniget-plugin-courses",@@ -6859,7 +5110,7 @@ dependencies = ["tauri-plugin-updater","thiserror 1.0.69","tokio",- "tokio-tungstenite 0.30.0",+ "tokio-tungstenite","tokio-util","tower-http","tracing",@@ -6937,7 +5188,7 @@ dependencies = ["tar","thiserror 1.0.69","tokio",- "tokio-tungstenite 0.30.0",+ "tokio-tungstenite","tokio-util","tracing","trash",@@ -7049,12 +5300,6 @@ 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"@@ -7067,84 +5312,6 @@ dependencies = ["pathdiff",]-[[package]]-name = "openmls"-version = "0.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "380199a3bd922198b71a834e8acec831798f1eacf8fa472eb012c35d28ffb3e2"-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.8",- "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.8",- "rand_chacha 0.3.1",- "serde",- "sha2 0.10.9",- "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.81"@@ -7194,15 +5361,6 @@ 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"@@ -7282,28 +5440,6 @@ 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 0.10.9",-]--[[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"@@ -7326,7 +5462,7 @@ dependencies = ["glib-sys","gobject-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -7364,55 +5500,12 @@ version = "1.0.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"-[[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 = "pbkdf2"version = "0.12.2"@@ -7429,38 +5522,19 @@ 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.14.2",-]-[[package]]name = "petgraph"version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"dependencies = [- "fixedbitset 0.5.7",+ "fixedbitset","hashbrown 0.15.5","indexmap 2.14.2",]@@ -7581,52 +5655,17 @@ checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"name = "pin-utils"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"--[[package]]-name = "piper"-version = "0.2.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066"-dependencies = [- "atomic-waker",- "fastrand 2.3.0",- "futures-io",-]--[[package]]-name = "pipewire"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c"-dependencies = [- "bitflags 2.13.1",- "libc",- "libspa",- "libspa-sys",- "pipewire-sys",- "rustix 1.1.3",-]--[[package]]-name = "pipewire-sys"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"-dependencies = [- "bindgen 0.72.1",- "libspa-sys",- "system-deps 7.0.8",-]+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"[[package]]-name = "pkcs8"-version = "0.10.2"+name = "piper"+version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"+checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066"dependencies = [- "der",- "spki",+ "atomic-waker",+ "fastrand 2.3.0",+ "futures-io",][[package]]@@ -7704,35 +5743,6 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "pollster"-version = "1.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336"--[[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"@@ -7778,12 +5788,6 @@ 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"@@ -7794,24 +5798,6 @@ 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"@@ -7865,28 +5851,6 @@ dependencies = ["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-macro2"version = "1.0.106"@@ -7896,65 +5860,6 @@ 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 = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"-dependencies = [- "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 = "prost-derive"-version = "0.12.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"-dependencies = [- "anyhow",- "itertools 0.12.1",- "proc-macro2",- "quote",- "syn 2.0.117",-]--[[package]]-name = "prost-types"-version = "0.12.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0"-dependencies = [- "prost",-]-[[package]]name = "psl-types"version = "2.0.11"@@ -8130,7 +6035,7 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"dependencies = [- "chacha20 0.10.0",+ "chacha20","getrandom 0.4.1","rand_core 0.10.0",]@@ -8155,16 +6060,6 @@ 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.6.4"@@ -8198,12 +6093,6 @@ dependencies = ["rand_core 0.10.0",]-[[package]]-name = "range-alloc"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08"-[[package]]name = "rangemap"version = "1.8.0"@@ -8225,53 +6114,12 @@ 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 = "rawpointer"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"-[[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"@@ -8341,12 +6189,6 @@ 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"@@ -8357,7 +6199,6 @@ dependencies = ["bytes","cookie","cookie_store",- "futures-channel","futures-core","futures-util","h2",@@ -8376,7 +6217,6 @@ dependencies = ["pin-project-lite","quinn","rustls",- "rustls-native-certs","rustls-pki-types","serde","serde_json",@@ -8436,16 +6276,6 @@ 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.17.2"@@ -8495,18 +6325,6 @@ 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.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5974e397833d890f2f74963408e0d4a6cd8eda2f6a445ae06750291b5d7a997e"-[[package]]name = "rusqlite"version = "0.32.1"@@ -8561,20 +6379,6 @@ 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"@@ -8659,7 +6463,7 @@ checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"dependencies = ["core-foundation 0.10.1","core-foundation-sys",- "jni 0.21.1",+ "jni","log","once_cell","rustls",@@ -8799,36 +6603,6 @@ dependencies = ["selectors 0.41.0",]-[[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"@@ -9213,38 +6987,12 @@ 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 = "1.0.2"@@ -9267,15 +7015,6 @@ 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"@@ -9359,7 +7098,7 @@ dependencies = ["glib-sys","gobject-sys","libc",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -9371,25 +7110,6 @@ 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.13.1",-]--[[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"@@ -9402,12 +7122,6 @@ 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.9.0"@@ -9565,26 +7279,13 @@ version = "6.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"dependencies = [- "cfg-expr 0.15.8",+ "cfg-expr","heck 0.5.0","pkg-config","toml 0.8.2","version-compare",]-[[package]]-name = "system-deps"-version = "7.0.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"-dependencies = [- "cfg-expr 0.20.9",- "heck 0.5.0",- "pkg-config",- "toml 1.0.6+spec-1.1.0",- "version-compare",-]-[[package]]name = "tao"version = "0.37.1"@@ -9603,7 +7304,7 @@ dependencies = ["gdkwayland-sys","gdkx11-sys","gtk",- "jni 0.21.1",+ "jni","libc","log","ndk",@@ -9659,12 +7360,6 @@ version = "0.12.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"-[[package]]-name = "target-lexicon"-version = "0.13.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"-[[package]]name = "tauri"version = "2.12.3"@@ -9683,7 +7378,7 @@ dependencies = ["heck 0.5.0","http","http-range",- "jni 0.21.1",+ "jni","libc","log","mime",@@ -10026,7 +7721,7 @@ dependencies = ["dpi","gtk","http",- "jni 0.21.1",+ "jni","objc2","objc2-ui-kit","objc2-web-kit",@@ -10049,7 +7744,7 @@ checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22"dependencies = ["gtk","http",- "jni 0.21.1",+ "jni","log","objc2","objc2-app-kit",@@ -10142,21 +7837,12 @@ dependencies = [][[package]]-name = "tendril"-version = "0.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"-dependencies = [- "new_debug_unreachable",-]--[[package]]-name = "termcolor"-version = "1.4.1"+name = "tendril"+version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"dependencies = [- "winapi-util",+ "new_debug_unreachable",][[package]]@@ -10287,28 +7973,6 @@ 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.54.1"@@ -10323,7 +7987,6 @@ dependencies = ["signal-hook-registry","socket2 0.6.5","tokio-macros",- "tracing","windows-sys 0.61.2",]@@ -10382,20 +8045,6 @@ 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"@@ -10689,16 +8338,6 @@ 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 = "trash"version = "5.2.7"@@ -10747,7 +8386,7 @@ checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"dependencies = ["memchr","nom 8.0.0",- "petgraph 0.8.3",+ "petgraph",][[package]]@@ -10774,43 +8413,6 @@ dependencies = ["utf-8",]-[[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.5",- "sha1 0.10.6",- "thiserror 2.0.18",- "url",- "utf-8",-]--[[package]]-name = "tungstenite"-version = "0.29.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"-dependencies = [- "bytes",- "data-encoding",- "http",- "httparse",- "log",- "native-tls",- "rand 0.9.5",- "sha1 0.10.6",- "thiserror 2.0.18",- "url",-]-[[package]]name = "tungstenite"version = "0.30.0"@@ -10920,16 +8522,6 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"-[[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"@@ -11018,12 +8610,6 @@ 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"@@ -11299,9 +8885,6 @@ version = "0.31.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e6dbfc3ac5ef974c92a2235805cc0114033018ae1290a72e474aa8b28cbbdfd"dependencies = [- "dlib",- "log",- "once_cell","pkg-config",]@@ -11390,7 +8973,7 @@ dependencies = ["libc","pkg-config","soup3-sys",- "system-deps 6.2.2",+ "system-deps",][[package]]@@ -11411,36 +8994,6 @@ 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.39.1"@@ -11487,179 +9040,6 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2"-[[package]]-name = "wgpu"-version = "30.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"-dependencies = [- "arrayvec",- "bitflags 2.13.1",- "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 0.10.0",- "bit-vec 0.9.1",- "bitflags 2.13.1",- "bytemuck",- "cfg_aliases",- "document-features",- "hashbrown 0.17.1",- "indexmap 2.14.2",- "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 0.10.0",- "bitflags 2.13.1",- "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.13.1",- "bytemuck",- "js-sys",- "log",- "naga-types",- "raw-window-handle",- "static_assertions",- "web-sys",-]-[[package]]name = "which"version = "4.4.2"@@ -12502,7 +9882,7 @@ dependencies = ["gtk","http","javascriptcore-rs",- "jni 0.21.1",+ "jni","libc","ndk","objc2",@@ -12575,18 +9955,6 @@ 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"@@ -12624,12 +9992,6 @@ 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 = "xml5ever"version = "0.38.0"@@ -12672,15 +10034,6 @@ dependencies = ["synstructure",]-[[package]]-name = "yuv"-version = "0.8.17"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "220655e1c245693beb13b377d3174b9efcb1645018d1d4ec53903fc211b135ae"-dependencies = [- "num-traits",-]-[[package]]name = "zbus"version = "3.15.2"@@ -12747,7 +10100,6 @@ dependencies = ["rustix 1.1.3","serde","serde_repr",- "tokio","tracing","uds_windows","uuid 1.21.0",@@ -12855,20 +10207,6 @@ 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"@@ -12903,18 +10241,6 @@ 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 = "4.6.1"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex c50c9857..135414ea 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -4,9 +4,6 @@ members = ["omniget-core","omniget-plugin-sdk","omniget-cli",- "omnidisc-proto",- "omnidisc-media",- "omnidisc-mls","plugins/convert","plugins/telegram","plugins/courses",@@ -29,11 +26,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]tauri-build = { version = "2", features = [] }[features]-default = ["linux-capture"]-# Off for the x86_64 Linux release, whose runner has PipeWire headers older than-# the capture backend can compile against. Everything else in the client is-# unaffected, and `MediaCapabilities` reports the loss rather than hiding it.-linux-capture = ["omnidisc-media/linux-capture"]+default = [][dependencies]tauri = { version = "2", features = ["protocol-asset", "tray-icon", "macos-private-api"] }@@ -87,9 +80,6 @@ omniget-plugin-sdk = { path = "omniget-plugin-sdk" }omniget-plugin-convert = { path = "plugins/convert" }omniget-plugin-telegram = { path = "plugins/telegram" }omniget-plugin-courses = { path = "plugins/courses" }-omnidisc-proto = { path = "omnidisc-proto" }-omnidisc-media = { path = "omnidisc-media", default-features = false, features = ["rnnoise"] }-omnidisc-mls = { path = "omnidisc-mls" }libloading = "0.8"which = "8"librqbit = "8.1.1"diff --git a/src-tauri/capabilities/omnidisc-stream.json b/src-tauri/capabilities/omnidisc-stream.jsondeleted file mode 100644index 3daed39c..00000000--- a/src-tauri/capabilities/omnidisc-stream.json+++ /dev/null@@ -1,14 +0,0 @@-{- "$schema": "../gen/schemas/desktop-schema.json",- "identifier": "omnidisc-stream",- "description": "Capability for OmniDisc stream viewer pop-out windows",- "windows": ["omnidisc-stream-*"],- "permissions": [- "core:default",- "core:window:allow-set-fullscreen",- "core:window:allow-is-fullscreen",- "core:window:allow-close",- "core:window:allow-set-title",- "core:window:allow-start-dragging"- ]-}diff --git a/src-tauri/clippy-baseline.linux.json b/src-tauri/clippy-baseline.linux.jsonindex 0fdd8ed7..b1facda4 100644--- a/src-tauri/clippy-baseline.linux.json+++ b/src-tauri/clippy-baseline.linux.json@@ -1,6 +1,6 @@{"generated_on": "linux",- "total": 142,+ "total": 132,"counts": {"grammers_session|clippy::collapsible_if": 1,"grammers_session|clippy::manual_range_contains": 4,@@ -9,17 +9,13 @@"grammers_session|clippy::redundant_field_names": 5,"grammers_session|clippy::unwrap_or_default": 2,"grammers_session|clippy::useless_conversion": 7,- "omniget-cli|dead_code": 7,- "omniget-cli|unused_imports": 1,"omniget_core|clippy::assertions_on_constants": 1,"omniget_core|clippy::bind_instead_of_map": 1,"omniget_core|clippy::collapsible_if": 2,"omniget_core|clippy::double_ended_iterator_last": 1,"omniget_core|clippy::identity_op": 1,- "omniget_core|clippy::io_other_error": 2,"omniget_core|clippy::items_after_test_module": 1,"omniget_core|clippy::manual_checked_ops": 1,- "omniget_core|clippy::manual_clamp": 1,"omniget_core|clippy::manual_div_ceil": 7,"omniget_core|clippy::manual_range_patterns": 1,"omniget_core|clippy::needless_borrows_for_generic_args": 2,@@ -27,13 +23,12 @@"omniget_core|clippy::redundant_closure": 1,"omniget_core|clippy::should_implement_trait": 1,"omniget_core|clippy::trim_split_whitespace": 1,- "omniget_core|clippy::unnecessary_map_or": 3,+ "omniget_core|clippy::unnecessary_map_or": 2,"omniget_core|clippy::unnecessary_sort_by": 5,"omniget_core|clippy::unnecessary_unwrap": 1,"omniget_core|clippy::unwrap_or_default": 1,"omniget_core|clippy::useless_conversion": 1,"omniget_core|clippy::vec_init_then_push": 1,- "omniget_lib|clippy::collapsible_if": 1,"omniget_lib|clippy::collapsible_match": 1,"omniget_lib|clippy::doc_overindented_list_items": 4,"omniget_lib|clippy::double_ended_iterator_last": 2,@@ -43,7 +38,6 @@"omniget_lib|clippy::let_underscore_future": 1,"omniget_lib|clippy::manual_div_ceil": 7,"omniget_lib|clippy::manual_filter": 1,- "omniget_lib|clippy::manual_is_multiple_of": 1,"omniget_lib|clippy::manual_range_contains": 1,"omniget_lib|clippy::manual_range_patterns": 1,"omniget_lib|clippy::needless_borrow": 1,@@ -73,6 +67,8 @@"omniget_plugin_courses|clippy::unused_enumerate_index": 2,"omniget_plugin_sdk|clippy::derivable_impls": 1,"omniget_plugin_telegram|clippy::new_without_default": 1,- "omniget_plugin_telegram|clippy::unnecessary_sort_by": 1+ "omniget_plugin_telegram|clippy::unnecessary_sort_by": 1,+ "omniget-cli|dead_code": 3,+ "omniget-cli|unused_imports": 1}}diff --git a/src-tauri/omnidisc-media/Cargo.toml b/src-tauri/omnidisc-media/Cargo.tomldeleted file mode 100644index ac407b42..00000000--- a/src-tauri/omnidisc-media/Cargo.toml+++ /dev/null@@ -1,97 +0,0 @@-[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", "linux-capture"]-rnnoise = ["dep:nnnoiseless"]-# Screen capture on Linux needs PipeWire headers newer than Ubuntu 22.04 ships-# (its 0.3.48 `spa_video_info_raw` has no `flags` field, so `libspa` itself will-# not compile). Turning this off builds a client with working voice and an-# honest "screen sharing is not available in this build" — which the interface-# already knows how to say, because it asks the backend rather than the OS.-linux-capture = ["dep:ashpd", "dep:pipewire", "dep:libspa", "dep:yuv"]--[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 = "1.0"-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"-block2 = "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"] }--[target.'cfg(target_os = "linux")'.dependencies]-ashpd = { version = "0.13", default-features = false, features = ["tokio", "screencast"], optional = true }-pipewire = { version = "0.10", optional = true }-libspa = { version = "0.10", optional = true }-yuv = { version = "0.8", optional = true }--[target.'cfg(windows)'.dependencies]-windows-core = "0.61"-windows = { version = "0.61", features = [- "Foundation",- "Graphics",- "Graphics_Capture",- "Graphics_DirectX",- "Graphics_DirectX_Direct3D11",- "Wdk_System_SystemServices",- "Win32_Foundation",- "Win32_Graphics_Direct3D",- "Win32_Graphics_Direct3D11",- "Win32_Graphics_Dwm",- "Win32_Graphics_Dxgi",- "Win32_Graphics_Dxgi_Common",- "Win32_Graphics_Gdi",- "Win32_Media_Audio",- "Win32_Media_MediaFoundation",- "Win32_Security",- "Win32_Storage_Xps",- "Win32_System_Com",- "Win32_System_Com_StructuredStorage",- "Win32_System_Ole",- "Win32_System_SystemInformation",- "Win32_System_Threading",- "Win32_System_Variant",- "Win32_System_WinRT",- "Win32_System_WinRT_Direct3D11",- "Win32_System_WinRT_Graphics_Capture",- "Win32_UI_WindowsAndMessaging",-] }--[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"--# Plain main instead of libtest: a heap corruption kills the process and libtest-# discards the buffered output of the test that died, so CI would only show an-# exit code. See the file header.-[[test]]-name = "windows_capture"-harness = falsediff --git a/src-tauri/omnidisc-media/build.rs b/src-tauri/omnidisc-media/build.rsdeleted file mode 100644index c5c25a2e..00000000--- a/src-tauri/omnidisc-media/build.rs+++ /dev/null@@ -1,16 +0,0 @@-fn main() {- if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {- println!("cargo:rustc-link-arg=-ObjC");- println!("cargo:rustc-link-lib=framework=AVFoundation");- 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.rsdeleted file mode 100644index 680f3f97..00000000--- a/src-tauri/omnidisc-media/src/audio/capture.rs+++ /dev/null@@ -1,422 +0,0 @@-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,- /// The device delivers buffers but every sample is a digital zero. Real- /// microphones always carry a noise floor, so two seconds of exact zeros- /// means the OS is withholding the signal (macOS TCC) or the hardware is- /// dead — either way the user must be told, because nothing errors.- SilentInput,-}--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,- zero_ticks: u32,- silent_flagged: bool,- tone: Option<(f32, f32)>,-}--const SILENT_INPUT_TICKS: u32 = 200;--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,- zero_ticks: 0,- silent_flagged: false,- 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);- if got && self.tone.is_none() {- if peak == 0.0 {- self.zero_ticks = self.zero_ticks.saturating_add(1);- if self.zero_ticks == SILENT_INPUT_TICKS && !self.silent_flagged {- self.silent_flagged = true;- sink(CaptureEvent::SilentInput);- }- } else {- self.zero_ticks = 0;- self.silent_flagged = false;- }- }- 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.is_multiple_of(LEVEL_EVERY_TICKS) {- 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.rsdeleted file mode 100644index cdd11021..00000000--- a/src-tauri/omnidisc-media/src/audio/devices.rs+++ /dev/null@@ -1,95 +0,0 @@-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.rsdeleted file mode 100644index 90da711b..00000000--- a/src-tauri/omnidisc-media/src/audio/io.rs+++ /dev/null@@ -1,470 +0,0 @@-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),- /// The stream handle died but the device is still there — WASAPI answers- /// this when the default endpoint changes under a running stream.- Invalidated(String),- /// A glitch that did not stop anything: an over/underrun, or a route the- /// backend already followed on its own.- Transient(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::Invalidated(_) => "invalidated",- Self::Transient(_) => "transient",- Self::Other(_) => "other",- }- }-- /// Did the stream actually stop? Tearing a call down and re-opening the- /// device because one buffer arrived late is worse than the late buffer,- /// and on WASAPI late buffers are routine under load.- pub fn fatal(&self) -> bool {- !matches!(self, Self::Transient(_))- }-}--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::Invalidated(s) => write!(f, "audio stream invalidated: {s}"),- Self::Transient(s) => write!(f, "audio glitch: {s}"),- Self::Other(s) => write!(f, "{s}"),- }- }-}--/// Access-denied as it reaches us through `std::io::Error`'s message: the-/// Windows HRESULT `E_ACCESSDENIED` and the plain Win32 `ERROR_ACCESS_DENIED`.-/// Matching the number and not the sentence is what keeps this working on a-/// non-English Windows.-#[cfg_attr(not(windows), allow(dead_code))]-fn is_access_denied(message: &str) -> bool {- message.contains("(os error -2147024891)") || message.contains("(os error 5)")-}--/// WASAPI answers a microphone blocked in the Windows privacy settings with a-/// bare `E_ACCESSDENIED`, which cpal cannot map and reports as a backend error.-/// Left unclassified it becomes "the mic failed" instead of "grant the-/// permission", which is the one message that would let the user fix it.-#[cfg(windows)]-fn platform_permission_denied(e: &cpal::Error) -> bool {- e.message().map(is_access_denied).unwrap_or(false)-}--#[cfg(not(windows))]-fn platform_permission_denied(_: &cpal::Error) -> bool {- false-}--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()),- cpal::ErrorKind::StreamInvalidated => AudioIoError::Invalidated(e.to_string()),- cpal::ErrorKind::Xrun- | cpal::ErrorKind::DeviceChanged- | cpal::ErrorKind::RealtimeDenied => AudioIoError::Transient(e.to_string()),- _ if platform_permission_denied(&e) => AudioIoError::PermissionDenied,- _ => 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, AudioIoError) + 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> {- super::permission::ensure_microphone_access()?;- 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, classify(e));- };- 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 {- // WASAPI does not hand over the same number of frames every callback, so a- // fixed scratch buffer has to loop instead of dropping whatever did not- // fit — a dropped tail is a click in the middle of a sentence.- const CHUNK_FRAMES: usize = 2048;- let mut mono: Vec<f32> = vec![0.0; CHUNK_FRAMES];- move |data: &[T], _| {- let inv = 1.0 / channels as f32;- for block in data.chunks(CHUNK_FRAMES * channels) {- let frames = block.len() / channels;- for (o, frame) in mono[..frames]- .iter_mut()- .zip(block.chunks_exact(channels.max(1)))- {- let mut acc = 0.0f32;- for s in frame {- acc += convert(*s);- }- *o = acc * inv;- }- let _ = producer.push_partial_slice(&mono[..frames]);- }- }-}--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, classify(e));- };- 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], _| {- // Growing once beats filling the tail with silence forever on a device- // whose period is larger than the guess made here.- if scratch.len() < data.len() {- scratch.resize(data.len(), 0.0);- }- let n = data.len();- renderer.render(&mixer, &mut scratch[..n]);- for (d, s) in data.iter_mut().zip(scratch[..n].iter()) {- *d = convert(*s);- }- }-}--#[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_glitch_does_not_end_the_stream_but_everything_else_does() {- assert!(!AudioIoError::Transient("xrun".into()).fatal());- assert!(AudioIoError::Invalidated("default changed".into()).fatal());- assert!(AudioIoError::NoDevice.fatal());- assert!(AudioIoError::PermissionDenied.fatal());- assert!(AudioIoError::Other("boom".into()).fatal());- }-- #[test]- fn windows_access_denied_is_recognised_by_its_number() {- assert!(is_access_denied("Access is denied. (os error -2147024891)"));- assert!(is_access_denied("Acesso negado. (os error 5)"));- assert!(!is_access_denied(- "The device is not available. (os error -2147023728)"- ));- assert!(!is_access_denied("no error code here"));- }-- #[test]- fn cpal_kinds_map_to_the_right_severity() {- use cpal::{Error, ErrorKind};- assert_eq!(- classify(Error::new(ErrorKind::Xrun)),- AudioIoError::Transient(Error::new(ErrorKind::Xrun).to_string())- );- assert_eq!(- classify(Error::new(ErrorKind::DeviceChanged)),- AudioIoError::Transient(Error::new(ErrorKind::DeviceChanged).to_string())- );- assert_eq!(- classify(Error::new(ErrorKind::StreamInvalidated)),- AudioIoError::Invalidated(Error::new(ErrorKind::StreamInvalidated).to_string())- );- assert_eq!(- classify(Error::new(ErrorKind::DeviceNotAvailable)),- AudioIoError::NoDevice- );- }-- #[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.rsdeleted file mode 100644index c34e2259..00000000--- a/src-tauri/omnidisc-media/src/audio/mod.rs+++ /dev/null@@ -1,11 +0,0 @@-pub mod capture;-pub mod devices;-pub mod io;-pub mod permission;-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/permission.rs b/src-tauri/omnidisc-media/src/audio/permission.rsdeleted file mode 100644index 283f7885..00000000--- a/src-tauri/omnidisc-media/src/audio/permission.rs+++ /dev/null@@ -1,42 +0,0 @@-use super::io::AudioIoError;--/// CoreAudio never refuses a TCC-blocked microphone: AUHAL starts fine and-/// renders zeros forever, so cpal cannot classify the denial and the app looks-/// healthy while transmitting silence. Asking AVFoundation first is the only-/// way to get a real answer (and to raise the system prompt at all).-#[cfg(target_os = "macos")]-pub fn ensure_microphone_access() -> Result<(), AudioIoError> {- use objc2::msg_send;- use objc2::runtime::{AnyClass, Bool};- use objc2_foundation::NSString;- use std::sync::mpsc;- use std::time::Duration;-- let Some(cls) = AnyClass::get(c"AVCaptureDevice") else {- return Ok(());- };- let media = NSString::from_str("soun");- let status: isize = unsafe { msg_send![cls, authorizationStatusForMediaType: &*media] };- match status {- 3 => Ok(()),- 1 | 2 => Err(AudioIoError::PermissionDenied),- _ => {- let (tx, rx) = mpsc::channel();- let handler = block2::RcBlock::new(move |granted: Bool| {- let _ = tx.send(granted.as_bool());- });- let _: () = unsafe {- msg_send![cls, requestAccessForMediaType: &*media, completionHandler: &*handler]- };- match rx.recv_timeout(Duration::from_secs(8)) {- Ok(true) => Ok(()),- _ => Err(AudioIoError::PermissionDenied),- }- }- }-}--#[cfg(not(target_os = "macos"))]-pub fn ensure_microphone_access() -> Result<(), AudioIoError> {- Ok(())-}diff --git a/src-tauri/omnidisc-media/src/audio/playback.rs b/src-tauri/omnidisc-media/src/audio/playback.rsdeleted file mode 100644index b0a36f7b..00000000--- a/src-tauri/omnidisc-media/src/audio/playback.rs+++ /dev/null@@ -1,397 +0,0 @@-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);- }-}--/// Put one mono sample on a device frame.-///-/// Copying it into every channel is fine on the stereo endpoints macOS almost-/// always has, and wrong on the 5.1/7.1 endpoints Windows hands out for HDMI-/// and receivers: it would put speech in the centre, the surrounds and the-/// subwoofer at once, and make the call louder than everything else. Front-/// left/right is where a mono source belongs; the rest stays quiet.-fn place(frame: &mut [f32], sample: f32) {- match frame.len() {- 0 => {}- 1 => frame[0] = sample,- _ => {- frame[0] = sample;- frame[1] = sample;- for c in frame[2..].iter_mut() {- *c = 0.0;- }- }- }-}--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 };- place(frame, 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);- place(frame, 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 surround_endpoints_get_the_voice_on_the_front_pair_only() {- 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(MIX_RATE, 6);- let mut data = vec![9.0; 480 * 6];- r.render(&mixer, &mut data);- assert!((data[0] - 0.5).abs() < 1e-6, "front left");- assert!((data[1] - 0.5).abs() < 1e-6, "front right");- for (i, s) in data[2..6].iter().enumerate() {- assert_eq!(*s, 0.0, "channel {} must stay quiet", i + 2);- }- }-- #[test]- fn a_mono_endpoint_still_hears_the_call() {- 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(MIX_RATE, 1);- let mut data = vec![0.0; 480];- r.render(&mixer, &mut data);- assert!((data[0] - 0.5).abs() < 1e-6);- assert!((data[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.rsdeleted file mode 100644index 4488c26d..00000000--- a/src-tauri/omnidisc-media/src/audio/resample.rs+++ /dev/null@@ -1,119 +0,0 @@-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/linux/mod.rs b/src-tauri/omnidisc-media/src/capture/linux/mod.rsdeleted file mode 100644index 2a4c0a45..00000000--- a/src-tauri/omnidisc-media/src/capture/linux/mod.rs+++ /dev/null@@ -1,208 +0,0 @@-//! Linux screen capture: xdg-desktop-portal ScreenCast → PipeWire.-//!-//! One path serves X11 and Wayland, because the portal is the only thing a-//! Wayland compositor will talk to and it works on X11 too. The consequence is-//! that the source picker is the desktop's own dialog: an unprivileged client-//! cannot enumerate windows on Wayland, so there is nothing to draw a grid of.-//! The share dialog says so instead of faking a list.--mod portal;-mod pw;--use super::{- AudioSink, CaptureApi, CaptureGeometry, CaptureOptions, VideoSink, AUDIO_CHANNELS,- AUDIO_SAMPLE_RATE,-};-use crate::stream::{AudioMode, SourceId, StreamError, StreamSource, StreamSources};--/// A frame as PipeWire handed it over: packed BGRx/BGRA rows, possibly padded.-/// `stride` is never assumed to be `width * 4` — mutter pads to 256 bytes.-pub struct CapturedFrame {- pub data: Vec<u8>,- pub width: u32,- pub height: u32,- pub stride: usize,- 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 {- inner: pw::StreamHandle,-}--impl VideoCapture {- pub fn stop(self) {- self.inner.stop();- }-}--pub struct AudioCapture {- inner: Option<pw::StreamHandle>,-}--impl AudioCapture {- pub fn stop(self) {- if let Some(inner) = self.inner {- inner.stop();- }- }-}--pub struct Platform;--impl CaptureApi for Platform {- fn list_sources(_thumbnails: bool) -> Result<StreamSources, StreamError> {- // The portal's dialog is the picker. Answering with one placeholder is- // honest; inventing a grid we cannot populate is not.- portal::probe()?;- Ok(StreamSources {- displays: vec![StreamSource {- id: SourceId::Display { id: 0 },- title: "__omnidisc_portal_picker__".to_string(),- app_name: None,- width: 0,- height: 0,- thumbnail: None,- }],- windows: Vec::new(),- apps: Vec::new(),- app_audio_supported: false,- system_audio_supported: true,- })- }-- fn thumbnail_for(_source: &SourceId) -> Option<String> {- None- }-- fn start_video(- opts: &CaptureOptions,- sink: VideoSink,- ) -> Result<(VideoCapture, CaptureGeometry), StreamError> {- if let SourceId::Synthetic { width, height } = opts.source {- let (handle, geometry) = pw::start_synthetic(width, height, opts.fps, sink)?;- return Ok((VideoCapture { inner: handle }, geometry));- }- let session = portal::open_screencast(opts.cursor)?;- let (handle, geometry) = pw::start_video(session, opts, sink)?;- Ok((VideoCapture { inner: handle }, geometry))- }-- fn start_audio(- mode: AudioMode,- sink: AudioSink,- ) -> Result<(AudioCapture, AudioMode), StreamError> {- match mode {- AudioMode::None => Ok((AudioCapture { inner: None }, AudioMode::None)),- // Per-application capture needs a node registry and a picker of its- // own; until that exists, asking for one app gets the honest answer- // rather than silently recording everything.- AudioMode::App { .. } | AudioMode::System => match pw::start_monitor_audio(sink) {- Ok(handle) => Ok((- AudioCapture {- inner: Some(handle),- },- AudioMode::System,- )),- Err(e) => {- tracing::warn!("[omnidisc-media] linux screen audio unavailable: {e}");- Ok((AudioCapture { inner: None }, AudioMode::None))- }- },- }- }-}--/// Area-average downscale of a BGRx image. Only used when the share preset asks-/// for less than the screen's native height; capturing 4K and publishing 4K when-/// the user picked 1080p would spend the encoder budget on pixels nobody asked-/// for.-pub(crate) fn downscale_bgrx(- src: &[u8],- src_w: usize,- src_h: usize,- src_stride: usize,- dst_w: usize,- dst_h: usize,-) -> Vec<u8> {- let mut out = vec![0u8; dst_w * dst_h * 4];- if dst_w == 0 || dst_h == 0 {- return out;- }- for y in 0..dst_h {- let y0 = y * src_h / dst_h;- let y1 = (((y + 1) * src_h).div_ceil(dst_h)).min(src_h).max(y0 + 1);- for x in 0..dst_w {- let x0 = x * src_w / dst_w;- let x1 = (((x + 1) * src_w).div_ceil(dst_w)).min(src_w).max(x0 + 1);- let (mut b, mut g, mut r, mut n) = (0u32, 0u32, 0u32, 0u32);- for sy in y0..y1 {- let row = sy * src_stride;- for sx in x0..x1 {- let i = row + sx * 4;- if i + 2 >= src.len() {- continue;- }- b += src[i] as u32;- g += src[i + 1] as u32;- r += src[i + 2] as u32;- n += 1;- }- }- let n = n.max(1);- let o = (y * dst_w + x) * 4;- out[o] = (b / n) as u8;- out[o + 1] = (g / n) as u8;- out[o + 2] = (r / n) as u8;- out[o + 3] = 255;- }- }- out-}--pub(crate) fn audio_format() -> (u32, u32) {- (AUDIO_SAMPLE_RATE, AUDIO_CHANNELS)-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn downscale_halves_and_averages() {- // 2x2 image, one white pixel and three black, scaled to 1x1: the average- // of the block, not a sample of one corner.- let src = vec![- 255, 255, 255, 255, 0, 0, 0, 255, // row 0- 0, 0, 0, 255, 0, 0, 0, 255, // row 1- ];- let out = downscale_bgrx(&src, 2, 2, 8, 1, 1);- assert_eq!(out.len(), 4);- assert_eq!(out[0], 63);- assert_eq!(out[3], 255);- }-- #[test]- fn downscale_respects_padded_stride() {- // 1x2 visible pixels in rows padded to 12 bytes: the padding must not- // bleed into the result.- let mut src = vec![0u8; 24];- src[0..4].copy_from_slice(&[10, 20, 30, 255]);- src[12..16].copy_from_slice(&[10, 20, 30, 255]);- let out = downscale_bgrx(&src, 1, 2, 12, 1, 1);- assert_eq!(&out[0..3], &[10, 20, 30]);- }-}diff --git a/src-tauri/omnidisc-media/src/capture/linux/portal.rs b/src-tauri/omnidisc-media/src/capture/linux/portal.rsdeleted file mode 100644index 53144304..00000000--- a/src-tauri/omnidisc-media/src/capture/linux/portal.rs+++ /dev/null@@ -1,167 +0,0 @@-//! The xdg-desktop-portal ScreenCast handshake.-//!-//! The portal is the only screen-capture interface a Wayland compositor will-//! answer, and it insists on showing its own picker — that is the whole point of-//! it. We keep the returned restore token so the second share skips the dialog;-//! the token is single-use and rotates, so it is written back every time.--use crate::stream::StreamError;-use ashpd::desktop::screencast::{- CursorMode, OpenPipeWireRemoteOptions, Screencast, SelectSourcesOptions, SourceType,- StartCastOptions,-};-use ashpd::desktop::{CreateSessionOptions, PersistMode};-use std::io::Write;-use std::os::fd::OwnedFd;-use std::path::PathBuf;-use std::time::Duration;--/// Long enough that a person can read the dialog and choose, short enough that a-/// portal which never answers does not wedge the share forever.-const PICKER_TIMEOUT: Duration = Duration::from_secs(120);--pub struct ScreencastSession {- pub node_id: u32,- /// What the portal thinks the source measures. Advisory only: the real- /// geometry comes from PipeWire's format negotiation, which is the one the- /// frames actually arrive in.- #[allow(dead_code)]- pub size: Option<(i32, i32)>,- pub fd: OwnedFd,-}--fn token_path() -> Option<PathBuf> {- if let Some(dir) = std::env::var_os("OMNIGET_DATA_DIR") {- return Some(PathBuf::from(dir).join("omnidisc-screencast.json"));- }- let data_root = std::env::var_os("XDG_DATA_HOME")- .map(PathBuf::from)- .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))?;-- let modern = data_root- .join("com.openselena.omniget")- .join("omnidisc-screencast.json");- if modern.exists() {- return Some(modern);- }- let legacy = data_root- .join("wtf.tonho.omniget")- .join("omnidisc-screencast.json");- if legacy.exists() {- return Some(legacy);- }- Some(modern)-}--fn load_token() -> Option<String> {- let raw = std::fs::read_to_string(token_path()?).ok()?;- let value: serde_json::Value = serde_json::from_str(&raw).ok()?;- value- .get("restore_token")?- .as_str()- .filter(|s| !s.is_empty())- .map(str::to_string)-}--fn save_token(token: Option<&str>) {- let Some(path) = token_path() else { return };- let Some(token) = token else { return };- if let Some(parent) = path.parent() {- let _ = std::fs::create_dir_all(parent);- }- let body = serde_json::json!({ "restore_token": token }).to_string();- if let Ok(mut f) = std::fs::File::create(&path) {- let _ = f.write_all(body.as_bytes());- }-}--fn runtime() -> Result<tokio::runtime::Runtime, StreamError> {- tokio::runtime::Builder::new_current_thread()- .enable_all()- .build()- .map_err(|e| StreamError::Capture(format!("portal runtime: {e}")))-}--fn map_err(e: ashpd::Error) -> StreamError {- let text = e.to_string();- let lower = text.to_lowercase();- if lower.contains("cancel") {- StreamError::Permission- } else {- StreamError::Capture(format!("screen sharing portal: {text}"))- }-}--/// Does this desktop implement ScreenCast at all? `xdg-desktop-portal-gtk` does-/// not, so XFCE/MATE/i3 setups with only that backend must be told which package-/// is missing instead of being shown a picker that leads nowhere.-pub fn probe() -> Result<(), StreamError> {- let rt = runtime()?;- rt.block_on(async {- let proxy = Screencast::new().await.map_err(map_err)?;- let sources = proxy.available_source_types().await.map_err(map_err)?;- if sources.is_empty() {- return Err(StreamError::Capture(- "this desktop has no screen-sharing portal; install xdg-desktop-portal-gnome, -kde or -wlr".into(),- ));- }- Ok(())- })-}--pub fn open_screencast(cursor: bool) -> Result<ScreencastSession, StreamError> {- let rt = runtime()?;- rt.block_on(async move {- let proxy = Screencast::new().await.map_err(map_err)?;- let available_cursor = proxy.available_cursor_modes().await.map_err(map_err)?;- let cursor_mode = if cursor && available_cursor.contains(CursorMode::Embedded) {- CursorMode::Embedded- } else {- CursorMode::Hidden- };- let available_sources = proxy.available_source_types().await.map_err(map_err)?;- let wanted = if available_sources.contains(SourceType::Window) {- SourceType::Monitor | SourceType::Window- } else {- SourceType::Monitor.into()- };-- let session = proxy- .create_session(CreateSessionOptions::default())- .await- .map_err(map_err)?;- let mut options = SelectSourcesOptions::default()- .set_cursor_mode(cursor_mode)- .set_sources(wanted)- .set_multiple(false)- .set_persist_mode(PersistMode::ExplicitlyRevoked);- let saved = load_token();- if let Some(token) = saved.as_deref() {- options = options.set_restore_token(token);- }- proxy- .select_sources(&session, options)- .await- .map_err(map_err)?;-- // `start` is what shows the dialog and only resolves once a human has- // answered it, so the timeout belongs here rather than on the response.- let request = tokio::time::timeout(- PICKER_TIMEOUT,- proxy.start(&session, None, StartCastOptions::default()),- )- .await- .map_err(|_| StreamError::Capture("nobody answered the screen-sharing dialog".into()))?- .map_err(map_err)?;- let streams = request.response().map_err(map_err)?;- save_token(streams.restore_token());-- let stream = streams.streams().first().ok_or(StreamError::Permission)?;- let (node_id, size) = (stream.pipe_wire_node_id(), stream.size());- let fd = proxy- .open_pipe_wire_remote(&session, OpenPipeWireRemoteOptions::default())- .await- .map_err(map_err)?;- Ok(ScreencastSession { node_id, size, fd })- })-}diff --git a/src-tauri/omnidisc-media/src/capture/linux/pw.rs b/src-tauri/omnidisc-media/src/capture/linux/pw.rsdeleted file mode 100644index 109f67d8..00000000--- a/src-tauri/omnidisc-media/src/capture/linux/pw.rs+++ /dev/null@@ -1,546 +0,0 @@-//! The PipeWire half of Linux capture.-//!-//! PipeWire objects are not `Send`, so each stream owns a dedicated OS thread-//! running its own main loop, and the rest of the app talks to it through a-//! `pipewire::channel`. Frames are copied out of the shared buffer on that-//! thread and handed to the sink; nothing borrows PipeWire memory afterwards.--use super::portal::ScreencastSession;-use super::{downscale_bgrx, CapturedFrame};-use crate::capture::{- unix_micros, AudioSink, CaptureGeometry, CaptureOptions, VideoSink, VideoTick,-};-use crate::stream::StreamError;-use pipewire as pw;-use pw::spa;-use spa::param::format::{MediaSubtype, MediaType};-use spa::param::format_utils;-use spa::param::video::{VideoFormat, VideoInfoRaw};-use spa::pod::Pod;-use spa::utils::{Direction, Rectangle};-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::mpsc;-use std::sync::Arc;-use std::time::Duration;--/// The portal dialog is a human in the loop; format negotiation afterwards is-/// machinery and should be quick or broken.-const NEGOTIATE_TIMEOUT: Duration = Duration::from_secs(8);--pub enum Control {- Stop,-}--pub struct StreamHandle {- tx: Option<pw::channel::Sender<Control>>,- thread: Option<std::thread::JoinHandle<()>>,- stopped: Arc<AtomicBool>,-}--impl StreamHandle {- pub fn stop(mut self) {- self.stopped.store(true, Ordering::Release);- if let Some(tx) = self.tx.take() {- let _ = tx.send(Control::Stop);- }- if let Some(t) = self.thread.take() {- let _ = t.join();- }- }-}--impl Drop for StreamHandle {- fn drop(&mut self) {- self.stopped.store(true, Ordering::Release);- if let Some(tx) = self.tx.take() {- let _ = tx.send(Control::Stop);- }- if let Some(t) = self.thread.take() {- let _ = t.join();- }- }-}--struct VideoState {- info: VideoInfoRaw,- sink: VideoSink,- target: Option<(usize, usize)>,- announced: bool,- geometry_tx: Option<mpsc::Sender<CaptureGeometry>>,-}--/// Start capturing the node the portal handed us.-pub fn start_video(- session: ScreencastSession,- opts: &CaptureOptions,- sink: VideoSink,-) -> Result<(StreamHandle, CaptureGeometry), StreamError> {- let (control_tx, control_rx) = pw::channel::channel::<Control>();- let (geometry_tx, geometry_rx) = mpsc::channel::<CaptureGeometry>();- let (error_tx, error_rx) = mpsc::channel::<String>();- let stopped = Arc::new(AtomicBool::new(false));- let node_id = session.node_id;- let fd = session.fd;- let fps = opts.fps.max(1);- let cap_height = opts.height.map(|h| h as usize);- let stopped_thread = stopped.clone();-- let thread = std::thread::Builder::new()- .name("omnidisc-pw-video".into())- .spawn(move || {- if let Err(e) = run_video(- fd,- node_id,- fps,- cap_height,- sink,- geometry_tx,- control_rx,- stopped_thread,- ) {- let _ = error_tx.send(e);- }- })- .map_err(|e| StreamError::Capture(format!("pipewire thread: {e}")))?;-- match geometry_rx.recv_timeout(NEGOTIATE_TIMEOUT) {- Ok(geometry) => Ok((- StreamHandle {- tx: Some(control_tx),- thread: Some(thread),- stopped,- },- geometry,- )),- Err(_) => {- stopped.store(true, Ordering::Release);- let _ = control_tx.send(Control::Stop);- let _ = thread.join();- let detail = error_rx- .try_recv()- .unwrap_or_else(|_| "the screen never produced a frame we can read".into());- Err(StreamError::Capture(detail))- }- }-}--#[allow(clippy::too_many_arguments)]-fn run_video(- fd: std::os::fd::OwnedFd,- node_id: u32,- fps: u16,- cap_height: Option<usize>,- sink: VideoSink,- geometry_tx: mpsc::Sender<CaptureGeometry>,- control_rx: pw::channel::Receiver<Control>,- stopped: Arc<AtomicBool>,-) -> Result<(), String> {- pw::init();- let main_loop = pw::main_loop::MainLoopRc::new(None).map_err(|e| e.to_string())?;- let context = pw::context::ContextRc::new(&main_loop, None).map_err(|e| e.to_string())?;- let core = context.connect_fd_rc(fd, None).map_err(|e| e.to_string())?;-- let props = pw::properties::properties! {- *pw::keys::MEDIA_TYPE => "Video",- *pw::keys::MEDIA_CATEGORY => "Capture",- *pw::keys::MEDIA_ROLE => "Screen",- };- let stream = pw::stream::StreamRc::new(core.clone(), "omnidisc-screen", props)- .map_err(|e| e.to_string())?;-- let state = VideoState {- info: VideoInfoRaw::default(),- sink,- target: None,- announced: false,- geometry_tx: Some(geometry_tx),- };-- let _listener = stream- .add_local_listener_with_user_data(state)- .param_changed(move |_, user, id, param| {- let Some(param) = param else { return };- if id != spa::param::ParamType::Format.as_raw() {- return;- }- let Ok((media_type, media_subtype)) = format_utils::parse_format(param) else {- return;- };- if media_type != MediaType::Video || media_subtype != MediaSubtype::Raw {- return;- }- if user.info.parse(param).is_err() {- return;- }- let size = user.info.size();- let (w, h) = (size.width as usize, size.height as usize);- if w == 0 || h == 0 {- return;- }- // A capped preset means publishing fewer pixels than the screen has;- // the encoder budget should go to the resolution the viewer asked- // for, not the one the monitor happens to be.- let (out_w, out_h) = match cap_height {- Some(cap) if cap < h => {- let scaled_w = ((w * cap / h.max(1)) + 1) & !1usize;- (scaled_w.max(2), cap & !1usize)- }- _ => (w & !1usize, h & !1usize),- };- user.target = Some((out_w, out_h));- if !user.announced {- user.announced = true;- if let Some(tx) = user.geometry_tx.take() {- let _ = tx.send(CaptureGeometry {- width: out_w as u32,- height: out_h as u32,- fps,- });- }- }- })- .process(move |stream, user| {- let Some(mut buffer) = stream.dequeue_buffer() else {- (user.sink)(VideoTick::Idle);- return;- };- let datas = buffer.datas_mut();- if datas.is_empty() {- (user.sink)(VideoTick::Idle);- return;- }- let data = &mut datas[0];- let chunk_size = data.chunk().size() as usize;- let stride = data.chunk().stride().max(0) as usize;- let size = user.info.size();- let (w, h) = (size.width as usize, size.height as usize);- let Some((out_w, out_h)) = user.target else {- (user.sink)(VideoTick::Idle);- return;- };- let Some(bytes) = data.data() else {- (user.sink)(VideoTick::Idle);- return;- };- if chunk_size == 0 || stride == 0 || w == 0 || h == 0 {- (user.sink)(VideoTick::Idle);- return;- }- let swap_rb = matches!(user.info.format(), VideoFormat::RGBx | VideoFormat::RGBA);- let frame = if (out_w, out_h) == (w, h) {- let mut packed = vec![0u8; w * h * 4];- for y in 0..h {- let src = y * stride;- let dst = y * w * 4;- if src + w * 4 > bytes.len() {- break;- }- packed[dst..dst + w * 4].copy_from_slice(&bytes[src..src + w * 4]);- }- packed- } else {- downscale_bgrx(bytes, w, h, stride, out_w, out_h)- };- let mut frame = frame;- if swap_rb {- for px in frame.chunks_exact_mut(4) {- px.swap(0, 2);- }- }- (user.sink)(VideoTick::Frame(CapturedFrame {- data: frame,- width: out_w as u32,- height: out_h as u32,- stride: out_w * 4,- capture_us: unix_micros(),- }));- })- .register()- .map_err(|e| e.to_string())?;-- let mut info = VideoInfoRaw::default();- info.set_format(VideoFormat::BGRx);- let obj = spa::pod::Object {- type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(),- id: spa::param::ParamType::EnumFormat.as_raw(),- properties: video_format_properties(fps),- };- let values: Vec<u8> = spa::pod::serialize::PodSerializer::serialize(- std::io::Cursor::new(Vec::new()),- &spa::pod::Value::Object(obj),- )- .map_err(|e| format!("building the video format: {e}"))?- .0- .into_inner();- let mut params = [Pod::from_bytes(&values).ok_or("invalid video format pod")?];-- stream- .connect(- Direction::Input,- Some(node_id),- pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS,- &mut params,- )- .map_err(|e| e.to_string())?;-- let quit_loop = main_loop.clone();- let _receiver = control_rx.attach(main_loop.loop_(), move |_| {- quit_loop.quit();- });- let _ = &stopped;- main_loop.run();- let _ = stream.disconnect();- Ok(())-}--/// One `EnumFormat` advertising the packed 32-bit layouts every compositor can-/// hand over through shared memory. The `modifier` property is deliberately-/// absent: omitting it is what tells the server we cannot take DMA-BUF.-fn video_format_properties(fps: u16) -> Vec<spa::pod::Property> {- use spa::param::format::{FormatProperties, MediaSubtype as Sub, MediaType as Mt};- use spa::pod::{property, Property};- use spa::utils::Fraction;- let props: Vec<Property> = vec![- property!(FormatProperties::MediaType, Id, Mt::Video),- property!(FormatProperties::MediaSubtype, Id, Sub::Raw),- property!(- FormatProperties::VideoFormat,- Choice,- Enum,- Id,- VideoFormat::BGRx,- VideoFormat::BGRx,- VideoFormat::RGBx,- VideoFormat::BGRA,- VideoFormat::RGBA- ),- property!(- FormatProperties::VideoSize,- Choice,- Range,- Rectangle,- Rectangle {- width: 1920,- height: 1080- },- Rectangle {- width: 1,- height: 1- },- Rectangle {- width: 8192,- height: 8192- }- ),- property!(- FormatProperties::VideoFramerate,- Choice,- Range,- Fraction,- Fraction {- num: fps as u32,- denom: 1- },- Fraction { num: 0, denom: 1 },- Fraction { num: 240, denom: 1 }- ),- ];- props-}--struct AudioState {- info: spa::param::audio::AudioInfoRaw,- sink: AudioSink,-}--/// The default sink's monitor. The ScreenCast portal carries no audio, so this-/// is a separate stream that follows whatever the desktop is playing.-pub fn start_monitor_audio(sink: AudioSink) -> Result<StreamHandle, StreamError> {- let (control_tx, control_rx) = pw::channel::channel::<Control>();- let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();- let stopped = Arc::new(AtomicBool::new(false));- let thread = std::thread::Builder::new()- .name("omnidisc-pw-audio".into())- .spawn(move || {- if let Err(e) = run_audio(sink, control_rx, ready_tx.clone()) {- let _ = ready_tx.send(Err(e));- }- })- .map_err(|e| StreamError::Capture(format!("pipewire audio thread: {e}")))?;-- match ready_rx.recv_timeout(NEGOTIATE_TIMEOUT) {- Ok(Ok(())) => Ok(StreamHandle {- tx: Some(control_tx),- thread: Some(thread),- stopped,- }),- Ok(Err(e)) => {- let _ = control_tx.send(Control::Stop);- let _ = thread.join();- Err(StreamError::Capture(e))- }- Err(_) => {- let _ = control_tx.send(Control::Stop);- let _ = thread.join();- Err(StreamError::Capture("no audio from the desktop".into()))- }- }-}--fn run_audio(- sink: AudioSink,- control_rx: pw::channel::Receiver<Control>,- ready_tx: mpsc::Sender<Result<(), String>>,-) -> Result<(), String> {- pw::init();- let main_loop = pw::main_loop::MainLoopRc::new(None).map_err(|e| e.to_string())?;- let context = pw::context::ContextRc::new(&main_loop, None).map_err(|e| e.to_string())?;- let core = context.connect_rc(None).map_err(|e| e.to_string())?;-- let mut props = pw::properties::properties! {- *pw::keys::MEDIA_TYPE => "Audio",- *pw::keys::MEDIA_CATEGORY => "Capture",- *pw::keys::MEDIA_ROLE => "Screen",- };- props.insert(*pw::keys::STREAM_CAPTURE_SINK, "true");- let stream = pw::stream::StreamRc::new(core.clone(), "omnidisc-screen-audio", props)- .map_err(|e| e.to_string())?;-- let state = AudioState {- info: spa::param::audio::AudioInfoRaw::new(),- sink,- };- let _listener = stream- .add_local_listener_with_user_data(state)- .param_changed(|_, user, id, param| {- let Some(param) = param else { return };- if id != spa::param::ParamType::Format.as_raw() {- return;- }- let Ok((media_type, media_subtype)) = format_utils::parse_format(param) else {- return;- };- if media_type != MediaType::Audio || media_subtype != MediaSubtype::Raw {- return;- }- let _ = user.info.parse(param);- })- .process(|stream, user| {- let Some(mut buffer) = stream.dequeue_buffer() else {- return;- };- let datas = buffer.datas_mut();- if datas.is_empty() {- return;- }- let data = &mut datas[0];- let size = data.chunk().size() as usize;- let Some(bytes) = data.data() else { return };- let n = (size / std::mem::size_of::<f32>()).min(bytes.len() / 4);- if n == 0 {- return;- }- let mut samples = Vec::with_capacity(n);- for i in 0..n {- let b = &bytes[i * 4..i * 4 + 4];- samples.push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));- }- (user.sink)(&samples);- })- .register()- .map_err(|e| e.to_string())?;-- let (rate, channels) = super::audio_format();- let mut info = spa::param::audio::AudioInfoRaw::new();- info.set_format(spa::param::audio::AudioFormat::F32LE);- info.set_rate(rate);- info.set_channels(channels);- let obj = spa::pod::Object {- type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(),- id: spa::param::ParamType::EnumFormat.as_raw(),- properties: info.into(),- };- let values: Vec<u8> = spa::pod::serialize::PodSerializer::serialize(- std::io::Cursor::new(Vec::new()),- &spa::pod::Value::Object(obj),- )- .map_err(|e| format!("building the audio format: {e}"))?- .0- .into_inner();- let mut params = [Pod::from_bytes(&values).ok_or("invalid audio format pod")?];-- stream- .connect(- Direction::Input,- None,- pw::stream::StreamFlags::AUTOCONNECT- | pw::stream::StreamFlags::MAP_BUFFERS- | pw::stream::StreamFlags::RT_PROCESS,- &mut params,- )- .map_err(|e| e.to_string())?;-- let _ = ready_tx.send(Ok(()));- let quit_loop = main_loop.clone();- let _receiver = control_rx.attach(main_loop.loop_(), move |_| {- quit_loop.quit();- });- main_loop.run();- let _ = stream.disconnect();- Ok(())-}--/// A moving test pattern, so the media pipeline can be exercised on a headless-/// box (CI) where there is no compositor to ask.-pub fn start_synthetic(- width: u32,- height: u32,- fps: u16,- sink: VideoSink,-) -> Result<(StreamHandle, CaptureGeometry), StreamError> {- let (control_tx, control_rx) = pw::channel::channel::<Control>();- let stopped = Arc::new(AtomicBool::new(false));- let running = stopped.clone();- let (w, h) = ((width.max(2) & !1) as usize, (height.max(2) & !1) as usize);- let interval = Duration::from_nanos(1_000_000_000 / fps.max(1) as u64);- let thread = std::thread::Builder::new()- .name("omnidisc-synthetic".into())- .spawn(move || {- let mut tick: usize = 0;- while !running.load(Ordering::Acquire) {- let mut data = vec![0u8; w * h * 4];- for y in 0..h {- for x in 0..w {- let i = (y * w + x) * 4;- data[i] = ((x + tick) % 256) as u8;- data[i + 1] = ((y + tick) % 256) as u8;- data[i + 2] = ((x + y) % 256) as u8;- data[i + 3] = 255;- }- }- sink(VideoTick::Frame(CapturedFrame {- data,- width: w as u32,- height: h as u32,- stride: w * 4,- capture_us: unix_micros(),- }));- tick = tick.wrapping_add(1);- std::thread::sleep(interval);- }- })- .map_err(|e| StreamError::Capture(format!("synthetic thread: {e}")))?;- drop(control_rx);- Ok((- StreamHandle {- tx: Some(control_tx),- thread: Some(thread),- stopped,- },- CaptureGeometry {- width: w as u32,- height: h as u32,- fps,- },- ))-}diff --git a/src-tauri/omnidisc-media/src/capture/macos.rs b/src-tauri/omnidisc-media/src/capture/macos.rsdeleted file mode 100644index 0be8a6f9..00000000--- a/src-tauri/omnidisc-media/src/capture/macos.rs+++ /dev/null@@ -1,652 +0,0 @@-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 std::ffi::c_char, 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(),- c"SCStreamUpdateFrameStatus".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 &s in &bufs[0][..frames] {- out.push(s);- out.push(s);- }- }- _ => {- for (&l, &r) in bufs[0][..frames].iter().zip(&bufs[1][..frames]) {- out.push(l);- out.push(r);- }- }- }- 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 thumbnail_for(source: &SourceId) -> Option<String> {- let content = shareable().ok()?;- match source {- SourceId::Display { id } => {- let d = content- .displays()- .into_iter()- .find(|d| d.display_id() == *id)?;- 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, d.width(), d.height())- }- SourceId::Window { id } => {- let w = content- .windows()- .into_iter()- .find(|w| w.window_id() == *id)?;- let frame = w.frame();- let filter = SCContentFilter::create().with_window(&w).build();- thumbnail(- &filter,- (frame.size.width as u32).max(1),- (frame.size.height as u32).max(1),- )- }- SourceId::Synthetic { .. } => None,- }- }-- 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.rsdeleted file mode 100644index 6181f13e..00000000--- a/src-tauri/omnidisc-media/src/capture/mod.rs+++ /dev/null@@ -1,107 +0,0 @@-use crate::stream::{AudioMode, SourceId, StreamError, StreamSources};-use std::sync::Arc;--#[cfg(target_os = "macos")]-mod macos;-#[cfg(target_os = "macos")]-pub use self::macos::*;--#[cfg(windows)]-mod windows;-#[cfg(windows)]-pub use self::windows::*;--#[cfg(all(target_os = "linux", feature = "linux-capture"))]-mod linux;-#[cfg(all(target_os = "linux", feature = "linux-capture"))]-pub use self::linux::*;--#[cfg(not(any(- target_os = "macos",- windows,- all(target_os = "linux", feature = "linux-capture")-)))]-mod stub;-#[cfg(not(any(- target_os = "macos",- windows,- all(target_os = "linux", feature = "linux-capture")-)))]-pub use self::stub::*;--/// Whether this build can capture a screen at all. The interface asks the-/// backend rather than the operating system, so a client compiled without the-/// Linux capture backend says so instead of offering a button that fails.-pub const SCREEN_CAPTURE_SUPPORTED: bool = cfg!(any(- target_os = "macos",- windows,- all(target_os = "linux", feature = "linux-capture")-));--#[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 thumbnail_for(source: &SourceId) -> Option<String>;- 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 thumbnail_for(source: &SourceId) -> Option<String> {- Platform::thumbnail_for(source)-}--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.rsdeleted file mode 100644index a878f0b7..00000000--- a/src-tauri/omnidisc-media/src/capture/stub.rs+++ /dev/null@@ -1,63 +0,0 @@-use super::{AudioSink, CaptureApi, CaptureGeometry, CaptureOptions, VideoSink};-use crate::stream::{AudioMode, SourceId, 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 thumbnail_for(_source: &SourceId) -> Option<String> {- None- }-- 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/capture/windows/audio.rs b/src-tauri/omnidisc-media/src/capture/windows/audio.rsdeleted file mode 100644index d40bf37c..00000000--- a/src-tauri/omnidisc-media/src/capture/windows/audio.rs+++ /dev/null@@ -1,457 +0,0 @@-use crate::capture::{AudioSink, AUDIO_CHANNELS, AUDIO_SAMPLE_RATE};-use crate::stream::{AudioApp, StreamError};-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{mpsc, Arc};-use std::time::{Duration, Instant};-use windows::core::{implement, Interface, Ref};-use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};-use windows::Win32::Media::Audio::{- eRender, ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation,- IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl,- IAudioCaptureClient, IAudioClient, IAudioSessionControl2, IAudioSessionManager2,- IMMDeviceEnumerator, MMDeviceEnumerator, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED,- AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK, AUDIOCLIENT_ACTIVATION_PARAMS,- AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,- AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, DEVICE_STATE_ACTIVE,- PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE,- PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,- WAVEFORMATEX,-};-use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PROPVARIANT_0_0};-use windows::Win32::System::Com::{CoCreateInstance, CoIncrementMTAUsage, BLOB, CLSCTX_ALL};-use windows::Win32::System::Threading::{CreateEventW, SetEvent, WaitForSingleObject};-use windows::Win32::System::Variant::VT_BLOB;--const WAVE_FORMAT_PCM: u16 = 1;-const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;-/// `ActivateAudioInterfaceAsync` can sit on a slow audio engine; the TODO-/// budget for "screen share started" is 12 s.-const ACTIVATE_TIMEOUT_MS: u32 = 12_000;-const BUFFER_DURATION_100NS: i64 = 20 * 10_000;-const HEARTBEAT_QUIET: Duration = Duration::from_millis(250);-const HEARTBEAT_FRAMES: usize = (AUDIO_SAMPLE_RATE as usize / 100) * AUDIO_CHANNELS as usize;--/// WASAPI process loopback landed in Windows 10 build 20348 (Server 2022 /-/// Windows 11). Below that there is no per-application audio at all.-pub const MIN_LOOPBACK_BUILD: u32 = 20348;--pub fn windows_build() -> u32 {- use windows::Wdk::System::SystemServices::RtlGetVersion;- use windows::Win32::System::SystemInformation::OSVERSIONINFOW;- let mut info = OSVERSIONINFOW {- dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32,- ..Default::default()- };- let status = unsafe { RtlGetVersion(&mut info) };- if status.is_ok() {- info.dwBuildNumber- } else {- 0- }-}--pub fn process_loopback_supported() -> bool {- windows_build() >= MIN_LOOPBACK_BUILD-}--pub fn unsupported_build_error() -> StreamError {- StreamError::Capture(format!(- "sharing application audio needs Windows 10 build {MIN_LOOPBACK_BUILD} or newer (this machine reports build {}); update Windows or share without audio",- windows_build()- ))-}--#[implement(IActivateAudioInterfaceCompletionHandler)]-struct Completion {- event: isize,-}--impl IActivateAudioInterfaceCompletionHandler_Impl for Completion_Impl {- fn ActivateCompleted(- &self,- _operation: Ref<'_, IActivateAudioInterfaceAsyncOperation>,- ) -> windows::core::Result<()> {- unsafe {- let _ = SetEvent(HANDLE(self.event as *mut std::ffi::c_void));- }- Ok(())- }-}--struct Event(HANDLE);--impl Event {- fn new() -> Result<Self, StreamError> {- let handle = unsafe { CreateEventW(None, false, false, None) }- .map_err(|e| StreamError::Capture(format!("CreateEventW: {e}")))?;- Ok(Self(handle))- }-- fn raw(&self) -> HANDLE {- self.0- }-- fn wait(&self, ms: u32) -> bool {- unsafe { WaitForSingleObject(self.0, ms) == WAIT_OBJECT_0 }- }-}--impl Drop for Event {- fn drop(&mut self) {- unsafe {- let _ = CloseHandle(self.0);- }- }-}--fn wave_format(float: bool) -> WAVEFORMATEX {- let bits: u16 = if float { 32 } else { 16 };- let channels = AUDIO_CHANNELS as u16;- let block_align = channels * bits / 8;- WAVEFORMATEX {- wFormatTag: if float {- WAVE_FORMAT_IEEE_FLOAT- } else {- WAVE_FORMAT_PCM- },- nChannels: channels,- nSamplesPerSec: AUDIO_SAMPLE_RATE,- nAvgBytesPerSec: AUDIO_SAMPLE_RATE * block_align as u32,- nBlockAlign: block_align,- wBitsPerSample: bits,- cbSize: 0,- }-}--struct Activated {- client: IAudioClient,- float: bool,-}--fn activate(pid: u32, include_tree: bool) -> Result<IAudioClient, StreamError> {- let mut params = AUDIOCLIENT_ACTIVATION_PARAMS {- ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,- Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 {- ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS {- TargetProcessId: pid,- ProcessLoopbackMode: if include_tree {- PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE- } else {- PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE- },- },- },- };- // Never let this variant be dropped: PROPVARIANT's Drop runs- // PropVariantClear, which for VT_BLOB hands pBlobData to the COM allocator —- // and this blob points at the stack local above. Freeing that corrupts the- // heap, which is precisely how this failed the first time. The variant only- // borrows `params` for the duration of the call, so there is nothing to- // release either way.- let mut prop = std::mem::ManuallyDrop::new(PROPVARIANT::default());- unsafe {- let inner: &mut PROPVARIANT_0_0 = &mut prop.Anonymous.Anonymous;- inner.vt = VT_BLOB;- inner.Anonymous.blob = BLOB {- cbSize: std::mem::size_of::<AUDIOCLIENT_ACTIVATION_PARAMS>() as u32,- pBlobData: &mut params as *mut AUDIOCLIENT_ACTIVATION_PARAMS as *mut u8,- };- }-- let event = Event::new()?;- let handler: IActivateAudioInterfaceCompletionHandler = Completion {- event: event.raw().0 as isize,- }- .into();- let operation = unsafe {- ActivateAudioInterfaceAsync(- VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK,- &IAudioClient::IID,- Some(&*prop as *const PROPVARIANT),- &handler,- )- }- .map_err(|e| StreamError::Capture(format!("ActivateAudioInterfaceAsync: {e}")))?;- if !event.wait(ACTIVATE_TIMEOUT_MS) {- return Err(StreamError::Capture(- "the Windows audio engine did not answer within 12 s; try sharing without audio".into(),- ));- }- let mut hr = windows::core::HRESULT(0);- let mut raw: Option<windows::core::IUnknown> = None;- unsafe {- operation- .GetActivateResult(&mut hr, &mut raw)- .map_err(|e| StreamError::Capture(format!("GetActivateResult: {e}")))?;- }- hr.ok()- .map_err(|e| StreamError::Capture(format!("process loopback activation refused: {e}")))?;- raw.ok_or_else(|| StreamError::Capture("process loopback returned no audio client".into()))?- .cast::<IAudioClient>()- .map_err(|e| StreamError::Capture(format!("IAudioClient: {e}")))-}--fn try_initialize(pid: u32, include_tree: bool, float: bool) -> Result<Activated, StreamError> {- let client = activate(pid, include_tree)?;- let format = wave_format(float);- unsafe {- client- .Initialize(- AUDCLNT_SHAREMODE_SHARED,- AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_EVENTCALLBACK,- BUFFER_DURATION_100NS,- 0,- &format,- None,- )- .map_err(|e| {- StreamError::Capture(format!(- "the audio engine refused 48 kHz stereo {} capture: {e}",- if float { "float" } else { "16-bit" }- ))- })?;- }- Ok(Activated { client, float })-}--fn initialize(pid: u32, include_tree: bool) -> Result<Activated, StreamError> {- match try_initialize(pid, include_tree, true) {- Ok(activated) => Ok(activated),- Err(e) => {- tracing::debug!("[omnidisc-media] {e}; retrying as 16-bit PCM");- try_initialize(pid, include_tree, false)- }- }-}--pub struct AudioCaptureHandle {- stop: Arc<AtomicBool>,- thread: Option<std::thread::JoinHandle<()>>,-}--impl AudioCaptureHandle {- pub fn stop(mut self) {- self.shutdown();- }-- fn shutdown(&mut self) {- self.stop.store(true, Ordering::Release);- if let Some(t) = self.thread.take() {- let _ = t.join();- }- }-}--impl Drop for AudioCaptureHandle {- fn drop(&mut self) {- self.shutdown();- }-}--fn pump(- activated: Activated,- sink: AudioSink,- stop: Arc<AtomicBool>,- ready: &Event,-) -> Result<(), StreamError> {- let client = activated.client;- unsafe {- client- .SetEventHandle(ready.raw())- .map_err(|e| StreamError::Capture(format!("SetEventHandle: {e}")))?;- }- let capture: IAudioCaptureClient = unsafe { client.GetService() }- .map_err(|e| StreamError::Capture(format!("IAudioCaptureClient: {e}")))?;- unsafe {- client- .Start()- .map_err(|e| StreamError::Capture(format!("IAudioClient::Start: {e}")))?;- }- let silence = vec![0f32; HEARTBEAT_FRAMES];- // The publish side expects whole 10 ms frames; WASAPI packet sizes are not- // guaranteed to line up, so partial frames are carried over instead of- // being dropped.- let mut pending: Vec<f32> = Vec::with_capacity(HEARTBEAT_FRAMES * 4);- let mut last_pcm = Instant::now();- while !stop.load(Ordering::Acquire) {- ready.wait(100);- loop {- let mut data: *mut u8 = std::ptr::null_mut();- let mut frames: u32 = 0;- let mut flags: u32 = 0;- let got = unsafe { capture.GetBuffer(&mut data, &mut frames, &mut flags, None, None) };- // A successful call with zero frames means the buffer is empty- // (AUDCLNT_S_BUFFER_EMPTY); nothing was acquired, so nothing is- // released.- if got.is_err() || frames == 0 {- break;- }- let channels = AUDIO_CHANNELS as usize;- let samples = frames as usize * channels;- if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 || data.is_null() {- pending.resize(pending.len() + samples, 0.0);- } else if activated.float {- let src = unsafe { std::slice::from_raw_parts(data as *const f32, samples) };- pending.extend_from_slice(src);- } else {- let src = unsafe { std::slice::from_raw_parts(data as *const i16, samples) };- pending.extend(src.iter().map(|s| *s as f32 / i16::MAX as f32));- }- unsafe {- let _ = capture.ReleaseBuffer(frames);- }- let whole = pending.len() / HEARTBEAT_FRAMES * HEARTBEAT_FRAMES;- if whole > 0 {- sink(&pending[..whole]);- pending.drain(..whole);- last_pcm = Instant::now();- }- }- if last_pcm.elapsed() >= HEARTBEAT_QUIET {- // WHY: process loopback delivers nothing at all while the target is- // silent, and the publish gate upstream waits for a first packet.- sink(&silence);- last_pcm = Instant::now();- }- }- unsafe {- let _ = client.Stop();- }- Ok(())-}--pub fn start_process_loopback(- pid: u32,- include_tree: bool,- sink: AudioSink,-) -> Result<AudioCaptureHandle, StreamError> {- if !process_loopback_supported() {- return Err(unsupported_build_error());- }- let stop = Arc::new(AtomicBool::new(false));- let stop_thread = stop.clone();- let (tx, rx) = mpsc::channel::<Result<(), StreamError>>();- let thread = std::thread::Builder::new()- .name("omnidisc-wasapi".into())- .spawn(move || {- ensure_mta();- let ready = match Event::new() {- Ok(e) => e,- Err(e) => {- let _ = tx.send(Err(e));- return;- }- };- match initialize(pid, include_tree) {- Ok(activated) => {- let _ = tx.send(Ok(()));- if let Err(e) = pump(activated, sink, stop_thread, &ready) {- tracing::warn!("[omnidisc-media] process loopback stopped: {e}");- }- }- Err(e) => {- let _ = tx.send(Err(e));- }- }- })- .map_err(|e| StreamError::Capture(format!("wasapi thread: {e}")))?;- match rx.recv() {- Ok(Ok(())) => Ok(AudioCaptureHandle {- stop,- thread: Some(thread),- }),- Ok(Err(e)) => {- let _ = thread.join();- Err(e)- }- Err(_) => {- let _ = thread.join();- Err(StreamError::Capture(- "the audio capture thread stopped before it started".into(),- ))- }- }-}--/// Enumerates render sessions across **every** active endpoint, not just the-/// default one: engines like FMOD and OpenAL open their own device, and a-/// session that only exists on a secondary endpoint would otherwise be missing.-/// Silent sessions stay in the list so a paused tab is still pickable.-pub fn audio_apps() -> Vec<AudioApp> {- let own_pid = std::process::id();- let mut out: Vec<AudioApp> = Vec::new();- let mut seen: Vec<u32> = Vec::new();- let enumerator: IMMDeviceEnumerator =- match unsafe { CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) } {- Ok(e) => e,- Err(e) => {- tracing::debug!("[omnidisc-media] MMDeviceEnumerator: {e}");- return out;- }- };- let devices = match unsafe { enumerator.EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) } {- Ok(d) => d,- Err(e) => {- tracing::debug!("[omnidisc-media] EnumAudioEndpoints: {e}");- return out;- }- };- let count = unsafe { devices.GetCount() }.unwrap_or(0);- for i in 0..count {- let Ok(device) = (unsafe { devices.Item(i) }) else {- continue;- };- let manager: IAudioSessionManager2 = match unsafe { device.Activate(CLSCTX_ALL, None) } {- Ok(m) => m,- Err(_) => continue,- };- let Ok(sessions) = (unsafe { manager.GetSessionEnumerator() }) else {- continue;- };- let n = unsafe { sessions.GetCount() }.unwrap_or(0);- for s in 0..n {- let Ok(control) = (unsafe { sessions.GetSession(s) }) else {- continue;- };- let Ok(control2) = control.cast::<IAudioSessionControl2>() else {- continue;- };- if unsafe { control2.IsSystemSoundsSession() }.is_ok() {- continue;- }- let Ok(pid) = (unsafe { control2.GetProcessId() }) else {- continue;- };- if pid == 0 || pid == own_pid || seen.contains(&pid) {- continue;- }- seen.push(pid);- if let Some(app) = super::sources::audio_app(pid) {- out.push(app);- }- }- }- out.sort_by_key(|a| a.name.to_lowercase());- out-}--/// COM apartment guard for the enumeration helpers, which may run on a tokio-/// blocking thread whose apartment we do not control.-/// Guarantees the process has a multithreaded apartment, once, for good.-///-/// The obvious shape — initialise COM on entry, uninitialise on the way out —-/// crashes. `CoUninitialize` tears the apartment down, but the activation-/// factories the windows crate caches for WinRT types survive it, so the next-/// `GraphicsCaptureSession::IsSupported` dereferences freed memory: opening the-/// share picker a second time was enough to fault. `CoIncrementMTAUsage` is the-/// API for this exact need — it keeps an implicit MTA alive for every thread-/// that never initialises one itself, and the cookie is deliberately never-/// released.-pub fn ensure_mta() {- static MTA: std::sync::OnceLock<()> = std::sync::OnceLock::new();- MTA.get_or_init(|| {- if let Err(e) = unsafe { CoIncrementMTAUsage() } {- tracing::warn!("[omnidisc-media] could not hold an MTA open: {e}");- }- });-}diff --git a/src-tauri/omnidisc-media/src/capture/windows/d3d.rs b/src-tauri/omnidisc-media/src/capture/windows/d3d.rsdeleted file mode 100644index fc5c0568..00000000--- a/src-tauri/omnidisc-media/src/capture/windows/d3d.rs+++ /dev/null@@ -1,489 +0,0 @@-use crate::stream::StreamError;-use std::sync::{Arc, Mutex, OnceLock, Weak};-use windows::core::Interface;-use windows::Win32::Foundation::HMODULE;-use windows::Win32::Graphics::Direct3D::{- D3D_DRIVER_TYPE, D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_FEATURE_LEVEL,- D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1,-};-use windows::Win32::Graphics::Direct3D11::{- D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Multithread, ID3D11Texture2D,- ID3D11VideoContext, ID3D11VideoDevice, ID3D11VideoProcessor, ID3D11VideoProcessorEnumerator,- ID3D11VideoProcessorInputView, ID3D11VideoProcessorOutputView, D3D11_BIND_RENDER_TARGET,- D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT,- D3D11_CREATE_DEVICE_VIDEO_SUPPORT, D3D11_MAPPED_SUBRESOURCE, D3D11_MAP_READ, D3D11_SDK_VERSION,- D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING,- D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE, D3D11_VIDEO_PROCESSOR_CONTENT_DESC,- D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0,- D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0,- D3D11_VIDEO_PROCESSOR_STREAM, D3D11_VPIV_DIMENSION, D3D11_VPIV_DIMENSION_TEXTURE2D,- D3D11_VPOV_DIMENSION_TEXTURE2D,-};-use windows::Win32::Graphics::Dxgi::Common::{- DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12, DXGI_RATIONAL, DXGI_SAMPLE_DESC,-};--const NV12_RING: usize = 3;--/// D3D11 device shared by the capture session and the encoder.-///-/// COM interfaces from `windows-rs` are `!Send`, but this device is created-/// with multithread protection on (`ID3D11Multithread::SetMultithreadProtected`),-/// so the immediate context may legally be driven from the WGC callback thread-/// and the encode thread at the same time. That is the invariant behind the-/// `Send`/`Sync` impls below; do not hand these objects to a context that has-/// multithread protection disabled.-pub struct Gpu {- device: ID3D11Device,- context: ID3D11DeviceContext,-}--unsafe impl Send for Gpu {}-unsafe impl Sync for Gpu {}--fn hr(what: &str, e: windows::core::Error) -> StreamError {- StreamError::Capture(format!("{what}: {e}"))-}--fn create_device(- driver: D3D_DRIVER_TYPE,-) -> windows::core::Result<(ID3D11Device, ID3D11DeviceContext)> {- let levels = [D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0];- let mut device: Option<ID3D11Device> = None;- let mut context: Option<ID3D11DeviceContext> = None;- let mut level = D3D_FEATURE_LEVEL::default();- unsafe {- D3D11CreateDevice(- None,- driver,- HMODULE::default(),- D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,- Some(&levels),- D3D11_SDK_VERSION,- Some(&mut device),- Some(&mut level),- Some(&mut context),- )?;- }- match (device, context) {- (Some(d), Some(c)) => Ok((d, c)),- _ => Err(windows::core::Error::from_win32()),- }-}--impl Gpu {- fn create() -> Result<Self, StreamError> {- let (device, context) = match create_device(D3D_DRIVER_TYPE_HARDWARE) {- Ok(pair) => pair,- Err(e) => {- tracing::warn!(- "[omnidisc-media] no hardware D3D11 device ({e}); falling back to the WARP software rasteriser, screen share will be slow"- );- create_device(D3D_DRIVER_TYPE_WARP)- .map_err(|e| hr("D3D11CreateDevice (WARP)", e))?- }- };- let multithread: ID3D11Multithread =- context.cast().map_err(|e| hr("ID3D11Multithread", e))?;- unsafe {- let _ = multithread.SetMultithreadProtected(true);- }- Ok(Self { device, context })- }-- pub fn device(&self) -> &ID3D11Device {- &self.device- }-- pub fn context(&self) -> &ID3D11DeviceContext {- &self.context- }-- fn texture(- &self,- width: u32,- height: u32,- format: DXGI_FORMAT,- staging: bool,- seed: Option<&[u8]>,- seed_pitch: u32,- ) -> Result<ID3D11Texture2D, StreamError> {- let desc = D3D11_TEXTURE2D_DESC {- Width: width,- Height: height,- MipLevels: 1,- ArraySize: 1,- Format: format,- SampleDesc: DXGI_SAMPLE_DESC {- Count: 1,- Quality: 0,- },- Usage: if staging {- D3D11_USAGE_STAGING- } else {- D3D11_USAGE_DEFAULT- },- BindFlags: if staging {- 0- } else {- (D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE).0 as u32- },- CPUAccessFlags: if staging {- D3D11_CPU_ACCESS_READ.0 as u32- } else {- 0- },- MiscFlags: 0,- };- let initial = seed.map(|data| D3D11_SUBRESOURCE_DATA {- pSysMem: data.as_ptr().cast(),- SysMemPitch: seed_pitch,- SysMemSlicePitch: 0,- });- let mut out: Option<ID3D11Texture2D> = None;- unsafe {- self.device- .CreateTexture2D(- &desc,- initial.as_ref().map(|d| d as *const _),- Some(&mut out),- )- .map_err(|e| hr("CreateTexture2D", e))?;- }- out.ok_or_else(|| StreamError::Capture("CreateTexture2D returned nothing".into()))- }-- pub fn bgra_texture(&self, width: u32, height: u32) -> Result<ID3D11Texture2D, StreamError> {- self.texture(width, height, DXGI_FORMAT_B8G8R8A8_UNORM, false, None, 0)- }-}--/// Process-wide device. Capture and encode must share one so a captured texture-/// can be converted without crossing devices.-pub fn gpu() -> Result<Arc<Gpu>, StreamError> {- static GPU: OnceLock<Result<Arc<Gpu>, String>> = OnceLock::new();- GPU.get_or_init(|| Gpu::create().map(Arc::new).map_err(|e| e.to_string()))- .clone()- .map_err(StreamError::Capture)-}--struct PoolInner {- free: Vec<ID3D11Texture2D>,-}--unsafe impl Send for PoolInner {}--/// Fixed-size ring of BGRA textures so the capture callback never writes into a-/// texture the encoder still holds.-pub struct TexturePool {- inner: Arc<Mutex<PoolInner>>,- gpu: Arc<Gpu>,- width: u32,- height: u32,- budget: usize,- handed_out: Arc<Mutex<usize>>,-}--impl TexturePool {- pub fn new(gpu: Arc<Gpu>, width: u32, height: u32, budget: usize) -> Self {- Self {- inner: Arc::new(Mutex::new(PoolInner { free: Vec::new() })),- gpu,- width,- height,- budget,- handed_out: Arc::new(Mutex::new(0)),- }- }-- pub fn size(&self) -> (u32, u32) {- (self.width, self.height)- }-- pub fn acquire(&self) -> Result<PooledTexture, StreamError> {- let reused = self.inner.lock().ok().and_then(|mut g| g.free.pop());- let texture = match reused {- Some(t) => t,- None => {- let live = self.handed_out.lock().map(|g| *g).unwrap_or(0);- if live >= self.budget {- return Err(StreamError::Capture(- "capture texture pool exhausted; the encoder is not releasing frames"- .into(),- ));- }- self.gpu.bgra_texture(self.width, self.height)?- }- };- if let Ok(mut g) = self.handed_out.lock() {- *g += 1;- }- Ok(PooledTexture {- texture: Some(texture),- pool: Arc::downgrade(&self.inner),- handed_out: Arc::downgrade(&self.handed_out),- })- }-}--pub struct PooledTexture {- texture: Option<ID3D11Texture2D>,- pool: Weak<Mutex<PoolInner>>,- handed_out: Weak<Mutex<usize>>,-}--// SAFETY: the texture is only ever touched through the shared `Gpu`, whose-// immediate context is multithread-protected (see `Gpu`).-unsafe impl Send for PooledTexture {}-unsafe impl Sync for PooledTexture {}--impl PooledTexture {- pub fn texture(&self) -> Option<&ID3D11Texture2D> {- self.texture.as_ref()- }-}--impl Drop for PooledTexture {- fn drop(&mut self) {- if let (Some(t), Some(pool)) = (self.texture.take(), self.pool.upgrade()) {- if let Ok(mut g) = pool.lock() {- g.free.push(t);- }- }- if let Some(count) = self.handed_out.upgrade() {- if let Ok(mut g) = count.lock() {- *g = g.saturating_sub(1);- }- }- }-}--/// BGRA -> NV12 with scaling, on the GPU, through the D3D11 video processor.-/// Both publish paths need NV12: Media Foundation encoders take it directly and-/// libwebrtc's `NV12Buffer` is the cheapest raw hand-off.-pub struct Nv12Converter {- gpu: Arc<Gpu>,- video_device: ID3D11VideoDevice,- video_context: ID3D11VideoContext,- enumerator: ID3D11VideoProcessorEnumerator,- processor: ID3D11VideoProcessor,- ring: Vec<(ID3D11Texture2D, ID3D11VideoProcessorOutputView)>,- next: usize,- staging: Option<ID3D11Texture2D>,- dst_width: u32,- dst_height: u32,-}--// SAFETY: same invariant as `Gpu` — the underlying immediate context is-// multithread-protected, and a converter is only driven from one thread at a-// time (the encode loop owns it).-unsafe impl Send for Nv12Converter {}--pub struct Nv12Cpu {- pub data: Vec<u8>,- pub stride_y: u32,- pub stride_uv: u32,- pub width: u32,- pub height: u32,-}--impl Nv12Cpu {- pub fn planes(&self) -> (&[u8], &[u8]) {- let split = (self.stride_y * self.height) as usize;- let split = split.min(self.data.len());- self.data.split_at(split)- }-}--impl Nv12Converter {- pub fn new(- gpu: Arc<Gpu>,- src_width: u32,- src_height: u32,- dst_width: u32,- dst_height: u32,- ) -> Result<Self, StreamError> {- let video_device: ID3D11VideoDevice = gpu- .device()- .cast()- .map_err(|e| hr("ID3D11VideoDevice (no GPU video support)", e))?;- let video_context: ID3D11VideoContext = gpu- .context()- .cast()- .map_err(|e| hr("ID3D11VideoContext", e))?;- let desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC {- InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,- InputFrameRate: DXGI_RATIONAL {- Numerator: 60,- Denominator: 1,- },- InputWidth: src_width,- InputHeight: src_height,- OutputFrameRate: DXGI_RATIONAL {- Numerator: 60,- Denominator: 1,- },- OutputWidth: dst_width,- OutputHeight: dst_height,- Usage: windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_USAGE_PLAYBACK_NORMAL,- };- let enumerator = unsafe {- video_device- .CreateVideoProcessorEnumerator(&desc)- .map_err(|e| hr("CreateVideoProcessorEnumerator", e))?- };- let processor = unsafe {- video_device- .CreateVideoProcessor(&enumerator, 0)- .map_err(|e| hr("CreateVideoProcessor", e))?- };- unsafe {- video_context.VideoProcessorSetStreamFrameFormat(- &processor,- 0,- D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,- );- }-- let mut ring = Vec::with_capacity(NV12_RING);- for _ in 0..NV12_RING {- let tex = gpu.texture(dst_width, dst_height, DXGI_FORMAT_NV12, false, None, 0)?;- let view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC {- ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D,- Anonymous: D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 {- Texture2D: windows::Win32::Graphics::Direct3D11::D3D11_TEX2D_VPOV {- MipSlice: 0,- },- },- };- let mut view: Option<ID3D11VideoProcessorOutputView> = None;- unsafe {- video_device- .CreateVideoProcessorOutputView(&tex, &enumerator, &view_desc, Some(&mut view))- .map_err(|e| hr("CreateVideoProcessorOutputView", e))?;- }- let view = view.ok_or_else(|| {- StreamError::Capture("CreateVideoProcessorOutputView returned nothing".into())- })?;- ring.push((tex, view));- }-- Ok(Self {- gpu,- video_device,- video_context,- enumerator,- processor,- ring,- next: 0,- staging: None,- dst_width,- dst_height,- })- }-- pub fn size(&self) -> (u32, u32) {- (self.dst_width, self.dst_height)- }-- pub fn convert(&mut self, src: &ID3D11Texture2D) -> Result<ID3D11Texture2D, StreamError> {- let idx = self.next % self.ring.len();- self.next = self.next.wrapping_add(1);- let input_desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC {- FourCC: 0,- ViewDimension: D3D11_VPIV_DIMENSION(D3D11_VPIV_DIMENSION_TEXTURE2D.0),- Anonymous: D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 {- Texture2D: windows::Win32::Graphics::Direct3D11::D3D11_TEX2D_VPIV {- MipSlice: 0,- ArraySlice: 0,- },- },- };- let mut input_view: Option<ID3D11VideoProcessorInputView> = None;- unsafe {- self.video_device- .CreateVideoProcessorInputView(- src,- &self.enumerator,- &input_desc,- Some(&mut input_view),- )- .map_err(|e| hr("CreateVideoProcessorInputView", e))?;- }- let input_view = input_view.ok_or_else(|| {- StreamError::Capture("CreateVideoProcessorInputView returned nothing".into())- })?;- let (out_tex, out_view) = &self.ring[idx];- // WHY: `pInputSurface` is a `ManuallyDrop`, so the reference it holds is- // never released on its own — the view is dropped by hand after the blt- // or it leaks one COM reference per captured frame.- let mut streams = [D3D11_VIDEO_PROCESSOR_STREAM {- Enable: true.into(),- OutputIndex: 0,- InputFrameOrField: 0,- PastFrames: 0,- FutureFrames: 0,- ppPastSurfaces: std::ptr::null_mut(),- pInputSurface: std::mem::ManuallyDrop::new(Some(input_view)),- ppFutureSurfaces: std::ptr::null_mut(),- ppPastSurfacesRight: std::ptr::null_mut(),- pInputSurfaceRight: std::mem::ManuallyDrop::new(None),- ppFutureSurfacesRight: std::ptr::null_mut(),- }];- let result = unsafe {- self.video_context- .VideoProcessorBlt(&self.processor, out_view, 0, &streams)- };- unsafe {- std::mem::ManuallyDrop::drop(&mut streams[0].pInputSurface);- std::mem::ManuallyDrop::drop(&mut streams[0].pInputSurfaceRight);- }- result.map_err(|e| hr("VideoProcessorBlt", e))?;- Ok(out_tex.clone())- }-- /// CPU copy of the last converted frame. Only the raw publish path (and the- /// system-memory Media Foundation fallback) needs this; the D3D-aware- /// encoder consumes the texture directly.- pub fn read_back(&mut self, nv12: &ID3D11Texture2D) -> Result<Nv12Cpu, StreamError> {- if self.staging.is_none() {- self.staging = Some(self.gpu.texture(- self.dst_width,- self.dst_height,- DXGI_FORMAT_NV12,- true,- None,- 0,- )?);- }- let staging = self- .staging- .as_ref()- .ok_or_else(|| StreamError::Capture("no staging texture".into()))?;- let ctx = self.gpu.context();- unsafe { ctx.CopyResource(staging, nv12) };- let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();- unsafe {- ctx.Map(staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))- .map_err(|e| hr("Map(NV12 staging)", e))?;- }- let stride = mapped.RowPitch;- let rows = self.dst_height as usize + self.dst_height as usize / 2;- let len = stride as usize * rows;- let mut data = vec![0u8; len];- // WHY: D3D11 maps NV12 as one allocation — the UV plane starts exactly- // `RowPitch * Height` bytes in and shares the Y row pitch. There is no- // per-plane pitch to query for a mapped NV12 staging resource.- unsafe {- std::ptr::copy_nonoverlapping(mapped.pData as *const u8, data.as_mut_ptr(), len);- ctx.Unmap(staging, 0);- }- Ok(Nv12Cpu {- data,- stride_y: stride,- stride_uv: stride,- width: self.dst_width,- height: self.dst_height,- })- }-}diff --git a/src-tauri/omnidisc-media/src/capture/windows/mod.rs b/src-tauri/omnidisc-media/src/capture/windows/mod.rsdeleted file mode 100644index 831e3ab8..00000000--- a/src-tauri/omnidisc-media/src/capture/windows/mod.rs+++ /dev/null@@ -1,291 +0,0 @@-mod audio;-pub mod d3d;-mod sources;-mod wgc;--pub use audio::{process_loopback_supported, windows_build, MIN_LOOPBACK_BUILD};-pub use d3d::{gpu, Gpu, Nv12Converter, Nv12Cpu, PooledTexture};--use super::{- unix_micros, AudioSink, CaptureApi, CaptureGeometry, CaptureOptions, VideoSink, VideoTick,-};-use crate::stream::{AudioMode, SourceId, StreamError, StreamSources};-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Arc;-use std::time::{Duration, Instant};-use windows::Graphics::Capture::GraphicsCaptureSession;-use windows::Win32::Graphics::Direct3D11::ID3D11Texture2D;--/// One captured screen frame. The pixels stay on the GPU: `texture` is a BGRA-/// `ID3D11Texture2D` owned by the capture pool and recycled when the frame is-/// dropped, so nothing is read back to system memory unless the encoder asks.-pub struct CapturedFrame {- texture: PooledTexture,- 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 texture(&self) -> Option<&ID3D11Texture2D> {- self.texture.texture()- }-}--struct SyntheticSource {- stop: Arc<AtomicBool>,- thread: Option<std::thread::JoinHandle<()>>,-}--impl Drop for SyntheticSource {- fn drop(&mut self) {- self.stop.store(true, Ordering::Release);- if let Some(t) = self.thread.take() {- let _ = t.join();- }- }-}--pub struct VideoCapture {- _wgc: Option<wgc::Capture>,- _synthetic: Option<SyntheticSource>,-}--impl VideoCapture {- pub fn stop(self) {}-}--pub struct AudioCapture {- inner: Option<audio::AudioCaptureHandle>,-}--impl AudioCapture {- pub fn stop(self) {- if let Some(h) = self.inner {- h.stop();- }- }-}--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 gpu = gpu()?;- let pool = d3d::TexturePool::new(gpu.clone(), width, height, 4);- 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 row = width as usize * 4;- let mut pixels = vec![0u8; row * height as usize];- let mut next = Instant::now();- let mut n: u64 = 0;- while !stop2.load(Ordering::Acquire) {- let shift = (n % 256) as usize;- for y in 0..height as usize {- let base = y * row;- let v = ((y / 4 + shift) % 256) as u8;- for x in 0..width as usize {- let p = base + x * 4;- pixels[p] = v;- pixels[p + 1] = ((x + shift) % 256) as u8;- pixels[p + 2] = v.wrapping_add(64);- pixels[p + 3] = 255;- }- }- match pool.acquire() {- Ok(slot) => {- if let Some(tex) = slot.texture() {- unsafe {- gpu.context().UpdateSubresource(- tex,- 0,- None,- pixels.as_ptr().cast(),- row as u32,- 0,- );- }- sink(VideoTick::Frame(CapturedFrame {- texture: slot,- width,- height,- capture_us: unix_micros(),- }));- }- }- Err(e) => tracing::debug!("[omnidisc-media] synthetic frame: {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 {- _wgc: None,- _synthetic: Some(SyntheticSource {- stop,- thread: Some(thread),- }),- },- CaptureGeometry { width, height, fps },- ))-}--fn wgc_available() -> Result<(), StreamError> {- match GraphicsCaptureSession::IsSupported() {- Ok(true) => Ok(()),- _ => Err(StreamError::Capture(- "Windows.Graphics.Capture is unavailable; screen sharing needs Windows 10 version 1903 or newer".into(),- )),- }-}--pub struct Platform;--impl CaptureApi for Platform {- fn list_sources(thumbnails: bool) -> Result<StreamSources, StreamError> {- audio::ensure_mta();- sources::trace("com guard ready");- wgc_available()?;- sources::trace("wgc available");- let displays = sources::display_sources(thumbnails);- sources::trace("displays done");- if displays.is_empty() {- return Err(StreamError::Capture(- "no displays were reported by Windows".into(),- ));- }- let windows = sources::window_sources(thumbnails);- sources::trace("windows done");- let loopback = audio::process_loopback_supported();- sources::trace("loopback probe done");- let apps = if loopback {- audio::audio_apps()- } else {- Vec::new()- };- Ok(StreamSources {- displays,- windows,- apps,- app_audio_supported: loopback,- system_audio_supported: loopback,- })- }-- fn thumbnail_for(source: &SourceId) -> Option<String> {- audio::ensure_mta();- match source {- SourceId::Display { id } => sources::monitor_from_id(*id)- .ok()- .and_then(|m| sources::monitor_thumbnail(&m)),- SourceId::Window { id } => sources::windows_list()- .into_iter()- .find(|w| sources::window_id(w.handle) == *id)- .and_then(|w| sources::window_thumbnail(&w)),- SourceId::Synthetic { .. } => None,- }- }-- 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);- }- // `GraphicsCaptureSession::IsSupported` is a WinRT static call, so the- // caller's thread needs an apartment even though the session itself- // runs on our own.- audio::ensure_mta();- wgc_available()?;- let gpu = gpu()?;- let target = match opts.source {- SourceId::Display { id } => wgc::Target::Monitor(sources::monitor_from_id(id)?.handle),- SourceId::Window { id } => {- wgc::Target::Window(sources::window_from_id(id).ok_or(StreamError::SourceGone)?)- }- SourceId::Synthetic { .. } => return Err(StreamError::Unsupported),- };- let (capture, geometry) =- wgc::start(gpu, target, sink, opts.cursor, opts.fps, opts.height)?;- Ok((- VideoCapture {- _wgc: Some(capture),- _synthetic: None,- },- geometry,- ))- }-- fn start_audio(- mode: AudioMode,- sink: AudioSink,- ) -> Result<(AudioCapture, AudioMode), StreamError> {- if mode == AudioMode::None {- return Ok((AudioCapture { inner: None }, AudioMode::None));- }- if !audio::process_loopback_supported() {- return Err(audio::unsupported_build_error());- }- let own_pid = std::process::id();- let mut attempt = mode;- loop {- let started = match attempt {- AudioMode::App { pid } if pid > 0 => {- audio::start_process_loopback(pid as u32, true, sink.clone())- }- AudioMode::App { pid } => Err(StreamError::Capture(format!(- "invalid audio source pid {pid}"- ))),- // "System except us": exclude our own process tree so the share- // never echoes OmniGet's own output back into the room.- AudioMode::System => audio::start_process_loopback(own_pid, false, sink.clone()),- AudioMode::None => return Ok((AudioCapture { inner: None }, AudioMode::None)),- };- match started {- Ok(handle) => {- return Ok((- AudioCapture {- inner: Some(handle),- },- attempt,- ))- }- Err(e) => {- tracing::warn!("[omnidisc-media] audio capture {attempt:?} failed: {e}");- attempt = match attempt {- AudioMode::App { .. } => AudioMode::System,- _ => return Ok((AudioCapture { inner: None }, AudioMode::None)),- };- }- }- }- }-}diff --git a/src-tauri/omnidisc-media/src/capture/windows/sources.rs b/src-tauri/omnidisc-media/src/capture/windows/sources.rsdeleted file mode 100644index f2e8c821..00000000--- a/src-tauri/omnidisc-media/src/capture/windows/sources.rs+++ /dev/null@@ -1,524 +0,0 @@-use crate::stream::{AudioApp, SourceId, StreamError, StreamSource};-use base64::Engine;-use std::ffi::c_void;-use windows::core::BOOL;-use windows::core::PWSTR;-use windows::Win32::Foundation::{FALSE, HWND, LPARAM, RECT, TRUE};-use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_CLOAKED};-use windows::Win32::Graphics::Gdi::{- CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, EnumDisplayMonitors, GetDC,- GetMonitorInfoW, ReleaseDC, SelectObject, SetStretchBltMode, StretchBlt, BITMAPINFO,- BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HALFTONE, HDC, HGDIOBJ, HMONITOR, MONITORINFO,- MONITORINFOEXW, SRCCOPY,-};-use windows::Win32::Storage::Xps::{PrintWindow, PRINT_WINDOW_FLAGS};-use windows::Win32::System::Threading::{- OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION,-};-use windows::Win32::UI::WindowsAndMessaging::{- EnumWindows, GetAncestor, GetWindowLongW, GetWindowRect, GetWindowTextLengthW, GetWindowTextW,- GetWindowThreadProcessId, IsIconic, IsWindow, IsWindowVisible, GA_ROOT, GWL_EXSTYLE, GWL_STYLE,- MONITORINFOF_PRIMARY, WS_CHILD, WS_EX_TOOLWINDOW,-};--const THUMB_WIDTH: u32 = 320;--/// Opt-in tracing for the thumbnail path. Enumeration runs inside GDI and DWM-/// calls that can fault on a window the compositor is tearing down, and the-/// only way to see which source did it — here or on a user's machine — is to-/// have the step on the wire before the call.-/// Same gate as [`trace_step!`], callable from the sibling modules.-pub fn trace(msg: &str) {- if std::env::var_os("OMNIDISC_CAPTURE_TRACE").is_some() {- println!("[capture-trace] {msg}");- std::io::Write::flush(&mut std::io::stdout()).ok();- }-}--macro_rules! trace_step {- ($($arg:tt)*) => {- if std::env::var_os("OMNIDISC_CAPTURE_TRACE").is_some() {- println!("[capture-trace] {}", format!($($arg)*));- std::io::Write::flush(&mut std::io::stdout()).ok();- }- };-}--const PW_RENDERFULLCONTENT: PRINT_WINDOW_FLAGS = PRINT_WINDOW_FLAGS(2);-const MIN_WINDOW_EDGE: i32 = 64;--pub struct Monitor {- pub handle: HMONITOR,- pub rect: RECT,- pub primary: bool,-}--// SAFETY: HMONITOR is a plain handle; it is only used to build a capture item.-unsafe impl Send for Monitor {}--unsafe extern "system" fn monitor_proc(- monitor: HMONITOR,- _hdc: HDC,- _rect: *mut RECT,- data: LPARAM,-) -> BOOL {- let list = unsafe { &mut *(data.0 as *mut Vec<Monitor>) };- let mut info = MONITORINFOEXW {- monitorInfo: MONITORINFO {- cbSize: std::mem::size_of::<MONITORINFOEXW>() as u32,- ..Default::default()- },- ..Default::default()- };- let ok = unsafe {- GetMonitorInfoW(- monitor,- &mut info as *mut MONITORINFOEXW as *mut MONITORINFO,- )- };- if ok.as_bool() {- list.push(Monitor {- handle: monitor,- rect: info.monitorInfo.rcMonitor,- primary: info.monitorInfo.dwFlags & MONITORINFOF_PRIMARY != 0,- });- }- TRUE-}--pub fn monitors() -> Vec<Monitor> {- let mut list: Vec<Monitor> = Vec::new();- unsafe {- let _ = EnumDisplayMonitors(- None,- None,- Some(monitor_proc),- LPARAM(&mut list as *mut Vec<Monitor> as isize),- );- }- list-}--pub struct Window {- pub handle: HWND,- pub title: String,- pub app: Option<String>,- pub width: u32,- pub height: u32,-}--// SAFETY: HWND is a plain handle; used only to build a capture item.-unsafe impl Send for Window {}--fn window_text(hwnd: HWND) -> String {- let len = unsafe { GetWindowTextLengthW(hwnd) };- if len <= 0 {- return String::new();- }- let mut buf = vec![0u16; len as usize + 1];- let written = unsafe { GetWindowTextW(hwnd, &mut buf) };- if written <= 0 {- return String::new();- }- String::from_utf16_lossy(&buf[..written as usize])-}--fn is_cloaked(hwnd: HWND) -> bool {- let mut cloaked: u32 = 0;- let ok = unsafe {- DwmGetWindowAttribute(- hwnd,- DWMWA_CLOAKED,- &mut cloaked as *mut u32 as *mut c_void,- std::mem::size_of::<u32>() as u32,- )- };- ok.is_ok() && cloaked != 0-}--pub fn process_path(pid: u32) -> Option<String> {- let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }.ok()?;- let mut buf = vec![0u16; 512];- let mut len = buf.len() as u32;- let ok = unsafe {- QueryFullProcessImageNameW(- handle,- PROCESS_NAME_FORMAT(0),- PWSTR(buf.as_mut_ptr()),- &mut len,- )- };- let _ = unsafe { windows::Win32::Foundation::CloseHandle(handle) };- if ok.is_err() || len == 0 {- return None;- }- Some(String::from_utf16_lossy(&buf[..len as usize]))-}--pub fn process_name(pid: u32) -> Option<String> {- let path = process_path(pid)?;- let stem = path- .rsplit(['\\', '/'])- .next()- .unwrap_or(&path)- .trim_end_matches(".exe")- .trim_end_matches(".EXE")- .to_string();- if stem.is_empty() {- None- } else {- Some(stem)- }-}--unsafe extern "system" fn window_proc(hwnd: HWND, data: LPARAM) -> BOOL {- let ctx = unsafe { &mut *(data.0 as *mut (Vec<Window>, u32)) };- let (list, own_pid) = (&mut ctx.0, ctx.1);- if list.len() >= 128 {- return FALSE;- }- if !unsafe { IsWindowVisible(hwnd) }.as_bool() || unsafe { IsIconic(hwnd) }.as_bool() {- return TRUE;- }- if unsafe { GetAncestor(hwnd, GA_ROOT) } != hwnd {- return TRUE;- }- let style = unsafe { GetWindowLongW(hwnd, GWL_STYLE) } as u32;- if style & WS_CHILD.0 != 0 {- return TRUE;- }- let ex_style = unsafe { GetWindowLongW(hwnd, GWL_EXSTYLE) } as u32;- if ex_style & WS_EX_TOOLWINDOW.0 != 0 {- return TRUE;- }- if is_cloaked(hwnd) {- return TRUE;- }- let mut pid: u32 = 0;- unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) };- if pid == 0 || pid == own_pid {- return TRUE;- }- let mut rect = RECT::default();- if unsafe { GetWindowRect(hwnd, &mut rect) }.is_err() {- return TRUE;- }- let w = rect.right - rect.left;- let h = rect.bottom - rect.top;- if w < MIN_WINDOW_EDGE || h < MIN_WINDOW_EDGE {- return TRUE;- }- let title = window_text(hwnd);- let app = process_name(pid);- if title.trim().is_empty() && app.is_none() {- return TRUE;- }- list.push(Window {- handle: hwnd,- title,- app,- width: w as u32,- height: h as u32,- });- TRUE-}--pub fn windows_list() -> Vec<Window> {- let mut ctx: (Vec<Window>, u32) = (Vec::new(), std::process::id());- unsafe {- let _ = EnumWindows(- Some(window_proc),- LPARAM(&mut ctx as *mut (Vec<Window>, u32) as isize),- );- }- ctx.0-}--struct Dib {- dc: HDC,- bitmap: windows::Win32::Graphics::Gdi::HBITMAP,- old: HGDIOBJ,- bits: *mut c_void,- width: i32,- height: i32,-}--impl Dib {- fn new(reference: HDC, width: i32, height: i32) -> Option<Self> {- if width <= 0 || height <= 0 {- return None;- }- let dc = unsafe { CreateCompatibleDC(Some(reference)) };- if dc.is_invalid() {- return None;- }- let info = BITMAPINFO {- bmiHeader: BITMAPINFOHEADER {- biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,- biWidth: width,- // Negative height gives a top-down DIB, which matches the row- // order the JPEG encoder expects.- biHeight: -height,- biPlanes: 1,- biBitCount: 32,- biCompression: BI_RGB.0,- ..Default::default()- },- ..Default::default()- };- let mut bits: *mut c_void = std::ptr::null_mut();- let bitmap =- unsafe { CreateDIBSection(Some(dc), &info, DIB_RGB_COLORS, &mut bits, None, 0) };- let bitmap = match bitmap {- Ok(b) if !bits.is_null() => b,- _ => {- unsafe {- let _ = DeleteDC(dc);- };- return None;- }- };- let old = unsafe { SelectObject(dc, bitmap.into()) };- Some(Self {- dc,- bitmap,- old,- bits,- width,- height,- })- }-- fn to_jpeg_data_url(&self) -> Option<String> {- let pixels = self.width as usize * self.height as usize * 4;- let bgra = unsafe { std::slice::from_raw_parts(self.bits as *const u8, pixels) };- let mut rgb = Vec::with_capacity(self.width as usize * self.height as usize * 3);- for px in bgra.chunks_exact(4) {- rgb.push(px[2]);- rgb.push(px[1]);- rgb.push(px[0]);- }- let mut jpeg = Vec::new();- let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 60);- enc.encode(- &rgb,- self.width as u32,- self.height as u32,- image::ExtendedColorType::Rgb8,- )- .ok()?;- Some(format!(- "data:image/jpeg;base64,{}",- base64::engine::general_purpose::STANDARD.encode(jpeg)- ))- }-}--impl Drop for Dib {- fn drop(&mut self) {- unsafe {- SelectObject(self.dc, self.old);- let _ = DeleteObject(self.bitmap.into());- let _ = DeleteDC(self.dc);- }- }-}--fn thumb_size(width: u32, height: u32) -> (i32, i32) {- let w = THUMB_WIDTH.min(width.max(1));- let h = ((height as u64 * w as u64) / width.max(1) as u64).clamp(1, THUMB_WIDTH as u64) as u32;- (w as i32, h as i32)-}--pub fn monitor_thumbnail(m: &Monitor) -> Option<String> {- let w = m.rect.right - m.rect.left;- let h = m.rect.bottom - m.rect.top;- trace_step!("monitor_thumbnail {}x{}", w, h);- if w <= 0 || h <= 0 {- return None;- }- let screen = unsafe { GetDC(None) };- if screen.is_invalid() {- return None;- }- let (tw, th) = thumb_size(w as u32, h as u32);- let out = (|| {- let dib = Dib::new(screen, tw, th)?;- unsafe {- SetStretchBltMode(dib.dc, HALFTONE);- StretchBlt(- dib.dc,- 0,- 0,- tw,- th,- Some(screen),- m.rect.left,- m.rect.top,- w,- h,- SRCCOPY,- )- .ok()- .ok()?;- }- trace_step!("blt ok, encoding");- dib.to_jpeg_data_url()- })();- unsafe { ReleaseDC(None, screen) };- out-}--pub fn window_thumbnail(win: &Window) -> Option<String> {- trace_step!(- "window_thumbnail hwnd={:?} {}x{} title={:.40}",- win.handle.0,- win.width,- win.height,- win.title- );- let screen = unsafe { GetDC(None) };- if screen.is_invalid() {- return None;- }- let (tw, th) = thumb_size(win.width, win.height);- let out = (|| {- let full = Dib::new(screen, win.width as i32, win.height as i32)?;- trace_step!("full dib ok, printing window");- let printed = unsafe { PrintWindow(win.handle, full.dc, PW_RENDERFULLCONTENT) }.as_bool();- trace_step!("printed={printed}");- if !printed {- return None;- }- let thumb = Dib::new(screen, tw, th)?;- unsafe {- SetStretchBltMode(thumb.dc, HALFTONE);- StretchBlt(- thumb.dc,- 0,- 0,- tw,- th,- Some(full.dc),- 0,- 0,- win.width as i32,- win.height as i32,- SRCCOPY,- )- .ok()- .ok()?;- }- trace_step!("blt ok, encoding");- thumb.to_jpeg_data_url()- })();- unsafe { ReleaseDC(None, screen) };- out-}--/// HWNDs are 32-bit significant by contract (USER handles are sign-extended on-/// 64-bit Windows), so the frontend's `u32` source id round-trips exactly.-pub fn window_id(hwnd: HWND) -> u32 {- hwnd.0 as usize as u32-}--pub fn window_from_id(id: u32) -> Option<HWND> {- // Rebuild the handle rather than re-enumerating: a window that was- // minimised or lost its title between the picker and the start of the share- // is still a valid capture target.- let hwnd = HWND(id as usize as *mut c_void);- if unsafe { IsWindow(Some(hwnd)) }.as_bool() {- Some(hwnd)- } else {- None- }-}--pub fn display_sources(thumbnails: bool) -> Vec<StreamSource> {- trace_step!("display_sources thumbnails={thumbnails}");- let found = monitors();- trace_step!("monitors enumerated: {}", found.len());- found- .iter()- .enumerate()- .map(|(i, m)| {- let w = (m.rect.right - m.rect.left).max(0) as u32;- let h = (m.rect.bottom - m.rect.top).max(0) as u32;- StreamSource {- id: SourceId::Display { id: i as u32 + 1 },- title: if m.primary {- format!("Display {} ({w}×{h}, primary)", i + 1)- } else {- format!("Display {} ({w}×{h})", i + 1)- },- app_name: None,- width: w,- height: h,- thumbnail: if thumbnails {- monitor_thumbnail(m)- } else {- None- },- }- })- .collect()-}--pub fn window_sources(thumbnails: bool) -> Vec<StreamSource> {- trace_step!("window_sources thumbnails={thumbnails}");- let mut out = Vec::new();- let listed = windows_list();- trace_step!("windows enumerated: {}", listed.len());- for (i, w) in listed.into_iter().enumerate() {- let title = if w.title.trim().is_empty() {- w.app.clone().unwrap_or_default()- } else {- w.title.clone()- };- out.push(StreamSource {- id: SourceId::Window {- id: window_id(w.handle),- },- title,- app_name: w.app.clone(),- width: w.width,- height: w.height,- thumbnail: if thumbnails && i < 16 {- window_thumbnail(&w)- } else {- None- },- });- if out.len() >= 40 {- break;- }- }- out-}--pub fn monitor_from_id(id: u32) -> Result<Monitor, StreamError> {- let mut list = monitors();- if id == 0 || id as usize > list.len() {- return Err(StreamError::SourceGone);- }- Ok(list.remove(id as usize - 1))-}--pub fn audio_app(pid: u32) -> Option<AudioApp> {- let path = process_path(pid)?;- let name = path- .rsplit(['\\', '/'])- .next()- .unwrap_or(&path)- .trim_end_matches(".exe")- .trim_end_matches(".EXE")- .to_string();- if name.is_empty() {- return None;- }- Some(AudioApp {- pid: pid as i32,- name,- bundle_id: path,- })-}diff --git a/src-tauri/omnidisc-media/src/capture/windows/wgc.rs b/src-tauri/omnidisc-media/src/capture/windows/wgc.rsdeleted file mode 100644index d14d3339..00000000--- a/src-tauri/omnidisc-media/src/capture/windows/wgc.rs+++ /dev/null@@ -1,319 +0,0 @@-use super::d3d::{Gpu, TexturePool};-use super::CapturedFrame;-use crate::capture::{unix_micros, CaptureGeometry, VideoSink, VideoTick};-use crate::stream::{resolve_geometry, StreamError};-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};-use std::sync::{mpsc, Arc};-use std::time::{Duration, Instant};-use windows::core::{Interface, Ref};-use windows::Foundation::TypedEventHandler;-use windows::Graphics::Capture::{- Direct3D11CaptureFramePool, GraphicsCaptureItem, GraphicsCaptureSession,-};-use windows::Graphics::DirectX::Direct3D11::IDirect3DDevice;-use windows::Graphics::DirectX::DirectXPixelFormat;-use windows::Graphics::SizeInt32;-use windows::Win32::Foundation::HWND;-use windows::Win32::Graphics::Direct3D11::{ID3D11Texture2D, D3D11_BOX};-use windows::Win32::Graphics::Dxgi::IDXGIDevice;-use windows::Win32::Graphics::Gdi::HMONITOR;-use windows::Win32::System::WinRT::Direct3D11::{- CreateDirect3D11DeviceFromDXGIDevice, IDirect3DDxgiInterfaceAccess,-};-use windows::Win32::System::WinRT::Graphics::Capture::IGraphicsCaptureItemInterop;--const POOL_BUFFERS: i32 = 2;-const POOL_BUDGET: usize = 4;--pub enum Target {- Monitor(HMONITOR),- Window(HWND),-}--// SAFETY: HMONITOR and HWND are opaque handle values, not thread-affine-// pointers; they are only passed to the capture-item interop factory.-unsafe impl Send for Target {}--/// `IDirect3DDevice` is agile (WinRT free-threaded marshalling), so it may be-/// used from the frame-pool callback thread that WGC picks.-struct SendDevice(IDirect3DDevice);-unsafe impl Send for SendDevice {}--impl SendDevice {- // A method, not a field read: edition-2021 closures capture disjoint- // fields, and capturing the bare `IDirect3DDevice` would make the handler- // closure `!Send`.- fn get(&self) -> &IDirect3DDevice {- &self.0- }-}--fn cap_err(what: &str, e: windows::core::Error) -> StreamError {- StreamError::Capture(format!("{what}: {e}"))-}--pub fn direct3d_device(gpu: &Gpu) -> Result<IDirect3DDevice, StreamError> {- let dxgi: IDXGIDevice = gpu.device().cast().map_err(|e| cap_err("IDXGIDevice", e))?;- let inspectable = unsafe {- CreateDirect3D11DeviceFromDXGIDevice(&dxgi)- .map_err(|e| cap_err("CreateDirect3D11DeviceFromDXGIDevice", e))?- };- inspectable- .cast()- .map_err(|e| cap_err("IDirect3DDevice", e))-}--pub fn capture_item(target: &Target) -> Result<GraphicsCaptureItem, StreamError> {- let interop = windows::core::factory::<GraphicsCaptureItem, IGraphicsCaptureItemInterop>()- .map_err(|e| cap_err("IGraphicsCaptureItemInterop", e))?;- let item = unsafe {- match target {- Target::Monitor(m) => interop.CreateForMonitor::<GraphicsCaptureItem>(*m),- Target::Window(w) => interop.CreateForWindow::<GraphicsCaptureItem>(*w),- }- };- item.map_err(|e| {- // WGC refuses items the user is not allowed to capture, and refuses- // everything when the machine is below Windows 10 1903.- if e.code().0 == windows::Win32::Foundation::E_INVALIDARG.0 {- StreamError::SourceGone- } else {- cap_err("GraphicsCaptureItem", e)- }- })-}--struct Session {- session: GraphicsCaptureSession,- pool: Direct3D11CaptureFramePool,-}--// SAFETY: WGC objects are agile (free-threaded marshalled); the session is-// created and closed on the capture thread and never touched concurrently.-unsafe impl Send for Session {}--pub struct Capture {- stop: Arc<AtomicBool>,- thread: Option<std::thread::JoinHandle<()>>,-}--impl Capture {- fn shutdown(&mut self) {- self.stop.store(true, Ordering::Release);- if let Some(t) = self.thread.take() {- let _ = t.join();- }- }-}--impl Drop for Capture {- fn drop(&mut self) {- self.shutdown();- }-}--#[allow(clippy::too_many_arguments)]-fn build(- gpu: &Arc<Gpu>,- item: &GraphicsCaptureItem,- pool: TexturePool,- sink: VideoSink,- cursor: bool,- fps: u16,- last_frame_us: Arc<AtomicU64>,-) -> Result<Session, StreamError> {- let device = direct3d_device(gpu)?;- let size = item.Size().map_err(|e| cap_err("item size", e))?;- let frame_pool = Direct3D11CaptureFramePool::CreateFreeThreaded(- &device,- DirectXPixelFormat::B8G8R8A8UIntNormalized,- POOL_BUFFERS,- size,- )- .map_err(|e| cap_err("Direct3D11CaptureFramePool", e))?;-- let gpu_cb = gpu.clone();- let min_interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);- let mut last_emit: Option<Instant> = None;- let mut pool_size = size;- let device_cb = SendDevice(device.clone());- let handler = TypedEventHandler::<Direct3D11CaptureFramePool, windows::core::IInspectable>::new(- move |sender: Ref<'_, Direct3D11CaptureFramePool>, _| {- let Ok(sender) = sender.ok() else {- return Ok(());- };- let Ok(frame) = sender.TryGetNextFrame() else {- return Ok(());- };- if let Ok(content) = frame.ContentSize() {- if content.Width != pool_size.Width || content.Height != pool_size.Height {- // WHY: WGC stops delivering frames after the item resizes- // unless the pool is recreated at the new size. Our own- // textures stay at the size the encoder was configured for;- // the copy below clamps to the smaller of the two.- let _ = sender.Recreate(- device_cb.get(),- DirectXPixelFormat::B8G8R8A8UIntNormalized,- POOL_BUFFERS,- content,- );- pool_size = content;- }- }- let now = Instant::now();- if let Some(prev) = last_emit {- if now.duration_since(prev) + Duration::from_micros(500) < min_interval {- return Ok(());- }- }- let Ok(surface) = frame.Surface() else {- return Ok(());- };- let Ok(access) = surface.cast::<IDirect3DDxgiInterfaceAccess>() else {- return Ok(());- };- let source: ID3D11Texture2D = match unsafe { access.GetInterface() } {- Ok(t) => t,- Err(_) => return Ok(()),- };- let slot = match pool.acquire() {- Ok(s) => s,- Err(e) => {- tracing::debug!("[omnidisc-media] wgc: {e}");- return Ok(());- }- };- let Some(dst) = slot.texture() else {- return Ok(());- };- let (pw, ph) = pool.size();- let src_w = pool_size.Width.max(0) as u32;- let src_h = pool_size.Height.max(0) as u32;- let box_ = D3D11_BOX {- left: 0,- top: 0,- front: 0,- right: pw.min(src_w),- bottom: ph.min(src_h),- back: 1,- };- if box_.right == 0 || box_.bottom == 0 {- return Ok(());- }- unsafe {- gpu_cb- .context()- .CopySubresourceRegion(dst, 0, 0, 0, 0, &source, 0, Some(&box_));- }- last_emit = Some(now);- let capture_us = unix_micros();- last_frame_us.store(capture_us as u64, Ordering::Relaxed);- sink(VideoTick::Frame(CapturedFrame {- texture: slot,- width: pw,- height: ph,- capture_us,- }));- Ok(())- },- );- frame_pool- .FrameArrived(&handler)- .map_err(|e| cap_err("FrameArrived", e))?;-- let session = frame_pool- .CreateCaptureSession(item)- .map_err(|e| cap_err("CreateCaptureSession", e))?;- if let Err(e) = session.SetIsCursorCaptureEnabled(cursor) {- tracing::debug!("[omnidisc-media] SetIsCursorCaptureEnabled unavailable: {e}");- }- // Windows 11 only; on Windows 10 the yellow border cannot be removed.- if let Err(e) = session.SetIsBorderRequired(false) {- tracing::debug!("[omnidisc-media] SetIsBorderRequired unavailable: {e}");- }- session- .StartCapture()- .map_err(|e| cap_err("StartCapture", e))?;- Ok(Session {- session,- pool: frame_pool,- })-}--/// Starts a WGC capture on a dedicated MTA thread. The thread also emits-/// `VideoTick::Idle` whenever a frame interval passes without a new frame — WGC-/// is dirty-driven like ScreenCaptureKit, so a still screen delivers nothing.-pub fn start(- gpu: Arc<Gpu>,- target: Target,- sink: VideoSink,- cursor: bool,- fps: u16,- requested_height: Option<u16>,-) -> Result<(Capture, CaptureGeometry), StreamError> {- let stop = Arc::new(AtomicBool::new(false));- let stop_thread = stop.clone();- let (tx, rx) = mpsc::channel::<Result<CaptureGeometry, StreamError>>();- let thread = std::thread::Builder::new()- .name("omnidisc-wgc".into())- .spawn(move || {- super::audio::ensure_mta();- let last_frame_us = Arc::new(AtomicU64::new(0));- let started = capture_item(&target).and_then(|item| {- let size: SizeInt32 = item.Size().map_err(|e| cap_err("item size", e))?;- let (native_w, native_h) = (size.Width.max(2) as u32, size.Height.max(2) as u32);- let (width, height) = resolve_geometry(native_w, native_h, requested_height);- let pool = TexturePool::new(gpu.clone(), native_w, native_h, POOL_BUDGET);- let session = build(- &gpu,- &item,- pool,- sink.clone(),- cursor,- fps,- last_frame_us.clone(),- )?;- Ok((session, CaptureGeometry { width, height, fps }))- });- let session = match started {- Ok((session, geometry)) => {- let _ = tx.send(Ok(geometry));- session- }- Err(e) => {- let _ = tx.send(Err(e));- return;- }- };- let interval = Duration::from_nanos(1_000_000_000u64 / fps.max(1) as u64);- while !stop_thread.load(Ordering::Acquire) {- std::thread::sleep(interval);- let last = last_frame_us.load(Ordering::Relaxed) as i64;- if unix_micros() - last > interval.as_micros() as i64 {- sink(VideoTick::Idle);- }- }- let _ = session.session.Close();- let _ = session.pool.Close();- })- .map_err(|e| StreamError::Capture(format!("wgc thread: {e}")))?;- match rx.recv() {- Ok(Ok(geometry)) => Ok((- Capture {- stop,- thread: Some(thread),- },- geometry,- )),- Ok(Err(e)) => {- let _ = thread.join();- Err(e)- }- Err(_) => {- let _ = thread.join();- Err(StreamError::Capture(- "the screen capture thread stopped before it started".into(),- ))- }- }-}diff --git a/src-tauri/omnidisc-media/src/e2ee.rs b/src-tauri/omnidisc-media/src/e2ee.rsdeleted file mode 100644index f9a802f5..00000000--- a/src-tauri/omnidisc-media/src/e2ee.rs+++ /dev/null@@ -1,189 +0,0 @@-//! 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/linux.rs b/src-tauri/omnidisc-media/src/encode/linux.rsdeleted file mode 100644index 3de50f1c..00000000--- a/src-tauri/omnidisc-media/src/encode/linux.rs+++ /dev/null@@ -1,163 +0,0 @@-//! Linux publish path: hand raw I420 to libwebrtc and let it encode.-//!-//! Unlike macOS and Windows there is no encoder of our own here. The vendored-//! libwebrtc already ships VAAPI and NVENC backends, and asking for one by name-//! at publish time is both less code and less to go wrong than a hand-written-//! encoder. What this module owns is the colour conversion the GPU path on the-//! other platforms gets for free.--use super::{EncoderConfig, EncoderCounters, PublishPath};-use crate::capture::CapturedFrame;-use crate::stream::{StreamCodec, StreamError};-use livekit::webrtc::prelude::VideoBuffer;-use livekit::webrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};-use livekit::webrtc::video_source::native::NativeVideoSource;-use std::sync::atomic::Ordering;-use std::sync::{Arc, Mutex};-use std::time::Instant;-use yuv::{- bgra_to_yuv420, BufferStoreMut, YuvConversionMode, YuvPlanarImageMut, YuvRange,- YuvStandardMatrix,-};--/// H.265 has no reliable software fallback across Linux desktops, and the-/// hardware path is not guaranteed either. Screen sharing stays on H.264.-pub fn clamp_codec(_codec: StreamCodec) -> StreamCodec {- StreamCodec::H264-}--pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {- PublishPath::Raw-}--pub struct VideoEncoder {- cfg: EncoderConfig,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- buffer: Mutex<Option<I420Buffer>>,-}--impl VideoEncoder {- pub fn new(- cfg: EncoderConfig,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- ) -> Result<Self, StreamError> {- Ok(Self {- cfg,- source,- counters,- buffer: Mutex::new(None),- })- }-- pub fn encode(&self, frame: &CapturedFrame, _force_key: bool) -> Result<(), StreamError> {- let started = Instant::now();- self.counters.submitted.fetch_add(1, Ordering::Relaxed);- let (w, h) = (frame.width, frame.height);- if w == 0 || h == 0 {- return Ok(());- }- let mut slot = self- .buffer- .lock()- .map_err(|_| StreamError::Encoder("frame buffer poisoned".into()))?;- let reusable = slot- .as_ref()- .map(|b| b.width() == w && b.height() == h)- .unwrap_or(false);- // The buffer is moved into the frame and moved back after the capture,- // so a 1080p allocation happens once instead of thirty times a second.- let mut buffer = if reusable {- slot.take()- .ok_or_else(|| StreamError::Encoder("no frame buffer".into()))?- } else {- I420Buffer::new(w, h)- };- let (stride_y, stride_u, stride_v) = buffer.strides();- let (y, u, v) = buffer.data_mut();- let mut planar = YuvPlanarImageMut {- y_plane: BufferStoreMut::Borrowed(y),- y_stride: stride_y,- u_plane: BufferStoreMut::Borrowed(u),- u_stride: stride_u,- v_plane: BufferStoreMut::Borrowed(v),- v_stride: stride_v,- width: w,- height: h,- };- bgra_to_yuv420(- &mut planar,- &frame.data,- frame.stride as u32,- // Screen content is studio-range BT.709: matching what every- // compositor and every decoder assumes keeps greys grey.- YuvRange::Limited,- YuvStandardMatrix::Bt709,- YuvConversionMode::Balanced,- )- .map_err(|e| StreamError::Encoder(format!("bgrx to i420: {e}")))?;-- let out = VideoFrame {- rotation: VideoRotation::VideoRotation0,- timestamp_us: frame.capture_us,- frame_metadata: None,- buffer,- };- self.source.capture_frame(&out);- *slot = Some(out.buffer);- self.counters.encoded.fetch_add(1, Ordering::Relaxed);- self.counters.captured_ok.fetch_add(1, Ordering::Relaxed);- let elapsed = started.elapsed().as_nanos() as u64;- self.counters- .latency_ns_sum- .fetch_add(elapsed, Ordering::Relaxed);- self.counters- .latency_ns_max- .fetch_max(elapsed, Ordering::Relaxed);- Ok(())- }-- /// Rate control belongs to libwebrtc on this path; the publication carries- /// the ceiling and the encoder inside the SDK obeys it.- pub fn set_bitrate(&self, bps: u64) {- self.counters.applied_bps.store(bps, Ordering::Relaxed);- }-- pub fn set_framerate(&self, _fps: u16) {}-- pub fn hardware(&self) -> Option<bool> {- Some(matches!(- preferred_backend(),- livekit::options::VideoEncoderBackend::Vaapi- | livekit::options::VideoEncoderBackend::Nvenc- ))- }-- pub fn name(&self) -> &str {- match preferred_backend() {- livekit::options::VideoEncoderBackend::Vaapi => "vaapi",- livekit::options::VideoEncoderBackend::Nvenc => "nvenc",- _ => "libwebrtc-software",- }- }-- pub fn finish(&self) {- let _ = &self.cfg;- }-}--/// Ask libwebrtc what it actually has rather than assuming a build flag. The-/// answer is also what the inspector reports, so the badge can never claim-/// hardware we did not get.-pub fn preferred_backend() -> livekit::options::VideoEncoderBackend {- use livekit::options::VideoEncoderBackend as B;- let available: Vec<B> = B::list_available().into_iter().collect();- if available.contains(&B::Vaapi) {- B::Vaapi- } else if available.contains(&B::Nvenc) {- B::Nvenc- } else {- B::Software- }-}diff --git a/src-tauri/omnidisc-media/src/encode/mod.rs b/src-tauri/omnidisc-media/src/encode/mod.rsdeleted file mode 100644index 86fce250..00000000--- a/src-tauri/omnidisc-media/src/encode/mod.rs+++ /dev/null@@ -1,71 +0,0 @@-use crate::stream::{StreamCodec, StreamMode};-use std::sync::atomic::{AtomicU64, Ordering};--#[cfg(target_os = "macos")]-mod videotoolbox;-#[cfg(target_os = "macos")]-pub use self::videotoolbox::{clamp_codec, publish_path, VideoEncoder};--#[cfg(windows)]-mod windows;-#[cfg(windows)]-pub use self::windows::{clamp_codec, publish_path, VideoEncoder};--#[cfg(all(target_os = "linux", feature = "linux-capture"))]-mod linux;-#[cfg(all(target_os = "linux", feature = "linux-capture"))]-pub use self::linux::{clamp_codec, preferred_backend, publish_path, VideoEncoder};--#[cfg(not(any(- target_os = "macos",- windows,- all(target_os = "linux", feature = "linux-capture")-)))]-mod stub;-#[cfg(not(any(- target_os = "macos",- windows,- all(target_os = "linux", feature = "linux-capture")-)))]-pub use self::stub::{clamp_codec, publish_path, VideoEncoder};--/// How a platform hands frames to LiveKit: through our own encoder and the-/// `PreEncoded` pass-through, or as raw frames for libwebrtc to encode.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum PublishPath {- PreEncoded,- Raw,-}--#[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.rsdeleted file mode 100644index 8e9663d5..00000000--- a/src-tauri/omnidisc-media/src/encode/stub.rs+++ /dev/null@@ -1,43 +0,0 @@-use super::{EncoderConfig, EncoderCounters, PublishPath};-use crate::capture::CapturedFrame;-use crate::stream::{StreamCodec, StreamError};-use livekit::webrtc::video_source::native::NativeVideoSource;-use std::sync::Arc;--pub fn clamp_codec(codec: StreamCodec) -> StreamCodec {- codec-}--pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {- PublishPath::PreEncoded-}--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) -> &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.rsdeleted file mode 100644index 87f62cfb..00000000--- a/src-tauri/omnidisc-media/src/encode/videotoolbox.rs+++ /dev/null@@ -1,521 +0,0 @@-use super::{EncoderConfig, EncoderCounters, PublishPath};-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;--pub fn clamp_codec(codec: StreamCodec) -> StreamCodec {- codec-}--pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {- PublishPath::PreEncoded-}--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.is_empty() {- 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) -> &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/encode/windows/mf.rs b/src-tauri/omnidisc-media/src/encode/windows/mf.rsdeleted file mode 100644index 8588d36d..00000000--- a/src-tauri/omnidisc-media/src/encode/windows/mf.rs+++ /dev/null@@ -1,815 +0,0 @@-use crate::capture::{gpu, CapturedFrame, Gpu, Nv12Converter};-use crate::encode::{EncoderConfig, EncoderCounters};-use crate::stream::{StreamError, StreamMode};-use livekit::webrtc::video_frame::{EncodedFrameType, EncodedVideoCodec, EncodedVideoFrame};-use livekit::webrtc::video_source::{native::NativeVideoSource, VideoResolution};-use std::collections::VecDeque;-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, Mutex, OnceLock, Weak};-use std::time::Instant;-use windows::core::{implement, Interface, Ref};-use windows::Win32::Foundation::E_NOTIMPL;-use windows::Win32::Graphics::Direct3D11::ID3D11Texture2D;-use windows::Win32::Media::MediaFoundation::{- eAVEncCommonRateControlMode_CBR, eAVEncH264VProfile_High, eAVEncH264VProfile_Main,- CODECAPI_AVEncCommonMeanBitRate, CODECAPI_AVEncCommonRateControlMode, CODECAPI_AVEncMPVGOPSize,- CODECAPI_AVEncVideoForceKeyFrame, CODECAPI_AVLowLatencyMode, ICodecAPI, IMF2DBuffer,- IMFActivate, IMFAsyncCallback, IMFAsyncCallback_Impl, IMFAsyncResult, IMFDXGIDeviceManager,- IMFMediaEventGenerator, IMFMediaType, IMFSample, IMFTransform, METransformHaveOutput,- METransformNeedInput, MFCreateDXGIDeviceManager, MFCreateDXGISurfaceBuffer, MFCreateMediaType,- MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFSampleExtension_CleanPoint,- MFStartup, MFTEnumEx, MFT_FRIENDLY_NAME_Attribute, MFVideoFormat_H264, MFVideoFormat_NV12,- MFVideoInterlace_Progressive, MFSTARTUP_LITE, MFT_CATEGORY_VIDEO_ENCODER,- MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_SORTANDFILTER, MFT_MESSAGE_COMMAND_FLUSH,- MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_END_OF_STREAM,- MFT_MESSAGE_NOTIFY_END_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM,- MFT_MESSAGE_SET_D3D_MANAGER, MFT_OUTPUT_DATA_BUFFER, MFT_REGISTER_TYPE_INFO, MF_LOW_LATENCY,- MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE,- MF_MT_MPEG2_PROFILE, MF_MT_MPEG_SEQUENCE_HEADER, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE,- MF_SA_D3D11_AWARE, MF_TRANSFORM_ASYNC, MF_TRANSFORM_ASYNC_UNLOCK, MF_VERSION,-};-use windows::Win32::System::Com::CoTaskMemFree;-use windows::Win32::System::Variant::{VARIANT, VARIANT_0_0, VT_BOOL, VT_UI4};--const KEYFRAME_INTERVAL: u32 = 240;-const QUEUE_DEPTH: usize = 2;--fn enc_err(what: &str, e: windows::core::Error) -> StreamError {- StreamError::Encoder(format!("{what}: {e}"))-}--fn mf_startup() -> Result<(), StreamError> {- static STARTED: OnceLock<Result<(), String>> = OnceLock::new();- STARTED- .get_or_init(|| unsafe {- MFStartup(MF_VERSION, MFSTARTUP_LITE).map_err(|e| format!("MFStartup: {e}"))- })- .clone()- .map_err(StreamError::Encoder)-}--fn var_u32(value: u32) -> VARIANT {- let mut v = VARIANT::default();- unsafe {- let inner: &mut VARIANT_0_0 = &mut v.Anonymous.Anonymous;- inner.vt = VT_UI4;- inner.Anonymous.ulVal = value;- }- v-}--fn var_bool(value: bool) -> VARIANT {- let mut v = VARIANT::default();- unsafe {- let inner: &mut VARIANT_0_0 = &mut v.Anonymous.Anonymous;- inner.vt = VT_BOOL;- inner.Anonymous.boolVal =- windows::Win32::Foundation::VARIANT_BOOL(if value { -1 } else { 0 });- }- v-}--fn pack2(a: u32, b: u32) -> u64 {- ((a as u64) << 32) | b as u64-}--struct Pending {- hungry: usize,- queue: VecDeque<(IMFSample, Instant)>,-}--struct Shared {- transform: IMFTransform,- generator: IMFMediaEventGenerator,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- width: u32,- height: u32,- io: Mutex<()>,- pending: Mutex<Pending>,- callback: Mutex<Option<IMFAsyncCallback>>,- seq_header: Mutex<Vec<u8>>,- stopping: AtomicBool,- in_flight: Mutex<VecDeque<Instant>>,-}--// SAFETY: every call into the MFT and its event generator goes through the-// `io` mutex or is itself thread-safe (`IMFMediaEventGenerator` is documented-// free-threaded), and the LiveKit source is `Send + Sync`.-unsafe impl Send for Shared {}-unsafe impl Sync for Shared {}--#[implement(IMFAsyncCallback)]-struct EventCallback {- shared: Weak<Shared>,-}--impl IMFAsyncCallback_Impl for EventCallback_Impl {- fn GetParameters(&self, _flags: *mut u32, _queue: *mut u32) -> windows::core::Result<()> {- Err(E_NOTIMPL.into())- }-- fn Invoke(&self, result: Ref<'_, IMFAsyncResult>) -> windows::core::Result<()> {- let Some(shared) = self.shared.upgrade() else {- return Ok(());- };- let Ok(result) = result.ok() else {- return Ok(());- };- let event = match unsafe { shared.generator.EndGetEvent(result) } {- Ok(e) => e,- Err(_) => return Ok(()),- };- let kind = unsafe { event.GetType() }.unwrap_or(0);- if kind == METransformNeedInput.0 as u32 {- shared.on_need_input();- } else if kind == METransformHaveOutput.0 as u32 {- shared.on_have_output();- }- if !shared.stopping.load(Ordering::Acquire) {- let cb = shared.callback.lock().ok().and_then(|g| g.clone());- if let Some(cb) = cb {- let _ = unsafe { shared.generator.BeginGetEvent(&cb, None) };- }- }- Ok(())- }-}--impl Shared {- fn on_need_input(&self) {- let next = {- let Ok(mut pending) = self.pending.lock() else {- return;- };- match pending.queue.pop_front() {- Some(item) => Some(item),- None => {- pending.hungry += 1;- None- }- }- };- if let Some((sample, submitted)) = next {- self.submit(sample, submitted);- }- }-- fn submit(&self, sample: IMFSample, submitted: Instant) {- let _guard = self.io.lock();- if unsafe { self.transform.ProcessInput(0, &sample, 0) }.is_err() {- self.counters.errors.fetch_add(1, Ordering::Relaxed);- return;- }- self.counters.submitted.fetch_add(1, Ordering::Relaxed);- if let Ok(mut q) = self.in_flight.lock() {- while q.len() > 8 {- q.pop_front();- }- q.push_back(submitted);- }- }-- fn on_have_output(&self) {- let mut buffers = [MFT_OUTPUT_DATA_BUFFER {- dwStreamID: 0,- pSample: std::mem::ManuallyDrop::new(None),- dwStatus: 0,- pEvents: std::mem::ManuallyDrop::new(None),- }];- let mut status: u32 = 0;- let ok = {- let _guard = self.io.lock();- unsafe { self.transform.ProcessOutput(0, &mut buffers, &mut status) }- };- let sample = std::mem::ManuallyDrop::into_inner(std::mem::replace(- &mut buffers[0].pSample,- std::mem::ManuallyDrop::new(None),- ));- let _events = std::mem::ManuallyDrop::into_inner(std::mem::replace(- &mut buffers[0].pEvents,- std::mem::ManuallyDrop::new(None),- ));- if ok.is_err() {- self.counters.errors.fetch_add(1, Ordering::Relaxed);- return;- }- let Some(sample) = sample else {- return;- };- if let Err(e) = self.publish(&sample) {- tracing::debug!("[omnidisc-media] mf output: {e}");- self.counters.errors.fetch_add(1, Ordering::Relaxed);- }- }-- fn publish(&self, sample: &IMFSample) -> Result<(), StreamError> {- let keyframe = unsafe { sample.GetUINT32(&MFSampleExtension_CleanPoint) }.unwrap_or(0) != 0;- let timestamp_us = unsafe { sample.GetSampleTime() }.unwrap_or(0) / 10;- let buffer = unsafe { sample.ConvertToContiguousBuffer() }- .map_err(|e| enc_err("ConvertToContiguousBuffer", e))?;- let mut data: *mut u8 = std::ptr::null_mut();- let mut max_len: u32 = 0;- let mut len: u32 = 0;- unsafe {- buffer- .Lock(&mut data, Some(&mut max_len), Some(&mut len))- .map_err(|e| enc_err("IMFMediaBuffer::Lock", e))?;- }- let mut payload: Vec<u8> = Vec::with_capacity(len as usize + 128);- if keyframe {- if let Ok(header) = self.seq_header.lock() {- let slice = unsafe { std::slice::from_raw_parts(data, len as usize) };- // Hardware MFTs usually inline SPS/PPS ahead of every IDR; the- // ones that do not leave them only in MF_MT_MPEG_SEQUENCE_HEADER,- // and libwebrtc's packetizer needs them in the access unit.- if !header.is_empty() && !starts_with_parameter_set(slice) {- payload.extend_from_slice(header.as_slice());- }- }- }- unsafe {- payload.extend_from_slice(std::slice::from_raw_parts(data, len as usize));- let _ = buffer.Unlock();- }- if payload.is_empty() {- return Ok(());- }- self.counters.encoded.fetch_add(1, Ordering::Relaxed);- self.counters- .bytes- .fetch_add(payload.len() as u64, Ordering::Relaxed);- // Low-latency H.264 without B-frames leaves the MFT in submission- // order, so the oldest outstanding submit time belongs to this frame.- let latency = self- .in_flight- .lock()- .ok()- .and_then(|mut q| q.pop_front())- .map(|t| t.elapsed().as_nanos() as u64)- .unwrap_or(0);- self.counters- .latency_ns_sum- .fetch_add(latency, Ordering::Relaxed);- self.counters- .latency_ns_max- .fetch_max(latency, Ordering::Relaxed);- if keyframe {- self.counters.keyframes.fetch_add(1, Ordering::Relaxed);- }- let frame = EncodedVideoFrame {- codec: EncodedVideoCodec::H264,- payload: &payload,- timestamp_us,- frame_type: if keyframe {- EncodedFrameType::Key- } else {- EncodedFrameType::Delta- },- resolution: VideoResolution {- width: self.width,- height: self.height,- },- frame_metadata: None,- };- if self.source.capture_encoded_frame(&frame) {- self.counters.captured_ok.fetch_add(1, Ordering::Relaxed);- } else {- self.counters- .captured_rejected- .fetch_add(1, Ordering::Relaxed);- }- Ok(())- }-}--fn starts_with_parameter_set(data: &[u8]) -> bool {- let nal = if data.starts_with(&[0, 0, 0, 1]) {- data.get(4)- } else if data.starts_with(&[0, 0, 1]) {- data.get(3)- } else {- return false;- };- matches!(nal.map(|b| b & 0x1f), Some(7) | Some(8))-}--struct HardwareMft {- transform: IMFTransform,- name: String,-}--fn enumerate_hardware_h264() -> Result<Vec<HardwareMft>, StreamError> {- mf_startup()?;- let output = MFT_REGISTER_TYPE_INFO {- guidMajorType: MFMediaType_Video,- guidSubtype: MFVideoFormat_H264,- };- let mut list: *mut Option<IMFActivate> = std::ptr::null_mut();- let mut count: u32 = 0;- unsafe {- MFTEnumEx(- MFT_CATEGORY_VIDEO_ENCODER,- MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER,- None,- Some(&output),- &mut list,- &mut count,- )- .map_err(|e| enc_err("MFTEnumEx", e))?;- }- let mut found = Vec::new();- for i in 0..count as isize {- let activate = unsafe { (*list.offset(i)).clone() };- let Some(activate) = activate else { continue };- let name = read_friendly_name(&activate);- if let Ok(transform) = unsafe { activate.ActivateObject::<IMFTransform>() } {- found.push(HardwareMft { transform, name });- }- }- if !list.is_null() {- unsafe { CoTaskMemFree(Some(list as *const std::ffi::c_void)) };- }- Ok(found)-}--fn read_friendly_name(activate: &IMFActivate) -> String {- let mut ptr = windows::core::PWSTR::null();- let mut len: u32 = 0;- let ok =- unsafe { activate.GetAllocatedString(&MFT_FRIENDLY_NAME_Attribute, &mut ptr, &mut len) };- if ok.is_err() || ptr.is_null() {- return "Media Foundation".into();- }- let name = unsafe { ptr.to_string() }.unwrap_or_else(|_| "Media Foundation".into());- unsafe { CoTaskMemFree(Some(ptr.0 as *const std::ffi::c_void)) };- name-}--/// True when at least one vendor-neutral hardware H.264 MFT (Intel QSV, AMD-/// VCN or NVIDIA through Media Foundation) can be activated on this machine.-pub fn hardware_h264_available() -> bool {- match enumerate_hardware_h264() {- Ok(list) => !list.is_empty(),- Err(_) => false,- }-}--pub struct MfEncoder {- shared: Arc<Shared>,- codec_api: Option<CodecApi>,- converter: Mutex<Option<Nv12Converter>>,- gpu: Arc<Gpu>,- dxgi_manager: Option<DxgiManager>,- cfg: EncoderConfig,- name: String,- finished: AtomicBool,-}--struct CodecApi(ICodecAPI);-// SAFETY: ICodecAPI on an encoder MFT is free-threaded; every use here is a-// simple property set.-unsafe impl Send for CodecApi {}-unsafe impl Sync for CodecApi {}--struct DxgiManager(#[allow(dead_code)] IMFDXGIDeviceManager);-// SAFETY: the manager is only held to keep the D3D device alive for the MFT.-unsafe impl Send for DxgiManager {}-unsafe impl Sync for DxgiManager {}--impl MfEncoder {- pub fn new(- cfg: EncoderConfig,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- ) -> Result<Self, StreamError> {- let gpu = gpu().map_err(|e| StreamError::Encoder(e.to_string()))?;- let candidates = enumerate_hardware_h264()?;- if candidates.is_empty() {- return Err(StreamError::Encoder(- "no hardware H.264 encoder is registered with Media Foundation".into(),- ));- }- let mut last: Option<StreamError> = None;- for candidate in candidates {- match Self::configure(&candidate, &cfg, &gpu, source.clone(), counters.clone()) {- Ok(enc) => return Ok(enc),- Err(e) => {- tracing::debug!(- "[omnidisc-media] hardware encoder '{}' unusable: {e}",- candidate.name- );- last = Some(e);- }- }- }- Err(last.unwrap_or_else(|| {- StreamError::Encoder("no hardware H.264 encoder could be configured".into())- }))- }-- fn configure(- mft: &HardwareMft,- cfg: &EncoderConfig,- gpu: &Arc<Gpu>,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- ) -> Result<Self, StreamError> {- let transform = mft.transform.clone();- let attributes = unsafe { transform.GetAttributes() }- .map_err(|e| enc_err("IMFTransform::GetAttributes", e))?;- let is_async = unsafe { attributes.GetUINT32(&MF_TRANSFORM_ASYNC) }.unwrap_or(0) == 1;- if is_async {- unsafe {- attributes- .SetUINT32(&MF_TRANSFORM_ASYNC_UNLOCK, 1)- .map_err(|e| enc_err("MF_TRANSFORM_ASYNC_UNLOCK", e))?;- }- }- let _ = unsafe { attributes.SetUINT32(&MF_LOW_LATENCY, 1) };-- let d3d_aware = unsafe { attributes.GetUINT32(&MF_SA_D3D11_AWARE) }.unwrap_or(0) == 1;- let mut dxgi_manager = None;- if d3d_aware {- match Self::attach_d3d(&transform, gpu) {- Ok(m) => dxgi_manager = Some(DxgiManager(m)),- Err(e) => tracing::debug!("[omnidisc-media] D3D11 hand-off refused: {e}"),- }- }-- let bps = cfg.bitrate_kbps.max(1) * 1000;- let out_type =- unsafe { MFCreateMediaType() }.map_err(|e| enc_err("MFCreateMediaType", e))?;- unsafe {- out_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video).ok();- out_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_H264).ok();- out_type.SetUINT32(&MF_MT_AVG_BITRATE, bps).ok();- out_type- .SetUINT64(&MF_MT_FRAME_SIZE, pack2(cfg.width, cfg.height))- .ok();- out_type- .SetUINT64(&MF_MT_FRAME_RATE, pack2(cfg.fps.max(1) as u32, 1))- .ok();- out_type- .SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)- .ok();- out_type- .SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, pack2(1, 1))- .ok();- out_type- .SetUINT32(- &MF_MT_MPEG2_PROFILE,- if cfg.mode == StreamMode::Game {- eAVEncH264VProfile_Main.0 as u32- } else {- eAVEncH264VProfile_High.0 as u32- },- )- .ok();- transform- .SetOutputType(0, &out_type, 0)- .map_err(|e| enc_err("SetOutputType(H264)", e))?;- }-- let in_type =- unsafe { MFCreateMediaType() }.map_err(|e| enc_err("MFCreateMediaType", e))?;- unsafe {- in_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video).ok();- in_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_NV12).ok();- in_type- .SetUINT64(&MF_MT_FRAME_SIZE, pack2(cfg.width, cfg.height))- .ok();- in_type- .SetUINT64(&MF_MT_FRAME_RATE, pack2(cfg.fps.max(1) as u32, 1))- .ok();- in_type- .SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)- .ok();- in_type- .SetUINT64(&MF_MT_PIXEL_ASPECT_RATIO, pack2(1, 1))- .ok();- transform- .SetInputType(0, &in_type, 0)- .map_err(|e| enc_err("SetInputType(NV12)", e))?;- }-- let codec_api = transform.cast::<ICodecAPI>().ok().map(CodecApi);- if let Some(api) = codec_api.as_ref() {- unsafe {- let _ = api.0.SetValue(&CODECAPI_AVLowLatencyMode, &var_bool(true));- let _ = api.0.SetValue(- &CODECAPI_AVEncCommonRateControlMode,- &var_u32(eAVEncCommonRateControlMode_CBR.0 as u32),- );- let _ = api- .0- .SetValue(&CODECAPI_AVEncCommonMeanBitRate, &var_u32(bps));- let _ = api- .0- .SetValue(&CODECAPI_AVEncMPVGOPSize, &var_u32(KEYFRAME_INTERVAL));- }- }-- let provides_samples = unsafe { transform.GetOutputStreamInfo(0) }- .map(|info| {- info.dwFlags- & windows::Win32::Media::MediaFoundation::MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0- as u32- != 0- })- .unwrap_or(false);-- if !provides_samples {- return Err(StreamError::Encoder(format!(- "the '{}' encoder wants the caller to allocate output samples, which this build does not do",- mft.name- )));- }- let seq_header = read_sequence_header(&transform);-- let generator = transform- .cast::<IMFMediaEventGenerator>()- .map_err(|e| enc_err("IMFMediaEventGenerator (encoder is not asynchronous)", e))?;-- unsafe {- transform- .ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)- .map_err(|e| enc_err("NOTIFY_BEGIN_STREAMING", e))?;- transform- .ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)- .map_err(|e| enc_err("NOTIFY_START_OF_STREAM", e))?;- }-- let shared = Arc::new(Shared {- transform,- generator,- source,- counters: counters.clone(),- width: cfg.width,- height: cfg.height,- io: Mutex::new(()),- pending: Mutex::new(Pending {- hungry: 0,- queue: VecDeque::with_capacity(QUEUE_DEPTH),- }),- callback: Mutex::new(None),- seq_header: Mutex::new(seq_header),- stopping: AtomicBool::new(false),- in_flight: Mutex::new(VecDeque::with_capacity(8)),- });- let callback: IMFAsyncCallback = EventCallback {- shared: Arc::downgrade(&shared),- }- .into();- if let Ok(mut slot) = shared.callback.lock() {- *slot = Some(callback.clone());- }- unsafe {- shared- .generator- .BeginGetEvent(&callback, None)- .map_err(|e| enc_err("BeginGetEvent", e))?;- }- counters.applied_bps.store(bps as u64, Ordering::Relaxed);- Ok(Self {- shared,- codec_api,- converter: Mutex::new(None),- gpu: gpu.clone(),- dxgi_manager,- cfg: *cfg,- name: format!("Media Foundation ({})", mft.name),- finished: AtomicBool::new(false),- })- }-- fn attach_d3d(- transform: &IMFTransform,- gpu: &Arc<Gpu>,- ) -> Result<IMFDXGIDeviceManager, StreamError> {- let mut token: u32 = 0;- let mut manager: Option<IMFDXGIDeviceManager> = None;- unsafe {- MFCreateDXGIDeviceManager(&mut token, &mut manager)- .map_err(|e| enc_err("MFCreateDXGIDeviceManager", e))?;- }- let manager =- manager.ok_or_else(|| StreamError::Encoder("no DXGI device manager".into()))?;- unsafe {- manager- .ResetDevice(gpu.device(), token)- .map_err(|e| enc_err("IMFDXGIDeviceManager::ResetDevice", e))?;- transform- .ProcessMessage(MFT_MESSAGE_SET_D3D_MANAGER, manager.as_raw() as usize)- .map_err(|e| enc_err("MFT_MESSAGE_SET_D3D_MANAGER", e))?;- }- Ok(manager)- }-- fn sample_from(- &self,- nv12: &ID3D11Texture2D,- capture_us: i64,- ) -> Result<IMFSample, StreamError> {- let sample = unsafe { MFCreateSample() }.map_err(|e| enc_err("MFCreateSample", e))?;- let buffer = if self.dxgi_manager.is_some() {- let buffer = unsafe {- MFCreateDXGISurfaceBuffer(&ID3D11Texture2D::IID, nv12, 0, false)- .map_err(|e| enc_err("MFCreateDXGISurfaceBuffer", e))?- };- let len = buffer- .cast::<IMF2DBuffer>()- .ok()- .and_then(|b| unsafe { b.GetContiguousLength() }.ok())- .unwrap_or(self.cfg.width * self.cfg.height * 3 / 2);- unsafe {- let _ = buffer.SetCurrentLength(len);- }- buffer- } else {- let mut converter = self- .converter- .lock()- .map_err(|_| StreamError::Encoder("converter poisoned".into()))?;- let cpu = converter- .as_mut()- .ok_or_else(|| StreamError::Encoder("no converter".into()))?- .read_back(nv12)?;- let tight = (self.cfg.width * self.cfg.height * 3 / 2) as usize;- let buffer = unsafe { MFCreateMemoryBuffer(tight as u32) }- .map_err(|e| enc_err("MFCreateMemoryBuffer", e))?;- let mut data: *mut u8 = std::ptr::null_mut();- unsafe {- buffer- .Lock(&mut data, None, None)- .map_err(|e| enc_err("IMFMediaBuffer::Lock", e))?;- let (y, uv) = cpu.planes();- for row in 0..self.cfg.height as usize {- let src = row * cpu.stride_y as usize;- let dst = row * self.cfg.width as usize;- if src + self.cfg.width as usize <= y.len() {- std::ptr::copy_nonoverlapping(- y.as_ptr().add(src),- data.add(dst),- self.cfg.width as usize,- );- }- }- let uv_base = (self.cfg.width * self.cfg.height) as usize;- for row in 0..(self.cfg.height / 2) as usize {- let src = row * cpu.stride_uv as usize;- let dst = uv_base + row * self.cfg.width as usize;- if src + self.cfg.width as usize <= uv.len() {- std::ptr::copy_nonoverlapping(- uv.as_ptr().add(src),- data.add(dst),- self.cfg.width as usize,- );- }- }- let _ = buffer.Unlock();- let _ = buffer.SetCurrentLength(tight as u32);- }- buffer- };- unsafe {- sample- .AddBuffer(&buffer)- .map_err(|e| enc_err("IMFSample::AddBuffer", e))?;- let _ = sample.SetSampleTime(capture_us * 10);- let _ = sample.SetSampleDuration(10_000_000i64 / self.cfg.fps.max(1) as i64);- }- Ok(sample)- }-- pub fn encode(&self, frame: &CapturedFrame, force_key: bool) -> Result<(), StreamError> {- let Some(texture) = frame.texture() else {- return Err(StreamError::Encoder("captured frame has no texture".into()));- };- let nv12 = {- let mut slot = self- .converter- .lock()- .map_err(|_| StreamError::Encoder("converter poisoned".into()))?;- let needs_new = match slot.as_ref() {- Some(c) => c.size() != (self.cfg.width, self.cfg.height),- None => true,- };- if needs_new {- *slot = Some(Nv12Converter::new(- self.gpu.clone(),- frame.width(),- frame.height(),- self.cfg.width,- self.cfg.height,- )?);- }- slot.as_mut()- .ok_or_else(|| StreamError::Encoder("no converter".into()))?- .convert(texture)?- };- if force_key {- if let Some(api) = self.codec_api.as_ref() {- unsafe {- let _ = api- .0- .SetValue(&CODECAPI_AVEncVideoForceKeyFrame, &var_u32(1));- }- }- }- let sample = self.sample_from(&nv12, frame.capture_us())?;- let submitted = Instant::now();- let hungry = {- let Ok(mut pending) = self.shared.pending.lock() else {- return Err(StreamError::Encoder("encoder queue poisoned".into()));- };- if pending.hungry > 0 {- pending.hungry -= 1;- true- } else {- while pending.queue.len() >= QUEUE_DEPTH {- pending.queue.pop_front();- self.shared.counters.dropped.fetch_add(1, Ordering::Relaxed);- }- pending.queue.push_back((sample.clone(), submitted));- false- }- };- if hungry {- self.shared.submit(sample, submitted);- }- Ok(())- }-- pub fn set_bitrate(&self, bps: u64) {- if let Some(api) = self.codec_api.as_ref() {- unsafe {- let _ = api- .0- .SetValue(&CODECAPI_AVEncCommonMeanBitRate, &var_u32(bps as u32));- }- }- self.shared- .counters- .applied_bps- .store(bps, Ordering::Relaxed);- }-- pub fn set_framerate(&self, _fps: u16) {}-- pub fn hardware(&self) -> Option<bool> {- Some(true)- }-- pub fn name(&self) -> &str {- &self.name- }-- pub fn finish(&self) {- if self.finished.swap(true, Ordering::AcqRel) {- return;- }- self.shared.stopping.store(true, Ordering::Release);- let _guard = self.shared.io.lock();- unsafe {- let _ = self- .shared- .transform- .ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);- let _ = self- .shared- .transform- .ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);- let _ = self- .shared- .transform- .ProcessMessage(MFT_MESSAGE_NOTIFY_END_STREAMING, 0);- }- if let Ok(mut slot) = self.shared.callback.lock() {- *slot = None;- }- }-}--impl Drop for MfEncoder {- fn drop(&mut self) {- self.finish();- }-}--fn read_sequence_header(transform: &IMFTransform) -> Vec<u8> {- let Ok(media_type): Result<IMFMediaType, _> = (unsafe { transform.GetOutputCurrentType(0) })- else {- return Vec::new();- };- let mut ptr: *mut u8 = std::ptr::null_mut();- let mut len: u32 = 0;- let ok =- unsafe { media_type.GetAllocatedBlob(&MF_MT_MPEG_SEQUENCE_HEADER, &mut ptr, &mut len) };- if ok.is_err() || ptr.is_null() || len == 0 {- return Vec::new();- }- let out = unsafe { std::slice::from_raw_parts(ptr, len as usize) }.to_vec();- unsafe { CoTaskMemFree(Some(ptr as *const std::ffi::c_void)) };- out-}diff --git a/src-tauri/omnidisc-media/src/encode/windows/mod.rs b/src-tauri/omnidisc-media/src/encode/windows/mod.rsdeleted file mode 100644index 2f77b238..00000000--- a/src-tauri/omnidisc-media/src/encode/windows/mod.rs+++ /dev/null@@ -1,111 +0,0 @@-mod mf;-mod raw;--use super::{EncoderConfig, EncoderCounters, PublishPath};-use crate::capture::CapturedFrame;-use crate::stream::{StreamCodec, StreamError};-use livekit::webrtc::video_source::native::NativeVideoSource;-use std::sync::{Arc, OnceLock};--/// Windows publishes H.264 only: the Media Foundation encoder wired here is-/// H.264, and libwebrtc's Windows build has no HEVC encoder for the raw path.-pub fn clamp_codec(codec: StreamCodec) -> StreamCodec {- if codec != StreamCodec::H264 {- tracing::info!("[omnidisc-media] {codec:?} is not encodable on Windows; using H.264");- }- StreamCodec::H264-}--fn forced_path() -> Option<PublishPath> {- match std::env::var("OMNIDISC_WIN_ENCODER")- .unwrap_or_default()- .to_ascii_lowercase()- .as_str()- {- "raw" | "libwebrtc" | "software" => Some(PublishPath::Raw),- "mf" | "mediafoundation" | "hardware" => Some(PublishPath::PreEncoded),- _ => None,- }-}--fn hardware_present() -> bool {- static AVAILABLE: OnceLock<bool> = OnceLock::new();- *AVAILABLE.get_or_init(mf::hardware_h264_available)-}--pub fn publish_path(_cfg: &EncoderConfig) -> PublishPath {- if let Some(forced) = forced_path() {- return forced;- }- if hardware_present() {- PublishPath::PreEncoded- } else {- PublishPath::Raw- }-}--pub enum VideoEncoder {- Mf(mf::MfEncoder),- Raw(raw::RawEncoder),-}--impl VideoEncoder {- pub fn new(- cfg: EncoderConfig,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- ) -> Result<Self, StreamError> {- match publish_path(&cfg) {- PublishPath::PreEncoded => mf::MfEncoder::new(cfg, source, counters)- .map(VideoEncoder::Mf)- .map_err(|e| {- StreamError::Encoder(format!(- "{e}; set OMNIDISC_WIN_ENCODER=raw to publish through the software encoder instead"- ))- }),- PublishPath::Raw => raw::RawEncoder::new(cfg, source, counters).map(VideoEncoder::Raw),- }- }-- pub fn encode(&self, frame: &CapturedFrame, force_key: bool) -> Result<(), StreamError> {- match self {- Self::Mf(e) => e.encode(frame, force_key),- Self::Raw(e) => e.encode(frame, force_key),- }- }-- pub fn set_bitrate(&self, bps: u64) {- match self {- Self::Mf(e) => e.set_bitrate(bps),- Self::Raw(e) => e.set_bitrate(bps),- }- }-- pub fn set_framerate(&self, fps: u16) {- match self {- Self::Mf(e) => e.set_framerate(fps),- Self::Raw(e) => e.set_framerate(fps),- }- }-- pub fn hardware(&self) -> Option<bool> {- match self {- Self::Mf(e) => e.hardware(),- Self::Raw(e) => e.hardware(),- }- }-- pub fn name(&self) -> &str {- match self {- Self::Mf(e) => e.name(),- Self::Raw(e) => e.name(),- }- }-- pub fn finish(&self) {- match self {- Self::Mf(e) => e.finish(),- Self::Raw(e) => e.finish(),- }- }-}diff --git a/src-tauri/omnidisc-media/src/encode/windows/raw.rs b/src-tauri/omnidisc-media/src/encode/windows/raw.rsdeleted file mode 100644index a1ec284f..00000000--- a/src-tauri/omnidisc-media/src/encode/windows/raw.rs+++ /dev/null@@ -1,133 +0,0 @@-use crate::capture::{gpu, CapturedFrame, Gpu, Nv12Converter};-use crate::encode::{EncoderConfig, EncoderCounters};-use crate::stream::StreamError;-use livekit::webrtc::video_frame::{NV12Buffer, VideoFrame, VideoRotation};-use livekit::webrtc::video_source::native::NativeVideoSource;-use std::sync::atomic::Ordering;-use std::sync::{Arc, Mutex};-use std::time::Instant;--/// Publishes raw NV12 frames and lets libwebrtc pick the encoder. This is the-/// path Windows uses when no hardware Media Foundation H.264 MFT is available:-/// slower and software-bound, but it always produces a working share.-pub struct RawEncoder {- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- converter: Mutex<Option<Nv12Converter>>,- gpu: Arc<Gpu>,- cfg: EncoderConfig,-}--impl RawEncoder {- pub fn new(- cfg: EncoderConfig,- source: NativeVideoSource,- counters: Arc<EncoderCounters>,- ) -> Result<Self, StreamError> {- let gpu = gpu().map_err(|e| StreamError::Encoder(e.to_string()))?;- counters- .applied_bps- .store(cfg.bitrate_kbps as u64 * 1000, Ordering::Relaxed);- Ok(Self {- source,- counters,- converter: Mutex::new(None),- gpu,- cfg,- })- }-- pub fn encode(&self, frame: &CapturedFrame, _force_key: bool) -> Result<(), StreamError> {- let Some(texture) = frame.texture() else {- return Err(StreamError::Encoder("captured frame has no texture".into()));- };- let started = Instant::now();- let mut slot = self- .converter- .lock()- .map_err(|_| StreamError::Encoder("converter poisoned".into()))?;- let needs_new = match slot.as_ref() {- Some(c) => c.size() != (self.cfg.width, self.cfg.height),- None => true,- };- if needs_new {- *slot = Some(Nv12Converter::new(- self.gpu.clone(),- frame.width(),- frame.height(),- self.cfg.width,- self.cfg.height,- )?);- }- let converter = slot- .as_mut()- .ok_or_else(|| StreamError::Encoder("no converter".into()))?;- let nv12 = converter.convert(texture)?;- let cpu = converter.read_back(&nv12)?;- drop(slot);-- let mut buffer = NV12Buffer::with_strides(- self.cfg.width,- self.cfg.height,- self.cfg.width,- self.cfg.width,- );- {- let (dst_y, dst_uv) = buffer.data_mut();- let (src_y, src_uv) = cpu.planes();- let w = self.cfg.width as usize;- for row in 0..self.cfg.height as usize {- let src = row * cpu.stride_y as usize;- let dst = row * w;- if src + w <= src_y.len() && dst + w <= dst_y.len() {- dst_y[dst..dst + w].copy_from_slice(&src_y[src..src + w]);- }- }- for row in 0..(self.cfg.height / 2) as usize {- let src = row * cpu.stride_uv as usize;- let dst = row * w;- if src + w <= src_uv.len() && dst + w <= dst_uv.len() {- dst_uv[dst..dst + w].copy_from_slice(&src_uv[src..src + w]);- }- }- }- let video = VideoFrame {- rotation: VideoRotation::VideoRotation0,- timestamp_us: frame.capture_us(),- frame_metadata: None,- buffer,- };- self.source.capture_frame(&video);- self.counters.submitted.fetch_add(1, Ordering::Relaxed);- self.counters.encoded.fetch_add(1, Ordering::Relaxed);- self.counters.captured_ok.fetch_add(1, Ordering::Relaxed);- let latency = started.elapsed().as_nanos() as u64;- self.counters- .latency_ns_sum- .fetch_add(latency, Ordering::Relaxed);- self.counters- .latency_ns_max- .fetch_max(latency, Ordering::Relaxed);- Ok(())- }-- pub fn set_bitrate(&self, bps: u64) {- // libwebrtc owns rate control on this path; record what was asked so the- // debug panel does not claim a number we never applied.- self.counters.applied_bps.store(bps, Ordering::Relaxed);- }-- pub fn set_framerate(&self, _fps: u16) {}-- /// Unknown until the SDK reports `encoder_implementation`; never claim- /// hardware we did not select ourselves.- pub fn hardware(&self) -> Option<bool> {- None- }-- pub fn name(&self) -> &str {- "libwebrtc"- }-- pub fn finish(&self) {}-}diff --git a/src-tauri/omnidisc-media/src/engine.rs b/src-tauri/omnidisc-media/src/engine.rsdeleted file mode 100644index 01bc8c16..00000000--- a/src-tauri/omnidisc-media/src/engine.rs+++ /dev/null@@ -1,503 +0,0 @@-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,- },- Stream {- user_id: String,- active: bool,- },- 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.rsdeleted file mode 100644index 7bb4a978..00000000--- a/src-tauri/omnidisc-media/src/lib.rs+++ /dev/null@@ -1,27 +0,0 @@-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.rsdeleted file mode 100644index c9989492..00000000--- a/src-tauri/omnidisc-media/src/livekit_backend.rs+++ /dev/null@@ -1,1212 +0,0 @@-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::options::TrackPublishOptions;-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::{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, message: String) {- const BACKOFF_MS: [u64; 3] = [250, 1_000, 3_000];- let wanted = match kind {- DeviceKind::Input => shared.input_device(),- DeviceKind::Output => shared.output_device(),- };- // Long enough for the failing callback to unwind before its stream is- // dropped, short enough that nobody sees it.- std::thread::sleep(Duration::from_millis(50));- if !shared.still_wanted(kind) {- return;- }- // One silent attempt before saying anything. Windows invalidates the stream- // handle whenever the default endpoint changes — switching headphones in- // the tray is a routine action, and it must not flash "microphone lost" at- // someone who is mid-sentence.- let reopened = match kind {- DeviceKind::Input => shared.io.start_input(wanted.clone()),- DeviceKind::Output => shared.io.start_output(wanted.clone()),- };- if reopened.is_ok() {- match kind {- DeviceKind::Input => shared.input_running.store(true, Ordering::Release),- DeviceKind::Output => shared.output_running.store(true, Ordering::Release),- }- tracing::debug!(- "[omnidisc-media] the {:?} device came back immediately after: {}",- kind,- message- );- return;- }- shared.emit(EngineNotification::Error {- code: match kind {- DeviceKind::Input => "ERR_VOICE_MIC_LOST".into(),- DeviceKind::Output => "ERR_VOICE_OUTPUT_LOST".into(),- },- message,- });- shared.emit(EngineNotification::Device {- kind,- status: DeviceStatus::Lost,- cause: None,- });- 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"),- CaptureEvent::SilentInput => {- tracing::warn!("[omnidisc-media] microphone delivers only digital silence");- shared.emit(EngineNotification::Device {- kind: DeviceKind::Input,- status: DeviceStatus::Silent,- cause: None,- });- }- }- });- 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, error| {- let Some(shared) = fault_slot- .lock()- .ok()- .and_then(|s| s.as_ref().and_then(|w| w.upgrade()))- else {- return;- };- if !error.fatal() {- tracing::debug!("[omnidisc-media] audio glitch on {:?}: {}", fault, error);- return;- }- let message = error.to_string();- tracing::warn!(- "[omnidisc-media] audio stream fault {:?}: {}",- fault,- message- );- let kind = match fault {- StreamFault::Input => {- shared.input_running.store(false, Ordering::Release);- DeviceKind::Input- }- StreamFault::Output => {- shared.output_running.store(false, Ordering::Release);- DeviceKind::Output- }- };- // 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, message);- 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 publication.source() == TrackSource::Screenshare {- let id = participant.identity().0;- if let Ok(mut m) = shared.video_publications.lock() {- m.insert(id.clone(), publication.clone());- }- shared.emit(EngineNotification::Stream {- user_id: id,- active: true,- });- }- } else {- subscribe_audio(&publication);- }- }- RoomEvent::TrackUnpublished {- publication,- participant,- } => {- if publication.kind() == TrackKind::Video- && publication.source() == TrackSource::Screenshare- {- let id = participant.identity().0;- if let Ok(mut m) = shared.video_publications.lock() {- m.remove(&id);- }- if let Ok(mut m) = shared.remote_video.lock() {- m.remove(&id);- }- shared.emit(EngineNotification::Stream {- user_id: id,- active: false,- });- }- }- 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 publication.source() == TrackSource::Screenshare {- if let Ok(mut m) = shared.video_publications.lock() {- m.insert(participant.identity().0, publication.clone());- }- shared.emit(EngineNotification::Stream {- user_id: participant.identity().0,- active: true,- });- }- } 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- && 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.rsdeleted file mode 100644index 35ce4fea..00000000--- a/src-tauri/omnidisc-media/src/state.rs+++ /dev/null@@ -1,120 +0,0 @@-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.rsdeleted file mode 100644index cc2725fc..00000000--- a/src-tauri/omnidisc-media/src/stream.rs+++ /dev/null@@ -1,280 +0,0 @@-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.rsdeleted file mode 100644index 9a4aac63..00000000--- a/src-tauri/omnidisc-media/src/streaming.rs+++ /dev/null@@ -1,500 +0,0 @@-use crate::capture::{self, AudioSink, CaptureOptions, CapturedFrame, VideoSink, VideoTick};-use crate::encode::{self, EncoderConfig, EncoderCounters, PublishPath, 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,- mode: AudioMode,-}--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 = encode::clamp_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 cfg = EncoderConfig {- width,- height,- fps: req.fps,- codec,- bitrate_kbps: bitrate,- mode: req.mode,- };- let path = encode::publish_path(&cfg);- let resolved = ResolvedStream {- width,- height,- fps: req.fps,- bitrate_kbps: bitrate,- codec,- mode: req.mode,- audio: req.audio,- };-- let resolution = VideoResolution { width, height };- let source = match path {- PublishPath::PreEncoded => NativeVideoSource::new_encoded(resolution),- PublishPath::Raw => NativeVideoSource::new(resolution, true),- };- 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: match path {- PublishPath::PreEncoded => VideoEncoderBackend::PreEncoded,- // On Linux the SDK's own VAAPI/NVENC backends replace the- // encoder we write by hand elsewhere, so ask for one by- // name instead of leaving the choice to `Auto`.- #[cfg(all(target_os = "linux", feature = "linux-capture"))]- PublishPath::Raw => encode::preferred_backend(),- #[cfg(not(all(target_os = "linux", feature = "linux-capture")))]- PublishPath::Raw => VideoEncoderBackend::Auto,- },- 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).- if path == PublishPath::PreEncoded {- 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 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;- // Report the mode actually obtained, not the one asked for: the capture- // side degrades per-app -> system-except-us -> none on its own.- let mut resolved = resolved;- resolved.audio = audio.as_ref().map(|a| a.mode).unwrap_or(AudioMode::None);-- 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_,- mode: obtained,- }),- 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;- // On the pass-through the SDK only knows "passthrough"; the- // encoder that actually ran is ours, so keep our name.- let reported = &o.outbound.encoder_implementation;- if !reported.is_empty() && !reported.to_lowercase().contains("passthrough") {- stats.encoder = reported.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.rsdeleted file mode 100644index 0b789a46..00000000--- a/src-tauri/omnidisc-media/src/tone.rs+++ /dev/null@@ -1,112 +0,0 @@-//! 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.rsdeleted file mode 100644index f52295de..00000000--- a/src-tauri/omnidisc-media/src/viewer/mod.rs+++ /dev/null@@ -1,272 +0,0 @@-mod wgpu_surface;--pub use wgpu_surface::{FrameSlot, Planes, WgpuViewer};--#[cfg(any(target_os = "macos", target_os = "windows"))]-use crate::stream::StreamError;-use crate::stream::{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};--/// # Safety-///-/// `ns_view` must be a non-null pointer to a live `NSView` that stays alive for-/// as long as the returned [`WgpuViewer`], and must be called from the main-/// thread — it reads and mutates the view's AppKit layer tree.-#[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)-}--/// Build the viewer surface from a Win32 window.-///-/// There is no layer ordering to fix here: WebView2 lives in its own child-/// `HWND` that DWM composes above the parent's swap chain, so the overlay is on-/// top by construction — unlike AppKit, where both are sibling `CALayer`s.-///-/// # Safety-///-/// `hwnd` must be a live window handle that stays alive for as long as the-/// returned [`WgpuViewer`], and this must be called from the thread that owns-/// that window — `raw-window-handle` requires it, and the swap chain is bound-/// to the window's message loop.-#[cfg(target_os = "windows")]-pub unsafe fn create_win32_surface(- hwnd: isize,- hinstance: isize,- width: u32,- height: u32,-) -> Result<Arc<WgpuViewer>, StreamError> {- use raw_window_handle::{- RawDisplayHandle, RawWindowHandle, Win32WindowHandle, WindowsDisplayHandle,- };- use std::num::NonZeroIsize;-- let hwnd = NonZeroIsize::new(hwnd).ok_or_else(|| StreamError::Viewer("null hwnd".into()))?;- let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();- desc.backends = wgpu::Backends::PRIMARY;- let instance = wgpu::Instance::new(desc);- let mut handle = Win32WindowHandle::new(hwnd);- // Vulkan's `VkWin32SurfaceCreateInfoKHR` wants the module handle; DX12 does- // not. Passing it keeps both backends usable instead of betting on DX12.- handle.hinstance = NonZeroIsize::new(hinstance);- let surface = instance- .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {- raw_display_handle: Some(RawDisplayHandle::Windows(WindowsDisplayHandle::new())),- raw_window_handle: RawWindowHandle::Win32(handle),- })- .map_err(|e| StreamError::Viewer(format!("create_surface: {e}")))?;- 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.wgsldeleted file mode 100644index c466c8cb..00000000--- a/src-tauri/omnidisc-media/src/viewer/shader.wgsl+++ /dev/null@@ -1,62 +0,0 @@-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.rsdeleted file mode 100644index a03967be..00000000--- a/src-tauri/omnidisc-media/src/viewer/wgpu_surface.rs+++ /dev/null@@ -1,435 +0,0 @@-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);- // An adapter that cannot present to this window answers with empty- // lists instead of an error; indexing them would abort the app.- let first_format = *caps.formats.first().ok_or_else(|| {- StreamError::Viewer("this GPU cannot draw into the stream window".into())- })?;- let format = caps- .formats- .iter()- .copied()- .find(|f| !f.is_srgb())- .unwrap_or(first_format);- 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: caps- .present_modes- .iter()- .copied()- .find(|m| *m == wgpu::PresentMode::Fifo)- .unwrap_or(wgpu::PresentMode::AutoVsync),- desired_maximum_frame_latency: 2,- alpha_mode: caps- .alpha_modes- .first()- .copied()- .unwrap_or(wgpu::CompositeAlphaMode::Auto),- 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);- let surf_h = viewport.surface_height.max(1);- 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.rsdeleted file mode 100644index 48584180..00000000--- a/src-tauri/omnidisc-media/tests/stream_e2e.rs+++ /dev/null@@ -1,405 +0,0 @@-//! 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;--/// Refuses to run against anything but a throwaway instance unless told-/// otherwise. These tests create real accounts, and pointing them at a live-/// server litters it — which is exactly what happened to the production-/// instance before this guard existed.-fn allow_target(base: &str) -> bool {- if std::env::var_os("OMNIDISC_TEST_ALLOW_REMOTE").is_some() {- return true;- }- let local = base.contains("localhost") || base.contains("127.0.0.1") || base.contains("[::1]");- if !local {- eprintln!(- "refusing to run against {base}: it is not a local instance. Set \- OMNIDISC_TEST_ALLOW_REMOTE=1 if that is really what you want."- );- }- local-}--/// A password nobody can guess from the repository.-///-/// These tests register real accounts on whatever instance `OMNIDISC_TEST_URL`-/// points at, and a constant in a public repo is a working credential for every-/// account they ever left behind. One random value per process keeps the run-/// self-consistent without publishing a key.-fn test_password() -> &'static str {- static PASSWORD: std::sync::OnceLock<String> = std::sync::OnceLock::new();- PASSWORD.get_or_init(|| {- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0);- format!(- "od-{}-{:x}-{:x}",- std::process::id(),- nanos,- nanos.rotate_left(29)- )- })-}--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": test_password() }))- .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();- if !allow_target(&base) {- return;- }- 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.rsdeleted file mode 100644index 6155aed3..00000000--- a/src-tauri/omnidisc-media/tests/voice_e2e.rs+++ /dev/null@@ -1,493 +0,0 @@-//! 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;--/// Refuses to run against anything but a throwaway instance unless told-/// otherwise. These tests create real accounts, and pointing them at a live-/// server litters it — which is exactly what happened to the production-/// instance before this guard existed.-fn allow_target(base: &str) -> bool {- if std::env::var_os("OMNIDISC_TEST_ALLOW_REMOTE").is_some() {- return true;- }- let local = base.contains("localhost") || base.contains("127.0.0.1") || base.contains("[::1]");- if !local {- eprintln!(- "refusing to run against {base}: it is not a local instance. Set \- OMNIDISC_TEST_ALLOW_REMOTE=1 if that is really what you want."- );- }- local-}--/// A password nobody can guess from the repository.-///-/// These tests register real accounts on whatever instance `OMNIDISC_TEST_URL`-/// points at, and a constant in a public repo is a working credential for every-/// account they ever left behind. One random value per process keeps the run-/// self-consistent without publishing a key.-fn test_password() -> &'static str {- static PASSWORD: std::sync::OnceLock<String> = std::sync::OnceLock::new();- PASSWORD.get_or_init(|| {- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0);- format!(- "od-{}-{:x}-{:x}",- std::process::id(),- nanos,- nanos.rotate_left(29)- )- })-}--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": test_password() }))- .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 let Some(key) = room_key {- // A commit on the group bumps the epoch; the ring index has to follow it- // without dropping the call.- let next = RoomKey::new(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> {- real_test_url().filter(|b| allow_target(b))-}--#[allow(dead_code)]-fn real_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-media/tests/windows_capture.rs b/src-tauri/omnidisc-media/tests/windows_capture.rsdeleted file mode 100644index e9e799ed..00000000--- a/src-tauri/omnidisc-media/tests/windows_capture.rs+++ /dev/null@@ -1,182 +0,0 @@-//! Runtime proof that the Windows capture stack actually initialises.-//!-//! Compiling is not evidence here: WinRT activation, the D3D11 device, the-//! frame pool and the WASAPI process-loopback activation all fail at runtime or-//! not at all, and none of that is reachable from the machine this code was-//! written on. The Windows CI job already runs `cargo test --workspace`, so-//! these run there on every push.-//!-//! `harness = false` on purpose: libtest buffers a test's output and throws it-//! away if the process dies, which is exactly what a heap corruption does. With-//! a plain `main` every checkpoint is already on the wire when the process-//! aborts, so CI names the step that died instead of just the exit code. It-//! also keeps the steps in one thread, so an apartment-threading bug in the COM-//! code is not mistaken for a memory bug.-//!-//! A CI runner is a virtual desktop with no audio endpoint, so the assertions-//! are about behaviour that must hold anywhere: enumeration answers, a capture-//! either starts or fails with a typed error, and nothing panics or hangs.--#[cfg(not(windows))]-fn main() {}--#[cfg(windows)]-fn main() {- use omnidisc_media::capture::{self, CaptureOptions, VideoTick};- use omnidisc_media::stream::{AudioMode, SourceId};- use std::sync::atomic::{AtomicU32, Ordering};- use std::sync::Arc;- use std::time::{Duration, Instant};-- macro_rules! step {- ($($arg:tt)*) => {{- println!("[windows-capture] {}", format!($($arg)*));- std::io::Write::flush(&mut std::io::stdout()).ok();- }};- }-- std::env::set_var("OMNIDISC_CAPTURE_TRACE", "1");-- step!("enumerating without thumbnails");- let sources = capture::list_sources(false).expect("list_sources must answer on Windows");- step!(- "displays={} windows={} apps={} app_audio={} system_audio={}",- sources.displays.len(),- sources.windows.len(),- sources.apps.len(),- sources.app_audio_supported,- sources.system_audio_supported- );- assert!(- !sources.displays.is_empty(),- "a Windows session always has at least one display"- );- for d in &sources.displays {- assert!(matches!(d.id, SourceId::Display { .. }));- assert!(- !d.title.trim().is_empty(),- "a display needs a label the user can read"- );- }- for w in &sources.windows {- assert!(matches!(w.id, SourceId::Window { .. }));- }- // Process loopback needs build 20348; the flag exists so the picker can say- // so instead of offering an option that always fails.- if sources.app_audio_supported {- assert!(- sources.system_audio_supported,- "a build new enough for per-app loopback also has the exclude-self mode"- );- }-- step!("enumerating with thumbnails");- let thumbed = capture::list_sources(true).expect("list_sources with thumbnails");- let mut thumbs = 0;- for s in thumbed.displays.iter().chain(thumbed.windows.iter()) {- if let Some(thumb) = &s.thumbnail {- thumbs += 1;- assert!(- thumb.starts_with("data:image/"),- "a thumbnail is a data URL the webview can render, got {:.32}",- thumb- );- }- }- step!("thumbnails produced: {thumbs}");-- step!("starting display capture");- let display = sources- .displays- .first()- .expect("at least one display")- .id- .clone();- let frames = Arc::new(AtomicU32::new(0));- let ticks = Arc::new(AtomicU32::new(0));- let (f, t) = (frames.clone(), ticks.clone());- let sink: capture::VideoSink = Arc::new(move |tick| {- t.fetch_add(1, Ordering::Relaxed);- if matches!(tick, VideoTick::Frame(_)) {- f.fetch_add(1, Ordering::Relaxed);- }- });- let opts = CaptureOptions {- source: display,- fps: 30,- height: Some(720),- cursor: false,- };- match capture::start_video(&opts, sink) {- Ok((handle, geometry)) => {- step!(- "capture started {}x{}@{}",- geometry.width,- geometry.height,- geometry.fps- );- assert!(- geometry.width > 0 && geometry.height > 0,- "geometry must be real"- );- assert!(geometry.fps > 0);- let deadline = Instant::now() + Duration::from_secs(3);- while Instant::now() < deadline && ticks.load(Ordering::Relaxed) == 0 {- std::thread::sleep(Duration::from_millis(50));- }- step!(- "ticks={} frames={}",- ticks.load(Ordering::Relaxed),- frames.load(Ordering::Relaxed)- );- handle.stop();- step!("capture stopped");- // A still virtual desktop may produce no *frames*, but the idle ticks- // that keep the encoder emitting CFR must arrive regardless — their- // absence is what silently freezes a viewer's picture.- assert!(- ticks.load(Ordering::Relaxed) > 0,- "capture started but delivered neither a frame nor an idle tick in 3 s"- );- }- Err(e) => {- // A headless or locked session is a legitimate refusal; a panic, a- // hang, or an error with nothing to act on is not.- step!("capture refused: {e}");- assert!(- !e.to_string().trim().is_empty(),- "a refusal must explain itself"- );- }- }-- step!("starting system audio");- let sink: capture::AudioSink = Arc::new(|_samples: &[f32]| {});- match capture::start_audio(AudioMode::System, sink) {- Ok((handle, mode)) => {- step!("audio started as {mode:?}");- // The ladder may have degraded; whatever it reports has to be a mode- // the UI can name, never a claim of something it did not get.- assert!(matches!(mode, AudioMode::System | AudioMode::None));- std::thread::sleep(Duration::from_millis(300));- handle.stop();- step!("audio stopped");- }- Err(e) => {- step!("audio refused: {e}");- assert!(- !e.to_string().trim().is_empty(),- "a refusal must explain itself"- );- }- }-- step!("starting the no-audio path");- let sink: capture::AudioSink = Arc::new(|_samples: &[f32]| {});- let (handle, mode) = capture::start_audio(AudioMode::None, sink)- .expect("AudioMode::None is the path a share with no audio takes");- assert_eq!(mode, AudioMode::None);- handle.stop();-- step!("all checks passed");-}diff --git a/src-tauri/omnidisc-mls/Cargo.toml b/src-tauri/omnidisc-mls/Cargo.tomldeleted file mode 100644index a88833eb..00000000--- a/src-tauri/omnidisc-mls/Cargo.toml+++ /dev/null@@ -1,23 +0,0 @@-[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.rsdeleted file mode 100644index 70c915e9..00000000--- a/src-tauri/omnidisc-mls/src/client.rs+++ /dev/null@@ -1,1010 +0,0 @@-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());- // A group listed in the snapshot but missing from storage means a- // partial write; dropping it is safer than refusing to start.- if let Some(group) =- MlsGroup::load(provider.storage(), &gid).map_err(mls("load group"))?- {- groups.insert(id.clone(), group);- }- }- 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.contains(&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 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.rsdeleted file mode 100644index d0f1fa55..00000000--- a/src-tauri/omnidisc-mls/src/file.rs+++ /dev/null@@ -1,263 +0,0 @@-//! 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.rsdeleted file mode 100644index 8f38c41d..00000000--- a/src-tauri/omnidisc-mls/src/lib.rs+++ /dev/null@@ -1,47 +0,0 @@-//! 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.rsdeleted file mode 100644index cb73f517..00000000--- a/src-tauri/omnidisc-mls/src/provider.rs+++ /dev/null@@ -1,125 +0,0 @@-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.rsdeleted file mode 100644index 57efc603..00000000--- a/src-tauri/omnidisc-mls/src/state.rs+++ /dev/null@@ -1,103 +0,0 @@-//! 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.tomldeleted file mode 100644index b81ade07..00000000--- a/src-tauri/omnidisc-proto/Cargo.toml+++ /dev/null@@ -1,14 +0,0 @@-[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.rsdeleted file mode 100644index 5ed20d81..00000000--- a/src-tauri/omnidisc-proto/src/bitrate.rs+++ /dev/null@@ -1,205 +0,0 @@-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.rsdeleted file mode 100644index 9b7f8573..00000000--- a/src-tauri/omnidisc-proto/src/channel.rs+++ /dev/null@@ -1,183 +0,0 @@-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.rsdeleted file mode 100644index 7d0c1582..00000000--- a/src-tauri/omnidisc-proto/src/gateway.rs+++ /dev/null@@ -1,542 +0,0 @@-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),- },-}--// Wire type shared with omnidisc-server: boxing a variant would keep the JSON-// identical but break every construction site in that repo.-#[allow(clippy::large_enum_variant)]-#[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>,- },-}--// Wire type shared with omnidisc-server: boxing a variant would keep the JSON-// identical but break every construction site in that repo.-#[allow(clippy::large_enum_variant)]-#[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>),- StorageStatus(StorageStatus),-}--/// How full the instance's disk is. Broadcast when it crosses a threshold so-/// people can save what matters before the sweep, and again after one.-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]-pub struct StorageStatus {- pub used_bytes: u64,- pub total_bytes: u64,- /// 0.0–1.0 of the whole volume.- pub ratio: f64,- pub level: StoragePressure,- /// Seconds a finished upload survives before the janitor deletes it.- pub attachment_ttl_seconds: u64,- /// Set when this status is the announcement of a purge that just ran.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub purged_files: Option<u64>,-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum StoragePressure {- Ok,- Warning,- Critical,- Purged,-}--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",- Self::StorageStatus(_) => "STORAGE_STATUS",- }- }-}--#[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.rsdeleted file mode 100644index 5ae98b29..00000000--- a/src-tauri/omnidisc-proto/src/lib.rs+++ /dev/null@@ -1,14 +0,0 @@-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.rsdeleted file mode 100644index 204d6d13..00000000--- a/src-tauri/omnidisc-proto/src/limits.rs+++ /dev/null@@ -1,40 +0,0 @@-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.rsdeleted file mode 100644index c754e98f..00000000--- a/src-tauri/omnidisc-proto/src/message.rs+++ /dev/null@@ -1,179 +0,0 @@-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,- /// When the server will delete the bytes. Files are deliberately temporary:- /// the instance never becomes a place where an old leak can be found.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub expires_at: Option<String>,- /// The bytes are already gone. The row survives as a tombstone so the- /// message reads "this file expired" instead of offering a dead link.- #[serde(default)]- pub expired: 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.rsdeleted file mode 100644index b79aa459..00000000--- a/src-tauri/omnidisc-proto/src/permissions.rs+++ /dev/null@@ -1,319 +0,0 @@-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.rsdeleted file mode 100644index 5652fc1b..00000000--- a/src-tauri/omnidisc-proto/src/rest.rs+++ /dev/null@@ -1,550 +0,0 @@-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.rsdeleted file mode 100644index 3e271735..00000000--- a/src-tauri/omnidisc-proto/src/snowflake.rs+++ /dev/null@@ -1,174 +0,0 @@-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.rsdeleted file mode 100644index da2b865b..00000000--- a/src-tauri/omnidisc-proto/src/user.rs+++ /dev/null@@ -1,116 +0,0 @@-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/core/tools/screen_record.rs b/src-tauri/omniget-core/src/core/tools/screen_record.rsindex a0d4dc42..268478ba 100644--- a/src-tauri/omniget-core/src/core/tools/screen_record.rs+++ b/src-tauri/omniget-core/src/core/tools/screen_record.rs@@ -337,7 +337,9 @@ pub async fn start(opts: RecordOptions) -> anyhow::Result<RecordState> {&& std::env::var("WAYLAND_DISPLAY").is_ok()&& std::env::var("DISPLAY").is_err(){- return Err(anyhow!("sessao Wayland sem XWayland: o x11grab nao enxerga a tela. Use a captura do OmniDisc (PipeWire) ou entre numa sessao X11."));+ return Err(anyhow!(+ "sessao Wayland sem XWayland: o x11grab nao enxerga a tela. Entre numa sessao X11."+ ));}let ffmpeg = crate::core::dependencies::ensure_ffmpeg().await?;let dir = if opts.output_dir.trim().is_empty() {diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rsindex cdfb81e8..b73e7ad5 100644--- a/src-tauri/omniget-core/src/models/settings.rs+++ b/src-tauri/omniget-core/src/models/settings.rs@@ -33,55 +33,6 @@ 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)]@@ -721,7 +672,6 @@ 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 b86452d3..03a5136e 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -14,7 +14,6 @@ pub mod integration;pub mod league;pub mod media_history;pub mod nami;-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.rsdeleted file mode 100644index 93685533..00000000--- a/src-tauri/src/commands/omnidisc/api.rs+++ /dev/null@@ -1,1063 +0,0 @@-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.-// The argument list is the IPC contract the frontend calls by name; folding it-// into a struct would change the payload shape for no gain here.-#[allow(clippy::too_many_arguments)]-#[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-}--// The argument list is the IPC contract the frontend calls by name; folding it-// into a struct would change the payload shape for no gain here.-#[allow(clippy::too_many_arguments)]-#[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!(path_id("od-3f2a1b4c-1111-2222-3333-444455556666").is_ok());- 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.rsdeleted file mode 100644index 5d5c28ab..00000000--- a/src-tauri/src/commands/omnidisc/auth.rs+++ /dev/null@@ -1,146 +0,0 @@-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.rsdeleted file mode 100644index 39cecfe8..00000000--- a/src-tauri/src/commands/omnidisc/device.rs+++ /dev/null@@ -1,276 +0,0 @@-//! 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/ducking.rs b/src-tauri/src/commands/omnidisc/ducking.rsdeleted file mode 100644index 730097fc..00000000--- a/src-tauri/src/commands/omnidisc/ducking.rs+++ /dev/null@@ -1,79 +0,0 @@-//! Keep Windows from muffling everything else the moment a call starts.-//!-//! Windows attenuates every other application by ~80 % while a process holds a-//! communications stream. Nobody asks for it and nothing in the app explains-//! it: the user joins a voice channel and the music, the game and the video-//! they deliberately left playing all drop. OmniDisc already has its own-//! ducking (`omnidisc.voice.ducking_percent`), it applies to the call mix, and-//! it is off unless the user turns it on — the system's version is a second,-//! invisible one on top.-//!-//! `IAudioSessionControl2::SetDuckingPreference(TRUE)` opts this process out.-//! It has to be set before the communications stream opens, which is why this-//! runs when the voice engine starts rather than when a call begins.-//!-//! No-op everywhere else: macOS and Linux do not duck other applications.--/// Ask Windows not to duck other applications for us. Best effort: failing-/// only means the platform default stays, so it never blocks a call.-pub fn opt_out_of_system_ducking() {- #[cfg(windows)]- {- if std::thread::Builder::new()- .name("omnidisc-ducking".into())- .spawn(|| match windows_impl::apply() {- Ok(()) => {- tracing::info!("[omnidisc] opted out of the Windows ducking of other apps")- }- Err(e) => tracing::warn!(- "[omnidisc] could not opt out of the Windows ducking of other apps: {}",- e- ),- })- .is_err()- {- tracing::warn!("[omnidisc] could not start the ducking opt-out thread");- }- }-}--#[cfg(windows)]-mod windows_impl {- use windows::core::Interface;- use windows::Win32::Foundation::RPC_E_CHANGED_MODE;- use windows::Win32::Media::Audio::{- eConsole, eRender, IAudioSessionControl2, IAudioSessionManager2, IMMDeviceEnumerator,- MMDeviceEnumerator,- };- use windows::Win32::System::Com::{- CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED,- };-- pub fn apply() -> windows::core::Result<()> {- unsafe {- // Tauri's main thread is an STA; this runs on its own thread, so an- // MTA is free here. `RPC_E_CHANGED_MODE` would only mean someone- // else already initialised it — still usable, just not ours to undo.- let hr = CoInitializeEx(None, COINIT_MULTITHREADED);- let owns_com = hr.is_ok();- if hr.is_err() && hr != RPC_E_CHANGED_MODE {- return Err(hr.into());- }- let result = set_preference();- if owns_com {- CoUninitialize();- }- result- }- }-- unsafe fn set_preference() -> windows::core::Result<()> {- let enumerator: IMMDeviceEnumerator =- CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL)?;- let device = enumerator.GetDefaultAudioEndpoint(eRender, eConsole)?;- let manager: IAudioSessionManager2 = device.Activate(CLSCTX_ALL, None)?;- let session = manager.GetAudioSessionControl(None, 0)?;- let session: IAudioSessionControl2 = session.cast()?;- session.SetDuckingPreference(true)- }-}diff --git a/src-tauri/src/commands/omnidisc/e2e_lock.rs b/src-tauri/src/commands/omnidisc/e2e_lock.rsdeleted file mode 100644index 2c2f1844..00000000--- a/src-tauri/src/commands/omnidisc/e2e_lock.rs+++ /dev/null@@ -1,38 +0,0 @@-//! 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.rsdeleted file mode 100644index 08239f86..00000000--- a/src-tauri/src/commands/omnidisc/e2e_test.rs+++ /dev/null@@ -1,476 +0,0 @@-//! 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;--/// Refuses to run against anything but a throwaway instance unless told-/// otherwise. These tests create real accounts, and pointing them at a live-/// server litters it — which is exactly what happened to the production-/// instance before this guard existed.-fn allow_target(base: &str) -> bool {- if std::env::var_os("OMNIDISC_TEST_ALLOW_REMOTE").is_some() {- return true;- }- let local = base.contains("localhost") || base.contains("127.0.0.1") || base.contains("[::1]");- if !local {- eprintln!(- "refusing to run against {base}: it is not a local instance. Set \- OMNIDISC_TEST_ALLOW_REMOTE=1 if that is really what you want."- );- }- local-}--/// A password nobody can guess from the repository.-///-/// These tests register real accounts on whatever instance `OMNIDISC_TEST_URL`-/// points at, and a constant in a public repo is a working credential for every-/// account they ever left behind. One random value per process keeps the run-/// self-consistent without publishing a key.-fn test_password() -> &'static str {- static PASSWORD: std::sync::OnceLock<String> = std::sync::OnceLock::new();- PASSWORD.get_or_init(|| {- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0);- format!(- "od-{}-{:x}-{:x}",- std::process::id(),- nanos,- nanos.rotate_left(29)- )- })-}--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");- if !allow_target(&base) {- return;- }- let _session_dir = super::e2e_lock::SessionDirGuard::acquire();-- let alice_name = unique("alice");- let bob_name = unique("bob");- let password = test_password();-- 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.rsdeleted file mode 100644index 07b29d8e..00000000--- a/src-tauri/src/commands/omnidisc/e2ee_e2e_test.rs+++ /dev/null@@ -1,421 +0,0 @@-//! 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 super::e2e_lock::SessionDirGuard;-use super::mls::{Decrypted, E2eePayload, MlsManager};-use super::{auth, device, mls, store, upload};-use base64::Engine;-use reqwest::Method;-use serde_json::{json, Value};-use sha2::{Digest, Sha256};-use std::path::PathBuf;--/// Refuses to run against anything but a throwaway instance unless told-/// otherwise. These tests create real accounts, and pointing them at a live-/// server litters it — which is exactly what happened to the production-/// instance before this guard existed.-fn allow_target(base: &str) -> bool {- if std::env::var_os("OMNIDISC_TEST_ALLOW_REMOTE").is_some() {- return true;- }- let local = base.contains("localhost") || base.contains("127.0.0.1") || base.contains("[::1]");- if !local {- eprintln!(- "refusing to run against {base}: it is not a local instance. Set \- OMNIDISC_TEST_ALLOW_REMOTE=1 if that is really what you want."- );- }- local-}--/// A password nobody can guess from the repository.-///-/// These tests register real accounts on whatever instance `OMNIDISC_TEST_URL`-/// points at, and a constant in a public repo is a working credential for every-/// account they ever left behind. One random value per process keeps the run-/// self-consistent without publishing a key.-fn test_password() -> &'static str {- static PASSWORD: std::sync::OnceLock<String> = std::sync::OnceLock::new();- PASSWORD.get_or_init(|| {- let nanos = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_nanos())- .unwrap_or(0);- format!(- "od-{}-{:x}-{:x}",- std::process::id(),- nanos,- nanos.rotate_left(29)- )- })-}--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, test_password(), 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");- if !allow_target(&base) {- return;- }- 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,- std::slice::from_ref(&bob.user_id),- 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,- std::slice::from_ref(&bob.user_id),- 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.rsdeleted file mode 100644index 43fe6a9e..00000000--- a/src-tauri/src/commands/omnidisc/gateway.rs+++ /dev/null@@ -1,611 +0,0 @@-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.rsdeleted file mode 100644index b658c2ee..00000000--- a/src-tauri/src/commands/omnidisc/mls.rs+++ /dev/null@@ -1,1374 +0,0 @@-//! 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.contains(&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.rsdeleted file mode 100644index 3addd81b..00000000--- a/src-tauri/src/commands/omnidisc/mod.rs+++ /dev/null@@ -1,187 +0,0 @@-pub mod api;-pub mod auth;-pub mod device;-pub mod ducking;-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.rsdeleted file mode 100644index 0b51242a..00000000--- a/src-tauri/src/commands/omnidisc/store.rs+++ /dev/null@@ -1,512 +0,0 @@-//! 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};-use std::sync::{Mutex, OnceLock};--pub const SERVICE: &str = "com.openselena.omniget.omnidisc";-#[cfg(any(target_os = "macos", windows))]-const LEGACY_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";-#[cfg(any(target_os = "macos", windows))]-const KEYRING_ENV: &str = "OMNIGET_OMNIDISC_KEYRING";--/// Whether to put secrets in the OS keyring at all.-///-/// A development build cannot hold a keychain grant: `tauri dev` produces an-/// unsigned binary that is rebuilt on every change, and macOS binds "Always-/// Allow" to the binary's identity, so the grant is void the next time you press-/// run. The prompt then returns on every launch and every read, no matter how-/// many times it is answered. Debug builds therefore use the encrypted file-/// store, and only release builds — signed, and stable across launches — use the-/// keyring. `OMNIGET_OMNIDISC_KEYRING=1` forces it on to exercise that path.-#[cfg(any(target_os = "macos", windows))]-fn use_keyring() -> bool {- match std::env::var(KEYRING_ENV) {- Ok(v) => matches!(v.trim(), "1" | "true" | "yes"),- Err(_) => !cfg!(debug_assertions),- }-}--/// Read-through cache so one launch asks the OS once per secret instead of once-/// per call. Every gateway reconnect and every authenticated request would-/// otherwise reach for the token again.-fn cache() -> &'static Mutex<HashMap<String, Option<String>>> {- static CACHE: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();- CACHE.get_or_init(|| Mutex::new(HashMap::new()))-}--/// The key carries the store the value came from, not just the account. The-/// integration tests give each side its own `OMNIGET_OMNIDISC_SESSION_DIR` and-/// switch between them in one process, so an account-only key would hand one-/// side the other's device key.-fn cache_key(account: &str) -> String {- match forced_dir() {- Some(dir) => format!("{}|{}", dir.display(), account),- None => format!("<default>|{account}"),- }-}--fn cache_put(account: &str, value: Option<String>) {- if let Ok(mut c) = cache().lock() {- c.insert(cache_key(account), value);- }-}--fn cache_get(account: &str) -> Option<Option<String>> {- cache()- .lock()- .ok()- .and_then(|c| c.get(&cache_key(account)).cloned())-}--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> {- cache_put(account, Some(value.to_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(hit) = cache_get(account) {- return Ok(hit);- }- if let Some(dir) = forced_dir() {- let found = FileStore::new(dir).get(account)?;- cache_put(account, found.clone());- return Ok(found);- }- match keyring_get(account) {- Some(Ok(found)) => {- if found.is_some() {- cache_put(account, found.clone());- return Ok(found);- }- }- Some(Err(e)) => tracing::warn!("[omnidisc] keyring read failed, using file store: {}", e),- None => {}- }- let found = FileStore::default_dir()?.get(account)?;- cache_put(account, found.clone());- Ok(found)-}--pub fn delete_secret(account: &str) -> Result<(), String> {- cache_put(account, None);- 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>> {- if !use_keyring() {- return None;- }- 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>> {- if !use_keyring() {- return None;- }- Some(keyring_entry(url).and_then(|e| match e.get_password() {- Ok(t) => Ok(Some(t)),- Err(keyring::Error::NoEntry) => {- if let Ok(legacy_e) = keyring::Entry::new(LEGACY_SERVICE, url) {- match legacy_e.get_password() {- Ok(t) => Ok(Some(t)),- Err(keyring::Error::NoEntry) => Ok(None),- Err(err) => Err(err.to_string()),- }- } else {- Ok(None)- }- }- Err(err) => Err(err.to_string()),- }))-}--#[cfg(any(target_os = "macos", windows))]-fn keyring_delete(url: &str) -> Option<Result<(), String>> {- if !use_keyring() {- return None;- }- if let Ok(legacy_e) = keyring::Entry::new(LEGACY_SERVICE, url) {- let _ = legacy_e.delete_credential();- }- 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)?;- 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.rsdeleted file mode 100644index bb05d522..00000000--- a/src-tauri/src/commands/omnidisc/stream.rs+++ /dev/null@@ -1,541 +0,0 @@-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::atomic::{AtomicU64, Ordering};-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>>,- preview_gen: AtomicU64,-}--impl Default for StreamManager {- fn default() -> Self {- Self {- active: Mutex::new(None),- viewers: Mutex::new(HashMap::new()),- preview_gen: AtomicU64::new(0),- }- }-}--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);-}--/// What this build can actually do with media, so the interface never has to-/// guess from the platform name.-#[derive(Debug, Clone, Copy, serde::Serialize)]-pub struct MediaCapabilities {- /// A voice backend was created at startup. False means calls are dead- /// weight in the UI and the entry points should say so.- pub voice: bool,- /// Screen capture exists for this platform. Whether the user has granted- /// the permission is a separate answer, and it belongs to the share dialog.- pub screen_share: bool,- /// Someone else's stream can be rendered into a window.- pub stream_viewer: bool,-}--#[tauri::command]-pub async fn omnidisc_media_capabilities(- state: tauri::State<'_, crate::AppState>,-) -> Result<MediaCapabilities, String> {- // Deliberately not probed by calling into the capture layer: on macOS the- // first enumeration is what raises the screen-recording prompt, and asking- // for that permission before the user has asked to share anything is the- // kind of thing that gets an app denied for good.- Ok(MediaCapabilities {- voice: state.omnidisc_voice.livekit_backend().is_some(),- screen_share: omnidisc_media::capture::SCREEN_CAPTURE_SUPPORTED,- stream_viewer: cfg!(any(target_os = "macos", target_os = "windows")),- })-}--#[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 preview_source = args.source.clone();- 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 gen = state- .omnidisc_stream- .preview_gen- .fetch_add(1, Ordering::SeqCst)- + 1;- spawn_preview(app.clone(), preview_source, gen);- 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 spawn_preview(app: tauri::AppHandle, source: SourceId, gen: u64) {- tauri::async_runtime::spawn(async move {- loop {- tokio::time::sleep(std::time::Duration::from_secs(3)).await;- let Some(state) = app.try_state::<crate::AppState>() else {- return;- };- if state.omnidisc_stream.preview_gen.load(Ordering::SeqCst) != gen {- return;- }- if state.omnidisc_stream.active.lock().await.is_none() {- return;- }- // The preview only exists so the sharer can see what they are- // sharing. Behind a game it is invisible, and a screenshot plus a- // JPEG encode every few seconds is exactly the kind of background- // cost that shows up as dropped frames.- let visible = app- .get_webview_window("main")- .and_then(|w| w.is_focused().ok())- .unwrap_or(true);- if !visible {- continue;- }- let src = source.clone();- let thumb =- tokio::task::spawn_blocking(move || omnidisc_media::capture::thumbnail_for(&src))- .await- .ok()- .flatten();- if let Some(image) = thumb {- let url = state.omnidisc_voice.session_info().await.map(|s| s.url);- emit_voice(&app, url, "stream_preview", json!({ "image": image }));- }- }- });-}--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)-}--/// Tear down the active publish without announcing anything: the caller is-/// already leaving the channel and the leave itself carries the flag change.-pub async fn stop_active_for_leave(state: &crate::AppState) {- state- .omnidisc_stream- .preview_gen- .fetch_add(1, Ordering::SeqCst);- 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);-}--#[tauri::command]-pub async fn omnidisc_stream_stop(- app: tauri::AppHandle,- state: tauri::State<'_, crate::AppState>,-) -> Result<(), String> {- state- .omnidisc_stream- .preview_gen- .fetch_add(1, Ordering::SeqCst);- 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 = match create_surface_on_main(&app, &window).await {- Ok(r) => r,- Err(e) => {- // A window that cannot draw anything is worse than no window: it- // looks like the stream is loading forever.- let _ = window.close();- publication.set_subscribed(false);- return Err(e);- }- };- 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()-}--/// The OS red-dot close bypasses `omnidisc_stream_unwatch`, and a `Viewer`-/// left behind blocks every later watch of the same user.-pub fn on_stream_window_destroyed(app: &tauri::AppHandle, label: &str) {- let Some(rest) = label.strip_prefix("omnidisc-stream-") else {- return;- };- let rest = rest.to_string();- let app = app.clone();- tauri::async_runtime::spawn(async move {- let Some(state) = app.try_state::<crate::AppState>() else {- return;- };- let removed = {- let mut viewers = state.omnidisc_stream.viewers.lock().await;- let key = viewers.keys().find(|k| sanitize(k) == rest).cloned();- key.and_then(|k| viewers.remove(&k).map(|_| k))- };- if let Some(user_id) = removed {- if let Some(b) = state.omnidisc_voice.livekit_backend() {- if let Some(p) = b.video_publication_for(&user_id) {- p.set_subscribed(false);- }- }- }- });-}--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}"))?;- 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(target_os = "windows")]- {- let hwnd = window.hwnd().map_err(|e| format!("OmniDisc: hwnd: {e}"))?.0 as isize;- let hinstance = window_hinstance(hwnd);- 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_win32_surface(hwnd, hinstance, 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(any(target_os = "macos", target_os = "windows")))]- {- let _ = (app, window, size);- Err(StreamError::Unsupported.code().to_string())- }-}--/// The module handle Vulkan asks for. DX12 ignores it, so a zero here only-/// costs the Vulkan backend, never the whole viewer.-#[cfg(target_os = "windows")]-fn window_hinstance(hwnd: isize) -> isize {- #[cfg(target_pointer_width = "64")]- {- use windows::Win32::Foundation::HWND;- use windows::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, GWLP_HINSTANCE};- unsafe { GetWindowLongPtrW(HWND(hwnd as *mut std::ffi::c_void), GWLP_HINSTANCE) }- }- #[cfg(not(target_pointer_width = "64"))]- {- let _ = hwnd;- 0- }-}--#[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.rsdeleted file mode 100644index 79312019..00000000--- a/src-tauri/src/commands/omnidisc/upload.rs+++ /dev/null@@ -1,1070 +0,0 @@-//! 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.rsdeleted file mode 100644index fc170529..00000000--- a/src-tauri/src/commands/omnidisc/voice.rs+++ /dev/null@@ -1,868 +0,0 @@-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;- }- super::ducking::opt_out_of_system_ducking();- 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(state: &crate::AppState) {- let manager = &state.omnidisc_voice;- let gateways = &state.omnidisc_gateways;- super::stream::stop_active_for_leave(state).await;- 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(&state).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).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())-}--/// Whether the OS actually handed us the push-to-talk key.-///-/// It can refuse: Windows gives a combination to the first process that asks-/// and answers everyone else with `ERROR_HOTKEY_ALREADY_REGISTERED`, and macOS-/// needs Accessibility permission. Both used to fail into a log line, so the-/// key simply did nothing and the app looked broken.-#[derive(Debug, Clone, Serialize)]-pub struct PttStatus {- pub binding: String,- pub registered: bool,-}--#[tauri::command]-pub async fn omnidisc_voice_ptt_status(app: tauri::AppHandle) -> Result<PttStatus, String> {- use tauri_plugin_global_shortcut::GlobalShortcutExt;- let binding = crate::storage::config::load_settings(&app)- .omnidisc- .voice- .ptt_key- .trim()- .to_string();- if binding.is_empty() {- return Ok(PttStatus {- binding,- registered: false,- });- }- let registered = binding- .parse::<tauri_plugin_global_shortcut::Shortcut>()- .map(|s| app.global_shortcut().is_registered(s))- .unwrap_or(false);- Ok(PttStatus {- binding,- registered,- })-}--#[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 3038f600..f98ef1cf 100644--- a/src-tauri/src/commands/settings.rs+++ b/src-tauri/src/commands/settings.rs@@ -16,7 +16,6 @@ pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSettlet 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();@@ -39,7 +38,6 @@ pub fn update_settings(app: tauri::AppHandle, partial: String) -> Result<AppSett|| 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);}diff --git a/src-tauri/src/hotkey.rs b/src-tauri/src/hotkey.rsindex 4f77401e..4b8eab6f 100644--- a/src-tauri/src/hotkey.rs+++ b/src-tauri/src/hotkey.rs@@ -8,8 +8,6 @@ pub fn reregister(app: &tauri::AppHandle) {if let Err(e) = app.global_shortcut().unregister_all() {tracing::warn!("Failed to unregister hotkeys: {}", e);}- #[cfg(windows)]- forget_held_ptt();register_from_settings(app);}@@ -25,89 +23,9 @@ 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");- }crate::commands::tools::desktop::register_tool_hotkeys(app);}-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;- }- #[cfg(windows)]- tame_key_repeat(app, *shortcut, pressed);- crate::commands::omnidisc::voice::ptt_from_hotkey(app, pressed);- true-}--/// Windows repeats `WM_HOTKEY` for as long as the key is down, and the-/// global-shortcut backend answers every repeat by spawning a thread that-/// busy-polls that key until it comes back up. A few seconds of push-to-talk-/// would therefore pile up dozens of spinning threads — a call that heats the-/// machine while you talk. Dropping the registration for the duration of the-/// hold stops the repeat at the source, and the release still arrives, because-/// the thread the first press spawned is already watching the key.-#[cfg(windows)]-fn tame_key_repeat(app: &tauri::AppHandle, shortcut: Shortcut, pressed: bool) {- use std::sync::atomic::Ordering;-- if !pressed {- restore_ptt_binding(app, shortcut);- return;- }- if PTT_HELD.swap(true, Ordering::AcqRel) {- return;- }- let generation = PTT_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;- if let Err(e) = app.global_shortcut().unregister(shortcut) {- tracing::debug!("[hotkey] could not pause the push-to-talk binding: {}", e);- }- // A release that never lands would leave the microphone open and the key- // unbound, so a hold gets an upper bound it can recover from.- let app = app.clone();- std::thread::spawn(move || {- std::thread::sleep(PTT_MAX_HOLD);- if PTT_GENERATION.load(Ordering::Acquire) != generation {- return;- }- tracing::warn!("[hotkey] push-to-talk stayed down too long; releasing it");- crate::commands::omnidisc::voice::ptt_from_hotkey(&app, false);- restore_ptt_binding(&app, shortcut);- });-}--#[cfg(windows)]-fn restore_ptt_binding(app: &tauri::AppHandle, shortcut: Shortcut) {- use std::sync::atomic::Ordering;-- if !PTT_HELD.swap(false, Ordering::AcqRel) {- return;- }- PTT_GENERATION.fetch_add(1, Ordering::AcqRel);- if let Err(e) = app.global_shortcut().register(shortcut) {- tracing::warn!("[hotkey] push-to-talk could not be re-armed: {}", e);- }-}--#[cfg(windows)]-fn forget_held_ptt() {- use std::sync::atomic::Ordering;-- PTT_HELD.store(false, Ordering::Release);- PTT_GENERATION.fetch_add(1, Ordering::AcqRel);-}--#[cfg(windows)]-static PTT_HELD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);-#[cfg(windows)]-static PTT_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);-#[cfg(windows)]-const PTT_MAX_HOLD: std::time::Duration = std::time::Duration::from_secs(30);-fn register_one(app: &tauri::AppHandle, binding: &str, label: &str) {match binding.parse::<Shortcut>() {Ok(shortcut) => {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 1adf6f78..89f2627f 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -202,11 +202,6 @@ 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)]@@ -265,11 +260,6 @@ 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()@@ -310,11 +300,7 @@ pub fn run() {.plugin(tauri_plugin_global_shortcut::Builder::new().with_handler(|app, shortcut, event| {- let pressed = event.state == tauri_plugin_global_shortcut::ShortcutState::Pressed;- if hotkey::handle_ptt(app, shortcut, pressed) {- return;- }- if pressed {+ if event.state == tauri_plugin_global_shortcut::ShortcutState::Pressed {hotkey::on_hotkey_pressed(app, shortcut);}})@@ -669,7 +655,6 @@ 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@@ -880,111 +865,11 @@ pub fn run() {api.prevent_close();let _ = window.hide();}- tauri::WindowEvent::Destroyed- if window.label().starts_with("omnidisc-stream-") =>- {- commands::omnidisc::stream::on_stream_window_destroyed(- &window.app_handle().clone(),- window.label(),- );- }_ => {}}).invoke_handler(tauri::generate_handler![local_bridge::media_stream_url,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::voice::omnidisc_voice_ptt_status,- commands::omnidisc::stream::omnidisc_media_capabilities,- 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/components/omnidisc/AttachmentStrip.svelte b/src/components/omnidisc/AttachmentStrip.sveltedeleted file mode 100644index 010bf898..00000000--- a/src/components/omnidisc/AttachmentStrip.svelte+++ /dev/null@@ -1,207 +0,0 @@-<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: none;- 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.sveltedeleted file mode 100644index 880dc43b..00000000--- a/src/components/omnidisc/ChannelList.svelte+++ /dev/null@@ -1,881 +0,0 @@-<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 {- 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 { isStreamer } from "$lib/stores/omnidisc-stream-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 homeMode = $derived(!page.url.pathname.startsWith("/omnidisc/g/"));- let guild = $derived(homeMode ? null : (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;-- interface ChannelGroup {- id: string;- category: string;- channels: OmnidiscChannel[];- }-- let groups = $derived.by(() => {- if (!guild) return [] as ChannelGroup[];- const map = new Map<string, ChannelGroup>();- for (const channel of guild.channels) {- if (channel.kind === "category") {- if (!map.has(channel.id)) map.set(channel.id, { id: channel.id, category: channel.name, channels: [] });- continue;- }- const key = channel.parentId ?? "";- const group = map.get(key) ?? { id: key, category: channel.category ?? "", channels: [] };- group.channels.push(channel);- map.set(key, group);- }- return [...map.values()];- });-- const COLLAPSED_KEY = "omnidisc.collapsed-categories";-- function loadCollapsed(): Record<string, boolean> {- try {- return JSON.parse(localStorage.getItem(COLLAPSED_KEY) ?? "{}") as Record<string, boolean>;- } catch {- return {};- }- }-- let collapsed = $state<Record<string, boolean>>(loadCollapsed());-- function toggleCategory(id: string) {- collapsed = { ...collapsed, [id]: !collapsed[id] };- try {- localStorage.setItem(COLLAPSED_KEY, JSON.stringify(collapsed));- } catch {- /* per-viewer convenience only */- }- }-- function visibleChannels(group: ChannelGroup): OmnidiscChannel[] {- if (!collapsed[group.id]) return group.channels;- return group.channels.filter(- (c) => c.id === selectedChannelId || isUnread(c.id) || getMentionCount(c.id) > 0,- );- }-- 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">{homeMode ? (instance?.name || $t("omnidisc.title")) : (guild?.name || instance?.name || $t("omnidisc.title"))}</h2>- {#if instance?.name && 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 homeMode && 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 !homeMode && 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.id)}- {#if group.category}- <button- type="button"- class="category cat-toggle"- aria-expanded={!collapsed[group.id]}- onclick={() => toggleCategory(group.id)}- >- <svg class="chev" class:closed={collapsed[group.id]} viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6" /></svg>- {group.category}- </button>- {/if}- <ul class="channels">- {#each visibleChannels(group) 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 m.streaming || isStreamer(m.userId)}<span class="live-mini">{$t("omnidisc.stream.live")}</span>{/if}- {#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: none;- }-- .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: none;- 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);- }-- .cat-toggle {- display: flex;- align-items: center;- gap: 4px;- width: calc(100% - var(--space-2) * 2);- padding: 0;- border: none;- background: none;- font: inherit;- font-size: var(--text-xs);- font-weight: 600;- text-align: left;- cursor: pointer;- }-- .cat-toggle:hover {- color: var(--text);- }-- .cat-toggle:focus-visible {- outline: var(--focus-ring);- outline-offset: var(--focus-ring-offset);- }-- .chev {- transition: transform 120ms ease;- flex-shrink: 0;- }-- .chev.closed {- transform: rotate(-90deg);- }-- @media (prefers-reduced-motion: reduce) {- .chev {- transition: none;- }- }-- .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;- }-- .live-mini {- flex: 0 0 auto;- font-size: 9px;- font-weight: 700;- letter-spacing: 0.04em;- color: var(--on-accent);- background: var(--danger);- padding: 0 4px;- border-radius: var(--radius-sm);- }-- .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: none;- 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: none;- 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: none;- 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: none;- 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.sveltedeleted file mode 100644index eee1cac9..00000000--- a/src/components/omnidisc/ChatView.svelte+++ /dev/null@@ -1,597 +0,0 @@-<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: none;- }-- .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: none;- 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: none;- 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.sveltedeleted file mode 100644index aa6eef29..00000000--- a/src/components/omnidisc/Composer.svelte+++ /dev/null@@ -1,496 +0,0 @@-<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: none;- 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: none;- 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: none;- 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: none;- 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.sveltedeleted file mode 100644index ff741db1..00000000--- a/src/components/omnidisc/ConnectInstanceForm.svelte+++ /dev/null@@ -1,553 +0,0 @@-<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: none;- 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: none;- }-- .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: none;- 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.sveltedeleted file mode 100644index d1c20b43..00000000--- a/src/components/omnidisc/EmojiPicker.svelte+++ /dev/null@@ -1,149 +0,0 @@-<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: none;- 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: none;- 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.sveltedeleted file mode 100644index f9c5c9c5..00000000--- a/src/components/omnidisc/IncomingCallBar.svelte+++ /dev/null@@ -1,146 +0,0 @@-<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: none;- 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.sveltedeleted file mode 100644index 052a08f5..00000000--- a/src/components/omnidisc/InstanceRail.svelte+++ /dev/null@@ -1,566 +0,0 @@-<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,- getGuildUnread,- createGuild,- joinInvite,- reconnectInstance,- resetConnect,- isImmersive,- toggleImmersive,- } 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 menuAnchor = $state<HTMLButtonElement | null>(null);- let menuEl = $state<HTMLDivElement | null>(null);- let menuPos = $state({ left: 0, bottom: 0 });-- // The rail scrolls, so it clips anything that leaves its 64px width. An- // absolutely positioned menu was being cut away entirely: the button looked- // dead because the menu it opened was never visible. Fixed positioning,- // measured from the button, escapes every clipping ancestor.- function toggleMenu() {- if (menuOpen) {- menuOpen = false;- return;- }- const rect = menuAnchor?.getBoundingClientRect();- if (rect) {- menuPos = { left: rect.right + 8, bottom: Math.max(8, window.innerHeight - rect.bottom) };- }- menuOpen = true;- }-- // A menu that only closes by pressing its own button reads as stuck.- $effect(() => {- if (!menuOpen) return;- const dismiss = (e: MouseEvent) => {- const target = e.target as Node | null;- if (menuAnchor && target && menuAnchor.contains(target)) return;- if (menuEl && target && menuEl.contains(target)) return;- menuOpen = false;- };- const reposition = () => (menuOpen = false);- window.addEventListener("pointerdown", dismiss, true);- window.addEventListener("resize", reposition);- return () => {- window.removeEventListener("pointerdown", dismiss, true);- window.removeEventListener("resize", reposition);- };- });- 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)}- {@const unread = getGuildUnread(guild.id)}- <button- type="button"- class="rail-item guild"- class:active={selectedGuildId === guild.id}- class:unread={unread.unread}- onclick={() => openGuild(guild)}- title={guild.name}- aria-label={guild.name}- aria-pressed={selectedGuildId === guild.id}- >- <span class="initials">{initials(guild.name)}</span>- {#if unread.mentions > 0}- <span class="mention-pill">{unread.mentions > 99 ? "99+" : unread.mentions}</span>- {:else if unread.unread}- <span class="unread-dot" aria-hidden="true"></span>- {/if}- </button>- {/each}- {/if}-- <div class="rail-spacer"></div>-- <button- type="button"- class="rail-action"- onclick={toggleImmersive}- title={isImmersive() ? $t("omnidisc.rail.immersive_exit") : $t("omnidisc.rail.immersive_enter")}- aria-label={isImmersive() ? $t("omnidisc.rail.immersive_exit") : $t("omnidisc.rail.immersive_enter")}- aria-pressed={isImmersive()}- >- {#if isImmersive()}- <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="M8 3v18M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />- </svg>- {:else}- <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="M8 3v18M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />- <path d="M13 9l3 3-3 3" />- </svg>- {/if}- </button>-- <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}- bind:this={menuAnchor}- onclick={toggleMenu}- >- <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}- bind:this={menuEl}- style="left: {menuPos.left}px; bottom: {menuPos.bottom}px;"- >- <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: none;- 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);- }-- .mention-pill {- position: absolute;- right: -4px;- bottom: -4px;- min-width: 16px;- height: 16px;- padding: 0 4px;- border-radius: var(--radius-full);- border: 2px solid var(--sidebar-bg);- background: var(--danger);- color: var(--on-accent);- font-size: 9px;- font-weight: 700;- line-height: 12px;- text-align: center;- }-- .unread-dot {- position: absolute;- right: -2px;- bottom: -2px;- width: 10px;- height: 10px;- border-radius: var(--radius-full);- border: 2px solid var(--sidebar-bg);- background: var(--text);- }-- .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: none;- 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: none;- }-- .rail-item.add:hover {- color: var(--accent);- border-color: var(--accent);- }-- .menu {- position: fixed;- z-index: 30;- display: flex;- flex-direction: column;- min-width: 200px;- padding: var(--space-1);- border-radius: var(--radius-md);- border: none;- 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.sveltedeleted file mode 100644index 26fbdd72..00000000--- a/src/components/omnidisc/MemberList.svelte+++ /dev/null@@ -1,318 +0,0 @@-<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: none;- }-- .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: none;- 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.sveltedeleted file mode 100644index 22fe74cd..00000000--- a/src/components/omnidisc/MessageAttachments.svelte+++ /dev/null@@ -1,359 +0,0 @@-<script lang="ts">- import { t } from "$lib/i18n";- import { translateBackendError } from "$lib/error-translate";- import { downloadAttachment } from "$lib/stores/omnidisc-store.svelte";- import { portal } from "$lib/omnidisc/popover";- import type { OmnidiscAttachment, OmnidiscMessage } from "$lib/omnidisc/types";-- let { message }: { message: OmnidiscMessage } = $props();-- let lightbox = $state<OmnidiscAttachment | null>(null);- let lightboxEl = $state<HTMLElement | null>(null);- let lightboxTrigger: HTMLElement | 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 ?? []);-- // Files die on a clock, so the clock has to be on screen. A minute-resolution- // tick is enough to keep the label honest without waking the UI constantly.- let now = $state(Date.now());- $effect(() => {- if (!items.some((a) => a.expiresAt && !a.expired)) return;- const timer = setInterval(() => (now = Date.now()), 30_000);- return () => clearInterval(timer);- });-- function isGone(a: OmnidiscAttachment): boolean {- return a.expired === true || (a.expiresAt !== undefined && a.expiresAt <= now);- }-- function expiryLabel(a: OmnidiscAttachment): string | null {- if (!a.expiresAt || isGone(a)) return null;- const minutes = Math.max(1, Math.round((a.expiresAt - now) / 60000));- return $t("omnidisc.attachments.expires_in", { minutes }) as string;- }-- 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 openLightbox(attachment: OmnidiscAttachment, trigger: HTMLElement) {- lightboxTrigger = trigger;- lightbox = attachment;- }-- function closeLightbox() {- lightbox = null;- lightboxTrigger?.focus();- lightboxTrigger = null;- }-- $effect(() => {- if (lightbox) lightboxEl?.focus();- });-- function onKeydown(e: KeyboardEvent) {- if (e.key === "Escape" && lightbox) {- e.preventDefault();- closeLightbox();- }- }-</script>--<svelte:window onkeydown={onKeydown} />--{#if items.length > 0}- <ul class="attachments">- {#each items as attachment (attachment.id)}- {@const kind = kindOf(attachment)}- {@const gone = isGone(attachment)}- <li class="item" class:media={kind === "image" && !gone}>- {#if gone}- <div class="file expired">- <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"><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 2" /></svg>- </span>- <span class="detail">- <span class="name" title={attachment.filename}>{attachment.filename}</span>- <span class="meta">{$t("omnidisc.attachments.expired")}</span>- </span>- </div>- {:else if kind === "image"}- <button- type="button"- class="image-button"- style:aspect-ratio={attachment.width && attachment.height- ? `${attachment.width} / ${attachment.height}`- : undefined}- onclick={(e) => openLightbox(attachment, e.currentTarget)}- 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}{#if expiryLabel(attachment)} · {expiryLabel(attachment)}{/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"- use:portal- bind:this={lightboxEl}- >- <img src={lightbox.url} alt={lightbox.filename} />- <button- type="button"- class="close"- onclick={closeLightbox}- 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: none;- 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: none;- border-radius: var(--radius-md);- background: var(--surface);- }-- .file.expired {- background: transparent;- border: 1px dashed var(--border);- color: var(--text-muted);- }-- .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: none;- 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.sveltedeleted file mode 100644index c2fba1da..00000000--- a/src/components/omnidisc/MessageItem.svelte+++ /dev/null@@ -1,872 +0,0 @@-<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 { placeMenu, portal } from "$lib/omnidisc/popover";- 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);- let actionsEl = $state<HTMLElement | null>(null);- let menuEl = $state<HTMLElement | null>(null);- let pickerEl = $state<HTMLElement | null>(null);- let menuBtn = $state<HTMLButtonElement | null>(null);- let pickerBtn = $state<HTMLButtonElement | null>(null);- let overlayPos = $state({ left: 0, top: 0 });- let placed = $state(false);-- $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 overlayNode(): HTMLElement | null {- return menuEl ?? pickerEl;- }-- function closeOverlays(restoreFocus = false) {- const trigger = menuOpen ? menuBtn : pickerOpen ? pickerBtn : null;- menuOpen = false;- pickerOpen = false;- placed = false;- if (restoreFocus) trigger?.focus();- }-- function place() {- const node = overlayNode();- const anchor = actionsEl?.getBoundingClientRect();- if (!node || !anchor) return;- const box = node.getBoundingClientRect();- overlayPos = placeMenu(- anchor,- { width: box.width, height: box.height },- { width: window.innerWidth, height: window.innerHeight },- );- placed = true;- }-- async function toggleOverlay(which: "menu" | "picker") {- const wasOpen = which === "menu" ? menuOpen : pickerOpen;- closeOverlays();- if (wasOpen) return;- if (which === "menu") menuOpen = true;- else pickerOpen = true;- await tick();- place();- if (which !== "menu") return;- await tick();- menuEl?.querySelector<HTMLButtonElement>("[role='menuitem']")?.focus();- }-- // The menu lives on the body, so nothing inside the message can be trusted to- // contain the click any more, and a scroll would leave it hanging in place.- $effect(() => {- if (!menuOpen && !pickerOpen) return;- const inside = (target: EventTarget | null): boolean =>- target instanceof Node && (overlayNode()?.contains(target) ?? false);- const dismiss = (e: PointerEvent) => {- if (inside(e.target)) return;- if (root && e.target instanceof Node && root.contains(e.target)) return;- closeOverlays();- };- const scrolled = (e: Event) => {- if (inside(e.target)) return;- closeOverlays();- };- const resized = () => closeOverlays();- window.addEventListener("pointerdown", dismiss, true);- window.addEventListener("scroll", scrolled, true);- window.addEventListener("resize", resized);- return () => {- window.removeEventListener("pointerdown", dismiss, true);- window.removeEventListener("scroll", scrolled, true);- window.removeEventListener("resize", resized);- };- });-- function react(emoji: string) {- closeOverlays(true);- 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>--{#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} bind:this={actionsEl}>- {#if canReact}- <button- type="button"- class="action"- bind:this={pickerBtn}- onclick={() => void toggleOverlay("picker")}- 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"- bind:this={menuBtn}- onclick={() => void toggleOverlay("menu")}- 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"- class:placed- use:portal- bind:this={pickerEl}- style="left: {overlayPos.left}px; top: {overlayPos.top}px;"- >- <EmojiPicker onPick={react} onClose={() => closeOverlays(true)} />- </div>- {/if}-- {#if menuOpen}- <div- class="overlay menu"- class:placed- role="menu"- tabindex="-1"- aria-label={$t("omnidisc.messages.more")}- use:portal- bind:this={menuEl}- style="left: {overlayPos.left}px; top: {overlayPos.top}px;"- onkeydown={(e) => { if (e.key === "Escape") closeOverlays(true); }}- >- {#if canPin}- <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(true); onTogglePin?.(message); }}>- {message.pinned ? $t("omnidisc.messages.unpin") : $t("omnidisc.messages.pin")}- </button>- {/if}- <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(true); onMarkUnread?.(message); }}>- {$t("omnidisc.messages.mark_unread")}- </button>- <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(true); onCopyLink?.(message); }}>- {$t("omnidisc.messages.copy_link")}- </button>- <button type="button" class="menu-item" role="menuitem" onclick={() => { closeOverlays(true); onCopyId?.(message); }}>- {$t("omnidisc.messages.copy_id")}- </button>- {#if canDelete}- <button type="button" class="menu-item danger" role="menuitem" onclick={() => { closeOverlays(true); 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: none;- 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: none;- 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: none;- 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: none;- 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: fixed;- z-index: 30;- }-- .overlay:not(.placed) {- visibility: hidden;- }-- .menu {- display: flex;- flex-direction: column;- min-width: 180px;- padding: var(--space-1);- border: none;- 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.sveltedeleted file mode 100644index 096a5194..00000000--- a/src/components/omnidisc/MessageList.svelte+++ /dev/null@@ -1,278 +0,0 @@-<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.sveltedeleted file mode 100644index 858815f8..00000000--- a/src/components/omnidisc/OmnidiscPrompt.svelte+++ /dev/null@@ -1,215 +0,0 @@-<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: none;- 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: none;- 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.sveltedeleted file mode 100644index c97ea09b..00000000--- a/src/components/omnidisc/PinsPanel.svelte+++ /dev/null@@ -1,263 +0,0 @@-<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: none;- }-- .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: none;- }-- .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: none;- 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.sveltedeleted file mode 100644index 4971f7e3..00000000--- a/src/components/omnidisc/ProfilePopover.svelte+++ /dev/null@@ -1,557 +0,0 @@-<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: none;- 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: none;- 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: none;- 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: none;- padding-top: var(--space-2);- }-- .btn {- flex: 1 1 auto;- padding: 6px var(--space-2);- border: none;- 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: none;- 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.sveltedeleted file mode 100644index fab9c1e4..00000000--- a/src/components/omnidisc/SearchPanel.svelte+++ /dev/null@@ -1,422 +0,0 @@-<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: none;- }-- .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: none;- 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: none;- 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.sveltedeleted file mode 100644index b95216d6..00000000--- a/src/components/omnidisc/ShareScreenDialog.svelte+++ /dev/null@@ -1,455 +0,0 @@-<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);- /// The Linux backend answers with a single placeholder because the portal- /// shows its own picker after "share" is pressed.- let portalPicker = $derived(- sources?.displays.length === 1 &&- sources.windows.length === 0 &&- sources.displays[0].title === "__omnidisc_portal_picker__",- );- 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 && portalPicker}- <!-- On Wayland an unprivileged app cannot enumerate windows: the- desktop's own dialog is the picker. Saying so beats drawing a grid- we cannot fill. -->- <section>- <h3>{$t("omnidisc.stream.pick_source")}</h3>- <p class="muted">{$t("omnidisc.stream.portal_picker")}</p>- </section>- {: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: none;- 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: none;- }- header h2 {- font-size: var(--text-lg);- color: var(--text);- }- footer {- justify-content: flex-end;- gap: var(--space-2);- border-top: none;- }- .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: none;- 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: none;- 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: none;- 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/StorageBanner.svelte b/src/components/omnidisc/StorageBanner.sveltedeleted file mode 100644index 06bbcb21..00000000--- a/src/components/omnidisc/StorageBanner.svelte+++ /dev/null@@ -1,99 +0,0 @@-<script lang="ts">- import { t } from "$lib/i18n";- import { getSelectedInstance, getStorage } from "$lib/stores/omnidisc-store.svelte";-- // A wipe that arrives unannounced reads as data loss. Warning early — while- // there is still room — is what turns the policy into something people can- // act on instead of something that happens to them.- let instance = $derived(getSelectedInstance());- let storage = $derived(getStorage(instance?.id ?? null));- let dismissed = $state<string | null>(null);- let key = $derived(storage ? `${storage.level}:${storage.purgedFiles ?? 0}` : null);- let visible = $derived(- !!storage && storage.level !== "ok" && key !== null && dismissed !== key,- );-- function percent(ratio: number): number {- return Math.min(100, Math.round(ratio * 100));- }-- function minutes(seconds: number): number {- return Math.max(1, Math.round(seconds / 60));- }-</script>--{#if visible && storage}- <div- class="storage-banner"- class:critical={storage.level !== "warning"}- role={storage.level === "warning" ? "status" : "alert"}- >- <span class="text">- {#if storage.level === "purged"}- {$t("omnidisc.storage.purged", { count: storage.purgedFiles ?? 0 })}- {:else if storage.level === "critical"}- {$t("omnidisc.storage.critical", { percent: percent(storage.ratio) })}- {:else}- {$t("omnidisc.storage.warning", {- percent: percent(storage.ratio),- minutes: minutes(storage.attachmentTtlSeconds),- })}- {/if}- </span>- <button- type="button"- class="dismiss"- onclick={() => (dismissed = key)}- aria-label={$t("common.dismiss")}- >- <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="M18 6L6 18M6 6l12 12" /></svg>- </button>- </div>-{/if}--<style>- .storage-banner {- display: flex;- align-items: center;- gap: var(--space-2);- padding: var(--space-2) var(--space-3);- background: color-mix(in srgb, var(--warning) 16%, var(--surface));- border-bottom: 1px solid color-mix(in srgb, var(--warning) 40%, var(--border));- color: var(--text);- font-size: var(--text-sm);- line-height: 1.4;- }-- .storage-banner.critical {- background: color-mix(in srgb, var(--danger) 16%, var(--surface));- border-bottom-color: color-mix(in srgb, var(--danger) 40%, var(--border));- }-- .text {- flex: 1;- min-width: 0;- }-- .dismiss {- flex: 0 0 auto;- display: grid;- place-items: center;- width: 24px;- height: 24px;- border: none;- border-radius: var(--radius-sm);- background: transparent;- color: var(--text-muted);- cursor: pointer;- }-- .dismiss:hover {- color: var(--text);- background: var(--surface-hi);- }-- .dismiss:focus-visible {- outline: var(--focus-ring);- outline-offset: var(--focus-ring-offset);- }-</style>diff --git a/src/components/omnidisc/VirtualList.svelte b/src/components/omnidisc/VirtualList.sveltedeleted file mode 100644index 6e1b9c84..00000000--- a/src/components/omnidisc/VirtualList.svelte+++ /dev/null@@ -1,258 +0,0 @@-<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.sveltedeleted file mode 100644index 4b7feeb2..00000000--- a/src/components/omnidisc/VoiceBar.svelte+++ /dev/null@@ -1,501 +0,0 @@-<script lang="ts">- import { goto } from "$app/navigation";- import { t } from "$lib/i18n";- import { translateBackendError } from "$lib/error-translate";- import { formatBinding } 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,- getMediaCapabilities,- } 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(formatBinding(pttKey));- let canShare = $derived(getMediaCapabilities().screen_share);-- 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" || !canShare}- title={canShare ? undefined : $t("omnidisc.error.stream_unsupported")}- >- <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>- {#if !publishing && !canShare}- <p class="note quiet">{$t("omnidisc.error.stream_unsupported")}</p>- {/if}-- <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: none;- 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: none;- 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: none;- 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.quiet {- color: var(--text-muted);- padding: 0 var(--space-2);- }-- .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: none;- 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.sveltedeleted file mode 100644index 29d7cb25..00000000--- a/src/components/omnidisc/VoiceChannelView.svelte+++ /dev/null@@ -1,498 +0,0 @@-<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,- getMediaCapabilities,- isStreamer,- getStreamPreview,- } 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 canWatch = $derived(getMediaCapabilities().stream_viewer);- 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 || isStreamer(userId) || (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 || !canWatch}- title={canWatch ? undefined : $t("omnidisc.stream.watch_unsupported")}- >- {watching ? $t("omnidisc.stream.stop_watching") : $t("omnidisc.stream.watch")}- </button>- {#if !canWatch}- <span class="watch-note">{$t("omnidisc.stream.watch_unsupported")}</span>- {/if}- {#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}- {@const preview = getStreamPreview()}- {#if preview}- <img class="self-preview" src={preview} alt={$t("omnidisc.stream.preview_alt")} />- {/if}- <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: none;- }-- .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);- }-- .watch-note {- font-size: var(--text-xs);- color: var(--text-muted);- text-align: center;- line-height: 1.4;- }-- .res-badge {- font-size: var(--text-xs);- color: var(--text-muted);- font-variant-numeric: tabular-nums;- text-align: center;- }-- .you-live {- color: var(--danger);- }-- .self-preview {- width: 100%;- border-radius: var(--radius-sm);- border: none;- display: block;- }-- .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: none;- 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: none;- 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.sveltedeleted file mode 100644index 6ee2fb12..00000000--- a/src/components/omnidisc/VoiceSettings.svelte+++ /dev/null@@ -1,396 +0,0 @@-<script lang="ts">- import { onDestroy, onMount } from "svelte";- import { t } from "$lib/i18n";- import { translateBackendError } from "$lib/error-translate";- import { formatBinding, isMac } 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,- isMicSilent,- isPttRegistered,- refreshPttStatus,- } 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 pttRefused = $derived(!!voice.ptt_key && isPttRegistered() === false);- 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 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();- void refreshPttStatus();- 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 || isMicSilent())}- <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 pttRefused}- <span class="setting-path refused" role="status">- {$t("omnidisc.voice.ptt_refused")}- {isMac() ? $t("omnidisc.voice.ptt_permission_hint") : $t("omnidisc.voice.ptt_conflict_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);- }-- .setting-path.refused {- color: var(--warning);- white-space: normal;- overflow: visible;- text-overflow: clip;- line-height: 1.45;- max-width: 52ch;- margin-top: var(--space-1);- }-- .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.sveltedeleted file mode 100644index ae11df78..00000000--- a/src/components/omnidisc/settings/DevicesSettings.svelte+++ /dev/null@@ -1,320 +0,0 @@-<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: none;- }-- .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: none;- 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.sveltedeleted file mode 100644index 06ece6a5..00000000--- a/src/components/omnidisc/settings/GuildAuditLog.svelte+++ /dev/null@@ -1,214 +0,0 @@-<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: none;- 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: none;- }-- .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.sveltedeleted file mode 100644index 42868be3..00000000--- a/src/components/omnidisc/settings/GuildBans.svelte+++ /dev/null@@ -1,209 +0,0 @@-<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: none;- }-- .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: none;- 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.sveltedeleted file mode 100644index 714a4f3c..00000000--- a/src/components/omnidisc/settings/GuildChannels.svelte+++ /dev/null@@ -1,508 +0,0 @@-<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: none;- 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: none;- 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.sveltedeleted file mode 100644index d297a198..00000000--- a/src/components/omnidisc/settings/GuildInvites.svelte+++ /dev/null@@ -1,208 +0,0 @@-<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: none;- 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: none;- 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: none;- 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.sveltedeleted file mode 100644index 43afea56..00000000--- a/src/components/omnidisc/settings/GuildRoles.svelte+++ /dev/null@@ -1,446 +0,0 @@-<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: none;- 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: none;- 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: none;- 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.sveltedeleted file mode 100644index 5ee7abe1..00000000--- a/src/components/omnidisc/settings/ProfileSettings.svelte+++ /dev/null@@ -1,389 +0,0 @@-<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: none;- 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: none;- 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: none;- 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: none;- 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: none;- 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.sveltedeleted file mode 100644index e617a024..00000000--- a/src/components/omnidisc/settings/SessionsSettings.svelte+++ /dev/null@@ -1,278 +0,0 @@-<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: none;- }-- .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: none;- 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 ff04aef9..bff643a7 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" | "omnidisc" | "debug";+ type AdvancedDrill = "performance" | "torrent" | "expert" | "league" | "debug";let subView = $state<AdvancedDrill | null>(null);let settings = $derived(getSettings());@@ -26,7 +26,6 @@{ 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" },];@@ -322,16 +321,6 @@</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 ?? true} onclick={() => updateSettings({ omnidisc: { enabled: !(settings.omnidisc?.enabled ?? true) } })} role="switch" aria-checked={settings.omnidisc?.enabled ?? true} 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 633cdd69..c6c7dc9d 100644--- a/src/components/shell/AppSidebar.svelte+++ b/src/components/shell/AppSidebar.svelte@@ -11,7 +11,6 @@pluginNav?: NavItem[];badgeLabel?: string;badgeCount?: number;- chatBadgeCount?: number;}let {@@ -20,11 +19,9 @@pluginNav = [],badgeLabel = "",badgeCount = 0,- chatBadgeCount = 0,}: Props = $props();let updateInfo = $derived(getUpdateInfo());- let chatBadgeLabel = $derived(chatBadgeCount > 99 ? "99+" : String(chatBadgeCount));const PLUGINS_KEY = "omniget.sidebar.plugins_expanded";let pluginsExpanded = $state(@@ -62,8 +59,6 @@<span class="mac-nav-label">{title}</span>{#if item.badge === "downloads" && badgeCount > 0}<span class="mac-nav-badge live">{badgeLabel}</span>- {:else if item.badge === "omnidisc" && chatBadgeCount > 0}- <span class="mac-nav-badge live">{chatBadgeLabel}</span>{:else if item.href === "/settings" && updateInfo.available}<span class="mac-nav-badge live update-badge">UPDATE</span>{/if}diff --git a/src/components/shell/AppToolbar.svelte b/src/components/shell/AppToolbar.svelteindex 802f05c9..993541eb 100644--- a/src/components/shell/AppToolbar.svelte+++ b/src/components/shell/AppToolbar.svelte@@ -15,7 +15,6 @@if (path.startsWith("/marketplace")) return $t("nav.marketplace");if (path.startsWith("/settings")) return $t("nav.settings");if (path.startsWith("/about")) return $t("nav.about");- if (path.startsWith("/omnidisc")) return $t("nav.omnidisc");if (path.startsWith("/league")) return $t("league.nav");if (path.startsWith("/courses")) return $t("courses.title");if (path.startsWith("/convert")) return $t("convert.title");diff --git a/src/lib/error-translate.ts b/src/lib/error-translate.tsindex 2969b6a6..4beee3dc 100644--- a/src/lib/error-translate.ts+++ b/src/lib/error-translate.ts@@ -44,80 +44,6 @@ 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",};/**@@ -151,12 +77,6 @@ export function translateBackendError(if (stripped.startsWith("ERR_PLUGIN_OUTDATED")) return t("errors.plugin_outdated");- 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 d3045763..77e84c5f 100644--- a/src/lib/i18n/el.json+++ b/src/lib/i18n/el.json@@ -476,7 +476,6 @@"marketplace": "Marketplace","settings": "Ρυθμίσεις","about": "Σχετικά",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "Θα βλέπετε τέτοιες ειδοποιήσεις όταν τα δέματά σας αλλάζουν κατάσταση."}},- "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": "Σύνδεση χωρίς κρυπτογράφηση"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex 1b8adb03..467732d3 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -476,7 +476,6 @@"marketplace": "Marketplace","settings": "Settings","about": "About",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.jsonindex 9287a9ce..bd597a22 100644--- a/src/lib/i18n/es.json+++ b/src/lib/i18n/es.json@@ -476,7 +476,6 @@"marketplace": "Marketplace","settings": "Configuración","about": "Acerca de",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "Verás notificaciones así cuando tus paquetes cambien de estado."}},- "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"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/fa.json b/src/lib/i18n/fa.jsonindex e1ee1aef..9191d6eb 100644--- a/src/lib/i18n/fa.json+++ b/src/lib/i18n/fa.json@@ -476,7 +476,6 @@"marketplace": "فروشگاه","settings": "تنظیمات","about": "درباره",- "omnidisc": "گفتگو","section_primary": "اصلی","section_app": "برنامه","section_plugins": "افزونهها",@@ -5697,818 +5696,6 @@"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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp موجود نیست، بنابراین دانلودها شروع نمیشوند. آن را از تنظیمات نصب کنید.","open_settings": "باز کردن تنظیمات",diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.jsonindex 9107bc04..3797a5ca 100644--- a/src/lib/i18n/fr.json+++ b/src/lib/i18n/fr.json@@ -476,7 +476,6 @@"marketplace": "Marketplace","settings": "Paramètres","about": "À propos",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "Vous verrez ce type de notification lorsque vos colis évoluent."}},- "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"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.jsonindex 8250dbf9..49404bf6 100644--- a/src/lib/i18n/it.json+++ b/src/lib/i18n/it.json@@ -476,7 +476,6 @@"marketplace": "Marketplace","settings": "Impostazioni","about": "Info",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "Vedrai notifiche come questa quando i tuoi pacchi cambiano stato."}},- "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"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.jsonindex 5f9126ee..149bc082 100644--- a/src/lib/i18n/ja.json+++ b/src/lib/i18n/ja.json@@ -476,7 +476,6 @@"marketplace": "マーケットプレイス","settings": "設定","about": "このアプリについて",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "荷物のステータスが変わると、このような通知が表示されます。"}},- "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": "暗号化されていない接続"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.tsindex 88bb501c..d7e9430d 100644--- a/src/lib/i18n/keys.ts+++ b/src/lib/i18n/keys.ts@@ -965,7 +965,6 @@ export type TranslationKeys =| 'nav.expand_plugins'| 'nav.home'| 'nav.marketplace'- | 'nav.omnidisc'| 'nav.section_app'| 'nav.section_plugins'| 'nav.section_primary'@@ -1116,755 +1115,6 @@ export type TranslationKeys =| 'omnibox.unsupported'| 'omnibox.view_formats'- | 'omnidisc.attachments.close_image'- | 'omnidisc.attachments.download'- | 'omnidisc.attachments.downloading'- | 'omnidisc.attachments.encrypted_note'- | 'omnidisc.attachments.expired'- | 'omnidisc.attachments.expires_in'- | '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.immersive_enter'- | 'omnidisc.rail.immersive_exit'- | '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.storage.critical'- | 'omnidisc.storage.purged'- | 'omnidisc.storage.retention_note'- | 'omnidisc.storage.warning'- | '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.portal_picker'- | 'omnidisc.stream.preview_alt'- | '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.watch_unsupported'- | '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_conflict_hint'- | '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.ptt_refused'- | '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/lo.json b/src/lib/i18n/lo.jsonindex 5dcdcd60..f6aa8cb3 100644--- a/src/lib/i18n/lo.json+++ b/src/lib/i18n/lo.json@@ -476,7 +476,6 @@"marketplace": "ຕະຫຼາດ","settings": "ການຕັ້ງຄ່າ","about": "ກ່ຽວກັບ",- "omnidisc": "ແຊັດ","section_primary": "ຫຼັກ","section_app": "ແອັບ","section_plugins": "ປລັກອິນ",@@ -5697,818 +5696,6 @@"test_body": "ທ່ານຈະເຫັນການແຈ້ງເຕືອນແບບນີ້ເມື່ອພັດສະດຸຂອງທ່ານເຄື່ອນທີ່."}},- "omnidisc": {- "title": "ແຊັດ",- "settings_title": "ແຊັດ (OmniDisc) — ທົດລອງ",- "settings_desc": "ແຊັດໃນຕົວສຳລັບເຊີບເວີ OmniDisc ທີ່ໂຮສເອງ. ປິດໄວ້ຕາມຄ່າເລີ່ມຕົ້ນ.",- "settings_enable": "ສະແດງເມນູແຊັດ",- "settings_enable_desc": "ເພີ່ມລາຍການແຊັດໃນແຖບຂ້າງ. ບໍ່ມີການເຊື່ອມຕໍ່ຈົນກວ່າທ່ານຈະເພີ່ມເຊີບເວີ.",- "disabled_title": "ແຊັດປິດຢູ່",- "disabled_body": "ເປີດໃຊ້ໃນ ການຕັ້ງຄ່າ → ຂັ້ນສູງ → ແຊັດ (OmniDisc). ບໍ່ມີຫຍັງເຮັດວຽກຈົນກວ່າທ່ານຈະເປີດ.",- "open_settings": "ເປີດການຕັ້ງຄ່າ",- "connect": {- "title": "ເຊື່ອມຕໍ່ກັບເຊີບເວີ",- "subtitle": "ວາງລິ້ງເຊີນທີ່ໝູ່ສົ່ງໃຫ້ທ່ານ ຫຼື ທີ່ຢູ່ເຊີບເວີ.",- "url_label": "ທີ່ຢູ່ເຊີບເວີ",- "url_placeholder": "https://chat.example.org",- "url_required": "ປ້ອນທີ່ຢູ່ເຊີບເວີເພື່ອສືບຕໍ່.",- "invite_label": "ລະຫັດເຊີນ (ບໍ່ບັງຄັບ)",- "invite_placeholder": "ວາງລະຫັດຈາກລິ້ງ",- "submit": "ເຊື່ອມຕໍ່",- "submitting": "ກຳລັງເຊື່ອມຕໍ່…",- "step_connecting": "ກຳລັງເຊື່ອມຕໍ່ກັບເຊີບເວີ",- "step_authenticating": "ກຳລັງເຂົ້າສູ່ລະບົບ",- "step_syncing": "ກຳລັງຊິງຄ໌ຊ່ອງ",- "error_title": "ເຊື່ອມຕໍ່ບໍ່ໄດ້",- "retry": "ລອງໃໝ່",- "success_title": "ເຊື່ອມຕໍ່ກັບ {{name}} ແລ້ວ",- "success_body": "ເລືອກຊ່ອງທາງຊ້າຍເພື່ອເລີ່ມແຊັດ.",- "open": "ເປີດແຊັດ",- "add_another": "ເພີ່ມເຊີບເວີອື່ນ",- "demo": "ໃຊ້ຂໍ້ມູນຕົວຢ່າງ",- "step_auth": "ກຳລັງເຂົ້າສູ່ລະບົບ",- "auth_title": "ເຂົ້າສູ່ລະບົບ {{name}}",- "auth_body": "ບັນຊີຂອງທ່ານມີຢູ່ໃນເຊີບເວີນີ້ເທົ່ານັ້ນ. ສ້າງບັນຊີໃໝ່ຢູ່ນີ້ ຫຼື ໃຊ້ບັນຊີທີ່ມີຢູ່ແລ້ວ.",- "mode_register": "ສ້າງບັນຊີ",- "mode_login": "ຂ້ອຍມີບັນຊີແລ້ວ",- "username_label": "ຊື່ຜູ້ໃຊ້",- "username_placeholder": "ເຊັ່ນ ana",- "username_hint": "2–32 ຕົວອັກສອນ: ຕົວອັກສອນ, ຕົວເລກ, _ . -",- "password_label": "ລະຫັດຜ່ານ",- "password_hint": "ຢ່າງໜ້ອຍ 8 ຕົວອັກສອນ.",- "display_name_label": "ຊື່ທີ່ສະແດງ (ບໍ່ບັງຄັບ)",- "display_name_placeholder": "ຊື່ທີ່ຄົນອື່ນຈະເຫັນ",- "register_submit": "ສ້າງບັນຊີ ແລະ ເຂົ້າຮ່ວມ",- "login_submit": "ເຂົ້າສູ່ລະບົບ",- "auth_required": "ປ້ອນຊື່ຜູ້ໃຊ້ ແລະ ລະຫັດຜ່ານເພື່ອສືບຕໍ່.",- "registration_closed": "ເຊີບເວີນີ້ຮັບບັນຊີໃໝ່ຜ່ານລິ້ງເຊີນເທົ່ານັ້ນ. ເຂົ້າສູ່ລະບົບ ຫຼື ກັບຄືນໄປເພີ່ມລະຫັດເຊີນ.",- "change_server": "ໃຊ້ເຊີບເວີອື່ນ",- "invite_noted": "ບັນທຶກລະຫັດເຊີນແລ້ວ — ທ່ານຈະເຂົ້າຮ່ວມເຊີບເວີນັ້ນຫຼັງຈາກເຂົ້າສູ່ລະບົບ.",- "insecure": "ເຊີບເວີນີ້ເຊື່ອມຕໍ່ຜ່ານ http ທຳມະດາ. ລະຫັດຜ່ານ ແລະ ທຸກຢ່າງທີ່ທ່ານສົ່ງຢູ່ນີ້ບໍ່ໄດ້ຖືກເຂົ້າລະຫັດ — ໃຜກໍໄດ້ໃນເຄືອຂ່າຍລະຫວ່າງທ່ານກັບເຊີບເວີສາມາດອ່ານໄດ້.",- "insecure_short": "ການເຊື່ອມຕໍ່ບໍ່ເຂົ້າລະຫັດ"- },- "home": {- "pick_channel_title": "ເລືອກຊ່ອງ",- "pick_channel_body": "ເລືອກເຊີບເວີທາງຊ້າຍ, ຈາກນັ້ນເລືອກຊ່ອງ ເພື່ອເລີ່ມແຊັດ."- },- "rail": {- "home": "ໜ້າຫຼັກແຊັດ",- "add_server": "ເພີ່ມເຊີບເວີ",- "status_connected": "ເຊື່ອມຕໍ່ແລ້ວ",- "status_connecting": "ກຳລັງເຊື່ອມຕໍ່",- "status_disconnected": "ຕັດການເຊື່ອມຕໍ່",- "status_error": "ເຊື່ອມຕໍ່ບໍ່ສຳເລັດ",- "status_reconnecting": "ກຳລັງເຊື່ອມຕໍ່ຄືນ",- "status_signed_out": "ອອກຈາກລະບົບແລ້ວ",- "menu": "ເພີ່ມ ຫຼື ສ້າງ",- "create_server": "ສ້າງເຊີບເວີ",- "join_invite": "ເຂົ້າຮ່ວມດ້ວຍລິ້ງເຊີນ",- "add_instance": "ເຊື່ອມຕໍ່ເຊີບເວີອື່ນ",- "sign_in": "ເຂົ້າສູ່ລະບົບອີກຄັ້ງ",- "reconnect": "ເຊື່ອມຕໍ່ຄືນ",- "remove": "ລືມເຊີບເວີນີ້",- "insecure": "{{name}} — ການເຊື່ອມຕໍ່ບໍ່ເຂົ້າລະຫັດ (http)",- "immersive_enter": "ໂໝດໂຟກັສ — ເຊື່ອງແຖບຂ້າງຂອງແອັບ",- "immersive_exit": "ອອກຈາກໂໝດໂຟກັສ — ສະແດງແຖບຂ້າງຂອງແອັບ"- },- "channels": {- "title": "ຊ່ອງ",- "empty": "ຍັງບໍ່ມີຊ່ອງ",- "empty_hint": "ເຊີບເວີຍັງບໍ່ໄດ້ແບ່ງປັນຊ່ອງໃດໃຫ້ທ່ານ.",- "not_found": "ບໍ່ພົບຊ່ອງ",- "not_found_hint": "ມັນອາດຖືກລຶບແລ້ວ ຫຼື ທ່ານບໍ່ມີສິດເຂົ້າເຖິງອີກຕໍ່ໄປ. ເລືອກຊ່ອງອື່ນທາງຊ້າຍ.",- "voice_soon": "ຊ່ອງສຽງ",- "voice_soon_hint": "ເຂົ້າຮ່ວມຈາກລາຍການທາງຊ້າຍ ຫຼື ດ້ວຍປຸ່ມຂ້າງລຸ່ມ.",- "dms": "ຂໍ້ຄວາມສ່ວນຕົວ",- "no_dms": "ຍັງບໍ່ມີຂໍ້ຄວາມສ່ວນຕົວ. ເລືອກສະມາຊິກທາງຂວາເພື່ອເລີ່ມ.",- "no_guilds": "ທ່ານຍັງບໍ່ໄດ້ຢູ່ໃນເຊີບເວີໃດຢູ່ນີ້.",- "no_guilds_hint": "ສ້າງເຊີບເວີ ຫຼື ເຂົ້າຮ່ວມດ້ວຍລິ້ງເຊີນ ໂດຍໃຊ້ປຸ່ມ + ທາງຊ້າຍ."- },- "members": {- "title": "ສະມາຊິກ",- "online": "ອອນລາຍ — {{count}}",- "offline": "ອອບລາຍ — {{count}}",- "empty": "ຍັງບໍ່ມີໃຜຢູ່ນີ້",- "show": "ສະແດງສະມາຊິກ",- "hide": "ເຊື່ອງສະມາຊິກ",- "message": "ສົ່ງຂໍ້ຄວາມຫາ {{name}}",- "owner": "ເຈົ້າຂອງ"- },- "messages": {- "empty_title": "ຍັງບໍ່ມີຂໍ້ຄວາມ",- "empty_body": "ທັກທາຍເລີຍ — ທ່ານຈະເປັນຄົນທຳອິດຢູ່ນີ້.",- "loading": "ກຳລັງໂຫຼດຂໍ້ຄວາມ…",- "today": "ມື້ນີ້",- "yesterday": "ມື້ວານ",- "you": "ທ່ານ",- "pending": "ກຳລັງສົ່ງ…",- "failed": "ບໍ່ໄດ້ສົ່ງ.",- "retry": "ລອງໃໝ່",- "discard": "ຍົກເລີກ",- "edited": "(ແກ້ໄຂແລ້ວ)",- "typing_one": "{{name}} ກຳລັງພິມ…",- "typing_two": "{{a}} ແລະ {{b}} ກຳລັງພິມ…",- "typing_many": "ຫຼາຍຄົນກຳລັງພິມ…",- "unknown_user": "ຜູ້ໃຊ້ທີ່ບໍ່ຮູ້ຈັກ",- "new_messages": "ຂໍ້ຄວາມໃໝ່",- "reply_unavailable": "ຂໍ້ຄວາມຕົ້ນສະບັບບໍ່ໄດ້ຖືກໂຫຼດ",- "pinned": "ປັກໝຸດແລ້ວ",- "edit_label": "ແກ້ໄຂຂໍ້ຄວາມ",- "edit_save": "ບັນທຶກ",- "react": "ເພີ່ມການຕອບສະໜອງ",- "reply": "ຕອບກັບ",- "edit": "ແກ້ໄຂ",- "more": "ການກະທຳເພີ່ມເຕີມ",- "pin": "ປັກໝຸດໃນຊ່ອງ",- "unpin": "ຖອນປັກໝຸດ",- "mark_unread": "ໝາຍວ່າຍັງບໍ່ໄດ້ອ່ານຈາກນີ້",- "copy_link": "ສຳເນົາລິ້ງຂໍ້ຄວາມ",- "copy_id": "ສຳເນົາ ID ຂໍ້ຄວາມ",- "delete": "ລຶບຂໍ້ຄວາມ",- "delete_title": "ລຶບຂໍ້ຄວາມນີ້ບໍ່?",- "delete_body": "ມັນຈະຫາຍໄປສຳລັບທຸກຄົນໃນຊ່ອງ. ບໍ່ສາມາດຍົກເລີກໄດ້.",- "delete_confirm": "ລຶບຂໍ້ຄວາມ",- "delete_no_text": "(ບໍ່ມີຂໍ້ຄວາມ)",- "copy_failed": "ຄລິບບອດບໍ່ພ້ອມໃຊ້ງານ. ກະລຸນາສຳເນົາດ້ວຍຕົນເອງ.",- "jump_present": "ໄປທີ່ປັດຈຸບັນ",- "reaction_add": "ຕອບສະໜອງດ້ວຍ {{emoji}}",- "reaction_remove": "ລຶບ {{emoji}} ຂອງທ່ານ"- },- "composer": {- "placeholder": "ຂໍ້ຄວາມຫາ #{{channel}}",- "send": "ສົ່ງ",- "hint": "Enter ເພື່ອສົ່ງ · Shift+Enter ເພື່ອຂຶ້ນແຖວໃໝ່",- "replying_to": "ກຳລັງຕອບກັບ {{name}}",- "cancel_reply": "ຍົກເລີກການຕອບກັບ",- "attach": "ແນບໄຟລ໌",- "drop_here": "ວາງເພື່ອແນບ",- "uploading_wait": "ລໍຖ້າໃຫ້ໄຟລ໌ອັບໂຫຼດສຳເລັດກ່ອນ"- },- "dm": {- "title": "ຂໍ້ຄວາມສ່ວນຕົວ",- "placeholder": "ຂໍ້ຄວາມຫາ {{name}}",- "not_found": "ບໍ່ພົບການສົນທະນາ",- "not_found_hint": "ມັນອາດຖືກປິດແລ້ວ ຫຼື ເຊີບເວີນີ້ບໍ່ໄດ້ເຊື່ອມຕໍ່ຢູ່ໃນຕອນນີ້."- },- "error": {- "unreachable": "ເຊີບເວີບໍ່ຕອບສະໜອງ. ກວດສອບທີ່ຢູ່ ຫຼື ຂໍລິ້ງໃໝ່ຈາກເຈົ້າຂອງ.",- "invalid_url": "ທີ່ຢູ່ນັ້ນເບິ່ງຄືບໍ່ຖືກຕ້ອງ. ໃຊ້ http:// ຫຼື https:// ໂດຍບໍ່ມີຊື່ຜູ້ໃຊ້ ຫຼື ລະຫັດຜ່ານ.",- "not_an_instance": "ບໍ່ມີເຊີບເວີ OmniDisc ຢູ່ທີ່ຢູ່ນີ້. ກວດສອບລິ້ງກັບຜູ້ທີ່ສົ່ງມາ.",- "unauthorized": "ເຊດຊັນຂອງທ່ານໃນເຊີບເວີນີ້ໝົດອາຍຸແລ້ວ. ເຂົ້າສູ່ລະບົບອີກຄັ້ງ.",- "no_session": "ທ່ານອອກຈາກລະບົບເຊີບເວີນີ້ແລ້ວ. ເຂົ້າສູ່ລະບົບເພື່ອສືບຕໍ່.",- "forbidden": "ເຊີບເວີນີ້ບໍ່ອະນຸຍາດໃຫ້ທ່ານເຮັດແບບນັ້ນ.",- "missing_permissions": "ທ່ານບໍ່ມີສິດເຮັດແບບນັ້ນຢູ່ນີ້. ສອບຖາມເຈົ້າຂອງເຊີບເວີ.",- "too_many_guilds": "ທ່ານຮອດຂີດຈຳກັດຈຳນວນກຸ່ມຕໍ່ຄົນຂອງເຊີບເວີນີ້ແລ້ວ.",- "not_found": "ສິ່ງນັ້ນບໍ່ມີຢູ່ໃນເຊີບເວີອີກແລ້ວ. ມັນອາດຖືກລຶບແລ້ວ.",- "rate_limited": "ເຊີບເວີຂໍໃຫ້ທ່ານຊ້າລົງ. ລໍຖ້າສອງສາມວິນາທີແລ້ວລອງໃໝ່.",- "server": "ເຊີບເວີເກີດຂໍ້ຜິດພາດພາຍໃນ. ລອງໃໝ່; ຖ້າຍັງເກີດຂຶ້ນອີກ, ແຈ້ງເຈົ້າຂອງເຊີບເວີ.",- "not_connected": "ບໍ່ໄດ້ເຊື່ອມຕໍ່ກັບເຊີບເວີນີ້ໃນຕອນນີ້. ມັນຈະເຊື່ອມຕໍ່ຄືນເອງ; ລອງໃໝ່ໃນອີກບໍ່ດົນ.",- "protocol": "ເຊີບເວີນີ້ໃຊ້ໂປຣໂຕຄໍແຊັດເວີຊັນທີ່ OmniGet ນີ້ບໍ່ເຂົ້າໃຈ. ອັບເດດ OmniGet ຫຼື ຂໍໃຫ້ເຈົ້າຂອງອັບເດດເຊີບເວີ.",- "bad_request": "ເຊີບເວີປະຕິເສດຄຳຮ້ອງນັ້ນ. ກວດສອບສິ່ງທີ່ທ່ານພິມແລ້ວລອງໃໝ່.",- "invalid_credentials": "ຊື່ຜູ້ໃຊ້ ຫຼື ລະຫັດຜ່ານບໍ່ຖືກຕ້ອງ. ກວດສອບທັງສອງແລ້ວລອງໃໝ່.",- "username_taken": "ຊື່ຜູ້ໃຊ້ນັ້ນຖືກໃຊ້ແລ້ວໃນເຊີບເວີນີ້. ເລືອກຊື່ອື່ນ.",- "invalid_username": "ຊື່ຜູ້ໃຊ້ຕ້ອງມີ 2–32 ຕົວອັກສອນ: ຕົວອັກສອນ, ຕົວເລກ, _ . -",- "invalid_password": "ລະຫັດຜ່ານຕ້ອງມີ 8 ຫາ 256 ຕົວອັກສອນ.",- "invalid_invite": "ລິ້ງເຊີນນັ້ນບໍ່ຖືກຕ້ອງ ຫຼື ໝົດອາຍຸແລ້ວ. ຂໍລິ້ງໃໝ່.",- "registration_closed": "ເຊີບເວີນີ້ຮັບບັນຊີໃໝ່ຜ່ານລິ້ງເຊີນເທົ່ານັ້ນ. ຂໍລິ້ງຈາກສະມາຊິກ.",- "message_too_long": "ຂໍ້ຄວາມນັ້ນຍາວເກີນກວ່າທີ່ເຊີບເວີນີ້ອະນຸຍາດ.",- "empty_message": "ພິມບາງຢ່າງກ່ອນສົ່ງ.",- "voice_mic_permission": "OmniGet ບໍ່ໄດ້ຮັບອະນຸຍາດໃຫ້ໃຊ້ໄມໂຄຣໂຟນ. ອະນຸຍາດໃນການຕັ້ງຄ່າຄວາມເປັນສ່ວນຕົວຂອງລະບົບ, ແລ້ວເຂົ້າຮ່ວມໃໝ່.",- "voice_no_input_device": "ບໍ່ພົບໄມໂຄຣໂຟນ. ສຽບໄມໂຄຣໂຟນ ຫຼື ເລືອກອັນອື່ນໃນການຕັ້ງຄ່າສຽງ. ທ່ານຍັງຟັງໄດ້ຢູ່.",- "voice_no_output_device": "ບໍ່ພົບລຳໂພງ ຫຼື ຫູຟັງ. ເຊື່ອມຕໍ່ອຸປະກອນແລ້ວເຂົ້າຮ່ວມໃໝ່.",- "voice_device_busy": "ແອັບອື່ນກຳລັງໃຊ້ອຸປະກອນສຽງ. ປິດແອັບນັ້ນ ຫຼື ເລືອກອຸປະກອນອື່ນໃນການຕັ້ງຄ່າສຽງ.",- "voice_mic_failed": "ບໍ່ສາມາດເລີ່ມໄມໂຄຣໂຟນໄດ້. ເລືອກອັນອື່ນໃນການຕັ້ງຄ່າສຽງ. ທ່ານຍັງຟັງໄດ້ຢູ່.",- "voice_output_failed": "ບໍ່ສາມາດເລີ່ມເອົາພຸດສຽງໄດ້. ເລືອກອຸປະກອນອື່ນໃນການຕັ້ງຄ່າສຽງ.",- "voice_mic_lost": "ໄມໂຄຣໂຟນຖືກຕັດການເຊື່ອມຕໍ່. ສຽບຄືນ ຫຼື ເລືອກອັນອື່ນໃນການຕັ້ງຄ່າສຽງ.",- "voice_output_lost": "ເອົາພຸດສຽງຖືກຕັດການເຊື່ອມຕໍ່. ເລືອກອຸປະກອນອື່ນໃນການຕັ້ງຄ່າສຽງ.",- "voice_unreachable": "ເຊີບເວີສຽງບໍ່ຕອບສະໜອງ. ກວດສອບການເຊື່ອມຕໍ່ແລ້ວລອງໃໝ່; ຖ້າຍັງລົ້ມເຫຼວ, ແຈ້ງເຈົ້າຂອງເຊີບເວີ.",- "voice_timeout": "ເຊີບເວີໃຊ້ເວລາຕັ້ງຄ່າສຽງດົນເກີນໄປ. ລອງໃໝ່ໃນອີກບໍ່ດົນ.",- "voice_denied": "ທ່ານບໍ່ສາມາດເຂົ້າຮ່ວມຊ່ອງສຽງນີ້ໄດ້. ຂໍອະນຸຍາດຈາກເຈົ້າຂອງເຊີບເວີ.",- "voice_dm_unsupported": "ເຊີບເວີນີ້ເກົ່າເກີນໄປສຳລັບການໂທໃນຂໍ້ຄວາມສ່ວນຕົວ. ຂໍໃຫ້ເຈົ້າຂອງອັບເດດ.",- "voice_not_connected": "ທ່ານບໍ່ໄດ້ຢູ່ໃນຊ່ອງສຽງ.",- "voice_disconnected": "ສຽງຫຼຸດ. ເຂົ້າຮ່ວມໃໝ່ເມື່ອທ່ານພ້ອມ.",- "voice_unavailable": "ສຽງບໍ່ພ້ອມໃຊ້ງານໃນບິວນີ້ຂອງ OmniGet.",- "voice_engine_crashed": "ເອນຈິນສຽງຂັດຂ້ອງ ແລະ ອອກຈາກການໂທ. ເຂົ້າຮ່ວມໃໝ່ເພື່ອລອງອີກຄັ້ງ; ຖ້າເກີດຂຶ້ນອີກ, ສົ່ງບັນທຶກລັອກຈາກ ກ່ຽວກັບ → Debug ມາໃຫ້ພວກເຮົາ.",- "screen_permission": "OmniGet ຕ້ອງການສິດບັນທຶກໜ້າຈໍ. ເປີດ System Settings → Privacy & Security → Screen & System Audio Recording, ເປີດໃຊ້ OmniGet, ແລ້ວລອງໃໝ່.",- "stream_unsupported": "ການແບ່ງປັນໜ້າຈໍຍັງບໍ່ພ້ອມໃຊ້ງານໃນແພລດຟອມນີ້.",- "stream_source_gone": "ໜ້າຈໍ ຫຼື ໜ້າຕ່າງນັ້ນບໍ່ມີຢູ່ອີກແລ້ວ. ເລືອກອັນອື່ນ.",- "stream_capture_failed": "ບໍ່ສາມາດຈັບພາບໜ້າຈໍໄດ້. ລອງແຫຼ່ງອື່ນ ຫຼື ເລີ່ມແອັບໃໝ່.",- "stream_encoder_failed": "ຕົວເຂົ້າລະຫັດວິດີໂອຂອງເຄື່ອງທ່ານບໍ່ສາມາດເລີ່ມໄດ້. ລອງຄວາມລະອຽດ ຫຼື ອັດຕາເຟຣມທີ່ຕ່ຳກວ່າ.",- "stream_not_streaming": "ທ່ານບໍ່ໄດ້ແບ່ງປັນໜ້າຈໍຢູ່ໃນຕອນນີ້.",- "stream_not_found": "ສະຕຣີມນັ້ນບໍ່ພ້ອມໃຊ້ງານອີກແລ້ວ.",- "stream_viewer_failed": "ບໍ່ສາມາດເປີດຕົວເບິ່ງສະຕຣີມໄດ້. ລອງເບິ່ງອີກຄັ້ງ.",- "e2ee": "OmniGet ບໍ່ສາມາດໃຊ້ການເຂົ້າລະຫັດສຳລັບການສົນທະນານີ້ໄດ້. ເຊື່ອມຕໍ່ເຊີບເວີຄືນແລ້ວລອງໃໝ່.",- "e2ee_not_ready": "ການເຂົ້າລະຫັດຍັງບໍ່ໄດ້ຕັ້ງຄ່າ — ອີກຝ່າຍຕ້ອງເປີດ OmniDisc ຢ່າງໜ້ອຍໜຶ່ງຄັ້ງ. ຂໍ້ຄວາມຂອງທ່ານບໍ່ໄດ້ຖືກສົ່ງ.",- "upload_too_large": "ໄຟລ໌ນັ້ນໃຫຍ່ເກີນກວ່າທີ່ເຊີບເວີນີ້ຮັບໄດ້.",- "upload_failed": "ການອັບໂຫຼດບໍ່ສຳເລັດ. ກວດສອບການເຊື່ອມຕໍ່ແລ້ວລອງໃໝ່.",- "upload_cancelled": "ຍົກເລີກການອັບໂຫຼດແລ້ວ.",- "unknown_upload": "ໄຟລ໌ແນບນັ້ນບໍ່ພ້ອມອີກແລ້ວ. ແນບໃໝ່ອີກຄັ້ງ.",- "attachment_corrupt": "ໄຟລ໌ນີ້ເສຍຫາຍລະຫວ່າງທາງ — ເນື້ອຫາບໍ່ກົງກັບທີ່ຜູ້ສົ່ງໄດ້ລົງລາຍເຊັນໄວ້. ມັນບໍ່ໄດ້ຖືກບັນທຶກ.",- "too_many_attachments": "ທ່ານສາມາດແນບໄດ້ສູງສຸດ 10 ໄຟລ໌ຕໍ່ໜຶ່ງຂໍ້ຄວາມ.",- "file_missing": "OmniGet ບໍ່ສາມາດອ່ານໄຟລ໌ນັ້ນໄດ້. ມັນອາດຖືກຍ້າຍ ຫຼື ລຶບແລ້ວ.",- "device_required": "ເຊີບເວີນີ້ຕ້ອງການໃຫ້ແອັບລົງທະບຽນອຸປະກອນກ່ອນເຂົ້າລະຫັດ. ເຊື່ອມຕໍ່ຄືນແລ້ວລອງໃໝ່.",- "epoch_conflict": "ມີຄົນປ່ຽນແປງການສົນທະນານີ້ໃນຂະນະທີ່ຂໍ້ຄວາມຂອງທ່ານກຳລັງສົ່ງ. ລອງສົ່ງອີກຄັ້ງ.",- "voice_output_permission": "OmniGet ບໍ່ໄດ້ຮັບອະນຸຍາດໃຫ້ໃຊ້ເອົາພຸດສຽງ. ອະນຸຍາດໃນການຕັ້ງຄ່າຄວາມເປັນສ່ວນຕົວຂອງລະບົບ, ແລ້ວເຂົ້າຮ່ວມໃໝ່.",- "e2ee_untrusted": "ເຊີບເວີຕອບກັບດ້ວຍອຸປະກອນທີ່ບຸກຄົນນີ້ບໍ່ເຄີຍເຜີຍແຜ່. OmniGet ຢຸດແທນທີ່ຈະເຂົ້າລະຫັດໄປຫາມັນ — ບໍ່ມີຫຍັງຖືກສົ່ງ. ແຈ້ງຜູ້ດູແລເຊີບເວີນີ້.",- "attachment_origin": "ໄຟລ໌ແນບນີ້ຊີ້ໄປບ່ອນອື່ນນອກເຊີບເວີນີ້. OmniGet ບໍ່ໄດ້ດາວໂຫຼດມັນ.",- "attachment_too_large": "ໄຟລ໌ແນບນີ້ສົ່ງຂໍ້ມູນເກີນຂະໜາດທີ່ແຈ້ງໄວ້, ສະນັ້ນການດາວໂຫຼດຈຶ່ງຖືກຢຸດ."- },- "guild": {- "create_title": "ສ້າງເຊີບເວີ",- "create_body": "ເຊີບເວີແມ່ນຊຸດຊ່ອງສຳລັບກຸ່ມຂອງທ່ານ. ທ່ານສາມາດເຊີນຄົນໄດ້ທັນທີຫຼັງຈາກນັ້ນ.",- "name_label": "ຊື່ເຊີບເວີ",- "name_placeholder": "ເຊັ່ນ ເກມຄືນວັນສຸກ",- "create_submit": "ສ້າງເຊີບເວີ",- "join_title": "ເຂົ້າຮ່ວມເຊີບເວີ",- "join_body": "ວາງລິ້ງເຊີນ ຫຼື ລະຫັດທີ່ໝູ່ສົ່ງໃຫ້ທ່ານ.",- "join_label": "ລິ້ງເຊີນ ຫຼື ລະຫັດ",- "join_placeholder": "https://chat.example.org/invite/abc123",- "join_submit": "ເຂົ້າຮ່ວມເຊີບເວີ",- "invite": "ເຊີນ",- "invite_copied": "ສຳເນົາລິ້ງເຊີນແລ້ວ. ສົ່ງໃຫ້ຜູ້ທີ່ທ່ານຕ້ອງການເຊີນ.",- "invite_failed": "ບໍ່ສາມາດສ້າງລິ້ງເຊີນໄດ້.",- "create_channel": "ສ້າງຊ່ອງ",- "create_channel_title": "ສ້າງຊ່ອງໃນ {{guild}}",- "channel_name_label": "ຊື່ຊ່ອງ",- "channel_name_placeholder": "ເຊັ່ນ memes",- "channel_kind_label": "ປະເພດ",- "channel_kind_text": "ຂໍ້ຄວາມ",- "channel_kind_voice": "ສຽງ",- "create_channel_submit": "ສ້າງຊ່ອງ",- "working": "ກຳລັງດຳເນີນການ…"- },- "voice": {- "title": "ສຽງ",- "join": "ເຂົ້າຮ່ວມສຽງ",- "join_channel": "ເຂົ້າຮ່ວມ {{channel}}",- "switch_title": "ປ່ຽນໄປ {{channel}} ບໍ່?",- "switch_body": "ທ່ານຈະອອກຈາກ {{current}}.",- "switch_confirm": "ປ່ຽນຊ່ອງ",- "leave": "ອອກຈາກສຽງ",- "leave_short": "ອອກ",- "connected_to": "ເຊື່ອມຕໍ່ສຽງແລ້ວ",- "connecting": "ກຳລັງເຊື່ອມຕໍ່ສຽງ…",- "reconnecting": "ກຳລັງເຊື່ອມຕໍ່ຄືນ…",- "failed": "ສຽງຫຼຸດ",- "retry": "ເຂົ້າຮ່ວມໃໝ່",- "mute": "ປິດໄມໂຄຣໂຟນ",- "unmute": "ເປີດໄມໂຄຣໂຟນ",- "deafen": "ປິດການຟັງ (ປິດສຽງທຸກຄົນ)",- "undeafen": "ເປີດການຟັງ",- "muted": "ປິດໄມແລ້ວ",- "deafened": "ປິດການຟັງແລ້ວ",- "ptt_hold": "ກົດ {{key}} ຄ້າງໄວ້ເພື່ອເວົ້າ",- "listen_only": "ຟັງຢ່າງດຽວ — ໄມໂຄຣໂຟນຂອງທ່ານບໍ່ເຮັດວຽກ.",- "no_output": "ລຳໂພງ ຫຼື ຫູຟັງຂອງທ່ານບໍ່ພ້ອມໃຊ້ງານ — ບໍ່ສາມາດໄດ້ຍິນຄົນອື່ນ.",- "quality_excellent": "ການເຊື່ອມຕໍ່: ດີເລີດ",- "quality_good": "ການເຊື່ອມຕໍ່: ດີ",- "quality_poor": "ການເຊື່ອມຕໍ່: ບໍ່ດີ — ສຽງອາດຂາດຫາຍ",- "quality_lost": "ການເຊື່ອມຕໍ່ຂາດ — ກຳລັງເຊື່ອມຕໍ່ຄືນ",- "quality_unknown": "ການເຊື່ອມຕໍ່: ກຳລັງວັດແທກ…",- "ping": "{{ms}} ms",- "participants": "{{count}} ຄົນໃນສຽງ",- "nobody": "ຍັງບໍ່ມີໃຜຢູ່ນີ້",- "nobody_hint": "ເຂົ້າຮ່ວມ ແລະ ເຊີນໝູ່ — ສຽງໃຊ້ຂໍ້ມູນໜ້ອຍກວ່າວິດີໂອ ແລະ ໃຊ້ໄດ້ກັບທຸກການເຊື່ອມຕໍ່.",- "you": "ທ່ານ",- "speaking": "ກຳລັງເວົ້າ",- "user_muted": "{{name}} ປິດໄມຢູ່",- "user_deafened": "{{name}} ປິດການຟັງຢູ່",- "volume_for": "ລະດັບສຽງຂອງ {{name}}",- "volume_reset": "ຣີເຊັດເປັນ 100%",- "settings": "ການຕັ້ງຄ່າສຽງ",- "open_settings": "ເປີດການຕັ້ງຄ່າສຽງ",- "settings_hint": "ໄມໂຄຣໂຟນ, ລຳໂພງ, ການຫຼຸດສຽງລົບກວນ ແລະ ກົດເພື່ອເວົ້າ.",- "input_device": "ໄມໂຄຣໂຟນ",- "output_device": "ລຳໂພງ / ຫູຟັງ",- "device_default": "ຄ່າເລີ່ມຕົ້ນຂອງລະບົບ",- "device_refresh": "ໂຫຼດອຸປະກອນຄືນ",- "no_input_devices": "ບໍ່ພົບໄມໂຄຣໂຟນ. ສຽບໄມໂຄຣໂຟນ ແລ້ວໂຫຼດຄືນ.",- "no_output_devices": "ບໍ່ພົບລຳໂພງ ຫຼື ຫູຟັງ.",- "mic_test": "ທົດສອບໄມໂຄຣໂຟນ",- "mic_test_stop": "ຢຸດທົດສອບ",- "mic_test_hint": "ເວົ້າຕາມປົກກະຕິ — ແຖບຄວນເຄື່ອນໄຫວ. ບໍ່ມີຫຍັງຖືກສົ່ງໄປບ່ອນໃດ.",- "mic_level": "ລະດັບໄມໂຄຣໂຟນ",- "mic_silent": "ບໍ່ພົບສຽງ. ກວດສອບວ່າໄມໂຄຣໂຟນສຽບຢູ່ ແລະ OmniGet ໄດ້ຮັບອະນຸຍາດໃຫ້ໃຊ້ມັນ.",- "noise_suppression": "ການຫຼຸດສຽງລົບກວນ",- "noise_suppression_desc": "ກັ່ນຕອງສຽງພັດລົມ, ຄີບອດ ແລະ ສຽງຮົບກວນພື້ນຫຼັງ ກ່ອນສົ່ງສຽງຂອງທ່ານ. ເປີດຕາມຄ່າເລີ່ມຕົ້ນ; ປິດສຳລັບດົນຕີ.",- "ptt_key": "ປຸ່ມກົດເພື່ອເວົ້າ",- "ptt_key_desc": "ປ່ອຍວ່າງໄວ້ເພື່ອໃຊ້ການກວດຈັບສຽງ: ໄມຈະເປີດເມື່ອທ່ານເວົ້າ.",- "ptt_record": "ບັນທຶກປຸ່ມ",- "ptt_recording": "ກົດປຸ່ມລັດ…",- "ptt_clear": "ໃຊ້ການກວດຈັບສຽງແທນ",- "ptt_permission_hint": "ໃນ macOS ປຸ່ມລັດທົ່ວລະບົບຕ້ອງການສິດ Accessibility: System Settings → Privacy & Security → Accessibility → OmniGet.",- "ptt_conflict_hint": "ແອັບພລິເຄຊັນອື່ນໃຊ້ປຸ່ມລັດນີ້ແລ້ວ. ບັນທຶກປຸ່ມອື່ນ ຫຼື ປິດແອັບທີ່ໃຊ້ມັນຢູ່.",- "ptt_refused": "ລະບົບບໍ່ຍອມໃຫ້ໃຊ້ປຸ່ມນີ້, ສະນັ້ນກົດເພື່ອເວົ້າຈະບໍ່ຕອບສະໜອງ.",- "vad_threshold": "ຄວາມໄວຕໍ່ສຽງ",- "vad_threshold_desc": "ຕ່ຳລົງຈະເປີດໄມກັບສຽງທີ່ເບົາກວ່າ; ສູງຂຶ້ນຕ້ອງເວົ້າດັງຂຶ້ນ.",- "e2ee_on": "ເຂົ້າລະຫັດແບບຕົ້ນທາງເຖິງປາຍທາງ",- "e2ee_on_desc": "ມີແຕ່ຄົນໃນການໂທນີ້ເທົ່ານັ້ນທີ່ໄດ້ຍິນ. ກະແຈມາຈາກການສົນທະນານີ້, ບໍ່ແມ່ນຈາກເຊີບເວີ.",- "e2ee_off": "ບໍ່ໄດ້ເຂົ້າລະຫັດແບບຕົ້ນທາງເຖິງປາຍທາງ",- "e2ee_off_desc": "ເຊີບເວີສາມາດໄດ້ຍິນການໂທນີ້. ຊ່ອງສຽງຂອງເຊີບເວີບໍ່ໄດ້ເຂົ້າລະຫັດ ເວັ້ນແຕ່ເຈົ້າຂອງຈະເປີດໃຊ້.",- "mic_back": "ໄມໂຄຣໂຟນຂອງທ່ານກັບມາແລ້ວ.",- "output_back": "ເອົາພຸດສຽງຂອງທ່ານກັບມາແລ້ວ.",- "mic_switched": "ໄມໂຄຣໂຟນຂອງທ່ານຖືກຖອດອອກ — ປ່ຽນໄປໃຊ້ຄ່າເລີ່ມຕົ້ນຂອງລະບົບແລ້ວ.",- "output_switched": "ເອົາພຸດສຽງຂອງທ່ານຖືກຖອດອອກ — ປ່ຽນໄປໃຊ້ຄ່າເລີ່ມຕົ້ນຂອງລະບົບແລ້ວ.",- "ducking": "ຫຼຸດສຽງຄົນອື່ນຂະນະທີ່ຂ້ອຍເວົ້າ",- "ducking_desc": "ຫຼຸດສຽງຂອງທຸກຄົນລົງໃນຂະນະທີ່ໄມໂຄຣໂຟນຂອງທ່ານເປີດ, ເພື່ອໃຫ້ທ່ານໄດ້ຍິນຕົນເອງຊັດເຈນ. ປິດຕາມຄ່າເລີ່ມຕົ້ນ.",- "ducking_off": "ປິດ",- "ducking_value": "ເບົາລົງ {{percent}}%",- "relay_only": "ເຊື່ອງທີ່ຢູ່ IP ຂອງຂ້ອຍ",- "relay_only_desc": "ສົ່ງສຽງທັງໝົດຜ່ານຣີເລຂອງເຊີບເວີ ແທນທີ່ຈະສົ່ງກົງຫາອີກຝ່າຍ. ຕ້ອງມີຣີເລ (TURN) ໃນເຊີບເວີ; ເພີ່ມຄວາມລ່າຊ້າເລັກນ້ອຍ. ມີຜົນກັບການໂທຄັ້ງຕໍ່ໄປ."- },- "stream": {- "live": "ສົດ",- "you_live": "ທ່ານກຳລັງຖ່າຍທອດສົດ",- "share_screen": "ແບ່ງປັນໜ້າຈໍ",- "stop_sharing": "ຢຸດແບ່ງປັນ",- "share_title": "ແບ່ງປັນໜ້າຈໍຂອງທ່ານ",- "pick_source": "ສິ່ງທີ່ຈະແບ່ງປັນ",- "loading_sources": "ກຳລັງຊອກຫາໜ້າຈໍ ແລະ ໜ້າຕ່າງ…",- "recheck": "ກວດອີກຄັ້ງ",- "audio": "ສຽງ",- "audio_none": "ບໍ່ມີສຽງ",- "audio_system": "ສຽງລະບົບ",- "quality": "ຄຸນນະພາບ",- "resolution": "ຄວາມລະອຽດ",- "framerate": "ອັດຕາເຟຣມ",- "implied_bitrate": "ປະມານ {{kbps}} Mbps · {{codec}}",- "hevc_note": "ຕົວເຂົ້າລະຫັດ H.264 ຂອງ Mac ທ່ານຮອງຮັບສູງສຸດປະມານ 60 fps ທີ່ 4K, ສະນັ້ນ 4K120 ຈະໃຊ້ HEVC. ຜູ້ຊົມທີ່ບໍ່ຮອງຮັບ HEVC ຈະເບິ່ງບໍ່ໄດ້.",- "custom_bitrate": "ຕັ້ງບິດເຣດເອງ",- "mode": "ການເຄື່ອນໄຫວ",- "mode_text": "ຂໍ້ຄວາມ ແລະ UI",- "mode_game": "ເຄື່ອນໄຫວໄວ",- "cursor": "ສະແດງເຄີເຊີຂອງຂ້ອຍ",- "starting": "ກຳລັງເລີ່ມ…",- "share_cta": "ແບ່ງປັນ {{res}}",- "watch": "ເບິ່ງ",- "stop_watching": "ຢຸດເບິ່ງ",- "watch_unsupported": "ການເບິ່ງສະຕຣີມຍັງບໍ່ພ້ອມໃຊ້ງານໃນແພລດຟອມນີ້.",- "volume": "ລະດັບສຽງສະຕຣີມ",- "fullscreen": "ເຕັມຈໍ",- "connecting": "ກຳລັງເຊື່ອມຕໍ່…",- "inspector": "ລາຍລະອຽດການເຊື່ອມຕໍ່",- "sending": "ກຳລັງສົ່ງ",- "receiving": "ກຳລັງຮັບ",- "software": "ຊອບແວ",- "software_warn": "ກຳລັງເຂົ້າລະຫັດດ້ວຍຊອບແວ — ໃຊ້ CPU ຫຼາຍຂຶ້ນ. ປິດແອັບອື່ນ ຫຼື ຫຼຸດຄຸນນະພາບລົງ.",- "rtt": "Ping",- "loss": "ການສູນເສຍ",- "encode": "ເຂົ້າລະຫັດ",- "no_active": "ຍັງບໍ່ມີສະຕຣີມທີ່ກຳລັງເຮັດວຽກ.",- "preview_alt": "ຕົວຢ່າງສົດຂອງໜ້າຈໍທີ່ທ່ານແບ່ງປັນ",- "portal_picker": "ເດັສທັອບຂອງທ່ານຈະຖາມວ່າຈະແບ່ງປັນໜ້າຈໍ ຫຼື ໜ້າຕ່າງໃດ ຫຼັງຈາກທ່ານກົດແບ່ງປັນ."- },- "emoji": {- "title": "ອີໂມຈິ",- "search": "ຄົ້ນຫາອີໂມຈິ",- "recent": "ໃຊ້ຫຼ້າສຸດ",- "no_match": "ບໍ່ມີອີໂມຈິທີ່ກົງກັບ “{{query}}”.",- "group_reactions": "ການຕອບສະໜອງດ່ວນ",- "group_people": "ຜູ້ຄົນ",- "group_nature": "ທຳມະຊາດ",- "group_food": "ອາຫານ",- "group_activity": "ກິດຈະກຳ",- "group_objects": "ວັດຖຸ",- "group_symbols": "ສັນຍາລັກ"- },- "search": {- "title": "ຄົ້ນຫາ",- "placeholder": "ຄົ້ນຫາຂໍ້ຄວາມ",- "scope": "ບ່ອນທີ່ຈະຄົ້ນຫາ",- "scope_channel": "ຊ່ອງນີ້",- "scope_guild": "ທັງເຊີບເວີ",- "run": "ຄົ້ນຫາ",- "filters_hint": "ຕົວກັ່ນຕອງ: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",- "unknown_from": "ບໍ່ມີສະມາຊິກຊື່ “{{name}}” ຢູ່ນີ້, ສະນັ້ນຕົວກັ່ນຕອງນັ້ນຖືກລະເລີຍ.",- "idle_title": "ຄົ້ນຫາໃນການສົນທະນານີ້",- "idle_body": "ພິມຄຳສັບແລ້ວກົດຄົ້ນຫາ. ຕົວກັ່ນຕອງຊ່ວຍໃຫ້ຜົນລັບແຄບລົງ.",- "empty_title": "ບໍ່ມີຫຍັງກົງກັນ",- "empty_body": "ລອງໃຊ້ຄຳສັບໜ້ອຍລົງ ຫຼື ລຶບຕົວກັ່ນຕອງອອກ.",- "results": "{{count}} ຜົນລັບ"- },- "pins": {- "title": "ຂໍ້ຄວາມທີ່ປັກໝຸດ",- "unpin": "ຖອນປັກໝຸດ",- "empty_title": "ຍັງບໍ່ມີການປັກໝຸດ",- "empty_body": "ປັກໝຸດຂໍ້ຄວາມຈາກເມນູຂອງມັນເພື່ອເກັບໄວ້ຢູ່ນີ້."- },- "notify": {- "title": "ການແຈ້ງເຕືອນ",- "channel_hint": "ສຳລັບຊ່ອງນີ້",- "inherit": "ໃຊ້ການຕັ້ງຄ່າຂອງເຊີບເວີ ({{level}})",- "level_all": "ທຸກຂໍ້ຄວາມ",- "level_mentions": "ສະເພາະການກ່າວເຖິງ",- "level_nothing": "ບໍ່ມີຫຍັງ",- "guild_title": "ການແຈ້ງເຕືອນສຳລັບເຊີບເວີນີ້",- "guild_hint": "ນຳໃຊ້ກັບທຸກຊ່ອງທີ່ບໍ່ມີການຕັ້ງຄ່າຂອງຕົນເອງ. ບັນທຶກໄວ້ໃນຄອມພິວເຕີເຄື່ອງນີ້."- },- "profile": {- "title": "ໂປຣໄຟລ໌ຂອງ {{name}}",- "open": "ເປີດໂປຣໄຟລ໌ຂອງ {{name}}",- "roles": "ບົດບາດ",- "mutual_servers": "ເຊີບເວີທີ່ມີຮ່ວມກັນ — {{count}}",- "note": "ບັນທຶກຂອງທ່ານ",- "note_placeholder": "ມີແຕ່ທ່ານທີ່ອ່ານໄດ້",- "message": "ຂໍ້ຄວາມ",- "copy_id": "ສຳເນົາ ID ຜູ້ໃຊ້",- "copy_failed": "ຄລິບບອດບໍ່ພ້ອມໃຊ້ງານ. ກະລຸນາສຳເນົາດ້ວຍຕົນເອງ.",- "moderation": "ການກວດກາ",- "nickname": "ປ່ຽນຊື່ຫຼິ້ນ",- "nickname_title": "ຊື່ຫຼິ້ນສຳລັບ {{name}}",- "nickname_confirm": "ບັນທຶກຊື່ຫຼິ້ນ",- "nickname_label": "ຊື່ຫຼິ້ນໃໝ່ (ປະວ່າງເພື່ອລ້າງ)",- "timeout": "ພັກການໃຊ້ງານຊົ່ວຄາວ",- "timeout_title": "ພັກການໃຊ້ງານ {{name}} ຊົ່ວຄາວບໍ?",- "timeout_confirm": "ພັກການໃຊ້ງານ {{name}}",- "timeout_label": "ດົນປານໃດ",- "timeout_5m": "5 ນາທີ",- "timeout_1h": "1 ຊົ່ວໂມງ",- "timeout_1d": "1 ມື້",- "timeout_1w": "1 ອາທິດ",- "kick": "ເຕະອອກ",- "kick_title": "ເຕະ {{name}} ອອກບໍ?",- "kick_body": "{{name}} ຈະອອກຈາກເຊີບເວີ ແລະ ສາມາດກັບມາໄດ້ດ້ວຍຄຳເຊີນໃໝ່.",- "kick_confirm": "ເຕະ {{name}} ອອກ",- "ban": "ແບນ",- "ban_title": "ແບນ {{name}} ບໍ?",- "ban_body": "{{name}} ຈະອອກຈາກເຊີບເວີ ແລະ ບໍ່ສາມາດເຂົ້າຮ່ວມຄືນໄດ້ ເຖິງຈະມີຄຳເຊີນກໍຕາມ ຈົນກວ່າທ່ານຈະຍົກເລີກການແບນ.",- "ban_confirm": "ແບນ {{name}}",- "reason_label": "ເຫດຜົນ (ບໍ່ບັງຄັບ)",- "reason_placeholder": "ສະແດງໃນບັນທຶກການກວດສອບ"- },- "friends": {- "title": "ໝູ່",- "tab_online": "ອອນລາຍ",- "tab_all": "ທັງໝົດ — {{count}}",- "tab_pending": "ລໍຖ້າ",- "tab_blocked": "ບລັອກແລ້ວ",- "add_label": "ເພີ່ມໝູ່",- "add_placeholder": "ຊື່ຜູ້ໃຊ້",- "add_hint": "ຊື່ຜູ້ໃຊ້ຕ້ອງຖືກຕ້ອງທຸກຕົວອັກສອນ. ຖາມຄົນນັ້ນວ່າສະກົດແນວໃດ.",- "send_request": "ສົ່ງຄຳຂໍ",- "sending": "ກຳລັງສົ່ງ…",- "request_sent": "ສົ່ງຄຳຂໍແລ້ວ. ເຂົາຈະເຫັນມັນຢູ່ໃນ ລໍຖ້າ.",- "accept": "ຍອມຮັບ",- "decline": "ປະຕິເສດ",- "remove": "ລຶບໝູ່",- "block": "ບລັອກ",- "unblock": "ຍົກເລີກບລັອກ",- "cancel_request": "ຍົກເລີກຄຳຂໍ",- "pending_out": "ລໍຖ້າເຂົາຕອບ",- "add": "ເພີ່ມໝູ່",- "empty_online_title": "ບໍ່ມີໃຜອອນລາຍ",- "empty_online_body": "ໝູ່ຂອງທ່ານຈະສະແດງຢູ່ນີ້ເມື່ອເຂົາເຊື່ອມຕໍ່.",- "empty_all_title": "ຍັງບໍ່ມີໝູ່",- "empty_all_body": "ເພີ່ມຄົນດ້ວຍຊື່ຜູ້ໃຊ້ຢູ່ຂ້າງເທິງ.",- "empty_pending_title": "ບໍ່ມີຄຳຂໍທີ່ລໍຖ້າ",- "empty_pending_body": "ຄຳຂໍທີ່ທ່ານສົ່ງ ຫຼື ໄດ້ຮັບຈະສະແດງຢູ່ນີ້.",- "empty_blocked_title": "ບໍ່ໄດ້ບລັອກໃຜ",- "empty_blocked_body": "ຄົນທີ່ຖືກບລັອກບໍ່ສາມາດສົ່ງ DM ຫາທ່ານໄດ້."- },- "guild_settings": {- "title": "ການຕັ້ງຄ່າ {{guild}}",- "back": "ກັບໄປຫາເຊີບເວີ",- "tab_overview": "ພາບລວມ",- "tab_roles": "ບົດບາດ",- "tab_channels": "ຊ່ອງ",- "tab_invites": "ຄຳເຊີນ",- "tab_bans": "ການແບນ",- "tab_audit": "ບັນທຶກການກວດສອບ",- "overview": "ພາບລວມ",- "description": "ຄຳອະທິບາຍ",- "save": "ບັນທຶກການປ່ຽນແປງ",- "saved": "ບັນທຶກແລ້ວ.",- "read_only": "ທ່ານເບິ່ງໄດ້ ແຕ່ການປ່ຽນແປງເຊີບເວີນີ້ຕ້ອງມີສິດ ຈັດການເຊີບເວີ.",- "not_found_title": "ບໍ່ພົບເຊີບເວີ",- "not_found_body": "ມັນອາດຖືກລຶບແລ້ວ ຫຼື ທ່ານໄດ້ອອກຈາກມັນແລ້ວ.",- "danger": "ເຂດອັນຕະລາຍ",- "leave": "ອອກຈາກເຊີບເວີ",- "leave_hint": "ທ່ານຈະເສຍສິດເຂົ້າເຖິງຊ່ອງຂອງມັນ ຈົນກວ່າຈະມີຄົນເຊີນທ່ານອີກ.",- "leave_owner_hint": "ໂອນຄວາມເປັນເຈົ້າຂອງກ່ອນອອກ — ເຊີບເວີບໍ່ສາມາດຢູ່ໂດຍບໍ່ມີເຈົ້າຂອງໄດ້.",- "leave_title": "ອອກຈາກ {{guild}} ບໍ?",- "leave_body": "ທ່ານຈະເສຍສິດເຂົ້າເຖິງຊ່ອງຂອງມັນ ຈົນກວ່າຈະມີຄົນເຊີນທ່ານອີກ.",- "leave_confirm": "ອອກຈາກ {{guild}}",- "transfer": "ໂອນຄວາມເປັນເຈົ້າຂອງ",- "transfer_hint": "ເຈົ້າຂອງໃໝ່ຈະໄດ້ຮັບທຸກສິດ. ທ່ານຍັງຄົງມີບົດບາດຂອງທ່ານ.",- "transfer_title": "ໂອນ {{guild}} ໃຫ້ຄົນອື່ນບໍ?",- "transfer_body": "ເຂົາຈະໄດ້ຮັບທຸກສິດໃນເຊີບເວີນີ້ ລວມທັງການລຶບມັນ.",- "transfer_confirm": "ໂອນຄວາມເປັນເຈົ້າຂອງ",- "transfer_to": "ເຈົ້າຂອງໃໝ່",- "transfer_pick": "ເລືອກສະມາຊິກ",- "delete": "ລຶບເຊີບເວີ",- "delete_hint": "ຊ່ອງ, ຂໍ້ຄວາມ ແລະ ບົດບາດຈະຖືກລຶບໄປນຳ. ບໍ່ສາມາດຍົກເລີກໄດ້.",- "delete_title": "ລຶບ {{guild}} ບໍ?",- "delete_body": "ທຸກຊ່ອງ, ຂໍ້ຄວາມ ແລະ ບົດບາດຈະຖືກລຶບສຳລັບທຸກຄົນ. ບໍ່ສາມາດຍົກເລີກໄດ້.",- "delete_confirm": "ລຶບ {{guild}}",- "delete_type": "ພິມ {{guild}} ເພື່ອຢືນຢັນ",- "roles_empty_title": "ຍັງບໍ່ມີບົດບາດ",- "roles_empty_body": "ສ້າງບົດບາດເພື່ອມອບສິດ.",- "everyone_role": "everyone",- "role_create": "ບົດບາດໃໝ່",- "role_create_title": "ບົດບາດໃໝ່",- "role_create_submit": "ສ້າງບົດບາດ",- "role_name": "ຊື່ບົດບາດ",- "role_name_placeholder": "ຜູ້ກວດກາ",- "role_color": "ສີ",- "role_hoist": "ສະແດງແຍກຕ່າງຫາກໃນລາຍຊື່ສະມາຊິກ",- "role_mentionable": "ທຸກຄົນສາມາດ @ກ່າວເຖິງບົດບາດນີ້",- "role_delete": "ລຶບ {{name}}",- "role_delete_title": "ລຶບບົດບາດ {{name}} ບໍ?",- "role_delete_body": "ສະມາຊິກຍັງຄົງມີບົດບາດອື່ນຂອງເຂົາ; ສິດທີ່ບົດບາດນີ້ມອບໃຫ້ຈະຫາຍໄປ.",- "role_delete_confirm": "ລຶບ {{name}}",- "role_delete_hint": "ບໍ່ສາມາດຍົກເລີກໄດ້.",- "perm_group_general": "ທົ່ວໄປ",- "perm_group_text": "ຂໍ້ຄວາມ",- "perm_group_voice": "ສຽງ",- "perm_group_moderation": "ການກວດກາ",- "invites_hint": "ລິ້ງເຊີນຊ່ວຍໃຫ້ຄົນເຂົ້າຮ່ວມເຊີບເວີນີ້ໄດ້.",- "invite_channel": "ເຂົ້າສູ່ຊ່ອງ",- "invite_channel_any": "ຄ່າເລີ່ມຕົ້ນຂອງເຊີບເວີ",- "invite_expiry": "ໝົດອາຍຸຫຼັງຈາກ",- "expiry_30m": "30 ນາທີ",- "expiry_1d": "1 ມື້",- "expiry_7d": "7 ມື້",- "expiry_never": "ບໍ່ມີກຳນົດ",- "invite_uses": "ຈຳນວນການໃຊ້ສູງສຸດ",- "uses_unlimited": "ບໍ່ຈຳກັດ",- "invite_create": "ສ້າງລິ້ງເຊີນ",- "invite_copy": "ສຳເນົາລິ້ງ",- "invites_empty": "ຍັງບໍ່ໄດ້ສ້າງລິ້ງໃນເຊດຊັນນີ້.",- "invites_no_list": "ເຊີບເວີນີ້ບໍ່ເກັບລາຍການຄຳເຊີນທີ່ຍັງໃຊ້ໄດ້ ສະນັ້ນຈຶ່ງສະແດງສະເພາະລິ້ງທີ່ທ່ານຫາກໍສ້າງ.",- "bans_empty_title": "ບໍ່ມີໃຜຖືກແບນ",- "bans_empty_body": "ການແບນທີ່ທ່ານເຮັດຈະສະແດງຢູ່ນີ້ ເພື່ອໃຫ້ທ່ານຍົກເລີກໄດ້.",- "ban_by": "ຖືກແບນໂດຍ {{name}}",- "unban": "ຍົກເລີກການແບນ",- "unban_title": "ຍົກເລີກການແບນ {{name}} ບໍ?",- "unban_body": "ເຂົາສາມາດເຂົ້າຮ່ວມອີກໄດ້ດ້ວຍຄຳເຊີນ.",- "unban_confirm": "ຍົກເລີກການແບນ {{name}}",- "unban_hint": "ເຂົາຈະບໍ່ເຂົ້າຮ່ວມຄືນອັດຕະໂນມັດ — ຕ້ອງມີຄຳເຊີນໃໝ່.",- "audit_filter": "ກັ່ນຕອງຕາມການກະທຳ",- "audit_all": "ທັງໝົດ",- "audit_empty_title": "ຍັງບໍ່ມີບັນທຶກ",- "audit_empty_body": "ການກວດກາ ແລະ ການປ່ຽນແປງການຕັ້ງຄ່າຈະສະແດງຢູ່ນີ້."- },- "channel_settings": {- "title": "ການຕັ້ງຄ່າຊ່ອງ",- "name": "ຊື່ຊ່ອງ",- "topic": "ຫົວຂໍ້",- "slowmode": "ໂໝດຊ້າ",- "slowmode_off": "ປິດ",- "nsfw": "ໝາຍເປັນເນື້ອຫາລະອຽດອ່ອນ",- "voice_note": "ບິດເຣດ ແລະ ຈຳນວນຜູ້ໃຊ້ສູງສຸດຖືກກຳນົດໂດຍນະໂຍບາຍຂອງອິນສະແຕນ ຈຶ່ງບໍ່ສາມາດແກ້ໄຂໄດ້ຢູ່ນີ້.",- "overwrites": "ສິດໃນຊ່ອງນີ້",- "overwrites_hint": "ສືບທອດ ຈະເຮັດຕາມສິດຂອງບົດບາດໃນເຊີບເວີ. ອະນຸຍາດ ແລະ ປະຕິເສດ ມີຜົນສະເພາະຢູ່ນີ້.",- "overwrite_target": "ສຳລັບ",- "allow": "ອະນຸຍາດ",- "inherit": "ສືບທອດ",- "deny": "ປະຕິເສດ",- "delete": "ລຶບ #{{name}}",- "delete_title": "ລຶບ #{{name}} ບໍ?",- "delete_body": "ຂໍ້ຄວາມຂອງມັນຈະຖືກລຶບໄປນຳ. ບໍ່ສາມາດຍົກເລີກໄດ້.",- "delete_confirm": "ລຶບ #{{name}}",- "delete_hint": "ທຸກຄົນຈະເສຍປະຫວັດໃນຊ່ອງນີ້."- },- "profile_settings": {- "title": "ໂປຣໄຟລ໌ຂອງທ່ານ",- "hint": "ຊື່, ສັບພະນາມ, ຄຳແນະນຳຕົວ, ສີ ແລະ ສະຖານະ",- "preview": "ສິ່ງທີ່ຄົນອື່ນເຫັນ",- "display_name": "ຊື່ທີ່ສະແດງ",- "pronouns": "ສັບພະນາມ",- "pronouns_placeholder": "she/her, he/him, they/them…",- "bio": "ກ່ຽວກັບທ່ານ",- "accent": "ສີເນັ້ນ",- "save": "ບັນທຶກໂປຣໄຟລ໌",- "saved": "ບັນທຶກໂປຣໄຟລ໌ແລ້ວ.",- "avatar_note": "ຍັງບໍ່ສາມາດອັບໂຫຼດຮູບໂປຣໄຟລ໌ ແລະ ແບນເນີໄດ້ — ອິນສະແຕນນີ້ບໍ່ມີ endpoint ອັບໂຫຼດໄຟລ໌. ຕົວອັກສອນທຳອິດ ແລະ ສີເນັ້ນຂອງທ່ານຈະໃຊ້ແທນໄປກ່ອນ.",- "presence": "ສະຖານະ",- "presence_online": "ອອນລາຍ",- "presence_idle": "ບໍ່ເຄື່ອນໄຫວ",- "presence_dnd": "ຫ້າມລົບກວນ",- "presence_invisible": "ເຊື່ອງຕົວ",- "custom_status": "ສະຖານະກຳນົດເອງ",- "custom_status_placeholder": "ຕັ້ງໃຈເຮັດວຽກຈົນຮອດ 5 ໂມງແລງ",- "custom_status_expiry": "ລ້າງຫຼັງຈາກ",- "expiry_never": "ບໍ່ມີກຳນົດ",- "expiry_30m": "30 ນາທີ",- "expiry_4h": "4 ຊົ່ວໂມງ",- "expiry_today": "ມື້ນີ້",- "apply_status": "ນຳໃຊ້ສະຖານະ",- "no_instance_title": "ບໍ່ມີເຊີບເວີທີ່ເຊື່ອມຕໍ່",- "no_instance_body": "ເຊື່ອມຕໍ່ກັບເຊີບເວີ OmniDisc ກ່ອນ — ໂປຣໄຟລ໌ຂອງທ່ານຢູ່ໃນນັ້ນ."- },- "sessions": {- "title": "ເຊດຊັນ",- "hint": "ບ່ອນທີ່ທ່ານເຂົ້າສູ່ລະບົບຢູ່",- "empty_title": "ບໍ່ມີເຊດຊັນອື່ນ",- "empty_body": "ມີແຕ່ອຸປະກອນນີ້ທີ່ເຂົ້າສູ່ລະບົບເຊີບເວີນີ້.",- "current": "ອຸປະກອນນີ້",- "last_seen": "ເຫັນຄັ້ງລ່າສຸດ {{when}}",- "revoke": "ອອກຈາກລະບົບ",- "revoke_title": "ໃຫ້ {{device}} ອອກຈາກລະບົບບໍ?",- "revoke_body": "ອຸປະກອນນັ້ນຕ້ອງເຂົ້າສູ່ລະບົບໃໝ່ເພື່ອໃຊ້ເຊີບເວີນີ້.",- "revoke_confirm": "ໃຫ້ {{device}} ອອກຈາກລະບົບ",- "revoke_hint": "ເຮັດແບບນີ້ຖ້າທ່ານບໍ່ຮູ້ຈັກອຸປະກອນນັ້ນ.",- "revoke_others": "ອອກຈາກລະບົບອີກ {{count}} ເຊດຊັນ",- "revoke_others_title": "ອອກຈາກລະບົບທຸກເຊດຊັນອື່ນບໍ?",- "revoke_others_body": "ອຸປະກອນນີ້ຍັງຄົງເຂົ້າສູ່ລະບົບຢູ່. ອຸປະກອນອື່ນທັງໝົດຕ້ອງເຂົ້າສູ່ລະບົບໃໝ່.",- "revoke_others_confirm": "ໃຫ້ອຸປະກອນອື່ນອອກຈາກລະບົບ",- "sign_out_here": "ອອກຈາກລະບົບຢູ່ນີ້",- "unknown_device": "ອຸປະກອນທີ່ບໍ່ຮູ້ຈັກ"- },- "perm": {- "VIEW_CHANNEL": "ເບິ່ງຊ່ອງ",- "SEND_MESSAGES": "ສົ່ງຂໍ້ຄວາມ",- "EMBED_LINKS": "ຝັງລິ້ງ",- "ATTACH_FILES": "ແນບໄຟລ໌",- "ADD_REACTIONS": "ເພີ່ມການຕອບໂຕ້",- "USE_EXTERNAL_EMOJI": "ໃຊ້ emoji ພາຍນອກ",- "MENTION_EVERYONE": "ກ່າວເຖິງທຸກຄົນ",- "READ_HISTORY": "ອ່ານປະຫວັດ",- "SEND_TTS": "ສົ່ງຂໍ້ຄວາມເປັນສຽງ",- "BYPASS_SLOWMODE": "ຂ້າມໂໝດຊ້າ",- "MANAGE_MESSAGES": "ຈັດການຂໍ້ຄວາມ",- "PIN_MESSAGES": "ປັກໝຸດຂໍ້ຄວາມ",- "MANAGE_CHANNELS": "ຈັດການຊ່ອງ",- "MANAGE_ROLES": "ຈັດການບົດບາດ",- "MANAGE_EMOJI": "ຈັດການ emoji",- "MANAGE_WEBHOOKS": "ຈັດການ webhook",- "MANAGE_GUILD": "ຈັດການເຊີບເວີ",- "VIEW_AUDIT_LOG": "ເບິ່ງບັນທຶກການກວດສອບ",- "CREATE_INVITES": "ສ້າງຄຳເຊີນ",- "CHANGE_NICKNAME": "ປ່ຽນຊື່ຫຼິ້ນຂອງຕົນເອງ",- "MANAGE_NICKNAMES": "ຈັດການຊື່ຫຼິ້ນ",- "VIEW_CHANNEL_MEMBERS": "ເບິ່ງລາຍຊື່ສະມາຊິກ",- "KICK_MEMBERS": "ເຕະສະມາຊິກອອກ",- "BAN_MEMBERS": "ແບນສະມາຊິກ",- "MODERATE_MEMBERS": "ພັກການໃຊ້ງານສະມາຊິກ",- "CONNECT": "ເຂົ້າຮ່ວມສຽງ",- "SPEAK": "ເວົ້າ",- "STREAM": "ແບ່ງປັນໜ້າຈໍ",- "VIDEO": "ເປີດກ້ອງ",- "USE_VAD": "ໃຊ້ການກວດຈັບສຽງ",- "PRIORITY_SPEAKER": "ຜູ້ເວົ້າລຳດັບຄວາມສຳຄັນ",- "MUTE_MEMBERS": "ປິດສຽງສະມາຊິກ",- "DEAFEN_MEMBERS": "ປິດການຟັງຂອງສະມາຊິກ",- "MOVE_MEMBERS": "ຍ້າຍສະມາຊິກ",- "USE_SOUNDBOARD": "ໃຊ້ຊາວບອດ",- "ADMINISTRATOR": "ຜູ້ດູແລລະບົບ"- },- "perm_desc": {- "VIEW_CHANNEL": "ເຫັນຊ່ອງ ແລະ ອ່ານເນື້ອຫາໃນນັ້ນ.",- "SEND_MESSAGES": "ຂຽນໃນຊ່ອງ.",- "EMBED_LINKS": "ລິ້ງທີ່ເຂົາໂພສຈະມີບັດຕົວຢ່າງ.",- "ATTACH_FILES": "ອັບໂຫຼດໄຟລ໌ ແລະ ຮູບພາບ.",- "ADD_REACTIONS": "ຕອບໂຕ້ຂໍ້ຄວາມດ້ວຍ emoji.",- "USE_EXTERNAL_EMOJI": "ໃຊ້ emoji ຈາກເຊີບເວີອື່ນ.",- "MENTION_EVERYONE": "ແຈ້ງເຕືອນທັງຊ່ອງພ້ອມກັນ.",- "READ_HISTORY": "ເຫັນຂໍ້ຄວາມທີ່ສົ່ງກ່ອນເຂົາເຂົ້າມາ.",- "SEND_TTS": "ສົ່ງຂໍ້ຄວາມທີ່ຖືກອ່ານອອກສຽງ.",- "BYPASS_SLOWMODE": "ສົ່ງໂດຍບໍ່ຕ້ອງລໍຖ້າລະຫວ່າງຂໍ້ຄວາມ.",- "MANAGE_MESSAGES": "ລຶບຂໍ້ຄວາມຂອງຄົນອື່ນ.",- "PIN_MESSAGES": "ປັກໝຸດ ແລະ ຖອນໝຸດຂໍ້ຄວາມໃນຊ່ອງ.",- "MANAGE_CHANNELS": "ສ້າງ, ປ່ຽນຊື່ ແລະ ລຶບຊ່ອງ.",- "MANAGE_ROLES": "ສ້າງບົດບາດ ແລະ ມອບສິດ.",- "MANAGE_EMOJI": "ເພີ່ມ ແລະ ລຶບ emoji ກຳນົດເອງ.",- "MANAGE_WEBHOOKS": "ສ້າງ ແລະ ລຶບ webhook.",- "MANAGE_GUILD": "ປ່ຽນຊື່, ຄຳອະທິບາຍ ແລະ ການຕັ້ງຄ່າຂອງເຊີບເວີ.",- "VIEW_AUDIT_LOG": "ເບິ່ງວ່າໃຜປ່ຽນຫຍັງ.",- "CREATE_INVITES": "ສ້າງລິ້ງເຊີນມາເຊີບເວີນີ້.",- "CHANGE_NICKNAME": "ປ່ຽນຊື່ຂອງຕົນເອງໃນເຊີບເວີນີ້.",- "MANAGE_NICKNAMES": "ປ່ຽນຊື່ສະມາຊິກອື່ນ.",- "VIEW_CHANNEL_MEMBERS": "ເປີດລາຍຊື່ສະມາຊິກຂອງຊ່ອງ.",- "KICK_MEMBERS": "ລຶບສະມາຊິກອອກ; ເຂົາສາມາດເຂົ້າຮ່ວມຄືນໄດ້ດ້ວຍຄຳເຊີນ.",- "BAN_MEMBERS": "ລຶບສະມາຊິກອອກ ແລະ ບລັອກບໍ່ໃຫ້ກັບມາ.",- "MODERATE_MEMBERS": "ປິດປາກສະມາຊິກຊົ່ວຄາວ.",- "CONNECT": "ເຂົ້າຊ່ອງສຽງ.",- "SPEAK": "ໃຊ້ໄມໂຄຣໂຟນໃນຊ່ອງສຽງ.",- "STREAM": "ສະຕຣີມໜ້າຈໍ ຫຼື ໜ້າຕ່າງ.",- "VIDEO": "ສົ່ງວິດີໂອໃນຊ່ອງສຽງ.",- "USE_VAD": "ເວົ້າໂດຍບໍ່ຕ້ອງກົດປຸ່ມຄ້າງໄວ້.",- "PRIORITY_SPEAKER": "ຄົນອື່ນຈະສຽງເບົາລົງເມື່ອເຂົາເວົ້າ.",- "MUTE_MEMBERS": "ປິດສຽງຄົນໃນຊ່ອງສຽງລະດັບເຊີບເວີ.",- "DEAFEN_MEMBERS": "ປິດການຟັງຂອງຄົນໃນຊ່ອງສຽງລະດັບເຊີບເວີ.",- "MOVE_MEMBERS": "ລາກຄົນລະຫວ່າງຊ່ອງສຽງ.",- "USE_SOUNDBOARD": "ຫຼິ້ນຄລິບຊາວບອດໃນຊ່ອງສຽງ.",- "ADMINISTRATOR": "ທຸກສິດ, ທຸກບ່ອນ, ບໍ່ສົນໃຈການກຳນົດສິດຂອງຊ່ອງ."- },- "audit": {- "guild_update": "{{actor}} ໄດ້ປ່ຽນການຕັ້ງຄ່າເຊີບເວີ",- "guild_delete": "{{actor}} ໄດ້ລຶບເຊີບເວີ",- "guild_transfer": "{{actor}} ໄດ້ໂອນເຊີບເວີໃຫ້ {{target}}",- "guild_create": "{{actor}} ໄດ້ສ້າງເຊີບເວີ",- "channel_create": "{{actor}} ໄດ້ສ້າງຊ່ອງ",- "channel_update": "{{actor}} ໄດ້ປ່ຽນແປງຊ່ອງ",- "channel_delete": "{{actor}} ໄດ້ລຶບຊ່ອງ",- "channel_overwrite": "{{actor}} ໄດ້ປ່ຽນສິດຂອງຊ່ອງ",- "role_create": "{{actor}} ໄດ້ສ້າງບົດບາດ",- "role_update": "{{actor}} ໄດ້ປ່ຽນແປງບົດບາດ",- "role_delete": "{{actor}} ໄດ້ລຶບບົດບາດ",- "member_update": "{{actor}} ໄດ້ອັບເດດ {{target}}",- "member_kick": "{{actor}} ໄດ້ເຕະ {{target}} ອອກ",- "member_ban": "{{actor}} ໄດ້ແບນ {{target}}",- "member_unban": "{{actor}} ໄດ້ຍົກເລີກການແບນ {{target}}",- "member_leave": "{{target}} ໄດ້ອອກຈາກເຊີບເວີ",- "message_delete": "{{actor}} ໄດ້ລຶບຂໍ້ຄວາມ",- "message_bulk_delete": "{{actor}} ໄດ້ລຶບຫຼາຍຂໍ້ຄວາມ",- "message_pin": "{{actor}} ໄດ້ປັກໝຸດຂໍ້ຄວາມ",- "message_unpin": "{{actor}} ໄດ້ຖອນໝຸດຂໍ້ຄວາມ",- "instance_update": "{{actor}} ໄດ້ປ່ຽນການຕັ້ງຄ່າອິນສະແຕນ",- "fallback": "{{actor}} — {{action}} {{target}}"- },- "audit_action": {- "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": "ໂອນຄວາມເປັນເຈົ້າຂອງແລ້ວ"- },- "attachments": {- "title": "ໄຟລ໌ແນບ",- "remove": "ລຶບ {{name}}",- "retry": "ລອງໃໝ່",- "preparing": "ກຳລັງເຂົ້າລະຫັດ…",- "uploading": "ກຳລັງສົ່ງ… {{percent}}%",- "resuming": "ການເຊື່ອມຕໍ່ຂາດ, ກຳລັງສືບຕໍ່ຈາກບ່ອນທີ່ຢຸດ…",- "ready": "ພ້ອມສົ່ງ",- "failed": "ອັບໂຫຼດບໍ່ສຳເລັດ",- "download": "ບັນທຶກໄປທີ່ Downloads",- "downloading": "ກຳລັງບັນທຶກ…",- "saved": "ບັນທຶກໄປທີ່ {{path}} ແລ້ວ",- "open_image": "ເປີດ {{name}}",- "close_image": "ປິດຕົວຢ່າງ",- "encrypted_note": "ເຂົ້າລະຫັດແລ້ວ — ບັນທຶກກ່ອນເພື່ອເປີດ",- "too_large": "ໄຟລ໌ນັ້ນໃຫຍ່ເກີນກວ່າທີ່ເຊີບເວີນີ້ຮັບໄດ້ ({{limit}}).",- "too_many": "ທ່ານສາມາດແນບໄດ້ສູງສຸດ {{count}} ໄຟລ໌ຕໍ່ໜຶ່ງຂໍ້ຄວາມ.",- "unreadable": "OmniGet ບໍ່ສາມາດອ່ານໄຟລ໌ນັ້ນໄດ້.",- "expires_in": "ໝົດອາຍຸໃນ {{minutes}} ນາທີ",- "expired": "ໄຟລ໌ນີ້ໝົດອາຍຸ ແລະ ຖືກລຶບອອກຈາກເຊີບເວີແລ້ວ."- },- "e2ee": {- "dm_locked": "ມີແຕ່ທ່ານ ແລະ {{name}} ທີ່ອ່ານຂໍ້ຄວາມເຫຼົ່ານີ້ໄດ້",- "group_locked": "ມີແຕ່ຄົນໃນການສົນທະນານີ້ທີ່ອ່ານຂໍ້ຄວາມເຫຼົ່ານີ້ໄດ້",- "guild_open": "ຂໍ້ຄວາມໃນຊ່ອງຂອງເຊີບເວີຖືກເກັບໄວ້ໂດຍບໍ່ເຂົ້າລະຫັດ — ຜູ້ທີ່ດູແລ {{host}} ສາມາດອ່ານໄດ້.",- "preparing": "ການເຂົ້າລະຫັດຈະເລີ່ມດ້ວຍຂໍ້ຄວາມທຳອິດທີ່ທ່ານສົ່ງຢູ່ນີ້",- "not_ready": "ກຳລັງລໍຖ້າອຸປະກອນອີກຝ່າຍຕັ້ງຄ່າການເຂົ້າລະຫັດ. ຂໍ້ຄວາມຂອງທ່ານຍັງບໍ່ໄດ້ສົ່ງ.",- "unavailable": "ຂໍ້ຄວາມນີ້ຖືກສົ່ງໄປຫາອຸປະກອນທີ່ທ່ານບໍ່ມີແລ້ວ. ເນື້ອຫາຍັງຢູ່ໃນອຸປະກອນທີ່ໄດ້ຮັບມັນ.",- "badge": "ເຂົ້າລະຫັດແບບຕົ້ນທາງຫາປາຍທາງ",- "devices_note": "{{count}} ອຸປະກອນສາມາດອ່ານການສົນທະນານີ້ໄດ້",- "unverified": "ອຸປະກອນທີ່ບໍ່ໄດ້ຢືນຢັນ",- "unverified_hint": "ຂໍ້ຄວາມນີ້ຖືກລົງລາຍເຊັນໂດຍອຸປະກອນທີ່ {{name}} ບໍ່ໄດ້ເຜີຍແຜ່. ອາດບໍ່ແມ່ນເຂົາແທ້ — ກວດສອບລາຍນິ້ວມືຂອງເຂົາກ່ອນທີ່ຈະເຊື່ອ."- },- "devices": {- "title": "ອຸປະກອນ",- "hint": "ອຸປະກອນໃດທີ່ອ່ານຂໍ້ຄວາມເຂົ້າລະຫັດຂອງທ່ານໄດ້",- "empty_title": "ຍັງບໍ່ມີອຸປະກອນ",- "empty_body": "ເຂົ້າສູ່ລະບົບເຊີບເວີ ແລ້ວອຸປະກອນນີ້ຈະລົງທະບຽນເອງ ເພື່ອໃຫ້ DM ຂອງທ່ານຖືກເຂົ້າລະຫັດໄດ້.",- "this_device": "ອຸປະກອນນີ້",- "added": "ເພີ່ມເມື່ອ {{when}}",- "last_seen": "ເຫັນຄັ້ງລ່າສຸດ {{when}}",- "fingerprint": "ລາຍນິ້ວມື",- "fingerprint_hint": "ອ່ານອັນນີ້ໃຫ້ໝູ່ຟັງຜ່ານການໂທ. ຖ້າລະຫັດກົງກັນ ແມ່ນບໍ່ມີໃຜຢູ່ລະຫວ່າງກາງ.",- "copy": "ສຳເນົາລາຍນິ້ວມື",- "copied": "ສຳເນົາແລ້ວ",- "copy_failed": "OmniGet ບໍ່ສາມາດເຂົ້າເຖິງຄລິບບອດໄດ້.",- "revoke": "ລຶບອອກ",- "revoke_title": "ລຶບ {{device}} ອອກບໍ?",- "revoke_body": "ອຸປະກອນນັ້ນຈະບໍ່ໄດ້ຮັບຂໍ້ຄວາມເຂົ້າລະຫັດໃໝ່ອີກ. ຂໍ້ຄວາມທີ່ມີຢູ່ແລ້ວຍັງຄົງຢູ່ໃນນັ້ນ.",- "revoke_confirm": "ລຶບ {{device}} ອອກ",- "revoke_this_title": "ລຶບອຸປະກອນນີ້ອອກບໍ?",- "revoke_this_body": "ທ່ານຈະຖືກອອກຈາກລະບົບຢູ່ນີ້ ແລະ ເສຍປະຫວັດທີ່ເຂົ້າລະຫັດທີ່ເກັບໄວ້ໃນອຸປະກອນນີ້. ບໍ່ມີການສຳຮອງຂໍ້ມູນ.",- "unnamed": "ອຸປະກອນບໍ່ມີຊື່",- "no_history_warning": "ອຸປະກອນຈະອ່ານໄດ້ສະເພາະຂໍ້ຄວາມທີ່ສົ່ງຫຼັງຈາກມັນເຂົ້າຮ່ວມ. ຂໍ້ຄວາມເກົ່າຍັງຢູ່ໃນອຸປະກອນທີ່ໄດ້ຮັບມັນ."- },- "call": {- "incoming": "{{name}} ກຳລັງໂທມາ",- "incoming_group": "{{name}} ກຳລັງໂທໃນ {{channel}}",- "accept": "ຮັບສາຍ",- "decline": "ປະຕິເສດ",- "expires_in": "ເຫຼືອ {{seconds}} ວິ",- "start": "ເລີ່ມການໂທ",- "start_hint": "ສະເພາະສຽງ — ບໍ່ມີໃຜເຫັນກ້ອງຂອງທ່ານ.",- "in_call": "ກຳລັງໂທ",- "leave": "ອອກຈາກການໂທ",- "joining": "ກຳລັງເຊື່ອມຕໍ່…"- },- "storage": {- "warning": "ດິສຂອງເຊີບເວີນີ້ເຕັມ {{percent}}% ແລ້ວ. ໄຟລ໌ຈະຖືກລຶບຫຼັງຈາກ {{minutes}} ນາທີຢູ່ແລ້ວ; ບັນທຶກສິ່ງທີ່ທ່ານຕ້ອງການດຽວນີ້.",- "critical": "ດິສຂອງເຊີບເວີນີ້ເຕັມ {{percent}}% ແລ້ວ. ທຸກໄຟລ໌ທີ່ເກັບໄວ້ກຳລັງຈະຖືກລຶບເພື່ອເພີ່ມພື້ນທີ່.",- "purged": "ດິສເຕັມ ຈຶ່ງລຶບໄຟລ໌ທີ່ເກັບໄວ້ທັງໝົດ {{count}} ໄຟລ໌. ຂໍ້ຄວາມບໍ່ໄດ້ຮັບຜົນກະທົບ — ມີແຕ່ໄຟລ໌ແນບທີ່ຫາຍໄປ.",- "retention_note": "ໄຟລ໌ຈະຖືກລຶບອອກຈາກເຊີບເວີຫຼັງຈາກ {{minutes}} ນາທີ."- }- },"ytdlp_missing_banner": {"text": "ບໍ່ພົບ yt-dlp ຈຶ່ງບໍ່ສາມາດເລີ່ມການດາວໂຫຼດໄດ້. ຕິດຕັ້ງມັນຈາກການຕັ້ງຄ່າ.","open_settings": "ເປີດການຕັ້ງຄ່າ",diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.jsonindex 33c4c4e8..56d633bd 100644--- a/src/lib/i18n/pt.json+++ b/src/lib/i18n/pt.json@@ -476,7 +476,6 @@"marketplace": "Marketplace","settings": "Configurações","about": "Sobre",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "Você verá notificações assim quando os pacotes mudarem de status."}},- "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"- },- "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)",- "immersive_enter": "Modo foco — esconder a barra lateral do app",- "immersive_exit": "Sair do modo foco — mostrar a barra lateral do app"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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": "AO VIVO",- "you_live": "Você está transmitindo",- "share_screen": "Compartilhar tela",- "stop_sharing": "Parar de compartilhar",- "share_title": "Compartilhar sua tela",- "pick_source": "O que compartilhar",- "loading_sources": "Procurando telas e janelas…",- "recheck": "Verificar de novo",- "audio": "Áudio",- "audio_none": "Sem áudio",- "audio_system": "Áudio do sistema",- "quality": "Qualidade",- "resolution": "Resolução",- "framerate": "Taxa de quadros",- "implied_bitrate": "Cerca de {{kbps}} Mbps · {{codec}}",- "hevc_note": "O encoder H.264 do seu Mac chega perto de 60 fps em 4K, então 4K120 usa HEVC. Quem não tem HEVC não consegue assistir.",- "custom_bitrate": "Definir o bitrate manualmente",- "mode": "Movimento",- "mode_text": "Texto e interface",- "mode_game": "Movimento rápido",- "cursor": "Mostrar meu cursor",- "starting": "Iniciando…",- "share_cta": "Compartilhar {{res}}",- "watch": "Assistir",- "stop_watching": "Parar de assistir",- "watch_unsupported": "Assistir a uma transmissão ainda não está disponível nesta plataforma.",- "volume": "Volume da transmissão",- "fullscreen": "Tela cheia",- "connecting": "Conectando…",- "inspector": "Detalhes da conexão",- "sending": "Enviando",- "receiving": "Recebendo",- "software": "software",- "software_warn": "Codificando em software — isso usa mais CPU. Feche outros apps ou reduza a qualidade.",- "rtt": "Ping",- "loss": "Perda",- "encode": "Codificação",- "no_active": "Nenhuma transmissão em andamento.",- "preview_alt": "Prévia ao vivo da sua tela compartilhada",- "portal_picker": "Seu sistema vai perguntar qual tela ou janela compartilhar depois que você tocar em Compartilhar."- },- "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.",- "expires_in": "expira em {{minutes}} min",- "expired": "Este arquivo expirou e foi apagado do servidor."- },- "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…"- },- "storage": {- "warning": "O disco deste servidor está {{percent}}% cheio. Os arquivos são apagados depois de {{minutes}} minutos de qualquer forma; salve agora o que precisar.",- "critical": "O disco deste servidor está {{percent}}% cheio. Todos os arquivos guardados estão prestes a ser apagados para liberar espaço.",- "purged": "O disco encheu, então os {{count}} arquivos guardados foram apagados. As mensagens continuam — só os anexos foram embora.",- "retention_note": "Os arquivos são apagados do servidor depois de {{minutes}} minutos."- }- },"ytdlp_missing_banner": {"text": "O yt-dlp não está instalado, então os downloads não começam. Instale em Configurações.","open_settings": "Abrir Configurações",diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.jsonindex 669fc365..c9dd4084 100644--- a/src/lib/i18n/ru.json+++ b/src/lib/i18n/ru.json@@ -476,7 +476,6 @@"marketplace": "Маркетплейс","settings": "Настройки","about": "О программе",- "omnidisc": "Чат","section_primary": "Основное","section_app": "Приложение","section_plugins": "Плагины",@@ -5697,818 +5696,6 @@"test_body": "Вы будете видеть такие уведомления, когда ваши посылки перемещаются."}},- "omnidisc": {- "title": "Чат",- "settings_title": "Чат (OmniDisc) — экспериментальный",- "settings_desc": "Встроенный чат для самоподдерживаемых серверов OmniDisc. По умолчанию отключён.",- "settings_enable": "Показать меню чата",- "settings_enable_desc": "Добавляет пункт «Чат» в боковую панель. Ничего не подключится, пока вы не добавите сервер.",- "disabled_title": "Чат отключён",- "disabled_body": "Включите его в Настройки → Дополнительно → Чат (OmniDisc). Ничего не запустится, пока вы это не сделаете.",- "open_settings": "Открыть настройки",- "connect": {- "title": "Подключиться к серверу",- "subtitle": "Вставьте ссылку-приглашение, которую прислал друг, или адрес сервера.",- "url_label": "Адрес сервера",- "url_placeholder": "https://chat.example.org",- "url_required": "Введите адрес сервера для продолжения.",- "invite_label": "Код приглашения (необязательно)",- "invite_placeholder": "Вставьте код из ссылки",- "submit": "Подключиться",- "submitting": "Подключение…",- "step_connecting": "Подключение к серверу",- "step_authenticating": "Вход в систему",- "step_syncing": "Синхронизация каналов",- "error_title": "Не удалось подключиться",- "retry": "Попробовать снова",- "success_title": "Подключено к {{name}}",- "success_body": "Выберите канал слева, чтобы начать общаться.",- "open": "Открыть чат",- "add_another": "Добавить другой сервер",- "demo": "Использовать демо-данные",- "step_auth": "Вход в систему",- "auth_title": "Вход в {{name}}",- "auth_body": "Ваш аккаунт хранится только на этом сервере. Создайте новый или войдите в уже существующий.",- "mode_register": "Создать аккаунт",- "mode_login": "У меня уже есть аккаунт",- "username_label": "Имя пользователя",- "username_placeholder": "например, ana",- "username_hint": "2–32 символа: буквы, цифры, _ . -",- "password_label": "Пароль",- "password_hint": "Не менее 8 символов.",- "display_name_label": "Отображаемое имя (необязательно)",- "display_name_placeholder": "Как вас увидят другие",- "register_submit": "Создать аккаунт и присоединиться",- "login_submit": "Войти",- "auth_required": "Введите имя пользователя и пароль для продолжения.",- "registration_closed": "Этот сервер принимает новые аккаунты только через ссылку-приглашение. Войдите или вернитесь и введите код приглашения.",- "change_server": "Использовать другой сервер",- "invite_noted": "Код приглашения принят — вы присоединитесь к серверу после входа.",- "insecure": "Этот сервер открыт по обычному http. Ваш пароль и всё, что вы здесь отправляете, идут без шифрования — их может прочитать любой в сети между вами и сервером.",- "insecure_short": "Соединение без шифрования"- },- "home": {- "pick_channel_title": "Выберите канал",- "pick_channel_body": "Выберите сервер слева, затем канал, чтобы начать общаться."- },- "rail": {- "home": "Главная чата",- "add_server": "Добавить сервер",- "status_connected": "подключён",- "status_connecting": "подключение",- "status_disconnected": "отключён",- "status_error": "ошибка подключения",- "status_reconnecting": "переподключение",- "status_signed_out": "вышли из аккаунта",- "menu": "Добавить или создать",- "create_server": "Создать сервер",- "join_invite": "Присоединиться по приглашению",- "add_instance": "Подключить другой сервер",- "sign_in": "Войти снова",- "reconnect": "Переподключиться",- "remove": "Забыть этот сервер",- "insecure": "{{name}} — соединение без шифрования (http)",- "immersive_enter": "Режим фокуса — скрыть боковую панель приложения",- "immersive_exit": "Выйти из режима фокуса — показать боковую панель приложения"- },- "channels": {- "title": "Каналы",- "empty": "Каналов пока нет",- "empty_hint": "Сервер пока не расделил с вами ни одного канала.",- "not_found": "Канал не найден",- "not_found_hint": "Возможно, он был удалён, или у вас больше нет доступа. Выберите другой слева.",- "voice_soon": "Голосовой канал",- "voice_soon_hint": "Заходите из списка слева или кнопкой ниже.",- "dms": "Личные сообщения",- "no_dms": "Личных сообщений пока нет. Выберите участника справа, чтобы начать переписку.",- "no_guilds": "Вы пока не состоите ни в одном сервере.",- "no_guilds_hint": "Создайте его или присоединитесь по приглашению с помощью кнопки + слева."- },- "members": {- "title": "Участники",- "online": "В сети — {{count}}",- "offline": "Не в сети — {{count}}",- "empty": "Здесь пока никого нет",- "show": "Показать участников",- "hide": "Скрыть участников",- "message": "Написать {{name}}",- "owner": "владелец"- },- "messages": {- "empty_title": "Сообщений пока нет",- "empty_body": "Напишите приветствие — вы будете первым.",- "loading": "Загрузка сообщений…",- "today": "Сегодня",- "yesterday": "Вчера",- "you": "Вы",- "pending": "Отправка…",- "failed": "Не отправлено.",- "retry": "Повторить",- "discard": "Отменить",- "edited": "(ред.)",- "typing_one": "{{name}} печатает…",- "typing_two": "{{a}} и {{b}} печатают…",- "typing_many": "Несколько человек печатают…",- "unknown_user": "Неизвестный пользователь",- "new_messages": "Новые сообщения",- "reply_unavailable": "Оригинальное сообщение не загружено",- "pinned": "Закреплено",- "edit_label": "Редактировать сообщение",- "edit_save": "Сохранить",- "react": "Добавить реакцию",- "reply": "Ответить",- "edit": "Редактировать",- "more": "Ещё действия",- "pin": "Закрепить в канале",- "unpin": "Открепить",- "mark_unread": "Отметить как непрочитанное отсюда",- "copy_link": "Скопировать ссылку на сообщение",- "copy_id": "Скопировать ID сообщения",- "delete": "Удалить сообщение",- "delete_title": "Удалить это сообщение?",- "delete_body": "Оно исчезнет для всех в канале. Это действие необратимо.",- "delete_confirm": "Удалить сообщение",- "delete_no_text": "(нет текста)",- "copy_failed": "Буфер обмена недоступен. Скопируйте вручную.",- "jump_present": "Перейти к текущим",- "reaction_add": "Реагировать {{emoji}}",- "reaction_remove": "Убрать вашу {{emoji}}"- },- "composer": {- "placeholder": "Сообщение в #{{channel}}",- "send": "Отправить",- "hint": "Enter — отправить · Shift+Enter — новая строка",- "replying_to": "Ответ {{name}}",- "cancel_reply": "Отменить ответ",- "attach": "Прикрепить файл",- "drop_here": "Перетащите для прикрепления",- "uploading_wait": "Дождитесь окончания загрузки файлов"- },- "dm": {- "title": "Личное сообщение",- "placeholder": "Написать {{name}}",- "not_found": "Переписка не найдена",- "not_found_hint": "Возможно, она была закрыта или этот сервер сейчас не подключён."- },- "error": {- "unreachable": "Сервер не отвечает. Проверьте адрес или попросите владельца прислать новую ссылку.",- "invalid_url": "Адрес выглядит неправильно. Используйте http:// или https:// без имени пользователя или пароля.",- "not_an_instance": "На этом адресе нет сервера OmniDisc. Проверьте ссылку с тем, кто её прислал.",- "unauthorized": "Ваша сессия на этом сервере истекла. Войдите снова.",- "no_session": "Вы вышли с этого сервера. Войдите для продолжения.",- "forbidden": "Этот сервер не разрешает вам это делать.",- "missing_permissions": "У вас нет разрешения для этого действия. Свяжитесь с владельцем сервера.",- "too_many_guilds": "Вы достигли лимита групп на человека для этого сервера.",- "not_found": "Этого больше нет на сервере. Возможно, было удалено.",- "rate_limited": "Сервер просит вас замедлиться. Подождите несколько секунд и попробуйте снова.",- "server": "На сервере произошла внутренняя ошибка. Попробуйте снова; если проблема повторяется, сообщите владельцу сервера.",- "not_connected": "Сейчас нет подключения к этому серверу. Он переподключится автоматически; попробуйте снова через минуту.",- "protocol": "Этот сервер использует версию протокола чата, которую OmniGet не понимает. Обновите OmniGet или попросите владельца обновить сервер.",- "bad_request": "Сервер отклонил запрос. Проверьте введённые данные и попробуйте снова.",- "invalid_credentials": "Неверное имя пользователя или пароль. Проверьте оба и попробуйте снова.",- "username_taken": "Это имя пользователя уже занято на сервере. Выберите другое.",- "invalid_username": "Имена пользователей: 2–32 символа: буквы, цифры, _ . -",- "invalid_password": "Пароли должны содержать от 8 до 256 символов.",- "invalid_invite": "Приглашение недействительно или истекло. Запросите новую ссылку.",- "registration_closed": "Этот сервер принимает новые аккаунты только через ссылку-приглашение. Попросите её у участника.",- "message_too_long": "Сообщение длиннее, чем допускает этот сервер.",- "empty_message": "Введите что-нибудь перед отправкой.",- "voice_mic_permission": "OmniGet не разрешено использовать микрофон. Разрешите это в настройках конфиденциальности системы и снова присоединитесь.",- "voice_no_input_device": "Микрофон не найден. Подключите его или выберите другой в настройках голоса. Вы всё равно можете слушать.",- "voice_no_output_device": "Колонки или наушники не найдены. Подключите их и снова присоединитесь.",- "voice_device_busy": "Аудиоустройство используется другим приложением. Закройте его или выберите другое устройство в настройках голоса.",- "voice_mic_failed": "Не удалось запустить микрофон. Выберите другой в настройках голоса. Вы всё равно можете слушать.",- "voice_output_failed": "Не удалось запустить вывод звука. Выберите другое устройство в настройках голоса.",- "voice_mic_lost": "Микрофон был отключён. Подключите его снова или выберите другой в настройках голоса.",- "voice_output_lost": "Вывод звука был отключён. Выберите другое устройство в настройках голоса.",- "voice_unreachable": "Голосовой сервер не ответил. Проверьте подключение и попробуйте снова; если проблема повторяется, сообщите владельцу сервера.",- "voice_timeout": "Сервер слишком долго настраивал голос. Попробуйте снова через минуту.",- "voice_denied": "Вы не можете присоединиться к этому голосовому каналу. Попросите разрешение у владельца сервера.",- "voice_dm_unsupported": "Этот сервер слишком стар для звонков в личных сообщениях. Попросите владельца обновить его.",- "voice_not_connected": "Вы не находитесь в голосовом канале.",- "voice_disconnected": "Голосовое соединение разорвалось. Присоединитесь снова, когда будете готовы.",- "voice_unavailable": "Голос недоступен в этой сборке OmniGet.",- "voice_engine_crashed": "Голосовой движок аварийно завершился и покинул вызов. Присоединитесь снова; если проблема повторяется, отправьте нам лог из «О программе → Отладка».",- "screen_permission": "OmniGet нужно разрешение на запись экрана. Откройте Системные настройки → Конфиденциальность и безопасность → Запись экрана и системного звука, включите OmniGet и попробуйте снова.",- "stream_unsupported": "Демонстрация экрана пока недоступна на этой платформе.",- "stream_source_gone": "Этот экран или окно больше не доступны. Выберите другой.",- "stream_capture_failed": "Не удалось захватить экран. Попробуйте другой источник или перезапустите приложение.",- "stream_encoder_failed": "Видеокодер вашей машины не смог запуститься. Попробуйте более низкое разрешение или частоту кадров.",- "stream_not_streaming": "Вы сейчас не демонстрируете экран.",- "stream_not_found": "Эта трансляция больше не доступна.",- "stream_viewer_failed": "Не удалось открыть просмотрщик трансляции. Попробуйте посмотреть снова.",- "e2ee": "OmniGet не смог использовать шифрование для этой беседы. Переподключитесь к серверу и попробуйте снова.",- "e2ee_not_ready": "Шифрование ещё не настроено — собеседник должен один раз открыть OmniDisc. Ваше сообщение не отправлено.",- "upload_too_large": "Файл больше, чем допускает этот сервер.",- "upload_failed": "Загрузка не завершилась. Проверьте подключение и попробуйте снова.",- "upload_cancelled": "Загрузка отменена.",- "unknown_upload": "Это вложение больше не готово. Прикрепите его снова.",- "attachment_corrupt": "Файл повреждён — его содержимое не совпадает с подписью отправителя. Он не был сохранён.",- "too_many_attachments": "К одному сообщению можно прикрепить до 10 файлов.",- "file_missing": "OmniGet не смог прочитать этот файл. Возможно, он был перемещён или удалён.",- "device_required": "Этот сервер требует регистрации устройства перед шифрованием. Переподключитесь и попробуйте снова.",- "epoch_conflict": "Кто-то изменил эту беседу, пока ваше сообщение отправлялось. Попробуйте отправить его снова.",- "voice_output_permission": "OmniGet не разрешено использовать вывод звука. Разрешите это в настройках конфиденциальности системы и снова присоединитесь.",- "e2ee_untrusted": "Сервер ответил устройством, которое этот человек никогда не публиковал. OmniGet остановился, вместо того чтобы шифровать для него — ничего не отправлено. Сообщите администратору сервера.",- "attachment_origin": "Это вложение указывает за пределы этого сервера. OmniGet не стал его скачивать.",- "attachment_too_large": "Это вложение продолжало передавать данные сверх заявленного размера, поэтому загрузка была остановлена."- },- "guild": {- "create_title": "Создать сервер",- "create_body": "Сервер — это набор каналов для вашей группы. Вы сможете пригласить людей сразу после создания.",- "name_label": "Название сервера",- "name_placeholder": "например, Пятничные игры",- "create_submit": "Создать сервер",- "join_title": "Присоединиться к серверу",- "join_body": "Вставьте ссылку-приглашение или код, который прислал друг.",- "join_label": "Ссылка-приглашение или код",- "join_placeholder": "https://chat.example.org/invite/abc123",- "join_submit": "Присоединиться",- "invite": "Пригласить",- "invite_copied": "Ссылка-приглашение скопирована. Отправьте её тому, кого хотите пригласить.",- "invite_failed": "Не удалось создать ссылку-приглашение.",- "create_channel": "Создать канал",- "create_channel_title": "Создать канал в {{guild}}",- "channel_name_label": "Название канала",- "channel_name_placeholder": "например, мемы",- "channel_kind_label": "Тип",- "channel_kind_text": "Текстовый",- "channel_kind_voice": "Голосовой",- "create_channel_submit": "Создать канал",- "working": "Выполняется…"- },- "voice": {- "title": "Голос",- "join": "Войти в голос",- "join_channel": "Войти в {{channel}}",- "switch_title": "Переключиться на {{channel}}?",- "switch_body": "Вы покинете {{current}}.",- "switch_confirm": "Переключить канал",- "leave": "Покинуть голос",- "leave_short": "Выйти",- "connected_to": "Голос подключён",- "connecting": "Подключение к голосу…",- "reconnecting": "Переподключение…",- "failed": "Голосовое соединение разорвалось",- "retry": "Присоединиться снова",- "mute": "Отключить микрофон",- "unmute": "Включить микрофон",- "deafen": "Заглушить (отключить звук всех)",- "undeafen": "Включить звук",- "muted": "Микрофон отключён",- "deafened": "Звук отключён",- "ptt_hold": "Удерживайте {{key}} для разговора",- "listen_only": "Только прослушивание — ваш микрофон не работает.",- "no_output": "Ваши колонки или наушники недоступны — других не слышно.",- "quality_excellent": "Подключение: отличное",- "quality_good": "Подключение: хорошее",- "quality_poor": "Подключение: нестабильное — звук может пропадать",- "quality_lost": "Соединение потеряно — переподключение",- "quality_unknown": "Подключение: измерение…",- "ping": "{{ms}} мс",- "participants": "{{count}} в голосе",- "nobody": "Здесь пока никого нет",- "nobody_hint": "Присоединяйтесь и пригласите друга — голос легче видео и работает на любом подключении.",- "you": "вы",- "speaking": "говорит",- "user_muted": "{{name}} отключил(а) микрофон",- "user_deafened": "{{name}} отключил(а) звук",- "volume_for": "Громкость для {{name}}",- "volume_reset": "Сбросить на 100%",- "settings": "Настройки голоса",- "open_settings": "Открыть настройки голоса",- "settings_hint": "Микрофон, колонки, подавление шумов и рация.",- "input_device": "Микрофон",- "output_device": "Колонки / наушники",- "device_default": "Системный по умолчанию",- "device_refresh": "Обновить устройства",- "no_input_devices": "Микрофон не найден. Подключите его и обновите список.",- "no_output_devices": "Колонки или наушники не найдены.",- "mic_test": "Тест микрофона",- "mic_test_stop": "Остановить тест",- "mic_test_hint": "Говорите нормально — полоска должна двигаться. Ничего не отправляется.",- "mic_level": "Уровень микрофона",- "mic_silent": "Звук не обнаружен. Проверьте, что микрофон подключён и OmniGet имеет к нему доступ.",- "noise_suppression": "Подавление шумов",- "noise_suppression_desc": "Фильтрует вентиляторы, клавиатуры и фоновый гул перед отправкой голоса. По умолчанию включено; выключите для музыки.",- "ptt_key": "Клавиша рации",- "ptt_key_desc": "Оставьте пустым для работы по голосовой активности: микрофон открывается, когда вы говорите.",- "ptt_record": "Записать",- "ptt_recording": "Нажмите комбинацию клавиш…",- "ptt_clear": "Использовать голосовую активность",- "ptt_permission_hint": "В macOS глобальная клавиша требует разрешения на специальные возможности: Системные настройки → Конфиденциальность и безопасность → Специальные возможности → OmniGet.",- "ptt_conflict_hint": "Другое приложение уже заняло эту комбинацию. Запишите другую или закройте приложение-владелец.",- "ptt_refused": "Система не передала эту клавишу, поэтому рация не будет работать.",- "vad_threshold": "Чувствительность голоса",- "vad_threshold_desc": "Ниже — микрофон открывается на более тихих звуках; выше — нужно говорить громче.",- "e2ee_on": "Сквозное шифрование",- "e2ee_on_desc": "Только участники этого вызова могут слышать. Ключ берётся из этой беседы, никогда с сервера.",- "e2ee_off": "Без сквозного шифрования",- "e2ee_off_desc": "Сервер может слушать этот вызов. Серверные голосовые каналы не шифруются, пока владелец не включит это.",- "mic_back": "Ваш микрофон снова работает.",- "output_back": "Ваш вывод звука снова работает.",- "mic_switched": "Ваш микрофон был отключён — переключено на системный по умолчанию.",- "output_switched": "Ваш вывод звука был отключён — переключено на системный по умолчанию.",- "ducking": "Приглушать других, когда я говорю",- "ducking_desc": "Уменьшает громкость других, пока ваш микрофон активен, чтобы вы слышали себя. По умолчанию отключено.",- "ducking_off": "Выкл.",- "ducking_value": "тише на {{percent}}%",- "relay_only": "Скрыть мой IP-адрес",- "relay_only_desc": "Отправляет весь голос через реле сервера вместо прямого подключения к собеседнику. Требует реле (TURN) на сервере; добавляет небольшую задержку. Применяется к следующему вызову."- },- "stream": {- "live": "ПРЯМОЙ ЭФИР",- "you_live": "Вы в эфире",- "share_screen": "Демонстрация экрана",- "stop_sharing": "Остановить демонстрацию",- "share_title": "Демонстрация вашего экрана",- "pick_source": "Что показать",- "loading_sources": "Поиск экранов и окон…",- "recheck": "Проверить снова",- "audio": "Звук",- "audio_none": "Без звука",- "audio_system": "Системный звук",- "quality": "Качество",- "resolution": "Разрешение",- "framerate": "Частота кадров",- "implied_bitrate": "Около {{kbps}} Мбит/с · {{codec}}",- "hevc_note": "Кодер H.264 вашего Mac ограничивается примерно 60 кадрами в секунду при 4K, поэтому 4K120 использует HEVC. Зрители без HEVC не смогут смотреть.",- "custom_bitrate": "Установить битрейт вручную",- "mode": "Движение",- "mode_text": "Текст и интерфейс",- "mode_game": "Быстрое движение",- "cursor": "Показывать курсор",- "starting": "Запуск…",- "share_cta": "Поделиться {{res}}",- "watch": "Смотреть",- "stop_watching": "Прекратить просмотр",- "watch_unsupported": "Просмотр трансляции пока недоступен на этой платформе.",- "volume": "Громкость трансляции",- "fullscreen": "Полный экран",- "connecting": "Подключение…",- "inspector": "Подробности подключения",- "sending": "Отправка",- "receiving": "Приём",- "software": "программный",- "software_warn": "Кодирование в программном режиме — это нагружает процессор. Закройте другие приложения или снизьте качество.",- "rtt": "Пинг",- "loss": "Потери",- "encode": "Кодирование",- "no_active": "Трансляция ещё не запущена.",- "preview_alt": "Предварительный просмотр вашего экрана в прямом эфире",- "portal_picker": "Ваш рабочий стол спросит, какой экран или окно показать, после нажатия «Поделиться»."- },- "emoji": {- "title": "Эмодзи",- "search": "Поиск эмодзи",- "recent": "Недавние",- "no_match": "Нет эмодзи по запросу «{{query}}».",- "group_reactions": "Быстрые реакции",- "group_people": "Люди",- "group_nature": "Природа",- "group_food": "Еда",- "group_activity": "Активность",- "group_objects": "Предметы",- "group_symbols": "Символы"- },- "search": {- "title": "Поиск",- "placeholder": "Поиск сообщений",- "scope": "Где искать",- "scope_channel": "Этот канал",- "scope_guild": "Весь сервер",- "run": "Найти",- "filters_hint": "Фильтры: from:name · has:file|image|link · before:2026-01-31 · after:2026-01-01",- "unknown_from": "Нет участника «{{name}}», фильтр проигнорирован.",- "idle_title": "Поиск в этой беседе",- "idle_body": "Введите слово и нажмите «Найти». Фильтры сужают поиск.",- "empty_title": "Ничего не найдено",- "empty_body": "Попробуйте меньше слов или уберите фильтр.",- "results": "{{count}} совпадений"- },- "pins": {- "title": "Закреплённые сообщения",- "unpin": "Открепить",- "empty_title": "Закреплённых пока нет",- "empty_body": "Закрепите сообщение через его меню, чтобы сохранить его здесь."- },- "notify": {- "title": "Уведомления",- "channel_hint": "Для этого канала",- "inherit": "Использовать настройку сервера ({{level}})",- "level_all": "Все сообщения",- "level_mentions": "Только упоминания",- "level_nothing": "Ничего",- "guild_title": "Уведомления для этого сервера",- "guild_hint": "Действует на все каналы без собственной настройки. Хранится на этом компьютере."- },- "profile": {- "title": "Профиль {{name}}",- "open": "Открыть профиль {{name}}",- "roles": "Роли",- "mutual_servers": "Общие серверы — {{count}}",- "note": "Ваша заметка",- "note_placeholder": "Только вы можете это прочитать",- "message": "Написать",- "copy_id": "Скопировать ID пользователя",- "copy_failed": "Буфер обмена недоступен. Скопируйте вручную.",- "moderation": "Модерация",- "nickname": "Изменить никнейм",- "nickname_title": "Никнейм для {{name}}",- "nickname_confirm": "Сохранить никнейм",- "nickname_label": "Новый никнейм (пустое поле сбросит его)",- "timeout": "Тайм-аут",- "timeout_title": "Тайм-аут для {{name}}?",- "timeout_confirm": "Тайм-аут для {{name}}",- "timeout_label": "На какое время",- "timeout_5m": "5 минут",- "timeout_1h": "1 час",- "timeout_1d": "1 день",- "timeout_1w": "1 неделя",- "kick": "Исключить",- "kick_title": "Исключить {{name}}?",- "kick_body": "{{name}} покинет сервер и сможет вернуться по новому приглашению.",- "kick_confirm": "Исключить {{name}}",- "ban": "Забанить",- "ban_title": "Забанить {{name}}?",- "ban_body": "{{name}} покинет сервер и не сможет вернуться — даже с приглашением — пока вы не разбаните его.",- "ban_confirm": "Забанить {{name}}",- "reason_label": "Причина (необязательно)",- "reason_placeholder": "Отображается в журнале аудита"- },- "friends": {- "title": "Друзья",- "tab_online": "В сети",- "tab_all": "Все — {{count}}",- "tab_pending": "Ожидают",- "tab_blocked": "Заблокированные",- "add_label": "Добавить друга",- "add_placeholder": "имя пользователя",- "add_hint": "Имена чувствительны к регистру. Уточните точное написание у человека.",- "send_request": "Отправить заявку",- "sending": "Отправка…",- "request_sent": "Заявка отправлена. Она видна в разделе «Ожидают».",- "accept": "Принять",- "decline": "Отклонить",- "remove": "Удалить из друзей",- "block": "Заблокировать",- "unblock": "Разблокировать",- "cancel_request": "Отменить заявку",- "pending_out": "Ожидает ответа",- "add": "Добавить в друзья",- "empty_online_title": "Никого нет в сети",- "empty_online_body": "Друзья появятся здесь, когда подключатся.",- "empty_all_title": "Пока нет друзей",- "empty_all_body": "Добавьте кого-нибудь по имени пользователя выше.",- "empty_pending_title": "Нет ожидающих заявок",- "empty_pending_body": "Отправленные и полученные заявки отображаются здесь.",- "empty_blocked_title": "Никто не заблокирован",- "empty_blocked_body": "Заблокированные не могут писать вам в личные сообщения."- },- "guild_settings": {- "title": "Настройки {{guild}}",- "back": "Назад к серверу",- "tab_overview": "Обзор",- "tab_roles": "Роли",- "tab_channels": "Каналы",- "tab_invites": "Приглашения",- "tab_bans": "Баны",- "tab_audit": "Журнал аудита",- "overview": "Обзор",- "description": "Описание",- "save": "Сохранить изменения",- "saved": "Сохранено.",- "read_only": "Вы можете смотреть, но для изменения сервера нужно разрешение «Управление сервером».",- "not_found_title": "Сервер не найден",- "not_found_body": "Возможно, он был удалён или вы его покинули.",- "danger": "Опасная зона",- "leave": "Покинуть сервер",- "leave_hint": "Вы потеряете доступ к каналам, пока кто-нибудь не пригласит вас снова.",- "leave_owner_hint": "Передайте права владельца перед выходом — сервер не может остаться без владельца.",- "leave_title": "Покинуть {{guild}}?",- "leave_body": "Вы потеряете доступ к каналам, пока кто-нибудь не пригласит вас снова.",- "leave_confirm": "Покинуть {{guild}}",- "transfer": "Передать права владельца",- "transfer_hint": "Новый владелец получит все разрешения. Вы сохраните свои роли.",- "transfer_title": "Передать {{guild}} другому пользователю?",- "transfer_body": "Он получит все разрешения на этом сервере, включая удаление.",- "transfer_confirm": "Передать права владельца",- "transfer_to": "Новый владелец",- "transfer_pick": "Выберите участника",- "delete": "Удалить сервер",- "delete_hint": "Каналы, сообщения и роли будут удалены. Это действие необратимо.",- "delete_title": "Удалить {{guild}}?",- "delete_body": "Каждый канал, сообщение и роль будут удалены для всех. Это действие необратимо.",- "delete_confirm": "Удалить {{guild}}",- "delete_type": "Введите {{guild}} для подтверждения",- "roles_empty_title": "Ролей пока нет",- "roles_empty_body": "Создайте роль, чтобы выдавать разрешения.",- "everyone_role": "все",- "role_create": "Новая роль",- "role_create_title": "Новая роль",- "role_create_submit": "Создать роль",- "role_name": "Название роли",- "role_name_placeholder": "Модераторы",- "role_color": "Цвет",- "role_hoist": "Показывать отдельно в списке участников",- "role_mentionable": "Любой может упомянуть эту роль",- "role_delete": "Удалить {{name}}",- "role_delete_title": "Удалить роль {{name}}?",- "role_delete_body": "Участники сохранят остальные роли; разрешения, которые давала эта роль, будут утрачены.",- "role_delete_confirm": "Удалить {{name}}",- "role_delete_hint": "Это действие необратимо.",- "perm_group_general": "Общие",- "perm_group_text": "Текстовые",- "perm_group_voice": "Голосовые",- "perm_group_moderation": "Модерация",- "invites_hint": "Ссылка-приглашение позволяет присоединиться к серверу.",- "invite_channel": "Попадёт в",- "invite_channel_any": "Настройки сервера",- "invite_expiry": "Истекает через",- "expiry_30m": "30 минут",- "expiry_1d": "1 день",- "expiry_7d": "7 дней",- "expiry_never": "Никогда",- "invite_uses": "Максимум использований",- "uses_unlimited": "Без ограничений",- "invite_create": "Создать ссылку-приглашение",- "invite_copy": "Скопировать ссылку",- "invites_empty": "Ссылки ещё не создавались в этой сессии.",- "invites_no_list": "Этот сервер не хранит список активных приглашений, поэтому отображается только что созданная ссылка.",- "bans_empty_title": "Никого не забанено",- "bans_empty_body": "Выданные вами баны отображаются здесь, чтобы вы могли их снять.",- "ban_by": "Забанен пользователем {{name}}",- "unban": "Разбанить",- "unban_title": "Разбанить {{name}}?",- "unban_body": "Он сможет снова присоединиться по приглашению.",- "unban_confirm": "Разбанить {{name}}",- "unban_hint": "Он не присоединится автоматически — ему нужно новое приглашение.",- "audit_filter": "Фильтр по действию",- "audit_all": "Все",- "audit_empty_title": "Журнал пуст",- "audit_empty_body": "Записи о модерации и изменениях настроек появятся здесь."- },- "channel_settings": {- "title": "Настройки канала",- "name": "Название канала",- "topic": "Тема",- "slowmode": "Медленный режим",- "slowmode_off": "Выкл.",- "nsfw": "Пометить как чувствительный контент",- "voice_note": "Битрейт и лимит пользователей определяются политикой инстанса и не редактируются здесь.",- "overwrites": "Разрешения на этом канале",- "overwrites_hint": "«Наследовать» использует серверные разрешения роли. «Разрешить» и «Запретить» действуют только здесь.",- "overwrite_target": "Для",- "allow": "Разрешить",- "inherit": "Наследовать",- "deny": "Запретить",- "delete": "Удалить #{{name}}",- "delete_title": "Удалить #{{name}}?",- "delete_body": "Сообщения будут удалены. Это действие необратимо.",- "delete_confirm": "Удалить #{{name}}",- "delete_hint": "Все потеряют историю этого канала."- },- "profile_settings": {- "title": "Ваш профиль",- "hint": "Имя, местоимения, био, цвет и статус",- "preview": "Как вас видят другие",- "display_name": "Отображаемое имя",- "pronouns": "Местоимения",- "pronouns_placeholder": "она/её, он/его, они/их…",- "bio": "О себе",- "accent": "Акцентный цвет",- "save": "Сохранить профиль",- "saved": "Профиль сохранён.",- "avatar_note": "Загрузка аватара и баннера пока недоступна — на этом инстансе нет эндпоинта для загрузки файлов. До этого используются ваша заглавная буква и акцентный цвет.",- "presence": "Статус",- "presence_online": "В сети",- "presence_idle": "Не активен",- "presence_dnd": "Не беспокоить",- "presence_invisible": "Невидимый",- "custom_status": "Пользовательский статус",- "custom_status_placeholder": "В работе до 17:00",- "custom_status_expiry": "Очистить через",- "expiry_never": "Никогда",- "expiry_30m": "30 минут",- "expiry_4h": "4 часа",- "expiry_today": "Сегодня",- "apply_status": "Применить статус",- "no_instance_title": "Нет подключённого сервера",- "no_instance_body": "Сначала подключитесь к серверу OmniDisc — ваш профиль хранится на нём."- },- "sessions": {- "title": "Сессии",- "hint": "Где вы вошли",- "empty_title": "Нет других сессий",- "empty_body": "Только это устройство вошло на этот сервер.",- "current": "Это устройство",- "last_seen": "Последний вход {{when}}",- "revoke": "Выйти",- "revoke_title": "Выйти на {{device}}?",- "revoke_body": "Устройству придётся заново войти, чтобы пользоваться сервером.",- "revoke_confirm": "Выйти на {{device}}",- "revoke_hint": "Сделайте это, если не узнаёте устройство.",- "revoke_others": "Выйти из остальных {{count}} сессий",- "revoke_others_title": "Выйти из всех остальных сессий?",- "revoke_others_body": "Это устройство останется авторизованным. Остальным придётся войти заново.",- "revoke_others_confirm": "Выйти из остальных",- "sign_out_here": "Выйти отсюда",- "unknown_device": "Неизвестное устройство"- },- "perm": {- "VIEW_CHANNEL": "Просматривать канал",- "SEND_MESSAGES": "Отправлять сообщения",- "EMBED_LINKS": "Встраивать ссылки",- "ATTACH_FILES": "Прикреплять файлы",- "ADD_REACTIONS": "Добавлять реакции",- "USE_EXTERNAL_EMOJI": "Использовать внешний эмодзи",- "MENTION_EVERYONE": "Упоминать всех",- "READ_HISTORY": "Читать историю",- "SEND_TTS": "Отправлять текст-в-речь",- "BYPASS_SLOWMODE": "Обходить медленный режим",- "MANAGE_MESSAGES": "Управлять сообщениями",- "PIN_MESSAGES": "Закреплять сообщения",- "MANAGE_CHANNELS": "Управлять каналами",- "MANAGE_ROLES": "Управлять ролями",- "MANAGE_EMOJI": "Управлять эмодзи",- "MANAGE_WEBHOOKS": "Управлять вебхуками",- "MANAGE_GUILD": "Управлять сервером",- "VIEW_AUDIT_LOG": "Просматривать журнал аудита",- "CREATE_INVITES": "Создавать приглашения",- "CHANGE_NICKNAME": "Изменять свой никнейм",- "MANAGE_NICKNAMES": "Управлять никнеймами",- "VIEW_CHANNEL_MEMBERS": "Просматривать список участников",- "KICK_MEMBERS": "Исключать участников",- "BAN_MEMBERS": "Банить участников",- "MODERATE_MEMBERS": "Ставить тайм-аут участникам",- "CONNECT": "Подключаться к голосовым каналам",- "SPEAK": "Говорить",- "STREAM": "Демонстрировать экран",- "VIDEO": "Включать камеру",- "USE_VAD": "Использовать голосовую активацию",- "PRIORITY_SPEAKER": "Приоритетный говорящий",- "MUTE_MEMBERS": "Отключать микрофон участникам",- "DEAFEN_MEMBERS": "Отключать звук участникам",- "MOVE_MEMBERS": "Перемещать участников",- "USE_SOUNDBOARD": "Использовать звуковую панель",- "ADMINISTRATOR": "Администратор"- },- "perm_desc": {- "VIEW_CHANNEL": "Видеть канал и читать его содержимое.",- "SEND_MESSAGES": "Писать в канале.",- "EMBED_LINKS": "Ссылки получают превью-карточку.",- "ATTACH_FILES": "Загружать файлы и изображения.",- "ADD_REACTIONS": "Реагировать на сообщения эмодзи.",- "USE_EXTERNAL_EMOJI": "Использовать эмодзи с других серверов.",- "MENTION_EVERYONE": "Пинговать весь канал сразу.",- "READ_HISTORY": "Видеть сообщения, отправленные до их появления.",- "SEND_TTS": "Отправлять сообщения, которые озвучиваются вслух.",- "BYPASS_SLOWMODE": "Писать без задержки между сообщениями.",- "MANAGE_MESSAGES": "Удалять чужие сообщения.",- "PIN_MESSAGES": "Закреплять и откреплять сообщения в канале.",- "MANAGE_CHANNELS": "Создавать, переименовывать и удалять каналы.",- "MANAGE_ROLES": "Создавать роли и выдавать разрешения.",- "MANAGE_EMOJI": "Добавлять и удалять пользовательские эмодзи.",- "MANAGE_WEBHOOKS": "Создавать и удалять вебхуки.",- "MANAGE_GUILD": "Изменять название, описание и настройки сервера.",- "VIEW_AUDIT_LOG": "Смотреть, кто что менял.",- "CREATE_INVITES": "Создавать ссылки-приглашения на этот сервер.",- "CHANGE_NICKNAME": "Переименовать себя на этом сервере.",- "MANAGE_NICKNAMES": "Переименовывать других участников.",- "VIEW_CHANNEL_MEMBERS": "Открывать список участников канала.",- "KICK_MEMBERS": "Удалять участников; они могут вернуться по приглашению.",- "BAN_MEMBERS": "Удалять участников и блокировать повторное присоединение.",- "MODERATE_MEMBERS": "Временно отключить участника.",- "CONNECT": "Заходить в голосовые каналы.",- "SPEAK": "Использовать микрофон в голосовых каналах.",- "STREAM": "Транслировать экран или окно.",- "VIDEO": "Передавать видео в голосовых каналах.",- "USE_VAD": "Говорить без использования PTT.",- "PRIORITY_SPEAKER": "Остальные становятся тише, пока вы говорите.",- "MUTE_MEMBERS": "Отключать микрофон участникам на сервере.",- "DEAFEN_MEMBERS": "Отключать звук участникам на сервере.",- "MOVE_MEMBERS": "Перемещать участников между голосовыми каналами.",- "USE_SOUNDBOARD": "Воспроизводить звуки с звуковой панели в голосовых каналах.",- "ADMINISTRATOR": "Все разрешения везде, игнорируя настройки каналов."- },- "audit": {- "guild_update": "{{actor}} изменил настройки сервера",- "guild_delete": "{{actor}} удалил сервер",- "guild_transfer": "{{actor}} передал сервер {{target}}",- "guild_create": "{{actor}} создал сервер",- "channel_create": "{{actor}} создал канал",- "channel_update": "{{actor}} изменил канал",- "channel_delete": "{{actor}} удалил канал",- "channel_overwrite": "{{actor}} изменил разрешения канала",- "role_create": "{{actor}} создал роль",- "role_update": "{{actor}} изменил роль",- "role_delete": "{{actor}} удалил роль",- "member_update": "{{actor}} обновил {{target}}",- "member_kick": "{{actor}} исключил {{target}}",- "member_ban": "{{actor}} забанил {{target}}",- "member_unban": "{{actor}} разбанил {{target}}",- "member_leave": "{{target}} покинул сервер",- "message_delete": "{{actor}} удалил сообщение",- "message_bulk_delete": "{{actor}} удалил несколько сообщений",- "message_pin": "{{actor}} закрепил сообщение",- "message_unpin": "{{actor}} открепил сообщение",- "instance_update": "{{actor}} изменил настройки инстанса",- "fallback": "{{actor}} — {{action}} {{target}}"- },- "audit_action": {- "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": "Права владельца переданы"- },- "attachments": {- "title": "Вложения",- "remove": "Удалить {{name}}",- "retry": "Попробовать снова",- "preparing": "Шифрование…",- "uploading": "Отправка… {{percent}}%",- "resuming": "Соединение разорвано, продолжаем с места обрыва…",- "ready": "Готово к отправке",- "failed": "Не удалось загрузить",- "download": "Сохранить в «Загрузки»",- "downloading": "Сохранение…",- "saved": "Сохранено в {{path}}",- "open_image": "Открыть {{name}}",- "close_image": "Закрыть превью",- "encrypted_note": "Зашифровано — сохраните, чтобы открыть",- "too_large": "Файл превышает допустимый размер на этом сервере ({{limit}}).",- "too_many": "К одному сообщению можно прикрепить не более {{count}} файлов.",- "unreadable": "OmniGet не смог прочитать этот файл.",- "expires_in": "истекает через {{minutes}} мин",- "expired": "Срок действия файла истёк, и он был удалён с сервера."- },- "e2ee": {- "dm_locked": "Только вы и {{name}} можете читать эти сообщения",- "group_locked": "Только участники этого разговора могут читать эти сообщения",- "guild_open": "Сообщения на серверных каналах хранятся без шифрования — владелец {{host}} может их читать.",- "preparing": "Шифрование начнётся с первого отправленного здесь сообщения",- "not_ready": "Ожидание настройки шифрования на другом устройстве. Сообщение не отправлено.",- "unavailable": "Это сообщение было отправлено на устройство, которого у вас больше нет. Его текст остался на устройстве получателя.",- "badge": "Сквозное шифрование",- "devices_note": "{{count}} устройств могут читать этот разговор",- "unverified": "Непроверенное устройство",- "unverified_hint": "Это сообщение подписано устройством, которое {{name}} не публиковал. Возможно, это не он — сверьте отпечатки, прежде чем доверять."- },- "devices": {- "title": "Устройства",- "hint": "Какие устройства могут читать ваши зашифрованные сообщения",- "empty_title": "Устройств пока нет",- "empty_body": "Войдите на сервер, и это устройство зарегистрируется, чтобы ваши личные сообщения были зашифрованы.",- "this_device": "Это устройство",- "added": "Добавлено {{when}}",- "last_seen": "Последний вход {{when}}",- "fingerprint": "Отпечаток",- "fingerprint_hint": "Прочитайте его другу по звонку. Если коды совпадают — третьей стороны нет.",- "copy": "Скопировать отпечаток",- "copied": "Скопировано",- "copy_failed": "OmniGet не смог обратиться к буферу обмена.",- "revoke": "Удалить",- "revoke_title": "Удалить {{device}}?",- "revoke_body": "Устройство перестанет получать новые зашифрованные сообщения. Старые останутся на нём.",- "revoke_confirm": "Удалить {{device}}",- "revoke_this_title": "Удалить это устройство?",- "revoke_this_body": "Вы будете разлогинены и потеряете зашифрованную историю на этом устройстве. Резервной копии нет.",- "unnamed": "Безымянное устройство",- "no_history_warning": "Устройство видит только сообщения, отправленные после его подключения. Старые остаются на устройстве получателя."- },- "call": {- "incoming": "{{name}} звонит вам",- "incoming_group": "{{name}} звонит в {{channel}}",- "accept": "Ответить",- "decline": "Отклонить",- "expires_in": "Осталось {{seconds}}с",- "start": "Начать звонок",- "start_hint": "Только голос — ваша камера не видна.",- "in_call": "В звонке",- "leave": "Покинуть звонок",- "joining": "Подключение…"- },- "storage": {- "warning": "Диск сервера заполнен на {{percent}}%. Файлы и так удаляются через {{minutes}} минут; сохраните нужное сейчас.",- "critical": "Диск сервера заполнен на {{percent}}%. Все сохранённые файлы скоро будут удалены для освобождения места.",- "purged": "Диск заполнен, поэтому все {{count}} сохранённых файлов были удалены. Сообщения не затронуты — удалились только вложения.",- "retention_note": "Файлы удаляются с сервера через {{minutes}} минут."- }- },"ytdlp_missing_banner": {"text": "yt-dlp не найден, загрузки невозможны. Установите его в настройках.","open_settings": "Открыть настройки",diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.jsonindex 4a189f6e..5c0e817d 100644--- a/src/lib/i18n/zh-TW.json+++ b/src/lib/i18n/zh-TW.json@@ -476,7 +476,6 @@"marketplace": "插件市场","settings": "設定","about": "關於",- "omnidisc": "Chat","section_primary": "Main","section_app": "App","section_plugins": "Plugins",@@ -5697,818 +5696,6 @@"test_body": "包裹狀態變化時,您將看到此類通知。"}},- "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": "未加密的連線"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.jsonindex 11aea69a..119e298b 100644--- a/src/lib/i18n/zh.json+++ b/src/lib/i18n/zh.json@@ -476,7 +476,6 @@"marketplace": "插件市场","settings": "设置","about": "关于",- "omnidisc": "Chat","section_primary": "主菜单","section_app": "应用","section_plugins": "插件",@@ -5697,818 +5696,6 @@"test_body": "包裹状态变化时,您将看到此类通知。"}},- "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": "未加密的连接"- },- "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)",- "immersive_enter": "Focus mode — hide the app sidebar",- "immersive_exit": "Exit focus mode — show the app sidebar"- },- "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.",- "ptt_conflict_hint": "Another application already claimed this combination. Record a different one, or close the app that owns it.",- "ptt_refused": "The system did not hand this key over, so push-to-talk will not respond.",- "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",- "watch_unsupported": "Watching a stream is not available on this platform yet.",- "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.",- "preview_alt": "Live preview of your shared screen",- "portal_picker": "Your desktop will ask which screen or window to share after you press Share."- },- "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.",- "expires_in": "expires in {{minutes}} min",- "expired": "This file expired and was deleted from the server."- },- "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…"- },- "storage": {- "warning": "This server's disk is {{percent}}% full. Files are deleted after {{minutes}} minutes anyway; save anything you need now.",- "critical": "This server's disk is {{percent}}% full. Every stored file is about to be deleted to free space.",- "purged": "The disk filled up, so all {{count}} stored files were deleted. Messages are untouched — only attachments are gone.",- "retention_note": "Files are deleted from the server after {{minutes}} minutes."- }- },"ytdlp_missing_banner": {"text": "yt-dlp is missing, so downloads cannot start. Install it from Settings.","open_settings": "Open Settings",diff --git a/src/lib/nav-config.test.ts b/src/lib/nav-config.test.tsindex 23f4d0ae..ea1ecd5d 100644--- a/src/lib/nav-config.test.ts+++ b/src/lib/nav-config.test.ts@@ -2,8 +2,8 @@ import { describe, it, expect } from "vitest";import { CORE_NAV_ITEMS } from "./nav-config";describe("CORE_NAV_ITEMS", () => {- it("has the expected 8 core entries", () => {- expect(CORE_NAV_ITEMS).toHaveLength(8);+ it("has the expected 7 core entries", () => {+ expect(CORE_NAV_ITEMS).toHaveLength(7);});it("Nami is in primary group with order 28", () => {@@ -14,13 +14,6 @@ describe("CORE_NAV_ITEMS", () => {expect(nami?.order).toBe(28);});- 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", () => {const home = CORE_NAV_ITEMS.find((i) => i.href === "/");expect(home?.group).toBe("primary");diff --git a/src/lib/nav-config.ts b/src/lib/nav-config.tsindex 16d413a6..f2309e2c 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" | "omnidisc";+ badge?: "downloads";pluginId?: string;order?: number;}@@ -13,7 +13,6 @@ 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: "/tools", labelKey: "nav.tools", icon: "tools", group: "primary", order: 27 },{ href: "/nami", label: "Nami", icon: "nami", group: "primary", order: 28 },{ href: "/marketplace", labelKey: "nav.marketplace", icon: "marketplace", group: "app", order: 30 },diff --git a/src/lib/omnidisc/emoji.ts b/src/lib/omnidisc/emoji.tsdeleted file mode 100644index 0d9dd326..00000000--- a/src/lib/omnidisc/emoji.ts+++ /dev/null@@ -1,110 +0,0 @@-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.tsdeleted file mode 100644index 202711e4..00000000--- a/src/lib/omnidisc/fixtures.ts+++ /dev/null@@ -1,82 +0,0 @@-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.tsdeleted file mode 100644index bc9a4950..00000000--- a/src/lib/omnidisc/permissions.test.ts+++ /dev/null@@ -1,158 +0,0 @@-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.tsdeleted file mode 100644index 1e189d84..00000000--- a/src/lib/omnidisc/permissions.ts+++ /dev/null@@ -1,194 +0,0 @@-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/popover.test.ts b/src/lib/omnidisc/popover.test.tsdeleted file mode 100644index 8c707eef..00000000--- a/src/lib/omnidisc/popover.test.ts+++ /dev/null@@ -1,44 +0,0 @@-import { describe, expect, it } from "vitest";-import { placeMenu, type AnchorRect } from "./popover";--const VIEWPORT = { width: 1000, height: 800 };--function rect(left: number, top: number, width: number, height: number): AnchorRect {- return { left, top, width, height, right: left + width, bottom: top + height };-}--describe("placeMenu", () => {- it("hangs below the anchor, right edges aligned", () => {- const place = placeMenu(rect(600, 200, 100, 30), { width: 180, height: 160 }, VIEWPORT);- expect(place).toEqual({ left: 520, top: 234 });- });-- it("aligns left edges when asked", () => {- const place = placeMenu(rect(600, 200, 100, 30), { width: 180, height: 160 }, VIEWPORT, {- align: "start",- });- expect(place.left).toBe(600);- });-- it("flips above when there is no room below", () => {- const place = placeMenu(rect(600, 700, 100, 30), { width: 180, height: 160 }, VIEWPORT);- expect(place.top).toBe(536);- });-- it("stays below and clamped when neither side fits", () => {- const place = placeMenu(rect(600, 300, 100, 30), { width: 180, height: 900 }, VIEWPORT);- expect(place.top).toBe(8);- });-- it("keeps a wide menu inside the left edge", () => {- const place = placeMenu(rect(20, 200, 30, 30), { width: 180, height: 160 }, VIEWPORT);- expect(place.left).toBe(8);- });-- it("keeps a menu inside the right edge", () => {- const place = placeMenu(rect(960, 200, 30, 30), { width: 180, height: 160 }, VIEWPORT, {- align: "start",- });- expect(place.left).toBe(812);- });-});diff --git a/src/lib/omnidisc/popover.ts b/src/lib/omnidisc/popover.tsdeleted file mode 100644index e0d26e0e..00000000--- a/src/lib/omnidisc/popover.ts+++ /dev/null@@ -1,55 +0,0 @@-export type AnchorRect = {- left: number;- top: number;- right: number;- bottom: number;- width: number;- height: number;-};--export type PopoverSize = { width: number; height: number };--export type Viewport = { width: number; height: number };--export type PopoverPlacement = { left: number; top: number };--export type PlaceOptions = {- align?: "start" | "end";- gap?: number;- margin?: number;-};--function clamp(value: number, min: number, max: number): number {- if (max < min) return min;- return Math.min(Math.max(value, min), max);-}--export function placeMenu(- anchor: AnchorRect,- size: PopoverSize,- viewport: Viewport,- options: PlaceOptions = {},-): PopoverPlacement {- const gap = options.gap ?? 4;- const margin = options.margin ?? 8;- const wanted = options.align === "start" ? anchor.left : anchor.right - size.width;- const left = clamp(wanted, margin, viewport.width - size.width - margin);- const below = anchor.bottom + gap;- const above = anchor.top - gap - size.height;- const fitsBelow = below + size.height <= viewport.height - margin;- const fitsAbove = above >= margin;- const top = fitsBelow || !fitsAbove ? clamp(below, margin, viewport.height - size.height - margin) : above;- return { left, top };-}--// A menu inside `contain: layout` is positioned against that box and clipped by-// the scroller around it, so even `position: fixed` cannot escape. Moving the-// node to the body is the only way out.-export function portal(node: HTMLElement) {- document.body.appendChild(node);- return {- destroy() {- node.remove();- },- };-}diff --git a/src/lib/omnidisc/snowflake.ts b/src/lib/omnidisc/snowflake.tsdeleted file mode 100644index b08e6c51..00000000--- a/src/lib/omnidisc/snowflake.ts+++ /dev/null@@ -1,28 +0,0 @@-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.tsdeleted file mode 100644index f458fd36..00000000--- a/src/lib/omnidisc/types.ts+++ /dev/null@@ -1,269 +0,0 @@-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;- /// When the server deletes the bytes. Files here are temporary by design.- expiresAt?: number;- expired?: boolean;-}--export type StoragePressure = "ok" | "warning" | "critical" | "purged";--export interface OmnidiscStorage {- usedBytes: number;- totalBytes: number;- ratio: number;- level: StoragePressure;- attachmentTtlSeconds: number;- purgedFiles?: number;-}--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.tsdeleted file mode 100644index 40bd50b6..00000000--- a/src/lib/omnidisc/wire.ts+++ /dev/null@@ -1,360 +0,0 @@-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,- expiresAt: parseTimestamp(raw.expires_at),- expired: raw.expired === true,- };-}--function parseTimestamp(raw: unknown): number | undefined {- const text = str(raw);- if (!text) return undefined;- const ms = Date.parse(text);- return Number.isFinite(ms) ? ms : undefined;-}--export function parseStorage(raw: unknown): import("./types").OmnidiscStorage | null {- if (!isRecord(raw)) return null;- const level = str(raw.level);- if (level !== "ok" && level !== "warning" && level !== "critical" && level !== "purged") {- return null;- }- return {- usedBytes: num(raw.used_bytes) ?? 0,- totalBytes: num(raw.total_bytes) ?? 0,- ratio: num(raw.ratio) ?? 0,- level,- attachmentTtlSeconds: num(raw.attachment_ttl_seconds) ?? 1800,- purgedFiles: num(raw.purged_files),- };-}--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.tsdeleted file mode 100644index c5c3b120..00000000--- a/src/lib/stores/omnidisc-store.svelte.ts+++ /dev/null@@ -1,2699 +0,0 @@-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,- parseStorage,- 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";-export const DEFAULT_INSTANCE_URL = "https://chat.tonho.wtf";-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 storageByInstance = $state<Record<string, import("$lib/omnidisc/types").OmnidiscStorage>>({});--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 getStorage(- instanceId: string | null,-): import("$lib/omnidisc/types").OmnidiscStorage | null {- return instanceId ? (storageByInstance[instanceId] ?? null) : null;-}--/// Files are deleted on a clock, so the client needs the clock to show a-/// countdown rather than letting an attachment quietly stop working.-export function getAttachmentTtlSeconds(instanceId: string | null): number {- return getStorage(instanceId)?.attachmentTtlSeconds ?? 1800;-}--export function isMemberListOpen(): boolean {- return memberListOpen;-}--export function toggleMemberList() {- memberListOpen = !memberListOpen;-}--const IMMERSIVE_KEY = "omnidisc.immersive";--function loadImmersive(): boolean {- try {- return localStorage.getItem(IMMERSIVE_KEY) === "1";- } catch {- return false;- }-}--let immersive = $state(loadImmersive());--export function isImmersive(): boolean {- return immersive;-}--export function toggleImmersive() {- immersive = !immersive;- try {- localStorage.setItem(IMMERSIVE_KEY, immersive ? "1" : "0");- } catch {- /* per-viewer convenience only */- }-}--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);- if (!windowFocused()) void maybeNotify(instance, message);- } 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 "STORAGE_STATUS": {- const parsed = parseStorage(d);- if (parsed) storageByInstance = { ...storageByInstance, [instance.id]: parsed };- 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.tsdeleted file mode 100644index da5e3c4b..00000000--- a/src/lib/stores/omnidisc-store.test.ts+++ /dev/null@@ -1,86 +0,0 @@-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.tsdeleted file mode 100644index 775e433f..00000000--- a/src/lib/stores/omnidisc-stream-store.svelte.ts+++ /dev/null@@ -1,356 +0,0 @@-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;-}--export interface MediaCapabilities {- voice: boolean;- screen_share: boolean;- stream_viewer: boolean;-}--/**- * What the interface assumes until the backend answers — which it does on- * mount, before anyone can click. Assuming "yes" keeps the buttons from- * blinking into existence on the platforms where they do work; when the answer- * is "no" they end up disabled with the reason attached, never silently gone.- */-const ASSUMED_CAPABILITIES: MediaCapabilities = {- voice: true,- screen_share: true,- stream_viewer: true,-};--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 capabilities = $state<MediaCapabilities>(ASSUMED_CAPABILITIES);-let previewImage = $state<string | null>(null);--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 getMediaCapabilities(): MediaCapabilities {- return capabilities;-}--export async function refreshMediaCapabilities(): Promise<void> {- try {- capabilities = await invoke<MediaCapabilities>("omnidisc_media_capabilities");- } catch (e) {- console.warn("[omnidisc] media capabilities unavailable", errorText(e));- }-}--export function isStreamer(userId: string): boolean {- return streamers[userId] === true;-}--export function getStreamerIds(): string[] {- return Object.keys(streamers).filter((id) => streamers[id]);-}--export function getStreamPreview(): string | null {- return previewImage;-}--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;- user_id?: string;- active?: boolean;- image?: string;- state?: string;-}--export async function initStream(): Promise<void> {- if (initialized) return;- initialized = true;- void refreshMediaCapabilities();- try {- unlisten = await listen<StreamEventPayload>("omnidisc://voice", (event) => {- const p = event.payload;- if (p.type === "stream_stopped") {- publishing = null;- previewImage = null;- } else if (p.type === "stream_preview" && typeof p.image === "string") {- previewImage = p.image;- } else if (p.type === "stream" && typeof p.user_id === "string") {- markStreamer(p.user_id, p.active === true);- if (p.active !== true && watchingIds.includes(p.user_id)) {- void unwatchStream(p.user_id);- }- } else if (p.type === "state" && (p.state === "idle" || p.state === "failed")) {- streamers = {};- previewImage = null;- publishing = null;- for (const id of watchingIds) void unwatchStream(id);- }- });- } 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.tsdeleted file mode 100644index 5f15d731..00000000--- a/src/lib/stores/omnidisc-voice-store.svelte.ts+++ /dev/null@@ -1,740 +0,0 @@-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 pttRegistered = $state<boolean | null>(null);-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 micSilent = $state(false);--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 isMicSilent(): boolean {- return micSilent;-}--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() };- if ((p.peak ?? 0) > 0 && micSilent) micSilent = false;- 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":- if (kind === "input") {- micSilent = true;- return;- }- 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 } } });- await refreshPttStatus();- try {- await invoke("omnidisc_voice_ptt", { pressed: false });- } catch {- return;- }-}--/**- * `null` while unknown or while no key is set; `false` when the OS refused to- * hand the combination over — Windows gives it to whoever asked first, macOS- * wants Accessibility permission. Both used to fail silently, so the key just- * did nothing.- */-export function isPttRegistered(): boolean | null {- return pttRegistered;-}--export async function refreshPttStatus(): Promise<void> {- try {- const status = await invoke<{ binding: string; registered: boolean }>(- "omnidisc_voice_ptt_status",- );- pttRegistered = status.binding ? status.registered : null;- } catch (e) {- pttRegistered = null;- console.warn("[omnidisc] push-to-talk status unavailable", errorText(e));- }-}--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.tsdeleted file mode 100644index b88c0455..00000000--- a/src/lib/stores/omnidisc-voice-store.test.ts+++ /dev/null@@ -1,47 +0,0 @@-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");-}, 30000);--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 0b763291..a6f1e3f8 100644--- a/src/lib/stores/settings-store.svelte.ts+++ b/src/lib/stores/settings-store.svelte.ts@@ -91,10 +91,6 @@ export type AppSettings = {app_id: string;large_image_key: string;};- omnidisc?: {- enabled?: boolean;- voice?: OmnidiscVoiceSettings;- };league?: {enabled?: boolean;auto_accept?: boolean;@@ -138,16 +134,6 @@ 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/lib/ui-lint.test.ts b/src/lib/ui-lint.test.tsindex aa696079..dc2f8547 100644--- a/src/lib/ui-lint.test.ts+++ b/src/lib/ui-lint.test.ts@@ -67,7 +67,7 @@ describe("UI Lint Policies & Target Runner", () => {const shellPlan = resolveTargets(["--shell"]);expect(shellPlan.targets).toEqual(SHELL_ROUTES);- expect(SHELL_ROUTES).toContain("/omnidisc");+ expect(SHELL_ROUTES).toContain("/nami");const docShort = resolveTargets(["docs/mcp"]);expect(docShort.surface).toBe("docs");@@ -81,7 +81,6 @@ describe("UI Lint Policies & Target Runner", () => {expect(ALL_APP_THEMES.length).toBe(14);const mockScript = buildTauriMockInitScript("dark");- expect(mockScript).toContain("omnidisc_connect");expect(mockScript).toContain("plugin:courses|courses_list_platforms");});diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelteindex 98d266a2..0e23b7e6 100644--- a/src/routes/+layout.svelte+++ b/src/routes/+layout.svelte@@ -9,12 +9,6 @@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,- isImmersive,- initOmnidisc,- } from "$lib/stores/omnidisc-store.svelte";import { getSettings, loadSettings } from "$lib/stores/settings-store.svelte";import { queueExternalPrefill, type ExternalUrlEvent } from "$lib/stores/external-url-store.svelte";import Toast from "$components/toast/Toast.svelte";@@ -52,9 +46,7 @@: []);- let coreNavItems = $derived(- CORE_NAV_ITEMS.filter((item) => item.href !== "/omnidisc" || (getSettings()?.omnidisc?.enabled ?? true))- );+ let coreNavItems = $derived(CORE_NAV_ITEMS);let allNav = $derived([...coreNavItems, ...leagueNavItems, ...pluginNavItems].sort((a, b) => (a.order ?? 50) - (b.order ?? 50)));let primaryNav = $derived(allNav.filter((item) => item.group === "primary"));@@ -71,11 +63,8 @@let counts = $derived(getCounts());let badgeLabel = $derived(counts.badge > 99 ? "99+" : String(counts.badge));- let chatBadgeCount = $derived(getChatMentionCount() || getChatUnreadCount());let settings = $derived(getSettings());- let isStreamPopout = $derived(page.url.pathname === "/omnidisc/stream");- let hideAppSidebar = $derived(page.url.pathname.startsWith("/omnidisc") && isImmersive());let isCoreRoute = $derived(page.url.pathname === "/" ||page.url.pathname.startsWith("/downloads") ||@@ -141,13 +130,6 @@.catch(() => {});}- let omnidiscStarted = false;- $effect(() => {- if (omnidiscStarted || !(getSettings()?.omnidisc?.enabled ?? true)) return;- omnidiscStarted = true;- void initOmnidisc();- });-onMount(() => {initDownloadListener();// If `get_settings` failed while the shell was booting, the sidebar has no@@ -352,15 +334,8 @@});</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}>- {#if !hideAppSidebar}- <AppSidebar {primaryNav} {appNav} {pluginNav} {badgeLabel} {chatBadgeCount} />- {/if}+ <AppSidebar {primaryNav} {appNav} {pluginNav} {badgeLabel} /><div class="shell-body"><AppToolbar />@@ -435,7 +410,6 @@</main></div></div>-{/if}<Toast /><CommandPalette />@@ -513,15 +487,6 @@overflow: hidden;}--- .stream-popout {- width: 100vw;- height: 100vh;- overflow: hidden;- background: var(--bg);- }-.global-update-banner {display: flex;align-items: center;diff --git a/src/routes/omnidisc/+layout.svelte b/src/routes/omnidisc/+layout.sveltedeleted file mode 100644index 535f9b67..00000000--- a/src/routes/omnidisc/+layout.svelte+++ /dev/null@@ -1,141 +0,0 @@-<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 StorageBanner from "$components/omnidisc/StorageBanner.svelte";- import type { Snippet } from "svelte";-- let { children }: { children: Snippet } = $props();-- let settings = $derived(getSettings());- let enabled = $derived(settings?.omnidisc?.enabled ?? true);- 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">- <StorageBanner />- {@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: transparent;- 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: none;- 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.sveltedeleted file mode 100644index be9f0ce4..00000000--- a/src/routes/omnidisc/+page.svelte+++ /dev/null@@ -1,168 +0,0 @@-<script lang="ts">- import { onMount } from "svelte";- import { page } from "$app/state";- import { goto } from "$app/navigation";- import { t } from "$lib/i18n";- import {- hasInstances,- resetConnect,- connectInstance,- getConnectStep,- DEFAULT_INSTANCE_URL,- } 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);-- onMount(() => {- if (!hasInstances() && !addRequested && getConnectStep() === "idle") {- void connectInstance(DEFAULT_INSTANCE_URL);- }- });-- 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: none;- 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.sveltedeleted file mode 100644index fbf7f35e..00000000--- a/src/routes/omnidisc/dm/[id]/+page.svelte+++ /dev/null@@ -1,122 +0,0 @@-<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.sveltedeleted file mode 100644index ce9bf035..00000000--- a/src/routes/omnidisc/friends/+page.svelte+++ /dev/null@@ -1,543 +0,0 @@-<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: none;- }-- .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: none;- 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: none;- 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: none;- }-- .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: none;- 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.sveltedeleted file mode 100644index 8ef338e4..00000000--- a/src/routes/omnidisc/g/[guild]/[channel]/+page.svelte+++ /dev/null@@ -1,134 +0,0 @@-<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: none;- }-- .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.sveltedeleted file mode 100644index 32f70d76..00000000--- a/src/routes/omnidisc/g/[guild]/settings/+page.svelte+++ /dev/null@@ -1,564 +0,0 @@-<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: none;- }-- .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: none;- 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: none;- 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: none;- 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: none;- 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: none;- 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: none;- }- }-</style>diff --git a/src/routes/omnidisc/settings/+page.svelte b/src/routes/omnidisc/settings/+page.sveltedeleted file mode 100644index 40b1bae7..00000000--- a/src/routes/omnidisc/settings/+page.svelte+++ /dev/null@@ -1,97 +0,0 @@-<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: none;- }-- .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.sveltedeleted file mode 100644index a0286ee0..00000000--- a/src/routes/omnidisc/stream/+page.svelte+++ /dev/null@@ -1,240 +0,0 @@-<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>