gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit34f2c15b34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre34f2c15b/tmdbsync.hl

28.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),
  37. // TVmaze is ignored for that show (`tvmazeSkipped`). Summaries are not taken (TVmaze's are HTML; the ticket asks for
  38. // 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)
  134. static isPlaceholderTitle = (v) => {
  135. let t = textOr(v)
  136. if (t == null) { return true }
  137. let l = t.trim().toLowerCase()
  138. if (l == 'tba' || l == 'tbd' || l == 'tba.' || l == 'to be announced') { return true }
  139. if (!l.startsWith('episode ') || l.length < 9) { return false }
  140. let i = 8
  141. while (i < l.length) {
  142. if (!'0123456789'.includes(l[i])) { return false }
  143. i = i + 1
  144. }
  145. return true
  146. }
  147. // 'YYYY-MM-DD' → a day number (only differences matter), null when it is no such date
  148. static dayNumber = (v) => {
  149. let t = textOr(v)
  150. if (t == null || t.length < 10) { return null }
  151. let y = toNumber(t.slice(0, 4))
  152. let m = toNumber(t.slice(5, 7))
  153. let d = toNumber(t.slice(8, 10))
  154. if (y == null || m == null || d == null || m < 1 || m > 12) { return null }
  155. let before = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  156. let py = m <= 2 ? y - 1 : y
  157. let leaps = (py - py % 4) / 4 - (py - py % 100) / 100 + (py - py % 400) / 400
  158. return y * 365 + leaps + before[m - 1] + d
  159. }
  160. static daysApart = (a, b) => {
  161. let x = dayNumber(a)
  162. let y = dayNumber(b)
  163. if (x == null || y == null) { return null }
  164. return x > y ? x - y : y - x
  165. }
  166. // TVmaze's episode list of one show: a list, or { failed }
  167. static tvmazeEpisodes = (tvmzId) => {
  168. let r = fetch(tvmazeBase + '/shows/' + tvmzId + '/episodes', { headers = { 'accept' = 'application/json' 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })
  169. if (r == null || r.status == null || r.status == 0) { return { failed = 'TVmaze: no answer for episodes of ' + tvmzId } }
  170. if (r.status != 200) { return { failed = 'TVmaze: HTTP ' + r.status + ' for episodes of ' + tvmzId } }
  171. let j = r.json()
  172. if (j == null || j.length == null) { return { failed = 'TVmaze: no episode list for ' + tvmzId } }
  173. return { list = j }
  174. }
  175. // Merge TVmaze's episodes of a series into what we have AFTER the TMDB step (gaps only, rules at the top).
  176. // `seasonsByNumber` / `epByNumber` = the show's seasons by number and episodes by '<s>x<e>', as the TMDB step left them.
  177. // Answers { tvmazeRequests, newSeasons, newEpisodes, filledEpisodes, skipped, errors, error, showSeasons }.
  178. static mergeTvmaze = (title, showKey, tvmzId, seasonsIn, episodesIn, showSeasonsIn) => {
  179. let seasonsByNumber = seasonsIn
  180. let epByNumber = episodesIn
  181. let out = { tvmazeRequests = 1 newSeasons = 0 newEpisodes = 0 filledEpisodes = 0 skipped = 0 errors = 0 error = '' showSeasons = showSeasonsIn }
  182. let got = tvmazeEpisodes(tvmzId)
  183. if (got.failed != null) { out.errors = 1 out.error = title + ': ' + got.failed return out }
  184. // the numbered episodes TVmaze has in seasons we take (no specials; season 0 only when the show has one)
  185. let list = []
  186. for (te of got.list) {
  187. if (numIdOr(te.season) != null && numIdOr(te.number) != null) { list.push(te) }
  188. else if (te.season == 0 && numIdOr(te.number) != null && seasonsByNumber['0'] != null) { list.push(te) }
  189. }
  190. // do both number the show the same way? the episodes both know must (mostly) air on the same day
  191. let known = 0
  192. let localCount = 0
  193. for (k of epByNumber.keys()) { localCount = localCount + 1 }
  194. let dated = 0
  195. let agree = 0
  196. for (te of list) {
  197. let e = epByNumber[te.season + 'x' + te.number]
  198. if (e != null) {
  199. known = known + 1
  200. let apart = daysApart(e.release, te.airdate)
  201. if (apart != null) {
  202. dated = dated + 1
  203. if (apart <= 1) { agree = agree + 1 }
  204. }
  205. }
  206. }
  207. if ((localCount > 0 && known == 0) || (dated > 0 && agree * 5 < dated * 4)) { out.skipped = 1 return out }
  208. let added = {}
  209. let addedFirstDate = {}
  210. for (te of list) {
  211. let key = te.season + 'x' + te.number
  212. let e = epByNumber[key]
  213. if (e == null) {
  214. let seasonKey = seasonsByNumber['' + te.season] != null ? seasonsByNumber['' + te.season].id : null
  215. if (seasonKey == null) {
  216. if (added['' + te.season] == null) { added['' + te.season] = [] addedFirstDate['' + te.season] = textOr(te.airdate) seasonsByNumber['' + te.season] = { id = newId() isNew = true } }
  217. seasonKey = seasonsByNumber['' + te.season].id
  218. }
  219. let fresh = { id = newId() episodeNumber = te.number seasonNumber = te.season
  220. title = textOr(te.name) summary = '' release = textOr(te.airdate)
  221. show = showKey season = seasonKey tmdbId = null tvmzId = te.id oldId = 'tvmaze-episode:' + te.id }
  222. if (episodesTable.put(fresh) == null) {
  223. out.errors = out.errors + 1
  224. out.error = title + ': TVmaze episode ' + te.id + ' not stored: ' + episodesTable.lastError()
  225. } else {
  226. if (added['' + te.season] == null) { added['' + te.season] = [] }
  227. let l = added['' + te.season]
  228. l.push(fresh.id)
  229. added['' + te.season] = l
  230. epByNumber[key] = fresh
  231. out.newEpisodes = out.newEpisodes + 1
  232. }
  233. } else {
  234. let changed = false
  235. if (isPlaceholderTitle(e.title) && !isPlaceholderTitle(te.name)) { e.title = te.name changed = true }
  236. if (textOr(e.release) == null && textOr(te.airdate) != null) { e.release = te.airdate changed = true }
  237. if (changed) {
  238. if (episodesTable.update(e.id, e) == null) {
  239. out.errors = out.errors + 1
  240. out.error = title + ': episode ' + e.id + ' not filled from TVmaze: ' + episodesTable.lastError()
  241. } else {
  242. epByNumber[key] = e
  243. out.filledEpisodes = out.filledEpisodes + 1
  244. }
  245. }
  246. }
  247. }
  248. // the seasons that got episodes: an existing one is updated, a new one stored and linked to the show
  249. let showSeasons = []
  250. for (sid of showSeasonsIn) { showSeasons.push(sid) }
  251. for (n of added.keys()) {
  252. let ids = added[n]
  253. let s = seasonsByNumber[n]
  254. if (ids.length > 0 && s.isNew == true) {
  255. let season = { id = s.id seasonNumber = toNumber(n) title = 'Season ' + n release = addedFirstDate[n] summary = ''
  256. show = showKey episodes = ids oldId = 'tvmaze-season:' + tvmzId + ':' + n }
  257. if (seasonsTable.put(season) == null) {
  258. out.errors = out.errors + 1
  259. out.error = title + ': TVmaze season ' + n + ' not stored: ' + seasonsTable.lastError()
  260. } else {
  261. showSeasons.push(season.id)
  262. out.newSeasons = out.newSeasons + 1
  263. }
  264. } else if (ids.length > 0) {
  265. let season = seasonsTable.fetch(s.id)
  266. let eps = []
  267. for (eid of season.episodes) { eps.push(eid) }
  268. for (eid of ids) { eps.push(eid) }
  269. season.episodes = eps
  270. if (seasonsTable.update(season.id, season) == null) {
  271. out.errors = out.errors + 1
  272. out.error = title + ': season ' + season.id + ' not updated: ' + seasonsTable.lastError()
  273. }
  274. }
  275. }
  276. out.showSeasons = showSeasons
  277. return out
  278. }
  279. // ---- posters ----------------------------------------------------------------------------------
  280. // the extension of a TMDB poster_path ('/abc.jpg' → 'jpg'); only the ones the poster route knows
  281. static posterExt = (posterPath) => {
  282. let parts = posterPath.split('.')
  283. let ext = parts[parts.length - 1].toLowerCase()
  284. if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'webp') { return ext }
  285. return null
  286. }
  287. // downloads the w342 poster when the file is missing or TMDB has a new one; answers { requests, saved, failed }
  288. // and sets show.image / show.tmdbPoster on the (caller's) record — the file is <oldId>.<ext>, the name
  289. // shows.hl posterName() already builds, served by project.hl's /posters/:name route
  290. static syncPoster = (show, posterPath) => {
  291. let out = { requests = 0 saved = 0 failed = null image = show.image tmdbPoster = show.tmdbPoster }
  292. if (textOr(posterPath) == null || show.oldId == null) { return out }
  293. let ext = posterExt(posterPath)
  294. if (ext == null) { return out }
  295. let file = postersDir + '/' + show.oldId + '.' + ext
  296. if (exists(file) && show.tmdbPoster == posterPath && show.image == ext) { return out }
  297. out.requests = 1
  298. let r = fetch(tmdbImageBase + '/w342' + posterPath, { headers = { 'user-agent' = 'tracker.worldapi.org (tmdb sync)' } timeoutMs = 20000 })
  299. if (r == null || r.status != 200 || r.body == null || r.body.length == 0) {
  300. out.failed = 'poster ' + posterPath + ': ' + (r == null ? 'no answer' : 'HTTP ' + r.status)
  301. return out
  302. }
  303. mkDir(postersDir)
  304. writeFile(file, toBytes(r.body), 420)
  305. out.saved = 1
  306. out.image = ext
  307. out.tmdbPoster = posterPath
  308. return out
  309. }
  310. // ---- one show -----------------------------------------------------------------------------------
  311. static newId = () => { return randomBytes(8, 'hex') }
  312. // which TMDB seasons to sync: every numbered one with episodes; 0 only when the show has a season 0 already
  313. static wantedSeasonNumbers = (details, localByNumber) => {
  314. let out = []
  315. if (details.seasons == null) { return out }
  316. for (s of details.seasons) {
  317. let n = s.season_number
  318. if (n != null && (n > 0 || localByNumber['' + n] != null) && (s.episode_count == null || s.episode_count > 0 || localByNumber['' + n] != null)) { out.push(n) }
  319. }
  320. return out
  321. }
  322. // the seasons in batches of 20 (TMDB's append_to_response limit)
  323. static batchesOf = (list, size) => {
  324. let out = []
  325. let cur = []
  326. for (x of list) {
  327. cur.push(x)
  328. if (cur.length == size) { out.push(cur) cur = [] }
  329. }
  330. if (cur.length > 0) { out.push(cur) }
  331. return out
  332. }
  333. // fields of an episode/season from TMDB that differ from the stored record (null/empty never overwrites)
  334. static changedText = (stored, fresh) => { return fresh != null && fresh != stored }
  335. // a MOVIE: one request — its imdb id (if missing) and its poster; nothing else of the record is touched
  336. static syncMovie = (show, res) => {
  337. let out = res
  338. out.requests = 1
  339. let details = tmdbGet('/movie/' + show.tmdbId + '?append_to_response=external_ids')
  340. if (details.failed != null) { out.errors = 1 out.error = show.title + ': ' + details.failed return out }
  341. let ids = externalIdsFor(show, details.external_ids, false)
  342. out.ids = ids.filled
  343. let poster = syncPoster(show, details.poster_path)
  344. out.requests = out.requests + poster.requests
  345. out.posters = poster.saved
  346. if (poster.failed != null) { out.errors = out.errors + 1 out.error = show.title + ': ' + poster.failed }
  347. let m = show
  348. m.imdbId = ids.imdbId
  349. m.image = poster.image
  350. m.tmdbPoster = poster.tmdbPoster
  351. m.tmdbSync = now()
  352. if (showsTable.update(m.id, m) == null) { out.errors = out.errors + 1 out.error = show.title + ': movie not updated: ' + showsTable.lastError() }
  353. return out
  354. }
  355. // Sync ONE show (by our id). Answers counts: { requests, tvmazeRequests, newSeasons, newEpisodes, updatedEpisodes,
  356. // updatedSeasons, posters, ids, tvmazeEpisodes, tvmazeSeasons, tvmazeFilled, tvmazeSkipped, errors, error }. Never throws for a TMDB failure — it is counted and the show left as is.
  357. static syncShow = (showId) => {
  358. 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 = '' }
  359. let show = showsTable.fetch(showId)
  360. if (show == null) { res.errors = 1 res.error = 'no show ' + showId return res }
  361. if (show.tmdbId == null) { res.errors = 1 res.error = show.title + ': no tmdbId' return res }
  362. if (show.type == 'movie') { return syncMovie(show, res) }
  363. res.requests = 1
  364. let details = tmdbGet('/tv/' + show.tmdbId + '?append_to_response=external_ids')
  365. if (details.failed != null) { res.errors = 1 res.error = show.title + ': ' + details.failed return res }
  366. // what we have: seasons by number, episodes by tmdbId and by S/E number
  367. let seasonsByNumber = {}
  368. let epByTmdb = {}
  369. let epByNumber = {}
  370. for (sid of show.seasons) {
  371. let s = seasonsTable.fetch(sid)
  372. if (s != null) {
  373. seasonsByNumber['' + s.seasonNumber] = s
  374. for (eid of s.episodes) {
  375. let e = episodesTable.fetch(eid)
  376. if (e != null) {
  377. if (e.tmdbId != null) { epByTmdb['' + e.tmdbId] = e }
  378. epByNumber[e.seasonNumber + 'x' + e.episodeNumber] = e
  379. }
  380. }
  381. }
  382. }
  383. // plain locals for the record literals below: inside a literal, an entry named `show`/`season` would shadow
  384. // the variable for every later entry (SPEC "A literal's entries are evaluated in order")
  385. let showKey = show.id
  386. let showTmdb = show.tmdbId
  387. let showSeasons = []
  388. for (sid of show.seasons) { showSeasons.push(sid) }
  389. let showChanged = false
  390. for (batch of batchesOf(wantedSeasonNumbers(details, seasonsByNumber), 20)) {
  391. let names = []
  392. for (n of batch) { names.push('season/' + n) }
  393. res.requests = res.requests + 1
  394. let withSeasons = tmdbGet('/tv/' + show.tmdbId + '?append_to_response=' + names.join(','))
  395. if (withSeasons.failed != null) {
  396. res.errors = res.errors + 1
  397. res.error = show.title + ': ' + withSeasons.failed
  398. } else {
  399. for (n of batch) {
  400. let ts = withSeasons['season/' + n]
  401. if (ts != null && ts.episodes != null) {
  402. let season = seasonsByNumber['' + n]
  403. let seasonIsNew = season == null
  404. let seasonChanged = false
  405. if (seasonIsNew) {
  406. season = { id = newId() seasonNumber = n title = textOr(ts.name) != null ? ts.name : 'Season ' + n
  407. release = textOr(ts.air_date) summary = textOr(ts.overview) != null ? ts.overview : ''
  408. show = showKey episodes = [] oldId = 'tmdb-season:' + showTmdb + ':' + n }
  409. } else {
  410. if (changedText(season.title, textOr(ts.name))) { season.title = ts.name seasonChanged = true }
  411. if (changedText(season.summary, textOr(ts.overview))) { season.summary = ts.overview seasonChanged = true }
  412. if (changedText(season.release, textOr(ts.air_date))) { season.release = ts.air_date seasonChanged = true }
  413. }
  414. let seasonKey = season.id
  415. let seasonEpisodes = []
  416. for (eid of season.episodes) { seasonEpisodes.push(eid) }
  417. for (te of ts.episodes) {
  418. if (te.id != null && te.episode_number != null) {
  419. let e = epByTmdb['' + te.id]
  420. if (e == null) {
  421. let byNum = epByNumber[n + 'x' + te.episode_number]
  422. if (byNum != null && byNum.tmdbId == null) { e = byNum }
  423. }
  424. if (e == null) {
  425. let fresh = { id = newId() episodeNumber = te.episode_number seasonNumber = n
  426. title = textOr(te.name) summary = textOr(te.overview) != null ? te.overview : '' release = textOr(te.air_date)
  427. show = showKey season = seasonKey tmdbId = te.id oldId = 'tmdb-episode:' + te.id }
  428. let putId = episodesTable.put(fresh)
  429. if (putId == null) {
  430. res.errors = res.errors + 1
  431. res.error = show.title + ': episode ' + te.id + ' not stored: ' + episodesTable.lastError()
  432. } else {
  433. seasonEpisodes.push(fresh.id)
  434. epByTmdb['' + te.id] = fresh
  435. epByNumber[n + 'x' + te.episode_number] = fresh
  436. res.newEpisodes = res.newEpisodes + 1
  437. seasonChanged = true
  438. }
  439. } else {
  440. let changed = false
  441. if (e.tmdbId == null) { e.tmdbId = te.id changed = true }
  442. // #15: TMDB's "Episode 4" never replaces a real title (one TVmaze filled, or the migrated one)
  443. if (changedText(e.title, textOr(te.name)) && !(isPlaceholderTitle(te.name) && !isPlaceholderTitle(e.title))) { e.title = te.name changed = true }
  444. if (changedText(e.summary, textOr(te.overview))) { e.summary = te.overview changed = true }
  445. if (changedText(e.release, textOr(te.air_date))) { e.release = te.air_date changed = true }
  446. if (changed) {
  447. if (episodesTable.update(e.id, e) == null) {
  448. res.errors = res.errors + 1
  449. res.error = show.title + ': episode ' + e.id + ' not updated: ' + episodesTable.lastError()
  450. } else {
  451. epByTmdb['' + e.tmdbId] = e
  452. epByNumber[e.seasonNumber + 'x' + e.episodeNumber] = e
  453. res.updatedEpisodes = res.updatedEpisodes + 1
  454. }
  455. }
  456. }
  457. }
  458. }
  459. season.episodes = seasonEpisodes
  460. if (seasonIsNew) {
  461. if (seasonsTable.put(season) == null) {
  462. res.errors = res.errors + 1
  463. res.error = show.title + ': season ' + n + ' not stored: ' + seasonsTable.lastError()
  464. } else {
  465. seasonsByNumber['' + n] = season
  466. showSeasons.push(season.id)
  467. showChanged = true
  468. res.newSeasons = res.newSeasons + 1
  469. }
  470. } else if (seasonChanged) {
  471. if (seasonsTable.update(season.id, season) == null) {
  472. res.errors = res.errors + 1
  473. res.error = show.title + ': season ' + season.id + ' not updated: ' + seasonsTable.lastError()
  474. } else {
  475. res.updatedSeasons = res.updatedSeasons + 1
  476. }
  477. }
  478. }
  479. }
  480. }
  481. }
  482. // the external ids (tracker.worldapi.org#12): missing ones from TMDB's external_ids, a missing TVmaze id from TVmaze
  483. let ids = externalIdsFor(show, details.external_ids, true)
  484. res.ids = ids.filled
  485. res.tvmazeRequests = ids.tvmazeRequests
  486. if (ids.failed != null) { res.errors = res.errors + 1 res.error = show.title + ': ' + ids.failed }
  487. // tracker.worldapi.org#15: what TVmaze has and TMDB not yet (new episodes/seasons, empty titles and air dates)
  488. if (numIdOr(ids.tvmzId) != null) {
  489. let tvm = mergeTvmaze(show.title, showKey, ids.tvmzId, seasonsByNumber, epByNumber, showSeasons)
  490. res.tvmazeRequests = res.tvmazeRequests + tvm.tvmazeRequests
  491. res.tvmazeEpisodes = tvm.newEpisodes
  492. res.tvmazeSeasons = tvm.newSeasons
  493. res.tvmazeFilled = tvm.filledEpisodes
  494. res.tvmazeSkipped = tvm.skipped
  495. if (tvm.errors > 0) { res.errors = res.errors + tvm.errors res.error = tvm.error }
  496. showSeasons = tvm.showSeasons
  497. }
  498. // the show itself: status, counts, TMDB's overview, the poster, when it was synced
  499. let poster = syncPoster(show, details.poster_path)
  500. res.requests = res.requests + poster.requests
  501. res.posters = poster.saved
  502. if (poster.failed != null) { res.errors = res.errors + 1 res.error = show.title + ': ' + poster.failed }
  503. show.seasons = showSeasons
  504. if (textOr(details.status) != null) { show.status = details.status }
  505. if (details.number_of_seasons != null) { show.seasonsCount = details.number_of_seasons }
  506. if (details.number_of_episodes != null) { show.episodesCount = details.number_of_episodes }
  507. if (textOr(details.overview) != null) { show.tmdbSummary = details.overview }
  508. show.image = poster.image
  509. show.tmdbPoster = poster.tmdbPoster
  510. show.imdbId = ids.imdbId
  511. show.tvdbId = ids.tvdbId
  512. show.tvmzId = ids.tvmzId
  513. show.tmdbSync = now()
  514. if (showsTable.update(show.id, show) == null) { res.errors = res.errors + 1 res.error = show.title + ': show not updated: ' + showsTable.lastError() }
  515. return res
  516. }
  517. // flush the three tables' index/meta state to disk (after a run, and every few shows)
  518. static persistSync = () => {
  519. showsTable.persist()
  520. seasonsTable.persist()
  521. episodesTable.persist()
  522. return true
  523. }
  524. // totals of a run: the per-show counts added up
  525. 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 } }
  526. static addTotals = (t, r) => {
  527. let o = t
  528. o.shows = o.shows + 1
  529. o.requests = o.requests + r.requests
  530. o.tvmazeRequests = o.tvmazeRequests + r.tvmazeRequests
  531. o.ids = o.ids + r.ids
  532. o.newSeasons = o.newSeasons + r.newSeasons
  533. o.newEpisodes = o.newEpisodes + r.newEpisodes
  534. o.updatedEpisodes = o.updatedEpisodes + r.updatedEpisodes
  535. o.updatedSeasons = o.updatedSeasons + r.updatedSeasons
  536. o.posters = o.posters + r.posters
  537. o.tvmazeEpisodes = o.tvmazeEpisodes + r.tvmazeEpisodes
  538. o.tvmazeSeasons = o.tvmazeSeasons + r.tvmazeSeasons
  539. o.tvmazeFilled = o.tvmazeFilled + r.tvmazeFilled
  540. o.tvmazeSkipped = o.tvmazeSkipped + r.tvmazeSkipped
  541. o.errors = o.errors + r.errors
  542. return o
  543. }
  544. static totalsLine = (t) => {
  545. return 'shows=' + t.shows + ' newSeasons=' + t.newSeasons + ' newEpisodes=' + t.newEpisodes + ' updatedEpisodes=' + t.updatedEpisodes
  546. + ' updatedSeasons=' + t.updatedSeasons + ' posters=' + t.posters + ' ids=' + t.ids + ' requests=' + t.requests + ' tvmazeRequests=' + t.tvmazeRequests + ' errors=' + t.errors
  547. + ' tvmazeEpisodes=' + t.tvmazeEpisodes + ' tvmazeSeasons=' + t.tvmazeSeasons + ' tvmazeFilled=' + t.tvmazeFilled + ' tvmazeSkipped=' + t.tvmazeSkipped
  548. }

Branches

Latest commits

  • 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
  • 17375427tracker#2: tools/migrate.hl + tools/verify.hl — old MongoDB data into mpackdb with new idsmre
  • 31aac936tracker#3: no border on the header and on filled buttons; inverted buttons keep theirsmre
  • 2ad9d29ctracker#1: login exactly like calendar (identity selector in the header, empty homepage)mre
  • 3691e176tracker#1: empty tracker with the ident login (state of 2026-09-27)mre