gitoriaLog in with ident

tracker

All repositories: gitoria

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

27.4 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, exists } from 'hl:fs'
  22. import { now, timestamp, every } from 'hl:time'
  23. import Styles from './styles.hl'
  24. import { exchangeCode, ensureUser } from './users.hl'
  25. import Home from './components/home.hl'
  26. import LoginFailed from './components/loginfailed.hl'
  27. import Show from './components/show.hl'
  28. import Unwatched from './components/unwatched.hl'
  29. import Schedule from './components/schedule.hl'
  30. import MyShows from './components/myshows.hl'
  31. import MyMovies from './components/mymovies.hl'
  32. import Movies from './components/movies.hl'
  33. import AllShows from './components/allshows.hl'
  34. import Search from './components/search.hl'
  35. import Person from './components/person.hl'
  36. import Genre from './components/genre.hl'
  37. import Franchises from './components/franchises.hl'
  38. import Franchise from './components/franchise.hl'
  39. import FranchiseEdit from './components/franchiseedit.hl'
  40. import TimelineEdit from './components/timelineedit.hl'
  41. import { ensureIndex, searchTitleChanged } from './search.hl'
  42. import { syncEnabled, syncShow, persistSync, emptyTotals, addTotals, totalsLine, pauseMsAfter, msPerRequest, adultBackfillQueue, backfillTitle } from './tmdbsync.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 { dark, darker } from './shared/tokens.hl'
  47. import { ensureFranchises, seedPrepare, seedStep, seedLine, seedPersist } from './franchises.hl'
  48. static appTitle = "tracker"
  49. // ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app
  50. // manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service
  51. // worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs
  52. // are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the
  53. // splash background the page's (dark) — both off the tokens, not written out again.
  54. appThemeColor = darker.value
  55. appBackgroundColor = dark.value
  56. appIcons = [
  57. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }
  58. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }
  59. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }
  60. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }
  61. ]
  62. appTouchIcon = '/icons/apple-touch-icon.png'
  63. appFavicon = '/icons/favicon.svg'
  64. // OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no
  65. // network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.
  66. offline = [ Home ]
  67. styles = Styles
  68. port = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008
  69. watching = env('TRACKER_WATCH') != '0'
  70. // read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call below
  71. sessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null
  72. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl
  73. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  74. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  75. nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  76. safePath = (want) => {
  77. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  78. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  79. let i = 0
  80. while (i < want.length) {
  81. if (!nextChars.includes(want[i])) { return '/' }
  82. i = i + 1
  83. }
  84. return want
  85. }
  86. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  87. failed = (req, why) => {
  88. let s = req.session
  89. let fresh = s == null
  90. if (fresh) { s = server.sessions.mint() }
  91. s.data.loginError = why
  92. server.sessions.save(s)
  93. let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  94. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  95. return res
  96. }
  97. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here
  98. loginCallback = (route, req) => {
  99. if (req.method != 'GET') { return failed(req, 'GET only') }
  100. let q = req.query != null ? req.query : {}
  101. let code = q.ident_code
  102. if (code == null || code == '') { return failed(req, 'ident sent no login code') }
  103. let x = exchangeCode(code)
  104. if (x.error != null) { return failed(req, x.error) }
  105. let u = ensureUser(x.identity)
  106. if (u == null) { return failed(req, 'could not store the user') }
  107. let s = req.session
  108. let fresh = s == null
  109. if (fresh) { s = server.sessions.mint() }
  110. s.user = { id = u.id }
  111. s.data.tag = randomBytes(16)
  112. s.data.loginError = null
  113. server.sessions.save(s)
  114. let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  115. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  116. return res
  117. }
  118. // ---- /posters/<name> (tracker.worldapi.org#4): a show's poster image, served dynamically from
  119. // storage/mpackdb/posters/ (the poster's file name is the show's oldId + its migrated extension,
  120. // shows.hl posterName) — falls back to a placeholder svg when the real file isn't there yet (the
  121. // mongo export never included the actual poster bytes, see the report's `open`).
  122. postersDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/posters'
  123. placeholderPoster = './assets/poster-placeholder.svg'
  124. posterNameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'
  125. isSafePosterName = (name) => {
  126. if (name == null || hlTypeName(name) != 'String' || name == '' || name.length > 100) { return false }
  127. let i = 0
  128. while (i < name.length) {
  129. if (!posterNameChars.includes(name[i])) { return false }
  130. i = i + 1
  131. }
  132. return true
  133. }
  134. endsWithStr = (s, suffix) => { return s.length >= suffix.length && s.slice(s.length - suffix.length) == suffix }
  135. mimeOfPoster = (name) => {
  136. if (endsWithStr(name, '.png')) { return 'image/png' }
  137. if (endsWithStr(name, '.webp')) { return 'image/webp' }
  138. if (endsWithStr(name, '.svg')) { return 'image/svg+xml' }
  139. return 'image/jpeg'
  140. }
  141. posterRoute = (route, req) => {
  142. let name = route.params != null ? route.params.name : null
  143. if (!isSafePosterName(name)) { return new Response('bad poster name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  144. let path = postersDir + '/' + name
  145. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  146. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  147. }
  148. // ---- /profiles/<name> (tracker.worldapi.org#16): a person's photo, from storage/mpackdb/profiles/ (people.hl syncProfile
  149. // downloads it on the first visit of the person page) — the same checks and placeholder as /posters/<name>
  150. profilesDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/profiles'
  151. profileRoute = (route, req) => {
  152. let name = route.params != null ? route.params.name : null
  153. if (!isSafePosterName(name)) { return new Response('bad photo name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  154. let path = profilesDir + '/' + name
  155. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  156. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  157. }
  158. // ---- the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now —
  159. // a permanent redirect so old links keep working (architect's decision)
  160. movedTo = (path) => { return new Response('moved to ' + path, { status = 301 headers = { 'Location' = path 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  161. unwatchedMoved = (route, req) => { return movedTo('/my/unwatched') }
  162. scheduleMoved = (route, req) => { return movedTo('/my/schedule') }
  163. // mission 058: the show page's genre pills linked `/genre/<x>` (no page there) — the genre pages are `/genres/<x>`
  164. genreMoved = (route, req) => {
  165. let g = route.params != null ? route.params.genre : null
  166. return movedTo(isSafePosterName(g) ? '/genres/' + g : '/')
  167. }
  168. // mission 060 (tracker.worldapi.org#27): `/<shortId>` → 301 to the title's or person's page (shortids.hl); upper case is
  169. // read as lower case; anything else is a 404
  170. shortIdRoute = (route, req) => {
  171. let sid = route.params != null ? route.params.sid : null
  172. let path = sid != null && hlTypeName(sid) == 'String' ? shortIdPath(sid.toLowerCase()) : null
  173. if (path == null) { return new Response('not found', { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  174. return movedTo(path)
  175. }
  176. routes = [
  177. { pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }
  178. // the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline)
  179. { pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }
  180. { pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }
  181. { pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }
  182. { pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }
  183. { pattern = "/login/callback" function = loginCallback }
  184. { pattern = "/login/failed" component = LoginFailed }
  185. { pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }
  186. { pattern = "/posters/:name" function = posterRoute }
  187. // tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a
  188. // page component cannot read `?page=` (hybriel#11) — and the movies the user follows
  189. { pattern = "/movies" component = Movies }
  190. { pattern = "/movies/page/:page" component = Movies }
  191. { pattern = "/shows" component = AllShows }
  192. { pattern = "/shows/page/:page" component = AllShows }
  193. { pattern = "/shows/:slug" component = Show }
  194. { pattern = "/my/shows" component = MyShows }
  195. { pattern = "/my/movies" component = MyMovies }
  196. { pattern = "/my/unwatched" component = Unwatched }
  197. { pattern = "/my/schedule" component = Schedule }
  198. { pattern = "/unwatched" function = unwatchedMoved }
  199. { pattern = "/schedule" function = scheduleMoved }
  200. // tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`)
  201. { pattern = "/search/:q?" component = Search }
  202. // tracker.worldapi.org#16: a person's page (the show page's cast and the search link here) and their photo
  203. { pattern = "/person/:slug" component = Person }
  204. { pattern = "/profiles/:name" function = profileRoute }
  205. // mission 058 (tracker.worldapi.org#25): a genre's movies and series, like /movies (the page in the path)
  206. { pattern = "/genres/:genre" component = Genre }
  207. { pattern = "/genres/:genre/page/:page" component = Genre }
  208. { pattern = "/genre/:genre" function = genreMoved }
  209. // tracker.worldapi.org#19 (mission 066): franchises and timelines, the creator's editor (`/franchises/edit` before the slug)
  210. { pattern = "/franchises" component = Franchises }
  211. { pattern = "/franchises/edit" component = FranchiseEdit }
  212. { pattern = "/franchises/:slug" component = Franchise }
  213. { pattern = "/timelines/:tslug" component = Franchise }
  214. { pattern = "/timelines/:slug/edit" component = TimelineEdit }
  215. { pattern = "/" component = Home }
  216. // mission 060 (tracker.worldapi.org#27): a short id → its page (LAST: every named one-segment route above wins)
  217. { pattern = "/:sid" function = shortIdRoute }
  218. ]
  219. // WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).
  220. tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }
  221. audience = {
  222. trackerSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }
  223. trackerSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }
  224. }
  225. // cookies are per host, not per port: an own name keeps this app's session apart from
  226. // ident's own (and from any other worldapi app sharing a dev host), see ident README "Design
  227. // tokens" / hybriel#10 hybriel#17.
  228. sessionCookie = 'trackersid'
  229. // 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
  230. // first search
  231. searchIndexReady = ensureIndex()
  232. // mission 060: every short id in use (one map over shows AND persons) and the records still without one, before the first request
  233. shortIdsReady = ensureShortIds()
  234. // mission 066: which timelines every title is in (one scan of the timelines), before the first show page
  235. franchisesReady = ensureFranchises()
  236. server =new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching)
  237. // ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, tmdbsync.hl) --------------------------------------
  238. // Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC) every
  239. // followed show is synced from TMDB. hl:web serves ONE request at a time, so the run never takes the server
  240. // for itself: a 1-second clock does ONE show per tick (1–3 TMDB requests + maybe its poster) and returns — the
  241. // requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.
  242. // After a show that made n requests the next waits n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze lookup
  243. // (≤ 20 / 10 s, tracker.worldapi.org#12).
  244. // TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).
  245. syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4
  246. syncOn = env('TRACKER_SYNC') != '0' && syncEnabled
  247. syncQueue = []
  248. syncAt = 0
  249. syncDay = ''
  250. syncNextAt = 0
  251. syncTotals = emptyTotals()
  252. syncTick = () => {
  253. let t = now()
  254. if (syncQueue.length == 0) {
  255. let stamp = timestamp(t)
  256. let day = stamp.slice(0, 10)
  257. if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }
  258. syncDay = day
  259. syncQueue = allFollowedShowIds()
  260. syncAt = t
  261. syncNextAt = 0
  262. syncTotals = emptyTotals()
  263. console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows')
  264. return null
  265. }
  266. if (t < syncNextAt) { return null }
  267. let id = syncQueue[0]
  268. let rest = []
  269. let i = 1
  270. while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }
  271. syncQueue = rest
  272. let r = syncShow(id)
  273. // the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode; the sync
  274. // also brings TMDB's adult flag (mission 054) → the search's view of it too
  275. refreshCatalogShow(id)
  276. searchTitleChanged(id)
  277. let took = now() - t
  278. syncTotals = addTotals(syncTotals, r)
  279. if (r.error != '') { console.log('tmdb sync: ' + r.error) }
  280. // a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the log
  281. if (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }
  282. syncNextAt = now() + pauseMsAfter(r)
  283. if (syncQueue.length == 0 || syncTotals.shows % 10 == 0) { persistSync() }
  284. if (syncQueue.length == 0) { console.log('tmdb sync done: ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000)) }
  285. return null
  286. }
  287. // ---- THE ADULT-FLAG BACKFILL (mission 054, tmdbsync.hl backfillTitle) -----------------------------------
  288. // The public lists and the search show only titles TMDB says are not adult (shows.hl isPublicTitle; unknown = hidden). At
  289. // start the app collects every title whose flag is still unknown and asks TMDB for ONE title per step — like the daily
  290. // sync, on the same clock, so requests queued meanwhile are served between two steps: one details request (adult,
  291. // poster_path, external ids) + the poster file when missing, then a pause of 260 ms per TMDB API request (≤ 40 / 10 s;
  292. // the poster comes from TMDB's image host, not the API, and is not counted). Each answered title goes into the lists
  293. // (catalog.hl refreshCatalogShow) and the search at once. RESUMES after a restart: the queue is built from what is
  294. // still unknown. Stops when the queue is empty; titles TMDB answers 404 for are marked (`adultCheck`) and stay hidden; a
  295. // passing failure (no answer, 429, 5xx) goes to the back of the queue, at most 2 more tries per start.
  296. // While the daily sync runs, the backfill waits. Log: start, every TRACKER_BACKFILL_LOG_EVERY (500) titles, done.
  297. // TRACKER_BACKFILL=0 switches it off; without TMDB_READ_TOKEN it is off too.
  298. backfillOn = env('TRACKER_BACKFILL') != '0' && syncEnabled
  299. backfillLogEvery = env('TRACKER_BACKFILL_LOG_EVERY') != null ? toNumber(env('TRACKER_BACKFILL_LOG_EVERY')) : 500
  300. backfillQueue = null
  301. backfillPos = 0
  302. backfillDone = false
  303. backfillAt = 0
  304. backfillNextAt = 0
  305. backfillTries = {}
  306. backfillTotals = { titles = 0 adult = 0 notAdult = 0 unknown = 0 posters = 0 ids = 0 requests = 0 errors = 0 retries = 0 }
  307. backfillLine = () => {
  308. let b = backfillTotals
  309. return b.titles + '/' + backfillQueue.length + ' titles, adult=' + b.adult + ' notAdult=' + b.notAdult + ' unknown=' + b.unknown + ' posters=' + b.posters
  310. + ' ids=' + b.ids + ' requests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - backfillAt) / 1000)
  311. }
  312. backfillTick = () => {
  313. if (backfillDone) { return null }
  314. let t = now()
  315. if (backfillQueue == null) {
  316. backfillQueue = adultBackfillQueue()
  317. backfillAt = t
  318. console.log('adult backfill: start, ' + backfillQueue.length + ' titles without an adult flag (' + (now() - t) + ' ms to find them)')
  319. if (backfillQueue.length == 0) { backfillDone = true console.log('adult backfill: nothing to do') }
  320. return null
  321. }
  322. if (t < backfillNextAt) { return null }
  323. let id = backfillQueue[backfillPos]
  324. backfillPos = backfillPos + 1
  325. let r = backfillTitle(id)
  326. if (r.retry && (backfillTries[id] == null || backfillTries[id] < 2)) {
  327. backfillTries[id] = backfillTries[id] == null ? 1 : backfillTries[id] + 1
  328. let q = backfillQueue
  329. q.push(id)
  330. backfillQueue = q
  331. backfillTotals.retries = backfillTotals.retries + 1
  332. } else {
  333. backfillTotals.titles = backfillTotals.titles + 1
  334. 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 }
  335. }
  336. backfillTotals.posters = backfillTotals.posters + r.posters
  337. backfillTotals.ids = backfillTotals.ids + r.ids
  338. backfillTotals.requests = backfillTotals.requests + r.requests
  339. backfillTotals.errors = backfillTotals.errors + r.errors
  340. if (r.error != '') { console.log('adult backfill: ' + r.error) }
  341. if (r.adult != null) {
  342. refreshCatalogShow(id)
  343. searchTitleChanged(id)
  344. }
  345. let took = now() - t
  346. if (took > 1500) { console.log('adult backfill: slow step, show ' + id + ', ' + took + ' ms') }
  347. backfillNextAt = now() + r.requests * msPerRequest
  348. let finished = backfillPos >= backfillQueue.length
  349. if (finished || backfillPos % 25 == 0) { persistSync() }
  350. if (!finished && backfillTotals.titles > 0 && backfillTotals.titles % backfillLogEvery == 0 && !r.retry) { console.log('adult backfill: ' + backfillLine()) }
  351. if (finished) {
  352. backfillDone = true
  353. console.log('adult backfill done: ' + backfillLine())
  354. }
  355. return null
  356. }
  357. // ONE clock for both (a tick every 0.1 s): the daily sync's step once a second as before; the backfill's steps in between,
  358. // only while no daily run is going on
  359. clockOn = syncOn || backfillOn
  360. clockTicks = 0
  361. 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') + ')') }
  362. if (!backfillOn) { console.log('adult backfill: off (' + (syncEnabled ? 'TRACKER_BACKFILL=0' : 'no TMDB_READ_TOKEN') + ')') }
  363. if (clockOn) {
  364. syncClock = every(0.1)
  365. on syncClock.tick(x) {
  366. clockTicks = clockTicks + 1
  367. let busy = syncQueue.length > 0
  368. if (syncOn && clockTicks % 10 == 0) { syncTick() }
  369. if (backfillOn && !busy && syncQueue.length == 0) { backfillTick() }
  370. return null
  371. }
  372. }
  373. // ---- THE SHORT-ID BACKFILL (mission 060, tracker.worldapi.org#27, shortids.hl shortIdStep) ----------------------------
  374. // 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,
  375. // as many records as fit into TRACKER_SHORTID_BUDGET_MS (default 40 ms) — no TMDB, only the tables — so a page waits at
  376. // most one batch. The queue is built at start (`ensureShortIds`) from what is still missing = it resumes after a restart.
  377. // Persisted every 20 batches and at the end. Log: start, every TRACKER_SHORTID_LOG_EVERY (5000) records, done; with nothing
  378. // to do one line. TRACKER_SHORTIDS=0 switches it off (the gate's resume check).
  379. shortIdOn = env('TRACKER_SHORTIDS') != '0'
  380. shortIdBudget = env('TRACKER_SHORTID_BUDGET_MS') != null ? toNumber(env('TRACKER_SHORTID_BUDGET_MS')) : 40
  381. shortIdLogEvery = env('TRACKER_SHORTID_LOG_EVERY') != null ? toNumber(env('TRACKER_SHORTID_LOG_EVERY')) : 5000
  382. shortIdRun = { at = 0 batches = 0 assigned = 0 nextLog = 0 slowest = 0 slowestPersist = 0 done = false }
  383. shortIdTick = () => {
  384. if (shortIdRun.done) { return null }
  385. let t = now()
  386. let r = shortIdStep(shortIdBudget)
  387. let took = now() - t
  388. shortIdRun.batches = shortIdRun.batches + 1
  389. shortIdRun.assigned = shortIdRun.assigned + r.assigned
  390. if (took > shortIdRun.slowest) { shortIdRun.slowest = took }
  391. if (r.done || shortIdRun.batches % 20 == 0) {
  392. let tp = now()
  393. persistShortIds()
  394. if (now() - tp > shortIdRun.slowestPersist) { shortIdRun.slowestPersist = now() - tp }
  395. }
  396. if (!r.done && shortIdRun.assigned >= shortIdRun.nextLog) {
  397. console.log('short ids: ' + shortIdRun.assigned + ' assigned, ' + r.left + ' left, ' + ((now() - shortIdRun.at) / 1000) + ' s')
  398. shortIdRun.nextLog = shortIdRun.nextLog + shortIdLogEvery
  399. }
  400. if (r.done) {
  401. shortIdRun.done = true
  402. let s = shortIdStats()
  403. 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))
  404. }
  405. return null
  406. }
  407. if (!shortIdOn) { console.log('short ids: backfill off (TRACKER_SHORTIDS=0), ' + shortIdsLeft() + ' records without one') }
  408. else if (shortIdsLeft() == 0) { console.log('short ids: nothing to do') }
  409. else {
  410. shortIdRun.at = now()
  411. shortIdRun.nextLog = shortIdLogEvery
  412. console.log('short ids: backfill start, ' + shortIdsLeft() + ' records, ' + shortIdBudget + ' ms per batch')
  413. shortIdClock = every(0.1)
  414. on shortIdClock.tick(x) {
  415. shortIdTick()
  416. return null
  417. }
  418. }
  419. // ---- THE COLLECTION SEED (mission 066, tracker.worldapi.org#19, franchises.hl seedStep) ------------------------------------
  420. // TMDB's movie collections become timelines: ONE movie per step (its details; once per collection the collection's parts), on
  421. // 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
  422. // sync or the adult backfill runs (they share TMDB's limit and the backfill brings the adult flags it skips by). The queue =
  423. // every non-adult movie without a check row, so it RESUMES after a restart and does nothing once all are checked. Persisted
  424. // every TRACKER_COLLECTIONS_PERSIST_EVERY (25) steps and at the end. Log: start, every TRACKER_COLLECTIONS_LOG_EVERY (500) movies, done.
  425. // TRACKER_COLLECTIONS=0 switches it off; without TMDB_READ_TOKEN it is off too.
  426. collectionsOn = env('TRACKER_COLLECTIONS') != '0' && syncEnabled
  427. collectionsLogEvery = env('TRACKER_COLLECTIONS_LOG_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_LOG_EVERY')) : 500
  428. collectionsPersistEvery = env('TRACKER_COLLECTIONS_PERSIST_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_PERSIST_EVERY')) : 25
  429. collectionRun = { at = 0 steps = 0 nextAt = 0 done = false started = false slowest = 0 }
  430. collectionTick = () => {
  431. if (collectionRun.done) { return null }
  432. if (syncQueue.length > 0 || (backfillOn && !backfillDone)) { return null }
  433. let t = now()
  434. if (!collectionRun.started) {
  435. collectionRun.started = true
  436. collectionRun.at = t
  437. let n = seedPrepare()
  438. console.log('collections: start, ' + n + ' movies to check (' + (now() - t) + ' ms to find them)')
  439. if (n == 0) { collectionRun.done = true console.log('collections: nothing to do') }
  440. return null
  441. }
  442. if (t < collectionRun.nextAt) { return null }
  443. let r = seedStep()
  444. if (r.done) {
  445. collectionRun.done = true
  446. seedPersist()
  447. console.log('collections done: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000) + ' slowestStepMs=' + collectionRun.slowest)
  448. return null
  449. }
  450. collectionRun.steps = collectionRun.steps + 1
  451. let took = now() - t
  452. if (took > collectionRun.slowest) { collectionRun.slowest = took }
  453. if (r.error != '') { console.log('collections: ' + r.error) }
  454. if (took > 1500) { console.log('collections: slow step, ' + took + ' ms') }
  455. collectionRun.nextAt = now() + r.requests * msPerRequest
  456. if (collectionRun.steps % collectionsPersistEvery == 0) { seedPersist() }
  457. if (collectionRun.steps % collectionsLogEvery == 0) { console.log('collections: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000)) }
  458. return null
  459. }
  460. if (!collectionsOn) { console.log('collections: off (' + (syncEnabled ? 'TRACKER_COLLECTIONS=0' : 'no TMDB_READ_TOKEN') + ')') }
  461. else {
  462. collectionClock = every(0.1)
  463. on collectionClock.tick(x) {
  464. collectionTick()
  465. return null
  466. }
  467. }
  468. on Error(e) { console.log('error absorbed: ' + e.message) }

Branches

Latest commits

  • 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
  • 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
  • f14db671tracker#22-#25 (mission 058): episode air dates, season check = all episodes watched, movie watched check (+ /my/movies count), /genres/<genre> pages (movies + series, newest first, paginated); gate 238, tests/realdata-058.mjs, README + STATUSmre
  • 1704ec45tracker#17 (mission 057): season caret down/up, skeleton rows while a season loads, sessionless showSeasonEpisodes face (no page re-mount), client-only close; gate 214, tests/realdata-057.mjs, README + STATUSmre
  • f2fe3e36mission 056: README + STATUS (merge, fixes, Hybriel 8590df63, real-data check), tests/realdata-056.mjs, tools/check-public-slugs.hlmre
  • f40c250emission 056: re-vendor hybriel master 8590df63 (#121, #122); an adult title's page is Not found for non-followers; gate: leave the page before stopping the servermre
  • 2b7fdd6cmission 056: signed-out header one row on phones ("Log in", nowrap), backfill skips adult titles' posters, gate checksmre
  • 2c53d5efMerge branch 't16-person' (tracker#16 person pages) into main; filmography shows only public titles (054 adult flag), gate race fix (backfill start line)mre
  • c171227emission 054: hide adult/unknown titles from the public lists and the search; in-app adult-flag backfill (TMDB details + poster per title, resumes), gate + real-data proofmre
  • 139fafd8tracker#16: short bio (4 lines, click = all), real-data check script, README + STATUSmre
  • 93be9476tracker#16: person pages /person/<slug> with the filmography fetched from TMDB on the first visit (step by step), gatemre
  • 47a3cae6STATUS: mission 053 merge commit idsmre
  • dcc5eecaMerge branch 't14-search'mre
  • 03edc783Merge branch 't15-tvmaze'mre
  • 71b46345tracker#15: numbering check by date or title, placeholder titles in other languages, docs + real-data proofmre
  • 6bb2daf1tracker#13: homepage (tiles, intro, latest movies/shows), /shows, /movies/page/N, /my/movies; lists cached in memorymre
  • b8bd1157tracker#14: README + STATUS (search, real-data numbers, gate, merge notes)mre
  • 65c694a8tracker#14: search — header magnifier, /search/<text> (in-memory word-prefix index over titles + people), Fetch from web (TMDB search/multi, ours left out), Add = import via syncShow; gate +25 checks, real-data scriptmre
  • 34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre