tracker
All repositories: gitoria
20.0 KB
import { importWithCredits } from './details.hl'import { personPhotoOf } from './people.hl'import SearchText from './search-text.hl'// lib/search.hl — THE SEARCH (tracker.worldapi.org#14): our own database first, then "Fetch from web" (TMDB) for titles// we don't have yet, and the import of the one picked. Used by components/search.hl (`/search/<text>`).//// dbSearch(text) our shows, movies and people — from an IN-MEMORY INDEX built once at boot (no table scan per// keystroke): every title/name split into words; each word's first 2 and first 3 characters are// a bucket key → the entries holding such a word. A query looks at ONE bucket (its longest word's// first 3 characters, or 2 for a 2-letter word) and keeps the entries where EVERY query word is// the start of one of the entry's words. A title's year is one of its words ("doctor who 2005").// webSearch(text) GET <TMDB_BASE_URL>/search/multi?query=… (one request; TV + movies only, people dropped) —// the titles we already have (same TMDB id and kind) are left out// importTitle(kind, id) a new show record from GET /tv/<id>?append_to_response=external_ids,aggregate_credits (a movie:// /movie/<id>?…,credits), then sync.hl `syncShowWith` fills it from that same answer exactly like// the daily sync does (seasons, episodes, poster, external ids); added to the index. The answer goes// back as `details`: the caller (components/search.hl) stores its cast + crew (credits.hl applyCredits,// tracker#28 — details.hl imports this file, so it cannot be called from here)//// ADULT TITLES (mission 054): our database lists only titles with `adult == false` (shows.hl isPublicTitle; unknown is// hidden) — `titleOk` holds that per show id, set by indexShow and by `searchTitleChanged` (the adult backfill and the daily// sync call it per title). The web list asks TMDB with include_adult=false AND keeps only results with `adult` false.//// ONE PROCESS PER STORAGE (hybriel#21): the index lives in the app's process and is kept up to date by importTitle; the// daily sync never changes a title. New rows get self-assigned 16-hex ids (hybriel#113), like sync.hl.import { now } from 'hl:time'import { warm } from './warm.hl'import { textOr, newId } from './util.hl'import { showsTable, personsTable, genresTable, isPublicTitle, kindOfTitle, titlePath, liveShowOf, showById, personById, posterUrlOf, titleWithYear, typeWordOf, typeClassOf } from './shows.hl'import { tmdbGet, tmdbImageBase, adultOf } from './tmdb.hl'import { syncShowWith, persistSync } from './sync.hl'import { refreshCatalogShow } from './catalog.hl'import { claimShortId } from './shortids.hl'import { wordsOf, bucketKeys, tmdbKeyOf, yearWordOf, scoreOf, matchesText, matchesSpaced, scoreText, beatsLast, entryWords, insertTop, yearOfDate, slugBaseOf } from './search-helpers.hl'import { Response } from 'hl:http1'// ---- the index --------------------------------------------------------------------------------------// Entry i keeps its kind, id and tie in parallel arrays in insertion order (mission T17).// HM63 stores normalized words joined by one space, including the title's year, in a// shared UTF-8 buffer with numeric offsets. Search decodes only its bucket candidates.static entKind = []static entId = []// HM63: normalized text is packed; only candidate Strings are decoded.static entText = new SearchText()static entTie = []static buckets = {}// what we have, by TMDB id: 'series:<id>' / 'movie:<id>' → our show id (the web list leaves these out)static haveTmdb = {}// tracker#18 (the daily sync's TVmaze change list, dailysync.hl): TVmaze id → our show id (kept by indexShow and// searchTitleChanged — the sync fills TVmaze ids)static haveTvmz = {}// every show slug in use (an imported title gets a free one)static slugTaken = {}// show id → true when the title may be listed (not adult, mission 054)static titleOk = {}// tracker#18 (a title renamed by the daily sync): show id → its entry's index; an entry replaced by a newer one is `stale`// (skipped by dbSearch — the buckets only ever grow)static titleEntry = {}static staleEntry = {}// GC1: how many entries are stale (usually none): while none is, the search skips the per-candidate key string `'' + i`static staleCount = { n = 0 }static indexStats = { built = false titles = 0 people = 0 keys = 0 ms = 0 }// `tie` orders equally good matches: lower first (a title: series before movies, then the newer one)static addEntry = (kind, id, &name, &extra, tie) => {words = wordsOf(&name)if (words.length == 0) { return false }i = entId.lengthall = []for (w of words) { all.push(w) }if (extra != null && extra != '') { all.push(extra) }entKind.push(kind == 'title' ? 0 : 1)entId.push(id)entText.push(all.join(' '))entTie.push(tie)if (kind == 'title') { titleEntry[id] = i }for (k of bucketKeys(&all)) {if (buckets[k] == null) { buckets[k] = [i] indexStats.keys = indexStats.keys + 1 } else { buckets[k].push(i) }}return true}static indexShow = (&s) => {if (s.urlSegment != null) { slugTaken[s.urlSegment] = true }// tracker#31: a merged tombstone keeps its slug taken, nothing else (its keeper is the title)if (s.mergedInto != null) {titleOk[s.id] = falsereturn null}if (s.tmdbId != null) { haveTmdb[tmdbKeyOf(&s.type, &s.tmdbId)] = s.id }if (s.tvmzId != null) { haveTvmz['' + s.tvmzId] = s.id }titleOk[s.id] = isPublicTitle(&s)y = toNumber(yearWordOf(&s))if (addEntry('title', s.id, &s.title, yearWordOf(&s), (s.type == 'movie' ? 10000 : 0) + (y != null ? 3000 - y : 2999))) { indexStats.titles = indexStats.titles + 1 }return null}// tracker#26 (details.hl): a person added from a title's cast — findable by the search at oncestatic indexPerson = (&p) => {ensureIndex()if (addEntry('person', p.id, &p.name, '', 0)) { indexStats.people = indexStats.people + 1 }return null}// a title's adult flag changed (the backfill / the daily sync): listed from now on, or notstatic searchTitleChanged = (&showId) => {s = showsTable.fetch(showId)if (s != null) { titleOk[s.id] = isPublicTitle(&s) }if (s != null && s.tvmzId != null) { haveTvmz['' + s.tvmzId] = s.id }return null}// tracker#31 (merge.hl): a duplicate became a tombstone of `keeperId` — its entry goes stale, its TMDB id (and TVmaze id) now// answer the keeper, so no import or filmography adds the title againstatic searchTitleMerged = (&tombId, &keeperId, &type, &tmdbId) => {ensureIndex()old = titleEntry[tombId]if (old != null) { staleEntry['' + old] = true staleCount.n = staleCount.n + 1 }titleOk[tombId] = falseif (tmdbId != null) { haveTmdb[tmdbKeyOf(&type, &tmdbId)] = keeperId }k = showsTable.fetch(keeperId)if (k != null) {if (k.urlSegment != null) { slugTaken[k.urlSegment] = true }if (k.tvmzId != null) { haveTvmz['' + k.tvmzId] = k.id }titleOk[k.id] = isPublicTitle(&k)}return null}// 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 oncestatic searchTitleRenamed = (&showId) => {if (!indexStats.built) { return null }s = showsTable.fetch(showId)if (s == null) { return null }old = titleEntry[s.id]if (old != null && entText.fetch(old) == wordsOf(&s.title).join(' ')) { return null }if (old != null) { staleEntry['' + old] = true staleCount.n = staleCount.n + 1 }indexShow(&s)return null}// one person into the index (the scan below and bootscan.hl's person pass)static noteIndexPerson = (&p) => {if (addEntry('person', p.id, &p.name, '', 0)) { indexStats.people = indexStats.people + 1 }return null}// the scan is done (bootscan.hl streams the tables itself): the log linestatic finishSearchIndex = (&t0) => {indexStats.built = trueindexStats.ms = now() - t0console.log('search index: ' + indexStats.titles + ' titles, ' + indexStats.people + ' people, ' + indexStats.keys + ' keys, ' + indexStats.ms + ' ms')return true}// built once: at boot (bootscan.hl does it inside its passes; this is the lazy fallback), else by the first search// mission T17: false while the progressive start is still filling the index (bootscan.hl) — the caller answers "starting up"static ensureIndex = () => {if (indexStats.built) { return true }if (warm.running) { return false }indexStats.built = truet0 = now()// mission 043: streamed, one record decoded at a timefor (s of showsTable.iterate(null, null)) { indexShow(&s) }for (p of personsTable.iterate(null, null)) { noteIndexPerson(&p) }finishSearchIndex(&t0)return true}// tracker.worldapi.org#16 (people.hl): our show id for a TMDB title — `type` 'series' | 'movie' — or nullstatic titleIdByTmdb = (&type, &tmdbId) => {ensureIndex()return haveTmdb[tmdbKeyOf(&type, &tmdbId)]}// tracker#18: our show id for a TVmaze id, or nullstatic titleIdByTvmaze = (&tvmzId) => {ensureIndex()return haveTvmz['' + tvmzId]}// ---- our database ------------------------------------------------------------------------------------static titleLimit = 30static peopleLimit = 10// { text, words, titles: [{ id }], people: [{ id }], titleCount, peopleCount, tooShort }static dbSearch = (text) => {out = { text = text titles = [] people = [] titleCount = 0 peopleCount = 0 tooShort = false ms = 0 warming = false }if (!ensureIndex()) { out.warming = true return out }t0 = now()qw = wordsOf(&text)let longest = ''for (w of qw) { if (w.length > longest.length) { longest = w } }if (longest.length < 2) { out.tooShort = true return out }key = longest.slice(0, longest.length >= 3 ? 3 : 2)cand = buckets[key]if (cand == null) { return out }qtext = qw.join(' ')// 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// 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)qsp = []for (w of qw) { qsp.push(' ' + w) }q0 = qw[0]let titles = []let people = []for (i of cand) {candidateText = entText.fetch(i)if (matchesSpaced(&candidateText, &qw, &qsp)) {isTitle = entKind[i] == 0if (!isTitle || (titleOk[entId[i]] == true && (staleCount.n == 0 || staleEntry['' + i] != true))) {score = scoreText(&candidateText, &qtext, &q0)len = candidateText.lengthtie = entTie[i]if (isTitle) {out.titleCount = out.titleCount + 1if (titles.length < titleLimit || beatsLast(score, len, tie, &titles[titles.length - 1])) {item = { score = score len = len tie = tie i = i }titles = insertTop(&titles, &item, &titleLimit)}} else {out.peopleCount = out.peopleCount + 1if (people.length < peopleLimit || beatsLast(score, len, tie, &people[people.length - 1])) {item = { score = score len = len tie = tie i = i }people = insertTop(&people, &item, &peopleLimit)}}}}}for (t of titles) { out.titles.push({ id = entId[t.i] }) }for (p of people) { out.people.push({ id = entId[p.i] }) }out.ms = now() - t0return out}// ---- the web (TMDB) -----------------------------------------------------------------------------------// TMDB's search: [{ kind ('tv' | 'movie'), tmdbId, title, year, overview, posterUrl }] of what we DON'T have, or// { failed }. One request (search/multi, page 1 = up to 20 results); people and titles we have are left out.static webSearch = (&text) => {if (!ensureIndex()) { return { rows = [] left = 0 failed = 'tracker is starting up, try again in a minute' } }qw = wordsOf(&text)if (text == null || text.trim().length < 2 || qw.length == 0) { return { rows = [] left = 0 failed = null } }j = tmdbGet('/search/multi?query=' + encodeURIComponent(text.trim()) + '&include_adult=false&page=1')if (j.failed != null) { return { rows = [] left = 0 failed = j.failed } }rows = []let left = 0if (j.results != null) {for (r of j.results) {kind = r.media_type// mission 054: only what TMDB says is not adult (include_adult=false already, and the result's own flag)if ((kind == 'tv' || kind == 'movie') && r.id != null && hlTypeName(r.id) == 'Number' && adultOf(&r) == false) {if (haveTmdb[tmdbKeyOf(kind == 'tv' ? 'series' : 'movie', &r.id)] != null) {left = left + 1} else {title = kind == 'tv' ? textOr(&r.name) : textOr(&r.title)year = yearOfDate(kind == 'tv' ? r.first_air_date : r.release_date)if (title != null) {rows.push({ kind = kind tmdbId = r.id title = title year = yearoverview = textOr(&r.overview) != null ? r.overview : ''posterUrl = textOr(&r.poster_path) != null ? tmdbImageBase + '/w92' + r.poster_path : '/posters/none' })}}}}}return { rows = rows left = left failed = null }}// ---- the import ------------------------------------------------------------------------------------// "Doctor Who" → "Doctor-Who" (the migrated urlSegment form: letters and digits, everything else one '-'); a slug in use// gets "-2", "-3", … like the migrated ones ("Raised-by-Wolves-2"); a title with no Latin letter at all → "title-<tmdbId>"static slugOf = (&title, &tmdbId) => {out = slugBaseOf(&title, 'title-' + tmdbId)if (slugTaken[out] != true) { return out }let n = 2while (slugTaken[out + '-' + n] == true) { n = n + 1 }return out + '-' + n}// our genres by lower-case name (TMDB's "Drama" → ours); TMDB-only names ("Sci-Fi & Fantasy") are left outstatic genreIdsOf = (&tmdbGenres) => {out = []if (tmdbGenres == null) { return out }byName = {}for (g of genresTable.find(null, null)) { if (g.name != null) { byName[('' + g.name).toLowerCase()] = g.id } }for (tg of tmdbGenres) {id = tg.name != null ? byName[('' + tg.name).toLowerCase()] : nullif (id != null && !out.includes(id)) { out.push(id) }}return out}// `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// TMDB id and kind) is not added again: its slug is answered.static importTitle = (&kind, tmdbId) => {if (kind != 'tv' && kind != 'movie') { return { error = 'unknown kind' } }// `tid`, not `id`: inside the record literal below an entry named `id` would shadow it for every later entrytid = toNumber('' + tmdbId)if (tid == null || tid <= 0 || tid % 1 != 0) { return { error = 'bad TMDB id' } }if (!ensureIndex()) { return { error = 'tracker is starting up, try again in a minute' } }type = kind == 'tv' ? 'series' : 'movie'have = haveTmdb[tmdbKeyOf(&type, &tid)]if (have != null) {// tracker#31: a merged tombstone answers its keepers = liveShowOf(showsTable.fetch(have))if (s != null) { return { slug = s.urlSegment path = titlePath(&s) show = s.id created = false } }}d = tmdbGet('/' + kind + '/' + tid + '?append_to_response=external_ids,' + (kind == 'tv' ? 'aggregate_credits' : 'credits'))if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }title = kind == 'tv' ? textOr(&d.name) : textOr(&d.title)if (title == null) { return { error = 'TMDB has no title for ' + kind + ' ' + tid } }release = textOr(kind == 'tv' ? d.first_air_date : d.release_date)year = release != null && release.length >= 4 ? toNumber(release.slice(0, 4)) : null// tracker#18: `summary` is the creator's own text — TMDB's goes to tmdbSummary onlyrecord = {id = newId() title = title summary = null tmdbSummary = textOr(&d.overview) tmdbId = tidlanguage = textOr(&d.original_language) type = type release = release year = year image = nullurlSegment = slugOf(&title, &tid) episodesCount = null homepage = textOr(&d.homepage) imdbId = null seasonsCount = nullstatus = textOr(&d.status) tagline = textOr(&d.tagline) tvdbId = null tvmzId = null genres = genreIdsOf(&d.genres)cast = [] seasons = [] oldId = 'tmdb-' + kind + '-' + tid imported = now() adult = adultOf(&d)}// tracker.worldapi.org#21: a TV title's TMDB type and kind (set after the literal: an entry named `kind` would shadow the// parameter for the entries after it)if (kind == 'tv') {record.tmdbType = textOr(&d.type)record.kind = kindOfTitle(&record.tmdbType, &record.genres, &record.tvmazeType)}// tracker#31: looked up again right before the put — the TMDB request above may have taken a whileagain = titleIdByTmdb(&type, &tid)if (again != null) {s = liveShowOf(showsTable.fetch(again))if (s != null) { return { slug = s.urlSegment path = titlePath(&s) show = s.id created = false } }}// mission 060: its short id (shortids.hl — unique across shows and persons)record.shortId = claimShortId('show', record.id, &record.oldId)if (showsTable.put(record) == null) { return { error = 'could not store the title: ' + showsTable.lastError() } }indexShow(&record)r = syncShowWith(&record.id, &d)persistSync()// the public lists (catalog.hl, #13) get it at once, like a show the daily sync touched (merge of #13 + #14)refreshCatalogShow(&record.id)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 : '') + ')')return { slug = record.urlSegment path = titlePath(&record) show = record.id created = true sync = r details = d }}static findRoute = (&route, &req) => {q = req.query != null && req.query.q != null && hlTypeName(req.query.q) == 'String' ? req.query.q.replaceAll('/', ' ').replaceAll('?', ' ').replaceAll('#', ' ').trim() : ''to = q != '' ? '/search/' + encodeURIComponent(q) : '/search'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' } })}// tracker#59: search page rows.static resultsOf = (text) => {t = text != null ? '' + text : ''r = dbSearch(t)titleRows = []for (x of r.titles) {s = showById(&x.id)if (s != null) { titleRows.push({ id = s.id title = titleWithYear(&s) href = titlePath(&s) posterUrl = posterUrlOf(&s) typeLabel = typeWordOf(&s) typeClass = typeClassOf(&s) }) }}peopleRows = []for (x of r.people) {p = personById(&x.id)// tracker#37: with their photo (people.hl personPhotoOf: ours, else TMDB's, else the placeholder)if (p != null) { peopleRows.push({ id = p.id name = p.name href = '/person/' + p.urlSegment photoUrl = personPhotoOf(&p) }) }}let note = ''if (t.trim() == '') { note = 'Search our shows, movies and people.' }else if (r.tooShort) { note = 'Type at least 2 letters.' }else if (titleRows.length == 0 && peopleRows.length == 0) { note = 'Nothing in our database yet.' }let more = ''if (r.titleCount > titleRows.length) { more = 'The first ' + titleRows.length + ' of ' + r.titleCount + ' titles — type more to narrow it down.' }return { text = t titleRows = titleRows peopleRows = peopleRows note = note more = more canFetch = t.trim() != '' && !r.tooShort }}static webRowsOf = (text) => {w = webSearch(&text)rows = []for (x of w.rows) {rows.push({ key = x.kind + ':' + x.tmdbId kind = x.kind tmdbId = x.tmdbId title = x.year != '' ? x.title + ' (' + x.year + ')' : x.titleoverview = x.overview posterUrl = x.posterUrl typeLabel = x.kind == 'movie' ? 'Movie' : 'TV' typeClass = x.kind == 'movie' ? 'pill type-1' : 'pill type-2' })}let note = ''if (w.failed != null) { note = 'TMDB did not answer — try again in a moment.' }else if (rows.length == 0) { note = w.left > 0 ? 'TMDB found nothing we don\'t have already.' : 'TMDB found nothing either.' }return { text = text rows = rows note = note }}static searchImportOf = (&kind, tmdbId) => {// tracker#28: with the imported title's cast + crew, from the import's own details answer (details.hl)r = importWithCredits(&kind, tmdbId)if (r.error != null) { return { error = r.error } }return { ok = true slug = r.slug path = r.path created = r.created }}
Branches
Latest commits
- 29867a75Merge hm59-logic: tracker#59 page logic moved to libmre
- f7bfe90bMove remaining page builders into their topicsmre
- 7c3991f9log: day46 from Antonmre
- ec54fc35Move show page logic into the shows topicmre
- 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