gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb3d8a80bb3d8a80bDP69 brief, RV48 mergedmreb3d8a80b/lib/shows.hl

50.4 KB

  1. // lib/shows.hl — title data, page rows and actions 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. import { isFollowing, toggleFollowed } from './follows.hl'
  12. import { watchesOfUser, watchedSetOf, isWatched, watchClassOf, seasonAllWatched, toggleWatched, toggleSeasonWatched } from './watches.hl'
  13. import { needsDetails } from './details.hl'
  14. import { widgetsOf } from './franchises.hl'
  15. import { listOr } from './util.hl'
  16. import { dateText } from './people.hl'
  17. static genresTable = new MPackDB(file = storageDir + '/genres.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  18. // tracker#62: first open builds missing indexes from data; compact stays false.
  19. static personsTable = new MPackDB(file = storageDir + '/persons.db', primaryKey = '@id', indexes = ['!oldId', 'urlSegment', 'tmdbId'], compact = false)
  20. static showsTable = new MPackDB(file = storageDir + '/shows.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  21. static seasonsTable = new MPackDB(file = storageDir + '/seasons.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  22. static episodesTable = new MPackDB(file = storageDir + '/episodes.db', primaryKey = '@id', indexes = ['!oldId'], compact = false)
  23. // 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
  24. // every record per call (twice per show page) decoded every title's cast + crew: 82 ms per call on the live copy before the
  25. // 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
  26. // 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-
  27. // time server blocked). A title added since the build (search import, filmography fill — the only two puts) is in the map through
  28. // catalog.hl refreshCatalogShow → refreshTitleCaches → noteSlugsOf, which both call right after the put; merge.hl notes its own.
  29. // (Flat static written key by key, like people.hl's maps.)
  30. // tracker#31 (mission 026): a MERGED title's slug (a tombstone's, below) and a keeper's former slug (`oldSlugs`) answer the
  31. // KEEPER — several records can share one slug (migrated duplicates did), so each slug has a rank: a live record's own slug (3)
  32. // beats a live record's former one (2) beats a tombstone's (1).
  33. static slugIds = {}
  34. static slugRank = {}
  35. static slugIdsBuilt = { yes = false }
  36. // ---- merged titles (tracker#31, mission 026, merge.hl) ----------------------------------------------------------------------
  37. // The old tracker left 68 titles as 2–6 records each (same type + TMDB id). The repair (merge.hl) keeps ONE record (the keeper)
  38. // and turns the others into TOMBSTONES — never deleted: `mergedInto` = the keeper's id, `mergedTmdbId` (their `tmdbId` is
  39. // null, so nothing looks them up by it), `mergedSeasons` (their `seasons` are empty). Every list skips them (isPublicTitle),
  40. // every job skips them, a tombstone's slug and short id lead to the keeper.
  41. static isMerged = (&show) => { return show != null && show.mergedInto != null }
  42. // the record a page shows for this one: the keeper of a tombstone (a chain is followed, at most 5 steps), else itself
  43. static liveShowOf = (&show) => {
  44. let s = show
  45. let n = 0
  46. while (s != null && s.mergedInto != null && n < 5) {
  47. s = showsTable.fetch(s.mergedInto)
  48. n = n + 1
  49. }
  50. return s
  51. }
  52. static holdsSlug = (&s, &slug) => { return s.urlSegment == slug || (s.oldSlugs != null && s.oldSlugs.includes(slug)) }
  53. // this record's slugs into the map (at the build, and by merge.hl after a merge changed a record)
  54. static noteSlugsOf = (&s) => {
  55. live = s.mergedInto == null
  56. mine = []
  57. if (s.urlSegment != null) { mine.push({ slug = s.urlSegment rank = live ? 3 : 1 }) }
  58. if (live && s.oldSlugs != null) { for (o of s.oldSlugs) { mine.push({ slug = o rank = 2 }) } }
  59. for (m of mine) {
  60. cur = slugRank[m.slug]
  61. if (cur == null || m.rank >= cur || slugIds[m.slug] == s.id) {
  62. slugIds[m.slug] = s.id
  63. slugRank[m.slug] = m.rank
  64. }
  65. }
  66. return null
  67. }
  68. // bootscan.hl streamed every title through noteSlugsOf
  69. static markSlugIdsBuilt = () => {
  70. slugIdsBuilt.yes = true
  71. return true
  72. }
  73. static ensureSlugIds = () => {
  74. // mission T17: during the progressive start the map is being filled (bootscan.hl) — no blocking full scan here
  75. if (!slugIdsBuilt.yes && !warm.running) {
  76. // mission 043: streamed (one title decoded at a time); at boot bootscan.hl fills the map in its own pass over the titles
  77. for (s of showsTable.iterate(null, null)) { noteSlugsOf(&s) }
  78. slugIdsBuilt.yes = true
  79. }
  80. return true
  81. }
  82. static showBySlug = (&slug) => {
  83. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  84. ensureSlugIds()
  85. id = slugIds[slug]
  86. if (id != null) {
  87. hit = showsTable.fetch(id)
  88. if (hit != null && holdsSlug(&hit, &slug)) { return liveShowOf(&hit) }
  89. }
  90. return null
  91. }
  92. // 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
  93. // 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
  94. // noteSlugsOf), never a scan. No route per such slug (hl:web writes every route into each page's HTML; the moved slugs there
  95. // included adult titles'): /movies/<slug> and /series/<slug> render the keeper's page (showBySlug), its head names this path.
  96. static movedSlugPath = (&slug) => {
  97. ensureSlugIds()
  98. rank = slugRank[slug]
  99. if (rank == null || rank >= 3) { return null }
  100. keeper = liveShowOf(showsTable.fetch(slugIds[slug]))
  101. if (keeper == null || keeper.mergedInto != null || keeper.urlSegment == null || keeper.urlSegment == slug) { return null }
  102. return titlePath(&keeper)
  103. }
  104. // how many slugs lead to a keeper now (project.hl's boot log line)
  105. static movedSlugCount = () => {
  106. ensureSlugIds()
  107. let n = 0
  108. for (slug of slugRank.keys()) { if (slugRank[slug] < 3 && movedSlugPath(&slug) != null) { n = n + 1 } }
  109. return n
  110. }
  111. static genreById = (&id) => { return id == null ? null : genresTable.fetch(id) }
  112. // /genres/<genre> (mission 058): the genre with this urlSegment ('Action', 'Sci-Fi-Fantasy'), exact first, else ignoring case
  113. // — a scan of the genres table (27 rows)
  114. static genreBySlug = (&slug) => {
  115. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  116. lower = slug.toLowerCase()
  117. let loose = null
  118. for (g of genresTable.find(null, null)) {
  119. if (g.urlSegment == slug) { return g }
  120. if (loose == null && g.urlSegment != null && ('' + g.urlSegment).toLowerCase() == lower) { loose = g }
  121. }
  122. return loose
  123. }
  124. static personById = (&id) => { return id == null ? null : personsTable.fetch(id) }
  125. // GC1: the five request caches (personLinkCache, cardCache, episodeRowsCache, episodeKeyCache, creditRowCache) only ever grew: every title
  126. // 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
  127. // at most `cacheLimit` entries; the one that is full is emptied before it takes the next (an entry is a plain recomputation of the
  128. // 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
  129. // set needs (the followed titles and their watched episodes, warmed at boot). TRACKER_CACHE_MAX sets all five (a test).
  130. static cacheMax = toNumber(envOr('TRACKER_CACHE_MAX', '0'))
  131. 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 }
  132. static cacheCount = { card = 0 episodeRows = 0 episodeKey = 0 creditRow = 0 personLink = 0 }
  133. // tracker#42 (mission 038): what a cast / crew row needs of a person — { name, urlSegment } — cached per person: a series page linked
  134. // up to 300 cast + crew people by fetching each WHOLE record (their `shows` credits: Saturday Night Live's 303 cast carry 4,761) —
  135. // ~49k allocations and 11 ms per render, a third of the page's allocations (every ~3M allocations the GC stops the server for
  136. // ~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
  137. // merge.hl only add data), so the cache is never stale. null = no such person (not remembered: a guest's person can come later).
  138. static personLinkCache = {}
  139. static personLinkOf = (&personId) => {
  140. if (personId == null) { return null }
  141. if (personLinkCache[personId] != null) { return personLinkCache[personId] }
  142. linkPerson = personsTable.fetch(personId)
  143. if (linkPerson == null) { return null }
  144. if (cacheCount.personLink >= cacheLimit.personLink) {
  145. for (k of personLinkCache.keys()) { delete personLinkCache[k] }
  146. cacheCount.personLink = 0
  147. }
  148. personLinkCache[personId] = { name = linkPerson.name urlSegment = linkPerson.urlSegment }
  149. cacheCount.personLink = cacheCount.personLink + 1
  150. return personLinkCache[personId]
  151. }
  152. static seasonById = (&id) => { return id == null ? null : seasonsTable.fetch(id) }
  153. static showById = (&id) => { return id == null ? null : showsTable.fetch(id) }
  154. static episodeById = (&id) => { return id == null ? null : episodesTable.fetch(id) }
  155. // EVERY show / episode as one array — for the tools in tools/ only (the app streams: bootscan.hl, mission 043)
  156. static allShows = () => { return showsTable.find(null, null) }
  157. static allEpisodes = () => { return episodesTable.find(null, null) }
  158. // insertion sort, hand-written (no list sort(), hybriel#1) — a show has a handful of seasons at most
  159. static insertDesc = (&sorted, &s) => {
  160. out = []
  161. let inserted = false
  162. for (x of sorted) {
  163. if (!inserted && s.seasonNumber >= x.seasonNumber) { out.push(s) inserted = true }
  164. out.push(x)
  165. }
  166. if (!inserted) { out.push(s) }
  167. return out
  168. }
  169. static insertAsc = (&sorted, &e) => {
  170. out = []
  171. let inserted = false
  172. for (x of sorted) {
  173. if (!inserted && e.episodeNumber <= x.episodeNumber) { out.push(e) inserted = true }
  174. out.push(x)
  175. }
  176. if (!inserted) { out.push(e) }
  177. return out
  178. }
  179. // a show's seasons, latest (highest seasonNumber) first — creator: "all seasons in reverse order,
  180. // latest on top"
  181. static seasonsOfShow = (&show) => {
  182. let sorted = []
  183. for (id of show.seasons) {
  184. s = seasonsTable.fetch(id)
  185. if (s != null) { sorted = insertDesc(&sorted, &s) }
  186. }
  187. return sorted
  188. }
  189. // a season's episodes, in episode-number order
  190. static episodesOfSeason = (&season) => {
  191. let sorted = []
  192. for (id of season.episodes) {
  193. e = episodesTable.fetch(id)
  194. if (e != null) { sorted = insertAsc(&sorted, &e) }
  195. }
  196. return sorted
  197. }
  198. // ---- labels shared by every list (tracker.worldapi.org#8) -------------------------------------
  199. static pad2 = (&n) => {
  200. let s = '' + n
  201. while (s.length < 2) { s = '0' + s }
  202. return s
  203. }
  204. // an episode as `S01E01` (creator: "write it like that: S01E01") — /my/shows, /my/unwatched, /my/schedule
  205. static episodeCode = (&seasonNumber, &episodeNumber) => { return 'S' + pad2(&seasonNumber) + 'E' + pad2(&episodeNumber) }
  206. // the show's year: `year`, else the first 4 characters of `release` ('YYYY-MM-DD'; 197 migrated shows have
  207. // no year, a few of those an empty release) — null when neither gives one
  208. static showYear = (&show) => {
  209. if (show.year != null) { return '' + show.year }
  210. if (show.release != null && hlTypeName(show.release) == 'String' && show.release.length >= 4) { return show.release.slice(0, 4) }
  211. return null
  212. }
  213. // a show's title as every list shows it: `Doctor Who (2005)` (creator: so same-named shows can be told apart)
  214. static titleWithYear = (&show) => {
  215. y = showYear(&show)
  216. return y != null ? show.title + ' (' + y + ')' : show.title
  217. }
  218. // ---- the description (tracker#18) ---------------------------------------------------------------
  219. // creator: "i put the summary in an own field for tmdb because some summaries i wanted to rewrite ... in that case the summary
  220. // has priority over maze or tmdb" — `summary` (the creator's own text, never written by the sync), else TMDB's `tmdbSummary`,
  221. // else TVmaze's `tvmazeSummary` (HTML stripped); '' when none
  222. static hasText = (&v) => { return v != null && hlTypeName(v) == 'String' && v.trim() != '' }
  223. static summaryOf = (&show) => {
  224. if (show == null) { return '' }
  225. if (hasText(&show.summary)) { return show.summary }
  226. if (hasText(&show.tmdbSummary)) { return show.tmdbSummary }
  227. if (hasText(&show.tvmazeSummary)) { return show.tvmazeSummary }
  228. return ''
  229. }
  230. // ---- a series' status (tracker#35, mission 030) -----------------------------------------------------------------------
  231. // The page's status pill (components/show.hl) next to a series' or show's title: TVmaze's `tvmazeStatus` (Running, Ended, To Be
  232. // Determined, In Development — stored by the sync and backfill.hl's status backfill) when there is one — creator: "this was also
  233. // something tvmaze was better updated about" — else TMDB's `status` (Returning Series, In Production, Planned, Pilot, Ended,
  234. // Canceled). TVmaze has no "canceled": its Ended + TMDB's Canceled shows Canceled (the same state, TMDB's word says more).
  235. // tracker#35 follow-up (mission 033): TVmaze's "Running" reads stale to the creator (Twisted Metal between seasons) — its LABEL
  236. // 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'
  237. // `release`, `isAiring`). Only the label: the stored tvmazeStatus stays "Running"; every other word (Ended, Canceled, To Be
  238. // Determined, TMDB's) is shown as before.
  239. // { text, tone } — tone running | pending | ended | canceled | other (the pill's colour, styles.hl); text '' = no pill (a movie,
  240. // or no status known).
  241. static statusTones = { 'Running' = 'running' 'Returning Series' = 'running' 'To Be Determined' = 'pending' 'In Development' = 'pending'
  242. 'In Production' = 'pending' 'Planned' = 'pending' 'Pilot' = 'pending' 'Ended' = 'ended' 'Canceled' = 'canceled' }
  243. static statusOf = (&show) => {
  244. if (show == null || show.type == 'movie') { return { text = '' tone = '' } }
  245. let word = hasText(&show.tvmazeStatus) ? show.tvmazeStatus : (hasText(&show.status) ? show.status : '')
  246. if (word == 'Ended' && show.status == 'Canceled') { word = 'Canceled' }
  247. if (word == '') { return { text = '' tone = '' } }
  248. tone = statusTones[word]
  249. let text = word == 'Returning Series' ? 'Returning' : word
  250. if (word == 'Running') { text = isAiring(&show) ? 'Airing' : 'Returning' }
  251. return { text = text tone = tone != null ? tone : 'other' }
  252. }
  253. // an episode released today-7 … today+7 (UTC days, both ends included); only the two newest numbered seasons are looked at (an
  254. // airing episode is in one of them — The Simpsons has 36 seasons). Specials (season 0; the sync keeps them only for a show that
  255. // already has one) do not count: Family Guy's special of 2026-10-05 between S24 and S25 is no "Airing".
  256. static isAiring = (&show) => {
  257. firstDay = dayStr(-7)
  258. lastDay = dayStr(7)
  259. seasons = []
  260. for (se of seasonsOfShow(&show)) { if (se.seasonNumber != 0 && seasons.length < 2) { seasons.push(se) } }
  261. let k = 0
  262. while (k < seasons.length) {
  263. for (id of seasons[k].episodes) {
  264. e = episodesTable.fetch(id)
  265. if (e != null && hasText(&e.release)) {
  266. d = e.release.slice(0, 10)
  267. if (d >= firstDay && d <= lastDay) { return true }
  268. }
  269. }
  270. k = k + 1
  271. }
  272. return false
  273. }
  274. // ---- adult titles (mission 054) -----------------------------------------------------------------
  275. // `adult` on every title: true / false from TMDB, null = not known yet (the migrated rows; the app's backfill, backfill.hl
  276. // `backfillTitle`, asks TMDB). The PUBLIC lists (catalog.hl: homepage rows, /movies, /shows) and the search (search.hl) show
  277. // ONLY a title TMDB says is not adult — unknown counts as hidden. A title the user follows stays on /my/* and its page.
  278. // A merged tombstone (tracker#31) is never public.
  279. static isPublicTitle = (&show) => { return show != null && show.adult == false && show.mergedInto == null }
  280. // ---- incomplete titles (tracker.worldapi.org#26; details.hl completes them, credits.hl and dailysync.hl skip them) ------------
  281. // COMPLETE = TMDB's details answer went through this app once: completed (`detailsAt`, details.hl) or synced (`tmdbSync`, the
  282. // last step of sync.hl's sync — the daily run, a search import) — or given up on (`detailsCheck`: TMDB 404 / adult).
  283. // INCOMPLETE = every other title with a TMDB id: a filmography title (`minimal`, #26) until it is completed, an import whose
  284. // sync never finished, and (tracker#33, mission 029) the old tracker's MIGRATED rows that were never synced — #26 only looked
  285. // at `minimal`/`imported`, so they passed: live copy 2026-10-03, 5,697 non-adult titles (4,206 movies, 1,491 series), 691
  286. // series without a single season, 209 + 84 without a poster, 389 + 120 without genres (tools/count-incomplete.hl). Also a
  287. // movie with a TV answer's leftovers (below). What a title still lacks that a page shows: `missingParts`.
  288. static isIncomplete = (&s) => {
  289. return s != null && s.tmdbId != null && s.detailsCheck == null
  290. && ((s.detailsAt == null && (s.minimal == true || s.tmdbSync == null)) || hasTvLeftovers(&s))
  291. }
  292. // tracker#33: what a title's page would miss — the parts a complete record has when TMDB has them: 'poster', 'summary',
  293. // 'genres', 'cast', 'ids' (no IMDb id), 'release', 'seasons' (a series without any). The repair does these titles first
  294. // (details.hl detailsRepairQueue); tools/count-incomplete.hl counts them. A complete title can still miss one — TMDB has none
  295. // (The Remaining, a 7-minute Finnish short: no poster, no IMDb id on TMDB).
  296. static missingParts = (&s) => {
  297. out = []
  298. if (s.image == null || s.image == '') { out.push('poster') }
  299. if (summaryOf(&s) == '') { out.push('summary') }
  300. if (s.genres == null || s.genres.length == 0) { out.push('genres') }
  301. if (s.cast == null || s.cast.length == 0) { out.push('cast') }
  302. if (s.imdbId == null) { out.push('ids') }
  303. if (s.release == null || s.release == '') { out.push('release') }
  304. if (s.type != 'movie' && (s.seasons == null || s.seasons.length == 0)) { out.push('seasons') }
  305. return out
  306. }
  307. // mission 025 (report 021's "wrong TMDB id"): the #9 sync once asked TMDB for every followed title as `/tv/<tmdbId>` — a movie's
  308. // id is ANOTHER title there (fixed in mission 006: movies go to /movie/) and the TV title's overview, status and season/episode
  309. // counts were stored on the movie. On the real data only Star Trek: First Contact: its tmdbId 199 IS the movie (/movie/199),
  310. // tmdbSummary was TV 199's ("Kabuhayang Swak na Swak …"), status 'Ended', seasonsCount/episodesCount 0. The movie path never
  311. // writes the counts, so a movie that has them is such a record: the repair asks /movie/<id> again (withDetailsFields: overview →
  312. // tmdbSummary, status, …) and firstStep drops the counts — repaired once, then it no longer matches.
  313. static hasTvLeftovers = (&s) => { return s.type == 'movie' && (s.seasonsCount != null || s.episodesCount != null) }
  314. // ---- the kind of a title (tracker.worldapi.org#21, mission 068; #43, mission 037) ------------------------------------------
  315. // A TV title (`type = 'series'`) is either a SERIES (TMDB's TV type Scripted, Miniseries, Documentary) or a SHOW (Reality,
  316. // Talk Show, News, Video — or one of our genres Reality / Talk / News, whatever the type — or, #43, TVmaze's type Variety, Talk
  317. // Show, Reality, Game Show, News, Panel Show, Award Show, Sports: TMDB calls Saturday Night Live UK "Scripted", TVmaze
  318. // "Variety"; TVmaze's type is stored as `tvmazeType` by the sync and the TVmaze status backfill). Stored on the title as `kind`
  319. // ('series' | 'show') and TMDB's type as `tmdbType`: by the kind backfill (backfill.hl `kindTitle`, one TMDB request per
  320. // title without a show genre), the daily sync and the search import. Until a title has `kind`, its genres decide (no
  321. // type known yet = series). Movies are `type = 'movie'` and have no kind.
  322. static showTmdbTypes = ['Reality', 'Talk Show', 'News', 'Video']
  323. static showGenreNames = ['Reality', 'Talk', 'News']
  324. // #43 (mission 037): TVmaze's show types that are SHOWS ("all that game show and reality and talkshow stuff", #21); its others —
  325. // Scripted, Animation, Documentary — are series. '' = TVmaze was asked and gave none
  326. static showTvmazeTypes = ['Variety', 'Talk Show', 'Reality', 'Game Show', 'News', 'Panel Show', 'Award Show', 'Sports']
  327. static showGenreIdsOf = () => {
  328. out = {}
  329. for (g of genresTable.find(null, null)) { if (g.name != null && showGenreNames.includes('' + g.name)) { out[g.id] = true } }
  330. return out
  331. }
  332. // the genre ids that make a title a show — read once (the genres table never changes while the app runs)
  333. static showGenreIds = showGenreIdsOf()
  334. static hasShowGenre = (&genres) => {
  335. if (genres == null) { return false }
  336. for (g of genres) { if (showGenreIds[g] == true) { return true } }
  337. return false
  338. }
  339. // 'show' | 'series' from TMDB's type, the title's genre ids and TVmaze's type (#43; null = not known)
  340. static kindOfTitle = (&tmdbType, &genres, &tvmazeType) => {
  341. if (hasShowGenre(&genres)) { return 'show' }
  342. if (tmdbType != null && showTmdbTypes.includes('' + tmdbType)) { return 'show' }
  343. if (tvmazeType != null && showTvmazeTypes.includes('' + tvmazeType)) { return 'show' }
  344. return 'series'
  345. }
  346. // #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:
  347. // the genres decide until the kind backfill asks TMDB, which it does only for a title without a stored kind)
  348. static kindWithTvmaze = (&show) => {
  349. known = (show.tmdbType != null && '' + show.tmdbType != '') || (show.tvmazeType != null && showTvmazeTypes.includes('' + show.tvmazeType))
  350. return known ? kindOfTitle(&show.tmdbType, &show.genres, &show.tvmazeType) : show.kind
  351. }
  352. // 'movie' | 'series' | 'show' of a stored title
  353. static titleKind = (&show) => {
  354. if (show.type == 'movie') { return 'movie' }
  355. if (show.kind == 'show' || show.kind == 'series') { return show.kind }
  356. return kindOfTitle(&show.tmdbType, &show.genres, &show.tvmazeType)
  357. }
  358. // a title's own page: /movies/<slug>, /series/<slug>, /shows/<slug> (the old /shows/<slug> of a movie or series answers 301,
  359. // project.hl showsRoute)
  360. static titlePath = (&show) => {
  361. k = titleKind(&show)
  362. return (k == 'movie' ? '/movies/' : (k == 'show' ? '/shows/' : '/series/')) + show.urlSegment
  363. }
  364. // `/shows/<slug>` (#21, mission 068; project.hl showsRoute): since the split only the game / reality / talk / news SHOWS live
  365. // 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
  366. // keeper's former one (tracker#31: the keeper's page); null = render the title page here (a show, or an unknown slug)
  367. static showsMovedPath = (&slug) => {
  368. show = showBySlug(&slug)
  369. return show != null && (titleKind(&show) != 'show' || show.urlSegment != slug) ? titlePath(&show) : null
  370. }
  371. // tracker.worldapi.org#20: the type word of a page heading / list label and its colour class (styles.hl `type-*`)
  372. static kindWord = (&kind) => { return kind == 'movie' ? 'Movie' : (kind == 'show' ? 'Show' : 'Series') }
  373. static typeWordOf = (&show) => { return kindWord(titleKind(&show)) }
  374. // 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
  375. static pillClassOfWord = (&word) => { return word == 'Movie' ? 'pill type-1' : (word == 'Show' ? 'pill type-3' : 'pill type-2') }
  376. static typeClassOf = (&show) => { return pillClassOfWord(typeWordOf(&show)) }
  377. // the poster file name (oldId + the migrated extension) — null when either is missing; served at
  378. // /posters/<name> (images.hl), which falls back to a placeholder when the file itself isn't there
  379. // yet (the real poster files are not part of the mongo export, see the report's `open`)
  380. static posterName = (&show) => {
  381. if (show.oldId == null || show.image == null || show.image == '') { return null }
  382. return show.oldId + '.' + show.image
  383. }
  384. // the poster's URL for a LIST (/my/shows, tracker.worldapi.org#8): `/posters/<name>` only when the file really
  385. // is in storage/mpackdb/posters/ (images.hl serves the same folder), else the ONE placeholder URL
  386. // `/posters/none` — the real data has no poster files yet, and 128 different URLs all answering the same
  387. // placeholder were 128 requests per page load (the browser can't cache them as one)
  388. static posterUrlOf = (&show) => { return posterUrlOfName(posterName(&show)) }
  389. static posterUrlOfName = (&name) => { return name != null && exists(postersDir + '/' + name) ? '/posters/' + name : '/posters/none' }
  390. // ---- slim per-title caches for the lists (tracker.worldapi.org#30, mission 025) ------------------------------------
  391. // /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
  392. // WHOLE record (cast + crew, up to 300 entries) and one episode per watch (11.7k fetches); /my/unwatched every season and
  393. // episode of every followed title. Each fetch decodes a new object, and with a big live heap (after the jobs) every byte
  394. // allocated feeds the byte-triggered GC. Now a list reads two small cached things per title:
  395. // - `cardOf(id)`: { id type kind title year titleYear href posterName } — what a row shows;
  396. // - `episodeRowsOf(id)`: every episode of the title as { id s e title release }, seasons latest first, episodes in order
  397. // (the same order as seasonsOfShow/episodesOfSeason);
  398. // - `episodeKeyOf(id)`: one episode as { show s e } — /my/series' last watched episode goes by the WATCHED episode's own
  399. // `show` (as before): migrated episodes the sync left outside the title's seasons (a duplicate season, e.g. Reacher S03 on
  400. // the real data) still count. project.hl warms every watched episode at boot.
  401. // Filled at the first ask (project.hl warms the followed titles at boot) and kept in sync by catalog.hl `refreshCatalogShow`,
  402. // which every writer of a title already calls after it changed one (daily sync, repair, kinds, adult backfill, imports):
  403. // it calls `refreshTitleCaches(show)`, which rebuilds the entries that exist. Cached values are only ever RETURNED from a
  404. // function (a `let x = map[k]` deep-copies the value; a return does not — measured: 3.7 ms per 20k-row copy).
  405. static cardCache = {}
  406. static episodeRowsCache = {}
  407. static episodeKeyCache = {}
  408. static cardFrom = (&show) => {
  409. y = showYear(&show)
  410. return {
  411. id = show.id type = show.type kind = titleKind(&show) title = show.title year = y != null ? y : ''
  412. titleYear = titleWithYear(&show) href = titlePath(&show) posterName = posterName(&show)
  413. }
  414. }
  415. // tracker#46 (mission 046): what the PERSON page needs of a title, per title id — { id mergedInto public title year release href
  416. // posterName typeLabel typeClass }. The person page used to fetch every credit's WHOLE title record (cast + crew, up to 300
  417. // entries each: 311 decoded records for Tom Hanks) on every request — the allocation fed the byte-triggered GC (a 6 s+ pause
  418. // on the live heap). Filled at the first ask, rebuilt by `refreshTitleCaches` (every writer of a title calls it); returned, never copied.
  419. static creditRowCache = {}
  420. static creditRowFrom = (&show) => {
  421. y = showYear(&show)
  422. return { id = show.id mergedInto = show.mergedInto public = isPublicTitle(&show) title = show.title year = y != null ? y : ''
  423. release = textOr(&show.release) href = titlePath(&show) posterName = posterName(&show) typeLabel = typeWordOf(&show) typeClass = typeClassOf(&show) }
  424. }
  425. static creditRowOf = (&id) => {
  426. if (id == null) { return null }
  427. if (creditRowCache[id] != null) { return creditRowCache[id] }
  428. show = showsTable.fetch(id)
  429. if (show == null) { return null }
  430. if (cacheCount.creditRow >= cacheLimit.creditRow) {
  431. for (k of creditRowCache.keys()) { delete creditRowCache[k] }
  432. cacheCount.creditRow = 0
  433. }
  434. creditRowCache[id] = creditRowFrom(&show)
  435. cacheCount.creditRow = cacheCount.creditRow + 1
  436. return creditRowCache[id]
  437. }
  438. // 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)
  439. static creditRowLive = (&id) => {
  440. let r = creditRowOf(&id)
  441. let n = 0
  442. while (r != null && r.mergedInto != null && n < 5) {
  443. r = creditRowOf(&r.mergedInto)
  444. n = n + 1
  445. }
  446. return r
  447. }
  448. // GC1 measurement (TRACKER_QSTATS=1, jobs.hl): how many entries the request caches hold
  449. static cacheSizes = () => {
  450. return { card = cardCache.keys().length episodeRows = episodeRowsCache.keys().length episodeKey = episodeKeyCache.keys().length creditRow = creditRowCache.keys().length personLink = personLinkCache.keys().length }
  451. }
  452. static cardOf = (&id) => {
  453. if (id == null) { return null }
  454. if (cardCache[id] != null) { return cardCache[id] }
  455. show = showsTable.fetch(id)
  456. if (show == null) { return null }
  457. if (cacheCount.card >= cacheLimit.card) {
  458. for (k of cardCache.keys()) { delete cardCache[k] }
  459. cacheCount.card = 0
  460. }
  461. cardCache[id] = cardFrom(&show)
  462. cacheCount.card = cacheCount.card + 1
  463. return cardCache[id]
  464. }
  465. static episodeRowsFrom = (&show) => {
  466. out = []
  467. if (show.seasons == null) { return out }
  468. // loop names apart from the row's own `s`/`e` keys: inside an object literal a key set earlier shadows the variable
  469. for (sn of seasonsOfShow(&show)) {
  470. for (ep of episodesOfSeason(&sn)) {
  471. out.push({ id = ep.id s = ep.seasonNumber e = ep.episodeNumber title = ep.title != null ? ep.title : '' release = ep.release })
  472. }
  473. }
  474. return out
  475. }
  476. static episodeRowsOf = (&id) => {
  477. if (id == null) { return [] }
  478. if (episodeRowsCache[id] != null) { return episodeRowsCache[id] }
  479. show = showsTable.fetch(id)
  480. if (show == null) { return [] }
  481. if (cacheCount.episodeRows >= cacheLimit.episodeRows) {
  482. for (k of episodeRowsCache.keys()) { delete episodeRowsCache[k] }
  483. cacheCount.episodeRows = 0
  484. }
  485. episodeRowsCache[id] = episodeRowsFrom(&show)
  486. cacheCount.episodeRows = cacheCount.episodeRows + 1
  487. return episodeRowsCache[id]
  488. }
  489. // an episode that is not stored is { show = null } (never fetched again)
  490. static episodeKeyOf = (&id) => {
  491. if (id == null) { return { show = null s = null e = null } }
  492. if (episodeKeyCache[id] != null) { return episodeKeyCache[id] }
  493. ep = episodesTable.fetch(id)
  494. if (cacheCount.episodeKey >= cacheLimit.episodeKey) {
  495. for (k of episodeKeyCache.keys()) { delete episodeKeyCache[k] }
  496. cacheCount.episodeKey = 0
  497. }
  498. cacheCount.episodeKey = cacheCount.episodeKey + 1
  499. episodeKeyCache[id] = ep != null ? { show = ep.show s = ep.seasonNumber e = ep.episodeNumber } : { show = null s = null e = null }
  500. return episodeKeyCache[id]
  501. }
  502. // a title changed (catalog.hl refreshCatalogShow): its cached entries again from the stored record; the episode keys of its
  503. // episodes from the new rows (numbers the sync changed). Keys of a title nobody follows (no rows cached) are not refreshed —
  504. // /my/series only reads followed titles, and warmTitleCaches covers every followed one at boot.
  505. static refreshTitleCaches = (&show) => {
  506. // tracker#42: its slugs into the slug map (a new title's page is found without a scan)
  507. noteSlugsOf(&show)
  508. if (cardCache[show.id] != null) { cardCache[show.id] = cardFrom(&show) }
  509. if (creditRowCache[show.id] != null) { creditRowCache[show.id] = creditRowFrom(&show) }
  510. if (episodeRowsCache[show.id] != null) {
  511. episodeRowsCache[show.id] = episodeRowsFrom(&show)
  512. sid = show.id
  513. for (r of episodeRowsOf(&sid)) {
  514. if (episodeKeyCache[r.id] != null) { episodeKeyCache[r.id] = { show = sid s = r.s e = r.e } }
  515. }
  516. }
  517. return null
  518. }
  519. // project.hl at boot: the titles anyone follows and every watched episode, so the first /my/ load after a start is not the one
  520. // that fills them
  521. static warmTitleCaches = (&ids) => {
  522. let n = 0
  523. for (id of ids) {
  524. if (cardOf(&id) != null) { episodeRowsOf(&id) n = n + 1 }
  525. }
  526. return n
  527. }
  528. static warmEpisodeKeys = (&ids) => {
  529. for (id of ids) { episodeKeyOf(&id) }
  530. return ids.length
  531. }
  532. // merge.hl (tracker#31): an episode that moved to another title — its key is read again at the next ask
  533. static forgetEpisodeKey = (&id) => {
  534. episodeKeyCache[id] = null
  535. return null
  536. }
  537. // ---- the show on other sites (tracker.worldapi.org#12) ------------------------------------------
  538. // the header's link icons: TMDB, IMDb, TheTVDB, TVmaze — ONLY for the ids the show has; a movie (`type = 'movie'`)
  539. // gets TMDB + IMDb. TheTVDB's id form is `/dereferrer/series/<id>` (checked 2026-10-01: it and the old
  540. // `?tab=series&id=` both 301 to the slug page); the others are the sites' own id URLs (they too 301 to a slug).
  541. static externalLinksOf = (&show) => {
  542. out = []
  543. movie = show.type == 'movie'
  544. if (hasId(&show.tmdbId)) { out.push({ site = 'tmdb' label = 'TMDB' title = 'On TMDB' href = 'https://www.themoviedb.org/' + (movie ? 'movie/' : 'tv/') + show.tmdbId }) }
  545. if (hasId(&show.imdbId)) { out.push({ site = 'imdb' label = 'IMDb' title = 'On IMDb' href = 'https://www.imdb.com/title/' + show.imdbId + '/' }) }
  546. if (!movie && hasId(&show.tvdbId)) { out.push({ site = 'tvdb' label = 'TVDB' title = 'On TheTVDB' href = 'https://thetvdb.com/dereferrer/series/' + show.tvdbId }) }
  547. if (!movie && hasId(&show.tvmzId)) { out.push({ site = 'tvmaze' label = 'TVmaze' title = 'On TVmaze' href = 'https://www.tvmaze.com/shows/' + show.tvmzId }) }
  548. return out
  549. }
  550. // ---- title page rows and actions (tracker#59; moved from components/show.hl) --------------------
  551. static initialCollapsed = (&seasons) => {
  552. m = {}
  553. let i = 0
  554. while (i < seasons.length) {
  555. // mobile audit MK: a season of more than 150 episodes starts closed too (a soap whose 1,175 episodes are ONE season made a 69,000 px page
  556. // of 1,200 tap targets); a tap on its header opens it
  557. if (i > 0 || seasons[i].episodes.length > 150) { m[seasons[i].id] = true }
  558. i = i + 1
  559. }
  560. return m
  561. }
  562. static genreRowsOf = (&show) => {
  563. out = []
  564. for (gid of show.genres) {
  565. g = genreById(&gid)
  566. if (g != null) { out.push({ id = g.id name = g.name href = '/genres/' + g.urlSegment }) }
  567. }
  568. return out
  569. }
  570. // tracker#28: how many names show before "Show all" (cast; per crew job)
  571. static castShown = 20
  572. static crewShown = 6
  573. // the cast as flat rows (no nested for, see THE ROWS above; tracker#42: people by shows.hl personLinkOf, not whole records): `isPerson` rows { name, href, roleText (' (Character)' or ''),
  574. // itemClass } and before the first guest one `isLabel` row "Guest stars". itemClass: `more` = hidden until "Show all", `end` =
  575. // no comma after it (the last of a group), `cut` = the last one shown while collapsed (no comma then)
  576. static castRowsOf = (show) => {
  577. people = []
  578. for (c of listOr(&show.cast)) {
  579. p = c != null && c.person != null ? personLinkOf(&c.person) : null
  580. // mission 062: a guest without a person record — the link creates it on the first open (project.hl guestRoute)
  581. if (p != null) { people.push({ name = c.actor != null ? c.actor : p.name href = '/person/' + p.urlSegment role = c.character != null ? c.character : '' guest = c.guest == true }) }
  582. else if (c != null && c.person == null && c.tmdbId != null && c.actor != null) { people.push({ name = c.actor href = '/person/tmdb/' + c.tmdbId + '?show=' + show.id role = c.character != null ? c.character : '' guest = true }) }
  583. }
  584. out = []
  585. let k = 0
  586. let guests = false
  587. while (k < people.length) {
  588. let c = people[k]
  589. if (c.guest && !guests && k > 0) {
  590. guests = true
  591. out.push({ isLabel = true isPerson = false text = 'Guest stars' name = '' href = '' roleText = '' itemClass = k >= castShown ? 'more' : '' })
  592. }
  593. last = k == people.length - 1 || (people[k + 1].guest && !c.guest)
  594. cls = (k >= castShown ? ' more' : '') + (last ? ' end' : '') + (k == castShown - 1 ? ' cut' : '')
  595. out.push({ isLabel = false isPerson = true text = '' name = c.name href = c.href roleText = c.role != '' ? ' (' + c.role + ')' : '' itemClass = 'artist-link' + cls })
  596. k = k + 1
  597. }
  598. return out
  599. }
  600. static castCountOf = (&rows) => {
  601. let n = 0
  602. for (r of rows) { if (r.isPerson) { n = n + 1 } }
  603. return n
  604. }
  605. static crewLabels = { creator = 'Created by' director = 'Directed by' writer = 'Written by' screenplay = 'Screenplay' story = 'Story' composer = 'Music' }
  606. // the crew as flat rows: per job (in stored order) an `isLabel` row, then its people (itemClass as for the cast, `more` after
  607. // the first crewShown of a job)
  608. static crewRowsOf = (&show) => {
  609. people = []
  610. for (c of listOr(&show.crew)) {
  611. p = c != null ? personLinkOf(&c.person) : null
  612. if (p != null && crewLabels[c.job] != null) { people.push({ name = c.name != null ? c.name : p.name href = '/person/' + p.urlSegment job = c.job }) }
  613. }
  614. out = []
  615. let k = 0
  616. let inJob = 0
  617. while (k < people.length) {
  618. let c = people[k]
  619. if (k == 0 || people[k - 1].job != c.job) {
  620. inJob = 0
  621. out.push({ isLabel = true isPerson = false text = crewLabels[c.job] name = '' href = '' itemClass = '' })
  622. }
  623. last = k == people.length - 1 || people[k + 1].job != c.job
  624. out.push({ isLabel = false isPerson = true text = '' name = c.name href = c.href itemClass = 'crew-link' + (inJob >= crewShown ? ' more' : '') + (last ? ' end' : '') + (inJob == crewShown - 1 ? ' cut' : '') })
  625. inJob = inJob + 1
  626. k = k + 1
  627. }
  628. return out
  629. }
  630. // how many crew names are hidden while collapsed (0 = no toggle) and how many there are
  631. static crewHiddenOf = (&rows) => {
  632. let n = 0
  633. for (r of rows) { if (r.isPerson && r.itemClass.includes(' more')) { n = n + 1 } }
  634. return n
  635. }
  636. static crewCountOf = (&rows) => {
  637. let n = 0
  638. for (r of rows) { if (r.isPerson) { n = n + 1 } }
  639. return n
  640. }
  641. // a View attribute must be a literal, a member or a field path — never an inline expression — so
  642. // every ternary (watched -> icon class, collapsed -> row class) is resolved HERE, once, into a
  643. // plain field the View just reads (row.watchClass, row.rowClass); `watchClassOf` itself lives in
  644. // watches.hl (shared with /unwatched and /schedule, "reuse, don't copy")
  645. // #22: an episode's air date as the lists show it ('YYYY-MM-DD'), '' when it has none
  646. static airDateOf = (&e) => { return e.release != null && hlTypeName(e.release) == 'String' ? e.release : '' }
  647. static buildRows = (&show, &uid, collapsed) => {
  648. // GC1: the user's kept watched set (watches.hl watchedSetOf, rebuilt after their next write), not a new one built from a by-value copy of
  649. // every watch row (12,866 rows on the creator's data) on every page and every check click
  650. watched = uid != null ? watchedSetOf(&uid) : {}
  651. out = []
  652. for (s of seasonsOfShow(&show)) {
  653. isCollapsed = collapsed[s.id] == true
  654. label = s.title != null && s.title != '' ? s.title : 'Season ' + s.seasonNumber
  655. seasonWatched = seasonAllWatched(&s, &watched)
  656. out.push({ kind = 'season' isSeason = true isEpisode = false isSkeleton = false id = s.id skeletonCount = s.episodes.length < 8 ? s.episodes.length : 8 label = label episodeCountText = s.episodes.length == 1 ? '1 episode' : s.episodes.length + ' episodes' watched = seasonWatched watchClass = watchClassOf(&seasonWatched) collapsed = isCollapsed rowClass = isCollapsed ? 'collapsed' : 'expanded' })
  657. if (!isCollapsed) {
  658. for (e of episodesOfSeason(&s)) {
  659. epWatched = watched['episode:' + e.id] == true
  660. out.push({ kind = 'episode' isSeason = false isEpisode = true isSkeleton = false id = e.id seasonId = s.id episodeNumber = e.episodeNumber title = e.title != null ? e.title : '' airDate = airDateOf(&e) watched = epWatched watchClass = watchClassOf(&epWatched) })
  661. }
  662. }
  663. }
  664. return out
  665. }
  666. // what the client marks the rows of a season it opens with (tracker#17) — only this show's, never the user's whole watch
  667. // list (every member is shipped to the browser). Per season with a watched episode: `{ all, except }` — `all` = most of
  668. // it is watched, then `except` holds the UNwatched ids, else the watched ones (a fully watched 142-episode season is
  669. // `{ all = true except = {} }`, not 142 ids). No entry = nothing watched.
  670. static watchedEpisodesOf = (&show, &uid) => {
  671. m = {}
  672. if (uid == null) { return m }
  673. watched = watchedSetOf(&uid)
  674. for (s of seasonsOfShow(&show)) {
  675. yes = {}
  676. no = {}
  677. let n = 0
  678. for (eid of s.episodes) {
  679. if (watched['episode:' + eid] == true) { yes[eid] = true n = n + 1 } else { no[eid] = true }
  680. }
  681. if (n > 0) { m[s.id] = n * 2 > s.episodes.length ? { all = true except = no } : { all = false except = yes } }
  682. }
  683. return m
  684. }
  685. // is this episode watched, by that per-season shape (client-side, pure)
  686. static watchedIn = (&entry, &episodeId) => {
  687. if (entry == null) { return false }
  688. listed = entry.except[episodeId] == true
  689. return entry.all ? !listed : listed
  690. }
  691. // ---- the rows as the CLIENT changes them (tracker#17) — pure: no import is reached, so they run in the browser ----------
  692. // (`watchClassOf` is an import of the mpackdb-backed watches.hl, so `filledRows` writes its two classes itself)
  693. static seasonRowAs = (&row, &isCollapsed) => {
  694. return { kind = 'season' isSeason = true isEpisode = false isSkeleton = false id = row.id skeletonCount = row.skeletonCount label = row.label episodeCountText = row.episodeCountText watched = row.watched watchClass = row.watchClass collapsed = isCollapsed rowClass = isCollapsed ? 'collapsed' : 'expanded' }
  695. }
  696. // the season opened: its caret up at once, `skeletonCount` placeholder rows under it
  697. static openingRows = (&rows, seasonId) => {
  698. out = []
  699. for (row of rows) {
  700. if (row.isSeason && row.id == seasonId) {
  701. out.push(seasonRowAs(&row, false))
  702. let i = 0
  703. while (i < row.skeletonCount) {
  704. out.push({ kind = 'skeleton' isSeason = false isEpisode = false isSkeleton = true id = seasonId + '-skeleton-' + i seasonId = seasonId })
  705. i = i + 1
  706. }
  707. } else { out.push(row) }
  708. }
  709. return out
  710. }
  711. // the season closed: its episode (and skeleton) rows gone, caret down
  712. static closedRows = (&rows, &seasonId) => {
  713. out = []
  714. for (row of rows) {
  715. if (row.isSeason && row.id == seasonId) { out.push(seasonRowAs(&row, true)) }
  716. else if (!row.isSeason && row.seasonId == seasonId) { }
  717. else { out.push(row) }
  718. }
  719. return out
  720. }
  721. // the episodes arrived: they replace the season's skeleton rows. No skeleton of it left (closed meanwhile, or a watch face
  722. // already rebuilt every row) → the rows stay as they are (no double rows)
  723. static filledRows = (&rows, seasonId, &episodes, watched) => {
  724. out = []
  725. let done = false
  726. for (row of rows) {
  727. if (row.isSkeleton && row.seasonId == seasonId) {
  728. if (!done) {
  729. for (e of episodes) {
  730. w = watchedIn(&watched[seasonId], &e.id)
  731. out.push({ kind = 'episode' isSeason = false isEpisode = true isSkeleton = false id = e.id seasonId = seasonId episodeNumber = e.episodeNumber title = e.title airDate = e.airDate watched = w watchClass = w ? 'checkicon solid' : 'checkicon regular' })
  732. }
  733. done = true
  734. }
  735. } else { out.push(row) }
  736. }
  737. return out
  738. }
  739. // a LOCAL static like buildRows (an imported mpackdb helper called straight from a member's initializer came back false
  740. // after a client-side navigation to the page — the gate's follow check)
  741. static followingOf = (&show, &uid) => { return uid != null && isFollowing(&uid, &show.id) }
  742. // #24: has this user watched this movie (a watch `movie:<title id>`)?
  743. static movieWatchedOf = (&show, &uid) => {
  744. if (uid == null) { return false }
  745. rows = watchesOfUser(&uid)
  746. return isWatched(&rows, 'movie', &show.id)
  747. }
  748. // mission 056: an ADULT title's page (TMDB's flag `adult == true`, mission 054) is "Not found" for everyone who does not
  749. // follow it (signed out too); a follower sees it as before. Unknown (`null`) is not hidden here — only in the lists.
  750. // With hybriel ≥ 73267707 (#121/#122) `showRow`/`found` are server sites re-derived after every session face with the page's
  751. // slug, so an Unfollow on the page hides it at once (the gate proves it; the old build left the page up until a reload).
  752. // Mission 054's try (`found = … && !adultHiddenFor(showRow, me)`, `collapsed`/`rows` from `found`) broke the checks.
  753. static adultHiddenFor = (&show, &uid) => { return show.adult == true && !followingOf(&show, &uid) }
  754. // the page's show — null when there is none OR it is hidden for this user: every member is shipped to the browser, so the
  755. // row of a hidden title must never be one
  756. static visibleShow = (&slug, &uid) => {
  757. s = showBySlug(&slug)
  758. return s != null && adultHiddenFor(&s, &uid) ? null : s
  759. }
  760. // tracker.worldapi.org#19 (mission 066): the franchise widget(s), one per timeline the title is in (components/franchisewidget.hl)
  761. static franchiseWidgetsOf = (&show) => { return widgetsOf(&show.id) }
  762. // tracker#33 (mission 032): a movie's release date and runtime under its title — "17 September 2026 · 7 min", "… · 2 h 15 min";
  763. // what is missing is left out ('' = no line)
  764. static runtimeText = (&m) => {
  765. if (m == null || hlTypeName(m) != 'Number' || m <= 0) { return '' }
  766. mins = m % 60
  767. hours = (m - mins) / 60
  768. if (hours == 0) { return mins + ' min' }
  769. return mins == 0 ? hours + ' h' : hours + ' h ' + mins + ' min'
  770. }
  771. static movieFactsOf = (&s) => {
  772. if (s.type != 'movie') { return '' }
  773. parts = []
  774. d = dateText(&s.release)
  775. if (d != null) { parts.push(d) }
  776. r = runtimeText(&s.runtime)
  777. if (r != '') { parts.push(r) }
  778. return parts.join(' · ')
  779. }
  780. // mission 062: what the page shows of the title, as a SMALL object — `showRow` reads the session, so hl:web ships it with the page
  781. // AND re-sends it after every watch/follow click (SESSION SYNC below): the whole record was ~1 MB on The Simpsons (300 cast + crew
  782. // entries). null = not found / hidden.
  783. static pageShowOf = (&slug, &uid) => {
  784. s = visibleShow(&slug, &uid)
  785. if (s == null) { return null }
  786. movie = s.type == 'movie'
  787. st = statusOf(&s)
  788. return { id = s.id title = s.title summary = summaryOf(&s) type = s.type adult = s.adult == true shortId = s.shortId != null ? '' + s.shortId : '' statusText = st.text statusTone = st.tone
  789. poster = posterName(&s) genreRows = genreRowsOf(&s) linkRows = externalLinksOf(&s) completing = completingOf(&s) following = followingOf(&s, &uid)
  790. movieWatched = movie ? movieWatchedOf(&s, &uid) : false facts = movieFactsOf(&s) }
  791. }
  792. // the seasons/episodes rows and the per-season watch state by the slug (the record itself stays on the server)
  793. static rowsOfSlug = (&slug, &uid, &collapsed) => {
  794. s = showBySlug(&slug)
  795. return s != null ? buildRows(&s, &uid, collapsed) : []
  796. }
  797. static watchedEpisodesOfSlug = (&slug, &uid) => {
  798. s = showBySlug(&slug)
  799. return s != null ? watchedEpisodesOf(&s, &uid) : {}
  800. }
  801. // the initial open/closed seasons and the title's kind (tracker#20/#21: the heading's type word) from the SLUG alone (not from
  802. // `showRow`, which reads the session — see `collapsed`) — one slug lookup for both
  803. static slugInfoOf = (&slug) => {
  804. s = showBySlug(&slug)
  805. return s != null ? { collapsed = initialCollapsed(seasonsOfShow(&s)) kind = titleKind(&s) canonical = titlePath(&s) } : { collapsed = {} kind = 'series' canonical = '' }
  806. }
  807. // mission 062: the cast and crew rows by the SLUG alone (not from `showRow`, which reads the session — see `castRows`). An
  808. // ADULT title (its page only for its followers) shows none: every member is shipped to the browser, and adult titles never get
  809. // credits anyway (details.hl skips them; at most a migrated cast)
  810. static publicShowOf = (&slug) => {
  811. s = showBySlug(&slug)
  812. return s != null && s.adult != true ? s : null
  813. }
  814. static castOfSlug = (&slug) => {
  815. s = publicShowOf(&slug)
  816. return s != null ? castRowsOf(s) : []
  817. }
  818. static crewOfSlug = (&slug) => {
  819. s = publicShowOf(&slug)
  820. return s != null ? crewRowsOf(&s) : []
  821. }
  822. static completingOf = (&show) => { return needsDetails(&show) }
  823. static showRowsOf = (slug, collapsed, uid) => {
  824. show = showBySlug(&slug)
  825. if (show == null || adultHiddenFor(&show, &uid)) { return { error = 'no such show' } }
  826. return { ok = true rows = buildRows(&show, &uid, collapsed) }
  827. }
  828. static showSeasonEpisodesOf = (seasonId) => {
  829. if (seasonId == null || hlTypeName(seasonId) != 'String') { return { error = 'no such season' } }
  830. season = seasonById(&seasonId)
  831. if (season == null) { return { error = 'no such season' } }
  832. show = showById(&season.show)
  833. if (show == null || show.adult == true) { return { error = 'no such season' } }
  834. out = []
  835. for (e of episodesOfSeason(&season)) { out.push({ id = e.id episodeNumber = e.episodeNumber title = e.title != null ? e.title : '' airDate = airDateOf(&e) }) }
  836. return { ok = true episodes = out }
  837. }
  838. static showToggleEpisodeOf = (slug, episodeId, collapsed, withRows, uid) => {
  839. show = showBySlug(&slug)
  840. if (show == null) { return { error = 'no such show' } }
  841. if (uid == null) { return { error = 'you are not signed in' } }
  842. if (adultHiddenFor(&show, &uid)) { return { error = 'no such show' } }
  843. // mission SK: only an episode OF THIS SHOW — the id is the peer's (any text became a watch row before)
  844. ep = episodeId != null && hlTypeName(episodeId) == 'String' ? episodeById(&episodeId) : null
  845. if (ep == null || ep.show != show.id) { return { error = 'no such episode' } }
  846. if (toggleWatched(&uid, 'episode', &episodeId) == null) { return { error = 'could not save the watch' } }
  847. return withRows == true ? { ok = true rows = buildRows(&show, &uid, collapsed) } : { ok = true }
  848. }
  849. static showToggleSeasonOf = (slug, seasonId, collapsed, withRows, uid) => {
  850. show = showBySlug(&slug)
  851. if (show == null) { return { error = 'no such show' } }
  852. if (uid == null) { return { error = 'you are not signed in' } }
  853. if (adultHiddenFor(&show, &uid)) { return { error = 'no such show' } }
  854. season = seasonId != null && hlTypeName(seasonId) == 'String' ? seasonById(&seasonId) : null
  855. if (season == null || season.show != show.id) { return { error = 'no such season' } }
  856. // #23: not all episodes watched → watch them all; all watched → unwatch them all (lib/watches.hl)
  857. if (toggleSeasonWatched(&uid, &season) == null) { return { error = 'could not save the watch' } }
  858. return withRows == true ? { ok = true rows = buildRows(&show, &uid, collapsed) } : { ok = true }
  859. }
  860. static showToggleMovieOf = (slug, uid) => {
  861. show = showBySlug(&slug)
  862. if (show == null || show.type != 'movie') { return { error = 'no such movie' } }
  863. if (uid == null) { return { error = 'you are not signed in' } }
  864. if (adultHiddenFor(&show, &uid)) { return { error = 'no such movie' } }
  865. watched = toggleWatched(&uid, 'movie', &show.id)
  866. if (watched == null) { return { error = 'could not save the watch' } }
  867. return { ok = true watched = watched }
  868. }
  869. static showToggleFollowOf = (slug, uid) => {
  870. show = showBySlug(&slug)
  871. if (show == null) { return { error = 'no such show' } }
  872. if (uid == null) { return { error = 'you are not signed in' } }
  873. // mission SK: an adult title is its followers' only — nobody else may start following it (that opened its page to anyone who
  874. // guessed the slug); a follower may still stop
  875. if (adultHiddenFor(&show, &uid)) { return { error = 'no such show' } }
  876. follow = toggleFollowed(&uid, &show.id)
  877. if (follow == null) { return { error = 'could not save the follow' } }
  878. return { ok = true following = follow }
  879. }

Branches

Latest commits

  • b3d8a80bDP69 brief, RV48 mergedmre
  • ce6d7d32Merge rv48: Hybriel day48mre
  • 3da2ea86RV48: report day48 cold starts, gates and cleanupmre
  • 8d9ecdfeRV48: re-vendor Hybriel set day48 (source b6a8f429, bin 660a9524)mre
  • 4a802ae7status: RV48 runningmre
  • 0a5412b6RV48 brief, day48 outmre
  • 56665efelog: CB69 mergedmre
  • 05448a98Merge cb69-imports: appTitle in a dependency-free topicmre
  • e55b379dKeep shared app title independent of the route import graphmre
  • 9a99659blog: hybriel#334, batch waits for day48mre
  • 85fa6c9blog: CB68 result, CB69 startedmre
  • 2f07c1b7log: DP68 boot gate failed, CB68mre
  • 9652782dlog: HM59 merged, DP68 startedmre
  • 29867a75Merge hm59-logic: tracker#59 page logic moved to libmre
  • f7bfe90bMove remaining page builders into their topicsmre
  • 7c3991f9log: day46 from Antonmre
  • ec54fc35Move show page logic into the shows topicmre
  • c1a8d074log: correct timesmre
  • 5827eba9log: HM57 merged, HM59 startedmre
  • d1a91be9Merge hm57-let: tracker#57 let only for reassigned namesmre