rob-revisited/ide/ui/js/screen-share.js

211 lines
11 KiB
JavaScript

// "Screen on a phone" (docs/ide-screen.md): this computer's screen, live, in the JumPHP Screen app (a phone's browser), with the mouse
// and the keyboard. Like VNC, but WebRTC: H.264 from the GPU, peer to peer (the LAN when the phone is on it), ~1 frame of latency.
// - the pixels and the input never go through a server: the sidecar of jumphp/webrtc (ide/src/Remote/ScreenHost.php) is the peer
// - the signaling (offer / answer / ICE) goes through the IDE Remote relay, end-to-end encrypted (remote/channel.js, its own pairing)
// - consent on this computer for every device, Stop at any time. Separate from IDE Remote (the screen icon): its own room and key.
import { backend } from './backend.js';
import { copyText, dialog, el, notify, prefs, t } from './ui.js';
import { relayUrl } from './remote-host.js';
import { qrSvg } from './remote/qr.js';
/** The viewer (JumPHP Screen, published on jumphp.net); the pairing goes in the fragment (never sent to a server). */
export const SCREEN_APP_URL = 'https://play.jumphp.net/jumphp-screen/play/';
const STUN = 'stun://stun.l.google.com:19302';
const QUALITIES = {
fast: { label: 'Fast (1280 px, 60 fps, 4 Mb/s)', width: 1280, fps: 60, kbps: 4000 },
balanced: { label: 'Balanced (1920 px, 60 fps, 8 Mb/s)', width: 1920, fps: 60, kbps: 8000 },
sharp: { label: 'Sharp (full size, 60 fps, 16 Mb/s)', width: 0, fps: 60, kbps: 16000 },
saver: { label: 'Data saver (1280 px, 30 fps, 1.5 Mb/s)', width: 1280, fps: 30, kbps: 1500 },
};
const STATES = { asking: 'Waiting for your answer', new: 'Starting…', starting: 'Starting…', connecting: 'Connecting…', connected: 'Connected',
disconnected: 'Disconnected', failed: 'Connection failed', closed: 'Closed', stopped: 'Stopped', error: 'Error' };
const cleanName = (s) => String(s ?? '').replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 40) || 'Unknown device';
class ScreenShare {
constructor() {
this.active = false;
this.pairing = null;
this.channel = null;
this.devices = new Map(); // relay peer -> {name, ok, id, state}
this.listeners = new Set();
this.relayState = 'off';
this.how = '';
this.off = null;
this.quality = prefs.get('screenQuality', 'balanced');
}
onChange(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
changed() { for (const fn of [...this.listeners]) { try { fn(this); } catch (e) { console.error(e); } } }
link() { return this.active && this.mod ? this.mod.Channel.pairingUrl(SCREEN_APP_URL, { room: this.pairing.room, key: this.pairing.key }) : ''; }
async start(quality) {
if (this.active) return;
this.quality = QUALITIES[quality] ? quality : 'balanced';
prefs.set('screenQuality', this.quality);
this.mod = await import('./remote/channel.js');
this.pairing = await this.mod.Channel.newPairing();
const { Channel, relayTransport } = this.mod;
this.relayState = 'connecting';
const ch = await Channel.open({ role: 'host', key: this.pairing.key, transport: relayTransport({ url: relayUrl(), room: this.pairing.room, role: 'host' }) });
this.channel = ch;
this.active = true;
ch.on('open', () => { this.relayState = 'ready'; this.changed(); });
ch.on('close', () => { if (this.channel === ch && this.active) { this.relayState = 'connecting'; this.changed(); } });
ch.on('error', (e) => { if (e?.code === 'decrypt' || e?.code === 'json') return; this.relayState = 'error'; this.changed(); });
ch.on('peer', (info) => { if (info?.type === 'leave') this.drop(info.peer); });
ch.on('message', (msg, from) => this.onMessage(from, msg));
this.off = backend.on('screen.event', (e) => this.onSidecar(e));
this.changed();
}
stop() {
if (!this.active) return;
for (const [peer, dev] of this.devices) if (dev.ok) this.send(peer, { t: 'denied', reason: 'stopped' });
this.devices.clear();
backend.invoke('screen.stop').catch(() => {});
this.off?.();
this.off = null;
const ch = this.channel;
this.channel = null;
setTimeout(() => ch?.close(), 300);
this.active = false;
this.relayState = 'off';
this.changed();
}
send(peer, obj) { return this.channel?.send(obj, peer === undefined ? {} : { to: peer }).catch(() => {}); }
onMessage(peer, msg) {
if (!msg || typeof msg !== 'object') return;
let dev = this.devices.get(peer);
if (msg.t === 'hello') {
if (msg.app !== 'screen') { this.send(peer, { t: 'denied', reason: 'version' }); return; }
if (dev) return;
dev = { name: cleanName(msg.name), ok: false, id: 's' + peer + '-' + Math.random().toString(36).slice(2, 8), state: 'asking' };
this.devices.set(peer, dev);
this.changed();
this.ask(peer, dev);
return;
}
if (!dev?.ok) return;
if (msg.t === 'answer' && typeof msg.sdp === 'string' && msg.sdp.length < 100000) backend.invoke('screen.signal', { id: dev.id, type: 'answer', sdp: msg.sdp });
else if (msg.t === 'ice' && typeof msg.candidate === 'string' && msg.candidate.length < 1000) backend.invoke('screen.signal', { id: dev.id, candidate: msg.candidate, mline: msg.mline | 0 });
else if (msg.t === 'ping') this.send(peer, { t: 'pong' });
else if (msg.t === 'restart') this.openPeer(peer, dev);
else if (msg.t === 'bye') this.drop(peer);
}
ask(peer, dev) {
let answered = false;
const answer = (allow) => {
if (answered) return;
answered = true;
if (!this.active || this.devices.get(peer) !== dev) return;
if (!allow) { this.send(peer, { t: 'denied', reason: 'refused' }); this.devices.delete(peer); this.changed(); return; }
dev.ok = true;
this.openPeer(peer, dev);
};
dialog({
title: t('A device wants to see this screen'),
sticky: true,
body: el('div', {},
el('p', {}, t('Allow “{name}” to see your screen and use your mouse and keyboard?', { name: dev.name })),
el('p', {}, t('It sees everything on this screen, not only the IDE. Only allow a device you just paired yourself.'))),
buttons: [{ label: t('Deny'), action: () => answer(false) }, { label: t('Allow'), primary: true, action: () => answer(true) }],
onClose: () => answer(false),
});
}
async openPeer(peer, dev) {
const q = QUALITIES[this.quality];
dev.state = 'starting';
this.changed();
try {
await backend.invoke('screen.close', { id: dev.id }).catch(() => {});
const r = await backend.invoke('screen.open', { id: dev.id, fps: q.fps, kbps: q.kbps, width: q.width, stun: STUN });
this.how = r?.how || '';
this.send(peer, { t: 'welcome', v: 1, quality: this.quality, kbps: q.kbps });
notify(t('“{name}” sees this screen.', { name: dev.name }), 'info', { title: t('Screen on a phone') });
} catch (e) {
this.send(peer, { t: 'error', message: e.message || String(e) });
notify(e.message || String(e), 'error', { title: t('Screen on a phone') });
dev.state = 'error';
}
this.changed();
}
// the sidecar's events: to the device of that peer
onSidecar(e) {
if (e.ev === 'building') { notify(t('Preparing the screen streamer (first time only, a few minutes)…'), 'info', { title: t('Screen on a phone') }); return; }
if (e.ev === 'exit') { if (this.active) notify(e.message || 'stopped', 'error', { title: t('Screen on a phone') }); for (const d of this.devices.values()) d.state = 'stopped'; this.changed(); return; }
const found = [...this.devices].find(([, d]) => d.id === e.id);
if (!found) return;
const [peer, dev] = found;
if (e.ev === 'offer') this.send(peer, { t: 'offer', sdp: e.sdp });
else if (e.ev === 'ice') this.send(peer, { t: 'ice', candidate: e.candidate, mline: e.mline });
else if (e.ev === 'screen') this.send(peer, { t: 'info', encoder: e.encoder, width: e.width, height: e.height, how: this.how });
else if (e.ev === 'state') { dev.state = e.state; this.changed(); }
else if (e.ev === 'error') console.warn('[screen]', e.message);
}
drop(peer) {
const dev = this.devices.get(peer);
if (!dev) return;
this.devices.delete(peer);
if (dev.ok) backend.invoke('screen.close', { id: dev.id }).catch(() => {});
this.changed();
}
}
let shared = null;
export const screenShare = () => (shared ||= new ScreenShare());
/** The dialog of the header button: start, link + QR code, connected devices, stop. */
export function openScreenDialog() {
const host = screenShare();
const content = el('div.remote-share');
const dlg = dialog({ title: t('Screen on a phone'), body: content, buttons: [{ label: t('Close') }], wide: true, onClose: () => off() });
let probe = null;
const draw = () => {
content.textContent = '';
if (!host.active) {
const select = el('select.input', {}, ...Object.entries(QUALITIES).map(([id, q]) => el('option', { value: id }, t(q.label))));
select.value = host.quality;
const start = el('button.btn.primary', { onclick: async () => {
start.disabled = true;
try { await host.start(select.value); } catch (e) { notify(e.message || String(e), 'error', { title: t('Screen on a phone') }); start.disabled = false; }
} }, t('Start'));
content.append(
el('p', {}, t('See and drive this computer from a phone, in its browser: the screen as a live video, a touchpad, zoom, a keyboard. The video goes straight from this computer to the phone (WebRTC), on your network when the phone is on it.')),
el('h4', {}, t('Quality')), select);
if (probe && !probe.available) {
content.append(el('p.remote-status', {}, t('Not available on this computer: {reason}', { reason: probe.reason })));
start.disabled = true;
} else if (probe && !probe.native) {
content.append(el('p.remote-status', {}, t('GStreamer WebRTC is not installed here: the streamer runs in Docker (built the first time). For the lowest latency: sudo apt install gstreamer1.0-nice gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly python3-gi')));
}
content.append(el('div.remote-actions', {}, start));
return;
}
const link = host.link();
const qr = el('div.remote-qr');
try { qr.innerHTML = qrSvg(link, { margin: 2 }); } catch { qr.textContent = t('The link is too long for a QR code: copy it.'); }
const devices = [...host.devices.values()];
content.append(
el('p', {}, t('Scan this code with the phone. Keep it private: it holds the key.')),
el('div.remote-pair', {}, qr, el('div.remote-pair-side', {},
el('input.input.remote-link', { value: link, readonly: '', onfocus: (e) => e.target.select() }),
el('div.remote-actions', {}, el('button.btn.primary', { onclick: async () => { await copyText(link); notify(t('Link copied.'), 'success', { title: t('Screen on a phone') }); } }, t('Copy the link'))),
el('p.remote-status', {}, host.relayState === 'ready' ? t('Waiting for a device…') : t('Server: connecting…')))),
el('h4', {}, t('Connected devices')),
devices.length ? el('div.remote-devices', {}, ...devices.map((d) => el('div.remote-device', {}, el('span.remote-device-name', {}, `${d.name} · ${t(STATES[d.state] || 'Starting…')}`))))
: el('p.remote-status', {}, t('No device connected yet.')),
el('div.remote-actions', {}, el('button.btn.danger', { onclick: () => host.stop() }, t('Stop sharing'))));
};
const off = host.onChange(() => { if (content.isConnected) draw(); });
draw();
if (!host.active) backend.invoke('screen.probe').then((p) => { probe = p; if (content.isConnected) draw(); }).catch((e) => { probe = { available: false, reason: e.message || String(e) }; draw(); });
return dlg;
}