-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserviceworker.js
279 lines (246 loc) · 7.44 KB
/
serviceworker.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
270
271
272
273
274
275
276
277
278
279
importScripts("/assets/js/localforage.js")
importScripts("/assets/js/functions.js")
const CACHE = "content-v28" // name of the current cache
const AVATARS = "avatars"
const DEFAULT_AVATAR = "./assets/image/kitty.webp"
const OFFLINE = "/offline.html"
const REPORT_PAGE = "/report.html"
let meowsUpdateBackgroundSyncTagName = 'meowsUpdateBackgroundSync'
let commentsUpdateBackgroundSyncTagName = 'commentsUpdateBackgroundSync'
let periodicMeowSyncTagName = 'periodicMeowSync'
const AUTO_CACHE = [
OFFLINE,
"/",
REPORT_PAGE,
"/assets/image/add.webp",
"/assets/image/cancel.webp",
"/assets/image/cat-face.webp",
"/assets/image/eye.webp",
"/assets/image/hide.webp",
"/assets/image/kitty.webp",
"/assets/image/location.webp",
"/assets/image/paw.webp",
"/assets/image/reviewed.webp",
"/assets/image/share.webp",
"/assets/image/unliked.webp",
"/assets/image/sadcat.webp",
"/assets/image/write.png",
"/assets/image/coffee.png",
"/assets/image/loading.gif",
"/assets/image/spinner.gif",
"/assets/image/error.gif",
"/assets/image/nodata.gif",
"/assets/image/done.gif",
"/assets/css/main.css",
"/assets/css/report.css",
"/assets/css/nprogress.css",
"/assets/css/SFRegular.woff",
"/assets/css/SFMedium.woff",
"/assets/css/SFBold.woff",
"/assets/css/Galactico-Basic.woff",
"/assets/js/pullToRefresh.js",
"/assets/js/fs.js",
"/assets/js/app.js",
"/assets/js/functions.js",
"/assets/js/impure.js",
"/assets/js/report.js",
"/assets/js/nprogress.js",
"/assets/js/localforage.js",
"/assets/js/noGoBack.js",
"./site.webmanifest"
]
self.addEventListener("install", (event) => {
event.waitUntil(
caches
.open(CACHE)
.then((cache) => cache.addAll(AUTO_CACHE))
.then(self.skipWaiting())
)
})
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((cacheNames) => {
return cacheNames.filter((cacheName) => CACHE !== cacheName && AVATARS !== cacheName)
})
.then((unusedCaches) => {
console.log("DESTROYING CACHE", unusedCaches.join(","))
return Promise.all(
unusedCaches.map((unusedCache) => {
return caches.delete(unusedCache)
})
)
})
.then(() => self.clients.claim())
)
})
function isCached(url) {
let origin = self.location.origin
if (url.includes("assets")) return true
if (url == `${origin}/`) return true
if (url == `${origin}/report`) return true
if (url == `${origin}/report.html`) return true
if (url.includes("logo.png") || url.includes("favicon.ico") || url.includes("site.webmanifest")) return true
return false
}
self.addEventListener("fetch", (event) => {
if (event.request.url.includes("avatars.dicebear.com")) {
event.respondWith(
caches.open(AVATARS).then((cache) => {
return cache.match(event.request).then((response) => {
if (response) return response
return fetch(event.request).then((response) => {
cache.put(event.request, response.clone())
return response
}).catch(() => {
return caches.match(DEFAULT_AVATAR)
})
})
})
)
return
}
if (
!event.request.url.startsWith(self.location.origin) ||
event.request.method !== "GET"
) {
return void event.respondWith(fetch(event.request).catch((err) => console.log(err)))
}
if(!isCached(event.request.url)){
event.respondWith(
fetch(event.request)
.then((response) => {
caches.open(CACHE).then((cache) => {
cache.put(event.request, response)
})
return response.clone()
})
.catch((_err) => {
return caches.match(event.request).then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse
}
return caches.open(CACHE).then((cache) => {
const offlineRequest = new Request(OFFLINE)
return cache.match(offlineRequest)
})
})
})
)
} else {
event.respondWith(
caches.match(event.request).then((response) => {
if (response) {
return response
}
return fetch(event.request).then((response) => {
caches.open(CACHE).then((cache) => {
cache.put(event.request, response)
})
return response.clone()
})
})
)
}
})
async function syncScheduledMeows () {
let scheduledMeows = await getLocalForage("meowQueue")
let newQueue = []
if (scheduledMeows == null) return
if(scheduledMeows.length > 0){
scheduledMeows.forEach(async (meow) => {
let lastSentId = await getLastSentContentId("meow")
let lastSentMeow = await getSavedTextData("meow")
if(meow._id == lastSentId || meow.text == lastSentMeow.text) return
let sentMeow = await newMeow(meow.text, meow.coords, meow.userid)
if(sentMeow._id == undefined) {
if(sentMeow.status !== undefined && sentMeow.status === false) {
await setLocalForage("meowQueue", null)
await localforage.clear()
return
}
newQueue.push(meow)
return
}
let meows = await getLocalForage("meows")
meows.unshift(sentMeow)
await setLocalForage("meows", meows)
})
}
await setLocalForage("meowQueue", newQueue)
return true
}
async function syncScheduledComments() {
let scheduledComments = await getLocalForage("commentQueue")
let newQueue = []
if (scheduledComments == null) return
if(scheduledComments.length > 0){
scheduledComments.forEach(async (comment) => {
let lastSentId = await getLastSentContentId("comment")
let lastSentComment = await getSavedTextData("comment")
if(comment._id == lastSentId || comment.text == lastSentComment.text) return
let sentComment = await createNewComment(comment)
if(sentComment._id == undefined) {
if(sentComment.status !== undefined && sentComment.status === false) {
await setLocalForage("meowQueue", null)
await localforage.clear()
return
}
newQueue.push(comment)
return
}
})
}
await setLocalForage("commentQueue", newQueue)
return true
}
async function periodicallySyncMeows() {
let position = await getLocalForage("position")
if(position == null) return true
let meows = await getPosts(position)
if(meows == null) return true
await setLocalForage("meows", meows)
await setLocalForage("lastSynced", new Date().getTime())
console.log("PERIODIC SYNCING MEOWS")
return true
}
async function requestBackgroundSync(backgroundSyncTagName) {
try {
await self.registration.sync.register(backgroundSyncTagName)
await setLocalForage("backgroundSync", true)
} catch (error) {
console.log("Unable to REGISTER background sync", error)
setTimeout(() => requestBackgroundSync(backgroundSyncTagName), 10000)
await setLocalForage("backgroundSync", false)
}
}
async function requestPeriodicBGSync(tagName, hours) {
try {
await self.registration.periodicSync.register(tagName, {
minInterval: hours * 60 * 60 * 1000,
})
await setLocalForage("periodicBGSync", true)
} catch (err) {
console.log(`Unable to REGISTER periodic sync`, err)
setTimeout(() => requestPeriodicBGSync(tagName, hours), 10000)
await setLocalForage("periodicBGSync", false)
}
}
requestBackgroundSync(meowsUpdateBackgroundSyncTagName)
requestBackgroundSync(commentsUpdateBackgroundSyncTagName)
requestPeriodicBGSync(periodicMeowSyncTagName, 1)
self.addEventListener('sync', event => {
if (event.tag === meowsUpdateBackgroundSyncTagName) {
console.log("SYNCING MEOWS")
event.waitUntil(syncScheduledMeows())
} else if (event.tag === commentsUpdateBackgroundSyncTagName) {
console.log("SYNCING COMMENTS")
event.waitUntil(syncScheduledComments())
}
})
self.addEventListener("periodicsync", (event) => {
if (event.tag == periodicMeowSyncTagName) {
event.waitUntil(periodicallySyncMeows())
}
})