calendar
All repositories: gitoria
7.2 KB
// lib/push.hl — WEB PUSH: reminders that reach the phone while the calendar page is closed (ticket calendar#9, part 2).// The page hands over its push subscription (face calPushSave); the server's clock (below) sends every reminder that came due// to every subscribed device of the event's owner (hl:web `sendPush`: VAPID + aes128gcm); the service worker shows it.// One table, storage/mpackdb/push.db, pk @id, unique index endpoint, index owner:// { owner (users @id), endpoint, p256dh, auth (base64url, as the browser gave them), zone (the device's IANA zone: it// reads the days of all-day events), since (epoch ms: the reminders up to here were sent or are not wanted),// created }// THE CLOCK (CALENDAR_PUSH_EVERY seconds, default 30; the gates 0.5): per subscription the reminders with since < time <= now// for events that have not started yet, one per event (the newest) — the same rule as the page's own missed reminders// (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// push service that answers 5xx is tried again next round; at most 15 minutes late (CALENDAR_PUSH_LATE), then it is dropped.// 404 / 410 → the subscription is deleted. The notification's `tag` is the page's own (event:time): a device whose page// is open and shows the same reminder through its timer shows ONE notification (same tag replaces).// Settings (environment / .env, like every setting of the calendar; README "Web Push"): CALENDAR_PUSH_PUBLIC (VAPID public key,// base64url), CALENDAR_PUSH_PRIVATE (the 32-byte scalar, base64url), CALENDAR_PUSH_SUBJECT ('mailto:…' or 'https://…').// Without all three there is no push: the page works as before and the button only asks for the browser's permission.import { MPackDB } from 'hl:mpackdb'import { sendPush } from 'hl:web'import { now, every, local, isZone as knownZone } from 'hl:time'import { envOr, storageDir, firstOf, countOfList } from './util.hl'import { upcoming } from './events.hl'import { pad } from '../components/month-view/dates.hl'import { shift } from '../components/month-view/reminders.hl'import { dueNow } from './push-plan.hl'static pushTable = new MPackDB(file = storageDir + '/push.db', primaryKey = '@id', indexes = ['!endpoint', 'owner'])static maxPerUser = 10static lateMs = toNumber(envOr('CALENDAR_PUSH_LATE', '900')) * 1000// http endpoints only for the gates' fake push service; a browser's push service is always httpsstatic allowHttp = envOr('CALENDAR_PUSH_ALLOW_HTTP', '') == '1'static isB64Url = (s, min, max) => {if (s == null || hlTypeName(s) != 'String' || s.length < min || s.length > max) { return false }let i = 0while (i < s.length) {let c = s.charCodeAt(i)if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95)) { return false }i = i + 1}return true}// the page's subscription ({ endpoint, keys = { p256dh, auth } }) and its zone → stored for the user (one row per endpoint:// a device that signs in as someone else takes it over). Answers { ok } or { error }.static savePush = (userId, sub, zone) => {if (sub == null || hlTypeName(sub) != 'Hybrid' || sub.keys == null || hlTypeName(sub.keys) != 'Hybrid') { return { error = 'no push subscription' } }e = sub.endpointif (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' } }if (!isB64Url(sub.keys.p256dh, 80, 100) || !isB64Url(sub.keys.auth, 16, 40)) { return { error = 'the push keys are not base64url' } }if (zone == null || hlTypeName(zone) != 'String' || !knownZone(zone)) { return { error = 'the time zone is missing' } }old = firstOf(pushTable.find('endpoint', e))if (old != null) {if (old.owner == userId && old.p256dh == sub.keys.p256dh && old.auth == sub.keys.auth && old.zone == zone) { return { ok = true } }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 })return { ok = true }}if (countOfList(pushTable.find('owner', userId)) >= maxPerUser) { return { error = 'too many devices with reminders' } }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() } }return { ok = true }}// this device stops getting pushesstatic dropPush = (userId, endpoint) => {old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : nullif (old != null && old.owner == userId) { pushTable.delete(old.id) }return { ok = true }}static hasPush = (userId, endpoint) => {old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : nullreturn old != null && old.owner == userId}// the date of an instant in a zone, 'YYYY-MM-DD'static dateIn = (ms, zone) => {l = local(ms, zone)return l.year + '-' + pad(l.month) + '-' + pad(l.day)}// the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }// one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.static roundOf = (s, nowMs, byOwner) => {if (byOwner[s.owner] == null) {t = dateIn(nowMs, 'UTC')byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))}events = []let i = 0while (i < byOwner[s.owner].length) {let v = byOwner[s.owner][i]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 })i = i + 1}sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.sincedue = dueNow(events, sinceMs, nowMs, s.zone, dateIn(nowMs, s.zone))sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }let allSent = truei = 0while (i < due.length) {let q = due[i]let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000if (ttl > 86400) { ttl = 86400 }if (ttl < 60) { ttl = 60 }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' })if (r.gone) {pushTable.delete(s.id)return null}if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }else { console.log('push sent (' + r.status + ') for ' + q.key) }i = i + 1}return allSent ? nowMs : s.since}static round = () => {nowMs = now()subs = pushTable.find(null, null)byOwner = {}let i = 0while (i < subs.length) {let s = subs[i]let next = roundOf(s, nowMs, byOwner)if (next != null && next != s.since) {pushTable.update(s.id, { owner = s.owner endpoint = s.endpoint p256dh = s.p256dh auth = s.auth zone = s.zone since = next created = s.created })}i = i + 1}}// THE CLOCK: project.hl constructs this file once (`push = new Push()`)static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))on ticker.tick(t) { round() }
Branches
Latest commits
- 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
- 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