feat(session): nommer les appareils, côté spectateur et côté hôte
CI / Formatting, tests and builds (push) Successful in 3m24s
CI / Formatting, tests and builds (push) Successful in 3m24s
Le viewer propose un nom tiré de l'appareil et du navigateur (iPad Safari, Android Chrome), modifiable dans son pied de page, gardé par le navigateur et envoyé tout de suite à l'hôte (message rename). L'ancien nom par défaut, écrit en dur en français, disparaît. L'hôte peut donner son propre nom à un appareil, en ligne dans la liste des spectateurs: il prime, il est gardé dans les réglages (aliases) et survit à un redémarrage, et un clic rend le nom annoncé. Les deux côtés nettoient le nom de la même façon (caractères de contrôle retirés, espaces resserrés, 40 caractères au plus). Le balisage reste du texte, affiché tel quel. Refs #36, #37 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
aee5dde679
commit
4e2298aa6c
26 files changed
+557
-23
No files matched your search
@@ -97,6 +97,15 @@ async fn switch_source(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn rename_device(
|
||||
host: State<'_, Host>,
|
||||
connection: u64,
|
||||
alias: Option<String>,
|
||||
) -> 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,
|
||||
|
||||
@@ -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))}
|
||||
/>
|
||||
) : (
|
||||
<SourcePicker
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { DeviceId } from "../../../viewer/src/proto/DeviceId";
|
||||
|
||||
/**
|
||||
* The host's name for a device (#37).
|
||||
*/
|
||||
export type DeviceAlias = { id: DeviceId, name: string, };
|
||||
@@ -2,6 +2,7 @@
|
||||
import type { QualityPreset } from "../../../viewer/src/proto/QualityPreset";
|
||||
import type { CloseAction } from "./CloseAction";
|
||||
import type { Codec } from "./Codec";
|
||||
import type { DeviceAlias } from "./DeviceAlias";
|
||||
import type { Theme } from "./Theme";
|
||||
import type { TrustedDevice } from "./TrustedDevice";
|
||||
|
||||
@@ -50,4 +51,9 @@ autostart: boolean, close_action: CloseAction,
|
||||
/**
|
||||
* Ask for confirmation before quitting during a share (#43).
|
||||
*/
|
||||
confirm_quit: boolean, trusted_devices: Array<TrustedDevice>, };
|
||||
confirm_quit: boolean, trusted_devices: Array<TrustedDevice>,
|
||||
/**
|
||||
* Names the host gave to devices, by device id (#37). They win over the
|
||||
* name a viewer announces, and survive a restart.
|
||||
*/
|
||||
aliases: Array<DeviceAlias>, };
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -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) {
|
||||
<ul className='devices'>
|
||||
{share.devices.map((device) => (
|
||||
<li key={device.connection}>
|
||||
<span className='device-name'>
|
||||
{device.name}
|
||||
{device.trusted && <span className='trusted-mark'>{t('trusted')}</span>}
|
||||
</span>
|
||||
<DeviceLabel device={device} onRename={onRename} />
|
||||
<span className='muted'>
|
||||
{[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<string | null>(null);
|
||||
if (draft !== null) {
|
||||
const commit = () => {
|
||||
const alias = draft.trim();
|
||||
setDraft(null);
|
||||
if (alias !== device.name) onRename(device.connection, alias || null);
|
||||
};
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<input
|
||||
// biome-ignore lint/a11y/noAutofocus: the field opens on the user's click.
|
||||
autoFocus
|
||||
aria-label={t('rename')}
|
||||
value={draft}
|
||||
maxLength={40}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
if (e.key === 'Escape') setDraft(null);
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className='device-name'>
|
||||
<button
|
||||
type='button'
|
||||
className='link-button'
|
||||
title={t('renameHelp')}
|
||||
onClick={() => setDraft(device.name)}
|
||||
>
|
||||
{device.name}
|
||||
</button>
|
||||
{device.trusted && <span className='trusted-mark'>{t('trusted')}</span>}
|
||||
{device.aliased && (
|
||||
<button
|
||||
type='button'
|
||||
className='link-button muted alias-reset'
|
||||
title={t('aliasResetHelp')}
|
||||
onClick={() => onRename(device.connection, null)}
|
||||
>
|
||||
{t('aliasReset', { name: device.announced })}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The current time, refreshed every second for the displayed durations. */
|
||||
function useNow(): number {
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
@@ -27,6 +27,8 @@ export type Host = {
|
||||
trustDevice(connection: number): Promise<void>;
|
||||
/** Stops trusting a key; a device connected with it is sent away. */
|
||||
revokeDevice(key: string): Promise<void>;
|
||||
/** The host's name for a device (#37); `null` gives back the announced one. */
|
||||
renameDevice(connection: number, alias: string | null): Promise<void>;
|
||||
/** Shares another source without cutting viewers off (#26). */
|
||||
switchSource(choice: SourceChoice): Promise<void>;
|
||||
settings(): Promise<Settings>;
|
||||
@@ -53,6 +55,7 @@ export const tauriHost: Host = {
|
||||
trustDevice: (connection) => invoke<void>('trust_device', { connection }),
|
||||
revokeDevice: (key) => invoke<void>('revoke_device', { key }),
|
||||
switchSource: (choice) => invoke<void>('switch_source', { choice }),
|
||||
renameDevice: (connection, alias) => invoke<void>('rename_device', { connection, alias }),
|
||||
settings: () => invoke<Settings>('settings'),
|
||||
updateSettings: (settings) => invoke<SettingsOutcome>('update_settings', { settings }),
|
||||
interfaces: () => invoke<InterfaceOption[]>('interfaces'),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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() {
|
||||
|
||||
<footer className='footer' {...hold}>
|
||||
<StatsBar stats={stats} />
|
||||
<DeviceName onRename={(name) => sessionRef.current?.rename(name)} />
|
||||
<LanguagePicker />
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
@@ -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 (
|
||||
<span className='device-name'>
|
||||
<label htmlFor={id} className='visually-hidden'>
|
||||
{t('deviceName')}
|
||||
</label>
|
||||
<input
|
||||
id={id}
|
||||
value={name}
|
||||
placeholder={suggestion}
|
||||
maxLength={NAME_MAX}
|
||||
title={t('deviceNameHelp')}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') e.currentTarget.blur();
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -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<string, string>();
|
||||
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('<b>Kitchen</b>')).toBe('<b>Kitchen</b>');
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
|
||||
@@ -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" };
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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::<Vec<_>>()
|
||||
.join(" ")
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.take(DEVICE_NAME_MAX)
|
||||
.collect::<String>()
|
||||
.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("<b>Kitchen</b>"), "<b>Kitchen</b>");
|
||||
assert_eq!(clean_name(&"é".repeat(60)).chars().count(), DEVICE_NAME_MAX);
|
||||
assert_eq!(clean_name(" "), "");
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
) -> 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<LocalNameInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@@ -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<String>,
|
||||
pub address: String,
|
||||
/// Arrival, in Unix milliseconds.
|
||||
|
||||
@@ -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<rs_session::HostState>,
|
||||
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: " <b>Kitchen</b>\n iPad ".into(),
|
||||
};
|
||||
ws.send(Message::text(serde_json::to_string(&rename).unwrap()))
|
||||
.await
|
||||
.unwrap();
|
||||
let renamed = named(&mut states, "<b>Kitchen</b> 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, "<b>Kitchen</b> 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, "<b>Kitchen</b> 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() {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -739,6 +739,15 @@ async fn handle_socket(mut socket: WebSocket, state: Arc<AppState>, 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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -164,6 +164,26 @@ pub struct Settings {
|
||||
pub confirm_quit: bool,
|
||||
#[serde(alias = "appareils_confiance")]
|
||||
pub trusted_devices: Vec<TrustedDevice>,
|
||||
/// 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<DeviceAlias>,
|
||||
}
|
||||
|
||||
/// 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: "<b>Salon</b>".into(),
|
||||
}],
|
||||
..Settings::default()
|
||||
};
|
||||
store.save(&settings).unwrap();
|
||||
|
||||
+9
-1
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user