Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4fcb2bfde | ||
|
|
f28f7d8594 | ||
|
|
bcd1eea5a2 |
@@ -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
|
||||||
@@ -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
@@ -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" }
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+1088
File diff suppressed because it is too large
Load Diff
+58
@@ -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]));
|
||||||
|
}
|
||||||
+98
-25
@@ -25,10 +25,12 @@
|
|||||||
*
|
*
|
||||||
* 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';
|
||||||
@@ -38,6 +40,8 @@ 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 { getWebDAVClient, WebDAVClient } from './webdav-client.js';
|
import { getWebDAVClient, WebDAVClient } from './webdav-client.js';
|
||||||
|
import { base32LowerMultibase } from './cid.js';
|
||||||
|
import { posterMembers } from './posters.js';
|
||||||
|
|
||||||
const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/original';
|
const IMAGE_BASE_URL = 'https://image.tmdb.org/t/p/original';
|
||||||
|
|
||||||
@@ -104,23 +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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const manifest: PluginManifest = {
|
export const manifest: PluginManifest = {
|
||||||
@@ -168,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';
|
||||||
@@ -218,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 {
|
||||||
@@ -406,7 +449,7 @@ export async function process(
|
|||||||
// entry now, but tolerates the legacy raw-payload format from older builds.
|
// entry now, but tolerates the legacy raw-payload format from older builds.
|
||||||
const midhash = existingMeta?.['cid_midhash256'];
|
const midhash = existingMeta?.['cid_midhash256'];
|
||||||
if (midhash && !forceRecompute) {
|
if (midhash && !forceRecompute) {
|
||||||
const cached = await readJson<any>(`${midhash}_tmdb.json`);
|
const cached = await readJson<any>(`${midhash}_aka_tmdb.json`);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
console.log(`[tmdb] Using byte-hash cached TMDB data for ${label}`);
|
console.log(`[tmdb] Using byte-hash cached TMDB data for ${label}`);
|
||||||
const isEntry = cached.data !== undefined;
|
const isEntry = cached.data !== undefined;
|
||||||
@@ -485,7 +528,7 @@ export async function process(
|
|||||||
// Keep the exact-file cache warm too, so a future re-enrichment of
|
// Keep the exact-file cache warm too, so a future re-enrichment of
|
||||||
// this same file skips straight to the byte-hash hit.
|
// this same file skips straight to the byte-hash hit.
|
||||||
if (midhash) {
|
if (midhash) {
|
||||||
await writeJson(`${midhash}_tmdb.json`, entry);
|
await writeJson(`${midhash}_aka_tmdb.json`, entry);
|
||||||
}
|
}
|
||||||
console.log(`[tmdb] Enriched ${label} (tmdbid=${entry.data.id})`);
|
console.log(`[tmdb] Enriched ${label} (tmdbid=${entry.data.id})`);
|
||||||
} else {
|
} else {
|
||||||
@@ -525,7 +568,9 @@ const tmdbEntryInflight = new Map<string, Promise<TmdbCacheEntry | null>>();
|
|||||||
// Persistent cache filename for a resolved show/movie. Includes mediaType +
|
// 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.
|
// language so a tv/movie id clash or a language switch can't return stale text.
|
||||||
function tmdbCacheKey(tmdbId: string, mediaType: string): string {
|
function tmdbCacheKey(tmdbId: string, mediaType: string): string {
|
||||||
return `tmdbid_${mediaType}_${tmdbId}_${metadataLanguage}_tmdb.json`;
|
// `_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
|
// Media type from a raw TMDB payload's own shape (tv payloads carry
|
||||||
@@ -632,6 +677,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;
|
||||||
@@ -648,6 +697,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;
|
||||||
@@ -662,9 +728,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;
|
||||||
}
|
}
|
||||||
@@ -706,6 +771,14 @@ async function applyTmdbData(
|
|||||||
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let backdropCid = images ? images.backdropCid : null;
|
let backdropCid = images ? images.backdropCid : null;
|
||||||
|
|||||||
+102
@@ -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;
|
||||||
|
}
|
||||||
@@ -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({});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
environment: 'node',
|
||||||
|
include: ['test/**/*.test.ts'],
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user