|
| 1 | +import { SqlDependency } from "gruber"; |
| 2 | +import { useAppConfig, useDatabase, useStore } from "../lib/globals.ts"; |
| 3 | +import { WebPushPayload, WebPushRepo } from "./web-push-repo.ts"; |
| 4 | +import { |
| 5 | + ConferenceTable, |
| 6 | + RegistrationTable, |
| 7 | + SessionSaveTable, |
| 8 | + SessionTable, |
| 9 | + WebPushDeviceTable, |
| 10 | + WebPushMessageTable, |
| 11 | +} from "../lib/tables.ts"; |
| 12 | +import { getConferenceInfo, getSessionUrl } from "../lib/utilities.ts"; |
| 13 | +import { AppConfig } from "../config.ts"; |
| 14 | + |
| 15 | +// |
| 16 | +// A context to run various sub-commands with containing relevant dependencies & helpers |
| 17 | +// |
| 18 | +class NotifyContext { |
| 19 | + options: NotifyOptions; |
| 20 | + webPush: WebPushRepo; |
| 21 | + sql: SqlDependency; |
| 22 | + appConfig: AppConfig; |
| 23 | + constructor( |
| 24 | + options: NotifyOptions, |
| 25 | + webPush: WebPushRepo, |
| 26 | + sql: SqlDependency, |
| 27 | + appConfig: AppConfig, |
| 28 | + ) { |
| 29 | + this.options = options; |
| 30 | + this.webPush = webPush; |
| 31 | + this.sql = sql; |
| 32 | + this.appConfig = appConfig; |
| 33 | + } |
| 34 | + |
| 35 | + /** Log a timestamped message */ |
| 36 | + log(message: string, ...args: any[]) { |
| 37 | + console.error(new Date().toISOString() + " " + message, ...args); |
| 38 | + } |
| 39 | + |
| 40 | + /** Wait for a duration to elapse (milliseconds) */ |
| 41 | + pause(ms: number) { |
| 42 | + this.log("pause ms=%o", ms); |
| 43 | + return new Promise((r) => setTimeout(r, ms)); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export interface NotifyOptions { |
| 48 | + dryRun: boolean; |
| 49 | + forever: boolean; |
| 50 | + interval: number; |
| 51 | + grace: number; |
| 52 | +} |
| 53 | + |
| 54 | +export async function notifyCommand(options: NotifyOptions) { |
| 55 | + // Set up context |
| 56 | + const appConfig = useAppConfig(); |
| 57 | + const store = useStore(); |
| 58 | + const sql = useDatabase(); |
| 59 | + const webPush = WebPushRepo.use(); |
| 60 | + const ctx = new NotifyContext(options, webPush, sql, appConfig); |
| 61 | + |
| 62 | + ctx.log("init"); |
| 63 | + |
| 64 | + try { |
| 65 | + while (options.forever) { |
| 66 | + ctx.log("starting"); |
| 67 | + |
| 68 | + await enqueueMySchedule(ctx); |
| 69 | + await sendPendingMessages(ctx); |
| 70 | + |
| 71 | + await ctx.pause(options.interval); |
| 72 | + } |
| 73 | + |
| 74 | + ctx.log("done"); |
| 75 | + } catch (error) { |
| 76 | + console.log("Fatal error", error); |
| 77 | + } |
| 78 | + |
| 79 | + await store.close(); |
| 80 | + await sql.end(); |
| 81 | +} |
| 82 | + |
| 83 | +interface PendingMessage { |
| 84 | + deviceId: number; |
| 85 | + saveId: number; |
| 86 | + payload: WebPushPayload; |
| 87 | +} |
| 88 | + |
| 89 | +async function enqueueMySchedule(ctx: NotifyContext, date = new Date()) { |
| 90 | + ctx.log("enqueue from schedule…"); |
| 91 | + |
| 92 | + // Get sessions starting in 15 minutes or started 5 minutes ago |
| 93 | + const upcoming = await SessionTable.select( |
| 94 | + ctx.sql, |
| 95 | + ctx.sql` |
| 96 | + start_date IS NOT NULL |
| 97 | + AND start_date >= ${date} - INTERVAL '15 minutes' |
| 98 | + AND start_date <= ${date} + INTERVAL '5 minutes' |
| 99 | + `, |
| 100 | + ); |
| 101 | + |
| 102 | + // Fetch conferences for those sessions |
| 103 | + const conferences = await ConferenceTable.select( |
| 104 | + ctx.sql, |
| 105 | + ctx.sql` |
| 106 | + id IN ${ctx.sql(upcoming.map((r) => r.conference_id))} |
| 107 | + `, |
| 108 | + ); |
| 109 | + |
| 110 | + // Generate portable information about the conferences |
| 111 | + const info = new Map( |
| 112 | + conferences.map((c) => [c.id, getConferenceInfo(c, ctx.appConfig)]), |
| 113 | + ); |
| 114 | + |
| 115 | + // Get saved sessions who haven't been notified yet |
| 116 | + const saved = await SessionSaveTable.select( |
| 117 | + ctx.sql, |
| 118 | + ctx.sql` |
| 119 | + session_id IN ${ctx.sql(upcoming.map((r) => r.id))} |
| 120 | + AND NOT notified ? 'web-push' |
| 121 | + `, |
| 122 | + ); |
| 123 | + |
| 124 | + // Get devices for people who have saved those sessions |
| 125 | + // which have opted-in to MySchedule messages and are not expired |
| 126 | + const devices = await WebPushDeviceTable.select( |
| 127 | + ctx.sql, |
| 128 | + ctx.sql` |
| 129 | + registration_id IN ${ctx.sql(saved.map((r) => r.registration_id))} |
| 130 | + AND categories ? 'MySchedule' |
| 131 | + AND ( |
| 132 | + expires_at IS NULL |
| 133 | + OR expires_at >= NOW() |
| 134 | + ) |
| 135 | + `, |
| 136 | + ); |
| 137 | + |
| 138 | + ctx.log("saves=%o devices=%o", saved.length, devices.length); |
| 139 | + |
| 140 | + const sessions = new Map(upcoming.map((s) => [s.id, s])); |
| 141 | + |
| 142 | + // Generate a list of messages to enqueu |
| 143 | + const queue: PendingMessage[] = []; |
| 144 | + |
| 145 | + // Loop through each saved session & fetch info |
| 146 | + for (const save of saved) { |
| 147 | + const session = sessions.get(save.session_id)!; |
| 148 | + const conference = info.get(session.conference_id)!; |
| 149 | + const userDevices = devices.filter( |
| 150 | + (r) => r.registration_id === save.registration_id, |
| 151 | + ); |
| 152 | + |
| 153 | + // Loop through each device and generate a message to send |
| 154 | + for (const device of userDevices) { |
| 155 | + queue.push({ |
| 156 | + deviceId: device.id, |
| 157 | + saveId: save.id, |
| 158 | + payload: { |
| 159 | + title: "Session starting soon", |
| 160 | + body: session.title.en!, |
| 161 | + data: { |
| 162 | + url: getSessionUrl(conference.sessionUrl, session.id), |
| 163 | + }, |
| 164 | + }, |
| 165 | + }); |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + // Exit early and dump information during a dry run |
| 170 | + if (ctx.options.dryRun) { |
| 171 | + console.log("Enqueue:"); |
| 172 | + console.log(JSON.stringify(queue)); |
| 173 | + return; |
| 174 | + } |
| 175 | + |
| 176 | + // Process the queue of messages with a transaction for each |
| 177 | + // NOTE: could be one big transaction? |
| 178 | + for (const item of queue) { |
| 179 | + await ctx.sql.begin(async (trx) => { |
| 180 | + ctx.log( |
| 181 | + "enqueue device=%o save=%o title=%o", |
| 182 | + item.deviceId, |
| 183 | + item.saveId, |
| 184 | + item.payload.title, |
| 185 | + ); |
| 186 | + |
| 187 | + // Insert a pending web push message |
| 188 | + await WebPushMessageTable.insertOne(trx, { |
| 189 | + device_id: item.deviceId, |
| 190 | + payload: item.payload, |
| 191 | + }); |
| 192 | + |
| 193 | + // Mark the save as notified |
| 194 | + await trx` |
| 195 | + UPDATE session_saves |
| 196 | + SET notified = notified || '["web-push"]'::jsonb |
| 197 | + WHERE id = ${item.saveId} |
| 198 | + `; |
| 199 | + }); |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +async function sendPendingMessages(ctx: NotifyContext) { |
| 204 | + ctx.log("send pending messages…"); |
| 205 | + |
| 206 | + const { messages, devices } = await ctx.webPush.listPending(); |
| 207 | + |
| 208 | + ctx.log("messages=%o devices=%o", messages.length, devices.size); |
| 209 | + |
| 210 | + if (ctx.options.dryRun) { |
| 211 | + console.log("Pending:"); |
| 212 | + console.log(JSON.stringify({ messages, devices })); |
| 213 | + return; |
| 214 | + } |
| 215 | + |
| 216 | + for (const message of messages) { |
| 217 | + const device = devices.get(message.device_id); |
| 218 | + if (!device) throw new Error("internal error - bad device"); |
| 219 | + |
| 220 | + ctx.log("send message=%o device=%o", message.id, device.id); |
| 221 | + const success = await ctx.webPush.attemptToSend(message, device); |
| 222 | + ctx.log(" success=%o", success); |
| 223 | + |
| 224 | + await ctx.pause(ctx.options.grace); |
| 225 | + } |
| 226 | +} |
0 commit comments