gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit10bb3f9310bb3f93tracker#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 + STATUSmre10bb3f93/project.hl

30.0 KB

  1. // project.hl — tracker.worldapi.org: STEP 1 (tracker.worldapi.org#1), an empty shell. Login copied unchanged from
  2. // calendar.worldapi.org (rejected once for a centered sign-in and no header selector — architect, 2026-09-27):
  3. // ident only, no own passwords (README "How apps use ident" of ident.worldapi.org), the identity selector in the
  4. // header (components/main.hl). No shows, no data yet — later steps come from the creator (CONCEPT.md).
  5. //
  6. // the header's ident-selector / "Log in with ident" -> <ident>/login?key=&return=<this app>/login/callback
  7. // /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id
  8. // (POST <ident>/api/exchange) and signs this app's OWN session in
  9. // (session.user = { id = <users @id> }, users.hl)
  10. // the header's "Log out" button signs this app's session out via the face trackerLogOut (components/main.hl)
  11. // — ident's own session, and the browser's ident cookie, are untouched
  12. //
  13. // Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the
  14. // architect, as with ident's own .env for SMTP):
  15. // TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),
  16. // IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…)
  17. import WebFramework from 'hl:web'
  18. import { Response } from 'hl:http1'
  19. import { randomBytes } from 'hl:crypto'
  20. import { env } from 'hl:proc'
  21. import { readBytes, readFile, exists } from 'hl:fs'
  22. import { now, timestamp, every } from 'hl:time'
  23. import Styles from './styles.hl'
  24. import { exchangeCode, ensureUser } from './users.hl'
  25. import Home from './components/home.hl'
  26. import LoginFailed from './components/loginfailed.hl'
  27. import Show from './components/show.hl'
  28. import Unwatched from './components/unwatched.hl'
  29. import Schedule from './components/schedule.hl'
  30. import MyShows from './components/myshows.hl'
  31. import MyMovies from './components/mymovies.hl'
  32. import Movies from './components/movies.hl'
  33. import AllShows from './components/allshows.hl'
  34. import Search from './components/search.hl'
  35. import Person from './components/person.hl'
  36. import { ensureIndex, searchTitleChanged } from './search.hl'
  37. import { syncEnabled, syncShow, persistSync, emptyTotals, addTotals, totalsLine, pauseMsAfter, msPerRequest, adultBackfillQueue, backfillTitle } from './tmdbsync.hl'
  38. import { detailsRepairQueue, completeStep, completeLine, persistDetails, persistCredits, applyCredits, creditsQueue, creditsStep } from './details.hl'
  39. import { allFollowedShowIds } from './follows.hl'
  40. import { refreshCatalogShow } from './catalog.hl'
  41. import { dark, darker } from './shared/tokens.hl'
  42. static appTitle = "tracker"
  43. // ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app
  44. // manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service
  45. // worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs
  46. // are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the
  47. // splash background the page's (dark) — both off the tokens, not written out again.
  48. appThemeColor = darker.value
  49. appBackgroundColor = dark.value
  50. appIcons = [
  51. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }
  52. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }
  53. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }
  54. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }
  55. ]
  56. appTouchIcon = '/icons/apple-touch-icon.png'
  57. appFavicon = '/icons/favicon.svg'
  58. // OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no
  59. // network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.
  60. offline = [ Home ]
  61. styles = Styles
  62. port = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008
  63. watching = env('TRACKER_WATCH') != '0'
  64. // read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call below
  65. sessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null
  66. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl
  67. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  68. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  69. nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  70. safePath = (want) => {
  71. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  72. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  73. let i = 0
  74. while (i < want.length) {
  75. if (!nextChars.includes(want[i])) { return '/' }
  76. i = i + 1
  77. }
  78. return want
  79. }
  80. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  81. failed = (req, why) => {
  82. let s = req.session
  83. let fresh = s == null
  84. if (fresh) { s = server.sessions.mint() }
  85. s.data.loginError = why
  86. server.sessions.save(s)
  87. let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  88. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  89. return res
  90. }
  91. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here
  92. loginCallback = (route, req) => {
  93. if (req.method != 'GET') { return failed(req, 'GET only') }
  94. let q = req.query != null ? req.query : {}
  95. let code = q.ident_code
  96. if (code == null || code == '') { return failed(req, 'ident sent no login code') }
  97. let x = exchangeCode(code)
  98. if (x.error != null) { return failed(req, x.error) }
  99. let u = ensureUser(x.identity)
  100. if (u == null) { return failed(req, 'could not store the user') }
  101. let s = req.session
  102. let fresh = s == null
  103. if (fresh) { s = server.sessions.mint() }
  104. s.user = { id = u.id }
  105. s.data.tag = randomBytes(16)
  106. s.data.loginError = null
  107. server.sessions.save(s)
  108. let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  109. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  110. return res
  111. }
  112. // ---- /posters/<name> (tracker.worldapi.org#4): a show's poster image, served dynamically from
  113. // storage/mpackdb/posters/ (the poster's file name is the show's oldId + its migrated extension,
  114. // shows.hl posterName) — falls back to a placeholder svg when the real file isn't there yet (the
  115. // mongo export never included the actual poster bytes, see the report's `open`).
  116. postersDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/posters'
  117. placeholderPoster = './assets/poster-placeholder.svg'
  118. posterNameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'
  119. isSafePosterName = (name) => {
  120. if (name == null || hlTypeName(name) != 'String' || name == '' || name.length > 100) { return false }
  121. let i = 0
  122. while (i < name.length) {
  123. if (!posterNameChars.includes(name[i])) { return false }
  124. i = i + 1
  125. }
  126. return true
  127. }
  128. endsWithStr = (s, suffix) => { return s.length >= suffix.length && s.slice(s.length - suffix.length) == suffix }
  129. mimeOfPoster = (name) => {
  130. if (endsWithStr(name, '.png')) { return 'image/png' }
  131. if (endsWithStr(name, '.webp')) { return 'image/webp' }
  132. if (endsWithStr(name, '.svg')) { return 'image/svg+xml' }
  133. return 'image/jpeg'
  134. }
  135. posterRoute = (route, req) => {
  136. let name = route.params != null ? route.params.name : null
  137. if (!isSafePosterName(name)) { return new Response('bad poster name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  138. let path = postersDir + '/' + name
  139. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  140. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  141. }
  142. // ---- /profiles/<name> (tracker.worldapi.org#16): a person's photo, from storage/mpackdb/profiles/ (people.hl syncProfile
  143. // downloads it on the first visit of the person page) — the same checks and placeholder as /posters/<name>
  144. profilesDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/profiles'
  145. profileRoute = (route, req) => {
  146. let name = route.params != null ? route.params.name : null
  147. if (!isSafePosterName(name)) { return new Response('bad photo name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  148. let path = profilesDir + '/' + name
  149. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  150. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  151. }
  152. // ---- the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now —
  153. // a permanent redirect so old links keep working (architect's decision)
  154. movedTo = (path) => { return new Response('moved to ' + path, { status = 301 headers = { 'Location' = path 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  155. unwatchedMoved = (route, req) => { return movedTo('/my/unwatched') }
  156. scheduleMoved = (route, req) => { return movedTo('/my/schedule') }
  157. routes = [
  158. { pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }
  159. // the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline)
  160. { pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }
  161. { pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }
  162. { pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }
  163. { pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }
  164. { pattern = "/login/callback" function = loginCallback }
  165. { pattern = "/login/failed" component = LoginFailed }
  166. { pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }
  167. { pattern = "/posters/:name" function = posterRoute }
  168. // tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a
  169. // page component cannot read `?page=` (hybriel#11) — and the movies the user follows
  170. { pattern = "/movies" component = Movies }
  171. { pattern = "/movies/page/:page" component = Movies }
  172. { pattern = "/shows" component = AllShows }
  173. { pattern = "/shows/page/:page" component = AllShows }
  174. { pattern = "/shows/:slug" component = Show }
  175. { pattern = "/my/shows" component = MyShows }
  176. { pattern = "/my/movies" component = MyMovies }
  177. { pattern = "/my/unwatched" component = Unwatched }
  178. { pattern = "/my/schedule" component = Schedule }
  179. { pattern = "/unwatched" function = unwatchedMoved }
  180. { pattern = "/schedule" function = scheduleMoved }
  181. // tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`)
  182. { pattern = "/search/:q?" component = Search }
  183. // tracker.worldapi.org#16: a person's page (the show page's cast and the search link here) and their photo
  184. { pattern = "/person/:slug" component = Person }
  185. { pattern = "/profiles/:name" function = profileRoute }
  186. { pattern = "/" component = Home }
  187. ]
  188. // WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).
  189. tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }
  190. audience = {
  191. trackerSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }
  192. trackerSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }
  193. }
  194. // cookies are per host, not per port: an own name keeps this app's session apart from
  195. // ident's own (and from any other worldapi app sharing a dev host), see ident README "Design
  196. // tokens" / hybriel#10 hybriel#17.
  197. sessionCookie = 'trackersid'
  198. // 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
  199. // first search
  200. searchIndexReady = ensureIndex()
  201. server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching)
  202. // ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, tmdbsync.hl) --------------------------------------
  203. // Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC) every
  204. // followed show is synced from TMDB. hl:web serves ONE request at a time, so the run never takes the server
  205. // for itself: a 1-second clock does ONE show per tick (1–3 TMDB requests + maybe its poster) and returns — the
  206. // requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.
  207. // After a show that made n requests the next waits n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze lookup
  208. // (≤ 20 / 10 s, tracker.worldapi.org#12).
  209. // TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).
  210. syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4
  211. syncOn = env('TRACKER_SYNC') != '0' && syncEnabled
  212. syncQueue = []
  213. syncAt = 0
  214. syncDay = ''
  215. syncNextAt = 0
  216. syncTotals = emptyTotals()
  217. syncTick = () => {
  218. let t = now()
  219. if (syncQueue.length == 0) {
  220. let stamp = timestamp(t)
  221. let day = stamp.slice(0, 10)
  222. if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }
  223. syncDay = day
  224. syncQueue = allFollowedShowIds()
  225. syncAt = t
  226. syncNextAt = 0
  227. syncTotals = emptyTotals()
  228. console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows')
  229. return null
  230. }
  231. if (t < syncNextAt) { return null }
  232. let id = syncQueue[0]
  233. let rest = []
  234. let i = 1
  235. while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }
  236. syncQueue = rest
  237. let r = syncShow(id)
  238. // tracker#28: the cast + crew came with the details request (details.hl applyCredits)
  239. if (r.details != null) {
  240. let c = applyCredits(id, r.details)
  241. if (c.error != '') { console.log('tmdb sync: ' + c.error) }
  242. }
  243. // the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode; the sync
  244. // also brings TMDB's adult flag (mission 054) → the search's view of it too
  245. refreshCatalogShow(id)
  246. searchTitleChanged(id)
  247. let took = now() - t
  248. syncTotals = addTotals(syncTotals, r)
  249. if (r.error != '') { console.log('tmdb sync: ' + r.error) }
  250. // a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the log
  251. if (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }
  252. syncNextAt = now() + pauseMsAfter(r)
  253. if (syncQueue.length == 0 || syncTotals.shows % 10 == 0) { persistDetails() }
  254. if (syncQueue.length == 0) { console.log('tmdb sync done: ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000)) }
  255. return null
  256. }
  257. // ---- THE ADULT-FLAG BACKFILL (mission 054, tmdbsync.hl backfillTitle) -----------------------------------
  258. // The public lists and the search show only titles TMDB says are not adult (shows.hl isPublicTitle; unknown = hidden). At
  259. // start the app collects every title whose flag is still unknown and asks TMDB for ONE title per step — like the daily
  260. // sync, on the same clock, so requests queued meanwhile are served between two steps: one details request (adult,
  261. // poster_path, external ids) + the poster file when missing, then a pause of 260 ms per TMDB API request (≤ 40 / 10 s;
  262. // the poster comes from TMDB's image host, not the API, and is not counted). Each answered title goes into the lists
  263. // (catalog.hl refreshCatalogShow) and the search at once. RESUMES after a restart: the queue is built from what is
  264. // still unknown. Stops when the queue is empty; titles TMDB answers 404 for are marked (`adultCheck`) and stay hidden; a
  265. // passing failure (no answer, 429, 5xx) goes to the back of the queue, at most 2 more tries per start.
  266. // While the daily sync runs, the backfill waits. Log: start, every TRACKER_BACKFILL_LOG_EVERY (500) titles, done.
  267. // TRACKER_BACKFILL=0 switches it off; without TMDB_READ_TOKEN it is off too.
  268. backfillOn = env('TRACKER_BACKFILL') != '0' && syncEnabled
  269. backfillLogEvery = env('TRACKER_BACKFILL_LOG_EVERY') != null ? toNumber(env('TRACKER_BACKFILL_LOG_EVERY')) : 500
  270. backfillQueue = null
  271. backfillPos = 0
  272. backfillDone = false
  273. backfillAt = 0
  274. backfillNextAt = 0
  275. backfillTries = {}
  276. backfillTotals = { titles = 0 adult = 0 notAdult = 0 unknown = 0 posters = 0 ids = 0 requests = 0 errors = 0 retries = 0 }
  277. backfillLine = () => {
  278. let b = backfillTotals
  279. return b.titles + '/' + backfillQueue.length + ' titles, adult=' + b.adult + ' notAdult=' + b.notAdult + ' unknown=' + b.unknown + ' posters=' + b.posters
  280. + ' ids=' + b.ids + ' requests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - backfillAt) / 1000)
  281. }
  282. backfillTick = () => {
  283. if (backfillDone) { return null }
  284. let t = now()
  285. if (backfillQueue == null) {
  286. backfillQueue = adultBackfillQueue()
  287. backfillAt = t
  288. console.log('adult backfill: start, ' + backfillQueue.length + ' titles without an adult flag (' + (now() - t) + ' ms to find them)')
  289. if (backfillQueue.length == 0) { backfillDone = true console.log('adult backfill: nothing to do') }
  290. return null
  291. }
  292. if (t < backfillNextAt) { return null }
  293. let id = backfillQueue[backfillPos]
  294. backfillPos = backfillPos + 1
  295. let r = backfillTitle(id)
  296. if (r.retry && (backfillTries[id] == null || backfillTries[id] < 2)) {
  297. backfillTries[id] = backfillTries[id] == null ? 1 : backfillTries[id] + 1
  298. let q = backfillQueue
  299. q.push(id)
  300. backfillQueue = q
  301. backfillTotals.retries = backfillTotals.retries + 1
  302. } else {
  303. backfillTotals.titles = backfillTotals.titles + 1
  304. if (r.adult == true) { backfillTotals.adult = backfillTotals.adult + 1 } else if (r.adult == false) { backfillTotals.notAdult = backfillTotals.notAdult + 1 } else { backfillTotals.unknown = backfillTotals.unknown + 1 }
  305. }
  306. backfillTotals.posters = backfillTotals.posters + r.posters
  307. backfillTotals.ids = backfillTotals.ids + r.ids
  308. backfillTotals.requests = backfillTotals.requests + r.requests
  309. backfillTotals.errors = backfillTotals.errors + r.errors
  310. if (r.error != '') { console.log('adult backfill: ' + r.error) }
  311. if (r.adult != null) {
  312. refreshCatalogShow(id)
  313. searchTitleChanged(id)
  314. }
  315. let took = now() - t
  316. if (took > 1500) { console.log('adult backfill: slow step, show ' + id + ', ' + took + ' ms') }
  317. backfillNextAt = now() + r.requests * msPerRequest
  318. let finished = backfillPos >= backfillQueue.length
  319. if (finished || backfillPos % 25 == 0) { persistSync() }
  320. if (!finished && backfillTotals.titles > 0 && backfillTotals.titles % backfillLogEvery == 0 && !r.retry) { console.log('adult backfill: ' + backfillLine()) }
  321. if (finished) {
  322. backfillDone = true
  323. console.log('adult backfill done: ' + backfillLine())
  324. }
  325. return null
  326. }
  327. // ---- THE DETAILS REPAIR (tracker.worldapi.org#26, details.hl completeStep) ----------------------------------------
  328. // Titles the person pages added from a filmography (#16) are MINIMAL (no poster, seasons, ids, cast …). Opening one completes
  329. // it (components/show.hl); this job completes the rest in the background: at start it collects every incomplete, non-adult
  330. // 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
  331. // (1–3 TMDB requests + poster + TVmaze), requests queued meanwhile are served between two steps; then a pause of 260 ms per
  332. // TMDB request + 550 ms per TVmaze request (pauseMsAfter: ≤ 40 / 10 s, ≤ 20 / 10 s). RESUMES after a restart (the queue is
  333. // what is still incomplete); TMDB 404 marks the title (`detailsCheck`), a passing failure goes to the back of the queue (at
  334. // most 2 more tries per start). Waits while the daily sync or the adult backfill runs. Persisted every 10 titles + at the end.
  335. // Log: start, every TRACKER_REPAIR_LOG_EVERY (100) titles, each failure, done. TRACKER_REPAIR=0 switches it off (off too
  336. // without TMDB_READ_TOKEN). TRACKER_REPAIR_FAST=1 (the gate, fake TMDB only): 20 ms pause instead.
  337. repairOn = env('TRACKER_REPAIR') != '0' && syncEnabled
  338. repairFast = env('TRACKER_REPAIR_FAST') == '1'
  339. repairLogEvery = env('TRACKER_REPAIR_LOG_EVERY') != null ? toNumber(env('TRACKER_REPAIR_LOG_EVERY')) : 100
  340. repairQueue = null
  341. repairPos = 0
  342. repairDone = false
  343. repairAt = 0
  344. repairNextAt = 0
  345. repairTries = {}
  346. repairTotals = { titles = 0 complete = 0 failed = 0 adult = 0 newSeasons = 0 newEpisodes = 0 posters = 0 cast = 0 requests = 0 tvmazeRequests = 0 retries = 0 }
  347. repairLine = () => {
  348. let b = repairTotals
  349. return b.titles + '/' + repairQueue.length + ' titles, complete=' + b.complete + ' failed=' + b.failed + ' adult=' + b.adult + ' newSeasons=' + b.newSeasons + ' newEpisodes=' + b.newEpisodes
  350. + ' posters=' + b.posters + ' cast=' + b.cast + ' requests=' + b.requests + ' tvmazeRequests=' + b.tvmazeRequests + ' retries=' + b.retries + ' seconds=' + ((now() - repairAt) / 1000)
  351. }
  352. repairTick = () => {
  353. if (repairDone) { return null }
  354. let t = now()
  355. if (repairQueue == null) {
  356. repairQueue = detailsRepairQueue()
  357. repairAt = t
  358. console.log('details repair: start, ' + repairQueue.length + ' incomplete titles (' + (now() - t) + ' ms to find them)')
  359. if (repairQueue.length == 0) { repairDone = true console.log('details repair: nothing to do') }
  360. return null
  361. }
  362. if (t < repairNextAt) { return null }
  363. let id = repairQueue[repairPos]
  364. let r = completeStep(id)
  365. let took = now() - t
  366. if (took > 1500) { console.log('details repair: slow step, show ' + id + ', ' + took + ' ms') }
  367. if (r.error != '') { console.log('details repair: ' + r.error) }
  368. repairNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))
  369. // a series takes several steps: the same title again next time
  370. if (!r.done && !r.retry) { return null }
  371. repairPos = repairPos + 1
  372. if (r.retry && (repairTries[id] == null || repairTries[id] < 2)) {
  373. repairTries[id] = repairTries[id] == null ? 1 : repairTries[id] + 1
  374. let q = repairQueue
  375. q.push(id)
  376. repairQueue = q
  377. repairTotals.retries = repairTotals.retries + 1
  378. } else if (!r.skipped) {
  379. // done: its counts (a failed first step: the request alone)
  380. let sum = r.sum
  381. repairTotals.titles = repairTotals.titles + 1
  382. if (r.adult == true) { repairTotals.adult = repairTotals.adult + 1 } else if (sum.steps == 0) { repairTotals.failed = repairTotals.failed + 1 } else { repairTotals.complete = repairTotals.complete + 1 }
  383. repairTotals.newSeasons = repairTotals.newSeasons + sum.newSeasons
  384. repairTotals.newEpisodes = repairTotals.newEpisodes + sum.newEpisodes
  385. repairTotals.posters = repairTotals.posters + sum.posters
  386. repairTotals.cast = repairTotals.cast + sum.cast
  387. repairTotals.requests = repairTotals.requests + (sum.steps == 0 ? r.requests : sum.requests)
  388. repairTotals.tvmazeRequests = repairTotals.tvmazeRequests + sum.tvmazeRequests
  389. }
  390. let finished = repairPos >= repairQueue.length
  391. if (finished || repairPos % 10 == 0) { persistDetails() }
  392. if (!finished && !r.skipped && !r.retry && repairTotals.titles > 0 && repairTotals.titles % repairLogEvery == 0) { console.log('details repair: ' + repairLine()) }
  393. if (finished) {
  394. repairDone = true
  395. console.log('details repair done: ' + repairLine())
  396. }
  397. return null
  398. }
  399. // ---- THE CREDITS JOB (tracker.worldapi.org#28, details.hl creditsStep) ------------------------------------------------------
  400. // Every PUBLIC title (adult == false; adult/unknown are skipped) with a TMDB id gets its whole cast + crew once: at start (after
  401. // the adult backfill and the details repair are done) the job collects every such title without `creditsAt` and asks ONE per
  402. // step on the app's clock — one request (details + credits / aggregate_credits), then 260 ms (≤ 40 / 10 s); requests queued
  403. // meanwhile are served between two steps. Titles the details repair, the daily sync or an import already did carry `creditsAt`
  404. // and are not asked. RESUMES after a restart (the queue = what still has no credits); TMDB 404 / adult → `creditsCheck`, never
  405. // asked again; a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily sync
  406. // runs. Persisted (shows + people only) every 25 titles + at the end. Log: start, every TRACKER_CREDITS_LOG_EVERY (500) titles, failures, slow steps
  407. // (> 1.5 s), done. TRACKER_CREDITS=0 switches it off (off too without TMDB_READ_TOKEN). TRACKER_CREDITS_FAST=1 (the gate, fake
  408. // TMDB only): 20 ms pause instead.
  409. // MEMORY LIMIT: the runtime never frees what a fetch + JSON parse took (mission 061 measured ~6 MB more RSS per title on the real
  410. // 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
  411. // step the job reads its own RSS (/proc/self/status); above TRACKER_CREDITS_MAX_MB (16000) it PAUSES for this process (logged) and
  412. // goes on with what is left after the next restart (deploy, `docker restart`).
  413. creditsOn = env('TRACKER_CREDITS') != '0' && syncEnabled
  414. creditsFast = env('TRACKER_CREDITS_FAST') == '1'
  415. creditsLogEvery = env('TRACKER_CREDITS_LOG_EVERY') != null ? toNumber(env('TRACKER_CREDITS_LOG_EVERY')) : 500
  416. creditsQueueIds = null
  417. creditsPos = 0
  418. creditsDone = false
  419. creditsAt = 0
  420. creditsNextAt = 0
  421. creditsTries = {}
  422. creditsMaxMb = env('TRACKER_CREDITS_MAX_MB') != null ? toNumber(env('TRACKER_CREDITS_MAX_MB')) : 16000
  423. creditsTotals = { titles = 0 done = 0 failed = 0 cast = 0 crew = 0 people = 0 requests = 0 retries = 0 slowest = 0 }
  424. // this process' resident memory in MB (VmRSS), 0 when unknown
  425. rssMb = () => {
  426. if (!exists('/proc/self/status')) { return 0 }
  427. let t = readFile('/proc/self/status')
  428. let i = t != null ? t.indexOf('VmRSS:') : -1
  429. if (i < 0) { return 0 }
  430. let kb = toNumber(t.slice(i + 6, t.indexOf('kB', i)).trim())
  431. return kb != null ? (kb - kb % 1024) / 1024 : 0
  432. }
  433. creditsLine = () => {
  434. let b = creditsTotals
  435. return b.titles + '/' + creditsQueueIds.length + ' titles, done=' + b.done + ' failed=' + b.failed + ' cast=' + b.cast + ' crew=' + b.crew + ' people=' + b.people
  436. + ' requests=' + b.requests + ' retries=' + b.retries + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - creditsAt) / 1000)
  437. }
  438. creditsTick = () => {
  439. if (creditsDone) { return null }
  440. let t = now()
  441. if (creditsQueueIds == null) {
  442. creditsQueueIds = creditsQueue()
  443. creditsAt = t
  444. console.log('credits job: start, ' + creditsQueueIds.length + ' titles without credits (' + (now() - t) + ' ms to find them)')
  445. if (creditsQueueIds.length == 0) { creditsDone = true console.log('credits job: nothing to do') }
  446. return null
  447. }
  448. if (t < creditsNextAt) { return null }
  449. let mb = rssMb()
  450. if (mb > creditsMaxMb) {
  451. creditsDone = true
  452. persistCredits()
  453. console.log('credits job: paused, RSS ' + mb + ' MB > TRACKER_CREDITS_MAX_MB ' + creditsMaxMb + ' — ' + (creditsQueueIds.length - creditsPos) + ' titles left for the next start; ' + creditsLine())
  454. return null
  455. }
  456. let id = creditsQueueIds[creditsPos]
  457. creditsPos = creditsPos + 1
  458. let r = creditsStep(id)
  459. let took = now() - t
  460. if (took > creditsTotals.slowest) { creditsTotals.slowest = took }
  461. if (took > 1500) { console.log('credits job: slow step, show ' + id + ', ' + took + ' ms, cast=' + r.cast + ' crew=' + r.crew + ' people=' + r.people) }
  462. if (r.error != '') { console.log('credits job: ' + r.error) }
  463. creditsNextAt = now() + (creditsFast ? 20 : r.requests * msPerRequest)
  464. if (r.retry && (creditsTries[id] == null || creditsTries[id] < 2)) {
  465. creditsTries[id] = creditsTries[id] == null ? 1 : creditsTries[id] + 1
  466. let q = creditsQueueIds
  467. q.push(id)
  468. creditsQueueIds = q
  469. creditsTotals.retries = creditsTotals.retries + 1
  470. } else if (!r.skipped) {
  471. creditsTotals.titles = creditsTotals.titles + 1
  472. if (r.error != '') { creditsTotals.failed = creditsTotals.failed + 1 } else { creditsTotals.done = creditsTotals.done + 1 }
  473. creditsTotals.cast = creditsTotals.cast + r.cast
  474. creditsTotals.crew = creditsTotals.crew + r.crew
  475. creditsTotals.people = creditsTotals.people + r.people
  476. }
  477. creditsTotals.requests = creditsTotals.requests + r.requests
  478. let finished = creditsPos >= creditsQueueIds.length
  479. if (finished || creditsPos % 25 == 0) { persistCredits() }
  480. if (!finished && !r.skipped && !r.retry && creditsTotals.titles > 0 && creditsTotals.titles % creditsLogEvery == 0) { console.log('credits job: ' + creditsLine()) }
  481. if (finished) {
  482. creditsDone = true
  483. console.log('credits job done: ' + creditsLine())
  484. }
  485. return null
  486. }
  487. // 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
  488. // between, only while no daily run is going on; the details repair only when neither has work; the credits job (#28) last
  489. clockOn = syncOn || backfillOn || repairOn || creditsOn
  490. clockTicks = 0
  491. if (syncOn) { console.log('tmdb sync: daily at ' + syncHour + ':00 UTC') } else { console.log('tmdb sync: off (' + (syncEnabled ? 'TRACKER_SYNC=0' : 'no TMDB_READ_TOKEN') + ')') }
  492. if (!backfillOn) { console.log('adult backfill: off (' + (syncEnabled ? 'TRACKER_BACKFILL=0' : 'no TMDB_READ_TOKEN') + ')') }
  493. if (!repairOn) { console.log('details repair: off (' + (syncEnabled ? 'TRACKER_REPAIR=0' : 'no TMDB_READ_TOKEN') + ')') }
  494. if (!creditsOn) { console.log('credits job: off (' + (syncEnabled ? 'TRACKER_CREDITS=0' : 'no TMDB_READ_TOKEN') + ')') }
  495. if (clockOn) {
  496. syncClock = every(0.1)
  497. on syncClock.tick(x) {
  498. clockTicks = clockTicks + 1
  499. let busy = syncQueue.length > 0
  500. if (syncOn && clockTicks % 10 == 0) { syncTick() }
  501. let free = !busy && syncQueue.length == 0
  502. if (backfillOn && free && !backfillDone) { backfillTick() }
  503. else if (repairOn && free && (!backfillOn || backfillDone) && !repairDone) { repairTick() }
  504. else if (creditsOn && free && (!backfillOn || backfillDone) && (!repairOn || repairDone)) { creditsTick() }
  505. return null
  506. }
  507. }
  508. on Error(e) { console.log('error absorbed: ' + e.message) }

Branches

Latest commits

  • 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
  • b105bcd8tracker#11: Hybriel master ff51cf46 (checks no longer vanish), mobile-first styles, carets, follow button, sign-in modal, inverted check, orange castmre