gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf1597214f1597214deploy.sh backup: tar --hard-dereference (hot tar stored mpackdb sidecars as hard links to .sessions files)mref1597214/lib/merge.hl

32.1 KB

  1. // lib/merge.hl — DUPLICATE TITLES MERGED (tracker.worldapi.org#31, mission 026). The architect: "Every TMDB title exists once in our
  2. // data; watches, follows and seasons all hang on that one record."
  3. //
  4. // WHERE THEY CAME FROM: the old tracker. On the live copy (2026-10-03) 68 type+tmdbId pairs were held by 157 records — every one
  5. // of them a migrated row (Mongo `oldId`, created 2022–2023 in runs of consecutive ids: Archive 81 ×6, Peripheral ×4, Ally
  6. // McBeal ×2 …); not one was made by this app. The app's two creating paths look the title up first (search.hl importTitle,
  7. // people.hl fillStep → search.hl titleIdByTmdb) and their records carry `oldId = tmdb-<tv|movie>-<id>`, which the table's
  8. // `!oldId` UNIQUE index refuses twice. Seasons the same way: 449 migrated seasons name a title that does not list them (the old
  9. // tracker showed a title's seasons by query); the daily sync goes by the list, so it made a SECOND season where TMDB has that
  10. // number (Reacher: the creator's S3 watches sat on the unlisted migrated S3, the page showed the sync's empty S3).
  11. //
  12. // THE REPAIR (in the app, on its own clock like the short-id backfill — no TMDB, one item per tick; jobs.hl `mergeTick`):
  13. // 1. per duplicate group: the KEEPER = the record with follows/watches (most first), else the one with its old short id
  14. // (shortids.hl), else the oldest (the Mongo id's time, else `imported`). Into it, from every other record:
  15. // follows + watches (a user who already has the keeper's: the moved row gets `target`/`show` null + `mergedInto` = the
  16. // row it repeats — no row is deleted), seasons the keeper lacks (moved: `show` = keeper), seasons it has (merged
  17. // episode by episode, below), cast + crew entries it lacks, the persons' credits, the timelines (franchises.hl
  18. // titleMerged), empty text/id fields, the poster file if the keeper has none. The keeper takes the plain slug of its
  19. // title when a duplicate held it (Archive 81: "Archive-82" → "Archive-81"; its former slug in `oldSlugs`).
  20. // The other record becomes a TOMBSTONE (shows.hl): `mergedInto`, `mergedAt`, `mergedTmdbId` (tmdbId null), `mergedSeasons`
  21. // (seasons []). Its slug and short id lead to the keeper (shows.hl showBySlug: its page shows the keeper; /shows/ and shortids.hl shortIdPath 301).
  22. // 2. per title with seasons that name it but are not in its list (STRAY seasons): such a season with a listed TWIN (same
  23. // number) is merged into the twin; one without is LINKED into the list only when someone watched it or one of its episodes
  24. // (recorded in the title's `linkedSeasons`). The other strays stay as they are: linking all 393 with episodes on the live
  25. // copy put 1,091 never-watched old talk-show episodes on the creator's /my/unwatched (1,273 → 2,364 rows). When the sync
  26. // later makes a season of that number, the next start merges the stray into it.
  27. // MERGING A SEASON INTO ITS TWIN: the season's watches → the twin; each episode: the twin's episode of that number gets its
  28. // watches (the episode becomes `mergedInto` = that one), an episode the twin lacks MOVES into the twin. The season gets
  29. // `mergedInto` = the twin, `mergedEpisodes` (episodes []).
  30. // 3. tracker#39 (mission 032): per listed season with two or more live EPISODES of one number (DOUBLE EPISODES: a migrated
  31. // episode whose TMDB id TMDB had replaced + the one the sync then added — sync.hl matches those by number now; live copy
  32. // 2026-10-04: 850 in 112 series): the KEEPER = the one with the most watches, else the synced one (`tmdb-episode:` oldId:
  33. // TMDB's current id), else the first listed. It gets the others' watches; a migrated keeper takes the synced one's tmdbId
  34. // (its own → `migratedTmdbId`, so the next sync matches it) and TMDB's texts (its own kept in migratedTitle/migratedSummary),
  35. // empty fields filled. The others become tombstones: `mergedInto`, `mergedAt`, `mergedTmdbId` (tmdbId null), out of the
  36. // season's `episodes` into its `mergedEpisodes`. Nothing is deleted.
  37. // RESUMES: the queue is built at start from what is still duplicated / stray — a restart in the middle goes on (a half-moved
  38. // group picks the same keeper again: it already has the moved follows/watches). A third start: "merge: nothing to do".
  39. // Persisted every 10 items and at the end. Log: start, one line per tombstone and per repaired title, done.
  40. //
  41. // ONE PROCESS PER STORAGE (hybriel#21): the tables are the app's own. Ids are unique (count-duplicate-ids), so update() is safe
  42. // (hybriel#113, sync.hl).
  43. import { now } from 'hl:time'
  44. import { readBytes, writeFile, exists } from 'hl:fs'
  45. import { postersDir, hexDigits, listOr } from './util.hl'
  46. import { showsTable, seasonsTable, episodesTable, personsTable, noteSlugsOf, forgetEpisodeKey, posterName } from './shows.hl'
  47. import { followsTable } from './follows.hl'
  48. import { watchesTable, forgetUserWatches } from './watches.hl'
  49. import { searchTitleMerged } from './search.hl'
  50. import { slugBaseOf } from './search-helpers.hl'
  51. import { sliceScan, sliceDone, sliceNext, sliceBudgetMs } from './slices.hl'
  52. import { refreshCatalogShow } from './catalog.hl'
  53. import { hasOldShortId } from './shortids.hl'
  54. import { titleMerged } from './franchises.hl'
  55. // the empty fields of a keeper a duplicate may fill (never ids, slugs, flags or the job markers)
  56. static fillFields = ['summary', 'tmdbSummary', 'tvmazeSummary', 'imdbId', 'tvdbId', 'tvmzId', 'homepage', 'tagline', 'release', 'year', 'language',
  57. 'migratedSummary', 'migratedTitle', 'migratedGenres', 'migratedHomepage', 'migratedTagline']
  58. // the work, [{ kind ('title' | 'seasons'), ids (a group's record ids) | id (a title) }], worked off from `run.pos`; filled in place
  59. // (a static list is never reassigned)
  60. static queue = []
  61. // watch id lists by target, follow id lists by show, person ids by the duplicates' ids they credit, seasons naming a title that
  62. // does not list them — built once by mergePrepare, kept up to date by the moves (flat maps, written key by key)
  63. static watchIds = {}
  64. static followIds = {}
  65. static creditedBy = {}
  66. static strays = {}
  67. static seasonsByDup = {}
  68. static run = { built = false pos = 0 groups = 0 records = 0 strayTitles = 0 doubleSeasons = 0 ms = 0 }
  69. static totals = { groups = 0 tombstones = 0 follows = 0 followRepeats = 0 watches = 0 watchRepeats = 0 seasonsMoved = 0 seasonsMerged = 0
  70. seasonsLinked = 0 episodesMoved = 0 episodesMerged = 0 cast = 0 people = 0 timelines = 0 slugs = 0 posters = 0 fields = 0 titles = 0
  71. doubleSeasons = 0 doubleEpisodes = 0 }
  72. static isEmpty = (&v) => { return v == null || (hlTypeName(v) == 'String' && v.trim() == '') }
  73. // ---- the queue ------------------------------------------------------------------------------------------------------------
  74. // one scan of shows, seasons, follows, watches and persons: the duplicate groups, the titles with stray seasons, the indexes.
  75. // mission 044: SLICED (slices.hl) — every table is read in primary-key slices, `mergePrepare()` takes slices until the time budget
  76. // is spent and answers false; the jobs.hl tick calls it again on its next timer tick; true = built (the queue is final). The
  77. // scan's working maps live in `prep` (fields, released at the end) — same results as the former one-pass-per-table version.
  78. static prep = { phase = 0 scan = null t0 = 0 byKey = {} order = [] listedBy = {} dup = {} listedNum = {} strayList = [] firstOfNumber = {} doubled = {} }
  79. // the persons pass: which duplicate titles a person is credited on
  80. static noteCredits = (&p) => {
  81. if (p.shows != null) {
  82. for (c of p.shows) {
  83. if (c != null && c.show != null && prep.dup[c.show] == true) {
  84. if (creditedBy[c.show] == null) { creditedBy[c.show] = [p.id] } else if (!creditedBy[c.show].includes(p.id)) { creditedBy[c.show].push(p.id) }
  85. }
  86. }
  87. }
  88. }
  89. static mergePrepare = () => {
  90. if (run.built) { return true }
  91. t0 = now()
  92. if (prep.phase == 0) {
  93. prep.t0 = t0
  94. prep.scan = sliceScan(showsTable)
  95. prep.phase = 1
  96. }
  97. while (true) {
  98. if (now() - t0 >= sliceBudgetMs) { return false }
  99. let ph = prep.phase
  100. if (ph == 1) {
  101. if (sliceDone(&prep.scan)) {
  102. // the duplicate groups
  103. for (k of prep.order) {
  104. let ids = prep.byKey[k]
  105. if (ids.length > 1) {
  106. queue.push({ kind = 'title' key = k ids = ids })
  107. run.groups = run.groups + 1
  108. run.records = run.records + ids.length
  109. for (id of ids) { prep.dup[id] = true }
  110. }
  111. }
  112. prep.byKey = {}
  113. prep.order = []
  114. prep.scan = sliceScan(watchesTable)
  115. prep.phase = 2
  116. } else {
  117. for (s of sliceNext(&prep.scan)) {
  118. if (s.mergedInto == null) {
  119. for (x of listOr(&s.seasons)) { prep.listedBy[x] = s.id }
  120. if (s.tmdbId != null) {
  121. let k = s.type + ':' + s.tmdbId
  122. if (prep.byKey[k] == null) {
  123. prep.byKey[k] = [s.id]
  124. prep.order.push(k)
  125. } else { prep.byKey[k].push(s.id) }
  126. }
  127. }
  128. }
  129. }
  130. } else if (ph == 2) {
  131. if (sliceDone(&prep.scan)) {
  132. prep.scan = sliceScan(seasonsTable)
  133. prep.phase = 3
  134. } else {
  135. for (w of sliceNext(&prep.scan)) {
  136. if (w.target != null) { if (watchIds[w.target] == null) { watchIds[w.target] = [w.id] } else { watchIds[w.target].push(w.id) } }
  137. }
  138. }
  139. } else if (ph == 3) {
  140. // seasons: a duplicate's (all of them, listed or not) and the stray ones (naming a live title that does not list them)
  141. if (sliceDone(&prep.scan)) {
  142. // a stray season is work when it has a listed twin or watches; its title must be live and no duplicate (a duplicate's
  143. // seasons go with its group)
  144. strayShows = []
  145. for (st of prep.strayList) {
  146. if (prep.dup[st.show] != true && (st.watched || prep.listedNum[st.show + '#' + st.n] == true)) {
  147. if (strays[st.show] == null) {
  148. strays[st.show] = [st.id]
  149. strayShows.push(st.show)
  150. } else { strays[st.show].push(st.id) }
  151. }
  152. }
  153. for (id of strayShows) {
  154. let s = showsTable.fetch(id)
  155. if (s != null && s.mergedInto == null) {
  156. queue.push({ kind = 'seasons' id = id })
  157. run.strayTitles = run.strayTitles + 1
  158. }
  159. }
  160. prep.strayList = []
  161. prep.listedNum = {}
  162. prep.scan = sliceScan(episodesTable)
  163. prep.phase = 4
  164. } else {
  165. for (x of sliceNext(&prep.scan)) {
  166. if (x.show != null && x.mergedInto == null) {
  167. if (prep.dup[x.show] == true) {
  168. if (seasonsByDup[x.show] == null) { seasonsByDup[x.show] = [x.id] } else { seasonsByDup[x.show].push(x.id) }
  169. }
  170. if (prep.listedBy[x.id] != null) { prep.listedNum[prep.listedBy[x.id] + '#' + x.seasonNumber] = true }
  171. else { prep.strayList.push({ id = x.id show = x.show n = x.seasonNumber watched = hasWatches(&x) }) }
  172. }
  173. }
  174. }
  175. } else if (ph == 4) {
  176. // tracker#39: the listed seasons holding two live episodes of one number
  177. if (sliceDone(&prep.scan)) {
  178. prep.firstOfNumber = {}
  179. prep.doubled = {}
  180. if (queue.length > 0) {
  181. prep.scan = sliceScan(followsTable)
  182. prep.phase = 5
  183. } else { prep.phase = 7 }
  184. } else {
  185. for (e of sliceNext(&prep.scan)) {
  186. if (e.mergedInto == null && e.season != null && prep.listedBy[e.season] != null) {
  187. let k = e.season + '#' + e.episodeNumber
  188. if (prep.firstOfNumber[k] == null) { prep.firstOfNumber[k] = true }
  189. else if (prep.doubled[e.season] == null) {
  190. prep.doubled[e.season] = true
  191. queue.push({ kind = 'episodes' id = e.season show = prep.listedBy[e.season] })
  192. run.doubleSeasons = run.doubleSeasons + 1
  193. }
  194. }
  195. }
  196. }
  197. } else if (ph == 5) {
  198. if (sliceDone(&prep.scan)) {
  199. if (run.groups > 0) {
  200. prep.scan = sliceScan(personsTable)
  201. prep.phase = 6
  202. } else { prep.phase = 7 }
  203. } else {
  204. for (f of sliceNext(&prep.scan)) {
  205. if (f.show != null) { if (followIds[f.show] == null) { followIds[f.show] = [f.id] } else { followIds[f.show].push(f.id) } }
  206. }
  207. }
  208. } else if (ph == 6) {
  209. if (sliceDone(&prep.scan)) { prep.phase = 7 }
  210. else {
  211. for (p of sliceNext(&prep.scan)) { noteCredits(&p) }
  212. // mission 045 guard: range() on the persons table answered non-rows (Hybriel bug): fall back to ONE iterate pass over the table
  213. if (prep.scan.skipped > 0) {
  214. console.log('merge: persons range() gave ' + prep.scan.skipped + ' non-rows, falling back to iterate for the persons pass')
  215. for (p of personsTable.iterate(null, null)) { noteCredits(&p) }
  216. prep.scan.k = prep.scan.n
  217. }
  218. }
  219. } else {
  220. prep.listedBy = {}
  221. prep.dup = {}
  222. prep.scan = null
  223. run.built = true
  224. run.ms = now() - prep.t0
  225. return true
  226. }
  227. }
  228. return false
  229. }
  230. // anyone's watch on the season or one of its episodes (watchIds is built)
  231. static hasWatches = (&season) => {
  232. if (watchIds[season.id] != null && watchIds[season.id].length > 0) { return true }
  233. for (eid of listOr(&season.episodes)) { if (watchIds[eid] != null && watchIds[eid].length > 0) { return true } }
  234. return false
  235. }
  236. static mergeLeft = () => { return queue.length - run.pos }
  237. static mergeStats = () => { return run }
  238. static mergeTotals = () => { return totals }
  239. static mergeLine = () => {
  240. t = totals
  241. return 'groups=' + t.groups + ' tombstones=' + t.tombstones + ' follows=' + t.follows + ' followRepeats=' + t.followRepeats + ' watches=' + t.watches
  242. + ' watchRepeats=' + t.watchRepeats + ' seasonsMoved=' + t.seasonsMoved + ' seasonsMerged=' + t.seasonsMerged + ' seasonsLinked=' + t.seasonsLinked
  243. + ' episodesMoved=' + t.episodesMoved + ' episodesMerged=' + t.episodesMerged + ' cast=' + t.cast + ' people=' + t.people + ' timelines=' + t.timelines
  244. + ' slugs=' + t.slugs + ' posters=' + t.posters + ' fields=' + t.fields + ' strayTitles=' + t.titles + ' doubleSeasons=' + t.doubleSeasons
  245. + ' doubleEpisodes=' + t.doubleEpisodes
  246. }
  247. static persistMerge = () => {
  248. showsTable.persist()
  249. seasonsTable.persist()
  250. episodesTable.persist()
  251. followsTable.persist()
  252. watchesTable.persist()
  253. personsTable.persist()
  254. return true
  255. }
  256. // ---- moving user data ------------------------------------------------------------------------------------------------------
  257. // every watch of `fromId` → `toId` (an episode, season or movie id); a user who already has a watch on `toId` keeps that one and
  258. // the moved row is parked (target null, `mergedInto` = the row it repeats). Every moved row keeps where it was (`mergedTarget`).
  259. static moveWatches = (&fromId, &toId) => {
  260. if (watchIds[fromId] == null) { return 0 }
  261. ids = []
  262. for (x of watchIds[fromId]) { ids.push(x) }
  263. mine = {}
  264. if (watchIds[toId] != null) {
  265. for (x of watchIds[toId]) {
  266. let w = watchesTable.fetch(x)
  267. if (w != null && w.target == toId) { mine[w.user] = w.id }
  268. }
  269. }
  270. moved = []
  271. let n = 0
  272. for (wid of ids) {
  273. let w = watchesTable.fetch(wid)
  274. if (w != null && w.target == fromId) {
  275. let x = w
  276. x.mergedTarget = fromId
  277. if (mine[x.user] != null) {
  278. x.target = null
  279. x.mergedInto = mine[x.user]
  280. totals.watchRepeats = totals.watchRepeats + 1
  281. } else {
  282. x.target = toId
  283. mine[x.user] = x.id
  284. moved.push(x.id)
  285. totals.watches = totals.watches + 1
  286. }
  287. if (watchesTable.update(x.id, x) == null) { console.log('merge: watch ' + x.id + ' not stored: ' + watchesTable.lastError()) } else { n = n + 1 }
  288. forgetUserWatches(&x.user)
  289. }
  290. }
  291. watchIds[fromId] = []
  292. if (moved.length > 0) {
  293. if (watchIds[toId] == null) { watchIds[toId] = moved } else { for (x of moved) { watchIds[toId].push(x) } }
  294. }
  295. return n
  296. }
  297. // every follow of title `fromId` → `toId`, the same way (`mergedShow` = where it was)
  298. static moveFollows = (&fromId, &toId) => {
  299. if (followIds[fromId] == null) { return 0 }
  300. ids = []
  301. for (x of followIds[fromId]) { ids.push(x) }
  302. mine = {}
  303. if (followIds[toId] != null) {
  304. for (x of followIds[toId]) {
  305. let f = followsTable.fetch(x)
  306. if (f != null && f.show == toId) { mine[f.user] = f.id }
  307. }
  308. }
  309. moved = []
  310. for (fid of ids) {
  311. let f = followsTable.fetch(fid)
  312. if (f != null && f.show == fromId) {
  313. let x = f
  314. x.mergedShow = fromId
  315. if (mine[x.user] != null) {
  316. x.show = null
  317. x.mergedInto = mine[x.user]
  318. totals.followRepeats = totals.followRepeats + 1
  319. } else {
  320. x.show = toId
  321. mine[x.user] = x.id
  322. moved.push(x.id)
  323. totals.follows = totals.follows + 1
  324. }
  325. if (followsTable.update(x.id, x) == null) { console.log('merge: follow ' + x.id + ' not stored: ' + followsTable.lastError()) }
  326. }
  327. }
  328. followIds[fromId] = []
  329. if (moved.length > 0) {
  330. if (followIds[toId] == null) { followIds[toId] = moved } else { for (x of moved) { followIds[toId].push(x) } }
  331. }
  332. return moved.length
  333. }
  334. // ---- seasons -------------------------------------------------------------------------------------------------------------------
  335. // season `x` into its twin `twinId` of title `titleId` (see the top) → the episode ids the twin gained
  336. static mergeSeasonInto = (&seasonId, &twinId, &titleId) => {
  337. x = seasonsTable.fetch(seasonId)
  338. twin = seasonsTable.fetch(twinId)
  339. if (x == null || twin == null || x.mergedInto != null) { return [] }
  340. moveWatches(&x.id, &twin.id)
  341. byNum = {}
  342. for (eid of listOr(&twin.episodes)) {
  343. let e = episodesTable.fetch(eid)
  344. if (e != null) { byNum['' + e.episodeNumber] = e.id }
  345. }
  346. gained = []
  347. tid = twin.id
  348. for (eid of listOr(&x.episodes)) {
  349. let e = episodesTable.fetch(eid)
  350. if (e != null && e.mergedInto == null) {
  351. let other = byNum['' + e.episodeNumber]
  352. let y = e
  353. if (other != null && other != e.id) {
  354. moveWatches(&e.id, &other)
  355. y.mergedInto = other
  356. totals.episodesMerged = totals.episodesMerged + 1
  357. } else if (other == null) {
  358. y.movedFrom = { show = e.show season = e.season }
  359. y.show = titleId
  360. y.season = tid
  361. byNum['' + e.episodeNumber] = e.id
  362. gained.push(e.id)
  363. totals.episodesMoved = totals.episodesMoved + 1
  364. }
  365. if (episodesTable.update(y.id, y) == null) { console.log('merge: episode ' + y.id + ' not stored: ' + episodesTable.lastError()) }
  366. forgetEpisodeKey(&y.id)
  367. }
  368. }
  369. if (gained.length > 0) {
  370. tw = seasonsTable.fetch(tid)
  371. eps = listOr(&tw.episodes)
  372. for (g of gained) { eps.push(g) }
  373. tw.episodes = eps
  374. if (seasonsTable.update(tw.id, tw) == null) { console.log('merge: season ' + tw.id + ' not stored: ' + seasonsTable.lastError()) }
  375. }
  376. done = seasonsTable.fetch(seasonId)
  377. done.mergedInto = tid
  378. done.mergedAt = now()
  379. done.mergedEpisodes = listOr(&done.episodes)
  380. done.episodes = []
  381. if (seasonsTable.update(done.id, done) == null) { console.log('merge: season ' + done.id + ' not stored: ' + seasonsTable.lastError()) }
  382. totals.seasonsMerged = totals.seasonsMerged + 1
  383. return gained
  384. }
  385. // a season (and its episodes) moved to title `titleId` — it was a duplicate's and the keeper has no season of its number
  386. static moveSeason = (&seasonId, &titleId) => {
  387. x = seasonsTable.fetch(seasonId)
  388. if (x == null) { return false }
  389. y = x
  390. y.movedFrom = { show = x.show }
  391. y.show = titleId
  392. if (seasonsTable.update(y.id, y) == null) {
  393. console.log('merge: season ' + y.id + ' not stored: ' + seasonsTable.lastError())
  394. return false
  395. }
  396. for (eid of listOr(&y.episodes)) {
  397. let e = episodesTable.fetch(eid)
  398. if (e != null) {
  399. let z = e
  400. z.movedFrom = { show = e.show season = e.season }
  401. z.show = titleId
  402. if (episodesTable.update(z.id, z) == null) { console.log('merge: episode ' + z.id + ' not stored: ' + episodesTable.lastError()) }
  403. forgetEpisodeKey(&z.id)
  404. }
  405. }
  406. totals.seasonsMoved = totals.seasonsMoved + 1
  407. return true
  408. }
  409. // a title's listed seasons by number → season id
  410. static seasonsByNumber = (&show) => {
  411. out = {}
  412. for (sid of listOr(&show.seasons)) {
  413. let s = seasonsTable.fetch(sid)
  414. if (s != null) { out['' + s.seasonNumber] = s.id }
  415. }
  416. return out
  417. }
  418. // ---- the keeper ---------------------------------------------------------------------------------------------------------------
  419. // follows + watches on the record, its seasons and their episodes
  420. static userDataOf = (&r) => {
  421. let n = listOr(&followIds[r.id]).length + listOr(&watchIds[r.id]).length
  422. sids = []
  423. for (x of listOr(&r.seasons)) { sids.push(x) }
  424. for (x of listOr(&seasonsByDup[r.id])) { if (!sids.includes(x)) { sids.push(x) } }
  425. for (sid of sids) {
  426. n = n + listOr(&watchIds[sid]).length
  427. let s = seasonsTable.fetch(sid)
  428. if (s != null) { for (eid of listOr(&s.episodes)) { n = n + listOr(&watchIds[eid]).length } }
  429. }
  430. return n
  431. }
  432. // when the record was made (ms): a Mongo id's first 8 hex digits are its seconds; else `imported`; else last
  433. static ageOf = (&r) => {
  434. o = r.oldId != null ? '' + r.oldId : ''
  435. if (o.length == 24) {
  436. let v = 0
  437. let i = 0
  438. let ok = true
  439. while (ok && i < 8) {
  440. let d = hexDigits.indexOf(o.slice(i, i + 1))
  441. if (d < 0) { ok = false } else { v = v * 16 + d }
  442. i = i + 1
  443. }
  444. if (ok) { return v * 1000 }
  445. }
  446. if (r.imported != null && hlTypeName(r.imported) == 'Number') { return r.imported }
  447. return 9000000000000000
  448. }
  449. // → the keeper's id: most user data, then the old short id, then the oldest; equal → the first
  450. static pickKeeper = (&recs) => {
  451. let best = null
  452. let bestData = -1
  453. let bestOld = false
  454. let bestAge = 0
  455. for (r of recs) {
  456. let d = userDataOf(&r)
  457. let o = hasOldShortId(&r)
  458. let a = ageOf(&r)
  459. let better = best == null || d > bestData || (d == bestData && o && !bestOld) || (d == bestData && o == bestOld && a < bestAge)
  460. if (better) {
  461. best = r.id
  462. bestData = d
  463. bestOld = o
  464. bestAge = a
  465. }
  466. }
  467. return best
  468. }
  469. // ---- one duplicate into its keeper ---------------------------------------------------------------------------------------------
  470. static creditKey = (&c) => { return c.person != null ? 'p' + c.person : 't' + c.tmdbId }
  471. static mergeTitleInto = (&dupId, &keeperId) => {
  472. t = showsTable.fetch(dupId)
  473. k0 = showsTable.fetch(keeperId)
  474. if (t == null || k0 == null || t.mergedInto != null) { return null }
  475. line = { follows = moveFollows(&t.id, &keeperId) watches = moveWatches(&t.id, &keeperId) seasons = 0 merged = 0 people = 0 }
  476. // seasons: the listed ones first, then the ones naming it
  477. sids = []
  478. for (x of listOr(&t.seasons)) { sids.push(x) }
  479. for (x of listOr(&seasonsByDup[t.id])) { if (!sids.includes(x)) { sids.push(x) } }
  480. have = seasonsByNumber(&k0)
  481. added = []
  482. for (sid of sids) {
  483. let s = seasonsTable.fetch(sid)
  484. if (s != null && s.mergedInto == null) {
  485. let twin = have['' + s.seasonNumber]
  486. if (twin != null && twin != s.id) {
  487. mergeSeasonInto(&s.id, &twin, &keeperId)
  488. line.merged = line.merged + 1
  489. } else if (twin == null && moveSeason(&s.id, &keeperId)) {
  490. have['' + s.seasonNumber] = s.id
  491. added.push(s.id)
  492. line.seasons = line.seasons + 1
  493. }
  494. }
  495. }
  496. // the persons' credits
  497. for (pid of listOr(&creditedBy[t.id])) {
  498. let p = personsTable.fetch(pid)
  499. if (p != null) {
  500. let shows = []
  501. let changed = false
  502. for (c of listOr(&p.shows)) {
  503. let x = c
  504. if (x != null && x.show == t.id) {
  505. x.show = keeperId
  506. changed = true
  507. }
  508. shows.push(x)
  509. }
  510. if (changed) {
  511. let q = p
  512. q.shows = shows
  513. if (personsTable.update(q.id, q) == null) { console.log('merge: person ' + q.id + ' not stored: ' + personsTable.lastError()) } else { line.people = line.people + 1 }
  514. }
  515. }
  516. }
  517. totals.people = totals.people + line.people
  518. totals.timelines = totals.timelines + titleMerged(&t.id, &keeperId)
  519. // the keeper: its new seasons, the cast/crew it lacks, empty fields, the poster, the plain slug
  520. k = showsTable.fetch(keeperId)
  521. seasons = listOr(&k.seasons)
  522. for (a of added) { seasons.push(a) }
  523. k.seasons = seasons
  524. castKeys = {}
  525. cast = listOr(&k.cast)
  526. for (c of cast) { if (c != null) { castKeys[creditKey(&c)] = true } }
  527. for (c of listOr(&t.cast)) {
  528. if (c != null && castKeys[creditKey(&c)] != true) {
  529. castKeys[creditKey(&c)] = true
  530. cast.push(c)
  531. totals.cast = totals.cast + 1
  532. }
  533. }
  534. k.cast = cast
  535. crewKeys = {}
  536. crew = listOr(&k.crew)
  537. for (c of crew) { if (c != null) { crewKeys[c.person + '|' + c.name + '|' + c.job] = true } }
  538. for (c of listOr(&t.crew)) {
  539. if (c != null && crewKeys[c.person + '|' + c.name + '|' + c.job] != true) {
  540. crewKeys[c.person + '|' + c.name + '|' + c.job] = true
  541. crew.push(c)
  542. totals.cast = totals.cast + 1
  543. }
  544. }
  545. if (crew.length > 0) { k.crew = crew }
  546. for (f of fillFields) {
  547. if (isEmpty(&k[f]) && !isEmpty(&t[f])) {
  548. k[f] = t[f]
  549. totals.fields = totals.fields + 1
  550. }
  551. }
  552. kp = posterName(&k)
  553. tp = posterName(&t)
  554. if ((kp == null || !exists(postersDir + '/' + kp)) && tp != null && exists(postersDir + '/' + tp) && k.oldId != null) {
  555. writeFile(postersDir + '/' + k.oldId + '.' + t.image, readBytes(postersDir + '/' + tp), 420)
  556. k.image = t.image
  557. totals.posters = totals.posters + 1
  558. }
  559. plain = slugBaseOf(&k.title, '')
  560. if (plain != '' && t.urlSegment == plain && k.urlSegment != plain) {
  561. olds = listOr(&k.oldSlugs)
  562. if (k.urlSegment != null && !olds.includes(k.urlSegment)) { olds.push(k.urlSegment) }
  563. k.oldSlugs = olds
  564. k.urlSegment = plain
  565. totals.slugs = totals.slugs + 1
  566. }
  567. if (showsTable.update(k.id, k) == null) { console.log('merge: keeper ' + k.id + ' not stored: ' + showsTable.lastError()) }
  568. // the duplicate becomes a tombstone (last: a stop before this leaves a group the next start finishes)
  569. d = showsTable.fetch(dupId)
  570. tmdbId = d.tmdbId
  571. type = d.type
  572. d.mergedInto = keeperId
  573. d.mergedAt = now()
  574. d.mergedTmdbId = tmdbId
  575. d.tmdbId = null
  576. d.mergedSeasons = listOr(&d.seasons)
  577. d.seasons = []
  578. if (showsTable.update(d.id, d) == null) {
  579. console.log('merge: tombstone ' + d.id + ' not stored: ' + showsTable.lastError())
  580. return null
  581. }
  582. totals.tombstones = totals.tombstones + 1
  583. noteSlugsOf(&d)
  584. noteSlugsOf(showsTable.fetch(keeperId))
  585. searchTitleMerged(&d.id, &keeperId, &type, &tmdbId)
  586. refreshCatalogShow(&d.id)
  587. refreshCatalogShow(&keeperId)
  588. console.log('merge: "' + d.title + '" ' + d.id + ' [' + d.urlSegment + ' ' + d.shortId + '] → ' + keeperId + ' [' + showsTable.fetch(keeperId).urlSegment + ']'
  589. + ' follows=' + line.follows + ' watches=' + line.watches + ' seasonsMoved=' + line.seasons + ' seasonsMerged=' + line.merged + ' people=' + line.people)
  590. return line
  591. }
  592. // ---- one title's stray seasons ----------------------------------------------------------------------------------------------
  593. static straySeasonsStep = (&showId) => {
  594. show = showsTable.fetch(showId)
  595. if (show == null || show.mergedInto != null) { return null }
  596. listed = listOr(&show.seasons)
  597. have = seasonsByNumber(&show)
  598. // the ones with more episodes first: of two watched strays of one number the fuller one is linked, the other merged into it
  599. let rows = []
  600. for (sid of listOr(&strays[showId])) {
  601. let s = seasonsTable.fetch(sid)
  602. if (s != null && s.mergedInto == null && s.show == showId && !listed.includes(s.id)) {
  603. let row = { id = s.id n = s.seasonNumber eps = listOr(&s.episodes).length watched = hasWatches(&s) }
  604. let out = []
  605. let put = false
  606. for (r of rows) {
  607. if (!put && row.eps > r.eps) { out.push(row) put = true }
  608. out.push(r)
  609. }
  610. if (!put) { out.push(row) }
  611. rows = out
  612. }
  613. }
  614. linked = []
  615. let merged = 0
  616. for (r of rows) {
  617. let twin = have['' + r.n]
  618. if (twin != null) {
  619. mergeSeasonInto(&r.id, &twin, &showId)
  620. merged = merged + 1
  621. } else if (r.watched) {
  622. linked.push(r.id)
  623. have['' + r.n] = r.id
  624. totals.seasonsLinked = totals.seasonsLinked + 1
  625. }
  626. }
  627. if (linked.length > 0) {
  628. x = showsTable.fetch(showId)
  629. seasons = listOr(&x.seasons)
  630. marks = listOr(&x.linkedSeasons)
  631. for (l of linked) {
  632. seasons.push(l)
  633. marks.push(l)
  634. }
  635. x.seasons = seasons
  636. // which ones the repair linked (they were in the data, not in the list)
  637. x.linkedSeasons = marks
  638. if (showsTable.update(x.id, x) == null) { console.log('merge: title ' + x.id + ' not stored: ' + showsTable.lastError()) }
  639. }
  640. if (linked.length > 0 || merged > 0) {
  641. totals.titles = totals.titles + 1
  642. refreshCatalogShow(&showId)
  643. console.log('merge: seasons of "' + show.title + '" ' + showId + ': linked=' + linked.length + ' merged=' + merged)
  644. }
  645. return null
  646. }
  647. // ---- double episodes (tracker#39) ----------------------------------------------------------------------------------------------
  648. static isSyncedEpisode = (&e) => { return e.oldId != null && ('' + e.oldId).startsWith('tmdb-episode:') }
  649. static watchCountOf = (&id) => { return watchIds[id] != null ? watchIds[id].length : 0 }
  650. // the most watches, else the synced one, else the first listed
  651. static pickEpisodeKeeper = (&group) => {
  652. let best = group[0]
  653. for (e of group) {
  654. let a = watchCountOf(&e.id)
  655. let b = watchCountOf(&best.id)
  656. if (a > b || (a == b && isSyncedEpisode(&e) && !isSyncedEpisode(&best))) { best = e }
  657. }
  658. return best
  659. }
  660. // episode `e` into `keeperId` (same season, same number)
  661. static mergeEpisodeInto = (&e, &keeperId) => {
  662. moveWatches(&e.id, &keeperId)
  663. k = episodesTable.fetch(keeperId)
  664. if (k == null) { return false }
  665. x = k
  666. if (isSyncedEpisode(&e) && !isSyncedEpisode(&k) && e.tmdbId != null) {
  667. // a migrated keeper takes TMDB's current id and texts (its own kept, like the sync keeps a migrated row's)
  668. if (k.tmdbId != null && k.migratedTmdbId == null) { x.migratedTmdbId = k.tmdbId }
  669. x.tmdbId = e.tmdbId
  670. if (!isEmpty(&e.title) && e.title != k.title) {
  671. if (!isEmpty(&k.title) && k.migratedTitle == null) { x.migratedTitle = k.title }
  672. x.title = e.title
  673. }
  674. if (!isEmpty(&e.summary) && e.summary != k.summary) {
  675. if (!isEmpty(&k.summary) && k.migratedSummary == null) { x.migratedSummary = k.summary }
  676. x.summary = e.summary
  677. }
  678. if (!isEmpty(&e.release)) { x.release = e.release }
  679. } else {
  680. if (isEmpty(&k.title) && !isEmpty(&e.title)) { x.title = e.title }
  681. if (isEmpty(&k.summary) && !isEmpty(&e.summary)) { x.summary = e.summary }
  682. if (isEmpty(&k.release) && !isEmpty(&e.release)) { x.release = e.release }
  683. }
  684. if (isEmpty(&k.tvmzId) && !isEmpty(&e.tvmzId)) { x.tvmzId = e.tvmzId }
  685. // the tombstone's TMDB id first (the table holds no id twice for the sync's lookup), then the keeper
  686. y = episodesTable.fetch(e.id)
  687. y.mergedInto = keeperId
  688. y.mergedAt = now()
  689. y.mergedTmdbId = e.tmdbId
  690. y.tmdbId = null
  691. if (episodesTable.update(y.id, y) == null) { console.log('merge: episode ' + y.id + ' not stored: ' + episodesTable.lastError()) }
  692. if (episodesTable.update(x.id, x) == null) { console.log('merge: episode ' + x.id + ' not stored: ' + episodesTable.lastError()) }
  693. forgetEpisodeKey(&y.id)
  694. forgetEpisodeKey(&x.id)
  695. return true
  696. }
  697. // one season: every number held twice or more → one episode (the others tombstones, out of the season's list)
  698. static doubleEpisodesStep = (&seasonId, &showId) => {
  699. se = seasonsTable.fetch(seasonId)
  700. if (se == null || se.mergedInto != null) { return 0 }
  701. byNum = {}
  702. order = []
  703. for (eid of listOr(&se.episodes)) {
  704. let e = episodesTable.fetch(eid)
  705. if (e != null && e.mergedInto == null) {
  706. let k = '' + e.episodeNumber
  707. if (byNum[k] == null) {
  708. byNum[k] = [e]
  709. order.push(k)
  710. } else { byNum[k].push(e) }
  711. }
  712. }
  713. gone = {}
  714. let n = 0
  715. for (k of order) {
  716. let group = byNum[k]
  717. if (group.length > 1) {
  718. let keeper = pickEpisodeKeeper(&group)
  719. for (e of group) {
  720. if (e.id != keeper.id && mergeEpisodeInto(&e, &keeper.id)) {
  721. gone[e.id] = true
  722. n = n + 1
  723. }
  724. }
  725. }
  726. }
  727. if (n == 0) { return 0 }
  728. keep = []
  729. parked = []
  730. for (x of listOr(&se.mergedEpisodes)) { parked.push(x) }
  731. for (eid of listOr(&se.episodes)) { if (gone[eid] == true) { parked.push(eid) } else { keep.push(eid) } }
  732. z = se
  733. z.episodes = keep
  734. z.mergedEpisodes = parked
  735. if (seasonsTable.update(z.id, z) == null) { console.log('merge: season ' + z.id + ' not stored: ' + seasonsTable.lastError()) }
  736. totals.doubleSeasons = totals.doubleSeasons + 1
  737. totals.doubleEpisodes = totals.doubleEpisodes + n
  738. refreshCatalogShow(&showId)
  739. s = showsTable.fetch(showId)
  740. console.log('merge: double episodes of "' + (s != null ? s.title : showId) + '" season ' + se.seasonNumber + ' ' + seasonId + ': ' + n + ' merged, ' + keep.length + ' left')
  741. return n
  742. }
  743. // ONE item of the queue → { done, left }
  744. static mergeStep = () => {
  745. if (!mergePrepare()) { return { done = false left = 0 } }
  746. if (run.pos >= queue.length) { return { done = true left = 0 } }
  747. item = queue[run.pos]
  748. run.pos = run.pos + 1
  749. if (item.kind == 'title') {
  750. recs = []
  751. for (id of item.ids) {
  752. let r = showsTable.fetch(id)
  753. if (r != null && r.mergedInto == null) { recs.push(r) }
  754. }
  755. if (recs.length > 1) {
  756. keeper = pickKeeper(&recs)
  757. for (r of recs) { if (r.id != keeper) { mergeTitleInto(&r.id, &keeper) } }
  758. totals.groups = totals.groups + 1
  759. // the keeper's own stray seasons (naming it, not listed — Reacher's kind) the same way as any title's
  760. strays[keeper] = listOr(&seasonsByDup[keeper])
  761. straySeasonsStep(&keeper)
  762. }
  763. } else if (item.kind == 'episodes') {
  764. doubleEpisodesStep(&item.id, &item.show)
  765. } else {
  766. straySeasonsStep(&item.id)
  767. }
  768. return { done = run.pos >= queue.length left = queue.length - run.pos }
  769. }

Branches

Latest commits

  • f1597214deploy.sh backup: tar --hard-dereference (hot tar stored mpackdb sidecars as hard links to .sessions files)mre
  • 6b58571elog: GC windowmre
  • 5c8baa1fdeploy lock: hold only around deploy.shmre
  • b8dac822log: hybriel#309mre
  • bf676d9elog: GC1 startedmre
  • c7828541mission GC1mre
  • ef949994conductor: neutral ticket rulemre
  • 89e91ef3log: RV39 livemre
  • ee2b677alog: RV39 deployingmre
  • c1c4178cMerge branch 'rv39'mre
  • a016e9abReapply "Merge branch 'rv39'"mre
  • f29e2502log: RV39 gate fixmre
  • d9fce111browser gate #26: exact frame count incl. SL1 people step (hybriel#308)mre
  • ad529ac1log: m572 verdictmre
  • 1b37d404RV39 on hold: hybriel#308mre
  • f9127c68Revert "Merge branch 'rv39'"mre
  • cd39f3d3log: hybriel#308mre
  • 51341d6elog: RV39 deploy startedmre
  • c9e29e06Merge branch 'rv39'mre
  • 0f8d1fdclog: RV39 report, browser 387/2mre