gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit46b2138946b21389tracker (mission 070, conductor): the sync never destroys migrated data — the one-time summary step MOVES a copied summary to migratedSummary (marker summaries-moved.txt) instead of clearing it; a migrated record's first title/genres/homepage/tagline TMDB replaces → migratedTitle/migratedGenres/migratedHomepage/migratedTagline, a migrated season's/episode's title/summary → migratedTitle/migratedSummary (set once); tests/peek-shows.hl prints them; gate 325/0mre46b21389/project.hl

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

Branches

Latest commits

  • 46b21389tracker (mission 070, conductor): the sync never destroys migrated data — the one-time summary step MOVES a copied summary to migratedSummary (marker summaries-moved.txt) instead of clearing it; a migrated record's first title/genres/homepage/tagline TMDB replaces → migratedTitle/migratedGenres/migratedHomepage/migratedTagline, a migrated season's/episode's title/summary → migratedTitle/migratedSummary (set once); tests/peek-shows.hl prints them; gate 325/0mre
  • 749019b0Merge t19 (tracker#19 franchises + timelines) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs/faketmdb.mjs, both sides kept; franchise/timeline pages get #20's typed heading (Franchise | …, Timeline | …), their title links via titlePath (/movies|/series|/shows); the collection seed waits for repair, kinds and credits too; franchises.mjs URLs + 2 new checks; gates browser 323/0, kinds 32/0, franchises 50/0mre
  • 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
  • 0553b51ftracker#19 (mission 066): franchises and timelines — tables, /franchises, /franchises/<slug>, /timelines/<slug> (Timeline | Release sort, series by last episode), the Prequel | Timeline | Sequel widget with the franchise above, the creator's editor, TMDB collection seed in the app (resumes, paced); gate tests/franchises.mjs 48/0 + browser.mjs 266/0, tests/realdata-066.mjs, docs/franchises.md, 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