gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitdcc5eecadcc5eecaMerge branch 't14-search'mredcc5eeca/project.hl

13.9 KB

  1. // project.hl — tracker.worldapi.org: STEP 1 (tracker.worldapi.org#1), an empty shell. Login copied unchanged from
  2. // calendar.worldapi.org (rejected once for a centered sign-in and no header selector — architect, 2026-09-27):
  3. // ident only, no own passwords (README "How apps use ident" of ident.worldapi.org), the identity selector in the
  4. // header (components/main.hl). No shows, no data yet — later steps come from the creator (CONCEPT.md).
  5. //
  6. // the header's ident-selector / "Log in with ident" -> <ident>/login?key=&return=<this app>/login/callback
  7. // /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id
  8. // (POST <ident>/api/exchange) and signs this app's OWN session in
  9. // (session.user = { id = <users @id> }, users.hl)
  10. // the header's "Log out" button signs this app's session out via the face trackerLogOut (components/main.hl)
  11. // — ident's own session, and the browser's ident cookie, are untouched
  12. //
  13. // Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the
  14. // architect, as with ident's own .env for SMTP):
  15. // TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),
  16. // IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…)
  17. import WebFramework from 'hl:web'
  18. import { Response } from 'hl:http1'
  19. import { randomBytes } from 'hl:crypto'
  20. import { env } from 'hl:proc'
  21. import { readBytes, exists } from 'hl:fs'
  22. import { now, timestamp, every } from 'hl:time'
  23. import Styles from './styles.hl'
  24. import { exchangeCode, ensureUser } from './users.hl'
  25. import Home from './components/home.hl'
  26. import LoginFailed from './components/loginfailed.hl'
  27. import Show from './components/show.hl'
  28. import Unwatched from './components/unwatched.hl'
  29. import Schedule from './components/schedule.hl'
  30. import MyShows from './components/myshows.hl'
  31. import MyMovies from './components/mymovies.hl'
  32. import Movies from './components/movies.hl'
  33. import AllShows from './components/allshows.hl'
  34. import Search from './components/search.hl'
  35. import { ensureIndex } from './search.hl'
  36. import { syncEnabled, syncShow, persistSync, emptyTotals, addTotals, totalsLine, pauseMsAfter } from './tmdbsync.hl'
  37. import { allFollowedShowIds } from './follows.hl'
  38. import { refreshCatalogShow } from './catalog.hl'
  39. import { dark, darker } from './shared/tokens.hl'
  40. static appTitle = "tracker"
  41. // ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app
  42. // manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service
  43. // worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs
  44. // are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the
  45. // splash background the page's (dark) — both off the tokens, not written out again.
  46. appThemeColor = darker.value
  47. appBackgroundColor = dark.value
  48. appIcons = [
  49. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }
  50. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }
  51. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }
  52. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }
  53. ]
  54. appTouchIcon = '/icons/apple-touch-icon.png'
  55. appFavicon = '/icons/favicon.svg'
  56. // OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no
  57. // network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.
  58. offline = [ Home ]
  59. styles = Styles
  60. port = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008
  61. watching = env('TRACKER_WATCH') != '0'
  62. // read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call below
  63. sessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null
  64. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl
  65. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  66. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  67. nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  68. safePath = (want) => {
  69. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  70. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  71. let i = 0
  72. while (i < want.length) {
  73. if (!nextChars.includes(want[i])) { return '/' }
  74. i = i + 1
  75. }
  76. return want
  77. }
  78. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  79. failed = (req, why) => {
  80. let s = req.session
  81. let fresh = s == null
  82. if (fresh) { s = server.sessions.mint() }
  83. s.data.loginError = why
  84. server.sessions.save(s)
  85. let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  86. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  87. return res
  88. }
  89. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here
  90. loginCallback = (route, req) => {
  91. if (req.method != 'GET') { return failed(req, 'GET only') }
  92. let q = req.query != null ? req.query : {}
  93. let code = q.ident_code
  94. if (code == null || code == '') { return failed(req, 'ident sent no login code') }
  95. let x = exchangeCode(code)
  96. if (x.error != null) { return failed(req, x.error) }
  97. let u = ensureUser(x.identity)
  98. if (u == null) { return failed(req, 'could not store the user') }
  99. let s = req.session
  100. let fresh = s == null
  101. if (fresh) { s = server.sessions.mint() }
  102. s.user = { id = u.id }
  103. s.data.tag = randomBytes(16)
  104. s.data.loginError = null
  105. server.sessions.save(s)
  106. let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  107. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  108. return res
  109. }
  110. // ---- /posters/<name> (tracker.worldapi.org#4): a show's poster image, served dynamically from
  111. // storage/mpackdb/posters/ (the poster's file name is the show's oldId + its migrated extension,
  112. // shows.hl posterName) — falls back to a placeholder svg when the real file isn't there yet (the
  113. // mongo export never included the actual poster bytes, see the report's `open`).
  114. postersDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/posters'
  115. placeholderPoster = './assets/poster-placeholder.svg'
  116. posterNameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'
  117. isSafePosterName = (name) => {
  118. if (name == null || hlTypeName(name) != 'String' || name == '' || name.length > 100) { return false }
  119. let i = 0
  120. while (i < name.length) {
  121. if (!posterNameChars.includes(name[i])) { return false }
  122. i = i + 1
  123. }
  124. return true
  125. }
  126. endsWithStr = (s, suffix) => { return s.length >= suffix.length && s.slice(s.length - suffix.length) == suffix }
  127. mimeOfPoster = (name) => {
  128. if (endsWithStr(name, '.png')) { return 'image/png' }
  129. if (endsWithStr(name, '.webp')) { return 'image/webp' }
  130. if (endsWithStr(name, '.svg')) { return 'image/svg+xml' }
  131. return 'image/jpeg'
  132. }
  133. posterRoute = (route, req) => {
  134. let name = route.params != null ? route.params.name : null
  135. if (!isSafePosterName(name)) { return new Response('bad poster name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  136. let path = postersDir + '/' + name
  137. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  138. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  139. }
  140. // ---- the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now —
  141. // a permanent redirect so old links keep working (architect's decision)
  142. movedTo = (path) => { return new Response('moved to ' + path, { status = 301 headers = { 'Location' = path 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  143. unwatchedMoved = (route, req) => { return movedTo('/my/unwatched') }
  144. scheduleMoved = (route, req) => { return movedTo('/my/schedule') }
  145. routes = [
  146. { pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }
  147. // the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline)
  148. { pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }
  149. { pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }
  150. { pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }
  151. { pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }
  152. { pattern = "/login/callback" function = loginCallback }
  153. { pattern = "/login/failed" component = LoginFailed }
  154. { pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }
  155. { pattern = "/posters/:name" function = posterRoute }
  156. // tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a
  157. // page component cannot read `?page=` (hybriel#11) — and the movies the user follows
  158. { pattern = "/movies" component = Movies }
  159. { pattern = "/movies/page/:page" component = Movies }
  160. { pattern = "/shows" component = AllShows }
  161. { pattern = "/shows/page/:page" component = AllShows }
  162. { pattern = "/shows/:slug" component = Show }
  163. { pattern = "/my/shows" component = MyShows }
  164. { pattern = "/my/movies" component = MyMovies }
  165. { pattern = "/my/unwatched" component = Unwatched }
  166. { pattern = "/my/schedule" component = Schedule }
  167. { pattern = "/unwatched" function = unwatchedMoved }
  168. { pattern = "/schedule" function = scheduleMoved }
  169. // tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`)
  170. { pattern = "/search/:q?" component = Search }
  171. { pattern = "/" component = Home }
  172. ]
  173. // WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).
  174. tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }
  175. audience = {
  176. trackerSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }
  177. trackerSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }
  178. }
  179. // cookies are per host, not per port: an own name keeps this app's session apart from
  180. // ident's own (and from any other worldapi app sharing a dev host), see ident README "Design
  181. // tokens" / hybriel#10 hybriel#17.
  182. sessionCookie = 'trackersid'
  183. // 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
  184. // first search
  185. searchIndexReady = ensureIndex()
  186. server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching)
  187. // ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, tmdbsync.hl) --------------------------------------
  188. // Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC) every
  189. // followed show is synced from TMDB. hl:web serves ONE request at a time, so the run never takes the server
  190. // for itself: a 1-second clock does ONE show per tick (1–3 TMDB requests + maybe its poster) and returns — the
  191. // requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.
  192. // After a show that made n requests the next waits n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze lookup
  193. // (≤ 20 / 10 s, tracker.worldapi.org#12).
  194. // TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).
  195. syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4
  196. syncOn = env('TRACKER_SYNC') != '0' && syncEnabled
  197. syncQueue = []
  198. syncAt = 0
  199. syncDay = ''
  200. syncNextAt = 0
  201. syncTotals = emptyTotals()
  202. syncTick = () => {
  203. let t = now()
  204. if (syncQueue.length == 0) {
  205. let stamp = timestamp(t)
  206. let day = stamp.slice(0, 10)
  207. if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }
  208. syncDay = day
  209. syncQueue = allFollowedShowIds()
  210. syncAt = t
  211. syncNextAt = 0
  212. syncTotals = emptyTotals()
  213. console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows')
  214. return null
  215. }
  216. if (t < syncNextAt) { return null }
  217. let id = syncQueue[0]
  218. let rest = []
  219. let i = 1
  220. while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }
  221. syncQueue = rest
  222. let r = syncShow(id)
  223. // the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode
  224. refreshCatalogShow(id)
  225. let took = now() - t
  226. syncTotals = addTotals(syncTotals, r)
  227. if (r.error != '') { console.log('tmdb sync: ' + r.error) }
  228. // a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the log
  229. if (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }
  230. syncNextAt = now() + pauseMsAfter(r)
  231. if (syncQueue.length == 0 || syncTotals.shows % 10 == 0) { persistSync() }
  232. if (syncQueue.length == 0) { console.log('tmdb sync done: ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000)) }
  233. return null
  234. }
  235. if (syncOn) {
  236. console.log('tmdb sync: daily at ' + syncHour + ':00 UTC')
  237. syncClock = every(1)
  238. on syncClock.tick(x) {
  239. syncTick()
  240. return null
  241. }
  242. } else {
  243. console.log('tmdb sync: off (' + (syncEnabled ? 'TRACKER_SYNC=0' : 'no TMDB_READ_TOKEN') + ')')
  244. }
  245. on Error(e) { console.log('error absorbed: ' + e.message) }

Branches

Latest commits

  • dcc5eecaMerge branch 't14-search'mre
  • 03edc783Merge branch 't15-tvmaze'mre
  • 71b46345tracker#15: numbering check by date or title, placeholder titles in other languages, docs + real-data proofmre
  • 6bb2daf1tracker#13: homepage (tiles, intro, latest movies/shows), /shows, /movies/page/N, /my/movies; lists cached in memorymre
  • b8bd1157tracker#14: README + STATUS (search, real-data numbers, gate, merge notes)mre
  • 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
  • 34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre
  • cbdc4ea7tracker#12: link icons TMDB/IMDb/TVDB/TVmaze; sync fills missing ids (TVmaze lookup); movies fetched via /movie/mre
  • b105bcd8tracker#11: Hybriel master ff51cf46 (checks no longer vanish), mobile-first styles, carets, follow button, sign-in modal, inverted check, orange castmre
  • 31b758aatracker#10: installable app (manifest, service worker, offline shell), own icon + faviconmre
  • 2fa9d997tracker#9: TMDB sync (followed shows: seasons, episodes, posters), tools/sync-tmdb.hl + daily run 04:00 UTC, fake TMDB in gatemre
  • 49e1f61edeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 54070a4etracker#8: /my/unwatched + /my/schedule (301 from old), S01E01, title (year), 1 episode, watched-set lookup (unwatched 15s -> 1s)mre
  • 3251488atracker#7: /my/shows (followed shows, newest follow first, poster, title, last watched SxxEyy); gate can take screenshots (TRACKER_GATE_SHOTS)mre
  • 44b7d9f9tracker#6: /schedule — upcoming episodes of followed shows, soonest firstmre
  • 91c9fc8ctracker#5: /unwatched — unwatched released episodes of followed shows, newest firstmre
  • a97c0295tracker#4: show page /shows/:slug (header, seasons, episodes, watch checks) + tools/relink-episode-seasons.hlmre
  • 05f407c5tracker: no border on any button except inverted ones (Log out, ident status and identities too); header brand weight 100mre
  • 17375427tracker#2: tools/migrate.hl + tools/verify.hl — old MongoDB data into mpackdb with new idsmre
  • 31aac936tracker#3: no border on the header and on filled buttons; inverted buttons keep theirsmre