gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitacb957cfacb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mreacb957cf/lib/push.hl

9.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`, the same code as the page). `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, missed } from '../components/month-view/reminders.hl'
  24. static pushTable = new MPackDB(file = storageDir + '/push.db', primaryKey = '@id', indexes = ['!endpoint', 'owner'])
  25. static maxPerUser = 10
  26. static lateMs = toNumber(envOr('CALENDAR_PUSH_LATE', '900')) * 1000
  27. // http endpoints only for the gates' fake push service; a browser's push service is always https
  28. static allowHttp = envOr('CALENDAR_PUSH_ALLOW_HTTP', '') == '1'
  29. static isB64Url = (s, min, max) => {
  30. if (s == null || hlTypeName(s) != 'String' || s.length < min || s.length > max) { return false }
  31. let i = 0
  32. while (i < s.length) {
  33. let c = s.charCodeAt(i)
  34. if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95)) { return false }
  35. i = i + 1
  36. }
  37. return true
  38. }
  39. // the page's subscription ({ endpoint, keys = { p256dh, auth } }) and its zone → stored for the user (one row per endpoint:
  40. // a device that signs in as someone else takes it over). Answers { ok } or { error }.
  41. static savePush = (userId, sub, zone) => {
  42. if (sub == null || hlTypeName(sub) != 'Hybrid' || sub.keys == null || hlTypeName(sub.keys) != 'Hybrid') { return { error = 'no push subscription' } }
  43. e = sub.endpoint
  44. 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' } }
  45. if (!isB64Url(sub.keys.p256dh, 80, 100) || !isB64Url(sub.keys.auth, 16, 40)) { return { error = 'the push keys are not base64url' } }
  46. if (zone == null || hlTypeName(zone) != 'String' || !knownZone(zone)) { return { error = 'the time zone is missing' } }
  47. old = firstOf(pushTable.find('endpoint', e))
  48. if (old != null) {
  49. if (old.owner == userId && old.p256dh == sub.keys.p256dh && old.auth == sub.keys.auth && old.zone == zone) { return { ok = true } }
  50. 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 test = old.owner == userId && old.test != null ? old.test : 0 })
  51. return { ok = true }
  52. }
  53. if (countOfList(pushTable.find('owner', userId)) >= maxPerUser) { return { error = 'too many devices with reminders' } }
  54. 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() } }
  55. return { ok = true }
  56. }
  57. // this device stops getting pushes
  58. static dropPush = (userId, endpoint) => {
  59. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  60. if (old != null && old.owner == userId) { pushTable.delete(old.id) }
  61. return { ok = true }
  62. }
  63. // "Send a test notification" (the button on the phone): the device's own row is marked to get ONE test push `testDelayMs` from now
  64. // (long enough to leave the app: it must arrive like a reminder, with the calendar closed). Only the owner's own device.
  65. static testDelayMs = toNumber(envOr('CALENDAR_PUSH_TEST_DELAY', '10')) * 1000
  66. static testPush = (userId, endpoint) => {
  67. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  68. if (old == null || old.owner != userId) { return { error = 'this device is not subscribed: turn the notifications on first' } }
  69. pushTable.update(old.id, { owner = old.owner endpoint = old.endpoint p256dh = old.p256dh auth = old.auth zone = old.zone since = old.since created = old.created test = now() + testDelayMs })
  70. return { ok = true }
  71. }
  72. static hasPush = (userId, endpoint) => {
  73. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  74. return old != null && old.owner == userId
  75. }
  76. // the date of an instant in a zone, 'YYYY-MM-DD'
  77. static dateIn = (ms, zone) => {
  78. l = local(ms, zone)
  79. return l.year + '-' + pad(l.month) + '-' + pad(l.day)
  80. }
  81. // the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"
  82. static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }
  83. // one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.
  84. static roundOf = (s, nowMs, byOwner) => {
  85. if (byOwner[s.owner] == null) {
  86. t = dateIn(nowMs, 'UTC')
  87. byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))
  88. }
  89. events = []
  90. let i = 0
  91. while (i < byOwner[s.owner].length) {
  92. let v = byOwner[s.owner][i]
  93. 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 })
  94. i = i + 1
  95. }
  96. sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.since
  97. due = missed(events, sinceMs, nowMs, dateIn(nowMs, s.zone), s.zone)
  98. sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }
  99. let allSent = true
  100. i = 0
  101. while (i < due.length) {
  102. let q = due[i]
  103. let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000
  104. if (ttl > 86400) { ttl = 86400 }
  105. if (ttl < 60) { ttl = 60 }
  106. 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' })
  107. if (r.gone) {
  108. pushTable.delete(s.id)
  109. return null
  110. }
  111. if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }
  112. else { console.log('push sent (' + r.status + ') for ' + q.key) }
  113. i = i + 1
  114. }
  115. return allSent ? nowMs : s.since
  116. }
  117. static round = () => {
  118. nowMs = now()
  119. subs = pushTable.find(null, null)
  120. byOwner = {}
  121. let i = 0
  122. while (i < subs.length) {
  123. let s = subs[i]
  124. let next = roundOf(s, nowMs, byOwner)
  125. if (next != null && next != s.since) {
  126. pushTable.update(s.id, { owner = s.owner endpoint = s.endpoint p256dh = s.p256dh auth = s.auth zone = s.zone since = next created = s.created test = s.test != null ? s.test : 0 })
  127. }
  128. i = i + 1
  129. }
  130. }
  131. // the test pushes that came due: what the phone will show is the title "Calendar test" and the body "Push works on this device"
  132. static testRound = () => {
  133. nowMs = now()
  134. subs = pushTable.find(null, null)
  135. let i = 0
  136. while (i < subs.length) {
  137. let s = subs[i]
  138. if (s.test != null && s.test > 0 && s.test <= nowMs) {
  139. pushTable.update(s.id, { owner = s.owner endpoint = s.endpoint p256dh = s.p256dh auth = s.auth zone = s.zone since = s.since created = s.created test = 0 })
  140. r = sendPush({ endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }, JSON.stringify({ title = 'Calendar test' body = 'Push works on this device' url = '/' tag = 'calendar-test' icon = '/icons/icon-192.png' }), { ttl = 120 urgency = 'high' })
  141. if (r.gone) { pushTable.delete(s.id) console.log('push test: the subscription is gone (' + r.status + ')') }
  142. else if (!r.ok) { console.log('push test not sent (' + r.status + '): ' + r.error) }
  143. else { console.log('push test sent (' + r.status + ')') }
  144. }
  145. i = i + 1
  146. }
  147. }
  148. // THE CLOCK: project.hl constructs this file once (`push = new Push()`)
  149. static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))
  150. on ticker.tick(t) { round() }
  151. static testTicker = every(2)
  152. on testTicker.tick(t) { testRound() }

Branches

Latest commits

  • acb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mre
  • 0b222eb8tests: e2e-theme CDP port default from E2E_THEME_CDP_PORT (8756 unchanged)mre
  • 8b8a5abare-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • a69b27f9docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 1a97edfdcalendar mission 010: reminder rows at 390 px (the 7-column month grid no longer catches the reminder lists), gate checks, settings-shots, reportmre
  • 61b21404calendar mission 009: reminder times on hl:time in the browser (lib/push-plan.hl and the Intl code removed), DST gate tests/dst.mjs, E2E script, reportmre
  • 875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre
  • ce16a4efdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • f490bc8cdeploy: Web Push gate tests/push.mjs (PUSH_GATE_PORT)mre
  • 3af29fc8calendar mission 008 (A8): report, README, LOG, push-shots.mjsmre
  • f91f3663calendar mission 008 (A8): push only asked of the browser when the app has the VAPID settings (pushAvailable); real-FCM E2E scripts (push-real-app.mjs, push-real.mjs)mre
  • bf571badcalendar mission 008 (A8): Turn off on this device (unsubscribes the browser, server drops the device, choice kept), subscribe/refresh when the app is shown again; push gate part 3mre
  • 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