gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5098570850985708calendar mission 008 (A7): Web Push report, README, mission, LOGmre50985708/lib/push.hl

7.2 KB

  1. // lib/push.hl — WEB PUSH: reminders that reach the phone while the calendar page is closed (ticket calendar#9, part 2).
  2. // The page hands over its push subscription (face calPushSave); the server's clock (below) sends every reminder that came due
  3. // to every subscribed device of the event's owner (hl:web `sendPush`: VAPID + aes128gcm); the service worker shows it.
  4. // One table, storage/mpackdb/push.db, pk @id, unique index endpoint, index owner:
  5. // { owner (users @id), endpoint, p256dh, auth (base64url, as the browser gave them), zone (the device's IANA zone: it
  6. // reads the days of all-day events), since (epoch ms: the reminders up to here were sent or are not wanted),
  7. // created }
  8. // THE CLOCK (CALENDAR_PUSH_EVERY seconds, default 30; the gates 0.5): per subscription the reminders with since < time <= now
  9. // for events that have not started yet, one per event (the newest) — the same rule as the page's own missed reminders
  10. // (reminders.hl `missed`; lib/push-plan.hl is its server copy). `since` moves up only when every send of the round was accepted or the subscription is gone, so a
  11. // push service that answers 5xx is tried again next round; at most 15 minutes late (CALENDAR_PUSH_LATE), then it is dropped.
  12. // 404 / 410 → the subscription is deleted. The notification's `tag` is the page's own (event:time): a device whose page
  13. // is open and shows the same reminder through its timer shows ONE notification (same tag replaces).
  14. // Settings (environment / .env, like every setting of the calendar; README "Web Push"): CALENDAR_PUSH_PUBLIC (VAPID public key,
  15. // base64url), CALENDAR_PUSH_PRIVATE (the 32-byte scalar, base64url), CALENDAR_PUSH_SUBJECT ('mailto:…' or 'https://…').
  16. // Without all three there is no push: the page works as before and the button only asks for the browser's permission.
  17. import { MPackDB } from 'hl:mpackdb'
  18. import { sendPush } from 'hl:web'
  19. import { now, every, local, isZone as knownZone } from 'hl:time'
  20. import { envOr, storageDir, firstOf, countOfList } from './util.hl'
  21. import { upcoming } from './events.hl'
  22. import { pad } from '../components/month-view/dates.hl'
  23. import { shift } from '../components/month-view/reminders.hl'
  24. import { dueNow } from './push-plan.hl'
  25. static pushTable = new MPackDB(file = storageDir + '/push.db', primaryKey = '@id', indexes = ['!endpoint', 'owner'])
  26. static maxPerUser = 10
  27. static lateMs = toNumber(envOr('CALENDAR_PUSH_LATE', '900')) * 1000
  28. // http endpoints only for the gates' fake push service; a browser's push service is always https
  29. static allowHttp = envOr('CALENDAR_PUSH_ALLOW_HTTP', '') == '1'
  30. static isB64Url = (s, min, max) => {
  31. if (s == null || hlTypeName(s) != 'String' || s.length < min || s.length > max) { return false }
  32. let i = 0
  33. while (i < s.length) {
  34. let c = s.charCodeAt(i)
  35. if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95)) { return false }
  36. i = i + 1
  37. }
  38. return true
  39. }
  40. // the page's subscription ({ endpoint, keys = { p256dh, auth } }) and its zone → stored for the user (one row per endpoint:
  41. // a device that signs in as someone else takes it over). Answers { ok } or { error }.
  42. static savePush = (userId, sub, zone) => {
  43. if (sub == null || hlTypeName(sub) != 'Hybrid' || sub.keys == null || hlTypeName(sub.keys) != 'Hybrid') { return { error = 'no push subscription' } }
  44. e = sub.endpoint
  45. if (e == null || hlTypeName(e) != 'String' || e.length > 1000 || !(e.startsWith('https://') || (allowHttp && e.startsWith('http://')))) { return { error = 'the push endpoint is not an https address' } }
  46. if (!isB64Url(sub.keys.p256dh, 80, 100) || !isB64Url(sub.keys.auth, 16, 40)) { return { error = 'the push keys are not base64url' } }
  47. if (zone == null || hlTypeName(zone) != 'String' || !knownZone(zone)) { return { error = 'the time zone is missing' } }
  48. old = firstOf(pushTable.find('endpoint', e))
  49. if (old != null) {
  50. if (old.owner == userId && old.p256dh == sub.keys.p256dh && old.auth == sub.keys.auth && old.zone == zone) { return { ok = true } }
  51. pushTable.update(old.id, { owner = userId endpoint = e p256dh = sub.keys.p256dh auth = sub.keys.auth zone = zone since = old.owner == userId ? old.since : now() created = old.created })
  52. return { ok = true }
  53. }
  54. if (countOfList(pushTable.find('owner', userId)) >= maxPerUser) { return { error = 'too many devices with reminders' } }
  55. if (pushTable.put({ owner = userId endpoint = e p256dh = sub.keys.p256dh auth = sub.keys.auth zone = zone since = now() created = now() }) == null) { return { error = 'could not store the push subscription: ' + pushTable.lastError() } }
  56. return { ok = true }
  57. }
  58. // this device stops getting pushes
  59. static dropPush = (userId, endpoint) => {
  60. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  61. if (old != null && old.owner == userId) { pushTable.delete(old.id) }
  62. return { ok = true }
  63. }
  64. static hasPush = (userId, endpoint) => {
  65. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  66. return old != null && old.owner == userId
  67. }
  68. // the date of an instant in a zone, 'YYYY-MM-DD'
  69. static dateIn = (ms, zone) => {
  70. l = local(ms, zone)
  71. return l.year + '-' + pad(l.month) + '-' + pad(l.day)
  72. }
  73. // the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"
  74. static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }
  75. // one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.
  76. static roundOf = (s, nowMs, byOwner) => {
  77. if (byOwner[s.owner] == null) {
  78. t = dateIn(nowMs, 'UTC')
  79. byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))
  80. }
  81. events = []
  82. let i = 0
  83. while (i < byOwner[s.owner].length) {
  84. let v = byOwner[s.owner][i]
  85. events.push({ id = v.id title = v.title allDay = v.allDay startDate = v.startDate startTime = v.startTime place = v.place zone = v.zone rows = v.rows })
  86. i = i + 1
  87. }
  88. sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.since
  89. due = dueNow(events, sinceMs, nowMs, s.zone, dateIn(nowMs, s.zone))
  90. sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }
  91. let allSent = true
  92. i = 0
  93. while (i < due.length) {
  94. let q = due[i]
  95. let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000
  96. if (ttl > 86400) { ttl = 86400 }
  97. if (ttl < 60) { ttl = 60 }
  98. r = sendPush(sub, JSON.stringify({ title = q.title body = wordsOf(q, nowMs) url = '/' tag = q.key icon = '/icons/icon-192.png' }), { ttl = ttl urgency = 'high' })
  99. if (r.gone) {
  100. pushTable.delete(s.id)
  101. return null
  102. }
  103. if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }
  104. else { console.log('push sent (' + r.status + ') for ' + q.key) }
  105. i = i + 1
  106. }
  107. return allSent ? nowMs : s.since
  108. }
  109. static round = () => {
  110. nowMs = now()
  111. subs = pushTable.find(null, null)
  112. byOwner = {}
  113. let i = 0
  114. while (i < subs.length) {
  115. let s = subs[i]
  116. let next = roundOf(s, nowMs, byOwner)
  117. if (next != null && next != s.since) {
  118. pushTable.update(s.id, { owner = s.owner endpoint = s.endpoint p256dh = s.p256dh auth = s.auth zone = s.zone since = next created = s.created })
  119. }
  120. i = i + 1
  121. }
  122. }
  123. // THE CLOCK: project.hl constructs this file once (`push = new Push()`)
  124. static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))
  125. on ticker.tick(t) { round() }

Branches

Latest commits

  • 50985708calendar mission 008 (A7): Web Push report, README, mission, LOGmre
  • ee318774calendar mission 008 (A7): push-real.mjs, push sent log linemre
  • ebda0fd1calendar mission 008 (A7): server-side reminder plan on hl:time (push-plan.hl; hl:time fromLocal in a browser static is refused: repro .scratch/hltime-client), push gate 9/9mre
  • d063dad3calendar mission 008 (A7): Web Push (WIP): lib/push.hl subscriptions + sender clock, faces calPushSave/calPushOff, button subscribes, VAPID tool, tests/push.mjs; instantOf on hl:timemre
  • cf175c80calendar mission 008 (A7): re-vendor Hybriel master 0e3c9830 (bin 9d957fed, plugins whole: hl:crypto Web Push primitives, hl:web sendPush)mre
  • 9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre
  • 186f969bcalendar mission 007: signed-in gate for the first-pointer race (fails on 3c5604f), README theme section, reportmre
  • ba9b4955calendar mission 006: first pointer event no longer re-runs the month (stale overwrite race), gate check, e2e settings cleanup, reportmre
  • bd730759calendar mission 006: theme move (WIP): brief, report, LOG, STATUSmre
  • b117b153calendar mission 006 WIP: reminder row fields keep 44 px; e2e script flagsmre
  • 53e3b0debrowser gate: Log out through the user menu, theme colour rgb(15, 20, 25)mre
  • 90bf9e2ecalendar mission 006 WIP: theme dbe3de7, theme shell (AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst), styles cut to the app's own rules, check-theme gate, e2e toolsmre
  • 3c5604f9identkit: refuse a taken ident port, cold-start deadline, abort on dead ident, clear no-code error (as notes)mre
  • 4996bbe7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • f5bf0803calendar mission 004: re-vendor Hybriel to the shared static build 0f396652; compose cache volume + tmpfs; notify-paths gate in deploy.sh; gate start waits 150 s; reportmre
  • eb86526fmission brief 004mre
  • 2f953b16deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • 9078e1b7calendar mission 003 (2/2): report, LOG, STATUS (cause: timers only in an open, front, touched page; gate old 5/2 new 7/0; Hybriel gaps Web Push + page-shown hook, STOP)mre
  • 31ffe910calendar mission 003 (1/2): calendar#9 — missed reminders shown when the app is back, timers set again when it is shownmre
  • 26c997d3mission brief 003mre