tracker
All repositories: gitoria
33.0 KB
// project.hl — tracker.worldapi.org: STEP 1 (tracker.worldapi.org#1), an empty shell. Login copied unchanged from// calendar.worldapi.org (rejected once for a centered sign-in and no header selector — architect, 2026-09-27):// ident only, no own passwords (README "How apps use ident" of ident.worldapi.org), the identity selector in the// header (components/main.hl). No shows, no data yet — later steps come from the creator (CONCEPT.md).//// the header's ident-selector / "Log in with ident" -> <ident>/login?key=&return=<this app>/login/callback// /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id// (POST <ident>/api/exchange) and signs this app's OWN session in// (session.user = { id = <users @id> }, users.hl)// the header's "Log out" button signs this app's session out via the face trackerLogOut (components/main.hl)// — ident's own session, and the browser's ident cookie, are untouched//// Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the// architect, as with ident's own .env for SMTP):// TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),// IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…)import WebFramework from 'hl:web'import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import { env } from 'hl:proc'import { readBytes, readFile, exists } from 'hl:fs'import { now, timestamp, every } from 'hl:time'import Styles from './styles.hl'import { exchangeCode, ensureUser } from './users.hl'import Home from './components/home.hl'import LoginFailed from './components/loginfailed.hl'import Show from './components/show.hl'import Unwatched from './components/unwatched.hl'import Schedule from './components/schedule.hl'import MyShows from './components/myshows.hl'import MyMovies from './components/mymovies.hl'import Movies from './components/movies.hl'import AllShows from './components/allshows.hl'import Search from './components/search.hl'import Person from './components/person.hl'import { ensureIndex, searchTitleChanged, searchTitleRenamed } from './search.hl'import { syncEnabled, syncShow, syncShowDelta, persistSync, emptyTotals, addTotals, totalsLine, pauseMsAfter, msPerRequest, adultBackfillQueue, backfillTitle } from './tmdbsync.hl'import { detailsRepairQueue, completeStep, completeLine, persistDetails, persistCredits, applySynced, creditsQueue, creditsStep } from './details.hl'import { planStart, planStep, planIds, planLine, markSynced, clearCopiedSummaries, isFollowedInRun } from './deltasync.hl'import { allFollowedShowIds } from './follows.hl'import { refreshCatalogShow } from './catalog.hl'import { dark, darker } from './shared/tokens.hl'static appTitle = "tracker"// ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app// manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service// worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs// are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the// splash background the page's (dark) — both off the tokens, not written out again.appThemeColor = darker.valueappBackgroundColor = dark.valueappIcons = [{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }]appTouchIcon = '/icons/apple-touch-icon.png'appFavicon = '/icons/favicon.svg'// OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no// network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.offline = [ Home ]styles = Stylesport = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008watching = env('TRACKER_WATCH') != '0'// read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call belowsessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null// ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl// BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH// goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'safePath = (want) => {if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }let i = 0while (i < want.length) {if (!nextChars.includes(want[i])) { return '/' }i = i + 1}return want}// A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failedfailed = (req, why) => {let s = req.sessionlet fresh = s == nullif (fresh) { s = server.sessions.mint() }s.data.loginError = whyserver.sessions.save(s)let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }return res}// the function route gets the cookie's session as req.session (hybriel #11); none yet → minted hereloginCallback = (route, req) => {if (req.method != 'GET') { return failed(req, 'GET only') }let q = req.query != null ? req.query : {}let code = q.ident_codeif (code == null || code == '') { return failed(req, 'ident sent no login code') }let x = exchangeCode(code)if (x.error != null) { return failed(req, x.error) }let u = ensureUser(x.identity)if (u == null) { return failed(req, 'could not store the user') }let s = req.sessionlet fresh = s == nullif (fresh) { s = server.sessions.mint() }s.user = { id = u.id }s.data.tag = randomBytes(16)s.data.loginError = nullserver.sessions.save(s)let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }return res}// ---- /posters/<name> (tracker.worldapi.org#4): a show's poster image, served dynamically from// storage/mpackdb/posters/ (the poster's file name is the show's oldId + its migrated extension,// shows.hl posterName) — falls back to a placeholder svg when the real file isn't there yet (the// mongo export never included the actual poster bytes, see the report's `open`).postersDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/posters'placeholderPoster = './assets/poster-placeholder.svg'posterNameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'isSafePosterName = (name) => {if (name == null || hlTypeName(name) != 'String' || name == '' || name.length > 100) { return false }let i = 0while (i < name.length) {if (!posterNameChars.includes(name[i])) { return false }i = i + 1}return true}endsWithStr = (s, suffix) => { return s.length >= suffix.length && s.slice(s.length - suffix.length) == suffix }mimeOfPoster = (name) => {if (endsWithStr(name, '.png')) { return 'image/png' }if (endsWithStr(name, '.webp')) { return 'image/webp' }if (endsWithStr(name, '.svg')) { return 'image/svg+xml' }return 'image/jpeg'}posterRoute = (route, req) => {let name = route.params != null ? route.params.name : nullif (!isSafePosterName(name)) { return new Response('bad poster name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }let path = postersDir + '/' + nameif (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })}// ---- /profiles/<name> (tracker.worldapi.org#16): a person's photo, from storage/mpackdb/profiles/ (people.hl syncProfile// downloads it on the first visit of the person page) — the same checks and placeholder as /posters/<name>profilesDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/profiles'profileRoute = (route, req) => {let name = route.params != null ? route.params.name : nullif (!isSafePosterName(name)) { return new Response('bad photo name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }let path = profilesDir + '/' + nameif (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })}// ---- the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now —// a permanent redirect so old links keep working (architect's decision)movedTo = (path) => { return new Response('moved to ' + path, { status = 301 headers = { 'Location' = path 'Content-Type' = 'text/plain; charset=utf-8' } }) }unwatchedMoved = (route, req) => { return movedTo('/my/unwatched') }scheduleMoved = (route, req) => { return movedTo('/my/schedule') }routes = [{ pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }// the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline){ pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/login/callback" function = loginCallback }{ pattern = "/login/failed" component = LoginFailed }{ pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/posters/:name" function = posterRoute }// tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a// page component cannot read `?page=` (hybriel#11) — and the movies the user follows{ pattern = "/movies" component = Movies }{ pattern = "/movies/page/:page" component = Movies }{ pattern = "/shows" component = AllShows }{ pattern = "/shows/page/:page" component = AllShows }{ pattern = "/shows/:slug" component = Show }{ pattern = "/my/shows" component = MyShows }{ pattern = "/my/movies" component = MyMovies }{ pattern = "/my/unwatched" component = Unwatched }{ pattern = "/my/schedule" component = Schedule }{ pattern = "/unwatched" function = unwatchedMoved }{ pattern = "/schedule" function = scheduleMoved }// tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`){ pattern = "/search/:q?" component = Search }// tracker.worldapi.org#16: a person's page (the show page's cast and the search link here) and their photo{ pattern = "/person/:slug" component = Person }{ pattern = "/profiles/:name" function = profileRoute }{ pattern = "/" component = Home }]// WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }audience = {trackerSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }trackerSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }}// cookies are per host, not per port: an own name keeps this app's session apart from// ident's own (and from any other worldapi app sharing a dev host), see ident README "Design// tokens" / hybriel#10 hybriel#17.sessionCookie = 'trackersid'// tracker.worldapi.org#14: the search index (search.hl) is built once here at boot (~0.6 s on the real data), not by the// first searchsearchIndexReady = ensureIndex()// tracker#18, ONCE (deltasync.hl clearCopiedSummaries): a `summary` that is only the migrated copy of tmdbSummary is cleared — the// current TMDB text shows; the creator's own texts staysummariesCleared = clearCopiedSummaries()if (summariesCleared.ran) { console.log('summaries: cleared ' + summariesCleared.cleared + ' copies of tmdbSummary, kept ' + summariesCleared.kept + ' own texts, errors ' + summariesCleared.errors + ', ' + summariesCleared.ms + ' ms') }server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching)// ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, tmdbsync.hl; tracker#18, deltasync.hl) -------------------------// Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC). hl:web serves ONE// request at a time, so the run never takes the server for itself: a 1-second clock does ONE step per tick and returns — the// requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.// tracker#18: the run first asks TMDB's and TVmaze's CHANGE LISTS since the last run (deltasync.hl — one list page per step)// and then syncs only the titles of ours that changed, followed ones first — every title stays current, not only the followed// ones. FULL WALK (every followed show, as before #18) on the first run, after a gap > 14 days, or when a change list fails.// A title's step: tmdbsync.hl syncShow (1–3 TMDB requests + maybe its poster, TVmaze) + details.hl applySynced (the record's// title, overview, tagline … and cast/crew from the same details answer). After a step that made n requests the next waits// n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze request (≤ 20 / 10 s, tracker.worldapi.org#12).// The finished run stores its day (deltasync.hl markSynced). Log: "tmdb sync: start, …", the change lists ("tmdb sync:// changes since …"), errors, slow steps, "tmdb sync done: mode=… changeRequests=… <totals>".// TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4syncOn = env('TRACKER_SYNC') != '0' && syncEnabledsyncQueue = []syncPlanning = falsesyncMode = ''syncMark = falsesyncChangeRequests = 0syncAt = 0syncDay = ''syncNextAt = 0syncTotals = emptyTotals()syncFinish = () => {persistDetails()if (syncMark) { markSynced(syncDay) }console.log('tmdb sync done: mode=' + syncMode + ' changeRequests=' + syncChangeRequests + ' ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000))return null}syncTick = () => {let t = now()if (syncQueue.length == 0 && !syncPlanning) {let stamp = timestamp(t)let day = stamp.slice(0, 10)if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }syncDay = daysyncAt = tsyncNextAt = 0syncTotals = emptyTotals()syncChangeRequests = 0let p = planStart(day, null)syncMode = p.modesyncMark = trueif (p.mode == 'delta') {syncPlanning = trueconsole.log('tmdb sync: start, changes ' + p.why)return null}syncQueue = allFollowedShowIds()console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows, full walk (' + p.why + ')')if (syncQueue.length == 0) { syncFinish() }return null}if (t < syncNextAt) { return null }if (syncPlanning) {let ps = planStep()syncChangeRequests = syncChangeRequests + ps.requests + ps.tvmazeRequestssyncTotals.requests = syncTotals.requests + ps.requestssyncTotals.tvmazeRequests = syncTotals.tvmazeRequests + ps.tvmazeRequestssyncNextAt = now() + pauseMsAfter(ps)if (!ps.done) { return null }syncPlanning = falseconsole.log('tmdb sync: ' + planLine())if (ps.failed != '') {// a change list could not be read: the old full walk, and the day is not advanced (the next run asks again)syncMode = 'full'syncMark = falsesyncQueue = allFollowedShowIds()console.log('tmdb sync: change list failed, full walk of ' + syncQueue.length + ' followed shows instead')} else {syncQueue = planIds()}if (syncQueue.length == 0) { syncFinish() }return null}let id = syncQueue[0]let rest = []let i = 1while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }syncQueue = rest// tracker#18: in a delta run a title nobody follows gets the light step (changed seasons, no TVmaze)let r = syncMode == 'delta' && !isFollowedInRun(id) ? syncShowDelta(id) : syncShow(id)// tracker#18 + #28: the record's own fields (title, overview, tagline …) and the cast + crew from the same details answerif (r.details != null) {let c = applySynced(id, r.details)if (c.error != '') { console.log('tmdb sync: ' + c.error) }if (c.renamed) { searchTitleRenamed(id) }}// the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode; the sync// also brings TMDB's adult flag (mission 054) → the search's view of it toorefreshCatalogShow(id)searchTitleChanged(id)let took = now() - tsyncTotals = addTotals(syncTotals, r)if (r.error != '') { console.log('tmdb sync: ' + r.error) }// a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the logif (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }syncNextAt = now() + pauseMsAfter(r)if (syncQueue.length > 0 && syncTotals.shows % 10 == 0) { persistDetails() }if (syncQueue.length == 0) { syncFinish() }return null}// ---- THE ADULT-FLAG BACKFILL (mission 054, tmdbsync.hl backfillTitle) -----------------------------------// The public lists and the search show only titles TMDB says are not adult (shows.hl isPublicTitle; unknown = hidden). At// start the app collects every title whose flag is still unknown and asks TMDB for ONE title per step — like the daily// sync, on the same clock, so requests queued meanwhile are served between two steps: one details request (adult,// poster_path, external ids) + the poster file when missing, then a pause of 260 ms per TMDB API request (≤ 40 / 10 s;// the poster comes from TMDB's image host, not the API, and is not counted). Each answered title goes into the lists// (catalog.hl refreshCatalogShow) and the search at once. RESUMES after a restart: the queue is built from what is// still unknown. Stops when the queue is empty; titles TMDB answers 404 for are marked (`adultCheck`) and stay hidden; a// passing failure (no answer, 429, 5xx) goes to the back of the queue, at most 2 more tries per start.// While the daily sync runs, the backfill waits. Log: start, every TRACKER_BACKFILL_LOG_EVERY (500) titles, done.// TRACKER_BACKFILL=0 switches it off; without TMDB_READ_TOKEN it is off too.backfillOn = env('TRACKER_BACKFILL') != '0' && syncEnabledbackfillLogEvery = env('TRACKER_BACKFILL_LOG_EVERY') != null ? toNumber(env('TRACKER_BACKFILL_LOG_EVERY')) : 500backfillQueue = nullbackfillPos = 0backfillDone = falsebackfillAt = 0backfillNextAt = 0backfillTries = {}backfillTotals = { titles = 0 adult = 0 notAdult = 0 unknown = 0 posters = 0 ids = 0 requests = 0 errors = 0 retries = 0 }backfillLine = () => {let b = backfillTotalsreturn b.titles + '/' + backfillQueue.length + ' titles, adult=' + b.adult + ' notAdult=' + b.notAdult + ' unknown=' + b.unknown + ' posters=' + b.posters+ ' ids=' + b.ids + ' requests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - backfillAt) / 1000)}backfillTick = () => {if (backfillDone) { return null }let t = now()if (backfillQueue == null) {backfillQueue = adultBackfillQueue()backfillAt = tconsole.log('adult backfill: start, ' + backfillQueue.length + ' titles without an adult flag (' + (now() - t) + ' ms to find them)')if (backfillQueue.length == 0) { backfillDone = true console.log('adult backfill: nothing to do') }return null}if (t < backfillNextAt) { return null }let id = backfillQueue[backfillPos]backfillPos = backfillPos + 1let r = backfillTitle(id)if (r.retry && (backfillTries[id] == null || backfillTries[id] < 2)) {backfillTries[id] = backfillTries[id] == null ? 1 : backfillTries[id] + 1let q = backfillQueueq.push(id)backfillQueue = qbackfillTotals.retries = backfillTotals.retries + 1} else {backfillTotals.titles = backfillTotals.titles + 1if (r.adult == true) { backfillTotals.adult = backfillTotals.adult + 1 } else if (r.adult == false) { backfillTotals.notAdult = backfillTotals.notAdult + 1 } else { backfillTotals.unknown = backfillTotals.unknown + 1 }}backfillTotals.posters = backfillTotals.posters + r.postersbackfillTotals.ids = backfillTotals.ids + r.idsbackfillTotals.requests = backfillTotals.requests + r.requestsbackfillTotals.errors = backfillTotals.errors + r.errorsif (r.error != '') { console.log('adult backfill: ' + r.error) }if (r.adult != null) {refreshCatalogShow(id)searchTitleChanged(id)}let took = now() - tif (took > 1500) { console.log('adult backfill: slow step, show ' + id + ', ' + took + ' ms') }backfillNextAt = now() + r.requests * msPerRequestlet finished = backfillPos >= backfillQueue.lengthif (finished || backfillPos % 25 == 0) { persistSync() }if (!finished && backfillTotals.titles > 0 && backfillTotals.titles % backfillLogEvery == 0 && !r.retry) { console.log('adult backfill: ' + backfillLine()) }if (finished) {backfillDone = trueconsole.log('adult backfill done: ' + backfillLine())}return null}// ---- THE DETAILS REPAIR (tracker.worldapi.org#26, details.hl completeStep) ----------------------------------------// Titles the person pages added from a filmography (#16) are MINIMAL (no poster, seasons, ids, cast …). Opening one completes// it (components/show.hl); this job completes the rest in the background: at start it collects every incomplete, non-adult// title and does ONE per step on the app's clock, like the adult backfill — a step is the daily sync's work for one title// (1–3 TMDB requests + poster + TVmaze), requests queued meanwhile are served between two steps; then a pause of 260 ms per// TMDB request + 550 ms per TVmaze request (pauseMsAfter: ≤ 40 / 10 s, ≤ 20 / 10 s). RESUMES after a restart (the queue is// what is still incomplete); TMDB 404 marks the title (`detailsCheck`), a passing failure goes to the back of the queue (at// most 2 more tries per start). Waits while the daily sync or the adult backfill runs. Persisted every 10 titles + at the end.// Log: start, every TRACKER_REPAIR_LOG_EVERY (100) titles, each failure, done. TRACKER_REPAIR=0 switches it off (off too// without TMDB_READ_TOKEN). TRACKER_REPAIR_FAST=1 (the gate, fake TMDB only): 20 ms pause instead.repairOn = env('TRACKER_REPAIR') != '0' && syncEnabledrepairFast = env('TRACKER_REPAIR_FAST') == '1'repairLogEvery = env('TRACKER_REPAIR_LOG_EVERY') != null ? toNumber(env('TRACKER_REPAIR_LOG_EVERY')) : 100repairQueue = nullrepairPos = 0repairDone = falserepairAt = 0repairNextAt = 0repairTries = {}repairTotals = { titles = 0 complete = 0 failed = 0 adult = 0 newSeasons = 0 newEpisodes = 0 posters = 0 cast = 0 requests = 0 tvmazeRequests = 0 retries = 0 }repairLine = () => {let b = repairTotalsreturn b.titles + '/' + repairQueue.length + ' titles, complete=' + b.complete + ' failed=' + b.failed + ' adult=' + b.adult + ' newSeasons=' + b.newSeasons + ' newEpisodes=' + b.newEpisodes+ ' posters=' + b.posters + ' cast=' + b.cast + ' requests=' + b.requests + ' tvmazeRequests=' + b.tvmazeRequests + ' retries=' + b.retries + ' seconds=' + ((now() - repairAt) / 1000)}repairTick = () => {if (repairDone) { return null }let t = now()if (repairQueue == null) {repairQueue = detailsRepairQueue()repairAt = tconsole.log('details repair: start, ' + repairQueue.length + ' incomplete titles (' + (now() - t) + ' ms to find them)')if (repairQueue.length == 0) { repairDone = true console.log('details repair: nothing to do') }return null}if (t < repairNextAt) { return null }let id = repairQueue[repairPos]let r = completeStep(id)let took = now() - tif (took > 1500) { console.log('details repair: slow step, show ' + id + ', ' + took + ' ms') }if (r.error != '') { console.log('details repair: ' + r.error) }repairNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))// a series takes several steps: the same title again next timeif (!r.done && !r.retry) { return null }repairPos = repairPos + 1if (r.retry && (repairTries[id] == null || repairTries[id] < 2)) {repairTries[id] = repairTries[id] == null ? 1 : repairTries[id] + 1let q = repairQueueq.push(id)repairQueue = qrepairTotals.retries = repairTotals.retries + 1} else if (!r.skipped) {// done: its counts (a failed first step: the request alone)let sum = r.sumrepairTotals.titles = repairTotals.titles + 1if (r.adult == true) { repairTotals.adult = repairTotals.adult + 1 } else if (sum.steps == 0) { repairTotals.failed = repairTotals.failed + 1 } else { repairTotals.complete = repairTotals.complete + 1 }repairTotals.newSeasons = repairTotals.newSeasons + sum.newSeasonsrepairTotals.newEpisodes = repairTotals.newEpisodes + sum.newEpisodesrepairTotals.posters = repairTotals.posters + sum.postersrepairTotals.cast = repairTotals.cast + sum.castrepairTotals.requests = repairTotals.requests + (sum.steps == 0 ? r.requests : sum.requests)repairTotals.tvmazeRequests = repairTotals.tvmazeRequests + sum.tvmazeRequests}let finished = repairPos >= repairQueue.lengthif (finished || repairPos % 10 == 0) { persistDetails() }if (!finished && !r.skipped && !r.retry && repairTotals.titles > 0 && repairTotals.titles % repairLogEvery == 0) { console.log('details repair: ' + repairLine()) }if (finished) {repairDone = trueconsole.log('details repair done: ' + repairLine())}return null}// ---- THE CREDITS JOB (tracker.worldapi.org#28, details.hl creditsStep) ------------------------------------------------------// Every PUBLIC title (adult == false; adult/unknown are skipped) with a TMDB id gets its whole cast + crew once: at start (after// the adult backfill and the details repair are done) the job collects every such title without `creditsAt` and asks ONE per// step on the app's clock — one request (details + credits / aggregate_credits), then 260 ms (≤ 40 / 10 s); requests queued// meanwhile are served between two steps. Titles the details repair, the daily sync or an import already did carry `creditsAt`// and are not asked. RESUMES after a restart (the queue = what still has no credits); TMDB 404 / adult → `creditsCheck`, never// asked again; a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily sync// runs. Persisted (shows + people only) every 25 titles + at the end. Log: start, every TRACKER_CREDITS_LOG_EVERY (500) titles, failures, slow steps// (> 1.5 s), done. TRACKER_CREDITS=0 switches it off (off too without TMDB_READ_TOKEN). TRACKER_CREDITS_FAST=1 (the gate, fake// TMDB only): 20 ms pause instead.// MEMORY LIMIT: the runtime never frees what a fetch + JSON parse took (mission 061 measured ~6 MB more RSS per title on the real// data, 300 fetches of a 440 KB JSON = +2.7 GB in a 10-line script) — the whole job in one process would add ~35 GB. Before every// step the job reads its own RSS (/proc/self/status); above TRACKER_CREDITS_MAX_MB (16000) it PAUSES for this process (logged) and// goes on with what is left after the next restart (deploy, `docker restart`).creditsOn = env('TRACKER_CREDITS') != '0' && syncEnabledcreditsFast = env('TRACKER_CREDITS_FAST') == '1'creditsLogEvery = env('TRACKER_CREDITS_LOG_EVERY') != null ? toNumber(env('TRACKER_CREDITS_LOG_EVERY')) : 500creditsQueueIds = nullcreditsPos = 0creditsDone = falsecreditsAt = 0creditsNextAt = 0creditsTries = {}creditsMaxMb = env('TRACKER_CREDITS_MAX_MB') != null ? toNumber(env('TRACKER_CREDITS_MAX_MB')) : 16000creditsTotals = { titles = 0 done = 0 failed = 0 cast = 0 crew = 0 people = 0 requests = 0 retries = 0 slowest = 0 }// this process' resident memory in MB (VmRSS), 0 when unknownrssMb = () => {if (!exists('/proc/self/status')) { return 0 }let t = readFile('/proc/self/status')let i = t != null ? t.indexOf('VmRSS:') : -1if (i < 0) { return 0 }let kb = toNumber(t.slice(i + 6, t.indexOf('kB', i)).trim())return kb != null ? (kb - kb % 1024) / 1024 : 0}creditsLine = () => {let b = creditsTotalsreturn b.titles + '/' + creditsQueueIds.length + ' titles, done=' + b.done + ' failed=' + b.failed + ' cast=' + b.cast + ' crew=' + b.crew + ' people=' + b.people+ ' requests=' + b.requests + ' retries=' + b.retries + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - creditsAt) / 1000)}creditsTick = () => {if (creditsDone) { return null }let t = now()if (creditsQueueIds == null) {creditsQueueIds = creditsQueue()creditsAt = tconsole.log('credits job: start, ' + creditsQueueIds.length + ' titles without credits (' + (now() - t) + ' ms to find them)')if (creditsQueueIds.length == 0) { creditsDone = true console.log('credits job: nothing to do') }return null}if (t < creditsNextAt) { return null }let mb = rssMb()if (mb > creditsMaxMb) {creditsDone = truepersistCredits()console.log('credits job: paused, RSS ' + mb + ' MB > TRACKER_CREDITS_MAX_MB ' + creditsMaxMb + ' — ' + (creditsQueueIds.length - creditsPos) + ' titles left for the next start; ' + creditsLine())return null}let id = creditsQueueIds[creditsPos]creditsPos = creditsPos + 1let r = creditsStep(id)let took = now() - tif (took > creditsTotals.slowest) { creditsTotals.slowest = took }if (took > 1500) { console.log('credits job: slow step, show ' + id + ', ' + took + ' ms, cast=' + r.cast + ' crew=' + r.crew + ' people=' + r.people) }if (r.error != '') { console.log('credits job: ' + r.error) }creditsNextAt = now() + (creditsFast ? 20 : r.requests * msPerRequest)if (r.retry && (creditsTries[id] == null || creditsTries[id] < 2)) {creditsTries[id] = creditsTries[id] == null ? 1 : creditsTries[id] + 1let q = creditsQueueIdsq.push(id)creditsQueueIds = qcreditsTotals.retries = creditsTotals.retries + 1} else if (!r.skipped) {creditsTotals.titles = creditsTotals.titles + 1if (r.error != '') { creditsTotals.failed = creditsTotals.failed + 1 } else { creditsTotals.done = creditsTotals.done + 1 }creditsTotals.cast = creditsTotals.cast + r.castcreditsTotals.crew = creditsTotals.crew + r.crewcreditsTotals.people = creditsTotals.people + r.people}creditsTotals.requests = creditsTotals.requests + r.requestslet finished = creditsPos >= creditsQueueIds.lengthif (finished || creditsPos % 25 == 0) { persistCredits() }if (!finished && !r.skipped && !r.retry && creditsTotals.titles > 0 && creditsTotals.titles % creditsLogEvery == 0) { console.log('credits job: ' + creditsLine()) }if (finished) {creditsDone = trueconsole.log('credits job done: ' + creditsLine())}return null}// ONE clock for all four (a tick every 0.1 s): the daily sync's step once a second as before; the backfill's steps in// between, only while no daily run is going on; the details repair only when neither has work; the credits job (#28) lastclockOn = syncOn || backfillOn || repairOn || creditsOnclockTicks = 0if (syncOn) { console.log('tmdb sync: daily at ' + syncHour + ':00 UTC') } else { console.log('tmdb sync: off (' + (syncEnabled ? 'TRACKER_SYNC=0' : 'no TMDB_READ_TOKEN') + ')') }if (!backfillOn) { console.log('adult backfill: off (' + (syncEnabled ? 'TRACKER_BACKFILL=0' : 'no TMDB_READ_TOKEN') + ')') }if (!repairOn) { console.log('details repair: off (' + (syncEnabled ? 'TRACKER_REPAIR=0' : 'no TMDB_READ_TOKEN') + ')') }if (!creditsOn) { console.log('credits job: off (' + (syncEnabled ? 'TRACKER_CREDITS=0' : 'no TMDB_READ_TOKEN') + ')') }if (clockOn) {syncClock = every(0.1)on syncClock.tick(x) {clockTicks = clockTicks + 1let busy = syncQueue.length > 0 || syncPlanningif (syncOn && clockTicks % 10 == 0) { syncTick() }let free = !busy && syncQueue.length == 0 && !syncPlanningif (backfillOn && free && !backfillDone) { backfillTick() }else if (repairOn && free && (!backfillOn || backfillDone) && !repairDone) { repairTick() }else if (creditsOn && free && (!backfillOn || backfillDone) && (!repairOn || repairDone)) { creditsTick() }return null}}on Error(e) { console.log('error absorbed: ' + e.message) }
Branches
- mainmain branch
Latest commits
- f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmre
- 10bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre
- 25a50bc4tracker#26 (mission 059): titles from a filmography are completed — on open (skeleton, step-wise face showComplete, no reload) and by the in-app details repair (resumes, TMDB-paced, series in parts); cast from TMDB credits; gate 231, tests/realdata-026.mjs, README + STATUSmre
- 1704ec45tracker#17 (mission 057): season caret down/up, skeleton rows while a season loads, sessionless showSeasonEpisodes face (no page re-mount), client-only close; gate 214, tests/realdata-057.mjs, README + STATUSmre
- f2fe3e36mission 056: README + STATUS (merge, fixes, Hybriel 8590df63, real-data check), tests/realdata-056.mjs, tools/check-public-slugs.hlmre
- f40c250emission 056: re-vendor hybriel master 8590df63 (#121, #122); an adult title's page is Not found for non-followers; gate: leave the page before stopping the servermre
- 2b7fdd6cmission 056: signed-out header one row on phones ("Log in", nowrap), backfill skips adult titles' posters, gate checksmre
- 2c53d5efMerge branch 't16-person' (tracker#16 person pages) into main; filmography shows only public titles (054 adult flag), gate race fix (backfill start line)mre
- c171227emission 054: hide adult/unknown titles from the public lists and the search; in-app adult-flag backfill (TMDB details + poster per title, resumes), gate + real-data proofmre
- 139fafd8tracker#16: short bio (4 lines, click = all), real-data check script, README + STATUSmre
- 93be9476tracker#16: person pages /person/<slug> with the filmography fetched from TMDB on the first visit (step by step), gatemre
- 47a3cae6STATUS: mission 053 merge commit idsmre
- dcc5eecaMerge branch 't14-search'mre
- 03edc783Merge branch 't15-tvmaze'mre
- 71b46345tracker#15: numbering check by date or title, placeholder titles in other languages, docs + real-data proofmre
- 6bb2daf1tracker#13: homepage (tiles, intro, latest movies/shows), /shows, /movies/page/N, /my/movies; lists cached in memorymre
- 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
- 34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre
- cbdc4ea7tracker#12: link icons TMDB/IMDb/TVDB/TVmaze; sync fills missing ids (TVmaze lookup); movies fetched via /movie/mre