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:
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