Suppression du système de notifications
- Plus de cloche sur l'accueil ni de panneau de notifications. - Plus de notifications push : réglage retiré, service worker sans push-sw.js, fonction send-push et script VAPID supprimés du dépôt. - Réglages « Notifications » retirés (et notifPrefs des réglages synchronisés). - Plus d'envoi des nouveaux épisodes au serveur pour les notifications. - Au lancement, l'appli résilie l'ancien abonnement push de l'appareil s'il en reste un. - Textes retirés des 18 langues ; politique de confidentialité mise à jour. - Serveur : migration 20261122120000_remove_notifications.sql (déjà appliquée en ligne) : plus aucune notification créée ni envoyée, données vidées. - Les demandes d'abonnement et invitations aux listes restent accessibles depuis le profil et les listes partagées. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
43 files changed
+62
-2298
No files matched your search
+1
-6
@@ -1,5 +1,5 @@
|
||||
import { t } from '../i18n'
|
||||
import type { BackupFile, Criteria, CustomList, MediaItem, MediaType, NotifPrefs, Settings, TopCategory, TopEntry, WatchStatus } from '../types'
|
||||
import type { BackupFile, Criteria, CustomList, MediaItem, MediaType, Settings, TopCategory, TopEntry, WatchStatus } from '../types'
|
||||
import { ALL_TOP_CATEGORIES, MEDIA_TYPES, STATUSES } from './constants'
|
||||
import { episodeCap } from './franchise'
|
||||
import { convertLegacyBackup, isLegacyBackup } from './legacyImport'
|
||||
@@ -154,11 +154,6 @@ export function normalizeSettings(raw: unknown): Partial<Settings> | undefined {
|
||||
if (Array.isArray(raw.topCategories)) out.topCategories = ALL_TOP_CATEGORIES.filter((c) => (raw.topCategories as unknown[]).includes(c))
|
||||
if (isHexColor(raw.accentColor)) out.accentColor = raw.accentColor.toLowerCase()
|
||||
if (raw.themeMode === 'auto' || raw.themeMode === 'light' || raw.themeMode === 'dark' || raw.themeMode === 'night' || raw.themeMode === 'starfield') out.themeMode = raw.themeMode
|
||||
if (isPlainObject(raw.notifPrefs)) {
|
||||
const np: NotifPrefs = {}
|
||||
for (const k of ['episodes', 'follows', 'accepted', 'reactions', 'comments', 'lists'] as const) if (typeof raw.notifPrefs[k] === 'boolean') np[k] = raw.notifPrefs[k] as boolean
|
||||
out.notifPrefs = np
|
||||
}
|
||||
const challenges = normalizeChallenges(raw.challenges)
|
||||
if (challenges) out.challenges = challenges
|
||||
if (Array.isArray(raw.statsHiddenMonths)) {
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import { t } from '../../i18n'
|
||||
import { cleanText, isPlainObject, safeIso } from '../security'
|
||||
import { cloudFetch } from './api'
|
||||
import { safeMediaUrl } from './social'
|
||||
|
||||
/** Notifications (cloche) : abonnements, demandes acceptées, réactions reçues. */
|
||||
|
||||
export type NotificationKind =
|
||||
| 'follow_request'
|
||||
| 'follow_accepted'
|
||||
| 'new_follower'
|
||||
| 'reaction'
|
||||
| 'new_episode'
|
||||
| 'new_season'
|
||||
| 'review_comment'
|
||||
| 'shared_list_invite'
|
||||
|
||||
export interface AppNotification {
|
||||
id: number
|
||||
kind: NotificationKind
|
||||
created_at: string
|
||||
read_at: string | null
|
||||
emoji: string | null
|
||||
item_id: string | null
|
||||
/** Numéro du dernier épisode sorti (épisodes) */
|
||||
episode: number | null
|
||||
/** Nombre de nouveaux épisodes (épisodes) */
|
||||
ep_count: number | null
|
||||
actor: { username: string; display_name: string; avatar_url: string | null } | null
|
||||
/** Titre de la fiche concernée (réactions, commentaires, épisodes) ou nom de la liste partagée */
|
||||
title: string | null
|
||||
/** Invitation à une liste partagée : en attente, acceptée, ou plus valable (null) */
|
||||
invite_status: 'pending' | 'accepted' | null
|
||||
}
|
||||
|
||||
/** Épisode/saison à signaler (envoyé après la vérification des sorties). */
|
||||
export interface EpisodeNotice {
|
||||
item_id: string
|
||||
kind: 'new_episode' | 'new_season'
|
||||
/** Dernier épisode sorti */
|
||||
episode: number
|
||||
/** Nombre de nouveaux épisodes */
|
||||
count: number
|
||||
}
|
||||
|
||||
/** Enregistre les nouveaux épisodes des séries suivies (dédoublonné côté serveur). Renvoie le nombre créé. */
|
||||
export async function addEpisodeNotifications(list: EpisodeNotice[]): Promise<number> {
|
||||
if (!list.length) return 0
|
||||
try {
|
||||
const n = await rpc<number>('add_episode_notifications', { p_list: list })
|
||||
return typeof n === 'number' ? n : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(args),
|
||||
})
|
||||
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
const KINDS: NotificationKind[] = ['follow_request', 'follow_accepted', 'new_follower', 'reaction', 'new_episode', 'new_season', 'review_comment', 'shared_list_invite']
|
||||
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
|
||||
|
||||
/** Réponse du serveur relue champ par champ (adresses d'images comprises), comme pour les profils. */
|
||||
function toNotification(v: unknown): AppNotification | null {
|
||||
if (!isPlainObject(v) || typeof v.id !== 'number' || !KINDS.includes(v.kind as NotificationKind)) return null
|
||||
const created = safeIso(v.created_at)
|
||||
if (!created) return null
|
||||
const a = isPlainObject(v.actor) ? v.actor : null
|
||||
const username = a && typeof a.username === 'string' && /^[a-z0-9_]{3,20}$/.test(a.username) ? a.username : null
|
||||
return {
|
||||
id: v.id,
|
||||
kind: v.kind as NotificationKind,
|
||||
created_at: created,
|
||||
read_at: safeIso(v.read_at) ?? null,
|
||||
emoji: cleanText(v.emoji, 8) ?? null,
|
||||
item_id: cleanText(v.item_id, 64) ?? null,
|
||||
episode: num(v.episode),
|
||||
ep_count: num(v.ep_count),
|
||||
actor: username ? { username, display_name: cleanText(a!.display_name, 40) ?? username, avatar_url: safeMediaUrl(a!.avatar_url) ?? null } : null,
|
||||
title: cleanText(v.title, 300) ?? null,
|
||||
invite_status: v.invite_status === 'pending' || v.invite_status === 'accepted' ? v.invite_status : null,
|
||||
}
|
||||
}
|
||||
|
||||
export const listNotifications = async (offset = 0): Promise<AppNotification[]> => {
|
||||
const raw = await rpc<unknown>('get_notifications', { p_offset: offset })
|
||||
return (Array.isArray(raw) ? raw : []).map(toNotification).filter((n): n is AppNotification => n !== null)
|
||||
}
|
||||
|
||||
export async function unreadCount(): Promise<number> {
|
||||
try {
|
||||
const n = await rpc<number>('notifications_unread')
|
||||
return typeof n === 'number' ? n : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
export async function markNotificationsRead(): Promise<void> {
|
||||
await rpc('mark_notifications_read')
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import { cloudFetch } from './api'
|
||||
* En cas de conflit, la modification la plus récente gagne (vérifié aussi par la base).
|
||||
*/
|
||||
|
||||
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor' | 'themeMode' | 'notifPrefs' | 'challenges' | 'statsHiddenMonths'>
|
||||
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor' | 'themeMode' | 'challenges' | 'statsHiddenMonths'>
|
||||
|
||||
export interface SyncHooks {
|
||||
getLists: () => CustomList[]
|
||||
|
||||
+12
-201
@@ -1,210 +1,21 @@
|
||||
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.
|
||||
* Les notifications ont été retirées de l'app (novembre 2026).
|
||||
* Un appareil qui les avait activées garde un abonnement dans son navigateur : on le résilie
|
||||
* au lancement, pour qu'il ne reste rien. Le serveur, lui, n'en envoie plus aucune.
|
||||
*/
|
||||
|
||||
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'
|
||||
export async function dropPushSubscription(): Promise<void> {
|
||||
try {
|
||||
return (await currentSubscription()) ? 'on' : 'off'
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) return
|
||||
const reg = await navigator.serviceWorker.getRegistration()
|
||||
const sub = await reg?.pushManager.getSubscription()
|
||||
await sub?.unsubscribe()
|
||||
} catch {
|
||||
return 'off'
|
||||
/* rien à faire */
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// Ancien état local des notifications push
|
||||
try {
|
||||
res = await cloudFetch('/functions/v1/send-push')
|
||||
for (const k of Object.keys(localStorage)) if (/^azuucine:(?:[^:]+:)?push$/.test(k)) localStorage.removeItem(k)
|
||||
} catch {
|
||||
throw new PushError('failed')
|
||||
/* stockage indisponible */
|
||||
}
|
||||
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(() => {})
|
||||
}
|
||||
Reference in new issue
Block a user