/** Shenron adapter: inventory public Archive.org media without copying it. */ import { Database } from "bun:sqlite"; import { archiveDownloadUrl, archiveEmbedUrl, type ArchiveClient, type ArchiveFile, type ArchiveItem, } from "./index.ts"; import { DRAGONBALL_URLS } from "../sources/dragonball.ts"; export type ShenronMediaKind = | "video" | "audio" | "image" | "document" | "other"; export type RightsStatus = "unverified" | "cleared" | "restricted"; export interface ShenronArchiveFile { identifier: string; filename: string; contentUrl: string; source: string | null; format: string | null; bytes: number | null; durationSec: number | null; width: number | null; height: number | null; sha1: string | null; mediaKind: ShenronMediaKind; series: string | null; episodeNumber: number | null; title: string | null; rightsStatus: RightsStatus; } export interface ShenronArchiveManifest { identifier: string; itemUrl: string; embedUrl: string; title: string; creator: string | null; mediatype: string | null; collections: string[]; rightsStatus: RightsStatus; metadata: Record; files: ShenronArchiveFile[]; } export interface ShenronImportResult { identifier: string; filesUpserted: number; episodesMissingFromShenron: number[]; } const MIGRATION_SQL = `-- BXC / Shenron Internet Archive catalogue migration (SQLite). CREATE TABLE IF NOT EXISTS archive_catalog_items ( identifier TEXT PRIMARY KEY NOT NULL, item_url TEXT NOT NULL, embed_url TEXT NOT NULL, title TEXT NOT NULL, creator TEXT, mediatype TEXT, collections_json TEXT NOT NULL DEFAULT '[]', rights_status TEXT NOT NULL DEFAULT 'unverified', metadata_json TEXT NOT NULL, discovered_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000), updated_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000) ); --> statement-breakpoint CREATE TABLE IF NOT EXISTS archive_catalog_files ( identifier TEXT NOT NULL REFERENCES archive_catalog_items(identifier) ON DELETE CASCADE, filename TEXT NOT NULL, content_url TEXT NOT NULL, source TEXT, format TEXT, bytes INTEGER, duration_sec REAL, width INTEGER, height INTEGER, sha1 TEXT, media_kind TEXT NOT NULL, series TEXT, episode_number INTEGER, title TEXT, rights_status TEXT NOT NULL DEFAULT 'unverified', discovered_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000), updated_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000), PRIMARY KEY (identifier, filename) ); --> statement-breakpoint CREATE INDEX IF NOT EXISTS archive_catalog_files_series_episode_idx ON archive_catalog_files(series, episode_number); --> statement-breakpoint CREATE INDEX IF NOT EXISTS archive_catalog_files_rights_idx ON archive_catalog_files(rights_status); `; const VIDEO_EXTENSIONS = new Set([ "avi", "mkv", "mov", "mp4", "m4v", "webm", "flv", "mpeg", "mpg", ]); const AUDIO_EXTENSIONS = new Set([ "mp3", "flac", "m4a", "ogg", "wav", "aac", "opus", ]); const IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "webp", "gif", "avif"]); function asNumber(value: unknown): number | null { const number = Number(value); return Number.isFinite(number) ? number : null; } function extension(filename: string): string { return filename.toLowerCase().split(".").at(-1) ?? ""; } export function archiveMediaKind(filename: string): ShenronMediaKind { const ext = extension(filename); if (VIDEO_EXTENSIONS.has(ext)) return "video"; if (AUDIO_EXTENSIONS.has(ext)) return "audio"; if (IMAGE_EXTENSIONS.has(ext)) return "image"; if (["pdf", "epub", "cbz", "cbr", "txt", "djvu"].includes(ext)) return "document"; return "other"; } /** Extracts a numbered episode title from common Archive.org filenames. */ export function parseEpisodeFilename(filename: string): { episodeNumber: number | null; title: string | null; } { const base = filename .split("/") .at(-1) ?.replace(/\.[^.]+$/, "") ?? filename; const match = base.match(/^\s*(\d{1,3})\s*[-_. ]+\s*(.+?)\s*$/); return match ? { episodeNumber: Number(match[1]), title: match[2] } : { episodeNumber: null, title: base || null }; } function usefulFile(file: ArchiveFile): boolean { return ( archiveMediaKind(file.name) !== "other" && !file.name.includes(".thumbs/") ); } /** Convert an Archive item into a rights-gated, database-ready external manifest. */ export function toShenronManifest( item: ArchiveItem, series: string | null = null, ): ShenronArchiveManifest { const metadata = item.metadata ?? {}; const identifier = String( metadata.identifier ?? item.dir.split("/").at(-1) ?? "", ); if (!identifier) throw new Error("Archive item has no identifier"); const collections = Array.isArray(metadata.collection) ? metadata.collection.map(String) : metadata.collection ? [String(metadata.collection)] : []; return { identifier, itemUrl: DRAGONBALL_URLS.archiveItem(identifier), embedUrl: archiveEmbedUrl(identifier), title: String(metadata.title ?? identifier), creator: metadata.creator ? String(metadata.creator) : null, mediatype: metadata.mediatype ? String(metadata.mediatype) : null, collections, rightsStatus: "unverified", metadata, files: item.files.filter(usefulFile).map((file) => { const parsed = parseEpisodeFilename(file.name); return { identifier, filename: file.name, contentUrl: archiveDownloadUrl(identifier, file.name), source: typeof file.source === "string" ? file.source : null, format: typeof file.format === "string" ? file.format : null, bytes: asNumber(file.size), durationSec: asNumber(file.length), width: asNumber(file.width), height: asNumber(file.height), sha1: typeof file.sha1 === "string" ? file.sha1 : null, mediaKind: archiveMediaKind(file.name), series, episodeNumber: parsed.episodeNumber, title: parsed.title, rightsStatus: "unverified" as const, }; }), }; } export async function scanArchiveForShenron( client: ArchiveClient, identifier: string, series: string | null = null, ): Promise { return toShenronManifest(await client.getItem(identifier), series); } /** * Applies the standalone BXC migration and upserts an external-only catalog. * This never alters `db_episodes`, downloads a file, or marks a work cleared. */ export function importShenronArchiveManifest( databasePath: string, manifest: ShenronArchiveManifest, ): ShenronImportResult { const db = new Database(databasePath); try { db.exec("PRAGMA foreign_keys = ON"); for (const statement of MIGRATION_SQL.split("--> statement-breakpoint") .map((part) => part.trim()) .filter(Boolean)) db.exec(statement); const now = Date.now(); db.query(`INSERT INTO archive_catalog_items (identifier, item_url, embed_url, title, creator, mediatype, collections_json, rights_status, metadata_json, discovered_at, updated_at) VALUES ($identifier, $itemUrl, $embedUrl, $title, $creator, $mediatype, $collections, $rightsStatus, $metadata, $now, $now) ON CONFLICT(identifier) DO UPDATE SET item_url=excluded.item_url, embed_url=excluded.embed_url, title=excluded.title, creator=excluded.creator, mediatype=excluded.mediatype, collections_json=excluded.collections_json, rights_status=excluded.rights_status, metadata_json=excluded.metadata_json, updated_at=excluded.updated_at`).run( { $identifier: manifest.identifier, $itemUrl: manifest.itemUrl, $embedUrl: manifest.embedUrl, $title: manifest.title, $creator: manifest.creator, $mediatype: manifest.mediatype, $collections: JSON.stringify(manifest.collections), $rightsStatus: manifest.rightsStatus, $metadata: JSON.stringify(manifest.metadata), $now: now, }, ); const upsert = db.query(`INSERT INTO archive_catalog_files (identifier, filename, content_url, source, format, bytes, duration_sec, width, height, sha1, media_kind, series, episode_number, title, rights_status, discovered_at, updated_at) VALUES ($identifier, $filename, $contentUrl, $source, $format, $bytes, $durationSec, $width, $height, $sha1, $mediaKind, $series, $episodeNumber, $title, $rightsStatus, $now, $now) ON CONFLICT(identifier, filename) DO UPDATE SET content_url=excluded.content_url, source=excluded.source, format=excluded.format, bytes=excluded.bytes, duration_sec=excluded.duration_sec, width=excluded.width, height=excluded.height, sha1=excluded.sha1, media_kind=excluded.media_kind, series=excluded.series, episode_number=excluded.episode_number, title=excluded.title, rights_status=excluded.rights_status, updated_at=excluded.updated_at`); for (const file of manifest.files) upsert.run({ $identifier: file.identifier, $filename: file.filename, $contentUrl: file.contentUrl, $source: file.source, $format: file.format, $bytes: file.bytes, $durationSec: file.durationSec, $width: file.width, $height: file.height, $sha1: file.sha1, $mediaKind: file.mediaKind, $series: file.series, $episodeNumber: file.episodeNumber, $title: file.title, $rightsStatus: file.rightsStatus, $now: now, }); const present = new Set( ( db .query( "SELECT number_in_series AS number FROM db_episodes WHERE series = $series", ) .all({ $series: manifest.files[0]?.series ?? "" }) as Array<{ number: number; }> ).map((row) => row.number), ); const missing = [ ...new Set( manifest.files .filter( (file) => file.mediaKind === "video" && file.episodeNumber !== null && !present.has(file.episodeNumber), ) .map((file) => file.episodeNumber!), ), ].sort((a, b) => a - b); return { identifier: manifest.identifier, filesUpserted: manifest.files.length, episodesMissingFromShenron: missing, }; } finally { db.close(); } }