tracker
All repositories: gitoria
13.1 KB
// project.hl — tracker.worldapi.org: STEP 1 (tracker.worldapi.org#1), an empty shell. Login copied unchanged from// calendar.worldapi.org (rejected once for a centered sign-in and no header selector — architect, 2026-09-27):// ident only, no own passwords (README "How apps use ident" of ident.worldapi.org), the identity selector in the// header (components/main.hl). No shows, no data yet — later steps come from the creator (CONCEPT.md).//// the header's ident-selector / "Log in with ident" -> <ident>/login?key=&return=<this app>/login/callback// /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id// (POST <ident>/api/exchange) and signs this app's OWN session in// (session.user = { id = <users @id> }, users.hl)// the header's "Log out" button signs this app's session out via the face trackerLogOut (components/main.hl)// — ident's own session, and the browser's ident cookie, are untouched//// Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the// architect, as with ident's own .env for SMTP):// TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),// IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…)import WebFramework from 'hl:web'import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import { env } from 'hl:proc'import { readBytes, exists } from 'hl:fs'import { now, timestamp, every } from 'hl:time'import Styles from './styles.hl'import { exchangeCode, ensureUser } from './users.hl'import Home from './components/home.hl'import LoginFailed from './components/loginfailed.hl'import Show from './components/show.hl'import Unwatched from './components/unwatched.hl'import Schedule from './components/schedule.hl'import MyShows from './components/myshows.hl'import Search from './components/search.hl'import { ensureIndex } from './search.hl'import { syncEnabled, syncShow, persistSync, emptyTotals, addTotals, totalsLine, pauseMsAfter } from './tmdbsync.hl'import { allFollowedShowIds } from './follows.hl'import { dark, darker } from './shared/tokens.hl'static appTitle = "tracker"// ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app// manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service// worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs// are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the// splash background the page's (dark) — both off the tokens, not written out again.appThemeColor = darker.valueappBackgroundColor = dark.valueappIcons = [{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }]appTouchIcon = '/icons/apple-touch-icon.png'appFavicon = '/icons/favicon.svg'// OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no// network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.offline = [ Home ]styles = Stylesport = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008watching = env('TRACKER_WATCH') != '0'// read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call belowsessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null// ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl// BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH// goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'safePath = (want) => {if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }let i = 0while (i < want.length) {if (!nextChars.includes(want[i])) { return '/' }i = i + 1}return want}// A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failedfailed = (req, why) => {let s = req.sessionlet fresh = s == nullif (fresh) { s = server.sessions.mint() }s.data.loginError = whyserver.sessions.save(s)let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }return res}// the function route gets the cookie's session as req.session (hybriel #11); none yet → minted hereloginCallback = (route, req) => {if (req.method != 'GET') { return failed(req, 'GET only') }let q = req.query != null ? req.query : {}let code = q.ident_codeif (code == null || code == '') { return failed(req, 'ident sent no login code') }let x = exchangeCode(code)if (x.error != null) { return failed(req, x.error) }let u = ensureUser(x.identity)if (u == null) { return failed(req, 'could not store the user') }let s = req.sessionlet fresh = s == nullif (fresh) { s = server.sessions.mint() }s.user = { id = u.id }s.data.tag = randomBytes(16)s.data.loginError = nullserver.sessions.save(s)let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }return res}// ---- /posters/<name> (tracker.worldapi.org#4): a show's poster image, served dynamically from// storage/mpackdb/posters/ (the poster's file name is the show's oldId + its migrated extension,// shows.hl posterName) — falls back to a placeholder svg when the real file isn't there yet (the// mongo export never included the actual poster bytes, see the report's `open`).postersDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/posters'placeholderPoster = './assets/poster-placeholder.svg'posterNameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'isSafePosterName = (name) => {if (name == null || hlTypeName(name) != 'String' || name == '' || name.length > 100) { return false }let i = 0while (i < name.length) {if (!posterNameChars.includes(name[i])) { return false }i = i + 1}return true}endsWithStr = (s, suffix) => { return s.length >= suffix.length && s.slice(s.length - suffix.length) == suffix }mimeOfPoster = (name) => {if (endsWithStr(name, '.png')) { return 'image/png' }if (endsWithStr(name, '.webp')) { return 'image/webp' }if (endsWithStr(name, '.svg')) { return 'image/svg+xml' }return 'image/jpeg'}posterRoute = (route, req) => {let name = route.params != null ? route.params.name : nullif (!isSafePosterName(name)) { return new Response('bad poster name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }let path = postersDir + '/' + nameif (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })}// ---- the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now —// a permanent redirect so old links keep working (architect's decision)movedTo = (path) => { return new Response('moved to ' + path, { status = 301 headers = { 'Location' = path 'Content-Type' = 'text/plain; charset=utf-8' } }) }unwatchedMoved = (route, req) => { return movedTo('/my/unwatched') }scheduleMoved = (route, req) => { return movedTo('/my/schedule') }routes = [{ pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }// the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline){ pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/login/callback" function = loginCallback }{ pattern = "/login/failed" component = LoginFailed }{ pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/posters/:name" function = posterRoute }{ pattern = "/shows/:slug" component = Show }{ pattern = "/my/shows" component = MyShows }{ pattern = "/my/unwatched" component = Unwatched }{ pattern = "/my/schedule" component = Schedule }{ pattern = "/unwatched" function = unwatchedMoved }{ pattern = "/schedule" function = scheduleMoved }// tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`){ pattern = "/search/:q?" component = Search }{ pattern = "/" component = Home }]// WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }audience = {trackerSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }trackerSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }}// cookies are per host, not per port: an own name keeps this app's session apart from// ident's own (and from any other worldapi app sharing a dev host), see ident README "Design// tokens" / hybriel#10 hybriel#17.sessionCookie = 'trackersid'// tracker.worldapi.org#14: the search index (search.hl) is built once here at boot (~0.6 s on the real data), not by the// first searchsearchIndexReady = ensureIndex()server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching)// ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, tmdbsync.hl) --------------------------------------// Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC) every// followed show is synced from TMDB. hl:web serves ONE request at a time, so the run never takes the server// for itself: a 1-second clock does ONE show per tick (1–3 TMDB requests + maybe its poster) and returns — the// requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.// After a show that made n requests the next waits n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze lookup// (≤ 20 / 10 s, tracker.worldapi.org#12).// TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4syncOn = env('TRACKER_SYNC') != '0' && syncEnabledsyncQueue = []syncAt = 0syncDay = ''syncNextAt = 0syncTotals = emptyTotals()syncTick = () => {let t = now()if (syncQueue.length == 0) {let stamp = timestamp(t)let day = stamp.slice(0, 10)if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }syncDay = daysyncQueue = allFollowedShowIds()syncAt = tsyncNextAt = 0syncTotals = emptyTotals()console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows')return null}if (t < syncNextAt) { return null }let id = syncQueue[0]let rest = []let i = 1while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }syncQueue = restlet r = syncShow(id)let took = now() - tsyncTotals = addTotals(syncTotals, r)if (r.error != '') { console.log('tmdb sync: ' + r.error) }// a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the logif (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }syncNextAt = now() + pauseMsAfter(r)if (syncQueue.length == 0 || syncTotals.shows % 10 == 0) { persistSync() }if (syncQueue.length == 0) { console.log('tmdb sync done: ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000)) }return null}if (syncOn) {console.log('tmdb sync: daily at ' + syncHour + ':00 UTC')syncClock = every(1)on syncClock.tick(x) {syncTick()return null}} else {console.log('tmdb sync: off (' + (syncEnabled ? 'TRACKER_SYNC=0' : 'no TMDB_READ_TOKEN') + ')')}on Error(e) { console.log('error absorbed: ' + e.message) }
Branches
- mainmain branch
Latest commits
- 65c694a8tracker#14: search — header magnifier, /search/<text> (in-memory word-prefix index over titles + people), Fetch from web (TMDB search/multi, ours left out), Add = import via syncShow; gate +25 checks, real-data scriptmre
- 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