Web-Push mit VAPID und Erinnerungs-Endpoint
This commit is contained in:
parent
67a1614081
commit
b50267e4f0
24 changed files with 1703 additions and 50 deletions
|
|
@ -59,6 +59,7 @@
|
|||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
|
|
@ -724,6 +725,28 @@ a .ico, button .ico { pointer-events: none; }
|
|||
/* --------------------------------------------------------------- Account */
|
||||
.account-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; align-items: start; }
|
||||
|
||||
.ico--inline { display: inline-block; width: 18px; height: 18px; vertical-align: -3px; margin-right: 2px; }
|
||||
.push-card { margin-top: 16px; }
|
||||
.push-browser-hint {
|
||||
display: flex; align-items: flex-start; gap: 11px;
|
||||
padding: 13px 15px; border-radius: 12px;
|
||||
background: var(--ice-50); border: 1px solid var(--ice-200); color: var(--brand-800);
|
||||
font-size: .86rem;
|
||||
}
|
||||
.push-browser-hint .ico { width: 20px; height: 20px; margin-top: 1px; }
|
||||
.push-browser-hint p { color: var(--ink-2); margin-top: 3px; }
|
||||
.push-controls { display: grid; gap: 12px; }
|
||||
.push-controls[hidden] { display: none; }
|
||||
.push-toggle { width: 100%; padding: 14px 15px; }
|
||||
.push-toggle > span { display: flex; flex-direction: column; gap: 2px; }
|
||||
.push-toggle strong { font-size: .9rem; color: var(--ink); }
|
||||
.push-toggle small { font-size: .77rem; color: var(--muted); font-weight: 500; }
|
||||
.push-status { min-height: 0; font-size: .82rem; color: var(--muted); }
|
||||
.push-status:empty { display: none; }
|
||||
.push-status.is-error { color: #9e2f25; font-weight: 600; }
|
||||
.push-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.push-actions .muted { font-size: .76rem; }
|
||||
|
||||
/* --------------------------------------------------------------- Auth */
|
||||
.auth-page { background: var(--white); margin: 0; }
|
||||
.auth-shell { display: grid; grid-template-columns: 1.05fr .95fr; min-height: 100vh; }
|
||||
|
|
|
|||
|
|
@ -524,3 +524,209 @@
|
|||
});
|
||||
});
|
||||
})();
|
||||
|
||||
/* ------------------------------------------------------- Web-Push (VAPID) */
|
||||
(() => {
|
||||
const card = document.querySelector('[data-push]');
|
||||
if (!card) return;
|
||||
|
||||
const toggle = card.querySelector('[data-push-toggle]');
|
||||
const controls = card.querySelector('[data-push-controls]');
|
||||
const browserHint = card.querySelector('[data-push-browser-hint]');
|
||||
const statusEl = card.querySelector('[data-push-status]');
|
||||
const testButton = card.querySelector('[data-push-test]');
|
||||
const countEl = card.querySelector('[data-push-count]');
|
||||
const vapidKey = card.dataset.vapidKey || '';
|
||||
const subscribeUrl = card.dataset.subscribeUrl;
|
||||
const unsubscribeUrl = card.dataset.unsubscribeUrl;
|
||||
const testUrl = card.dataset.testUrl;
|
||||
const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
|
||||
if (!toggle || !controls || !statusEl || !testButton || !subscribeUrl || !unsubscribeUrl || !testUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const standalone = window.matchMedia('(display-mode: standalone)').matches
|
||||
|| window.navigator.standalone === true;
|
||||
const supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window;
|
||||
|
||||
const setStatus = (text, isError = false) => {
|
||||
statusEl.textContent = text || '';
|
||||
statusEl.classList.toggle('is-error', isError);
|
||||
};
|
||||
|
||||
const updateCount = (count) => {
|
||||
if (!countEl || typeof count !== 'number') return;
|
||||
countEl.textContent = count > 0
|
||||
? `${count} Gerät${count === 1 ? '' : 'e'} aktiv`
|
||||
: 'nicht aktiviert';
|
||||
countEl.classList.toggle('pill--green', count > 0);
|
||||
countEl.classList.toggle('pill--grey', count === 0);
|
||||
};
|
||||
|
||||
const postJson = async (url, payload) => {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json;charset=UTF-8',
|
||||
'Accept': 'application/json',
|
||||
'X-Requested-With': 'fetch',
|
||||
'X-CSRF-Token': csrf
|
||||
},
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(payload || {})
|
||||
});
|
||||
const type = response.headers.get('content-type') || '';
|
||||
if (!type.includes('application/json')) {
|
||||
throw new Error('Die Sitzung ist abgelaufen. Bitte die Seite neu laden.');
|
||||
}
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `Server meldet HTTP ${response.status}.`);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const keyToBytes = (base64url) => {
|
||||
const padding = '='.repeat((4 - (base64url.length % 4)) % 4);
|
||||
const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const raw = window.atob(base64);
|
||||
const bytes = new Uint8Array(raw.length);
|
||||
for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
if (!supported || !vapidKey) {
|
||||
if (browserHint) {
|
||||
browserHint.innerHTML = '<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg><div><strong>Push wird von diesem Browser nicht unterstützt.</strong><p>Bitte die installierte App auf einem aktuellen Android-Gerät oder iPhone verwenden.</p></div>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!standalone) {
|
||||
controls.hidden = true;
|
||||
if (browserHint) browserHint.hidden = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (browserHint) browserHint.hidden = true;
|
||||
controls.hidden = false;
|
||||
|
||||
let registration = null;
|
||||
|
||||
const getRegistration = async () => {
|
||||
if (!registration) {
|
||||
registration = await navigator.serviceWorker.ready;
|
||||
}
|
||||
return registration;
|
||||
};
|
||||
|
||||
const getSubscription = async () => {
|
||||
const reg = await getRegistration();
|
||||
return reg.pushManager.getSubscription();
|
||||
};
|
||||
|
||||
const subscribe = async () => {
|
||||
const reg = await getRegistration();
|
||||
let subscription = await reg.pushManager.getSubscription();
|
||||
if (subscription) return subscription;
|
||||
|
||||
try {
|
||||
subscription = await reg.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: keyToBytes(vapidKey)
|
||||
});
|
||||
} catch (error) {
|
||||
if (error && error.name === 'InvalidStateError') {
|
||||
const old = await reg.pushManager.getSubscription();
|
||||
if (old) await old.unsubscribe();
|
||||
subscription = await reg.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: keyToBytes(vapidKey)
|
||||
});
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return subscription;
|
||||
};
|
||||
|
||||
const syncExisting = async () => {
|
||||
const subscription = await getSubscription();
|
||||
toggle.checked = !!subscription;
|
||||
testButton.hidden = !subscription;
|
||||
if (subscription) {
|
||||
// Gerät beim Öffnen dem aktuell angemeldeten Konto zuordnen.
|
||||
try {
|
||||
const data = await postJson(subscribeUrl, subscription.toJSON());
|
||||
updateCount(data.count);
|
||||
} catch (error) {
|
||||
setStatus('Das bestehende Abo konnte nicht zugeordnet werden. Bitte aus- und wieder einschalten.', true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Notification.permission === 'denied') {
|
||||
toggle.disabled = true;
|
||||
setStatus('Benachrichtigungen sind für diese App blockiert. Bitte in den Systemeinstellungen erlauben.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
syncExisting().catch(() => {
|
||||
setStatus('Push konnte nicht initialisiert werden.', true);
|
||||
});
|
||||
|
||||
toggle.addEventListener('change', async () => {
|
||||
toggle.disabled = true;
|
||||
testButton.disabled = true;
|
||||
setStatus(toggle.checked ? 'Erinnerungen werden aktiviert …' : 'Erinnerungen werden deaktiviert …');
|
||||
try {
|
||||
if (toggle.checked) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
throw new Error('Benachrichtigungen wurden nicht erlaubt. Bitte in den Einstellungen freigeben.');
|
||||
}
|
||||
const subscription = await subscribe();
|
||||
const data = await postJson(subscribeUrl, subscription.toJSON());
|
||||
updateCount(data.count);
|
||||
testButton.hidden = false;
|
||||
setStatus('Aktiviert. Erinnerungen erscheinen jetzt auf diesem Gerät.');
|
||||
} else {
|
||||
const subscription = await getSubscription();
|
||||
const endpoint = subscription ? subscription.endpoint : '';
|
||||
if (subscription) {
|
||||
await subscription.unsubscribe();
|
||||
}
|
||||
const data = await postJson(unsubscribeUrl, { endpoint });
|
||||
updateCount(data.count);
|
||||
testButton.hidden = true;
|
||||
setStatus('Erinnerungen sind auf diesem Gerät ausgeschaltet.');
|
||||
}
|
||||
} catch (error) {
|
||||
const subscription = await getSubscription().catch(() => null);
|
||||
toggle.checked = !!subscription;
|
||||
testButton.hidden = !subscription;
|
||||
setStatus(error && error.message ? error.message : 'Aktion fehlgeschlagen.', true);
|
||||
} finally {
|
||||
toggle.disabled = false;
|
||||
testButton.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
testButton.addEventListener('click', async () => {
|
||||
if (testButton.disabled) return;
|
||||
testButton.disabled = true;
|
||||
setStatus('Test-Erinnerung wird gesendet …');
|
||||
try {
|
||||
const subscription = await getSubscription();
|
||||
if (!subscription) {
|
||||
throw new Error('Dieses Gerät ist noch nicht angemeldet.');
|
||||
}
|
||||
await postJson(testUrl, { endpoint: subscription.endpoint });
|
||||
setStatus('Test-Erinnerung gesendet. Sie sollte jetzt erscheinen.');
|
||||
} catch (error) {
|
||||
setStatus(error && error.message ? error.message : 'Test fehlgeschlagen.', true);
|
||||
} finally {
|
||||
testButton.disabled = false;
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
|
|
|||
51
web/sw.js
51
web/sw.js
|
|
@ -6,7 +6,7 @@
|
|||
* zwischengespeichert, damit niemand veraltete Buchungen sieht.
|
||||
*/
|
||||
|
||||
const VERSION = 'dic-v2';
|
||||
const VERSION = 'dic-v3';
|
||||
const CACHE = VERSION;
|
||||
const BASE = new URL(self.registration.scope).pathname.replace(/\/$/, '');
|
||||
|
||||
|
|
@ -138,3 +138,52 @@ self.addEventListener('fetch', (event) => {
|
|||
event.respondWith(cacheFirst(event, request));
|
||||
}
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------- Web-Push */
|
||||
self.addEventListener('push', (event) => {
|
||||
let data = {};
|
||||
try {
|
||||
data = event.data ? event.data.json() : {};
|
||||
} catch (error) {
|
||||
data = {};
|
||||
}
|
||||
|
||||
const title = data.title || 'Drink it cold – Erinnerung';
|
||||
const target = data.url || `${BASE}/reminders`;
|
||||
const options = {
|
||||
body: data.body || '',
|
||||
icon: data.icon || `${BASE}/assets/icons/icon-192.png`,
|
||||
badge: data.badge || `${BASE}/assets/icons/icon-192.png`,
|
||||
tag: data.tag || 'dic-reminder',
|
||||
lang: 'de',
|
||||
data: { url: target },
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
event.waitUntil(self.registration.showNotification(title, options));
|
||||
});
|
||||
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
event.notification.close();
|
||||
const raw = (event.notification.data && event.notification.data.url) || `${BASE}/reminders`;
|
||||
let target;
|
||||
try {
|
||||
const url = new URL(raw, self.location.origin);
|
||||
target = url.origin === self.location.origin ? url.href : `${self.location.origin}${BASE}/reminders`;
|
||||
} catch (error) {
|
||||
target = `${self.location.origin}${BASE}/reminders`;
|
||||
}
|
||||
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
|
||||
for (const client of list) {
|
||||
if (new URL(client.url).origin !== self.location.origin) continue;
|
||||
return client.focus().then(() => {
|
||||
if ('navigate' in client) return client.navigate(target);
|
||||
return client;
|
||||
});
|
||||
}
|
||||
return self.clients.openWindow(target);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue