gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3a29760a3a29760aC13 report (handoff)mre3a29760a/lib/push.hl

9.6 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 testAt = old.owner == userId && old.testAt != null ? old.testAt : 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. // rate limit: one test per device per 30 s (a test still waiting counts: testAt is set when it is asked for)
  70. if (old.testAt != null && old.testAt > now() - 30000) { return { error = 'a test was just sent: wait 30 seconds' } }
  71. 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 testAt = now() })
  72. return { ok = true }
  73. }
  74. static hasPush = (userId, endpoint) => {
  75. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  76. return old != null && old.owner == userId
  77. }
  78. // the date of an instant in a zone, 'YYYY-MM-DD'
  79. static dateIn = (ms, zone) => {
  80. l = local(ms, zone)
  81. return l.year + '-' + pad(l.month) + '-' + pad(l.day)
  82. }
  83. // the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"
  84. static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }
  85. // one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.
  86. static roundOf = (s, nowMs, byOwner) => {
  87. if (byOwner[s.owner] == null) {
  88. t = dateIn(nowMs, 'UTC')
  89. byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))
  90. }
  91. events = []
  92. let i = 0
  93. while (i < byOwner[s.owner].length) {
  94. let v = byOwner[s.owner][i]
  95. 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 })
  96. i = i + 1
  97. }
  98. sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.since
  99. due = missed(events, sinceMs, nowMs, dateIn(nowMs, s.zone), s.zone)
  100. sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }
  101. let allSent = true
  102. i = 0
  103. while (i < due.length) {
  104. let q = due[i]
  105. let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000
  106. if (ttl > 86400) { ttl = 86400 }
  107. if (ttl < 60) { ttl = 60 }
  108. 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' })
  109. if (r.gone) {
  110. pushTable.delete(s.id)
  111. return null
  112. }
  113. if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }
  114. else { console.log('push sent (' + r.status + ') for ' + q.key) }
  115. i = i + 1
  116. }
  117. return allSent ? nowMs : s.since
  118. }
  119. static round = () => {
  120. nowMs = now()
  121. subs = pushTable.find(null, null)
  122. byOwner = {}
  123. let i = 0
  124. while (i < subs.length) {
  125. let s = subs[i]
  126. let next = roundOf(s, nowMs, byOwner)
  127. if (next != null && next != s.since) {
  128. 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 testAt = s.testAt != null ? s.testAt : 0 })
  129. }
  130. i = i + 1
  131. }
  132. }
  133. // the test pushes that came due: what the phone will show is the title "Calendar test" and the body "Push works on this device"
  134. static testRound = () => {
  135. nowMs = now()
  136. subs = pushTable.find(null, null)
  137. let i = 0
  138. while (i < subs.length) {
  139. let s = subs[i]
  140. if (s.test != null && s.test > 0 && s.test <= nowMs) {
  141. 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 testAt = s.testAt != null ? s.testAt : 0 })
  142. 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' })
  143. if (r.gone) { pushTable.delete(s.id) console.log('push test: the subscription is gone (' + r.status + ')') }
  144. else if (!r.ok) { console.log('push test not sent (' + r.status + '): ' + r.error) }
  145. else { console.log('push test sent (' + r.status + ')') }
  146. }
  147. i = i + 1
  148. }
  149. }
  150. // THE CLOCK: project.hl constructs this file once (`push = new Push()`)
  151. static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))
  152. on ticker.tick(t) { round() }
  153. static testTicker = every(2)
  154. on testTicker.tick(t) { testRound() }

Branches

Latest commits

  • 3a29760aC13 report (handoff)mre
  • 33ab66ffCalendar: notification controls move from the month view into Reminder settings (user menu), one consistent state, state read when the dialog opensmre
  • 682a5b43reports: calendar gate countsmre
  • 876d22b2reports/H1-hydrate.mdmre
  • ef0cae45tests/dst.mjs: wait for hydration instead of a fixed 2.5 s sleep before clicking #gomre
  • d9cadecatests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • efa61227re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • 7808adbecalendar#12: report 011, LOG, STATUS, push-shots-testmre
  • df2e4fa0calendar#12: test push rate limit (1 per 30 s per device), owner-only gate checksmre
  • 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