gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit34f2c15b34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre34f2c15b/project.hl

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

Branches

Latest commits

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