From abb2d58ed5c588373ec751924b12e4ec896e419d Mon Sep 17 00:00:00 2001 From: MuslemRahimi Date: Sun, 2 Feb 2025 23:05:54 +0100 Subject: [PATCH] bugfixing --- .../api/sendPushSubscription/+server.ts | 28 ++- src/service-worker.ts | 220 +++++++++++++++--- static/manifest.json | 17 +- 3 files changed, 212 insertions(+), 53 deletions(-) diff --git a/src/routes/api/sendPushSubscription/+server.ts b/src/routes/api/sendPushSubscription/+server.ts index d73dba46..3c1e7ead 100644 --- a/src/routes/api/sendPushSubscription/+server.ts +++ b/src/routes/api/sendPushSubscription/+server.ts @@ -1,3 +1,4 @@ +// server endpoints file import type { RequestHandler } from '@sveltejs/kit'; import webPush from 'web-push'; @@ -12,7 +13,7 @@ webPush.setVapidDetails( export const POST: RequestHandler = async ({ request, locals }) => { const { pb, apiKey } = locals; - const { body, key } = await request?.json(); + const { title, body, key, options = {} } = await request?.json(); if (apiKey !== key) { console.warn('Invalid API key'); @@ -20,7 +21,6 @@ export const POST: RequestHandler = async ({ request, locals }) => { } try { - // Get all push subscriptions const subscriptions = await pb.collection('pushSubscription').getFullList({ sort: '-created' }); if (!subscriptions.length) { @@ -28,7 +28,6 @@ export const POST: RequestHandler = async ({ request, locals }) => { return new Response(JSON.stringify({ success: false, error: 'No subscriptions found' }), { status: 404 }); } - // Send notifications const sendNotifications = subscriptions.map(async (subRecord) => { try { const subscriptionData = subRecord.subscription?.subscription; @@ -38,8 +37,19 @@ export const POST: RequestHandler = async ({ request, locals }) => { return; } - // Apple Push Notifications do not support VAPID - const payload = subscriptionData.endpoint.includes('web.push.apple.com') ? '' : body; + const isApple = subscriptionData.endpoint.includes('web.push.apple.com'); + const payload = JSON.stringify({ + title, + body, + options: { + ...options, + // Additional options specific to the platform + ...(isApple && { + silent: false, // Ensure notification shows on iOS + timestamp: Date.now(), // Required for iOS + }) + } + }); await webPush.sendNotification(subscriptionData, payload); console.log(`Notification sent to: ${subscriptionData.endpoint}`); @@ -47,7 +57,6 @@ export const POST: RequestHandler = async ({ request, locals }) => { } catch (error: any) { console.error(`Error sending notification to ${subRecord.id}:`, error); - // Remove invalid subscriptions if (error.statusCode === 410 || error.statusCode === 404) { console.warn(`Deleting invalid subscription: ${subRecord.id}`); await pb.collection('pushSubscription').delete(subRecord.id); @@ -57,9 +66,12 @@ export const POST: RequestHandler = async ({ request, locals }) => { await Promise.all(sendNotifications); - return new Response(JSON.stringify({ success: true, message: `Notifications sent to ${subscriptions.length} devices` })); + return new Response(JSON.stringify({ + success: true, + message: `Notifications sent to ${subscriptions.length} devices` + })); } catch (error: any) { console.error('Error sending notifications:', error); return new Response(JSON.stringify({ success: false, error: error.message }), { status: 500 }); } -}; +}; \ No newline at end of file diff --git a/src/service-worker.ts b/src/service-worker.ts index ea28b6ad..984f6826 100644 --- a/src/service-worker.ts +++ b/src/service-worker.ts @@ -5,35 +5,77 @@ declare let self: ServiceWorkerGlobalScope; import { build, files, version } from "$service-worker"; -// Fixed template literal syntax +// Constants const CACHE = `cache-${version}`; const ASSETS = [...build, ...files]; -// install service worker +// Helper function to resolve icon paths +function getIconPath(size: string) { + return new URL(`/pwa-${size}.png`, self.location.origin).href; +} + +// Icon configurations +const ICONS = { + DEFAULT: getIconPath('192x192'), + SMALL: getIconPath('64x64'), + LARGE: getIconPath('512x512') +}; + +// Cache list of essential assets including icons +const ESSENTIAL_ASSETS = [ + ...ASSETS, + ICONS.DEFAULT, + ICONS.SMALL, + ICONS.LARGE +]; + +/** + * Installation handler + * Caches all static assets and icon files + */ self.addEventListener("install", (event) => { async function addFilesToCache() { try { const cache = await caches.open(CACHE); - await cache.addAll(ASSETS); + await cache.addAll(ESSENTIAL_ASSETS); + console.log('Service worker: Cache populated successfully'); } catch (error) { - console.error('Service worker installation failed:', error); + console.error('Service worker: Cache population failed:', error); } } + event.waitUntil(addFilesToCache()); }); +/** + * Activation handler + * Cleans up old caches + */ self.addEventListener("activate", (event) => { async function deleteOldCaches() { - for (const key of await caches.keys()) { - if (key !== CACHE) { - await caches.delete(key); - } + try { + const keys = await caches.keys(); + await Promise.all( + keys.map(key => { + if (key !== CACHE) { + console.log('Service worker: Removing old cache:', key); + return caches.delete(key); + } + }) + ); + } catch (error) { + console.error('Service worker: Error cleaning old caches:', error); } } + event.waitUntil(deleteOldCaches()); }); -//listen to fetch events +/** + * Fetch handler + * Implements a cache-first strategy for static assets + * and a network-first strategy for other requests + */ self.addEventListener("fetch", (event) => { if (event.request.method !== "GET") return; @@ -41,52 +83,154 @@ self.addEventListener("fetch", (event) => { const url = new URL(event.request.url); const cache = await caches.open(CACHE); - //serve build files from cache; - if (ASSETS.includes(url.pathname)) { + // Serve static assets from cache first + if (ESSENTIAL_ASSETS.includes(url.pathname)) { const cacheResponse = await cache.match(url.pathname); if (cacheResponse) { return cacheResponse; } } - // try the network first + + // Network-first strategy for other requests try { const response = await fetch(event.request); - const isNotExtension = url.protocol === "http:"; - const isSuccess = response.status === 200; - - if (isNotExtension && isSuccess) { - cache.put(event.request, response.clone()); + + // Cache successful responses + if (response.status === 200) { + const responseToCache = response.clone(); + cache.put(event.request, responseToCache).catch(error => { + console.error('Service worker: Error caching response:', error); + }); } - + return response; - } catch { - //fall back to cache - const cachedResponse = await cache.match(url.pathname); + } catch (error) { + // Fallback to cache if network fails + const cachedResponse = await cache.match(event.request); if (cachedResponse) { return cachedResponse; } + + console.error('Service worker: Network and cache fetch failed:', error); + return new Response("Network error", { status: 503 }); } - - return new Response("Not found", { status: 404 }); } + + event.respondWith(respond()); }); +/** + * Push notification handler + * Processes push notifications and displays them to the user + */ +self.addEventListener('push', (event: PushEvent) => { + let payload = 'No payload'; + let title = 'Stocknear'; + + let options: NotificationOptions = { + icon: ICONS.DEFAULT, + badge: ICONS.SMALL, + image: ICONS.LARGE, + data: {}, + tag: 'stocknear-notification', // Group similar notifications + renotify: true, // Notify even if there's an existing notification + silent: false, + timestamp: Date.now(), // Required for iOS + requireInteraction: true, // Keep notification until user interacts + vibrate: [200, 100, 200], // Vibration pattern [vibrate, pause, vibrate] + }; + + try { + if (event.data) { + let data; + try { + // Try to parse JSON payload + data = event.data.json(); + } catch (e) { + // Fallback to text payload + data = { body: event.data.text() }; + } + + payload = data.body || data.message || 'New notification'; + title = data.title || title; + + // Merge options while preserving critical values + options = { + ...options, + body: payload, + ...(data.options || {}), + // Ensure icon paths aren't overwritten + icon: ICONS.DEFAULT, + badge: ICONS.SMALL, + image: ICONS.LARGE + }; + } + } catch (error) { + console.error('Service worker: Error processing push notification:', error); + options.body = payload; + } + + // Log notification details for debugging + console.log('Service worker: Showing notification', { + title, + options, + icons: { + icon: options.icon, + badge: options.badge, + image: options.image + } + }); + + const promiseChain = self.registration.showNotification(title, options); + event.waitUntil(promiseChain); +}); + +/** + * Notification click handler + * Handles user interaction with notifications + */ +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + + const urlToOpen = new URL('/', self.location.origin).href; + + const promiseChain = clients.matchAll({ + type: 'window', + includeUncontrolled: true + }) + .then((windowClients) => { + // Focus existing window if available + for (let i = 0; i < windowClients.length; i++) { + const client = windowClients[i]; + if (client.url === urlToOpen && 'focus' in client) { + return client.focus(); + } + } + // Open new window if necessary + if (clients.openWindow) { + return clients.openWindow(urlToOpen); + } + }); + + event.waitUntil(promiseChain); +}); + +/** + * Message handler + * Processes messages from the main thread + */ self.addEventListener("message", (event) => { + // Handle skip waiting if (event.data && event.data.type === "SKIP_WAITING") { self.skipWaiting(); } -}); - - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -self.addEventListener('push', function (event: any) { - const payload = event.data?.text() ?? 'no payload'; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const registration = (self as any).registration as ServiceWorkerRegistration; - event.waitUntil( - registration.showNotification('Stocknear', { - body: payload, - icon: '/pwa-192x192.png', - }) - ); -} as EventListener); \ No newline at end of file + + // Handle cache update + if (event.data && event.data.type === "CACHE_URLS") { + event.waitUntil( + caches.open(CACHE) + .then((cache) => cache.addAll(event.data.payload)) + .catch((error) => console.error('Service worker: Cache update failed:', error)) + ); + } +}); \ No newline at end of file diff --git a/static/manifest.json b/static/manifest.json index 52c481a2..79c36ded 100644 --- a/static/manifest.json +++ b/static/manifest.json @@ -8,19 +8,22 @@ "description": "Clear & Simple Market Insight", "icons": [ { - "src": "pwa-64x64.png", + "src": "/pwa-64x64.png", "type": "image/png", - "sizes": "64x64" + "sizes": "64x64", + "purpose": "any maskable" }, { - "src": "pwa-192x192.png", + "src": "/pwa-192x192.png", "type": "image/png", - "sizes": "192x192" + "sizes": "192x192", + "purpose": "any maskable" }, { - "src": "pwa-512x512.png", + "src": "/pwa-512x512.png", "type": "image/png", - "sizes": "512x512" + "sizes": "512x512", + "purpose": "any maskable" } ] -} +} \ No newline at end of file