gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9edcc2df9edcc2dflog: #58 live, HM57 startedmre9edcc2df/lib/shows.hl

32.7 KB

  1. // lib/shows.hl — READ-ONLY data access for a show's page (tracker.worldapi.org#4): shows, seasons,
  2. // episodes, persons, genres (storage/mpackdb/, migrated by tools/migrate.hl, tracker.worldapi.org#2).
  3. // Kept apart from watches.hl (the per-user watch state) and from components/show.hl (the page itself)
  4. // so /unwatched and /schedule (tickets #5/#6, "reuse, don't copy") can import the same functions.
  5. //
  6. // Person slug/TMDB indexes are native; title slug maps remain in this module.
  7. import { MPackDB } from 'hl:mpackdb'
  8. import { warm } from './warm.hl'
  9. import { exists } from 'hl:fs'
  10. import { storageDir, postersDir, hasId, dayStr, textOr, envOr } from './util.hl'
  11. static genresTable = new MPackDB(file = storageDir + '/genres.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  12. // tracker#62: first open builds missing indexes from data; compact stays false.
  13. static personsTable = new MPackDB(file = storageDir + '/persons.db', primaryKey = '@id', indexes = ['!oldId', 'urlSegment', 'tmdbId'], compact = false)
  14. static showsTable = new MPackDB(file = storageDir + '/shows.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  15. static seasonsTable = new MPackDB(file = storageDir + '/seasons.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  16. static episodesTable = new MPackDB(file = storageDir + '/episodes.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  17. // the show with this urlSegment (slug), or null. tracker#28: by a slug → id map (one scan, at the first call) — the old scan of
  18. // every record per call (twice per show page) decoded every title's cast + crew: 82 ms per call on the live copy before the
  19. // credits, growing with them. tracker#42 (mission 038): a slug the map does not know is NOT a title — no scan any more (an unknown
  20. // slug, a bot's or a typo, cost one scan of every title per lookup and the page does 4: ~9 s on the live copy, the one-request-at-a-
  21. // time server blocked). A title added since the build (search import, filmography fill — the only two puts) is in the map through
  22. // catalog.hl refreshCatalogShow → refreshTitleCaches → noteSlugsOf, which both call right after the put; merge.hl notes its own.
  23. // (Flat static written key by key, like people.hl's maps.)
  24. // tracker#31 (mission 026): a MERGED title's slug (a tombstone's, below) and a keeper's former slug (`oldSlugs`) answer the
  25. // KEEPER — several records can share one slug (migrated duplicates did), so each slug has a rank: a live record's own slug (3)
  26. // beats a live record's former one (2) beats a tombstone's (1).
  27. static slugIds = {}
  28. static slugRank = {}
  29. static slugIdsBuilt = { yes = false }
  30. // ---- merged titles (tracker#31, mission 026, merge.hl) ----------------------------------------------------------------------
  31. // The old tracker left 68 titles as 2–6 records each (same type + TMDB id). The repair (merge.hl) keeps ONE record (the keeper)
  32. // and turns the others into TOMBSTONES — never deleted: `mergedInto` = the keeper's id, `mergedTmdbId` (their `tmdbId` is
  33. // null, so nothing looks them up by it), `mergedSeasons` (their `seasons` are empty). Every list skips them (isPublicTitle),
  34. // every job skips them, a tombstone's slug and short id lead to the keeper.
  35. static isMerged = (&show) => { return show != null && show.mergedInto != null }
  36. // the record a page shows for this one: the keeper of a tombstone (a chain is followed, at most 5 steps), else itself
  37. static liveShowOf = (&show) => {
  38. let s = show
  39. let n = 0
  40. while (s != null && s.mergedInto != null && n < 5) {
  41. s = showsTable.fetch(s.mergedInto)
  42. n = n + 1
  43. }
  44. return s
  45. }
  46. static holdsSlug = (&s, &slug) => { return s.urlSegment == slug || (s.oldSlugs != null && s.oldSlugs.includes(slug)) }
  47. // this record's slugs into the map (at the build, and by merge.hl after a merge changed a record)
  48. static noteSlugsOf = (&s) => {
  49. live = s.mergedInto == null
  50. mine = []
  51. if (s.urlSegment != null) { mine.push({ slug = s.urlSegment rank = live ? 3 : 1 }) }
  52. if (live && s.oldSlugs != null) { for (o of s.oldSlugs) { mine.push({ slug = o rank = 2 }) } }
  53. for (m of mine) {
  54. let cur = slugRank[m.slug]
  55. if (cur == null || m.rank >= cur || slugIds[m.slug] == s.id) {
  56. slugIds[m.slug] = s.id
  57. slugRank[m.slug] = m.rank
  58. }
  59. }
  60. return null
  61. }
  62. // bootscan.hl streamed every title through noteSlugsOf
  63. static markSlugIdsBuilt = () => {
  64. slugIdsBuilt.yes = true
  65. return true
  66. }
  67. static ensureSlugIds = () => {
  68. // mission T17: during the progressive start the map is being filled (bootscan.hl) — no blocking full scan here
  69. if (!slugIdsBuilt.yes && !warm.running) {
  70. // mission 043: streamed (one title decoded at a time); at boot bootscan.hl fills the map in its own pass over the titles
  71. for (s of showsTable.iterate(null, null)) { noteSlugsOf(&s) }
  72. slugIdsBuilt.yes = true
  73. }
  74. return true
  75. }
  76. static showBySlug = (&slug) => {
  77. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  78. ensureSlugIds()
  79. id = slugIds[slug]
  80. if (id != null) {
  81. hit = showsTable.fetch(id)
  82. if (hit != null && holdsSlug(&hit, &slug)) { return liveShowOf(&hit) }
  83. }
  84. return null
  85. }
  86. // tracker#31/#41 (missions 026, 037b): a slug that is not a live title's own any more (a tombstone's, a keeper's former one) → the
  87. // keeper's path, or null (a live title's own slug, an unknown one). Only the slug map (built at boot, kept current by merge.hl
  88. // noteSlugsOf), never a scan. No route per such slug (hl:web writes every route into each page's HTML; the moved slugs there
  89. // included adult titles'): /movies/<slug> and /series/<slug> render the keeper's page (showBySlug), its head names this path.
  90. static movedSlugPath = (&slug) => {
  91. ensureSlugIds()
  92. rank = slugRank[slug]
  93. if (rank == null || rank >= 3) { return null }
  94. keeper = liveShowOf(showsTable.fetch(slugIds[slug]))
  95. if (keeper == null || keeper.mergedInto != null || keeper.urlSegment == null || keeper.urlSegment == slug) { return null }
  96. return titlePath(&keeper)
  97. }
  98. // how many slugs lead to a keeper now (project.hl's boot log line)
  99. static movedSlugCount = () => {
  100. ensureSlugIds()
  101. let n = 0
  102. for (slug of slugRank.keys()) { if (slugRank[slug] < 3 && movedSlugPath(&slug) != null) { n = n + 1 } }
  103. return n
  104. }
  105. static genreById = (&id) => { return id == null ? null : genresTable.fetch(id) }
  106. // /genres/<genre> (mission 058): the genre with this urlSegment ('Action', 'Sci-Fi-Fantasy'), exact first, else ignoring case
  107. // — a scan of the genres table (27 rows)
  108. static genreBySlug = (&slug) => {
  109. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  110. lower = slug.toLowerCase()
  111. let loose = null
  112. for (g of genresTable.find(null, null)) {
  113. if (g.urlSegment == slug) { return g }
  114. if (loose == null && g.urlSegment != null && ('' + g.urlSegment).toLowerCase() == lower) { loose = g }
  115. }
  116. return loose
  117. }
  118. static personById = (&id) => { return id == null ? null : personsTable.fetch(id) }
  119. // GC1: the five request caches (personLinkCache, cardCache, episodeRowsCache, episodeKeyCache, creditRowCache) only ever grew: every title
  120. // a bot or a visitor opened, every person it linked, stayed in the heap for good and every collection marked it again. Each now holds
  121. // at most `cacheLimit` entries; the one that is full is emptied before it takes the next (an entry is a plain recomputation of the
  122. // stored record, so a dropped one is read again at its next ask and the page is the same). The limits sit far above what the warm
  123. // set needs (the followed titles and their watched episodes, warmed at boot). TRACKER_CACHE_MAX sets all five (a test).
  124. static cacheMax = toNumber(envOr('TRACKER_CACHE_MAX', '0'))
  125. static cacheLimit = { card = cacheMax > 0 ? cacheMax : 20000 episodeRows = cacheMax > 0 ? cacheMax : 2000 episodeKey = cacheMax > 0 ? cacheMax : 60000 creditRow = cacheMax > 0 ? cacheMax : 20000 personLink = cacheMax > 0 ? cacheMax : 50000 }
  126. static cacheCount = { card = 0 episodeRows = 0 episodeKey = 0 creditRow = 0 personLink = 0 }
  127. // tracker#42 (mission 038): what a cast / crew row needs of a person — { name, urlSegment } — cached per person: a series page linked
  128. // up to 300 cast + crew people by fetching each WHOLE record (their `shows` credits: Saturday Night Live's 303 cast carry 4,761) —
  129. // ~49k allocations and 11 ms per render, a third of the page's allocations (every ~3M allocations the GC stops the server for
  130. // ~0.8 s on the live copy's heap). A person's name and slug never change once stored (people.hl creates them; the fill, photos and
  131. // merge.hl only add data), so the cache is never stale. null = no such person (not remembered: a guest's person can come later).
  132. static personLinkCache = {}
  133. static personLinkOf = (&personId) => {
  134. if (personId == null) { return null }
  135. if (personLinkCache[personId] != null) { return personLinkCache[personId] }
  136. linkPerson = personsTable.fetch(personId)
  137. if (linkPerson == null) { return null }
  138. if (cacheCount.personLink >= cacheLimit.personLink) {
  139. for (k of personLinkCache.keys()) { delete personLinkCache[k] }
  140. cacheCount.personLink = 0
  141. }
  142. personLinkCache[personId] = { name = linkPerson.name urlSegment = linkPerson.urlSegment }
  143. cacheCount.personLink = cacheCount.personLink + 1
  144. return personLinkCache[personId]
  145. }
  146. static seasonById = (&id) => { return id == null ? null : seasonsTable.fetch(id) }
  147. static showById = (&id) => { return id == null ? null : showsTable.fetch(id) }
  148. static episodeById = (&id) => { return id == null ? null : episodesTable.fetch(id) }
  149. // EVERY show / episode as one array — for the tools in tools/ only (the app streams: bootscan.hl, mission 043)
  150. static allShows = () => { return showsTable.find(null, null) }
  151. static allEpisodes = () => { return episodesTable.find(null, null) }
  152. // insertion sort, hand-written (no list sort(), hybriel#1) — a show has a handful of seasons at most
  153. static insertDesc = (&sorted, &s) => {
  154. out = []
  155. let inserted = false
  156. for (x of sorted) {
  157. if (!inserted && s.seasonNumber >= x.seasonNumber) { out.push(s) inserted = true }
  158. out.push(x)
  159. }
  160. if (!inserted) { out.push(s) }
  161. return out
  162. }
  163. static insertAsc = (&sorted, &e) => {
  164. out = []
  165. let inserted = false
  166. for (x of sorted) {
  167. if (!inserted && e.episodeNumber <= x.episodeNumber) { out.push(e) inserted = true }
  168. out.push(x)
  169. }
  170. if (!inserted) { out.push(e) }
  171. return out
  172. }
  173. // a show's seasons, latest (highest seasonNumber) first — creator: "all seasons in reverse order,
  174. // latest on top"
  175. static seasonsOfShow = (&show) => {
  176. let sorted = []
  177. for (id of show.seasons) {
  178. let s = seasonsTable.fetch(id)
  179. if (s != null) { sorted = insertDesc(&sorted, &s) }
  180. }
  181. return sorted
  182. }
  183. // a season's episodes, in episode-number order
  184. static episodesOfSeason = (&season) => {
  185. let sorted = []
  186. for (id of season.episodes) {
  187. let e = episodesTable.fetch(id)
  188. if (e != null) { sorted = insertAsc(&sorted, &e) }
  189. }
  190. return sorted
  191. }
  192. // ---- labels shared by every list (tracker.worldapi.org#8) -------------------------------------
  193. static pad2 = (&n) => {
  194. let s = '' + n
  195. while (s.length < 2) { s = '0' + s }
  196. return s
  197. }
  198. // an episode as `S01E01` (creator: "write it like that: S01E01") — /my/shows, /my/unwatched, /my/schedule
  199. static episodeCode = (&seasonNumber, &episodeNumber) => { return 'S' + pad2(&seasonNumber) + 'E' + pad2(&episodeNumber) }
  200. // the show's year: `year`, else the first 4 characters of `release` ('YYYY-MM-DD'; 197 migrated shows have
  201. // no year, a few of those an empty release) — null when neither gives one
  202. static showYear = (&show) => {
  203. if (show.year != null) { return '' + show.year }
  204. if (show.release != null && hlTypeName(show.release) == 'String' && show.release.length >= 4) { return show.release.slice(0, 4) }
  205. return null
  206. }
  207. // a show's title as every list shows it: `Doctor Who (2005)` (creator: so same-named shows can be told apart)
  208. static titleWithYear = (&show) => {
  209. y = showYear(&show)
  210. return y != null ? show.title + ' (' + y + ')' : show.title
  211. }
  212. // ---- the description (tracker#18) ---------------------------------------------------------------
  213. // creator: "i put the summary in an own field for tmdb because some summaries i wanted to rewrite ... in that case the summary
  214. // has priority over maze or tmdb" — `summary` (the creator's own text, never written by the sync), else TMDB's `tmdbSummary`,
  215. // else TVmaze's `tvmazeSummary` (HTML stripped); '' when none
  216. static hasText = (&v) => { return v != null && hlTypeName(v) == 'String' && v.trim() != '' }
  217. static summaryOf = (&show) => {
  218. if (show == null) { return '' }
  219. if (hasText(&show.summary)) { return show.summary }
  220. if (hasText(&show.tmdbSummary)) { return show.tmdbSummary }
  221. if (hasText(&show.tvmazeSummary)) { return show.tvmazeSummary }
  222. return ''
  223. }
  224. // ---- a series' status (tracker#35, mission 030) -----------------------------------------------------------------------
  225. // The page's status pill (components/show.hl) next to a series' or show's title: TVmaze's `tvmazeStatus` (Running, Ended, To Be
  226. // Determined, In Development — stored by the sync and backfill.hl's status backfill) when there is one — creator: "this was also
  227. // something tvmaze was better updated about" — else TMDB's `status` (Returning Series, In Production, Planned, Pilot, Ended,
  228. // Canceled). TVmaze has no "canceled": its Ended + TMDB's Canceled shows Canceled (the same state, TMDB's word says more).
  229. // tracker#35 follow-up (mission 033): TVmaze's "Running" reads stale to the creator (Twisted Metal between seasons) — its LABEL
  230. // is "Returning", or "Airing" while an episode of the series aired in the last 7 days or airs in the next 7 (the stored episodes'
  231. // `release`, `isAiring`). Only the label: the stored tvmazeStatus stays "Running"; every other word (Ended, Canceled, To Be
  232. // Determined, TMDB's) is shown as before.
  233. // { text, tone } — tone running | pending | ended | canceled | other (the pill's colour, styles.hl); text '' = no pill (a movie,
  234. // or no status known).
  235. static statusTones = { 'Running' = 'running' 'Returning Series' = 'running' 'To Be Determined' = 'pending' 'In Development' = 'pending'
  236. 'In Production' = 'pending' 'Planned' = 'pending' 'Pilot' = 'pending' 'Ended' = 'ended' 'Canceled' = 'canceled' }
  237. static statusOf = (&show) => {
  238. if (show == null || show.type == 'movie') { return { text = '' tone = '' } }
  239. let word = hasText(&show.tvmazeStatus) ? show.tvmazeStatus : (hasText(&show.status) ? show.status : '')
  240. if (word == 'Ended' && show.status == 'Canceled') { word = 'Canceled' }
  241. if (word == '') { return { text = '' tone = '' } }
  242. tone = statusTones[word]
  243. let text = word == 'Returning Series' ? 'Returning' : word
  244. if (word == 'Running') { text = isAiring(&show) ? 'Airing' : 'Returning' }
  245. return { text = text tone = tone != null ? tone : 'other' }
  246. }
  247. // an episode released today-7 … today+7 (UTC days, both ends included); only the two newest numbered seasons are looked at (an
  248. // airing episode is in one of them — The Simpsons has 36 seasons). Specials (season 0; the sync keeps them only for a show that
  249. // already has one) do not count: Family Guy's special of 2026-10-05 between S24 and S25 is no "Airing".
  250. static isAiring = (&show) => {
  251. firstDay = dayStr(-7)
  252. lastDay = dayStr(7)
  253. seasons = []
  254. for (se of seasonsOfShow(&show)) { if (se.seasonNumber != 0 && seasons.length < 2) { seasons.push(se) } }
  255. let k = 0
  256. while (k < seasons.length) {
  257. for (id of seasons[k].episodes) {
  258. let e = episodesTable.fetch(id)
  259. if (e != null && hasText(&e.release)) {
  260. let d = e.release.slice(0, 10)
  261. if (d >= firstDay && d <= lastDay) { return true }
  262. }
  263. }
  264. k = k + 1
  265. }
  266. return false
  267. }
  268. // ---- adult titles (mission 054) -----------------------------------------------------------------
  269. // `adult` on every title: true / false from TMDB, null = not known yet (the migrated rows; the app's backfill, backfill.hl
  270. // `backfillTitle`, asks TMDB). The PUBLIC lists (catalog.hl: homepage rows, /movies, /shows) and the search (search.hl) show
  271. // ONLY a title TMDB says is not adult — unknown counts as hidden. A title the user follows stays on /my/* and its page.
  272. // A merged tombstone (tracker#31) is never public.
  273. static isPublicTitle = (&show) => { return show != null && show.adult == false && show.mergedInto == null }
  274. // ---- incomplete titles (tracker.worldapi.org#26; details.hl completes them, credits.hl and dailysync.hl skip them) ------------
  275. // COMPLETE = TMDB's details answer went through this app once: completed (`detailsAt`, details.hl) or synced (`tmdbSync`, the
  276. // last step of sync.hl's sync — the daily run, a search import) — or given up on (`detailsCheck`: TMDB 404 / adult).
  277. // INCOMPLETE = every other title with a TMDB id: a filmography title (`minimal`, #26) until it is completed, an import whose
  278. // sync never finished, and (tracker#33, mission 029) the old tracker's MIGRATED rows that were never synced — #26 only looked
  279. // at `minimal`/`imported`, so they passed: live copy 2026-10-03, 5,697 non-adult titles (4,206 movies, 1,491 series), 691
  280. // series without a single season, 209 + 84 without a poster, 389 + 120 without genres (tools/count-incomplete.hl). Also a
  281. // movie with a TV answer's leftovers (below). What a title still lacks that a page shows: `missingParts`.
  282. static isIncomplete = (&s) => {
  283. return s != null && s.tmdbId != null && s.detailsCheck == null
  284. && ((s.detailsAt == null && (s.minimal == true || s.tmdbSync == null)) || hasTvLeftovers(&s))
  285. }
  286. // tracker#33: what a title's page would miss — the parts a complete record has when TMDB has them: 'poster', 'summary',
  287. // 'genres', 'cast', 'ids' (no IMDb id), 'release', 'seasons' (a series without any). The repair does these titles first
  288. // (details.hl detailsRepairQueue); tools/count-incomplete.hl counts them. A complete title can still miss one — TMDB has none
  289. // (The Remaining, a 7-minute Finnish short: no poster, no IMDb id on TMDB).
  290. static missingParts = (&s) => {
  291. out = []
  292. if (s.image == null || s.image == '') { out.push('poster') }
  293. if (summaryOf(&s) == '') { out.push('summary') }
  294. if (s.genres == null || s.genres.length == 0) { out.push('genres') }
  295. if (s.cast == null || s.cast.length == 0) { out.push('cast') }
  296. if (s.imdbId == null) { out.push('ids') }
  297. if (s.release == null || s.release == '') { out.push('release') }
  298. if (s.type != 'movie' && (s.seasons == null || s.seasons.length == 0)) { out.push('seasons') }
  299. return out
  300. }
  301. // mission 025 (report 021's "wrong TMDB id"): the #9 sync once asked TMDB for every followed title as `/tv/<tmdbId>` — a movie's
  302. // id is ANOTHER title there (fixed in mission 006: movies go to /movie/) and the TV title's overview, status and season/episode
  303. // counts were stored on the movie. On the real data only Star Trek: First Contact: its tmdbId 199 IS the movie (/movie/199),
  304. // tmdbSummary was TV 199's ("Kabuhayang Swak na Swak …"), status 'Ended', seasonsCount/episodesCount 0. The movie path never
  305. // writes the counts, so a movie that has them is such a record: the repair asks /movie/<id> again (withDetailsFields: overview →
  306. // tmdbSummary, status, …) and firstStep drops the counts — repaired once, then it no longer matches.
  307. static hasTvLeftovers = (&s) => { return s.type == 'movie' && (s.seasonsCount != null || s.episodesCount != null) }
  308. // ---- the kind of a title (tracker.worldapi.org#21, mission 068; #43, mission 037) ------------------------------------------
  309. // A TV title (`type = 'series'`) is either a SERIES (TMDB's TV type Scripted, Miniseries, Documentary) or a SHOW (Reality,
  310. // Talk Show, News, Video — or one of our genres Reality / Talk / News, whatever the type — or, #43, TVmaze's type Variety, Talk
  311. // Show, Reality, Game Show, News, Panel Show, Award Show, Sports: TMDB calls Saturday Night Live UK "Scripted", TVmaze
  312. // "Variety"; TVmaze's type is stored as `tvmazeType` by the sync and the TVmaze status backfill). Stored on the title as `kind`
  313. // ('series' | 'show') and TMDB's type as `tmdbType`: by the kind backfill (backfill.hl `kindTitle`, one TMDB request per
  314. // title without a show genre), the daily sync and the search import. Until a title has `kind`, its genres decide (no
  315. // type known yet = series). Movies are `type = 'movie'` and have no kind.
  316. static showTmdbTypes = ['Reality', 'Talk Show', 'News', 'Video']
  317. static showGenreNames = ['Reality', 'Talk', 'News']
  318. // #43 (mission 037): TVmaze's show types that are SHOWS ("all that game show and reality and talkshow stuff", #21); its others —
  319. // Scripted, Animation, Documentary — are series. '' = TVmaze was asked and gave none
  320. static showTvmazeTypes = ['Variety', 'Talk Show', 'Reality', 'Game Show', 'News', 'Panel Show', 'Award Show', 'Sports']
  321. static showGenreIdsOf = () => {
  322. out = {}
  323. for (g of genresTable.find(null, null)) { if (g.name != null && showGenreNames.includes('' + g.name)) { out[g.id] = true } }
  324. return out
  325. }
  326. // the genre ids that make a title a show — read once (the genres table never changes while the app runs)
  327. static showGenreIds = showGenreIdsOf()
  328. static hasShowGenre = (&genres) => {
  329. if (genres == null) { return false }
  330. for (g of genres) { if (showGenreIds[g] == true) { return true } }
  331. return false
  332. }
  333. // 'show' | 'series' from TMDB's type, the title's genre ids and TVmaze's type (#43; null = not known)
  334. static kindOfTitle = (&tmdbType, &genres, &tvmazeType) => {
  335. if (hasShowGenre(&genres)) { return 'show' }
  336. if (tmdbType != null && showTmdbTypes.includes('' + tmdbType)) { return 'show' }
  337. if (tvmazeType != null && showTvmazeTypes.includes('' + tvmazeType)) { return 'show' }
  338. return 'series'
  339. }
  340. // #43: the kind to STORE after TVmaze's type came in — the rule once TMDB's or TVmaze's type is known, else the stored one (null:
  341. // the genres decide until the kind backfill asks TMDB, which it does only for a title without a stored kind)
  342. static kindWithTvmaze = (&show) => {
  343. known = (show.tmdbType != null && '' + show.tmdbType != '') || (show.tvmazeType != null && showTvmazeTypes.includes('' + show.tvmazeType))
  344. return known ? kindOfTitle(&show.tmdbType, &show.genres, &show.tvmazeType) : show.kind
  345. }
  346. // 'movie' | 'series' | 'show' of a stored title
  347. static titleKind = (&show) => {
  348. if (show.type == 'movie') { return 'movie' }
  349. if (show.kind == 'show' || show.kind == 'series') { return show.kind }
  350. return kindOfTitle(&show.tmdbType, &show.genres, &show.tvmazeType)
  351. }
  352. // a title's own page: /movies/<slug>, /series/<slug>, /shows/<slug> (the old /shows/<slug> of a movie or series answers 301,
  353. // project.hl showsRoute)
  354. static titlePath = (&show) => {
  355. k = titleKind(&show)
  356. return (k == 'movie' ? '/movies/' : (k == 'show' ? '/shows/' : '/series/')) + show.urlSegment
  357. }
  358. // `/shows/<slug>` (#21, mission 068; project.hl showsRoute): since the split only the game / reality / talk / news SHOWS live
  359. // there — the page a series or a movie answers with a 301 instead (its own page), as does a merged duplicate's slug or a
  360. // keeper's former one (tracker#31: the keeper's page); null = render the title page here (a show, or an unknown slug)
  361. static showsMovedPath = (&slug) => {
  362. show = showBySlug(&slug)
  363. return show != null && (titleKind(&show) != 'show' || show.urlSegment != slug) ? titlePath(&show) : null
  364. }
  365. // tracker.worldapi.org#20: the type word of a page heading / list label and its colour class (styles.hl `type-*`)
  366. static kindWord = (&kind) => { return kind == 'movie' ? 'Movie' : (kind == 'show' ? 'Show' : 'Series') }
  367. static typeWordOf = (&show) => { return kindWord(titleKind(&show)) }
  368. // the theme's pill classes of a kind (layouts "Type colours and pills": Movie = type-1, Series = type-2, Show = type-3) — the kind label of a list row
  369. static pillClassOfWord = (&word) => { return word == 'Movie' ? 'pill type-1' : (word == 'Show' ? 'pill type-3' : 'pill type-2') }
  370. static typeClassOf = (&show) => { return pillClassOfWord(typeWordOf(&show)) }
  371. // the poster file name (oldId + the migrated extension) — null when either is missing; served at
  372. // /posters/<name> (images.hl), which falls back to a placeholder when the file itself isn't there
  373. // yet (the real poster files are not part of the mongo export, see the report's `open`)
  374. static posterName = (&show) => {
  375. if (show.oldId == null || show.image == null || show.image == '') { return null }
  376. return show.oldId + '.' + show.image
  377. }
  378. // the poster's URL for a LIST (/my/shows, tracker.worldapi.org#8): `/posters/<name>` only when the file really
  379. // is in storage/mpackdb/posters/ (images.hl serves the same folder), else the ONE placeholder URL
  380. // `/posters/none` — the real data has no poster files yet, and 128 different URLs all answering the same
  381. // placeholder were 128 requests per page load (the browser can't cache them as one)
  382. static posterUrlOf = (&show) => { return posterUrlOfName(posterName(&show)) }
  383. static posterUrlOfName = (&name) => { return name != null && exists(postersDir + '/' + name) ? '/posters/' + name : '/posters/none' }
  384. // ---- slim per-title caches for the lists (tracker.worldapi.org#30, mission 025) ------------------------------------
  385. // /my/series took 4.4 s on a process that had run the first-start jobs (0.4 s fresh): every load fetched each followed title's
  386. // WHOLE record (cast + crew, up to 300 entries) and one episode per watch (11.7k fetches); /my/unwatched every season and
  387. // episode of every followed title. Each fetch decodes a new object, and with a big live heap (after the jobs) every byte
  388. // allocated feeds the byte-triggered GC. Now a list reads two small cached things per title:
  389. // - `cardOf(id)`: { id type kind title year titleYear href posterName } — what a row shows;
  390. // - `episodeRowsOf(id)`: every episode of the title as { id s e title release }, seasons latest first, episodes in order
  391. // (the same order as seasonsOfShow/episodesOfSeason);
  392. // - `episodeKeyOf(id)`: one episode as { show s e } — /my/series' last watched episode goes by the WATCHED episode's own
  393. // `show` (as before): migrated episodes the sync left outside the title's seasons (a duplicate season, e.g. Reacher S03 on
  394. // the real data) still count. project.hl warms every watched episode at boot.
  395. // Filled at the first ask (project.hl warms the followed titles at boot) and kept in sync by catalog.hl `refreshCatalogShow`,
  396. // which every writer of a title already calls after it changed one (daily sync, repair, kinds, adult backfill, imports):
  397. // it calls `refreshTitleCaches(show)`, which rebuilds the entries that exist. Cached values are only ever RETURNED from a
  398. // function (a `let x = map[k]` deep-copies the value; a return does not — measured: 3.7 ms per 20k-row copy).
  399. static cardCache = {}
  400. static episodeRowsCache = {}
  401. static episodeKeyCache = {}
  402. static cardFrom = (&show) => {
  403. y = showYear(&show)
  404. return {
  405. id = show.id type = show.type kind = titleKind(&show) title = show.title year = y != null ? y : ''
  406. titleYear = titleWithYear(&show) href = titlePath(&show) posterName = posterName(&show)
  407. }
  408. }
  409. // tracker#46 (mission 046): what the PERSON page needs of a title, per title id — { id mergedInto public title year release href
  410. // posterName typeLabel typeClass }. The person page used to fetch every credit's WHOLE title record (cast + crew, up to 300
  411. // entries each: 311 decoded records for Tom Hanks) on every request — the allocation fed the byte-triggered GC (a 6 s+ pause
  412. // on the live heap). Filled at the first ask, rebuilt by `refreshTitleCaches` (every writer of a title calls it); returned, never copied.
  413. static creditRowCache = {}
  414. static creditRowFrom = (&show) => {
  415. y = showYear(&show)
  416. return { id = show.id mergedInto = show.mergedInto public = isPublicTitle(&show) title = show.title year = y != null ? y : ''
  417. release = textOr(&show.release) href = titlePath(&show) posterName = posterName(&show) typeLabel = typeWordOf(&show) typeClass = typeClassOf(&show) }
  418. }
  419. static creditRowOf = (&id) => {
  420. if (id == null) { return null }
  421. if (creditRowCache[id] != null) { return creditRowCache[id] }
  422. show = showsTable.fetch(id)
  423. if (show == null) { return null }
  424. if (cacheCount.creditRow >= cacheLimit.creditRow) {
  425. for (k of creditRowCache.keys()) { delete creditRowCache[k] }
  426. cacheCount.creditRow = 0
  427. }
  428. creditRowCache[id] = creditRowFrom(&show)
  429. cacheCount.creditRow = cacheCount.creditRow + 1
  430. return creditRowCache[id]
  431. }
  432. // the row of the title a page shows for this id: the keeper of a merged tombstone (chain followed, at most 5 steps, like liveShowOf)
  433. static creditRowLive = (&id) => {
  434. let r = creditRowOf(&id)
  435. let n = 0
  436. while (r != null && r.mergedInto != null && n < 5) {
  437. r = creditRowOf(&r.mergedInto)
  438. n = n + 1
  439. }
  440. return r
  441. }
  442. // GC1 measurement (TRACKER_QSTATS=1, jobs.hl): how many entries the request caches hold
  443. static cacheSizes = () => {
  444. return { card = cardCache.keys().length episodeRows = episodeRowsCache.keys().length episodeKey = episodeKeyCache.keys().length creditRow = creditRowCache.keys().length personLink = personLinkCache.keys().length }
  445. }
  446. static cardOf = (&id) => {
  447. if (id == null) { return null }
  448. if (cardCache[id] != null) { return cardCache[id] }
  449. show = showsTable.fetch(id)
  450. if (show == null) { return null }
  451. if (cacheCount.card >= cacheLimit.card) {
  452. for (k of cardCache.keys()) { delete cardCache[k] }
  453. cacheCount.card = 0
  454. }
  455. cardCache[id] = cardFrom(&show)
  456. cacheCount.card = cacheCount.card + 1
  457. return cardCache[id]
  458. }
  459. static episodeRowsFrom = (&show) => {
  460. out = []
  461. if (show.seasons == null) { return out }
  462. // loop names apart from the row's own `s`/`e` keys: inside an object literal a key set earlier shadows the variable
  463. for (sn of seasonsOfShow(&show)) {
  464. for (ep of episodesOfSeason(&sn)) {
  465. out.push({ id = ep.id s = ep.seasonNumber e = ep.episodeNumber title = ep.title != null ? ep.title : '' release = ep.release })
  466. }
  467. }
  468. return out
  469. }
  470. static episodeRowsOf = (&id) => {
  471. if (id == null) { return [] }
  472. if (episodeRowsCache[id] != null) { return episodeRowsCache[id] }
  473. show = showsTable.fetch(id)
  474. if (show == null) { return [] }
  475. if (cacheCount.episodeRows >= cacheLimit.episodeRows) {
  476. for (k of episodeRowsCache.keys()) { delete episodeRowsCache[k] }
  477. cacheCount.episodeRows = 0
  478. }
  479. episodeRowsCache[id] = episodeRowsFrom(&show)
  480. cacheCount.episodeRows = cacheCount.episodeRows + 1
  481. return episodeRowsCache[id]
  482. }
  483. // an episode that is not stored is { show = null } (never fetched again)
  484. static episodeKeyOf = (&id) => {
  485. if (id == null) { return { show = null s = null e = null } }
  486. if (episodeKeyCache[id] != null) { return episodeKeyCache[id] }
  487. ep = episodesTable.fetch(id)
  488. if (cacheCount.episodeKey >= cacheLimit.episodeKey) {
  489. for (k of episodeKeyCache.keys()) { delete episodeKeyCache[k] }
  490. cacheCount.episodeKey = 0
  491. }
  492. cacheCount.episodeKey = cacheCount.episodeKey + 1
  493. episodeKeyCache[id] = ep != null ? { show = ep.show s = ep.seasonNumber e = ep.episodeNumber } : { show = null s = null e = null }
  494. return episodeKeyCache[id]
  495. }
  496. // a title changed (catalog.hl refreshCatalogShow): its cached entries again from the stored record; the episode keys of its
  497. // episodes from the new rows (numbers the sync changed). Keys of a title nobody follows (no rows cached) are not refreshed —
  498. // /my/series only reads followed titles, and warmTitleCaches covers every followed one at boot.
  499. static refreshTitleCaches = (&show) => {
  500. // tracker#42: its slugs into the slug map (a new title's page is found without a scan)
  501. noteSlugsOf(&show)
  502. if (cardCache[show.id] != null) { cardCache[show.id] = cardFrom(&show) }
  503. if (creditRowCache[show.id] != null) { creditRowCache[show.id] = creditRowFrom(&show) }
  504. if (episodeRowsCache[show.id] != null) {
  505. episodeRowsCache[show.id] = episodeRowsFrom(&show)
  506. sid = show.id
  507. for (r of episodeRowsOf(&sid)) {
  508. if (episodeKeyCache[r.id] != null) { episodeKeyCache[r.id] = { show = sid s = r.s e = r.e } }
  509. }
  510. }
  511. return null
  512. }
  513. // project.hl at boot: the titles anyone follows and every watched episode, so the first /my/ load after a start is not the one
  514. // that fills them
  515. static warmTitleCaches = (&ids) => {
  516. let n = 0
  517. for (id of ids) {
  518. if (cardOf(&id) != null) { episodeRowsOf(&id) n = n + 1 }
  519. }
  520. return n
  521. }
  522. static warmEpisodeKeys = (&ids) => {
  523. for (id of ids) { episodeKeyOf(&id) }
  524. return ids.length
  525. }
  526. // merge.hl (tracker#31): an episode that moved to another title — its key is read again at the next ask
  527. static forgetEpisodeKey = (&id) => {
  528. episodeKeyCache[id] = null
  529. return null
  530. }
  531. // ---- the show on other sites (tracker.worldapi.org#12) ------------------------------------------
  532. // the header's link icons: TMDB, IMDb, TheTVDB, TVmaze — ONLY for the ids the show has; a movie (`type = 'movie'`)
  533. // gets TMDB + IMDb. TheTVDB's id form is `/dereferrer/series/<id>` (checked 2026-10-01: it and the old
  534. // `?tab=series&id=` both 301 to the slug page); the others are the sites' own id URLs (they too 301 to a slug).
  535. static externalLinksOf = (&show) => {
  536. out = []
  537. movie = show.type == 'movie'
  538. if (hasId(&show.tmdbId)) { out.push({ site = 'tmdb' label = 'TMDB' title = 'On TMDB' href = 'https://www.themoviedb.org/' + (movie ? 'movie/' : 'tv/') + show.tmdbId }) }
  539. if (hasId(&show.imdbId)) { out.push({ site = 'imdb' label = 'IMDb' title = 'On IMDb' href = 'https://www.imdb.com/title/' + show.imdbId + '/' }) }
  540. if (!movie && hasId(&show.tvdbId)) { out.push({ site = 'tvdb' label = 'TVDB' title = 'On TheTVDB' href = 'https://thetvdb.com/dereferrer/series/' + show.tvdbId }) }
  541. if (!movie && hasId(&show.tvmzId)) { out.push({ site = 'tvmaze' label = 'TVmaze' title = 'On TVmaze' href = 'https://www.tvmaze.com/shows/' + show.tvmzId }) }
  542. return out
  543. }

Branches

Latest commits

  • 9edcc2dflog: #58 live, HM57 startedmre
  • 73fa20ddMerge hm49b-styles: tracker#49 rest of the component stylesmre
  • 14195720log: HM49B done, HM51 startedmre
  • 78ee6b56Move remaining component styles into Style blocksmre
  • 7f04de33log: HM49Bmre
  • 00616cf3log: #49 batch merged, DP67 startedmre
  • d7232e86Merge hm49-styles: tracker#49 first batch of component stylesmre
  • 079f376dMove seven components' styles into Style blocksmre
  • 17d66feelog: #58 mergedmre
  • 69a6640bMerge hm58-map: tracker#58 project.hl only the mapmre
  • a85f7900Move route logic out of the project mapmre
  • 13dea5belog: #56 live, HM49 and HM58 startedmre
  • a31c8f2fdocs: tracker#36 remaining listmre
  • 975d06d1log: #36 live, DP66 startedmre
  • d6d03fa3mission: T36Bmre
  • e7512d00status: #36 rolled back, retry askedmre
  • c98e2043log: T36A rollbackmre
  • ae905f15Merge t36a: tracker#36 apply rechecks, reportmre
  • 796bfaceT36A: report validated fixes, failed live SSH check and verified rollbackmre
  • 55257852log: #53 live, #56 mergedmre