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/tmdbsync.hl

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

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