gitoriaLog in with ident

tracker

All repositories: gitoria

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

29.5 KB

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

Branches

Latest commits

  • 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
  • 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