tracker
All repositories: gitoria
9.7 KB
// lib/tmdb.hl — TALKING TO TMDB AND TVMAZE (tracker.worldapi.org#9/#12/#15): the one GET with the token, the TVmaze lookups, the// external ids a title may take from them, TMDB's adult flag, the poster download, and the pacing every runner keeps between// two titles. Shared by the sync (sync.hl), the backfills (backfill.hl), the completion and the credits (details.hl, credits.hl),// the person fill (people.hl), the search (search.hl), the daily run's change lists (dailysync.hl) and the collection seed// (collections.hl). Until mission 028 this was the top half of tmdbsync.hl.//// Env: TMDB_READ_TOKEN (required unless TMDB_BASE_URL points at a fake), TMDB_BASE_URL// (https://api.themoviedb.org/3), TMDB_IMAGE_URL (https://image.tmdb.org/t/p) — the gate points both at its// fake TMDB (tests/browser.mjs).import { fetch } from 'hl:fetch'import { mkDir, exists, writeFile } from 'hl:fs'import { envOr, postersDir, textOr, hasId } from './util.hl'import { stripHtml } from './sync-helpers.hl'static tmdbBase = envOr('TMDB_BASE_URL', 'https://api.themoviedb.org/3')static tmdbImageBase = envOr('TMDB_IMAGE_URL', 'https://image.tmdb.org/t/p')static tmdbToken = envOr('TMDB_READ_TOKEN', '')static tvmazeBase = envOr('TVMAZE_BASE_URL', 'https://api.tvmaze.com')// the sync can run: a token is set (never printed) — the dev .env on Loreana has one, a gate sets its ownstatic syncEnabled = tmdbToken != ''// TMDB allows 40 requests / 10 s: every runner waits this long per request it made before the next showstatic msPerRequest = 260// TVmaze allows 20 requests / 10 s (its API docs): 550 ms per lookup madestatic msPerTvmazeRequest = 550// how long a runner waits after a show before the next one (both runners: jobs.hl syncTick, tools/sync-tmdb.hl)static pauseMsAfter = (&r) => { return r.requests * msPerRequest + r.tvmazeRequests * msPerTvmazeRequest }// one GET → the parsed JSON, or { failed = '<why>' }. A refused/timed-out fetch is an Error event (absorbed// by the runner's `on Error`), the fetch then yields null.static tmdbGet = (&path) => {r = fetch(tmdbBase + path, { headers = { 'authorization' = 'Bearer ' + tmdbToken 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })if (r == null || r.status == null || r.status == 0) { return { failed = 'no answer for ' + path } }if (r.status != 200) { return { failed = 'HTTP ' + r.status + ' for ' + path status = r.status } }j = r.json()if (j == null) { return { failed = 'no JSON for ' + path } }return j}// ---- external ids (tracker.worldapi.org#12) -----------------------------------------------------// an IMDb id as TMDB gives it ('tt' + digits), else nullstatic imdbOr = (&v) => {t = textOr(v)if (t == null || t.length < 3 || t.slice(0, 2) != 'tt') { return null }let i = 2while (i < t.length) {if (!'0123456789'.includes(t[i])) { return null }i = i + 1}return t}// a positive numeric id (TMDB's tvdb_id, TVmaze's id), else nullstatic numIdOr = (&v) => { return v != null && hlTypeName(v) == 'Number' && v > 0 ? v : null }// TVmaze's lookup by one external id: { id } (null = TVmaze doesn't know it, 404) or { failed }. hl:fetch follows the// 301 to /shows/<id> by itself, so a hit answers the show's own JSON.static tvmazeLookup = (¶m, &value) => {r = fetch(tvmazeBase + '/lookup/shows?' + param + '=' + value, { headers = { 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })if (r == null || r.status == null || r.status == 0) { return { failed = 'TVmaze: no answer for ' + param + '=' + value } }if (r.status == 404) { return { id = null } }if (r.status != 200) { return { failed = 'TVmaze: HTTP ' + r.status + ' for ' + param + '=' + value } }j = r.json()if (j == null || numIdOr(j.id) == null) { return { failed = 'TVmaze: no id for ' + param + '=' + value } }return { id = j.id }}// the ids to SET on a show from TMDB's external_ids (+ TVmaze for a series): { imdbId, tvdbId, tvmzId } — each the// show's own value when it has one (never overwritten), else the found one, else null — plus { filled, tvmazeRequests,// failed }. TVmaze is asked by imdb, then by thetvdb, only while the show (after TMDB) still has no tvmzId — and only// when `askTvmaze` (the adult backfill does not: one request per title)static externalIdsFor = (&show, &ext, &isSeries, &askTvmaze) => {out = { imdbId = show.imdbId tvdbId = show.tvdbId tvmzId = show.tvmzId filled = 0 tvmazeRequests = 0 failed = null }e = ext != null ? ext : {}if (!hasId(out.imdbId) && imdbOr(e.imdb_id) != null) { out.imdbId = e.imdb_id out.filled = out.filled + 1 }if (!isSeries) { return out }if (!hasId(out.tvdbId) && numIdOr(e.tvdb_id) != null) { out.tvdbId = e.tvdb_id out.filled = out.filled + 1 }if (hasId(out.tvmzId) || !askTvmaze) { return out }tries = []if (imdbOr('' + out.imdbId) != null) { tries.push({ param = 'imdb' value = '' + out.imdbId }) }if (numIdOr(out.tvdbId) != null) { tries.push({ param = 'thetvdb' value = '' + out.tvdbId }) }for (t of tries) {if (!hasId(out.tvmzId) && out.failed == null) {out.tvmazeRequests = out.tvmazeRequests + 1let found = tvmazeLookup(t.param, t.value)if (found.failed != null) { out.failed = found.failed } else if (found.id != null) { out.tvmzId = found.id out.filled = out.filled + 1 }}}return out}// TVmaze's show WITH its episode list, one request (tracker#18: `?embed=episodes` brings the show's own summary too — before// it was `/shows/<id>/episodes`): { list, summary (HTML stripped, or null), status (tracker#35: Running / Ended / To Be// Determined / In Development, or null) } or { failed }static tvmazeEpisodes = (&tvmzId) => {r = fetch(tvmazeBase + '/shows/' + tvmzId + '?embed=episodes', { headers = { 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })if (r == null || r.status == null || r.status == 0) { return { failed = 'TVmaze: no answer for episodes of ' + tvmzId } }if (r.status != 200) { return { failed = 'TVmaze: HTTP ' + r.status + ' for episodes of ' + tvmzId } }j = r.json()if (j == null || j._embedded == null || j._embedded.episodes == null || j._embedded.episodes.length == null) { return { failed = 'TVmaze: no episode list for ' + tvmzId } }return { list = j._embedded.episodes summary = stripHtml(j.summary) status = textOr(j.status) type = textOr(j.type) }}// tracker#35: TVmaze's show alone (`GET /shows/<id>`, one request) — { status, type (#43) (or null) }, { notFound = true } (404) or { failed }// (no answer, 429, 5xx: ask again later). The status backfill (backfill.hl) asks it for a series the sync has not brought one for.static tvmazeShow = (&tvmzId) => {r = fetch(tvmazeBase + '/shows/' + tvmzId, { headers = { 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })if (r == null || r.status == null || r.status == 0) { return { failed = 'TVmaze: no answer for show ' + tvmzId } }if (r.status == 404) { return { notFound = true failed = 'TVmaze: HTTP 404 for show ' + tvmzId } }if (r.status != 200) { return { failed = 'TVmaze: HTTP ' + r.status + ' for show ' + tvmzId } }j = r.json()if (j == null) { return { failed = 'TVmaze: no JSON for show ' + tvmzId } }return { status = textOr(j.status) type = textOr(j.type) }}// ---- posters ----------------------------------------------------------------------------------// the extension of a TMDB poster_path ('/abc.jpg' → 'jpg'); only the ones the poster route knowsstatic posterExt = (&posterPath) => {parts = posterPath.split('.')ext = parts[parts.length - 1].toLowerCase()if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'webp') { return ext }return null}// downloads the w342 poster when the file is missing or TMDB has a new one; answers { requests, saved, failed, image, tmdbPoster,// fromBackdrop } — the caller stores image / tmdbPoster / posterFromBackdrop on its record. The file is <oldId>.<ext>, the name// shows.hl posterName() already builds, served by images.hl (/posters/:name).// tracker#33 (mission 032, The Remaining): a title TMDB has NO poster for gets its BACKDROP (w780, 16:9) as the poster file// instead (`fromBackdrop`); every poster box shows it centre-cropped to 2:3 (CSS aspect-ratio + object-fit: cover). When TMDB// later has a poster, it replaces the backdrop (a new path).static syncPoster = (&show, posterPath, backdropPath) => {out = { requests = 0 saved = 0 failed = null image = show.image tmdbPoster = show.tmdbPoster fromBackdrop = show.posterFromBackdrop == true }let path = textOr(posterPath)let size = '/w342'let fromBackdrop = falseif (path == null && textOr(backdropPath) != null) {path = backdropPathsize = '/w780'fromBackdrop = true}if (path == null || show.oldId == null) { return out }ext = posterExt(path)if (ext == null) { return out }file = postersDir + '/' + show.oldId + '.' + extif (exists(file) && show.tmdbPoster == path && show.image == ext) { return out }out.requests = 1r = fetch(tmdbImageBase + size + path, { headers = { 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })if (r == null || r.status != 200 || r.body == null || r.body.length == 0) {out.failed = (fromBackdrop ? 'backdrop ' : 'poster ') + path + ': ' + (r == null ? 'no answer' : 'HTTP ' + r.status)return out}mkDir(postersDir)writeFile(file, toBytes(r.body), 420)out.saved = 1out.image = extout.tmdbPoster = pathout.fromBackdrop = fromBackdropreturn out}// TMDB's adult flag of a details/search answer: true / false, null when it has none (mission 054)static adultOf = (&j) => {if (j == null) { return null }if (j.adult == true) { return true }if (j.adult == false) { return false }return null}
Branches
Latest commits
- f03dfbfcmission 040: re-vendor Hybriel 0f396652 (static build): plugins, compose cache volume/HL_CACHE_DIR/tmpfs, README, reportmre
- 5d4683b4mission brief 040mre
- e00d3bf7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
- a8c7f234tracker#36 (mission 039): tools/tmdb-check.hl survives a dropped connection (on Error, asked again, failed lines) and resumes with --from N; tests/tmdbcheck.mjs 6/6 against a fake TMDBmre
- 9c230516mission brief w39mre
- 3609121dmission 038 docs + report (quota stop): README/kinds.md for #43 #42 #36, STATUS, LOG; HEAD browser gate 374/8 in the in-app daily run block (hour-boundary suspected, rerun pending), other gates green; #36 real run needs TMDB_READ_TOKENmre
- a5d06e79tracker#36 (mission 038): tools/tmdb-check.hl + lib/tmdbcheck.hl — every live migrated title's migrated title + year against its TMDB entry (one GET /movie|tv/<id>?append_to_response=alternative_titles, 260 ms apart, passing failures asked once more): ok / ambiguous (one of title, year disagrees) / clear (both, or 404); read-only; token only from TMDB_READ_TOKEN; --stored = a title-only preview from the TMDB names already stored (no request). Tested against a fake TMDB (.scratch/w38/t36): 7 titles, 3 ok, 2 ambiguous, 2 clear, data unchangedmre
- 982554f3tracker#42 (mission 038): series pages — an unknown slug no longer scans every title (lib/shows.hl showBySlug: the slug map only; new titles are noted by refreshTitleCaches, which both title puts already reach): 10.7–15.7 s → 0.013 s on the real copy (the one-request-at-a-time server was blocked meanwhile); cast/crew rows take name + slug from a person-link cache (personLinkOf) instead of whole person records (SNL: 303 cast with 4,761 credits, ~49k allocations per render) — allocations per series page −5…−40 %; HTML of 20 pages identical to beforemre
- 4586b6e3docker-compose: init: true (hybriel#156)mre
- 085c2e5ftracker#43 (mission 038): TVmaze's type makes Variety / Talk Show / Game Show / Reality / News / Panel Show / Award Show / Sports titles Shows (TMDB calls Saturday Night Live UK Scripted) — the #43 part of parked w37-wip a79c8c1 only (no re-vendor, no cache volume): tvmazeType stored by the sync and the TVmaze status backfill (asks every series with a TVmaze id once), kindOfTitle/kindWithTvmaze, tools/tvmaze-types.hl, gate fixture Variety Gate Series; start waits 150 smre
- 4fa303b5mission brief w38mre
- 975f6843tracker#41 (mission 037b): no request tap — an old /movies|/series slug renders the keeper's page (slug map) with og:url naming the keeper's address, /shows/ 301; no moved slug in any page's HTML. Real copy 168/168 old addresses, 0 moved slugs in 54 pages, 300x + 1000x stress without a crash; gates on 06617221 380/0, 32/0, 53/0, 229/0, 26/0, theme 0mre
- 6decff4ftracker#41 (mission 037): moved slugs no longer listed in every page's HTML — a request tap answers their 301 by a slug-map lookup (shows.hl movedTitlePath); catalog.hl buildIndex pushes genre lists in place (the quadratic copy hung the boot > 20 min on today's data); gate: no moved slug in 19 page kinds signed out/in, immediate 301 after a merge. Gates on hybriel 06617221 green (380/0, 32/0, 53/0, 229/0, 26/0, theme 0); real copy 84/84 301, 0 moved slugs in 54 pages. NOT deployable: the tap faults after ~38 answers on 06617221 (report 037).mre
- 35f7a872mission brief 037mre
- 5cbcddd7tracker mission 036: recheck of the 16 review tickets — 15 WORKS, #39 PARTLY; review packages + bugs in reports/036-review-recheck.md (no code change)mre
- 9e18c2d0mission brief (w36)mre
- 216fac57missions 028-035 + reports 033/034 (were untracked)mre
- 5cb85d75deploy.sh: a backup taken while a background job writes (tar exit 1) is a warning; archive checked with gzip -tmre
- 9abda75dtracker: report 035mre
- 12595e47mission 035: theme re-vendored from layouts.worldapi.org 0222f67 (two corner radii: radiusSmall 5px, radiusLarge 10px); the tracker's 18 own radii -> radiusSmall/radiusLarge (--layout-radius is gone); check-theme 0; gates 379/0, 32/0, 53/0, 229/0, 26/0; real copy: every computed radius in {0, 5px, 10px, 50%}mre