gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit0553b51f0553b51ftracker#19 (mission 066): franchises and timelines — tables, /franchises, /franchises/<slug>, /timelines/<slug> (Timeline | Release sort, series by last episode), the Prequel | Timeline | Sequel widget with the franchise above, the creator's editor, TMDB collection seed in the app (resumes, paced); gate tests/franchises.mjs 48/0 + browser.mjs 266/0, tests/realdata-066.mjs, docs/franchises.md, README + STATUSmre0553b51f/tmdbsync.hl

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

Branches

Latest commits

  • 0553b51ftracker#19 (mission 066): franchises and timelines — tables, /franchises, /franchises/<slug>, /timelines/<slug> (Timeline | Release sort, series by last episode), the Prequel | Timeline | Sequel widget with the franchise above, the creator's editor, TMDB collection seed in the app (resumes, paced); gate tests/franchises.mjs 48/0 + browser.mjs 266/0, tests/realdata-066.mjs, docs/franchises.md, README + STATUSmre
  • fa1f9dfatracker#29 (mission 063): unwatched check muted grey outline + check (accent only on hover), watched stays solid — no code regression, the accent outline read as ticked; gate checks real checks visibly (computed style + screenshot pixel) on /my/unwatched, show, movie, /my/movies; gate 266, tests/realdata-063.mjs, README + STATUSmre
  • d8b12d67tracker#27 (mission 060): short ids for movies, series and persons — old 702 kept (data/old-short-ids.json), new random [a-z0-9]{5} unique across both, claimed at creation, background backfill (resumes), shown under poster/photo, /<shortId> → 301; gate 259, tests/realdata-060*, README + STATUSmre
  • f14db671tracker#22-#25 (mission 058): episode air dates, season check = all episodes watched, movie watched check (+ /my/movies count), /genres/<genre> pages (movies + series, newest first, paginated); gate 238, tests/realdata-058.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