Files
rosterchirp/frontend/public/sw.js
2026-03-23 12:07:52 -04:00

165 lines
6.4 KiB
JavaScript

// ── Firebase Messaging (background push for Android PWA) ──────────────────────
// Dynamically fetch Firebase config from backend to ensure consistency
importScripts('https://www.gstatic.com/firebasejs/10.14.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.14.1/firebase-messaging-compat.js');
let FIREBASE_CONFIG = null;
let VAPID_KEY = null;
// Fetch Firebase config and initialise messaging
let messaging = null;
let firebaseConfigPromise = fetch('/api/push/firebase-config')
.then(res => res.json())
.then(config => {
FIREBASE_CONFIG = {
apiKey: config.apiKey,
authDomain: config.authDomain || `${config.projectId}.firebaseapp.com`,
projectId: config.projectId,
storageBucket: config.storageBucket || `${config.projectId}.firebasestorage.app`,
messagingSenderId: config.messagingSenderId,
appId: config.appId
};
VAPID_KEY = config.vapidKey;
if (FIREBASE_CONFIG.apiKey) {
firebase.initializeApp(FIREBASE_CONFIG);
messaging = firebase.messaging();
console.log('[SW] Firebase initialized with dynamic config');
}
})
.catch(err => {
console.warn('[SW] Failed to fetch Firebase config:', err);
});
// ── Cache ─────────────────────────────────────────────────────────────────────
const CACHE_NAME = 'rosterchirp-v1';
const STATIC_ASSETS = ['/'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS))
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
)
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
const url = event.request.url;
if (url.includes('/api/') || url.includes('/socket.io/') || url.includes('/manifest.json')) {
return;
}
event.respondWith(
fetch(event.request).catch(() => caches.match(event.request))
);
});
// ── Badge counter ─────────────────────────────────────────────────────────────
let badgeCount = 0;
function showRosterChirpNotification(data) {
console.log('[SW] showRosterChirpNotification:', JSON.stringify(data));
badgeCount++;
if (self.navigator?.setAppBadge) self.navigator.setAppBadge(badgeCount).catch(() => {});
return self.registration.showNotification(data.title || 'New Message', {
body: data.body || '',
icon: '/icons/icon-192.png',
badge: '/icons/icon-192-maskable.png',
data: { url: data.url || '/' },
tag: data.groupId ? `rosterchirp-group-${data.groupId}` : 'rosterchirp-message',
renotify: true,
vibrate: [200, 100, 200],
});
}
// ── FCM background messages ───────────────────────────────────────────────────
// Wait for Firebase config to be loaded before setting up message handler
firebaseConfigPromise.then(() => {
if (messaging) {
messaging.onBackgroundMessage((payload) => {
console.log('[SW] onBackgroundMessage received, data:', JSON.stringify(payload.data));
return showRosterChirpNotification(payload.data || {});
});
} else {
console.warn('[SW] Firebase messaging not initialised — push notifications disabled');
}
});
// ── Raw push event (fallback for Android) ─────────────────────────────────────
// Android Chrome sometimes doesn't properly trigger Firebase's onBackgroundMessage
// This fallback ensures notifications are displayed even if Firebase SDK fails
self.addEventListener('push', (event) => {
console.log('[SW] push event received, hasData:', !!event.data, 'text:', event.data?.text?.()?.slice(0, 120));
// Try to handle the push event directly as a fallback
if (event.data) {
try {
const data = event.data.json();
console.log('[SW] Push data parsed:', JSON.stringify(data));
// If this is a Firebase message with data payload, show notification
if (data.data || (data.title && data.body)) {
const notificationData = data.data || data;
return showRosterChirpNotification(notificationData);
}
} catch (e) {
console.warn('[SW] Failed to parse push data:', e);
// Try to show a basic notification with the raw text
const text = event.data.text();
if (text) {
return self.registration.showNotification('RosterChirp', {
body: text.slice(0, 100),
icon: '/icons/icon-192.png',
badge: '/icons/icon-192-maskable.png',
tag: 'rosterchirp-fallback',
});
}
}
}
});
// ── Notification click ────────────────────────────────────────────────────────
self.addEventListener('notificationclick', (event) => {
event.notification.close();
badgeCount = 0;
if (self.navigator?.clearAppBadge) self.navigator.clearAppBadge().catch(() => {});
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
const url = event.notification.data?.url || '/';
for (const client of clientList) {
if (client.url.includes(self.location.origin) && 'focus' in client) {
client.focus();
return;
}
}
return clients.openWindow(url);
})
);
});
// ── Badge control messages from main thread ───────────────────────────────────
self.addEventListener('message', (event) => {
if (event.data?.type === 'CLEAR_BADGE') {
badgeCount = 0;
if (self.navigator?.clearAppBadge) self.navigator.clearAppBadge().catch(() => {});
}
if (event.data?.type === 'SET_BADGE') {
badgeCount = event.data.count || 0;
if (self.navigator?.setAppBadge) {
if (badgeCount > 0) {
self.navigator.setAppBadge(badgeCount).catch(() => {});
} else {
self.navigator.clearAppBadge().catch(() => {});
}
}
}
});