-
Notifications
You must be signed in to change notification settings - Fork 22
/
useInboxApi.ts
343 lines (301 loc) · 8.49 KB
/
useInboxApi.ts
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
import { fromBase64, toBase64 } from '@cosmjs/encoding'
import { useCallback, useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { useTranslation } from 'react-i18next'
import { useSetRecoilState } from 'recoil'
import { temporaryClearedInboxItemsAtom } from '@dao-dao/state'
import { useServiceWorker } from '@dao-dao/stateless'
import {
InboxApi,
InboxConfig,
InboxUpdateConfig,
PushSubscriptionManager,
} from '@dao-dao/types'
import {
INBOX_API_BASE,
WEB_PUSH_PUBLIC_KEY,
processError,
toBech32Hash,
} from '@dao-dao/utils'
import { useCfWorkerAuthPostRequest } from './useCfWorkerAuthPostRequest'
import { useWallet } from './useWallet'
export const useInboxApi = (): InboxApi => {
const { t } = useTranslation()
const { address = '' } = useWallet()
// Following API doesn't update right away, so this serves to keep track of
// all successful updates for the current session. This will be reset on page
// refresh.
const setTemporary = useSetRecoilState(
temporaryClearedInboxItemsAtom(toBech32Hash(address))
)
const [updating, setUpdating] = useState(false)
const { ready, postRequest } = useCfWorkerAuthPostRequest(
INBOX_API_BASE,
'Inbox'
)
const [config, setConfig] = useState<InboxConfig>()
const serviceWorker = useServiceWorker()
const [pushSubscribed, setPushSubscribed] = useState(false)
const [pushSubscription, setPushSubscription] = useState<PushSubscription>()
const [pushUpdating, setPushUpdating] = useState(true)
// Load push service worker registration and subscription.
useEffect(() => {
if (!serviceWorker.ready) {
return
}
;(async () => {
try {
if (!serviceWorker.registration) {
return
}
const subscription =
await serviceWorker.registration.pushManager.getSubscription()
if (
subscription &&
!(
subscription.expirationTime !== null &&
// If greater than 5 minutes until expiration, assume subscribed.
Date.now() > subscription.expirationTime - 5 * 60 * 1000
)
) {
setPushSubscription(subscription)
setPushSubscribed(true)
}
} catch (err) {
console.error(err)
} finally {
setPushUpdating(false)
}
})()
}, [serviceWorker.ready, serviceWorker.registration])
const clear = useCallback(
async (
items: {
chainId: string
id: string
}[]
) => {
if (!ready) {
toast.error(t('error.logInToContinue'))
return false
}
if (updating) {
return false
}
setUpdating(true)
try {
// Group by chain ID.
const idsToClear = items.reduce(
(acc, { chainId, id }) => ({
...acc,
[chainId]: [...(acc[chainId] ?? []), ...[id].flat()],
}),
{} as Record<string, string[]>
)
for (const [chainId, ids] of Object.entries(idsToClear)) {
await postRequest(
'/clear',
{
ids,
},
'Clear Inbox Items',
chainId
)
}
setTemporary((prev) => [...prev, ...items.flatMap(({ id }) => id)])
return true
} catch (err) {
console.error(err)
toast.error(processError(err))
return false
} finally {
setUpdating(false)
}
},
[postRequest, ready, setTemporary, t, updating]
)
const updateConfig = useCallback(
async (
data: InboxUpdateConfig,
signatureType = 'Save Notification Settings'
) => {
if (!ready) {
toast.error(t('error.logInToContinue'))
return false
}
if (updating || pushUpdating) {
return false
}
setUpdating(true)
try {
const p256dhKey = pushSubscription?.getKey('p256dh')
const p256dh = p256dhKey
? toBase64(new Uint8Array(p256dhKey))
: undefined
const push =
data.push ||
(p256dh
? // If no push provided, just check if subscribed.
{
type: 'check',
p256dh,
}
: undefined)
const config = await postRequest<InboxConfig>(
'/config',
{
...data,
...(push && { push }),
},
signatureType
)
setConfig(config)
return true
} catch (err) {
console.error(err)
toast.error(processError(err))
return false
} finally {
setUpdating(false)
}
},
[postRequest, pushSubscription, pushUpdating, ready, t, updating]
)
const loadConfig = useCallback(
() => updateConfig({}, 'Load Notification Settings'),
[updateConfig]
)
const resendVerificationEmail = useCallback(
() => updateConfig({ resend: true }, 'Resend Verification Email'),
[updateConfig]
)
const verify = useCallback(
(code: string) => updateConfig({ verify: code }, 'Verify Email'),
[updateConfig]
)
const subscribe = useCallback(async () => {
if (!WEB_PUSH_PUBLIC_KEY || pushUpdating || !serviceWorker.registration) {
return
}
setPushUpdating(true)
try {
const notificationPermission = await Notification.requestPermission()
if (notificationPermission === 'denied') {
toast.error(t('error.notificationsNotAllowed'))
return
}
const subscription =
await serviceWorker.registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: fromBase64(WEB_PUSH_PUBLIC_KEY),
})
const saved = await updateConfig({
push: {
type: 'subscribe',
subscription: JSON.parse(JSON.stringify(subscription)),
},
})
if (saved) {
setPushSubscription(subscription)
setPushSubscribed(true)
} else {
// Unsubscribe if there was an error after the subscription was created.
await subscription.unsubscribe().catch(() => {})
}
} catch (err) {
console.error(err)
toast.error(processError(err))
} finally {
setPushUpdating(false)
}
}, [pushUpdating, serviceWorker.registration, t, updateConfig])
const unsubscribe = useCallback(async () => {
if (!pushSubscription || pushUpdating) {
return
}
setPushUpdating(true)
try {
let saved = true
// Key should always be found, but just in case.
const p256dhKey = pushSubscription.getKey('p256dh')
const p256dh = p256dhKey ? toBase64(new Uint8Array(p256dhKey)) : undefined
if (p256dh) {
saved = await updateConfig({
push: {
type: 'unsubscribe',
p256dh,
},
})
}
// Unsubscribe locally once removed from server successfully. If key could
// not be found for some reason, just unsubscribe locally.
if (saved) {
await pushSubscription.unsubscribe()
setPushSubscription(undefined)
setPushSubscribed(false)
}
} catch (err) {
console.error(err)
toast.error(processError(err))
} finally {
setPushUpdating(false)
}
}, [pushSubscription, pushUpdating, updateConfig])
const unsubscribeAll = useCallback(async () => {
if (pushUpdating) {
return
}
setPushUpdating(true)
try {
const saved = await updateConfig({
push: {
type: 'unsubscribe_all',
},
})
if (saved) {
// Unsubscribe the current one if it exists.
await pushSubscription?.unsubscribe()
setPushSubscription(undefined)
setPushSubscribed(false)
}
} catch (err) {
console.error(err)
toast.error(processError(err))
} finally {
setPushUpdating(false)
}
}, [pushSubscription, pushUpdating, updateConfig])
const push = useMemo(
(): PushSubscriptionManager => ({
ready: serviceWorker.ready,
supported: serviceWorker.ready && !!serviceWorker.registration,
updating: pushUpdating,
subscribed: pushSubscribed,
subscribe,
subscription: pushSubscription,
unsubscribe,
unsubscribeAll,
}),
[
serviceWorker.ready,
serviceWorker.registration,
pushUpdating,
pushSubscribed,
subscribe,
pushSubscription,
unsubscribe,
unsubscribeAll,
]
)
return {
ready,
updating,
clear,
loadConfig,
updateConfig,
resendVerificationEmail,
verify,
config,
push,
}
}