gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb9e841a7b9e841a7Merge branch 'sy-sync'mreb9e841a7/lib/people.hl

30.8 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 (real data: see STATUS.md ticket #16 for the per-step time)
  43. static fillBatch = 40
  44. // ---- the person -------------------------------------------------------------------------------------------------
  45. static slugIndex = { built = false ids = {} }
  46. // mission 043: one person into the slug map IN PLACE (bootscan.hl's person pass, or the lazy scan below — streamed)
  47. static noteSlugOfPerson = (&p) => {
  48. if (p.urlSegment != null) { slugIndex.ids[p.urlSegment] = p.id }
  49. return null
  50. }
  51. static ensureSlugIndex = () => {
  52. if (!slugIndex.built && !warm.running) {
  53. slugIndex.built = true
  54. for (p of personsTable.iterate(null, null)) { noteSlugOfPerson(p) }
  55. }
  56. return true
  57. }
  58. static personBySlug = (&slug) => {
  59. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  60. ensureSlugIndex()
  61. id = slugIndex.ids[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. let role = textOr(c.character)
  107. let 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. let 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. let s = creditRowLive(sid)
  126. if (s != null && s.public && !c.adult && listed[s.id] != true) {
  127. listed[s.id] = true
  128. let release = s.release
  129. let 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. let 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. let kind = c.media_type
  174. if ((kind == 'tv' || kind == 'movie') && c.id != null && hlTypeName(c.id) == 'Number') {
  175. let k = kind + ':' + c.id
  176. let known = byKey[k]
  177. if (known == null) {
  178. let 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. let 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)
  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. while (i < end) {
  276. let item = job.items[i]
  277. let sid = titleIdByTmdb(item.kind == 'tv' ? 'series' : 'movie', item.tmdbId)
  278. if (sid == null) {
  279. sid = addMinimalTitle(item, pid, pname)
  280. if (sid != null) { added = added + 1 }
  281. }
  282. if (sid != null) { credits.push({ show = sid character = item.role posterPath = item.posterPath adult = item.adult }) }
  283. i = i + 1
  284. }
  285. job.pos = end
  286. job.credits = credits
  287. job.added = added
  288. job.steps = job.steps + 1
  289. jobs[pid] = job
  290. if (end < total) { return { done = false pos = end total = total } }
  291. // done: the credits (+ the migrated ones TMDB no longer lists), complete
  292. have = {}
  293. all = []
  294. for (c of credits) { have[c.show] = true all.push(c) }
  295. for (c of listOr(p.shows)) { if (c != null && c.show != null && have[c.show] != true) { all.push(c) } }
  296. x = p
  297. x.shows = all
  298. x.filmographyAt = now()
  299. x.updatedAt = x.filmographyAt
  300. if (personsTable.update(x.id, x) == null) { return { error = 'could not store the filmography: ' + personsTable.lastError() } }
  301. personTouched(x.id)
  302. personsTable.persist()
  303. showsTable.persist()
  304. jobs[pid] = null
  305. 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))
  306. return { done = true pos = total total = total added = added }
  307. }
  308. // one step for the person with this id: { done, pos, total } or { error }
  309. static personFillStep = (&personId) => {
  310. if (warmBlocked()) { return { error = 'tracker is starting up, try again in a minute' } }
  311. p = personsTable.fetch(personId)
  312. if (p == null) { return { error = 'no such person' } }
  313. if (isComplete(p)) { return { done = true } }
  314. if (p.tmdbId == null) { return { error = 'TMDB does not know this person' } }
  315. job = jobs[personId]
  316. if (job == null) { return startFill(p) }
  317. return fillStep(p, job)
  318. }
  319. // ---- people from a title's cast (tracker#26, details.hl completeStep) ------------------------------------------
  320. // TMDB person id → our person id, built once (15k people, one scan), kept up to date by castPersonId
  321. // (flat statics, written key by key like search.hl's haveTmdb: `let m = …ids` would copy the whole map — plain data
  322. // deep-copies on assignment)
  323. static personTmdbBuilt = { yes = false }
  324. static personTmdbIds = {}
  325. static noteTmdbOfPerson = (&p) => {
  326. if (p.tmdbId != null) { personTmdbIds['' + p.tmdbId] = p.id }
  327. return null
  328. }
  329. // bootscan.hl streamed every person through noteSlugOfPerson / noteTmdbOfPerson, every title through noteCastProfiles
  330. static markPeopleIndexesBuilt = (&castPhotos) => {
  331. slugIndex.built = true
  332. personTmdbBuilt.yes = true
  333. peopleView.castProfiles = castPhotos
  334. return true
  335. }
  336. static personIdByTmdb = (&tmdbId) => {
  337. if (!personTmdbBuilt.yes && !warm.running) {
  338. personTmdbBuilt.yes = true
  339. for (p of personsTable.iterate(null, null)) { noteTmdbOfPerson(p) }
  340. }
  341. return personTmdbIds['' + tmdbId]
  342. }
  343. // a free person slug: "Maya-Rudolph", taken → "-2", … (the migrated people's form)
  344. static personSlugOf = (&name, &tmdbId) => {
  345. ensureSlugIndex()
  346. base = slugBaseOf(name, 'person-' + tmdbId)
  347. if (slugIndex.ids[base] == null) { return base }
  348. let n = 2
  349. while (slugIndex.ids[base + '-' + n] != null) { n = n + 1 }
  350. return base + '-' + n
  351. }
  352. // how many people castPersonId added since the start (details.hl counts a title's new people by the difference, tracker#28)
  353. static castPeopleAdded = { n = 0 }
  354. static castPeopleCount = () => { return castPeopleAdded.n }
  355. // our person for one cast entry of TMDB ({ tmdbId, name, character, gender, profile }) — the one we have by TMDB id, else a NEW
  356. // person (name, tmdbId, a free slug, this one credit, TMDB's profile path as `tmdbProfile` (tracker#37: the photo of /people and
  357. // the search); not complete: their page fetches the rest on the first visit like any migrated person). Answers the id, or null
  358. // when it could not be stored. Also a CREW person (tracker#28: `character` = the job, "Director").
  359. static castPersonId = (&c, &showId) => {
  360. if (warmBlocked()) { return null }
  361. have = personIdByTmdb(c.tmdbId)
  362. if (have != null) { return have }
  363. record = { id = newId() name = c.name tmdbId = c.tmdbId urlSegment = personSlugOf(c.name, c.tmdbId) oldId = 'tmdb-person-' + c.tmdbId
  364. gender = c.gender image = null tmdbProfile = textOr(c.profile) adult = false birthDate = null birthPlace = null deathDate = null imdbId = null
  365. shows = showId != null ? [{ show = showId character = c.character }] : [] added = now() }
  366. // mission 062 (tracker#27 for #26/#28): every person the app creates gets its short id at once (shortids.hl)
  367. record.shortId = claimShortId('person', record.id, record.oldId)
  368. if (personsTable.put(record) == null) {
  369. console.log('details: person "' + c.name + '" not stored: ' + personsTable.lastError())
  370. return null
  371. }
  372. personTmdbIds['' + c.tmdbId] = record.id
  373. slugIndex.ids[record.urlSegment] = record.id
  374. indexPerson(record)
  375. personTouched(record.id)
  376. castPeopleAdded.n = castPeopleAdded.n + 1
  377. return record.id
  378. }
  379. // ---- GUEST STARS (mission 062): a series' guests are NOT person records — details.hl stores them on the title ({ tmdbId, actor,
  380. // character, profile, episodes, guest }, `person` only when we have them already). 160k people (most of them one-episode guests)
  381. // 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
  382. // open creates the person (name + role from that title's guest entry; without one — an old link — TMDB's /person/<id>), with its
  383. // short id, then the person page fills it like any other.
  384. static guestFallbackPerHour = toNumber(envOr('TRACKER_GUEST_FALLBACK_PER_HOUR', '20'))
  385. static guestOf = (&showId, &tmdbId) => {
  386. s = showId != null && hlTypeName(showId) == 'String' && showId != '' ? showsTable.fetch(showId) : null
  387. if (s == null) { return null }
  388. for (c of listOr(s.cast)) { if (c != null && c.tmdbId == tmdbId && textOr(c.actor) != null) { return c } }
  389. return null
  390. }
  391. // our person for this TMDB person (created now when we have none) → { id, created } or { error }
  392. static guestPersonId = (tmdbId, showId) => {
  393. if (warmBlocked()) { return { error = 'tracker is starting up, try again in a minute' } }
  394. have = personIdByTmdb(tmdbId)
  395. if (have != null) { return { id = have created = false } }
  396. g = guestOf(showId, tmdbId)
  397. let c = null
  398. let inShow = null
  399. if (g != null) {
  400. c = { tmdbId = tmdbId name = g.actor character = g.character gender = null }
  401. inShow = showId
  402. } else {
  403. // mission SK: this branch (an old link without ?show=) is an anonymous GET that makes a TMDB request and may store a person —
  404. // at most `guestFallbackPerHour` of them an hour in all, so it cannot be used to fill the table or burn the TMDB quota
  405. if (!allowHit('guest-tmdb', 'all', guestFallbackPerHour, 3600000)) { return { error = 'too many new people from TMDB just now, try again later' } }
  406. d = tmdbGet('/person/' + tmdbId)
  407. if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }
  408. if (textOr(d.name) == null || d.adult == true) { return { error = 'no such person' } }
  409. c = { tmdbId = tmdbId name = d.name character = null gender = d.gender }
  410. }
  411. pid = castPersonId(c, inShow)
  412. if (pid == null) { return { error = 'could not store the person' } }
  413. personsTable.persist()
  414. console.log('guest opened: ' + c.name + ' (tmdb ' + tmdbId + ') → new person ' + pid + (inShow != null ? ' from show ' + inShow : ' from TMDB'))
  415. return { id = pid created = true }
  416. }
  417. // ---- /people (tracker#37, mission 032): everyone we have, the one updated last first ------------------------------------------
  418. // Creator: "/people just lists persons by last one updated with poster name and pagination". LAST UPDATED = the newest of
  419. // `updatedAt` (stamped by the person page's fetch, startFill / fillStep), `filmographyAt` and `added` (a person the app created);
  420. // the migrated people with none of them come last (newest stored first). No adult filter (tracker#32's /people had none either).
  421. // A CACHED VIEW like tracker#30's list caches (mission 025): the order is built ONCE at boot (project.hl warmPeopleView: one pass
  422. // 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
  423. // fetches those people (~15 ms server time, any page). Kept current without a rebuild: every person the app creates or updates is
  424. // `personTouched` → `recent`; the next page read moves them to the front (one pass over the ids, ~50 ms, only after a change).
  425. static peopleView = { built = false ids = [] recent = [] castProfiles = 0 }
  426. static updatedKeyOf = (&p) => {
  427. let k = p.updatedAt != null ? p.updatedAt : 0
  428. if (p.filmographyAt != null && p.filmographyAt > k) { k = p.filmographyAt }
  429. if (p.added != null && p.added > k) { k = p.added }
  430. return k
  431. }
  432. // one person's entry of the view's list (table order; bootscan.hl's person pass collects them) — mission T17: two parallel arrays (the
  433. // id, the key) instead of an object { id, key } per person (680 K people: 3 live objects each, every collection marks them)
  434. static viewIds = []
  435. static viewKeys = []
  436. static noteViewRow = (&p) => {
  437. viewIds.push(p.id)
  438. viewKeys.push(updatedKeyOf(p))
  439. return null
  440. }
  441. static warmPeopleView = () => {
  442. if (peopleView.built) { return peopleView.ids.length }
  443. peopleView.castProfiles = castProfilesOf()
  444. for (p of personsTable.iterate(null, null)) { noteViewRow(p) }
  445. return finishPeopleView()
  446. }
  447. static finishPeopleView = () => {
  448. // newest stored first: the table is in the order the people were stored, so the list is nearly sorted already (util.hl sortDesc
  449. // keeps runs) and equal keys (the migrated people: 0) end newest stored first. The people with a key above 0 (touched since the
  450. // migration — few) are sorted; sortDesc is stable, so the zeros after them stay in the same newest-stored-first order as when
  451. // everything was sorted together. (A key that is not a plain number >= 0 never happened: then everything is sorted, as before.)
  452. positive = []
  453. zeros = []
  454. let odd = false
  455. let i = viewIds.length - 1
  456. while (i >= 0) {
  457. k = viewKeys[i]
  458. if (hlTypeName(k) != 'Number') { odd = true }
  459. else if (k > 0) { positive.push({ id = viewIds[i] key = k }) }
  460. else if (k == 0) { zeros.push(viewIds[i]) }
  461. else { odd = true }
  462. i = i - 1
  463. }
  464. ids = []
  465. if (odd) {
  466. newestFirst = []
  467. let j = viewIds.length - 1
  468. while (j >= 0) { newestFirst.push({ id = viewIds[j] key = viewKeys[j] }) j = j - 1 }
  469. for (x of sortDesc(newestFirst)) { ids.push(x.id) }
  470. } else {
  471. for (x of sortDesc(positive)) { ids.push(x.id) }
  472. for (id of zeros) { ids.push(id) }
  473. }
  474. peopleView.ids = ids
  475. peopleView.built = true
  476. return ids.length
  477. }
  478. // a person was created or updated: first in /people from the next page read on
  479. static personTouched = (&id) => {
  480. if (peopleView.built && id != null) { peopleView.recent.push(id) }
  481. return null
  482. }
  483. static peopleViewCurrent = () => {
  484. if (!peopleView.built && !warm.running) { warmPeopleView() }
  485. if (peopleView.recent.length == 0) { return true }
  486. seen = {}
  487. out = []
  488. let i = peopleView.recent.length - 1
  489. while (i >= 0) {
  490. let id = peopleView.recent[i]
  491. if (seen[id] != true) { seen[id] = true out.push(id) }
  492. i = i - 1
  493. }
  494. for (id of peopleView.ids) { if (seen[id] != true) { out.push(id) } }
  495. peopleView.ids = out
  496. peopleView.recent = []
  497. return true
  498. }
  499. static peopleViewStats = () => { return { people = peopleView.ids.length castProfiles = peopleView.castProfiles } }
  500. static peopleCount = () => {
  501. peopleViewCurrent()
  502. return peopleView.ids.length
  503. }
  504. // a person's photo for a tile or a search row: our file (photoUrlOf), else TMDB's (`tmdbProfile`, w185 — like the filmography's
  505. // TMDB posters), else TMDB's from a title's cast entry (castProfiles), else the placeholder
  506. static personPhotoOf = (&p) => {
  507. local = photoUrlOf(p)
  508. if (local != '') { return local }
  509. path = textOr(p.tmdbProfile) != null ? p.tmdbProfile : castProfiles[p.id]
  510. return path != null ? tmdbImageBase + '/w185' + path : '/profiles/none'
  511. }
  512. // person id → TMDB's profile path from a title's cast or crew entry (credits.hl stores `profile` there: cast since tracker#28, crew
  513. // since tracker#37) — for the people the credits job created before castPersonId kept it as `tmdbProfile` (live copy 2026-10-04:
  514. // 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
  515. // MEMORY, not written to the people: 51,907 record updates took 511 s at a start (mission 032, measured on the live copy).
  516. // (Flat static written key by key, like the maps above.)
  517. static castProfiles = {}
  518. // one title's cast and crew photos into the map; how many were new (bootscan.hl's title pass sums them)
  519. static noteCastProfiles = (&s) => {
  520. let n = 0
  521. for (c of listOr(s.cast)) {
  522. if (c != null && c.person != null && textOr(c.profile) != null && castProfiles[c.person] == null) {
  523. castProfiles[c.person] = c.profile
  524. n = n + 1
  525. }
  526. }
  527. for (c of listOr(s.crew)) {
  528. if (c != null && c.person != null && textOr(c.profile) != null && castProfiles[c.person] == null) {
  529. castProfiles[c.person] = c.profile
  530. n = n + 1
  531. }
  532. }
  533. return n
  534. }
  535. static castProfilesOf = () => {
  536. let n = 0
  537. // iterate, not find: one title decoded at a time
  538. for (s of showsTable.iterate(null, null)) { n = n + noteCastProfiles(s) }
  539. return n
  540. }
  541. // one page: { page, pages, tiles } — a tile like the title grids' (components/tilelist.hl): photo, name, no year
  542. static peoplePage = (&raw) => {
  543. peopleViewCurrent()
  544. pages = pagesOf(peopleView.ids.length)
  545. page = pageNumberOf(raw, pages)
  546. tiles = []
  547. for (id of peopleView.ids.slice((page - 1) * pageSize, page * pageSize)) {
  548. let p = personsTable.fetch(id)
  549. if (p != null && p.urlSegment != null) {
  550. tiles.push({ href = '/person/' + p.urlSegment posterUrl = personPhotoOf(p) title = p.name != null ? '' + p.name : '' year = '' })
  551. }
  552. }
  553. return { page = page pages = pages tiles = tiles }
  554. }
  555. // ---- THE PHOTO BACKFILL (mission 032, for tracker#37's /people) ----------------------------------------------------------------
  556. // 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
  557. // 72) — one TMDB request per person (`GET /person/<tmdbId>`, ≤ 40 / 10 s, jobs.hl `photoTick`, the last start job) stores TMDB's
  558. // `profile_path` as `tmdbProfile` (shown from TMDB w185 like the cast photos, no file downloaded); TMDB has none → `photoCheck`
  559. // (never asked again), 404 the same. In /people's order (the one updated last first): page 1 is filled first. Not an update of
  560. // the person (`updatedAt` untouched). Resumes after a restart (the queue = who still has no photo source and no check).
  561. static needsPhoto = (&p) => {
  562. return p.tmdbId != null && p.photoCheck == null && textOr(p.tmdbProfile) == null && castProfiles[p.id] == null && photoUrlOf(p) == ''
  563. }
  564. // 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
  565. // 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
  566. // 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).
  567. static photoQueueStart = () => {
  568. peopleViewCurrent()
  569. return { ids = peopleView.ids pos = 0 out = [] ms = 0 steps = 0 skipped = 0 }
  570. }
  571. // true when the whole list is done
  572. static photoQueueStep = (&c) => {
  573. t0 = now()
  574. n = c.ids.length
  575. while (c.pos < n) {
  576. let id = c.ids[c.pos]
  577. c.pos = c.pos + 1
  578. let p = personsTable.fetch(id)
  579. // the damaged persons index of the real data: fetch() can answer a Number (mission 045, slices.hl): skipped + counted, as sliceNext does
  580. if (p != null && hlTypeName(p) != 'Hybrid') { c.skipped = c.skipped + 1 }
  581. else if (p != null && needsPhoto(p)) { c.out.push(id) }
  582. if (c.pos % 64 == 0 && now() - t0 >= sliceBudgetMs) { break }
  583. }
  584. c.steps = c.steps + 1
  585. c.ms = c.ms + (now() - t0)
  586. return c.pos >= n
  587. }
  588. // ONE person → { requests, found (a photo stored), errors, error, retry (a passing failure: ask again later) }
  589. static photoStep = (&personId) => {
  590. out = { requests = 0 found = false errors = 0 error = '' retry = false }
  591. p = personsTable.fetch(personId)
  592. if (p == null || !needsPhoto(p)) { return out }
  593. out.requests = 1
  594. d = tmdbGet('/person/' + p.tmdbId)
  595. x = p
  596. if (d.failed != null) {
  597. out.errors = 1
  598. out.error = p.name + ': ' + d.failed
  599. if (d.status != 404) { out.retry = true return out }
  600. x.photoCheck = 'TMDB 404'
  601. } else if (textOr(d.profile_path) != null) {
  602. x.tmdbProfile = d.profile_path
  603. out.found = true
  604. } else { x.photoCheck = 'TMDB has none' }
  605. if (personsTable.update(x.id, x) == null) { out.errors = out.errors + 1 out.error = p.name + ': not stored: ' + personsTable.lastError() }
  606. return out
  607. }
  608. static persistPhotos = () => {
  609. personsTable.persist()
  610. return true
  611. }

Branches

Latest commits

  • b9e841a7Merge branch 'sy-sync'mre
  • d1ae2701sync components.hybriel 4922f9c: modal and pagination 44 px targets (vendored copies, verbatim) (SY)mre
  • 043624b2theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 05d89fd0deploy: security gate (tests/security.mjs)mre
  • 2ae8a47bMerge branch 'sk-sec'mre
  • 8fee5d52sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 944ad51eSK: report reports/SK-sec.md, LOGsk
  • 415487c1SK: import budget per user + id type check, gate checkssk
  • 7b8a4f74security audit SK: nosniff + image sandbox headers, face id checks, adult follow, login budget + new session at login, guest-link budget, tests/security.mjssk
  • f0f26c5areports: T18 section (gates, boot-gate, 3x3 table, search + short-id compare)mre
  • 2a8682a1deploy.sh GATES: tests/warmstart.mjsmre
  • 3761338breports/T17-boot.md: handoff (phase table, fix, numbers so far, open proof)mre
  • 52e09eb2boot: sync window 1000 ms (the gates ask for a complete start), README boot-time sectionmre
  • c87149e8tests/warmstart.mjs: the progressive start proven over HTTP (note in the window, 503 short id, after: everything); bootBeginmre
  • 593a6350boot: resumable start-up scan, the server listens first (T17)mre
  • be4890a0reports: H2 hydration audit (no test change needed)mre
  • 1f9c8bf4re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • c1df88eddocker-compose: HL_GC_TABLE_LOAD=62 (tracker mission 048, T16 real-data numbers)mre
  • d0a82867mission 048: report, LOG (HL_GC_TABLE_LOAD=62 measured)mre
  • 2d4be66fre-vendor Hybriel 5df4eb7e (GC: HL_GC_TABLE_LOAD knob, mission 406)mre