-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathweb-push.js
More file actions
296 lines (272 loc) · 8.52 KB
/
web-push.js
File metadata and controls
296 lines (272 loc) · 8.52 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
/* global Notification */
import React, { useContext, useState, useEffect } from 'react'
import styled from 'styled-components'
import axios from 'axios'
import PropTypes from 'prop-types'
import { useSelector } from 'react-redux'
// constants
import statusCodeConst from '../constants/status-code'
// utils
import loggerFactory from '../logger'
// contexts
import { CoreContext, WebpushPromoContext } from '../contexts'
// hooks
import useWebpush from '../hooks/use-web-push'
// components
import { DesktopBanner, MobileBanner } from './notify-and-promo/notify-banner'
// twreporter
import twreporterRedux from '@twreporter/redux'
import zIndexConst from '@twreporter/core/lib/constants/z-index'
import {
DesktopAndAbove,
TabletAndBelow,
} from '@twreporter/react-components/lib/rwd'
import requestOrigins from '@twreporter/core/lib/constants/request-origins'
// lodash
import get from 'lodash/get'
const logger = loggerFactory.getLogger()
const _ = {
get,
}
const formURL = twreporterRedux.utils.formURL
const applicationServerPublicKey = process.env.APPLICATION_SERVER_PUBLIC_KEY
/**
* The application server's public key is base 64 URL safe encoded.
* We convert it to a UInt8Array as this is the expected input of the subscribe call.
* @param {string} base64String Base 64 URL
* @return {Uint8Array} Array contains uint8 values
*/
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/')
const rawData = window.atob(base64)
const outputArray = new Uint8Array(rawData.length)
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}
/**
* @return {boolean}
*/
function isNotificationSupported() {
return 'Notification' in window
}
/**
* @return {boolean}
*/
function isPushSupported() {
return 'PushManager' in window
}
/**
* @return {boolean}
*/
function isServiceWorkerSupported() {
return 'serviceWorker' in navigator
}
const Box = styled.div`
z-index: ${zIndexConst.webPush};
visibility: ${props => (props.$show ? 'visible' : 'hidden')};
${props => (props.$show ? '' : 'transition: visibility 0.5s linear 0.5s;')}
`
const { reduxStateFields } = twreporterRedux
const defaultSubscribed = true
const apiPath = '/v1/web-push/subscriptions'
const WebPush = ({ pathname, showHamburger }) => {
const [isSubscribed, setIsSubscribed] = useState(defaultSubscribed)
const [isShowInstruction, setIsShowInstruction] = useState(false)
const { isShowPromo, closePromo } = useWebpush(
pathname,
isSubscribed,
showHamburger
)
const { releaseBranch } = useContext(CoreContext)
const apiOrigin = requestOrigins.forServerSideRendering[releaseBranch].api
const userId = useSelector(state =>
_.get(state, [reduxStateFields.auth, 'userInfo', 'user_id'])
)
useEffect(() => {
const initialize = async () => {
try {
const subscribedStatus = await getIsSubscribed()
setIsSubscribed(subscribedStatus)
} catch (err) {
logger.warn(err)
}
}
initialize()
}, [])
const getIsSubscribed = async () => {
// check service support
// push manager and service worker only existed on client side
if (!isServiceWorkerSupported() || !isPushSupported()) {
logger.info('Browser does not support web push or service worker')
return defaultSubscribed
}
// check if service worker registered web push notification or not
try {
const reg = await navigator.serviceWorker.getRegistration()
if (!reg) {
return false
}
const subscribeStatus = await reg.pushManager.permissionState({
userVisibleOnly: true,
})
if (subscribeStatus === 'denied') {
setIsShowInstruction(true)
}
const subscription = await reg.pushManager.getSubscription()
if (!subscription) {
return false
}
const endpoint = subscription.endpoint
const url = formURL(apiOrigin, apiPath, { endpoint }, false)
try {
const axiosRes = await axios.get(url)
if (_.get(axiosRes, 'status') === statusCodeConst.ok) {
return true
}
return false
} catch (err) {
const statusCode = _.get(err, 'response.status')
if (statusCode === statusCodeConst.notFound) {
return false
}
return Promise.reject(err)
}
} catch (err) {
logger.errorReport({
report: err,
message:
'Something went wrong during checking web push subscription is existed or not',
})
return defaultSubscribed
}
}
const requestNotificationPermission = () => {
return new Promise((resolve, reject) => {
Notification.requestPermission(permission => {
const isGrant = permission === 'granted'
if (isGrant) {
return resolve(isGrant)
}
return reject(new Error('User denies Notification request permission'))
})
})
}
const acceptNotification = async () => {
if (
!isNotificationSupported() ||
!isPushSupported() ||
!isServiceWorkerSupported()
) {
logger.info(
'Browser does not support `Notification`, `PushManager` or `serviceWorker`.'
)
return
}
if (Notification.permission === 'granted') {
return true
}
const breakHere = () => {
// eslint-disable-next-line prefer-promise-reject-errors
return Promise.reject('BREAK')
}
try {
// request permission on client side
const isGrant = await requestNotificationPermission()
if (!isGrant) {
breakHere()
}
const reg = await navigator.serviceWorker.getRegistration()
if (!reg) {
breakHere()
}
const applicationServerKey = urlB64ToUint8Array(
applicationServerPublicKey
)
const subscription = await reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey,
})
if (!subscription || typeof subscription.toJSON !== 'function') {
breakHere()
}
// update subscription data to twreporter backend
const _subscription = subscription.toJSON()
const data = {
endpoint: _subscription.endpoint,
keys: JSON.stringify(_subscription.keys),
user_id: userId,
}
if (
_subscription.expirationTime &&
typeof _subscription.expirationTime.toString === 'function'
) {
data.expirationTime = _subscription.expirationTime.toString()
}
const axiosRes = await axios.post(formURL(apiOrigin, apiPath), data)
let accepted = false
if (_.get(axiosRes, 'status') === statusCodeConst.created) {
accepted = true
}
closePromo()
return accepted
} catch (err) {
if (err === 'BREAK') {
return
}
logger.errorReport({
report: err,
message: 'Fail to accept web push notification',
})
setIsShowInstruction(true)
}
}
const contextValue = { isShowPromo, closePromo }
const description = isShowInstruction
? ['您的瀏覽器目前封鎖推播通知,需先更改瀏覽器設定!']
: ['開啟文章推播功能得到報導者第一手消息!']
const buttonText = isShowInstruction ? '前往操作教學' : '開啟通知'
const onClickButton = async () => {
if (isShowInstruction) {
window.open(
'https://www.twreporter.org/a/how-to-follow-the-reporter#方法2:設定文章推播',
'_blank'
)
} else {
await acceptNotification()
}
closePromo()
}
return (
<Box $show={isShowPromo}>
<WebpushPromoContext.Provider value={contextValue}>
<DesktopAndAbove>
<DesktopBanner
customContext={WebpushPromoContext}
imageUrl={`https://www.twreporter.org/assets/membership-promo/${releaseBranch}/ciao.png`}
title="即時追蹤最新報導"
description={description}
buttonText={buttonText}
onClickButton={onClickButton}
/>
</DesktopAndAbove>
<TabletAndBelow>
<MobileBanner
customContext={WebpushPromoContext}
title="即時追蹤最新報導"
description={description}
buttonText={buttonText}
onClickButton={onClickButton}
/>
</TabletAndBelow>
</WebpushPromoContext.Provider>
</Box>
)
}
WebPush.propTypes = {
pathname: PropTypes.string.isRequired,
showHamburger: PropTypes.bool.isRequired,
}
export default WebPush