From 57f826b13e434ab8a626ef89103255fff6d1d524 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 20:51:06 +0000 Subject: [PATCH 01/42] docs: UI review, and what to take from TeamSpeak 6 and Discord A review of the desktop and phone UI (from the code and the screenshots), the classic and TS6 client features Voelin lacks, the Discord ideas that fit a TeamSpeak client (client-only, gateway or existing TS features), and an order of work. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- docs/research/ui-review.md | 348 +++++++++++++++++++++++++++++++++++++ 1 file changed, 348 insertions(+) create mode 100644 docs/research/ui-review.md diff --git a/docs/research/ui-review.md b/docs/research/ui-review.md new file mode 100644 index 0000000..35ac498 --- /dev/null +++ b/docs/research/ui-review.md @@ -0,0 +1,348 @@ +# UI review, and what to take from TeamSpeak 6 and Discord + +**Question.** How good is the UI, what should change, and which features of +TeamSpeak 6 and Discord should Voelin port or add? + +**Answer, short.** The UI is not bad. It has a real design system, two +themes, a phone layout from the same components, screen reader labels and a +Ctrl+K palette. Its problems are elsewhere: + +1. The desktop shows the same things two or three times, and the app's own + advertising takes space from the content. +2. Behaviour every TeamSpeak user expects is missing: right-click menus, drag + and drop, moderation, channel creation, whisper, sounds. +3. Some things show wrong data: raw BBCode, raw spacer names, a password lock + that cannot be opened. + +Against TeamSpeak 6, the gap is mostly the *classic* client (admin, +whisper, sounds, chat formatting). TS6's genuinely new features Voelin +mostly has already, or beats (Android, channel history, simulcast, the +studio). Against Discord, the most useful ideas need no server support at +all: unread state, search, notification levels per channel, ducking, hotkeys, +a call bar, an overlay. + +What was checked: + +- The UI at `1064cce`: the Slint code, plus the screenshots in + `docs/screenshots/` (taken 2026-10-03/04, sample data). +- TeamSpeak 6: client 6.0.0-beta4.1 and server 6.0.0-beta13.1, from their + release notes and the TeamSpeak forum. +- Discord: its changelogs up to September 2026. + +Sources are at the end. + +## 1. The UI + +### Keep + +- `Theme` tokens for every colour and size. The light palette is complete, + and the font scale works everywhere. +- The component catalogue (`ui/components/`) is used consistently. The + screens look like one app. +- The phone layout is built from the same components. Its bottom navigation + is sane: Home, Servers, Chats, Activity, You. +- About 470 `accessible-*` attributes. Tree rows have default actions and + descriptions ("talking", "streaming", "microphone off"). +- The Ctrl+K palette shows keyboard hints. The member card, the event cards, + the pins and topics drawers and the Stream Studio are good screens. + +### Wrong or broken (fix first) + +| What | Where | Why it matters | +|---|---|---| +| BBCode is shown raw in chat. Only `[URL=ts3file://…]` file links are turned into cards (`src/vm/chat.rs:84`). Previews strip the tags (`src/vm/social.rs:53`) but the message view does not | `ui/screens/chat.slint` (`RichText` = text + emoji runs only) | Every official TS3/TS6 client sends `[b]`, `[url]`, `[color]` and `[img]`. The server welcome message is BBCode too (see the sample `[b]Nightfall Guild[/b]` in `src/dev.rs:428`) | +| Links in chat are not clickable | chat | People post links all day | +| Message text cannot be copied: no selection, no "Copy text" action | `MessageRow` hover actions: react, pin, topic only | Basic | +| Only `[cspacerN]` is understood. `[spacer]`, `[lspacer]`, `[rspacer]` and `[*spacer]` (repeated characters such as `[*spacer]---`) show their raw names | `src/vm/tree.rs:107` | Most community servers decorate their tree with these, so it looks broken on exactly those servers | +| A locked channel shows a lock, but joining always sends `password: None`, and nothing asks for the password | `src/bind/servers.rs:26` | The join fails with a server error and the user has no way in | +| A poke is always sent with an empty message | `src/members.rs:99` | A poke is usually *about* something | +| Invite links can be made but not opened. Voelin copies `ts3server://` links, but registers no URL handler: no `MimeType` in the `.desktop` file, no protocol in the installer, and `main.rs` does not read a link argument | packaging, `src/main.rs` | Half a feature; also blocks TS6's `tmspk.gg` invite links | +| Other clients' badges are parsed (`voelin-model/src/presence.rs:110`) but never shown | members, tree | TS6 users care about their badges | +| The priority speaker is shown with an icon, but others are not dimmed by `virtualserver_priority_speaker_dimm_modificator` (the server's dimming level for a priority speaker, −18 dB by default) | audio mixer | Every official client dims others while a priority speaker talks | +| The README and `docs/ui.md` screenshots still show the "via relay" chips, which `8deb778` removed | `docs/screenshots/` | The first impression is outdated. Regenerate them with `VOELIN_SCREENSHOT` | + +### Desktop layout: too much repetition + +At 1440×960 the server page has four columns: the rail (72), the sidebar +(264), the chat (~770) and the members panel (~280). + +- **The same people are shown up to three times.** On the voice page you + see who is in Chill Zone in the tree under the channel, as the large + avatars on the stage, and again as "In Voice — 5" in the members panel. + On the chat page you see them in the tree and in the panel. On + TeamSpeak the tree *is* the member list. + - Close the members panel by default whenever the tree shows clients. + Keep it for observe-only servers, for searching, and for groups. + - Or offer one setting, "people in the tree / in a panel" (the Discord + model), and show them only once. +- **The top bar (56 px) adds little.** It holds a second Voelin logo, the + search field, the bell, the members toggle and help. + - Drop the wordmark, since the rail already has the logo. + - Move the members toggle into the chat header, where it also is. + - Then the bar can be lower, or merged with the chat header. +- **The same actions appear several times.** + - The settings gear is both at the bottom of the rail and in the user + card. + - On Home, "Add a Server" appears **four times**: the hero button, the + sidebar's Quick Actions, the "Your Servers" link and the right column's + Quick Actions. + - Quick Actions appear on both the left and the right. + - The "Friends Online" bubbles and the "Friend Activity" column list the + same people. +- **The app advertises itself.** + - The Home hero is a carousel ("Voice, chat and streams on TeamSpeak + servers. Talk. Watch. Share."). + - The sidebar's lower half shows decorative art ("Hang out / Play + together / Find your people") on Home, Friends and Direct Messages. + - That is a quarter of the screen for someone who already installed the + app. Show the hero on first run only. Use the space for "continue where + you left off" (last server and channel, with Join), unread mentions and + pinned DMs. +- **"Join a Server" and "Add a Server"** are two names for nearly the same + dialog. Make it one dialog with two buttons: *Connect* and *Save*. +- **The chat header squeezes the channel topic.** "Pinned Messages" and + "Topics" are wide labelled buttons, so the topic is cut short ("Hang out, + chat, and explore t…"). Make them icon buttons with a tooltip and a + count. +- **Direct messages live in two places.** The chat tabs mix the server, the + channels and DMs (`@Kairo`, `@Mira`…), and there is also a Direct + Messages page. Keep channels in the tabs and DMs on their page. If the + tabs are still wanted, add "Open in a tab" as an option. +- **Channel icons disagree.** The tree draws voice channels with a speaker, + but the chat header and the search results use `#`. On TeamSpeak every + channel is a voice channel with a chat, so pick one icon. +- **Unlabelled numbers.** The "75" and "100" at the right of member rows + are talk power. Label them ("TP 75"), or leave them to the member card. +- **Tree avatars are 22 px with two-letter initials** ("RI", "DE"), which + is unreadable. Use the picture, one letter, or a coloured dot. +- **The server rail is all blue squares with initials.** Use the server's + icon (`virtualserver_icon_id`), or a different hue per server (`Avatar` + already has `tint`). +- **The voice page has no call bar.** Mute and deafen exist only in the + sidebar's user card. The phone has a bottom bar (Mute, Deafen, Go Live, + Share, Leave). Give the desktop voice page the same bar under the stage, + with mute and deafen showing their state. +- **The voice page leaves little room for chat.** Under the stage and the + stream card, the chat gets about 300 px. Collapse the stage into a strip + of avatars when the chat scrolls, or add a divider that can be dragged. +- **The stream card shows a placeholder icon**, not a thumbnail of the + stream. +- **The stream viewer:** + - The header (streamer, title, "12 watching") is drawn straight on the + video, so it collides with the picture. Add top and bottom gradients, + and hide the controls after 2–3 s without mouse movement. + - Add a theatre mode between "in the page" and "full screen" that hides + the sidebar and the members panel. + - Make pop-out a real window (it is documented as missing). +- **Pop-ups have no edge.** The notifications panel has no shadow and no + scrim (the software renderer draws no shadows), so it blends into the + page behind it; LIVE badges from behind show next to it. Give pop-ups + `border-strong`, a darker surface, or a light scrim. Also, its fixed + height leaves an empty area. +- **Light theme:** the server card's title is dark text on the dark banner. + Text over pictures should be white with a scrim in both themes. +- **Older messages need a click.** Load them when the list reaches the top, + and keep the button as a fallback. +- **Unread is not marked.** There is no "new messages" divider and no + "jump to unread". Unread counts live in memory only. +- **Icon-only buttons.** The friend rows (message, poke, join, watch) and + the DM header (poke, join, profile, more) need visible tooltips. + +### Settings: twelve sections that overlap + +- **Streaming settings are scattered.** Streaming permissions are in + Voice & Video, Streaming and Privacy. Stream quality is in Voice & Video + and Streaming. Devices lists the microphones, speakers and cameras that + Voice & Video lists too. Suggested sections: + - **Voice**: microphone, output, processing, input mode and sensitivity. + - **Video & Streaming**: camera, quality, codec, simulcast, permissions, + recording. + - Make **Devices** a read-only diagnostics page, or drop it. +- **The voice activation threshold is in Keybinds**, away from the level + meter. Discord and TS6 put the input mode and the threshold on the meter. + `Meter` already has `threshold` and `show-threshold`. +- **"My Account" vs "Profiles" is unclear.** Call them "myTeamSpeak + account" and "Identities"; Profiles is `identities` underneath anyway. +- **Device names are cut off and confusing.** One microphone reads "System + default (Default ALSA Output (cu…"; it is called an Output, yet it is a + microphone. Show the PipeWire/Pulse description, with the full name in a + tooltip. +- **The phone shows Keybinds.** It has no keyboard in most cases. + +### Phone + +- **The voice screen:** + - It has two Leave buttons, in the header and in the bottom bar. + - Two headers repeat each other ("Voelin / Nightfall Guild", then + "Chill Zone"). + - Below the player and the avatar strip, the chat shows about two + messages. + - There is a microphone button next to the composer as well as Mute in + the bar. Say which is hold-to-talk. +- **The Servers tab names the server three times**: the top bar, the server + pills and a banner card about 130 px tall. +- **Home:** the marketing hero takes about a quarter of the screen. +- **Untested on a device** (`docs/android.md`). Dialogs ignore the safe + areas, and audio focus is not handled. Expect more issues on the first + real device. + +## 2. What to take from TeamSpeak 6 + +TS6 is still a beta: client 6.0.0-beta4.1 (2026-05-27), server +6.0.0-beta13.1 (2026-09-22). Most of what its users would miss in Voelin +is not new in TS6. It is the classic client that TS3 already had. + +### 2a. Classic client features (TS3 and TS6 both have them) + +| Feature | Voelin today | Notes | +|---|---|---| +| Right-click / long-press menus on channels and clients | none (click = chat or card, double-click = join) | The way TS users do everything. Channel menu: join, chat, edit, subscribe, copy link. Client menu: whisper, poke with a message, volume, mute, move, kick, ban, groups, info | +| Moving clients by drag and drop | none | Also: dragging channels to sort them | +| Kick from channel or server, ban, ban list | none (`Command` has no variant) | | +| Creating, editing and deleting channels: temporary, semi-permanent, permanent; password; max clients; codec quality; topic; description | none | Without it a user cannot even open a temporary channel, the most common TS action | +| Assigning server and channel groups, privilege keys (tokens) | none | | +| Permission editor | none | TS6 discusses a simpler "easy view"; start there | +| Server edit, "Recent server events" (log), complaints, client database, snapshots (TS6 beta4) | none | For admins; lower priority | +| Whisper lists and whisper hotkeys | incoming whispers only (`voelin-audio/src/encode.rs:90`: C2S only) | A TS signature feature: team leads whisper to the other leads | +| Asking for talk power | none (`client_talk_request` is not modelled) | Moderated channels | +| Channel description (BBCode, pictures) | none (`ChannelInfo` has the topic only) | Shown when a channel is selected | +| Server welcome message and host message in the chat | only stripped, in Home's news | Official clients print them in the Server tab, and host message mode 3 as a dialog | +| Notification sounds (sound pack): someone joined or left the channel, poke, message, connection lost, muted | none | Important for a voice app used while gaming: people do not look at the window | +| Hotkeys for mute, deafen, away, whisper, switching channel | PTT only | | +| Away with a message, auto-away when idle, mute while away | away is only shown | | +| Subscribing to channels one by one | always all channels (`voice.rs:424`) | Costs bandwidth and presence noise on large servers | +| Bookmark folders, importing the official clients' bookmarks | flat list; no import | TS6 syncs bookmarks through myTeamSpeak | +| Client info: version, platform, connected for, idle for, country flag, badges | partly (country as text) | | +| A file browser for the channel's files | none (the engine has `ListFiles`, `DeleteFiles`, `RenameFile`, `CreateDirectory`) | Only the UI is missing | +| Uploading an avatar | none (the engine has `SetAvatar`) | Only the UI is missing | +| Server and channel group icons next to names | crown, shield, chips | TS shows the group icons right of the name; servers rely on them | + +### 2b. What is new in TS6 + +| Feature | Status in TS6 | Voelin | Recommendation | +|---|---|---|---| +| Chat editor: Markdown with live preview, toolbar, slash commands, undo; tables, code, KaTeX, Mermaid; full BBCode (beta4) | shipped | plain text | Render BBCode first: `b i u s url img color size quote code list table`. Then a composer with a formatting toolbar that writes BBCode. Check what beta4 puts on the wire for channel chat before matching its Markdown | +| YouTube inline, picture lightbox with zoom and pan, GIFs | shipped | picture overlay for `ts3file://` pictures only | Add http(s) pictures (opt-in, size-limited) and zoom/pan in the overlay | +| Several streams of a channel at once, pause, hide your own and inactive streams, auto-focus | shipped | one stream at a time (`viewer-streamer-id`) | Show a grid of the channel's streams on the voice page | +| Camera as a quick share | shipped | camera only as a Stream Studio source | Add "Camera" to the Share menu | +| Viewer limit, privacy (channel / contacts / private), join requests | shipped (fixed in beta4) | permissions plus accept/deny exist | Add the viewer limit | +| Global chat: DMs and group chats across servers, through myTeamSpeak (Matrix based, optional E2EE), with offline delivery, reply, edit, delete, reactions, pins, search | shipped | DMs need a voice connection to the peer's server | The largest interop item. Voelin already signs in to myTeamSpeak. Research the chat service (extend `research/myteamspeak.md`); it would give real DMs with official TS6 users, and streaming in DMs | +| myTeamSpeak cloud sync: bookmarks, contacts, group chats, badges | shipped | sign-in only (`docs/identity.md:239`) | Sync bookmarks and contacts first | +| Direct calls 1:1 with picture-in-picture | alpha (2026-08-20) | — | Wait; needs the global chat | +| Multi-track recording (a track per speaker) | alpha (2026-09-04) | the Studio records streams | Possible later with the Studio's recorder | +| Per-application audio for screen sharing | alpha | **already in Voelin** | — | +| Server directory and discovery, Communities (hosted servers) | shipped | — | A "Browse servers" page if the directory can be read | +| Several PTT bindings, voice activation modes (volume gate / hybrid / automatic) | shipped | one PTT key, one VAD | Several keys; an automatic threshold | +| Auto-connect to bookmarks (optionally muted), a hotkey to stream the focused application | shipped | — | Cheap | +| Custom themes (CSS extensions), custom fonts | shipped | dark/light | CSS does not apply to Slint, but every colour is a `Theme` token: an accent picker, a true-black theme, and importing token sets as JSON are cheap | +| Server snapshots from the client | shipped | — | Admin; later | +| Server-routed streaming (SFU) | announced, unreleased | — | Follow the server releases; it changes the stream negotiation | + +**Where Voelin is already ahead of TS6.** Don't spend time catching up on +these; put them forward instead. + +- An Android app. TS6 has no mobile client. +- Channel chat history, pins, reactions, topics and events through the + gateway. TS6 channel chat is not persistent and has no edit, delete or + reactions. +- Chatting in channels and seeing presence without joining. +- Simulcast layers, the Stream Studio (scenes, mixer, replay buffer), + AV1/VP8 decoding. +- Push-to-talk on Wayland through the portal. + +## 3. What to take from Discord + +The TeamSpeak protocol has no message ids, so some ideas need the `tsgw` +gateway. The table says which need what: + +- **client**: works on any server. +- **gateway**: needs `tsgw`. Users without a gateway still see the plain + message. +- **TS**: maps onto a TeamSpeak feature that already exists. + +| Feature | Needs | Notes | +|---|---|---| +| Read state per channel that survives restarts, a "new messages" divider, jump to unread, Esc marks read, Alt+↑/↓ and Alt+Shift+↑/↓ to move between channels and unreads | client | The store already keeps history; keep a "last read" per chat | +| Searching messages (`from:`, `in:`, `has:file`, before and after a date) | client | SQLite FTS5 over the stored history | +| Notification level per server and channel (all / mentions / nothing), mute for 1 h / 8 h / until switched back | client | Today the levels are per kind only | +| A Mentions tab in the bell, mentions highlighted in the chat, @ autocomplete in the composer | client | Mentions are already detected (`vm/social.rs:104`) | +| Typing indicator in DMs | client / TS | `clientchatcomposing` is declared and unused | +| Global mute and deafen hotkeys (Ctrl+Shift+M / D), a shortcut sheet on Ctrl+/, mouse back and forward | client | | +| Ducking: other apps get quieter while someone talks | client | Windows session volume; PipeWire stream volume | +| A call bar on the voice page | client | See §1 | +| Overlay: who is talking and our mute state, as a transparent always-on-top window that does not hook into games | client | Discord rebuilt its overlay this way in 2025 | +| Streamer mode: hide addresses, unique ids and server passwords, on its own when the Studio is live or OBS runs | client | Home shows `127.0.0.1:9987` today | +| Compact message layout, UI density, a true-black theme, an accent colour | client | Tokens make this cheap | +| Soundboard: short clips mixed into *our own* voice | client | Everyone hears it on any server, since it is just our voice. The gateway could share a server's sounds; respect talk power | +| Voice clips: "save the last 30 s" of the channel | client | The Studio has a replay buffer; ask for consent and show the recording flag | +| Zoom and pan while watching, picture-in-picture, a real pop-out window | client | Voelin already shows the stream statistics | +| "Ask to stream" (a request to someone to share their screen) | client | A poke with a fixed message, or a gateway request | +| Voice invite links with a preview of who is inside | gateway | `ts3server://` plus a page served by the gateway | +| How long a channel has been busy, its topic in the tree | client / TS | The channel topic exists | +| Stage-style view of moderated channels: speakers vs audience, "raise hand" | TS | TS has moderated channels and talk power requests; present them the Discord way | +| Priority speaker lowers the others | TS | See §1: the server already sends the dimming level | +| Replies | gateway | Others see a `> quote`-style prefix | +| Edit and delete | gateway | Only gateway users see the change; say so in the UI | +| Polls | gateway | Next to events and topics | +| Forwarding | client | Post again with "forwarded from" | +| Bookmarks and reminders for messages | client | Local | +| Link previews (OpenGraph), http pictures inline | client | Opt-in: fetching leaks the IP to the linked site | +| Onboarding and rules screening on a server | gateway | Later | +| Roles UI ("view as role") | TS | Maps onto server groups; after the permission editor | + +**Not worth copying.** + +- Nitro, boosts, quests: no equivalent. +- Activities: embedded web apps, and Slint has no web view. +- E2EE voice: the TS protocol cannot do it. +- Server discovery: TS6 has its own directory, see §2b. + +## 4. Order of work + +| # | Work | Size | +|---|---|---| +| 1 | BBCode rendering, clickable links, Copy text | S–M | +| 2 | Spacers, channel password prompt, poke with a message, badges, priority-speaker dimming | S | +| 3 | Regenerate the screenshots | S | +| 4 | Context menus and drag and drop. Then moderation: move, kick, ban; create, edit and delete channels; assign groups | L | +| 5 | Notification sounds; mute, deafen and away hotkeys; auto-away | M | +| 6 | Unread state, "new messages" divider, loading older messages on scroll, mention highlight and autocomplete | M | +| 7 | Desktop layout: members panel closed by default when the tree shows people, no duplicate actions or advertising, call bar, viewer scrim and theatre mode | M | +| 8 | `ts3server://` and `tmspk.gg` link handler | S–M | +| 9 | Sending whispers, asking for talk power, per-channel subscription | M | +| 10 | Message search (FTS5), notification level per server and channel | M | +| 11 | Merge the settings sections; tray, minimise to tray, autostart; streamer mode | M | + +Later: the myTeamSpeak global chat and cloud sync, the overlay, the +soundboard, the stream grid and camera share, direct calls, the permission +editor, translations (the `.pot` exists, no `.po` yet). + +## Sources + +TeamSpeak 6: + +- beta1: https://community.teamspeak.com/t/teamspeak-6-0-0-beta1-screen-camera-sharing-communities-design-overhaul/54925 +- beta3 "Foundation I": https://community.teamspeak.com/t/teamspeak-6-0-0-beta3-foundation-i-update/62417 +- beta3.3: https://community.teamspeak.com/t/teamspeak-6-0-0-beta3-3-minor-update/62656 +- beta4 "Foundation II": https://community.teamspeak.com/t/teamspeak-6-0-0-beta4-foundation-ii-update/64497 +- beta4.1: https://community.teamspeak.com/t/teamspeak-6-0-0-beta4-1-hotfix/64672 +- Direct calls: https://community.teamspeak.com/t/first-look-at-1-1-direct-calls-for-teamspeak-6/65124 +- Per-application audio: https://community.teamspeak.com/t/multi-app-audio-picker-for-screensharing/65236 +- Multi-track recording: https://community.teamspeak.com/t/multi-track-audio-recording/65237 +- Server beta13: https://community.teamspeak.com/t/ts6-server-beta-v6-0-0-beta13/65349 +- Server repository: https://github.com/teamspeak/teamspeak6-server +- Channel chat is not persistent: https://community.teamspeak.com/t/cant-delete-messages-or-pictures-posted-in-ts6-server-channels/63343 +- Staff on persistent text channels: https://community.teamspeak.com/t/subject-making-ts6-the-ultimate-discord-alternative-feedback-suggestions/63483/26 +- What myTeamSpeak syncs: https://community.teamspeak.com/t/feedback-add-indicator-what-settings-are-synced-through-myts/56152 + +Discord: + +- https://discord.com/blog/discord-update-march-25-2025-changelog (call bar, overlay rebuild, density) +- https://discord.com/blog/discord-update-september-25-2025-changelog +- https://discord.com/blog/discord-patch-notes-february-4-2026 (stream zoom/pan, stats) +- https://discord.com/blog/discord-patch-notes-june-4-2026 (clips, voice invites) +- https://discord.com/blog/discord-patch-notes-july-7-2026 (Request to Stream) +- https://discord.com/blog/discord-update-september-25-2026 +- https://support.discord.com/hc/en-us/articles/22163184112407-Polls-FAQ +- https://support.discord.com/hc/en-us/articles/26442819646999-Message-Bookmarks-and-Reminders +- https://discord.com/blog/improving-mobile-with-squircles-styles-and-spacing From ba82d9338cf1352300ebd94a808b14e2a6a12791 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 21:48:47 +0000 Subject: [PATCH 02/42] gateway: try every published gateway in turn Discovery returns every gateway the server publishes, best first: the most specific name, at a name _tsgws before _tsgw, by priority, then tsgw's own /.well-known answer (only when a plain record or nothing is published, so a TLS-only server is never reached without TLS). The engine tries them in turn, each for up to 20 s, and uses the first that logs in; only a round that fails waits before the next. The bookmark keeps the published list and the one in use. A TLS proxy that answers 404 (Zoraxy without a rule for the host) no longer keeps the gateway away when tsgw's plain port is published too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- crates/voelin-core/src/discover.rs | 241 +++++++++++++++++++++------- crates/voelin-core/src/gateway.rs | 119 +++++++++----- crates/voelin-core/src/lib.rs | 6 +- crates/voelin-core/src/session.rs | 16 +- crates/voelin-core/tests/gateway.rs | 69 +++++++- crates/voelin-store/src/store.rs | 69 +++++++- crates/voelin-ui/src/app.rs | 3 + crates/voelin-ui/src/dev.rs | 2 + crates/voelin-ui/src/messages.rs | 9 +- crates/voelin-ui/src/servers.rs | 53 ++++-- docs/gateway-admin.md | 30 +++- 11 files changed, 477 insertions(+), 140 deletions(-) diff --git a/crates/voelin-core/src/discover.rs b/crates/voelin-core/src/discover.rs index 804b8e5..5bc52de 100644 --- a/crates/voelin-core/src/discover.rs +++ b/crates/voelin-core/src/discover.rs @@ -8,12 +8,20 @@ //! - SRV `_tsgws._tcp.`: `wss://:`, //! - SRV `_tsgw._tcp.`: `ws://:`, //! -//! TLS first at the same name; `` is `path=…` from a TXT record at the -//! SRV record's name, `/v1` without one. Without any such record, as TSDNS -//! has its well-known port, the gateway itself is asked at tsgw's default -//! port: `http://:7788/.well-known/tsgw` answers `{"url": "…"}`. For an -//! IP address (or `localhost`) only that is tried. What an admin publishes is -//! in `docs/gateway-admin.md`. +//! `` is `path=…` from a TXT record at the SRV record's name, `/v1` +//! without one. As TSDNS has its well-known port, the gateway itself is also +//! asked at tsgw's default port: `http://:7788/.well-known/tsgw` +//! answers `{"url": "…"}`; for an IP address (or `localhost`) only that is +//! tried. That answer is plain HTTP, so it is asked only when nothing or a +//! plain record is published: a TLS-only publication stays TLS-only. +//! +//! Every gateway found is kept, best first (the most specific name, at a +//! name TLS before plain, by priority, then the gateway's own answer), and +//! tried in turn ([`crate::Command::ObserveGateway`]): a TLS proxy that +//! fails falls back to a published plain one. Discovery trusts DNS and the +//! network as TSDNS does; falling back from a published `_tsgws` to a +//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an +//! admin publishes is in `docs/gateway-admin.md`. use std::net::IpAddr; use std::sync::Arc; @@ -34,9 +42,12 @@ pub const DEFAULT_PORT: u16 = 7788; const DEFAULT_PATH: &str = "/v1"; /// Give up on asking one name's gateway after this long. const PROBE_TIMEOUT: Duration = Duration::from_secs(3); +/// At most this many gateways are kept, best first. +const MAX_CANDIDATES: usize = 8; type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync; type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec> + Send + Sync; +type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option> + Send + Sync; /// Where [`gateway`] gets its answers from; the tests put fakes in. #[derive(Clone)] @@ -45,8 +56,8 @@ struct Lookups { srv: Arc, /// The strings of the TXT records at a name. txt: Arc, - /// Where a gateway is asked for its URL. - probe_port: u16, + /// The URL a gateway at a name gives for itself (`/.well-known/tsgw`). + probe: Arc, } impl Lookups { @@ -101,30 +112,45 @@ impl Lookups { .map(Option::unwrap_or_default) .boxed() }), - probe_port: DEFAULT_PORT, + probe: Arc::new(|name| { + async move { + timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await.ok().flatten() + } + .boxed() + }), } } } -/// The URL of the gateway of the server at `address` (as a bookmark has it: -/// host, host:port, an IP), if one is published. -pub async fn gateway(address: &str) -> Option { - gateway_with(address, Lookups::system()).await +/// The URLs of the gateway of the server at `address` (as a bookmark has +/// it: host, host:port, an IP), best first: everything published, to be +/// tried in turn. Empty: none is published. +pub async fn gateways(address: &str) -> Vec { + gateways_with(address, Lookups::system()).await } -async fn gateway_with(address: &str, lookups: Lookups) -> Option { +async fn gateways_with(address: &str, lookups: Lookups) -> Vec { let host = host_of(address); let names = names(host); if names.is_empty() { - return None; + return Vec::new(); } - if host.parse::().is_err() - && host.contains('.') - && let Some(url) = from_srv(&names, &lookups).await - { - return Some(url); + let mut urls = if host.parse::().is_err() && host.contains('.') { + from_srv(&names, &lookups).await + } else { + Vec::new() + }; + // The gateway's own answer comes over plain HTTP: not for a server that + // publishes only TLS. + if urls.is_empty() || urls.iter().any(|url| url.starts_with("ws://")) { + for url in from_well_known(&names, &lookups).await { + if !urls.contains(&url) { + urls.push(url); + } + } } - from_well_known(&names, lookups.probe_port).await + urls.truncate(MAX_CANDIDATES); + urls } /// The host of an address: without the port, the brackets of an IPv6 @@ -155,8 +181,9 @@ fn names(host: &str) -> Vec<&str> { .collect() } -/// The URL from SRV records, every name and service asked at once. -async fn from_srv(names: &[&str], lookups: &Lookups) -> Option { +/// The URLs from SRV records, every name and service asked at once: the +/// most specific name first, at a name TLS first, by priority. +async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec { let queries: Vec<(&str, String)> = names .iter() .flat_map(|name| { @@ -164,14 +191,33 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Option { }) .collect(); let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await; - // The first (most specific, TLS first) name with a usable record. - let ((scheme, owner), (_, target, port)) = - queries.iter().zip(answers).find_map(|(q, records)| { + let found: Vec<_> = queries + .iter() + .zip(answers) + .filter_map(|(query, mut records)| { // A target of "." says there is no such service there. - let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?; - Some((q, best)) - })?; - let mut path = (lookups.txt)(owner.clone()) + records.retain(|r| r.1 != "."); + records.sort_by_key(|r| r.0); + (!records.is_empty()).then_some((query, records)) + }) + .collect(); + let paths = join_all(found.iter().map(|((_, owner), _)| path_at(lookups, owner))).await; + let mut urls = Vec::new(); + for (((scheme, _), records), path) in found.into_iter().zip(paths) { + for (_, target, port) in records { + let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')); + if !urls.contains(&url) { + urls.push(url); + } + } + } + urls +} + +/// The path at a SRV record's name: `path=…` from its TXT records, `/v1` +/// without one. +async fn path_at(lookups: &Lookups, owner: &str) -> String { + let mut path = (lookups.txt)(owner.to_owned()) .await .into_iter() .find_map(|s| s.strip_prefix("path=").map(str::to_owned)) @@ -179,15 +225,20 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Option { if !path.starts_with('/') { path.insert(0, '/'); } - Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'))) + path } -/// The URL a gateway gives for itself at one of `names`, all asked at once; -/// the most specific that answers wins. -async fn from_well_known(names: &[&str], port: u16) -> Option { - let answers = - join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await; - answers.into_iter().find_map(|answer| answer.ok().flatten()) +/// The URLs gateways give for themselves at `names`, all asked at once, +/// the most specific first. +async fn from_well_known(names: &[&str], lookups: &Lookups) -> Vec { + let answers = join_all(names.iter().map(|name| (lookups.probe)((*name).to_owned()))).await; + let mut urls: Vec = Vec::new(); + for url in answers.into_iter().flatten() { + if !urls.contains(&url) { + urls.push(url); + } + } + urls } /// tsgw's answer at `http://:/.well-known/tsgw`. @@ -215,8 +266,8 @@ mod tests { use super::*; /// DNS answers from these lists only: SRV `(name, priority, target, - /// port)`, TXT `(name, string)`. - fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups { + /// port)`, TXT `(name, string)`; no gateway answers for itself. + fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)]) -> Lookups { let srv: Vec<(String, u16, String, u16)> = srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect(); let txt: Vec<(String, String)> = @@ -231,10 +282,30 @@ mod tests { let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect(); futures::future::ready(found).boxed() }), - probe_port, + probe: Arc::new(|_| futures::future::ready(None).boxed()), } } + /// `lookups` where the gateway at a name answers `(name, url)`. + fn answering(mut lookups: Lookups, answers: &[(&str, &str)]) -> Lookups { + let answers: Vec<(String, String)> = + answers.iter().map(|(n, u)| (n.to_string(), u.to_string())).collect(); + lookups.probe = Arc::new(move |name| { + let url = answers.iter().find(|a| a.0 == name).map(|a| a.1.clone()); + futures::future::ready(url).boxed() + }); + lookups + } + + /// `lookups` asking the real `/.well-known/tsgw` at `port`. + fn probing(mut lookups: Lookups, port: u16) -> Lookups { + lookups.probe = Arc::new(move |name| { + async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok().flatten() } + .boxed() + }); + lookups + } + /// A port nothing listens on. fn closed_port() -> u16 { std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() @@ -242,20 +313,20 @@ mod tests { #[tokio::test] async fn finds_the_gateway_at_the_host_or_its_domain() { - let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0); + let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[]); for address in ["ts.example.test", "ts.example.test:9987", "example.test"] { assert_eq!( - gateway_with(address, lookups.clone()).await.as_deref(), - Some("ws://gw.example.test:7788/v1"), + gateways_with(address, lookups.clone()).await, + ["ws://gw.example.test:7788/v1"], "{address}" ); } // The parent's parent is not the domain any more. - assert_eq!(gateway_with("example", lookups).await, None); + assert!(gateways_with("example", lookups).await.is_empty()); } #[tokio::test] - async fn the_most_specific_name_wins_then_tls() { + async fn every_record_in_order_most_specific_name_then_tls() { let lookups = fake( &[ ("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443), @@ -264,18 +335,73 @@ mod tests { ("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443), ], &[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")], - 0, ); assert_eq!( - gateway_with("ts.example.test", lookups.clone()).await.as_deref(), - Some("wss://tls.example.test:8443/tsgw/v1") + gateways_with("ts.example.test", lookups.clone()).await, + [ + "wss://tls.example.test:8443/tsgw/v1", + "wss://backup.example.test:443/tsgw/v1", + "ws://plain.example.test:7788/v1", + "wss://domain.example.test:443/v1", + ] ); assert_eq!( - gateway_with("voice.example.test", lookups).await.as_deref(), - Some("wss://domain.example.test:443/v1") + gateways_with("voice.example.test", lookups).await, + ["wss://domain.example.test:443/v1"] ); } + /// A TLS proxy in front of tsgw and tsgw itself published next to the + /// server (and again at the domain): TLS first, the plain one after it, + /// once; the gateway's own answer is the plain one again. + #[tokio::test] + async fn a_tls_proxy_falls_back_to_the_published_plain_gateway() { + let lookups = answering( + fake( + &[ + ("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443), + ("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788), + ("_tsgw._tcp.example.test.", 0, "ts.example.test.", 7788), + ], + &[], + ), + &[("ts.example.test", "ws://ts.example.test:7788/v1")], + ); + assert_eq!( + gateways_with("ts.example.test", lookups).await, + ["wss://gw.example.test:443/v1", "ws://ts.example.test:7788/v1"] + ); + } + + #[tokio::test] + async fn the_gateways_own_answer_comes_last() { + let lookups = answering( + fake(&[("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788)], &[]), + &[("ts.example.test", "wss://gw.example.test/v1")], + ); + assert_eq!( + gateways_with("ts.example.test", lookups).await, + ["ws://plain.example.test:7788/v1", "wss://gw.example.test/v1"] + ); + } + + #[tokio::test] + async fn a_tls_only_publication_is_not_widened() { + let asked = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut lookups = + fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]); + let flag = asked.clone(); + lookups.probe = Arc::new(move |_| { + flag.store(true, std::sync::atomic::Ordering::SeqCst); + futures::future::ready(Some("ws://ts.example.test:7788/v1".to_owned())).boxed() + }); + assert_eq!( + gateways_with("ts.example.test", lookups).await, + ["wss://gw.example.test:443/v1"] + ); + assert!(!asked.load(std::sync::atomic::Ordering::SeqCst), "plain HTTP was asked"); + } + #[tokio::test] async fn a_record_that_says_no_service_is_skipped() { let lookups = fake( @@ -284,12 +410,8 @@ mod tests { ("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80), ], &[("_tsgw._tcp.example.test.", "path=ws")], - closed_port(), - ); - assert_eq!( - gateway_with("ts.example.test", lookups).await.as_deref(), - Some("ws://gw.example.test:80/ws") ); + assert_eq!(gateways_with("ts.example.test", lookups).await, ["ws://gw.example.test:80/ws"]); } /// Without records the gateway next to the server answers at its port, @@ -313,16 +435,17 @@ mod tests { socket.write_all(response.as_bytes()).await.unwrap(); } }); - let lookups = fake(&[], &[], port); + let lookups = probing(fake(&[], &[]), port); for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] { assert_eq!( - gateway_with(address, lookups.clone()).await.as_deref(), - Some("wss://gw.example.test/v1"), + gateways_with(address, lookups.clone()).await, + ["wss://gw.example.test/v1"], "{address}" ); } // Nothing there. - assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None); + let nothing = probing(fake(&[], &[]), closed_port()); + assert!(gateways_with("127.0.0.1", nothing).await.is_empty()); } #[test] diff --git a/crates/voelin-core/src/gateway.rs b/crates/voelin-core/src/gateway.rs index a75eb9f..7b4296b 100644 --- a/crates/voelin-core/src/gateway.rs +++ b/crates/voelin-core/src/gateway.rs @@ -65,8 +65,8 @@ pub(crate) enum GatewayCmd { } pub(crate) enum GatewayEvent { - /// Logged in; requests go through `client`. - Connected(GatewayClient), + /// Logged in at the URL; requests go through the client. + Connected(GatewayClient, String), Presence(Box), /// A push other than presence. Push(Box), @@ -87,37 +87,58 @@ pub async fn connect( voelin_gateway_proto::client::connect(url, login).await } +/// Observe through the first of `urls` (best first, as published) that +/// logs in. pub(crate) async fn run( - url: String, + mut urls: Vec, identity: tsclientlib::Identity, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { - // A gateway that is away (down, restarting, a network change) is tried - // again until the session stops observing; only a refused login ends it. + // A gateway that is away (down, restarting, a network change, a proxy + // in front of it that fails) is tried again until the session stops + // observing; only a refused login ends it. A round tries every URL in + // turn without waiting; only a round that fails waits. let mut chats = Chats::default(); let mut failures = 0; - let mut last_reason = String::new(); - let reason = loop { - match attempt(&url, &identity, &mut commands, &events, &mut chats, &mut failures).await { - Ended::Stopped => break None, - Ended::Refused(reason) => break Some(reason), - Ended::Lost(reason) => { - failures += 1; - let delay = retry_delay(failures); - // Once per cause, not every minute of a long absence. - if reason != last_reason { - warn!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway unreachable"); - } else { - debug!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway still unreachable"); - } - last_reason.clone_from(&reason); - let _ = events.send(GatewayEvent::Retrying(reason)); - if !chats.wait(delay, &mut commands).await { - break None; + // What was logged per URL: once per cause, not every minute of a long + // absence. + let mut told: Vec<(String, String)> = Vec::new(); + let reason = 'observe: loop { + let mut lost = None; + let mut index = 0; + while index < urls.len() { + let url = urls[index].clone(); + match attempt(&url, &identity, &mut commands, &events, &mut chats).await { + Ended::Stopped => break 'observe None, + Ended::Refused(reason) => break 'observe Some(reason), + Ended::Lost { reason, logged_in } => { + let next = urls.get(index + 1); + if told.iter().any(|(u, r)| *u == url && *r == reason) { + debug!(%url, error = %reason, ?next, "gateway still unreachable"); + } else { + warn!(%url, error = %reason, ?next, "gateway unreachable"); + told.retain(|(u, _)| *u != url); + told.push((url.clone(), reason.clone())); + } + lost = Some(reason); + if logged_in { + // It worked: it is tried first again, after a wait. + urls[..=index].rotate_right(1); + failures = 0; + break; + } + index += 1; } } } + let Some(reason) = lost else { break None }; + failures += 1; + let delay = retry_delay(failures); + let _ = events.send(GatewayEvent::Retrying(reason)); + if !chats.wait(delay, &mut commands).await { + break None; + } }; let _ = events.send(GatewayEvent::Disconnected(reason)); } @@ -128,10 +149,15 @@ enum Ended { Stopped, /// The gateway refused the login: trying again would not help. Refused(String), - /// Not reached, or lost: try again. - Lost(String), + /// Not reached, or lost (after logging in): try again. + Lost { reason: String, logged_in: bool }, } +/// One attempt to reach a gateway and log in (TCP, TLS, the WebSocket +/// upgrade, the login's own queries at the gateway) gives up after this +/// long, so a gateway that never answers does not hold up the next one. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); + /// The wait before the next attempt after `failures` failed ones in a row. fn retry_delay(failures: u32) -> Duration { const SECONDS: [u64; 5] = [2, 5, 15, 30, 60]; @@ -235,37 +261,42 @@ async fn attempt( commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, chats: &mut Chats, - failures: &mut u32, ) -> Ended { - let (client, mut pushes) = match connect(url, identity).await { - Ok(connected) => connected, - Err(ClientError::Gateway { code, message }) => { - warn!(%url, ?code, %message, "gateway refused the login"); - return Ended::Refused(format!("gateway refused login: {code:?}: {message}")); - } - Err(e) => return Ended::Lost(e.to_string()), - }; - *failures = 0; + let lost = |reason: String| Ended::Lost { reason, logged_in: false }; + let (client, mut pushes) = + match tokio::time::timeout(CONNECT_TIMEOUT, connect(url, identity)).await { + Ok(Ok(connected)) => connected, + Ok(Err(ClientError::Gateway { code, message })) => { + warn!(%url, ?code, %message, "gateway refused the login"); + return Ended::Refused(format!("gateway refused login: {code:?}: {message}")); + } + Ok(Err(e)) => return lost(e.to_string()), + Err(_) => return lost(format!("no answer within {} s", CONNECT_TIMEOUT.as_secs())), + }; info!(%url, server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected"); - match relay(&client, &mut pushes, commands, events, chats).await { - Ok(ended) => ended, - Err(e) => Ended::Lost(e.to_string()), - } + let reason = match relay(url, &client, &mut pushes, commands, events, chats).await { + Ok(Ended::Lost { reason, .. }) => reason, + Ok(ended) => return ended, + Err(e) => e.to_string(), + }; + Ended::Lost { reason, logged_in: true } } async fn relay( + url: &str, client: &GatewayClient, pushes: &mut mpsc::UnboundedReceiver, commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, chats: &mut Chats, ) -> Result { + let lost = |reason: String| Ended::Lost { reason, logged_in: true }; // Messages with their gateway ids, pins, reactions and topics of open // chats (older gateways answer `unknown_type` as a push; ignored). if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) { client.send(ClientMsg::Enable { features: Vec::new() })?; } - let _ = events.send(GatewayEvent::Connected(client.clone())); + let _ = events.send(GatewayEvent::Connected(client.clone(), url.to_owned())); client.subscribe_presence()?; chats.restore(client)?; let mut presence = Presence::default(); @@ -274,9 +305,9 @@ async fn relay( tokio::select! { push = pushes.recv() => match push { None | Some(Push::Disconnected(None)) => { - return Ok(Ended::Lost("the gateway closed the connection".into())); + return Ok(lost("the gateway closed the connection".into())); } - Some(Push::Disconnected(Some(reason))) => return Ok(Ended::Lost(reason)), + Some(Push::Disconnected(Some(reason))) => return Ok(lost(reason)), Some(Push::PresenceSnapshot(snapshot)) => { presence = Presence::from_snapshot(snapshot); let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone()))); @@ -289,7 +320,7 @@ async fn relay( Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {} // The gateway forgot the login (restarted): log in again. Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => { - return Ok(Ended::Lost(format!("gateway session lost: {message}"))); + return Ok(lost(format!("gateway session lost: {message}"))); } Some(push) => { let _ = events.send(GatewayEvent::Push(Box::new(push))); @@ -528,6 +559,8 @@ pub struct Pin { pub enum GatewayUpdate { /// Logged in. Connected { + /// Where: the first of the published URLs that logged in. + url: String, gateway_id: String, server_uid: String, server_name: String, diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index e9424f6..10a2729 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -111,10 +111,12 @@ pub enum Command { DisconnectVoice { session: SessionId, }, - /// Invisible presence and relay chat through a `tsgw` gateway. + /// Invisible presence and relay chat through a `tsgw` gateway: the first + /// of `urls` (best first, [`discover::gateways`]) that logs in, tried in + /// turn again whenever it is lost. ObserveGateway { session: SessionId, - url: String, + urls: Vec, identity: Box, }, /// Invisible presence and relay chat with own ServerQuery credentials. diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index e011d1c..376548b 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -404,13 +404,20 @@ impl Session { let _ = tx.send(VoiceCmd::Disconnect); } } - Command::ObserveGateway { url, identity, .. } => { + Command::ObserveGateway { urls, identity, .. } => { self.stop_observing(); + if urls.is_empty() { + return; + } let generation = self.next_generation(); - self.known_server(format!("gateway:{url}")); + // Each is published for this server (history before its + // unique id is known). + for url in &urls { + self.known_server(format!("gateway:{url}")); + } let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); - tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx)); + tokio::spawn(gateway::run(urls, *identity, cmd_rx, ev_tx)); self.forward(ev_rx, move |e| SourceEvent::Gateway(generation, e)); self.gateway = Some((generation, cmd_tx)); self.state.observe = ObserveState::Connecting; @@ -1711,7 +1718,7 @@ impl Session { fn gateway_event(&mut self, e: GatewayEvent) { match e { - GatewayEvent::Connected(client) => { + GatewayEvent::Connected(client, url) => { self.state.observe = ObserveState::Observing; let info = client.info().clone(); self.gateway_client = Some(client.clone()); @@ -1721,6 +1728,7 @@ impl Session { self.learn_server_uid(info.server_uid.clone(), Source::Gateway); self.emit_state(); self.gateway_update(GatewayUpdate::Connected { + url, gateway_id: info.gateway_id, server_uid: info.server_uid, server_name: info.server_name, diff --git a/crates/voelin-core/tests/gateway.rs b/crates/voelin-core/tests/gateway.rs index 43ea463..ceeebc5 100644 --- a/crates/voelin-core/tests/gateway.rs +++ b/crates/voelin-core/tests/gateway.rs @@ -434,7 +434,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) { let identity = tsclientlib::Identity::create(); engine.send(Command::ObserveGateway { session, - url: gw.url.clone(), + urls: vec![gw.url.clone()], identity: Box::new(identity), }); } @@ -726,7 +726,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() { engine.send(Command::OpenChat { session: 3, target: LOBBY }); engine.send(Command::ObserveGateway { session: 3, - url: format!("ws://127.0.0.1:{port}/v1"), + urls: vec![format!("ws://127.0.0.1:{port}/v1")], identity: Box::new(tsclientlib::Identity::create()), }); // The first attempt fails (the next one is 2 s later): still connecting, @@ -766,3 +766,68 @@ async fn an_unreachable_gateway_is_tried_again_quietly() { drop(engine); let _ = std::fs::remove_dir_all(path.parent().unwrap()); } + +/// A reverse proxy without a rule for the gateway's host, as Zoraxy's +/// default site answers: 404 to everything. +async fn not_found_proxy() -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}/v1", listener.local_addr().unwrap()); + tokio::spawn(async move { + while let Ok((mut tcp, _)) = listener.accept().await { + tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut request = [0; 4096]; + let _ = tcp.read(&mut request).await; + let _ = tcp + .write_all( + b"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\n\ + Content-Length: 19\r\n\r\n404 page not found\n", + ) + .await; + }); + } + }); + url +} + +/// Every published gateway is tried in turn, without waiting: a TLS proxy +/// that answers 404 and a port nothing listens on are passed over, and the +/// plain gateway published after them is used, quietly. +#[tokio::test(flavor = "multi_thread")] +async fn the_next_published_gateway_is_used_when_one_fails() { + let proxy = not_found_proxy().await; + let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let gw = FakeGateway::start().await; + let path = temp_db("fallback"); + let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap()); + let mut rx = engine.subscribe(); + engine.send(Command::ObserveGateway { + session: 4, + urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()], + identity: Box::new(tsclientlib::Identity::create()), + }); + // Within one round: sooner than the first wait (2 s) after a failed round. + let url = timeout(Duration::from_millis(1800), async { + loop { + match rx.recv().await { + Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"), + Ok(Event::Gateway { session: 4, update: GatewayUpdate::Connected { url, .. } }) => { + return url; + } + Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + Err(e) => panic!("{e}"), + } + } + }) + .await + .expect("the plain gateway was not used within a round"); + assert_eq!(url, gw.url); + wait(&mut rx, "observing", |e| match e { + Event::Error { message, .. } => panic!("the user was told: {message}"), + Event::State { session: 4, state } if state.observe == ObserveState::Observing => Some(()), + _ => None, + }) + .await; + drop(engine); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); +} diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index f8d4352..8174824 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -147,8 +147,14 @@ pub struct Bookmark { /// Identity to connect with (`IdentityEntry::id`). pub identity: Option, pub default_channel: Option, - /// `wss://` URL of a companion gateway, for invisible presence and relay chat. + /// The companion gateway in use (`wss://` or `ws://`), for invisible + /// presence and relay chat: the one that last logged in, else the best + /// published one, else one typed into an older version. pub gateway_url: Option, + /// Every URL the server publishes for its gateway, best first: tried in + /// this order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub gateway_urls: Vec, /// Own ServerQuery credentials (the password is kept in [`crate::Secrets`]). pub query: Option, /// Signed client version to present (`voelinctl versions` spec), `None` for the default. @@ -167,6 +173,37 @@ pub struct CachedServerIcon { } impl Bookmark { + /// The gateways to try, best first: those published, else the one kept. + pub fn gateways(&self) -> Vec { + if self.gateway_urls.is_empty() { + self.gateway_url.iter().cloned().collect() + } else { + self.gateway_urls.clone() + } + } + + /// Discovery found `urls` (best first, not empty); true if what is tried + /// changed. The one in use stays if it is still published. + pub fn set_gateways(&mut self, urls: Vec) -> bool { + if self.gateway_urls == urls { + return false; + } + if !self.gateway_url.as_ref().is_some_and(|url| urls.contains(url)) { + self.gateway_url = urls.first().cloned(); + } + self.gateway_urls = urls; + true + } + + /// The gateway logged in at `url`; true if the one in use changed. + pub fn gateway_in_use(&mut self, url: &str) -> bool { + if self.gateway_url.as_deref() == Some(url) || !self.gateways().iter().any(|u| u == url) { + return false; + } + self.gateway_url = Some(url.to_owned()); + true + } + pub fn server_icon_id(&self) -> Option { self.cached_server_icon .as_ref() @@ -562,6 +599,36 @@ mod tests { assert_eq!(b.server_password_key(), format!("bookmark/{}/server-password", b.id)); } + #[test] + fn published_gateways_are_kept_with_the_one_in_use() { + let store = Store::open_in_memory().unwrap(); + // From an older version: one URL, no list. + let mut b = Bookmark { + address: "ts.example.org".into(), + gateway_url: Some("ws://127.0.0.1:7788/v1".into()), + ..Default::default() + }; + b.id = store.add_bookmark(&b).unwrap(); + assert_eq!(b.gateways(), ["ws://127.0.0.1:7788/v1"]); + let published = + vec!["wss://gw.example.org/v1".to_owned(), "ws://ts.example.org:7788/v1".into()]; + assert!(b.set_gateways(published.clone())); + assert!(!b.set_gateways(published.clone()), "unchanged"); + // The old one is not published: the best published one is in use. + assert_eq!(b.gateway_url.as_deref(), Some("wss://gw.example.org/v1")); + assert_eq!(b.gateways(), published); + // The plain one logged in; one that is not published never counts. + assert!(b.gateway_in_use("ws://ts.example.org:7788/v1")); + assert!(!b.gateway_in_use("ws://ts.example.org:7788/v1")); + assert!(!b.gateway_in_use("ws://elsewhere.test/v1")); + store.update_bookmark(&b).unwrap(); + let reloaded = store.bookmarks().unwrap().remove(0); + assert_eq!(reloaded, b); + // Still published: the one in use stays. + b.set_gateways(vec!["ws://ts.example.org:7788/v1".into()]); + assert_eq!(b.gateway_url.as_deref(), Some("ws://ts.example.org:7788/v1")); + } + #[test] fn bookmark_icons_survive_reload_and_are_bound_to_the_server_address() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index acd65e6..f5f87d1 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -980,6 +980,9 @@ impl App { self.history_batch(session as i64, &target, messages, source, complete); } Event::Gateway { session, update } => { + if let voelin_core::gateway::GatewayUpdate::Connected { url, .. } = &update { + self.gateway_in_use(session as i64, url); + } self.gateway_extra(session as i64, &update); self.gateway_update(session as i64, update); } diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index aec945b..f4b159f 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -408,6 +408,7 @@ fn demo_ui(app: &mut App) { identity: None, default_channel: None, gateway_url: None, + gateway_urls: Vec::new(), query: None, client_version: None, cached_server_icon: None, @@ -539,6 +540,7 @@ fn demo_ui(app: &mut App) { Event::Gateway { session, update: GatewayUpdate::Connected { + url: "wss://gw.nightfall.example/v1".into(), gateway_id: "demo".into(), server_uid: "demo-server".into(), server_name: "Nightfall Guild".into(), diff --git a/crates/voelin-ui/src/messages.rs b/crates/voelin-ui/src/messages.rs index 877d2f6..74cee33 100644 --- a/crates/voelin-ui/src/messages.rs +++ b/crates/voelin-ui/src/messages.rs @@ -76,12 +76,9 @@ impl App { } self.social.dm.bookmark_of.clear(); for b in &self.bookmarks { - for alias in [ - Some(format!("voice:{}", b.address)), - b.gateway_url.as_ref().map(|u| format!("gateway:{u}")), - ] - .into_iter() - .flatten() + let gateways = b.gateways().into_iter().chain(b.gateway_url.clone()); + for alias in std::iter::once(format!("voice:{}", b.address)) + .chain(gateways.map(|url| format!("gateway:{url}"))) { if let Ok(Some(uid)) = self.store.server_alias(&alias) { self.social.dm.bookmark_of.insert(uid, b.id); diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 821bd78..bb5e0b9 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -49,6 +49,7 @@ fn bookmark_from_form( if old.is_some_and(|old| old.address != bookmark.address) { bookmark.cached_server_icon = None; bookmark.gateway_url = None; + bookmark.gateway_urls.clear(); bookmark.query = None; } bookmark.name = match form.name.trim() { @@ -135,10 +136,10 @@ impl App { } /// Look up the gateway of a server ([`voelin_core::discover`]), once a - /// run: one found is kept as if typed, and takes the place of a stored - /// one that is no longer what the server publishes (a gateway that - /// moved, or one typed into an older version, which showed the field). - /// Nothing found keeps what is stored. + /// run: every one the server publishes is kept, best first, and tried in + /// turn; they take the place of a stored one that is no longer published + /// (a gateway that moved, or one typed into an older version, which + /// showed the field). Nothing found keeps what is stored. pub(crate) fn discover_gateway(&mut self, id: i64) { if self.demo_ui || !self.gateways_looked_up.insert(id) { return; @@ -146,31 +147,33 @@ impl App { let Some(b) = self.bookmark(id) else { return }; let address = b.address.clone(); self.engine.runtime().spawn(async move { - if let Some(url) = voelin_core::discover::gateway(&address).await { - later(move |app| app.gateway_found(id, &address, url)); + let urls = voelin_core::discover::gateways(&address).await; + if !urls.is_empty() { + later(move |app| app.gateway_found(id, &address, urls)); } }); } - /// A gateway was found for the server at `address`; it is kept unless - /// the server changed meanwhile, and the server is observed through it - /// if it is the one shown. Users never hear of it (logged only). - fn gateway_found(&mut self, id: i64, address: &str, url: String) { + /// Gateways were found for the server at `address` (best first); they + /// are kept unless the server changed meanwhile, and the server is + /// observed through them if it is the one shown. Users never hear of + /// them (logged only). + fn gateway_found(&mut self, id: i64, address: &str, urls: Vec) { let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else { return; }; - if b.gateway_url.as_deref() == Some(url.as_str()) { + let previous = b.gateways(); + if !b.set_gateways(urls) { return; } - let previous = b.gateway_url.replace(url.clone()); if let Err(e) = self.store.update_bookmark(b) { warn!(%e, "could not keep the gateway found"); return; } - info!(server = %b.address, %url, ?previous, "gateway found"); + info!(server = %b.address, urls = ?b.gateway_urls, ?previous, "gateway found"); self.refresh_toolbar(); - // Observed through the old one: through this one now. - if previous.is_some() { + // Observed through the old ones: through these now. + if !previous.is_empty() { self.engine.send(Command::StopObserving { session: id as u64 }); if let Some(view) = self.sessions.get_mut(&id) { view.state.observe = ObserveState::Off; @@ -181,6 +184,19 @@ impl App { } } + /// The gateway logged in at `url`: it is the one in use from now on. + pub(crate) fn gateway_in_use(&mut self, id: i64, url: &str) { + let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id) else { return }; + if !b.gateway_in_use(url) { + return; + } + if let Err(e) = self.store.update_bookmark(b) { + warn!(%e, "could not keep the gateway in use"); + return; + } + info!(server = %b.address, %url, "gateway in use"); + } + /// The server told its name: a server still named by its address takes /// it, so the address is all a user has to type. pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) { @@ -213,10 +229,11 @@ impl App { if observing { return; } - if let Some(url) = &b.gateway_url { + let urls = b.gateways(); + if !urls.is_empty() { self.engine.send(Command::ObserveGateway { session, - url: url.clone(), + urls, identity: Box::new(self.identity_for(Some(b.id))), }); // Still the one the server publishes? @@ -608,6 +625,7 @@ mod tests { identity: Some(2), default_channel: Some("Lobby/Sub".into()), gateway_url: Some("ws://gw.example.test:7788/v1".into()), + gateway_urls: vec!["ws://gw.example.test:7788/v1".into()], query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }), client_version: Some("linux".into()), cached_server_icon: Some(voelin_store::CachedServerIcon { @@ -636,6 +654,7 @@ mod tests { assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into()))); assert_eq!(b.client_version.as_deref(), Some("linux")); assert_eq!((b.gateway_url, b.query), (None, None)); + assert!(b.gateway_urls.is_empty()); } #[test] diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md index 42ff8c2..3c2ffb8 100644 --- a/docs/gateway-admin.md +++ b/docs/gateway-admin.md @@ -102,9 +102,11 @@ registered domain, the most specific name first; for `ts.example.org` that is `ts.example.org`, then `example.org`. It looks once per run when the server is selected or connects with voice, and again when its address changes: what is published takes the place of what was found before (a -lookup that finds nothing keeps it). A gateway that cannot be reached is -tried again by itself (after 2, 5, 15, 30, then every 60 seconds); users -see nothing of it, the log file has the URL and the error. +lookup that finds nothing keeps it). Every gateway found is kept and +tried in turn, best first, each for up to 20 seconds; the first that logs +in is used, and the log file names those it passed over (URL and error). +Only when all of them fail does it wait (2, 5, 15, 30, then every 60 +seconds) and start over; users see nothing of it. **DNS records** (preferred). An SRV record names the gateway's host and port, the service name says whether it speaks TLS: @@ -115,9 +117,14 @@ port, the service name says whether it speaks TLS: | `_tsgw._tcp. SRV ` | `ws://:/v1` (plain, e.g. tsgw itself on 7788) | | `_tsgws._tcp. TXT "path=/"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy | -At the same name TLS wins; among several records of one name the lowest -priority. A target of `.` means "no gateway here" and the search goes on at -the parent domain. Examples (zone of `example.org`): +The order: the most specific name first; at a name `_tsgws` before +`_tsgw`; among several records of one name the lowest priority first; +then tsgw's own answer (below), but only when a plain record or nothing is +published, so a server that publishes only TLS is never reached without +it. A TLS proxy that fails (no rule for the host, no certificate) thus +falls back to a published plain gateway. A target of `.` means "no gateway +here" and the search goes on at the parent domain. Examples (zone of +`example.org`): ```dns ; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw: @@ -135,6 +142,17 @@ itself speaks plain WebSocket, so its own port (7788) is published as `_tsgw`; a `_tsgws` record there makes Voelin start TLS with it, which fails. Publish `_tsgws` only for a port with TLS in front. +Behind [Zoraxy](https://zoraxy.aroz.org/): add an HTTP proxy rule for the +gateway's host (`gw.example.org`) with one upstream, tsgw's plain address +(`:7788`), "Proxy Target require TLS Connection" off, +WebSockets on, and a certificate for the host (ACME). If the rule also +has an uptime monitor, point it at `/health` (tsgw's `/` answers 404). +Check from outside: `curl https://gw.example.org/health` prints `ok`; +Zoraxy's own `404 page not found` there means no rule matched the host or +the request went to another upstream. Then set `listen.public_url = +"wss://gw.example.org/v1"` in tsgw.toml, so its own answer points at the +proxy. + One domain with several servers and several gateways: publish one record per server host (`_tsgws._tcp.ts1.example.org`, `_tsgws._tcp.ts2.example.org`); a record at the domain itself applies to every host below it that has none From d5dd09aae33bb2111538af39558637a196331acd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 21:53:38 +0000 Subject: [PATCH 03/42] avatars: show other clients' myTeamSpeak avatars TeamSpeak 6 tells a client's myTeamSpeak avatar as client_myteamspeak_avatar ",;...". The book now keeps it, and the model reads it as the official client does (one bad entry, an empty one too, spoils the value; the online picture first, else away, do not disturb, offline; HTTPS links only). The engine downloads it from the web (4 MiB at most, cached by link) where the server's avatar is not shown: the client has none, there is no voice connection to get it over (observing), or its download gave up (the server's files unreachable). The server's avatar comes first, as in the official client. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- .../tsproto-structs/declarations/Book.toml | 1 + crates/voelin-core/src/book.rs | 92 +++++++-- crates/voelin-core/src/session.rs | 187 +++++++++++++++++- crates/voelin-core/src/web.rs | 21 +- crates/voelin-model/src/lib.rs | 2 +- crates/voelin-model/src/presence.rs | 65 ++++++ crates/voelin-observer/src/convert.rs | 1 + 7 files changed, 340 insertions(+), 29 deletions(-) diff --git a/crates/proto/tsproto-structs/declarations/Book.toml b/crates/proto/tsproto-structs/declarations/Book.toml index e84e844..3e9fd88 100644 --- a/crates/proto/tsproto-structs/declarations/Book.toml +++ b/crates/proto/tsproto-structs/declarations/Book.toml @@ -192,6 +192,7 @@ properties = [ { name="InheritedChannelGroupFromChannel", type="ChannelId" }, { name="Badges", type="str" }, { name="UserTag", type="str", opt=true }, + { name="MyTeamSpeakAvatar", type="str", opt=true, doc="`,;…` of the myTeamSpeak avatar (TeamSpeak 6)" }, { name="PermissionHints", type="ClientPermissionHint", opt=true }, { name="OptionalData", type="OptionalClientData", opt=true }, { name="ConnectionData", type="ConnectionClientData", opt=true }, diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs index 83c65d3..ba94a82 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/book.rs @@ -3,7 +3,7 @@ use tsclientlib::{ClientType, MaxClients, data}; use voelin_model::{ BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode, - Presence, ServerDetails, parse_badges, + Presence, ServerDetails, myts_avatar_url, parse_badges, }; fn group_info( @@ -147,6 +147,7 @@ pub(crate) fn presence_from_book( server_groups, country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()), + myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url), description: Some(c.description.clone()).filter(|d| !d.is_empty()), talk_power: c.talk_power, talker: c.talk_power_granted, @@ -177,10 +178,8 @@ mod tests { InMessage::new(&packet.header(), text.as_bytes()).unwrap() } - /// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them: - /// in the channel list, when a channel is created and when it is edited. - #[test] - fn channel_banners() { + /// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`. + fn ts6_book() -> data::Connection { let InMessage::InitServer(init) = message(concat!( "initserver virtualserver_name=Test virtualserver_welcomemessage ", "virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ", @@ -200,20 +199,29 @@ mod tests { )) else { panic!("not an initserver"); }; - let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init); - let channel = |cid: u64, order: u64, name: &str, banner: &str| { - format!( - "cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \ - channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \ - channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \ - channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \ - channel_codec_is_unencrypted=1 channel_delete_delay=0 \ - channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \ - channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \ - channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \ - channel_storage_quota=4294967295" - ) - }; + data::Connection::new(EccKeyPrivP256::create().to_pub(), &init) + } + + /// A `channellist` entry as TeamSpeak 6 sends it. + fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String { + format!( + "cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \ + channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \ + channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \ + channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \ + channel_codec_is_unencrypted=1 channel_delete_delay=0 \ + channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \ + channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \ + channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \ + channel_storage_quota=4294967295" + ) + } + + /// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them: + /// in the channel list, when a channel is created and when it is edited. + #[test] + fn channel_banners() { + let mut book = ts6_book(); let list = format!( "channellist {}|{}", channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"), @@ -266,4 +274,50 @@ mod tests { assert_eq!(p.server.banner_mode, BannerMode::KeepAspect); assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust); } + + /// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it: + /// when the client enters and when it changes. + #[test] + fn myts_avatars() { + let mut book = ts6_book(); + book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", "")))) + .unwrap(); + let enter = |clid: u16, avatar: &str| { + format!( + "notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \ + client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \ + client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \ + client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \ + client_output_hardware=1 client_meta_data client_is_recording=0 \ + client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \ + client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \ + client_talk_request=0 client_talk_request_msg client_is_talker=0 \ + client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \ + client_needed_serverquery_view_power=75 client_is_channel_commander=0 \ + client_country=RU client_badges client_myteamspeak_id=m{clid} \ + client_integrations{avatar}" + ) + }; + for text in [ + enter( + 5, + r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png", + ), + // A TeamSpeak 3 server, or a client without one. + enter(6, ""), + enter(7, " client_myteamspeak_avatar"), + ] { + book.handle_command(&message(&text)).unwrap(); + } + let p = presence_from_book(&book, None, |_| false); + let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone(); + assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png")); + assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None)); + book.handle_command(&message( + r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png", + )) + .unwrap(); + let p = presence_from_book(&book, None, |_| false); + assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png")); + } } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 376548b..3d0e23e 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -125,7 +125,15 @@ enum SourceEvent { /// Identity of a wanted image, independent of its transport. #[derive(Clone, Debug, PartialEq, Eq, Hash)] enum ImageRequest { - Avatar { uid: String, hash: String }, + Avatar { + uid: String, + hash: String, + }, + /// A client's myTeamSpeak avatar (TeamSpeak 6), on the web. + MytsAvatar { + uid: String, + url: String, + }, Icon(u32), Picture(String), } @@ -164,6 +172,13 @@ struct ImageRetry { due: Option, } +/// Whether an explicitly requested image belongs to the voice connection +/// (downloaded over it, so dropped with it); a myTeamSpeak avatar is on the +/// web. +fn voice_bound(request: &ImageRequest) -> bool { + !matches!(request, ImageRequest::MytsAvatar { .. }) +} + /// Our live stream, for the gateway's directory. struct OwnStream { id: String, @@ -222,6 +237,12 @@ struct Session { contacts_rx: Option>, /// Avatars reported per client unique id (their hash), voice only. avatars: HashMap, + /// myTeamSpeak avatars wanted per client unique id (their link), any + /// presence: where the server's avatar is not shown. + myts_avatars: HashMap, + /// Clients whose server avatar could not be downloaded (retries used + /// up): their myTeamSpeak avatar is shown instead. + server_avatars_failed: HashSet, /// Icons reported or being fetched, voice only. icons: HashSet, /// Pictures on the web (banners) reported or being fetched, by address. @@ -259,6 +280,8 @@ impl Session { contacts, contacts_rx, avatars: HashMap::new(), + myts_avatars: HashMap::new(), + server_avatars_failed: HashSet::new(), icons: HashSet::new(), pictures: HashSet::new(), image_epoch: 0, @@ -673,9 +696,13 @@ impl Session { .voice_presence .as_ref() .and_then(|p| p.client_by_uid(&client_uid)) - .and_then(|c| c.avatar.clone()); - if let Some(hash) = hash { + .and_then(|c| c.avatar.clone()) + .filter(|_| !self.server_avatars_failed.contains(&client_uid)); + let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone()); + if let Some(hash) = hash.filter(|_| self.voice.is_some()) { self.fetch_avatar(&client_uid, &hash, true); + } else if let Some(url) = myts { + self.fetch_myts_avatar(&client_uid, &url, true); } } Command::ListOfflineMessages { request, .. } => { @@ -828,6 +855,8 @@ impl Session { self.image_epoch += 1; self.image_retries.clear(); self.avatars.clear(); + self.myts_avatars.clear(); + self.server_avatars_failed.clear(); self.icons.clear(); self.pictures.clear(); self.contact_audio.clear(); @@ -866,7 +895,7 @@ impl Session { } fn image_waiter(&self, request: ImageRequest, requested: bool) -> Waiter { - let epoch = if requested { + let epoch = if requested && voice_bound(&request) { self.voice.as_ref().map_or(0, |(generation, _)| *generation) } else { self.image_epoch @@ -884,6 +913,45 @@ impl Session { self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, waiter); } + /// The myTeamSpeak avatars of the presence shown (any source) where the + /// server's avatar is not shown: none set, no voice connection to + /// download it over, or its download gave up. As the official client: + /// the server's avatar first. + fn fetch_myts_avatars(&mut self, p: &Presence) { + if !self.settings.current().get(&CACHE_FETCH_IMAGES) { + return; + } + let mut wanted = HashMap::with_capacity(self.myts_avatars.len()); + for c in p.clients.values() { + let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue }; + let server_avatar = c.avatar.is_some() + && self.voice.is_some() + && !self.server_avatars_failed.contains(uid); + if server_avatar { + continue; + } + if self.myts_avatars.get(uid) != Some(url) { + self.fetch_myts_avatar(uid, url, false); + } + wanted.insert(uid.clone(), url.clone()); + } + self.myts_avatars = wanted; + } + + fn fetch_myts_avatar(&self, uid: &str, url: &str, requested: bool) { + let request = ImageRequest::MytsAvatar { uid: uid.into(), url: url.into() }; + let waiter = self.image_waiter(request, requested); + web::fetch_avatar(self.cache.current(), url, max_cache_bytes(&self.settings), waiter); + } + + /// The client shown (any presence) with this unique id. + fn shown_client(&self, uid: &str) -> Option<&voelin_model::ClientInfo> { + [&self.voice_presence, &self.gateway_presence, &self.query_presence] + .into_iter() + .find_map(|p| p.as_ref()) + .and_then(|p| p.client_by_uid(uid)) + } + fn fetch_icon(&self, icon: u32) { let waiter = self.image_waiter(ImageRequest::Icon(icon), false); self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter); @@ -894,6 +962,7 @@ impl Session { ImageRequest::Avatar { uid, hash } => { self.voice.is_some() && self.avatars.get(uid) == Some(hash) } + ImageRequest::MytsAvatar { uid, url } => self.myts_avatars.get(uid) == Some(url), ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id), ImageRequest::Picture(url) => self.pictures.contains(url), } @@ -907,13 +976,25 @@ impl Session { result: Result, ) { let wanted = if requested { - matches!(&request, ImageRequest::Avatar { uid, hash } - if self.voice.is_some() && self.voice_presence.as_ref() - .and_then(|p| p.client_by_uid(uid)).and_then(|c| c.avatar.as_ref()) == Some(hash)) + match &request { + ImageRequest::Avatar { uid, hash } => { + self.voice.is_some() + && self + .voice_presence + .as_ref() + .and_then(|p| p.client_by_uid(uid)) + .and_then(|c| c.avatar.as_ref()) + == Some(hash) + } + ImageRequest::MytsAvatar { uid, url } => { + self.shown_client(uid).and_then(|c| c.myts_avatar.as_ref()) == Some(url) + } + _ => false, + } } else { self.wants_image(&request) }; - let current = if requested { + let current = if requested && voice_bound(&request) { self.is_current(Source::Voice, epoch) } else { epoch == self.image_epoch @@ -932,12 +1013,21 @@ impl Session { ImageRequest::Avatar { uid: client_uid, hash } => { Event::AvatarReady { session, client_uid, hash, path } } + // The address in place of a hash: it changes with the + // picture. + ImageRequest::MytsAvatar { uid: client_uid, url } => { + Event::AvatarReady { session, client_uid, hash: url, path } + } ImageRequest::Icon(icon) => Event::IconReady { session, icon, path }, ImageRequest::Picture(url) => Event::PictureReady { session, url, path }, }); } Err(error) => { debug!(?request, %error, "image download failed"); + let avatar_of = match &request { + ImageRequest::Avatar { uid, .. } => Some(uid.clone()), + _ => None, + }; let retry = self .image_retries .entry(request) @@ -949,6 +1039,14 @@ impl Session { } _ => None, }; + // The server's avatar gave up (its files unreachable): the + // myTeamSpeak one, if the client has one. + if let (None, Some(uid)) = (retry.due, avatar_of) + && self.server_avatars_failed.insert(uid) + && let Some(presence) = self.voice_presence.clone() + { + self.fetch_myts_avatars(&presence); + } } } } @@ -959,6 +1057,7 @@ impl Session { self.images_enabled = enabled; self.image_epoch += 1; self.avatars.clear(); + self.myts_avatars.clear(); self.icons.clear(); self.pictures.clear(); self.image_retries.clear(); @@ -996,6 +1095,7 @@ impl Session { for request in ready { match request { ImageRequest::Avatar { uid, hash } => self.fetch_avatar(&uid, &hash, false), + ImageRequest::MytsAvatar { uid, url } => self.fetch_myts_avatar(&uid, &url, false), ImageRequest::Icon(icon) => self.fetch_icon(icon), ImageRequest::Picture(url) => self.fetch_picture(&url, true), } @@ -1927,6 +2027,7 @@ impl Session { self.emit_state(); } self.fetch_pictures(&presence); + self.fetch_myts_avatars(&presence); let presence = Arc::new(presence); self.contacts.presence(self.id, presence.clone()); self.emit(Event::Presence { session: self.id, presence }); @@ -2219,6 +2320,76 @@ mod banner_tests { std::fs::remove_dir_all(cache.dir()).unwrap(); } + /// myTeamSpeak avatars (TeamSpeak 6) come from the web where the + /// server's avatar is not shown: none set, no voice connection to get it + /// over (observing), or its download gave up. + #[tokio::test] + async fn myts_avatars_where_the_servers_is_not_shown() { + let (mut session, mut events) = session("myts-avatar"); + let cache = session.cache.current(); + let client = |id, uid: &str, avatar: Option<&str>, myts: &str| voelin_model::ClientInfo { + id, + uid: Some(uid.into()), + avatar: avatar.map(Into::into), + myts_avatar: Some(myts.into()), + ..Default::default() + }; + let (a, b) = ("https://a.example.test/a.png", "https://a.example.test/b.png"); + let hash = "0123456789abcdef0123456789abcdef"; + let mut presence = Presence::default(); + presence.clients.insert(1, client(1, "A=", None, a)); + presence.clients.insert(2, client(2, "B=", Some(hash), b)); + // Owned here, so nothing goes to the network. + let temps: Vec<_> = [a, b] + .iter() + .map(|url| { + let key = cache::picture_key(url).unwrap(); + let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else { + panic!("first download"); + }; + (key, temp) + }) + .collect(); + // Observing: both, even the one with a server avatar. + session.gateway_presence = Some(presence.clone()); + session.publish_presence(); + assert_eq!(session.myts_avatars.len(), 2); + for (key, temp) in &temps { + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(temp, b"\x89PNG\r\n\x1a\npicture").unwrap(); + cache.finish(key, temp, Ok(()), 0); + let done = session.sources_rx.as_mut().unwrap().recv().await.unwrap(); + session.source_event(done); + } + let mut ready = Vec::new(); + while let Ok(event) = events.try_recv() { + if let Event::AvatarReady { client_uid, hash, .. } = event { + ready.push((client_uid, hash)); + } + } + ready.sort(); + assert_eq!(ready, [("A=".to_owned(), a.to_owned()), ("B=".to_owned(), b.to_owned())]); + // With voice the server's avatar is shown where there is one. + let (tx, _rx) = mpsc::unbounded_channel(); + session.voice = Some((1, tx)); + session.voice_presence = Some(presence.clone()); + session.publish_presence(); + assert_eq!(session.myts_avatars.keys().collect::>(), ["A="]); + // Until its download gives up (the server's files unreachable). + let request = ImageRequest::Avatar { uid: "B=".into(), hash: hash.into() }; + session.avatars.insert("B=".into(), hash.into()); + for _ in 0..4 { + session.image_finished( + false, + session.image_epoch, + request.clone(), + Err("refused".into()), + ); + } + assert_eq!(session.myts_avatars.get("B=").map(String::as_str), Some(b)); + std::fs::remove_dir_all(cache.dir()).unwrap(); + } + #[tokio::test] async fn enabling_images_replays_current_presence_without_server_updates() { let (mut session, mut events) = session("policy-enable"); diff --git a/crates/voelin-core/src/web.rs b/crates/voelin-core/src/web.rs index 9af4ddf..5373a4f 100644 --- a/crates/voelin-core/src/web.rs +++ b/crates/voelin-core/src/web.rs @@ -54,6 +54,23 @@ static CLIENT: LazyLock> = LazyLock::new(|| { /// ask (again with `fresh`: it changes at its address); `waiter` is told /// where it is. `max_cache_bytes`: `cache.max_mb` in bytes. pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, waiter: Waiter) { + fetch_within(cache, url, fresh, max_cache_bytes, &LIMITS, waiter); +} + +/// [`fetch`] a myTeamSpeak avatar: a picture of at most +/// [`AVATAR_LIMITS`]'s size, once (its link changes with it). +pub(crate) fn fetch_avatar(cache: Cache, url: &str, max_cache_bytes: u64, waiter: Waiter) { + fetch_within(cache, url, false, max_cache_bytes, &AVATAR_LIMITS, waiter); +} + +fn fetch_within( + cache: Cache, + url: &str, + fresh: bool, + max_cache_bytes: u64, + limits: &'static Limits, + waiter: Waiter, +) { let Some(key) = cache::picture_key(url) else { waiter(Err("not an http or https address".into())); return; @@ -62,7 +79,7 @@ pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, let url = url.to_owned(); tokio::spawn(async move { let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open"); - let result = download(&url, &temp, &LIMITS).await; + let result = download(&url, &temp, limits).await; cache.finish(&key, &temp, result, max_cache_bytes); }); } @@ -77,6 +94,8 @@ struct Limits { const LIMITS: Limits = Limits { max_bytes: cache::MAX_PICTURE_BYTES, grace: GRACE, min_rate: cache::MIN_PICTURE_RATE }; +/// Avatars are small pictures (as myTeamSpeak's own, 4 MiB at most). +const AVATAR_LIMITS: Limits = Limits { max_bytes: 4 << 20, ..LIMITS }; /// Download the picture at `url` into `to` within `limits`, and only if it /// is a picture (what arrived stays in `to` on failure; the cache removes it). diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index 95acfa9..8ba52df 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -11,7 +11,7 @@ mod tree; pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message}; pub use presence::{ ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType, - Presence, PresenceDelta, PresenceSnapshot, parse_badges, + Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, }; pub use server::{ BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, diff --git a/crates/voelin-model/src/presence.rs b/crates/voelin-model/src/presence.rs index 7776838..b9b2b6f 100644 --- a/crates/voelin-model/src/presence.rs +++ b/crates/voelin-model/src/presence.rs @@ -98,6 +98,11 @@ pub struct ClientInfo { /// no avatar. A new hash means a new avatar. #[serde(default, skip_serializing_if = "Option::is_none")] pub avatar: Option, + /// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from + /// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the + /// server has no avatar for the client. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub myts_avatar: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, #[serde(default, skip_serializing_if = "is_zero_i32")] @@ -136,6 +141,34 @@ pub fn parse_badges(value: &str) -> Vec { .collect() } +/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak +/// 6): `,;,…`, states as myTeamSpeak's +/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the +/// official client reads it: an entry that is not `,` (an +/// empty one too, from a trailing `;`) makes the whole value no avatar; +/// the "online" picture is shown whatever the client's state (an unknown +/// state counts as online), else away, do not disturb, offline, the first +/// of a kind. Only an HTTPS link of at most 4 KiB. +pub fn myts_avatar_url(value: &str) -> Option { + let mut best: Option<(u8, &str)> = None; + for entry in value.split(';') { + let mut parts = entry.split(','); + let state: u32 = parts.next()?.trim().parse().ok()?; + let url = parts.next()?.trim(); + let rank = match state { + 3 => 1, + 1 => 2, + 4 => 3, + _ => 0, + }; + if best.is_none_or(|(r, _)| rank < r) { + best = Some((rank, url)); + } + } + let url = best?.1; + (url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned()) +} + /// How a group's name is shown next to its members. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -348,6 +381,38 @@ mod tests { assert!(new.diff(&new).is_empty()); } + #[test] + fn myts_avatars_as_the_official_client_reads_them() { + let on = "https://a.example.test/on.png"; + assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on)); + // Away before do not disturb before offline; the first of a kind. + assert_eq!( + myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b") + .as_deref(), + Some("https://a/away") + ); + assert_eq!( + myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(), + Some("https://a/dnd") + ); + // An unknown state counts as online. + assert_eq!( + myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(), + Some("https://a/x") + ); + // One bad entry spoils the value. + for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] { + assert_eq!(myts_avatar_url(bad), None, "{bad:?}"); + } + // Only HTTPS, and not endless. + assert_eq!(myts_avatar_url("2,http://a/on"), None); + assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None); + // Older JSON without the field still loads. + let client: ClientInfo = + serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap(); + assert_eq!(client.myts_avatar, None); + } + #[test] fn badges_and_groups() { assert_eq!( diff --git a/crates/voelin-observer/src/convert.rs b/crates/voelin-observer/src/convert.rs index a174f40..6b630fe 100644 --- a/crates/voelin-observer/src/convert.rs +++ b/crates/voelin-observer/src/convert.rs @@ -89,6 +89,7 @@ pub fn client_from_row(row: &Row) -> Option { // What the row carries (`notifycliententerview` all of it, // `clientlist -voice -groups -icon` some). avatar: row.get("client_flag_avatar").filter(|a| !a.is_empty()).map(str::to_string), + myts_avatar: row.get("client_myteamspeak_avatar").and_then(voelin_model::myts_avatar_url), description: row.get("client_description").filter(|d| !d.is_empty()).map(str::to_string), talk_power: row.parse("client_talk_power").unwrap_or(0), talker: row.flag("client_is_talker").unwrap_or(false), From 013a7f95f283c6ac0468fd527533ad21f3ef6fd1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 22:00:34 +0000 Subject: [PATCH 04/42] account: show servers the account's avatar As the official TeamSpeak 6 client does once connected and after a sign-in, Voelin sends updatemytsdata with the account's certificate and its avatar (LoginSession.mytsid_user_cert.cert and user_avatar, raw bytes with TeamSpeak's escaping only; \a and \b now escaped too). The avatar is sliced out of the login response as it came: its signature covers it. Both come from a password sign-in; they are kept per account next to the avatar picture (public data, outside the keyring) and published to every voice connection that presents the account (Command::SetMytsData, beside the identity). A refusal is only logged. Accounts signed in before need one password sign-in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- crates/proto/tsclientlib/src/lib.rs | 1 + crates/proto/tsclientlib/src/myts.rs | 59 +++++++++++ crates/proto/tsproto-packets/src/packets.rs | 4 + crates/voelin-core/src/lib.rs | 17 +++ crates/voelin-core/src/session.rs | 21 +++- crates/voelin-core/src/voice.rs | 65 +++++++++++- crates/voelin-myts/src/lib.rs | 16 ++- crates/voelin-myts/src/profile.rs | 105 +++++++++++++++++++ crates/voelin-myts/src/tests.rs | 20 ++++ crates/voelin-ui/src/myts.rs | 110 +++++++++++++++++++- docs/research/myteamspeak.md | 37 +++++++ 11 files changed, 448 insertions(+), 7 deletions(-) diff --git a/crates/proto/tsclientlib/src/lib.rs b/crates/proto/tsclientlib/src/lib.rs index 41d7fe4..0d410cf 100644 --- a/crates/proto/tsclientlib/src/lib.rs +++ b/crates/proto/tsclientlib/src/lib.rs @@ -61,6 +61,7 @@ pub use ts_bookkeeping::messages::s2c::InMessage; pub use ts_bookkeeping::*; pub use tsproto::resend::{ConnectionStats, PacketStat}; pub use tsproto::Identity; +pub use myts::MytsData; pub use tsproto_types::errors::Error as TsError; /// Wait this time for initserver, in seconds. diff --git a/crates/proto/tsclientlib/src/myts.rs b/crates/proto/tsclientlib/src/myts.rs index 91bd276..9b3c20e 100644 --- a/crates/proto/tsclientlib/src/myts.rs +++ b/crates/proto/tsclientlib/src/myts.rs @@ -14,7 +14,38 @@ impl ConnectOptions { } } +/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6), +/// as myTeamSpeak signed it: the account's certificate and its avatar +/// (`LoginSession.user_avatar` as it came). The server shows the avatar to +/// everyone (`client_myteamspeak_avatar`). +#[derive(Clone, Default, PartialEq, Eq)] +pub struct MytsData { + pub certificate: Vec, + /// Empty: none. + pub avatar: Vec, +} + +impl std::fmt::Debug for MytsData { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MytsData") + .field("certificate", &self.certificate.len()) + .field("avatar", &self.avatar.len()) + .finish() + } +} + impl Connection { + /// Show the server the account's certificate and avatar + /// (`updatemytsdata`), as the official client does once connected and + /// after a sign-in, after the account proof (`updatemytsid`). + /// Await the returned handle's `StreamItem::MessageResult` for the answer. + pub fn send_myts_data(&mut self, data: &MytsData) -> Result { + if !matches!(self.state, ConnectionState::Connected { .. }) { + return Err(Error::NotConnected); + } + self.send_command_with_result(data_packet(data)) + } + /// Publish a connection-bound account proof, or clear the account identity. /// /// Always updates the reconnect options, even if currently disconnected or @@ -34,6 +65,18 @@ impl Connection { } } +/// The values are the raw bytes with TeamSpeak's escaping only (no +/// base64), as the official client sends them; an empty avatar is left out. +fn data_packet(data: &MytsData) -> OutCommand { + let mut packet = + OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsdata"); + packet.write_bin_arg("myts_certificate", &data.certificate); + if !data.avatar.is_empty() { + packet.write_bin_arg("myts_avatar", &data.avatar); + } + packet +} + fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand { let mut packet = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsid"); @@ -50,6 +93,22 @@ fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand { mod tests { use super::*; + #[test] + fn account_data_goes_raw_and_escaped() { + let data = MytsData { + certificate: b"a b/c|d\\\x07\x08\x00\xff".to_vec(), + avatar: vec![0x0a, 0x02, b'h', b'i'], + }; + let packet = data_packet(&data).into_packet(); + assert_eq!( + packet.content(), + b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff myts_avatar=\\n\x02hi" + ); + // Without an avatar: the certificate alone. + let packet = data_packet(&MytsData { avatar: Vec::new(), ..data }).into_packet(); + assert!(!packet.content().windows(11).any(|w| w == b"myts_avatar")); + } + #[test] fn clear_contains_no_previous_account_proof() { let packet = update_packet(None, &[0; 64]).into_packet(); diff --git a/crates/proto/tsproto-packets/src/packets.rs b/crates/proto/tsproto-packets/src/packets.rs index bc4c7a8..5e085c2 100644 --- a/crates/proto/tsproto-packets/src/packets.rs +++ b/crates/proto/tsproto-packets/src/packets.rs @@ -968,6 +968,10 @@ impl io::Write for EscapedWriter<'_> { self.0.reserve(buf.len()); for c in buf { match c { + // Voelin patch: \a and \b as TeamSpeak escapes them (binary + // values, e.g. `updatemytsdata`). + b'\x07' => self.0.extend_from_slice(b"\\a"), + b'\x08' => self.0.extend_from_slice(b"\\b"), b'\x0b' => self.0.extend_from_slice(b"\\v"), b'\x0c' => self.0.extend_from_slice(b"\\f"), b'\\' => self.0.extend_from_slice(b"\\\\"), diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 10a2729..cc12950 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -104,6 +104,10 @@ pub type SessionId = u64; pub enum Command { /// Main account proof for every current and future voice connection. SetMytsIdentity(Option>), + /// What voice servers are shown of the main account (its certificate + /// and avatar, TeamSpeak 6): sent to every connection that presents the + /// account, once connected and when it changes. + SetMytsData(Option>), ConnectVoice { session: SessionId, options: Box, @@ -818,6 +822,7 @@ async fn run( contacts.load().await; let mut sessions: HashMap = HashMap::new(); let (myts_identity, _) = watch::channel(None); + let (myts_data, _) = watch::channel(None); let mut current = shared.current(); // Pruning: at start, then hourly (and when the setting changes). let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600)); @@ -875,6 +880,16 @@ async fn run( }); continue; } + Command::SetMytsData(data) => { + myts_data.send_if_modified(|current| { + if *current == data { + return false; + } + *current = data; + true + }); + continue; + } Command::SetAudioSettings(new) => { settings = (*new).clone(); for s in sessions.values() { @@ -951,6 +966,7 @@ async fn run( settings.clone(), engine.clone(), myts_identity.subscribe(), + myts_data.subscribe(), ); if let Some(profiles) = &srtp_profiles { s.send(Command::SetSrtpProfiles(profiles.clone())); @@ -1029,6 +1045,7 @@ fn command_session(command: &Command) -> SessionId { | Command::SetOfflineMessageRead { session, .. } | Command::CloseSession { session } => *session, Command::SetMytsIdentity(_) + | Command::SetMytsData(_) | Command::SetAudioSettings(_) | Command::SetSrtpProfiles(_) | Command::TestMicrophone { .. } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 3d0e23e..b7ad265 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -87,10 +87,12 @@ impl SessionHandle { audio_settings: AudioSettings, shared: Shared, myts_identity: watch::Receiver>>, + myts_data: watch::Receiver>>, ) -> Self { let (tx, rx) = mpsc::unbounded_channel(); tokio::spawn( - Session::new(id, events, frames, audio_settings, shared, myts_identity).run(rx), + Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data) + .run(rx), ); Self { tx } } @@ -190,6 +192,7 @@ struct OwnStream { struct Session { myts_identity: watch::Receiver>>, + myts_data: watch::Receiver>>, id: SessionId, events: broadcast::Sender, state: SessionState, @@ -270,12 +273,14 @@ impl Session { audio_settings: AudioSettings, shared: Shared, myts_identity: watch::Receiver>>, + myts_data: watch::Receiver>>, ) -> Self { let (sources_tx, sources_rx) = mpsc::unbounded_channel(); let Shared { settings, history, cache, contacts } = shared; let contacts_rx = Some(contacts.watch()); Self { myts_identity, + myts_data, cache, contacts, contacts_rx, @@ -411,6 +416,7 @@ impl Session { } let link = VoiceLink { myts_identity: self.myts_identity.clone(), + myts_data: self.myts_data.clone(), session: self.id, events: self.events.clone(), settings: self.settings.clone(), @@ -733,6 +739,7 @@ impl Session { } // Engine-wide. Command::SetMytsIdentity(_) + | Command::SetMytsData(_) | Command::CloseSession { .. } | Command::TestMicrophone { .. } | Command::SetSetting { .. } @@ -2056,7 +2063,17 @@ mod banner_tests { // No myTeamSpeak account; its source stays open, as the engine's does // (a closed one ends voice connections). let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); - (Session::new(1, events, frames, AudioSettings::default(), shared, myts_identity), receiver) + let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); + let session = Session::new( + 1, + events, + frames, + AudioSettings::default(), + shared, + myts_identity, + myts_data, + ); + (session, receiver) } #[tokio::test] diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index a4687d9..d435570 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -70,6 +70,8 @@ impl VoiceOptions { #[derive(Clone)] pub(crate) struct VoiceLink { pub myts_identity: watch::Receiver>>, + /// What the server is shown of the account ([`crate::Command::SetMytsData`]). + pub myts_data: watch::Receiver>>, pub session: SessionId, pub events: broadcast::Sender, pub settings: SharedSettings, @@ -227,6 +229,7 @@ fn now_ms() -> i64 { enum Input { MytsIdentityChanged, + MytsDataChanged, AccountSourceClosed, Item(Option>), Cmd(Option), @@ -236,6 +239,8 @@ enum Input { /// A command waiting for the server's answer. enum Pending { MytsIdentity(Instant), + /// `updatemytsdata`: its answer is only logged. + MytsData, Stream(Request), FileList { request: RequestId, @@ -366,6 +371,7 @@ async fn run_inner( builder = builder.channel(channel.clone()); } let mut identity = link.myts_identity.clone(); + let mut data = link.myts_data.clone(); // A changed account invalidates an in-flight handshake. Drop that connection // and take a fresh snapshot before publishing any connected state. let mut con = timeout(Duration::from_secs(30), async { @@ -435,6 +441,10 @@ async fn run_inner( transfers: HashMap::new(), }; voice.publish_state()?; + // The account's avatar, for everyone on the server (as the official + // client, once connected). + data.borrow_and_update(); + voice.send_myts_data(&identity, &data); let mut tick = tokio::time::interval(Duration::from_millis(250)); let result = loop { @@ -445,7 +455,9 @@ async fn run_inner( }) { break Err(anyhow::anyhow!("myTeamSpeak account update timed out")); } - let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await; + let input = + next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data) + .await; match input { Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")), Input::MytsIdentityChanged => { @@ -456,6 +468,12 @@ async fn run_inner( } Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")), } + // After the proof, what is shown of the account (a sign-in). + voice.send_myts_data(&identity, &data); + } + Input::MytsDataChanged => { + data.borrow_and_update(); + voice.send_myts_data(&identity, &data); } Input::Item(None) => break Err(anyhow::anyhow!("connection closed")), Input::Item(Some(Err(e))) => break Err(e.into()), @@ -488,6 +506,7 @@ async fn next_input( commands: &mut mpsc::UnboundedReceiver, tick: &mut tokio::time::Interval, identity: &mut watch::Receiver>>, + data: &mut watch::Receiver>>, ) -> Input { tokio::select! { biased; @@ -496,6 +515,11 @@ async fn next_input( } else { Input::AccountSourceClosed }, + changed = data.changed() => if changed.is_ok() { + Input::MytsDataChanged + } else { + Input::AccountSourceClosed + }, input = async { // Keep account changes first without starving network or timers when // the audio command queue remains ready. @@ -802,6 +826,10 @@ impl Voice { self.link.emit(Event::OfflineMessage { session, request, result }); } Pending::Quiet | Pending::MytsIdentity(_) => {} + Pending::MytsData => match result { + Ok(()) => debug!("the server took the account's avatar"), + Err(e) => warn!(error = %e, "the server refused the account's avatar"), + }, Pending::Report(what) => { if let Err(e) = result { let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}"))); @@ -810,6 +838,27 @@ impl Voice { } } + /// Show the server the account's certificate and avatar + /// (`updatemytsdata`), when connected with the account. + fn send_myts_data( + &mut self, + identity: &watch::Receiver>>, + data: &watch::Receiver>>, + ) { + if identity.borrow().is_none() { + return; + } + let Some(data) = data.borrow().clone().filter(|d| !d.certificate.is_empty()) else { + return; + }; + match self.con.send_myts_data(&data) { + Ok(handle) => { + self.pending.insert(handle, Pending::MytsData); + } + Err(e) => warn!(error = %e, "the account's avatar was not sent"), + } + } + fn send(&mut self, cmd: OutCommand, pending: Pending) -> anyhow::Result<()> { let handle = cmd.send_with_result(&mut self.con)?; self.pending.insert(handle, pending); @@ -1116,6 +1165,7 @@ mod account_tests { #[tokio::test(start_paused = true)] async fn account_priority_preserves_ready_network_and_timer_progress() { let (account, mut identity) = watch::channel(None); + let (account_data, mut data) = watch::channel(None); let (commands, mut receiver) = mpsc::unbounded_channel(); for _ in 0..512 { commands.send(VoiceCmd::SetInputMuted(false)).unwrap(); @@ -1126,14 +1176,22 @@ mod account_tests { let mut tick = tokio::time::interval(Duration::from_millis(1)); account.send_replace(None); assert!(matches!( - next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await, + next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await, Input::MytsIdentityChanged )); identity.borrow_and_update(); + // What is shown of the account changes too, ahead of the rest. + account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default()))); + assert!(matches!( + next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await, + Input::MytsDataChanged + )); + data.borrow_and_update(); let (mut network, mut timers, mut audio) = (0, 0, 0); for _ in 0..512 { tokio::time::advance(Duration::from_millis(1)).await; - match next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await { + match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await + { Input::Item(_) => network += 1, Input::Tick => timers += 1, Input::Cmd(_) => audio += 1, @@ -1168,6 +1226,7 @@ mod account_tests { events, settings: SharedSettings::new(crate::settings::Settings::default()), myts_identity: identity, + myts_data: watch::channel(None).1, }; let (_commands, commands) = mpsc::unbounded_channel(); let (events, mut received) = mpsc::unbounded_channel(); diff --git a/crates/voelin-myts/src/lib.rs b/crates/voelin-myts/src/lib.rs index 5931b31..59f710e 100644 --- a/crates/voelin-myts/src/lib.rs +++ b/crates/voelin-myts/src/lib.rs @@ -6,7 +6,7 @@ mod identity; mod profile; mod transport; pub use identity::IdentityError; -pub use profile::{Badge, Device, Profile}; +pub use profile::{Badge, Device, Presentation, Profile}; pub use tsproto::myts::Identity as ServerIdentity; use zeroize::{Zeroize, Zeroizing}; @@ -27,6 +27,9 @@ pub struct Login { /// What the login response tells about the account (the avatar's file /// names, the description); [`Client::profile`] tells more. pub profile: Profile, + /// What voice servers are shown of the account (its avatar), as + /// signed by myTeamSpeak. + pub presentation: Presentation, } /// Server-provided alternative login material, stored only in a secret store. @@ -181,7 +184,17 @@ impl Client { encryption_key: Option>, ) -> Result { let bytes = self.transport.call("authentication", method, body).await?; + // The avatar exactly as it came: its signature covers its bytes. + let avatar = profile::raw_field(&bytes, profile::USER_AVATAR).unwrap_or_default().to_vec(); let response: api::LoginSession = wire::decode(bytes)?; + let presentation = Presentation { + certificate: response + .mytsid_user_cert + .as_ref() + .map(|c| c.cert.clone()) + .unwrap_or_default(), + avatar, + }; let token = SessionToken::try_from(&response)?; let (response, identity) = tokio::task::spawn_blocking(move || { let identity = match encryption_key { @@ -197,6 +210,7 @@ impl Client { token, identity, profile, + presentation, uuid: response.uuid, username: response.username, renewal: response.alternative_login_info.map(|info| Renewal { diff --git a/crates/voelin-myts/src/profile.rs b/crates/voelin-myts/src/profile.rs index 4deff05..7527d0f 100644 --- a/crates/voelin-myts/src/profile.rs +++ b/crates/voelin-myts/src/profile.rs @@ -5,6 +5,81 @@ use crate::Error; use schema_api::SessionToken; use schema_api::api::{self, user}; +/// `LoginSession.user_avatar`, the account's avatar as myTeamSpeak signed +/// it. +pub(crate) const USER_AVATAR: u32 = 11; + +/// What voice servers show of the account (TeamSpeak 6): sent to each +/// server once connected (`updatemytsdata`), as the official client does. +/// Public data, as myTeamSpeak signed it; empty without it. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct Presentation { + /// The account's certificate (`LoginSession.mytsid_user_cert.cert`). + pub certificate: Vec, + /// The avatar (`LoginSession.user_avatar`, an `AvatarData`: its + /// pictures' links, a timestamp and myTeamSpeak's signature), the bytes + /// exactly as they came: the signature covers them, and fields this + /// version does not know would be lost by encoding them again. + pub avatar: Vec, +} + +impl Presentation { + /// Whether there is anything to show (a certificate, without which a + /// server takes nothing). + pub fn is_empty(&self) -> bool { + self.certificate.is_empty() + } +} + +impl std::fmt::Debug for Presentation { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Presentation") + .field("certificate", &self.certificate.len()) + .field("avatar", &self.avatar.len()) + .finish() + } +} + +/// The bytes of the last length-delimited field `number` at the top level +/// of a protobuf message, as they are; `None` without one or for a message +/// that does not parse. +pub(crate) fn raw_field(message: &[u8], number: u32) -> Option<&[u8]> { + fn varint(data: &[u8], at: &mut usize) -> Option { + let mut value = 0u64; + for shift in (0..64).step_by(7) { + let byte = *data.get(*at)?; + *at += 1; + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Some(value); + } + } + None + } + let mut at = 0; + let mut found = None; + while at < message.len() { + let key = varint(message, &mut at)?; + let skip = match key & 7 { + 0 => { + varint(message, &mut at)?; + 0 + } + 1 => 8, + 2 => usize::try_from(varint(message, &mut at)?).ok()?, + 5 => 4, + // Groups are not used by myTeamSpeak. + _ => return None, + }; + let end = at.checked_add(skip).filter(|end| *end <= message.len())?; + if key & 7 == 2 && key >> 3 == u64::from(number) { + found = Some(&message[at..end]); + } + at = end; + } + found +} + /// `ERROR_SESSION_EXPIRED` of the `/user` service. pub(crate) const SESSION_EXPIRED: i32 = user::ErrorReturnCode::ErrorSessionExpired as i32; /// Avatars are small pictures; anything larger is not one. @@ -141,6 +216,36 @@ fn unix_seconds(value: i64) -> i64 { mod tests { use super::*; + #[test] + fn the_avatar_is_kept_as_it_came() { + let avatar = api::AvatarData { + info: Some(api::AvatarInfo { map: vec![map(api::AvatarState::Online, "https://a/o")] }), + timestamp: 1_760_000_000, + sign: vec![7; 64], + ..Default::default() + }; + // A field this version does not know, inside the avatar. + let mut raw = schema_api::wire::encode(&avatar); + raw.extend_from_slice(&[0x78, 0x01]); + let mut message = schema_api::wire::encode(&api::LoginSession { + session: "s".into(), + username: "u".into(), + ..Default::default() + }); + message.push(((USER_AVATAR << 3) | 2) as u8); + message.push(raw.len() as u8); + message.extend_from_slice(&raw); + message.extend_from_slice(&schema_api::wire::encode(&api::LoginSession { + push_token: "after".into(), + ..Default::default() + })); + assert_eq!(raw_field(&message, USER_AVATAR), Some(raw.as_slice())); + assert_eq!(raw_field(&message, 13), None); + // Cut short: nothing rather than a part. + assert_eq!(raw_field(&message[..message.len() - 3], USER_AVATAR), None); + assert!(Presentation::default().is_empty()); + } + fn map(state: api::AvatarState, name: &str) -> api::avatar_info::AvatarMap { api::avatar_info::AvatarMap { state: state as i32, name: name.into() } } diff --git a/crates/voelin-myts/src/tests.rs b/crates/voelin-myts/src/tests.rs index 5bc02f4..e8ee3cc 100644 --- a/crates/voelin-myts/src/tests.rs +++ b/crates/voelin-myts/src/tests.rs @@ -145,6 +145,26 @@ async fn login_roundtrip_keeps_credentials_in_body_and_redacts_results() { assert!(!data.skip_session); } +/// What servers are shown of the account comes with the login: the +/// certificate, and the avatar as it came. +#[tokio::test] +async fn the_login_brings_the_accounts_presentation() { + let avatar = api::AvatarData { timestamp: 42, sign: vec![1; 64], ..Default::default() }; + let response = api::LoginSession { + mytsid_user_cert: Some(api::MyTsUserCertificate { cert: vec![9, 8, 7] }), + user_avatar: Some(avatar.clone()), + ..success() + }; + let (client, _server) = mock(200, "", wire::encode(&response)).await; + let login = client.login("mail", "password", None, "device").await.unwrap(); + assert_eq!(login.presentation.certificate, [9, 8, 7]); + assert_eq!(login.presentation.avatar, wire::encode(&avatar)); + // Without them: nothing to show. + let (client, _server) = mock(200, "", wire::encode(&success())).await; + let login = client.login("mail", "password", None, "device").await.unwrap(); + assert!(login.presentation.is_empty() && login.presentation.avatar.is_empty()); +} + #[tokio::test] async fn login_requires_explicit_success_nonempty_token_and_preserves_status() { for code in [0, 202, 208, 98765] { diff --git a/crates/voelin-ui/src/myts.rs b/crates/voelin-ui/src/myts.rs index af7739d..6c3f380 100644 --- a/crates/voelin-ui/src/myts.rs +++ b/crates/voelin-ui/src/myts.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; use std::path::PathBuf; use std::sync::Arc; -use voelin_myts::{Client, Login, Profile, ServerIdentity, SessionToken}; +use voelin_myts::{Client, Login, Presentation, Profile, ServerIdentity, SessionToken}; use voelin_store::Secrets; use crate::app::{App, Bridge, MytsForm, later}; @@ -50,6 +50,18 @@ struct SavedProfile { /// The account's avatar picture, in the account directory. const AVATAR_FILE: &str = "avatar"; +/// What servers are shown of the account ([`Presentation`]), in the +/// account directory: public data, so not in the keyring (whose items are +/// small on some systems). +const PRESENTATION_FILE: &str = "presentation.json"; + +/// [`PRESENTATION_FILE`]: whose it is, and what. +#[derive(Serialize, Deserialize)] +struct SavedPresentation { + uuid: String, + certificate: Vec, + avatar: Vec, +} /// A date (Unix seconds) as the profile shows it; empty when not known. fn date(seconds: i64) -> String { @@ -97,6 +109,9 @@ pub(crate) struct Account { /// The avatar, decoded. avatar: slint::Image, saved: Option, + /// What servers are shown of the account; only from a password + /// sign-in (a kept session is not told again). + presentation: Option, signed_in: bool, busy: bool, /// The saved session is being checked (not a password sign-in). @@ -121,6 +136,57 @@ impl Account { self.dir.as_ref().map(|dir| dir.join(AVATAR_FILE)) } + fn presentation_path(&self) -> Option { + self.dir.as_ref().map(|dir| dir.join(PRESENTATION_FILE)) + } + + /// The kept presentation, if it is the saved account's. + fn load_presentation(&mut self) { + let uuid = self.saved.as_ref().map(|s| s.uuid.as_str()).unwrap_or_default(); + self.presentation = self + .presentation_path() + .and_then(|path| std::fs::read(path).ok()) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|kept| !uuid.is_empty() && kept.uuid == uuid) + .map(|kept| Presentation { certificate: kept.certificate, avatar: kept.avatar }); + } + + /// A sign-in's presentation, kept for the next start. + fn set_presentation(&mut self, uuid: &str, presentation: Presentation) { + if let Some(path) = self.presentation_path() { + let kept = SavedPresentation { + uuid: uuid.to_owned(), + certificate: presentation.certificate.clone(), + avatar: presentation.avatar.clone(), + }; + let written = + serde_json::to_vec(&kept).map_err(std::io::Error::other).and_then(|json| { + path.parent().map_or(Ok(()), std::fs::create_dir_all)?; + std::fs::write(&path, json) + }); + if let Err(error) = written { + tracing::warn!(%error, "could not keep what servers are shown of the account"); + } + } + self.presentation = Some(presentation); + } + + fn forget_presentation(&mut self) { + self.presentation = None; + if let Some(path) = self.presentation_path() { + let _ = std::fs::remove_file(path); + } + } + + /// What voice servers are shown of the signed-in account. + fn myts_data(&self) -> Option { + self.identity()?; + self.presentation.as_ref().filter(|p| !p.is_empty()).map(|p| tsclientlib::MytsData { + certificate: p.certificate.clone(), + avatar: p.avatar.clone(), + }) + } + /// The kept picture, shown while the session is checked. fn load_avatar(&mut self) { let bytes = self.avatar_path().and_then(|path| std::fs::read(path).ok()); @@ -162,6 +228,7 @@ impl Account { self.saved = saved; if self.saved.is_some() { self.load_avatar(); + self.load_presentation(); } self.can_forget = false; self.status = 0; @@ -202,6 +269,11 @@ impl Account { if same_account { self.saved.take().unwrap().profile } else { SavedProfile::default() }; if !same_account { self.forget_avatar(); + self.forget_presentation(); + } + // A sign-in without it keeps the same account's known one. + if !login.presentation.is_empty() { + self.set_presentation(&login.uuid, login.presentation); } profile.update(&login.profile); let saved = Saved { @@ -327,6 +399,7 @@ impl Account { self.persistence_status = if cleared { 0 } else { 8 }; self.can_forget = !cleared; self.forget_avatar(); + self.forget_presentation(); cleared } } @@ -381,6 +454,13 @@ impl App { self.engine.send(voelin_core::Command::SetMytsIdentity( self.myts.identity().cloned().map(Arc::new), )); + // What servers are shown of it (its avatar), after the proof. + let data = self.myts.myts_data(); + if data.is_none() && self.myts.identity().is_some() { + // Signed in before Voelin kept it: only a password sign-in tells it. + tracing::info!("servers see no avatar of the account until the next password sign-in"); + } + self.engine.send(voelin_core::Command::SetMytsData(data.map(Arc::new))); } pub(crate) fn refresh_myts(&self) { @@ -642,9 +722,37 @@ mod tests { otp_token: format!("{name}-otp"), device_id: format!("{name}-device"), }), + presentation: Presentation { + certificate: format!("{name}-cert").into_bytes(), + avatar: format!("{name}-avatar").into_bytes(), + }, } } + /// What servers are shown of the account is kept for it, told once its + /// session is valid again, and never shown for another account. + #[test] + fn what_servers_are_shown_is_kept_per_account() { + let dir = std::env::temp_dir().join(format!("voelin-presentation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let secrets = MemorySecrets::default(); + let mut account = Account::new(dir.clone()); + account.accept(&secrets, login("Alice"), "alice@example.test".into()); + assert_eq!(account.myts_data().unwrap().certificate, b"Alice-cert"); + let mut restarted = Account::new(dir.clone()); + restarted.load(&secrets); + assert!(restarted.myts_data().is_none(), "not before the session is checked"); + restarted.restored(); + assert_eq!(restarted.myts_data().unwrap().avatar, b"Alice-avatar"); + restarted.forget(&secrets); + assert!(!dir.join(PRESENTATION_FILE).exists()); + let mut bob = login("Bob"); + bob.presentation = Presentation::default(); + restarted.accept(&secrets, bob, "bob@example.test".into()); + assert!(restarted.myts_data().is_none()); + let _ = std::fs::remove_dir_all(dir); + } + fn server_identity() -> ServerIdentity { let mut private = [0; 32]; private[0] = 1; diff --git a/docs/research/myteamspeak.md b/docs/research/myteamspeak.md index 22bc286..4be240b 100644 --- a/docs/research/myteamspeak.md +++ b/docs/research/myteamspeak.md @@ -108,6 +108,43 @@ file names and description are used until then. What is kept goes into the same secret-store bundle as the session (`profile`), never the token into a URL. +### Presenting the account's avatar, and other clients' avatars (TeamSpeak 6) + +Voice servers show the account's avatar (and the blurred banner behind it +in the client-info view) from what the client sends once connected, not +from `clientinit` (the official 6.0.0-beta4.1 client never sets +`client_myteamspeak_avatar` or `client_signed_badges` itself): + + updatemytsdata myts_certificate= [myts_signed_badge=] [myts_avatar=] + +built at 0x1f38520: `myts_certificate` is `LoginSession.mytsid_user_cert.cert`, +`myts_avatar` the serialized `LoginSession.user_avatar` (`AvatarData` with its +timestamp and myTeamSpeak's signature, which covers `AvatarInfo`, the myTS +id and the timestamp), `myts_signed_badge` a `UserBadgesSignedList` from +`getSignedBadges`. The values are the raw bytes with TeamSpeak's escaping +only (`\a` and `\b` included), no base64. It is sent once the connection is +established, after a sign-in (after `updatemytsid`), after an avatar upload +and after a badge change. Voelin sends the certificate and the avatar: both +come only from a password sign-in (`LoginSession`, fields 10 and 11), the +avatar sliced out of the response as it came (encoding it again would drop +fields this version does not know and break the signature). They are kept +in `/account/presentation.json` (public data) and sent to every +connection that presents the account; a refusal is only logged. + +Other clients' avatars arrive as `client_myteamspeak_avatar`, plain text +`,;,…` with myTeamSpeak's `AvatarState` numbers +(`request_avatar_with_ts_server_client_property`, 0x1ae2840): an entry +that is not `,` (an empty one from a trailing `;` too) spoils +the whole value; the online picture is shown, else away, do not disturb, +offline; the server's own avatar (`client_flag_avatar`) wins when it loads. +Voelin downloads it (HTTPS, 4 MiB) where the server's is not shown: none +set, no voice connection (observing), or its download gave up. + +`client_user_tag` (the "User Tag", a TeamSpeak chat alias) is set by the +client as JSON `{"myts_token":…,"tag":…,"updated":}` with a token from +`requestSignedAllowedIdentifierList` at `/tschat`; receivers show it only +after verifying the token. Voelin does not set it yet. + `requestAvatarSignedUrl` is not a download call: it signs *upload* links. In the TS6 6.0.0-beta4.1 Linux client, `Account_Manager_Impl:: request_avatar_signed_urls`'s reply goes only to `upload_avatar`, whose From 7d0e0affa547184fdfff463c4c2a54b0b6c4d119 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 22:05:12 +0000 Subject: [PATCH 05/42] banners: tell why one is missing, accept more, bigger defaults Failures are in the log with the host and the reason, never the whole address: HTTP status, the whole chain of causes (TLS, DNS, timeouts), what came instead of a picture (an HTML page, AVIF); banner addresses that cannot be fetched at all once; avatars and icons in the server's files when they give up (a closed file transfer port shows here). More is shown: BMP and ICO, SVG after a comment or a DOCTYPE, addresses with blanks around them; pictures larger than 4096 px are scaled down instead of refused (only above 512 MiB of pixels). Banners keep being tried while shown (after 1, 4, 16, 60, 300, 900 s, then every 15 min). Defaults: connect 20 s, read 60 s, slow start 120 s, 16 downloads at once, 20 redirects, pictures up to 128 MiB at 8 KiB/s at least, file transfer negotiation 30 s and a minute plus size, cache.max_mb 1024, ui.image_cache_mb 256. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- crates/voelin-core/src/book.rs | 9 +- crates/voelin-core/src/cache.rs | 7 +- crates/voelin-core/src/session.rs | 92 +++++++++++++++++---- crates/voelin-core/src/settings.rs | 4 +- crates/voelin-core/src/voice.rs | 24 +++--- crates/voelin-core/src/web.rs | 127 +++++++++++++++++++++++++---- crates/voelin-ui/Cargo.toml | 2 +- crates/voelin-ui/src/images.rs | 98 +++++++++++++++------- crates/voelin-ui/src/settings.rs | 4 +- 9 files changed, 282 insertions(+), 85 deletions(-) diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs index ba94a82..688bd4e 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/book.rs @@ -46,7 +46,7 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails { tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit, }, banner_url: server.hostbanner_url.clone(), - banner_gfx_url: server.hostbanner_gfx_url.clone(), + banner_gfx_url: server.hostbanner_gfx_url.trim().to_owned(), banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64, banner_mode: match server.hostbanner_mode { tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust, @@ -115,7 +115,12 @@ pub(crate) fn presence_from_book( needed_talk_power: c.needed_talk_power.unwrap_or(0), is_default: c.is_default.unwrap_or(false), icon: c.icon.map_or(0, |i| i.0), - banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()), + banner_gfx_url: c + .banner_gfx_url + .as_deref() + .map(str::trim) + .filter(|u| !u.is_empty()) + .map(str::to_owned), // A number the book keeps as text. banner_mode: c .banner_mode diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index adab3fd..cf52e4f 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -80,16 +80,17 @@ pub(crate) fn icon_key(id: u32) -> String { /// The largest picture downloaded into the cache, from the web or from the /// server's files: animated banners of several megabytes are common. The /// download goes to disk as it arrives, so this bounds the disk, not memory. -pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20; +pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20; /// The slowest a picture may arrive on average after its first seconds: /// a large banner on a slow link still arrives, one trickling in forever /// does not hold a download slot. -pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10; +pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10; /// The cache key of a picture on the web: only `http` and `https` -/// addresses. +/// addresses (blanks around one are not part of it). pub(crate) fn picture_key(url: &str) -> Option { + let url = url.trim(); let (scheme, rest) = url.split_once("://")?; let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"); (web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url))) diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index b7ad265..aeae41f 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -15,7 +15,7 @@ use std::time::Duration; use tokio::time::Instant; use tokio::sync::{broadcast, mpsc, watch}; -use tracing::{debug, warn}; +use tracing::{debug, info, warn}; use tsclientlib::ClientId; use voelin_audio::AudioSettings; use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature}; @@ -167,13 +167,54 @@ impl Drop for ImageDownload { } } -/// At most three retries (after 1, 4 and 16 seconds) per image version. -/// Keeping exhausted entries prevents presence traffic from causing a retry storm. +/// Retries per image version ([`retry_delay`]). Keeping exhausted entries +/// prevents presence traffic from causing a retry storm. struct ImageRetry { failures: u8, due: Option, } +/// When to try an image again after its `failures`-th failed download: +/// a banner after 1, 4, 16, 60, 300 and 900 seconds, then every 15 minutes +/// while it is shown (its host may be away for a while); avatars and icons +/// after 1, 4 and 16 seconds, then no more. +fn retry_delay(request: &ImageRequest, failures: u8) -> Option { + const BANNERS: [u64; 6] = [1, 4, 16, 60, 300, 900]; + let failures = usize::from(failures.max(1)); + match request { + ImageRequest::Picture(_) => Some(Duration::from_secs(BANNERS[(failures - 1).min(5)])), + _ if failures <= 3 => Some(Duration::from_secs(1 << (2 * (failures - 1)))), + _ => None, + } +} + +/// A failed image download in the log, with what it was and why (the +/// host, never the whole address): banners at once, avatars and icons in +/// the server's files when they give up (their files unreachable, a +/// closed file transfer port). +fn log_image_failure( + request: &ImageRequest, + failures: u8, + retry_in: Option, + error: &str, +) { + let retry_in_s = retry_in.map(|d| d.as_secs()); + match request { + ImageRequest::Picture(url) if failures <= 6 => { + let host = web::host_of(url); + info!(%host, failures, ?retry_in_s, %error, "banner not downloaded"); + } + ImageRequest::MytsAvatar { url, .. } if retry_in.is_none() => { + let host = web::host_of(url); + info!(%host, %error, "myTeamSpeak avatar not downloaded"); + } + ImageRequest::Avatar { .. } | ImageRequest::Icon(_) if retry_in.is_none() => { + info!(?request, %error, "server file not downloaded (avatar or icon)"); + } + _ => debug!(?request, failures, ?retry_in_s, %error, "image download failed"), + } +} + /// Whether an explicitly requested image belongs to the voice connection /// (downloaded over it, so dropped with it); a myTeamSpeak avatar is on the /// web. @@ -250,6 +291,9 @@ struct Session { icons: HashSet, /// Pictures on the web (banners) reported or being fetched, by address. pictures: HashSet, + /// Banner addresses that cannot be fetched at all (another scheme), + /// logged once. + unfetchable: HashSet, image_epoch: u64, images_enabled: bool, image_retries: HashMap, @@ -289,6 +333,7 @@ impl Session { server_avatars_failed: HashSet::new(), icons: HashSet::new(), pictures: HashSet::new(), + unfetchable: HashSet::new(), image_epoch: 0, images_enabled: settings.current().get(&CACHE_FETCH_IMAGES), image_retries: HashMap::new(), @@ -866,6 +911,7 @@ impl Session { self.server_avatars_failed.clear(); self.icons.clear(); self.pictures.clear(); + self.unfetchable.clear(); self.contact_audio.clear(); self.stream_friends.clear(); self.details = None; @@ -1030,22 +1076,18 @@ impl Session { }); } Err(error) => { - debug!(?request, %error, "image download failed"); let avatar_of = match &request { ImageRequest::Avatar { uid, .. } => Some(uid.clone()), _ => None, }; let retry = self .image_retries - .entry(request) + .entry(request.clone()) .or_insert(ImageRetry { failures: 0, due: None }); retry.failures = retry.failures.saturating_add(1); - retry.due = match retry.failures { - 1..=3 => { - Some(Instant::now() + Duration::from_secs(1 << (2 * (retry.failures - 1)))) - } - _ => None, - }; + let delay = retry_delay(&request, retry.failures); + retry.due = delay.map(|delay| Instant::now() + delay); + log_image_failure(&request, retry.failures, delay, &error); // The server's avatar gave up (its files unreachable): the // myTeamSpeak one, if the client has one. if let (None, Some(uid)) = (retry.due, avatar_of) @@ -1148,11 +1190,18 @@ impl Session { if !enabled { return; } - let urls: HashSet<_> = std::iter::once(&p.server.banner_gfx_url) + let all = std::iter::once(&p.server.banner_gfx_url) .chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref())) - .filter(|u| self.can_fetch_picture(u)) - .cloned() - .collect(); + .filter(|u| !u.is_empty()); + let mut urls = HashSet::new(); + for url in all { + if self.can_fetch_picture(url) { + urls.insert(url.clone()); + } else if files::server_image(url).is_none() && self.unfetchable.insert(url.clone()) { + let scheme = url.split(':').next().unwrap_or_default(); + info!(%scheme, "banner not downloaded: only http, https and ts3image addresses"); + } + } self.pictures.retain(|url| urls.contains(url)); for url in &urls { if self.pictures.insert(url.clone()) { @@ -2249,6 +2298,16 @@ mod banner_tests { let _ = std::fs::remove_dir_all(cache.dir()); } + #[test] + fn banners_keep_trying_avatars_and_icons_give_up() { + let banner = ImageRequest::Picture("https://example.com/b.png".into()); + let delays: Vec<_> = (1..=8).map(|f| retry_delay(&banner, f).unwrap().as_secs()).collect(); + assert_eq!(delays, [1, 4, 16, 60, 300, 900, 900, 900]); + let icon = ImageRequest::Icon(1234); + let delays: Vec<_> = (1..=4).map(|f| retry_delay(&icon, f).map(|d| d.as_secs())).collect(); + assert_eq!(delays, [Some(1), Some(4), Some(16), None]); + } + #[tokio::test] async fn retries_are_bounded_and_obey_policy_presence_and_epoch() { let (mut session, mut events) = session("retry-guards"); @@ -2264,7 +2323,8 @@ mod banner_tests { ); let retry = &session.image_retries[&request]; assert_eq!(retry.failures, failure); - assert_eq!(retry.due.is_some(), failure <= 3); + // A banner is tried again while it is shown. + assert!(retry.due.is_some()); } assert!(events.try_recv().is_err()); // Disabling fetch invalidates pending retries and completions. diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 4b42fb1..0c1fa29 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1121,8 +1121,8 @@ pub static CHAT_RETENTION_DAYS: Key = Key::new( pub static CACHE_MAX_MB: Key = Key::new( "cache.max_mb", Kind::UInt { min: 0 }, - "Size of the avatar and icon cache in MiB (0: no limit).", - || 256, + "Size of the picture cache (avatars, icons, banners) in MiB (0: no limit).", + || 1024, ); /// Download the avatars, icons and banners of servers we are on. diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index d435570..ff64847 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -295,17 +295,21 @@ impl Job { } } -/// How long a picture of `size` bytes may take to arrive: half a minute, -/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on -/// slow links while a stalled transfer still ends. +/// How long a picture of `size` bytes may take to arrive: a minute, plus +/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow +/// links while a stalled transfer still ends. fn image_download_time(size: u64) -> Duration { - Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE) + Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE) } +/// How long the server may take to start an image transfer (a busy server +/// answers the requests of a large channel tree in turn). +const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30); + /// Bound background image handshakes without imposing a deadline on user transfers. fn expire_image_jobs(jobs: &mut HashMap, now: Instant) { jobs.retain(|_, job| { - if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= Duration::from_secs(15)) { + if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) { job.report()(TransferState::Failed("image transfer negotiation timed out".into())); false } else { @@ -1136,10 +1140,10 @@ mod image_download_tests { }, ); } - expire_image_jobs(&mut jobs, started + Duration::from_secs(14)); + expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1)); assert_eq!(jobs.len(), 2); assert!(reports.lock().unwrap().is_empty()); - expire_image_jobs(&mut jobs, started + Duration::from_secs(15)); + expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION); assert_eq!(jobs.len(), 1); assert!(jobs.contains_key(&FiletransferHandle(2))); assert!( @@ -1151,10 +1155,10 @@ mod image_download_tests { #[test] fn large_pictures_get_time_to_arrive() { - assert_eq!(image_download_time(0), Duration::from_secs(30)); - assert_eq!(image_download_time(100 << 10), Duration::from_secs(33)); + assert_eq!(image_download_time(0), Duration::from_secs(60)); + assert_eq!(image_download_time(100 << 10), Duration::from_secs(72)); // The largest picture, at the slowest rate allowed. - assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048)); + assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384)); } } diff --git a/crates/voelin-core/src/web.rs b/crates/voelin-core/src/web.rs index 5373a4f..aa18510 100644 --- a/crates/voelin-core/src/web.rs +++ b/crates/voelin-core/src/web.rs @@ -25,18 +25,22 @@ use tokio::io::AsyncWriteExt; use crate::cache::{self, Cache, Fetch, Waiter}; -const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -const READ_TIMEOUT: Duration = Duration::from_secs(20); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); +const READ_TIMEOUT: Duration = Duration::from_secs(60); /// How long a download may start slowly before its rate counts. -const GRACE: Duration = Duration::from_secs(30); -/// The first bytes, enough to tell a picture from an error page. -const SNIFF: usize = 1024; +const GRACE: Duration = Duration::from_secs(120); +/// The first bytes, enough to tell a picture from an error page (SVG with +/// a comment or a DOCTYPE before it too). +const SNIFF: usize = 4096; /// The pictures the UI decodes, so a host choosing between formats /// (`Accept`) does not answer with one it cannot show (AVIF, JPEG XL). -const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml;q=0.9,*/*;q=0.1"; +const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml,image/bmp,\ + image/x-icon;q=0.9,*/*;q=0.1"; /// Fetch independent URLs in parallel without letting a large channel tree /// open unbounded connections or buffer unbounded image data. -static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(8); +static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(16); +/// Redirects followed, as many as a browser does. +const REDIRECTS: usize = 20; /// The host banner is reloaded at most this often, whatever the server /// asks (TeamSpeak 3 and 6 servers refuse intervals below a minute). pub(crate) const MIN_RELOAD: Duration = Duration::from_secs(60); @@ -45,6 +49,7 @@ static CLIENT: LazyLock> = LazyLock::new(|| { reqwest::Client::builder() .connect_timeout(CONNECT_TIMEOUT) .read_timeout(READ_TIMEOUT) + .redirect(reqwest::redirect::Policy::limited(REDIRECTS)) .user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION"))) .build() .map_err(|e| e.to_string()) @@ -79,7 +84,7 @@ fn fetch_within( let url = url.to_owned(); tokio::spawn(async move { let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open"); - let result = download(&url, &temp, limits).await; + let result = download(url.trim(), &temp, limits).await; cache.finish(&key, &temp, result, max_cache_bytes); }); } @@ -108,7 +113,7 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { .send() .await .and_then(reqwest::Response::error_for_status) - .map_err(|e| e.to_string())?; + .map_err(describe)?; if response.content_length().is_some_and(|n| n > limits.max_bytes) { return Err(too_big()); } @@ -119,7 +124,7 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { let started = tokio::time::Instant::now(); let mut head = Vec::with_capacity(SNIFF); let mut received = 0u64; - while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? { + while let Some(chunk) = response.chunk().await.map_err(describe)? { received += chunk.len() as u64; if received > limits.max_bytes { return Err(too_big()); @@ -128,7 +133,7 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { head.extend_from_slice(&chunk[..chunk.len().min(SNIFF - head.len())]); // An error page is refused without waiting for all of it. if head.len() == SNIFF && !is_picture(&head) { - return Err("not a picture".into()); + return Err(not_a_picture(&head)); } } let elapsed = started.elapsed(); @@ -141,20 +146,92 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { file.flush().await.map_err(|e| e.to_string())?; drop(file); if !is_picture(&head) { - return Err("not a picture".into()); + return Err(not_a_picture(&head)); } Ok(()) } +/// What went wrong, for the log: the status, or the whole chain of causes +/// (a TLS, DNS or timeout reason); never the address, whose query may be +/// a signed link's secret. +fn describe(error: reqwest::Error) -> String { + if let Some(status) = error.status() { + return format!("HTTP {status}"); + } + let error = error.without_url(); + let mut text = if error.is_timeout() { + "timed out".to_owned() + } else if error.is_connect() { + "could not connect".to_owned() + } else if error.is_redirect() { + "too many redirects".to_owned() + } else { + error.to_string() + }; + let mut source = std::error::Error::source(&error); + while let Some(cause) = source { + text.push_str(": "); + text.push_str(&cause.to_string()); + source = cause.source(); + } + text +} + +/// What arrived instead of a picture, for the log. +fn not_a_picture(head: &[u8]) -> String { + let start = head.trim_ascii_start(); + let lower = + start.get(..15.min(start.len())).map(<[u8]>::to_ascii_lowercase).unwrap_or_default(); + let what = if lower.starts_with(b"= 12 && &head[4..8] == b"ftyp" { + "AVIF or HEIF, which cannot be shown" + } else if start.starts_with(b"{") { + "JSON" + } else { + "something else" + }; + format!("not a picture ({what})") +} + +/// The host of `url`, for the log; the scheme for one without (a server +/// file, `ts3image://`). +pub(crate) fn host_of(url: &str) -> String { + match reqwest::Url::parse(url.trim()) { + Ok(u) if matches!(u.scheme(), "http" | "https") => u.host_str().unwrap_or("?").to_owned(), + Ok(u) => u.scheme().to_owned(), + Err(_) => "?".to_owned(), + } +} + /// Whether `data` is a picture the UI decodes, told by its content as the -/// UI tells it (SVG by its start, without leading blanks). +/// UI tells it (SVG by its start, without leading blanks, or after a +/// comment or a DOCTYPE). fn is_picture(data: &[u8]) -> bool { - const STARTS: [&[u8]; 4] = [b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a"]; - let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start(); + const STARTS: [&[u8]; 7] = [ + b"\x89PNG\r\n\x1a\n", + b"\xff\xd8\xff", + b"GIF87a", + b"GIF89a", + b"BM", + // ICO and CUR. + b"\0\0\x01\0", + b"\0\0\x02\0", + ]; STARTS.iter().any(|s| data.starts_with(s)) - || xml.starts_with(b"= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP") + || is_svg(data) +} + +/// Whether `data` starts an SVG document: after a BOM and blanks, with +/// ` bool { + let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start(); + let prolog = xml.starts_with(b"\n")); + assert!(is_picture(b"")); + assert!(!is_picture(b"")); + // What came instead is told. + assert_eq!(not_a_picture(b""), "not a picture (an HTML page)"); + assert_eq!( + not_a_picture(b"\0\0\0\x1cftypavif"), + "not a picture (AVIF or HEIF, which cannot be shown)" + ); + assert_eq!(host_of(" https://cdn.example.test/b.png?sig=x "), "cdn.example.test"); + assert_eq!(host_of("ts3image://banner.png?channel=1"), "ts3image"); } } diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index 10427a8..02e234f 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -23,7 +23,7 @@ dirs = "6" # Slint decodes pictures with `image`, which it builds with PNG and JPEG only; # avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the # decoders are in the tree already, for SVG pictures). -image = { version = "0.25", default-features = false, features = ["gif", "webp"] } +image = { version = "0.25", default-features = false, features = ["gif", "webp", "bmp", "ico"] } # Twemoji archive blocks (raw deflate); already used by png. miniz_oxide = "0.8" png = "0.18" diff --git a/crates/voelin-ui/src/images.rs b/crates/voelin-ui/src/images.rs index 3ad9915..ee7f90e 100644 --- a/crates/voelin-ui/src/images.rs +++ b/crates/voelin-ui/src/images.rs @@ -93,7 +93,7 @@ fn svg_cost(svg_len: usize) -> usize { } thread_local! { - static CACHE: RefCell> = RefCell::new(Lru::new(64 << 20)); + static CACHE: RefCell> = RefCell::new(Lru::new(256 << 20)); } /// Set the budget in megabytes. @@ -138,35 +138,59 @@ pub fn forget(path: &std::path::Path) { CACHE.with(|c| c.borrow_mut().remove(&path.to_string_lossy())); } +/// The largest side a raster picture keeps: larger ones (a banner made for +/// print) are scaled down when decoded, as nothing shows them larger. +const MAX_SIDE: u32 = 4096; +/// A picture with more pixels than this (RGBA bytes) is not decoded at all. +const MAX_DECODED_BYTES: u64 = 512 << 20; + /// Compressed pictures can be small on disk but huge when decoded. Check /// raster dimensions before Slint allocates pixels on the UI thread. SVGs /// keep Slint's native vector loader and are rasterized at the displayed size. fn decode(bytes: &[u8]) -> Option<(Image, usize)> { let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes); let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; - let cost = if reader.format().is_some() { - let (width, height) = reader.into_dimensions().ok()?; - // At most the default decoded-image cache (64 MiB of RGBA). - if width == 0 - || height == 0 - || width > 16_384 - || height > 16_384 - || u64::from(width) * u64::from(height) * 4 > 64 << 20 - { - tracing::debug!(width, height, "image exceeds the decoded raster size limit"); - return None; - } - width as usize * height as usize * 4 - } else { + if reader.format().is_none() { let start = bytes.trim_ascii_start(); - if !start.starts_with(b" MAX_DECODED_BYTES { + tracing::warn!(width, height, "picture not shown: too large to decode"); + return None; + } + if width <= MAX_SIDE && height <= MAX_SIDE { + let cost = width as usize * height as usize * 4; + return Image::load_from_data(bytes, None).ok().map(|image| (image, cost)); + } + // Scaled down (the first frame of an animation). + let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_DECODED_BYTES + (64 << 20)); + reader.limits(limits); + let small = reader.decode().ok()?.thumbnail(MAX_SIDE, MAX_SIDE).to_rgba8(); + let (width, height) = small.dimensions(); + let pixels = slint::SharedPixelBuffer::::clone_from_slice( + small.as_raw(), + width, + height, + ); + Some((Image::from_rgba8(pixels), width as usize * height as usize * 4)) +} + +/// Whether `start` (without a BOM and leading blanks) is an SVG document: +/// ` bool { + let prolog = start.starts_with(b""; + assert_eq!(picture("test:svg-prolog", svg).size().width, 8); + assert!(decode(b"").is_none()); + } + + #[test] + fn rasters_beyond_the_pixel_cap_are_refused_before_pixels_are_read() { + // Only the header: its size is all that is read. + let mut bytes = Vec::new(); + let mut encoder = png::Encoder::new(&mut bytes, 20_000, 20_000); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + std::mem::forget(encoder.write_header().unwrap()); + assert!(decode(&bytes).is_none()); + } + + #[test] + fn large_rasters_are_scaled_down() { use std::io::Write; for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] { let mut bytes = Vec::new(); @@ -279,19 +321,13 @@ mod tests { } stream.finish().unwrap(); writer.finish().unwrap(); - // A valid solid picture fits the download cap but not the - // decoded budget. Generate it a row at a time, without ever - // allocating the large pixel buffer this test guards against. + // Generated a row at a time. assert!(bytes.len() < 4 << 20); - assert_eq!( - image::ImageReader::new(Cursor::new(&bytes)) - .with_guessed_format() - .unwrap() - .into_dimensions() - .unwrap(), - (width, height) - ); - assert!(decode(&bytes).is_none()); + let (image, cost) = decode(&bytes).unwrap(); + let size = image.size(); + assert!(size.width <= MAX_SIDE && size.height <= MAX_SIDE, "{size:?}"); + assert_eq!(size.width.max(size.height), MAX_SIDE); + assert_eq!(cost, size.width as usize * size.height as usize * 4); } } diff --git a/crates/voelin-ui/src/settings.rs b/crates/voelin-ui/src/settings.rs index 595d8bb..2faf789 100644 --- a/crates/voelin-ui/src/settings.rs +++ b/crates/voelin-ui/src/settings.rs @@ -87,8 +87,8 @@ pub static UI_NARROW_BREAKPOINT: Key = Key::new( pub static UI_IMAGE_CACHE_MB: Key = Key::new( "ui.image_cache_mb", Kind::UInt { min: 0 }, - "Memory in MB for decoded images (avatars, icons, emoji); 0 keeps none.", - || 64, + "Memory in MB for decoded images (avatars, icons, banners, emoji); 0 keeps none.", + || 256, ); /// `ui.members_width`: how wide the members and streams panel is, in From 4886d90e86e82bdf235f6c8a6f0e25a37331a314 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 22:36:29 +0000 Subject: [PATCH 06/42] images: the decoded-image budget's test follows the new default (256 MB) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- crates/voelin-ui/src/images.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/voelin-ui/src/images.rs b/crates/voelin-ui/src/images.rs index ee7f90e..7d87fce 100644 --- a/crates/voelin-ui/src/images.rs +++ b/crates/voelin-ui/src/images.rs @@ -392,6 +392,6 @@ mod tests { let image = emoji("1f600"); assert!(image.size().width > 0); assert_eq!(emoji("nope").size().width, 0); - assert!(usage_text().contains("of 64 MB")); + assert!(usage_text().contains("of 256 MB")); } } From 90b033536f18f051fdd781190474f58b39fc76c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 23:09:23 +0000 Subject: [PATCH 07/42] review: fix what the review of the gateway, avatar and banner changes found - voelinctl observes with the new gateway list and checks avatar hashes only when they are MD5s (a myTeamSpeak avatar's hash is its link). - Gateway discovery keeps to the most specific name that publishes a record; another server's gateway is no fallback. The admin guide says so. - The observer's resync keeps the avatars clientlist does not tell (they come with the enter and update notifications). - A server avatar given up on counts for that picture only: a new one is tried again, and one that arrives after all is shown again. - updatemytsdata goes again after tsclientlib reconnects (the server forgets it), and once, not twice, when signing in. - SVG is told by its prolog: a page with an svg in it (HTML, XHTML) is a page, refused and logged as one; the UI tells it the same way. - Cursors (CUR) are no longer taken for pictures; MP4 and MOV are named videos, not AVIF. - The UI decodes at most 128 MiB of pixels on its thread, drops the full picture before copying the small one, logs what it cannot decode, and remembers pictures it cannot show instead of decoding them on every refresh; a banner that reloads unchanged is not decoded again. - The early refusal of a long error page is tested again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- crates/voelin-core/src/discover.rs | 97 +++++++++++++-------- crates/voelin-core/src/lib.rs | 9 +- crates/voelin-core/src/session.rs | 42 ++++++--- crates/voelin-core/src/voice.rs | 80 ++++++++++++++--- crates/voelin-core/src/web.rs | 110 +++++++++++++++++++----- crates/voelin-observer/src/observer.rs | 54 +++++++++++- crates/voelin-ui/src/app.rs | 8 +- crates/voelin-ui/src/images.rs | 113 ++++++++++++++++++------- docs/gateway-admin.md | 19 +++-- tools/voelinctl/src/client.rs | 6 +- tools/voelinctl/src/engine.rs | 2 +- 11 files changed, 415 insertions(+), 125 deletions(-) diff --git a/crates/voelin-core/src/discover.rs b/crates/voelin-core/src/discover.rs index 5bc52de..35900ec 100644 --- a/crates/voelin-core/src/discover.rs +++ b/crates/voelin-core/src/discover.rs @@ -15,10 +15,12 @@ //! tried. That answer is plain HTTP, so it is asked only when nothing or a //! plain record is published: a TLS-only publication stays TLS-only. //! -//! Every gateway found is kept, best first (the most specific name, at a -//! name TLS before plain, by priority, then the gateway's own answer), and -//! tried in turn ([`crate::Command::ObserveGateway`]): a TLS proxy that -//! fails falls back to a published plain one. Discovery trusts DNS and the +//! The most specific name with a record wins: a parent domain's records +//! are another server's gateway when the host publishes its own. Every +//! gateway of that name is kept, best first (TLS before plain, by +//! priority, then the gateway's own answer at that name), and tried in turn +//! ([`crate::Command::ObserveGateway`]): a TLS proxy that fails falls back +//! to the plain gateway published next to it. Discovery trusts DNS and the //! network as TSDNS does; falling back from a published `_tsgws` to a //! published `_tsgw` is no weaker than publishing only `_tsgw`. What an //! admin publishes is in `docs/gateway-admin.md`. @@ -135,20 +137,26 @@ async fn gateways_with(address: &str, lookups: Lookups) -> Vec { if names.is_empty() { return Vec::new(); } - let mut urls = if host.parse::().is_err() && host.contains('.') { + let srv = if host.parse::().is_err() && host.contains('.') { from_srv(&names, &lookups).await } else { - Vec::new() + None }; // The gateway's own answer comes over plain HTTP: not for a server that - // publishes only TLS. - if urls.is_empty() || urls.iter().any(|url| url.starts_with("ws://")) { - for url in from_well_known(&names, &lookups).await { - if !urls.contains(&url) { + // publishes only TLS; at the name that publishes, or without records the + // most specific name that answers. + let mut urls = match srv { + None => from_well_known(&names, &lookups).await.into_iter().collect(), + Some((name, mut urls)) => { + if urls.iter().any(|url| url.starts_with("ws://")) + && let Some(url) = from_well_known(&[name], &lookups).await + && !urls.contains(&url) + { urls.push(url); } + urls } - } + }; urls.truncate(MAX_CANDIDATES); urls } @@ -181,17 +189,21 @@ fn names(host: &str) -> Vec<&str> { .collect() } -/// The URLs from SRV records, every name and service asked at once: the -/// most specific name first, at a name TLS first, by priority. -async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec { - let queries: Vec<(&str, String)> = names +/// The URLs from SRV records, every name and service asked at once: those +/// of the most specific name with a usable record (with that name), TLS +/// first, by priority. +async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<(&'a str, Vec)> { + let queries: Vec<(&str, &str, String)> = names .iter() .flat_map(|name| { - [("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))] + [ + (*name, "wss", format!("_tsgws._tcp.{name}.")), + (*name, "ws", format!("_tsgw._tcp.{name}.")), + ] }) .collect(); - let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await; - let found: Vec<_> = queries + let answers = join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))).await; + let mut found: Vec<_> = queries .iter() .zip(answers) .filter_map(|(query, mut records)| { @@ -201,9 +213,11 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec { (!records.is_empty()).then_some((query, records)) }) .collect(); - let paths = join_all(found.iter().map(|((_, owner), _)| path_at(lookups, owner))).await; + let name = found.first()?.0.0; + found.retain(|((n, ..), _)| *n == name); + let paths = join_all(found.iter().map(|((.., owner), _)| path_at(lookups, owner))).await; let mut urls = Vec::new(); - for (((scheme, _), records), path) in found.into_iter().zip(paths) { + for (((_, scheme, _), records), path) in found.into_iter().zip(paths) { for (_, target, port) in records { let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')); if !urls.contains(&url) { @@ -211,7 +225,7 @@ async fn from_srv(names: &[&str], lookups: &Lookups) -> Vec { } } } - urls + Some((name, urls)) } /// The path at a SRV record's name: `path=…` from its TXT records, `/v1` @@ -228,17 +242,11 @@ async fn path_at(lookups: &Lookups, owner: &str) -> String { path } -/// The URLs gateways give for themselves at `names`, all asked at once, -/// the most specific first. -async fn from_well_known(names: &[&str], lookups: &Lookups) -> Vec { +/// The URL a gateway gives for itself at one of `names`, all asked at +/// once; the most specific that answers wins. +async fn from_well_known(names: &[&str], lookups: &Lookups) -> Option { let answers = join_all(names.iter().map(|name| (lookups.probe)((*name).to_owned()))).await; - let mut urls: Vec = Vec::new(); - for url in answers.into_iter().flatten() { - if !urls.contains(&url) { - urls.push(url); - } - } - urls + answers.into_iter().flatten().next() } /// tsgw's answer at `http://:/.well-known/tsgw`. @@ -325,8 +333,10 @@ mod tests { assert!(gateways_with("example", lookups).await.is_empty()); } + /// All of the most specific name's gateways, TLS first, by priority; a + /// parent domain's only for a host without its own. #[tokio::test] - async fn every_record_in_order_most_specific_name_then_tls() { + async fn the_most_specific_name_wins_with_all_its_gateways() { let lookups = fake( &[ ("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443), @@ -342,7 +352,6 @@ mod tests { "wss://tls.example.test:8443/tsgw/v1", "wss://backup.example.test:443/tsgw/v1", "ws://plain.example.test:7788/v1", - "wss://domain.example.test:443/v1", ] ); assert_eq!( @@ -373,6 +382,28 @@ mod tests { ); } + /// A gateway at the domain fronts another server than one of its hosts + /// that publishes its own: never a fallback for it, nor the domain's own + /// answer. + #[tokio::test] + async fn another_servers_gateway_is_no_fallback() { + let lookups = answering( + fake( + &[ + ("_tsgws._tcp.ts1.example.test.", 0, "gw1.example.test.", 443), + ("_tsgw._tcp.ts1.example.test.", 0, "ts1.example.test.", 7788), + ("_tsgws._tcp.example.test.", 0, "gw-main.example.test.", 443), + ], + &[], + ), + &[("example.test", "ws://main.example.test:7788/v1")], + ); + assert_eq!( + gateways_with("ts1.example.test", lookups).await, + ["wss://gw1.example.test:443/v1", "ws://ts1.example.test:7788/v1"] + ); + } + #[tokio::test] async fn the_gateways_own_answer_comes_last() { let lookups = answering( diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index cc12950..4f7c0b8 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -96,6 +96,8 @@ use voelin_stream::{ EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo, }; pub use voice::VoiceOptions; +/// Banners are downloaded and shown by the same rule. +pub use web::is_svg; pub type SessionId = u64; @@ -646,9 +648,10 @@ pub enum Event { request: RequestId, result: Result<(), String>, }, - /// A client's avatar is in the cache: `path`, its MD5 `hash` - /// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears - /// with an avatar and when it changes. + /// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a + /// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address + /// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]). + /// Comes when the client appears with an avatar and when it changes. AvatarReady { session: SessionId, client_uid: String, diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index aeae41f..542d249 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -284,9 +284,10 @@ struct Session { /// myTeamSpeak avatars wanted per client unique id (their link), any /// presence: where the server's avatar is not shown. myts_avatars: HashMap, - /// Clients whose server avatar could not be downloaded (retries used - /// up): their myTeamSpeak avatar is shown instead. - server_avatars_failed: HashSet, + /// Server avatars that could not be downloaded (retries used up), per + /// client unique id (their hash): the client's myTeamSpeak avatar is + /// shown instead, until it sets another. + server_avatars_failed: HashMap, /// Icons reported or being fetched, voice only. icons: HashSet, /// Pictures on the web (banners) reported or being fetched, by address. @@ -330,7 +331,7 @@ impl Session { contacts_rx, avatars: HashMap::new(), myts_avatars: HashMap::new(), - server_avatars_failed: HashSet::new(), + server_avatars_failed: HashMap::new(), icons: HashSet::new(), pictures: HashSet::new(), unfetchable: HashSet::new(), @@ -748,7 +749,7 @@ impl Session { .as_ref() .and_then(|p| p.client_by_uid(&client_uid)) .and_then(|c| c.avatar.clone()) - .filter(|_| !self.server_avatars_failed.contains(&client_uid)); + .filter(|hash| self.server_avatars_failed.get(&client_uid) != Some(hash)); let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone()); if let Some(hash) = hash.filter(|_| self.voice.is_some()) { self.fetch_avatar(&client_uid, &hash, true); @@ -979,7 +980,7 @@ impl Session { let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue }; let server_avatar = c.avatar.is_some() && self.voice.is_some() - && !self.server_avatars_failed.contains(uid); + && self.server_avatars_failed.get(uid) != c.avatar.as_ref(); if server_avatar { continue; } @@ -1058,6 +1059,16 @@ impl Session { match result { Ok(path) => { self.image_retries.remove(&request); + // A server avatar given up on came after all (asked for + // again): it is shown again in place of the myTeamSpeak one. + if let ImageRequest::Avatar { uid, hash } = &request + && self.server_avatars_failed.get(uid) == Some(hash) + { + self.server_avatars_failed.remove(uid); + if let Some(presence) = self.voice_presence.clone() { + self.fetch_myts_avatars(&presence); + } + } if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) { return; } @@ -1077,7 +1088,7 @@ impl Session { } Err(error) => { let avatar_of = match &request { - ImageRequest::Avatar { uid, .. } => Some(uid.clone()), + ImageRequest::Avatar { uid, hash } => Some((uid.clone(), hash.clone())), _ => None, }; let retry = self @@ -1090,11 +1101,13 @@ impl Session { log_image_failure(&request, retry.failures, delay, &error); // The server's avatar gave up (its files unreachable): the // myTeamSpeak one, if the client has one. - if let (None, Some(uid)) = (retry.due, avatar_of) - && self.server_avatars_failed.insert(uid) - && let Some(presence) = self.voice_presence.clone() + if let (None, Some((uid, hash))) = (retry.due, avatar_of) + && self.server_avatars_failed.get(&uid) != Some(&hash) { - self.fetch_myts_avatars(&presence); + self.server_avatars_failed.insert(uid, hash); + if let Some(presence) = self.voice_presence.clone() { + self.fetch_myts_avatars(&presence); + } } } } @@ -1107,6 +1120,7 @@ impl Session { self.image_epoch += 1; self.avatars.clear(); self.myts_avatars.clear(); + self.server_avatars_failed.clear(); self.icons.clear(); self.pictures.clear(); self.image_retries.clear(); @@ -2464,6 +2478,12 @@ mod banner_tests { ); } assert_eq!(session.myts_avatars.get("B=").map(String::as_str), Some(b)); + // A new server avatar is tried again: the failure was that one's. + let presence = session.voice_presence.as_mut().unwrap(); + presence.clients.get_mut(&2).unwrap().avatar = + Some("fedcba9876543210fedcba9876543210".into()); + session.publish_presence(); + assert_eq!(session.myts_avatars.keys().collect::>(), ["A="]); std::fs::remove_dir_all(cache.dir()).unwrap(); } diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index ff64847..227ccde 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -349,6 +349,9 @@ struct Voice { pending: HashMap, jobs: HashMap, transfers: HashMap, + /// `updatemytsdata` is to be sent once connected again: a reconnect + /// (tsclientlib's own) leaves the server without it. + myts_data_due: bool, } async fn run_inner( @@ -443,12 +446,13 @@ async fn run_inner( pending: HashMap::new(), jobs: HashMap::new(), transfers: HashMap::new(), + myts_data_due: false, }; voice.publish_state()?; // The account's avatar, for everyone on the server (as the official // client, once connected). data.borrow_and_update(); - voice.send_myts_data(&identity, &data); + voice.send_myts_data(); let mut tick = tokio::time::interval(Duration::from_millis(250)); let result = loop { @@ -472,12 +476,14 @@ async fn run_inner( } Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")), } - // After the proof, what is shown of the account (a sign-in). - voice.send_myts_data(&identity, &data); + // After the proof, what is shown of the account (a sign-in): + // its change, if any, is in this one. + data.borrow_and_update(); + voice.send_myts_data(); } Input::MytsDataChanged => { data.borrow_and_update(); - voice.send_myts_data(&identity, &data); + voice.send_myts_data(); } Input::Item(None) => break Err(anyhow::anyhow!("connection closed")), Input::Item(Some(Err(e))) => break Err(e.into()), @@ -590,6 +596,10 @@ impl Voice { self.message(target, invoker, message); } } + // Connected again after a reconnect. + if self.myts_data_due { + self.send_myts_data(); + } self.publish_state()?; } StreamItem::Audio(packet) => { @@ -672,6 +682,7 @@ impl Voice { } StreamItem::DisconnectedTemporarily(reason) => { warn!(?reason, "voice connection interrupted, reconnecting"); + self.myts_data_due = true; } _ => {} } @@ -843,22 +854,22 @@ impl Voice { } /// Show the server the account's certificate and avatar - /// (`updatemytsdata`), when connected with the account. - fn send_myts_data( - &mut self, - identity: &watch::Receiver>>, - data: &watch::Receiver>>, - ) { - if identity.borrow().is_none() { + /// (`updatemytsdata`), when connected with the account; while + /// reconnecting, once connected again. + fn send_myts_data(&mut self) { + self.myts_data_due = false; + if self.link.myts_identity.borrow().is_none() { return; } - let Some(data) = data.borrow().clone().filter(|d| !d.certificate.is_empty()) else { + let data = self.link.myts_data.borrow().clone(); + let Some(data) = data.filter(|d| !d.certificate.is_empty()) else { return; }; match self.con.send_myts_data(&data) { Ok(handle) => { self.pending.insert(handle, Pending::MytsData); } + Err(tsclientlib::Error::NotConnected) => self.myts_data_due = true, Err(e) => warn!(error = %e, "the account's avatar was not sent"), } } @@ -1205,6 +1216,51 @@ mod account_tests { assert!(network > 0 && timers > 0 && audio > 0); } + /// A reconnect (tsclientlib's own) leaves the server without the + /// account's avatar: it goes again once connected, not before. + #[tokio::test] + async fn account_data_waits_for_the_connection() { + // A silent UDP peer: never connected. + let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + // Scalar one and the standard compressed Edwards base point. + let mut private = [0; 32]; + private[0] = 1; + let mut public = [0x66; 32]; + public[0] = 0x58; + let identity = + tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(); + let data = tsclientlib::MytsData { certificate: vec![1], avatar: Vec::new() }; + let (events, _) = broadcast::channel(8); + let link = VoiceLink { + session: 1, + events, + settings: SharedSettings::new(crate::settings::Settings::default()), + myts_identity: watch::channel(Some(Arc::new(identity))).1, + myts_data: watch::channel(Some(Arc::new(data))).1, + }; + let mut voice = Voice { + con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(), + link, + events: mpsc::unbounded_channel().0, + server_uid: String::new(), + talking: HashMap::new(), + pending: HashMap::new(), + jobs: HashMap::new(), + transfers: HashMap::new(), + myts_data_due: false, + }; + voice.send_myts_data(); + assert!(voice.myts_data_due && voice.pending.is_empty()); + voice.myts_data_due = false; + let reconnecting = tsclientlib::TemporaryDisconnectReason::Timeout("test"); + voice.item(StreamItem::DisconnectedTemporarily(reconnecting)).unwrap(); + assert!(voice.myts_data_due); + // Not connected yet: still due. + let _ = voice.item(StreamItem::BookEvents(Vec::new())); + assert!(voice.myts_data_due && voice.pending.is_empty()); + timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap(); + } + #[tokio::test] async fn shutdown_never_polls_a_connecting_connection() { let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); diff --git a/crates/voelin-core/src/web.rs b/crates/voelin-core/src/web.rs index aa18510..a44e04a 100644 --- a/crates/voelin-core/src/web.rs +++ b/crates/voelin-core/src/web.rs @@ -185,7 +185,12 @@ fn not_a_picture(head: &[u8]) -> String { let what = if lower.starts_with(b"= 12 && &head[4..8] == b"ftyp" { - "AVIF or HEIF, which cannot be shown" + // ISO media, told by its brand. + match &head[8..12] { + b"avif" | b"avis" | b"heic" | b"heix" | b"heim" | b"heis" | b"hevc" | b"hevx" + | b"mif1" | b"msf1" => "AVIF or HEIF, which cannot be shown", + _ => "a video (MP4, MOV), which cannot be shown", + } } else if start.starts_with(b"{") { "JSON" } else { @@ -205,33 +210,62 @@ pub(crate) fn host_of(url: &str) -> String { } /// Whether `data` is a picture the UI decodes, told by its content as the -/// UI tells it (SVG by its start, without leading blanks, or after a -/// comment or a DOCTYPE). +/// UI tells it (SVG by [`is_svg`]). fn is_picture(data: &[u8]) -> bool { - const STARTS: [&[u8]; 7] = [ + const STARTS: [&[u8]; 6] = [ b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"BM", - // ICO and CUR. + // ICO. b"\0\0\x01\0", - b"\0\0\x02\0", ]; STARTS.iter().any(|s| data.starts_with(s)) || (data.len() >= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP") || is_svg(data) } -/// Whether `data` starts an SVG document: after a BOM and blanks, with -/// ` bool { - let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start(); - let prolog = xml.starts_with(b"".as_slice()) + } else if rest.get(..9).is_some_and(|s| s.eq_ignore_ascii_case(b"' | b'[')); + } else if let Some(element) = rest.strip_prefix(b"<") { + return names_svg(element); + } else { + return false; + }; + let Some(at) = skipped.windows(end.len()).position(|w| w == end) else { + return false; + }; + rest = &skipped[at + end.len()..]; + } +} + +/// Whether the element named at the start of `tag` is `svg`, with a +/// namespace prefix or without. +fn names_svg(tag: &[u8]) -> bool { + let Some(len) = tag.iter().position(|b| b.is_ascii_whitespace() || matches!(b, b'>' | b'/')) + else { + return false; + }; + let name = &tag[..len]; + name == b"svg" || name.ends_with(b":svg") } #[cfg(test)] @@ -277,9 +311,11 @@ mod tests { "/big" => ("200 OK", true, [PNG, &[0; 4000]].concat()), "/big-unannounced" => ("200 OK", false, [PNG, &[0; 4000]].concat()), "/page" => ("200 OK", true, b"".to_vec()), - "/long-page" => { - ("200 OK", false, [b"", &[b' '; 4000][..]].concat()) - } + "/long-page" | "/endless-page" => ( + "200 OK", + false, + [b"".as_slice(), &vec![b' '; SNIFF]].concat(), + ), // A picture, then a byte every 100 ms. "/slow" => ("200 OK", true, [PNG, &[0; 20]].concat()), _ => ("404 Not Found", true, b"no".to_vec()), @@ -302,6 +338,12 @@ mod tests { return; } let _ = socket.write_all(&body).await; + // Never done: refused by its start or not at all. + if path == "/endless-page" { + while socket.write_all(b" ").await.is_ok() { + tokio::time::sleep(Duration::from_millis(100)).await; + } + } }); } }); @@ -332,9 +374,14 @@ mod tests { let e = download(&format!("{base}{path}"), &to, &limits).await.unwrap_err(); assert!(e.contains(error), "{path}: {e}"); } - // An error page longer than the first bytes looked at, unannounced. - let e = download(&format!("{base}/long-page"), &to, &LIMITS).await.unwrap_err(); - assert!(e.contains("not a picture"), "{e}"); + // An error page longer than the first bytes looked at, unannounced: + // refused by them, without waiting for the rest. + for path in ["/long-page", "/endless-page"] { + let url = format!("{base}{path}"); + let fetch = download(&url, &to, &LIMITS); + let e = tokio::time::timeout(Duration::from_secs(5), fetch).await.unwrap().unwrap_err(); + assert!(e.contains("not a picture (an HTML page)"), "{path}: {e}"); + } // Nothing listens there. let port = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port(); assert!(download(&format!("http://127.0.0.1:{port}/b"), &to, &limits).await.is_err()); @@ -476,12 +523,33 @@ mod tests { assert!(is_picture(b"\n")); assert!(is_picture(b"")); assert!(!is_picture(b"")); + assert!(is_picture(b"")); + assert!(is_picture( + b"" + )); + assert!(is_picture(b" ]>")); + // Pages with an SVG in them are pages. + assert!(!is_picture( + b"\">" + )); + assert!(!is_picture(b"")); + assert!(!is_picture(b"")); + assert!(!is_picture(b"")); + // Cut off before it tells. + assert!(!is_picture(b""; assert_eq!(picture("test:svg-prolog", svg).size().width, 8); assert!(decode(b"").is_none()); + // A page with an SVG in it is a page (told so by the engine). + assert!(decode(b"").is_none()); } #[test] @@ -308,7 +354,7 @@ mod tests { #[test] fn large_rasters_are_scaled_down() { use std::io::Write; - for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] { + for (width, height) in [(5000, 5000), (16_385, 1), (1, 16_385)] { let mut bytes = Vec::new(); let mut encoder = png::Encoder::new(&mut bytes, width, height); encoder.set_color(png::ColorType::Rgba); @@ -364,16 +410,23 @@ mod tests { std::fs::write(&path, bytes).unwrap(); assert_eq!(file(&path).size().width, width, "{name}"); } - // A file that changed is decoded again once forgotten. + // A file that arrives again unchanged is not decoded again. let path = dir.join("287478770"); + let decoded = || CACHE.with(|c| c.borrow().len()); + let before = decoded(); + std::fs::write(&path, &png).unwrap(); + reloaded(&path); + assert_eq!(decoded(), before, "kept"); + // One that changed is, once it arrived. let mut wider = Vec::new(); let mut encoder = png::Encoder::new(&mut wider, 5, 2); encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); encoder.write_header().unwrap().write_image_data(&[90; 40]).unwrap(); std::fs::write(&path, wider).unwrap(); - assert_eq!(file(&path).size().width, 3, "kept until forgotten"); - forget(&path); + assert_eq!(file(&path).size().width, 3, "kept until it arrived"); + reloaded(&path); + assert_eq!(decoded(), before - 1); assert_eq!(file(&path).size().width, 5); // A file that is no picture is remembered as such until forgotten, // not read again on every refresh. @@ -382,7 +435,7 @@ mod tests { assert_eq!(file(&junk).size().width, 0); std::fs::write(&junk, &png).unwrap(); assert_eq!(file(&junk).size().width, 0, "remembered"); - forget(&junk); + reloaded(&junk); assert_eq!(file(&junk).size().width, 3); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md index 3c2ffb8..cae6dc5 100644 --- a/docs/gateway-admin.md +++ b/docs/gateway-admin.md @@ -117,14 +117,17 @@ port, the service name says whether it speaks TLS: | `_tsgw._tcp. SRV ` | `ws://:/v1` (plain, e.g. tsgw itself on 7788) | | `_tsgws._tcp. TXT "path=/"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy | -The order: the most specific name first; at a name `_tsgws` before -`_tsgw`; among several records of one name the lowest priority first; -then tsgw's own answer (below), but only when a plain record or nothing is -published, so a server that publishes only TLS is never reached without -it. A TLS proxy that fails (no rule for the host, no certificate) thus -falls back to a published plain gateway. A target of `.` means "no gateway -here" and the search goes on at the parent domain. Examples (zone of -`example.org`): +Which gateways: those of the most specific name that publishes a record, +and only those (a parent domain's records are another server's gateway +when the host publishes its own). At that name `_tsgws` before `_tsgw`, +among several records of one kind the lowest priority first, then tsgw's +own answer at that name (below), but only when a plain record is published +there, so a server that publishes only TLS is never reached without it. A +TLS proxy that fails (no rule for the host, no certificate) thus falls +back to the plain gateway published next to it. With no record at any +name, tsgw's own answer at the most specific name that gives one. A target +of `.` means "no gateway here" and the search goes on at the parent +domain. Examples (zone of `example.org`): ```dns ; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw: diff --git a/tools/voelinctl/src/client.rs b/tools/voelinctl/src/client.rs index f58cb28..5a4990c 100644 --- a/tools/voelinctl/src/client.rs +++ b/tools/voelinctl/src/client.rs @@ -461,7 +461,11 @@ impl Runner<'_> { { let data = std::fs::read(&path)?; let actual = format!("{:x}", md5_of(&data)); - if actual != hash { + // A server avatar is named by its MD5; a myTeamSpeak + // avatar by its address. + let server_avatar = + hash.len() == 32 && hash.bytes().all(|b| b.is_ascii_hexdigit()); + if server_avatar && actual != hash { bail!("avatar file hash {actual} is not the announced {hash}"); } if let Some(md5) = md5 diff --git a/tools/voelinctl/src/engine.rs b/tools/voelinctl/src/engine.rs index 2ba88a5..df52c73 100644 --- a/tools/voelinctl/src/engine.rs +++ b/tools/voelinctl/src/engine.rs @@ -99,7 +99,7 @@ pub async fn run(args: GatewayArgs) -> Result<()> { } engine.send(Command::ObserveGateway { session: SESSION, - url: args.url.clone(), + urls: vec![args.url.clone()], identity: Box::new(identity.clone()), }); if let Some(addr) = &args.voice { From c529fd73fe3793c4b317d3250175653c1fff7b5d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 23:10:41 +0000 Subject: [PATCH 08/42] changelog: myTeamSpeak avatars both ways, gateway fallback, banners Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN --- CHANGELOG.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01b8111..2e122ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,15 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows decoders work without installing FFmpeg. - AV1 decoding through dav1d in every desktop build. - 122 more signed client versions (`Versions.csv`). +- Other users' myTeamSpeak avatars (TeamSpeak 6), as the official client + shows them: where the server has no avatar of them, its avatar could not + be downloaded, or the server is only observed. +- Voice connections show servers the account's avatar and badges, as the + official client does, so other TeamSpeak 6 users see them; again after + a reconnect. +- Every gateway a server publishes is tried in turn (TLS first, 20 seconds + each) before waiting to try again, so a TLS proxy that fails falls back to + the plain gateway published next to it. ### Changed @@ -48,6 +57,12 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - A server's published gateway replaces one stored before (found or typed into an older version), so a gateway that moved is followed. - zbus's warnings about desktop portal requests are left out of the logs. +- Banners: up to 128 MiB, more time on slow hosts, BMP and ICO too, and + SVG after a comment or DOCTYPE; pictures larger than 4096 pixels on a + side are scaled down. A banner that fails is tried again for as long as + it is shown (every 15 minutes at most), and the log says why it is + missing (HTTP status, an HTML page, a video, too large). The picture + cache defaults to 1 GiB, the decoded images to 256 MB. ### Fixed From 477040c0ec17605dd26ed226975a1e76b96ea312 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 00:01:23 +0000 Subject: [PATCH 09/42] ui: tooltips on icon buttons, and a count IconButton names itself in a tooltip after a moment of hover, also while it is disabled (mute or deafen when not connected), and can show a neutral count at its top right (for pins and topics later). Tooltips are desktop only: the new Bridge.desktop is false in the Android app. Tooltip showed once (its Timer turned off its own binding) and stayed open after the pointer left. Both now use Slint's Tooltip element with our TooltipBubble: it opens at the pointer, closes when the pointer leaves, and lets clicks and hover through, which a PopupWindow of our own does not while it is open. A press closes it until the pointer leaves. The bubble sets its own preferred width, up to 400px, so long text wraps: the tooltip's popup takes that width, and a max-width would not narrow it. IconButton's look moves onto an inner rectangle: with an opacity and an animation on its root, Slint inlined it at each of its 100-odd uses, and the tooltip and count alone added 3.3 MB of generated code to a crate whose compile already peaks near 14 GB. Now the generated code is 1.1 MB smaller than before (70.7 MB). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- CHANGELOG.md | 5 + crates/voelin-ui/src/app.rs | 1 + crates/voelin-ui/ui/bridge.slint | 3 + crates/voelin-ui/ui/components/badge.slint | 6 +- crates/voelin-ui/ui/components/button.slint | 119 +++++++++++------- crates/voelin-ui/ui/components/index.slint | 1 + crates/voelin-ui/ui/components/overlay.slint | 37 +----- crates/voelin-ui/ui/components/tooltip.slint | 70 +++++++++++ .../voelin-ui/ui/screens/studio-parts.slint | 1 - docs/ui.md | 15 ++- 10 files changed, 175 insertions(+), 83 deletions(-) create mode 100644 crates/voelin-ui/ui/components/tooltip.slint diff --git a/CHANGELOG.md b/CHANGELOG.md index 01b8111..bb0ea18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows decoders work without installing FFmpeg. - AV1 decoding through dav1d in every desktop build. - 122 more signed client versions (`Versions.csv`). +- Icon buttons show their name on hover (desktop), also while they are + disabled. ### Changed @@ -53,6 +55,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - The account's avatar is downloaded from its own link; it was asked for as an upload link and refused with HTTP 403. +- Hover help in the Stream Studio (a source's error, the status details) + shows each time and closes when the pointer leaves; it showed only once, + and stayed open until a click. ## [0.0.1-alpha] - 2026-10-04 diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index acd65e6..9eb45f6 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -643,6 +643,7 @@ pub fn run(options: RunOptions) -> Result<()> { let bridge = ui.global::(); bridge.set_app_name(voelin_platform::APP_NAME.into()); bridge.set_app_version(env!("CARGO_PKG_VERSION").into()); + bridge.set_desktop(cfg!(not(target_os = "android"))); let models = Models::new(&bridge); // Wayland and X11 find the desktop file (and icon) by this id. #[cfg(not(target_os = "android"))] diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index 71d2051..a6b144b 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -934,6 +934,9 @@ export global Bridge { // The product name (voelin_platform::APP_NAME, not translated) and version. in property app-name: "Voelin"; in property app-version; + // False in the Android app; the one platform flag (tooltips are desktop + // only). The studio's own window, desktop only, keeps the default. + in property desktop: true; in-out property client-audio; // Opt-in local crash reports, and a notice about reports on disk. in-out property crash-reports; diff --git a/crates/voelin-ui/ui/components/badge.slint b/crates/voelin-ui/ui/components/badge.slint index fa46017..b5e1a02 100644 --- a/crates/voelin-ui/ui/components/badge.slint +++ b/crates/voelin-ui/ui/components/badge.slint @@ -1,10 +1,12 @@ import { Theme } from "../theme.slint"; import { Icon } from "icon.slint"; -// A red count bubble (unread, requests). +// A count bubble (unread, requests), red unless `fill` says otherwise. export component CountBadge inherits Rectangle { in property count; in property fill: Theme.live; + // The number's colour. + in property ink: Theme.on-accent; width: max(18px, label.preferred-width + 10px); height: 18px; border-radius: 9px; @@ -16,7 +18,7 @@ export component CountBadge inherits Rectangle { padding-right: 5px; label := Text { text: root.count > 99 ? "99+" : root.count; - color: #ffffff; + color: root.ink; font-size: Theme.font-xs; font-weight: Theme.weight-bold; horizontal-alignment: center; diff --git a/crates/voelin-ui/ui/components/button.slint b/crates/voelin-ui/ui/components/button.slint index 493e66d..ee12c1f 100644 --- a/crates/voelin-ui/ui/components/button.slint +++ b/crates/voelin-ui/ui/components/button.slint @@ -1,5 +1,7 @@ import { Theme } from "../theme.slint"; import { Icon } from "icon.slint"; +import { CountBadge } from "badge.slint"; +import { HoverTooltip } from "tooltip.slint"; export enum ButtonKind { // Filled accent: the main action. @@ -117,11 +119,19 @@ export component Button inherits Rectangle { } } -// A square (or round) button with only an icon; `label` is for screen -// readers and the tooltip-less toolbar. +// A square (or round) button with only an icon. `label` names it for +// screen readers and, on the desktop, in a tooltip. +// +// The look is on `face`, not on the root: an opacity or an animation on a +// component's root makes Slint inline the component where it is used, and +// there are over a hundred IconButtons. Shared, their code stays small (and +// so does the compiler's memory). export component IconButton inherits Rectangle { in property icon; in property label; + // Shown when the pointer rests on the button (desktop only, also while + // disabled); "" for none. + in property tooltip: label; in property enabled: true; in property checked; in property round; @@ -135,63 +145,80 @@ export component IconButton inherits Rectangle { // A small dot at the top right (unread, live). in property dot; in property dot-color: Theme.live; + // A neutral count at the top right (pins, topics); hidden at 0 or less. + in property count; callback clicked(); width: size; height: size; - border-radius: round ? size / 2 : Theme.radius-md; - background: touch.pressed ? Theme.surface-4 - : checked ? (danger ? Theme.danger-soft : Theme.accent-soft) - : touch.has-hover ? Theme.surface-3 - : filled ? Theme.surface-2 : transparent; - border-width: filled || checked ? 1px : 0px; - border-color: checked ? (danger ? Theme.danger.transparentize(50%) : Theme.accent) : Theme.border; - opacity: enabled ? 1.0 : 0.45; - animate background { duration: Theme.fast; } accessible-role: AccessibleRole.button; accessible-label: label; accessible-enabled: enabled; accessible-action-default => { if enabled { clicked(); } } - FocusRing { - shown: focus.has-focus; - radius: root.border-radius; - w: root.width; - h: root.height; - } - focus := FocusScope { - enabled: root.enabled; - key-pressed(event) => { - if event.text == " " || event.text == "\n" { - root.clicked(); - return accept; - } - reject + face := Rectangle { + border-radius: root.round ? root.size / 2 : Theme.radius-md; + background: touch.pressed ? Theme.surface-4 + : root.checked ? (root.danger ? Theme.danger-soft : Theme.accent-soft) + : touch.has-hover ? Theme.surface-3 + : root.filled ? Theme.surface-2 : transparent; + border-width: root.filled || root.checked ? 1px : 0px; + border-color: root.checked ? (root.danger ? Theme.danger.transparentize(50%) : Theme.accent) : Theme.border; + opacity: root.enabled ? 1.0 : 0.45; + animate background { duration: Theme.fast; } + + FocusRing { + shown: focus.has-focus; + radius: face.border-radius; + w: root.width; + h: root.height; } - touch := TouchArea { + focus := FocusScope { enabled: root.enabled; - mouse-cursor: MouseCursor.pointer; - clicked => { - focus.focus(); - root.clicked(); + key-pressed(event) => { + if event.text == " " || event.text == "\n" { + root.clicked(); + return accept; + } + reject + } + touch := TouchArea { + enabled: root.enabled; + mouse-cursor: MouseCursor.pointer; + clicked => { + focus.focus(); + root.clicked(); + } } } - } - Icon { - source: icon; - size: icon-size; - tint: root.tint; - } - if dot: Rectangle { - x: parent.width - self.width - root.size * 0.18; - y: root.size * 0.16; - width: 9px; - height: 9px; - border-radius: 4.5px; - background: dot-color; - border-width: 2px; - border-color: Theme.surface; + Icon { + source: root.icon; + size: root.icon-size; + tint: root.tint; + } + if root.dot: Rectangle { + x: parent.width - self.width - root.size * 0.18; + y: root.size * 0.16; + width: 9px; + height: 9px; + border-radius: 4.5px; + background: root.dot-color; + border-width: 2px; + border-color: Theme.surface; + } + if root.count > 0: CountBadge { + x: parent.width - self.width + 4px; + y: -4px; + count: root.count; + fill: Theme.icon; + ink: Theme.surface; + } + HoverTooltip { + text: root.tooltip; + pressed: touch.pressed; + hovered: touch.has-hover; + } } } @@ -211,6 +238,8 @@ export component ActionButton inherits VerticalLayout { IconButton { icon: root.icon; label: root.text; + // The caption already names it. + tooltip: ""; checked: root.checked; danger: root.danger; enabled: root.enabled; diff --git a/crates/voelin-ui/ui/components/index.slint b/crates/voelin-ui/ui/components/index.slint index b67248d..f07d22a 100644 --- a/crates/voelin-ui/ui/components/index.slint +++ b/crates/voelin-ui/ui/components/index.slint @@ -15,6 +15,7 @@ export { SectionHeader, Card, Divider, Banner } from "card.slint"; export { Meter, SpeakingBars } from "meter.slint"; export { NavItem, ListItem } from "list-item.slint"; export { MenuEntry, PopupMenu, Tooltip, Modal, Toast, ResizeHandle } from "overlay.slint"; +export { TooltipBubble, HoverTooltip } from "tooltip.slint"; export { RichText, EmojiPicker } from "emoji.slint"; // Virtualised lists and scrolling come from the standard widgets (styled by // the fluent-dark style); ListView builds only the visible rows. diff --git a/crates/voelin-ui/ui/components/overlay.slint b/crates/voelin-ui/ui/components/overlay.slint index 8f62997..7fad49a 100644 --- a/crates/voelin-ui/ui/components/overlay.slint +++ b/crates/voelin-ui/ui/components/overlay.slint @@ -5,6 +5,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Icon } from "icon.slint"; import { IconButton } from "button.slint"; +import { HoverTooltip } from "tooltip.slint"; // An entry of a `PopupMenu`. export struct MenuEntry { @@ -102,39 +103,13 @@ export component PopupMenu inherits Rectangle { } } -// Hover help: wraps @children and shows `text` in a bubble after a moment. +// Hover help: wraps @children and shows `text` in a bubble near the +// pointer after a moment, until the pointer leaves (desktop only). export component Tooltip inherits Rectangle { in property text; - // Above (default) or below the element. - in property below; - area := TouchArea { - @children - } - Timer { - interval: 600ms; - running: area.has-hover && root.text != ""; - triggered => { - self.running = false; - bubble.show(); - } - } - bubble := PopupWindow { - x: (root.width - self.width) / 2; - y: root.below ? root.height + 6px : -self.height - 6px; - width: label.preferred-width + 20px; - height: label.preferred-height + 12px; - close-policy: PopupClosePolicy.close-on-click-outside; - Rectangle { - border-radius: Theme.radius-sm; - background: Theme.surface-4; - border-width: 1px; - border-color: Theme.border-strong; - label := Text { - text: root.text; - color: Theme.text; - font-size: Theme.font-sm; - } - } + @children + HoverTooltip { + text: root.text; } } diff --git a/crates/voelin-ui/ui/components/tooltip.slint b/crates/voelin-ui/ui/components/tooltip.slint new file mode 100644 index 0000000..c6e2484 --- /dev/null +++ b/crates/voelin-ui/ui/components/tooltip.slint @@ -0,0 +1,70 @@ +// Tooltips: the bubble, and the hover area that shows it on the desktop. +// Kept apart from overlay.slint, which imports button.slint, so buttons can +// use them. + +import { Theme } from "../theme.slint"; +import { Bridge } from "../bridge.slint"; + +// The bubble of a tooltip: short text on a raised surface. Longer text +// wraps at `widest`. +export component TooltipBubble inherits Rectangle { + in property text; + in property widest: 400px; + // The tooltip's popup takes this preferred width (a max-width would not + // narrow it), and the text wraps inside it. + preferred-width: min(root.widest, label.preferred-width + 2 * Theme.space-3); + // Slint's own tooltip frame (4px corners) lies under the bubble, so the + // corners match it. + border-radius: Theme.radius-xs; + background: Theme.surface-4; + border-width: 1px; + border-color: Theme.border-strong; + HorizontalLayout { + padding-left: Theme.space-3; + padding-right: Theme.space-3; + padding-top: Theme.space-2; + padding-bottom: Theme.space-2; + label := Text { + text: root.text; + color: Theme.text; + font-size: Theme.font-sm; + vertical-alignment: center; + wrap: word-wrap; + } + } +} + +// Put last in an element: it fills the element, and once the pointer rests +// on it for a moment, `text` shows in a bubble at the pointer until the +// pointer leaves. Desktop only (`Bridge.desktop`). +// +// It is Slint's `Tooltip`, whose bubble lets the pointer through: a +// PopupWindow of our own takes every click and move while it is open, so +// the element under it would lose the click and its hover. Being last, the +// hover area sees the pointer before the element's other children, also +// over a disabled button. Near the window's edges Slint moves the bubble +// inside. +export component HoverTooltip inherits Rectangle { + in property text; + // The element's own TouchArea, if it has one: a press closes the bubble + // until the pointer leaves. + in property pressed; + in property hovered; + property clicked; + changed pressed => { + if self.pressed { + self.clicked = true; + } + } + changed hovered => { + if !self.hovered { + self.clicked = false; + } + } + // Removing the area closes an open bubble. + if Bridge.desktop && !root.clicked && root.text != "": Tooltip { + TooltipBubble { + text: root.text; + } + } +} diff --git a/crates/voelin-ui/ui/screens/studio-parts.slint b/crates/voelin-ui/ui/screens/studio-parts.slint index e9fab2a..9798240 100644 --- a/crates/voelin-ui/ui/screens/studio-parts.slint +++ b/crates/voelin-ui/ui/screens/studio-parts.slint @@ -710,7 +710,6 @@ export component StudioHeader inherits HorizontalLayout { } Tooltip { text: StudioBridge.status.details; - below: true; width: 20px; height: 20px; Icon { diff --git a/docs/ui.md b/docs/ui.md index e7f307b..19699e1 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -84,13 +84,18 @@ The standard widgets (scroll bars, context menus) follow through All in `ui/components/`, exported by `components/index.slint`. +A component used in many places keeps `opacity`, `visible`, shadows and +animations off its root element: Slint inlines such a component at every +use, which grows the generated code and the compiler's memory (IconButton +puts them on an inner `face`). + | Component | File | Key properties | |---|---|---| | `Icon` | icon.slint | `source` (an `Icons.*`), `size`, `tint` | | `Spinner` | icon.slint | `size`, `tint`, `running` | | `Button` | button.slint | `text`, `icon`, `kind` (`ButtonKind.primary/secondary/danger/ghost`), `enabled`, `checked`, `small`; `clicked` | -| `IconButton` | button.slint | `icon`, `label` (screen readers), `checked`, `danger`, `round`, `filled`, `size`, `icon-size`, `tint`, `dot`; `clicked` | -| `ActionButton` | button.slint | round button with a caption (Mute, Deafen, Go Live): `icon`, `text`, `checked`, `danger` | +| `IconButton` | button.slint | `icon`, `label` (screen readers), `tooltip` (default `label`, "" for none; on hover, also while disabled, desktop only), `checked`, `danger`, `round`, `filled`, `size`, `icon-size`, `tint`, `dot`, `count` (a neutral number at the top right, hidden at 0 or less); `clicked` | +| `ActionButton` | button.slint | round button with a caption (Mute, Deafen, Go Live), no tooltip: `icon`, `text`, `checked`, `danger` | | `FocusRing` | button.slint | the accent ring of focused controls | | `TextField` | text-field.slint | `text`, `placeholder`, `input-type`, `icon`, `label`, `bare`, `read-only`; `accepted`, `edited`, `key-pressed`; `clear()`, `select-all()` | | `SearchBox` | text-field.slint | a TextField with a magnifier and the Ctrl K hint (`show-shortcut`) | @@ -104,7 +109,7 @@ All in `ui/components/`, exported by `components/index.slint`. | `SegmentedTabs` | tabs.slint | `model`, `current-index`, `label`; `selected(int)` | | `TabItem` | tabs.slint | underlined tab: `text`, `selected`, `badge`, `closable`; `clicked`, `close` | | `Avatar` | avatar.slint | `image` or `initials` + `tint`, `size`, `status` (`Status.online/idle/dnd/offline/info`), `speaking` (green ring), `crown`, `square` (server icons) | -| `CountBadge` | badge.slint | red count bubble: `count`, `fill` | +| `CountBadge` | badge.slint | count bubble: `count`, `fill` (red), `ink` (the number) | | `LiveBadge` | badge.slint | `text` (LIVE), `large` | | `Chip` | badge.slint | tag: `text`, `icon`, `tint`, `fill`, `outlined` | | `Dot` | badge.slint | a status dot | @@ -117,7 +122,9 @@ All in `ui/components/`, exported by `components/index.slint`. | `NavItem` | list-item.slint | navigation entry: `icon`, `text`, `subtitle`, `selected`, `badge`, `chevron`; `clicked` | | `ListItem` | list-item.slint | row with a leading slot (@children), `title`, `subtitle`, `trailing`, `selected` | | `PopupMenu` | overlay.slint | themed menu: `entries` ([MenuEntry]), `show(x, y)`; `activated(int)` | -| `Tooltip` | overlay.slint | wraps @children, shows `text` on hover | +| `Tooltip` | overlay.slint | wraps @children; `text` shows at the pointer after a moment, until it leaves (desktop only: `Bridge.desktop`) | +| `HoverTooltip` | tooltip.slint | the same, put last in an element (as IconButton does): `text`; `pressed` and `hovered` of the element's TouchArea (a press closes it until the pointer leaves) | +| `TooltipBubble` | tooltip.slint | a tooltip's bubble: `text`, wrapping at `widest` (400px) | | `Modal` | overlay.slint | dialog with backdrop: `title`, `subtitle`, `icon`, `card-width`, `card-height`; `dismissed` (backdrop, Escape, ×) | | `Toast` | overlay.slint | `text`, `icon`, `timeout`, `shown` | | `ResizeHandle` | overlay.slint | drag to resize a side panel: `size` (two-way), `minimum`, `maximum`, `left` | From 38bae1150c5f0f02a5e51d5eb656a4161ab29ad1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 06:36:32 +0000 Subject: [PATCH 10/42] ui: a clearer edge on pop-ups, and a light scrim behind them Pop-ups, menus and tooltips had the border-strong edge, which barely shows against the panels under them. They get a new border-popup token; the Select and Stream Studio drop-downs too, being the same kind of menu. The member card, the emoji picker and the bell's panel now dim the window behind them with a new scrim-light, lighter than the modals' scrim; a click on it still closes them. The toast moves above them, so that scrim does not dim it (a poke from the member card is confirmed there). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- CHANGELOG.md | 2 ++ crates/voelin-ui/ui/app.slint | 31 ++++++++++++------- crates/voelin-ui/ui/components/emoji.slint | 2 +- crates/voelin-ui/ui/components/overlay.slint | 2 +- crates/voelin-ui/ui/components/select.slint | 2 +- crates/voelin-ui/ui/components/tooltip.slint | 2 +- crates/voelin-ui/ui/screens/members.slint | 2 +- crates/voelin-ui/ui/screens/overlays.slint | 2 +- .../voelin-ui/ui/screens/studio-parts.slint | 2 +- crates/voelin-ui/ui/theme.slint | 5 +++ docs/ui.md | 4 +-- 11 files changed, 35 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb0ea18..705a80c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,8 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - A server's published gateway replaces one stored before (found or typed into an older version), so a gateway that moved is followed. - zbus's warnings about desktop portal requests are left out of the logs. +- Pop-ups, menus and tooltips have a clearer edge, and the member card, the + emoji picker and the notifications panel dim the window behind them. ### Fixed diff --git a/crates/voelin-ui/ui/app.slint b/crates/voelin-ui/ui/app.slint index 858d27b..4303cc1 100644 --- a/crates/voelin-ui/ui/app.slint +++ b/crates/voelin-ui/ui/app.slint @@ -287,19 +287,11 @@ export component MainWindow inherits Window { } } - toast := Toast { - x: (parent.width - self.width) / 2; - y: parent.height - self.height - (Nav.narrow ? 140px : 96px); - text: Bridge.status-text; - visible: self.shown && !Bridge.myts.prompt; - // A notice from the start (an imported identity) waits for the - // account prompt to close. - paused: Bridge.myts.prompt; - widest: min(560px, parent.width - 32px); - } - - // The member card of the members panel, over everything. + // The member card of the members panel, over everything. Like the emoji + // picker and the bell's panel below, it dims the window a little, and a + // click outside it closes it. if !Bridge.myts.prompt && (Bridge.member-card.open): Rectangle { + background: Theme.scrim-light; TouchArea { clicked => { Bridge.open-member(-1); } } @@ -310,6 +302,7 @@ export component MainWindow inherits Window { } if !Bridge.myts.prompt && (Nav.emoji-open): Rectangle { + background: Theme.scrim-light; // Clicks outside the picker close it. TouchArea { clicked => { Nav.emoji-open = false; } @@ -336,6 +329,7 @@ export component MainWindow inherits Window { // The bell's panel, under the bell (the phone: the whole width). if !Bridge.myts.prompt && (Nav.notifications-open): Rectangle { + background: Theme.scrim-light; TouchArea { clicked => { Nav.notifications-open = false; } } @@ -347,6 +341,19 @@ export component MainWindow inherits Window { } } + // Over the pop-ups, so their scrim does not dim it (a poke from the + // member card says so here); under the dialogs. + toast := Toast { + x: (parent.width - self.width) / 2; + y: parent.height - self.height - (Nav.narrow ? 140px : 96px); + text: Bridge.status-text; + visible: self.shown && !Bridge.myts.prompt; + // A notice from the start (an imported identity) waits for the + // account prompt to close. + paused: Bridge.myts.prompt; + widest: min(560px, parent.width - 32px); + } + if !Bridge.myts.prompt && (Nav.search-open): SearchPalette { } if !Bridge.myts.prompt && (Nav.lightbox-open): Lightbox { } diff --git a/crates/voelin-ui/ui/components/emoji.slint b/crates/voelin-ui/ui/components/emoji.slint index 39c3b30..7c54b8a 100644 --- a/crates/voelin-ui/ui/components/emoji.slint +++ b/crates/voelin-ui/ui/components/emoji.slint @@ -82,7 +82,7 @@ export component EmojiPicker inherits Rectangle { border-radius: Theme.radius-lg; background: Theme.surface; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; accessible-role: AccessibleRole.groupbox; accessible-label: @tr("Emoji"); FocusScope { diff --git a/crates/voelin-ui/ui/components/overlay.slint b/crates/voelin-ui/ui/components/overlay.slint index 7fad49a..5b18897 100644 --- a/crates/voelin-ui/ui/components/overlay.slint +++ b/crates/voelin-ui/ui/components/overlay.slint @@ -47,7 +47,7 @@ export component PopupMenu inherits Rectangle { border-radius: Theme.radius-md; background: Theme.surface-3; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; accessible-role: AccessibleRole.list; VerticalLayout { padding: Theme.space-2; diff --git a/crates/voelin-ui/ui/components/select.slint b/crates/voelin-ui/ui/components/select.slint index 1449fb9..750b194 100644 --- a/crates/voelin-ui/ui/components/select.slint +++ b/crates/voelin-ui/ui/components/select.slint @@ -124,7 +124,7 @@ export component Select inherits Rectangle { border-radius: Theme.radius-md; background: Theme.surface-3; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; clip: true; ScrollView { VerticalLayout { diff --git a/crates/voelin-ui/ui/components/tooltip.slint b/crates/voelin-ui/ui/components/tooltip.slint index c6e2484..67fb2bb 100644 --- a/crates/voelin-ui/ui/components/tooltip.slint +++ b/crates/voelin-ui/ui/components/tooltip.slint @@ -18,7 +18,7 @@ export component TooltipBubble inherits Rectangle { border-radius: Theme.radius-xs; background: Theme.surface-4; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; HorizontalLayout { padding-left: Theme.space-3; padding-right: Theme.space-3; diff --git a/crates/voelin-ui/ui/screens/members.slint b/crates/voelin-ui/ui/screens/members.slint index de20514..b494cf5 100644 --- a/crates/voelin-ui/ui/screens/members.slint +++ b/crates/voelin-ui/ui/screens/members.slint @@ -187,7 +187,7 @@ export component MemberCardPopup inherits Rectangle { background: Theme.surface-3; border-radius: Theme.radius-lg; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; accessible-role: AccessibleRole.groupbox; accessible-label: Bridge.member-card.name; // Clicks inside stay inside. diff --git a/crates/voelin-ui/ui/screens/overlays.slint b/crates/voelin-ui/ui/screens/overlays.slint index 10c3d5c..17340e4 100644 --- a/crates/voelin-ui/ui/screens/overlays.slint +++ b/crates/voelin-ui/ui/screens/overlays.slint @@ -106,7 +106,7 @@ export component NotificationsPanel inherits Rectangle { background: Theme.surface-3; border-radius: Theme.radius-lg; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; clip: true; accessible-role: AccessibleRole.groupbox; accessible-label: @tr("Notifications"); diff --git a/crates/voelin-ui/ui/screens/studio-parts.slint b/crates/voelin-ui/ui/screens/studio-parts.slint index 9798240..819438d 100644 --- a/crates/voelin-ui/ui/screens/studio-parts.slint +++ b/crates/voelin-ui/ui/screens/studio-parts.slint @@ -1147,7 +1147,7 @@ export component DestinationSelect inherits Rectangle { border-radius: Theme.radius-md; background: Theme.surface-3; border-width: 1px; - border-color: Theme.border-strong; + border-color: Theme.border-popup; VerticalLayout { padding: Theme.space-2; for item[i] in StudioBridge.destinations: Rectangle { diff --git a/crates/voelin-ui/ui/theme.slint b/crates/voelin-ui/ui/theme.slint index e9fc528..c7a67f5 100644 --- a/crates/voelin-ui/ui/theme.slint +++ b/crates/voelin-ui/ui/theme.slint @@ -39,11 +39,16 @@ export global Theme { out property surface-4: dark ? #1c2b5c : #dce5f7; // Dimmed backdrop behind modals. out property scrim: dark ? #02050fc0 : #0b132b80; + // A lighter dim behind pop-ups: the member card, emoji picker, bell. + out property scrim-light: dark ? #02050f73 : #0b132b33; // Translucent bar over video. out property overlay: dark ? #060a18c8 : #0b1330b0; out property border: dark ? #1b2750 : #d3dcee; out property border-strong: dark ? #2a3a6e : #b9c6e2; + // The edge of pop-ups, menus and tooltips, which lie over surfaces of + // about their own colour. + out property border-popup: dark ? #3d5296 : #9fb0d4; // Accent (buttons, selection, links). out property accent: dark ? #2d6bff : #2458e6; diff --git a/docs/ui.md b/docs/ui.md index 19699e1..d54a30d 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -64,8 +64,8 @@ literal colours. | Group | Tokens | |---|---| | Mode | `mode` ("dark", "light", "system"; set from `ui.theme`), `dark` (resolved), `font-scale` (from `ui.font_scale`) | -| Backgrounds | `bg-app`, `backdrop` (gradient), `bg-rail`, `surface` (panels), `surface-2` (cards, inputs), `surface-3` (hover, menus), `surface-4` (pressed), `scrim`, `overlay` | -| Lines | `border`, `border-strong`, `glow`, `glow-width` (focus/selection ring; the software renderer draws no shadows) | +| Backgrounds | `bg-app`, `backdrop` (gradient), `bg-rail`, `surface` (panels), `surface-2` (cards, inputs), `surface-3` (hover, menus), `surface-4` (pressed), `scrim` (behind modals), `scrim-light` (behind pop-ups), `overlay` | +| Lines | `border`, `border-strong`, `border-popup` (pop-ups, menus, tooltips), `glow`, `glow-width` (focus/selection ring; the software renderer draws no shadows) | | Accent | `accent`, `accent-hover`, `accent-pressed`, `accent-soft` (selected rows), `accent-soft-hover`, `accent-text` (links), `name-text` (chat authors), `on-accent` | | States | `live`, `live-soft`, `danger`, `danger-soft`, `success`, `success-soft`, `warning`, `warning-soft`, `idle`, `dnd`, `offline`, `gold` (crown), `info` | | Text | `text`, `text-secondary`, `text-muted`, `text-disabled`, `icon` | From e3f78dceda8c41a38951c0ff5465b568b8d77391 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 08:44:29 +0000 Subject: [PATCH 11/42] ui: one clipboard path, and Copy invite link in the voice header Copying went through a hidden text field on the phone's voice screen only. It moves into MainWindow: any screen calls Nav.copy(text), and Bridge.copied() confirms it in one toast, shown again when its text is the same as the last copy's. The invite leaves its own message for that toast (the channel and the link) instead of a status of its own, so a copy never shows two. The desktop voice channel view gets the same Invite as a Copy invite link button next to Chat only. Icons.channel is the speaker, for the channel spots that use it later. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- CHANGELOG.md | 2 ++ crates/voelin-ui/src/app.rs | 10 ++++++++++ crates/voelin-ui/src/bind/servers.rs | 6 +++++- crates/voelin-ui/src/servers.rs | 6 ++++-- crates/voelin-ui/ui/app.slint | 17 +++++++++++++++++ crates/voelin-ui/ui/bridge.slint | 4 +++- crates/voelin-ui/ui/icons.slint | 2 ++ crates/voelin-ui/ui/nav.slint | 14 ++++++++++++++ crates/voelin-ui/ui/screens/mobile-voice.slint | 13 +------------ crates/voelin-ui/ui/screens/voice.slint | 6 ++++++ docs/ui.md | 5 +++-- 11 files changed, 67 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 705a80c..8c9e8ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,8 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - 122 more signed client versions (`Versions.csv`). - Icon buttons show their name on hover (desktop), also while they are disabled. +- The voice channel view on desktop can copy an invite link to the channel, + as the phone's Invite button does. ### Changed diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 9eb45f6..18b95db 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -430,6 +430,9 @@ pub(crate) struct App { pub sessions: HashMap, pub models: Models, pub status: String, + /// What the toast of the next copy says instead of "Copied" (an invite + /// names its channel and link). + pub copy_note: Option, /// The members panel's search. pub member_filter: String, /// The topics drawer's search. @@ -679,6 +682,7 @@ pub fn run(options: RunOptions) -> Result<()> { sessions: HashMap::new(), models, status: String::new(), + copy_note: None, member_filter: String::new(), topic_filter: String::new(), voice_view: false, @@ -844,6 +848,12 @@ impl App { } } + /// Nav.copy put text on the clipboard: one toast says so. + pub fn copied(&mut self) { + let text = self.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); + self.set_status(text); + } + pub fn store_settings(&self) { if let Err(e) = self.prefs.set(&UI, self.settings.clone()) { warn!(%e, "could not store settings"); diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index 18a0960..7d61501 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -4,7 +4,7 @@ use slint::ComponentHandle; use voelin_core::Command; use voelin_model::ChannelId; -use crate::app::{Bridge, MainWindow, with_app}; +use crate::app::{App, Bridge, MainWindow, with_app}; pub(super) fn wire(ui: &MainWindow) { let bridge = ui.global::(); @@ -56,4 +56,8 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.client_playback_changed(&form)); }); bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into()); + // Nav.copy, from any screen. + bridge.on_copied(|| { + with_app(App::copied); + }); } diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 821bd78..b4737f8 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -503,7 +503,8 @@ impl App { } /// A link to the voice channel we are in, for the Invite button (which - /// copies it); empty, with a note, without one. + /// copies it, and the copy's toast names the channel); empty, with a + /// note, without one. pub(crate) fn invite_link(&mut self) -> String { let bookmark = self.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone()); let path = self.view().and_then(|v| { @@ -525,7 +526,8 @@ impl App { }; let path: Vec<&str> = path.iter().map(String::as_str).collect(); let link = vm::servers::invite_link(&address, &path); - self.set_status(format!("Copied an invite to {}: {link}", path.last().unwrap_or(&""))); + self.copy_note = + Some(format!("Copied an invite to {}: {link}", path.last().unwrap_or(&""))); link } diff --git a/crates/voelin-ui/ui/app.slint b/crates/voelin-ui/ui/app.slint index 4303cc1..1e76276 100644 --- a/crates/voelin-ui/ui/app.slint +++ b/crates/voelin-ui/ui/app.slint @@ -341,6 +341,23 @@ export component MainWindow inherits Window { } } + // Nav.copy: Slint copies only what is selected in a text field, so the + // text goes through this hidden one. Rust confirms it in the toast, + // shown again even when its text is the last one's. + property clip-requests: Nav.clip-requests; + changed clip-requests => { + clipboard.text = Nav.clip-text; + clipboard.select-all(); + clipboard.copy(); + Bridge.copied(); + toast.shown = true; + } + clipboard := TextInput { + visible: false; + width: 0; + height: 0; + } + // Over the pop-ups, so their scrim does not dim it (a poke from the // member card says so here); under the dialogs. toast := Toast { diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index a6b144b..a23ce53 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -1030,8 +1030,10 @@ export global Bridge { callback dismiss-crash-notice(); callback open-about(); // A link to our voice channel (`ts3server://`) to hand to others; the - // caller copies it. + // caller copies it (Nav.copy). callback invite() -> string; + // Nav.copy put text on the clipboard: Rust says so in the toast. + callback copied(); // Home, friends, direct messages, notifications, search, events and // the settings pages. diff --git a/crates/voelin-ui/ui/icons.slint b/crates/voelin-ui/ui/icons.slint index 720ee77..ce6dc6e 100644 --- a/crates/voelin-ui/ui/icons.slint +++ b/crates/voelin-ui/ui/icons.slint @@ -116,6 +116,8 @@ export global Icons { out property video-off: @image-url("assets/icons/video-off.svg"); out property video: @image-url("assets/icons/video.svg"); out property volume-2: @image-url("assets/icons/volume-2.svg"); + // The icon for channels (voice and chat in one): the speaker. + out property channel: @image-url("assets/icons/volume-2.svg"); out property volume-x: @image-url("assets/icons/volume-x.svg"); out property x: @image-url("assets/icons/x.svg"); // Home, friends, messages, events and the settings pages (from diff --git a/crates/voelin-ui/ui/nav.slint b/crates/voelin-ui/ui/nav.slint index 46b4242..3407aed 100644 --- a/crates/voelin-ui/ui/nav.slint +++ b/crates/voelin-ui/ui/nav.slint @@ -102,6 +102,11 @@ export global Nav { in-out property dm-tab; in-out property join-open; + // Text for the clipboard, and a counter that changes with every copy: + // MainWindow copies it through a hidden text field (`copy` below). + in-out property clip-text; + in-out property clip-requests; + // The phone layout (narrow windows). // The server's members as a page of their own (the desktop shows them // beside the chat). @@ -306,4 +311,13 @@ export global Nav { show(Page.server); Bridge.select-server(id); } + + // Put text on the clipboard; a toast says so. Nothing to copy (an + // invite without a channel, which Rust explains) does nothing. + public function copy(text: string) { + if text != "" { + clip-text = text; + clip-requests += 1; + } + } } diff --git a/crates/voelin-ui/ui/screens/mobile-voice.slint b/crates/voelin-ui/ui/screens/mobile-voice.slint index 9e37500..8e9fae2 100644 --- a/crates/voelin-ui/ui/screens/mobile-voice.slint +++ b/crates/voelin-ui/ui/screens/mobile-voice.slint @@ -631,11 +631,6 @@ export component MobileVoice inherits VerticalLayout { Nav.mobile-tab = MobileTab.chat; } } - clip := TextInput { - visible: false; - width: 0; - height: 0; - } ChannelBar { } sv := ScrollView { // The stream, the people and the chat header scroll away together @@ -678,13 +673,7 @@ export component MobileVoice inherits VerticalLayout { filled: true; size: 62px; icon-size: 24px; - // Through a text field: Slint copies only - // what is selected in one. - clicked => { - clip.text = Bridge.invite(); - clip.select-all(); - clip.copy(); - } + clicked => { Nav.copy(Bridge.invite()); } } } Text { diff --git a/crates/voelin-ui/ui/screens/voice.slint b/crates/voelin-ui/ui/screens/voice.slint index a44ee55..724056a 100644 --- a/crates/voelin-ui/ui/screens/voice.slint +++ b/crates/voelin-ui/ui/screens/voice.slint @@ -244,6 +244,12 @@ export component VoiceView inherits VerticalLayout { horizontal-stretch: 1; overflow: elide; } + IconButton { + icon: Icons.user-plus; + label: @tr("Copy invite link"); + y: (parent.height - self.height) / 2; + clicked => { Nav.copy(Bridge.invite()); } + } IconButton { icon: Icons.message-square; label: @tr("Chat only"); diff --git a/docs/ui.md b/docs/ui.md index d54a30d..79f7739 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -149,7 +149,7 @@ comes from the engine's events; what a gateway adds is hidden without it. | Member card | `member` | Description, groups, talk power, country; private message, poke, friend, block; volume and mute for us | `ContactsChanged`; `Command::SetContact`, `SetClientVolume`, `SetClientMuted`, `Poke` | | Pinned messages | `pins` | In the members panel's place: cards with author, time, text, files and reactions; the pin unpins, a click jumps to the message | `Gateway` `Pins`, `Pinned`, `Unpinned`; `GatewayRequest::Pins`, `Unpin` | | Topics | `topics`, `topic:` | In the members panel's place: search, cards with the message count, creator and last activity, Create Topic; an open topic replaces the chat's messages and takes replies | `Gateway` `Topics`, `Topic`, `TopicHistory`; `GatewayRequest::Topics`, `TopicHistory`, `CreateTopic`, `Post` | -| Voice channel | `voice` | Title, topic, "5 in voice / 50 total", Voice Settings, Leave; the people as large avatars (talking ring and bars, muted, crown, streaming); the streams as cards (LIVE, viewers, kind, bitrate, sound, Watch Stream); the channel's chat | `Presence`, `Talking`, `StreamsChanged`, viewer counts from `StreamsChanged`, else the `Gateway` stream directory | +| Voice channel | `voice` | Title, topic, "5 in voice / 50 total", Copy invite link (a `ts3server://` link to the channel; the phone's Invite button does the same), Chat only, Voice Settings, Leave; the people as large avatars (talking ring and bars, muted, crown, streaming); the streams as cards (LIVE, viewers, kind, bitrate, sound, Watch Stream); the channel's chat | `Presence`, `Talking`, `StreamsChanged`, viewer counts from `StreamsChanged`, else the `Gateway` stream directory | | Watching a stream | `watch`, `popout` | The channel's header with "5 in voice" and Leave; the player with the streamer, title, viewers, LIVE, the picture's height (the simulcast picker when a Voelin streamer offers layers), volume, elapsed time, what arrives (codec, size, frame rate, bitrate), back to the chat, pop out, full screen; a note that the stream belongs to the channel; the channel's chat and a Stream Info tab. Popped out (and in full screen) it fills the window | `WatchState`, `WatchLayers`, decoded frames and their stats (`src/video.rs`), `StreamsChanged` (viewer counts; the `Gateway` stream directory where the server gives none) | The pins and topics share the place of the members panel: opening one @@ -322,7 +322,8 @@ for importing the official clients' identities on start 1. Write the screen in `ui/screens/.slint` from the components (`import { ... } from "../components/index.slint";`), reading data from `Bridge` and navigating through `Nav` (e.g. `Nav.open-settings(...)`, - `Nav.show(Page.home)`). + `Nav.show(Page.home)`). Text goes to the clipboard with `Nav.copy(text)` + (through a hidden text field in `MainWindow`; a toast confirms it). 2. New data: add a struct and a property (models: `[Struct]`) and callbacks to `ui/bridge.slint`. 3. Place it: add a `Page` value in `ui/nav.slint` if it is a page, and in From ae1b864f43fb15c282c970640645ac709098e66e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 10:25:41 +0000 Subject: [PATCH 12/42] voelin-core: channel moves report why they fail; password and token on connect A move went out without asking for an answer, so a wrong password or a full channel came back as nothing. It is sent with a return code now, and a refusal comes as Event::JoinFailed: Password, Full, or a sentence for anything else. Moving to the channel we are in says nothing. The UI does not show it yet; the channel password dialog will. VoiceOptions gets channel_password and token, for joining a channel when connecting and for links with a privilege key; tsclientlib's ConnectOptions gets default_token for the latter (UPSTREAM.md patch 15). Live tests on both dev servers check the password and the key on connect, and the refused moves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- crates/proto/UPSTREAM.md | 4 + crates/proto/tsclientlib/src/lib.rs | 22 ++++- crates/voelin-core/src/lib.rs | 18 ++++ crates/voelin-core/src/voice.rs | 98 ++++++++++++++++++++-- crates/voelin-core/tests/live.rs | 125 ++++++++++++++++++++++++++++ crates/voelin-ui/src/app.rs | 2 + 6 files changed, 260 insertions(+), 9 deletions(-) diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index 481464f..0554dca 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -129,3 +129,7 @@ against or offered back to upstream. Tests cover an independent signature vector, persistence validation/redaction, wire field names, clearing and reconnect snapshot replacement. The account UUID and the ordinary server identity remain separate. +15. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch"). + `ConnectOptions::default_token` sets `client_default_token` of `clientinit`, + which upstream always sent empty, so a privilege key (a bookmark's, or the + `token=` of a `ts3server://` link) can be used on connect. diff --git a/crates/proto/tsclientlib/src/lib.rs b/crates/proto/tsclientlib/src/lib.rs index 41d7fe4..4f8911e 100644 --- a/crates/proto/tsclientlib/src/lib.rs +++ b/crates/proto/tsclientlib/src/lib.rs @@ -392,6 +392,7 @@ impl Connection { channel: None, channel_password: None, password: None, + default_token: None, input_muted: false, output_muted: false, input_hardware_enabled: true, @@ -556,7 +557,7 @@ impl Connection { version_sign: Cow::Borrowed(client_version_sign.as_ref()), client_key_offset: counter, phonetic_name: "".into(), - default_token: "".into(), + default_token: Cow::Borrowed(options.default_token.as_deref().unwrap_or_default()), hardware_id: Cow::Borrowed(options.hardware_id.as_ref()), badges: None, signed_badges: None, @@ -1730,6 +1731,7 @@ pub struct ConnectOptions { channel: Option>, channel_password: Option>, password: Option>, + default_token: Option>, input_muted: bool, output_muted: bool, input_hardware_enabled: bool, @@ -1944,6 +1946,20 @@ impl ConnectOptions { self } + /// Use a privilege key (token) when connecting. + /// Voelin patch: sent as `client_default_token` in `clientinit`. + /// + /// # Example + /// ``` + /// # use tsclientlib::Connection; + /// let opts = Connection::build("localhost").default_token("My privilege key"); + /// ``` + #[inline] + pub fn default_token>>(mut self, token: S) -> Self { + self.default_token = Some(token.into()); + self + } + /// Connect to the server in a muted state. /// /// # Example @@ -2064,6 +2080,10 @@ impl ConnectOptions { #[inline] pub fn get_password(&self) -> Option<&str> { self.password.as_ref().map(AsRef::as_ref) } #[inline] + pub fn get_default_token(&self) -> Option<&str> { + self.default_token.as_ref().map(AsRef::as_ref) + } + #[inline] pub fn get_input_muted(&self) -> bool { self.input_muted } #[inline] pub fn get_output_muted(&self) -> bool { self.output_muted } diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index e9424f6..f7a953b 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -153,6 +153,7 @@ pub enum Command { session: SessionId, request: GatewayRequest, }, + /// Refusals come as [`Event::JoinFailed`]. MoveToChannel { session: SessionId, channel: ChannelId, @@ -469,6 +470,17 @@ pub struct SessionState { pub server_uid: Option, } +/// Why the server did not let us into a channel ([`Event::JoinFailed`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum JoinFailure { + /// The channel's password is missing or wrong. + Password, + /// The channel, or the channel with its subchannels, is full. + Full, + /// Anything else, as a sentence for the user. + Other(String), +} + /// What the engine reports. #[derive(Clone, Debug)] pub enum Event { @@ -534,6 +546,12 @@ pub enum Event { session: SessionId, message: String, }, + /// The server refused [`Command::MoveToChannel`] into `channel`. + JoinFailed { + session: SessionId, + channel: ChannelId, + reason: JoinFailure, + }, /// The streams in our channel (TeamSpeak 6), full list. StreamsChanged { session: SessionId, diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index a4687d9..3e06911 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -33,7 +33,7 @@ use crate::cache; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; use crate::settings::{FILES_PROGRESS_MS, SharedSettings}; -use crate::{Event, SessionId}; +use crate::{Event, JoinFailure, SessionId}; #[derive(Clone, Debug)] pub struct VoiceOptions { @@ -45,6 +45,10 @@ pub struct VoiceOptions { pub server_password: Option, /// Channel path to join, e.g. `Lobby/Sub`. pub channel: Option, + /// The password of `channel`. + pub channel_password: Option, + /// A privilege key to use when connecting. + pub token: Option, /// Open the audio devices (capture and playback). pub audio: bool, /// Network settings for stream peer connections (TeamSpeak 6). @@ -60,6 +64,8 @@ impl VoiceOptions { client_version: None, server_password: None, channel: None, + channel_password: None, + token: None, audio: false, stream_peer: PeerConfig::default(), } @@ -253,6 +259,10 @@ enum Pending { id: u32, message: Option, }, + /// Moving ourselves; refusals are reported as [`Event::JoinFailed`]. + Move { + channel: ChannelId, + }, /// Failures are reported as [`VoiceEvent::Error`] with this label. Report(&'static str), /// Best effort: the answer does not matter. @@ -365,6 +375,12 @@ async fn run_inner( if let Some(channel) = &options.channel { builder = builder.channel(channel.clone()); } + if let Some(pw) = options.channel_password.as_ref().filter(|p| !p.is_empty()) { + builder = builder.channel_password(pw.clone()); + } + if let Some(token) = &options.token { + builder = builder.default_token(token.clone()); + } let mut identity = link.myts_identity.clone(); // A changed account invalidates an in-flight handshake. Drop that connection // and take a fresh snapshot before publishing any connected state. @@ -801,6 +817,13 @@ impl Voice { }; self.link.emit(Event::OfflineMessage { session, request, result }); } + Pending::Move { channel } => { + if let Err(e) = result + && let Some(reason) = join_failure(e) + { + self.link.emit(Event::JoinFailed { session, channel, reason }); + } + } Pending::Quiet | Pending::MytsIdentity(_) => {} Pending::Report(what) => { if let Err(e) = result { @@ -840,13 +863,15 @@ impl Voice { self.send(out, Pending::Report("message"))?; } VoiceCmd::Move(channel, password) => { - let state = self.con.get_state()?; - let own = &state.clients[&state.own_client]; - let mut part = own.client_move(tsclientlib::ChannelId(channel)); - if let Some(pw) = &password { - part = part.set_password(pw); - } - part.send(&mut self.con)?; + let own = self.con.get_state()?.own_client; + let cpw = encode_password(password.as_deref()); + let cmd = + c2s::OutClientMoveMessage::new(&mut std::iter::once(c2s::OutClientMovePart { + client_id: own, + channel_id: tsclientlib::ChannelId(channel), + channel_password: (!cpw.is_empty()).then_some(cpw.as_str().into()), + })); + self.send(cmd, Pending::Move { channel })?; } VoiceCmd::SetInputMuted(muted) => { self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?; @@ -1053,6 +1078,39 @@ impl Voice { } } +/// Why a move into a channel failed, for the user; `None` when there is +/// nothing to tell (we are in that channel already). +fn join_failure(error: TsError) -> Option { + let text = match error { + TsError::ChannelAlreadyIn => return None, + TsError::ChannelInvalidPassword => return Some(JoinFailure::Password), + TsError::ChannelMaxclientsReached | TsError::ChannelMaxfamilyReached => { + return Some(JoinFailure::Full); + } + TsError::ChannelInvalidId => "The channel does not exist any more.".to_owned(), + TsError::PermissionsClientInsufficient | TsError::Permissions => { + "You are not allowed to join this channel.".to_owned() + } + TsError::ClientIsFlooding => "Too many requests: try again in a moment.".to_owned(), + // The error's name in words (its Display is the name). + e => format!("The server refused to move you: {}.", error_words(e)), + }; + Some(JoinFailure::Other(text)) +} + +/// A TeamSpeak error's name in lowercase words: +/// `ChannelIsPrivateChannel` is "channel is private channel". +fn error_words(error: TsError) -> String { + let mut words = String::new(); + for c in format!("{error:?}").chars() { + if c.is_ascii_uppercase() && !words.is_empty() { + words.push(' '); + } + words.push(c.to_ascii_lowercase()); + } + words +} + /// A failed transfer, for the user. fn transfer_error(error: &tsclientlib::Error) -> String { match error { @@ -1063,6 +1121,30 @@ fn transfer_error(error: &tsclientlib::Error) -> String { } } +#[cfg(test)] +mod join_tests { + use super::*; + + #[test] + fn refused_moves_say_why() { + assert_eq!(join_failure(TsError::ChannelInvalidPassword), Some(JoinFailure::Password)); + assert_eq!(join_failure(TsError::ChannelMaxclientsReached), Some(JoinFailure::Full)); + assert_eq!(join_failure(TsError::ChannelMaxfamilyReached), Some(JoinFailure::Full)); + // Moving to the channel we are in. + assert_eq!(join_failure(TsError::ChannelAlreadyIn), None); + let other = |text: &str| Some(JoinFailure::Other(text.into())); + assert_eq!( + join_failure(TsError::PermissionsClientInsufficient), + other("You are not allowed to join this channel.") + ); + // The rest in words, not the error's name. + assert_eq!( + join_failure(TsError::ChannelIsPrivateChannel), + other("The server refused to move you: channel is private channel.") + ); + } +} + #[cfg(test)] mod image_download_tests { use super::*; diff --git a/crates/voelin-core/tests/live.rs b/crates/voelin-core/tests/live.rs index a47706f..498b734 100644 --- a/crates/voelin-core/tests/live.rs +++ b/crates/voelin-core/tests/live.rs @@ -123,6 +123,131 @@ async fn ts3_engine() { .await; } +/// A channel password and a privilege key work when connecting; a refused +/// move says why. One connection, as the servers refuse quick reconnects. +async fn channel_joins(voice_addr: &str, query: voelin_query::Connect) { + use voelin_core::JoinFailure; + use voelin_query::{Command as Query, QueryClient}; + let (admin, _) = QueryClient::connect(&query).await.unwrap(); + let tag = std::process::id() % 10_000; + let create = |name: &str| { + Query::new("channelcreate") + .arg("channel_name", format!("{name}-{tag}")) + .arg("channel_flag_semi_permanent", 1) + }; + let locked = admin.send(&create("locked").arg("channel_password", "secret")).await.unwrap()[0] + .parse::("cid") + .unwrap(); + let full = + create("full").arg("channel_maxclients", 0).arg("channel_flag_maxclients_unlimited", 0); + let full = admin.send(&full).await.unwrap()[0].parse::("cid").unwrap(); + // A key for the Normal group, which has to keep to passwords and limits. + let groups = admin.send(&Query::new("servergrouplist")).await.unwrap(); + let normal = groups + .iter() + .find(|g| g.get("name") == Some("Normal") && g.get("type") == Some("1")) + .and_then(|g| g.parse::("sgid")) + .expect("a Normal server group"); + let key = Query::new("privilegekeyadd") + .arg("tokentype", 0) + .arg("tokenid1", normal) + .arg("tokenid2", 0); + let token = admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned(); + let channels = admin.send(&Query::new("channellist").flag("-flags")).await.unwrap(); + let lobby = channels + .iter() + .find(|c| c.flag("channel_flag_default") == Some(true)) + .and_then(|c| c.parse::("cid")) + .expect("a default channel"); + + let engine = Engine::start(); + let check = { + let (engine, voice_addr, token) = (engine.clone(), voice_addr.to_owned(), token.clone()); + tokio::spawn(async move { + let mut events = engine.subscribe(); + let mut options = VoiceOptions::new(&voice_addr, format!("joins-{tag}")); + options.channel = Some(format!("locked-{tag}")); + options.channel_password = Some("secret".into()); + options.token = Some(token); + engine.send(Command::ConnectVoice { session: 1, options: Box::new(options) }); + let (mut own, mut presence) = (None, None); + wait_for(&mut events, "connected into the channel, in the key's group", |e| { + match e { + Event::State { session: 1, state } => own = state.own_client, + Event::Presence { session: 1, presence: p } => presence = Some(p.clone()), + _ => {} + } + let client = own.and_then(|id| presence.as_ref()?.clients.get(&id).cloned()); + client.is_some_and(|c| c.channel == locked && c.server_groups.contains(&normal)) + }) + .await; + let moved = async |events: &mut Receiver, channel: u64| { + wait_for( + events, + "a move", + |e| matches!(e, Event::State { session: 1, state } if state.own_channel == Some(channel)), + ) + .await; + }; + let refused = + async |events: &mut Receiver, channel: u64, reason: JoinFailure| { + let failed = wait_for(events, "a refused move", |e| { + matches!(e, Event::JoinFailed { session: 1, .. }) + }) + .await; + let Event::JoinFailed { channel: c, reason: r, .. } = failed else { + unreachable!() + }; + assert_eq!((c, r), (channel, reason)); + }; + let move_to = |channel, password: Option<&str>| Command::MoveToChannel { + session: 1, + channel, + password: password.map(Into::into), + }; + engine.send(move_to(lobby, None)); + moved(&mut events, lobby).await; + engine.send(move_to(locked, None)); + refused(&mut events, locked, JoinFailure::Password).await; + engine.send(move_to(locked, Some("wrong"))); + refused(&mut events, locked, JoinFailure::Password).await; + engine.send(move_to(locked, Some("secret"))); + moved(&mut events, locked).await; + // Moving where we are says nothing: the next refusal is the full channel's. + engine.send(move_to(locked, Some("secret"))); + engine.send(move_to(full, None)); + refused(&mut events, full, JoinFailure::Full).await; + }) + }; + let result = check.await; + engine.send(Command::CloseSession { session: 1 }); + tokio::time::sleep(Duration::from_millis(500)).await; + // Clean up everything before reporting a failure; the key is gone once used. + let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await; + for cid in [locked, full] { + admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap(); + } + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts6_channel_joins() { + if !live() { + return; + } + channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ts3_channel_joins() { + if !live() { + return; + } + channel_joins("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011")).await; +} + /// A 1×1 PNG. const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 18b95db..1985241 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -1056,6 +1056,8 @@ impl App { // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. Event::Error { .. } if self.demo_ui => {} Event::Error { message, .. } => self.set_status(message), + // Not shown yet: the channel password dialog will handle it. + Event::JoinFailed { .. } => {} Event::SettingChanged { key } => self.setting_changed(&key), Event::SettingRejected { key, message } => { self.set_status(format!("Setting {key}: {message}")); From f22c2428e01dfff10567fc7bc13a8bd7bdfdc6f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 11:36:21 +0000 Subject: [PATCH 13/42] ui: every kind of spacer channel, and its text wherever a channel is named Only [cspacerN] was recognized, so [spacer], [rspacer] and [*spacer]--- rows showed their raw names, and so did chat tabs, search results, notifications and the other screens that name a channel. parse_spacer (in voelin-model, so the Android voice notification uses it too) reads them all, with any suffix (it only keeps names unique); a line repeats its text across the row and is cut at its end. The tree search, Ctrl+K and the event form leave out lines and empty spacers. Names that go to the server (the invite link, joining a friend's channel) stay raw; the toast after copying an invite shows the text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- CHANGELOG.md | 4 + crates/voelin-android/src/foreground.rs | 13 +- crates/voelin-model/src/lib.rs | 2 +- crates/voelin-model/src/tree.rs | 78 +++++++++- crates/voelin-ui/src/app.rs | 2 +- crates/voelin-ui/src/chat.rs | 2 +- crates/voelin-ui/src/dev.rs | 8 +- crates/voelin-ui/src/events.rs | 8 +- crates/voelin-ui/src/home.rs | 2 +- crates/voelin-ui/src/inbox.rs | 3 +- crates/voelin-ui/src/messages.rs | 13 +- crates/voelin-ui/src/servers.rs | 12 +- crates/voelin-ui/src/social.rs | 42 +++--- crates/voelin-ui/src/streams.rs | 3 +- crates/voelin-ui/src/studio.rs | 10 +- crates/voelin-ui/src/vm/social.rs | 38 +++++ crates/voelin-ui/src/vm/tree.rs | 159 ++++++++++++++++----- crates/voelin-ui/ui/bridge.slint | 6 +- crates/voelin-ui/ui/screens/channels.slint | 24 ++-- docs/ui.md | 14 +- 20 files changed, 347 insertions(+), 96 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c9e8ef..98306eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,10 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - Hover help in the Stream Studio (a source's error, the status details) shows each time and closes when the pointer leaves; it showed only once, and stayed open until a click. +- Spacer channels: `[spacer]`, `[lspacer]`, `[rspacer]` and `[*spacer]` lines + are drawn as TeamSpeak draws them, like `[cspacer]` was, and chats, search + results, notifications and the other screens show a spacer's text instead + of its raw name. ## [0.0.1-alpha] - 2026-10-04 diff --git a/crates/voelin-android/src/foreground.rs b/crates/voelin-android/src/foreground.rs index e48434e..afe59c4 100644 --- a/crates/voelin-android/src/foreground.rs +++ b/crates/voelin-android/src/foreground.rs @@ -13,7 +13,7 @@ use std::sync::Arc; use voelin_core::stream::{StreamState, ViewerInfo, ViewerState}; use voelin_core::{Event, SessionId, VoiceState}; -use voelin_model::Presence; +use voelin_model::{Presence, channel_title}; /// What the voice notification shows. #[derive(Clone, Debug, PartialEq, Eq)] @@ -72,13 +72,13 @@ impl Session { self.name.as_deref().unwrap_or("a server") } - /// Our channel's name and how many are in it. + /// Our channel's name (a spacer's text) and how many are in it. fn channel(&self) -> Option<(&str, usize)> { let id = self.own_channel?; let channel = self.presence.channels.get(&id)?; let people = self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count(); - Some((channel.name.as_str(), people)) + Some((channel_title(channel).0, people)) } } @@ -222,8 +222,11 @@ mod tests { fn presence(people: u16) -> Event { let mut p = Presence::default(); - p.channels - .insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() }); + // A spacer shows its text. + p.channels.insert( + 2, + ChannelInfo { id: 2, name: "[cspacer1]Chill Zone".into(), ..Default::default() }, + ); for id in 1..=people { p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() }); } diff --git a/crates/voelin-model/src/lib.rs b/crates/voelin-model/src/lib.rs index 95acfa9..44dd2f8 100644 --- a/crates/voelin-model/src/lib.rs +++ b/crates/voelin-model/src/lib.rs @@ -16,4 +16,4 @@ pub use presence::{ pub use server::{ BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion, }; -pub use tree::{TreeRow, order_siblings, tree_rows}; +pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows}; diff --git a/crates/voelin-model/src/tree.rs b/crates/voelin-model/src/tree.rs index e13fe2d..fe97c6e 100644 --- a/crates/voelin-model/src/tree.rs +++ b/crates/voelin-model/src/tree.rs @@ -1,4 +1,5 @@ -//! Flatten presence into display rows in TeamSpeak's channel order. +//! Flatten presence into display rows in TeamSpeak's channel order, and +//! read the names of spacer channels. use std::collections::HashMap; @@ -64,6 +65,51 @@ fn add_level<'a>( } } +/// How a TeamSpeak spacer channel draws its text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Spacer { + Left, + Center, + Right, + /// The text repeated across the row: a line such as `---`. + Fill, +} + +impl Spacer { + /// Whether a spacer with this text only separates the rows around it + /// (a line, or no text): nothing to search for or pick. + pub fn separates(self, text: &str) -> bool { + self == Spacer::Fill || text.trim().is_empty() + } +} + +/// A spacer name split into its kind and its text: `[cspacer]Games` is a +/// centred "Games", `[*spacer1]-=` repeats "-=", plain `[spacer3]` is an +/// empty row. The part between `spacer` and `]` only keeps the names +/// unique, so anything goes there. Anything else is not a spacer. +pub fn parse_spacer(name: &str) -> Option<(Spacer, &str)> { + let (inside, text) = name.strip_prefix('[')?.split_once(']')?; + let (kind, _suffix) = inside.split_once("spacer")?; + let kind = match kind { + "" | "l" => Spacer::Left, + "c" => Spacer::Center, + "r" => Spacer::Right, + "*" => Spacer::Fill, + _ => return None, + }; + Some((kind, text)) +} + +/// A channel's name as shown, and its spacer kind. Only top-level channels +/// are spacers, as in TeamSpeak: a sub-channel keeps its name as it is. +/// Names sent to the server (joining by name, invite links) stay raw. +pub fn channel_title(channel: &ChannelInfo) -> (&str, Option) { + match parse_spacer(&channel.name).filter(|_| channel.parent == 0) { + Some((kind, text)) => (text, Some(kind)), + None => (&channel.name, None), + } +} + #[cfg(test)] mod tests { use super::*; @@ -113,4 +159,34 @@ mod tests { ["0#Lobby", "1-Alice", "1-zed", "0#Games"] ); } + + #[test] + fn spacer_names() { + use Spacer::*; + for (name, spacer) in [ + ("[spacer0]", Some((Left, ""))), + ("[spacer3]Hi", Some((Left, "Hi"))), + ("[lspacer]Hi", Some((Left, "Hi"))), + ("[rspacer9]Hi", Some((Right, "Hi"))), + ("[cspacer]Hi", Some((Center, "Hi"))), + ("[cspacerx]Hi", Some((Center, "Hi"))), + ("[cspacer12]Гамесы [1]", Some((Center, "Гамесы [1]"))), + ("[*spacer1]-=", Some((Fill, "-="))), + ("[*spacer]", Some((Fill, ""))), + ("[cspacer2Games", None), + ("Games", None), + ("[Spacer]x", None), + ("[xspacer]x", None), + ("[spacr]x", None), + ("x[spacer]", None), + ] { + assert_eq!(parse_spacer(name), spacer, "{name}"); + } + assert!(Fill.separates("-=") && Left.separates("") && Center.separates(" ")); + assert!(!Left.separates("Hi")); + // Only top-level channels are spacers: a sub-channel keeps its name. + assert_eq!(channel_title(&ch(1, 0, 0, "[rspacer]Staff")), ("Staff", Some(Right))); + assert_eq!(channel_title(&ch(2, 1, 0, "[rspacer]Staff")), ("[rspacer]Staff", None)); + assert_eq!(channel_title(&ch(3, 0, 0, "Lobby")), ("Lobby", None)); + } } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 1985241..ea654fa 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -290,7 +290,7 @@ impl SessionView { self.channel_of(client) .filter(|c| Some(*c) != self.state.own_channel) .and_then(|c| self.presence.channels.get(&c)) - .map_or_else(String::new, |c| c.name.clone()) + .map_or_else(String::new, |c| crate::vm::tree::channel_title(c).0.to_owned()) } /// A client's nickname, or its id. diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index ca7e3dc..b4e29fe 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -145,7 +145,7 @@ impl App { view.presence .channels .get(cid) - .map(|c| c.name.clone()) + .map(|c| vm::tree::channel_title(c).0.to_owned()) .unwrap_or_else(|| cid.to_string()) ), ChatTarget::Private(_) => format!("@{author}"), diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index aec945b..f85fac5 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -444,16 +444,20 @@ fn demo_ui(app: &mut App) { music.icon = DEMO_MUSIC_ICON; music.banner_gfx_url = Some(DEMO_MUSIC_BANNER.into()); music.banner_mode = BannerMode::NoAdjust; - let mut locked = channel(7, 0, 6, "Officers"); + let mut locked = channel(7, 0, 9, "Officers"); locked.has_password = true; + // Spacers as servers name them: a centred heading, one on the right and + // a line. for c in [ channel(1, 0, 0, "Lobby"), chill, channel(3, 0, 2, "[cspacer0]Gaming"), raid, music, - channel(6, 0, 5, "AFK"), + channel(9, 0, 5, "[rspacer2]Staff"), locked, + channel(8, 0, 7, "[*spacer1]---"), + channel(6, 0, 8, "AFK"), ] { p.channels.insert(c.id, c); } diff --git a/crates/voelin-ui/src/events.rs b/crates/voelin-ui/src/events.rs index db634d2..d3ca4e0 100644 --- a/crates/voelin-ui/src/events.rs +++ b/crates/voelin-ui/src/events.rs @@ -126,12 +126,16 @@ impl App { self.refresh_events(); } - /// Channels an event can be in: server-wide first. + /// Channels an event can be in: server-wide first; no lines or empty + /// spacers. fn event_channels(&self) -> Vec<(Option, String)> { let mut out = vec![(None, "Server-wide".to_owned())]; if let Some(view) = self.view() { out.extend( - view.presence.channels.values().map(|c| (Some(c.id), format!("#{}", c.name))), + view.presence + .channels + .values() + .filter_map(|c| Some((Some(c.id), format!("#{}", vm::tree::listed_title(c)?)))), ); } out diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs index 6f4a9e9..57ddab4 100644 --- a/crates/voelin-ui/src/home.rs +++ b/crates/voelin-ui/src/home.rs @@ -35,7 +35,7 @@ impl App { let Some(view) = self.sessions.get(&b.id) else { continue }; let channel_of = |cid: Option| { cid.and_then(|c| view.presence.channels.get(&c)) - .map(|c| c.name.clone()) + .map(|c| vm::tree::channel_title(c).0.to_owned()) .unwrap_or_default() }; let backdrop = vm::avatar::tint(&b.name); diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs index 0bb05c1..494cdfd 100644 --- a/crates/voelin-ui/src/inbox.rs +++ b/crates/voelin-ui/src/inbox.rs @@ -67,7 +67,8 @@ impl App { _ => view.state.own_channel, } .map(|c| { - let name = view.presence.channels.get(&c).map(|c| c.name.as_str()); + let name = + view.presence.channels.get(&c).map(|c| crate::vm::tree::channel_title(c).0); (c, name.map_or_else(|| "the channel".to_owned(), |n| format!("#{n}"))) }); Some((id, tab.title.clone(), channel)) diff --git a/crates/voelin-ui/src/messages.rs b/crates/voelin-ui/src/messages.rs index 877d2f6..52994c8 100644 --- a/crates/voelin-ui/src/messages.rs +++ b/crates/voelin-ui/src/messages.rs @@ -195,7 +195,10 @@ impl App { let name = session .and_then(|s| self.sessions.get(&s)) .and_then(|v| v.presence.channels.get(cid)) - .map_or_else(|| format!("#channel {cid}"), |c| format!("#{}", c.name)); + .map_or_else( + || format!("#channel {cid}"), + |c| format!("#{}", vm::tree::channel_title(c).0), + ); (name, slint::Image::default(), false, 1) } ChatTarget::Server => (server.clone(), slint::Image::default(), false, 0), @@ -463,8 +466,8 @@ impl App { Some(s) => match &s.away { Some(m) if !m.is_empty() => format!("Away: {m} · {}", s.server), Some(_) => format!("Away · {}", s.server), - None if s.channel_name.is_empty() => format!("Online · {}", s.server), - None => format!("Online · {} · #{}", s.server, s.channel_name), + None if s.channel_title.is_empty() => format!("Online · {}", s.server), + None => format!("Online · {} · #{}", s.server, s.channel_title), }, None => match contact.filter(|c| c.last_seen_ms > 0) { Some(c) => format!("Offline · last seen {}", ago(c.last_seen_ms)), @@ -494,10 +497,10 @@ impl App { spots .iter() .map(|s| { - if s.channel_name.is_empty() { + if s.channel_title.is_empty() { s.server.clone().into() } else { - format!("{} · #{}", s.server, s.channel_name).into() + format!("{} · #{}", s.server, s.channel_title).into() } }) .collect() diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index b4737f8..54b2d63 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -509,7 +509,8 @@ impl App { let bookmark = self.current.and_then(|id| self.bookmark(id)).map(|b| b.address.clone()); let path = self.view().and_then(|v| { let mut names = Vec::new(); - let mut channel = v.presence.channels.get(&v.state.own_channel?)?; + let own = v.presence.channels.get(&v.state.own_channel?)?; + let mut channel = own; loop { names.push(channel.name.clone()); match v.presence.channels.get(&channel.parent) { @@ -518,16 +519,17 @@ impl App { } } names.reverse(); - Some(names) + // The link names the channels as the server has them; the + // toast as the tree shows them. + Some((names, vm::tree::channel_title(own).0.to_owned())) }); - let (Some(address), Some(path)) = (bookmark, path) else { + let (Some(address), Some((path, title))) = (bookmark, path) else { self.set_status("Join a voice channel to invite others to it"); return String::new(); }; let path: Vec<&str> = path.iter().map(String::as_str).collect(); let link = vm::servers::invite_link(&address, &path); - self.copy_note = - Some(format!("Copied an invite to {}: {link}", path.last().unwrap_or(&""))); + self.copy_note = Some(format!("Copied an invite to {title}: {link}")); link } diff --git a/crates/voelin-ui/src/social.rs b/crates/voelin-ui/src/social.rs index 28957e3..85a9446 100644 --- a/crates/voelin-ui/src/social.rs +++ b/crates/voelin-ui/src/social.rs @@ -130,7 +130,10 @@ pub(crate) struct Spot { pub server: String, pub client: u16, pub channel: u64, + /// The channel's name as the server has it (to join it by name). pub channel_name: String, + /// The channel's name as shown (a spacer's text). + pub channel_title: String, pub away: Option, pub streaming: bool, /// We are connected with voice there (messages, pokes, moving). @@ -275,16 +278,15 @@ impl App { else { continue; }; + let channel = view.presence.channels.get(&c.channel); spots.push(Spot { session: id, server: self.server_name(id), client: c.id, channel: c.channel, - channel_name: view - .presence - .channels - .get(&c.channel) - .map(|ch| ch.name.clone()) + channel_name: channel.map(|ch| ch.name.clone()).unwrap_or_default(), + channel_title: channel + .map(|ch| vm::tree::channel_title(ch).0.to_owned()) .unwrap_or_default(), away: c.away.clone(), streaming: c.streaming == Some(true), @@ -328,8 +330,8 @@ impl App { (Some(s), None) => match &s.away { Some(m) if !m.is_empty() => format!("Away: {m}"), Some(_) => "Away".into(), - None if s.channel_name.is_empty() => "Online".into(), - None => format!("In {}", s.channel_name), + None if s.channel_title.is_empty() => "Online".into(), + None => format!("In {}", s.channel_title), }, (None, None) => "Offline".into(), }; @@ -356,10 +358,10 @@ impl App { let spot_texts: Vec = spots .iter() .map(|s| { - if s.channel_name.is_empty() { + if s.channel_title.is_empty() { s.server.clone().into() } else { - format!("{} · #{}", s.server, s.channel_name).into() + format!("{} · #{}", s.server, s.channel_title).into() } }) .collect(); @@ -742,7 +744,7 @@ impl App { .sessions .get(&session) .and_then(|v| v.presence.channels.get(cid)) - .map(|c| format!("#{} · {server}", c.name)) + .map(|c| format!("#{} · {server}", vm::tree::channel_title(c).0)) .unwrap_or(server), _ => server, }; @@ -906,10 +908,15 @@ impl App { }); if new { let s = &sessions[0]; - let place = if s.channel_name.is_empty() { + let channel = self + .sessions + .get(&(s.session as i64)) + .and_then(|v| v.presence.channels.get(&s.channel)) + .map_or(s.channel_name.as_str(), |c| vm::tree::channel_title(c).0); + let place = if channel.is_empty() { format!("on {}", self.server_name(s.session as i64)) } else { - format!("on {} · #{}", self.server_name(s.session as i64), s.channel_name) + format!("on {} · #{channel}", self.server_name(s.session as i64)) }; self.notify( NoticeKind::Friend, @@ -971,15 +978,17 @@ impl App { let mut channels = Vec::new(); for b in &self.bookmarks { let Some(view) = self.sessions.get(&b.id) else { continue }; - for c in view.presence.channels.values().filter(|c| matches(&query, &[&c.name])) { + for (channel, title) in + vm::social::found_channels(view.presence.channels.values(), &query) + { channels.push(( SearchItem { kind: "channel".into(), - title: c.name.clone().into(), + title: title.into(), subtitle: b.name.clone().into(), ..Default::default() }, - Found::Channel(b.id, c.id), + Found::Channel(b.id, channel), )); } } @@ -1004,8 +1013,7 @@ impl App { .presence .channels .get(&c.channel) - .map(|ch| ch.name.as_str()) - .unwrap_or(""); + .map_or("", |ch| vm::tree::channel_title(ch).0); people.push(( SearchItem { kind: "person".into(), diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index cd1a4de..2eb6416 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -436,7 +436,8 @@ impl App { ); let channel = u16::try_from(streamer).ok().and_then(|id| { let view = self.view()?; - view.presence.channels.get(&view.channel_of(id)?).map(|c| c.name.clone()) + let channel = view.presence.channels.get(&view.channel_of(id)?)?; + Some(crate::vm::tree::channel_title(channel).0.to_owned()) }); bridge.set_viewer_channel(channel.unwrap_or_default().into()); bridge.set_viewer_elapsed(watch.elapsed().into()); diff --git a/crates/voelin-ui/src/studio.rs b/crates/voelin-ui/src/studio.rs index 38a2a5c..0c9e12f 100644 --- a/crates/voelin-ui/src/studio.rs +++ b/crates/voelin-ui/src/studio.rs @@ -874,7 +874,7 @@ impl App { .state .own_channel .and_then(|c| view.presence.channels.get(&c)) - .map(|c| c.name.clone()) + .map(|c| vm::tree::channel_title(c).0.to_owned()) .unwrap_or_default(); let server = if view.presence.server_name.is_empty() { self.bookmark(id).map(|b| b.name.clone()).unwrap_or_default() @@ -929,8 +929,12 @@ impl App { let target = ChatTarget::Channel(channel); let demo = self.demo_ui; let view = self.sessions.entry(id).or_default(); - let name = view.presence.channels.get(&channel).map(|c| c.name.clone()); - let name = name.unwrap_or_default(); + let name = view + .presence + .channels + .get(&channel) + .map(|c| vm::tree::channel_title(c).0.to_owned()) + .unwrap_or_default(); if !view.tabs.iter().any(|t| t.target == target) { view.tabs.push(Tab::new(target.clone(), format!("#{name}"))); if !demo { diff --git a/crates/voelin-ui/src/vm/social.rs b/crates/voelin-ui/src/vm/social.rs index 79023de..ac51cdb 100644 --- a/crates/voelin-ui/src/vm/social.rs +++ b/crates/voelin-ui/src/vm/social.rs @@ -120,6 +120,19 @@ pub fn matches(query: &str, fields: &[&str]) -> bool { q.is_empty() || fields.iter().any(|f| f.to_lowercase().contains(&q)) } +/// The channels the search (Ctrl+K) finds for `query`, with their titles: +/// a spacer by its text, never a line or an empty spacer. +pub fn found_channels<'a>( + channels: impl IntoIterator, + query: &str, +) -> Vec<(u64, &'a str)> { + channels + .into_iter() + .filter_map(|c| Some((c.id, crate::vm::tree::listed_title(c)?))) + .filter(|(_, title)| matches(query, &[*title])) + .collect() +} + /// The date block of an event: "SAT", "26", "APR". pub fn date_block(ts_ms: i64) -> (String, String, String) { local(ts_ms) @@ -224,6 +237,31 @@ mod tests { assert!(!matches("zz", &["Kairo"])); } + /// The search shows spacers by their text and leaves out lines. + #[test] + fn search_channels() { + let channel = |id, parent, name: &str| voelin_model::ChannelInfo { + id, + parent, + name: name.into(), + ..Default::default() + }; + let channels = [ + channel(1, 0, "[cspacer0]Gaming"), + channel(2, 0, "[*spacer]---"), + channel(3, 0, "[spacer1]"), + // Only top-level channels are spacers. + channel(4, 1, "[cspacer]Game Night"), + channel(5, 0, "Lobby"), + ]; + assert_eq!(found_channels(&channels, "gam"), [(1, "Gaming"), (4, "[cspacer]Game Night")]); + assert!(found_channels(&channels, "-").is_empty()); + // A spacer is not found by its prefix; a sub-channel's name is all + // its own. + assert_eq!(found_channels(&channels, "spacer"), [(4, "[cspacer]Game Night")]); + assert_eq!(found_channels(&channels, "").len(), 3); + } + #[test] fn event_dates() { let start = parse_local("2026-04-25 19:00").unwrap(); diff --git a/crates/voelin-ui/src/vm/tree.rs b/crates/voelin-ui/src/vm/tree.rs index b97c97a..41d05b4 100644 --- a/crates/voelin-ui/src/vm/tree.rs +++ b/crates/voelin-ui/src/vm/tree.rs @@ -4,8 +4,9 @@ use std::collections::{HashMap, HashSet}; use std::path::PathBuf; +pub use voelin_model::channel_title; use voelin_model::{ - BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows, + BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, tree_rows, }; use crate::app::{MemberItem, TreeItem}; @@ -104,22 +105,40 @@ fn talking(input: &TreeInput, client: &ClientInfo) -> bool { input.talking.contains(&client.id) || client.talking == Some(true) } -/// Centered spacer prefixes are presentation metadata, not part of the title. -/// Leave other names untouched rather than guessing at the full spacer syntax. -fn channel_label(name: &str) -> (&str, bool) { - if let Some((suffix, label)) = name.strip_prefix("[cspacer").and_then(|s| s.split_once(']')) - && suffix.bytes().all(|b| b.is_ascii_digit()) - { - return (label, true); +/// A spacer kind as the UI takes it (`TreeItem.spacer`, 0: no spacer). +fn spacer_index(kind: Spacer) -> i32 { + match kind { + Spacer::Left => 1, + Spacer::Center => 2, + Spacer::Right => 3, + Spacer::Fill => 4, } - (name, false) } -/// A channel's name as shown, and whether it is a centred spacer. Only -/// top-level channels are spacers, as in TeamSpeak: a sub-channel keeps its -/// name as it is. -pub fn channel_title(channel: &ChannelInfo) -> (&str, bool) { - if channel.parent == 0 { channel_label(&channel.name) } else { (&channel.name, false) } +/// A channel's title for lists and pickers (the search, the event form); +/// none for a spacer that only separates. +pub fn listed_title(channel: &ChannelInfo) -> Option<&str> { + match channel_title(channel) { + (text, Some(kind)) if kind.separates(text) => None, + (text, _) => Some(text), + } +} + +/// About as many characters as a fill spacer's row holds: more than the +/// widest tree shows. +const FILL_CHARS: usize = 200; + +/// A spacer's text as its row shows it: a fill pattern repeated across the +/// row, a blank text empty. +fn spacer_text(kind: Spacer, text: &str) -> String { + match kind { + Spacer::Fill => match text.chars().count() { + 0 => String::new(), + n => text.repeat((FILL_CHARS / n).max(1)), + }, + _ if text.trim().is_empty() => String::new(), + _ => text.to_owned(), + } } /// The rows of the tree, channels with their clients below. @@ -129,9 +148,12 @@ pub fn rows(input: &TreeInput) -> Vec { .into_iter() .map(|row| match row { TreeRow::Channel { depth, channel } => { - let (name, centered_spacer) = channel_title(channel); + let (name, spacer) = match channel_title(channel) { + (text, Some(kind)) => (spacer_text(kind, text), spacer_index(kind)), + (name, None) => (name.to_owned(), 0), + }; TreeItem { - centered_spacer, + spacer, is_channel: true, depth: depth as i32, id: channel.id as i32, @@ -183,14 +205,24 @@ pub fn rows(input: &TreeInput) -> Vec { filter(rows, input.filter) } -/// Rows that match `query`, and the channels above them. +/// A spacer row that only separates: a line, or no text. +fn separator(row: &TreeItem) -> bool { + row.is_channel + && (row.spacer == spacer_index(Spacer::Fill) || (row.spacer != 0 && row.name.is_empty())) +} + +/// Rows that match `query`, and the channels above them. A separator +/// never matches (`---` is no channel to look for), but stays above what +/// does. fn filter(rows: Vec, query: &str) -> Vec { let query = query.trim().to_lowercase(); if query.is_empty() { return rows; } - let matches: Vec = - rows.iter().map(|r| r.name.to_lowercase().contains(query.as_str())).collect(); + let matches: Vec = rows + .iter() + .map(|r| !separator(r) && r.name.to_lowercase().contains(query.as_str())) + .collect(); let mut keep = matches.clone(); // A channel stays if anything below it matches. for i in 0..rows.len() { @@ -505,28 +537,85 @@ mod tests { } #[test] - fn centered_spacer_titles_keep_tree_identity_and_search() { + fn spacer_rows_keep_tree_identity() { let mut p = presence(); p.channels.get_mut(&2).unwrap().name = "[cspacer12]Гамесы".into(); + let more = |id, order, name: &str| ChannelInfo { + id, + order, + name: name.into(), + has_password: id == 5, + ..Default::default() + }; + for c in + [more(4, 2, "[*spacer1]-="), more(5, 4, "[rspacer2]Staff"), more(6, 5, "[spacer3]")] + { + p.channels.insert(c.id, c); + } let (t, c, pb) = (HashSet::new(), HashSet::from([2]), ClientPlaybackMap::new()); let e = Extras::default(); - let rows = rows(&input(&p, &t, &c, &pb, "Гамесы", &e)); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].name, "Гамесы"); - assert!(rows[0].centered_spacer && rows[0].collapsed); - assert_eq!(rows[0].id, 2); - assert_eq!(channel_label("[cspacer]Games"), ("Games", true)); - for name in ["[cspacerx]Games", "[cspacer2Games", "Games", "[spacer0]Games"] { - assert_eq!(channel_label(name), (name, false)); - } + let rows = rows(&input(&p, &t, &c, &pb, "", &e)); + let channels: Vec<_> = rows + .iter() + .filter(|r| r.is_channel) + .map(|r| (r.id, r.spacer, r.name.chars().take(6).collect::())) + .collect(); + let row = |id, spacer, name: &str| (id, spacer, name.to_owned()); + assert_eq!( + channels, + [ + row(1, 0, "Lobby"), + row(2, 2, "Гамесы"), + row(4, 4, "-=-=-="), + row(5, 3, "Staff"), + row(6, 1, ""), + ] + ); + // A fill line repeats its pattern across the row. + let fill = &rows.iter().find(|r| r.id == 4 && r.is_channel).unwrap().name; + assert_eq!(fill.chars().count(), FILL_CHARS); + assert_eq!(spacer_text(Spacer::Fill, ""), ""); + assert_eq!(spacer_text(Spacer::Fill, "x".repeat(300).as_str()).len(), 300); + let games = rows.iter().find(|r| r.id == 2 && r.is_channel).unwrap(); + assert!(games.collapsed && games.members == 1); + assert!(rows.iter().any(|r| r.id == 5 && r.is_channel && r.locked)); // Only top-level channels are spacers: a sub-channel keeps its name. p.channels.get_mut(&3).unwrap().name = "[cspacer1]Chess".into(); - let (t, c) = (HashSet::new(), HashSet::new()); - let found = super::rows(&input(&p, &t, &c, &pb, "Chess", &e)); - let chess = found.iter().find(|r| r.is_channel && r.id == 3).unwrap(); - assert_eq!((chess.name.as_str(), chess.centered_spacer), ("[cspacer1]Chess", false)); - assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", true)); - assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", false)); + let c = HashSet::new(); + let rows = super::rows(&input(&p, &t, &c, &pb, "", &e)); + let chess = rows.iter().find(|r| r.is_channel && r.id == 3).unwrap(); + assert_eq!((chess.name.as_str(), chess.spacer), ("[cspacer1]Chess", 0)); + assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", Some(Spacer::Center))); + assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", None)); + // Lists and pickers leave out what only separates. + let listed: Vec<_> = p.channels.values().filter_map(listed_title).collect(); + assert_eq!(listed, ["Lobby", "Гамесы", "[cspacer1]Chess", "Staff"]); + } + + /// The search finds a spacer by its text, never a separator, but keeps + /// separators above what it finds. + #[test] + fn search_skips_separators() { + let mut p = presence(); + p.channels.get_mut(&2).unwrap().name = "[*spacer1]---".into(); + p.channels.get_mut(&1).unwrap().name = "[cspacer]Lobby".into(); + p.channels.insert( + 4, + ChannelInfo { id: 4, order: 2, name: "[spacer4]".into(), ..Default::default() }, + ); + let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); + let e = Extras::default(); + let names = |filter| { + super::rows(&input(&p, &t, &c, &pb, filter, &e)) + .iter() + .map(|r| r.name.chars().take(3).collect::()) + .collect::>() + }; + assert!(names("-").is_empty()); + assert!(names("spacer").is_empty()); + assert_eq!(names("lob"), ["Lob"]); + // The line stays as the parent of Chess. + assert_eq!(names("chess"), ["---", "Che"]); } #[test] diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index a23ce53..e5a0000 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -27,8 +27,10 @@ export struct ServerItem { export struct TreeItem { is-channel: bool, - // Recognized centred TeamSpeak spacer; name excludes its wire prefix. - centered-spacer: bool, + // A TeamSpeak spacer channel, its name without the `[cspacer1]` part: + // 0 none, 1 left, 2 centred, 3 right, 4 a line (the name repeats its + // pattern across the row). + spacer: int, depth: int, id: int, name: string, diff --git a/crates/voelin-ui/ui/screens/channels.slint b/crates/voelin-ui/ui/screens/channels.slint index 0a1e206..f4a9541 100644 --- a/crates/voelin-ui/ui/screens/channels.slint +++ b/crates/voelin-ui/ui/screens/channels.slint @@ -126,6 +126,8 @@ component TreeRow inherits Rectangle { in property item; callback client-clicked(int); property indent: item.depth * 14px; + // A spacer that only separates: a line, or no text. + property separator: item.is-channel && (item.spacer == 4 || (item.spacer != 0 && item.name == "")); height: item.is-channel ? 34px * Theme.font-scale : 30px * Theme.font-scale; clip: true; border-radius: Theme.radius-md; @@ -133,7 +135,7 @@ component TreeRow inherits Rectangle { border-width: item.is-channel && item.own ? 1px : 0px; border-color: Theme.accent; accessible-role: AccessibleRole.list-item; - accessible-label: item.is-channel ? @tr("Channel {}", item.name) : item.name; + accessible-label: !item.is-channel ? item.name : root.separator ? @tr("Separator") : @tr("Channel {}", item.name); accessible-description: (item.talking ? @tr("talking") + " " : "") + (item.streaming ? @tr("streaming") + " " : "") + (item.muted ? @tr("microphone off") + " " : "") + (item.local-muted ? @tr("muted for you") : ""); accessible-action-default => { if item.is-channel { @@ -177,11 +179,13 @@ component TreeRow inherits Rectangle { padding-left: Theme.space-2 + root.indent; padding-right: Theme.space-3; spacing: Theme.space-2; - if item.centered-spacer: Rectangle { width: 18px; } - if !item.centered-spacer && item.icon.width > 0: RowIcon { + // Spacers have no icon; a centred one is balanced against the + // chevron. + if item.spacer == 2: Rectangle { width: 18px; } + if item.spacer == 0 && item.icon.width > 0: RowIcon { source: item.icon; } - if !item.centered-spacer && item.icon.width == 0: Icon { + if item.spacer == 0 && item.icon.width == 0: Icon { source: item.locked ? Icons.lock : Icons.volume-2; size: 18px; tint: item.banner.width > 0 || item.own ? Theme.text : Theme.icon; @@ -189,23 +193,25 @@ component TreeRow inherits Rectangle { } Text { text: item.name; - horizontal-alignment: item.centered-spacer ? center : left; + horizontal-alignment: item.spacer == 2 ? center : item.spacer == 3 ? right : left; // Full contrast over a banner. color: item.own || item.banner.width > 0 ? Theme.text : Theme.text-secondary; font-weight: item.own || item.banner.width > 0 ? Theme.weight-semibold : Theme.weight-medium; vertical-alignment: center; horizontal-stretch: 1; - overflow: elide; + // A line is cut where the row ends; it must not widen the list. + overflow: item.spacer == 4 ? clip : elide; + min-width: 0px; } // At the end where the start shows the channel's icon, or nothing - // (a centred spacer). - if item.locked && (item.icon.width > 0 || item.centered-spacer): Icon { + // (a spacer). + if item.locked && (item.icon.width > 0 || item.spacer != 0): Icon { source: Icons.lock; size: 14px; tint: item.banner.width > 0 ? Theme.text : Theme.icon; y: (parent.height - self.height) / 2; } - if !item.centered-spacer && (item.members > 0 || item.max-members >= 0): HorizontalLayout { + if item.spacer == 0 && (item.members > 0 || item.max-members >= 0): HorizontalLayout { spacing: 3px; if item.own: Icon { source: Icons.users; diff --git a/docs/ui.md b/docs/ui.md index 79f7739..baba270 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -463,10 +463,16 @@ The compact server card shows its icon over the host banner. TeamSpeak 6 channel banners sit behind their titles in fixed-height tree rows (34 pixels), and behind desktop and phone chat/voice headers. Artwork uses centred cover cropping without distortion; it never adds height to navigation. Custom channel -icons lead the title, and recognized `[cspacerN]` labels are centred without -showing the prefix. A theme-aware surface gradient (74% to 66% opacity) keeps -primary text above 4.5:1 contrast even on all-white or all-black artwork, while -leaving the image visible. Missing pictures retain the normal background. +icons lead the title. Top-level spacer channels show their text without the +prefix and without an icon or a member count: `[spacerN]` and `[lspacerN]` on +the left, `[cspacerN]` centred, `[rspacerN]` on the right, and `[*spacerN]---` +repeats its text across the row as a line (any text may follow `spacer`, as +it only keeps names unique). Every screen that names a channel, and the +Android voice notification, shows a spacer's text; the tree search, Ctrl+K and +the event form leave out lines and empty spacers. A theme-aware surface +gradient (74% to 66% opacity) keeps primary text above 4.5:1 contrast even on +all-white or all-black artwork, while leaving the image visible. Missing +pictures retain the normal background. Bookmarks remember the server icon ID and the address that supplied it. The server list, search results and server header load its cached bytes before From 8b605b5b45588814c3328e823ce0c18fdb762841 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 16:15:03 +0000 Subject: [PATCH 14/42] ui: a password dialog for locked channels, and pokes with a message Joining a locked channel sent no password, so the server refused it and nothing said so; pokes always went out empty. Every join (a double-click in the tree, joining a friend) now goes through App::join_channel: a locked channel asks for its password first (join_password), which is kept for the session until voice disconnects, and it is used when connecting into the channel too. Event::JoinFailed asks again under "Wrong password", or says the channel is full or why the server refused. Without voice, a double-click connects into the channel, as joining a friend did. Connecting into a channel names it by id (`/`): by name the server finds only a top-level channel, so a subchannel's name connected into the default channel. A wrong password when connecting also puts us into the default channel without a word, so the channel is joined again once it shows in the presence (after_connect), and that move asks again. Both seen on the dev TS3 and TS6 servers. Poking opens a dialog with an optional message, its length counted up to 100 characters; the UI trims and cuts it (poke_message), and the engine cuts it on characters too. Both dev servers take 100 characters of any width (400 bytes of emoji) and refuse 101 (seen through ServerQuery). Dev switches channel-password[:wrong] and poke. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ --- CHANGELOG.md | 9 ++ crates/voelin-core/src/lib.rs | 7 +- crates/voelin-core/src/voice.rs | 32 ++++- crates/voelin-ui/src/app.rs | 25 +++- crates/voelin-ui/src/bind/chat.rs | 3 + crates/voelin-ui/src/bind/servers.rs | 11 +- crates/voelin-ui/src/dev.rs | 46 +++++++- crates/voelin-ui/src/members.rs | 35 ++++-- crates/voelin-ui/src/servers.rs | 135 ++++++++++++++++++++-- crates/voelin-ui/src/social.rs | 27 +---- crates/voelin-ui/src/vm/servers.rs | 67 ++++++++++- crates/voelin-ui/src/vm/social.rs | 23 +++- crates/voelin-ui/ui/app.slint | 10 +- crates/voelin-ui/ui/bridge.slint | 6 + crates/voelin-ui/ui/nav.slint | 7 ++ crates/voelin-ui/ui/screens/dialogs.slint | 122 ++++++++++++++++++- docs/architecture.md | 5 +- docs/ui.md | 5 +- 18 files changed, 512 insertions(+), 63 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98306eb..d26f6fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,8 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - zbus's warnings about desktop portal requests are left out of the logs. - Pop-ups, menus and tooltips have a clearer edge, and the member card, the emoji picker and the notifications panel dim the window behind them. +- Double-clicking a channel of a server without voice connects into it + (it said "not connected with voice"). ### Fixed @@ -66,6 +68,13 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows are drawn as TeamSpeak draws them, like `[cspacer]` was, and chats, search results, notifications and the other screens show a spacer's text instead of its raw name. +- Locked channels ask for their password (kept until voice disconnects, and + asked again when it is wrong), and joining a full channel or one the + server refuses says why; joining did nothing before. +- Pokes can carry a message (up to 100 characters); they were always sent + empty. +- Joining a friend in a subchannel of a server without voice connects into + that subchannel; it connected into the default channel. ## [0.0.1-alpha] - 2026-10-04 diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index f7a953b..28abf56 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -99,6 +99,10 @@ pub use voice::VoiceOptions; pub type SessionId = u64; +/// The longest poke message servers take, in characters; a longer one is +/// cut ([`Command::Poke`]). +pub const POKE_MESSAGE_MAX: usize = 100; + /// What the UI asks for. #[derive(Clone, Debug)] pub enum Command { @@ -274,7 +278,8 @@ pub enum Command { volume: f32, }, /// Poke a client (voice): the server shows it a notification with - /// `message`. Failures come as [`Event::Error`]. + /// `message`, cut to [`POKE_MESSAGE_MAX`] characters. Failures come as + /// [`Event::Error`]. Poke { session: SessionId, client: u16, diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index 3e06911..00534de 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -33,7 +33,7 @@ use crate::cache; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; use crate::settings::{FILES_PROGRESS_MS, SharedSettings}; -use crate::{Event, JoinFailure, SessionId}; +use crate::{Event, JoinFailure, POKE_MESSAGE_MAX, SessionId}; #[derive(Clone, Debug)] pub struct VoiceOptions { @@ -43,7 +43,7 @@ pub struct VoiceOptions { /// Signed compatibility version; `None` selects the native platform's tuple. pub client_version: Option, pub server_password: Option, - /// Channel path to join, e.g. `Lobby/Sub`. + /// Channel path to join, e.g. `Lobby/Sub`, or `/`. pub channel: Option, /// The password of `channel`. pub channel_password: Option, @@ -889,7 +889,7 @@ impl Voice { let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once( c2s::OutClientPokeRequestPart { client_id: tsclientlib::ClientId(client), - message: message.as_str().into(), + message: poke_message(&message).into(), }, )); self.send(cmd, Pending::Report("poke"))?; @@ -1098,6 +1098,15 @@ fn join_failure(error: TsError) -> Option { Some(JoinFailure::Other(text)) } +/// A poke's message as servers take it: its first [`POKE_MESSAGE_MAX`] +/// characters (not bytes, so a letter is never cut in half). +fn poke_message(message: &str) -> &str { + match message.char_indices().nth(POKE_MESSAGE_MAX) { + Some((end, _)) => &message[..end], + None => message, + } +} + /// A TeamSpeak error's name in lowercase words: /// `ChannelIsPrivateChannel` is "channel is private channel". fn error_words(error: TsError) -> String { @@ -1145,6 +1154,23 @@ mod join_tests { } } +#[cfg(test)] +mod poke_tests { + use super::*; + + #[test] + fn long_pokes_are_cut_by_characters() { + assert_eq!(poke_message("hi"), "hi"); + assert_eq!(poke_message(""), ""); + let exact = "x".repeat(POKE_MESSAGE_MAX); + assert_eq!(poke_message(&exact), exact); + // Two bytes each: cut after 100 letters, not 100 bytes. + let long = "ä".repeat(150); + assert_eq!(poke_message(&long), "ä".repeat(POKE_MESSAGE_MAX)); + assert_eq!(poke_message(&"🙂".repeat(101)).chars().count(), POKE_MESSAGE_MAX); + } +} + #[cfg(test)] mod image_download_tests { use super::*; diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index ea654fa..a19373b 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -234,6 +234,11 @@ pub(crate) struct SessionView { pub gateway_caps: Vec, /// The client whose member card is open. pub member_card: Option, + /// Passwords given for locked channels, until voice disconnects. + pub channel_passwords: HashMap, + /// The channel a voice connection was asked into, until it is joined + /// or joined again (`App::join_after_connect`). + pub join_after_connect: Option, /// Viewers of the streams in the gateway's directory, by stream id. pub stream_viewers: HashMap, /// Downloads started from chat, by transfer id. @@ -266,6 +271,8 @@ impl Default for SessionView { channel_groups: Vec::new(), gateway_caps: Vec::new(), member_card: None, + channel_passwords: HashMap::new(), + join_after_connect: None, stream_viewers: HashMap::new(), downloads: HashMap::new(), next_transfer: 1, @@ -454,6 +461,10 @@ pub(crate) struct App { pub contacts: HashMap, /// The client in the volume dialog: session, client id, unique id. pub playback_dialog: Option<(i64, u16, Option)>, + /// The locked channel the password dialog is for: session, channel. + pub join_target: Option<(i64, ChannelId)>, + /// Who the poke dialog pokes: session, client, nickname. + pub poke_target: Option<(i64, u16, String)>, pub mic_test: bool, pub ptt: GlobalPtt, pub video: Video, @@ -695,6 +706,8 @@ pub fn run(options: RunOptions) -> Result<()> { playback, contacts: HashMap::new(), playback_dialog: None, + join_target: None, + poke_target: None, mic_test: false, ptt, video, @@ -902,6 +915,11 @@ impl App { if state.voice != VoiceState::Connected { view.focused_own_channel = false; } + if state.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected + { + view.channel_passwords.clear(); + view.join_after_connect = None; + } if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { // A new connection: volumes are sent again. view.applied_playback.clear(); @@ -926,6 +944,7 @@ impl App { if self.open_client_pending && self.current == Some(id) { self.open_first_client(); } + self.join_after_connect(id); } Event::ServerInfo { session, name, flavor, capabilities } => { self.sessions.entry(session as i64).or_default().capabilities = capabilities; @@ -944,6 +963,7 @@ impl App { Event::Presence { session, presence } => { self.sessions.entry(session as i64).or_default().presence = presence; self.apply_client_playback(session as i64); + self.join_after_connect(session as i64); if self.current == Some(session as i64) { self.refresh_toolbar(); self.refresh_tree(); @@ -1056,8 +1076,9 @@ impl App { // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. Event::Error { .. } if self.demo_ui => {} Event::Error { message, .. } => self.set_status(message), - // Not shown yet: the channel password dialog will handle it. - Event::JoinFailed { .. } => {} + Event::JoinFailed { session, channel, reason } => { + self.join_failed(session as i64, channel, reason); + } Event::SettingChanged { key } => self.setting_changed(&key), Event::SettingRejected { key, message } => { self.set_status(format!("Setting {key}: {message}")); diff --git a/crates/voelin-ui/src/bind/chat.rs b/crates/voelin-ui/src/bind/chat.rs index 54d1ecb..ed9a7dc 100644 --- a/crates/voelin-ui/src/bind/chat.rs +++ b/crates/voelin-ui/src/bind/chat.rs @@ -61,6 +61,9 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_member_action(|action| { with_app(|app| app.member_action(&action)); }); + bridge.on_send_poke(|text| { + with_app(|app| app.send_poke(&text)); + }); bridge.on_member_volume(|percent| { with_app(|app| app.member_volume(percent)); }); diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index 7d61501..1096031 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -25,13 +25,14 @@ pub(super) fn wire(ui: &MainWindow) { }); bridge.on_join_channel(|cid| { with_app(|app| { - app.command(|session| Command::MoveToChannel { - session, - channel: cid as ChannelId, - password: None, - }) + if let Some(session) = app.current { + app.join_channel(session, cid as ChannelId); + } }); }); + bridge.on_join_with_password(|password| { + with_app(|app| app.join_with_password(password.to_string())); + }); bridge.on_toggle_collapse(|cid| { with_app(|app| app.toggle_collapse(cid as ChannelId)); }); diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index f85fac5..4321ee5 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -21,7 +21,11 @@ //! notification), `shared:` (text shared to the app on Android), //! `pins`, `topics` (the drawers), //! `topic:` (a topic's messages), `member` (the member card of the -//! first other client), `watch` (the first stream; with sample data the +//! first other client), `poke` (the poke dialog: for the contact shown +//! after `friends`, else for the first other client, its card open), +//! `channel-password` (the password dialog of the first locked channel, +//! the sample's Officers; `channel-password:wrong` as after a refused +//! one), `watch` (the first stream; with sample data the //! local test pattern in its place), `popout` (the same, popped out), //! `tab:` (phone layout); `friends[:]`, //! `messages[:]` (a private chat), `inbox` (offline messages), @@ -49,8 +53,8 @@ use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; use voelin_core::gateway::Pin; use voelin_core::stream::{StreamInfo, StreamKind}; use voelin_core::{ - Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, OfflineMessageInfo, - Relation, SessionState, Source, VoiceState, + Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure, ObserveState, + OfflineMessageInfo, Relation, SessionState, Source, VoiceState, }; use voelin_gateway_proto::{ Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule, @@ -255,6 +259,23 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { "member" => { with_app(|app| app.open_first_member()); } + // After `friends` the contact path (Kairo without a contact + // chosen), else the member card's. + "poke" => { + let friends = nav.get_page() == Page::Friends; + with_app(|app| { + if friends { + let uid = app.social.selected.clone().unwrap_or_else(|| "demo-3".into()); + app.contact_action(&uid, "poke"); + } else { + app.open_first_member(); + app.member_action("poke"); + } + }); + } + "channel-password" => { + with_app(|app| open_channel_password(app, arg == "wrong")); + } "watch" | "popout" => { with_app(|app| { if switches.demo_ui { app.demo_watch() } else { app.watch_first_stream() } @@ -382,6 +403,25 @@ fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Re Ok(()) } +/// `VOELIN_OPEN=channel-password`: join the current server's first locked +/// channel, which asks for its password; `wrong` as if the server had +/// refused one. +fn open_channel_password(app: &mut App, wrong: bool) { + let Some(session) = app.current else { return }; + let locked = app + .view() + .and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min()); + let Some(channel) = locked else { return }; + if wrong { + if let Some(view) = app.view_mut() { + view.channel_passwords.insert(channel, "guess".into()); + } + app.join_failed(session, channel, JoinFailure::Password); + } else { + app.join_channel(session, channel); + } +} + const DEMO: i64 = 9001; fn channel(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo { diff --git a/crates/voelin-ui/src/members.rs b/crates/voelin-ui/src/members.rs index 4aa3b2a..2023eed 100644 --- a/crates/voelin-ui/src/members.rs +++ b/crates/voelin-ui/src/members.rs @@ -6,7 +6,7 @@ use slint::ComponentHandle; use voelin_core::{Command, Contact, Relation}; use voelin_model::ChatTarget; -use crate::app::{App, Bridge, MemberCard}; +use crate::app::{App, Bridge, MemberCard, Nav}; use crate::settings::ClientPlayback; use crate::vm; @@ -96,14 +96,7 @@ impl App { self.open_member(-1); self.watch_client(client_id); } - "poke" => { - self.command(|session| Command::Poke { - session, - client: client_id, - message: String::new(), - }); - self.set_status(format!("Poked {nickname}")); - } + "poke" => self.ask_poke(id, client_id), "friend" | "blocked" => { let Some(uid) = uid else { return }; let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked }; @@ -126,6 +119,30 @@ impl App { } } + /// Open the poke dialog for a client (the member card, a contact). + pub(crate) fn ask_poke(&mut self, session: i64, client: u16) { + let Some(view) = self.sessions.get(&session) else { return }; + let name = view.nickname(client); + self.poke_target = Some((session, client, name.clone())); + let Some(ui) = self.ui.upgrade() else { return }; + let nav = ui.global::