/** * 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, ) {} static async open(path: string): Promise { const byId = new Map(); 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; 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 { 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 { await this.append({ op: 'rm', id }); this.byId.delete(id); } private async append(o: unknown): Promise { await mkdir(dirname(this.path), { recursive: true, mode: 0o700 }); await appendFile(this.path, `${JSON.stringify(o)}\n`, { mode: 0o600 }); } }