-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice-worker.js
269 lines (219 loc) · 7.33 KB
/
service-worker.js
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
importScripts('./js/config.js')
// Creates a storage object with access and mutate methods
// that uses the Chrome storage API under the hood
function createStorage(key) {
return {
add: async (item) => {
const { [key]: items } = await chrome.storage.local.get([key])
const newItems = [...new Set([...(items || []), item])]
await chrome.storage.local.set({ [key]: newItems })
},
remove: async (item) => {
const { [key]: items } = await chrome.storage.local.get([key])
if (!items) return
const newItems = items.filter((i) => i !== item)
await chrome.storage.local.set({ [key]: newItems })
},
all: async () => {
const { [key]: items } = await chrome.storage.local.get([key])
return items || []
},
length: async () => {
const { [key]: items } = await chrome.storage.local.get([key])
return items?.length || 0
},
}
}
// Holds the set of tabs that have sent a message to the service worker
const tabs = createStorage('tabs')
// Remove tabs from the set when they are closed
chrome.tabs.onRemoved.addListener(tabs.remove)
function getCredentials() {
return chrome.storage.local.get(['accessToken', 'accountId'])
}
function setCredentials(accessToken, accountId) {
return chrome.storage.local.set({ accessToken, accountId })
}
self.addEventListener('install', async () => {
const { accessToken, accountId } = await getCredentials()
processAuthCredentialsMessage(accessToken, accountId)
})
const messageHandlers = {
'auth:credentials': async (params) => {
const { accessToken, accountId } = params
await processAuthCredentialsMessage(accessToken, accountId)
},
'harvest:settings': async () => settings,
}
let requestId = 0
const messageAuthenticatedHandlers = {
'asana:get-task-hours': async ({
external_item_id,
external_group_id,
external_service_name,
}) => {
const reqId = ++requestId
const { accessToken, accountId } = await getCredentials()
const headers = {
'harvest-account-id': accountId,
accept: 'application/json',
authorization: `Bearer ${accessToken}`,
}
const url = new URL(`${settings.api_host}/v2/platform/asana_reference`)
url.searchParams.append('external_item_id', external_item_id)
url.searchParams.append('external_group_id', external_group_id)
url.searchParams.append('external_service_name', external_service_name)
const timerName = `asana:get-task-hours:${external_item_id}:${reqId}`
console.time(timerName)
const response = await fetch(url, { headers, method: 'GET' })
console.timeEnd(timerName)
if (response.ok) {
const { total_hours } = await response.json()
return total_hours
}
},
}
async function getHandler(type) {
const handler = messageHandlers[type]
if (handler) return handler
const { accessToken, accountId } = await getCredentials()
if (accessToken && accountId) {
const handler = messageAuthenticatedHandlers[type]
if (handler) return handler
}
return null
}
chrome.runtime.onMessage.addListener((message, sender, respond) => {
const { type, value } = message
if (sender.tab) tabs.add(sender.tab.id)
if (!type) return respond(null)
getHandler(type).then((handler) => {
if (handler) {
handler(value).then((result) => respond(result))
} else {
respond(null)
}
})
return true
})
chrome.runtime.onInstalled.addListener(({ reason }) => {
if (reason === chrome.runtime.OnInstalledReason.INSTALL) {
const { version } = chrome.runtime.getManifest()
const splashUrl = 'https://www.getharvest.com/harvest-for-chrome-installed'
chrome.tabs.create({ url: `${splashUrl}?version=${version}` })
setUninstallUrl()
}
if (reason === chrome.runtime.OnInstalledReason.UPDATE) {
setUninstallUrl()
chrome.notifications.create({
iconUrl: 'images/[email protected]',
message: 'Please reopen the extension to continue to receive updates.',
priority: 0,
title: 'Harvest Time Tracker was updated',
type: 'basic',
})
}
})
// Send a message to all tabs that have sent a message to the service worker
async function sendMessageToTabs(message) {
const allTabs = await tabs.all()
allTabs?.forEach((tabId) => chrome.tabs.sendMessage(tabId, message))
}
async function processAuthCredentialsMessage(accessToken, accountId) {
if (!accessToken || !accountId) return
const { accountId: currentAccountId } = await getCredentials()
const subscription = await getSubscription()
const token = await getWebsocketToken(accessToken, accountId)
const accountIdChanged = currentAccountId !== accountId
if (token) {
await setCredentials(accessToken, accountId)
setUninstallUrl({ account_id: accountId })
sendSubscriptionToHaws(subscription, token)
}
console.log('Notifying tabs of credentials update')
await sendMessageToTabs({
type: 'auth:credentialsUpdated',
value: { accountIdChanged },
})
}
self.addEventListener('push', function (event) {
const data = event.data.json()
const running = data.event_type === 'start_timer'
const iconState = running ? 'on' : 'off'
chrome.action.setIcon({
path: {
19: `images/h-toolbar-${iconState}@19px.png`,
38: `images/h-toolbar-${iconState}@38px.png`,
},
})
const title = running
? 'View the running Harvest timer'
: 'Start a Harvest timer'
chrome.action.setTitle({ title })
})
const sendSubscriptionToHaws = async (subscription, token) => {
const headers = {
authorization: `Bearer ${token}`,
'content-type': 'application/json',
}
const body = JSON.stringify({ subscription })
await fetch(`${settings.haws_host}/subscriptions`, {
body,
headers,
method: 'post',
})
}
const getWebsocketToken = async (accessToken, accountId) => {
const headers = {
'harvest-account-id': accountId,
accept: 'application/json',
authorization: `Bearer ${accessToken}`,
}
const response = await fetch(`${settings.api_host}/v2/websocket_token`, {
headers,
method: 'GET',
})
if (response.ok) {
const payload = await response.json()
return payload.token
}
}
const getSubscription = async () => {
let subscription = await self.registration.pushManager.getSubscription()
if (subscription) {
return subscription
}
convertedVapidKey = urlBase64ToUint8Array(settings.vapid_public_key)
const chromeVersion = parseInt(
navigator.userAgentData.brands.find(
(brand) => brand.brand === 'Google Chrome'
).version,
10
)
subscription = await self.registration.pushManager.subscribe({
applicationServerKey: convertedVapidKey,
userVisibleOnly: chromeVersion < 121,
})
return subscription
}
function setUninstallUrl(params = {}) {
const { version } = chrome.runtime.getManifest()
const hiddenFields = new URLSearchParams({
account_id: '',
browser: 'chrome',
version,
...params,
})
const typeformUrl = `https://harvest.typeform.com/to/ECkKrUFP#${hiddenFields}`
chrome.runtime.setUninstallURL(typeformUrl)
}
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
const rawData = atob(base64)
const outputArray = new Uint8Array(rawData.length)
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i)
}
return outputArray
}