diff --git a/src/components/SharePreview.tsx b/src/components/SharePreview.tsx index b0dcff8..82b1995 100644 --- a/src/components/SharePreview.tsx +++ b/src/components/SharePreview.tsx @@ -1,7 +1,7 @@ import { t } from '../i18n' import { Download, Share2, X } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' -import { shareImage } from '../lib/shareCard' +import { shareImage } from '../lib/shareImage' import { useBackToClose } from '../lib/backNav' import { useEscape } from '../lib/escape' import { useScrollLock } from '../lib/scrollLock' diff --git a/src/components/moderation/BugReport.tsx b/src/components/moderation/BugReport.tsx index 51e5116..69cdf93 100644 --- a/src/components/moderation/BugReport.tsx +++ b/src/components/moderation/BugReport.tsx @@ -57,7 +57,7 @@ export function BugReportRow() { } /** Formulaire « Signaler un bug » : description + infos techniques (montrées avant l'envoi, rien de personnel). */ -export default function BugReportDialog({ onClose }: { onClose: () => void }) { +function BugReportDialog({ onClose }: { onClose: () => void }) { const { settings } = useMedia() const info = useMemo(() => techInfo(settings.themeMode), [settings.themeMode]) const [text, setText] = useState('') diff --git a/src/components/title/TitleSheet.tsx b/src/components/title/TitleSheet.tsx index 2954f27..e7ec1ff 100644 --- a/src/components/title/TitleSheet.tsx +++ b/src/components/title/TitleSheet.tsx @@ -5,7 +5,6 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { getTitleExtras, getTmdbCredits, getTmdbDetails, getTmdbExtras, type SearchResult, type TitleExtras } from '../../lib/catalogApi' import { CRITERIA, STATUS_BY_VALUE, TYPE_BY_VALUE } from '../../lib/constants' import { genreLabel } from '../../lib/genres' -import { remotePosterToLocal } from '../../lib/image' import { airedCount, nextAirDate, useAiringCache } from '../../lib/airing' import { useBackToClose } from '../../lib/backNav' import { useEscape } from '../../lib/escape' @@ -164,8 +163,9 @@ export default function TitleSheet({ item: initial, seed, onClose, onOpenPerson, try { const base: Partial = { ...(seed.source === 'tmdb' ? meta : seed.prefill) } if (seed.source === 'tmdb' && !meta) Object.assign(base, await getTmdbDetails(seed, settings.tmdbKey ?? '')) - // TMDB autorise la copie locale de l'affiche (visible hors-ligne) ; AniList non, on garde l'adresse. - if (seed.posterUrl) base.poster = seed.source === 'tmdb' ? await remotePosterToLocal(seed.posterUrl).catch(() => seed.posterUrl) : seed.posterUrl + // On garde l'adresse de l'affiche (le service worker la met en cache : visible hors-ligne). La copier dans + // la fiche l'alourdissait d'environ 50 Ko, renvoyés au serveur à chaque modification et chez les amis. + if (seed.posterUrl) base.poster = seed.posterUrl if (extras?.average != null) base.publicRating = extras.average const created = await add({ ...BLANK, diff --git a/src/lib/backup.ts b/src/lib/backup.ts index 0aa3527..a6c077d 100644 --- a/src/lib/backup.ts +++ b/src/lib/backup.ts @@ -2,7 +2,6 @@ import { t } from '../i18n' 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' import { cleanThemeMode } from './theme' import { cleanText, @@ -225,9 +224,14 @@ export async function parseBackupFile(file: File): Promise { } catch { throw new Error(t('backup.notJson')) } - if (isLegacyBackup(data)) { - const legacy = convertLegacyBackup(data) - return { items: dedupe(legacy.items), skipped: legacy.skipped, format: 'legacy' } + // Ancien format (AzuuCine) : son convertisseur n'est chargé que pour ces fichiers-là + const first = isPlainObject(data) && Array.isArray(data.items) ? (data.items[0] as unknown) : undefined + if (isPlainObject(first) && ('tmdb_id' in first || 'media_type' in first || 'poster_path' in first)) { + const { convertLegacyBackup, isLegacyBackup } = await import('./legacyImport') + if (isLegacyBackup(data)) { + const legacy = convertLegacyBackup(data) + return { items: dedupe(legacy.items), skipped: legacy.skipped, format: 'legacy' } + } } const rawItems = Array.isArray(data) ? data : isPlainObject(data) && Array.isArray(data.items) ? data.items : null if (!rawItems) throw new Error(t('backup.noItems')) diff --git a/src/lib/image.ts b/src/lib/image.ts index b87640f..e2bcb7b 100644 --- a/src/lib/image.ts +++ b/src/lib/image.ts @@ -1,8 +1,8 @@ import { t } from '../i18n' -import { LIMITS, safePosterUrl } from './security' +import { LIMITS } from './security' /** - * Convertit une image (photo de la galerie, affiche téléchargée…) en petit JPEG + * Convertit une image (photo de la galerie) en petit JPEG * compressé (data URL), pour garder la base légère et 100 % hors-ligne. */ export function blobToPosterDataURL(blob: Blob, maxWidth = 360, quality = 0.8): Promise { @@ -42,29 +42,6 @@ export function fileToPosterDataURL(file: File) { return blobToPosterDataURL(file) } -/** - * Télécharge une affiche distante et la garde en local (visible hors-ligne). - * Si le serveur refuse (CORS, réseau), on garde simplement l'URL. - */ -export async function remotePosterToLocal(url: string): Promise { - const safe = safePosterUrl(url) - if (!safe || safe.startsWith('data:')) return safe - try { - const res = await fetch(safe, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(15_000) }) - // Réponse en erreur ou annoncée trop grosse : on ne lit pas le corps - const announced = Number(res.headers.get('Content-Length')) - if (!res.ok || (Number.isFinite(announced) && announced > LIMITS.imageFileBytes)) { - await res.body?.cancel().catch(() => {}) - return safe - } - const blob = await res.blob() - if (!blob.type.startsWith('image/') || blob.size > LIMITS.imageFileBytes) return safe - return await blobToPosterDataURL(blob) - } catch { - return safe - } -} - /** * Photo de profil ou bannière : recadrée au centre aux dimensions voulues et ré-encodée en JPEG * (aucune métadonnée cachée n'est conservée). diff --git a/src/lib/releaseAdd.ts b/src/lib/releaseAdd.ts index 7f624b4..939770c 100644 --- a/src/lib/releaseAdd.ts +++ b/src/lib/releaseAdd.ts @@ -1,5 +1,4 @@ import { findTmdbSeries, getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease } from './catalogApi' -import { remotePosterToLocal } from './image' import type { MediaInput } from '../types' /** @@ -13,7 +12,7 @@ export async function releaseToInput(r: GlobalRelease, tmdbKey?: string): Promis const series = r.externalId.startsWith('anilist:') && hasKey ? await findTmdbSeries([r.title, r.originalTitle], tmdbKey!).catch(() => undefined) : undefined if (series) { data = await getTmdbDetails(series, tmdbKey!) - poster = series.posterUrl ? await remotePosterToLocal(series.posterUrl) : undefined + poster = series.posterUrl } else if (r.externalId.startsWith('anilist:')) { const res = await getAniListById(r.externalId) data = { ...res?.prefill } @@ -21,7 +20,7 @@ export async function releaseToInput(r: GlobalRelease, tmdbKey?: string): Promis } else { const res = releaseToResult(r) if (res && hasKey) data = await getTmdbDetails(res, tmdbKey!) - poster = r.poster ? await remotePosterToLocal(r.poster) : undefined + poster = r.poster } return { title: r.title, diff --git a/src/lib/shareCard.ts b/src/lib/shareCard.ts index 7b2271a..3bb3fca 100644 --- a/src/lib/shareCard.ts +++ b/src/lib/shareCard.ts @@ -423,28 +423,6 @@ export async function renderTopCard(title: string, entries: (MediaItem | undefin return toBlob(canvas) } -/** Ouvre la feuille de partage (mobile) ou télécharge l'image. */ -export async function shareImage(blob: Blob, filename: string, title: string): Promise<'shared' | 'downloaded'> { - const file = new File([blob], filename, { type: 'image/png' }) - if (navigator.canShare?.({ files: [file] })) { - try { - await navigator.share({ files: [file], title }) - return 'shared' - } catch (e) { - if ((e as DOMException)?.name === 'AbortError') return 'shared' - } - } - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = filename - document.body.appendChild(a) - a.click() - a.remove() - setTimeout(() => URL.revokeObjectURL(url), 2000) - return 'downloaded' -} - export const slug = (s: string) => s .normalize('NFD') diff --git a/src/lib/shareImage.ts b/src/lib/shareImage.ts new file mode 100644 index 0000000..00676fd --- /dev/null +++ b/src/lib/shareImage.ts @@ -0,0 +1,23 @@ +// Petit module à part : la fenêtre d'aperçu l'importe directement, sans embarquer le dessin des cartes (shareCard, chargé à la demande). + +/** Ouvre la feuille de partage (mobile) ou télécharge l'image. */ +export async function shareImage(blob: Blob, filename: string, title: string): Promise<'shared' | 'downloaded'> { + const file = new File([blob], filename, { type: 'image/png' }) + if (navigator.canShare?.({ files: [file] })) { + try { + await navigator.share({ files: [file], title }) + return 'shared' + } catch (e) { + if ((e as DOMException)?.name === 'AbortError') return 'shared' + } + } + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = filename + document.body.appendChild(a) + a.click() + a.remove() + setTimeout(() => URL.revokeObjectURL(url), 2000) + return 'downloaded' +} diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index 90a7eea..63075dc 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -1,10 +1,9 @@ import { t } from '../i18n' import { LanguageSelect } from '../i18n/react' import { Check, Download, ExternalLink, HardDrive, Import, ShieldCheck, Trash2, Upload, UserX } from 'lucide-react' -import { useEffect, useRef, useState, type ReactNode } from 'react' +import { lazy, Suspense, useEffect, useRef, useState, type ReactNode } from 'react' import AccountSection from '../components/AccountSection' import ConfirmDialog from '../components/ConfirmDialog' -import ImportWizard from '../components/ImportWizard' import { PageHeader, SectionTitle } from '../components/ui' import { exportBackup, parseBackupFile, type ParsedBackup } from '../lib/backup' import { ALL_TOP_CATEGORIES, TOP_CATEGORIES } from '../lib/constants' @@ -16,6 +15,9 @@ import { BugReportRow } from '../components/moderation/BugReport' import { alertsSummary, useAdminAlerts } from '../components/moderation/useAdminAlerts' import { APP_VERSION, buildLabel } from '../lib/appInfo' +// Assistant d'import (lecture des fichiers, recherche des titres) : chargé seulement quand on l'ouvre +const ImportWizard = lazy(() => import('../components/ImportWizard')) + type Message = { kind: 'ok' | 'error'; text: string } function Row({ icon, title, hint, onClick, danger }: { icon: ReactNode; title: string; hint?: string; onClick: () => void; danger?: boolean }) { @@ -221,7 +223,11 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void onFile(e.target.files?.[0])} /> } title={t('import.row')} hint={t('import.rowHint')} onClick={() => setShowImport(true)} /> - {showImport && setShowImport(false)} />} + {showImport && ( + + setShowImport(false)} /> + + )} {pending && (
diff --git a/supabase/migrations/20261129120000_cleanup_indexes.sql b/supabase/migrations/20261129120000_cleanup_indexes.sql new file mode 100644 index 0000000..da2b889 --- /dev/null +++ b/supabase/migrations/20261129120000_cleanup_indexes.sql @@ -0,0 +1,12 @@ +-- Bobinoo — 29 nov. 2026 : ménage de la base. Idempotent. +-- 1) pg_net ne sert plus (les notifications push ont été retirées ; aucune fonction ni déclencheur ne l'utilise). +-- L'extension était en plus installée dans le schéma public (alerte de sécurité Supabase). +drop extension if exists pg_net; + +-- 2) Notifications : un index taillé pour les lectures (mes notifications, les plus récentes d'abord, triées par id : +-- liste, compteur de non-lues, nettoyage des 200 plus récentes)… +create index if not exists notifications_user_id_idx on public.notifications (user_id, id desc); +-- … qui remplace (user_id, created_at), plus utilisé par aucune requête, +drop index if exists public.notifications_user_idx; +-- … et un doublon : (user_id, actor_id, kind) couvre déjà (user_id, actor_id). +drop index if exists public.notifications_user_actor_idx; diff --git a/vite.config.ts b/vite.config.ts index 7b0fa6b..8d7eedf 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -81,7 +81,22 @@ export default defineConfig(({ mode }) => { // Le serveur de dev n'écoute que sur ce PC (voir « npm run dev:mobile » pour tester sur le téléphone) server: { host: 'localhost', strictPort: false }, preview: { host: 'localhost' }, - build: { sourcemap: false }, + build: { + sourcemap: false, + rollupOptions: { + output: { + // React à part : il change rarement, il reste donc en cache d'une mise à jour de l'app à l'autre + manualChunks: (id) => (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id) ? 'react' : undefined), + // Noms reconnaissables : les langues et l'administration ne sont pas pré-téléchargées (voir workbox plus bas) + chunkFileNames: (chunk) => { + const id = chunk.facadeModuleId ?? '' + if (/[\\/]src[\\/]i18n[\\/]locales[\\/]/.test(id)) return 'assets/locale-[name]-[hash].js' + if (/[\\/]src[\\/]pages[\\/](AdminPage|admin[\\/])/.test(id)) return 'assets/admin-[name]-[hash].js' + return 'assets/[name]-[hash].js' + }, + }, + }, + }, plugins: [ contentSecurityPolicy(supabaseUrl), react(), @@ -108,6 +123,10 @@ export default defineConfig(({ mode }) => { }, workbox: { globPatterns: ['**/*.{js,css,html,svg,png,ico,webmanifest,woff2}'], + // Pas pré-téléchargés pour tout le monde (~1 Mo) : les 17 autres langues (le français est dans l'app), + // l'administration et les variantes de la police pour d'autres alphabets. Ils passent par le cache « app-files » + // dès qu'on s'en sert (langue choisie, écran admin…), donc restent disponibles hors-ligne ensuite. + globIgnores: ['**/assets/locale-*.js', '**/assets/admin-*.js', '**/assets/epilogue-latin-ext-*.woff2', '**/assets/epilogue-vietnamese-*.woff2'], // L'app vit entièrement sur « / » (routes après le #) : toute autre adresse reçoit la page 404 du serveur navigateFallbackAllowlist: [/^\/(?:index\.html)?(?:\?.*)?$/], // Les pages légales sont de vraies pages, pas l'app @@ -115,15 +134,52 @@ export default defineConfig(({ mode }) => { // Les affiches AniList ne peuvent pas être copiées dans la base (CORS) : // on les garde en cache après le premier affichage pour les voir hors-ligne. runtimeCaching: [ + // Fichiers de l'app non pré-téléchargés (langues, admin, police) : leur nom change à chaque modification, + // une copie en cache est donc toujours la bonne { - urlPattern: /^https:\/\/(s4\.anilist\.co|image\.tmdb\.org)\//, + urlPattern: /\/assets\/(locale-|admin-|epilogue-).+\.(js|woff2)$/, + handler: 'CacheFirst', + options: { cacheName: 'app-files', expiration: { maxEntries: 40, maxAgeSeconds: 60 * 60 * 24 * 180 }, cacheableResponse: { statuses: [200] } }, + }, + // Affiches, photos et images d'épisodes (petites tailles) : visibles hors-ligne après le premier affichage. + // Les affiches AniList ne peuvent pas être copiées dans la base (CORS) : ce cache les garde aussi. + { + urlPattern: /^https:\/\/(s4\.anilist\.co\/|image\.tmdb\.org\/t\/p\/(w92|w154|w185|w300|w342|w500)\/)/, handler: 'CacheFirst', options: { cacheName: 'posters', - expiration: { maxEntries: 800, maxAgeSeconds: 60 * 60 * 24 * 365 }, + expiration: { maxEntries: 1500, maxAgeSeconds: 60 * 60 * 24 * 365, purgeOnQuotaError: true }, cacheableResponse: { statuses: [0, 200] }, }, }, + // Grandes images de fond : lourdes (~200 Ko), on n'en garde que quelques-unes pour ne pas chasser les affiches + { + urlPattern: /^https:\/\/image\.tmdb\.org\/t\/p\/(w780|w1280|original)\//, + handler: 'CacheFirst', + options: { + cacheName: 'backdrops', + expiration: { maxEntries: 80, maxAgeSeconds: 60 * 60 * 24 * 60, purgeOnQuotaError: true }, + cacheableResponse: { statuses: [0, 200] }, + }, + }, + ...(supabaseUrl + ? [ + // Fiches TMDB (détails, épisodes d'une saison, personnes) et notes Trakt : la copie en cache s'affiche + // tout de suite (et hors-ligne), puis est rafraîchie en arrière-plan. Données publiques, sans rien de personnel. + // Pas les requêtes « /tv/123 » seules : elles servent aux prochains épisodes, qui doivent rester à jour. + { + urlPattern: new RegExp( + `^${supabaseUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/functions/v1/(ratings\\?|tmdb\\?path=%2F((movie|tv)%2F\\d+&.*append_to_response=|tv%2F\\d+%2Fseason%2F\\d+&|person%2F\\d+&))`, + ), + handler: 'StaleWhileRevalidate' as const, + options: { + cacheName: 'catalog', + expiration: { maxEntries: 400, maxAgeSeconds: 60 * 60 * 24 * 14, purgeOnQuotaError: true }, + cacheableResponse: { statuses: [200] }, + }, + }, + ] + : []), ], }, }),