gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitdaf49feadaf49feaMerge t20 (tracker#20 typed headings + #21 series/shows split) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/search.hl/components/search.hl/browser.mjs/faketmdb.mjs, both sides kept; clock order backfill → repair → kinds → credits; withDetailsFields stores tmdbType + kind; gates: browser.mjs URLs → /series|/movies, typed h1 selectors; kinds.mjs repair/credits off, fixture name = seed name; browser 323/0, kinds 32/0mredaf49fea/project.hl

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

Branches

Latest commits

  • daf49feaMerge t20 (tracker#20 typed headings + #21 series/shows split) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/search.hl/components/search.hl/browser.mjs/faketmdb.mjs, both sides kept; clock order backfill → repair → kinds → credits; withDetailsFields stores tmdbType + kind; gates: browser.mjs URLs → /series|/movies, typed h1 selectors; kinds.mjs repair/credits off, fixture name = seed name; browser 323/0, kinds 32/0mre
  • 20e09d89Merge t18 (tracker#18 delta sync) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs, both sides kept; pageShowOf summary = summaryOfmre
  • 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
  • 1ed5457etracker#20 + #21 (mission 068): typed headings "<Type> | <name>" in type colours; TV titles split into Series (/series) and Shows (/shows) by TMDB type + Reality/Talk/News genres — kind stored by sync/import/adult backfill + new kind backfill (resumes), /movies/<slug>, /shows/<slug> of a series/movie → 301, /my/series + /my/shows, home 5 tiles + 3 rows, search/filmography labels; gates kinds 32 + browser 266, tests/realdata-068.mjs, tools/count-kinds.hl, docs/kinds.md, README + STATUSmre
  • 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