gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit10bb3f9310bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre10bb3f93/tmdbsync.hl

35.9 KB

  1. // tmdbsync.hl — THE TMDB SYNC (tracker.worldapi.org#9): for every show SOMEONE follows, fetch the show's
  2. // details, seasons and episodes from TMDB and bring storage/mpackdb/ up to date, plus the show's poster.
  3. // Used by BOTH runners: the daily run inside the app (project.hl `syncTick`, one show per step) and the
  4. // command-line tool (tools/sync-tmdb.hl). Reference for the API use: the old tracker's
  5. // crates/sync/commands/sync.js (read-only).
  6. //
  7. // GET <TMDB_BASE_URL>/tv/<tmdbId>?append_to_response=external_ids,aggregate_credits the details (status,
  8. // counts, overview, poster_path, seasons[])
  9. // + external_ids (imdb_id, tvdb_id) + the cast/crew
  10. // of every season (tracker#28: the answer goes back
  11. // as `res.details`, the caller stores the credits —
  12. // details.hl applyCredits; no extra request)
  13. // GET <TMDB_BASE_URL>/tv/<tmdbId>?append_to_response=season/1,season/2… up to 20 seasons with their
  14. // episodes in ONE request
  15. // GET <TMDB_IMAGE_URL>/w342<poster_path> the poster → storage/mpackdb/posters/
  16. // Authorization: Bearer $TMDB_READ_TOKEN
  17. // GET <TVMAZE_BASE_URL>/lookup/shows?imdb=tt… (else ?thetvdb=<id>) the TVmaze id, ONLY when the show
  18. // has none (301 → /shows/<id>, 404 = unknown)
  19. // GET <TVMAZE_BASE_URL>/shows/<tvmzId>/episodes a SERIES' episodes on TVmaze (#15), see below
  20. // A MOVIE (`type = 'movie'`, 7814 of the migrated rows, 1 followed): only
  21. // GET <TMDB_BASE_URL>/movie/<tmdbId>?append_to_response=external_ids,credits its imdb id + poster (+ credits); no seasons,
  22. // status, overview (it is no TV show)
  23. //
  24. // EXTERNAL IDS (tracker.worldapi.org#12, the show page's link icons): a MISSING imdbId/tvdbId is filled from TMDB's
  25. // external_ids, a missing tvmzId from TVmaze's lookup — an id the show already has is NEVER overwritten.
  26. // RULES (ticket): new seasons/episodes are ADDED, existing ones UPDATED (title, summary, release) —
  27. // matched by tmdbId, never duplicated; NOTHING is deleted. An episode without a tmdbId (161 migrated ones)
  28. // is matched by its S/E number instead and gets the tmdbId. A season (no tmdbId in the migrated data) is
  29. // matched by (show, seasonNumber). A TMDB value that is empty/null never overwrites a stored one.
  30. // Season 0 ("Specials") is only synced for a show that already has a season 0 (else every followed show
  31. // would suddenly flood /my/unwatched with specials); a TMDB season with no episodes is not created.
  32. //
  33. // TVMAZE MERGE (tracker.worldapi.org#15): AFTER TMDB, a series with a tvmzId gets TVmaze's episode list (one request)
  34. // and TVmaze FILLS GAPS only — matched by season/episode number: a missing episode (and its season) is ADDED, an empty
  35. // title or air date of an existing one is FILLED; a value TMDB gave is never overwritten. A placeholder title
  36. // ("Episode 4", "TBA") counts as empty — and TMDB's own placeholder never overwrites a real title either (else the
  37. // two would flip it every day). When TMDB later lists the episode, the TMDB step adopts it by number (it has no tmdbId)
  38. // and TMDB's values win. TVmaze specials (no episode number) are skipped, season 0 only if the show has one. SAFETY:
  39. // when the two number a show differently (fewer than 80 % of the episodes both know air within a day of each other or
  40. // share the title — `numberingAgrees`), TVmaze is ignored for that show (`tvmazeSkipped`). Summaries are not taken
  41. // (TVmaze's are HTML; the ticket asks for episodes, air dates, titles).
  42. //
  43. // ADULT FLAG (mission 054): every details answer carries TMDB's `adult` — the sync, the import (search.hl) and the
  44. // BACKFILL below store it as show.adult (true/false; null = not known yet, hidden from the public lists, shows.hl
  45. // isPublicTitle). THE BACKFILL (`backfillTitle`, run one title per step by project.hl `backfillTick`, like the daily sync):
  46. // GET <TMDB_BASE_URL>/movie|tv/<tmdbId>?append_to_response=external_ids ONE request: adult, poster_path, imdb/tvdb id
  47. // GET <TMDB_IMAGE_URL>/w342<poster_path> the poster when its file is missing (not for
  48. // an adult title — never shown, mission 056)
  49. // for every title whose adult flag is unknown (no TVmaze, no seasons — the daily sync does those for followed shows). A
  50. // title TMDB answers 404 for (or one without tmdbId) gets `adultCheck` = why, stays unknown (hidden) and is not asked again.
  51. //
  52. // IDS ARE SELF-ASSIGNED (randomBytes, like watches.hl): hl:mpackdb's own generated @id can repeat within
  53. // one millisecond, which is what made update() lose rows (hybriel#113, fixed upstream, not in the vendored
  54. // build) — a table holding only unique ids is safe to update().
  55. //
  56. // ONE PROCESS PER STORAGE: hl:mpackdb does not coordinate two processes (hybriel#21) — the in-app run uses
  57. // the app's own open tables (imported from shows.hl); the tool only ever runs against a stopped app or a copy.
  58. //
  59. // Env: TMDB_READ_TOKEN (required unless TMDB_BASE_URL points at a fake), TMDB_BASE_URL
  60. // (https://api.themoviedb.org/3), TMDB_IMAGE_URL (https://image.tmdb.org/t/p) — the gate points both at its
  61. // fake TMDB (tests/browser.mjs).
  62. import { fetch } from 'hl:fetch'
  63. import { env } from 'hl:proc'
  64. import { now } from 'hl:time'
  65. import { randomBytes } from 'hl:crypto'
  66. import { writeFile, mkDir, exists } from 'hl:fs'
  67. import { showsTable, seasonsTable, episodesTable, storageDir } from './shows.hl'
  68. static envOr = (name, fallback) => {
  69. let v = env(name)
  70. return v != null && v.trim() != '' ? v.trim() : fallback
  71. }
  72. static tmdbBase = envOr('TMDB_BASE_URL', 'https://api.themoviedb.org/3')
  73. static tmdbImageBase = envOr('TMDB_IMAGE_URL', 'https://image.tmdb.org/t/p')
  74. static tmdbToken = envOr('TMDB_READ_TOKEN', '')
  75. static postersDir = storageDir + '/posters'
  76. static tvmazeBase = envOr('TVMAZE_BASE_URL', 'https://api.tvmaze.com')
  77. // the sync can run: a token is set (never printed) — the dev .env on Loreana has one, a gate sets its own
  78. static syncEnabled = tmdbToken != ''
  79. // TMDB allows 40 requests / 10 s: every runner waits this long per request it made before the next show
  80. static msPerRequest = 260
  81. // TVmaze allows 20 requests / 10 s (its API docs): 550 ms per lookup made
  82. static msPerTvmazeRequest = 550
  83. // how long a runner waits after a show before the next one (both runners: project.hl syncTick, tools/sync-tmdb.hl)
  84. static pauseMsAfter = (r) => { return r.requests * msPerRequest + r.tvmazeRequests * msPerTvmazeRequest }
  85. // one GET → the parsed JSON, or { failed = '<why>' }. A refused/timed-out fetch is an Error event (absorbed
  86. // by the runner's `on Error`), the fetch then yields null.
  87. static tmdbGet = (path) => {
  88. let r = fetch(tmdbBase + path, { headers = { 'authorization' = 'Bearer ' + tmdbToken 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })
  89. if (r == null || r.status == null || r.status == 0) { return { failed = 'no answer for ' + path } }
  90. if (r.status != 200) { return { failed = 'HTTP ' + r.status + ' for ' + path status = r.status } }
  91. let j = r.json()
  92. if (j == null) { return { failed = 'no JSON for ' + path } }
  93. return j
  94. }
  95. static textOr = (v) => { return v != null && hlTypeName(v) == 'String' && v.trim() != '' ? v : null }
  96. // ---- external ids (tracker.worldapi.org#12) -----------------------------------------------------
  97. static hasId = (v) => { return v != null && ('' + v).trim() != '' }
  98. // an IMDb id as TMDB gives it ('tt' + digits), else null
  99. static imdbOr = (v) => {
  100. let t = textOr(v)
  101. if (t == null || t.length < 3 || t.slice(0, 2) != 'tt') { return null }
  102. let i = 2
  103. while (i < t.length) {
  104. if (!'0123456789'.includes(t[i])) { return null }
  105. i = i + 1
  106. }
  107. return t
  108. }
  109. // a positive numeric id (TMDB's tvdb_id, TVmaze's id), else null
  110. static numIdOr = (v) => { return v != null && hlTypeName(v) == 'Number' && v > 0 ? v : null }
  111. // TVmaze's lookup by one external id: { id } (null = TVmaze doesn't know it, 404) or { failed }. hl:fetch follows the
  112. // 301 to /shows/<id> by itself, so a hit answers the show's own JSON.
  113. static tvmazeLookup = (param, value) => {
  114. let r = fetch(tvmazeBase + '/lookup/shows?' + param + '=' + value, { headers = { 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })
  115. if (r == null || r.status == null || r.status == 0) { return { failed = 'TVmaze: no answer for ' + param + '=' + value } }
  116. if (r.status == 404) { return { id = null } }
  117. if (r.status != 200) { return { failed = 'TVmaze: HTTP ' + r.status + ' for ' + param + '=' + value } }
  118. let j = r.json()
  119. if (j == null || numIdOr(j.id) == null) { return { failed = 'TVmaze: no id for ' + param + '=' + value } }
  120. return { id = j.id }
  121. }
  122. // the ids to SET on a show from TMDB's external_ids (+ TVmaze for a series): { imdbId, tvdbId, tvmzId } — each the
  123. // show's own value when it has one (never overwritten), else the found one, else null — plus { filled, tvmazeRequests,
  124. // failed }. TVmaze is asked by imdb, then by thetvdb, only while the show (after TMDB) still has no tvmzId — and only
  125. // when `askTvmaze` (the adult backfill does not: one request per title)
  126. static externalIdsFor = (show, ext, isSeries, askTvmaze) => {
  127. let out = { imdbId = show.imdbId tvdbId = show.tvdbId tvmzId = show.tvmzId filled = 0 tvmazeRequests = 0 failed = null }
  128. let e = ext != null ? ext : {}
  129. if (!hasId(out.imdbId) && imdbOr(e.imdb_id) != null) { out.imdbId = e.imdb_id out.filled = out.filled + 1 }
  130. if (!isSeries) { return out }
  131. if (!hasId(out.tvdbId) && numIdOr(e.tvdb_id) != null) { out.tvdbId = e.tvdb_id out.filled = out.filled + 1 }
  132. if (hasId(out.tvmzId) || !askTvmaze) { return out }
  133. let tries = []
  134. if (imdbOr('' + out.imdbId) != null) { tries.push({ param = 'imdb' value = '' + out.imdbId }) }
  135. if (numIdOr(out.tvdbId) != null) { tries.push({ param = 'thetvdb' value = '' + out.tvdbId }) }
  136. for (t of tries) {
  137. if (!hasId(out.tvmzId) && out.failed == null) {
  138. out.tvmazeRequests = out.tvmazeRequests + 1
  139. let found = tvmazeLookup(t.param, t.value)
  140. if (found.failed != null) { out.failed = found.failed } else if (found.id != null) { out.tvmzId = found.id out.filled = out.filled + 1 }
  141. }
  142. }
  143. return out
  144. }
  145. // ---- TVmaze merge (tracker.worldapi.org#15) ------------------------------------------------------
  146. // a title that is none yet: empty, "TBA"/"TBD", or "Episode <n>" (what TMDB and TVmaze name an untitled episode; also
  147. // French/German/Spanish: real data has TVmaze "Épisode 1" where TMDB says "Episode 1")
  148. static placeholderWords = ['episode', 'épisode', 'Épisode', 'folge', 'episodio']
  149. static isPlaceholderTitle = (v) => {
  150. let t = textOr(v)
  151. if (t == null) { return true }
  152. let l = t.trim().toLowerCase()
  153. if (l == 'tba' || l == 'tbd' || l == 'tba.' || l == 'to be announced') { return true }
  154. let parts = l.split(' ')
  155. if (parts.length != 2 || !placeholderWords.includes(parts[0]) || parts[1].length == 0) { return false }
  156. let i = 0
  157. while (i < parts[1].length) {
  158. if (!'0123456789'.includes(parts[1][i])) { return false }
  159. i = i + 1
  160. }
  161. return true
  162. }
  163. // 'YYYY-MM-DD' → a day number (only differences matter), null when it is no such date
  164. static dayNumber = (v) => {
  165. let t = textOr(v)
  166. if (t == null || t.length < 10) { return null }
  167. let y = toNumber(t.slice(0, 4))
  168. let m = toNumber(t.slice(5, 7))
  169. let d = toNumber(t.slice(8, 10))
  170. if (y == null || m == null || d == null || m < 1 || m > 12) { return null }
  171. let before = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  172. let py = m <= 2 ? y - 1 : y
  173. let leaps = (py - py % 4) / 4 - (py - py % 100) / 100 + (py - py % 400) / 400
  174. return y * 365 + leaps + before[m - 1] + d
  175. }
  176. static daysApart = (a, b) => {
  177. let x = dayNumber(a)
  178. let y = dayNumber(b)
  179. if (x == null || y == null) { return null }
  180. return x > y ? x - y : y - x
  181. }
  182. // TVmaze's episode list of one show: a list, or { failed }
  183. static tvmazeEpisodes = (tvmzId) => {
  184. let r = fetch(tvmazeBase + '/shows/' + tvmzId + '/episodes', { headers = { 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })
  185. if (r == null || r.status == null || r.status == 0) { return { failed = 'TVmaze: no answer for episodes of ' + tvmzId } }
  186. if (r.status != 200) { return { failed = 'TVmaze: HTTP ' + r.status + ' for episodes of ' + tvmzId } }
  187. let j = r.json()
  188. if (j == null || j.length == null) { return { failed = 'TVmaze: no episode list for ' + tvmzId } }
  189. return { list = j }
  190. }
  191. // do we and TVmaze number a show the same way? Of the episodes both know (same S/E), at least 80 % must air within a day
  192. // of each other OR carry the same title (a streaming show TVmaze dates all on its release day, TMDB week by week, still
  193. // agrees by title). A show we have episodes of but TVmaze numbers none of the same (e.g. seasons by year) never agrees.
  194. // Answers { known, compared, agree, ok }.
  195. static sameTitle = (a, b) => { return !isPlaceholderTitle(a) && !isPlaceholderTitle(b) && a.trim().toLowerCase() == b.trim().toLowerCase() }
  196. static numberingAgrees = (epByNumber, list) => {
  197. let out = { known = 0 compared = 0 agree = 0 ok = true }
  198. let localCount = epByNumber.keys().length
  199. for (te of list) {
  200. let e = epByNumber[te.season + 'x' + te.number]
  201. if (e != null) {
  202. out.known = out.known + 1
  203. let apart = daysApart(e.release, te.airdate)
  204. let titled = !isPlaceholderTitle(e.title) && !isPlaceholderTitle(te.name)
  205. if (apart != null || titled) {
  206. out.compared = out.compared + 1
  207. if ((apart != null && apart <= 1) || sameTitle(e.title, te.name)) { out.agree = out.agree + 1 }
  208. }
  209. }
  210. }
  211. out.ok = !((localCount > 0 && out.known == 0) || (out.compared > 0 && out.agree * 5 < out.compared * 4))
  212. return out
  213. }
  214. // Merge TVmaze's episodes of a series into what we have AFTER the TMDB step (gaps only, rules at the top).
  215. // `seasonsByNumber` / `epByNumber` = the show's seasons by number and episodes by '<s>x<e>', as the TMDB step left them.
  216. // Answers { tvmazeRequests, newSeasons, newEpisodes, filledEpisodes, skipped, errors, error, showSeasons }.
  217. static mergeTvmaze = (title, showKey, tvmzId, seasonsIn, episodesIn, showSeasonsIn) => {
  218. let seasonsByNumber = seasonsIn
  219. let epByNumber = episodesIn
  220. let out = { tvmazeRequests = 1 newSeasons = 0 newEpisodes = 0 filledEpisodes = 0 skipped = 0 errors = 0 error = '' showSeasons = showSeasonsIn }
  221. let got = tvmazeEpisodes(tvmzId)
  222. if (got.failed != null) { out.errors = 1 out.error = title + ': ' + got.failed return out }
  223. // the numbered episodes TVmaze has in seasons we take (no specials; season 0 only when the show has one)
  224. let list = []
  225. for (te of got.list) {
  226. if (numIdOr(te.season) != null && numIdOr(te.number) != null) { list.push(te) }
  227. else if (te.season == 0 && numIdOr(te.number) != null && seasonsByNumber['0'] != null) { list.push(te) }
  228. }
  229. if (!numberingAgrees(epByNumber, list).ok) { out.skipped = 1 return out }
  230. let added = {}
  231. let addedFirstDate = {}
  232. for (te of list) {
  233. let key = te.season + 'x' + te.number
  234. let e = epByNumber[key]
  235. if (e == null) {
  236. let seasonKey = seasonsByNumber['' + te.season] != null ? seasonsByNumber['' + te.season].id : null
  237. if (seasonKey == null) {
  238. if (added['' + te.season] == null) { added['' + te.season] = [] addedFirstDate['' + te.season] = textOr(te.airdate) seasonsByNumber['' + te.season] = { id = newId() isNew = true } }
  239. seasonKey = seasonsByNumber['' + te.season].id
  240. }
  241. let fresh = { id = newId() episodeNumber = te.number seasonNumber = te.season
  242. title = textOr(te.name) summary = '' release = textOr(te.airdate)
  243. show = showKey season = seasonKey tmdbId = null tvmzId = te.id oldId = 'tvmaze-episode:' + te.id }
  244. if (episodesTable.put(fresh) == null) {
  245. out.errors = out.errors + 1
  246. out.error = title + ': TVmaze episode ' + te.id + ' not stored: ' + episodesTable.lastError()
  247. } else {
  248. if (added['' + te.season] == null) { added['' + te.season] = [] }
  249. let l = added['' + te.season]
  250. l.push(fresh.id)
  251. added['' + te.season] = l
  252. epByNumber[key] = fresh
  253. out.newEpisodes = out.newEpisodes + 1
  254. }
  255. } else {
  256. let changed = false
  257. if (isPlaceholderTitle(e.title) && !isPlaceholderTitle(te.name)) { e.title = te.name changed = true }
  258. if (textOr(e.release) == null && textOr(te.airdate) != null) { e.release = te.airdate changed = true }
  259. if (changed) {
  260. if (episodesTable.update(e.id, e) == null) {
  261. out.errors = out.errors + 1
  262. out.error = title + ': episode ' + e.id + ' not filled from TVmaze: ' + episodesTable.lastError()
  263. } else {
  264. epByNumber[key] = e
  265. out.filledEpisodes = out.filledEpisodes + 1
  266. }
  267. }
  268. }
  269. }
  270. // the seasons that got episodes: an existing one is updated, a new one stored and linked to the show
  271. let showSeasons = []
  272. for (sid of showSeasonsIn) { showSeasons.push(sid) }
  273. for (n of added.keys()) {
  274. let ids = added[n]
  275. let s = seasonsByNumber[n]
  276. if (ids.length > 0 && s.isNew == true) {
  277. let season = { id = s.id seasonNumber = toNumber(n) title = 'Season ' + n release = addedFirstDate[n] summary = ''
  278. show = showKey episodes = ids oldId = 'tvmaze-season:' + tvmzId + ':' + n }
  279. if (seasonsTable.put(season) == null) {
  280. out.errors = out.errors + 1
  281. out.error = title + ': TVmaze season ' + n + ' not stored: ' + seasonsTable.lastError()
  282. } else {
  283. showSeasons.push(season.id)
  284. out.newSeasons = out.newSeasons + 1
  285. }
  286. } else if (ids.length > 0) {
  287. let season = seasonsTable.fetch(s.id)
  288. let eps = []
  289. for (eid of season.episodes) { eps.push(eid) }
  290. for (eid of ids) { eps.push(eid) }
  291. season.episodes = eps
  292. if (seasonsTable.update(season.id, season) == null) {
  293. out.errors = out.errors + 1
  294. out.error = title + ': season ' + season.id + ' not updated: ' + seasonsTable.lastError()
  295. }
  296. }
  297. }
  298. out.showSeasons = showSeasons
  299. return out
  300. }
  301. // ---- posters ----------------------------------------------------------------------------------
  302. // the extension of a TMDB poster_path ('/abc.jpg' → 'jpg'); only the ones the poster route knows
  303. static posterExt = (posterPath) => {
  304. let parts = posterPath.split('.')
  305. let ext = parts[parts.length - 1].toLowerCase()
  306. if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'webp') { return ext }
  307. return null
  308. }
  309. // downloads the w342 poster when the file is missing or TMDB has a new one; answers { requests, saved, failed }
  310. // and sets show.image / show.tmdbPoster on the (caller's) record — the file is <oldId>.<ext>, the name
  311. // shows.hl posterName() already builds, served by project.hl's /posters/:name route
  312. static syncPoster = (show, posterPath) => {
  313. let out = { requests = 0 saved = 0 failed = null image = show.image tmdbPoster = show.tmdbPoster }
  314. if (textOr(posterPath) == null || show.oldId == null) { return out }
  315. let ext = posterExt(posterPath)
  316. if (ext == null) { return out }
  317. let file = postersDir + '/' + show.oldId + '.' + ext
  318. if (exists(file) && show.tmdbPoster == posterPath && show.image == ext) { return out }
  319. out.requests = 1
  320. let r = fetch(tmdbImageBase + '/w342' + posterPath, { headers = { 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })
  321. if (r == null || r.status != 200 || r.body == null || r.body.length == 0) {
  322. out.failed = 'poster ' + posterPath + ': ' + (r == null ? 'no answer' : 'HTTP ' + r.status)
  323. return out
  324. }
  325. mkDir(postersDir)
  326. writeFile(file, toBytes(r.body), 420)
  327. out.saved = 1
  328. out.image = ext
  329. out.tmdbPoster = posterPath
  330. return out
  331. }
  332. // ---- one show -----------------------------------------------------------------------------------
  333. static newId = () => { return randomBytes(8, 'hex') }
  334. // TMDB's adult flag of a details/search answer: true / false, null when it has none (mission 054)
  335. static adultOf = (j) => {
  336. if (j == null) { return null }
  337. if (j.adult == true) { return true }
  338. if (j.adult == false) { return false }
  339. return null
  340. }
  341. // which TMDB seasons to sync: every numbered one with episodes; 0 only when the show has a season 0 already
  342. static wantedSeasonNumbers = (details, localByNumber) => {
  343. let out = []
  344. if (details.seasons == null) { return out }
  345. for (s of details.seasons) {
  346. let n = s.season_number
  347. if (n != null && (n > 0 || localByNumber['' + n] != null) && (s.episode_count == null || s.episode_count > 0 || localByNumber['' + n] != null)) { out.push(n) }
  348. }
  349. return out
  350. }
  351. // the seasons in batches of 20 (TMDB's append_to_response limit)
  352. static batchesOf = (list, size) => {
  353. let out = []
  354. let cur = []
  355. for (x of list) {
  356. cur.push(x)
  357. if (cur.length == size) { out.push(cur) cur = [] }
  358. }
  359. if (cur.length > 0) { out.push(cur) }
  360. return out
  361. }
  362. // fields of an episode/season from TMDB that differ from the stored record (null/empty never overwrites)
  363. static changedText = (stored, fresh) => { return fresh != null && fresh != stored }
  364. // a MOVIE: one request — its imdb id (if missing) and its poster; nothing else of the record is touched. `pre` = that
  365. // request's answer when the caller already made it (details.hl firstStep, tracker#26), else null
  366. static syncMovie = (show, res, pre) => {
  367. let out = res
  368. out.requests = 1
  369. let details = pre != null ? pre : tmdbGet('/movie/' + show.tmdbId + '?append_to_response=external_ids,credits')
  370. if (details.failed != null) { out.errors = 1 out.error = show.title + ': ' + details.failed return out }
  371. if (pre == null) { out.details = details }
  372. let ids = externalIdsFor(show, details.external_ids, false, false)
  373. out.ids = ids.filled
  374. let poster = syncPoster(show, details.poster_path)
  375. out.requests = out.requests + poster.requests
  376. out.posters = poster.saved
  377. if (poster.failed != null) { out.errors = out.errors + 1 out.error = show.title + ': ' + poster.failed }
  378. let m = show
  379. m.imdbId = ids.imdbId
  380. m.image = poster.image
  381. m.tmdbPoster = poster.tmdbPoster
  382. if (adultOf(details) != null) { m.adult = adultOf(details) }
  383. m.tmdbSync = now()
  384. if (showsTable.update(m.id, m) == null) { out.errors = out.errors + 1 out.error = show.title + ': movie not updated: ' + showsTable.lastError() }
  385. return out
  386. }
  387. // Sync ONE show (by our id). Answers counts: { requests, tvmazeRequests, newSeasons, newEpisodes, updatedEpisodes,
  388. // updatedSeasons, posters, ids, tvmazeEpisodes, tvmazeSeasons, tvmazeFilled, tvmazeSkipped, errors, error } + `details` (the
  389. // details answer with its credits when this call asked for it, else null — tracker#28: the caller stores the credits). Never throws for a TMDB failure — it is counted and the show left as is.
  390. static syncShow = (showId) => { return syncShowPart(showId, null, null) }
  391. // the same with the details request (`/tv|movie/<id>?append_to_response=external_ids…`) already answered — `pre`, counted as
  392. // this show's first request — so details.hl (tracker#26) asks TMDB once for details, ids AND the cast
  393. static syncShowWith = (showId, pre) => { return syncShowPart(showId, pre, null) }
  394. // ONE PART of a series' sync (tracker#26: a talk show with 4,000 episodes took 10 s in one step, blocking every request):
  395. // `only` = { seasons (the TMDB season numbers of this part), finish (false: only those seasons — new ones linked to the show,
  396. // nothing else; true: the ids, TVmaze, poster and the show record) }; null = everything at once. `pre` is required with
  397. // `only` (its request is the caller's: a part counts only its own requests).
  398. static syncShowPart = (showId, pre, only) => {
  399. let res = { requests = 0 tvmazeRequests = 0 newSeasons = 0 newEpisodes = 0 updatedEpisodes = 0 updatedSeasons = 0 posters = 0 ids = 0 tvmazeEpisodes = 0 tvmazeSeasons = 0 tvmazeFilled = 0 tvmazeSkipped = 0 errors = 0 error = '' details = null }
  400. let show = showsTable.fetch(showId)
  401. if (show == null) { res.errors = 1 res.error = 'no show ' + showId return res }
  402. if (show.tmdbId == null) { res.errors = 1 res.error = show.title + ': no tmdbId' return res }
  403. if (show.type == 'movie') { return syncMovie(show, res, pre) }
  404. res.requests = only != null ? 0 : 1
  405. let details = pre != null ? pre : tmdbGet('/tv/' + show.tmdbId + '?append_to_response=external_ids,aggregate_credits')
  406. if (details.failed != null) { res.errors = 1 res.error = show.title + ': ' + details.failed return res }
  407. if (pre == null) { res.details = details }
  408. // what we have: seasons by number, episodes by tmdbId and by S/E number
  409. let seasonsByNumber = {}
  410. let epByTmdb = {}
  411. let epByNumber = {}
  412. for (sid of show.seasons) {
  413. let s = seasonsTable.fetch(sid)
  414. if (s != null) {
  415. seasonsByNumber['' + s.seasonNumber] = s
  416. for (eid of s.episodes) {
  417. let e = episodesTable.fetch(eid)
  418. if (e != null) {
  419. if (e.tmdbId != null) { epByTmdb['' + e.tmdbId] = e }
  420. epByNumber[e.seasonNumber + 'x' + e.episodeNumber] = e
  421. }
  422. }
  423. }
  424. }
  425. // plain locals for the record literals below: inside a literal, an entry named `show`/`season` would shadow
  426. // the variable for every later entry (SPEC "A literal's entries are evaluated in order")
  427. let showKey = show.id
  428. let showTmdb = show.tmdbId
  429. let showSeasons = []
  430. for (sid of show.seasons) { showSeasons.push(sid) }
  431. let showChanged = false
  432. let wanted = wantedSeasonNumbers(details, seasonsByNumber)
  433. if (only != null) {
  434. let part = []
  435. for (n of wanted) { if (only.seasons.includes(n)) { part.push(n) } }
  436. wanted = part
  437. }
  438. for (batch of batchesOf(wanted, 20)) {
  439. let names = []
  440. for (n of batch) { names.push('season/' + n) }
  441. res.requests = res.requests + 1
  442. let withSeasons = tmdbGet('/tv/' + show.tmdbId + '?append_to_response=' + names.join(','))
  443. if (withSeasons.failed != null) {
  444. res.errors = res.errors + 1
  445. res.error = show.title + ': ' + withSeasons.failed
  446. } else {
  447. for (n of batch) {
  448. let ts = withSeasons['season/' + n]
  449. if (ts != null && ts.episodes != null) {
  450. let season = seasonsByNumber['' + n]
  451. let seasonIsNew = season == null
  452. let seasonChanged = false
  453. if (seasonIsNew) {
  454. season = { id = newId() seasonNumber = n title = textOr(ts.name) != null ? ts.name : 'Season ' + n
  455. release = textOr(ts.air_date) summary = textOr(ts.overview) != null ? ts.overview : ''
  456. show = showKey episodes = [] oldId = 'tmdb-season:' + showTmdb + ':' + n }
  457. } else {
  458. if (changedText(season.title, textOr(ts.name))) { season.title = ts.name seasonChanged = true }
  459. if (changedText(season.summary, textOr(ts.overview))) { season.summary = ts.overview seasonChanged = true }
  460. if (changedText(season.release, textOr(ts.air_date))) { season.release = ts.air_date seasonChanged = true }
  461. }
  462. let seasonKey = season.id
  463. let seasonEpisodes = []
  464. for (eid of season.episodes) { seasonEpisodes.push(eid) }
  465. for (te of ts.episodes) {
  466. if (te.id != null && te.episode_number != null) {
  467. let e = epByTmdb['' + te.id]
  468. if (e == null) {
  469. let byNum = epByNumber[n + 'x' + te.episode_number]
  470. if (byNum != null && byNum.tmdbId == null) { e = byNum }
  471. }
  472. if (e == null) {
  473. let fresh = { id = newId() episodeNumber = te.episode_number seasonNumber = n
  474. title = textOr(te.name) summary = textOr(te.overview) != null ? te.overview : '' release = textOr(te.air_date)
  475. show = showKey season = seasonKey tmdbId = te.id oldId = 'tmdb-episode:' + te.id }
  476. let putId = episodesTable.put(fresh)
  477. if (putId == null) {
  478. res.errors = res.errors + 1
  479. res.error = show.title + ': episode ' + te.id + ' not stored: ' + episodesTable.lastError()
  480. } else {
  481. seasonEpisodes.push(fresh.id)
  482. epByTmdb['' + te.id] = fresh
  483. epByNumber[n + 'x' + te.episode_number] = fresh
  484. res.newEpisodes = res.newEpisodes + 1
  485. seasonChanged = true
  486. }
  487. } else {
  488. let changed = false
  489. if (e.tmdbId == null) { e.tmdbId = te.id changed = true }
  490. // #15: TMDB's "Episode 4" never replaces a real title (one TVmaze filled, or the migrated one)
  491. if (changedText(e.title, textOr(te.name)) && !(isPlaceholderTitle(te.name) && !isPlaceholderTitle(e.title))) { e.title = te.name changed = true }
  492. if (changedText(e.summary, textOr(te.overview))) { e.summary = te.overview changed = true }
  493. if (changedText(e.release, textOr(te.air_date))) { e.release = te.air_date changed = true }
  494. if (changed) {
  495. if (episodesTable.update(e.id, e) == null) {
  496. res.errors = res.errors + 1
  497. res.error = show.title + ': episode ' + e.id + ' not updated: ' + episodesTable.lastError()
  498. } else {
  499. epByTmdb['' + e.tmdbId] = e
  500. epByNumber[e.seasonNumber + 'x' + e.episodeNumber] = e
  501. res.updatedEpisodes = res.updatedEpisodes + 1
  502. }
  503. }
  504. }
  505. }
  506. }
  507. season.episodes = seasonEpisodes
  508. if (seasonIsNew) {
  509. if (seasonsTable.put(season) == null) {
  510. res.errors = res.errors + 1
  511. res.error = show.title + ': season ' + n + ' not stored: ' + seasonsTable.lastError()
  512. } else {
  513. seasonsByNumber['' + n] = season
  514. showSeasons.push(season.id)
  515. showChanged = true
  516. res.newSeasons = res.newSeasons + 1
  517. }
  518. } else if (seasonChanged) {
  519. if (seasonsTable.update(season.id, season) == null) {
  520. res.errors = res.errors + 1
  521. res.error = show.title + ': season ' + season.id + ' not updated: ' + seasonsTable.lastError()
  522. } else {
  523. res.updatedSeasons = res.updatedSeasons + 1
  524. }
  525. }
  526. }
  527. }
  528. }
  529. }
  530. // a part that is not the last: only the new seasons are linked to the show (the next part reads them)
  531. if (only != null && !only.finish) {
  532. if (showChanged) {
  533. show.seasons = showSeasons
  534. if (showsTable.update(show.id, show) == null) { res.errors = res.errors + 1 res.error = show.title + ': show not updated: ' + showsTable.lastError() }
  535. }
  536. return res
  537. }
  538. // the external ids (tracker.worldapi.org#12): missing ones from TMDB's external_ids, a missing TVmaze id from TVmaze
  539. let ids = externalIdsFor(show, details.external_ids, true, true)
  540. res.ids = ids.filled
  541. res.tvmazeRequests = ids.tvmazeRequests
  542. if (ids.failed != null) { res.errors = res.errors + 1 res.error = show.title + ': ' + ids.failed }
  543. // tracker.worldapi.org#15: what TVmaze has and TMDB not yet (new episodes/seasons, empty titles and air dates)
  544. if (numIdOr(ids.tvmzId) != null) {
  545. let tvm = mergeTvmaze(show.title, showKey, ids.tvmzId, seasonsByNumber, epByNumber, showSeasons)
  546. res.tvmazeRequests = res.tvmazeRequests + tvm.tvmazeRequests
  547. res.tvmazeEpisodes = tvm.newEpisodes
  548. res.tvmazeSeasons = tvm.newSeasons
  549. res.tvmazeFilled = tvm.filledEpisodes
  550. res.tvmazeSkipped = tvm.skipped
  551. if (tvm.errors > 0) { res.errors = res.errors + tvm.errors res.error = tvm.error }
  552. showSeasons = tvm.showSeasons
  553. }
  554. // the show itself: status, counts, TMDB's overview, the poster, when it was synced
  555. let poster = syncPoster(show, details.poster_path)
  556. res.requests = res.requests + poster.requests
  557. res.posters = poster.saved
  558. if (poster.failed != null) { res.errors = res.errors + 1 res.error = show.title + ': ' + poster.failed }
  559. show.seasons = showSeasons
  560. if (textOr(details.status) != null) { show.status = details.status }
  561. if (details.number_of_seasons != null) { show.seasonsCount = details.number_of_seasons }
  562. if (details.number_of_episodes != null) { show.episodesCount = details.number_of_episodes }
  563. if (textOr(details.overview) != null) { show.tmdbSummary = details.overview }
  564. show.image = poster.image
  565. show.tmdbPoster = poster.tmdbPoster
  566. show.imdbId = ids.imdbId
  567. show.tvdbId = ids.tvdbId
  568. show.tvmzId = ids.tvmzId
  569. if (adultOf(details) != null) { show.adult = adultOf(details) }
  570. show.tmdbSync = now()
  571. if (showsTable.update(show.id, show) == null) { res.errors = res.errors + 1 res.error = show.title + ': show not updated: ' + showsTable.lastError() }
  572. return res
  573. }
  574. // ---- the adult backfill (mission 054) ------------------------------------------------------------
  575. // a title still to ask: its adult flag unknown, it has a tmdbId and TMDB never answered "no such title" for it
  576. static needsAdultFlag = (show) => { return show.adult != true && show.adult != false && show.adultCheck == null && show.tmdbId != null }
  577. // the ids of every title the backfill still has to ask, in table order (read once when the backfill starts — so after a
  578. // restart it goes on with what is left)
  579. static adultBackfillQueue = () => {
  580. let out = []
  581. for (s of showsTable.find(null, null)) { if (needsAdultFlag(s)) { out.push(s.id) } }
  582. return out
  583. }
  584. // ONE title: one TMDB details request (adult, poster_path, external ids) + its poster when the file is missing. Answers
  585. // { requests (TMDB API requests: what the pause counts), posters, adult (true / false / null), ids, errors, error, retry
  586. // (a passing failure: no answer, 429, 5xx — ask again later) }. A 404 marks the title `adultCheck` (never asked again).
  587. static backfillTitle = (showId) => {
  588. let out = { requests = 0 posters = 0 adult = null ids = 0 errors = 0 error = '' retry = false }
  589. let show = showsTable.fetch(showId)
  590. if (show == null || !needsAdultFlag(show)) { return out }
  591. let movie = show.type == 'movie'
  592. out.requests = 1
  593. let details = tmdbGet((movie ? '/movie/' : '/tv/') + show.tmdbId + '?append_to_response=external_ids')
  594. if (details.failed != null) {
  595. out.errors = 1
  596. out.error = show.title + ': ' + details.failed
  597. if (details.status == 404) {
  598. show.adultCheck = 'TMDB 404'
  599. showsTable.update(show.id, show)
  600. } else { out.retry = true }
  601. return out
  602. }
  603. let ids = externalIdsFor(show, details.external_ids, !movie, false)
  604. out.ids = ids.filled
  605. out.adult = adultOf(details)
  606. // an ADULT title's poster is never shown publicly → not downloaded (mission 056: ~170 MB of the live data); its flag and
  607. // ids are stored as for any other title
  608. let poster = { saved = 0 failed = null image = show.image tmdbPoster = show.tmdbPoster }
  609. if (out.adult != true) { poster = syncPoster(show, details.poster_path) }
  610. out.posters = poster.saved
  611. if (poster.failed != null) { out.errors = out.errors + 1 out.error = show.title + ': ' + poster.failed }
  612. if (out.adult == null) { show.adultCheck = 'TMDB gave no adult flag' } else { show.adult = out.adult }
  613. show.imdbId = ids.imdbId
  614. show.tvdbId = ids.tvdbId
  615. show.image = poster.image
  616. show.tmdbPoster = poster.tmdbPoster
  617. if (showsTable.update(show.id, show) == null) { out.errors = out.errors + 1 out.error = show.title + ': not updated: ' + showsTable.lastError() }
  618. return out
  619. }
  620. // flush the three tables' index/meta state to disk (after a run, and every few shows)
  621. static persistSync = () => {
  622. showsTable.persist()
  623. seasonsTable.persist()
  624. episodesTable.persist()
  625. return true
  626. }
  627. // totals of a run: the per-show counts added up
  628. static emptyTotals = () => { return { shows = 0 requests = 0 tvmazeRequests = 0 newSeasons = 0 newEpisodes = 0 updatedEpisodes = 0 updatedSeasons = 0 posters = 0 ids = 0 tvmazeEpisodes = 0 tvmazeSeasons = 0 tvmazeFilled = 0 tvmazeSkipped = 0 errors = 0 } }
  629. static addTotals = (t, r) => {
  630. let o = t
  631. o.shows = o.shows + 1
  632. o.requests = o.requests + r.requests
  633. o.tvmazeRequests = o.tvmazeRequests + r.tvmazeRequests
  634. o.ids = o.ids + r.ids
  635. o.newSeasons = o.newSeasons + r.newSeasons
  636. o.newEpisodes = o.newEpisodes + r.newEpisodes
  637. o.updatedEpisodes = o.updatedEpisodes + r.updatedEpisodes
  638. o.updatedSeasons = o.updatedSeasons + r.updatedSeasons
  639. o.posters = o.posters + r.posters
  640. o.tvmazeEpisodes = o.tvmazeEpisodes + r.tvmazeEpisodes
  641. o.tvmazeSeasons = o.tvmazeSeasons + r.tvmazeSeasons
  642. o.tvmazeFilled = o.tvmazeFilled + r.tvmazeFilled
  643. o.tvmazeSkipped = o.tvmazeSkipped + r.tvmazeSkipped
  644. o.errors = o.errors + r.errors
  645. return o
  646. }
  647. static totalsLine = (t) => {
  648. return 'shows=' + t.shows + ' newSeasons=' + t.newSeasons + ' newEpisodes=' + t.newEpisodes + ' updatedEpisodes=' + t.updatedEpisodes
  649. + ' updatedSeasons=' + t.updatedSeasons + ' posters=' + t.posters + ' ids=' + t.ids + ' requests=' + t.requests + ' tvmazeRequests=' + t.tvmazeRequests + ' errors=' + t.errors
  650. + ' tvmazeEpisodes=' + t.tvmazeEpisodes + ' tvmazeSeasons=' + t.tvmazeSeasons + ' tvmazeFilled=' + t.tvmazeFilled + ' tvmazeSkipped=' + t.tvmazeSkipped
  651. }

Branches

Latest commits

  • 10bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre
  • 25a50bc4tracker#26 (mission 059): titles from a filmography are completed — on open (skeleton, step-wise face showComplete, no reload) and by the in-app details repair (resumes, TMDB-paced, series in parts); cast from TMDB credits; gate 231, tests/realdata-026.mjs, README + STATUSmre
  • 1704ec45tracker#17 (mission 057): season caret down/up, skeleton rows while a season loads, sessionless showSeasonEpisodes face (no page re-mount), client-only close; gate 214, tests/realdata-057.mjs, README + STATUSmre
  • f2fe3e36mission 056: README + STATUS (merge, fixes, Hybriel 8590df63, real-data check), tests/realdata-056.mjs, tools/check-public-slugs.hlmre
  • f40c250emission 056: re-vendor hybriel master 8590df63 (#121, #122); an adult title's page is Not found for non-followers; gate: leave the page before stopping the servermre
  • 2b7fdd6cmission 056: signed-out header one row on phones ("Log in", nowrap), backfill skips adult titles' posters, gate checksmre
  • 2c53d5efMerge branch 't16-person' (tracker#16 person pages) into main; filmography shows only public titles (054 adult flag), gate race fix (backfill start line)mre
  • c171227emission 054: hide adult/unknown titles from the public lists and the search; in-app adult-flag backfill (TMDB details + poster per title, resumes), gate + real-data proofmre
  • 139fafd8tracker#16: short bio (4 lines, click = all), real-data check script, README + STATUSmre
  • 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