tracker
All repositories: gitoria
14.0 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> the details (status, counts,// overview, poster_path, seasons[])// 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//// 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'// 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// 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 }// ---- 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 }// Sync ONE show (by our id). Answers counts: { requests, newSeasons, newEpisodes, updatedEpisodes,// updatedSeasons, posters, errors, error }. Never throws for a TMDB failure — it is counted and the show left as is.static syncShow = (showId) => {let res = { requests = 0 newSeasons = 0 newEpisodes = 0 updatedEpisodes = 0 updatedSeasons = 0 posters = 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 }res.requests = 1let details = tmdbGet('/tv/' + show.tmdbId)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 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.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 newSeasons = 0 newEpisodes = 0 updatedEpisodes = 0 updatedSeasons = 0 posters = 0 errors = 0 } }static addTotals = (t, r) => {let o = to.shows = o.shows + 1o.requests = o.requests + r.requestso.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 + ' requests=' + t.requests + ' errors=' + t.errors}
Branches
- mainmain branch
Latest commits
- 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