gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf2b00674f2b00674Merge t26 (tracker#26 + #28) into main (mission 062): short ids for every new person (castPersonId, guest route), guest stars stored on the title and created as people only when opened (/person/tmdb/<id>?show=<id> → 302), lean watch/follow clicks (showRow a small object, cast/crew from the slug, watches cached per user, face rows only after a season toggle); gate 311, tests/realdata-062.mjs, README + STATUSmref2b00674/project.hl

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

Branches

Latest commits

  • f2b00674Merge t26 (tracker#26 + #28) into main (mission 062): short ids for every new person (castPersonId, guest route), guest stars stored on the title and created as people only when opened (/person/tmdb/<id>?show=<id> → 302), lean watch/follow clicks (showRow a small object, cast/crew from the slug, watches cached per user, face rows only after a season toggle); gate 311, tests/realdata-062.mjs, README + STATUSmre
  • fa1f9dfatracker#29 (mission 063): unwatched check muted grey outline + check (accent only on hover), watched stays solid — no code regression, the accent outline read as ticked; gate checks real checks visibly (computed style + screenshot pixel) on /my/unwatched, show, movie, /my/movies; gate 266, tests/realdata-063.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
  • d8b12d67tracker#27 (mission 060): short ids for movies, series and persons — old 702 kept (data/old-short-ids.json), new random [a-z0-9]{5} unique across both, claimed at creation, background backfill (resumes), shown under poster/photo, /<shortId> → 301; gate 259, tests/realdata-060*, 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
  • f14db671tracker#22-#25 (mission 058): episode air dates, season check = all episodes watched, movie watched check (+ /my/movies count), /genres/<genre> pages (movies + series, newest first, paginated); gate 238, tests/realdata-058.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