Notifications push (Web Push) et indicateur hors-ligne / synchro en attente
- Réglages → Notifications : interrupteur « Notifications sur cet appareil » (permission demandée au clic uniquement, iOS : explication « installe l'app », permission refusée, navigateur non compatible). Désinscription à la déconnexion. - Service worker : push-sw.js chargé via workbox.importScripts (affichage + clic qui ouvre/focalise l'app sur le bon écran via « /?open=… »). - Serveur : table push_subscriptions (RLS, anti-SSRF, 10 appareils max), déclencheur pg_net + secret dans Vault, fonction send-push (aes128gcm + VAPID ES256 en WebCrypto, testée sur le vecteur RFC 8291), regroupement des épisodes, préférences notifPrefs, ménage des abonnements expirés. - scripts/gen-vapid.mjs et supabase/PUSH_SETUP.md (étapes manuelles). - Pastille discrète hors-ligne / « N modifications en attente » (mobile au-dessus de la barre de nav, ordinateur dans la barre latérale), basée sur l'état du moteur de synchro existant. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
35 files changed
+1779
No files matched your search
@@ -13,6 +13,8 @@ import StatsPage from './pages/StatsPage'
|
||||
import SettingsPage from './pages/SettingsPage'
|
||||
import AdminPage from './pages/AdminPage'
|
||||
import NotFoundPage from './pages/NotFoundPage'
|
||||
import PushBridge from './components/PushBridge'
|
||||
import SyncIndicator from './components/SyncIndicator'
|
||||
import { useMedia } from './store'
|
||||
import type { SearchResult } from './lib/catalogApi'
|
||||
import type { MediaItem } from './types'
|
||||
@@ -81,6 +83,8 @@ export default function App() {
|
||||
</main>
|
||||
|
||||
<BottomNav current={navTab} onChange={go} onAdd={openNew} />
|
||||
<SyncIndicator />
|
||||
<PushBridge />
|
||||
|
||||
{roulette && <Roulette onClose={() => setRoulette(false)} onOpen={openItem} />}
|
||||
{calendar && <CalendarView onClose={() => setCalendar(false)} onOpen={openItem} />}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { keepPushFresh } from '../lib/push'
|
||||
import { useMedia } from '../store'
|
||||
import { useSocial } from './social/SocialProvider'
|
||||
|
||||
/** Écrans qu'une notification push peut ouvrir (« /?open=… », voir public/push-sw.js). */
|
||||
const OPEN_RE = /^(notifications|item:[A-Za-z0-9_-]{1,64}|u:[a-z0-9_]{3,20})$/
|
||||
|
||||
/** Lit (et retire de l'adresse) l'écran demandé par une notification au lancement de l'app. */
|
||||
function takeOpenParam(): string | null {
|
||||
try {
|
||||
const params = new URLSearchParams(location.search)
|
||||
const open = params.get('open')
|
||||
if (open === null) return null
|
||||
params.delete('open')
|
||||
const q = params.toString()
|
||||
history.replaceState(history.state, '', `${location.pathname}${q ? `?${q}` : ''}${location.hash}`)
|
||||
return OPEN_RE.test(open) ? open : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lien entre les notifications push et l'app : ouvre le bon écran au clic sur une notification
|
||||
* (app lancée, ou déjà ouverte : message du service worker), met à jour la cloche quand
|
||||
* une notification arrive, et garde l'abonnement de l'appareil à jour côté serveur.
|
||||
*/
|
||||
export default function PushBridge() {
|
||||
const { account, items, loading } = useMedia()
|
||||
const social = useSocial()
|
||||
const [target, setTarget] = useState<string | null>(takeOpenParam)
|
||||
const socialRef = useRef(social)
|
||||
socialRef.current = social
|
||||
|
||||
// Messages du service worker
|
||||
useEffect(() => {
|
||||
if (!('serviceWorker' in navigator)) return
|
||||
const onMessage = (e: MessageEvent) => {
|
||||
const data = e.data as { type?: unknown; open?: unknown } | null
|
||||
if (!data || typeof data !== 'object') return
|
||||
if (data.type === 'azuu:open' && typeof data.open === 'string' && OPEN_RE.test(data.open)) setTarget(data.open)
|
||||
else if (data.type === 'azuu:push') void socialRef.current.refresh()
|
||||
}
|
||||
navigator.serviceWorker.addEventListener('message', onMessage)
|
||||
return () => navigator.serviceWorker.removeEventListener('message', onMessage)
|
||||
}, [])
|
||||
|
||||
// Ouvre l'écran demandé une fois le compte et la bibliothèque chargés
|
||||
useEffect(() => {
|
||||
if (!target) return
|
||||
if (!account) {
|
||||
// Pas (ou plus) connecté : rien à ouvrir
|
||||
if (!loading) setTarget(null)
|
||||
return
|
||||
}
|
||||
if (!social.enabled || loading) return
|
||||
setTarget(null)
|
||||
if (target === 'notifications') social.openNotifications()
|
||||
else if (target.startsWith('u:')) social.openProfile(target.slice(2))
|
||||
else {
|
||||
const item = items.find((i) => i.id === target.slice(5))
|
||||
if (item) social.openItem(item)
|
||||
else social.openNotifications()
|
||||
}
|
||||
}, [target, account, social, loading, items])
|
||||
|
||||
// Abonnement push renouvelé par le navigateur, langue changée… : on le signale au serveur
|
||||
const accountOn = !!account
|
||||
useEffect(() => {
|
||||
if (accountOn) void keepPushFresh()
|
||||
}, [accountOn])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { BellRing, Loader2 } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { enablePush, disablePush, getPushState, PushError, type PushState } from '../lib/push'
|
||||
import { cx } from '../lib/utils'
|
||||
|
||||
/** Réglages → Notifications : « Notifications sur cet appareil » (Web Push, même app fermée). */
|
||||
export default function PushToggle() {
|
||||
const [state, setState] = useState<PushState | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
void getPushState().then((s) => alive && setState(s))
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (state === null) return null
|
||||
const on = state === 'on'
|
||||
const available = state === 'on' || state === 'off'
|
||||
|
||||
const toggle = async () => {
|
||||
if (busy || !available) return
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
if (on) {
|
||||
await disablePush()
|
||||
setState('off')
|
||||
} else {
|
||||
// La permission n'est demandée qu'ici, au clic
|
||||
setState(await enablePush())
|
||||
}
|
||||
} catch (e) {
|
||||
const code = e instanceof PushError ? e.code : 'failed'
|
||||
if (code === 'denied') setState('denied')
|
||||
else setError(code === 'not-ready' ? t('push.notReady') : t('push.error'))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const hint =
|
||||
state === 'needs-install'
|
||||
? t('push.iosInstall')
|
||||
: state === 'unsupported'
|
||||
? t('push.unsupported')
|
||||
: state === 'denied'
|
||||
? t('push.denied')
|
||||
: t('push.deviceHint')
|
||||
|
||||
return (
|
||||
<div className="card mb-3 overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={on}
|
||||
aria-disabled={!available || busy}
|
||||
onClick={() => void toggle()}
|
||||
className={cx('flex w-full items-center gap-3.5 px-4 py-3.5 text-start', !available && 'cursor-default')}
|
||||
>
|
||||
<span className={cx('grid size-10 shrink-0 place-items-center rounded-full bg-surface-2', on ? 'text-accent' : 'text-ink-2')}>
|
||||
{busy ? <Loader2 size={18} className="animate-spin" /> : <BellRing size={18} />}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-medium">{t('push.device')}</span>
|
||||
<span className={cx('mt-0.5 block text-xs', state === 'denied' ? 'text-accent' : 'text-ink-3')}>{hint}</span>
|
||||
</span>
|
||||
{available && (
|
||||
<span className={cx('relative h-6 w-11 shrink-0 rounded-full transition-colors', on ? 'bg-accent-fill' : 'border border-line-strong bg-surface-2')}>
|
||||
<span className={cx('absolute top-0.5 size-5 rounded-full bg-ink transition-all', on ? 'start-[22px] bg-on-accent' : 'start-0.5')} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{error && (
|
||||
<p role="alert" className="border-t border-line px-4 py-2.5 text-xs text-accent">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { Check, CloudOff, RefreshCw, X } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
|
||||
function useOnline(): boolean {
|
||||
const [online, setOnline] = useState(() => navigator.onLine)
|
||||
useEffect(() => {
|
||||
const up = () => setOnline(true)
|
||||
const down = () => setOnline(false)
|
||||
window.addEventListener('online', up)
|
||||
window.addEventListener('offline', down)
|
||||
return () => {
|
||||
window.removeEventListener('online', up)
|
||||
window.removeEventListener('offline', down)
|
||||
}
|
||||
}, [])
|
||||
return online
|
||||
}
|
||||
|
||||
type Kind = 'offline' | 'offline-local' | 'pending' | 'synced'
|
||||
|
||||
/**
|
||||
* Petite pastille discrète : hors-ligne, ou modifications pas encore envoyées au compte.
|
||||
* Mobile : juste au-dessus de la barre de navigation ; ordinateur : en bas de la barre latérale.
|
||||
* Elle disparaît une fois tout synchronisé (après un bref « Synchronisé »).
|
||||
* L'état vient du moteur de synchro (useMedia().account.sync) : rien n'est recalculé ici.
|
||||
*/
|
||||
export default function SyncIndicator() {
|
||||
const { account } = useMedia()
|
||||
const online = useOnline()
|
||||
const pending = account?.sync.pending ?? 0
|
||||
const syncing = account?.sync.state === 'syncing'
|
||||
const failed = account?.sync.state === 'error'
|
||||
|
||||
// Une modification part normalement en 1-2 s : on ne signale l'attente que si elle dure
|
||||
const [slow, setSlow] = useState(false)
|
||||
useEffect(() => {
|
||||
if (pending === 0) {
|
||||
setSlow(false)
|
||||
return
|
||||
}
|
||||
const timer = setTimeout(() => setSlow(true), failed ? 0 : 4000)
|
||||
return () => clearTimeout(timer)
|
||||
}, [pending > 0, failed])
|
||||
|
||||
// Sans compte, l'app marche hors-ligne : message rassurant, que l'on peut masquer
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
useEffect(() => {
|
||||
if (online) setDismissed(false)
|
||||
}, [online])
|
||||
|
||||
const base: Kind | null = !online
|
||||
? account
|
||||
? 'offline'
|
||||
: dismissed
|
||||
? null
|
||||
: 'offline-local'
|
||||
: account && pending > 0 && slow
|
||||
? 'pending'
|
||||
: null
|
||||
|
||||
// Bref « Synchronisé » quand la pastille d'attente disparaît
|
||||
const [flash, setFlash] = useState(false)
|
||||
const shown = useRef<Kind | null>(null)
|
||||
useEffect(() => {
|
||||
const was = shown.current
|
||||
shown.current = base
|
||||
if (base) {
|
||||
setFlash(false)
|
||||
return
|
||||
}
|
||||
if (account && was === 'pending' && pending === 0 && online) setFlash(true)
|
||||
}, [base, account, pending, online])
|
||||
useEffect(() => {
|
||||
if (!flash) return
|
||||
const timer = setTimeout(() => setFlash(false), 2200)
|
||||
return () => clearTimeout(timer)
|
||||
}, [flash])
|
||||
const kind: Kind | null = base ?? (flash ? 'synced' : null)
|
||||
if (!kind) return null
|
||||
|
||||
const text =
|
||||
kind === 'offline'
|
||||
? pending > 0
|
||||
? `${t('sync.offline')} · ${t('sync.pending', { count: pending })}`
|
||||
: t('netPill.offlineSync')
|
||||
: kind === 'offline-local'
|
||||
? t('netPill.offlineLocal')
|
||||
: kind === 'pending'
|
||||
? syncing
|
||||
? `${t('sync.syncing')} · ${t('sync.pending', { count: pending })}`
|
||||
: t('sync.pending', { count: pending })
|
||||
: t('netPill.synced')
|
||||
|
||||
const icon =
|
||||
kind === 'synced' ? (
|
||||
<Check size={14} className="shrink-0 text-accent" />
|
||||
) : kind === 'pending' ? (
|
||||
<RefreshCw size={14} className={cx('shrink-0', syncing && 'animate-spin', failed && 'text-accent')} />
|
||||
) : (
|
||||
<CloudOff size={14} className="shrink-0" />
|
||||
)
|
||||
|
||||
const pill = 'pointer-events-auto inline-flex max-w-full items-center gap-2 rounded-full border border-line bg-surface px-3.5 py-1.5 text-xs font-medium text-ink-2 shadow-lg lg:w-full lg:rounded-xl lg:px-3 lg:py-2 lg:text-start'
|
||||
|
||||
return (
|
||||
<div
|
||||
className="pointer-events-none fixed inset-x-0 bottom-[calc(4.75rem+env(safe-area-inset-bottom))] z-20 flex justify-center px-4 lg:inset-x-auto lg:start-0 lg:bottom-5 lg:z-[31] lg:w-60 lg:justify-start"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
data-testid="sync-indicator"
|
||||
data-kind={kind}
|
||||
>
|
||||
{kind === 'pending' ? (
|
||||
// Envoi en attente : un appui relance la synchro
|
||||
<button type="button" onClick={() => void account?.syncNow().catch(() => {})} className={pill} title={t('sync.now')}>
|
||||
{icon}
|
||||
<span className="truncate lg:overflow-visible lg:whitespace-normal">{text}</span>
|
||||
</button>
|
||||
) : kind === 'offline-local' ? (
|
||||
<span className={pill}>
|
||||
{icon}
|
||||
<span className="truncate lg:overflow-visible lg:whitespace-normal">{text}</span>
|
||||
<button type="button" onClick={() => setDismissed(true)} aria-label={t('netPill.hide')} className="-me-1 ms-0.5 grid size-5 shrink-0 place-items-center rounded-full text-ink-3 hover:text-ink">
|
||||
<X size={12} />
|
||||
</button>
|
||||
</span>
|
||||
) : (
|
||||
<span className={pill}>
|
||||
{icon}
|
||||
<span className="truncate lg:overflow-visible lg:whitespace-normal">{text}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1035,6 +1035,18 @@ const dict: Translations = {
|
||||
'sync.pending_two': "تعديلان في الانتظار",
|
||||
'sync.pending_few': "{count} تعديلات في الانتظار",
|
||||
'sync.pending_many': "{count} تعديلًا في الانتظار",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "الإشعارات على هذا الجهاز",
|
||||
'push.deviceHint': "حتى عندما يكون التطبيق مغلقًا. تنطبق الخيارات أدناه أيضًا.",
|
||||
'push.iosInstall': "على iPhone وiPad، أضف AzuuCine أولًا إلى الشاشة الرئيسية (iOS 16.4 أو أحدث)، ثم افتح التطبيق من أيقونته لتفعيل الإشعارات.",
|
||||
'push.unsupported': "هذا المتصفح لا يدعم الإشعارات الفورية.",
|
||||
'push.denied': "الإشعارات محظورة لهذا الموقع. اسمح بها من إعدادات المتصفح ثم حاول مجددًا.",
|
||||
'push.notReady': "الإشعارات الفورية غير متاحة على الخادم بعد.",
|
||||
'push.error': "تعذّر تفعيل الإشعارات. تحقق من اتصالك وحاول مجددًا.",
|
||||
'netPill.offlineSync': "غير متصل — ستتم مزامنة تعديلاتك",
|
||||
'netPill.offlineLocal': "غير متصل — كل شيء محفوظ على هذا الجهاز",
|
||||
'netPill.synced': "تمت المزامنة",
|
||||
'netPill.hide': "إخفاء",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} Änderung ausstehend",
|
||||
'sync.pending_other': "{count} Änderungen ausstehend",
|
||||
'sync.now': "Jetzt synchronisieren",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Benachrichtigungen auf diesem Gerät",
|
||||
'push.deviceHint': "Auch wenn die App geschlossen ist. Die Auswahl unten gilt ebenfalls.",
|
||||
'push.iosInstall': "Auf iPhone und iPad füge AzuuCine zuerst zum Home-Bildschirm hinzu (iOS 16.4 oder neuer) und öffne die App dann über ihr Symbol, um Benachrichtigungen zu aktivieren.",
|
||||
'push.unsupported': "Dieser Browser unterstützt keine Push-Benachrichtigungen.",
|
||||
'push.denied': "Benachrichtigungen sind für diese Seite blockiert. Erlaube sie in den Browser-Einstellungen und versuche es erneut.",
|
||||
'push.notReady': "Push-Benachrichtigungen sind auf dem Server noch nicht verfügbar.",
|
||||
'push.error': "Benachrichtigungen konnten nicht aktiviert werden. Prüfe deine Verbindung und versuche es erneut.",
|
||||
'netPill.offlineSync': "Offline — deine Änderungen werden synchronisiert",
|
||||
'netPill.offlineLocal': "Offline — alles bleibt auf diesem Gerät gespeichert",
|
||||
'netPill.synced': "Synchronisiert",
|
||||
'netPill.hide': "Ausblenden",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} change waiting",
|
||||
'sync.pending_other': "{count} changes waiting",
|
||||
'sync.now': "Sync now",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Notifications on this device",
|
||||
'push.deviceHint': "Even when the app is closed. The choices below apply too.",
|
||||
'push.iosInstall': "On iPhone and iPad, first add AzuuCine to your Home Screen (iOS 16.4 or later), then open the app from its icon to turn on notifications.",
|
||||
'push.unsupported': "This browser doesn’t support push notifications.",
|
||||
'push.denied': "Notifications are blocked for this site. Allow them in your browser settings, then try again.",
|
||||
'push.notReady': "Push notifications aren’t available on the server yet.",
|
||||
'push.error': "Couldn’t turn on notifications. Check your connection and try again.",
|
||||
'netPill.offlineSync': "Offline — your changes will sync",
|
||||
'netPill.offlineLocal': "Offline — everything stays saved on this device",
|
||||
'netPill.synced': "Synced",
|
||||
'netPill.hide': "Hide",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} cambio pendiente",
|
||||
'sync.pending_other': "{count} cambios pendientes",
|
||||
'sync.now': "Sincronizar",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Notificaciones en este dispositivo",
|
||||
'push.deviceHint': "Incluso con la app cerrada. Las opciones de abajo también se aplican.",
|
||||
'push.iosInstall': "En iPhone y iPad, primero añade AzuuCine a la pantalla de inicio (iOS 16.4 o posterior) y abre la app desde su icono para activar las notificaciones.",
|
||||
'push.unsupported': "Este navegador no admite notificaciones push.",
|
||||
'push.denied': "Las notificaciones están bloqueadas para este sitio. Permítelas en los ajustes del navegador y vuelve a intentarlo.",
|
||||
'push.notReady': "Las notificaciones push aún no están disponibles en el servidor.",
|
||||
'push.error': "No se pudieron activar las notificaciones. Comprueba tu conexión e inténtalo de nuevo.",
|
||||
'netPill.offlineSync': "Sin conexión — tus cambios se sincronizarán",
|
||||
'netPill.offlineLocal': "Sin conexión — todo queda guardado en este dispositivo",
|
||||
'netPill.synced': "Sincronizado",
|
||||
'netPill.hide': "Ocultar",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -899,6 +899,18 @@ const dict = {
|
||||
'sync.pending_one': "{count} modification en attente",
|
||||
'sync.pending_other': "{count} modifications en attente",
|
||||
'sync.now': "Synchroniser",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Notifications sur cet appareil",
|
||||
'push.deviceHint': "Même quand l’app est fermée. Les choix ci-dessous s’appliquent aussi.",
|
||||
'push.iosInstall': "Sur iPhone et iPad, ajoute d’abord AzuuCine à l’écran d’accueil (iOS 16.4 ou plus récent), puis ouvre l’app depuis son icône pour activer les notifications.",
|
||||
'push.unsupported': "Ce navigateur ne gère pas les notifications push.",
|
||||
'push.denied': "Notifications bloquées pour ce site. Autorise-les dans les réglages du navigateur, puis réessaie.",
|
||||
'push.notReady': "Les notifications push ne sont pas encore disponibles sur le serveur.",
|
||||
'push.error': "Impossible d’activer les notifications. Vérifie ta connexion et réessaie.",
|
||||
'netPill.offlineSync': "Hors ligne — tes modifs seront synchronisées",
|
||||
'netPill.offlineLocal': "Hors ligne — tout reste enregistré sur cet appareil",
|
||||
'netPill.synced': "Synchronisé",
|
||||
'netPill.hide': "Masquer",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} बदलाव बाकी",
|
||||
'sync.pending_other': "{count} बदलाव बाकी",
|
||||
'sync.now': "अभी सिंक करें",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "इस डिवाइस पर सूचनाएँ",
|
||||
'push.deviceHint': "ऐप बंद होने पर भी। नीचे दिए विकल्प भी लागू होते हैं।",
|
||||
'push.iosInstall': "iPhone और iPad पर पहले AzuuCine को होम स्क्रीन पर जोड़ें (iOS 16.4 या नया), फिर सूचनाएँ चालू करने के लिए ऐप को उसके आइकन से खोलें।",
|
||||
'push.unsupported': "यह ब्राउज़र पुश सूचनाएँ सपोर्ट नहीं करता।",
|
||||
'push.denied': "इस साइट के लिए सूचनाएँ ब्लॉक हैं। ब्राउज़र सेटिंग्स में अनुमति दें, फिर दोबारा कोशिश करें।",
|
||||
'push.notReady': "पुश सूचनाएँ अभी सर्वर पर उपलब्ध नहीं हैं।",
|
||||
'push.error': "सूचनाएँ चालू नहीं हो सकीं। अपना कनेक्शन जाँचें और दोबारा कोशिश करें।",
|
||||
'netPill.offlineSync': "ऑफ़लाइन — आपके बदलाव सिंक हो जाएँगे",
|
||||
'netPill.offlineLocal': "ऑफ़लाइन — सब कुछ इस डिवाइस पर सहेजा रहता है",
|
||||
'netPill.synced': "सिंक हो गया",
|
||||
'netPill.hide': "छिपाएँ",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} perubahan menunggu",
|
||||
'sync.pending_other': "{count} perubahan menunggu",
|
||||
'sync.now': "Sinkronkan",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Notifikasi di perangkat ini",
|
||||
'push.deviceHint': "Bahkan saat aplikasi ditutup. Pilihan di bawah juga berlaku.",
|
||||
'push.iosInstall': "Di iPhone dan iPad, tambahkan dulu AzuuCine ke Layar Utama (iOS 16.4 atau lebih baru), lalu buka aplikasi dari ikonnya untuk mengaktifkan notifikasi.",
|
||||
'push.unsupported': "Browser ini tidak mendukung notifikasi push.",
|
||||
'push.denied': "Notifikasi diblokir untuk situs ini. Izinkan di pengaturan browser, lalu coba lagi.",
|
||||
'push.notReady': "Notifikasi push belum tersedia di server.",
|
||||
'push.error': "Tidak dapat mengaktifkan notifikasi. Periksa koneksimu dan coba lagi.",
|
||||
'netPill.offlineSync': "Offline — perubahanmu akan disinkronkan",
|
||||
'netPill.offlineLocal': "Offline — semuanya tetap tersimpan di perangkat ini",
|
||||
'netPill.synced': "Tersinkron",
|
||||
'netPill.hide': "Sembunyikan",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} modifica in attesa",
|
||||
'sync.pending_other': "{count} modifiche in attesa",
|
||||
'sync.now': "Sincronizza",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Notifiche su questo dispositivo",
|
||||
'push.deviceHint': "Anche con l’app chiusa. Valgono anche le scelte qui sotto.",
|
||||
'push.iosInstall': "Su iPhone e iPad, aggiungi prima AzuuCine alla schermata Home (iOS 16.4 o successivo), poi apri l’app dalla sua icona per attivare le notifiche.",
|
||||
'push.unsupported': "Questo browser non supporta le notifiche push.",
|
||||
'push.denied': "Le notifiche sono bloccate per questo sito. Consentile nelle impostazioni del browser, poi riprova.",
|
||||
'push.notReady': "Le notifiche push non sono ancora disponibili sul server.",
|
||||
'push.error': "Impossibile attivare le notifiche. Controlla la connessione e riprova.",
|
||||
'netPill.offlineSync': "Offline — le modifiche verranno sincronizzate",
|
||||
'netPill.offlineLocal': "Offline — tutto resta salvato su questo dispositivo",
|
||||
'netPill.synced': "Sincronizzato",
|
||||
'netPill.hide': "Nascondi",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} 件の変更が保留中",
|
||||
'sync.pending_other': "{count} 件の変更が保留中",
|
||||
'sync.now': "今すぐ同期",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "このデバイスの通知",
|
||||
'push.deviceHint': "アプリを閉じていても届きます。下の設定も適用されます。",
|
||||
'push.iosInstall': "iPhone・iPad では、まず AzuuCine をホーム画面に追加し(iOS 16.4 以降)、アイコンからアプリを開いて通知をオンにしてください。",
|
||||
'push.unsupported': "このブラウザはプッシュ通知に対応していません。",
|
||||
'push.denied': "このサイトの通知はブロックされています。ブラウザの設定で許可してから、もう一度お試しください。",
|
||||
'push.notReady': "プッシュ通知はまだサーバーで利用できません。",
|
||||
'push.error': "通知をオンにできませんでした。接続を確認して、もう一度お試しください。",
|
||||
'netPill.offlineSync': "オフライン — 変更は後で同期されます",
|
||||
'netPill.offlineLocal': "オフライン — すべてこのデバイスに保存されています",
|
||||
'netPill.synced': "同期済み",
|
||||
'netPill.hide': "閉じる",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "변경 {count}개 대기 중",
|
||||
'sync.pending_other': "변경 {count}개 대기 중",
|
||||
'sync.now': "지금 동기화",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "이 기기의 알림",
|
||||
'push.deviceHint': "앱이 닫혀 있어도 받아요. 아래 선택 사항도 적용돼요.",
|
||||
'push.iosInstall': "iPhone과 iPad에서는 먼저 AzuuCine을 홈 화면에 추가한 뒤(iOS 16.4 이상) 아이콘으로 앱을 열어 알림을 켜 주세요.",
|
||||
'push.unsupported': "이 브라우저는 푸시 알림을 지원하지 않아요.",
|
||||
'push.denied': "이 사이트의 알림이 차단되어 있어요. 브라우저 설정에서 허용한 뒤 다시 시도해 주세요.",
|
||||
'push.notReady': "서버에서 아직 푸시 알림을 사용할 수 없어요.",
|
||||
'push.error': "알림을 켜지 못했어요. 연결을 확인하고 다시 시도해 주세요.",
|
||||
'netPill.offlineSync': "오프라인 — 변경 사항은 나중에 동기화돼요",
|
||||
'netPill.offlineLocal': "오프라인 — 모든 내용이 이 기기에 저장돼 있어요",
|
||||
'netPill.synced': "동기화됨",
|
||||
'netPill.hide': "숨기기",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} wijziging in wachtrij",
|
||||
'sync.pending_other': "{count} wijzigingen in wachtrij",
|
||||
'sync.now': "Nu synchroniseren",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Meldingen op dit apparaat",
|
||||
'push.deviceHint': "Ook als de app gesloten is. De keuzes hieronder gelden ook.",
|
||||
'push.iosInstall': "Voeg op iPhone en iPad AzuuCine eerst toe aan je beginscherm (iOS 16.4 of nieuwer) en open de app via het pictogram om meldingen aan te zetten.",
|
||||
'push.unsupported': "Deze browser ondersteunt geen pushmeldingen.",
|
||||
'push.denied': "Meldingen zijn geblokkeerd voor deze site. Sta ze toe in je browserinstellingen en probeer het opnieuw.",
|
||||
'push.notReady': "Pushmeldingen zijn nog niet beschikbaar op de server.",
|
||||
'push.error': "Kon meldingen niet aanzetten. Controleer je verbinding en probeer het opnieuw.",
|
||||
'netPill.offlineSync': "Offline — je wijzigingen worden gesynchroniseerd",
|
||||
'netPill.offlineLocal': "Offline — alles blijft op dit apparaat bewaard",
|
||||
'netPill.synced': "Gesynchroniseerd",
|
||||
'netPill.hide': "Verbergen",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -989,6 +989,18 @@ const dict: Translations = {
|
||||
'sync.now': "Synchronizuj",
|
||||
'sync.pending_few': "{count} zmiany oczekują",
|
||||
'sync.pending_many': "{count} zmian oczekuje",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Powiadomienia na tym urządzeniu",
|
||||
'push.deviceHint': "Nawet gdy aplikacja jest zamknięta. Poniższe ustawienia też obowiązują.",
|
||||
'push.iosInstall': "Na iPhonie i iPadzie najpierw dodaj AzuuCine do ekranu początkowego (iOS 16.4 lub nowszy), a potem otwórz aplikację z jej ikony, aby włączyć powiadomienia.",
|
||||
'push.unsupported': "Ta przeglądarka nie obsługuje powiadomień push.",
|
||||
'push.denied': "Powiadomienia są zablokowane dla tej witryny. Zezwól na nie w ustawieniach przeglądarki i spróbuj ponownie.",
|
||||
'push.notReady': "Powiadomienia push nie są jeszcze dostępne na serwerze.",
|
||||
'push.error': "Nie udało się włączyć powiadomień. Sprawdź połączenie i spróbuj ponownie.",
|
||||
'netPill.offlineSync': "Offline — zmiany zostaną zsynchronizowane",
|
||||
'netPill.offlineLocal': "Offline — wszystko zostaje zapisane na tym urządzeniu",
|
||||
'netPill.synced': "Zsynchronizowano",
|
||||
'netPill.hide': "Ukryj",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} alteração pendente",
|
||||
'sync.pending_other': "{count} alterações pendentes",
|
||||
'sync.now': "Sincronizar",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Notificações neste dispositivo",
|
||||
'push.deviceHint': "Mesmo com o app fechado. As opções abaixo também valem.",
|
||||
'push.iosInstall': "No iPhone e iPad, primeiro adicione o AzuuCine à Tela de Início (iOS 16.4 ou mais recente) e abra o app pelo ícone para ativar as notificações.",
|
||||
'push.unsupported': "Este navegador não suporta notificações push.",
|
||||
'push.denied': "As notificações estão bloqueadas para este site. Permita-as nas configurações do navegador e tente de novo.",
|
||||
'push.notReady': "As notificações push ainda não estão disponíveis no servidor.",
|
||||
'push.error': "Não foi possível ativar as notificações. Verifique sua conexão e tente de novo.",
|
||||
'netPill.offlineSync': "Offline — suas alterações serão sincronizadas",
|
||||
'netPill.offlineLocal': "Offline — tudo fica salvo neste dispositivo",
|
||||
'netPill.synced': "Sincronizado",
|
||||
'netPill.hide': "Ocultar",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -989,6 +989,18 @@ const dict: Translations = {
|
||||
'sync.now': "Синхронизировать",
|
||||
'sync.pending_few': "{count} изменения ожидают",
|
||||
'sync.pending_many': "{count} изменений ожидают",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Уведомления на этом устройстве",
|
||||
'push.deviceHint': "Даже когда приложение закрыто. Настройки ниже тоже действуют.",
|
||||
'push.iosInstall': "На iPhone и iPad сначала добавьте AzuuCine на экран «Домой» (iOS 16.4 или новее), затем откройте приложение с его значка, чтобы включить уведомления.",
|
||||
'push.unsupported': "Этот браузер не поддерживает push-уведомления.",
|
||||
'push.denied': "Уведомления для этого сайта заблокированы. Разрешите их в настройках браузера и повторите попытку.",
|
||||
'push.notReady': "Push-уведомления пока недоступны на сервере.",
|
||||
'push.error': "Не удалось включить уведомления. Проверьте подключение и повторите попытку.",
|
||||
'netPill.offlineSync': "Нет сети — изменения будут синхронизированы",
|
||||
'netPill.offlineLocal': "Нет сети — всё сохранено на этом устройстве",
|
||||
'netPill.synced': "Синхронизировано",
|
||||
'netPill.hide': "Скрыть",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "รอซิงค์ {count} รายการ",
|
||||
'sync.pending_other': "รอซิงค์ {count} รายการ",
|
||||
'sync.now': "ซิงค์ตอนนี้",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "การแจ้งเตือนบนอุปกรณ์นี้",
|
||||
'push.deviceHint': "แม้ปิดแอปอยู่ ตัวเลือกด้านล่างก็มีผลด้วย",
|
||||
'push.iosInstall': "บน iPhone และ iPad ให้เพิ่ม AzuuCine ไปยังหน้าจอโฮมก่อน (iOS 16.4 ขึ้นไป) แล้วเปิดแอปจากไอคอนเพื่อเปิดการแจ้งเตือน",
|
||||
'push.unsupported': "เบราว์เซอร์นี้ไม่รองรับการแจ้งเตือนแบบพุช",
|
||||
'push.denied': "การแจ้งเตือนถูกบล็อกสำหรับเว็บไซต์นี้ อนุญาตในการตั้งค่าเบราว์เซอร์แล้วลองอีกครั้ง",
|
||||
'push.notReady': "เซิร์ฟเวอร์ยังไม่พร้อมสำหรับการแจ้งเตือนแบบพุช",
|
||||
'push.error': "เปิดการแจ้งเตือนไม่สำเร็จ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง",
|
||||
'netPill.offlineSync': "ออฟไลน์ — การเปลี่ยนแปลงจะซิงค์ภายหลัง",
|
||||
'netPill.offlineLocal': "ออฟไลน์ — ทุกอย่างยังบันทึกอยู่ในอุปกรณ์นี้",
|
||||
'netPill.synced': "ซิงค์แล้ว",
|
||||
'netPill.hide': "ซ่อน",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} değişiklik bekliyor",
|
||||
'sync.pending_other': "{count} değişiklik bekliyor",
|
||||
'sync.now': "Şimdi eşitle",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Bu cihazda bildirimler",
|
||||
'push.deviceHint': "Uygulama kapalıyken bile. Aşağıdaki seçimler de geçerlidir.",
|
||||
'push.iosInstall': "iPhone ve iPad’de önce AzuuCine’i Ana Ekran’a ekle (iOS 16.4 veya üstü), ardından bildirimleri açmak için uygulamayı simgesinden aç.",
|
||||
'push.unsupported': "Bu tarayıcı anlık bildirimleri desteklemiyor.",
|
||||
'push.denied': "Bu site için bildirimler engellendi. Tarayıcı ayarlarından izin ver ve tekrar dene.",
|
||||
'push.notReady': "Anlık bildirimler sunucuda henüz kullanılamıyor.",
|
||||
'push.error': "Bildirimler açılamadı. Bağlantını kontrol edip tekrar dene.",
|
||||
'netPill.offlineSync': "Çevrimdışı — değişikliklerin eşitlenecek",
|
||||
'netPill.offlineLocal': "Çevrimdışı — her şey bu cihazda kayıtlı kalır",
|
||||
'netPill.synced': "Eşitlendi",
|
||||
'netPill.hide': "Gizle",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} thay đổi đang chờ",
|
||||
'sync.pending_other': "{count} thay đổi đang chờ",
|
||||
'sync.now': "Đồng bộ ngay",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "Thông báo trên thiết bị này",
|
||||
'push.deviceHint': "Ngay cả khi ứng dụng đã đóng. Các lựa chọn bên dưới cũng được áp dụng.",
|
||||
'push.iosInstall': "Trên iPhone và iPad, trước tiên hãy thêm AzuuCine vào Màn hình chính (iOS 16.4 trở lên), sau đó mở ứng dụng từ biểu tượng để bật thông báo.",
|
||||
'push.unsupported': "Trình duyệt này không hỗ trợ thông báo đẩy.",
|
||||
'push.denied': "Thông báo đã bị chặn cho trang này. Hãy cho phép trong cài đặt trình duyệt rồi thử lại.",
|
||||
'push.notReady': "Máy chủ chưa hỗ trợ thông báo đẩy.",
|
||||
'push.error': "Không thể bật thông báo. Kiểm tra kết nối rồi thử lại.",
|
||||
'netPill.offlineSync': "Ngoại tuyến — thay đổi của bạn sẽ được đồng bộ",
|
||||
'netPill.offlineLocal': "Ngoại tuyến — mọi thứ vẫn được lưu trên thiết bị này",
|
||||
'netPill.synced': "Đã đồng bộ",
|
||||
'netPill.hide': "Ẩn",
|
||||
}
|
||||
|
||||
export default dict
|
||||
@@ -897,6 +897,18 @@ const dict: Translations = {
|
||||
'sync.pending_one': "{count} 项更改待上传",
|
||||
'sync.pending_other': "{count} 项更改待上传",
|
||||
'sync.now': "立即同步",
|
||||
// — Notifications push & indicateur hors-ligne —
|
||||
'push.device': "此设备上的通知",
|
||||
'push.deviceHint': "即使应用已关闭也会提醒。下方的选项同样适用。",
|
||||
'push.iosInstall': "在 iPhone 和 iPad 上,请先将 AzuuCine 添加到主屏幕(iOS 16.4 或更高版本),再从图标打开应用以开启通知。",
|
||||
'push.unsupported': "此浏览器不支持推送通知。",
|
||||
'push.denied': "此网站的通知已被阻止。请在浏览器设置中允许后重试。",
|
||||
'push.notReady': "服务器暂未开放推送通知。",
|
||||
'push.error': "无法开启通知。请检查网络连接后重试。",
|
||||
'netPill.offlineSync': "离线 — 你的修改将稍后同步",
|
||||
'netPill.offlineLocal': "离线 — 所有内容都保存在此设备上",
|
||||
'netPill.synced': "已同步",
|
||||
'netPill.hide': "隐藏",
|
||||
}
|
||||
|
||||
export default dict
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
import { getLang } from '../i18n'
|
||||
import { cloudFetch } from './cloud/api'
|
||||
import { cloudEnabled } from './cloud/config'
|
||||
import { detectPlatform } from './pwa'
|
||||
import { scopedKey } from './scope'
|
||||
import { isPlainObject, storageGet, storageSet } from './security'
|
||||
|
||||
/**
|
||||
* Notifications push (Web Push) sur cet appareil :
|
||||
* - la permission n'est demandée qu'au clic sur l'interrupteur (jamais au chargement) ;
|
||||
* - l'abonnement du navigateur est enregistré sur le serveur (register_push_subscription) ;
|
||||
* - le serveur envoie ensuite les notifications de la cloche, même app fermée.
|
||||
*/
|
||||
|
||||
export type PushSupport = 'ok' | 'unsupported' | 'needs-install'
|
||||
export type PushState = 'unsupported' | 'needs-install' | 'denied' | 'off' | 'on'
|
||||
|
||||
export class PushError extends Error {
|
||||
constructor(public code: 'denied' | 'not-ready' | 'failed') {
|
||||
super(code)
|
||||
}
|
||||
}
|
||||
|
||||
/** Dernier enregistrement réussi (par compte) */
|
||||
const storeKey = () => scopedKey('push')
|
||||
const REFRESH_MS = 7 * 24 * 3600 * 1000
|
||||
|
||||
function isStandalone(): boolean {
|
||||
return window.matchMedia?.('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true
|
||||
}
|
||||
|
||||
/** Ce navigateur sait-il recevoir des notifications push ? (iPhone : seulement l'app installée, iOS 16.4+) */
|
||||
export function pushSupport(): PushSupport {
|
||||
if (!cloudEnabled || typeof window === 'undefined') return 'unsupported'
|
||||
const api = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window
|
||||
if (detectPlatform() === 'ios' && (!isStandalone() || !api)) return 'needs-install'
|
||||
return api ? 'ok' : 'unsupported'
|
||||
}
|
||||
|
||||
function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new PushError('failed')), ms)
|
||||
p.then(
|
||||
(v) => {
|
||||
clearTimeout(timer)
|
||||
resolve(v)
|
||||
},
|
||||
(e) => {
|
||||
clearTimeout(timer)
|
||||
reject(e)
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** Service worker actif (absent en mode développement : on n'attend pas indéfiniment). */
|
||||
const registration = () => withTimeout(navigator.serviceWorker.ready, 8000)
|
||||
|
||||
async function currentSubscription(): Promise<PushSubscription | null> {
|
||||
const reg = await navigator.serviceWorker.getRegistration()
|
||||
return (await reg?.pushManager.getSubscription()) ?? null
|
||||
}
|
||||
|
||||
export async function getPushState(): Promise<PushState> {
|
||||
const support = pushSupport()
|
||||
if (support !== 'ok') return support
|
||||
if (Notification.permission === 'denied') return 'denied'
|
||||
if (Notification.permission !== 'granted') return 'off'
|
||||
try {
|
||||
return (await currentSubscription()) ? 'on' : 'off'
|
||||
} catch {
|
||||
return 'off'
|
||||
}
|
||||
}
|
||||
|
||||
function b64urlToBytes(s: string): Uint8Array<ArrayBuffer> {
|
||||
const b64 = s.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4))
|
||||
const out = new Uint8Array(new ArrayBuffer(bin.length))
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
||||
return out
|
||||
}
|
||||
|
||||
function bytesToB64url(buf: ArrayBuffer | null): string {
|
||||
if (!buf) return ''
|
||||
let s = ''
|
||||
for (const b of new Uint8Array(buf)) s += String.fromCharCode(b)
|
||||
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
/** Clé publique VAPID du serveur (la clé privée ne quitte jamais Supabase). */
|
||||
async function serverKey(): Promise<string> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await cloudFetch('/functions/v1/send-push')
|
||||
} catch {
|
||||
throw new PushError('failed')
|
||||
}
|
||||
if (res.status === 404 || res.status === 503) throw new PushError('not-ready')
|
||||
if (!res.ok) throw new PushError('failed')
|
||||
const body = (await res.json().catch(() => null)) as unknown
|
||||
const key = isPlainObject(body) && typeof body.publicKey === 'string' ? body.publicKey : ''
|
||||
if (!/^B[A-Za-z0-9_-]{86}$/.test(key)) throw new PushError('not-ready')
|
||||
return key
|
||||
}
|
||||
|
||||
/** Petit libellé de l'appareil (« Chrome · Android ») pour s'y retrouver côté serveur. */
|
||||
function deviceLabel(): string {
|
||||
const ua = navigator.userAgent
|
||||
const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Web'
|
||||
const p = detectPlatform()
|
||||
const os = p === 'ios' ? 'iOS' : p === 'android' ? 'Android' : /Windows/.test(ua) ? 'Windows' : /Mac/.test(ua) ? 'macOS' : /Linux|CrOS/.test(ua) ? 'Linux' : ''
|
||||
return os ? `${browser} · ${os}` : browser
|
||||
}
|
||||
|
||||
async function register(sub: PushSubscription): Promise<void> {
|
||||
const lang = getLang()
|
||||
const res = await cloudFetch('/rest/v1/rpc/register_push_subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
p_endpoint: sub.endpoint,
|
||||
p_p256dh: bytesToB64url(sub.getKey('p256dh')),
|
||||
p_auth: bytesToB64url(sub.getKey('auth')),
|
||||
p_lang: lang,
|
||||
p_ua: deviceLabel(),
|
||||
}),
|
||||
})
|
||||
if (res.status === 404) throw new PushError('not-ready')
|
||||
if (!res.ok) throw new PushError('failed')
|
||||
storageSet(storeKey(), JSON.stringify({ endpoint: sub.endpoint, lang, at: Date.now() }))
|
||||
}
|
||||
|
||||
/** Active les notifications push sur cet appareil. À appeler uniquement depuis un clic. */
|
||||
export async function enablePush(): Promise<PushState> {
|
||||
const support = pushSupport()
|
||||
if (support !== 'ok') return support
|
||||
const permission = await Notification.requestPermission()
|
||||
if (permission === 'denied') throw new PushError('denied')
|
||||
if (permission !== 'granted') return 'off'
|
||||
|
||||
const key = await serverKey()
|
||||
const reg = await registration()
|
||||
let sub = await reg.pushManager.getSubscription()
|
||||
// Abonnement créé avec une autre clé serveur (clés VAPID changées) : on le refait
|
||||
if (sub && sub.options.applicationServerKey && bytesToB64url(sub.options.applicationServerKey) !== key) {
|
||||
await sub.unsubscribe().catch(() => false)
|
||||
sub = null
|
||||
}
|
||||
if (!sub) {
|
||||
try {
|
||||
sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64urlToBytes(key) })
|
||||
} catch {
|
||||
throw new PushError(Notification.permission === 'denied' ? 'denied' : 'failed')
|
||||
}
|
||||
}
|
||||
try {
|
||||
await register(sub)
|
||||
} catch (e) {
|
||||
await sub.unsubscribe().catch(() => false)
|
||||
throw e instanceof PushError ? e : new PushError('failed')
|
||||
}
|
||||
return 'on'
|
||||
}
|
||||
|
||||
/** Coupe les notifications push sur cet appareil (et retire l'appareil du serveur). */
|
||||
export async function disablePush(): Promise<void> {
|
||||
if (pushSupport() !== 'ok') return
|
||||
const sub = await currentSubscription().catch(() => null)
|
||||
storageSet(storeKey(), null)
|
||||
if (!sub) return
|
||||
try {
|
||||
await cloudFetch('/rest/v1/rpc/unregister_push_subscription', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ p_endpoint: sub.endpoint }),
|
||||
})
|
||||
} catch {
|
||||
/* hors-ligne : le serveur oubliera l'abonnement au premier envoi refusé (410) */
|
||||
}
|
||||
await sub.unsubscribe().catch(() => false)
|
||||
}
|
||||
|
||||
/** Désabonne seulement le navigateur (compte supprimé : le serveur a déjà tout effacé). */
|
||||
export async function forgetPushLocally(): Promise<void> {
|
||||
storageSet(storeKey(), null)
|
||||
if (pushSupport() !== 'ok') return
|
||||
const sub = await currentSubscription().catch(() => null)
|
||||
await sub?.unsubscribe().catch(() => false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Au lancement : réenregistre l'abonnement si le navigateur l'a renouvelé, si la langue a changé,
|
||||
* ou une fois par semaine (le serveur garde ainsi les appareils réellement utilisés).
|
||||
*/
|
||||
export async function keepPushFresh(): Promise<void> {
|
||||
if (pushSupport() !== 'ok' || Notification.permission !== 'granted' || !navigator.onLine) return
|
||||
const sub = await currentSubscription().catch(() => null)
|
||||
if (!sub) return
|
||||
let saved: unknown = null
|
||||
try {
|
||||
saved = JSON.parse(storageGet(storeKey()) ?? 'null')
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// Pas d'enregistrement connu : l'abonnement n'a pas été créé par ce compte, on n'y touche pas
|
||||
if (!isPlainObject(saved)) return
|
||||
const fresh = saved.endpoint === sub.endpoint && saved.lang === getLang() && typeof saved.at === 'number' && Date.now() - saved.at < REFRESH_MS
|
||||
if (!fresh) await register(sub).catch(() => {})
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { LanguageSelect } from '../i18n/react'
|
||||
import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import AccountSection from '../components/AccountSection'
|
||||
import PushToggle from '../components/PushToggle'
|
||||
import ConfirmDialog from '../components/ConfirmDialog'
|
||||
import { PageHeader, SectionTitle } from '../components/ui'
|
||||
import { exportBackup, parseBackupFile, type ParsedBackup } from '../lib/backup'
|
||||
@@ -308,6 +309,7 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
|
||||
<>
|
||||
<SectionTitle>{t('settings.notifs')}</SectionTitle>
|
||||
<p className="mb-3 text-xs text-ink-3">{t('settings.notifsHint')}</p>
|
||||
<PushToggle />
|
||||
<div className="card divide-y divide-line overflow-hidden">
|
||||
{NOTIF_PREFS.map(({ key, label }) => {
|
||||
const on = settings.notifPrefs?.[key] !== false
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createSync, type SyncEngine, type SyncStatus } from './lib/cloud/sync'
|
||||
import { deleteDatabase, readOtherDatabase } from './lib/db'
|
||||
import { cloudFetch } from './lib/cloud/api'
|
||||
import { signOut } from './lib/cloud/auth'
|
||||
import { disablePush, forgetPushLocally } from './lib/push'
|
||||
import { dbNameFor, scopedKey } from './lib/scope'
|
||||
import { isPlainObject, LIMITS, readStorage, storageGet, storageSet } from './lib/security'
|
||||
import { mediaDB, requestPersistentStorage } from './lib/db'
|
||||
@@ -396,6 +397,8 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl
|
||||
if (engine && navigator.onLine) await engine.syncNow()
|
||||
if (!force && engine && engine.status().pending > 0) return 'pending'
|
||||
engine?.stop()
|
||||
// Cet appareil ne doit plus recevoir les notifications push de ce compte
|
||||
await disablePush().catch(() => {})
|
||||
await wipeAccountFromDevice(userId)
|
||||
await signOut()
|
||||
return 'done'
|
||||
@@ -408,6 +411,7 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl
|
||||
})
|
||||
if (!res.ok) throw new Error(res.status === 429 ? t('account.err.deleteRate') : t('account.err.delete'))
|
||||
syncRef.current?.stop()
|
||||
await forgetPushLocally().catch(() => {})
|
||||
await wipeAccountFromDevice(userId)
|
||||
await signOut()
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user