-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
335 lines (289 loc) · 11.6 KB
/
service-worker.js
File metadata and controls
335 lines (289 loc) · 11.6 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
// Service Worker สำหรับ SSKratomYMT
const CACHE_NAME = 'sskratomymt-v2.1.0';
const STATIC_CACHE = 'static-v2';
const DYNAMIC_CACHE = 'dynamic-v2';
// ทรัพยากรที่ต้องการ cache ไว้ล่วงหน้า
const STATIC_ASSETS = [
'/',
'/index.html',
'/manifest.json',
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
'https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600&display=swap',
'/images/icons/icon-72x72.png',
'/images/icons/icon-96x96.png',
'/images/icons/icon-128x128.png',
'/images/icons/icon-144x144.png',
'/images/icons/icon-152x152.png',
'/images/icons/icon-192x192.png',
'/images/icons/icon-384x384.png',
'/images/icons/icon-512x512.png'
];
// ฟังก์ชันติดตั้ง Service Worker
self.addEventListener('install', (event) => {
console.log('Service Worker: Installing...');
event.waitUntil(
caches.open(STATIC_CACHE)
.then((cache) => {
console.log('Service Worker: Caching Static Assets');
return cache.addAll(STATIC_ASSETS);
})
.then(() => {
console.log('Service Worker: Install Completed');
return self.skipWaiting();
})
.catch((error) => {
console.error('Service Worker: Installation Failed', error);
})
);
});
// ฟังก์ชันเปิดใช้งาน Service Worker
self.addEventListener('activate', (event) => {
console.log('Service Worker: Activating...');
event.waitUntil(
caches.keys()
.then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== STATIC_CACHE && cache !== DYNAMIC_CACHE && cache !== CACHE_NAME) {
console.log('Service Worker: Clearing Old Cache', cache);
return caches.delete(cache);
}
})
);
})
.then(() => {
console.log('Service Worker: Activate Completed');
return self.clients.claim();
})
);
});
// ฟังก์ชันดักจับการขอทรัพยากร
self.addEventListener('fetch', (event) => {
// ข้ามการดักจับสำหรับ requests ไปยัง Google Apps Script
if (event.request.url.includes('script.google.com')) {
return;
}
// ข้ามการดักจับสำหรับ non-GET requests
if (event.request.method !== 'GET') {
return;
}
event.respondWith(
caches.match(event.request)
.then((cachedResponse) => {
// ถ้ามีใน cache ให้ส่งคืนจาก cache
if (cachedResponse) {
return cachedResponse;
}
// ถ้าไม่มีใน cache ให้ดึงจาก network
return fetch(event.request)
.then((networkResponse) => {
// ตรวจสอบว่าการตอบกลับถูกต้องหรือไม่
if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
return networkResponse;
}
// คัดลอก response และเก็บใน cache
const responseToCache = networkResponse.clone();
caches.open(DYNAMIC_CACHE)
.then((cache) => {
// เก็บเฉพาะทรัพยากรจาก origin เดียวกัน
if (event.request.url.startsWith(self.location.origin)) {
cache.put(event.request, responseToCache);
}
});
return networkResponse;
})
.catch(() => {
// กรณี offline และไม่มีใน cache
// สำหรับหน้า HTML ให้ส่งคืนหน้า index.html
if (event.request.destination === 'document') {
return caches.match('/index.html');
}
// สำหรับรูปภาพ ให้ส่งคืนรูปภาพ placeholder
if (event.request.destination === 'image') {
return caches.match('/images/icons/icon-192x192.png');
}
// สำหรับ CSS และ Fonts
if (event.request.destination === 'style' || event.request.destination === 'font') {
// สามารถเพิ่ม fallback ได้ที่นี่
}
});
})
);
});
// ฟังก์ชันจัดการการซิงค์ข้อมูลในพื้นหลัง
self.addEventListener('sync', (event) => {
console.log('Service Worker: Background Sync', event.tag);
if (event.tag === 'sync-offline-data') {
event.waitUntil(syncOfflineData());
}
});
// ฟังก์ชันซิงค์ข้อมูลออฟไลน์
async function syncOfflineData() {
try {
console.log('Service Worker: Syncing offline data...');
// เปิดฐานข้อมูล IndexedDB
const db = await new Promise((resolve, reject) => {
const request = indexedDB.open('salesDB', 3);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
// ดึงข้อมูลที่รอซิงค์
const offlineData = await new Promise((resolve) => {
const transaction = db.transaction(['sales'], 'readonly');
const store = transaction.objectStore('sales');
const request = store.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = () => resolve([]);
});
if (offlineData.length === 0) {
console.log('Service Worker: No offline data to sync');
return;
}
console.log(`Service Worker: Syncing ${offlineData.length} records`);
// ส่งข้อมูลไปยังเซิร์ฟเวอร์
const response = await fetch('https://script.google.com/macros/s/AKfycbxcz209lJDCwls20sDnXMG8V2uP5rUowZ5JWCjG8JEhSfCCyAAWJBBv4sBUrnofuYJH/exec', {
method: 'POST',
headers: {
'Content-Type': 'text/plain;charset=utf-8',
},
body: JSON.stringify(offlineData)
});
const result = await response.json();
if (result.status === 'success') {
// ลบข้อมูลที่ซิงค์สำเร็จแล้วออกจากฐานข้อมูล
await new Promise((resolve) => {
const transaction = db.transaction(['sales'], 'readwrite');
const store = transaction.objectStore('sales');
store.clear();
transaction.oncomplete = () => resolve();
});
console.log('Service Worker: Offline data synced successfully');
// แสดงการแจ้งเตือน
self.registration.showNotification('SSKratomYMT', {
body: `ซิงค์ข้อมูลสำเร็จ ${result.records_count || offlineData.length} รายการ`,
icon: '/images/icons/icon-192x192.png',
badge: '/images/icons/icon-72x72.png',
tag: 'sync-success'
});
} else {
throw new Error(result.message || 'Sync failed');
}
} catch (error) {
console.error('Service Worker: Sync failed', error);
// แสดงการแจ้งเตือนข้อผิดพลาด
self.registration.showNotification('SSKratomYMT', {
body: 'การซิงค์ข้อมูลล้มเหลว จะลองอีกครั้งเมื่อออนไลน์',
icon: '/images/icons/icon-192x192.png',
badge: '/images/icons/icon-72x72.png',
tag: 'sync-error'
});
}
}
// ฟังก์ชันจัดการการแจ้งเตือน
self.addEventListener('push', (event) => {
console.log('Service Worker: Push Received');
if (!event.data) return;
const data = event.data.json();
const options = {
body: data.body || 'มีการอัปเดตใหม่จาก SSKratomYMT',
icon: '/images/icons/icon-192x192.png',
badge: '/images/icons/icon-72x72.png',
image: data.image || '/images/icons/icon-512x512.png',
tag: data.tag || 'general-notification',
requireInteraction: data.requireInteraction || false,
actions: data.actions || [
{
action: 'open',
title: 'เปิดแอป'
},
{
action: 'close',
title: 'ปิด'
}
]
};
event.waitUntil(
self.registration.showNotification(data.title || 'SSKratomYMT', options)
);
});
// ฟังก์ชันจัดการเมื่อมีการคลิกการแจ้งเตือน
self.addEventListener('notificationclick', (event) => {
console.log('Service Worker: Notification Clicked');
event.notification.close();
if (event.action === 'close') {
return;
}
event.waitUntil(
self.clients.matchAll({ type: 'window' })
.then((clientList) => {
// ถ้ามีหน้าต่างที่เปิดอยู่แล้ว ให้โฟกัสที่หน้านั้น
for (const client of clientList) {
if (client.url === self.location.origin && 'focus' in client) {
return client.focus();
}
}
// ถ้าไม่มีหน้าต่างที่เปิดอยู่ ให้เปิดหน้าใหม่
if (self.clients.openWindow) {
return self.clients.openWindow('/');
}
})
);
});
// ฟังก์ชันจัดการเมื่อการแจ้งเตือนถูกปิด
self.addEventListener('notificationclose', (event) => {
console.log('Service Worker: Notification Closed', event.notification.tag);
});
// ฟังก์ชันจัดการข้อความจาก main thread
self.addEventListener('message', (event) => {
console.log('Service Worker: Message Received', event.data);
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
if (event.data && event.data.type === 'SYNC_DATA') {
event.waitUntil(syncOfflineData());
}
if (event.data && event.data.type === 'GET_VERSION') {
event.ports[0].postMessage({
type: 'VERSION_INFO',
version: '2.1.0',
cacheName: CACHE_NAME
});
}
});
// ฟังก์ชันตรวจสอบสถานะออนไลน์/ออฟไลน์
function updateOnlineStatus() {
self.clients.matchAll().then((clients) => {
clients.forEach((client) => {
client.postMessage({
type: 'NETWORK_STATUS',
isOnline: navigator.onLine
});
});
});
}
// ฟังก์ชันตรวจสอบและอัปเดตแคช
async function updateCache() {
try {
const cache = await caches.open(STATIC_CACHE);
const requests = STATIC_ASSETS.map(url => new Request(url));
for (const request of requests) {
try {
const networkResponse = await fetch(request);
if (networkResponse.ok) {
await cache.put(request, networkResponse);
console.log('Service Worker: Updated cache for', request.url);
}
} catch (error) {
console.warn('Service Worker: Failed to update cache for', request.url, error);
}
}
} catch (error) {
console.error('Service Worker: Cache update failed', error);
}
}
// อัปเดตแคชทุกๆ 24 ชั่วโมง
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'update-cache') {
event.waitUntil(updateCache());
}
});