/** * `shade media …` and `shade live …` — the command line for streaming. * * shade media serve relay + media store + watch page * shade media put film.mkv --server URL seal, upload, print a watch link * shade media put Season1/ --server URL every file, plus an album: one link for all * shade media get -o out.mkv download and decrypt * shade media ls|rm --server URL * tail -f app.log | shade live text --server URL --name "app logs" * ffmpeg … -f webm - | shade live video --server URL --name "Camera" (or fragmented MP4) * shade live watch a live text channel in the terminal * * The owner key (who may upload and delete) is created on first use under * `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure. */ import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; import { createWriteStream } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { basename, dirname, extname, join } from 'node:path'; import { fromB64u, randomBytes, toB64u, toHex } from './bytes.js'; import { ALBUM_MIME } from './album.js'; import type { Album } from './album.js'; import { MediaClient, openGrant, readAlbum } from './client.js'; import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js'; import type { Grant, MediaGrant } from './grant.js'; import { LivePublisher } from './live/channel.js'; import { LivePublishClient, LiveWatchClient } from './live/client.js'; import { sealFile } from './node.js'; import { OwnerKey } from './owner.js'; import type { MediaMeta } from './sealed.js'; import { MediaSplitter } from './splitter.js'; import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js'; import { prepareForWeb, webIssues } from './web-prep.js'; import type { SubtitleTrack } from './subtitles.js'; import type { LiveContainer } from './splitter.js'; type Flags = Record; function parseArgs(argv: string[]): { pos: string[]; flags: Flags } { const pos: string[] = []; const flags: Flags = {}; for (let i = 0; i < argv.length; i++) { const a = argv[i]!; if (a.startsWith('--')) { const [k, v] = a.slice(2).split('=', 2) as [string, string | undefined]; if (v !== undefined) flags[k] = v; else if (argv[i + 1] !== undefined && !argv[i + 1]!.startsWith('-')) flags[k] = argv[++i]!; else flags[k] = true; } else if (a === '-o') { flags.out = argv[++i] ?? ''; } else { pos.push(a); } } return { pos, flags }; } function str(flags: Flags, k: string): string | undefined { const v = flags[k]; return typeof v === 'string' ? v : undefined; } function need(flags: Flags, k: string, envName?: string): string { const v = str(flags, k) ?? (envName !== undefined ? process.env[envName] : undefined); if (v === undefined || v === '') throw new UsageError(`--${k} is required${envName ? ` (or ${envName})` : ''}`); return v.replace(/\/$/, ''); } class UsageError extends Error {} const MIME_BY_EXT: Record = { '.mp4': 'video/mp4', '.m4v': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.mkv': 'video/x-matroska', '.ogv': 'video/ogg', '.mp3': 'audio/mpeg', '.m4a': 'audio/mp4', '.aac': 'audio/aac', '.ogg': 'audio/ogg', '.opus': 'audio/ogg', '.wav': 'audio/wav', '.flac': 'audio/flac', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif', '.txt': 'text/plain; charset=utf-8', '.log': 'text/plain; charset=utf-8', '.md': 'text/markdown; charset=utf-8', '.json': 'application/json', '.pdf': 'application/pdf', '.srt': 'text/plain; charset=utf-8', '.vtt': 'text/vtt', }; export function guessMime(path: string): string | undefined { return MIME_BY_EXT[extname(path).toLowerCase()]; } function configDir(): string { return join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'shade'); } /** The owner key, created on first use and kept 0600. */ export async function loadOwnerKey(path = join(configDir(), 'media-owner.key')): Promise { try { return new OwnerKey(fromB64u((await readFile(path, 'utf8')).trim(), 32)); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; } const key = OwnerKey.generate(); await mkdir(configDir(), { recursive: true, mode: 0o700 }); await writeFile(path, `${toB64u(key.exportSecret())}\n`, { mode: 0o600, flag: 'wx' }); return key; } function watchLink(server: string, g: Grant): string { return toCapabilityUrl(`${server}/watch/`, g); } const out = (s: string) => process.stdout.write(`${s}\n`); const err = (s: string) => process.stderr.write(`${s}\n`); // ─── media ─────────────────────────────────────────────────── async function mediaServe(flags: Flags): Promise { const { websocket } = await import('hono/bun'); const { createMediaService, parseOwners, mediaMaxRequestBody } = await import('./server.js'); const dir = str(flags, 'dir') ?? process.env.SHADE_MEDIA_DIR ?? './shade-media-data'; const port = Number(str(flags, 'port') ?? process.env.PORT ?? 3910); // Closed by default: this machine's own owner key, plus any listed. `--open` // lets every key in — for a relay on a private network only. const own = (await loadOwnerKey()).id; const listed = parseOwners(str(flags, 'owners') ?? process.env.SHADE_MEDIA_OWNERS); const owners = flags.open === true || listed === 'any' ? 'any' : [own, ...listed]; const svc = createMediaService({ dir, owners, dev: flags.dev === true }); svc.app.get('/health', (c) => c.json({ ok: true, live: svc.relay.stats() })); const server = Bun.serve({ port, hostname: str(flags, 'host') ?? '0.0.0.0', fetch: (req, srv) => svc.app.fetch(req, { server: srv }), websocket, idleTimeout: 0, // Every route here bounds its own body; the 128 MiB default would refuse films. maxRequestBodySize: mediaMaxRequestBody(), }); err(`shade media: serving on http://localhost:${server.port} (data in ${dir})`); err(owners === 'any' ? 'open relay: any key may upload and publish' : `owners: ${owners.join(', ')}`); await new Promise(() => {}); return 0; } /** * `media put a.mkv b.jpg Season1/ …`: one path that is a file uploads that * file; several paths, a directory or `--album T` upload every file and then * an album that holds them all, and print the album's link. Directories * become nested albums, in natural order (episode 2 before episode 10). */ async function mediaPut(pos: string[], flags: Flags): Promise { if (pos.length === 0) throw new UsageError('usage: shade media put … --server URL [--album T]'); const server = need(flags, 'server', 'SHADE_MEDIA_SERVER'); const client = new MediaClient(server, await loadOwnerKey()); const started = Date.now(); const albumTitle = str(flags, 'album'); const oneDir = pos.length === 1 && (await stat(pos[0]!)).isDirectory(); let grant: MediaGrant; if (pos.length === 1 && !oneDir && albumTitle === undefined) { const name = str(flags, 'name'); const mime = str(flags, 'mime'); grant = await putFile(client, pos[0]!, flags, { ...(name !== undefined ? { name } : {}), ...(mime !== undefined ? { mime } : {}) }); } else if (oneDir) { // The directory is the album (`--album` renames it), not an album inside one. grant = await putPath(client, pos[0]!, flags, albumTitle); } else { const items: Grant[] = []; for (const p of pos) items.push(await putPath(client, p, flags)); const title = albumTitle ?? 'Album'; grant = await client.uploadAlbum({ title, items }, putOpts(flags)); err(`album "${title}": ${items.length} item(s)`); } err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`); out(flags.json === true ? encodeGrant(grant) : watchLink(server, grant)); return 0; } const naturally = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); /** A file, or a directory as an album of its (non-hidden) entries. */ async function putPath(client: MediaClient, path: string, flags: Flags, titled?: string): Promise { if (!(await stat(path)).isDirectory()) return putFile(client, path, flags); const all = (await readdir(path)).filter((n) => !n.startsWith('.')).sort(naturally.compare); // Subtitles next to a video travel inside it, not as items of their own. const videos = all.filter((n) => guessMime(n)?.startsWith('video/')).map((n) => n.slice(0, -extname(n).length)); const names = all.filter((n) => !videos.some((v) => subtitleFor(v, n) !== null)); const items: Grant[] = []; for (const n of names) items.push(await putPath(client, join(path, n), flags)); const title = titled ?? basename(path.replace(/\/+$/, '')); err(`album "${title}": ${items.length} item(s)`); return client.uploadAlbum({ title, items }, putOpts(flags)); } /** Seal and upload `Film.srt`, `Film.no.srt`, `Film.en.vtt` … found next to `Film.mkv`. */ async function putSubtitles(client: MediaClient, video: string, flags: Flags): Promise { const base = basename(video).slice(0, -extname(video).length); const siblings = (await readdir(dirname(video))).sort(naturally.compare); const tracks: SubtitleTrack[] = []; for (const n of siblings) { const lang = subtitleFor(base, n); if (lang === null) continue; const grant = await putFile(client, join(dirname(video), n), flags); tracks.push(lang === '' ? { grant } : { grant, lang }); err(` subtitles: ${n}${lang ? ` (${lang})` : ''}`); } return tracks; } function putOpts(flags: Flags): { readToken?: null } { return flags.public === true ? { readToken: null } : {}; } /** `as` overrides name and type — only for the one file named on the command line. */ async function putFile(client: MediaClient, file: string, flags: Flags, as: { name?: string; mime?: string } = {}): Promise { let meta: MediaMeta = { name: as.name ?? basename(file) }; const mime = as.mime ?? guessMime(file); if (mime !== undefined) meta.mime = mime; let source = file; let work: string | null = null; try { if (mime?.startsWith('video/')) { const tracks = await putSubtitles(client, file, flags); if (flags.web === true) { // Re-encode only what browsers cannot play; pull text subtitles out as tracks. work = await mkdtemp(join(tmpdir(), 'shade-web-')); const prep = await prepareForWeb(file, work, { onProgress: (l) => err(` ${basename(file)}: ${l}`) }); const stem = basename(file).slice(0, basename(file).length - extname(file).length); source = prep.file; meta = { name: as.name ?? `${stem}.mp4`, mime: prep.mime }; for (const sub of prep.subtitles) { const name = `${stem}${sub.lang !== undefined ? `.${sub.lang}` : ''}.srt`; const grant = await putFile(client, sub.path, flags, { name, mime: 'text/plain; charset=utf-8' }); tracks.push({ grant, ...(sub.lang !== undefined ? { lang: sub.lang } : {}), ...(sub.title !== undefined ? { label: sub.title } : {}) }); } } else { const issues = await webIssues(file); if (issues.length > 0) { err(` note: browsers will not play ${issues.join(', ')} in ${basename(file)} (most Android devices will); add --web to convert`); } } if (tracks.length > 0) meta = withSubtitles(meta, tracks); } const size = (await stat(source)).size; const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`); try { err(`sealing ${meta.name ?? basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`); const result = await sealFile(source, tmp, { meta }); return await client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) }); } finally { await rm(tmp, { force: true }); } } finally { if (work !== null) await rm(work, { recursive: true, force: true }); } } /** * `media get [-o path|-]`: a file is written to `path` (default: its * own name); an album becomes a directory of its items, nested albums as * subdirectories. Live items cannot be downloaded; their links are listed. */ async function mediaGet(pos: string[], flags: Flags): Promise { const link = pos[0]; if (link === undefined) throw new UsageError('usage: shade media get [-o file|dir|-]'); const g = fromCapabilityUrl(link); if (g.kind !== 'shade.media-grant/v1') throw new UsageError('that link is a live channel — use `shade live watch`'); const target = str(flags, 'out'); const reader = await openGrant(g); if (reader.meta.mime === ALBUM_MIME && target !== '-') { const album = await readAlbum(reader); const dir = target ?? safeName(album.title, 'album'); const n = await getAlbum(album, dir, server(g)); err(`wrote ${dir}/ (${n} file(s), verified)`); return 0; } const path = target ?? safeName(reader.meta.name, 'shade-media.bin'); await writeReader(reader, path); if (path !== '-') { err(`wrote ${path} (${reader.size} bytes, verified)`); await getSubtitles(reader.meta, path); } return 0; } /** A film's subtitles next to it, named the way `media put` finds them: `Film.no.srt`. */ async function getSubtitles(meta: MediaMeta, filmPath: string): Promise { let tracks; try { tracks = subtitlesOf(meta); } catch (e) { err(` (subtitles skipped: ${(e as Error).message})`); return 0; } const stem = filmPath.slice(0, filmPath.length - extname(filmPath).length); const used = new Set(); let n = 0; for (const t of tracks) { const sub = await openGrant(t.grant); const ext = SUBTITLE_EXTENSIONS.find((e) => sub.meta.name?.toLowerCase().endsWith(e)) ?? '.srt'; let path = `${stem}${t.lang !== undefined ? `.${t.lang}` : ''}${ext}`; for (let i = 2; used.has(path); i++) path = `${stem}${t.lang !== undefined ? `.${t.lang}` : ''}.${i}${ext}`; used.add(path); await writeReader(sub, path); err(` ${path}`); n++; } return n; } /** Origin of the relay a grant points at, for watch links of live items. */ function server(g: MediaGrant): string { return g.url !== undefined ? new URL(g.url).origin : 'http://localhost'; } async function writeReader(reader: Awaited>, path: string): Promise { const ws = path === '-' ? process.stdout : createWriteStream(path); for await (const chunk of reader.stream()) { if (!ws.write(chunk)) await new Promise((r) => ws.once('drain', () => r())); } if (ws !== process.stdout) await new Promise((r) => (ws as ReturnType).end(() => r())); } async function getAlbum(album: Album, dir: string, relay: string): Promise { await mkdir(dir, { recursive: true }); const taken = new Set(); // Names come from whoever sealed the files: never a path, never twice. const unique = (name: string) => { let n = name; const ext = extname(name); for (let i = 2; taken.has(n.toLowerCase()); i++) n = `${name.slice(0, name.length - ext.length)} (${i})${ext}`; taken.add(n.toLowerCase()); return n; }; let files = 0; for (const [i, item] of album.items.entries()) { const fallback = `item-${i + 1}`; if (item.kind !== 'shade.media-grant/v1') { err(` live: ${item.meta?.name ?? fallback} ${watchLink(relay, item)}`); continue; } const reader = await openGrant(item); if (reader.meta.mime === ALBUM_MIME) { files += await getAlbum(await readAlbum(reader), join(dir, unique(safeName(reader.meta.name, fallback))), relay); } else { const path = join(dir, unique(safeName(reader.meta.name, fallback))); await writeReader(reader, path); err(` ${path}`); files += 1 + (await getSubtitles(reader.meta, path)); } } return files; } /** * A display name made safe as one path component: the last segment only, * no control characters, no leading dots (no `..`, no hidden files). */ export function safeName(name: string | undefined, fallback: string): string { const last = (name ?? '').split(/[\\/]/).pop() ?? ''; const clean = last.replace(/[\u0000-\u001f\u007f]/g, '').replace(/^[.\s]+/, '').trim().slice(0, 200); return clean.length > 0 ? clean : fallback; } async function mediaLs(flags: Flags): Promise { const server = need(flags, 'server', 'SHADE_MEDIA_SERVER'); const res = await new MediaClient(server, await loadOwnerKey()).list(); for (const i of res.items) out(`${i.id} ${(i.size / 1048576).toFixed(1).padStart(9)} MiB ${new Date(i.createdAt).toISOString()}`); err(`${res.items.length} item(s), ${(res.usage / 1048576).toFixed(1)} MiB`); return 0; } async function mediaRm(pos: string[], flags: Flags): Promise { const server = need(flags, 'server', 'SHADE_MEDIA_SERVER'); const target = pos[0]; if (target === undefined) throw new UsageError('usage: shade media rm --server URL'); let id: Uint8Array; if (/^[0-9a-f]{32}$/.test(target)) { id = Uint8Array.from(target.match(/../g)!.map((h) => parseInt(h, 16))); } else { const g = fromCapabilityUrl(target) as MediaGrant; id = g.mediaId; } const ok = await new MediaClient(server, await loadOwnerKey()).delete(id); err(ok ? 'deleted' : 'not found (or not yours)'); return ok ? 0 : 1; } // ─── live ──────────────────────────────────────────────────── interface ChannelFile { channelId: string; signingSecret: string; channelSecret: string; readToken: string; epoch: number; } /** * A channel that outlives the process: same id, same link, next epoch. Kept * 0600 — it holds the signing key and the link secret. */ async function loadChannel(path: string | undefined, meta: MediaMeta): Promise<{ pub: LivePublisher; readToken: Uint8Array }> { const rotateEvery = 20_000; if (path === undefined) { return { pub: new LivePublisher({ meta, channelSecret: randomBytes(32), rotateEvery }), readToken: randomBytes(32) }; } let cf: ChannelFile | null = null; try { cf = JSON.parse(await readFile(path, 'utf8')) as ChannelFile; } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; } const next: ChannelFile = cf ? { ...cf, epoch: cf.epoch + 1 } : { channelId: toB64u(randomBytes(16)), signingSecret: toB64u(randomBytes(32)), channelSecret: toB64u(randomBytes(32)), readToken: toB64u(randomBytes(32)), epoch: 0, }; await writeFile(path, JSON.stringify(next, null, 2), { mode: 0o600 }); await chmod(path, 0o600); return { pub: new LivePublisher({ meta, channelId: fromB64u(next.channelId, 16), signingSecret: fromB64u(next.signingSecret, 32), channelSecret: fromB64u(next.channelSecret, 32), epoch: next.epoch, rotateEvery, }), readToken: fromB64u(next.readToken, 32), }; } async function startPublishing(flags: Flags, meta: MediaMeta): Promise<{ client: LivePublishClient; server: string }> { const server = need(flags, 'server', 'SHADE_MEDIA_SERVER'); const { pub, readToken } = await loadChannel(str(flags, 'channel'), meta); const client = new LivePublishClient({ relay: server, publisher: pub, readToken, owner: await loadOwnerKey(), onViewers: (n) => err(`viewers: ${n}`), onError: (m) => err(`relay: ${m}`), onState: (s) => { if (s === 'reconnecting') err('relay connection lost — reconnecting…'); }, }); await client.whenReady(); // Link mode: the link holds the channel secret and survives restarts. out(watchLink(server, client.grant('oldest', true))); return { client, server }; } async function liveText(flags: Flags): Promise { const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live log', mime: 'text/plain' }; const { client } = await startPublishing(flags, meta); await client.send({ type: 'meta', meta }, { sticky: true }); const batchMs = Number(str(flags, 'batch-ms') ?? 100); const keyEvery = Number(str(flags, 'keyframe-every') ?? 20); let pending = ''; let batches = 0; // Only whole lines go out: a batch boundary must never split a log line. // A partial line waits for its newline — unless it grows past the cap, or // the input ends. const flush = async (final = false) => { const cut = final || pending.length > 256 * 1024 ? pending.length : pending.lastIndexOf('\n') + 1; if (cut === 0) return; const text = pending.slice(0, cut); pending = pending.slice(cut); // A keyframe every N batches bounds how far back a late viewer sees. await client.send({ type: 'text', text }, { keyframe: batches++ % keyEvery === 0 }); }; const timer = setInterval(() => void flush(), batchMs); const dec = new TextDecoder(); for await (const chunk of Bun.stdin.stream()) { pending += dec.decode(chunk, { stream: true }); if (pending.length > 256 * 1024) await flush(); } clearInterval(timer); pending += dec.decode(); await flush(true); await client.end(); return 0; } /** * A live WebM or fragmented-MP4 stream from stdin. `--format webm|fmp4` pins * the container (the `webm` subcommand pins WebM); otherwise the first bytes * decide. */ async function liveVideo(flags: Flags, pinned?: LiveContainer): Promise { const format = pinned ?? str(flags, 'format'); if (format !== undefined && format !== 'webm' && format !== 'fmp4') throw new UsageError('--format must be webm or fmp4'); const splitter = new MediaSplitter(format); const stdin = Bun.stdin.stream().getReader(); // Read until the container is known, so the meta can carry the right type. let first: ReturnType = []; while (splitter.container === null) { const { value, done } = await stdin.read(); if (done) throw new UsageError('no input on stdin'); first = first.concat(splitter.push(value)); } const fallbackMime = splitter.container === 'webm' ? 'video/webm' : 'video/mp4'; const meta: MediaMeta = { name: str(flags, 'name') ?? 'Live', mime: str(flags, 'mime') ?? fallbackMime }; const { client } = await startPublishing(flags, meta); let pieces = 0; const send = async (batch: ReturnType) => { for (const p of batch) { if (p.type === 'init') { await client.send({ type: 'init', mime: p.mime, bytes: p.bytes }, { sticky: true }); err(`stream: ${p.mime}`); } else { await client.send({ type: 'chunk', bytes: p.bytes }, { keyframe: p.keyframe }); pieces++; } } }; await send(first); for (;;) { const { value, done } = await stdin.read(); if (done) break; await send(splitter.push(value)); } await send(splitter.finish()); err(`${pieces} ${splitter.container === 'webm' ? 'clusters' : 'fragments'} sent`); await client.end(); return 0; } async function liveWatch(pos: string[]): Promise { const link = pos[0]; if (link === undefined) throw new UsageError('usage: shade live watch '); const g = fromCapabilityUrl(link); if (g.kind !== 'shade.live-grant/v1') throw new UsageError('that link is a sealed file — use `shade media get`'); await new Promise((resolve) => { const w = new LiveWatchClient(g, { onFrame: (f) => { const c = f.content; if (c.type === 'text') process.stdout.write(c.text); else if (c.type === 'end') { w.close(); resolve(); } }, onState: (s) => { if (s === 'waiting') err('(waiting for the publisher)'); }, onError: (e) => err(`! ${e.message}`), }); }); return 0; } export const MEDIA_HELP = ` media serve [--port 3910] [--dir ./shade-media-data] [--owners k1,k2] [--open] Run a media relay: sealed store, live relay, watch page. Only this machine's key (and --owners) may upload/publish. media whoami Print this machine's owner key (to add to a relay's --owners) media put … --server URL [--album T] [--name N] [--mime M] [--web] [--public] [--json] Seal a film/video/image/song, upload it, print a watch link. Several files or a directory become an album: one link for all. Film.no.srt etc. next to a film travel with it as subtitles. --web: make films play in any browser first (ffmpeg): copy what browsers play, AC-3/DTS audio → AAC, HEVC → H.264, embedded text subtitles → subtitle tracks. media get [-o file|dir|-] Download and decrypt a sealed file (an album: a directory) media ls --server URL Your uploads on that server media rm --server URL live text --server URL [--name N] [--channel file.json] Publish stdin as a live log (tail -f app.log | shade live text …) live video --server URL [--name N] [--channel file.json] [--format webm|fmp4] Publish a live WebM or fragmented MP4 from stdin: ffmpeg … -f webm - | … ffmpeg … -c:v libx264 -c:a aac -f mp4 \\ -movflags frag_keyframe+empty_moov+default_base_moof - | … live webm … The same, pinned to WebM live watch Follow a live text channel in the terminal `; /** Entry for `shade media …` / `shade live …`. Returns the exit code. */ export async function runMediaCli(group: 'media' | 'live', argv: string[]): Promise { const [sub, ...rest] = argv; const { pos, flags } = parseArgs(rest); try { if (group === 'media') { switch (sub) { case 'serve': return await mediaServe(flags); case 'whoami': out((await loadOwnerKey()).id); return 0; case 'put': return await mediaPut(pos, flags); case 'get': return await mediaGet(pos, flags); case 'ls': return await mediaLs(flags); case 'rm': return await mediaRm(pos, flags); } } else { switch (sub) { case 'text': return await liveText(flags); case 'video': return await liveVideo(flags); case 'webm': return await liveVideo(flags, 'webm'); case 'watch': return await liveWatch(pos); } } err(`Usage:${MEDIA_HELP}`); return 2; } catch (e) { err(e instanceof UsageError ? e.message : `error: ${(e as Error).message}`); return 1; } }