gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit074a7418074a7418log: #62 assigned to Tracker; pending rulemre074a7418/lib/people.hl

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

Branches

Latest commits

  • 074a7418log: #62 assigned to Tracker; pending rulemre
  • 06f6ae8fHM62 report: mpackdb index gapmre
  • 86fe5430log: HM62 startedmre
  • 755307bbmission HM62mre
  • 4b2f2995HM61 report: tracker#61 packed people ordermre
  • 48faa84flog: #60 deploy startedmre
  • 90734c6cMerge branch 'hm60-shortids'mre
  • e0db0d1bHM60 report: tracker#60 packed short-ID ownersmre
  • 3c79b576Pack short-ID ownership into byte buffersmre
  • e822524bstatus wordingmre
  • 1c7f0480log: HM60/HM61 startedmre
  • 2841d215missions HM60 HM61mre
  • 289c6ce4HM1 report: heap object breakdownmre
  • 2e7d6257log: HM1 startedmre
  • 2f790465mission HM1: heap object breakdownmre
  • a18957falog: evening re-measure after CBmre
  • aac9a98dlog: evening re-measure startmre
  • 45163bd4log: person/tmdb error hypothesismre
  • cb38de2blog: swap 503 causemre
  • fd10c3d5log: CB livemre