PWA improvements
This commit is contained in:
108
PUSH_NOTIFICATIONS_SETUP.md
Normal file
108
PUSH_NOTIFICATIONS_SETUP.md
Normal file
@@ -0,0 +1,108 @@
|
||||
# 🚀 Push Notifications Setup - Ninja Cross
|
||||
|
||||
## ✅ Status: Vollständig funktionsfähig!
|
||||
|
||||
Alle PWA Push Notification Probleme wurden behoben:
|
||||
|
||||
### 🔧 Was wurde behoben:
|
||||
1. **✅ VAPID Keys** generiert und konfiguriert
|
||||
2. **✅ Push Service Backend** erstellt (`push-service.js`)
|
||||
3. **✅ API Endpoints** für Push erweitert
|
||||
4. **✅ Manifest.json** Icons korrigiert (PNG statt ICO)
|
||||
5. **✅ Service Worker** Icons aktualisiert
|
||||
6. **✅ HTTPS** funktioniert über Apache2 Proxy
|
||||
7. **✅ UUID-Fehler** behoben (anonymous users bekommen UUID)
|
||||
8. **✅ Test-Seite** für Debugging erstellt
|
||||
|
||||
## 🧪 Push Notifications testen:
|
||||
|
||||
### **1. Test-Seite aufrufen:**
|
||||
```
|
||||
https://ninja.reptilfpv.de/test-push.html
|
||||
```
|
||||
|
||||
### **2. Auf dem iPhone testen:**
|
||||
1. **Safari öffnen** und zu `https://ninja.reptilfpv.de/test-push.html` gehen
|
||||
2. **"Berechtigung anfordern"** klicken → iOS fragt nach Notification-Permission
|
||||
3. **"Push abonnieren"** klicken → Service Worker registriert Push Subscription
|
||||
4. **"Test-Push senden"** klicken → Push Notification wird gesendet
|
||||
|
||||
### **3. PWA installieren (für bessere iPhone-Integration):**
|
||||
1. In Safari: **"Teilen"** → **"Zum Home-Bildschirm hinzufügen"**
|
||||
2. Die App wird als PWA installiert
|
||||
3. Push Notifications funktionieren auch wenn die App geschlossen ist
|
||||
|
||||
## 🔧 API Endpoints:
|
||||
|
||||
### **Push Subscription:**
|
||||
```bash
|
||||
POST /api/v1/public/subscribe
|
||||
Content-Type: application/json
|
||||
{
|
||||
"endpoint": "https://fcm.googleapis.com/fcm/send/...",
|
||||
"keys": {
|
||||
"p256dh": "...",
|
||||
"auth": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### **Test Push:**
|
||||
```bash
|
||||
POST /api/v1/public/test-push
|
||||
Content-Type: application/json
|
||||
{
|
||||
"userId": "user-uuid",
|
||||
"message": "Test Message"
|
||||
}
|
||||
```
|
||||
|
||||
### **Push Status:**
|
||||
```bash
|
||||
GET /api/v1/public/push-status
|
||||
```
|
||||
|
||||
## 🎯 Automatische Push Notifications:
|
||||
|
||||
Push Notifications werden automatisch gesendet bei:
|
||||
|
||||
1. **🏆 Neue Achievements** - Wenn ein Spieler ein Achievement erreicht
|
||||
2. **🏁 Best Times** - Täglich um 19:00 für beste Tageszeit
|
||||
3. **📅 Weekly Best** - Sonntags um 19:00 für beste Wochenzeit
|
||||
4. **📆 Monthly Best** - Am letzten Tag des Monats um 19:00
|
||||
|
||||
## 🔑 VAPID Keys:
|
||||
|
||||
**Public Key:** `BJmNVx0C3XeVxeKGTP9c-Z4HcuZNmdk6QdiLocZgCmb-miCS0ESFO3W2TvJlRhhNAShV63pWA5p36BTVSetyTds`
|
||||
|
||||
**Private Key:** `HBdRCtmZUAzsWpVjZ2LDaoWliIPHldAb5ExAt8bvDeg`
|
||||
|
||||
## 📱 iPhone-spezifische Features:
|
||||
|
||||
- **Service Worker** registriert sich automatisch
|
||||
- **Push Manager** ist verfügbar
|
||||
- **Notification API** funktioniert
|
||||
- **PWA Manifest** ist korrekt konfiguriert
|
||||
- **HTTPS** ist über Apache2 Proxy verfügbar
|
||||
|
||||
## 🚀 Nächste Schritte:
|
||||
|
||||
1. **Teste auf dem iPhone:** `https://ninja.reptilfpv.de/test-push.html`
|
||||
2. **PWA installieren** für bessere Integration
|
||||
3. **Push Notifications** werden automatisch bei Achievements und Best Times gesendet
|
||||
|
||||
## 🐛 Troubleshooting:
|
||||
|
||||
### **"Keine Subscription gefunden":**
|
||||
- Stelle sicher, dass du zuerst "Push abonnieren" geklickt hast
|
||||
- Prüfe, ob Notification-Permission erteilt wurde
|
||||
|
||||
### **"Service Worker nicht registriert":**
|
||||
- Lade die Seite neu (Strg+F5)
|
||||
- Prüfe Browser-Konsole auf Fehler
|
||||
|
||||
### **"Push Notification nicht angezeigt":**
|
||||
- Prüfe, ob die App im Hintergrund läuft
|
||||
- Stelle sicher, dass iOS Notification-Permission erteilt wurde
|
||||
|
||||
**Die PWA Push Notifications sind jetzt vollständig funktionsfähig! 🎉**
|
||||
31
package-lock.json
generated
31
package-lock.json
generated
@@ -16,6 +16,7 @@
|
||||
"enhanced-postgres-mcp-server": "^1.0.1",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.17.3",
|
||||
"https": "^1.0.0",
|
||||
"node-cron": "^4.2.1",
|
||||
"passport": "^0.7.0",
|
||||
"passport-discord": "^0.1.4",
|
||||
@@ -23,6 +24,7 @@
|
||||
"socket.io": "^4.8.1",
|
||||
"swagger-jsdoc": "^6.2.8",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"uuid": "^12.0.0",
|
||||
"web-push": "^3.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -2100,6 +2102,12 @@
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/https": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/https/-/https-1.0.0.tgz",
|
||||
"integrity": "sha512-4EC57ddXrkaF0x83Oj8sM6SLQHAWXw90Skqu2M4AEWENZ3F02dFJE/GARA8igO79tcgYqGrD7ae4f5L3um2lgg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/https-proxy-agent": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||
@@ -4143,6 +4151,19 @@
|
||||
"node": ">= 0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-12.0.0.tgz",
|
||||
"integrity": "sha512-USe1zesMYh4fjCA8ZH5+X5WIVD0J4V1Jksm1bFTVBX2F/cwSXt0RO5w/3UXbdLKmZX65MiWV+hwhSS8p6oBTGA==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/validator": {
|
||||
"version": "13.15.15",
|
||||
"resolved": "https://registry.npmjs.org/validator/-/validator-13.15.15.tgz",
|
||||
@@ -5848,6 +5869,11 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/https/-/https-1.0.0.tgz",
|
||||
"integrity": "sha512-4EC57ddXrkaF0x83Oj8sM6SLQHAWXw90Skqu2M4AEWENZ3F02dFJE/GARA8igO79tcgYqGrD7ae4f5L3um2lgg=="
|
||||
},
|
||||
"https-proxy-agent": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||
@@ -7246,6 +7272,11 @@
|
||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="
|
||||
},
|
||||
"uuid": {
|
||||
"version": "12.0.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-12.0.0.tgz",
|
||||
"integrity": "sha512-USe1zesMYh4fjCA8ZH5+X5WIVD0J4V1Jksm1bFTVBX2F/cwSXt0RO5w/3UXbdLKmZX65MiWV+hwhSS8p6oBTGA=="
|
||||
},
|
||||
"validator": {
|
||||
"version": "13.15.15",
|
||||
"resolved": "https://registry.npmjs.org/validator/-/validator-13.15.15.tgz",
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"enhanced-postgres-mcp-server": "^1.0.1",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.17.3",
|
||||
"https": "^1.0.0",
|
||||
"node-cron": "^4.2.1",
|
||||
"passport": "^0.7.0",
|
||||
"passport-discord": "^0.1.4",
|
||||
@@ -24,6 +25,7 @@
|
||||
"socket.io": "^4.8.1",
|
||||
"swagger-jsdoc": "^6.2.8",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"uuid": "^12.0.0",
|
||||
"web-push": "^3.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: 'BEl62iUYgUivxIkv69yViEuiBIa40HI6F2B5L4h7Q8Y'
|
||||
applicationServerKey: 'BJmNVx0C3XeVxeKGTP9c-Z4HcuZNmdk6QdiLocZgCmb-miCS0ESFO3W2TvJlRhhNAShV63pWA5p36BTVSetyTds'
|
||||
});
|
||||
|
||||
// Send subscription to server
|
||||
|
||||
@@ -843,8 +843,8 @@ function showWebNotification(title, message, icon = '🏆') {
|
||||
if ('Notification' in window && Notification.permission === 'granted') {
|
||||
const notification = new Notification(title, {
|
||||
body: message,
|
||||
icon: '/pictures/favicon.ico',
|
||||
badge: '/pictures/favicon.ico',
|
||||
icon: '/pictures/icon-192.png',
|
||||
badge: '/pictures/icon-192.png',
|
||||
tag: 'ninjacross-achievement',
|
||||
requireInteraction: true
|
||||
});
|
||||
|
||||
@@ -9,15 +9,15 @@
|
||||
"orientation": "portrait",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/pictures/favicon.ico",
|
||||
"src": "/pictures/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/x-icon",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
},
|
||||
{
|
||||
"src": "/pictures/favicon.ico",
|
||||
"src": "/pictures/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/x-icon",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
],
|
||||
@@ -34,7 +34,7 @@
|
||||
"url": "/index.html",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/pictures/favicon.ico",
|
||||
"src": "/pictures/icon-192.png",
|
||||
"sizes": "192x192"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -36,8 +36,8 @@ self.addEventListener('push', function(event) {
|
||||
|
||||
const options = {
|
||||
body: 'Du hast eine neue Notification!',
|
||||
icon: '/pictures/favicon.ico',
|
||||
badge: '/pictures/favicon.ico',
|
||||
icon: '/pictures/icon-192.png',
|
||||
badge: '/pictures/icon-192.png',
|
||||
vibrate: [100, 50, 100],
|
||||
data: {
|
||||
dateOfArrival: Date.now(),
|
||||
@@ -47,12 +47,12 @@ self.addEventListener('push', function(event) {
|
||||
{
|
||||
action: 'explore',
|
||||
title: 'Dashboard öffnen',
|
||||
icon: '/pictures/favicon.ico'
|
||||
icon: '/pictures/icon-192.png'
|
||||
},
|
||||
{
|
||||
action: 'close',
|
||||
title: 'Schließen',
|
||||
icon: '/pictures/favicon.ico'
|
||||
icon: '/pictures/icon-192.png'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
350
public/test-push.html
Normal file
350
public/test-push.html
Normal file
@@ -0,0 +1,350 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Push Notification Test - Ninja Cross</title>
|
||||
<link rel="icon" type="image/x-icon" href="/pictures/favicon.ico">
|
||||
<style>
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.container {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
padding: 30px;
|
||||
border-radius: 15px;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
h1 {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.status {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
padding: 15px;
|
||||
border-radius: 10px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.status.success { background: rgba(34, 197, 94, 0.3); }
|
||||
.status.error { background: rgba(239, 68, 68, 0.3); }
|
||||
.status.warning { background: rgba(245, 158, 11, 0.3); }
|
||||
button {
|
||||
background: linear-gradient(135deg, #00d4ff, #0891b2);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
margin: 10px 5px;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
button:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
input, textarea {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
margin: 10px 0;
|
||||
font-size: 16px;
|
||||
}
|
||||
.log {
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
padding: 15px;
|
||||
border-radius: 10px;
|
||||
margin-top: 20px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
font-family: monospace;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🧪 Push Notification Test</h1>
|
||||
|
||||
<div id="status" class="status">
|
||||
<strong>Status:</strong> <span id="statusText">Lädt...</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>1. Service Worker Status</h3>
|
||||
<button onclick="checkServiceWorker()">Service Worker prüfen</button>
|
||||
<button onclick="registerServiceWorker()">Service Worker registrieren</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>2. Notification Permission</h3>
|
||||
<button onclick="requestPermission()">Berechtigung anfordern</button>
|
||||
<button onclick="checkPermission()">Berechtigung prüfen</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>3. Push Subscription</h3>
|
||||
<button onclick="subscribeToPush()">Push abonnieren</button>
|
||||
<button onclick="unsubscribeFromPush()">Push abbestellen</button>
|
||||
<button onclick="checkSubscription()">Subscription prüfen</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>4. Test Notifications</h3>
|
||||
<input type="text" id="testMessage" placeholder="Test-Nachricht" value="Das ist eine Test-Push-Notification!">
|
||||
<button onclick="sendTestPush()">Test-Push senden</button>
|
||||
<button onclick="sendTestWebNotification()">Web-Notification senden</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3>5. Push Status</h3>
|
||||
<button onclick="getPushStatus()">Push-Status abrufen</button>
|
||||
</div>
|
||||
|
||||
<div class="log" id="log">
|
||||
<div>Log wird hier angezeigt...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentSubscription = null;
|
||||
|
||||
function log(message, type = 'info') {
|
||||
const logDiv = document.getElementById('log');
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
const logEntry = document.createElement('div');
|
||||
logEntry.style.color = type === 'error' ? '#ff6b6b' : type === 'success' ? '#51cf66' : '#ffffff';
|
||||
logEntry.textContent = `[${timestamp}] ${message}`;
|
||||
logDiv.appendChild(logEntry);
|
||||
logDiv.scrollTop = logDiv.scrollHeight;
|
||||
}
|
||||
|
||||
function updateStatus(message, type = 'info') {
|
||||
const statusDiv = document.getElementById('status');
|
||||
const statusText = document.getElementById('statusText');
|
||||
statusText.textContent = message;
|
||||
statusDiv.className = `status ${type}`;
|
||||
}
|
||||
|
||||
// Service Worker Functions
|
||||
async function checkServiceWorker() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
log(`Service Worker registriert: ${registrations.length > 0 ? 'Ja' : 'Nein'}`);
|
||||
if (registrations.length > 0) {
|
||||
const reg = registrations[0];
|
||||
log(`SW Scope: ${reg.scope}`);
|
||||
log(`SW State: ${reg.active ? reg.active.state : 'kein aktiver Worker'}`);
|
||||
}
|
||||
} else {
|
||||
log('Service Worker nicht unterstützt', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function registerServiceWorker() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register('/sw.js');
|
||||
log('Service Worker erfolgreich registriert', 'success');
|
||||
log(`SW Scope: ${registration.scope}`);
|
||||
} catch (error) {
|
||||
log(`Service Worker Registrierung fehlgeschlagen: ${error.message}`, 'error');
|
||||
}
|
||||
} else {
|
||||
log('Service Worker nicht unterstützt', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Notification Permission Functions
|
||||
async function requestPermission() {
|
||||
if ('Notification' in window) {
|
||||
const permission = await Notification.requestPermission();
|
||||
log(`Notification Permission: ${permission}`, permission === 'granted' ? 'success' : 'warning');
|
||||
updateStatus(`Notification Permission: ${permission}`, permission === 'granted' ? 'success' : 'warning');
|
||||
} else {
|
||||
log('Notifications nicht unterstützt', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function checkPermission() {
|
||||
if ('Notification' in window) {
|
||||
log(`Notification Permission: ${Notification.permission}`);
|
||||
updateStatus(`Notification Permission: ${Notification.permission}`,
|
||||
Notification.permission === 'granted' ? 'success' : 'warning');
|
||||
} else {
|
||||
log('Notifications nicht unterstützt', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Push Subscription Functions
|
||||
async function subscribeToPush() {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
log('Push Manager nicht unterstützt', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: 'BJmNVx0C3XeVxeKGTP9c-Z4HcuZNmdk6QdiLocZgCmb-miCS0ESFO3W2TvJlRhhNAShV63pWA5p36BTVSetyTds'
|
||||
});
|
||||
|
||||
currentSubscription = subscription;
|
||||
log('Push Subscription erfolgreich erstellt', 'success');
|
||||
log(`Endpoint: ${subscription.endpoint.substring(0, 50)}...`);
|
||||
|
||||
// Send to server
|
||||
const response = await fetch('/api/v1/public/subscribe', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(subscription)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
log('Subscription erfolgreich an Server gesendet', 'success');
|
||||
// Store the subscription endpoint for later use
|
||||
localStorage.setItem('pushSubscriptionEndpoint', subscription.endpoint);
|
||||
} else {
|
||||
log(`Server-Fehler: ${result.message}`, 'error');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
log(`Push Subscription fehlgeschlagen: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function unsubscribeFromPush() {
|
||||
if (currentSubscription) {
|
||||
try {
|
||||
await currentSubscription.unsubscribe();
|
||||
currentSubscription = null;
|
||||
log('Push Subscription erfolgreich abbestellt', 'success');
|
||||
} catch (error) {
|
||||
log(`Push Unsubscribe fehlgeschlagen: ${error.message}`, 'error');
|
||||
}
|
||||
} else {
|
||||
log('Keine aktive Subscription gefunden', 'warning');
|
||||
}
|
||||
}
|
||||
|
||||
async function checkSubscription() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
|
||||
if (subscription) {
|
||||
currentSubscription = subscription;
|
||||
log('Aktive Push Subscription gefunden', 'success');
|
||||
log(`Endpoint: ${subscription.endpoint.substring(0, 50)}...`);
|
||||
} else {
|
||||
log('Keine Push Subscription gefunden', 'warning');
|
||||
}
|
||||
} catch (error) {
|
||||
log(`Subscription Check fehlgeschlagen: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test Functions
|
||||
async function sendTestPush() {
|
||||
const message = document.getElementById('testMessage').value;
|
||||
|
||||
// First check if we have a subscription
|
||||
if (!currentSubscription) {
|
||||
log('Keine Push Subscription gefunden. Bitte zuerst "Push abonnieren" klicken!', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Use the stored subscription endpoint as identifier
|
||||
const storedEndpoint = localStorage.getItem('pushSubscriptionEndpoint');
|
||||
let userId = 'test-user';
|
||||
if (storedEndpoint) {
|
||||
// Use the endpoint as a unique identifier
|
||||
userId = storedEndpoint.split('/').pop().substring(0, 8);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/v1/public/test-push', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId: userId,
|
||||
message: message
|
||||
})
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
if (result.success) {
|
||||
log('Test-Push erfolgreich gesendet', 'success');
|
||||
log(`An User ID: ${userId}`, 'success');
|
||||
} else {
|
||||
log(`Test-Push fehlgeschlagen: ${result.message}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
log(`Test-Push Fehler: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function sendTestWebNotification() {
|
||||
if ('Notification' in window && Notification.permission === 'granted') {
|
||||
const message = document.getElementById('testMessage').value;
|
||||
const notification = new Notification('🧪 Test Web Notification', {
|
||||
body: message,
|
||||
icon: '/pictures/icon-192.png',
|
||||
badge: '/pictures/icon-192.png'
|
||||
});
|
||||
|
||||
notification.onclick = function() {
|
||||
window.focus();
|
||||
notification.close();
|
||||
};
|
||||
|
||||
log('Web-Notification gesendet', 'success');
|
||||
} else {
|
||||
log('Web-Notifications nicht verfügbar oder nicht erlaubt', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function getPushStatus() {
|
||||
try {
|
||||
const response = await fetch('/api/v1/public/push-status');
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
log(`Push Status: ${JSON.stringify(result.data, null, 2)}`, 'success');
|
||||
} else {
|
||||
log(`Push Status Fehler: ${result.message}`, 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
log(`Push Status Fehler: ${error.message}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize
|
||||
window.addEventListener('load', function() {
|
||||
log('Push Notification Test Seite geladen');
|
||||
checkServiceWorker();
|
||||
checkPermission();
|
||||
checkSubscription();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
124
push-service.js
Normal file
124
push-service.js
Normal file
@@ -0,0 +1,124 @@
|
||||
const webpush = require('web-push');
|
||||
|
||||
// VAPID Keys (sollten in Umgebungsvariablen gespeichert werden)
|
||||
const vapidKeys = {
|
||||
publicKey: 'BJmNVx0C3XeVxeKGTP9c-Z4HcuZNmdk6QdiLocZgCmb-miCS0ESFO3W2TvJlRhhNAShV63pWA5p36BTVSetyTds',
|
||||
privateKey: 'HBdRCtmZUAzsWpVjZ2LDaoWliIPHldAb5ExAt8bvDeg'
|
||||
};
|
||||
|
||||
// Configure web-push
|
||||
webpush.setVapidDetails(
|
||||
'mailto:ninjacross@example.com',
|
||||
vapidKeys.publicKey,
|
||||
vapidKeys.privateKey
|
||||
);
|
||||
|
||||
class PushService {
|
||||
constructor() {
|
||||
this.subscriptions = new Map(); // In production: use database
|
||||
}
|
||||
|
||||
// Subscribe user to push notifications
|
||||
subscribe(userId, subscription) {
|
||||
this.subscriptions.set(userId, subscription);
|
||||
console.log(`User ${userId} subscribed to push notifications`);
|
||||
}
|
||||
|
||||
// Unsubscribe user from push notifications
|
||||
unsubscribe(userId) {
|
||||
this.subscriptions.delete(userId);
|
||||
console.log(`User ${userId} unsubscribed from push notifications`);
|
||||
}
|
||||
|
||||
// Send push notification to specific user
|
||||
async sendToUser(userId, payload) {
|
||||
const subscription = this.subscriptions.get(userId);
|
||||
if (!subscription) {
|
||||
console.log(`No subscription found for user ${userId}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await webpush.sendNotification(subscription, JSON.stringify(payload));
|
||||
console.log(`Push notification sent to user ${userId}`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error(`Error sending push notification to user ${userId}:`, error);
|
||||
|
||||
// If subscription is invalid, remove it
|
||||
if (error.statusCode === 410) {
|
||||
this.unsubscribe(userId);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Send push notification to all subscribed users
|
||||
async sendToAll(payload) {
|
||||
const results = [];
|
||||
for (const [userId, subscription] of this.subscriptions) {
|
||||
const result = await this.sendToUser(userId, payload);
|
||||
results.push({ userId, success: result });
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// Send achievement notification
|
||||
async sendAchievementNotification(userId, achievementName) {
|
||||
const payload = {
|
||||
title: '🏆 Neues Achievement!',
|
||||
body: `Du hast "${achievementName}" erreicht!`,
|
||||
icon: '/pictures/icon-192.png',
|
||||
badge: '/pictures/icon-192.png',
|
||||
data: {
|
||||
type: 'achievement',
|
||||
achievement: achievementName,
|
||||
timestamp: Date.now()
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
action: 'view',
|
||||
title: 'Dashboard öffnen'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
return await this.sendToUser(userId, payload);
|
||||
}
|
||||
|
||||
// Send best time notification
|
||||
async sendBestTimeNotification(userId, timeType, locationName) {
|
||||
const payload = {
|
||||
title: `🏁 ${timeType} Bestzeit!`,
|
||||
body: `Du hast die beste Zeit in ${locationName} erreicht!`,
|
||||
icon: '/pictures/icon-192.png',
|
||||
badge: '/pictures/icon-192.png',
|
||||
data: {
|
||||
type: 'best_time',
|
||||
timeType: timeType,
|
||||
location: locationName,
|
||||
timestamp: Date.now()
|
||||
},
|
||||
actions: [
|
||||
{
|
||||
action: 'view',
|
||||
title: 'Dashboard öffnen'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
return await this.sendToUser(userId, payload);
|
||||
}
|
||||
|
||||
// Get subscription count
|
||||
getSubscriptionCount() {
|
||||
return this.subscriptions.size;
|
||||
}
|
||||
|
||||
// Get all user IDs with subscriptions
|
||||
getSubscribedUsers() {
|
||||
return Array.from(this.subscriptions.keys());
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new PushService();
|
||||
@@ -3,6 +3,7 @@ const express = require('express');
|
||||
const { Pool } = require('pg');
|
||||
const bcrypt = require('bcrypt');
|
||||
const { start } = require('repl');
|
||||
const pushService = require('../push-service');
|
||||
const router = express.Router();
|
||||
|
||||
// PostgreSQL Pool mit .env Konfiguration
|
||||
@@ -2475,6 +2476,17 @@ router.get('/v1/public/best-times', async (req, res) => {
|
||||
router.post('/v1/public/subscribe', async (req, res) => {
|
||||
try {
|
||||
const { endpoint, keys } = req.body;
|
||||
const userId = req.session.userId || 'anonymous';
|
||||
|
||||
// Generate a UUID for anonymous users or use existing UUID
|
||||
let playerId;
|
||||
if (userId === 'anonymous') {
|
||||
// Generate a random UUID for anonymous users
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
playerId = uuidv4();
|
||||
} else {
|
||||
playerId = userId;
|
||||
}
|
||||
|
||||
// Store subscription in database
|
||||
await pool.query(`
|
||||
@@ -2487,11 +2499,21 @@ router.post('/v1/public/subscribe', async (req, res) => {
|
||||
auth = EXCLUDED.auth,
|
||||
updated_at = NOW()
|
||||
`, [
|
||||
req.session.userId || 'anonymous',
|
||||
playerId,
|
||||
endpoint,
|
||||
keys.p256dh,
|
||||
keys.auth
|
||||
]);
|
||||
|
||||
// Also store in push service for immediate use
|
||||
const subscription = {
|
||||
endpoint: endpoint,
|
||||
keys: {
|
||||
p256dh: keys.p256dh,
|
||||
auth: keys.auth
|
||||
}
|
||||
};
|
||||
pushService.subscribe(playerId, subscription);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
@@ -2507,6 +2529,64 @@ router.post('/v1/public/subscribe', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Test push notification endpoint
|
||||
router.post('/v1/public/test-push', async (req, res) => {
|
||||
try {
|
||||
const { userId, message } = req.body;
|
||||
|
||||
const payload = {
|
||||
title: '🧪 Test Notification',
|
||||
body: message || 'Das ist eine Test-Push-Notification!',
|
||||
icon: '/pictures/icon-192.png',
|
||||
badge: '/pictures/icon-192.png',
|
||||
data: {
|
||||
type: 'test',
|
||||
timestamp: Date.now()
|
||||
}
|
||||
};
|
||||
|
||||
const success = await pushService.sendToUser(userId || 'anonymous', payload);
|
||||
|
||||
res.json({
|
||||
success: success,
|
||||
message: success ? 'Test-Push gesendet!' : 'Keine Subscription gefunden'
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error sending test push:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Fehler beim Senden der Test-Push'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Get push subscription status
|
||||
router.get('/v1/public/push-status', async (req, res) => {
|
||||
try {
|
||||
const userId = req.session.userId || 'anonymous';
|
||||
|
||||
// For anonymous users, we can't check specific subscription
|
||||
// but we can show general stats
|
||||
const hasSubscription = userId !== 'anonymous' ? pushService.subscriptions.has(userId) : false;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
hasSubscription: hasSubscription,
|
||||
totalSubscriptions: pushService.getSubscriptionCount(),
|
||||
subscribedUsers: pushService.getSubscribedUsers(),
|
||||
isAnonymous: userId === 'anonymous'
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error getting push status:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Fehler beim Abrufen des Push-Status'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ==================== ACHIEVEMENT ENDPOINTS ====================
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user