gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb8bd1157b8bd1157tracker#14: README + STATUS (search, real-data numbers, gate, merge notes)mreb8bd1157/project.hl

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

Branches

Latest commits

  • 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
  • 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