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:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -81,7 +81,11 @@ export function mediaKeysOf(g: MediaGrant): MediaKeys {
|
||||
return { mediaId: g.mediaId, mediaKey: g.mediaKey, rootDigest: g.rootDigest };
|
||||
}
|
||||
|
||||
/** Wire JSON: binary fields as base64url, the digest as hex (it is a hash, and greppable). */
|
||||
/**
|
||||
* Wire JSON: binary fields as base64url, the digest as hex (it is a hash, and
|
||||
* greppable). The meta is written in its canonical order, so a grant always
|
||||
* encodes to the same link, however its meta object was built.
|
||||
*/
|
||||
export function encodeGrant(g: Grant): string {
|
||||
if (g.kind === MEDIA_GRANT_KIND) {
|
||||
return JSON.stringify({
|
||||
@@ -91,7 +95,7 @@ export function encodeGrant(g: Grant): string {
|
||||
root: toHex(g.rootDigest),
|
||||
...(g.url !== undefined ? { url: g.url } : {}),
|
||||
...(g.readToken !== undefined ? { token: toB64u(g.readToken) } : {}),
|
||||
...(g.meta !== undefined ? { meta: g.meta } : {}),
|
||||
...(g.meta !== undefined ? { meta: validateMeta(g.meta) } : {}),
|
||||
});
|
||||
}
|
||||
return JSON.stringify({
|
||||
@@ -105,7 +109,7 @@ export function encodeGrant(g: Grant): string {
|
||||
...(g.channelSecret !== undefined ? { channelSecret: toB64u(g.channelSecret) } : {}),
|
||||
...(g.url !== undefined ? { url: g.url } : {}),
|
||||
...(g.readToken !== undefined ? { token: toB64u(g.readToken) } : {}),
|
||||
...(g.meta !== undefined ? { meta: g.meta } : {}),
|
||||
...(g.meta !== undefined ? { meta: validateMeta(g.meta) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
112
packages/shade-media/src/library.ts
Normal file
112
packages/shade-media/src/library.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* This machine's record of what it uploaded: names and links.
|
||||
*
|
||||
* The relay knows ids and sizes, never names, and a link is only printed
|
||||
* once. Lose the link and a film you own is unreachable. So every upload is
|
||||
* written down here, with its grant, under `$XDG_CONFIG_HOME/shade/` beside
|
||||
* the owner key, mode 0600: a grant is a key.
|
||||
*
|
||||
* Format: one JSON object per line, appended (`{"op":"add",…}`,
|
||||
* `{"op":"rm","id":…}`). Appends of a line are atomic on a local disk, so two
|
||||
* `shade media put` running at once cannot lose each other's entries, and no
|
||||
* lock is needed. Reading folds the lines; a damaged line is skipped.
|
||||
*/
|
||||
|
||||
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { toHex } from './bytes.js';
|
||||
import { encodeGrant, parseGrant } from './grant.js';
|
||||
import type { MediaGrant } from './grant.js';
|
||||
|
||||
export interface LibraryEntry {
|
||||
/** Lowercase hex media id. */
|
||||
id: string;
|
||||
/** Relay base URL it was uploaded to. */
|
||||
server: string;
|
||||
name?: string;
|
||||
mime?: string;
|
||||
/** Sealed bytes on the relay. */
|
||||
size: number;
|
||||
createdAt: number;
|
||||
grant: MediaGrant;
|
||||
}
|
||||
|
||||
export class MediaLibrary {
|
||||
private constructor(
|
||||
readonly path: string,
|
||||
private readonly byId: Map<string, LibraryEntry>,
|
||||
) {}
|
||||
|
||||
static async open(path: string): Promise<MediaLibrary> {
|
||||
const byId = new Map<string, LibraryEntry>();
|
||||
let text = '';
|
||||
try {
|
||||
text = await readFile(path, 'utf8');
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;
|
||||
}
|
||||
for (const line of text.split('\n')) {
|
||||
if (line.trim() === '') continue;
|
||||
try {
|
||||
const o = JSON.parse(line) as Record<string, unknown>;
|
||||
if (o.op === 'rm' && typeof o.id === 'string') {
|
||||
byId.delete(o.id);
|
||||
} else if (o.op === 'add' && typeof o.id === 'string' && typeof o.server === 'string') {
|
||||
const grant = parseGrant(JSON.stringify(o.grant));
|
||||
if (grant.kind !== 'shade.media-grant/v1') continue;
|
||||
byId.set(o.id, {
|
||||
id: o.id,
|
||||
server: o.server,
|
||||
...(typeof o.name === 'string' ? { name: o.name } : {}),
|
||||
...(typeof o.mime === 'string' ? { mime: o.mime } : {}),
|
||||
size: typeof o.size === 'number' ? o.size : 0,
|
||||
createdAt: typeof o.createdAt === 'number' ? o.createdAt : 0,
|
||||
grant,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// A torn or hand-edited line costs that entry, not the library.
|
||||
}
|
||||
}
|
||||
return new MediaLibrary(path, byId);
|
||||
}
|
||||
|
||||
entries(): LibraryEntry[] {
|
||||
return [...this.byId.values()].sort((a, b) => b.createdAt - a.createdAt);
|
||||
}
|
||||
|
||||
get(id: string): LibraryEntry | undefined {
|
||||
return this.byId.get(id);
|
||||
}
|
||||
|
||||
/** Entries whose id starts with `query`, or whose name contains it (any case). */
|
||||
find(query: string): LibraryEntry[] {
|
||||
const q = query.toLowerCase();
|
||||
return this.entries().filter((e) => e.id.startsWith(q) || (e.name ?? '').toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
async add(server: string, grant: MediaGrant, size: number): Promise<LibraryEntry> {
|
||||
const entry: LibraryEntry = {
|
||||
id: toHex(grant.mediaId),
|
||||
server: server.replace(/\/$/, ''),
|
||||
...(grant.meta?.name !== undefined ? { name: grant.meta.name } : {}),
|
||||
...(grant.meta?.mime !== undefined ? { mime: grant.meta.mime } : {}),
|
||||
size,
|
||||
createdAt: Date.now(),
|
||||
grant,
|
||||
};
|
||||
await this.append({ op: 'add', ...entry, grant: JSON.parse(encodeGrant(grant)) as unknown });
|
||||
this.byId.set(entry.id, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
await this.append({ op: 'rm', id });
|
||||
this.byId.delete(id);
|
||||
}
|
||||
|
||||
private async append(o: unknown): Promise<void> {
|
||||
await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
|
||||
await appendFile(this.path, `${JSON.stringify(o)}\n`, { mode: 0o600 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user