|
| 1 | +// usePush — Web Push: detección de soporte, suscripción y baja. |
| 2 | +// Reglas (skill web-push-alerts): el prompt nativo SOLO tras gesto del usuario; |
| 3 | +// iOS necesita la PWA instalada; sin secure context (LAN HTTP) el push está |
| 4 | +// dormido y se activará solo cuando la app se sirva por HTTPS. |
| 5 | +// Helios no tiene modo demo en server: no hay estado 'demo'. |
| 6 | +import { useCallback, useEffect, useState } from 'react'; |
| 7 | +import { apiFetch, apiPost } from '@/data/api-client'; |
| 8 | + |
| 9 | +export type SoportePush = |
| 10 | + | 'ok' // se puede suscribir aquí y ahora |
| 11 | + | 'requiere-https' // LAN HTTP: dormido hasta servir por HTTPS |
| 12 | + | 'ios-necesita-instalacion' // iOS sin PWA en Home Screen |
| 13 | + | 'no-configurado' // el servidor no tiene claves VAPID |
| 14 | + | 'no-soportado'; |
| 15 | + |
| 16 | +export interface EstadoPush { |
| 17 | + permiso: NotificationPermission | 'desconocido'; |
| 18 | + suscrito: boolean; |
| 19 | + cargando: boolean; |
| 20 | + error: string | null; |
| 21 | +} |
| 22 | + |
| 23 | +function esStandalone(): boolean { |
| 24 | + return ( |
| 25 | + window.matchMedia('(display-mode: standalone)').matches || |
| 26 | + (navigator as { standalone?: boolean }).standalone === true |
| 27 | + ); |
| 28 | +} |
| 29 | + |
| 30 | +function esIOS(): boolean { |
| 31 | + return ( |
| 32 | + /iPad|iPhone|iPod/.test(navigator.userAgent) || |
| 33 | + (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) |
| 34 | + ); |
| 35 | +} |
| 36 | + |
| 37 | +function soportaPush(): boolean { |
| 38 | + return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; |
| 39 | +} |
| 40 | + |
| 41 | +function urlBase64ToUint8Array(base64: string): Uint8Array { |
| 42 | + const padding = '='.repeat((4 - (base64.length % 4)) % 4); |
| 43 | + const b64 = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/'); |
| 44 | + const raw = atob(b64); |
| 45 | + const salida = new Uint8Array(raw.length); |
| 46 | + for (let i = 0; i < raw.length; i++) salida[i] = raw.charCodeAt(i); |
| 47 | + return salida; |
| 48 | +} |
| 49 | + |
| 50 | +export function usePush(): { |
| 51 | + soporte: SoportePush; |
| 52 | + estado: EstadoPush; |
| 53 | + activar: () => Promise<boolean>; |
| 54 | + desactivar: () => Promise<void>; |
| 55 | +} { |
| 56 | + const [soporte, setSoporte] = useState<SoportePush>('no-soportado'); |
| 57 | + const [estado, setEstado] = useState<EstadoPush>({ |
| 58 | + permiso: 'desconocido', |
| 59 | + suscrito: false, |
| 60 | + cargando: true, |
| 61 | + error: null, |
| 62 | + }); |
| 63 | + |
| 64 | + useEffect(() => { |
| 65 | + let cancelado = false; |
| 66 | + (async () => { |
| 67 | + // Sin contexto seguro (http://192.168.x.x): no hay SW ni PushManager |
| 68 | + // funcional. NO es un bug: se activará al servir la app por HTTPS. |
| 69 | + if (!window.isSecureContext) { |
| 70 | + if (!cancelado) { |
| 71 | + setSoporte('requiere-https'); |
| 72 | + setEstado((e) => ({ ...e, cargando: false })); |
| 73 | + } |
| 74 | + return; |
| 75 | + } |
| 76 | + if (!soportaPush()) { |
| 77 | + if (!cancelado) { |
| 78 | + setSoporte('no-soportado'); |
| 79 | + setEstado((e) => ({ ...e, cargando: false })); |
| 80 | + } |
| 81 | + return; |
| 82 | + } |
| 83 | + if (esIOS() && !esStandalone()) { |
| 84 | + if (!cancelado) { |
| 85 | + setSoporte('ios-necesita-instalacion'); |
| 86 | + setEstado((e) => ({ ...e, permiso: Notification.permission, cargando: false })); |
| 87 | + } |
| 88 | + return; |
| 89 | + } |
| 90 | + try { |
| 91 | + await apiFetch('/api/push/vapid-public-key'); |
| 92 | + const reg = await navigator.serviceWorker.ready; |
| 93 | + const sub = await reg.pushManager.getSubscription(); |
| 94 | + // Re-sincronización: si el navegador tiene suscripción, asegurar que el |
| 95 | + // servidor la conoce (cubre pushsubscriptionchange perdidos). |
| 96 | + if (sub) { |
| 97 | + apiPost('/api/push/subscribe', sub).catch(() => {}); |
| 98 | + } |
| 99 | + if (!cancelado) { |
| 100 | + setSoporte('ok'); |
| 101 | + setEstado({ permiso: Notification.permission, suscrito: sub !== null, cargando: false, error: null }); |
| 102 | + } |
| 103 | + } catch { |
| 104 | + // 503 del servidor: sin claves VAPID configuradas |
| 105 | + if (!cancelado) { |
| 106 | + setSoporte('no-configurado'); |
| 107 | + setEstado((e) => ({ ...e, cargando: false })); |
| 108 | + } |
| 109 | + } |
| 110 | + })(); |
| 111 | + return () => { |
| 112 | + cancelado = true; |
| 113 | + }; |
| 114 | + }, []); |
| 115 | + |
| 116 | + // LLAMAR SOLO DESDE UN GESTO DEL USUARIO (onClick). |
| 117 | + const activar = useCallback(async (): Promise<boolean> => { |
| 118 | + if (soporte !== 'ok') return false; |
| 119 | + setEstado((e) => ({ ...e, cargando: true, error: null })); |
| 120 | + try { |
| 121 | + const permiso = await Notification.requestPermission(); |
| 122 | + if (permiso !== 'granted') { |
| 123 | + setEstado({ permiso, suscrito: false, cargando: false, error: null }); |
| 124 | + return false; |
| 125 | + } |
| 126 | + const { publicKey } = await apiFetch<{ publicKey: string }>('/api/push/vapid-public-key'); |
| 127 | + const reg = await navigator.serviceWorker.ready; |
| 128 | + const sub = await reg.pushManager.subscribe({ |
| 129 | + userVisibleOnly: true, // contrato: todo push visible |
| 130 | + applicationServerKey: urlBase64ToUint8Array(publicKey) as BufferSource, |
| 131 | + }); |
| 132 | + await apiPost('/api/push/subscribe', sub); |
| 133 | + setEstado({ permiso, suscrito: true, cargando: false, error: null }); |
| 134 | + return true; |
| 135 | + } catch (err) { |
| 136 | + setEstado((e) => ({ |
| 137 | + ...e, |
| 138 | + cargando: false, |
| 139 | + error: err instanceof Error ? err.message : 'error', |
| 140 | + })); |
| 141 | + return false; |
| 142 | + } |
| 143 | + }, [soporte]); |
| 144 | + |
| 145 | + const desactivar = useCallback(async (): Promise<void> => { |
| 146 | + setEstado((e) => ({ ...e, cargando: true, error: null })); |
| 147 | + try { |
| 148 | + const reg = await navigator.serviceWorker.ready; |
| 149 | + const sub = await reg.pushManager.getSubscription(); |
| 150 | + if (sub) { |
| 151 | + await apiFetch('/api/push/unsubscribe', { |
| 152 | + method: 'DELETE', |
| 153 | + headers: { 'Content-Type': 'application/json' }, |
| 154 | + body: JSON.stringify({ endpoint: sub.endpoint }), |
| 155 | + }).catch(() => {}); |
| 156 | + await sub.unsubscribe(); |
| 157 | + } |
| 158 | + setEstado((e) => ({ ...e, suscrito: false, cargando: false })); |
| 159 | + } catch (err) { |
| 160 | + setEstado((e) => ({ |
| 161 | + ...e, |
| 162 | + cargando: false, |
| 163 | + error: err instanceof Error ? err.message : 'error', |
| 164 | + })); |
| 165 | + } |
| 166 | + }, []); |
| 167 | + |
| 168 | + return { soporte, estado, activar, desactivar }; |
| 169 | +} |
0 commit comments