bugfixing
This commit is contained in:
parent
ac4d5b536e
commit
abb2d58ed5
@ -1,3 +1,4 @@
|
|||||||
|
// server endpoints file
|
||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import webPush from 'web-push';
|
import webPush from 'web-push';
|
||||||
|
|
||||||
@ -12,7 +13,7 @@ webPush.setVapidDetails(
|
|||||||
|
|
||||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||||
const { pb, apiKey } = locals;
|
const { pb, apiKey } = locals;
|
||||||
const { body, key } = await request?.json();
|
const { title, body, key, options = {} } = await request?.json();
|
||||||
|
|
||||||
if (apiKey !== key) {
|
if (apiKey !== key) {
|
||||||
console.warn('Invalid API key');
|
console.warn('Invalid API key');
|
||||||
@ -20,7 +21,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get all push subscriptions
|
|
||||||
const subscriptions = await pb.collection('pushSubscription').getFullList({ sort: '-created' });
|
const subscriptions = await pb.collection('pushSubscription').getFullList({ sort: '-created' });
|
||||||
|
|
||||||
if (!subscriptions.length) {
|
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 });
|
return new Response(JSON.stringify({ success: false, error: 'No subscriptions found' }), { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send notifications
|
|
||||||
const sendNotifications = subscriptions.map(async (subRecord) => {
|
const sendNotifications = subscriptions.map(async (subRecord) => {
|
||||||
try {
|
try {
|
||||||
const subscriptionData = subRecord.subscription?.subscription;
|
const subscriptionData = subRecord.subscription?.subscription;
|
||||||
@ -38,8 +37,19 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apple Push Notifications do not support VAPID
|
const isApple = subscriptionData.endpoint.includes('web.push.apple.com');
|
||||||
const payload = subscriptionData.endpoint.includes('web.push.apple.com') ? '' : body;
|
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);
|
await webPush.sendNotification(subscriptionData, payload);
|
||||||
console.log(`Notification sent to: ${subscriptionData.endpoint}`);
|
console.log(`Notification sent to: ${subscriptionData.endpoint}`);
|
||||||
@ -47,7 +57,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error(`Error sending notification to ${subRecord.id}:`, error);
|
console.error(`Error sending notification to ${subRecord.id}:`, error);
|
||||||
|
|
||||||
// Remove invalid subscriptions
|
|
||||||
if (error.statusCode === 410 || error.statusCode === 404) {
|
if (error.statusCode === 410 || error.statusCode === 404) {
|
||||||
console.warn(`Deleting invalid subscription: ${subRecord.id}`);
|
console.warn(`Deleting invalid subscription: ${subRecord.id}`);
|
||||||
await pb.collection('pushSubscription').delete(subRecord.id);
|
await pb.collection('pushSubscription').delete(subRecord.id);
|
||||||
@ -57,7 +66,10 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
|
|
||||||
await Promise.all(sendNotifications);
|
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) {
|
} catch (error: any) {
|
||||||
console.error('Error sending notifications:', error);
|
console.error('Error sending notifications:', error);
|
||||||
return new Response(JSON.stringify({ success: false, error: error.message }), { status: 500 });
|
return new Response(JSON.stringify({ success: false, error: error.message }), { status: 500 });
|
||||||
|
|||||||
@ -5,35 +5,77 @@ declare let self: ServiceWorkerGlobalScope;
|
|||||||
|
|
||||||
import { build, files, version } from "$service-worker";
|
import { build, files, version } from "$service-worker";
|
||||||
|
|
||||||
// Fixed template literal syntax
|
// Constants
|
||||||
const CACHE = `cache-${version}`;
|
const CACHE = `cache-${version}`;
|
||||||
const ASSETS = [...build, ...files];
|
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) => {
|
self.addEventListener("install", (event) => {
|
||||||
async function addFilesToCache() {
|
async function addFilesToCache() {
|
||||||
try {
|
try {
|
||||||
const cache = await caches.open(CACHE);
|
const cache = await caches.open(CACHE);
|
||||||
await cache.addAll(ASSETS);
|
await cache.addAll(ESSENTIAL_ASSETS);
|
||||||
|
console.log('Service worker: Cache populated successfully');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Service worker installation failed:', error);
|
console.error('Service worker: Cache population failed:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
event.waitUntil(addFilesToCache());
|
event.waitUntil(addFilesToCache());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Activation handler
|
||||||
|
* Cleans up old caches
|
||||||
|
*/
|
||||||
self.addEventListener("activate", (event) => {
|
self.addEventListener("activate", (event) => {
|
||||||
async function deleteOldCaches() {
|
async function deleteOldCaches() {
|
||||||
for (const key of await caches.keys()) {
|
try {
|
||||||
|
const keys = await caches.keys();
|
||||||
|
await Promise.all(
|
||||||
|
keys.map(key => {
|
||||||
if (key !== CACHE) {
|
if (key !== CACHE) {
|
||||||
await caches.delete(key);
|
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());
|
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) => {
|
self.addEventListener("fetch", (event) => {
|
||||||
if (event.request.method !== "GET") return;
|
if (event.request.method !== "GET") return;
|
||||||
|
|
||||||
@ -41,52 +83,154 @@ self.addEventListener("fetch", (event) => {
|
|||||||
const url = new URL(event.request.url);
|
const url = new URL(event.request.url);
|
||||||
const cache = await caches.open(CACHE);
|
const cache = await caches.open(CACHE);
|
||||||
|
|
||||||
//serve build files from cache;
|
// Serve static assets from cache first
|
||||||
if (ASSETS.includes(url.pathname)) {
|
if (ESSENTIAL_ASSETS.includes(url.pathname)) {
|
||||||
const cacheResponse = await cache.match(url.pathname);
|
const cacheResponse = await cache.match(url.pathname);
|
||||||
if (cacheResponse) {
|
if (cacheResponse) {
|
||||||
return cacheResponse;
|
return cacheResponse;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// try the network first
|
|
||||||
|
// Network-first strategy for other requests
|
||||||
try {
|
try {
|
||||||
const response = await fetch(event.request);
|
const response = await fetch(event.request);
|
||||||
const isNotExtension = url.protocol === "http:";
|
|
||||||
const isSuccess = response.status === 200;
|
|
||||||
|
|
||||||
if (isNotExtension && isSuccess) {
|
// Cache successful responses
|
||||||
cache.put(event.request, response.clone());
|
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;
|
return response;
|
||||||
} catch {
|
} catch (error) {
|
||||||
//fall back to cache
|
// Fallback to cache if network fails
|
||||||
const cachedResponse = await cache.match(url.pathname);
|
const cachedResponse = await cache.match(event.request);
|
||||||
if (cachedResponse) {
|
if (cachedResponse) {
|
||||||
return 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) => {
|
self.addEventListener("message", (event) => {
|
||||||
|
// Handle skip waiting
|
||||||
if (event.data && event.data.type === "SKIP_WAITING") {
|
if (event.data && event.data.type === "SKIP_WAITING") {
|
||||||
self.skipWaiting();
|
self.skipWaiting();
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
|
// Handle cache update
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
if (event.data && event.data.type === "CACHE_URLS") {
|
||||||
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(
|
event.waitUntil(
|
||||||
registration.showNotification('Stocknear', {
|
caches.open(CACHE)
|
||||||
body: payload,
|
.then((cache) => cache.addAll(event.data.payload))
|
||||||
icon: '/pwa-192x192.png',
|
.catch((error) => console.error('Service worker: Cache update failed:', error))
|
||||||
})
|
|
||||||
);
|
);
|
||||||
} as EventListener);
|
}
|
||||||
|
});
|
||||||
@ -8,19 +8,22 @@
|
|||||||
"description": "Clear & Simple Market Insight",
|
"description": "Clear & Simple Market Insight",
|
||||||
"icons": [
|
"icons": [
|
||||||
{
|
{
|
||||||
"src": "pwa-64x64.png",
|
"src": "/pwa-64x64.png",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"sizes": "64x64"
|
"sizes": "64x64",
|
||||||
|
"purpose": "any maskable"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "pwa-192x192.png",
|
"src": "/pwa-192x192.png",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"sizes": "192x192"
|
"sizes": "192x192",
|
||||||
|
"purpose": "any maskable"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"src": "pwa-512x512.png",
|
"src": "/pwa-512x512.png",
|
||||||
"type": "image/png",
|
"type": "image/png",
|
||||||
"sizes": "512x512"
|
"sizes": "512x512",
|
||||||
|
"purpose": "any maskable"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user