gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7c3991f97c3991f9log: day46 from Antonmre7c3991f9/lib/search.hl

17.7 KB

  1. import SearchText from './search-text.hl'
  2. // lib/search.hl — THE SEARCH (tracker.worldapi.org#14): our own database first, then "Fetch from web" (TMDB) for titles
  3. // we don't have yet, and the import of the one picked. Used by components/search.hl (`/search/<text>`).
  4. //
  5. // dbSearch(text) our shows, movies and people — from an IN-MEMORY INDEX built once at boot (no table scan per
  6. // keystroke): every title/name split into words; each word's first 2 and first 3 characters are
  7. // a bucket key → the entries holding such a word. A query looks at ONE bucket (its longest word's
  8. // first 3 characters, or 2 for a 2-letter word) and keeps the entries where EVERY query word is
  9. // the start of one of the entry's words. A title's year is one of its words ("doctor who 2005").
  10. // webSearch(text) GET <TMDB_BASE_URL>/search/multi?query=… (one request; TV + movies only, people dropped) —
  11. // the titles we already have (same TMDB id and kind) are left out
  12. // importTitle(kind, id) a new show record from GET /tv/<id>?append_to_response=external_ids,aggregate_credits (a movie:
  13. // /movie/<id>?…,credits), then sync.hl `syncShowWith` fills it from that same answer exactly like
  14. // the daily sync does (seasons, episodes, poster, external ids); added to the index. The answer goes
  15. // back as `details`: the caller (components/search.hl) stores its cast + crew (credits.hl applyCredits,
  16. // tracker#28 — details.hl imports this file, so it cannot be called from here)
  17. //
  18. // ADULT TITLES (mission 054): our database lists only titles with `adult == false` (shows.hl isPublicTitle; unknown is
  19. // hidden) — `titleOk` holds that per show id, set by indexShow and by `searchTitleChanged` (the adult backfill and the daily
  20. // sync call it per title). The web list asks TMDB with include_adult=false AND keeps only results with `adult` false.
  21. //
  22. // ONE PROCESS PER STORAGE (hybriel#21): the index lives in the app's process and is kept up to date by importTitle; the
  23. // daily sync never changes a title. New rows get self-assigned 16-hex ids (hybriel#113), like sync.hl.
  24. import { now } from 'hl:time'
  25. import { warm } from './warm.hl'
  26. import { textOr, newId } from './util.hl'
  27. import { showsTable, personsTable, genresTable, isPublicTitle, kindOfTitle, titlePath, liveShowOf } from './shows.hl'
  28. import { tmdbGet, tmdbImageBase, adultOf } from './tmdb.hl'
  29. import { syncShowWith, persistSync } from './sync.hl'
  30. import { refreshCatalogShow } from './catalog.hl'
  31. import { claimShortId } from './shortids.hl'
  32. import { wordsOf, bucketKeys, tmdbKeyOf, yearWordOf, scoreOf, matchesText, matchesSpaced, scoreText, beatsLast, entryWords, insertTop, yearOfDate, slugBaseOf } from './search-helpers.hl'
  33. import { Response } from 'hl:http1'
  34. // ---- the index --------------------------------------------------------------------------------------
  35. // Entry i keeps its kind, id and tie in parallel arrays in insertion order (mission T17).
  36. // HM63 stores normalized words joined by one space, including the title's year, in a
  37. // shared UTF-8 buffer with numeric offsets. Search decodes only its bucket candidates.
  38. static entKind = []
  39. static entId = []
  40. // HM63: normalized text is packed; only candidate Strings are decoded.
  41. static entText = new SearchText()
  42. static entTie = []
  43. static buckets = {}
  44. // what we have, by TMDB id: 'series:<id>' / 'movie:<id>' → our show id (the web list leaves these out)
  45. static haveTmdb = {}
  46. // tracker#18 (the daily sync's TVmaze change list, dailysync.hl): TVmaze id → our show id (kept by indexShow and
  47. // searchTitleChanged — the sync fills TVmaze ids)
  48. static haveTvmz = {}
  49. // every show slug in use (an imported title gets a free one)
  50. static slugTaken = {}
  51. // show id → true when the title may be listed (not adult, mission 054)
  52. static titleOk = {}
  53. // tracker#18 (a title renamed by the daily sync): show id → its entry's index; an entry replaced by a newer one is `stale`
  54. // (skipped by dbSearch — the buckets only ever grow)
  55. static titleEntry = {}
  56. static staleEntry = {}
  57. // GC1: how many entries are stale (usually none): while none is, the search skips the per-candidate key string `'' + i`
  58. static staleCount = { n = 0 }
  59. static indexStats = { built = false titles = 0 people = 0 keys = 0 ms = 0 }
  60. // `tie` orders equally good matches: lower first (a title: series before movies, then the newer one)
  61. static addEntry = (kind, id, &name, &extra, tie) => {
  62. words = wordsOf(&name)
  63. if (words.length == 0) { return false }
  64. i = entId.length
  65. all = []
  66. for (w of words) { all.push(w) }
  67. if (extra != null && extra != '') { all.push(extra) }
  68. entKind.push(kind == 'title' ? 0 : 1)
  69. entId.push(id)
  70. entText.push(all.join(' '))
  71. entTie.push(tie)
  72. if (kind == 'title') { titleEntry[id] = i }
  73. for (k of bucketKeys(&all)) {
  74. if (buckets[k] == null) { buckets[k] = [i] indexStats.keys = indexStats.keys + 1 } else { buckets[k].push(i) }
  75. }
  76. return true
  77. }
  78. static indexShow = (&s) => {
  79. if (s.urlSegment != null) { slugTaken[s.urlSegment] = true }
  80. // tracker#31: a merged tombstone keeps its slug taken, nothing else (its keeper is the title)
  81. if (s.mergedInto != null) {
  82. titleOk[s.id] = false
  83. return null
  84. }
  85. if (s.tmdbId != null) { haveTmdb[tmdbKeyOf(&s.type, &s.tmdbId)] = s.id }
  86. if (s.tvmzId != null) { haveTvmz['' + s.tvmzId] = s.id }
  87. titleOk[s.id] = isPublicTitle(&s)
  88. y = toNumber(yearWordOf(&s))
  89. if (addEntry('title', s.id, &s.title, yearWordOf(&s), (s.type == 'movie' ? 10000 : 0) + (y != null ? 3000 - y : 2999))) { indexStats.titles = indexStats.titles + 1 }
  90. return null
  91. }
  92. // tracker#26 (details.hl): a person added from a title's cast — findable by the search at once
  93. static indexPerson = (&p) => {
  94. ensureIndex()
  95. if (addEntry('person', p.id, &p.name, '', 0)) { indexStats.people = indexStats.people + 1 }
  96. return null
  97. }
  98. // a title's adult flag changed (the backfill / the daily sync): listed from now on, or not
  99. static searchTitleChanged = (&showId) => {
  100. s = showsTable.fetch(showId)
  101. if (s != null) { titleOk[s.id] = isPublicTitle(&s) }
  102. if (s != null && s.tvmzId != null) { haveTvmz['' + s.tvmzId] = s.id }
  103. return null
  104. }
  105. // tracker#31 (merge.hl): a duplicate became a tombstone of `keeperId` — its entry goes stale, its TMDB id (and TVmaze id) now
  106. // answer the keeper, so no import or filmography adds the title again
  107. static searchTitleMerged = (&tombId, &keeperId, &type, &tmdbId) => {
  108. ensureIndex()
  109. old = titleEntry[tombId]
  110. if (old != null) { staleEntry['' + old] = true staleCount.n = staleCount.n + 1 }
  111. titleOk[tombId] = false
  112. if (tmdbId != null) { haveTmdb[tmdbKeyOf(&type, &tmdbId)] = keeperId }
  113. k = showsTable.fetch(keeperId)
  114. if (k != null) {
  115. if (k.urlSegment != null) { slugTaken[k.urlSegment] = true }
  116. if (k.tvmzId != null) { haveTvmz['' + k.tvmzId] = k.id }
  117. titleOk[k.id] = isPublicTitle(&k)
  118. }
  119. return null
  120. }
  121. // a title's name changed (the daily sync, tracker#18): its old entry goes stale, a new one is added — found by the new name at once
  122. static searchTitleRenamed = (&showId) => {
  123. if (!indexStats.built) { return null }
  124. s = showsTable.fetch(showId)
  125. if (s == null) { return null }
  126. old = titleEntry[s.id]
  127. if (old != null && entText.fetch(old) == wordsOf(&s.title).join(' ')) { return null }
  128. if (old != null) { staleEntry['' + old] = true staleCount.n = staleCount.n + 1 }
  129. indexShow(&s)
  130. return null
  131. }
  132. // one person into the index (the scan below and bootscan.hl's person pass)
  133. static noteIndexPerson = (&p) => {
  134. if (addEntry('person', p.id, &p.name, '', 0)) { indexStats.people = indexStats.people + 1 }
  135. return null
  136. }
  137. // the scan is done (bootscan.hl streams the tables itself): the log line
  138. static finishSearchIndex = (&t0) => {
  139. indexStats.built = true
  140. indexStats.ms = now() - t0
  141. console.log('search index: ' + indexStats.titles + ' titles, ' + indexStats.people + ' people, ' + indexStats.keys + ' keys, ' + indexStats.ms + ' ms')
  142. return true
  143. }
  144. // built once: at boot (bootscan.hl does it inside its passes; this is the lazy fallback), else by the first search
  145. // mission T17: false while the progressive start is still filling the index (bootscan.hl) — the caller answers "starting up"
  146. static ensureIndex = () => {
  147. if (indexStats.built) { return true }
  148. if (warm.running) { return false }
  149. indexStats.built = true
  150. t0 = now()
  151. // mission 043: streamed, one record decoded at a time
  152. for (s of showsTable.iterate(null, null)) { indexShow(&s) }
  153. for (p of personsTable.iterate(null, null)) { noteIndexPerson(&p) }
  154. finishSearchIndex(&t0)
  155. return true
  156. }
  157. // tracker.worldapi.org#16 (people.hl): our show id for a TMDB title — `type` 'series' | 'movie' — or null
  158. static titleIdByTmdb = (&type, &tmdbId) => {
  159. ensureIndex()
  160. return haveTmdb[tmdbKeyOf(&type, &tmdbId)]
  161. }
  162. // tracker#18: our show id for a TVmaze id, or null
  163. static titleIdByTvmaze = (&tvmzId) => {
  164. ensureIndex()
  165. return haveTvmz['' + tvmzId]
  166. }
  167. // ---- our database ------------------------------------------------------------------------------------
  168. static titleLimit = 30
  169. static peopleLimit = 10
  170. // { text, words, titles: [{ id }], people: [{ id }], titleCount, peopleCount, tooShort }
  171. static dbSearch = (text) => {
  172. out = { text = text titles = [] people = [] titleCount = 0 peopleCount = 0 tooShort = false ms = 0 warming = false }
  173. if (!ensureIndex()) { out.warming = true return out }
  174. t0 = now()
  175. qw = wordsOf(&text)
  176. let longest = ''
  177. for (w of qw) { if (w.length > longest.length) { longest = w } }
  178. if (longest.length < 2) { out.tooShort = true return out }
  179. key = longest.slice(0, longest.length >= 3 ? 3 : 2)
  180. cand = buckets[key]
  181. if (cand == null) { return out }
  182. qtext = qw.join(' ')
  183. // GC1: per candidate no split, no map, no list copy unless the hit can still enter the top (a common word has ~100 k candidates and
  184. // each one used to build 3 maps, split its text twice and rebuild the top-30 list: 190 MB and 1.2 s per search on the real copy)
  185. qsp = []
  186. for (w of qw) { qsp.push(' ' + w) }
  187. q0 = qw[0]
  188. let titles = []
  189. let people = []
  190. for (i of cand) {
  191. candidateText = entText.fetch(i)
  192. if (matchesSpaced(&candidateText, &qw, &qsp)) {
  193. isTitle = entKind[i] == 0
  194. if (!isTitle || (titleOk[entId[i]] == true && (staleCount.n == 0 || staleEntry['' + i] != true))) {
  195. score = scoreText(&candidateText, &qtext, &q0)
  196. len = candidateText.length
  197. tie = entTie[i]
  198. if (isTitle) {
  199. out.titleCount = out.titleCount + 1
  200. if (titles.length < titleLimit || beatsLast(score, len, tie, &titles[titles.length - 1])) {
  201. item = { score = score len = len tie = tie i = i }
  202. titles = insertTop(&titles, &item, &titleLimit)
  203. }
  204. } else {
  205. out.peopleCount = out.peopleCount + 1
  206. if (people.length < peopleLimit || beatsLast(score, len, tie, &people[people.length - 1])) {
  207. item = { score = score len = len tie = tie i = i }
  208. people = insertTop(&people, &item, &peopleLimit)
  209. }
  210. }
  211. }
  212. }
  213. }
  214. for (t of titles) { out.titles.push({ id = entId[t.i] }) }
  215. for (p of people) { out.people.push({ id = entId[p.i] }) }
  216. out.ms = now() - t0
  217. return out
  218. }
  219. // ---- the web (TMDB) -----------------------------------------------------------------------------------
  220. // TMDB's search: [{ kind ('tv' | 'movie'), tmdbId, title, year, overview, posterUrl }] of what we DON'T have, or
  221. // { failed }. One request (search/multi, page 1 = up to 20 results); people and titles we have are left out.
  222. static webSearch = (&text) => {
  223. if (!ensureIndex()) { return { rows = [] left = 0 failed = 'tracker is starting up, try again in a minute' } }
  224. qw = wordsOf(&text)
  225. if (text == null || text.trim().length < 2 || qw.length == 0) { return { rows = [] left = 0 failed = null } }
  226. j = tmdbGet('/search/multi?query=' + encodeURIComponent(text.trim()) + '&include_adult=false&page=1')
  227. if (j.failed != null) { return { rows = [] left = 0 failed = j.failed } }
  228. rows = []
  229. let left = 0
  230. if (j.results != null) {
  231. for (r of j.results) {
  232. kind = r.media_type
  233. // mission 054: only what TMDB says is not adult (include_adult=false already, and the result's own flag)
  234. if ((kind == 'tv' || kind == 'movie') && r.id != null && hlTypeName(r.id) == 'Number' && adultOf(&r) == false) {
  235. if (haveTmdb[tmdbKeyOf(kind == 'tv' ? 'series' : 'movie', &r.id)] != null) {
  236. left = left + 1
  237. } else {
  238. title = kind == 'tv' ? textOr(&r.name) : textOr(&r.title)
  239. year = yearOfDate(kind == 'tv' ? r.first_air_date : r.release_date)
  240. if (title != null) {
  241. rows.push({ kind = kind tmdbId = r.id title = title year = year
  242. overview = textOr(&r.overview) != null ? r.overview : ''
  243. posterUrl = textOr(&r.poster_path) != null ? tmdbImageBase + '/w92' + r.poster_path : '/posters/none' })
  244. }
  245. }
  246. }
  247. }
  248. }
  249. return { rows = rows left = left failed = null }
  250. }
  251. // ---- the import ------------------------------------------------------------------------------------
  252. // "Doctor Who" → "Doctor-Who" (the migrated urlSegment form: letters and digits, everything else one '-'); a slug in use
  253. // gets "-2", "-3", … like the migrated ones ("Raised-by-Wolves-2"); a title with no Latin letter at all → "title-<tmdbId>"
  254. static slugOf = (&title, &tmdbId) => {
  255. out = slugBaseOf(&title, 'title-' + tmdbId)
  256. if (slugTaken[out] != true) { return out }
  257. let n = 2
  258. while (slugTaken[out + '-' + n] == true) { n = n + 1 }
  259. return out + '-' + n
  260. }
  261. // our genres by lower-case name (TMDB's "Drama" → ours); TMDB-only names ("Sci-Fi & Fantasy") are left out
  262. static genreIdsOf = (&tmdbGenres) => {
  263. out = []
  264. if (tmdbGenres == null) { return out }
  265. byName = {}
  266. for (g of genresTable.find(null, null)) { if (g.name != null) { byName[('' + g.name).toLowerCase()] = g.id } }
  267. for (tg of tmdbGenres) {
  268. id = tg.name != null ? byName[('' + tg.name).toLowerCase()] : null
  269. if (id != null && !out.includes(id)) { out.push(id) }
  270. }
  271. return out
  272. }
  273. // `kind` 'tv' | 'movie', `tmdbId` a number → { slug, path (its page, shows.hl titlePath), show, created, sync, details } or { error }. A title we already have (same
  274. // TMDB id and kind) is not added again: its slug is answered.
  275. static importTitle = (&kind, tmdbId) => {
  276. if (kind != 'tv' && kind != 'movie') { return { error = 'unknown kind' } }
  277. // `tid`, not `id`: inside the record literal below an entry named `id` would shadow it for every later entry
  278. tid = toNumber('' + tmdbId)
  279. if (tid == null || tid <= 0 || tid % 1 != 0) { return { error = 'bad TMDB id' } }
  280. if (!ensureIndex()) { return { error = 'tracker is starting up, try again in a minute' } }
  281. type = kind == 'tv' ? 'series' : 'movie'
  282. have = haveTmdb[tmdbKeyOf(&type, &tid)]
  283. if (have != null) {
  284. // tracker#31: a merged tombstone answers its keeper
  285. s = liveShowOf(showsTable.fetch(have))
  286. if (s != null) { return { slug = s.urlSegment path = titlePath(&s) show = s.id created = false } }
  287. }
  288. d = tmdbGet('/' + kind + '/' + tid + '?append_to_response=external_ids,' + (kind == 'tv' ? 'aggregate_credits' : 'credits'))
  289. if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }
  290. title = kind == 'tv' ? textOr(&d.name) : textOr(&d.title)
  291. if (title == null) { return { error = 'TMDB has no title for ' + kind + ' ' + tid } }
  292. release = textOr(kind == 'tv' ? d.first_air_date : d.release_date)
  293. year = release != null && release.length >= 4 ? toNumber(release.slice(0, 4)) : null
  294. // tracker#18: `summary` is the creator's own text — TMDB's goes to tmdbSummary only
  295. record = {
  296. id = newId() title = title summary = null tmdbSummary = textOr(&d.overview) tmdbId = tid
  297. language = textOr(&d.original_language) type = type release = release year = year image = null
  298. urlSegment = slugOf(&title, &tid) episodesCount = null homepage = textOr(&d.homepage) imdbId = null seasonsCount = null
  299. status = textOr(&d.status) tagline = textOr(&d.tagline) tvdbId = null tvmzId = null genres = genreIdsOf(&d.genres)
  300. cast = [] seasons = [] oldId = 'tmdb-' + kind + '-' + tid imported = now() adult = adultOf(&d)
  301. }
  302. // tracker.worldapi.org#21: a TV title's TMDB type and kind (set after the literal: an entry named `kind` would shadow the
  303. // parameter for the entries after it)
  304. if (kind == 'tv') {
  305. record.tmdbType = textOr(&d.type)
  306. record.kind = kindOfTitle(&record.tmdbType, &record.genres, &record.tvmazeType)
  307. }
  308. // tracker#31: looked up again right before the put — the TMDB request above may have taken a while
  309. again = titleIdByTmdb(&type, &tid)
  310. if (again != null) {
  311. s = liveShowOf(showsTable.fetch(again))
  312. if (s != null) { return { slug = s.urlSegment path = titlePath(&s) show = s.id created = false } }
  313. }
  314. // mission 060: its short id (shortids.hl — unique across shows and persons)
  315. record.shortId = claimShortId('show', record.id, &record.oldId)
  316. if (showsTable.put(record) == null) { return { error = 'could not store the title: ' + showsTable.lastError() } }
  317. indexShow(&record)
  318. r = syncShowWith(&record.id, &d)
  319. persistSync()
  320. // the public lists (catalog.hl, #13) get it at once, like a show the daily sync touched (merge of #13 + #14)
  321. refreshCatalogShow(&record.id)
  322. console.log('search import: ' + kind + ' ' + tid + ' "' + title + '" → ' + titlePath(&record) + ' (newSeasons=' + r.newSeasons + ' newEpisodes=' + r.newEpisodes + ' posters=' + r.posters + ' ids=' + r.ids + ' requests=' + r.requests + ' errors=' + r.errors + (r.error != '' ? ' ' + r.error : '') + ')')
  323. return { slug = record.urlSegment path = titlePath(&record) show = record.id created = true sync = r details = d }
  324. }
  325. static findRoute = (&route, &req) => {
  326. q = req.query != null && req.query.q != null && hlTypeName(req.query.q) == 'String' ? req.query.q.replaceAll('/', ' ').replaceAll('?', ' ').replaceAll('#', ' ').trim() : ''
  327. to = q != '' ? '/search/' + encodeURIComponent(q) : '/search'
  328. return new Response('see ' + to, { status = 302 headers = { 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })
  329. }

Branches

Latest commits

  • 7c3991f9log: day46 from Antonmre
  • c1a8d074log: correct timesmre
  • 5827eba9log: HM57 merged, HM59 startedmre
  • d1a91be9Merge hm57-let: tracker#57 let only for reassigned namesmre
  • a404ed75Report HM57 audit, gates and integration notesmre
  • 1dcb87a7Use plain declarations for unchanged bindingsmre
  • b90395e3log: HM51 mergedmre
  • 9888d076Merge hm51-classes: tracker#51 views use Style referencesmre
  • 4399bc2fReference remaining component-owned root Style rulesmre
  • 9edcc2dflog: #58 live, HM57 startedmre
  • 73fa20ddMerge hm49b-styles: tracker#49 rest of the component stylesmre
  • aed12917Reference owned Style rules in genres and searchmre
  • 14195720log: HM49B done, HM51 startedmre
  • 78ee6b56Move remaining component styles into Style blocksmre
  • 7f04de33log: HM49Bmre
  • 00616cf3log: #49 batch merged, DP67 startedmre
  • d7232e86Merge hm49-styles: tracker#49 first batch of component stylesmre
  • 079f376dMove seven components' styles into Style blocksmre
  • 17d66feelog: #58 mergedmre
  • 69a6640bMerge hm58-map: tracker#58 project.hl only the mapmre