feat(media): a local library of uploads — media ls with names, media link; canonical grant encoding

The relay never knows names and a link is printed once, so a lost link
made an owned film unreachable. media put now appends each upload and its
grant to $XDG_CONFIG_HOME/shade/media-library.jsonl (0600, one JSON line
per change: concurrent uploads cannot lose entries, a torn line costs only
itself). media ls names uploads from it; media link <name|id> prints the
link again; media rm forgets it.

encodeGrant now writes meta in canonical (validateMeta) order, so one
grant is always one link; media.json vectors regenerated (album and
subtitle vectors only), Kotlin 82/0.

Verified: 82 TS tests (library: fold, find, 0600, torn line, 200
concurrent appends, stable encoding); CLI put → ls → link gives back the
identical link.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 22:08:22 +02:00
parent d784e47ab3
commit 01f8471fb5
8 changed files with 269 additions and 25 deletions

View File

@@ -32,6 +32,7 @@ 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 { MediaLibrary } from './library.js';
import type { SubtitleTrack } from './subtitles.js';
import type { LiveContainer } from './splitter.js';
@@ -145,7 +146,7 @@ async function mediaServe(flags: Flags): Promise<number> {
async function mediaPut(pos: string[], flags: Flags): Promise<number> {
if (pos.length === 0) throw new UsageError('usage: shade media put <file|dir>… --server URL [--album T]');
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const client = new MediaClient(server, await loadOwnerKey());
const ctx: PutCtx = { client: new MediaClient(server, await loadOwnerKey()), server, library: await openLibrary() };
const started = Date.now();
const albumTitle = str(flags, 'album');
const oneDir = pos.length === 1 && (await stat(pos[0]!)).isDirectory();
@@ -153,15 +154,15 @@ async function mediaPut(pos: string[], flags: Flags): Promise<number> {
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 } : {}) });
grant = await putFile(ctx, 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);
grant = await putPath(ctx, pos[0]!, flags, albumTitle);
} else {
const items: Grant[] = [];
for (const p of pos) items.push(await putPath(client, p, flags));
for (const p of pos) items.push(await putPath(ctx, p, flags));
const title = albumTitle ?? 'Album';
grant = await client.uploadAlbum({ title, items }, putOpts(flags));
grant = await putAlbum(ctx, title, items, flags);
err(`album "${title}": ${items.length} item(s)`);
}
err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
@@ -169,31 +170,47 @@ async function mediaPut(pos: string[], flags: Flags): Promise<number> {
return 0;
}
interface PutCtx {
client: MediaClient;
server: string;
library: MediaLibrary;
}
async function putAlbum(ctx: PutCtx, title: string, items: Grant[], flags: Flags): Promise<MediaGrant> {
const grant = await ctx.client.uploadAlbum({ title, items }, putOpts(flags));
await ctx.library.add(ctx.server, grant, 0);
return grant;
}
export function openLibrary(path = join(configDir(), 'media-library.jsonl')): Promise<MediaLibrary> {
return MediaLibrary.open(path);
}
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<MediaGrant> {
if (!(await stat(path)).isDirectory()) return putFile(client, path, flags);
async function putPath(ctx: PutCtx, path: string, flags: Flags, titled?: string): Promise<MediaGrant> {
if (!(await stat(path)).isDirectory()) return putFile(ctx, 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));
for (const n of names) items.push(await putPath(ctx, join(path, n), flags));
const title = titled ?? basename(path.replace(/\/+$/, ''));
err(`album "${title}": ${items.length} item(s)`);
return client.uploadAlbum({ title, items }, putOpts(flags));
return putAlbum(ctx, title, items, 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<SubtitleTrack[]> {
async function putSubtitles(ctx: PutCtx, video: string, flags: Flags): Promise<SubtitleTrack[]> {
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);
const grant = await putFile(ctx, join(dirname(video), n), flags);
tracks.push(lang === '' ? { grant } : { grant, lang });
err(` subtitles: ${n}${lang ? ` (${lang})` : ''}`);
}
@@ -205,7 +222,7 @@ function putOpts(flags: Flags): { 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<MediaGrant> {
async function putFile(ctx: PutCtx, file: string, flags: Flags, as: { name?: string; mime?: string } = {}): Promise<MediaGrant> {
let meta: MediaMeta = { name: as.name ?? basename(file) };
const mime = as.mime ?? guessMime(file);
if (mime !== undefined) meta.mime = mime;
@@ -213,7 +230,7 @@ async function putFile(client: MediaClient, file: string, flags: Flags, as: { na
let work: string | null = null;
try {
if (mime?.startsWith('video/')) {
const tracks = await putSubtitles(client, file, flags);
const tracks = await putSubtitles(ctx, 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-'));
@@ -223,7 +240,7 @@ async function putFile(client: MediaClient, file: string, flags: Flags, as: { na
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' });
const grant = await putFile(ctx, 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 {
@@ -239,7 +256,9 @@ async function putFile(client: MediaClient, file: string, flags: Flags, as: { na
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) });
const grant = await ctx.client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) });
await ctx.library.add(ctx.server, grant, result.sealedSize);
return grant;
} finally {
await rm(tmp, { force: true });
}
@@ -355,14 +374,35 @@ export function safeName(name: string | undefined, fallback: string): string {
return clean.length > 0 ? clean : fallback;
}
/** Your uploads on a relay, named from this machine's library where it knows them. */
async function mediaLs(flags: Flags): Promise<number> {
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()}`);
const [res, library] = await Promise.all([new MediaClient(server, await loadOwnerKey()).list(), openLibrary()]);
for (const i of res.items) {
const e = library.get(i.id);
const name = e === undefined ? '(not in this machine\'s library)' : `${e.name ?? '(no name)'}${e.mime === ALBUM_MIME ? '/' : ''}`;
out(`${i.id} ${(i.size / 1048576).toFixed(1).padStart(9)} MiB ${new Date(i.createdAt).toISOString().slice(0, 16).replace('T', ' ')} ${name}`);
}
err(`${res.items.length} item(s), ${(res.usage / 1048576).toFixed(1)} MiB`);
return 0;
}
/** `media link <name|id-prefix>`: the watch links of matching uploads, from the library. */
async function mediaLink(pos: string[]): Promise<number> {
const query = pos.join(' ').trim();
if (query === '') throw new UsageError('usage: shade media link <name or id prefix>');
const hits = (await openLibrary()).find(query);
if (hits.length === 0) {
err(`nothing in this machine's library matches "${query}"`);
return 1;
}
for (const e of hits) {
if (hits.length > 1) err(`${e.name ?? e.id}${e.mime === ALBUM_MIME ? '/' : ''}`);
out(watchLink(e.server, e.grant));
}
return 0;
}
async function mediaRm(pos: string[], flags: Flags): Promise<number> {
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
const target = pos[0];
@@ -375,6 +415,8 @@ async function mediaRm(pos: string[], flags: Flags): Promise<number> {
id = g.mediaId;
}
const ok = await new MediaClient(server, await loadOwnerKey()).delete(id);
const library = await openLibrary();
if (library.get(toHex(id)) !== undefined) await library.remove(toHex(id));
err(ok ? 'deleted' : 'not found (or not yours)');
return ok ? 0 : 1;
}
@@ -562,7 +604,8 @@ export const MEDIA_HELP = `
embedded text subtitles → subtitle tracks.
media get <link> [-o file|dir|-]
Download and decrypt a sealed file (an album: a directory)
media ls --server URL Your uploads on that server
media ls --server URL Your uploads on that server, named from this machine's library
media link <name|id> Print the watch link of an upload again (from the library)
media rm <link|id> --server URL
live text --server URL [--name N] [--channel file.json]
Publish stdin as a live log (tail -f app.log | shade live text …)
@@ -593,6 +636,8 @@ export async function runMediaCli(group: 'media' | 'live', argv: string[]): Prom
return await mediaGet(pos, flags);
case 'ls':
return await mediaLs(flags);
case 'link':
return await mediaLink(pos);
case 'rm':
return await mediaRm(pos, flags);
}