tracker
All repositories: gitoria
19.7 KB
// tmdbsync.hl — THE TMDB SYNC (tracker.worldapi.org#9): for every show SOMEONE follows, fetch the show's// details, seasons and episodes from TMDB and bring storage/mpackdb/ up to date, plus the show's poster.// Used by BOTH runners: the daily run inside the app (project.hl `syncTick`, one show per step) and the// command-line tool (tools/sync-tmdb.hl). Reference for the API use: the old tracker's// crates/sync/commands/sync.js (read-only).//// GET <TMDB_BASE_URL>/tv/<tmdbId>?append_to_response=external_ids the details (status, counts,// overview, poster_path, seasons[])// + external_ids (imdb_id, tvdb_id)// GET <TMDB_BASE_URL>/tv/<tmdbId>?append_to_response=season/1,season/2… up to 20 seasons with their// episodes in ONE request// GET <TMDB_IMAGE_URL>/w342<poster_path> the poster → storage/mpackdb/posters/// Authorization: Bearer $TMDB_READ_TOKEN// GET <TVMAZE_BASE_URL>/lookup/shows?imdb=tt… (else ?thetvdb=<id>) the TVmaze id, ONLY when the show// has none (301 → /shows/<id>, 404 = unknown)// A MOVIE (`type = 'movie'`, 7814 of the migrated rows, 1 followed): only// GET <TMDB_BASE_URL>/movie/<tmdbId>?append_to_response=external_ids its imdb id + poster; no seasons,// status, overview (it is no TV show)//// EXTERNAL IDS (tracker.worldapi.org#12, the show page's link icons): a MISSING imdbId/tvdbId is filled from TMDB's// external_ids, a missing tvmzId from TVmaze's lookup — an id the show already has is NEVER overwritten.// RULES (ticket): new seasons/episodes are ADDED, existing ones UPDATED (title, summary, release) —// matched by tmdbId, never duplicated; NOTHING is deleted. An episode without a tmdbId (161 migrated ones)// is matched by its S/E number instead and gets the tmdbId. A season (no tmdbId in the migrated data) is// matched by (show, seasonNumber). A TMDB value that is empty/null never overwrites a stored one.// Season 0 ("Specials") is only synced for a show that already has a season 0 (else every followed show// would suddenly flood /my/unwatched with specials); a TMDB season with no episodes is not created.//// IDS ARE SELF-ASSIGNED (randomBytes, like watches.hl): hl:mpackdb's own generated @id can repeat within// one millisecond, which is what made update() lose rows (hybriel#113, fixed upstream, not in the vendored// build) — a table holding only unique ids is safe to update().//// ONE PROCESS PER STORAGE: hl:mpackdb does not coordinate two processes (hybriel#21) — the in-app run uses// the app's own open tables (imported from shows.hl); the tool only ever runs against a stopped app or a copy.//// 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 { env } from 'hl:proc'import { now } from 'hl:time'import { randomBytes } from 'hl:crypto'import { writeFile, mkDir, exists } from 'hl:fs'import { showsTable, seasonsTable, episodesTable, storageDir } from './shows.hl'static envOr = (name, fallback) => {let v = env(name)return v != null && v.trim() != '' ? v.trim() : fallback}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 postersDir = storageDir + '/posters'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: project.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) => {let 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 } }let j = r.json()if (j == null) { return { failed = 'no JSON for ' + path } }return j}static textOr = (v) => { return v != null && hlTypeName(v) == 'String' && v.trim() != '' ? v : null }// ---- external ids (tracker.worldapi.org#12) -----------------------------------------------------static hasId = (v) => { return v != null && ('' + v).trim() != '' }// an IMDb id as TMDB gives it ('tt' + digits), else nullstatic imdbOr = (v) => {let 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 = (param, value) => {let 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 } }let 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.static externalIdsFor = (show, ext, isSeries) => {let out = { imdbId = show.imdbId tvdbId = show.tvdbId tvmzId = show.tvmzId filled = 0 tvmazeRequests = 0 failed = null }let 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)) { return out }let 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}// ---- posters ----------------------------------------------------------------------------------// the extension of a TMDB poster_path ('/abc.jpg' → 'jpg'); only the ones the poster route knowsstatic posterExt = (posterPath) => {let parts = posterPath.split('.')let 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 }// and sets show.image / show.tmdbPoster on the (caller's) record — the file is <oldId>.<ext>, the name// shows.hl posterName() already builds, served by project.hl's /posters/:name routestatic syncPoster = (show, posterPath) => {let out = { requests = 0 saved = 0 failed = null image = show.image tmdbPoster = show.tmdbPoster }if (textOr(posterPath) == null || show.oldId == null) { return out }let ext = posterExt(posterPath)if (ext == null) { return out }let file = postersDir + '/' + show.oldId + '.' + extif (exists(file) && show.tmdbPoster == posterPath && show.image == ext) { return out }out.requests = 1let r = fetch(tmdbImageBase + '/w342' + posterPath, { 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 = 'poster ' + posterPath + ': ' + (r == null ? 'no answer' : 'HTTP ' + r.status)return out}mkDir(postersDir)writeFile(file, toBytes(r.body), 420)out.saved = 1out.image = extout.tmdbPoster = posterPathreturn out}// ---- one show -----------------------------------------------------------------------------------static newId = () => { return randomBytes(8, 'hex') }// which TMDB seasons to sync: every numbered one with episodes; 0 only when the show has a season 0 alreadystatic wantedSeasonNumbers = (details, localByNumber) => {let out = []if (details.seasons == null) { return out }for (s of details.seasons) {let n = s.season_numberif (n != null && (n > 0 || localByNumber['' + n] != null) && (s.episode_count == null || s.episode_count > 0 || localByNumber['' + n] != null)) { out.push(n) }}return out}// the seasons in batches of 20 (TMDB's append_to_response limit)static batchesOf = (list, size) => {let out = []let cur = []for (x of list) {cur.push(x)if (cur.length == size) { out.push(cur) cur = [] }}if (cur.length > 0) { out.push(cur) }return out}// fields of an episode/season from TMDB that differ from the stored record (null/empty never overwrites)static changedText = (stored, fresh) => { return fresh != null && fresh != stored }// a MOVIE: one request — its imdb id (if missing) and its poster; nothing else of the record is touchedstatic syncMovie = (show, res) => {let out = resout.requests = 1let details = tmdbGet('/movie/' + show.tmdbId + '?append_to_response=external_ids')if (details.failed != null) { out.errors = 1 out.error = show.title + ': ' + details.failed return out }let ids = externalIdsFor(show, details.external_ids, false)out.ids = ids.filledlet poster = syncPoster(show, details.poster_path)out.requests = out.requests + poster.requestsout.posters = poster.savedif (poster.failed != null) { out.errors = out.errors + 1 out.error = show.title + ': ' + poster.failed }let m = showm.imdbId = ids.imdbIdm.image = poster.imagem.tmdbPoster = poster.tmdbPosterm.tmdbSync = now()if (showsTable.update(m.id, m) == null) { out.errors = out.errors + 1 out.error = show.title + ': movie not updated: ' + showsTable.lastError() }return out}// Sync ONE show (by our id). Answers counts: { requests, tvmazeRequests, newSeasons, newEpisodes, updatedEpisodes,// updatedSeasons, posters, ids, errors, error }. Never throws for a TMDB failure — it is counted and the show left as is.static syncShow = (showId) => {let res = { requests = 0 tvmazeRequests = 0 newSeasons = 0 newEpisodes = 0 updatedEpisodes = 0 updatedSeasons = 0 posters = 0 ids = 0 errors = 0 error = '' }let show = showsTable.fetch(showId)if (show == null) { res.errors = 1 res.error = 'no show ' + showId return res }if (show.tmdbId == null) { res.errors = 1 res.error = show.title + ': no tmdbId' return res }if (show.type == 'movie') { return syncMovie(show, res) }res.requests = 1let details = tmdbGet('/tv/' + show.tmdbId + '?append_to_response=external_ids')if (details.failed != null) { res.errors = 1 res.error = show.title + ': ' + details.failed return res }// what we have: seasons by number, episodes by tmdbId and by S/E numberlet seasonsByNumber = {}let epByTmdb = {}let epByNumber = {}for (sid of show.seasons) {let s = seasonsTable.fetch(sid)if (s != null) {seasonsByNumber['' + s.seasonNumber] = sfor (eid of s.episodes) {let e = episodesTable.fetch(eid)if (e != null) {if (e.tmdbId != null) { epByTmdb['' + e.tmdbId] = e }epByNumber[e.seasonNumber + 'x' + e.episodeNumber] = e}}}}// plain locals for the record literals below: inside a literal, an entry named `show`/`season` would shadow// the variable for every later entry (SPEC "A literal's entries are evaluated in order")let showKey = show.idlet showTmdb = show.tmdbIdlet showSeasons = []for (sid of show.seasons) { showSeasons.push(sid) }let showChanged = falsefor (batch of batchesOf(wantedSeasonNumbers(details, seasonsByNumber), 20)) {let names = []for (n of batch) { names.push('season/' + n) }res.requests = res.requests + 1let withSeasons = tmdbGet('/tv/' + show.tmdbId + '?append_to_response=' + names.join(','))if (withSeasons.failed != null) {res.errors = res.errors + 1res.error = show.title + ': ' + withSeasons.failed} else {for (n of batch) {let ts = withSeasons['season/' + n]if (ts != null && ts.episodes != null) {let season = seasonsByNumber['' + n]let seasonIsNew = season == nulllet seasonChanged = falseif (seasonIsNew) {season = { id = newId() seasonNumber = n title = textOr(ts.name) != null ? ts.name : 'Season ' + nrelease = textOr(ts.air_date) summary = textOr(ts.overview) != null ? ts.overview : ''show = showKey episodes = [] oldId = 'tmdb-season:' + showTmdb + ':' + n }} else {if (changedText(season.title, textOr(ts.name))) { season.title = ts.name seasonChanged = true }if (changedText(season.summary, textOr(ts.overview))) { season.summary = ts.overview seasonChanged = true }if (changedText(season.release, textOr(ts.air_date))) { season.release = ts.air_date seasonChanged = true }}let seasonKey = season.idlet seasonEpisodes = []for (eid of season.episodes) { seasonEpisodes.push(eid) }for (te of ts.episodes) {if (te.id != null && te.episode_number != null) {let e = epByTmdb['' + te.id]if (e == null) {let byNum = epByNumber[n + 'x' + te.episode_number]if (byNum != null && byNum.tmdbId == null) { e = byNum }}if (e == null) {let fresh = { id = newId() episodeNumber = te.episode_number seasonNumber = ntitle = textOr(te.name) summary = textOr(te.overview) != null ? te.overview : '' release = textOr(te.air_date)show = showKey season = seasonKey tmdbId = te.id oldId = 'tmdb-episode:' + te.id }let putId = episodesTable.put(fresh)if (putId == null) {res.errors = res.errors + 1res.error = show.title + ': episode ' + te.id + ' not stored: ' + episodesTable.lastError()} else {seasonEpisodes.push(fresh.id)epByTmdb['' + te.id] = freshres.newEpisodes = res.newEpisodes + 1seasonChanged = true}} else {let changed = falseif (e.tmdbId == null) { e.tmdbId = te.id changed = true }if (changedText(e.title, textOr(te.name))) { e.title = te.name changed = true }if (changedText(e.summary, textOr(te.overview))) { e.summary = te.overview changed = true }if (changedText(e.release, textOr(te.air_date))) { e.release = te.air_date changed = true }if (changed) {if (episodesTable.update(e.id, e) == null) {res.errors = res.errors + 1res.error = show.title + ': episode ' + e.id + ' not updated: ' + episodesTable.lastError()} else {epByTmdb['' + e.tmdbId] = eres.updatedEpisodes = res.updatedEpisodes + 1}}}}}season.episodes = seasonEpisodesif (seasonIsNew) {if (seasonsTable.put(season) == null) {res.errors = res.errors + 1res.error = show.title + ': season ' + n + ' not stored: ' + seasonsTable.lastError()} else {seasonsByNumber['' + n] = seasonshowSeasons.push(season.id)showChanged = trueres.newSeasons = res.newSeasons + 1}} else if (seasonChanged) {if (seasonsTable.update(season.id, season) == null) {res.errors = res.errors + 1res.error = show.title + ': season ' + season.id + ' not updated: ' + seasonsTable.lastError()} else {res.updatedSeasons = res.updatedSeasons + 1}}}}}}// the external ids (tracker.worldapi.org#12): missing ones from TMDB's external_ids, a missing TVmaze id from TVmazelet ids = externalIdsFor(show, details.external_ids, true)res.ids = ids.filledres.tvmazeRequests = ids.tvmazeRequestsif (ids.failed != null) { res.errors = res.errors + 1 res.error = show.title + ': ' + ids.failed }// the show itself: status, counts, TMDB's overview, the poster, when it was syncedlet poster = syncPoster(show, details.poster_path)res.requests = res.requests + poster.requestsres.posters = poster.savedif (poster.failed != null) { res.errors = res.errors + 1 res.error = show.title + ': ' + poster.failed }show.seasons = showSeasonsif (textOr(details.status) != null) { show.status = details.status }if (details.number_of_seasons != null) { show.seasonsCount = details.number_of_seasons }if (details.number_of_episodes != null) { show.episodesCount = details.number_of_episodes }if (textOr(details.overview) != null) { show.tmdbSummary = details.overview }show.image = poster.imageshow.tmdbPoster = poster.tmdbPostershow.imdbId = ids.imdbIdshow.tvdbId = ids.tvdbIdshow.tvmzId = ids.tvmzIdshow.tmdbSync = now()if (showsTable.update(show.id, show) == null) { res.errors = res.errors + 1 res.error = show.title + ': show not updated: ' + showsTable.lastError() }return res}// flush the three tables' index/meta state to disk (after a run, and every few shows)static persistSync = () => {showsTable.persist()seasonsTable.persist()episodesTable.persist()return true}// totals of a run: the per-show counts added upstatic emptyTotals = () => { return { shows = 0 requests = 0 tvmazeRequests = 0 newSeasons = 0 newEpisodes = 0 updatedEpisodes = 0 updatedSeasons = 0 posters = 0 ids = 0 errors = 0 } }static addTotals = (t, r) => {let o = to.shows = o.shows + 1o.requests = o.requests + r.requestso.tvmazeRequests = o.tvmazeRequests + r.tvmazeRequestso.ids = o.ids + r.idso.newSeasons = o.newSeasons + r.newSeasonso.newEpisodes = o.newEpisodes + r.newEpisodeso.updatedEpisodes = o.updatedEpisodes + r.updatedEpisodeso.updatedSeasons = o.updatedSeasons + r.updatedSeasonso.posters = o.posters + r.posterso.errors = o.errors + r.errorsreturn o}static totalsLine = (t) => {return 'shows=' + t.shows + ' newSeasons=' + t.newSeasons + ' newEpisodes=' + t.newEpisodes + ' updatedEpisodes=' + t.updatedEpisodes+ ' updatedSeasons=' + t.updatedSeasons + ' posters=' + t.posters + ' ids=' + t.ids + ' requests=' + t.requests + ' tvmazeRequests=' + t.tvmazeRequests + ' errors=' + t.errors}
Branches
- mainmain branch
Latest commits
- b8bd1157tracker#14: README + STATUS (search, real-data numbers, gate, merge notes)mre
- 65c694a8tracker#14: search — header magnifier, /search/<text> (in-memory word-prefix index over titles + people), Fetch from web (TMDB search/multi, ours left out), Add = import via syncShow; gate +25 checks, real-data scriptmre
- cbdc4ea7tracker#12: link icons TMDB/IMDb/TVDB/TVmaze; sync fills missing ids (TVmaze lookup); movies fetched via /movie/mre
- b105bcd8tracker#11: Hybriel master ff51cf46 (checks no longer vanish), mobile-first styles, carets, follow button, sign-in modal, inverted check, orange castmre
- 31b758aatracker#10: installable app (manifest, service worker, offline shell), own icon + faviconmre
- 2fa9d997tracker#9: TMDB sync (followed shows: seasons, episodes, posters), tools/sync-tmdb.hl + daily run 04:00 UTC, fake TMDB in gatemre
- 49e1f61edeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
- 54070a4etracker#8: /my/unwatched + /my/schedule (301 from old), S01E01, title (year), 1 episode, watched-set lookup (unwatched 15s -> 1s)mre
- 3251488atracker#7: /my/shows (followed shows, newest follow first, poster, title, last watched SxxEyy); gate can take screenshots (TRACKER_GATE_SHOTS)mre
- 44b7d9f9tracker#6: /schedule — upcoming episodes of followed shows, soonest firstmre
- 91c9fc8ctracker#5: /unwatched — unwatched released episodes of followed shows, newest firstmre
- a97c0295tracker#4: show page /shows/:slug (header, seasons, episodes, watch checks) + tools/relink-episode-seasons.hlmre
- 05f407c5tracker: no border on any button except inverted ones (Log out, ident status and identities too); header brand weight 100mre
- 17375427tracker#2: tools/migrate.hl + tools/verify.hl — old MongoDB data into mpackdb with new idsmre
- 31aac936tracker#3: no border on the header and on filled buttons; inverted buttons keep theirsmre
- 2ad9d29ctracker#1: login exactly like calendar (identity selector in the header, empty homepage)mre
- 3691e176tracker#1: empty tracker with the ident login (state of 2026-09-27)mre