-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathwebPush.js
More file actions
606 lines (540 loc) · 20.7 KB
/
webPush.js
File metadata and controls
606 lines (540 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import webPush from 'web-push'
import removeMd from 'remove-markdown'
import { COMMENT_DEPTH_LIMIT, FOUND_BLURBS, LOST_BLURBS, DEFAULT_POSTS_SATS_FILTER, DEFAULT_COMMENTS_SATS_FILTER } from './constants'
import { msatsToSats, numWithUnits } from './format'
import { nextBillingWithGrace } from '@/lib/territory'
import models from '@/api/models'
import { isMuted } from '@/lib/user'
import { Prisma } from '@prisma/client'
// Check if an item meets a user's sat filter threshold for push notifications
async function meetsUserSatFilter (userId, item) {
const user = await models.user.findUnique({
where: { id: userId },
select: { postsSatsFilter: true, commentsSatsFilter: true }
})
const isPost = !!item.title
const filter = user
? (isPost ? user.postsSatsFilter : user.commentsSatsFilter)
: (isPost ? DEFAULT_POSTS_SATS_FILTER : DEFAULT_COMMENTS_SATS_FILTER)
// null means "show all" — item always passes
if (filter == null) return true
return item.netInvestment >= filter
}
// Batch version of meetsUserSatFilter: fetches all users' sat filter
// preferences in a single query instead of N individual findUnique calls.
// Returns a Set of user IDs that meet the sat filter threshold for the item.
async function getUsersPassingSatFilter (userIds, item) {
if (!userIds.length) return new Set()
const isPost = !!item.title
const defaultFilter = isPost ? DEFAULT_POSTS_SATS_FILTER : DEFAULT_COMMENTS_SATS_FILTER
const users = await models.user.findMany({
where: { id: { in: userIds } },
select: { id: true, postsSatsFilter: true, commentsSatsFilter: true }
})
const userMap = new Map(users.map(u => [u.id, u]))
return new Set(
userIds.filter(id => {
const user = userMap.get(id)
const filter = user
? (isPost ? user.postsSatsFilter : user.commentsSatsFilter)
: defaultFilter
// null means "show all" — item always passes
if (filter == null) return true
return item.netInvestment >= filter
})
)
}
const webPushEnabled = process.env.NODE_ENV === 'production' ||
(process.env.VAPID_MAILTO && process.env.NEXT_PUBLIC_VAPID_PUBKEY && process.env.VAPID_PRIVKEY)
function log (...args) {
console.log('[webPush]', ...args)
}
function createPayload (notification) {
// https://web.dev/push-notifications-display-a-notification/#visual-options
// https://webkit.org/blog/16535/meet-declarative-web-push/
// DEV: localhost in URLs is not supported by declarative web push
let { title, body, ...options } = notification
if (body) body = removeMd(body)
return JSON.stringify({
web_push: 8030, // Declarative Web Push JSON format
notification: {
title,
body,
timestamp: Date.now(),
icon: process.env.NEXT_PUBLIC_URL + '/icons/icon_x96.png',
navigate: process.env.NEXT_PUBLIC_URL + '/notifications', // navigate is required
app_badge: 1, // TODO: establish a proper badge count system
...options
}
})
}
function userFilterFragment (setting) {
return setting ? { user: { [setting]: true } } : undefined
}
async function createItemUrl (id) {
const [rootItem] = await models.$queryRawUnsafe(
'SELECT subpath(path, -LEAST(nlevel(path), $1::INTEGER), 1)::text AS id FROM "Item" WHERE id = $2::INTEGER',
COMMENT_DEPTH_LIMIT + 1, Number(id)
)
return `/items/${rootItem.id}` + (rootItem.id !== id ? `?commentId=${id}` : '')
}
async function sendNotification (subscription, payload) {
if (!webPushEnabled) {
log('webPush not configured, skipping notification')
return
}
const { id, endpoint, p256dh, auth } = subscription
return await webPush.sendNotification(
{
endpoint,
keys: { p256dh, auth }
},
payload,
{
vapidDetails: {
subject: process.env.VAPID_MAILTO,
publicKey: process.env.NEXT_PUBLIC_VAPID_PUBKEY,
privateKey: process.env.VAPID_PRIVKEY
},
// conformant to declarative web push spec
headers: {
'Content-Type': 'application/notification+json'
}
})
.catch(async (err) => {
switch (err.statusCode) {
case 400:
log('invalid request:', err)
break
case 401:
case 403:
log('auth error:', err)
break
case 404:
case 410: {
log('subscription expired or no longer valid:', err)
const deletedSubscripton = await models.pushSubscription.delete({ where: { id } })
log(`deleted subscription ${id} of user ${deletedSubscripton.userId} due to push error`)
break
}
case 413:
log('payload too large:', err)
break
case 429:
log('too many requests:', err)
break
default:
log('error:', err)
}
})
}
async function sendUserNotification (userId, notification) {
try {
if (!userId) {
throw new Error('user id is required')
}
notification.data ??= {}
if (notification.itemId) {
// legacy Push API notificationclick event needs data.url as the navigate key is consumed by the browser
notification.data.url ??= await createItemUrl(notification.itemId)
// Declarative Web Push can't use relative paths
notification.navigate ??= process.env.NEXT_PUBLIC_URL + notification.data.url
delete notification.itemId
}
const filterFragment = userFilterFragment(notification.setting)
const payload = createPayload(notification)
const subscriptions = await models.pushSubscription.findMany({
where: { userId, ...filterFragment }
})
await Promise.allSettled(
subscriptions.map(subscription => sendNotification(subscription, payload))
)
} catch (err) {
log('error sending user notification:', err)
}
}
export async function sendPushSubscriptionReply (subscription) {
try {
const payload = createPayload({ title: 'Stacker News notifications are now active' })
await sendNotification(subscription, payload)
} catch (err) {
log('error sending subscription reply:', err)
}
}
export async function notifyUserSubscribers ({ models, item }) {
try {
const isPost = !!item.title
const userSubsExcludingMutes = await models.$queryRaw`
SELECT "UserSubscription"."followerId", "UserSubscription"."followeeId", users.name as "followeeName"
FROM "UserSubscription"
INNER JOIN users ON users.id = "UserSubscription"."followeeId"
WHERE "followeeId" = ${Number(item.userId)}::INTEGER
AND ${isPost ? Prisma.sql`"postsSubscribedAt"` : Prisma.sql`"commentsSubscribedAt"`} IS NOT NULL
-- ignore muted users
AND NOT EXISTS (
SELECT 1
FROM "Mute"
WHERE "Mute"."muterId" = "UserSubscription"."followerId"
AND "Mute"."mutedId" = ${Number(item.userId)}::INTEGER)
-- ignore subscription if user was already notified of item as a reply
AND NOT EXISTS (
SELECT 1 FROM "Reply"
INNER JOIN users follower ON follower.id = "UserSubscription"."followerId"
WHERE "Reply"."itemId" = ${Number(item.id)}::INTEGER
AND "Reply"."ancestorUserId" = follower.id
AND follower."noteAllDescendants"
)
-- ignore subscription if user has posted to a territory the recipient is subscribed to
${isPost
? Prisma.sql`AND NOT EXISTS (
SELECT 1
FROM "SubSubscription"
WHERE "SubSubscription"."userId" = "UserSubscription"."followerId"
AND "SubSubscription"."subName" = ANY(${item.subNames})
)`
: Prisma.empty}`
// Batch-fetch sat filter preferences in a single query instead of per-user
const passingUserIds = await getUsersPassingSatFilter(
userSubsExcludingMutes.map(sub => sub.followerId),
item
)
await Promise.allSettled(
userSubsExcludingMutes
.filter(({ followerId }) => passingUserIds.has(followerId))
.map(({ followerId, followeeName }) => sendUserNotification(followerId, {
title: `@${followeeName} ${isPost ? 'created a post' : 'replied to a post'}`,
body: isPost ? item.title : item.text,
itemId: item.id
}))
)
} catch (err) {
log('error sending user notification:', err)
}
}
export async function notifyTerritorySubscribers ({ models, item }) {
try {
const isPost = !!item.title
const { subNames } = item
// only notify on posts in subs
if (!isPost || !subNames?.length) return
const territorySubsExcludingMuted = await models.$queryRaw`
SELECT "userId", "subName"
FROM "SubSubscription"
WHERE "subName" = ANY(${subNames})
AND NOT EXISTS (
SELECT 1
FROM "Mute" m
WHERE m."muterId" = "SubSubscription"."userId"
AND m."mutedId" = ${Number(item.userId)}::INTEGER
)`
const author = await models.user.findUnique({ where: { id: item.userId } })
const subsExcludingAuthor = territorySubsExcludingMuted
.filter(({ userId }) => userId !== author.id)
// Batch-fetch sat filter preferences in a single query instead of per-user
const passingUserIds = await getUsersPassingSatFilter(
subsExcludingAuthor.map(sub => sub.userId),
item
)
await Promise.allSettled(
subsExcludingAuthor
.filter(({ userId }) => passingUserIds.has(userId))
.map(({ userId, subName }) =>
sendUserNotification(userId, {
title: `@${author.name} created a post in ~${subName}`,
body: item.title,
itemId: item.id
}))
)
} catch (err) {
log('error sending territory notification:', err)
}
}
export async function notifyThreadSubscribers ({ models, item }) {
try {
const author = await models.user.findUnique({ where: { id: item.userId } })
const subscribers = await models.$queryRaw`
SELECT DISTINCT "ThreadSubscription"."userId" FROM "ThreadSubscription"
JOIN users ON users.id = "ThreadSubscription"."userId"
JOIN "Reply" r ON "ThreadSubscription"."itemId" = r."ancestorId"
WHERE r."itemId" = ${item.id}
-- don't send notifications for own items
AND r."userId" <> "ThreadSubscription"."userId"
-- send notifications for all levels?
AND CASE WHEN users."noteAllDescendants" THEN TRUE ELSE r.level = 1 END
-- muted?
AND NOT EXISTS (SELECT 1 FROM "Mute" m WHERE m."muterId" = users.id AND m."mutedId" = r."userId")
-- already received notification as reply to self?
AND NOT EXISTS (
SELECT 1 FROM "Item" i
JOIN "Item" p ON p.path @> i.path
WHERE i.id = ${item.parentId} AND p."userId" = "ThreadSubscription"."userId" AND users."noteAllDescendants"
)`
// Batch-fetch sat filter preferences in a single query instead of per-user
const passingUserIds = await getUsersPassingSatFilter(
subscribers.map(sub => sub.userId),
item
)
await Promise.allSettled(
subscribers
.filter(({ userId }) => passingUserIds.has(userId))
.map(({ userId }) =>
sendUserNotification(userId, {
title: `@${author.name} replied to a post`,
body: item.text,
itemId: item.id
})
)
)
} catch (err) {
log('error sending thread notification:', err)
}
}
export async function notifyItemParents ({ models, item }) {
try {
const user = await models.user.findUnique({ where: { id: item.userId } })
const parents = await models.$queryRaw`
SELECT DISTINCT p."userId", i."userId" = p."userId" as "isDirect"
FROM "Item" i
JOIN "Item" p ON p.path @> i.path
WHERE i.id = ${Number(item.parentId)} and p."userId" <> ${Number(user.id)}
AND NOT EXISTS (
SELECT 1 FROM "Mute" m
WHERE m."muterId" = p."userId" AND m."mutedId" = ${Number(user.id)}
)
AND EXISTS (
-- check that there is at least one parent subscribed to this thread
SELECT 1 FROM "ThreadSubscription" ts WHERE p.id = ts."itemId" AND p."userId" = ts."userId"
)`
// Batch-fetch sat filter preferences in a single query instead of per-user
const passingUserIds = await getUsersPassingSatFilter(
parents.map(parent => parent.userId),
item
)
await Promise.allSettled(
parents
.filter(({ userId }) => passingUserIds.has(userId))
.map(({ userId, isDirect }) => {
return sendUserNotification(userId, {
title: `@${user.name} replied to you`,
body: item.text,
itemId: item.id,
setting: isDirect ? undefined : 'noteAllDescendants'
})
})
)
} catch (err) {
log('error sending item parents notification:', err)
}
}
export async function notifyZapped ({ models, item }) {
try {
const forwards = await models.itemForward.findMany({ where: { itemId: item.id } })
const userPromises = forwards.map(fwd => models.user.findUnique({ where: { id: fwd.userId } }))
const userResults = await Promise.allSettled(userPromises)
const mappedForwards = forwards.map((fwd, index) => ({ ...fwd, user: userResults[index].value ?? null }))
let forwardedSats = 0
let forwardedUsers = ''
if (mappedForwards.length) {
forwardedSats = Math.floor(msatsToSats(item.msats) * mappedForwards.map(fwd => fwd.pct).reduce((sum, cur) => sum + cur) / 100)
forwardedUsers = mappedForwards.map(fwd => `@${fwd.user.name}`).join(', ')
}
let title
if (item.title) {
if (forwards.length > 0) {
title = `your post forwarded ${numWithUnits(forwardedSats)} to ${forwardedUsers}`
} else {
title = `your post stacked ${numWithUnits(msatsToSats(item.msats))}`
}
} else {
if (forwards.length > 0) {
// I don't think this case is possible
title = `your reply forwarded ${numWithUnits(forwardedSats)} to ${forwardedUsers}`
} else {
title = `your reply stacked ${numWithUnits(msatsToSats(item.msats))}`
}
}
await sendUserNotification(item.userId, {
title,
body: item.title ? item.title : item.text,
itemId: item.id,
setting: 'noteItemSats',
tag: `TIP-${item.id}`
})
// send push notifications to forwarded recipients
if (mappedForwards.length) {
await Promise.allSettled(mappedForwards.map(forward => sendUserNotification(forward.user.id, {
title: `you were forwarded ${numWithUnits(Math.round(msatsToSats(item.msats) * forward.pct / 100))}`,
body: item.title ?? item.text,
itemId: item.id,
setting: 'noteForwardedSats',
tag: `FORWARDEDTIP-${item.id}`
})))
}
} catch (err) {
log('error sending zapped notification:', err)
}
}
export async function notifyBountyPaid ({ models, item, payIn }) {
try {
const payOutMsats = payIn.payOutBolt11?.msats ??
(await models.payOutBolt11.findUnique({
where: { payInId: payIn.id },
select: { msats: true }
}))?.msats
if (payOutMsats === null || payOutMsats === undefined) {
throw new Error(`missing bounty payout amount for payIn ${payIn.id}`)
}
const sats = msatsToSats(payOutMsats)
const title = `you received a ${numWithUnits(sats)} bounty payment`
await sendUserNotification(item.userId, {
title,
body: item.title ?? item.text,
itemId: item.id,
setting: 'noteItemSats',
tag: `BOUNTY-${item.id}`
})
} catch (err) {
log('error sending bounty paid notification:', err)
}
}
export async function notifyMention ({ models, userId, item }) {
try {
const muted = await isMuted({ models, muterId: userId, mutedId: item.userId })
if (muted) return
// Check if item meets user's sat filter
if (!await meetsUserSatFilter(userId, item)) return
await sendUserNotification(userId, {
title: `@${item.user.name} mentioned you`,
body: item.text,
itemId: item.id,
setting: 'noteMentions'
})
} catch (err) {
log('error sending mention notification:', err)
}
}
export async function notifyItemMention ({ models, referrerItem, refereeItem }) {
try {
const muted = await isMuted({ models, muterId: refereeItem.userId, mutedId: referrerItem.userId })
if (muted) return
// Check if referrer item meets user's sat filter
if (!await meetsUserSatFilter(refereeItem.userId, referrerItem)) return
const referrer = await models.user.findUnique({ where: { id: referrerItem.userId } })
// replace full links to #<id> syntax as rendered on site
const body = referrerItem.text.replace(new RegExp(`${process.env.NEXT_PUBLIC_URL}/items/(\\d+)`, 'gi'), '#$1')
await sendUserNotification(refereeItem.userId, {
title: `@${referrer.name} mentioned one of your items`,
body,
itemId: referrerItem.id,
setting: 'noteItemMentions'
})
} catch (err) {
log('error sending item mention notification:', err)
}
}
export async function notifyReferral (userId) {
try {
await sendUserNotification(userId, { title: 'someone joined via one of your referral links', tag: 'REFERRAL' })
} catch (err) {
log('error sending referral notification:', err)
}
}
export async function notifyInvite (userId) {
try {
await sendUserNotification(userId, { title: 'your invite has been redeemed', tag: 'INVITE' })
} catch (err) {
log('error sending invite notification:', err)
}
}
export async function notifyTerritoryTransfer ({ models, sub, to }) {
try {
await sendUserNotification(to.id, { title: `~${sub.name} was transferred to you` })
} catch (err) {
log('error sending territory transfer notification:', err)
}
}
export const notifyTerritoryStatusChange = async ({ sub }) => {
const dueDate = nextBillingWithGrace(sub)
const days = Math.ceil((new Date(dueDate) - new Date()) / (1000 * 60 * 60 * 24))
const timeLeft = days === 1 ? 'tomorrow' : `in ${days} days`
const title = sub.status === 'ACTIVE'
? `~${sub.name} is active again`
: sub.status === 'GRACE'
? `~${sub.name}'s payment is due or it will be archived ${timeLeft}`
: `~${sub.name} has been archived`
try {
await sendUserNotification(sub.userId, { title, tag: `TERRITORY_STATUS-${sub.name}` })
} catch (err) {
console.error(err)
}
}
export async function notifyEarner (userId, earnings) {
const fmt = msats => numWithUnits(msatsToSats(msats, { abbreviate: false }))
const title = `you stacked ${fmt(earnings.msats)} in rewards`
let body = ''
if (earnings.POST) body += `#${earnings.POST.bestRank} among posts with ${fmt(earnings.POST.msats)} in total\n`
if (earnings.COMMENT) body += `#${earnings.COMMENT.bestRank} among comments with ${fmt(earnings.COMMENT.msats)} in total\n`
if (earnings.TIP_POST) body += `#${earnings.TIP_POST.bestRank} in post zapping with ${fmt(earnings.TIP_POST.msats)} in total\n`
if (earnings.TIP_COMMENT) body += `#${earnings.TIP_COMMENT.bestRank} in comment zapping with ${fmt(earnings.TIP_COMMENT.msats)} in total`
try {
await sendUserNotification(userId, { title, body, setting: 'noteEarning' })
} catch (err) {
log('error sending earn notification:', err)
}
}
export async function notifyDeposit (userId, invoice) {
try {
await sendUserNotification(userId, {
title: `${numWithUnits(msatsToSats(invoice.msatsReceived), { abbreviate: false, unitSingular: 'sat was', unitPlural: 'sats were' })} deposited in your account`,
body: invoice.comment || undefined,
setting: 'noteDeposits'
})
} catch (err) {
log('error sending deposit notification:', err)
}
}
export async function notifyWithdrawal (payOutBolt11) {
try {
if (payOutBolt11.msats > 1000) {
await sendUserNotification(payOutBolt11.userId, {
title: `${numWithUnits(msatsToSats(payOutBolt11.msats), { abbreviate: false, unitSingular: 'sat was', unitPlural: 'sats were' })} withdrawn from your account`,
setting: 'noteWithdrawals'
})
}
} catch (err) {
log('error sending withdrawal notification:', err)
}
}
export async function notifyNewStreak (userId, streak) {
const index = streak.id % FOUND_BLURBS[streak.type].length
const blurb = FOUND_BLURBS[streak.type][index]
try {
await sendUserNotification(userId, {
title: `you found a ${streak.type.toLowerCase().replace('_', ' ')}`,
body: blurb,
setting: 'noteCowboyHat'
})
} catch (err) {
log('error sending streak found notification:', err)
}
}
export async function notifyStreakLost (userId, streak) {
const index = streak.id % LOST_BLURBS[streak.type].length
const blurb = LOST_BLURBS[streak.type][index]
try {
await sendUserNotification(userId, {
title: `you lost your ${streak.type.toLowerCase().replace('_', ' ')}`,
body: blurb,
setting: 'noteCowboyHat'
})
} catch (err) {
log('error sending streak lost notification:', err)
}
}
export async function notifyReminder ({ userId, item }) {
await sendUserNotification(userId, {
title: 'you requested this reminder',
body: item.title ?? item.text,
itemId: item.id
})
}