-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
382 lines (344 loc) · 10.3 KB
/
service-worker.js
File metadata and controls
382 lines (344 loc) · 10.3 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
const SW_URL = new URL(self.location.href);
const CACHE_VERSION = (SW_URL.searchParams.get('v') || 'dev').replace(/[^a-zA-Z0-9._-]/g, '_');
const STATIC_CACHE = `dimicheck-static-${CACHE_VERSION}`;
const RUNTIME_CACHE = `dimicheck-runtime-${CACHE_VERSION}`;
const TIMETABLE_META_CACHE = 'dimicheck-timetable-meta';
const TIMETABLE_META_URL = '/__timetable-meta__';
const CLASS_CONTEXT_URL = '/__class-context__';
const ATPT_OFCDC_SC_CODE = 'J10';
const SD_SCHUL_CODE = '7530560';
const NEIS_API_KEY = 'da82433f0f3a4351bda4ca9a0f11fc7d';
const PRECACHE_URLS = [
'/404.html',
'/manifest.webmanifest',
'/src/infoicn.png',
'/src/dimicheck_templogo.png',
'/src/dipulllogo.svg',
'/src/favicon/android-chrome-192x192.png',
'/src/favicon/android-chrome-512x512.png',
'/src/favicon/apple-touch-icon.png',
'/src/favicon/favicon-32x32.png',
'/src/favicon/favicon-16x16.png',
'/src/favicon/favicon.ico'
];
const PRECACHE_SET = new Set(PRECACHE_URLS);
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(STATIC_CACHE).then((cache) => cache.addAll(PRECACHE_URLS))
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
const currentCaches = [STATIC_CACHE, RUNTIME_CACHE, TIMETABLE_META_CACHE];
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => !currentCaches.includes(key))
.map((key) => caches.delete(key))
)
)
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') {
return;
}
const url = new URL(request.url);
if (
url.origin === self.location.origin &&
(url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/auth/') ||
url.pathname === '/me')
) {
event.respondWith(fetchBypassingHttpCache(request));
return;
}
if (url.origin !== self.location.origin) {
return;
}
if (request.mode === 'navigate') {
event.respondWith(handleNavigationRequest(request));
return;
}
if (isVolatileAsset(url.pathname)) {
event.respondWith(handleVolatileAssetRequest(request, url.pathname));
return;
}
event.respondWith(handleStableAssetRequest(event, request, url.pathname));
});
async function handleNavigationRequest(request) {
try {
const networkResponse = await fetchBypassingHttpCache(request);
if (isCacheableResponse(networkResponse)) {
const runtime = await caches.open(RUNTIME_CACHE);
await runtime.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
const cached = await caches.match(request);
if (cached) {
return cached;
}
const fallback = await caches.match('/404.html');
if (fallback) {
return fallback;
}
throw error;
}
}
function isVolatileAsset(pathname) {
return (
pathname.endsWith('.html') ||
pathname.endsWith('.js') ||
pathname.endsWith('.css') ||
pathname.endsWith('.json') ||
pathname === '/service-worker.js' ||
pathname === '/js/pwa.js'
);
}
async function fetchBypassingHttpCache(request) {
return fetch(new Request(request, { cache: 'no-store' }));
}
function isCacheableResponse(response) {
return Boolean(response && response.ok && response.status !== 206);
}
async function handleVolatileAssetRequest(request, pathname) {
try {
return await fetchBypassingHttpCache(request);
} catch (error) {
const cached = await caches.match(request);
if (cached) {
return cached;
}
if (PRECACHE_SET.has(pathname)) {
const fallback = await caches.match(pathname);
if (fallback) {
return fallback;
}
}
throw error;
}
}
function handleStableAssetRequest(event, request, pathname) {
return (async () => {
const cached = await caches.match(request);
if (cached) {
event.waitUntil(updateRuntimeCache(request));
return cached;
}
try {
const networkResponse = await fetchBypassingHttpCache(request);
if (isCacheableResponse(networkResponse)) {
const runtime = await caches.open(RUNTIME_CACHE);
await runtime.put(request, networkResponse.clone());
}
return networkResponse;
} catch (error) {
if (PRECACHE_SET.has(pathname)) {
const fallback = await caches.match(pathname);
if (fallback) {
return fallback;
}
}
throw error;
}
})();
}
async function updateRuntimeCache(request) {
try {
const response = await fetchBypassingHttpCache(request);
if (isCacheableResponse(response)) {
const runtime = await caches.open(RUNTIME_CACHE);
await runtime.put(request, response.clone());
}
} catch (error) {
// Ignore background update failures
}
}
self.addEventListener('notificationclick', (event) => {
const targetUrl = event.notification?.data?.url || '/';
event.notification?.close();
event.waitUntil(openOrFocusClient(targetUrl));
});
self.addEventListener('message', (event) => {
const data = event.data || {};
if (data.type === 'TIMETABLE_FORCE_CHECK') {
event.waitUntil(triggerTimetableNotification());
}
if (data.type === 'TIMETABLE_PREF_CHANGED' && data.enabled === false) {
event.waitUntil(clearTimetableMeta());
}
if (data.type === 'CLASS_CONTEXT') {
event.waitUntil(storeClassContext(data.context));
}
});
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'dimicheck-timetable') {
event.waitUntil(triggerTimetableNotification());
}
});
async function openOrFocusClient(url) {
const target = new URL(url, self.location.origin);
const clientsList = await clients.matchAll({ type: 'window', includeUncontrolled: true });
for (const client of clientsList) {
const clientUrl = new URL(client.url);
if (clientUrl.pathname === target.pathname) {
await client.focus();
return client;
}
}
return clients.openWindow(target.href);
}
async function triggerTimetableNotification() {
const now = new Date();
if (!isWeekday(now)) {
return;
}
if (now.getHours() >= 12) {
return;
}
const target = new Date(now);
target.setHours(6, 30, 0, 0);
if (now.getTime() < target.getTime()) {
return;
}
const dateKey = now.toISOString().slice(0, 10);
const last = await getLastTimetableDate();
if (last === dateKey) {
return;
}
const context = await getClassContext();
if (!context || !context.grade || !context.section) {
return;
}
const timetableLines = await fetchTodayTimetable(context.grade, context.section, now);
try {
await self.registration.showNotification('시간표 알림', {
body: timetableLines.length ? timetableLines.join('\n') : '오늘 일정을 확인해보세요.',
tag: 'dimicheck-timetable',
data: { url: '/routine.html' },
icon: '/src/favicon/android-chrome-192x192.png',
badge: '/src/favicon/android-chrome-192x192.png',
timestamp: Date.now()
});
await setLastTimetableDate(dateKey);
} catch (error) {
console.warn('[SW] Failed to show timetable notification', error);
}
}
async function getLastTimetableDate() {
const cache = await caches.open(TIMETABLE_META_CACHE);
const match = await cache.match(TIMETABLE_META_URL);
if (!match) {
return null;
}
return match.text();
}
async function setLastTimetableDate(dateKey) {
const cache = await caches.open(TIMETABLE_META_CACHE);
await cache.put(TIMETABLE_META_URL, new Response(dateKey, {
headers: { 'Content-Type': 'text/plain' }
}));
}
async function clearTimetableMeta() {
const cache = await caches.open(TIMETABLE_META_CACHE);
await cache.delete(TIMETABLE_META_URL);
}
async function storeClassContext(context) {
const cache = await caches.open(TIMETABLE_META_CACHE);
const grade = Number(context?.grade);
const section = Number(context?.section);
if (!grade || !section) {
await cache.delete(CLASS_CONTEXT_URL);
return;
}
await cache.put(
CLASS_CONTEXT_URL,
new Response(JSON.stringify({ grade, section }), { headers: { 'Content-Type': 'application/json' } })
);
}
async function getClassContext() {
const cache = await caches.open(TIMETABLE_META_CACHE);
const match = await cache.match(CLASS_CONTEXT_URL);
if (!match) {
return null;
}
try {
const parsed = await match.json();
const grade = Number(parsed?.grade);
const section = Number(parsed?.section);
if (!grade || !section) {
return null;
}
return { grade, section };
} catch (error) {
console.warn('[SW] Failed to read class context', error);
return null;
}
}
function isWeekday(date) {
const day = date.getDay();
return day >= 1 && day <= 5;
}
function formatYMD(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}${m}${d}`;
}
function normalizeSubject(row) {
return (
row?.ITRT_CNTNT ||
row?.SUBJECT ||
row?.SUB_NM ||
row?.CONT ||
row?.CONTNT ||
''
);
}
async function fetchTodayTimetable(grade, section, date = new Date()) {
try {
const params = new URLSearchParams({
KEY: NEIS_API_KEY,
Type: 'json',
ATPT_OFCDC_SC_CODE,
SD_SCHUL_CODE,
GRADE: grade,
CLASS_NM: section,
ALL_TI_YMD: formatYMD(date)
});
const response = await fetch(`https://open.neis.go.kr/hub/hisTimetable?${params.toString()}`);
if (!response.ok) {
throw new Error(`NEIS error ${response.status}`);
}
const data = await response.json();
const tables = data?.hisTimetable;
if (!Array.isArray(tables)) {
return [];
}
const rows = tables.find((part) => Array.isArray(part.row))?.row || [];
const sorted = rows
.map((row) => ({
period: Number(row?.PERIO || row?.PERIOD || row?.ITRT_CNTNTSEQ || row?.PERIOD_NM) || null,
subject: normalizeSubject(row)
}))
.filter((item) => item.subject)
.sort((a, b) => {
if (a.period == null) return 1;
if (b.period == null) return -1;
return a.period - b.period;
});
return sorted.map((item, index) => {
const label = item.period ? `${item.period}교시` : `${index + 1}교시`;
return `${label}: ${item.subject}`;
});
} catch (error) {
console.warn('[SW] Failed to fetch timetable data', error);
return [];
}
}