gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2fa9d9972fa9d997tracker#9: TMDB sync (followed shows: seasons, episodes, posters), tools/sync-tmdb.hl + daily run 04:00 UTC, fake TMDB in gatemre2fa9d997/project.hl

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

Branches

Latest commits

  • 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