diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 77a8989..a3fbc15 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -97,6 +97,15 @@ async fn switch_source( Ok(()) } +#[tauri::command] +async fn rename_device( + host: State<'_, Host>, + connection: u64, + alias: Option, +) -> Result<(), Notice> { + host.rename_device(connection, alias).await +} + #[tauri::command] async fn revoke_device(host: State<'_, Host>, key: String) -> Result<(), Notice> { host.revoke_device(&key).await @@ -283,6 +292,7 @@ fn main() { regenerate_access, trust_device, revoke_device, + rename_device, switch_source, translate_tray, quit, diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 1dc0188..bd11713 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -149,6 +149,7 @@ function Shell({ host, onLanguage }: { host: Host; onLanguage: (code: string | n onDisconnect={(connection) => send(() => host.disconnect(connection))} onNewCode={() => send(() => host.regenerateAccess())} onTrust={(connection) => send(() => host.trustDevice(connection))} + onRename={(connection, alias) => send(() => host.renameDevice(connection, alias))} /> ) : ( , }; +confirm_quit: boolean, trusted_devices: Array, +/** + * Names the host gave to devices, by device id (#37). They win over the + * name a viewer announces, and survive a restart. + */ +aliases: Array, }; diff --git a/apps/desktop/src/bindings/ViewerDevice.ts b/apps/desktop/src/bindings/ViewerDevice.ts index 24a8094..0a59360 100644 --- a/apps/desktop/src/bindings/ViewerDevice.ts +++ b/apps/desktop/src/bindings/ViewerDevice.ts @@ -7,7 +7,17 @@ export type ViewerDevice = { /** * Number to send back to disconnect it. */ -connection: number, name: string, platform: string | null, address: string, +connection: number, +/** + * The name to show: the host's alias if it gave one (#37), otherwise the + * name the viewer announces (#36). Plain text, markup included. + */ +name: string, +/** + * The name the viewer announces, to show next to an alias and to go + * back to. + */ +announced: string, aliased: boolean, platform: string | null, address: string, /** * Arrival, in Unix milliseconds. */ diff --git a/apps/desktop/src/components/SharePanel.tsx b/apps/desktop/src/components/SharePanel.tsx index 4644470..1ca5942 100644 --- a/apps/desktop/src/components/SharePanel.tsx +++ b/apps/desktop/src/components/SharePanel.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react'; import type { Share } from '../bindings/Share'; +import type { ViewerDevice } from '../bindings/ViewerDevice'; import { useI18n } from '../i18n'; import { displayCode, displayName, duration, expiry } from '../lib/view'; @@ -8,9 +9,10 @@ type Props = { onDisconnect: (connection: number) => void; onNewCode: () => void; onTrust: (connection: number) => void; + onRename: (connection: number, alias: string | null) => void; }; -export function SharePanel({ share, onDisconnect, onNewCode, onTrust }: Props) { +export function SharePanel({ share, onDisconnect, onNewCode, onTrust, onRename }: Props) { const { t } = useI18n(); const now = useNow(); const [copied, setCopied] = useState(false); @@ -120,10 +122,7 @@ export function SharePanel({ share, onDisconnect, onNewCode, onTrust }: Props) {
    {share.devices.map((device) => (
  • - - {device.name} - {device.trusted && {t('trusted')}} - + {[device.platform, device.address].filter(Boolean).join(' · ')} {' · '} @@ -178,6 +177,69 @@ export function SharePanel({ share, onDisconnect, onNewCode, onTrust }: Props) { ); } +/** + * The device name, renamed in place by the host (#37). React renders it as + * text: a name with markup shows as typed. An alias shows the announced name + * next to it, with the way back to it. + */ +function DeviceLabel({ + device, + onRename, +}: { + device: ViewerDevice; + onRename: (connection: number, alias: string | null) => void; +}) { + const { t } = useI18n(); + const [draft, setDraft] = useState(null); + if (draft !== null) { + const commit = () => { + const alias = draft.trim(); + setDraft(null); + if (alias !== device.name) onRename(device.connection, alias || null); + }; + return ( + + setDraft(e.target.value)} + onBlur={commit} + onKeyDown={(e) => { + if (e.key === 'Enter') e.currentTarget.blur(); + if (e.key === 'Escape') setDraft(null); + }} + /> + + ); + } + return ( + + + {device.trusted && {t('trusted')}} + {device.aliased && ( + + )} + + ); +} + /** The current time, refreshed every second for the displayed durations. */ function useNow(): number { const [now, setNow] = useState(() => Date.now()); diff --git a/apps/desktop/src/lib/host.ts b/apps/desktop/src/lib/host.ts index 46c2c04..74b44be 100644 --- a/apps/desktop/src/lib/host.ts +++ b/apps/desktop/src/lib/host.ts @@ -27,6 +27,8 @@ export type Host = { trustDevice(connection: number): Promise; /** Stops trusting a key; a device connected with it is sent away. */ revokeDevice(key: string): Promise; + /** The host's name for a device (#37); `null` gives back the announced one. */ + renameDevice(connection: number, alias: string | null): Promise; /** Shares another source without cutting viewers off (#26). */ switchSource(choice: SourceChoice): Promise; settings(): Promise; @@ -53,6 +55,7 @@ export const tauriHost: Host = { trustDevice: (connection) => invoke('trust_device', { connection }), revokeDevice: (key) => invoke('revoke_device', { key }), switchSource: (choice) => invoke('switch_source', { choice }), + renameDevice: (connection, alias) => invoke('rename_device', { connection, alias }), settings: () => invoke('settings'), updateSettings: (settings) => invoke('update_settings', { settings }), interfaces: () => invoke('interfaces'), diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index aca3652..1a36ac6 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -466,6 +466,29 @@ h2 { font-weight: 600; } +.link-button { + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; + text-align: left; + cursor: text; +} + +.alias-reset { + margin-left: 0.5rem; + font-size: 0.8rem; + font-weight: 400; + text-decoration: underline; + cursor: pointer; +} + +.device-name input { + font: inherit; + padding: 0.1rem 0.3rem; +} + .trusted-mark { margin-left: 0.5rem; color: var(--live); diff --git a/apps/viewer/src/App.tsx b/apps/viewer/src/App.tsx index fbb93bd..cfba949 100644 --- a/apps/viewer/src/App.tsx +++ b/apps/viewer/src/App.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { DeviceName } from './components/DeviceName'; import { ErrorPanel } from './components/ErrorPanel'; import { LanguagePicker } from './components/LanguagePicker'; import { Pairing } from './components/Pairing'; @@ -295,6 +296,7 @@ export function App() {
    + sessionRef.current?.rename(name)} />
    diff --git a/apps/viewer/src/components/DeviceName.tsx b/apps/viewer/src/components/DeviceName.tsx new file mode 100644 index 0000000..3e854b9 --- /dev/null +++ b/apps/viewer/src/components/DeviceName.tsx @@ -0,0 +1,48 @@ +import { useId, useState } from 'react'; + +import { useI18n } from '../i18n'; +import { NAME_MAX, readName, saveName, suggestedName } from '../lib/deviceName'; + +type Props = { + /** The name changed: the session tells the host. */ + onRename: (name: string) => void; +}; + +/** + * The name of this device, as the host sees it (#36). Kept by the browser; + * empty, it goes back to the suggestion. React shows it as text: markup typed + * here stays visible as typed. + */ +export function DeviceName({ onRename }: Props) { + const { t } = useI18n(); + const id = useId(); + const suggestion = suggestedName(navigator.userAgent); + const [name, setName] = useState(() => readName() ?? ''); + + const commit = () => { + saveName(name); + const kept = readName() ?? ''; + setName(kept); + onRename(kept || suggestion); + }; + + return ( + + + setName(e.target.value)} + onBlur={commit} + onKeyDown={(e) => { + if (e.key === 'Enter') e.currentTarget.blur(); + }} + /> + + ); +} diff --git a/apps/viewer/src/lib/deviceName.test.ts b/apps/viewer/src/lib/deviceName.test.ts new file mode 100644 index 0000000..d3e6ee5 --- /dev/null +++ b/apps/viewer/src/lib/deviceName.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest'; + +import { cleanName, NAME_MAX, readName, saveName, suggestedName } from './deviceName'; + +function memory() { + const map = new Map(); + return { + getItem: (k: string) => map.get(k) ?? null, + setItem: (k: string, v: string) => void map.set(k, v), + removeItem: (k: string) => void map.delete(k), + }; +} + +describe('device name (#36)', () => { + it('is cleaned like the host does, markup kept as text', () => { + expect(cleanName(' iPad\tdu\n salon ')).toBe('iPad du salon'); + expect(cleanName('Kitchen')).toBe('Kitchen'); + expect(cleanName('é'.repeat(60))).toHaveLength(NAME_MAX); + }); + + it('is suggested from the device and the browser', () => { + const ipad = + 'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1'; + expect(suggestedName(ipad)).toBe('iPad Safari'); + const pixel = + 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36'; + expect(suggestedName(pixel)).toBe('Android Chrome'); + expect( + suggestedName('Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0'), + ).toBe('Linux Firefox'); + }); + + it('is kept, and an empty one goes back to the suggestion', () => { + const storage = memory(); + expect(readName(storage)).toBeNull(); + saveName(' Salon ', storage); + expect(readName(storage)).toBe('Salon'); + saveName(' ', storage); + expect(readName(storage)).toBeNull(); + }); +}); diff --git a/apps/viewer/src/lib/deviceName.ts b/apps/viewer/src/lib/deviceName.ts new file mode 100644 index 0000000..9493187 --- /dev/null +++ b/apps/viewer/src/lib/deviceName.ts @@ -0,0 +1,78 @@ +/** + * The name this device gives itself (#36): chosen by the user, kept by the + * browser, suggested from the device and the browser until then. + * + * The host may give its own name to the device (#37): that one shows on the + * host side, this one stays the device's choice. The name is text: the host + * cleans it the same way (`rs_proto::clean_name`), and every interface shows + * markup literally. + */ +import { browserStorage, type KeyValueStore } from './storage'; + +const KEY = 'rustscreen.name'; +/** `rs_proto::DEVICE_NAME_MAX`. */ +export const NAME_MAX = 40; + +/** Same rule as the host: control characters out, spaces collapsed, 40 at most. */ +export function cleanName(raw: string): string { + return Array.from( + raw + // biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point. + .split(/[\s\u0000-\u001f\u007f-\u009f]+/) + .filter(Boolean) + .join(' '), + ) + .slice(0, NAME_MAX) + .join('') + .trimEnd(); +} + +/** A name from the device and the browser: proper nouns, readable in any language. */ +export function suggestedName(userAgent: string): string { + const device = /iPad/.test(userAgent) + ? 'iPad' + : /iPhone/.test(userAgent) + ? 'iPhone' + : /Android/.test(userAgent) + ? 'Android' + : /CrOS/.test(userAgent) + ? 'Chromebook' + : /Mac OS X|Macintosh/.test(userAgent) + ? 'Mac' + : /Windows/.test(userAgent) + ? 'Windows' + : /Linux/.test(userAgent) + ? 'Linux' + : ''; + const browser = /Edg\//.test(userAgent) + ? 'Edge' + : /Firefox\//.test(userAgent) + ? 'Firefox' + : /Chrome\//.test(userAgent) + ? 'Chrome' + : /Safari\//.test(userAgent) + ? 'Safari' + : ''; + return [device, browser].filter(Boolean).join(' '); +} + +/** The name the user chose, `null` if none. */ +export function readName(storage: KeyValueStore | null = browserStorage()): string | null { + try { + const name = cleanName(storage?.getItem(KEY) ?? ''); + return name || null; + } catch { + return null; + } +} + +/** Keeps the chosen name; an empty one goes back to the suggestion. */ +export function saveName(name: string, storage: KeyValueStore | null = browserStorage()): void { + try { + const clean = cleanName(name); + if (clean) storage?.setItem(KEY, clean); + else storage?.removeItem(KEY); + } catch { + // Private browsing: the name holds for this page only. + } +} diff --git a/apps/viewer/src/lib/session.ts b/apps/viewer/src/lib/session.ts index d935a05..b8b512d 100644 --- a/apps/viewer/src/lib/session.ts +++ b/apps/viewer/src/lib/session.ts @@ -17,6 +17,7 @@ import type { } from '../proto'; import type { Translate } from './i18n'; import { deviceId } from './device'; +import { cleanName, readName, suggestedName } from './deviceName'; import { type WakeReason, watchLifecycle } from './lifecycle'; import { type DeviceKey, deviceKey, rememberTrust } from './trust'; @@ -419,6 +420,12 @@ export class ViewerSession { } } + /** Tells the host the new name of this device (#36), right away if connected. */ + rename(name: string): void { + const clean = cleanName(name) || suggestedName(navigator.userAgent); + this.send({ type: 'rename', name: clean } as ClientMessage); + } + private send(message: ClientMessage): void { if (this.ws?.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(message)); @@ -526,10 +533,7 @@ export type VideoStats = { * `hello` and displayed by the host, kept as they were. */ function defaultDeviceName(): string { - const ua = navigator.userAgent; - if (/iPad|Tablet/i.test(ua)) return 'Tablette'; - if (/Mobile|Android/i.test(ua)) return 'Téléphone'; - return 'Navigateur'; + return readName() ?? suggestedName(navigator.userAgent); } async function waitForIceGathering(pc: RTCPeerConnection, timeoutMs: number): Promise { diff --git a/apps/viewer/src/proto/ClientMessage.ts b/apps/viewer/src/proto/ClientMessage.ts index db4163e..5424433 100644 --- a/apps/viewer/src/proto/ClientMessage.ts +++ b/apps/viewer/src/proto/ClientMessage.ts @@ -11,4 +11,4 @@ export type ClientMessage = { "type": "hello", version: number, room: RoomId | n /** * Ed25519 public key of the device, 64 hex digits. Never the private key. */ -key: string | null, } | { "type": "proof", signature: string, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "bye" }; +key: string | null, } | { "type": "proof", signature: string, } | { "type": "offer", sdp: string, } | { "type": "ice_candidate", candidate: string, sdp_mid: string | null, sdp_mline_index: number | null, } | { "type": "quality_request", settings: StreamSettings, } | { "type": "rename", name: string, } | { "type": "bye" }; diff --git a/apps/viewer/src/styles.css b/apps/viewer/src/styles.css index db44f7e..01dcbba 100644 --- a/apps/viewer/src/styles.css +++ b/apps/viewer/src/styles.css @@ -257,8 +257,24 @@ body { } /* Language picker (#21): discreet, at the end of the footer. */ -.language { +.device-name { margin-left: auto; + padding-left: 1rem; +} + +.device-name input { + width: 11rem; + max-width: 40vw; + padding: 0.25rem 0.4rem; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--surface); + color: var(--fg); + font: inherit; + font-size: 0.82rem; +} + +.language { padding: 0 1rem; } diff --git a/crates/rs-proto/src/lib.rs b/crates/rs-proto/src/lib.rs index 1c97732..a961c3d 100644 --- a/crates/rs-proto/src/lib.rs +++ b/crates/rs-proto/src/lib.rs @@ -11,8 +11,8 @@ pub mod trust; pub use messages::{ClientMessage, ErrorCode, ServerMessage}; pub use pairing::{LINK_VERSION, PairingRequest, PairingResponse, normalize_code}; pub use session::{ - DeviceId, DeviceInfo, QualityPreset, RoomId, SessionToken, SourceId, SourceInfo, SourceKind, - StreamSettings, + DEVICE_NAME_MAX, DeviceId, DeviceInfo, QualityPreset, RoomId, SessionToken, SourceId, + SourceInfo, SourceKind, StreamSettings, clean_name, }; /// Protocol version, negotiated in `hello`. diff --git a/crates/rs-proto/src/messages.rs b/crates/rs-proto/src/messages.rs index fac5009..59ee43a 100644 --- a/crates/rs-proto/src/messages.rs +++ b/crates/rs-proto/src/messages.rs @@ -75,6 +75,9 @@ pub enum ClientMessage { }, /// Request to change the quality preset. QualityRequest { settings: StreamSettings }, + /// The viewer renamed this device (#36). The host's alias, if any, still + /// wins in its own interface. + Rename { name: String }, /// Voluntary leave, to free the slot without waiting for the timeout. Bye, } diff --git a/crates/rs-proto/src/session.rs b/crates/rs-proto/src/session.rs index a785d5c..c9395ec 100644 --- a/crates/rs-proto/src/session.rs +++ b/crates/rs-proto/src/session.rs @@ -118,6 +118,26 @@ pub struct SourceInfo { #[ts(export, type = "string")] pub struct DeviceId(pub String); +/// Longest device name kept, in characters (#36). The viewer's field has the +/// same `maxLength`. +pub const DEVICE_NAME_MAX: usize = 40; + +/// A device name as the host keeps it: control characters removed, spaces +/// collapsed, at most [`DEVICE_NAME_MAX`] characters. Markup is not removed: +/// it is text, and every interface displays it as such (#36). +pub fn clean_name(raw: &str) -> String { + raw.split(|c: char| c.is_whitespace() || c.is_control()) + .filter(|part| !part.is_empty()) + .collect::>() + .join(" ") + .chars() + .filter(|c| !c.is_control()) + .take(DEVICE_NAME_MAX) + .collect::() + .trim_end() + .to_string() +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] #[ts(export)] pub struct DeviceInfo { @@ -204,3 +224,18 @@ mod tests { assert!(sharp.max_fps > saver.max_fps); } } + +#[cfg(test)] +mod name_tests { + use super::*; + + #[test] + fn a_name_is_cleaned_not_escaped() { + assert_eq!(clean_name(" iPad\tdu\n salon "), "iPad du salon"); + assert_eq!(clean_name("a\u{7}b"), "a b"); + // Markup stays text: displaying it literally is the interfaces' job. + assert_eq!(clean_name("Kitchen"), "Kitchen"); + assert_eq!(clean_name(&"é".repeat(60)).chars().count(), DEVICE_NAME_MAX); + assert_eq!(clean_name(" "), ""); + } +} diff --git a/crates/rs-session/src/host.rs b/crates/rs-session/src/host.rs index a8f5fd3..04482f0 100644 --- a/crates/rs-session/src/host.rs +++ b/crates/rs-session/src/host.rs @@ -19,7 +19,7 @@ use rs_codec::{LiveSource, SharedMedia}; use rs_platform::{Environment, Inhibition, PortalInfo, SessionType}; use rs_proto::StreamSettings; use rs_signaling::{HostConfig, Room, ServerError, TlsMaterial}; -use rs_store::{Notice, Origin, Rejection, Settings, Store, TrustedDevice}; +use rs_store::{DeviceAlias, Notice, Origin, Rejection, Settings, Store, TrustedDevice}; use tokio::sync::{oneshot, watch}; use tokio::task::JoinHandle; @@ -382,6 +382,41 @@ impl Host { .map_err(|rejections| joined(&rejections)) } + /// Names a device from the host (#37), or gives it back the name it + /// announces (`None`, or an empty name). Applied at once, kept across + /// restarts, and it wins over the viewer's own choice. + pub async fn rename_device( + &self, + connection: u64, + alias: Option, + ) -> Result<(), Notice> { + let room = lock(&self.0.view).as_ref().map(|v| v.room.clone()); + let device = room + .and_then(|room| room.device(connection)) + .ok_or_else(|| Notice::new("viewer_gone", "this viewer is no longer connected"))?; + if device.id.is_empty() { + return Err(Notice::new( + "no_device_id", + "this browser keeps no identifier: its name cannot be remembered", + )); + } + let alias = alias + .map(|a| rs_proto::clean_name(&a)) + .filter(|a| !a.is_empty()); + let mut settings = self.settings(); + settings.aliases.retain(|a| a.id.0 != device.id); + if let Some(name) = alias { + settings.aliases.push(DeviceAlias { + id: rs_proto::DeviceId(device.id), + name, + }); + } + self.update_settings(settings) + .await + .map(|_| ()) + .map_err(|rejections| joined(&rejections)) + } + /// Stops trusting a key. A device connected with it is sent away at once /// (#34); one connected by a link stays until it leaves. pub async fn revoke_device(&self, key: &str) -> Result<(), Notice> { @@ -516,6 +551,7 @@ impl Host { change("autostart", new.autostart != old.autostart, None); let trust_changed = new.trusted_devices != old.trusted_devices; change("trusted_devices", trust_changed, None); + change("aliases", new.aliases != old.aliases, None); if trust_changed && let Some(room) = &room { let sent_away = room.set_trusted(trusted_keys(&new)); tracing::info!( @@ -914,10 +950,11 @@ impl Host { let inner = &self.0; let state = { let base = lock(&inner.base); + let aliases = lock(&inner.settings).aliases.clone(); let mut view = lock(&inner.view); HostState { phase: base.phase.unwrap_or(Phase::Stopped), - share: view.as_mut().map(describe), + share: view.as_mut().map(|view| describe(view, &aliases)), error: base.error.clone(), stop: base.stop.clone(), warnings: base.warnings.clone(), @@ -968,7 +1005,7 @@ fn local_name(view: &mut View) -> Option { }) } -fn describe(view: &mut View) -> Share { +fn describe(view: &mut View, aliases: &[DeviceAlias]) -> Share { let local_name = local_name(view); let advertised = (!view.listen.ip().is_unspecified()).then_some(view.listen.ip()); let url = rs_signaling::session_url( @@ -1014,9 +1051,15 @@ fn describe(view: &mut View) -> Share { .key .as_deref() .is_some_and(|key| view.room.trusted_name(key).is_some()); + let alias = aliases + .iter() + .find(|a| !d.id.is_empty() && a.id.0 == d.id) + .map(|a| a.name.clone()); ViewerDevice { connection: d.connection, - name: d.name, + name: alias.clone().unwrap_or_else(|| d.name.clone()), + announced: d.name, + aliased: alias.is_some(), platform: d.platform, address: d.address.to_string(), since_ms: d.since_ms, diff --git a/crates/rs-session/src/state.rs b/crates/rs-session/src/state.rs index 187807d..c6781ac 100644 --- a/crates/rs-session/src/state.rs +++ b/crates/rs-session/src/state.rs @@ -160,7 +160,13 @@ pub struct ViewerDevice { /// Number to send back to disconnect it. #[ts(type = "number")] pub connection: u64, + /// The name to show: the host's alias if it gave one (#37), otherwise the + /// name the viewer announces (#36). Plain text, markup included. pub name: String, + /// The name the viewer announces, to show next to an alias and to go + /// back to. + pub announced: String, + pub aliased: bool, pub platform: Option, pub address: String, /// Arrival, in Unix milliseconds. diff --git a/crates/rs-session/tests/host.rs b/crates/rs-session/tests/host.rs index d43eb41..da2fb0a 100644 --- a/crates/rs-session/tests/host.rs +++ b/crates/rs-session/tests/host.rs @@ -340,6 +340,69 @@ async fn switching_source_keeps_the_viewer_and_tells_it() { host.stop().await; } +#[tokio::test(flavor = "multi_thread")] +async fn the_host_name_for_a_device_wins_and_can_be_dropped() { + if no_network() { + return; + } + let (host, _dir) = host("alias", 0).await; + let mut states = host.subscribe(); + host.start(test_pattern()).await.expect("share"); + let (port, room, token) = identifiers(&host.state().share.unwrap().url); + let (mut ws, _) = viewer(port, &room, &token, "tablet").await; + let named = |states: &mut tokio::sync::watch::Receiver, + wanted: &'static str| { + let mut states = states.clone(); + async move { + tokio::time::timeout( + Duration::from_secs(3), + states.wait_for(|s| { + s.share + .as_ref() + .is_some_and(|p| p.devices.first().is_some_and(|d| d.name == wanted)) + }), + ) + .await + .unwrap_or_else(|_| panic!("name {wanted} expected")) + .unwrap() + .share + .clone() + .unwrap() + .devices[0] + .clone() + } + }; + let device = named(&mut states, "device tablet").await; + + // The viewer renames itself (#36): the host follows without a reconnection. + let rename = ClientMessage::Rename { + name: " Kitchen\n iPad ".into(), + }; + ws.send(Message::text(serde_json::to_string(&rename).unwrap())) + .await + .unwrap(); + let renamed = named(&mut states, "Kitchen iPad").await; + assert_eq!(renamed.connection, device.connection); + + // The host's name wins (#37), and is kept in the settings. + host.rename_device(device.connection, Some("Living room".into())) + .await + .expect("alias"); + let aliased = named(&mut states, "Living room").await; + assert!(aliased.aliased); + assert_eq!(aliased.announced, "Kitchen iPad"); + assert_eq!(host.settings().aliases.len(), 1); + + // Reset: the announced name comes back. + host.rename_device(device.connection, None) + .await + .expect("reset"); + let back = named(&mut states, "Kitchen iPad").await; + assert!(!back.aliased); + assert!(host.settings().aliases.is_empty()); + host.stop().await; +} + #[tokio::test(flavor = "multi_thread")] async fn stopping_tells_viewers_the_share_ended_and_frees_the_port() { if no_network() { diff --git a/crates/rs-signaling/src/room.rs b/crates/rs-signaling/src/room.rs index 8692e4d..072181b 100644 --- a/crates/rs-signaling/src/room.rs +++ b/crates/rs-signaling/src/room.rs @@ -493,6 +493,17 @@ impl Room { Registration { connection, kicked } } + /// The viewer renamed itself (#36): the host interface follows at once. + pub fn rename(&self, connection: u64, name: &str) { + if let Some(present) = lock(&self.present) + .iter_mut() + .find(|p| p.device.connection == connection) + { + present.device.name = name.to_string(); + } + self.notify(); + } + /// Removes a viewer that left, whatever the reason. pub fn unregister(&self, connection: u64) { lock(&self.present).retain(|p| p.device.connection != connection); diff --git a/crates/rs-signaling/src/server.rs b/crates/rs-signaling/src/server.rs index 34df006..dd3730e 100644 --- a/crates/rs-signaling/src/server.rs +++ b/crates/rs-signaling/src/server.rs @@ -739,6 +739,15 @@ async fn handle_socket(mut socket: WebSocket, state: Arc, peer: Socket tracing::debug!("trickled candidate ignored: the offer already carries the candidates"); } Ok(ClientMessage::Bye) => break Cause::Bye, + Ok(ClientMessage::Rename { name }) => { + // A device that came by its key keeps the host's + // name for it: the viewer's choice applies next + // time it comes by a link. + let name = rs_proto::clean_name(&name); + if !name.is_empty() && !by_key { + state.room.rename(connection, &name); + } + } Ok(ClientMessage::Proof { .. }) => { let _ = send(&mut socket, &error(ErrorCode::ProtocolViolation, "no challenge pending")).await; } @@ -887,10 +896,11 @@ pub enum ServerError { /// The default device name when the client does not provide one. pub fn device_name(device: &DeviceInfo) -> String { - if device.name.is_empty() { + let name = rs_proto::clean_name(&device.name); + if name.is_empty() { "device".to_string() } else { - device.name.clone() + name } } diff --git a/crates/rs-store/src/lib.rs b/crates/rs-store/src/lib.rs index 84e8d37..cc00e52 100644 --- a/crates/rs-store/src/lib.rs +++ b/crates/rs-store/src/lib.rs @@ -164,6 +164,26 @@ pub struct Settings { pub confirm_quit: bool, #[serde(alias = "appareils_confiance")] pub trusted_devices: Vec, + /// Names the host gave to devices, by device id (#37). They win over the + /// name a viewer announces, and survive a restart. + pub aliases: Vec, +} + +/// The host's name for a device (#37). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "../../../desktop/src/bindings/")] +pub struct DeviceAlias { + pub id: DeviceId, + pub name: String, +} + +impl DeviceAlias { + /// A device id, and a name already as `rs_proto::clean_name` leaves it. + pub fn is_valid(&self) -> bool { + !self.id.0.trim().is_empty() + && !self.name.is_empty() + && rs_proto::clean_name(&self.name) == self.name + } } impl Default for Settings { @@ -182,6 +202,7 @@ impl Default for Settings { close_action: CloseAction::default(), confirm_quit: true, trusted_devices: Vec::new(), + aliases: Vec::new(), } } } @@ -272,6 +293,15 @@ impl Settings { Notice::new("trusted_device_invalid", "a device without an identifier"), )); } + if self.aliases.iter().any(|a| !a.is_valid()) { + rejections.push(Rejection::new( + "aliases", + Notice::new( + "alias_invalid", + "a device name is empty, too long or has control characters", + ), + )); + } rejections } @@ -287,6 +317,7 @@ impl Settings { "limit" => self.limit = default.limit, "code_validity_min" => self.code_validity_min = default.code_validity_min, "trusted_devices" => self.trusted_devices.retain(|d| !d.id.0.trim().is_empty()), + "aliases" => self.aliases.retain(DeviceAlias::is_valid), _ => {} } } @@ -615,6 +646,7 @@ mod tests { key: String::new(), added_ms: 0, }], + aliases: Vec::new(), } } @@ -729,6 +761,10 @@ mod tests { key: "ab".repeat(32), added_ms: 1_761_800_000_000, }], + aliases: vec![DeviceAlias { + id: DeviceId("ipad".into()), + name: "Salon".into(), + }], ..Settings::default() }; store.save(&settings).unwrap(); diff --git a/locales/en.json b/locales/en.json index 67594e9..9cbdc80 100644 --- a/locales/en.json +++ b/locales/en.json @@ -55,6 +55,8 @@ "screen": "a screen", "window": "a window" }, + "deviceName": "Name of this device", + "deviceNameHelp": "The name the host sees. Empty: the suggestion.", "networkFallback": "Connection lost. Check that you are on the same network as the host.", "errors": { "bad_token": "This link matches no session on this host. Scan its QR code again, or type its short code.", @@ -120,6 +122,10 @@ "trust": "Trust", "trustHelp": "This device will come back without a QR code, to this share and the next ones. You can revoke it in the settings.", "trusted": "trusted", + "rename": "Name of this device", + "renameHelp": "Click to rename this device on this host. Empty: the name it announces.", + "aliasReset": "(it calls itself {name})", + "aliasResetHelp": "Go back to the name the device announces", "refused": "Refused connections", "refusedNone": "No connection refused since this share started.", "unknownDevice": "unnamed device", @@ -278,7 +284,9 @@ "source_not_found": "Source {id} not found.", "no_x11": "X11 capture only exists on Linux.", "no_virtual_display": "This desktop cannot create a virtual screen: share an existing screen.", - "no_window": "This desktop can only share an entire screen." + "no_window": "This desktop can only share an entire screen.", + "alias_invalid": "A device name is empty, too long or has control characters.", + "no_device_id": "This browser keeps no identifier: its name cannot be remembered." } } } diff --git a/locales/fr.json b/locales/fr.json index 50554bf..f0f118f 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -55,6 +55,8 @@ "screen": "un écran", "window": "une fenêtre" }, + "deviceName": "Nom de cet appareil", + "deviceNameHelp": "Le nom que voit l'hôte. Vide : la suggestion.", "networkFallback": "Connexion perdue. Vérifiez que vous êtes sur le même réseau que l’hôte.", "errors": { "bad_token": "Ce lien ne correspond à aucune session de cet hôte. Scannez à nouveau son QR code, ou tapez son code court.", @@ -120,6 +122,10 @@ "trust": "Faire confiance", "trustHelp": "Cet appareil reviendra sans QR code, à ce partage et aux suivants. Vous pouvez le révoquer dans les réglages.", "trusted": "de confiance", + "rename": "Nom de cet appareil", + "renameHelp": "Cliquer pour renommer cet appareil sur cet hôte. Vide : le nom qu'il annonce.", + "aliasReset": "(il s'appelle {name})", + "aliasResetHelp": "Revenir au nom que l'appareil annonce", "refused": "Connexions refusées", "refusedNone": "Aucune connexion refusée depuis le début du partage.", "unknownDevice": "appareil sans nom", @@ -278,7 +284,9 @@ "source_not_found": "Source {id} introuvable.", "no_x11": "La capture X11 n'existe que sous Linux.", "no_virtual_display": "Ce bureau ne sait pas créer d'écran virtuel : partagez un écran existant.", - "no_window": "Ce bureau ne sait partager qu'un écran entier." + "no_window": "Ce bureau ne sait partager qu'un écran entier.", + "alias_invalid": "Un nom d'appareil est vide, trop long ou contient des caractères de contrôle.", + "no_device_id": "Ce navigateur ne garde pas d'identifiant : son nom ne peut pas être retenu." } } }