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
- 31dcf2admission 045: report, LOGmre
- 9c3971d0tests/persons-skip-count.hlmre
- 4d72e365mission 045mre
- b9cae4c9slices: skip and count non-row values from range(); merge persons pass falls back to iterate; guard testmre
- 3db7dc31merge w44-jobs-slices into w43-trkmemmre
- 593dab6fmission 043: report, LOGmre
- 1a5a4818boot scans back to iterate (slices measured slower: titles 114 s, episodes 141 s, persons failed); lambda per rowmre
- 03d29893boot scans read primary-key slices (lib/slices.hl from mission 044): iterate is eager too; people view log line back; allShows/allEpisodes stay for toolsmre
- 23375c58mission 044: report, LOG, STATUSmre
- c6fd928emission 044: 4096 slices for tables over 200 K rows, 15 ms budget, TRACKER_SLICE_DEPTH for testsmre
- fb057680mission 044: jobs.hl imports mergeLeft (gate found it), mission file, slices benchmre
- 0d6293ebmission 043: mission filemre
- d25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemre
- 633ee210mission 044: sliced table scans (slices.hl, pk-range slices) for the adult/kind/status/art/credits/details-repair queuesmre
- 55bbd619boot: one streamed pass per table (lib/bootscan.hl) instead of find(null,null) per module; follows/watches/franchises scans streammre
- 1d465d3ere-vendor plugins to Hybriel master f9614007 (mpackdb #202 copy fix, libmpackdb sha 6fb3b9d6)mre
- 6648ba44mission 042: real-browser E2E on ce6f2e0a re-vendor 69/0 at 390 + 1280mre
- 3ed3a0efmission 042: gates old/new equal (browser #41 route-table regex accepts unescaped hl:web output), real-data TTFB, E2E blocked by lisbeth lockmre
- d5b61e90LOG 042mre
- 4acdbaccmission 042: memory comparison old vs ce6f2e0a (stopped: warm VmHWM higher), reportmre