gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit833dcfc9833dcfc9Merge hm52-search: report only, tracker#52 blocked by framework gapmre833dcfc9/lib/people.hl

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

Branches

Latest commits

  • 833dcfc9Merge hm52-search: report only, tracker#52 blocked by framework gapmre
  • 73010cc0HM52: report replace-navigation search draft regressionmre
  • 1742e92bstatus: DP64 and HM52 runningmre
  • 29ad5b58log: #64 merged, DP64 and HM52 startedmre
  • fafddbf9Merge hm64-catalog: tracker#64 catalog from packed entriesmre
  • b2e2206dlog: #63 livemre
  • 5831e0e0log: HM64 donemre
  • 4042b923Flatten catalog membership rows into paired slotsmre
  • ea8a759elog: #61 #62 live, DP63 and HM64 startedmre
  • 40439456Merge hm63-searchtext: tracker#63 packed search textmre
  • b7e6b48ePack normalized search text behind numeric offsetsmre
  • b35f53e1log: DP62 stale runtime decisionmre
  • f9593602log: Apollo deploy rule correctionmre
  • 3c95f7f3log: DP62 and HM63 startedmre
  • 9c4397c9mission HM63mre
  • 8dfe42c8mission DP62mre
  • e347fef4Merge rv44: tracker#61 #62 on Hybriel day44mre
  • 8274bcf1log: RV44 done, deploy held for the usage windowmre
  • 1ef7a3b1RV44: report day44 gates and migration/restart proofsmre
  • a5f62f6cRV44: re-vendor Hybriel set day44 (source 222edef7, bin 4f0f263e)mre