11 Commits
Author SHA1 Message Date
Worph a811bb9a57 sign every write as an MMUR2 claim (POST /api/claims); search with parsedTitle
Build and Push Docker Image / build (push) Successful in 1m25s
2026-10-25 17:36:46 +00:00
Manielle e63a8993e8 CI accepts four-part tags (v1.2.3.1) for fixes
Build and Push Docker Image / build (push) Successful in 29s
2026-10-25 14:21:57 +01:00
Worph 07da89bf07 release (first build on gitea-watch / IPCR)
Build and Push Docker Image / build (push) Successful in 57s
2026-10-13 11:04:13 +00:00
Worph 99f6372526 gitea workflow: push to IPCR's direct host (Cloudflare 100 MB cap) [skip ci] 2026-10-13 10:03:27 +00:00
Worph 0aa5920ebb gitea workflow: publish to IPCR (metadec.eth) instead of ghcr
Build and Push Docker Image / build (push) Successful in 36s
2026-10-12 18:31:45 +00:00
Worph f5e28b0d4e advertise over beacon v2 as metamesh.enrich/<id> so meta-sort's Plugins page can find it (Scan -> Add)
Build and Push Docker Image / build (push) Failing after 14s
2026-10-04 17:19:24 +00:00
Worph e4fcb2bfde align with metadata standard
Build and Push Docker Image / build (push) Failing after 14s
2026-09-13 15:56:06 +02:00
Worph f28f7d8594 align to metadata keys doc 2026-08-30 19:48:53 +02:00
Worph bcd1eea5a2 gitattributes
Build and Push Docker Image / build (push) Failing after 13s
2026-07-14 16:01:30 +02:00
Worph bee5734251 fix webdav dependencies
Build and Push Docker Image / build (push) Failing after 14s
2026-07-12 19:20:15 +02:00
Worph 0d57dbeee3 add cache 2026-07-05 22:30:06 +02:00
15 changed files with 2327 additions and 221 deletions
+6
View File
@@ -0,0 +1,6 @@
# FIX CRLF always when developer has not set
# Linux/Mac: git config --global core.autocrlf input
# Windows: git config --global core.autocrlf true
# Auto detect text files and perform LF normalization
* text=auto
* eol=lf
+85
View File
@@ -0,0 +1,85 @@
# Gitea twin of .github/workflows/docker.yml. Gitea runs only .gitea/workflows/ once this
# folder exists, and GitHub never reads it.
#
# Publishes to IPCR on watch.nsl.sh instead of ghcr.io:
# push ipcr-push-85-17-246-67.nip.io/metadec.eth/<repo>:<tag> docker login as metadec.eth with the
# IPCR_PUSH_TOKEN secret (the metadec.eth namespace token from the IPCR dashboard)
# pull ipcr-watch.nsl.sh/ipns/metadec.eth/metadec.eth/<repo>:<tag> anonymous
# The push goes to ipcr-push-85-17-246-67.nip.io, the box's own address, not ipcr-push-watch.nsl.sh: Cloudflare fronts
# *.watch.nsl.sh and refuses any request over 100 MB (413), which a large image layer is.
# That host's certificate is signed by the box's private Mesh Router CA, given to buildkit from
# the IPCR_CA_PEM repo variable. docker login would make the job's Docker daemon check the
# certificate without that CA, so the login is written straight into ~/.docker/config.json.
# The runner's job image (node:22-bookworm) has no docker CLI, so the static one is
# installed first; buildx installs itself. No `type=gha` cache: the runner has none.
name: Build and Push Docker Image
on:
push:
branches: [main, master]
tags: ['v*']
pull_request:
branches: [main, master]
env:
REGISTRY: ipcr-push-85-17-246-67.nip.io
IMAGE_NAME: metadec.eth/${{ github.event.repository.name }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Docker CLI
run: curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-28.5.1.tgz | tar -xz -C /usr/local/bin --strip-components=1 docker/docker
- name: Trust the Mesh Router CA
run: printf '%s\n' "$IPCR_CA_PEM" > /tmp/ipcr-ca.pem
env:
IPCR_CA_PEM: ${{ vars.IPCR_CA_PEM }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
version: latest
buildkitd-config-inline: |
[registry."${{ env.REGISTRY }}"]
ca = ["/tmp/ipcr-ca.pem"]
- name: Log in to IPCR
if: github.event_name != 'pull_request'
env:
IPCR_PUSH_TOKEN: ${{ secrets.IPCR_PUSH_TOKEN }}
run: |
mkdir -p ~/.docker
printf '{"auths":{"%s":{"auth":"%s"}}}\n' "$REGISTRY" "$(printf 'metadec.eth:%s' "$IPCR_PUSH_TOKEN" | base64 -w0)" > ~/.docker/config.json
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
# A fix to release 1.2.3 is tagged v1.2.3.1: four numbers are not semver, so
# the pattern above makes no tag for it; this one does (image tag 1.2.3.1).
type=match,pattern=v(\d+\.\d+\.\d+\.\d+),group=1
type=semver,pattern={{major}}.{{minor}}
type=sha
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+3
View File
@@ -42,6 +42,9 @@ jobs:
type=ref,event=branch type=ref,event=branch
type=ref,event=pr type=ref,event=pr
type=semver,pattern={{version}} type=semver,pattern={{version}}
# A fix to release 1.2.3 is tagged v1.2.3.1: four numbers are not semver, so
# the pattern above makes no tag for it; this one does (image tag 1.2.3.1).
type=match,pattern=v(\d+\.\d+\.\d+\.\d+),group=1
type=semver,pattern={{major}}.{{minor}} type=semver,pattern={{major}}.{{minor}}
type=sha type=sha
+3 -3
View File
@@ -8,7 +8,8 @@ This plugin enriches video metadata by querying the TMDB API:
- **Search by IMDB ID**: Uses existing IMDB ID for precise matching - **Search by IMDB ID**: Uses existing IMDB ID for precise matching
- **Search by title**: Falls back to title/year search - **Search by title**: Falls back to title/year search
- **Image download**: Downloads poster and backdrop images to `/files/poster/` - **Image download**: Downloads poster and backdrop images to `/files/plugin/tmdb/`
- **Alternative posters**: Lists up to 10 posters (the primary plus the best-voted alternatives, as `url` locator CIDs — nothing extra is downloaded)
- **Rich metadata**: Fetches plot, rating, genres, studios - **Rich metadata**: Fetches plot, rating, genres, studios
**Note**: This runs on the background queue as it makes external API calls. **Note**: This runs on the background queue as it makes external API calls.
@@ -26,9 +27,8 @@ This plugin enriches video metadata by querying the TMDB API:
| `rating` | Vote average | | `rating` | Vote average |
| `plot/eng` | English plot synopsis | | `plot/eng` | English plot synopsis |
| `poster` | Poster image CID | | `poster` | Poster image CID |
| `posterPath` | Poster file path | | `posters/{lang3}/{cid}` | Alternative posters key-set, `poster` among them (METADATA_KEYS.md §6) |
| `backdrop` | Backdrop image CID | | `backdrop` | Backdrop image CID |
| `backdropPath` | Backdrop file path |
| `genres` | Genre set | | `genres` | Genre set |
| `studio` | Production company set | | `studio` | Production company set |
+2 -2
View File
@@ -5,7 +5,7 @@
"description": "MetaMesh plugin: Fetches metadata from TMDB API", "description": "MetaMesh plugin: Fetches metadata from TMDB API",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "build": "tsc", "start": "node dist/index.js" }, "scripts": { "build": "tsc", "start": "node dist/index.js", "test": "vitest run", "test:watch": "vitest" },
"dependencies": { "fastify": "^5.0.0", "axios": "^1.6.0" }, "dependencies": { "fastify": "^5.0.0", "axios": "^1.6.0" },
"devDependencies": { "@types/node": "^20.0.0", "typescript": "^5.3.0" } "devDependencies": { "@types/node": "^20.0.0", "typescript": "^5.3.0", "vitest": "^1.6.1" }
} }
+1088
View File
File diff suppressed because it is too large Load Diff
+188
View File
@@ -0,0 +1,188 @@
/**
* Beacon v2 advertiser — makes this plugin findable by meta-sort's Plugins
* page (Scan → Add) without anyone typing its URL.
*
* Advertises one resource, cap `metamesh.enrich/<manifest id>`, on the beacon
* group (239.255.99.1:9099): unsolicited every 10 s, and unicast in reply to
* any probe whose `want` matches. Says `bye` on shutdown. It keeps no view of
* other nodes — a plugin only needs to be found. Spec:
* meta-root docs/project-architecture/beacon-v2.md.
*
* Env:
* ENABLE_UDP_DISCOVERY false/0/no/off disables
* BEACON_ADVERTISE_URL endpoints.http (default http://$HOSTNAME:$PORT)
* BEACON_BINDS the one meta-sort instance allowed to list it
* (meta-sort sets this on containers it spawns)
* BEACON_GROUP / BEACON_PORT / BEACON_INTERVAL_MS
*
* ⚠ MIRRORED FILE. Byte-identical copies live in every TypeScript
* metamesh-plugin-*; see meta-root `scripts/check-mirrors.sh`. Never fatal: a
* host that blocks multicast logs a warning and the plugin serves on.
*/
import dgram from 'dgram';
import { hostname, networkInterfaces } from 'os';
const PROTO = 'beacon';
const VERSION = 2;
interface Resource {
id: string;
caps: string[];
endpoints: Record<string, string>;
binds?: string;
}
interface NodeInfo {
name: string;
instance: string;
version?: string;
}
function envNum(key: string): number | undefined {
const n = Number(process.env[key]);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
function enabled(): boolean {
const v = (process.env.ENABLE_UDP_DISCOVERY ?? '').trim().toLowerCase();
return !['false', '0', 'no', 'off'].includes(v);
}
/** IPv4 addresses of every up, non-internal interface. */
function interfaceAddresses(): string[] {
const out: string[] = [];
for (const list of Object.values(networkInterfaces())) {
for (const ni of list ?? []) {
const v4 = (ni as { family: string | number }).family === 'IPv4' || (ni as { family: string | number }).family === 4;
if (v4 && !ni.internal && ni.address) out.push(ni.address);
}
}
return out;
}
/** Same matching rules as the spec: `*`, `x/*`, optional `@contract`. */
function capMatches(pattern: string, cap: string): boolean {
if (pattern === '*') return true;
const split = (s: string): [string, string | null] => {
const i = s.lastIndexOf('@');
return i >= 0 ? [s.slice(0, i), s.slice(i + 1)] : [s, null];
};
const [pb, pc] = split(pattern);
const [cb, cc] = split(cap);
if (pc !== null && cc !== pc) return false;
if (pb.endsWith('/*')) {
const prefix = pb.slice(0, -2);
const rest = cb.startsWith(prefix) ? cb.slice(prefix.length) : '';
return rest.startsWith('/') && rest.length > 1;
}
return pb === cb;
}
let socket: dgram.Socket | null = null;
let timer: NodeJS.Timeout | null = null;
let node: NodeInfo | null = null;
let resource: Resource | null = null;
let ifaces: string[] = [];
let group = '239.255.99.1';
let udpPort = 9099;
function send(msg: object, dest?: { address: string; port: number }): void {
const s = socket;
if (!s) return;
const body = Buffer.from(JSON.stringify(msg));
if (dest) {
s.send(body, dest.port, dest.address, () => {});
return;
}
// Once per interface: the default route alone reaches one network.
for (const addr of ifaces) {
try {
s.setMulticastInterface(addr);
s.send(body, udpPort, group, () => {});
} catch (e) {
console.warn(`[beacon] send on ${addr} failed:`, e);
}
}
}
function advertise(dest?: { address: string; port: number }): void {
if (!node || !resource) return;
send({ proto: PROTO, v: VERSION, type: 'advertise', node, resources: [resource] }, dest);
}
/**
* Start advertising this plugin. Call once the HTTP server is listening, so a
* consumer that hears it can reach it. Idempotent.
*/
export function startBeacon(pluginId: string, version: string, httpPort: number): void {
if (socket || !enabled()) return;
group = process.env.BEACON_GROUP || group;
udpPort = envNum('BEACON_PORT') ?? udpPort;
const intervalMs = envNum('BEACON_INTERVAL_MS') ?? 10_000;
const instance = process.env.HOSTNAME || hostname();
const url = (process.env.BEACON_ADVERTISE_URL || `http://${instance}:${httpPort}`).replace(/\/+$/, '');
const binds = (process.env.BEACON_BINDS || '').trim();
node = { name: `metamesh-plugin-${pluginId}`, instance, ...(version ? { version } : {}) };
resource = {
id: pluginId,
caps: [`metamesh.enrich/${pluginId}`],
endpoints: { http: url, manifest: '/manifest' },
...(binds ? { binds } : {}),
};
const s = dgram.createSocket({ type: 'udp4', reuseAddr: true });
socket = s;
s.on('error', (err) => console.warn('[beacon] socket error:', err.message));
s.on('message', (buf, rinfo) => {
let m: { proto?: string; v?: number; type?: string; from?: string; want?: string[] };
try {
m = JSON.parse(buf.toString('utf8'));
} catch {
return; // foreign traffic on the shared group
}
if (m?.proto !== PROTO || m.v !== VERSION || m.type !== 'probe' || m.from === instance) return;
const want = Array.isArray(m.want) ? m.want : [];
if (want.length === 0 || resource!.caps.some((c) => want.some((p) => capMatches(p, c)))) {
advertise({ address: rinfo.address, port: rinfo.port });
}
});
s.bind(udpPort, '0.0.0.0', () => {
try {
s.setMulticastTTL(1);
} catch {
/* best effort */
}
ifaces = interfaceAddresses();
for (const addr of ifaces) {
try {
s.addMembership(group, addr);
} catch (e) {
console.warn(`[beacon] join ${group} on ${addr} failed:`, e);
}
}
console.log(`[beacon] advertising metamesh.enrich/${pluginId} at ${url} on ${group}:${udpPort}`);
advertise();
timer = setInterval(() => advertise(), intervalMs);
timer.unref?.();
});
}
/** Say `bye` so consumers drop this plugin at once. */
export async function stopBeacon(): Promise<void> {
if (!socket || !node) return;
if (timer) clearInterval(timer);
send({ proto: PROTO, v: VERSION, type: 'bye', node });
// Let the bye datagrams leave before the socket closes under them.
await new Promise((r) => setTimeout(r, 50));
const s = socket;
socket = null;
await new Promise<void>((resolve) => {
try {
s.close(() => resolve());
} catch {
resolve();
}
});
}
+58
View File
@@ -0,0 +1,58 @@
/**
* CID encoding helpers (METADATA_KEYS.md §2).
*/
const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
/** RFC 4648 base32, lowercase, no padding, with the `b` multibase prefix. */
export function base32LowerMultibase(bytes: Uint8Array): string {
let out = 'b';
let bits = 0;
let value = 0;
for (const byte of bytes) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
bits -= 5;
out += BASE32_ALPHABET[(value >> bits) & 0x1f];
}
}
if (bits > 0) {
out += BASE32_ALPHABET[(value << (5 - bits)) & 0x1f];
}
return out;
}
/** Unsigned LEB128 varint, as multiformats encodes codecs and lengths. */
function varint(value: number): number[] {
const out: number[] = [];
let n = value;
while (n >= 0x80) {
out.push((n & 0x7f) | 0x80);
n = Math.floor(n / 0x80);
}
out.push(n);
return out;
}
/** Custom multicodec of the `url` locator (METADATA_KEYS.md §2.1). */
export const URL_LOCATOR_CODEC = 0x1006;
/**
* Encode an absolute http(s) URL as a `0x1006` identity-multihash CIDv1:
* `[0x01][varint codec][0x00][varint len][utf-8 url]`, base32lower. The digest
* is the URL itself, so minting one costs no I/O. `null` for anything that is
* not an absolute http(s) URL.
*
* CROSS-BINARY CONTRACT: byte-identical to meta-feeder-sdk's `compute_url_cid`
* (`hash.rs`); both test suites pin the same vectors.
*/
export function encodeUrlCid(url: string): string | null {
const trimmed = url.trim();
if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
return null;
}
const digest = Buffer.from(trimmed, 'utf8');
const header = Buffer.from([0x01, ...varint(URL_LOCATOR_CODEC), 0x00, ...varint(digest.length)]);
return base32LowerMultibase(Buffer.concat([header, digest]));
}
+3 -2
View File
@@ -27,6 +27,7 @@
import Fastify from 'fastify'; import Fastify from 'fastify';
import type { HealthResponse, ProcessRequest, ProcessResponse, CallbackPayload, ConfigureRequest, ConfigureResponse } from './types.js'; import type { HealthResponse, ProcessRequest, ProcessResponse, CallbackPayload, ConfigureRequest, ConfigureResponse } from './types.js';
import { manifest, process as processFile, configure } from './plugin.js'; import { manifest, process as processFile, configure } from './plugin.js';
import { startBeacon, stopBeacon } from './beacon-advertise.js';
const app = Fastify({ logger: true }); const app = Fastify({ logger: true });
let ready = false; let ready = false;
@@ -64,5 +65,5 @@ app.post<{ Body: ProcessRequest }>('/process', async (request, reply) => {
}); });
const port = parseInt(process.env.PORT || '8080', 10); const port = parseInt(process.env.PORT || '8080', 10);
app.listen({ port, host: '0.0.0.0' }).then(() => { ready = true; console.log(`[${manifest.id}] Listening on port ${port}`); }); app.listen({ port, host: '0.0.0.0' }).then(() => { startBeacon(manifest.id, manifest.version, port); ready = true; console.log(`[${manifest.id}] Listening on port ${port}`); });
process.on('SIGTERM', async () => { ready = false; await app.close(); process.exit(0); }); process.on('SIGTERM', async () => { await stopBeacon(); ready = false; await app.close(); process.exit(0); });
+345 -54
View File
@@ -1,89 +1,380 @@
/** /**
* meta-core API Client for writing metadata * meta-core client: signed claim writes (MMUR2) + plain reads.
* Fails gracefully if meta-core is unavailable (logs warning, returns without throwing) *
* MIRRORED byte-for-byte across every `metamesh-plugin-*` TypeScript plugin and
* meta-sort-core (`src/kv/meta-core-client.ts`) — guarded by
* `scripts/check-mirrors.sh`. Edit one copy, then copy it everywhere.
*
* Every write is a vote signed by THIS container's key
* (docs/implementation/metacore-claims-model.md §3, §9):
*
* bytes_to_sign = "MMUR2\n" || canonical CBOR [cid, uid, key, value, ts]
* sig = ECDSA-secp256k1(SHA-256(bytes)), compact r||s, low-S
*
* and is posted to `POST {baseUrl}/api/claims` — meta-core directly, or
* meta-sort's pass-through relay when the plugin runs under meta-sort. The
* encoding is pinned by meta-core's `internal/claim/testdata/claim-vectors.json`
* (vendored as `test/claim-vectors.json`).
*
* Key: `METAMESH_SIGNING_KEY` (64 hex chars) or `METAMESH_SIGNING_KEY_FILE`
* (read; generated and written 0600 if missing). With neither, writes are
* refused (logged, return false) — no silent throwaway identities.
*
* Fails gracefully if meta-core is unavailable: logs and returns, never throws.
*/ */
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
// ---------------------------------------------------------------- encoding --
const DOMAIN = Buffer.from('MMUR2\n', 'utf8');
const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const N = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');
const HALF_N = N >> 1n;
/** A claim value: text (public), bytes (private envelope) or null (retraction). */
export type ClaimValue = string | Uint8Array | null;
export interface SignedClaim {
cid: string;
uid: string;
key: string;
value: ClaimValue;
ts: number;
sig: Uint8Array;
}
function head(major: number, n: number | bigint): Buffer {
const m = major << 5;
const v = BigInt(n);
if (v < 24n) return Buffer.from([m | Number(v)]);
if (v <= 0xffn) return Buffer.from([m | 24, Number(v)]);
if (v <= 0xffffn) {
const b = Buffer.alloc(3);
b[0] = m | 25;
b.writeUInt16BE(Number(v), 1);
return b;
}
if (v <= 0xffffffffn) {
const b = Buffer.alloc(5);
b[0] = m | 26;
b.writeUInt32BE(Number(v), 1);
return b;
}
const b = Buffer.alloc(9);
b[0] = m | 27;
b.writeBigUInt64BE(v, 1);
return b;
}
function text(s: string): Buffer {
const raw = Buffer.from(s, 'utf8');
return Buffer.concat([head(3, raw.length), raw]);
}
/** The exact bytes an MMUR2 signature covers. */
export function signedBytes(cid: string, uid: string, key: string, value: ClaimValue, ts: number): Buffer {
let v: Buffer;
if (value === null) v = Buffer.from([0xf6]);
else if (typeof value === 'string') v = text(value);
else v = Buffer.concat([head(2, value.length), Buffer.from(value)]);
return Buffer.concat([DOMAIN, head(4, 5), text(cid), text(uid), text(key), v, head(0, ts)]);
}
function base58Encode(bytes: Uint8Array): string {
let n = BigInt('0x' + (Buffer.from(bytes).toString('hex') || '0'));
let out = '';
while (n > 0n) {
out = B58[Number(n % 58n)] + out;
n /= 58n;
}
for (const b of bytes) {
if (b !== 0) break;
out = '1' + out;
}
return out;
}
function base58Decode(s: string): Buffer {
let n = 0n;
for (const ch of s) {
const i = B58.indexOf(ch);
if (i < 0) throw new Error(`invalid base58 character ${ch}`);
n = n * 58n + BigInt(i);
}
let hex = n === 0n ? '' : n.toString(16);
if (hex.length % 2) hex = '0' + hex;
let zeros = 0;
while (zeros < s.length && s[zeros] === '1') zeros++;
return Buffer.concat([Buffer.alloc(zeros), Buffer.from(hex, 'hex')]);
}
function b64url(b: Buffer): string {
return b.toString('base64url');
}
function publicKeyFromCompressed(compressed: Buffer): crypto.KeyObject {
const full = crypto.ECDH.convertKey(compressed, 'secp256k1', undefined, undefined, 'uncompressed') as Buffer;
return crypto.createPublicKey({
key: { kty: 'EC', crv: 'secp256k1', x: b64url(full.subarray(1, 33)), y: b64url(full.subarray(33, 65)) },
format: 'jwk',
});
}
/** Rewrite a compact signature to its low-S form (MMUR2 refuses high-S). */
function lowS(sig: Buffer): Buffer {
const s = BigInt('0x' + sig.subarray(32).toString('hex'));
if (s <= HALF_N) return sig;
const fixed = Buffer.from((N - s).toString(16).padStart(64, '0'), 'hex');
return Buffer.concat([sig.subarray(0, 32), fixed]);
}
/** True when the claim's signature is a valid low-S signature by its uid. */
export function verifyClaim(c: SignedClaim): boolean {
try {
const sig = Buffer.from(c.sig);
if (sig.length !== 64) return false;
if (BigInt('0x' + sig.subarray(32).toString('hex')) > HALF_N) return false;
if (!c.uid.startsWith('z')) return false;
const pub = base58Decode(c.uid.slice(1));
if (pub.length !== 33) return false;
return crypto.verify(
'sha256',
signedBytes(c.cid, c.uid, c.key, c.value, c.ts),
{ key: publicKeyFromCompressed(pub), dsaEncoding: 'ieee-p1363' },
sig,
);
} catch {
return false;
}
}
// ----------------------------------------------------------------- signer --
export class ClaimSigner {
readonly uid: string;
private readonly key: crypto.KeyObject;
private lastTs = 0;
constructor(privateKeyHex: string) {
const hex = privateKeyHex.trim().replace(/^0x/i, '');
if (!/^[0-9a-fA-F]{64}$/.test(hex)) throw new Error('signing key must be 64 hex characters');
const d = Buffer.from(hex, 'hex');
const ecdh = crypto.createECDH('secp256k1');
ecdh.setPrivateKey(d);
const full = ecdh.getPublicKey(null, 'uncompressed');
this.uid = 'z' + base58Encode(ecdh.getPublicKey(null, 'compressed'));
this.key = crypto.createPrivateKey({
key: {
kty: 'EC', crv: 'secp256k1', d: b64url(d),
x: b64url(full.subarray(1, 33)), y: b64url(full.subarray(33, 65)),
},
format: 'jwk',
});
}
/** Milliseconds, strictly increasing within this process (ts is the version). */
nextTs(): number {
this.lastTs = Math.max(Date.now(), this.lastTs + 1);
return this.lastTs;
}
sign(cid: string, key: string, value: ClaimValue, ts: number = this.nextTs()): SignedClaim {
const raw = crypto.sign('sha256', signedBytes(cid, this.uid, key, value, ts), {
key: this.key,
dsaEncoding: 'ieee-p1363',
});
return { cid, uid: this.uid, key, value, ts, sig: lowS(raw) };
}
}
let cachedSigner: ClaimSigner | null | undefined;
/**
* The process signer from the environment, or null when no key is configured.
* Read lazily on first write; `resetSignerForTests()` forgets it.
*/
export function loadSigner(): ClaimSigner | null {
if (cachedSigner !== undefined) return cachedSigner;
const inline = process.env.METAMESH_SIGNING_KEY;
const file = process.env.METAMESH_SIGNING_KEY_FILE;
try {
if (inline) {
cachedSigner = new ClaimSigner(inline);
} else if (file) {
if (!fs.existsSync(file)) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, crypto.randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
}
cachedSigner = new ClaimSigner(fs.readFileSync(file, 'utf8'));
} else {
cachedSigner = null;
}
} catch (error) {
console.warn(`[MetaCoreClient] Signing key unusable: ${error instanceof Error ? error.message : String(error)}`);
cachedSigner = null;
}
if (cachedSigner) console.log(`[MetaCoreClient] Signing claims as ${cachedSigner.uid}`);
else console.warn('[MetaCoreClient] No METAMESH_SIGNING_KEY / METAMESH_SIGNING_KEY_FILE — metadata writes are refused');
return cachedSigner;
}
export function resetSignerForTests(): void {
cachedSigner = undefined;
}
/** The §3.4 JSON form. */
export function claimToJSON(c: SignedClaim): Record<string, unknown> {
let value: unknown = null;
if (typeof c.value === 'string') value = c.value;
else if (c.value) value = { b64: Buffer.from(c.value).toString('base64') };
return { cid: c.cid, uid: c.uid, key: c.key, value, ts: c.ts, sig: Buffer.from(c.sig).toString('base64') };
}
// ----------------------------------------------------------------- client --
export class MetaCoreClient { export class MetaCoreClient {
constructor(private baseUrl: string) {} constructor(private baseUrl: string) {}
private async safeFetch(url: string, options: RequestInit): Promise<Response | null> { private async safeFetch(url: string, options: RequestInit): Promise<Response | null> {
try { try {
return await fetch(url, { ...options, signal: AbortSignal.timeout(5000) }); return await fetch(url, { ...options, signal: AbortSignal.timeout(10000) });
} catch (error) { } catch (error) {
console.warn(`[MetaCoreClient] Warning: meta-core unavailable at ${this.baseUrl}`); console.warn(`[MetaCoreClient] Warning: meta-core unavailable at ${this.baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
return null; return null;
} }
} }
async setProperty(hashId: string, key: string, value: string): Promise<void> { /**
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { * Sign and post claims about `cid`. True when every claim was accepted (or
method: 'PUT', * was already stored: `unchanged` / `stale` are not failures).
*/
async writeClaims(cid: string, values: Array<[string, ClaimValue]>): Promise<boolean> {
if (values.length === 0) return true;
const signer = loadSigner();
if (!signer) return false;
const claims = values.map(([key, value]) => claimToJSON(signer.sign(cid, key, value)));
const response = await this.safeFetch(`${this.baseUrl}/api/claims`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value }), body: JSON.stringify(claims),
}); });
if (response && !response.ok) { if (!response) return false;
console.warn(`[MetaCoreClient] Failed to set property: ${response.status}`); if (!response.ok) {
console.warn(`[MetaCoreClient] Claims for ${cid} rejected: ${response.status}`);
return false;
} }
const statuses = await response.json().catch(() => null) as Array<{ status?: string; reason?: string }> | null;
const bad = (statuses ?? []).filter((s) => s.status === 'bad_signature' || s.status === 'bad_request');
if (bad.length > 0) {
console.warn(`[MetaCoreClient] ${bad.length} claim(s) for ${cid} refused: ${bad[0].status} ${bad[0].reason ?? ''}`);
return false;
}
return true;
}
/** One text claim. */
async setProperty(hashId: string, key: string, value: string): Promise<boolean> {
return this.writeClaims(hashId, [[key, String(value)]]);
}
/** One text claim per entry, in a single batch. */
async mergeMetadata(hashId: string, metadata: Record<string, string>): Promise<boolean> {
return this.writeClaims(hashId, Object.entries(metadata).map(([k, v]) => [k, String(v)]));
}
/**
* Retract this signer's own vote for `key`. Other signers' votes for the
* same key are untouched (there are no negative votes).
*/
async deleteProperty(hashId: string, key: string): Promise<boolean> {
return this.writeClaims(hashId, [[key, null]]);
}
/**
* Append a member to a legacy csv-set field (`genres`, `studio`, `tags`,
* `announceList`, …) — the comma-joined shape readers still parse (the
* METADATA_KEYS §14.12 key-set migration is out of scope for phase 1).
*
* Under claims a signer owns only its OWN vote, so this reads this
* signer's current claim for (cid, key) from
* `GET /api/meta/{cid}/claims?key=<key>` (other signers' claims are
* ignored), adds the member if absent and signs the new full value as one
* text claim. Members are kept raw (no escaping), same as the old
* meta-sort `_add` proxy. A member already present writes nothing.
*/
async addToSet(hashId: string, key: string, value: string): Promise<boolean> {
const member = String(value);
if (!member) return true;
const signer = loadSigner();
if (!signer) return false;
const current = await this.ownClaimValue(hashId, key, signer.uid);
if (current === undefined) return false; // could not read: never clobber our own set
const members = current ? current.split(',').map((v) => v.trim()).filter(Boolean) : [];
if (members.includes(member)) return true;
return this.writeClaims(hashId, [[key, [...members, member].join(',')]]);
}
/**
* This signer's newest text claim for (cid, key): the value, `null` when it
* has none, `undefined` when the claims could not be read.
*/
private async ownClaimValue(cid: string, key: string, uid: string): Promise<string | null | undefined> {
const url = `${this.baseUrl}/api/meta/${encodeURIComponent(cid)}/claims?key=${encodeURIComponent(key)}`;
const response = await this.safeFetch(url, { method: 'GET' });
if (!response) return undefined;
if (response.status === 404) return null;
if (!response.ok) {
console.warn(`[MetaCoreClient] Failed to read claims for ${cid}/${key}: ${response.status}`);
return undefined;
}
const body = await response.json().catch(() => null) as unknown;
const list = (Array.isArray(body) ? body : (body as { claims?: unknown })?.claims) as
Array<{ uid?: string; key?: string; value?: unknown; ts?: number }> | undefined;
let best: { value: string; ts: number } | null = null;
for (const c of Array.isArray(list) ? list : []) {
if (c.uid !== uid || c.key !== key || typeof c.value !== 'string') continue;
const ts = Number(c.ts) || 0;
if (!best || ts > best.ts) best = { value: c.value, ts };
}
return best ? best.value : null;
} }
async getProperty(hashId: string, key: string): Promise<string | null> { async getProperty(hashId: string, key: string): Promise<string | null> {
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' }); const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' });
if (!response || response.status === 404) return null; if (!response || !response.ok) return null;
if (!response.ok) return null; const data = await response.json() as { value?: unknown };
const data = await response.json() as { value?: string }; return data.value === undefined || data.value === null ? null : String(data.value);
return data.value ?? null;
} }
async mergeMetadata(hashId: string, metadata: Record<string, string>): Promise<void> { /**
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { * Whole merged record, in whatever form the endpoint serves (meta-sort's
method: 'PATCH', * /meta is nested, meta-core's is flat) — callers flatten. `null` when the
headers: { 'Content-Type': 'application/json' }, * call itself failed, `{}` when the record does not exist.
body: JSON.stringify(metadata), */
}); async getMetadata(hashId: string): Promise<Record<string, unknown> | null> {
if (response && !response.ok) {
console.warn(`[MetaCoreClient] Failed to merge metadata: ${response.status}`);
}
}
async deleteProperty(hashId: string, key: string): Promise<void> {
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'DELETE' });
if (response && !response.ok && response.status !== 404) {
console.warn(`[MetaCoreClient] Failed to delete property: ${response.status}`);
}
}
async addToSet(hashId: string, key: string, value: string): Promise<void> {
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/_add/${key}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value }),
});
if (response && !response.ok) {
console.warn(`[MetaCoreClient] Failed to add to set: ${response.status}`);
}
}
async getMetadata(hashId: string): Promise<Record<string, string>> {
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' }); const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' });
if (!response || response.status === 404) return {}; if (!response) return null;
if (!response.ok) return {}; if (response.status === 404) return {};
const data = await response.json() as { metadata?: Record<string, string> }; if (!response.ok) return null;
const data = await response.json() as { metadata?: Record<string, unknown> };
return data.metadata ?? {}; return data.metadata ?? {};
} }
/** /**
* Compute CID for a file * Compute the CID of a file under FILES_PATH via meta-core's `POST /file/cid`.
* @param path - Path relative to FILES_PATH (e.g., "poster/Movie (2024)[tmdb12345]_poster.jpg") * @param filePath - path relative to FILES_PATH (e.g. "poster/Movie (2024)_poster.jpg")
* @returns CID string or null if failed
*/ */
async computeFileCID(path: string): Promise<string | null> { async computeFileCID(filePath: string): Promise<string | null> {
const response = await this.safeFetch(`${this.baseUrl}/file/cid`, { const response = await this.safeFetch(`${this.baseUrl}/file/cid`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path }), body: JSON.stringify({ path: filePath }),
}); });
if (!response || !response.ok) return null; if (!response || !response.ok) return null;
const data = await response.json() as { cid?: string }; const data = await response.json().catch(() => null) as { cid?: string } | null;
return data.cid ?? null; return data?.cid ?? null;
} }
} }
+272 -134
View File
@@ -9,7 +9,8 @@
* PLUGIN FILE ACCESS ARCHITECTURE * PLUGIN FILE ACCESS ARCHITECTURE
* ============================================================================ * ============================================================================
* *
* File access via WebDAV (WEBDAV_URL environment variable): * File access via WebDAV, on the meta-core named by each /process request
* (its /urls -> webdavUrlInternal; WEBDAV_URL overrides):
* - Read media files: GET /webdav/watch/... or /webdav/test/... * - Read media files: GET /webdav/watch/... or /webdav/test/...
* - Write output: PUT /webdav/plugin/tmdb/... * - Write output: PUT /webdav/plugin/tmdb/...
* - Cache: Local /cache mount (for JSON cache files) * - Cache: Local /cache mount (for JSON cache files)
@@ -18,33 +19,29 @@
* - No output mount needed on plugin containers * - No output mount needed on plugin containers
* - Consistent read/write architecture via HTTP * - Consistent read/write architecture via HTTP
* - Works in any orchestration environment * - Works in any orchestration environment
* - Posters land in the same core the CIDs are written to, always
* *
* ============================================================================ * ============================================================================
* *
* Matches old TMDBProcessor output: * Matches old TMDBProcessor output:
* - tmdbid, imdbid * - tmdbid, imdbid
* - originalTitle, movieYear, releasedate * - title, originalTitle, movieYear, releasedate
* - titles/<lang3>/<name> key-set: localized + original title + every AKA
* - plot/eng, rating * - plot/eng, rating
* - genres (add), studio (add), tags (add) * - genres (add), studio (add), tags (add)
* - poster, backdrop (CID hashes of downloaded images) * - poster, backdrop (CID hashes of downloaded images)
* - posters/{lang3}/{cid} (alternative posters as url locators, `poster` among them)
*/ */
import axios from 'axios'; import axios from 'axios';
import { statSync, openSync, readSync, closeSync } from 'fs';
import { createHash } from 'crypto'; import { createHash } from 'crypto';
import * as path from 'path'; import * as path from 'path';
import type { PluginManifest, ProcessRequest, CallbackPayload } from './types.js'; import type { PluginManifest, ProcessRequest, CallbackPayload } from './types.js';
import { MetaCoreClient } from './meta-core-client.js'; import { MetaCoreClient } from './meta-core-client.js';
import { readJson, writeJson } from './cache.js'; import { readJson, writeJson } from './cache.js';
import { createWebDAVClient, WebDAVClient } from './webdav-client.js'; import { getWebDAVClient, WebDAVClient } from './webdav-client.js';
import { base32LowerMultibase } from './cid.js';
// Initialize WebDAV client - required for plugin operation import { posterMembers } from './posters.js';
const webdavClient = createWebDAVClient();
if (webdavClient) {
console.log('[tmdb] WebDAV client initialized for file access');
} else {
console.warn('[tmdb] WARNING: WEBDAV_URL not set - plugin will not be able to write output files');
}
const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/original'; const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/original';
@@ -52,54 +49,14 @@ const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/original';
* ============================================================================ * ============================================================================
* PLUGIN OUTPUT PATH - Written via WebDAV * PLUGIN OUTPUT PATH - Written via WebDAV
* ============================================================================ * ============================================================================
* Output files (posters, backdrops) are written via WebDAV PUT requests. * Output files (posters, backdrops) are written via WebDAV PUT requests, to the
* Path: /files/plugin/tmdb/<filename> (accessible at WEBDAV_URL/plugin/tmdb/) * WebDAV of the meta-core that issued the /process call.
* Path: /files/plugin/tmdb/<filename>
* CACHE_PATH (/cache) - Local mount for plugin cache (handled by cache.ts) * CACHE_PATH (/cache) - Local mount for plugin cache (handled by cache.ts)
* ============================================================================ * ============================================================================
*/ */
const PLUGIN_OUTPUT_WEBDAV_PATH = '/files/plugin/tmdb'; const PLUGIN_OUTPUT_WEBDAV_PATH = '/files/plugin/tmdb';
/**
* Compute midhash256 CID for a file (matches meta-hash algorithm)
*
* Algorithm:
* - For files <= 1MB: Hashes entire file content + 8-byte size prefix
* - For files > 1MB: Hashes middle 1MB + 8-byte size prefix
* - Returns CIDv1 with custom codec 0x1000
*/
function computeMidHash256Sync(filePath: string): string {
const SAMPLE_SIZE = 1024 * 1024; // 1MB
// varint encoding of 0x1000 (4096) for both codec and hash function code
const MIDHASH_VARINT = Buffer.from([0x80, 0x20]);
// Get file size
const stats = statSync(filePath);
const fileSize = stats.size;
// Create size buffer (64-bit big-endian)
const sizeBuffer = Buffer.allocUnsafe(8);
sizeBuffer.writeBigUInt64BE(BigInt(fileSize), 0);
// Extract sample data
let sampleData: Buffer;
if (fileSize <= SAMPLE_SIZE) {
// Small file: read entire content
const fd = openSync(filePath, 'r');
sampleData = Buffer.allocUnsafe(fileSize);
readSync(fd, sampleData, 0, fileSize, 0);
closeSync(fd);
} else {
// Large file: read middle 1MB
const middleOffset = Math.floor((fileSize - SAMPLE_SIZE) / 2);
const fd = openSync(filePath, 'r');
sampleData = Buffer.allocUnsafe(SAMPLE_SIZE);
readSync(fd, sampleData, 0, SAMPLE_SIZE, middleOffset);
closeSync(fd);
}
return computeMidHash256FromData(fileSize, sampleData);
}
/** /**
* Compute midhash256 CID via WebDAV * Compute midhash256 CID via WebDAV
*/ */
@@ -151,33 +108,7 @@ function computeMidHash256FromData(fileSize: number, sampleData: Buffer): string
]); ]);
// Encode as base32lower with 'b' prefix (multibase) // Encode as base32lower with 'b' prefix (multibase)
const base32Chars = 'abcdefghijklmnopqrstuvwxyz234567'; return base32LowerMultibase(cidBytes);
let cid = 'b';
let bits = 0;
let value = 0;
for (const byte of cidBytes) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
bits -= 5;
cid += base32Chars[(value >> bits) & 0x1f];
}
}
if (bits > 0) {
cid += base32Chars[(value << (5 - bits)) & 0x1f];
}
return cid;
}
/**
* Compute midhash256 CID for a file (auto-selects WebDAV or filesystem)
*/
async function computeMidHash256(filePath: string): Promise<string> {
if (webdavClient) {
return computeMidHash256WebDAV(webdavClient, filePath);
}
return computeMidHash256Sync(filePath);
} }
export const manifest: PluginManifest = { export const manifest: PluginManifest = {
@@ -225,6 +156,51 @@ let forceRecompute = false;
const BASE_URL = 'https://api.themoviedb.org/3'; const BASE_URL = 'https://api.themoviedb.org/3';
// ISO 639-1 → ISO 639-3 (`lang3`, the 639-2/T form where B/T differ) for the
// languages TMDB commonly returns. Unknown codes map to nothing.
const ISO639_1_TO_3: Record<string, string> = {
en: 'eng', ja: 'jpn', fr: 'fra', de: 'deu', es: 'spa', it: 'ita', ru: 'rus',
ko: 'kor', zh: 'zho', pt: 'por', nl: 'nld', sv: 'swe', no: 'nor', da: 'dan',
fi: 'fin', pl: 'pol', tr: 'tur', cs: 'ces', hu: 'hun', el: 'ell', he: 'heb',
th: 'tha', vi: 'vie', id: 'ind', uk: 'ukr', ro: 'ron', ar: 'ara', fa: 'fas',
hi: 'hin', ta: 'tam', te: 'tel', ms: 'msa', tl: 'tgl', ca: 'cat', bg: 'bul',
hr: 'hrv', sr: 'srp', sk: 'slk', sl: 'slv', et: 'est', lv: 'lav', lt: 'lit',
is: 'isl', ga: 'gle', cn: 'zho',
};
function iso639_1to3(code: string | undefined | null): string | undefined {
return code ? ISO639_1_TO_3[code.trim().toLowerCase()] : undefined;
}
// TMDB keys AKAs by MARKET (`iso_3166_1`), not language. Only markets that
// clearly imply one language are mapped; a multilingual or unknown market
// (CA, CH, BE, IN, HK, SG, …, or empty) files its AKA under `und` rather than
// guessing (METADATA_KEYS.md §3).
const MARKET_TO_LANG3: Record<string, string> = {
US: 'eng', GB: 'eng', AU: 'eng', NZ: 'eng', IE: 'eng',
FR: 'fra', DE: 'deu', AT: 'deu', ES: 'spa', MX: 'spa', AR: 'spa', CO: 'spa',
CL: 'spa', PE: 'spa', VE: 'spa', IT: 'ita', BR: 'por', PT: 'por', JP: 'jpn',
KR: 'kor', CN: 'zho', TW: 'zho', RU: 'rus', NL: 'nld', SE: 'swe', NO: 'nor',
DK: 'dan', FI: 'fin', PL: 'pol', TR: 'tur', CZ: 'ces', HU: 'hun', GR: 'ell',
IL: 'heb', TH: 'tha', VN: 'vie', ID: 'ind', UA: 'ukr', RO: 'ron', IR: 'fas',
SA: 'ara', EG: 'ara', AE: 'ara', BG: 'bul', HR: 'hrv', RS: 'srp', SK: 'slk',
SI: 'slv', EE: 'est', LV: 'lav', LT: 'lit', IS: 'isl',
};
function marketToLang3(market: string | undefined | null): string {
return (market && MARKET_TO_LANG3[market.trim().toUpperCase()]) || 'und';
}
/**
* `titles/<lang3>/<name>` key-set member key (METADATA_KEYS.md §3): trimmed,
* whitespace collapsed, `/` (the key-set separator) written as U+2215 `∕`.
* `undefined` when nothing is left to name.
*/
function titleMemberKey(lang3: string, name: string | undefined | null): string | undefined {
const clean = (name ?? '').trim().replace(/\s+/g, ' ').replace(/\//g, '\u2215');
return clean ? `titles/${lang3}/${clean}` : undefined;
}
let apiKey: string | null = null; let apiKey: string | null = null;
let isV4Token = false; let isV4Token = false;
let metadataLanguage = 'en-US'; let metadataLanguage = 'en-US';
@@ -275,7 +251,17 @@ async function findByImdbId(imdbId: string): Promise<any> {
async function getByTmdbId(tmdbId: string, mediaType: string): Promise<any> { async function getByTmdbId(tmdbId: string, mediaType: string): Promise<any> {
try { try {
const config = getAxiosConfig({ language: metadataLanguage }); // `alternative_titles` rides along so the AKAs land in `titles/*` (§3).
// `images` rides the same call too: the poster candidates for the
// `posters/{lang3}/{cid}` key-set (§6). `language` would otherwise filter
// them to one language, so widen it to the configured one, English and
// textless (`null`).
const lang1 = metadataLanguage.split('-')[0];
const config = getAxiosConfig({
language: metadataLanguage,
append_to_response: 'alternative_titles,images',
include_image_language: [...new Set([lang1, 'en'])].join(',') + ',null',
});
const response = await axios.get(`${BASE_URL}/${mediaType}/${tmdbId}`, config); const response = await axios.get(`${BASE_URL}/${mediaType}/${tmdbId}`, config);
return response.data; return response.data;
} catch { } catch {
@@ -352,6 +338,7 @@ async function downloadImageToWebDAV(
* no need to store any path in the parent file's metadata. * no need to store any path in the parent file's metadata.
*/ */
async function downloadAndHashImage( async function downloadAndHashImage(
webdavClient: WebDAVClient | null,
imagePath: string, imagePath: string,
imageType: string, imageType: string,
title: string, title: string,
@@ -409,6 +396,9 @@ export async function process(
): Promise<void> { ): Promise<void> {
const startTime = Date.now(); const startTime = Date.now();
const metaCore = new MetaCoreClient(request.metaCoreUrl); const metaCore = new MetaCoreClient(request.metaCoreUrl);
// WebDAV of the very core we're enriching, so poster blobs and the poster
// CIDs we write can never point at different cores. Cached per core URL.
const webdavClient = await getWebDAVClient(request.metaCoreUrl);
try { try {
const { cid, existingMeta } = request; const { cid, existingMeta } = request;
@@ -451,15 +441,26 @@ export async function process(
console.log(`[tmdb] Force recompute enabled for ${request.filePath ?? existingMeta?.fileName ?? cid}`); console.log(`[tmdb] Force recompute enabled for ${request.filePath ?? existingMeta?.fileName ?? cid}`);
} }
// Get midhash for caching const label = request.filePath ?? existingMeta?.fileName ?? cid;
const midhash = existingMeta?.['cid_midhash256'];
// Check cache (skip if forceRecompute) // Exact-file cache, keyed by the file's byte-hash. Only records carrying
// real file bytes have `cid_midhash256`; gateway/usenet records don't —
// which is exactly why the per-tmdbid cache below exists. Stores a full
// entry now, but tolerates the legacy raw-payload format from older builds.
const midhash = existingMeta?.['cid_midhash256'];
if (midhash && !forceRecompute) { if (midhash && !forceRecompute) {
const cachedData = await readJson<any>(`${midhash}_tmdb.json`); const cached = await readJson<any>(`${midhash}_aka_tmdb.json`);
if (cachedData) { if (cached) {
console.log(`[tmdb] Using cached TMDB data for ${request.filePath ?? existingMeta?.fileName ?? cid}`); console.log(`[tmdb] Using byte-hash cached TMDB data for ${label}`);
await applyTmdbData(metaCore, cid, cachedData); const isEntry = cached.data !== undefined;
await applyTmdbData(
metaCore,
webdavClient,
cid,
isEntry ? cached.data : cached,
// Legacy raw payloads carry no image CIDs → let applyTmdbData recompute.
isEntry ? { posterCid: cached.posterCid, backdropCid: cached.backdropCid } : undefined
);
await sendCallback({ await sendCallback({
taskId: request.taskId, taskId: request.taskId,
status: 'completed', status: 'completed',
@@ -469,33 +470,40 @@ export async function process(
} }
} }
let tmdbData = null; // Resolve the show/movie entry, deduped per tmdbid. A record that already
// carries a tmdbid anchor (every gateway torrent/usenet hit does) takes
// Resolve by a known TMDB id first (authoritative — e.g. a gateway // the cached + single-flighted fast path, so N releases of one show share
// anchor or jellyfin-nfo). Completes the full cycle (poster + plot + // ONE TMDB fetch + poster seed instead of N.
// genres) from an id alone, with no fuzzy re-search. let entry: TmdbCacheEntry | null = null;
const knownTmdbId = existingMeta?.tmdbid; const knownTmdbId = existingMeta?.tmdbid;
if (knownTmdbId) { if (knownTmdbId) {
const mediaType = const mediaType =
existingMeta?.videoType === 'tvshow' || existingMeta?.videoType === 'tv' existingMeta?.videoType === 'tvshow' || existingMeta?.videoType === 'tv'
? 'tv' ? 'tv'
: 'movie'; : 'movie';
tmdbData = await getByTmdbId(knownTmdbId, mediaType); entry = await resolveEntryById(webdavClient, knownTmdbId, mediaType);
} }
// Try by IMDB ID // Fallback: no usable id → resolve by IMDB id or fuzzy title, then cache
// the result by its resolved tmdbid so later releases of the same show
// take the fast path above.
if (!entry) {
let tmdbData: any = null;
const imdbId = existingMeta?.imdbid; const imdbId = existingMeta?.imdbid;
if (!tmdbData && imdbId) { if (imdbId) {
tmdbData = await findByImdbId(imdbId); tmdbData = await findByImdbId(imdbId);
} }
// Try by title search
if (!tmdbData) { if (!tmdbData) {
let title = existingMeta?.originalTitle || existingMeta?.fileName; // filename-parser's guess lives under `parsedTitle` since the
// claims model (D12); `originalTitle` is kept as a fallback for
// records an NFO or an older parser wrote.
let title = existingMeta?.parsedTitle || existingMeta?.originalTitle || existingMeta?.fileName;
const year = existingMeta?.movieYear; const year = existingMeta?.movieYear;
const videoType = existingMeta?.videoType; const videoType = existingMeta?.videoType;
// Strip trailing year from title if present (e.g., "Sintel 2010" -> "Sintel") // Strip trailing year from title if present ("Sintel 2010" -> "Sintel").
if (title && year) { if (title && year) {
const yearRegex = new RegExp(`\\s*[\\(\\[]?${year}[\\)\\]]?\\s*$`); const yearRegex = new RegExp(`\\s*[\\(\\[]?${year}[\\)\\]]?\\s*$`);
title = title.replace(yearRegex, '').trim(); title = title.replace(yearRegex, '').trim();
@@ -507,16 +515,27 @@ export async function process(
} }
if (tmdbData) { if (tmdbData) {
await applyTmdbData(metaCore, cid, tmdbData); const images = await computeImageCids(webdavClient, tmdbData);
entry = { data: tmdbData, ...images };
// Cache TMDB data for future use if (tmdbData.id) {
if (midhash) { await writeJson(tmdbCacheKey(String(tmdbData.id), mediaTypeOf(tmdbData)), entry);
await writeJson(`${midhash}_tmdb.json`, tmdbData); }
}
} }
console.log(`[tmdb] Fetched TMDB data for ${request.filePath ?? existingMeta?.fileName ?? cid}`); if (entry) {
await applyTmdbData(metaCore, webdavClient, cid, entry.data, {
posterCid: entry.posterCid,
backdropCid: entry.backdropCid,
});
// Keep the exact-file cache warm too, so a future re-enrichment of
// this same file skips straight to the byte-hash hit.
if (midhash) {
await writeJson(`${midhash}_aka_tmdb.json`, entry);
}
console.log(`[tmdb] Enriched ${label} (tmdbid=${entry.data.id})`);
} else { } else {
console.log(`[tmdb] No TMDB match found for ${request.filePath ?? existingMeta?.fileName ?? cid}`); console.log(`[tmdb] No TMDB match found for ${label}`);
} }
await sendCallback({ await sendCallback({
@@ -534,14 +553,111 @@ export async function process(
} }
} }
/** Resolved TMDB payload plus the seeded poster/backdrop CIDs, cached per
* tmdbid. Every torrent/usenet release of an episode carries the same
* `tmdbid`, and TMDB only gives us show/movie-level fields (poster, plot,
* genres — no per-episode data), so N releases can share ONE fetch + seed. */
interface TmdbCacheEntry {
data: any;
posterCid: string | null;
backdropCid: string | null;
}
// In-process single-flight: collapses concurrent resolves of the same key onto
// one promise, so a burst of same-tmdbid records that all miss the cold cache
// triggers a single TMDB fetch (no thundering herd) — the rest await it.
const tmdbEntryInflight = new Map<string, Promise<TmdbCacheEntry | null>>();
// Persistent cache filename for a resolved show/movie. Includes mediaType +
// language so a tv/movie id clash or a language switch can't return stale text.
function tmdbCacheKey(tmdbId: string, mediaType: string): string {
// `_aka`: entries written before `alternative_titles` was appended carry no
// AKAs, so the name moved to make them refetch once.
return `tmdbid_${mediaType}_${tmdbId}_${metadataLanguage}_aka_tmdb.json`;
}
// Media type from a raw TMDB payload's own shape (tv payloads carry
// name/first_air_date). Mirrors the check in applyTmdbData.
function mediaTypeOf(data: any): string {
return data?.first_air_date !== undefined ||
data?.name !== undefined ||
data?.original_name !== undefined
? 'tv'
: 'movie';
}
// Download + hash the poster/backdrop for a resolved payload. Record-independent
// (the image filename is keyed by tmdbId, so the blob dedups across records), so
// the CIDs can be computed once per show and reused for every release.
async function computeImageCids(
webdavClient: WebDAVClient | null,
data: any
): Promise<{ posterCid: string | null; backdropCid: string | null }> {
const tmdbId = data?.id ? String(data.id) : '';
const displayTitle =
data?.title || data?.name || data?.original_title || data?.original_name || 'Unknown';
const releaseDate = data?.release_date || data?.first_air_date;
const year = releaseDate ? releaseDate.split('-')[0] : undefined;
const posterCid =
data?.poster_path && tmdbId
? await downloadAndHashImage(webdavClient, data.poster_path, 'poster', displayTitle, year, tmdbId)
: null;
const backdropCid =
data?.backdrop_path && tmdbId
? await downloadAndHashImage(webdavClient, data.backdrop_path, 'backdrop', displayTitle, year, tmdbId)
: null;
return { posterCid, backdropCid };
}
// Resolve the full entry (payload + image CIDs) for a KNOWN tmdbid, served from
// the persistent per-tmdbid cache when possible and single-flighted otherwise.
// This is the hot path for gateway records (torrent + usenet), which always
// carry a `tmdbid` anchor — so N releases of one show share one TMDB fetch.
async function resolveEntryById(
webdavClient: WebDAVClient | null,
tmdbId: string,
mediaType: string
): Promise<TmdbCacheEntry | null> {
const key = tmdbCacheKey(tmdbId, mediaType);
if (!forceRecompute) {
const cached = await readJson<TmdbCacheEntry>(key);
if (cached?.data) {
return cached;
}
}
const inflight = tmdbEntryInflight.get(key);
if (inflight) {
return inflight;
}
const pending = (async (): Promise<TmdbCacheEntry | null> => {
console.log(`[tmdb] Resolving TMDB ${mediaType}/${tmdbId} (cache miss)`);
const data = await getByTmdbId(tmdbId, mediaType);
if (!data) {
return null;
}
const images = await computeImageCids(webdavClient, data);
const entry: TmdbCacheEntry = { data, ...images };
await writeJson(key, entry);
return entry;
})();
tmdbEntryInflight.set(key, pending);
try {
return await pending;
} finally {
tmdbEntryInflight.delete(key);
}
}
/** /**
* Apply TMDB data to KV store using same keys as old TMDBProcessor * Apply TMDB data to KV store using same keys as old TMDBProcessor
*/ */
async function applyTmdbData( async function applyTmdbData(
metaCore: MetaCoreClient, metaCore: MetaCoreClient,
webdavClient: WebDAVClient | null,
cid: string, cid: string,
data: any data: any,
): Promise<void> { images?: { posterCid: string | null; backdropCid: string | null }
): Promise<{ posterCid: string | null; backdropCid: string | null }> {
const metadata: Record<string, string> = {}; const metadata: Record<string, string> = {};
// Basic IDs // Basic IDs
@@ -564,6 +680,10 @@ async function applyTmdbData(
data.original_name !== undefined; data.original_name !== undefined;
metadata.videoType = isTv ? 'tvshow' : 'movie'; metadata.videoType = isTv ? 'tvshow' : 'movie';
metadata.contentKind = isTv ? 'episode' : 'movie'; metadata.contentKind = isTv ? 'episode' : 'movie';
// `domain` is written in the same breath as `contentKind`
// (METADATA_KEYS.md §1) — it is the key meta-watch filters its wall on,
// and TMDB is precisely the identity graph that decides film vs tv here.
metadata.domain = isTv ? 'tv' : 'film';
// Title - store both original and localized // Title - store both original and localized
const originalTitle = data.original_title || data.original_name; const originalTitle = data.original_title || data.original_name;
@@ -580,6 +700,23 @@ async function applyTmdbData(
metadata.originalTitle = originalTitle; metadata.originalTitle = originalTitle;
} }
// Every clean name as a `titles/<lang3>/<name>` key-set member
// (METADATA_KEYS.md §3): the localized title under the configured metadata
// language, the original title under TMDB's `original_language`, and each
// AKA under the language its market implies (`und` when it doesn't).
const addTitleMember = (lang3: string, name: string | undefined) => {
const key = titleMemberKey(lang3, name);
if (key) metadata[key] = 'true';
};
addTitleMember(iso639_1to3(metadataLanguage.split('-')[0]) ?? 'und', localizedTitle);
addTitleMember(iso639_1to3(data.original_language) ?? 'und', originalTitle);
const akas = data.alternative_titles?.titles ?? data.alternative_titles?.results;
if (Array.isArray(akas)) {
for (const aka of akas) {
addTitleMember(marketToLang3(aka?.iso_3166_1), aka?.title);
}
}
// Dates // Dates
const releaseDate = data.release_date || data.first_air_date; const releaseDate = data.release_date || data.first_air_date;
let year: string | undefined; let year: string | undefined;
@@ -594,9 +731,8 @@ async function applyTmdbData(
// Plot (in configured language) // Plot (in configured language)
if (data.overview) { if (data.overview) {
// Extract language code from metadataLanguage (e.g., 'en-US' -> 'eng') // Extract language code from metadataLanguage (e.g., 'en-US' -> 'eng')
const langCode = metadataLanguage.split('-')[0]; const langKey = iso639_1to3(metadataLanguage.split('-')[0]);
const langKey = langCode === 'en' ? 'eng' : langCode; if (langKey) metadata[`plot/${langKey}`] = data.overview;
metadata[`plot/${langKey}`] = data.overview;
// Also set as primary plot for compatibility // Also set as primary plot for compatibility
metadata['plot/eng'] = data.overview; metadata['plot/eng'] = data.overview;
} }
@@ -625,35 +761,37 @@ async function applyTmdbData(
// Add tmdb-verified tag (same as old processor) // Add tmdb-verified tag (same as old processor)
await metaCore.addToSet(cid, 'tags', 'tmdb-verified'); await metaCore.addToSet(cid, 'tags', 'tmdb-verified');
// Download poster and backdrop images to plugin output folder. The // Poster/backdrop CIDs. Reuse the precomputed values when the caller already
// watcher picks them up as first-class file entries, so all we need to // seeded them (a per-tmdbid cache hit — so we don't re-download + re-hash the
// store is the CID — `/api/file/{cid}` resolves through the standard // same image for every release of a show); otherwise download + hash now.
// reverse index, no path companion needed. // The image filename is keyed by tmdbId, so the blob is deduped either way —
if (data.poster_path && tmdbId) { // this just also skips the WebDAV round-trips. The watcher picks the images
const posterCid = await downloadAndHashImage( // up as first-class file entries, so storing the CID is all that's needed.
data.poster_path, let posterCid = images ? images.posterCid : null;
'poster', if (!images && data.poster_path && tmdbId) {
displayTitle, posterCid = await downloadAndHashImage(webdavClient, data.poster_path, 'poster', displayTitle, year, tmdbId);
year, }
tmdbId
);
if (posterCid) { if (posterCid) {
await metaCore.setProperty(cid, 'poster', posterCid); await metaCore.setProperty(cid, 'poster', posterCid);
console.log(`[tmdb] Set poster CID: ${posterCid}`); console.log(`[tmdb] Set poster CID: ${posterCid}`);
// The alternatives, as the `posters/{lang3}/{cid}` key-set with `poster`
// among them (METADATA_KEYS.md §6). Leaf keys through PATCH — never
// addToSet, which writes the legacy comma-joined csv-set. Empty for a
// cached payload from before the `images` append: no backfill by design.
const members = posterMembers(data, posterCid);
if (Object.keys(members).length > 0) {
await metaCore.mergeMetadata(cid, members);
} }
} }
if (data.backdrop_path && tmdbId) { let backdropCid = images ? images.backdropCid : null;
const backdropCid = await downloadAndHashImage( if (!images && data.backdrop_path && tmdbId) {
data.backdrop_path, backdropCid = await downloadAndHashImage(webdavClient, data.backdrop_path, 'backdrop', displayTitle, year, tmdbId);
'backdrop', }
displayTitle,
year,
tmdbId
);
if (backdropCid) { if (backdropCid) {
await metaCore.setProperty(cid, 'backdrop', backdropCid); await metaCore.setProperty(cid, 'backdrop', backdropCid);
console.log(`[tmdb] Set backdrop CID: ${backdropCid}`); console.log(`[tmdb] Set backdrop CID: ${backdropCid}`);
} }
}
return { posterCid, backdropCid };
} }
+102
View File
@@ -0,0 +1,102 @@
/**
* The `posters/{lang3}/{cid}` key-set for a TMDB-enriched video record
* (METADATA_KEYS.md §6): the primary poster plus the best-voted alternatives.
*
* CROSS-BINARY CONTRACT: same ranking, cap, CDN size and language rule as the
* tmdb card feeder's `poster_member_keys`
* (`meta-feeder-tmdb/feeder-plugin/card-feeder/src/card.rs`).
*/
import { encodeUrlCid } from './cid.js';
/** Most members a record's `posters/*` key-set may carry, the primary included. */
export const MAX_POSTER_MEMBERS = 10;
/**
* CDN root + size the alternatives are referenced at. `w500`, as the card
* feeder's `poster_url`, so both writers mint the same locator for one image.
*/
export const ALT_POSTER_BASE_URL = 'https://image.tmdb.org/t/p/w500';
/** One entry of a TMDB details payload's `images.posters` (`append_to_response=images`). */
export interface TmdbImage {
file_path?: string;
iso_639_1?: string | null;
vote_average?: number;
vote_count?: number;
}
/**
* ISO 639-1 → ISO 639-3 (`lang3`), the 639-2/T form where B and T differ
* (`fra`, `deu`, `zho` — never `fre`/`ger`/`chi`). Mirrors the card feeder's
* `iso639_1_to_3` table.
*/
const ISO639_1_TO_3: Record<string, string> = {
en: 'eng', ja: 'jpn', fr: 'fra', de: 'deu', es: 'spa', it: 'ita', ru: 'rus',
ko: 'kor', zh: 'zho', pt: 'por', nl: 'nld', sv: 'swe', no: 'nor', da: 'dan',
fi: 'fin', pl: 'pol', tr: 'tur', ar: 'ara', hi: 'hin', th: 'tha', vi: 'vie',
id: 'ind', cs: 'ces', el: 'ell', he: 'heb', hu: 'hun', ro: 'ron', uk: 'ukr',
fa: 'fas', ms: 'msa', tl: 'tgl', ca: 'cat', nb: 'nob',
};
/**
* The language segment for a poster: that of the text printed on it. `zxx`
* (no linguistic content) when TMDB gives none — a textless poster — and
* `und` for a code outside the table.
*/
export function posterLang3(code: string | null | undefined): string {
const trimmed = (code ?? '').trim().toLowerCase();
if (!trimmed) return 'zxx';
return ISO639_1_TO_3[trimmed] ?? 'und';
}
function compareCandidates(a: TmdbImage, b: TmdbImage): number {
const byAverage = (b.vote_average ?? 0) - (a.vote_average ?? 0);
if (byAverage !== 0) return byAverage;
const byCount = (b.vote_count ?? 0) - (a.vote_count ?? 0);
if (byCount !== 0) return byCount;
const pa = a.file_path ?? '';
const pb = b.file_path ?? '';
return pa < pb ? -1 : pa > pb ? 1 : 0;
}
/**
* The `posters/{lang3}/{cid}` members to merge onto a record whose `poster` is
* `primaryPosterCid`. The primary is always a member, filed under the language
* of its own `images.posters` entry (`und` if TMDB did not list it); the
* alternatives follow as `url` locators, ranked by `vote_average`, then
* `vote_count`, then `file_path` (so equal payloads give equal keys), capped at
* {@link MAX_POSTER_MEMBERS} in total.
*
* Returns `{}` when the payload has no image list — a cached entry from before
* the `images` append. Without one the primary's language is unknown, and a set
* is better absent than mislabelled.
*/
export function posterMembers(data: any, primaryPosterCid: string): Record<string, 'true'> {
const candidates: TmdbImage[] = Array.isArray(data?.images?.posters) ? data.images.posters : [];
if (candidates.length === 0 || !primaryPosterCid) {
return {};
}
const primaryPath: string | undefined = data?.poster_path;
const members: Record<string, 'true'> = {};
const primary = candidates.find((img) => !!img.file_path && img.file_path === primaryPath);
const primaryLang = primary ? posterLang3(primary.iso_639_1) : 'und';
members[`posters/${primaryLang}/${primaryPosterCid}`] = 'true';
let count = 1;
const ranked = candidates
.filter((img) => typeof img.file_path === 'string' && img.file_path.trim() !== '' && img.file_path !== primaryPath)
.sort(compareCandidates);
for (const img of ranked) {
if (count >= MAX_POSTER_MEMBERS) break;
const cid = encodeUrlCid(`${ALT_POSTER_BASE_URL}/${img.file_path!.replace(/^\/+/, '')}`);
if (!cid) continue;
const key = `posters/${posterLang3(img.iso_639_1)}/${cid}`;
if (!(key in members)) {
members[key] = 'true';
count++;
}
}
return members;
}
+54 -5
View File
@@ -136,15 +136,64 @@ export class WebDAVClient {
} }
/** /**
* Create a WebDAV client from environment variables * WebDAV client for the meta-core that drove a /process call.
*
* The endpoint is read from that core's own /urls (`webdavUrlInternal`),
* so blobs always land in the /files of the core we write metadata to. A feeder
* whose plugins run beside it but enrich a remote hub core needs no per-stack
* wiring, and it is impossible to write posters into one core while pointing
* CIDs at another.
*
* WEBDAV_URL still wins when set — an explicit override for tests and for
* topologies where the core's advertised internal URL isn't reachable from here.
*
* Resolutions are cached per meta-core URL; failures are not, so a core that is
* still starting up is retried on the next task.
*/ */
export function createWebDAVClient(): WebDAVClient | null { const clientCache = new Map<string, Promise<WebDAVClient | null>>();
const webdavUrl = process.env.WEBDAV_URL;
async function resolveWebDAVUrl(metaCoreUrl: string): Promise<string | null> {
// /urls, not /api/urls — metaCoreUrl points at the meta-core backend, whose
// discovery routes are unprefixed (same base the /meta/* writes use).
const base = metaCoreUrl.replace(/\/$/, '');
const response = await fetch(`${base}/urls`, { signal: AbortSignal.timeout(5000) });
if (!response.ok) {
throw new Error(`GET ${base}/urls failed: ${response.status} ${response.statusText}`);
}
const urls = await response.json() as { webdavUrlInternal?: string; webdavUrl?: string };
return urls.webdavUrlInternal ?? urls.webdavUrl ?? null;
}
export async function getWebDAVClient(metaCoreUrl: string): Promise<WebDAVClient | null> {
const override = process.env.WEBDAV_URL;
if (override) {
return new WebDAVClient(override);
}
let pending = clientCache.get(metaCoreUrl);
if (!pending) {
pending = resolveWebDAVUrl(metaCoreUrl).then((webdavUrl) => {
if (!webdavUrl) { if (!webdavUrl) {
console.warn('[webdav-client] WEBDAV_URL not set, WebDAV client unavailable'); console.warn(`[webdav-client] meta-core ${metaCoreUrl} advertises no WebDAV URL`);
return null; return null;
} }
console.log(`[webdav-client] Using WebDAV endpoint ${webdavUrl} (from ${metaCoreUrl})`);
return new WebDAVClient(webdavUrl); return new WebDAVClient(webdavUrl);
});
clientCache.set(metaCoreUrl, pending);
}
try {
const client = await pending;
if (!client) {
clientCache.delete(metaCoreUrl);
}
return client;
} catch (error) {
clientCache.delete(metaCoreUrl);
console.warn(`[webdav-client] Failed to resolve WebDAV URL from ${metaCoreUrl}: ${error instanceof Error ? error.message : String(error)}`);
return null;
}
} }
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest';
import { encodeUrlCid } from '../src/cid.js';
import { ALT_POSTER_BASE_URL, MAX_POSTER_MEMBERS, posterLang3, posterMembers, type TmdbImage } from '../src/posters.js';
const alt = (path: string) => encodeUrlCid(`${ALT_POSTER_BASE_URL}${path}`)!;
const img = (file_path: string, iso_639_1: string | null, vote_average = 0, vote_count = 0): TmdbImage => ({
file_path,
iso_639_1,
vote_average,
vote_count,
});
describe('encodeUrlCid', () => {
// Same vectors as meta-feeder-tmdb's vendored `hash.rs::url_cid_matches_pinned_vectors`.
it('matches the pinned Rust vectors', () => {
expect(encodeUrlCid('https://image.tmdb.org/t/p/w500/dqZENchTd7lp5zit1Q7Bkjzcxpi.jpg')).toBe(
'bagdcaab7nb2hi4dthixs62lnmftwkltunvsgeltpojts65bpoaxxonjqgaxwi4k2ivhgg2cumq3wy4bvpjuximkrg5bgw2t2mn4ha2jonjygo',
);
});
it('uses a two-byte length varint past 127 bytes', () => {
const long = `https://image.tmdb.org/t/p/w500/${'a'.repeat(100)}.jpg`;
expect(long.length).toBe(136);
expect(encodeUrlCid(long)).toBe(
'bagdcaaeiafuhi5dqom5c6l3jnvqwozjoorwwiyron5zgol3uf5yc65zvgayc6ylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcylbmfqwcltkobtq',
);
});
it('rejects anything but an absolute http(s) URL', () => {
expect(encodeUrlCid('/relative.jpg')).toBeNull();
expect(encodeUrlCid('ftp://example.com/x.jpg')).toBeNull();
expect(encodeUrlCid('')).toBeNull();
});
});
describe('posterLang3', () => {
it('maps to ISO 639-3, never 639-2/B', () => {
expect(posterLang3('fr')).toBe('fra');
expect(posterLang3('de')).toBe('deu');
expect(posterLang3('EN')).toBe('eng');
});
it('files a textless poster under zxx and an unknown code under und', () => {
expect(posterLang3(null)).toBe('zxx');
expect(posterLang3(undefined)).toBe('zxx');
expect(posterLang3('xx')).toBe('und');
});
});
describe('posterMembers', () => {
const PRIMARY_CID = 'bagacbabaecontentcid';
it('lists the primary under its own language, once, beside the alternatives', () => {
const data = {
poster_path: '/primary.jpg',
images: {
posters: [img('/alt-fr.jpg', 'fr', 5.5, 10), img('/primary.jpg', 'ja', 5, 3), img('/textless.jpg', null, 6, 1)],
},
};
expect(posterMembers(data, PRIMARY_CID)).toEqual({
[`posters/jpn/${PRIMARY_CID}`]: 'true',
[`posters/zxx/${alt('/textless.jpg')}`]: 'true',
[`posters/fra/${alt('/alt-fr.jpg')}`]: 'true',
});
});
it('ranks by vote_average then vote_count, and caps at ten including the primary', () => {
const posters = Array.from({ length: 15 }, (_, i) => img(`/p${String(i).padStart(2, '0')}.jpg`, 'en', i, 1));
const keys = Object.keys(posterMembers({ poster_path: '/primary.jpg', images: { posters } }, PRIMARY_CID));
expect(keys).toHaveLength(MAX_POSTER_MEMBERS);
expect(keys[0]).toBe(`posters/und/${PRIMARY_CID}`);
expect(keys[1]).toBe(`posters/eng/${alt('/p14.jpg')}`);
expect(keys).not.toContain(`posters/eng/${alt('/p05.jpg')}`);
const tie = Object.keys(
posterMembers(
{ poster_path: '/primary.jpg', images: { posters: [img('/few.jpg', null, 5, 1), img('/many.jpg', null, 5, 9)] } },
PRIMARY_CID,
),
);
expect(tie[1]).toBe(`posters/zxx/${alt('/many.jpg')}`);
});
it('writes no set when the payload has no image list', () => {
expect(posterMembers({ poster_path: '/primary.jpg' }, PRIMARY_CID)).toEqual({});
expect(posterMembers({ poster_path: '/primary.jpg', images: { posters: [] } }, PRIMARY_CID)).toEqual({});
});
});
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
include: ['test/**/*.test.ts'],
},
});