gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita4d1a7d2a4d1a7d2|||PR records: later steps checked, branch auditTrackera4d1a7d2/lib/people.hl

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

Branches

Latest commits

  • a4d1a7d2|||PR records: later steps checked, branch auditTracker
  • e070e16fMerge branch 'records-dp75' into mainTracker
  • 642b4fa8|||PR records: DP75 day62 live, AP62 briefTracker
  • bfc4ea4dMerge branch 'ap62' into mainTracker
  • 2c95ac46|||PR AP62: re-vendor Hybriel set day62 (source 70341ad2, bin a54f5f08)Tracker
  • b9c7c3c8Merge branch 'records-dp74' into mainTracker
  • 85cfb4ae|||PR records: AP61 day61, DP74 liveTracker
  • b1496147Merge branch 'ap61' into mainTracker
  • 2047955bMerge branch 'u12-gateports' into mainTracker
  • c8da40f3|||PR AP61: re-vendor Hybriel set day61 (source a05af47c, bin a11042e5)Tracker
  • 4e018678|||PR deploy.sh: gates use Tracker's ports 8716-8719 and LC_ALL=C; README: 2 backups keptTracker
  • 0b86324aMerge branch 'records-dp73' into mainTracker
  • 9ce5f59b|||PR records: DP73 live 613ae0e; deploy.sh keeps 2 backupsTracker
  • 613ae0ecMerge branch 'bs3' into mainTracker
  • 1383264b|||PR BS3: keep shared synchronous sorting fastTracker
  • 63e5ba1a|||PR BS3: guard boot imports and share resumable sort buffersTracker
  • 310613f1Merge branch 'records-dp72' into mainTracker
  • 6f7b61ba|||PR records: deploy-swap fix live, Kunibert findingsTracker
  • c41587d2Merge branch 'bs2' into mainTracker
  • 0dd538a6|||PR BS2: finish the boot index in slices so a booting instance keeps answeringTracker