Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add push notifications with auto-generated VAPID keys
Murtaza Nasir90f816bcec52
diff --git a/docs/PUSH_NOTIFICATIONS_SETUP.md b/docs/PUSH_NOTIFICATIONS_SETUP.mdnew file mode 100644index 00000000..df4c824d--- /dev/null+++ b/docs/PUSH_NOTIFICATIONS_SETUP.md@@ -0,0 +1,324 @@+# Push Notifications Setup Guide++This guide explains how to complete the push notification setup for Speakr.++## Overview++The client-side push notification infrastructure is now complete. To enable push notifications, you need to:++1. Generate VAPID keys+2. Configure the client with the public key+3. Implement backend endpoints to store subscriptions and send notifications++## Step 1: Generate VAPID Keys++### Method A: Using web-push (Node.js)++```bash+npm install -g web-push+web-push generate-vapid-keys+```++### Method B: Using Python++```bash+pip install pywebpush+```++```python+from pywebpush import vapid_keys++vapid_keys = vapid_keys()+print("Public Key:", vapid_keys['publicKey'])+print("Private Key:", vapid_keys['privateKey'])+```++### Method C: Using pywebpush CLI++```bash+pywebpush generate-vapid-keys+```++**IMPORTANT:** Keep the private key secret! Never commit it to version control.++## Step 2: Configure Client++1. Open `static/js/config/push-config.js`+2. Set `ENABLED: true`+3. Add your VAPID public key to `VAPID_PUBLIC_KEY`+4. Update `CONTACT_INFO` with your admin email or website++```javascript+export const PUSH_CONFIG = {+ ENABLED: true,+ VAPID_PUBLIC_KEY: 'YOUR_PUBLIC_KEY_HERE',+ CONTACT_INFO: 'mailto:[email protected]'+};+```++## Step 3: Implement Backend Endpoints++### Required Backend Endpoints++#### 1. Store Push Subscription++**Endpoint:** `POST /api/push/subscribe`++**Purpose:** Save user's push subscription to database++**Request Body:**+```json+{+ "endpoint": "https://fcm.googleapis.com/fcm/send/...",+ "keys": {+ "p256dh": "...",+ "auth": "..."+ }+}+```++**Response:**+```json+{+ "success": true,+ "message": "Subscription saved"+}+```++**Implementation Example (Flask):**++```python+from flask import Blueprint, request, jsonify+from flask_login import login_required, current_user+from models import db, PushSubscription++push_bp = Blueprint('push', __name__)++@push_bp.route('/api/push/subscribe', methods=['POST'])+@login_required+def subscribe():+ """Store push subscription for current user"""+ subscription_data = request.json++ # Check if subscription already exists+ existing = PushSubscription.query.filter_by(+ user_id=current_user.id,+ endpoint=subscription_data['endpoint']+ ).first()++ if existing:+ return jsonify({'success': True, 'message': 'Already subscribed'})++ # Create new subscription+ subscription = PushSubscription(+ user_id=current_user.id,+ endpoint=subscription_data['endpoint'],+ p256dh_key=subscription_data['keys']['p256dh'],+ auth_key=subscription_data['keys']['auth']+ )++ db.session.add(subscription)+ db.session.commit()++ return jsonify({'success': True, 'message': 'Subscription saved'})+```++#### 2. Remove Push Subscription++**Endpoint:** `POST /api/push/unsubscribe`++**Purpose:** Remove user's push subscription from database++**Request Body:** Same as subscribe++**Response:**+```json+{+ "success": true,+ "message": "Subscription removed"+}+```++**Implementation Example:**++```python+@push_bp.route('/api/push/unsubscribe', methods=['POST'])+@login_required+def unsubscribe():+ """Remove push subscription for current user"""+ subscription_data = request.json++ subscription = PushSubscription.query.filter_by(+ user_id=current_user.id,+ endpoint=subscription_data['endpoint']+ ).first()++ if subscription:+ db.session.delete(subscription)+ db.session.commit()+ return jsonify({'success': True, 'message': 'Subscription removed'})++ return jsonify({'success': False, 'message': 'Subscription not found'}), 404+```++## Step 4: Database Model++Add a `PushSubscription` model to your database:++```python+from models import db+from sqlalchemy import Column, Integer, String, ForeignKey, DateTime+from sqlalchemy.sql import func++class PushSubscription(db.Model):+ __tablename__ = 'push_subscriptions'++ id = Column(Integer, primary_key=True)+ user_id = Column(Integer, ForeignKey('users.id'), nullable=False)+ endpoint = Column(String(500), nullable=False, unique=True)+ p256dh_key = Column(String(200), nullable=False)+ auth_key = Column(String(100), nullable=False)+ created_at = Column(DateTime, server_default=func.now())++ __table_args__ = (+ db.Index('idx_user_endpoint', 'user_id', 'endpoint'),+ )+```++Create the migration:++```bash+flask db migrate -m "Add push subscriptions table"+flask db upgrade+```++## Step 5: Send Push Notifications++Use the `pywebpush` library to send notifications when transcription is complete:++```python+from pywebpush import webpush, WebPushException+import json+import os++def send_push_notification(user_id, title, body, data=None):+ """Send push notification to all subscriptions for a user"""+ subscriptions = PushSubscription.query.filter_by(user_id=user_id).all()++ vapid_private_key = os.getenv('VAPID_PRIVATE_KEY')+ vapid_contact = os.getenv('VAPID_CONTACT', 'mailto:[email protected]')++ notification_data = {+ 'title': title,+ 'body': body,+ 'icon': '/static/img/icon-192x192.png',+ 'badge': '/static/img/icon-192x192.png',+ 'data': data or {}+ }++ for subscription in subscriptions:+ try:+ webpush(+ subscription_info={+ 'endpoint': subscription.endpoint,+ 'keys': {+ 'p256dh': subscription.p256dh_key,+ 'auth': subscription.auth_key+ }+ },+ data=json.dumps(notification_data),+ vapid_private_key=vapid_private_key,+ vapid_claims={'sub': vapid_contact}+ )+ print(f'Push notification sent to user {user_id}')+ except WebPushException as e:+ print(f'Failed to send push to {subscription.endpoint}: {e}')+ # If subscription is expired, remove it+ if e.response and e.response.status_code in [404, 410]:+ db.session.delete(subscription)+ db.session.commit()+```++## Step 6: Integrate with Transcription++Call the push notification function when transcription is complete:++```python+# In your transcription completion handler+def on_transcription_complete(recording_id):+ recording = AudioFile.query.get(recording_id)++ if recording:+ send_push_notification(+ user_id=recording.user_id,+ title='Transcription Complete',+ body=f'"{recording.display_name or recording.filename}" has been transcribed',+ data={+ 'recording_id': recording_id,+ 'url': f'/recording/{recording_id}'+ }+ )+```++## Step 7: Environment Variables++Add these environment variables to your `.env` file:++```bash+# VAPID keys for push notifications+VAPID_PRIVATE_KEY=your_private_key_here+VAPID_CONTACT=mailto:[email protected]+```++## Testing Push Notifications++1. Open the app in a browser+2. Open Developer Tools > Console+3. Run: `await pwaComposable.subscribeToPushNotifications()`+4. Check database to verify subscription was saved+5. Trigger a test notification from the backend+6. Verify notification appears++## Browser Support++| Browser | Desktop | Mobile |+|---------|---------|--------|+| Chrome | ✅ | ✅ |+| Edge | ✅ | ✅ |+| Firefox | ✅ | ✅ |+| Safari | ✅ | ⚠️ iOS 16.4+ |+| Opera | ✅ | ✅ |++**Note:** iOS Safari requires iOS 16.4+ and the app must be added to the home screen.++## Troubleshooting++### Subscription fails with "NotAllowedError"+- User denied notification permission+- Ask user to enable notifications in browser settings++### Subscription not saving on server+- Check backend endpoint is accessible+- Verify CSRF token is valid+- Check server logs for errors++### Push notifications not received+- Verify VAPID keys match between client and server+- Check subscription is in database+- Test with browser developer tools+- Ensure service worker is registered++## Security Considerations++1. **Never expose private VAPID key** - Keep it on server only+2. **Validate subscriptions** - Ensure they belong to authenticated users+3. **Rate limit subscriptions** - Prevent abuse+4. **Clean up expired subscriptions** - Remove 404/410 responses+5. **Use HTTPS** - Required for push notifications++## Additional Resources++- [Web Push Protocol](https://datatracker.ietf.org/doc/html/rfc8030)+- [VAPID Specification](https://datatracker.ietf.org/doc/html/rfc8292)+- [pywebpush Documentation](https://github.com/web-push-libs/pywebpush)+- [MDN Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)diff --git a/requirements.txt b/requirements.txtindex 946ddb99..dafc15de 100644--- a/requirements.txt+++ b/requirements.txt@@ -6,6 +6,7 @@ flask-bcrypt==1.0.1Flask-Limiter==3.5.0email-validator==2.2.0openai>=2.2.0+pywebpush==1.14.0werkzeug==2.3.7gunicorn==21.2.0python-dotenv==1.0.0diff --git a/src/api/push_notifications.py b/src/api/push_notifications.pynew file mode 100644index 00000000..f7b18ecf--- /dev/null+++ b/src/api/push_notifications.py@@ -0,0 +1,232 @@+"""+Push Notification API Endpoints+Handles push notification subscriptions and delivery+"""+from flask import Blueprint, request, jsonify+from flask_login import login_required, current_user+from src.database import db+from src.models.push_subscription import PushSubscription+import json+++push_bp = Blueprint('push', __name__)++# VAPID config is loaded lazily to avoid startup issues+_vapid_config = None+++def _get_vapid_config():+ """Load VAPID configuration lazily"""+ global _vapid_config+ if _vapid_config is None:+ try:+ from src.utils.vapid_keys import VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, VAPID_ENABLED+ _vapid_config = {+ 'enabled': VAPID_ENABLED,+ 'public_key': VAPID_PUBLIC_KEY,+ 'private_key': VAPID_PRIVATE_KEY+ }+ except Exception as e:+ print(f"[Push] Failed to load VAPID config: {e}")+ _vapid_config = {+ 'enabled': False,+ 'public_key': None,+ 'private_key': None+ }+ return _vapid_config+++@push_bp.route('/api/push/config', methods=['GET'])+def get_push_config():+ """Get push notification configuration for client"""+ config = _get_vapid_config()+ return jsonify({+ 'enabled': config['enabled'],+ 'public_key': config['public_key'] if config['enabled'] else None+ })+++@push_bp.route('/api/push/subscribe', methods=['POST'])+@login_required+def subscribe():+ """Store push subscription for current user"""+ config = _get_vapid_config()+ if not config['enabled']:+ return jsonify({+ 'success': False,+ 'error': 'Push notifications not available'+ }), 503++ try:+ subscription_data = request.json++ if not subscription_data or 'endpoint' not in subscription_data:+ return jsonify({+ 'success': False,+ 'error': 'Invalid subscription data'+ }), 400++ # Check if subscription already exists+ existing = PushSubscription.query.filter_by(+ user_id=current_user.id,+ endpoint=subscription_data['endpoint']+ ).first()++ if existing:+ return jsonify({+ 'success': True,+ 'message': 'Already subscribed',+ 'subscription_id': existing.id+ })++ # Create new subscription+ subscription = PushSubscription(+ user_id=current_user.id,+ endpoint=subscription_data['endpoint'],+ p256dh_key=subscription_data.get('keys', {}).get('p256dh', ''),+ auth_key=subscription_data.get('keys', {}).get('auth', '')+ )++ db.session.add(subscription)+ db.session.commit()++ return jsonify({+ 'success': True,+ 'message': 'Subscription saved',+ 'subscription_id': subscription.id+ })++ except Exception as e:+ db.session.rollback()+ print(f"[Push] Subscription error: {e}")+ return jsonify({+ 'success': False,+ 'error': str(e)+ }), 500+++@push_bp.route('/api/push/unsubscribe', methods=['POST'])+@login_required+def unsubscribe():+ """Remove push subscription for current user"""+ config = _get_vapid_config()+ if not config['enabled']:+ return jsonify({'success': True, 'message': 'Push notifications not enabled'})++ try:+ subscription_data = request.json++ if not subscription_data or 'endpoint' not in subscription_data:+ return jsonify({+ 'success': False,+ 'error': 'Invalid subscription data'+ }), 400++ subscription = PushSubscription.query.filter_by(+ user_id=current_user.id,+ endpoint=subscription_data['endpoint']+ ).first()++ if subscription:+ db.session.delete(subscription)+ db.session.commit()+ return jsonify({+ 'success': True,+ 'message': 'Subscription removed'+ })++ return jsonify({+ 'success': False,+ 'error': 'Subscription not found'+ }), 404++ except Exception as e:+ db.session.rollback()+ print(f"[Push] Unsubscribe error: {e}")+ return jsonify({+ 'success': False,+ 'error': str(e)+ }), 500+++def send_push_notification(user_id, title, body, data=None, url=None):+ """+ Send push notification to all subscriptions for a user++ Args:+ user_id: User ID to send notification to+ title: Notification title+ body: Notification body text+ data: Optional dictionary of extra data+ url: Optional URL to open when notification is clicked+ """+ config = _get_vapid_config()+ if not config['enabled']:+ print("[Push] Push notifications not enabled, skipping")+ return++ try:+ from pywebpush import webpush, WebPushException++ subscriptions = PushSubscription.query.filter_by(user_id=user_id).all()++ if not subscriptions:+ print(f"[Push] No subscriptions found for user {user_id}")+ return++ notification_data = {+ 'title': title,+ 'body': body,+ 'icon': '/static/img/icon-192x192.png',+ 'badge': '/static/img/icon-192x192.png',+ 'data': data or {}+ }++ if url:+ notification_data['data']['url'] = url++ sent_count = 0+ failed_count = 0++ for subscription in subscriptions:+ try:+ webpush(+ subscription_info={+ 'endpoint': subscription.endpoint,+ 'keys': {+ 'p256dh': subscription.p256dh_key,+ 'auth': subscription.auth_key+ }+ },+ data=json.dumps(notification_data),+ vapid_private_key=config['private_key'],+ vapid_claims={+ 'sub': 'mailto:[email protected]'+ }+ )+ sent_count += 1+ print(f'[Push] Sent notification to user {user_id} subscription {subscription.id}')++ except WebPushException as e:+ failed_count += 1+ print(f'[Push] Failed to send to subscription {subscription.id}: {e}')++ # Remove expired subscriptions+ if e.response and e.response.status_code in [404, 410]:+ print(f'[Push] Removing expired subscription {subscription.id}')+ db.session.delete(subscription)++ except Exception as e:+ failed_count += 1+ print(f'[Push] Unexpected error sending to subscription {subscription.id}: {e}')++ # Commit any deletions+ if failed_count > 0:+ db.session.commit()++ print(f'[Push] Sent {sent_count} notifications, {failed_count} failed')++ except ImportError:+ print("[Push] pywebpush not installed, cannot send notifications")+ except Exception as e:+ print(f"[Push] Error sending notifications: {e}")diff --git a/src/app.py b/src/app.pyindex 8aaa7e53..456a957a 100644--- a/src/app.py+++ b/src/app.py@@ -367,7 +367,7 @@ db.init_app(app)from src.models import (User, Speaker, Recording, TranscriptChunk, Share, InternalShare,SharedRecordingState, Group, GroupMembership, Tag, RecordingTag,- Event, TranscriptTemplate, InquireSession, SystemSetting+ Event, TranscriptTemplate, InquireSession, SystemSetting, PushSubscription)# Import utility functions from extracted modules@@ -488,6 +488,7 @@ from src.api.inquire import inquire_bp, init_inquire_helpersfrom src.api.templates import templates_bp, init_templates_helpersfrom src.api.events import events_bp, init_events_helpersfrom src.api.system import system_bp, init_system_helpers+from src.api.push_notifications import push_bp# Database initialization (extracted to src/init_db.py)from src.init_db import initialize_database@@ -523,6 +524,7 @@ app.register_blueprint(inquire_bp)app.register_blueprint(templates_bp)app.register_blueprint(events_bp)app.register_blueprint(system_bp)+app.register_blueprint(push_bp)# File monitor and scheduler initialization functions belowdiff --git a/src/models/__init__.py b/src/models/__init__.pyindex d79f2ddc..856542df 100644--- a/src/models/__init__.py+++ b/src/models/__init__.py@@ -24,6 +24,7 @@ from .templates import TranscriptTemplatefrom .inquire import InquireSessionfrom .system import SystemSettingfrom .audit import ShareAuditLog+from .push_subscription import PushSubscription# Export all models__all__ = [@@ -51,4 +52,5 @@ __all__ = ['TranscriptTemplate','InquireSession','SystemSetting',+ 'PushSubscription',]diff --git a/src/models/push_subscription.py b/src/models/push_subscription.pynew file mode 100644index 00000000..d44662dd--- /dev/null+++ b/src/models/push_subscription.py@@ -0,0 +1,37 @@+"""+Push Subscription Model+Stores web push notification subscriptions for users+"""+from datetime import datetime+from src.database import db+++class PushSubscription(db.Model):+ """Web Push notification subscription"""+ __tablename__ = 'push_subscriptions'++ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)++ # Push subscription endpoint (unique per browser/device)+ endpoint = db.Column(db.String(500), nullable=False, unique=True)++ # Encryption keys for sending push messages+ p256dh_key = db.Column(db.String(200), nullable=False)+ auth_key = db.Column(db.String(100), nullable=False)++ # Timestamps+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ def __repr__(self):+ return f'<PushSubscription {self.id} user={self.user_id}>'++ def to_dict(self):+ """Convert to dictionary"""+ return {+ 'id': self.id,+ 'user_id': self.user_id,+ 'endpoint': self.endpoint,+ 'created_at': self.created_at.isoformat() if self.created_at else None+ }diff --git a/src/utils/vapid_keys.py b/src/utils/vapid_keys.pynew file mode 100644index 00000000..e910084b--- /dev/null+++ b/src/utils/vapid_keys.py@@ -0,0 +1,101 @@+"""+VAPID Key Management+Auto-generates and stores VAPID keys for push notifications+"""+import os+import json+from pathlib import Path+++def generate_vapid_keys():+ """Generate new VAPID keys using pywebpush"""+ try:+ from pywebpush import webpush++ # Generate keys+ vapid_claims = webpush.WebPusher().vapid_claims++ # For newer versions of pywebpush, use this approach:+ from py_vapid import Vapid+ vapid = Vapid()+ vapid.generate_keys()++ return {+ 'public_key': vapid.public_key.export_public(encoding='uncompressed'),+ 'private_key': vapid.private_key.export_private(encoding='pem')+ }+ except ImportError:+ print("[VAPID] pywebpush not installed. Push notifications will be disabled.")+ print("[VAPID] Install with: pip install pywebpush")+ return None+ except Exception as e:+ print(f"[VAPID] Failed to generate keys: {e}")+ return None+++def get_vapid_keys_file():+ """Get path to VAPID keys storage file"""+ # Store in /config directory (persistent in Docker)+ config_dir = Path(os.getenv('CONFIG_DIR', '/config'))+ config_dir.mkdir(parents=True, exist_ok=True)+ return config_dir / 'vapid_keys.json'+++def load_vapid_keys():+ """Load existing VAPID keys or generate new ones"""+ keys_file = get_vapid_keys_file()++ # Try to load existing keys+ if keys_file.exists():+ try:+ with open(keys_file, 'r') as f:+ keys = json.load(f)+ print(f"[VAPID] Loaded existing keys from {keys_file}")+ return keys+ except Exception as e:+ print(f"[VAPID] Failed to load existing keys: {e}")+ # Continue to generate new keys++ # Generate new keys+ print("[VAPID] Generating new VAPID keys...")+ keys = generate_vapid_keys()++ if keys:+ # Save keys to file+ try:+ with open(keys_file, 'w') as f:+ json.dump(keys, f, indent=2)++ # Set restrictive permissions (owner read/write only)+ os.chmod(keys_file, 0o600)++ print(f"[VAPID] Saved new keys to {keys_file}")+ print(f"[VAPID] Public key: {keys['public_key'][:50]}...")+ return keys+ except Exception as e:+ print(f"[VAPID] Failed to save keys: {e}")+ return keys+ else:+ print("[VAPID] Push notifications disabled - pywebpush not available")+ return None+++def get_public_key():+ """Get the public VAPID key for client use"""+ keys = load_vapid_keys()+ return keys['public_key'] if keys else None+++def get_private_key():+ """Get the private VAPID key for server use"""+ keys = load_vapid_keys()+ return keys['private_key'] if keys else None+++# Initialize on module import+VAPID_KEYS = load_vapid_keys()+VAPID_ENABLED = VAPID_KEYS is not None++# Make keys available as module-level variables+VAPID_PUBLIC_KEY = VAPID_KEYS['public_key'] if VAPID_KEYS else None+VAPID_PRIVATE_KEY = VAPID_KEYS['private_key'] if VAPID_KEYS else Nonediff --git a/static/js/config/push-config.js b/static/js/config/push-config.jsnew file mode 100644index 00000000..0d5932a3--- /dev/null+++ b/static/js/config/push-config.js@@ -0,0 +1,78 @@+/**+ * Push Notification Configuration+ *+ * AUTO-CONFIGURATION:+ * ------------------+ * Push notifications are now auto-configured!+ *+ * On first server startup:+ * 1. VAPID keys are automatically generated (requires pywebpush)+ * 2. Keys are saved to /config/vapid_keys.json (persists across restarts)+ * 3. Public key is served via /api/push/config+ * 4. Client fetches config dynamically+ *+ * No manual configuration needed - just make sure:+ * - pywebpush is installed: pip install pywebpush+ * - /config directory is mounted as Docker volume (for persistence)+ */++// Cached config fetched from server+let cachedConfig = null;++/**+ * Fetch push notification config from server+ */+export async function getPushConfig() {+ if (cachedConfig) {+ return cachedConfig;+ }++ try {+ const response = await fetch('/api/push/config');+ if (!response.ok) {+ console.warn('[Push Config] Failed to fetch config:', response.status);+ return { enabled: false, public_key: null };+ }++ cachedConfig = await response.json();+ console.log('[Push Config] Loaded from server:', cachedConfig.enabled ? 'enabled' : 'disabled');+ return cachedConfig;+ } catch (error) {+ console.error('[Push Config] Error fetching config:', error);+ return { enabled: false, public_key: null };+ }+}++/**+ * Check if push notifications are enabled+ */+export async function isPushEnabled() {+ const config = await getPushConfig();+ return config.enabled && !!config.public_key;+}++/**+ * Get VAPID public key from server+ */+export async function getPublicKey() {+ const config = await getPushConfig();+ return config.public_key;+}++/**+ * Convert a base64 string to Uint8Array (required for push subscription)+ */+export function urlBase64ToUint8Array(base64String) {+ const padding = '='.repeat((4 - base64String.length % 4) % 4);+ const base64 = (base64String + padding)+ .replace(/-/g, '+')+ .replace(/_/g, '/');++ const rawData = window.atob(base64);+ const outputArray = new Uint8Array(rawData.length);++ for (let i = 0; i < rawData.length; ++i) {+ outputArray[i] = rawData.charCodeAt(i);+ }+ return outputArray;+}diff --git a/static/js/modules/composables/pwa.js b/static/js/modules/composables/pwa.jsindex bec82be4..4688a9aa 100644--- a/static/js/modules/composables/pwa.js+++ b/static/js/modules/composables/pwa.js@@ -3,6 +3,8 @@* Handles install prompt, push notifications, badging, and other PWA APIs*/+import { isPushEnabled, getPublicKey, urlBase64ToUint8Array } from '../../config/push-config.js';+export function usePWA(state, utils) {const {deferredInstallPrompt,@@ -114,6 +116,23 @@ export function usePWA(state, utils) {const subscribeToPushNotifications = async () => {if (!('serviceWorker' in navigator) || !('PushManager' in window)) {console.warn('[PWA] Push notifications not supported');+ showToast('Push notifications not supported in this browser', 'warning');+ return null;+ }++ // Check if push is enabled on server+ const enabled = await isPushEnabled();+ if (!enabled) {+ console.warn('[PWA] Push notifications not configured on server');+ showToast('Push notifications not available. Install pywebpush on server.', 'warning');+ return null;+ }++ // Get public key from server+ const publicKey = await getPublicKey();+ if (!publicKey) {+ console.error('[PWA] Failed to get VAPID public key from server');+ showToast('Failed to configure push notifications', 'error');return null;}@@ -125,23 +144,108 @@ export function usePWA(state, utils) {if (!subscription) {// Subscribe to push notifications- // Note: You'll need to generate VAPID keys and add them here- // For now, we'll just set up the structure- console.log('[PWA] Push notification subscription would be created here');- // subscription = await registration.pushManager.subscribe({- // userVisibleOnly: true,- // applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)- // });+ console.log('[PWA] Creating new push subscription...');++ const applicationServerKey = urlBase64ToUint8Array(publicKey);++ subscription = await registration.pushManager.subscribe({+ userVisibleOnly: true,+ applicationServerKey: applicationServerKey+ });++ // Send subscription to server+ const success = await sendSubscriptionToServer(subscription);++ if (success) {+ pushSubscription.value = subscription;+ showToast('Push notifications enabled', 'success');+ console.log('[PWA] Push subscription successful:', subscription);+ } else {+ console.warn('[PWA] Failed to save subscription on server');+ showToast('Failed to enable push notifications', 'error');+ return null;+ }+ } else {+ pushSubscription.value = subscription;+ console.log('[PWA] Already subscribed to push notifications');}- pushSubscription.value = subscription;return subscription;} catch (error) {console.error('[PWA] Failed to subscribe to push notifications:', error);++ if (error.name === 'NotAllowedError') {+ showToast('Push notification permission denied', 'error');+ } else {+ showToast('Failed to enable push notifications', 'error');+ }+return null;}};+ /**+ * Send subscription to server for storage+ */+ const sendSubscriptionToServer = async (subscription) => {+ try {+ const response = await fetch('/api/push/subscribe', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(subscription),+ credentials: 'same-origin'+ });++ if (!response.ok) {+ console.error('[PWA] Server rejected push subscription:', response.status);+ return false;+ }++ const data = await response.json();+ console.log('[PWA] Subscription saved on server:', data);+ return true;+ } catch (error) {+ console.error('[PWA] Failed to send subscription to server:', error);+ return false;+ }+ };++ /**+ * Unsubscribe from push notifications+ */+ const unsubscribeFromPushNotifications = async () => {+ if (!pushSubscription.value) {+ console.log('[PWA] No active push subscription to unsubscribe');+ return true;+ }++ try {+ // Unsubscribe on client+ await pushSubscription.value.unsubscribe();++ // Remove from server+ await fetch('/api/push/unsubscribe', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(pushSubscription.value),+ credentials: 'same-origin'+ });++ pushSubscription.value = null;+ showToast('Push notifications disabled', 'info');+ console.log('[PWA] Unsubscribed from push notifications');+ return true;+ } catch (error) {+ console.error('[PWA] Failed to unsubscribe from push notifications:', error);+ showToast('Failed to disable push notifications', 'error');+ return false;+ }+ };+/*** Show a local notification*/@@ -390,6 +494,7 @@ export function usePWA(state, utils) {// NotificationsrequestNotificationPermission,subscribeToPushNotifications,+ unsubscribeFromPushNotifications,showNotification,// Badging