gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2f986ca32f986ca3Log: RT50 passmre2f986ca3/lib/people.hl

33.7 KB

  1. // lib/people.hl — THE PERSON PAGE's data (tracker.worldapi.org#16, components/person.hl `/person/<slug>`): a person by slug,
  2. // their facts and filmography, and the ONE-TIME fetch of their whole filmography from TMDB on the first visit. Creator:
  3. // "the movies come from artist scrolls. when one clicks on an artist that has no dataset yet the old version fetched that
  4. // artist and its entire bibilogrqphy so its profile was complete".
  5. //
  6. // personBySlug(slug) the person (slug = `urlSegment`) — a native urlSegment index lookup
  7. // personInfoOf(p) name, photo URL, born/died lines, bio
  8. // filmographyOf(p) their credits (`p.shows`): poster, title, year, role, kind — newest first, adult titles hidden
  9. // personFillStep(id) ONE step of the fetch, called again and again by the page until it answers `done`:
  10. // 1st call: GET <TMDB>/person/<tmdbId>?append_to_response=combined_credits (ONE request: details +
  11. // every cast/crew credit) + the photo (w185, like the posters); the person's facts are updated;
  12. // every next call stores the next `fillBatch` titles; the last one links the credits and marks
  13. // the person complete (`filmographyAt`, ms). hl:web serves one request at a time — between two
  14. // steps every other request is served, so a person with 300 credits never holds the server.
  15. // peoplePage(page) /people (tracker#37): everyone, the one updated last first, 24 per page — a view built once at boot
  16. // personPhotoOf(p) the photo of a /people tile and a search row: our file, else TMDB's (`tmdbProfile`), else the placeholder
  17. //
  18. // COMPLETE = `filmographyAt` set: never fetched again (the daily sync may refresh followed people later — not built).
  19. // Migrated people are NOT complete (153 of them carry the old tracker's credits — kept, the fetch adds the rest).
  20. // A title we don't have → a MINIMAL show record (title, year, type, tmdbId, `adult`, overview, genres by TMDB id, language;
  21. // no seasons, no poster file; `minimal = true` — details.hl completes it when it is opened or by the repair job, tracker#26), shaped like search.hl importTitle's
  22. // (`oldId tmdb-<tv|movie>-<id>`, a free slug), indexed for the search and put into the public lists (catalog.hl).
  23. // The person's credits (`shows`, the migrated field): [{ show, character, posterPath, adult }] — `character` is the role
  24. // text (the characters, then crew jobs like "Director", " / " between them); `posterPath` = TMDB's, so the page can show
  25. // TMDB's small poster (w92, like search's web rows) until we have the file. ADULT (TMDB's flag, mission 054): a row is
  26. // shown only for a PUBLIC title (shows.hl `isPublicTitle`: `adult == false`, unknown hidden like the public lists) whose
  27. // credit is not adult either (mission 056 merge).
  28. // ONE PROCESS PER STORAGE (hybriel#21); new rows get self-assigned 16-hex ids (hybriel#113), like sync.hl.
  29. import { now } from 'hl:time'
  30. import { warm, warmBlocked } from './warm.hl'
  31. import { fetch } from 'hl:fetch'
  32. import { writeFile, mkDir, exists } from 'hl:fs'
  33. import { profilesDir, newId, textOr, listOr, sortDesc, envOr } from './util.hl'
  34. import { allowHit } from './security.hl'
  35. import { personsTable, showsTable, genresTable, showById, showYear, posterUrlOf, posterUrlOfName, creditRowLive, isPublicTitle, titlePath, typeWordOf, typeClassOf, liveShowOf } from './shows.hl'
  36. import { tmdbGet, tmdbImageBase } from './tmdb.hl'
  37. import { titleIdByTmdb, indexShow, slugOf, indexPerson } from './search.hl'
  38. import { slugBaseOf } from './search-helpers.hl'
  39. import { refreshCatalogShow, pagesOf, pageNumberOf, pageSize } from './catalog.hl'
  40. import { claimShortId } from './shortids.hl'
  41. import { sliceBudgetMs } from './slices.hl'
  42. import { Response } from 'hl:http1'
  43. import { startingUpText } from './warm.hl'
  44. import { notFoundText } from './util.hl'
  45. import { personById } from './shows.hl'
  46. // titles stored per step: at most `fillBatch`, and a step stops when `fillStepMs` are used (SL1: the real titles cost ~6 ms each since the
  47. // lists are changed in place; before they cost 300 ms each and a step of 40 blocked the loop for 10 s)
  48. static fillBatch = 40
  49. static fillStepMs = 40
  50. // ---- the person -------------------------------------------------------------------------------------------------
  51. // Native indexes return matches in storage order. The former maps kept the last
  52. // matching row's ID; fetch that ID afterwards to preserve duplicate-PK behaviour.
  53. static indexedPersonId = (String field, value) => {
  54. let id = null
  55. for (p of personsTable.cursor(field, value)) { id = p.id }
  56. return id
  57. }
  58. static personBySlug = (&slug) => {
  59. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  60. id = indexedPersonId('urlSegment', slug)
  61. return id == null ? null : personsTable.fetch(id)
  62. }
  63. static isComplete = (&p) => { return p.filmographyAt != null }
  64. // the page asks TMDB for this person: not complete yet, and TMDB knows them
  65. static needsFill = (&p) => { return !isComplete(&p) && p.tmdbId != null }
  66. // the photo: /profiles/<oldId>.<ext> (images.hl) — only when the file is there (the migrated `image` = 'jpg'
  67. // of 129 people never came with a file)
  68. static profileName = (&p) => {
  69. if (p.oldId == null || p.image == null || p.image == '') { return null }
  70. return p.oldId + '.' + p.image
  71. }
  72. static photoUrlOf = (&p) => {
  73. name = profileName(&p)
  74. return name != null && exists(profilesDir + '/' + name) ? '/profiles/' + name : ''
  75. }
  76. static monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  77. // '1986-03-04' → '4 March 1986'; a bare year or anything else as it is
  78. static dateText = (&d) => {
  79. t = textOr(&d)
  80. if (t == null) { return null }
  81. if (t.length < 10) { return t }
  82. m = toNumber(t.slice(5, 7))
  83. day = toNumber(t.slice(8, 10))
  84. if (m == null || day == null || m < 1 || m > 12) { return t }
  85. return day + ' ' + monthNames[m - 1] + ' ' + t.slice(0, 4)
  86. }
  87. // { name, photoUrl, born, died, bio } — every field a plain string ('' = none)
  88. static personInfoOf = (&p) => {
  89. born = dateText(&p.birthDate)
  90. place = textOr(&p.birthPlace)
  91. let bornText = ''
  92. if (born != null && place != null) { bornText = 'Born ' + born + ' in ' + place } else if (born != null) { bornText = 'Born ' + born } else if (place != null) { bornText = 'Born in ' + place }
  93. died = dateText(&p.deathDate)
  94. return { name = p.name != null ? p.name : '' photoUrl = photoUrlOf(&p) born = bornText died = died != null ? 'Died ' + died : ''
  95. bio = textOr(&p.biography) != null ? p.biography : '' }
  96. }
  97. // ---- the filmography --------------------------------------------------------------------------------------------
  98. // the credits, one row per title (a title twice — the migrated credit and TMDB's — is ONE row, roles merged), newest
  99. // first by the title's release ('YYYY-MM-DD', else its year), undated last; only public titles (no adult/unknown)
  100. static filmographyOf = (&p) => {
  101. byShow = {}
  102. order = []
  103. for (c of listOr(&p.shows)) {
  104. if (c != null && c.show != null) {
  105. role = textOr(&c.character)
  106. prev = byShow[c.show]
  107. if (prev == null) {
  108. byShow[c.show] = { role = role != null ? role : '' posterPath = textOr(&c.posterPath) adult = c.adult == true }
  109. order.push(c.show)
  110. } else {
  111. x = prev
  112. if (role != null && !(' / ' + x.role + ' / ').includes(' / ' + role + ' / ')) { x.role = x.role == '' ? role : x.role + ' / ' + role }
  113. if (x.posterPath == null) { x.posterPath = textOr(&c.posterPath) }
  114. if (c.adult == true) { x.adult = true }
  115. byShow[c.show] = x
  116. }
  117. }
  118. }
  119. list = []
  120. listed = {}
  121. for (sid of order) {
  122. let c = byShow[sid]
  123. // tracker#31: a credit on a merged tombstone is the keeper's (merge.hl repoints them; a keeper listed once)
  124. s = creditRowLive(&sid)
  125. if (s != null && s.public && !c.adult && listed[s.id] != true) {
  126. listed[s.id] = true
  127. release = s.release
  128. key = release != null && release.length >= 4 ? release : s.year
  129. let poster = posterUrlOfName(&s.posterName)
  130. if (poster == '/posters/none' && c.posterPath != null) { poster = tmdbImageBase + '/w92' + c.posterPath }
  131. list.push({ key = key id = s.id title = s.title year = s.year href = s.href posterUrl = poster
  132. role = c.role typeLabel = s.typeLabel typeClass = s.typeClass })
  133. }
  134. }
  135. out = []
  136. undated = []
  137. for (r of sortDesc(&list)) { if (r.key == '') { undated.push(r) } else { out.push(r) } }
  138. for (r of undated) { out.push(r) }
  139. return out
  140. }
  141. // ---- the fetch ------------------------------------------------------------------------------------------------
  142. // person id → { items, pos, credits, added, requests, started, steps } while a fetch is under way (in memory: a restart
  143. // loses it — the titles stored so far are found again by TMDB id, nothing is duplicated)
  144. static jobs = {}
  145. // TMDB genre id → ours (our genres carry TMDB's id)
  146. static genreMap = { built = false ids = {} }
  147. static genreIdsOfTmdb = (&tmdbIds) => {
  148. if (!genreMap.built) {
  149. m = {}
  150. for (g of genresTable.find(null, null)) { if (g.tmdbId != null) { m['' + g.tmdbId] = g.id } }
  151. genreMap.ids = m
  152. genreMap.built = true
  153. }
  154. out = []
  155. for (t of listOr(&tmdbIds)) {
  156. id = genreMap.ids['' + t]
  157. if (id != null && !out.includes(id)) { out.push(id) }
  158. }
  159. return out
  160. }
  161. // TMDB's combined_credits → one item per title (cast AND crew of the same title merged), TV + movies only
  162. static creditItems = (&cc) => {
  163. byKey = {}
  164. order = []
  165. all = []
  166. if (cc != null) {
  167. for (c of listOr(&cc.cast)) { all.push({ credit = c role = textOr(&c.character) }) }
  168. for (c of listOr(&cc.crew)) { all.push({ credit = c role = textOr(&c.job) }) }
  169. }
  170. for (a of all) {
  171. let c = a.credit
  172. kind = c.media_type
  173. if ((kind == 'tv' || kind == 'movie') && c.id != null && hlTypeName(c.id) == 'Number') {
  174. let k = kind + ':' + c.id
  175. known = byKey[k]
  176. if (known == null) {
  177. name = kind == 'tv' ? textOr(&c.name) : textOr(&c.title)
  178. if (name != null) {
  179. byKey[k] = { kind = kind tmdbId = c.id title = name release = textOr(kind == 'tv' ? c.first_air_date : c.release_date)
  180. overview = textOr(&c.overview) language = textOr(&c.original_language) genreIds = listOr(&c.genre_ids)
  181. posterPath = textOr(&c.poster_path) adult = c.adult == true role = a.role != null ? a.role : '' }
  182. order.push(k)
  183. }
  184. } else if (a.role != null && !(' / ' + known.role + ' / ').includes(' / ' + a.role + ' / ')) {
  185. x = known
  186. x.role = x.role == '' ? a.role : x.role + ' / ' + a.role
  187. byKey[k] = x
  188. }
  189. }
  190. }
  191. out = []
  192. for (k of order) { out.push(byKey[k]) }
  193. return out
  194. }
  195. // the photo: w185 → storage/mpackdb/profiles/<oldId>.<ext> — { requests, image, tmdbProfile, failed }
  196. static syncProfile = (&p, profilePath) => {
  197. out = { requests = 0 image = p.image tmdbProfile = p.tmdbProfile failed = null }
  198. if (textOr(&profilePath) == null || p.oldId == null) { return out }
  199. parts = profilePath.split('.')
  200. ext = parts[parts.length - 1].toLowerCase()
  201. if (ext != 'jpg' && ext != 'jpeg' && ext != 'png' && ext != 'webp') { return out }
  202. file = profilesDir + '/' + p.oldId + '.' + ext
  203. if (exists(file) && p.tmdbProfile == profilePath && p.image == ext) { return out }
  204. out.requests = 1
  205. r = fetch(tmdbImageBase + '/w185' + profilePath, { headers = { 'user-agent' = 'tracker.worldapi.org (person page)' } timeoutMs = 20000 })
  206. if (r == null || r.status != 200 || r.body == null || r.body.length == 0) {
  207. out.failed = 'photo ' + profilePath + ': ' + (r == null ? 'no answer' : 'HTTP ' + r.status)
  208. return out
  209. }
  210. mkDir(profilesDir)
  211. writeFile(file, toBytes(r.body), 420)
  212. out.image = ext
  213. out.tmdbProfile = profilePath
  214. return out
  215. }
  216. // step 1: TMDB's person + credits; the facts (a TMDB value that is empty never overwrites ours) and the photo
  217. static startFill = (p) => {
  218. t0 = now()
  219. d = tmdbGet('/person/' + p.tmdbId + '?append_to_response=combined_credits')
  220. if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }
  221. items = creditItems(&d.combined_credits)
  222. photo = syncProfile(&p, d.profile_path)
  223. x = p
  224. if (textOr(&d.biography) != null) { x.biography = d.biography }
  225. if (textOr(&d.birthday) != null) { x.birthDate = d.birthday }
  226. if (textOr(&d.deathday) != null) { x.deathDate = d.deathday }
  227. if (textOr(&d.place_of_birth) != null) { x.birthPlace = d.place_of_birth }
  228. if (textOr(&x.imdbId) == null && textOr(&d.imdb_id) != null) { x.imdbId = d.imdb_id }
  229. if (d.adult != null) { x.adult = d.adult == true }
  230. x.image = photo.image
  231. x.tmdbProfile = photo.tmdbProfile
  232. x.updatedAt = now()
  233. if (personsTable.update(x.id, x) == null) { return { error = 'could not store the person: ' + personsTable.lastError() } }
  234. personTouched(&x.id)
  235. if (photo.failed != null) { console.log('person fill: ' + p.name + ': ' + photo.failed) }
  236. jobs[p.id] = { items = items pos = 0 credits = [] added = 0 requests = 1 + photo.requests started = t0 steps = 1 tmdbMs = now() - t0 }
  237. return { done = false pos = 0 total = items.length }
  238. }
  239. // a title we don't have: the minimal record (shape: search.hl importTitle) → its id, or null
  240. static addMinimalTitle = (&cr, &pid, pname) => {
  241. kindType = cr.kind == 'tv' ? 'series' : 'movie'
  242. rel = cr.release
  243. yr = rel != null && rel.length >= 4 ? toNumber(rel.slice(0, 4)) : null
  244. slug = slugOf(&cr.title, &cr.tmdbId)
  245. record = {
  246. id = newId() title = cr.title summary = null tmdbSummary = cr.overview tmdbId = cr.tmdbId
  247. language = cr.language type = kindType release = rel year = yr image = null
  248. urlSegment = slug episodesCount = null homepage = null imdbId = null seasonsCount = null
  249. status = null tagline = null tvdbId = null tvmzId = null genres = genreIdsOfTmdb(&cr.genreIds)
  250. cast = [{ person = pid character = cr.role actor = pname }] seasons = [] oldId = 'tmdb-' + cr.kind + '-' + cr.tmdbId
  251. adult = cr.adult imported = now() minimal = true
  252. }
  253. // mission 060: its short id (shortids.hl — unique across shows and persons)
  254. record.shortId = claimShortId('show', record.id, &record.oldId)
  255. if (showsTable.put(record) == null) {
  256. console.log('person fill: "' + cr.title + '" not stored: ' + showsTable.lastError())
  257. return null
  258. }
  259. indexShow(&record)
  260. refreshCatalogShow(&record.id, true)
  261. return record.id
  262. }
  263. // every next step: the next `fillBatch` titles; the last one links the credits and marks the person complete
  264. static fillStep = (p, jobIn) => {
  265. job = jobIn
  266. total = job.items.length
  267. let end = job.pos + fillBatch
  268. if (end > total) { end = total }
  269. credits = job.credits
  270. let added = job.added
  271. pid = p.id
  272. pname = p.name
  273. let i = job.pos
  274. t0 = now()
  275. while (i < end) {
  276. if (i > job.pos && now() - t0 >= fillStepMs) { end = i break }
  277. item = job.items[i]
  278. let sid = titleIdByTmdb(item.kind == 'tv' ? 'series' : 'movie', &item.tmdbId)
  279. if (sid == null) {
  280. sid = addMinimalTitle(&item, &pid, pname)
  281. if (sid != null) { added = added + 1 }
  282. }
  283. if (sid != null) { credits.push({ show = sid character = item.role posterPath = item.posterPath adult = item.adult }) }
  284. i = i + 1
  285. }
  286. job.pos = end
  287. job.credits = credits
  288. job.added = added
  289. job.steps = job.steps + 1
  290. jobs[pid] = job
  291. if (end < total) { return { done = false pos = end total = total } }
  292. // done: the credits (+ the migrated ones TMDB no longer lists), complete
  293. have = {}
  294. all = []
  295. for (c of credits) { have[c.show] = true all.push(c) }
  296. for (c of listOr(&p.shows)) { if (c != null && c.show != null && have[c.show] != true) { all.push(c) } }
  297. x = p
  298. x.shows = all
  299. x.filmographyAt = now()
  300. x.updatedAt = x.filmographyAt
  301. if (personsTable.update(x.id, x) == null) { return { error = 'could not store the filmography: ' + personsTable.lastError() } }
  302. personTouched(&x.id)
  303. // SL1: both tables are written by persistFillsTick (one table per loop turn, jobs.hl) — not here, 150 + 280 ms in this step
  304. fillDirty.shows = true
  305. fillDirty.persons = true
  306. jobs[pid] = null
  307. console.log('person fill: ' + pname + ' (tmdb ' + p.tmdbId + ') credits=' + total + ' added=' + added + ' requests=' + job.requests + ' steps=' + job.steps + ' tmdbMs=' + job.tmdbMs + ' ms=' + (now() - job.started))
  308. return { done = true pos = total total = total added = added }
  309. }
  310. // the tables a finished fill wrote and that are not on disk yet; persistFillsTick (a clock in jobs.hl) writes ONE table per turn,
  311. // the titles first (a person is complete only when its titles are stored: a stop in between leaves it incomplete, never dangling)
  312. static fillDirty = { shows = false persons = false }
  313. static persistFillsTick = () => {
  314. if (fillDirty.shows) {
  315. fillDirty.shows = false
  316. showsTable.persist()
  317. return true
  318. }
  319. if (fillDirty.persons) {
  320. fillDirty.persons = false
  321. personsTable.persist()
  322. return true
  323. }
  324. return false
  325. }
  326. // one step for the person with this id: { done, pos, total } or { error }
  327. static personFillStep = (&personId) => {
  328. if (warmBlocked()) { return { error = 'tracker is starting up, try again in a minute' } }
  329. p = personsTable.fetch(personId)
  330. if (p == null) { return { error = 'no such person' } }
  331. if (isComplete(&p)) { return { done = true } }
  332. if (p.tmdbId == null) { return { error = 'TMDB does not know this person' } }
  333. job = jobs[personId]
  334. if (job == null) { return startFill(p) }
  335. return fillStep(p, job)
  336. }
  337. // ---- people from a title's cast (tracker#26, details.hl completeStep) ------------------------------------------
  338. // Person lookup indexes are declared on personsTable in shows.hl. Nonunique
  339. // indexes retain migrated duplicates; creation still chooses the first free slug.
  340. static markPeopleIndexesBuilt = (&castPhotos) => {
  341. peopleView.castProfiles = castPhotos
  342. return true
  343. }
  344. static personIdByTmdb = (&tmdbId) => {
  345. return indexedPersonId('tmdbId', '' + tmdbId)
  346. }
  347. // a free person slug: "Maya-Rudolph", taken → "-2", … (the migrated people's form)
  348. static personSlugOf = (&name, &tmdbId) => {
  349. base = slugBaseOf(&name, 'person-' + tmdbId)
  350. if (indexedPersonId('urlSegment', base) == null) { return base }
  351. let n = 2
  352. while (indexedPersonId('urlSegment', base + '-' + n) != null) { n = n + 1 }
  353. return base + '-' + n
  354. }
  355. // how many people castPersonId added since the start (details.hl counts a title's new people by the difference, tracker#28)
  356. static castPeopleAdded = { n = 0 }
  357. static castPeopleCount = () => { return castPeopleAdded.n }
  358. // our person for one cast entry of TMDB ({ tmdbId, name, character, gender, profile }) — the one we have by TMDB id, else a NEW
  359. // person (name, tmdbId, a free slug, this one credit, TMDB's profile path as `tmdbProfile` (tracker#37: the photo of /people and
  360. // the search); not complete: their page fetches the rest on the first visit like any migrated person). Answers the id, or null
  361. // when it could not be stored. Also a CREW person (tracker#28: `character` = the job, "Director").
  362. static castPersonId = (&c, &showId) => {
  363. if (warmBlocked()) { return null }
  364. have = personIdByTmdb(&c.tmdbId)
  365. if (have != null) { return have }
  366. record = { id = newId() name = c.name tmdbId = c.tmdbId urlSegment = personSlugOf(&c.name, &c.tmdbId) oldId = 'tmdb-person-' + c.tmdbId
  367. gender = c.gender image = null tmdbProfile = textOr(&c.profile) adult = false birthDate = null birthPlace = null deathDate = null imdbId = null
  368. shows = showId != null ? [{ show = showId character = c.character }] : [] added = now() }
  369. // mission 062 (tracker#27 for #26/#28): every person the app creates gets its short id at once (shortids.hl)
  370. record.shortId = claimShortId('person', record.id, &record.oldId)
  371. if (personsTable.put(record) == null) {
  372. console.log('details: person "' + c.name + '" not stored: ' + personsTable.lastError())
  373. return null
  374. }
  375. indexPerson(&record)
  376. personTouched(&record.id)
  377. castPeopleAdded.n = castPeopleAdded.n + 1
  378. return record.id
  379. }
  380. // ---- GUEST STARS (mission 062): a series' guests are NOT person records — details.hl stores them on the title ({ tmdbId, actor,
  381. // character, profile, episodes, guest }, `person` only when we have them already). 160k people (most of them one-episode guests)
  382. // cost 3.3 GB of RSS at boot (w061). A guest's link is `/person/tmdb/<tmdbId>?show=<show id>` (project.hl guestRoute): the FIRST
  383. // open creates the person (name + role from that title's guest entry; without one — an old link — TMDB's /person/<id>), with its
  384. // short id, then the person page fills it like any other.
  385. static guestFallbackPerHour = toNumber(envOr('TRACKER_GUEST_FALLBACK_PER_HOUR', '20'))
  386. static guestOf = (&showId, &tmdbId) => {
  387. s = showId != null && hlTypeName(showId) == 'String' && showId != '' ? showsTable.fetch(showId) : null
  388. if (s == null) { return null }
  389. for (c of listOr(&s.cast)) { if (c != null && c.tmdbId == tmdbId && textOr(&c.actor) != null) { return c } }
  390. return null
  391. }
  392. // our person for this TMDB person (created now when we have none) → { id, created } or { error }
  393. static guestPersonId = (tmdbId, showId) => {
  394. if (warmBlocked()) { return { error = 'tracker is starting up, try again in a minute' } }
  395. have = personIdByTmdb(&tmdbId)
  396. if (have != null) { return { id = have created = false } }
  397. g = guestOf(&showId, &tmdbId)
  398. let c = null
  399. let inShow = null
  400. if (g != null) {
  401. c = { tmdbId = tmdbId name = g.actor character = g.character gender = null }
  402. inShow = showId
  403. } else {
  404. // mission SK: this branch (an old link without ?show=) is an anonymous GET that makes a TMDB request and may store a person —
  405. // at most `guestFallbackPerHour` of them an hour in all, so it cannot be used to fill the table or burn the TMDB quota
  406. if (!allowHit('guest-tmdb', 'all', &guestFallbackPerHour, 3600000)) { return { error = 'too many new people from TMDB just now, try again later' } }
  407. d = tmdbGet('/person/' + tmdbId)
  408. if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }
  409. if (textOr(&d.name) == null || d.adult == true) { return { error = 'no such person' } }
  410. c = { tmdbId = tmdbId name = d.name character = null gender = d.gender }
  411. }
  412. pid = castPersonId(&c, &inShow)
  413. if (pid == null) { return { error = 'could not store the person' } }
  414. personsTable.persist()
  415. console.log('guest opened: ' + c.name + ' (tmdb ' + tmdbId + ') → new person ' + pid + (inShow != null ? ' from show ' + inShow : ' from TMDB'))
  416. return { id = pid created = true }
  417. }
  418. // ---- /people (tracker#37, mission 032): everyone we have, the one updated last first ------------------------------------------
  419. // Creator: "/people just lists persons by last one updated with poster name and pagination". LAST UPDATED = the newest of
  420. // `updatedAt` (stamped by the person page's fetch, startFill / fillStep), `filmographyAt` and `added` (a person the app created);
  421. // the migrated people with none of them come last (newest stored first). No adult filter (tracker#32's /people had none either).
  422. // A CACHED VIEW like tracker#30's list caches (mission 025): the order is built ONCE at boot (project.hl warmPeopleView: one pass
  423. // over the people + one sort, and the cast photos below — 105k people, 3–4 s on the live copy), a page only decodes its 24 ids and
  424. // fetches those people (~15 ms server time, any page). Kept current without a rebuild: every person the app creates or updates is
  425. // `personTouched` → `recent`; the next page read moves them to the front (one pass over the ids, ~50 ms, only after a change).
  426. static peopleView = { built = false ids = toBytes(0) offsets = toBytes(4) count = 0 recent = [] castProfiles = 0 }
  427. static updatedKeyOf = (&p) => {
  428. let k = p.updatedAt != null ? p.updatedAt : 0
  429. if (p.filmographyAt != null && p.filmographyAt > k) { k = p.filmographyAt }
  430. if (p.added != null && p.added > k) { k = p.added }
  431. return k
  432. }
  433. // one person's entry of the view's list (table order; bootscan.hl's person pass collects them) — mission T17: two parallel arrays (the
  434. // id, the key) instead of an object { id, key } per person (680 K people: 3 live objects each, every collection marks them)
  435. static viewIds = []
  436. static viewKeys = []
  437. static noteViewRow = (&p) => {
  438. viewIds.push(p.id)
  439. viewKeys.push(updatedKeyOf(&p))
  440. return null
  441. }
  442. static warmPeopleView = () => {
  443. if (peopleView.built) { return peopleView.count }
  444. peopleView.castProfiles = castProfilesOf()
  445. for (p of personsTable.iterate(null, null)) { noteViewRow(&p) }
  446. return finishPeopleView()
  447. }
  448. static finishPeopleView = () => {
  449. // newest stored first: the table is in the order the people were stored, so the list is nearly sorted already (util.hl sortDesc
  450. // keeps runs) and equal keys (the migrated people: 0) end newest stored first. The people with a key above 0 (touched since the
  451. // migration — few) are sorted; sortDesc is stable, so the zeros after them stay in the same newest-stored-first order as when
  452. // everything was sorted together. (A key that is not a plain number >= 0 never happened: then everything is sorted, as before.)
  453. positive = []
  454. zeros = []
  455. let odd = false
  456. let i = viewIds.length - 1
  457. while (i >= 0) {
  458. k = viewKeys[i]
  459. if (hlTypeName(k) != 'Number') { odd = true }
  460. else if (k > 0) { positive.push({ id = viewIds[i] key = k }) }
  461. else if (k == 0) { zeros.push(viewIds[i]) }
  462. else { odd = true }
  463. i = i - 1
  464. }
  465. ids = toBytes(0)
  466. offsets = toBytes(4)
  467. if (odd) {
  468. newestFirst = []
  469. let j = viewIds.length - 1
  470. while (j >= 0) { newestFirst.push({ id = viewIds[j] key = viewKeys[j] }) j = j - 1 }
  471. for (x of sortDesc(&newestFirst)) { appendPeopleId(&ids, &offsets, &x.id) }
  472. } else {
  473. for (x of sortDesc(&positive)) { appendPeopleId(&ids, &offsets, &x.id) }
  474. for (id of zeros) { appendPeopleId(&ids, &offsets, &id) }
  475. }
  476. peopleView.ids = ids
  477. peopleView.offsets = offsets
  478. peopleView.count = viewIds.length
  479. peopleView.built = true
  480. // The scan buffers are finished: release their backing arrays as well as their entries.
  481. viewIds = []
  482. viewKeys = []
  483. return peopleView.count
  484. }
  485. // a person was created or updated: first in /people from the next page read on
  486. static personTouched = (&id) => {
  487. if (peopleView.built && id != null) { peopleView.recent.push(id) }
  488. return null
  489. }
  490. // Packed UTF-8 IDs plus little-endian 32-bit end offsets. The initial offset is zero.
  491. // IDs keep their exact spelling and length; no storage key or uniqueness rule changes.
  492. static appendPeopleId = (&ids, &offsets, &id) => {
  493. ids.append(toBytes(id))
  494. n = ids.length
  495. offsets.append(n % 256)
  496. offsets.append((n >> 8) & 255)
  497. offsets.append((n >> 16) & 255)
  498. offsets.append((n >> 24) & 255)
  499. return null
  500. }
  501. static peopleOffset = (&offsets, Number pos) => {
  502. i = pos * 4
  503. return offsets[i] + offsets[i + 1] * 256 + offsets[i + 2] * 65536 + offsets[i + 3] * 16777216
  504. }
  505. static packedPeopleId = (&ids, &offsets, Number pos) => {
  506. return ids.text(peopleOffset(&offsets, pos), peopleOffset(&offsets, pos + 1))
  507. }
  508. static peopleViewCurrent = () => {
  509. if (!peopleView.built && !warm.running) { warmPeopleView() }
  510. if (peopleView.recent.length == 0) { return true }
  511. seen = {}
  512. out = toBytes(0)
  513. offsets = toBytes(4)
  514. let i = peopleView.recent.length - 1
  515. while (i >= 0) {
  516. id = peopleView.recent[i]
  517. if (seen[id] != true) { seen[id] = true appendPeopleId(&out, &offsets, &id) }
  518. i = i - 1
  519. }
  520. let pos = 0
  521. while (pos < peopleView.count) {
  522. id = packedPeopleId(&peopleView.ids, &peopleView.offsets, pos)
  523. if (seen[id] != true) { appendPeopleId(&out, &offsets, &id) }
  524. pos = pos + 1
  525. }
  526. peopleView.ids = out
  527. peopleView.offsets = offsets
  528. peopleView.count = offsets.length / 4 - 1
  529. peopleView.recent = []
  530. return true
  531. }
  532. static peopleViewStats = () => { return { people = peopleView.count castProfiles = peopleView.castProfiles } }
  533. static peopleCount = () => {
  534. peopleViewCurrent()
  535. return peopleView.count
  536. }
  537. // a person's photo for a tile or a search row: our file (photoUrlOf), else TMDB's (`tmdbProfile`, w185 — like the filmography's
  538. // TMDB posters), else TMDB's from a title's cast entry (castProfiles), else the placeholder
  539. static personPhotoOf = (&p) => {
  540. local = photoUrlOf(&p)
  541. if (local != '') { return local }
  542. path = textOr(&p.tmdbProfile) != null ? p.tmdbProfile : castProfiles[p.id]
  543. return path != null ? tmdbImageBase + '/w185' + path : '/profiles/none'
  544. }
  545. // person id → TMDB's profile path from a title's cast or crew entry (credits.hl stores `profile` there: cast since tracker#28, crew
  546. // since tracker#37) — for the people the credits job created before castPersonId kept it as `tmdbProfile` (live copy 2026-10-04:
  547. // 51,922 of 105,018 people; the crew entries had none yet). Built at boot with the view (one pass over the titles, ~1–3 s). IN
  548. // MEMORY, not written to the people: 51,907 record updates took 511 s at a start (mission 032, measured on the live copy).
  549. // (Flat static written key by key, like the maps above.)
  550. static castProfiles = {}
  551. // one title's cast and crew photos into the map; how many were new (bootscan.hl's title pass sums them)
  552. static noteCastProfiles = (&s) => {
  553. let n = 0
  554. for (c of listOr(&s.cast)) {
  555. if (c != null && c.person != null && textOr(&c.profile) != null && castProfiles[c.person] == null) {
  556. castProfiles[c.person] = c.profile
  557. n = n + 1
  558. }
  559. }
  560. for (c of listOr(&s.crew)) {
  561. if (c != null && c.person != null && textOr(&c.profile) != null && castProfiles[c.person] == null) {
  562. castProfiles[c.person] = c.profile
  563. n = n + 1
  564. }
  565. }
  566. return n
  567. }
  568. static castProfilesOf = () => {
  569. let n = 0
  570. // iterate, not find: one title decoded at a time
  571. for (s of showsTable.iterate(null, null)) { n = n + noteCastProfiles(&s) }
  572. return n
  573. }
  574. // one page: { page, pages, tiles } — a tile like the title grids' (components/tilelist.hl): photo, name, no year
  575. static peoplePage = (&raw) => {
  576. peopleViewCurrent()
  577. pages = pagesOf(&peopleView.count)
  578. page = pageNumberOf(&raw, &pages)
  579. tiles = []
  580. let pos = (page - 1) * pageSize
  581. while (pos < page * pageSize && pos < peopleView.count) {
  582. id = packedPeopleId(&peopleView.ids, &peopleView.offsets, pos)
  583. pos = pos + 1
  584. p = personsTable.fetch(id)
  585. if (p != null && p.urlSegment != null) {
  586. tiles.push({ href = '/person/' + p.urlSegment posterUrl = personPhotoOf(&p) title = p.name != null ? '' + p.name : '' year = '' })
  587. }
  588. }
  589. return { page = page pages = pages tiles = tiles }
  590. }
  591. // ---- THE PHOTO BACKFILL (mission 032, for tracker#37's /people) ----------------------------------------------------------------
  592. // The people the credits job created are mostly CREW with no photo source at all (live copy 2026-10-04: /people pages 1–3 = 72 of
  593. // 72) — one TMDB request per person (`GET /person/<tmdbId>`, ≤ 40 / 10 s, jobs.hl `photoTick`, the last start job) stores TMDB's
  594. // `profile_path` as `tmdbProfile` (shown from TMDB w185 like the cast photos, no file downloaded); TMDB has none → `photoCheck`
  595. // (never asked again), 404 the same. In /people's order (the one updated last first): page 1 is filled first. Not an update of
  596. // the person (`updatedAt` untouched). Resumes after a restart (the queue = who still has no photo source and no check).
  597. static needsPhoto = (&p) => {
  598. return p.tmdbId != null && p.photoCheck == null && textOr(&p.tmdbProfile) == null && castProfiles[p.id] == null && photoUrlOf(&p) == ''
  599. }
  600. // mission 046: the queue is built in SLICES (lib/slices.hl's idea, ids only): the people view's packed IDs (already in /people's order, in RAM) is
  601. // walked from a cursor, a tick fetches rows until its time budget (sliceBudgetMs) is spent — the old one-shot loop did ~621 K fetches in
  602. // ONE tick. Same queue, same order (the view's order); the view is snapshotted at the start (people added while it runs are the next start's).
  603. static photoQueueStart = () => {
  604. peopleViewCurrent()
  605. return { ids = peopleView.ids offsets = peopleView.offsets count = peopleView.count pos = 0 out = [] ms = 0 steps = 0 skipped = 0 }
  606. }
  607. // true when the whole list is done
  608. static photoQueueStep = (&c) => {
  609. t0 = now()
  610. n = c.count
  611. while (c.pos < n) {
  612. id = packedPeopleId(&c.ids, &c.offsets, c.pos)
  613. c.pos = c.pos + 1
  614. p = personsTable.fetch(id)
  615. // the damaged persons index of the real data: fetch() can answer a Number (mission 045, slices.hl): skipped + counted, as sliceNext does
  616. if (p != null && hlTypeName(p) != 'Hybrid') { c.skipped = c.skipped + 1 }
  617. else if (p != null && needsPhoto(&p)) { c.out.push(id) }
  618. if (c.pos % 64 == 0 && now() - t0 >= sliceBudgetMs) { break }
  619. }
  620. c.steps = c.steps + 1
  621. c.ms = c.ms + (now() - t0)
  622. return c.pos >= n
  623. }
  624. // ONE person → { requests, found (a photo stored), errors, error, retry (a passing failure: ask again later) }
  625. static photoStep = (&personId) => {
  626. out = { requests = 0 found = false errors = 0 error = '' retry = false }
  627. p = personsTable.fetch(personId)
  628. if (p == null || !needsPhoto(&p)) { return out }
  629. out.requests = 1
  630. d = tmdbGet('/person/' + p.tmdbId)
  631. x = p
  632. if (d.failed != null) {
  633. out.errors = 1
  634. out.error = p.name + ': ' + d.failed
  635. if (d.status != 404) { out.retry = true return out }
  636. x.photoCheck = 'TMDB 404'
  637. } else if (textOr(&d.profile_path) != null) {
  638. x.tmdbProfile = d.profile_path
  639. out.found = true
  640. } else { x.photoCheck = 'TMDB has none' }
  641. if (personsTable.update(x.id, x) == null) { out.errors = out.errors + 1 out.error = p.name + ': not stored: ' + personsTable.lastError() }
  642. return out
  643. }
  644. static persistPhotos = () => {
  645. personsTable.persist()
  646. return true
  647. }
  648. static guestRoute = (&route, &req) => {
  649. t = route.params != null ? route.params.tmdb : null
  650. if (warmBlocked()) { return startingUpText() }
  651. tmdbId = t != null && hlTypeName(t) == 'String' && t.length <= 10 ? toNumber(t) : null
  652. if (tmdbId == null || tmdbId < 1) { return notFoundText('not found') }
  653. q = req.query != null ? req.query : {}
  654. r = guestPersonId(tmdbId, q.show)
  655. p = r.id != null ? personById(&r.id) : null
  656. if (p == null || p.urlSegment == null) { return notFoundText('not found: ' + (r.error != null ? r.error : 'no such person')) }
  657. return new Response('see /person/' + p.urlSegment, { status = 302 headers = { 'Location' = '/person/' + p.urlSegment 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })
  658. }
  659. // tracker#59: person page rows.
  660. static pageOf = (&slug) => {
  661. p = personBySlug(&slug)
  662. if (p == null) { return { found = false name = '' photoUrl = '' born = '' died = '' bio = '' rows = [] loading = false shortId = '' } }
  663. info = personInfoOf(&p)
  664. return { found = true name = info.name photoUrl = info.photoUrl born = info.born died = info.died bio = info.bio
  665. rows = filmographyOf(&p) loading = needsFill(&p) shortId = p.shortId != null ? '' + p.shortId : '' }
  666. }

Branches

Latest commits

  • 2f986ca3Log: RT50 passmre
  • 1c4715a4RT50 mission: day50 repro retestmre
  • 57d1c0dcLog: day50 retest requestmre
  • 60b1f419Log: Anton #336 result, wake checkmre
  • 919a18aalog: scratchmre
  • 6b504440status tidymre
  • 9332bd10log: DP70 livemre
  • be11daa0DP70 brief fixmre
  • 886a7028DP70 brief, HM67 mergedmre
  • b41cdd6dMerge hm67-searchids: packed search IDsmre
  • 385904eaReport HM67 matched heap measurements and gate proofmre
  • e5c9b659Pack retained search IDs into UTF-8 bytesmre
  • 62a5f6c7HM67 brief, HM66 mergedmre
  • b32b8440Merge hm66-catalogindex: packed catalog indexmre
  • 2db0f7adReport HM66 heap measurements and validationmre
  • 6ce15623Pack catalog lists and membership maps in UTF-8 bytesmre
  • 71134e21HM66 briefmre
  • ed4cbab2status timemre
  • e982c26dlog: HM65 mergedmre
  • 6e72f9d1Merge hm65-fields: episode boot scan reads three fieldsmre