Files
Shade/packages/shade-media/src/browser/watch-app.ts

322 lines
12 KiB
TypeScript
Raw Normal View History

/**
* The watch page: open a capability link, play what it grants.
*
* /watch/#shade=<grant>
*
* A sealed file plays through the Service Worker in a native element —
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
* channel plays through MSE (video/audio) or as a scrolling log (text),
* with images replacing each other in place. An album shows its items as a
* grid; opening one pushes a view, and Back returns to the album.
*
* The grant never leaves the browser: it is in the fragment, which is not
* sent to the server, and the page drops it from the address bar once read.
*/
import { ALBUM_MIME, parseAlbum } from '../album.js';
import type { Album } from '../album.js';
import { fromCapabilityUrl } from '../grant.js';
import type { Grant, LiveGrant, MediaGrant } from '../grant.js';
import { LiveWatchClient } from '../live/client.js';
import type { ReceivedFrame } from '../live/channel.js';
import { installMediaWorker } from './index.js';
import type { MediaKeyring } from './index.js';
import { LivePlayer } from './player.js';
interface Stats {
kind: 'media' | 'live' | 'album' | 'none';
items?: number;
state: string;
mime?: string;
frames: number;
lines: number;
images: number;
error?: string;
player?: () => unknown;
}
const stats: Stats = { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 };
(globalThis as unknown as { __shade: Stats }).__shade = stats;
const $ = <T extends HTMLElement>(sel: string) => document.querySelector(sel) as T;
function setStatus(text: string, tone: 'ok' | 'warn' | 'bad' = 'ok'): void {
stats.state = text;
const el = $('#status');
el.textContent = text;
el.dataset.tone = tone;
}
function fail(message: string): void {
stats.error = message;
setStatus(message, 'bad');
}
function human(n: number): string {
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
while (n >= 1024 && i < u.length - 1) {
n /= 1024;
i++;
}
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
}
// ─── Views ──────────────────────────────────────────────────────
//
// A stack of views mirrored in the history, so Back leaves an item for its
// album. History entries hold only the depth: the grants stay in memory.
type View = () => Promise<void> | void;
const views: View[] = [];
let cleanups: (() => void)[] = [];
function reset(): void {
for (const c of cleanups) c();
cleanups = [];
const stage = $('#stage');
for (const m of stage.querySelectorAll('video, audio')) (m as HTMLMediaElement).pause();
stage.replaceChildren();
stage.className = '';
$('#actions').replaceChildren();
$('#sub').textContent = '';
Object.assign(stats, { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 });
delete stats.error;
delete stats.player;
delete stats.items;
}
async function render(view: View): Promise<void> {
reset();
if (views.length > 1) {
const back = document.createElement('a');
back.href = '#';
back.id = 'back';
back.textContent = '← Back';
back.addEventListener('click', (e) => {
e.preventDefault();
history.back();
});
$('#actions').append(back);
}
try {
await view();
} catch (e) {
fail(String((e as Error)?.message ?? e));
}
}
function push(view: View): Promise<void> {
views.push(view);
history.pushState({ depth: views.length - 1 }, '');
return render(view);
}
window.addEventListener('popstate', (e: PopStateEvent) => {
const depth = Math.min((e.state as { depth?: number } | null)?.depth ?? 0, views.length - 1);
views.length = depth + 1;
void render(views[depth]!);
});
let keyring: Promise<MediaKeyring> | null = null;
function ring(): Promise<MediaKeyring> {
keyring ??= installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
return keyring;
}
async function open(g: Grant): Promise<void> {
if (g.kind === 'shade.media-grant/v1') await playMedia(g);
else playLive(g);
}
async function playMedia(g: MediaGrant): Promise<void> {
stats.kind = 'media';
setStatus('starting the decryption worker…');
const src = await (await ring()).add(g);
const head = await fetch(src, { method: 'HEAD' });
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
const size = Number(head.headers.get('content-length'));
stats.mime = mime;
if (mime === ALBUM_MIME) return showAlbum(parseAlbum(new Uint8Array(await (await fetch(src)).arrayBuffer())));
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
const stage = $('#stage');
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
el.controls = true;
el.autoplay = true;
el.muted = true; // autoplay policy; the viewer unmutes
el.src = src;
el.id = 'player';
el.addEventListener('playing', () => setStatus('playing'));
el.addEventListener('waiting', () => setStatus('buffering…', 'warn'));
el.addEventListener('error', () => fail(`player error: ${el.error?.message ?? el.error?.code}`));
stage.append(el);
} else if (mime.startsWith('image/')) {
const img = document.createElement('img');
img.src = src;
img.id = 'player';
img.addEventListener('load', () => setStatus(`showing ${img.naturalWidth}×${img.naturalHeight}`));
img.addEventListener('error', () => fail('image failed to decode'));
stage.append(img);
} else if (mime.startsWith('text/') || mime === 'application/json') {
const pre = document.createElement('pre');
pre.id = 'log';
pre.textContent = await (await fetch(src)).text();
stage.append(pre);
setStatus('showing text');
} else {
setStatus('ready to download');
}
const a = document.createElement('a');
a.href = src;
a.download = name || 'download';
a.textContent = 'Download decrypted';
$('#actions').append(a);
}
/** What an item is, from its grant's meta preview (before opening it). */
function itemKind(g: Grant): string {
if (g.kind === 'shade.live-grant/v1') return 'live';
const mime = g.meta?.mime ?? '';
if (mime === ALBUM_MIME) return 'album';
return mime.split('/')[0] || 'file';
}
const ICONS: Record<string, string> = { album: '▦', audio: '♪', text: '≡', live: '●', file: '⬚', video: '▶', image: '◩' };
async function showAlbum(album: Album): Promise<void> {
stats.kind = 'album';
stats.items = album.items.length;
$('#title').textContent = album.title || 'Album';
const counts = new Map<string, number>();
for (const it of album.items) counts.set(itemKind(it), (counts.get(itemKind(it)) ?? 0) + 1);
$('#sub').textContent = `album · ${[...counts].map(([k, n]) => `${n} ${k}`).join(', ') || 'empty'} · end-to-end encrypted`;
const stage = $('#stage');
stage.className = 'album';
const grid = document.createElement('div');
grid.className = 'grid';
stage.append(grid);
const kr = await ring();
for (const [i, item] of album.items.entries()) {
const kind = itemKind(item);
const card = document.createElement('button');
card.className = 'card';
card.dataset.kind = kind;
const thumb = document.createElement('div');
thumb.className = 'thumb';
thumb.textContent = ICONS[kind] ?? ICONS.file!;
const label = document.createElement('div');
label.className = 'name';
label.textContent = item.meta?.name ?? `Item ${i + 1}`;
const sub = document.createElement('div');
sub.className = 'kind';
sub.textContent = kind === 'live' ? 'live channel' : kind === 'album' ? 'album' : (item.meta?.mime ?? kind);
card.append(thumb, label, sub);
card.addEventListener('click', () => void push(() => open(item)));
grid.append(card);
// Previews decrypt through the worker like the item itself: an image
// shows itself, a video its first frame. Fetched only as cards scroll in.
if (item.kind === 'shade.media-grant/v1' && (kind === 'image' || kind === 'video')) {
const io = new IntersectionObserver(async (entries) => {
if (!entries.some((e) => e.isIntersecting)) return;
io.disconnect();
const src = await kr.add(item);
if (kind === 'image') {
const img = document.createElement('img');
img.alt = '';
img.addEventListener('load', () => thumb.replaceChildren(img));
img.src = src;
} else {
const v = document.createElement('video');
v.muted = true;
v.preload = 'metadata';
v.addEventListener('loadeddata', () => thumb.replaceChildren(v));
v.src = `${src}#t=1`;
}
});
io.observe(card);
cleanups.push(() => io.disconnect());
}
}
setStatus(`${album.items.length} item(s)`);
}
function playLive(g: LiveGrant): void {
stats.kind = 'live';
$('#title').textContent = g.meta?.name ?? 'Live channel';
const mime = g.meta?.mime ?? '';
stats.mime = mime;
$('#sub').textContent = `live · ${mime || 'text'} · end-to-end encrypted`;
const stage = $('#stage');
const states = (s: string) => setStatus(s === 'live' ? 'live' : s === 'waiting' ? 'waiting for the publisher…' : s, s === 'live' ? 'ok' : 'warn');
const onErr = (e: Error) => {
stats.error = e.message;
};
let log: HTMLPreElement | null = null;
let img: HTMLImageElement | null = null;
const other = (f: ReceivedFrame) => {
stats.frames++;
const c = f.content;
if (c.type === 'text') {
if (log === null) {
log = document.createElement('pre');
log.id = 'log';
stage.append(log);
}
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 4;
log.append(document.createTextNode(c.text));
stats.lines += c.text.split('\n').length - 1;
// Bound the DOM: a log stream runs for days.
while (log.childNodes.length > 5000) log.firstChild!.remove();
if (atBottom) log.scrollTop = log.scrollHeight;
} else if (c.type === 'image') {
if (img === null) {
img = document.createElement('img');
img.id = 'player';
stage.prepend(img);
}
const old = img.src;
img.src = URL.createObjectURL(new Blob([c.bytes as Uint8Array<ArrayBuffer>], { type: c.mime }));
if (old.startsWith('blob:')) URL.revokeObjectURL(old);
stats.images++;
} else if (c.type === 'end') {
setStatus('the broadcast has ended', 'warn');
}
};
if (mime.startsWith('video/') || mime.startsWith('audio/')) {
const el = document.createElement(mime.startsWith('video/') ? 'video' : 'audio');
el.controls = true;
el.autoplay = true;
el.muted = true;
el.id = 'player';
stage.append(el);
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
cleanups.push(() => player.close());
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
} else {
const client = new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
cleanups.push(() => client.close());
}
}
async function main(): Promise<void> {
let grant;
try {
grant = fromCapabilityUrl(location.href);
} catch (e) {
$('#title').textContent = 'Shade';
return fail(`no grant in this link — ${(e as Error).message}`);
}
// Keep the key out of the history and out of anything that reads the URL later.
history.replaceState({ depth: 0 }, '', location.pathname + location.search);
views.push(() => open(grant));
await render(views[0]!);
}
main().catch((e) => fail(String((e as Error)?.message ?? e)));