gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit93be947693be9476tracker#16: person pages /person/<slug> with the filmography fetched from TMDB on the first visit (step by step), gatemre93be9476/people.hl

14.8 KB

  1. // 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. //
  16. // COMPLETE = `filmographyAt` set: never fetched again (the daily sync may refresh followed people later — not built).
  17. // Migrated people are NOT complete (153 of them carry the old tracker's credits — kept, the fetch adds the rest).
  18. // A title we don't have → a MINIMAL show record (title, year, type, tmdbId, `adult`, overview, genres by TMDB id, language;
  19. // no seasons, no poster file — the daily sync / a backfill brings those), shaped like search.hl importTitle's
  20. // (`oldId tmdb-<tv|movie>-<id>`, a free slug), indexed for the search and put into the public lists (catalog.hl).
  21. // The person's credits (`shows`, the migrated field): [{ show, character, posterPath, adult }] — `character` is the role
  22. // text (the characters, then crew jobs like "Director", " / " between them); `posterPath` = TMDB's, so the page can show
  23. // TMDB's small poster (w92, like search's web rows) until we have the file. ADULT (TMDB's flag, mission 054): hidden when
  24. // the show's `adult` or the credit's is true.
  25. // ONE PROCESS PER STORAGE (hybriel#21); new rows get self-assigned 16-hex ids (hybriel#113), like tmdbsync.hl.
  26. import { now } from 'hl:time'
  27. import { fetch } from 'hl:fetch'
  28. import { randomBytes } from 'hl:crypto'
  29. import { writeFile, mkDir, exists } from 'hl:fs'
  30. import { personsTable, showsTable, genresTable, storageDir, showById, showYear, posterUrlOf } from './shows.hl'
  31. import { tmdbGet, tmdbImageBase, textOr } from './tmdbsync.hl'
  32. import { titleIdByTmdb, indexShow, slugOf } from './search.hl'
  33. import { refreshCatalogShow, sortDesc } from './catalog.hl'
  34. static profilesDir = storageDir + '/profiles'
  35. // titles stored per step (real data: see STATUS.md ticket #16 for the per-step time)
  36. static fillBatch = 40
  37. static listOr = (v) => { return v == null ? [] : v }
  38. // ---- the person -------------------------------------------------------------------------------------------------
  39. static slugIndex = { built = false ids = {} }
  40. static personBySlug = (slug) => {
  41. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  42. if (!slugIndex.built) {
  43. let m = {}
  44. for (p of personsTable.find(null, null)) { if (p.urlSegment != null) { m[p.urlSegment] = p.id } }
  45. slugIndex.ids = m
  46. slugIndex.built = true
  47. }
  48. let id = slugIndex.ids[slug]
  49. return id == null ? null : personsTable.fetch(id)
  50. }
  51. static isComplete = (p) => { return p.filmographyAt != null }
  52. // the page asks TMDB for this person: not complete yet, and TMDB knows them
  53. static needsFill = (p) => { return !isComplete(p) && p.tmdbId != null }
  54. // the photo: /profiles/<oldId>.<ext> (project.hl profileRoute) — only when the file is there (the migrated `image` = 'jpg'
  55. // of 129 people never came with a file)
  56. static profileName = (p) => {
  57. if (p.oldId == null || p.image == null || p.image == '') { return null }
  58. return p.oldId + '.' + p.image
  59. }
  60. static photoUrlOf = (p) => {
  61. let name = profileName(p)
  62. return name != null && exists(profilesDir + '/' + name) ? '/profiles/' + name : ''
  63. }
  64. static monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  65. // '1986-03-04' → '4 March 1986'; a bare year or anything else as it is
  66. static dateText = (d) => {
  67. let t = textOr(d)
  68. if (t == null) { return null }
  69. if (t.length < 10) { return t }
  70. let m = toNumber(t.slice(5, 7))
  71. let day = toNumber(t.slice(8, 10))
  72. if (m == null || day == null || m < 1 || m > 12) { return t }
  73. return day + ' ' + monthNames[m - 1] + ' ' + t.slice(0, 4)
  74. }
  75. // { name, photoUrl, born, died, bio } — every field a plain string ('' = none)
  76. static personInfoOf = (p) => {
  77. let born = dateText(p.birthDate)
  78. let place = textOr(p.birthPlace)
  79. let bornText = ''
  80. 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 }
  81. let died = dateText(p.deathDate)
  82. return { name = p.name != null ? p.name : '' photoUrl = photoUrlOf(p) born = bornText died = died != null ? 'Died ' + died : ''
  83. bio = textOr(p.biography) != null ? p.biography : '' }
  84. }
  85. // ---- the filmography --------------------------------------------------------------------------------------------
  86. // the credits, one row per title (a title twice — the migrated credit and TMDB's — is ONE row, roles merged), newest
  87. // first by the title's release ('YYYY-MM-DD', else its year), undated last; adult titles left out
  88. static filmographyOf = (p) => {
  89. let byShow = {}
  90. let order = []
  91. for (c of listOr(p.shows)) {
  92. if (c != null && c.show != null) {
  93. let role = textOr(c.character)
  94. let prev = byShow[c.show]
  95. if (prev == null) {
  96. byShow[c.show] = { role = role != null ? role : '' posterPath = textOr(c.posterPath) adult = c.adult == true }
  97. order.push(c.show)
  98. } else {
  99. let x = prev
  100. if (role != null && !(' / ' + x.role + ' / ').includes(' / ' + role + ' / ')) { x.role = x.role == '' ? role : x.role + ' / ' + role }
  101. if (x.posterPath == null) { x.posterPath = textOr(c.posterPath) }
  102. if (c.adult == true) { x.adult = true }
  103. byShow[c.show] = x
  104. }
  105. }
  106. }
  107. let list = []
  108. for (sid of order) {
  109. let c = byShow[sid]
  110. let s = showById(sid)
  111. if (s != null && s.adult != true && !c.adult) {
  112. let y = showYear(s)
  113. let release = textOr(s.release)
  114. let key = release != null && release.length >= 4 ? release : (y != null ? y : '')
  115. let poster = posterUrlOf(s)
  116. if (poster == '/posters/none' && c.posterPath != null) { poster = tmdbImageBase + '/w92' + c.posterPath }
  117. list.push({ key = key id = s.id title = s.title year = y != null ? y : '' href = '/shows/' + s.urlSegment posterUrl = poster
  118. role = c.role typeLabel = s.type == 'movie' ? 'Movie' : 'Series' })
  119. }
  120. }
  121. let out = []
  122. let undated = []
  123. for (r of sortDesc(list)) { if (r.key == '') { undated.push(r) } else { out.push(r) } }
  124. for (r of undated) { out.push(r) }
  125. return out
  126. }
  127. // ---- the fetch ------------------------------------------------------------------------------------------------
  128. // person id → { items, pos, credits, added, requests, started, steps } while a fetch is under way (in memory: a restart
  129. // loses it — the titles stored so far are found again by TMDB id, nothing is duplicated)
  130. static jobs = {}
  131. // TMDB genre id → ours (our genres carry TMDB's id)
  132. static genreMap = { built = false ids = {} }
  133. static genreIdsOfTmdb = (tmdbIds) => {
  134. if (!genreMap.built) {
  135. let m = {}
  136. for (g of genresTable.find(null, null)) { if (g.tmdbId != null) { m['' + g.tmdbId] = g.id } }
  137. genreMap.ids = m
  138. genreMap.built = true
  139. }
  140. let out = []
  141. for (t of listOr(tmdbIds)) {
  142. let id = genreMap.ids['' + t]
  143. if (id != null && !out.includes(id)) { out.push(id) }
  144. }
  145. return out
  146. }
  147. // TMDB's combined_credits → one item per title (cast AND crew of the same title merged), TV + movies only
  148. static creditItems = (cc) => {
  149. let byKey = {}
  150. let order = []
  151. let all = []
  152. if (cc != null) {
  153. for (c of listOr(cc.cast)) { all.push({ credit = c role = textOr(c.character) }) }
  154. for (c of listOr(cc.crew)) { all.push({ credit = c role = textOr(c.job) }) }
  155. }
  156. for (a of all) {
  157. let c = a.credit
  158. let kind = c.media_type
  159. if ((kind == 'tv' || kind == 'movie') && c.id != null && hlTypeName(c.id) == 'Number') {
  160. let k = kind + ':' + c.id
  161. let known = byKey[k]
  162. if (known == null) {
  163. let name = kind == 'tv' ? textOr(c.name) : textOr(c.title)
  164. if (name != null) {
  165. byKey[k] = { kind = kind tmdbId = c.id title = name release = textOr(kind == 'tv' ? c.first_air_date : c.release_date)
  166. overview = textOr(c.overview) language = textOr(c.original_language) genreIds = listOr(c.genre_ids)
  167. posterPath = textOr(c.poster_path) adult = c.adult == true role = a.role != null ? a.role : '' }
  168. order.push(k)
  169. }
  170. } else if (a.role != null && !(' / ' + known.role + ' / ').includes(' / ' + a.role + ' / ')) {
  171. let x = known
  172. x.role = x.role == '' ? a.role : x.role + ' / ' + a.role
  173. byKey[k] = x
  174. }
  175. }
  176. }
  177. let out = []
  178. for (k of order) { out.push(byKey[k]) }
  179. return out
  180. }
  181. // the photo: w185 → storage/mpackdb/profiles/<oldId>.<ext> — { requests, image, tmdbProfile, failed }
  182. static syncProfile = (p, profilePath) => {
  183. let out = { requests = 0 image = p.image tmdbProfile = p.tmdbProfile failed = null }
  184. if (textOr(profilePath) == null || p.oldId == null) { return out }
  185. let parts = profilePath.split('.')
  186. let ext = parts[parts.length - 1].toLowerCase()
  187. if (ext != 'jpg' && ext != 'jpeg' && ext != 'png' && ext != 'webp') { return out }
  188. let file = profilesDir + '/' + p.oldId + '.' + ext
  189. if (exists(file) && p.tmdbProfile == profilePath && p.image == ext) { return out }
  190. out.requests = 1
  191. let r = fetch(tmdbImageBase + '/w185' + profilePath, { headers = { 'user-agent' = 'tracker.worldapi.org (person page)' } timeoutMs = 20000 })
  192. if (r == null || r.status != 200 || r.body == null || r.body.length == 0) {
  193. out.failed = 'photo ' + profilePath + ': ' + (r == null ? 'no answer' : 'HTTP ' + r.status)
  194. return out
  195. }
  196. mkDir(profilesDir)
  197. writeFile(file, toBytes(r.body), 420)
  198. out.image = ext
  199. out.tmdbProfile = profilePath
  200. return out
  201. }
  202. // step 1: TMDB's person + credits; the facts (a TMDB value that is empty never overwrites ours) and the photo
  203. static startFill = (p) => {
  204. let t0 = now()
  205. let d = tmdbGet('/person/' + p.tmdbId + '?append_to_response=combined_credits')
  206. if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }
  207. let items = creditItems(d.combined_credits)
  208. let photo = syncProfile(p, d.profile_path)
  209. let x = p
  210. if (textOr(d.biography) != null) { x.biography = d.biography }
  211. if (textOr(d.birthday) != null) { x.birthDate = d.birthday }
  212. if (textOr(d.deathday) != null) { x.deathDate = d.deathday }
  213. if (textOr(d.place_of_birth) != null) { x.birthPlace = d.place_of_birth }
  214. if (textOr(x.imdbId) == null && textOr(d.imdb_id) != null) { x.imdbId = d.imdb_id }
  215. if (d.adult != null) { x.adult = d.adult == true }
  216. x.image = photo.image
  217. x.tmdbProfile = photo.tmdbProfile
  218. if (personsTable.update(x.id, x) == null) { return { error = 'could not store the person: ' + personsTable.lastError() } }
  219. if (photo.failed != null) { console.log('person fill: ' + p.name + ': ' + photo.failed) }
  220. jobs[p.id] = { items = items pos = 0 credits = [] added = 0 requests = 1 + photo.requests started = t0 steps = 1 tmdbMs = now() - t0 }
  221. return { done = false pos = 0 total = items.length }
  222. }
  223. // a title we don't have: the minimal record (shape: search.hl importTitle) → its id, or null
  224. static addMinimalTitle = (cr, pid, pname) => {
  225. let kindType = cr.kind == 'tv' ? 'series' : 'movie'
  226. let rel = cr.release
  227. let yr = rel != null && rel.length >= 4 ? toNumber(rel.slice(0, 4)) : null
  228. let slug = slugOf(cr.title, cr.tmdbId)
  229. let record = {
  230. id = randomBytes(8, 'hex') title = cr.title summary = cr.overview != null ? cr.overview : '' tmdbSummary = cr.overview tmdbId = cr.tmdbId
  231. language = cr.language type = kindType release = rel year = yr image = null
  232. urlSegment = slug episodesCount = null homepage = null imdbId = null seasonsCount = null
  233. status = null tagline = null tvdbId = null tvmzId = null genres = genreIdsOfTmdb(cr.genreIds)
  234. cast = [{ person = pid character = cr.role actor = pname }] seasons = [] oldId = 'tmdb-' + cr.kind + '-' + cr.tmdbId
  235. adult = cr.adult imported = now()
  236. }
  237. if (showsTable.put(record) == null) {
  238. console.log('person fill: "' + cr.title + '" not stored: ' + showsTable.lastError())
  239. return null
  240. }
  241. indexShow(record)
  242. refreshCatalogShow(record.id)
  243. return record.id
  244. }
  245. // every next step: the next `fillBatch` titles; the last one links the credits and marks the person complete
  246. static fillStep = (p, jobIn) => {
  247. let job = jobIn
  248. let total = job.items.length
  249. let end = job.pos + fillBatch
  250. if (end > total) { end = total }
  251. let credits = job.credits
  252. let added = job.added
  253. let pid = p.id
  254. let pname = p.name
  255. let i = job.pos
  256. while (i < end) {
  257. let item = job.items[i]
  258. let sid = titleIdByTmdb(item.kind == 'tv' ? 'series' : 'movie', item.tmdbId)
  259. if (sid == null) {
  260. sid = addMinimalTitle(item, pid, pname)
  261. if (sid != null) { added = added + 1 }
  262. }
  263. if (sid != null) { credits.push({ show = sid character = item.role posterPath = item.posterPath adult = item.adult }) }
  264. i = i + 1
  265. }
  266. job.pos = end
  267. job.credits = credits
  268. job.added = added
  269. job.steps = job.steps + 1
  270. jobs[pid] = job
  271. if (end < total) { return { done = false pos = end total = total } }
  272. // done: the credits (+ the migrated ones TMDB no longer lists), complete
  273. let have = {}
  274. let all = []
  275. for (c of credits) { have[c.show] = true all.push(c) }
  276. for (c of listOr(p.shows)) { if (c != null && c.show != null && have[c.show] != true) { all.push(c) } }
  277. let x = p
  278. x.shows = all
  279. x.filmographyAt = now()
  280. if (personsTable.update(x.id, x) == null) { return { error = 'could not store the filmography: ' + personsTable.lastError() } }
  281. personsTable.persist()
  282. showsTable.persist()
  283. jobs[pid] = null
  284. 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))
  285. return { done = true pos = total total = total added = added }
  286. }
  287. // one step for the person with this id: { done, pos, total } or { error }
  288. static personFillStep = (personId) => {
  289. let p = personsTable.fetch(personId)
  290. if (p == null) { return { error = 'no such person' } }
  291. if (isComplete(p)) { return { done = true } }
  292. if (p.tmdbId == null) { return { error = 'TMDB does not know this person' } }
  293. let job = jobs[personId]
  294. if (job == null) { return startFill(p) }
  295. return fillStep(p, job)
  296. }

Branches

Latest commits

  • 93be9476tracker#16: person pages /person/<slug> with the filmography fetched from TMDB on the first visit (step by step), gatemre
  • 47a3cae6STATUS: mission 053 merge commit idsmre
  • dcc5eecaMerge branch 't14-search'mre
  • 03edc783Merge branch 't15-tvmaze'mre
  • 71b46345tracker#15: numbering check by date or title, placeholder titles in other languages, docs + real-data proofmre
  • 6bb2daf1tracker#13: homepage (tiles, intro, latest movies/shows), /shows, /movies/page/N, /my/movies; lists cached in memorymre
  • b8bd1157tracker#14: README + STATUS (search, real-data numbers, gate, merge notes)mre
  • 65c694a8tracker#14: search — header magnifier, /search/<text> (in-memory word-prefix index over titles + people), Fetch from web (TMDB search/multi, ours left out), Add = import via syncShow; gate +25 checks, real-data scriptmre
  • 34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre
  • cbdc4ea7tracker#12: link icons TMDB/IMDb/TVDB/TVmaze; sync fills missing ids (TVmaze lookup); movies fetched via /movie/mre
  • b105bcd8tracker#11: Hybriel master ff51cf46 (checks no longer vanish), mobile-first styles, carets, follow button, sign-in modal, inverted check, orange castmre
  • 31b758aatracker#10: installable app (manifest, service worker, offline shell), own icon + faviconmre
  • 2fa9d997tracker#9: TMDB sync (followed shows: seasons, episodes, posters), tools/sync-tmdb.hl + daily run 04:00 UTC, fake TMDB in gatemre
  • 49e1f61edeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 54070a4etracker#8: /my/unwatched + /my/schedule (301 from old), S01E01, title (year), 1 episode, watched-set lookup (unwatched 15s -> 1s)mre
  • 3251488atracker#7: /my/shows (followed shows, newest follow first, poster, title, last watched SxxEyy); gate can take screenshots (TRACKER_GATE_SHOTS)mre
  • 44b7d9f9tracker#6: /schedule — upcoming episodes of followed shows, soonest firstmre
  • 91c9fc8ctracker#5: /unwatched — unwatched released episodes of followed shows, newest firstmre
  • a97c0295tracker#4: show page /shows/:slug (header, seasons, episodes, watch checks) + tools/relink-episode-seasons.hlmre
  • 05f407c5tracker: no border on any button except inverted ones (Log out, ident status and identities too); header brand weight 100mre