Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05c75c74f7 | ||
|
|
81d9cae1f7 | ||
|
|
2a9f790f19 | ||
|
|
43e2ecd589 | ||
|
|
7903064147 | ||
|
|
9180671d61 | ||
|
|
5e9994091f | ||
|
|
361ea66a32 | ||
|
|
0daee3eddf | ||
|
|
897fb2e008 | ||
|
|
ead3a08cd1 | ||
|
|
e54489f90f | ||
|
|
82bdaac3fe | ||
|
|
26a2b10b1a | ||
|
|
1bdf164f46 | ||
|
|
425bff8864 | ||
|
|
4e547c5c9d | ||
|
|
ac27542947 | ||
|
|
11d4de5894 | ||
|
|
f3b7d0c025 | ||
|
|
e627e935c4 | ||
|
|
a92e0e7252 | ||
|
|
21fc2917c8 | ||
|
|
c97a1d95c6 | ||
|
|
abcc12648e | ||
|
|
a0e8f5ad51 | ||
|
|
3dc1021f59 | ||
|
|
7f53445d27 | ||
|
|
25a120f44f | ||
|
|
dd928785f1 | ||
|
|
19bb2cbb03 | ||
|
|
cb693cd9d8 | ||
|
|
263f1bb445 | ||
|
|
036ecf61af | ||
|
|
9a05afec5c | ||
|
|
c7a1f5062e | ||
|
|
fbc4fcab6a | ||
|
|
b501e0b8f6 | ||
|
|
3487e8c305 | ||
|
|
2a4261219c | ||
|
|
1e8705e74b | ||
|
|
dbaec8e03e | ||
|
|
f864be834b | ||
|
|
0db3205060 | ||
|
|
4b9f1e73e3 | ||
|
|
6ce2e302f1 | ||
|
|
d97ee00e1a | ||
|
|
3f207b17c0 | ||
|
|
9ce9bbc0c0 | ||
|
|
614f566662 | ||
|
|
aad97867aa | ||
|
|
71b1e91947 | ||
|
|
81c6a447d9 | ||
|
|
e366f38727 | ||
|
|
f7160e3401 | ||
|
|
cb305bcfe1 | ||
|
|
db6c504325 | ||
|
|
6ce972179e | ||
|
|
d0681c62ab |
No files matched your search
@@ -5,9 +5,9 @@ Sélection de 16 skills défensifs / de test tirés de
|
||||
(commit `54a7988`, licence Apache-2.0 — fichier `LICENSE` dans chaque dossier).
|
||||
Projet communautaire, non affilié à Anthropic.
|
||||
|
||||
Retenus pour AzuuCine : contrôle d'accès / IDOR (≈ RLS Supabase), en-têtes et CSP, CORS,
|
||||
Retenus pour Bobinoo : contrôle d'accès / IDOR (≈ RLS Supabase), en-têtes et CSP, CORS,
|
||||
OAuth/PKCE, JWT, XSS, Edge Functions (serverless), limitation de débit, dépendances npm,
|
||||
secrets (gitleaks), RGPD, OWASP API Top 10.
|
||||
|
||||
Les scripts `scripts/*.py` envoient des requêtes de test : ne les lancer que contre
|
||||
AzuuCine (ou une copie locale), jamais contre un site tiers.
|
||||
Bobinoo (ou une copie locale), jamais contre un site tiers.
|
||||
@@ -1,32 +0,0 @@
|
||||
# Sauvegarde automatique de la base Supabase : chaque nuit, pg_dump -> chiffrement -> VPS, avec rotation
|
||||
# (7 quotidiennes, 4 hebdomadaires, 6 mensuelles). Voir deploy/BACKUP.md.
|
||||
# Secrets à créer dans Gitea (Dépôt -> Paramètres -> Actions -> Secrets) — JAMAIS dans le dépôt :
|
||||
# SUPABASE_DB_URL chaîne « Session pooler » (IPv4) de Supabase, avec le mot de passe de la base
|
||||
# BACKUP_PASSPHRASE phrase de chiffrement (16 caractères min.), conservée aussi hors du VPS
|
||||
# Variable optionnelle : BACKUP_DIR (défaut /srv/backups/azuucine)
|
||||
name: backup
|
||||
on:
|
||||
schedule:
|
||||
- cron: '17 2 * * *' # tous les jours à 02:17 UTC
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
backup:
|
||||
runs-on: azuucine
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Récupérer le script
|
||||
# Le jeton n'est visible que de cette étape
|
||||
env:
|
||||
GIT_TOKEN: ${{ github.token }}
|
||||
REPO_URL: ${{ github.server_url }}/${{ github.repository }}.git
|
||||
run: |
|
||||
rm -rf src
|
||||
AUTH=$(printf 'x-access-token:%s' "$GIT_TOKEN" | base64 -w0)
|
||||
git -c http.extraheader="AUTHORIZATION: basic $AUTH" clone --depth 1 --branch main "$REPO_URL" src
|
||||
- name: Sauvegarder (dump, contrôle, chiffrement, rotation)
|
||||
env:
|
||||
SUPABASE_DB_URL: ${{ secrets.SUPABASE_DB_URL }}
|
||||
BACKUP_PASSPHRASE: ${{ secrets.BACKUP_PASSPHRASE }}
|
||||
BACKUP_DIR: ${{ vars.BACKUP_DIR }}
|
||||
run: bash src/deploy/backup.sh
|
||||
@@ -1,4 +1,4 @@
|
||||
# Déploiement : à chaque push sur main -> build -> publication atomique sur le VPS (runner "azuucine").
|
||||
# Déploiement : à chaque push sur main -> build -> publication atomique sur le VPS (runner "bobinoo").
|
||||
# Variables à créer dans Gitea (Dépôt -> Paramètres -> Actions) :
|
||||
# Variables : VITE_SUPABASE_URL Secrets : VITE_SUPABASE_ANON_KEY (clé publique "sb_publishable_…")
|
||||
# La clé TMDB et la service_role restent dans les secrets Supabase : jamais ici.
|
||||
@@ -8,10 +8,14 @@ on:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# Droits minimaux : le jeton du job ne peut que lire le dépôt (il ne sert qu'au clonage)
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: azuucine
|
||||
runs-on: bobinoo
|
||||
env:
|
||||
REQUIRE_SUPABASE: '1' # le build échoue si VITE_SUPABASE_* manquent (garde dans vite.config.ts)
|
||||
steps:
|
||||
@@ -31,7 +35,7 @@ jobs:
|
||||
env:
|
||||
VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }}
|
||||
VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}
|
||||
run: cd src && npm run build
|
||||
run: cd src && npm run build && npm run build:admin && npm run build:mail
|
||||
- name: Publier (atomique, 3 versions conservées)
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
|
||||
@@ -10,3 +10,6 @@ supabase/.temp
|
||||
supabase/.branches
|
||||
_to_delete
|
||||
.env.deploy
|
||||
tsconfig.tsbuildinfo
|
||||
dist-admin
|
||||
dist-mail
|
||||
@@ -1,7 +1,7 @@
|
||||
# Bobinoo (ex-Kino, ex-AzuuCine) — contexte projet (lu automatiquement par Claude Code)
|
||||
|
||||
PWA de suivi de films, séries, animes, K-dramas et C-dramas. Interface en français
|
||||
(18 langues). Thème « salle obscure » chaud par défaut (clair = papier crème), accent ambre, sans dégradés. Une seule police embarquée : Inter. Accent fixe (pas de couleur au choix) ; apparences : auto / clair / sombre uniquement. Pas d'étiquettes en capitales espacées.
|
||||
(18 langues). Thème « Encre » (28 nov. 2026) : blanc pur / noir profond, une seule touche de vert d'eau (accent fixe), coins droits, filets fins, titres de section soulignés ; seul élément décoratif : le billet « Reprendre ». Police embarquée : Epilogue. Apparences : auto / clair / sombre. Pas d'étiquettes en capitales espacées.
|
||||
|
||||
## Stack
|
||||
- **Vite + React 19 + TypeScript**, **Tailwind CSS v4**, PWA (vite-plugin-pwa, service worker auto-update).
|
||||
@@ -18,52 +18,74 @@ npm run build # build de prod
|
||||
```
|
||||
|
||||
## Déploiement
|
||||
- Remote git : **Gitea** `https://gitea.rdacet.fr/romain/kino.git` (branche `main`).
|
||||
- Claude Code (cloud) accède directement à Gitea : jeton `GITEA_TOKEN` en « network secret » de l'environnement (portée `write:repository`). Claude pousse sur une branche `claude/…` ; Romain fusionne dans `main` depuis Gitea (ce qui déploie). Plus de dépôt GitHub.
|
||||
- Remote git : **Gitea** `https://gitea.rdacet.fr/romain/bobinoo.git` (branche `main`).
|
||||
- Claude Code (cloud) accède directement à Gitea : jeton `GITEA_TOKEN` en « network secret » de l'environnement (portée `write:repository`). Depuis le 27 nov. 2026, Romain demande que Claude **fusionne et pousse directement dans `main`** sans redemander (ce qui déploie), puis vérifie le déploiement (Gitea Actions + site en ligne). Plus de dépôt GitHub.
|
||||
- Push via **PowerShell** : `git push`.
|
||||
- **Gitea Actions** (`.gitea/workflows/deploy.yml`) build et publie sur le **VPS** (nginx en LXC) à chaque push sur `main`. Site : https://azuucine.rdacet.fr
|
||||
- **Gitea Actions** (`.gitea/workflows/deploy.yml`) build et publie sur le **VPS** (nginx en LXC) à chaque push sur `main`. Site : **https://bobinoo.org** (www → 301 ; kino.rdacet.fr abandonné le 28 nov. 2026). Proxy HTTPS = conteneur `proxy` (nginx + certbot), app = conteneur `kino`
|
||||
- `vite.config.ts` contient un garde-fou : le build échoue si `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` manquent en CI (variables/secrets Gitea Actions). La CSP et les en-têtes de sécurité y sont aussi définis (source unique → convertis en conf nginx par `deploy/headers-to-nginx.mjs`).
|
||||
|
||||
## Supabase
|
||||
- **Plan de la base** : `docs/database.md` (tables, fonctions, règles). Chaque table et fonction a une description (`comment on`) : en ajouter une à tout nouvel objet.
|
||||
- Project ref : `qfgnxonqwldcfdjqhhjz` — URL `https://qfgnxonqwldcfdjqhhjz.supabase.co`
|
||||
- Clé **publishable** (publique, déjà dans le bundle client) : `sb_publishable_s459lWM86bjiteGzWxSYcw_WbiRYydR`
|
||||
- **Secrets (JAMAIS dans le dépôt, jamais dans .env/VITE_)** : la clé TMDB et la `service_role` vivent dans les **secrets Supabase** / Edge Functions. Ne jamais les committer ni les coller dans le chat.
|
||||
- **Migrations** : `supabase/migrations/*.sql`. ⚠️ L'outil MCP `apply_migration` **tombe souvent en timeout** sur ce projet (création de fonctions). **Appliquer le SQL en le collant dans Supabase → SQL Editor → Run.** Tous les fichiers sont écrits **idempotents** (`create or replace`, `if not exists`, `drop ... if exists`).
|
||||
- Edge functions : `tmdb` (proxy pour cacher la clé TMDB), `delete-account`. Storage bucket `profile-media`.
|
||||
- Compte **admin** = Romain, user id `4529202d-618c-4b40-ab13-228eef3f71ad` (table `public.admins`).
|
||||
- Edge functions : `tmdb` (proxy pour cacher la clé TMDB), `ratings` (notes Trakt : moyenne, votes, répartition 1→10 des films et séries, secret `TRAKT_CLIENT_ID`, app Trakt du compte bobinoo26 ; réserve partagée `title_ratings` 24 h + correspondance TMDB → Trakt, lue/écrite avec la clé de service, aucune règle d'accès pour les clients), `delete-account`. Storage bucket `profile-media`. Secret `ALLOWED_ORIGINS` = `https://bobinoo.org,https://www.bobinoo.org`.
|
||||
|
||||
### Règles de sécurité Supabase (NON négociables — « aucune faille »)
|
||||
- **RLS activé partout** ; chaque utilisateur ne voit que ses données.
|
||||
- Toute fonction exposée est **`security definer` + `set search_path = ''`** et **vérifie les droits en interne** (`auth.uid()`, `can_view()`, `is_admin()`), puis `revoke ... from public, anon` / `grant execute ... to authenticated`.
|
||||
- Toute fonction exposée est **`security definer` + `set search_path = ''`** et **vérifie les droits en interne** (`auth.uid()`, `can_view()`), puis `revoke ... from public, anon` / `grant execute ... to authenticated`.
|
||||
- La clé TMDB ne doit jamais fuiter côté client (passe par l'edge function `tmdb`).
|
||||
|
||||
## Architecture client (repères)
|
||||
- `src/store.tsx` — fournisseur de données (IndexedDB = source locale, état React = copie de travail), synchro, thème.
|
||||
- `src/lib/cloud/` — `auth.ts` (GoTrue maison, PKCE Google), `sync.ts` (push/pull LWW), `social.ts`, `admin.ts`, `reviews.ts`, `api.ts` (`cloudFetch`).
|
||||
- `src/lib/cloud/` — `auth.ts` (GoTrue maison, PKCE Google), `sync.ts` (push/pull LWW), `social.ts`, `moderation.ts` (blocages), `reviews.ts`, `api.ts` (`cloudFetch`).
|
||||
- `src/lib/airing.ts` — suivi des sorties d'épisodes (TMDB/AniList), cache local.
|
||||
- `src/lib/franchise.ts` — saisons & dédoublonnage de franchises (TMDB 1 fiche multi-saisons vs AniList 1 entrée/saison).
|
||||
- `src/components/social/` — profils, recherche, fil d'amis, avis par titre (`TitleReviews`), réactions (`Reactions`), aperçu d'une fiche (`ItemPeek`), `SocialProvider` (pile d'overlays).
|
||||
- `src/pages/` — `HomePage`, `CatalogPage`, `StatsPage`, `SettingsPage`, `AdminPage`.
|
||||
- `src/App.tsx` — shell + routes par hash (`#/home`, `#/admin`…), `BottomNav` (mobile) + `SideNav` (desktop ≥ lg).
|
||||
- `src/pages/` — `HomePage`, `CatalogPage`, `StatsPage`, `SettingsPage`.
|
||||
- `src/App.tsx` — shell + routes par hash (`#/home`, `#/catalog`…), `BottomNav` (mobile) + `SideNav` (desktop ≥ lg).
|
||||
|
||||
## i18n (IMPORTANT)
|
||||
- 18 langues dans `src/i18n/locales/*.ts`. **`fr` est la référence** : toute clé doit exister dans **toutes** les langues (sinon erreur TS).
|
||||
- Textes vus par les membres → traduire dans les 18. Un écran réservé à l'admin → `fr` + `en` suffit.
|
||||
- Textes vus par les membres → traduire dans les 18.
|
||||
- Clés plurielles `xxx_one`/`xxx_other` (+ `_few`/`_many` pour ar/ru/pl). Variables `{x}`.
|
||||
- Thèmes d'apparence : `auto` (suit le navigateur), `light`, `dark` (les anciens `night`/`starfield` sont relus comme `dark`). Accent fixe, défini dans `src/index.css`. Toujours utiliser les **tokens de thème** (`bg-bg`, `text-ink`, `bg-accent-fill`…), **jamais de couleur hex en dur**.
|
||||
|
||||
- **Nom affiché : « Bobinoo »** (renommé le 27 nov. 2026 ; avant : « Kino » depuis le 14 oct. 2026). Le dépôt Gitea, le dossier local et le runner gardent le nom `kino`. Les identifiants techniques gardent `azuu`/`azuucine` (clés localStorage, bases IndexedDB, fonctions SQL `azuu_*`, secret Vault, dossiers `/srv/azuucine`, runner Gitea) : ne pas les renommer, ça casserait les données existantes.
|
||||
- **Nom affiché : « Bobinoo »** (renommé le 27 nov. 2026 ; avant : « Kino » depuis le 14 oct. 2026). Depuis le 1er déc. 2026, le dépôt Gitea (`romain/bobinoo`), le conteneur LXC, le runner et le dossier `/srv/bobinoo` s'appellent `bobinoo` (`/srv/azuucine` reste un lien vers `/srv/bobinoo` sur le VPS). Les identifiants techniques dans les données gardent `azuu`/`azuucine` (clés localStorage, bases IndexedDB, fonctions SQL `azuu_*`, secret Vault, format d'export) : ne pas les renommer, ça casserait les données existantes.
|
||||
|
||||
## Conventions
|
||||
- `npm run typecheck` doit passer après chaque modif.
|
||||
- Ne pas mettre `localStorage`/`sessionStorage` sans try/catch.
|
||||
- Garder les fichiers idempotents côté SQL.
|
||||
- RTL géré (arabe) : préférer les classes logiques (`ps-`/`pe-`, `ms-`/`me-`, `start-`/`end-`, `border-e`).
|
||||
- **Dates et nombres** : `dateFormat(opts).format(d)` / `numberFormat(opts)` / `fmtNumber` (`src/i18n`), formateurs gardés en mémoire — jamais `toLocaleDateString` ni `new Intl.*` dans un rendu (lent sur les longues listes).
|
||||
- **Store** : un composant qui ne fait qu'agir (cocher, ajouter…) prend `useMediaActions()` (fonctions stables, ne se redessine pas quand la bibliothèque change) ; l'état de la synchro, c'est `useSyncStatus()`. `useMedia()` seulement pour lire les fiches / réglages. Les écrans principaux (`HomePage`, `CatalogPage`, `SelectableCard`, `MediaCard`) sont mémorisés : leur passer des fonctions stables (`useCallback` dans `App.tsx`).
|
||||
- **Images** : ne PAS ajouter `crossOrigin` aux `<img>` TMDB / AniList. Essayé le 29/11/2026 (pour réduire le quota compté par Chrome) : sur iPhone, les affiches déjà en mémoire, reçues sans en-tête CORS, ne s'affichaient plus du tout. Annulé le soir même. Pas d'effet de flou (`backdrop-blur`) sur les barres fixes : coûteux au défilement sur téléphone.
|
||||
- **Appels aux données publiques** (proxy TMDB, notes Trakt) : `publicFetch` dans `cloud/api.ts`, sans aucun en-tête → pas de pré-requête CORS (un aller-retour au lieu de deux). Limite côté serveur par adresse IP (tmdb 1000, ratings 400 / 10 min). Les données perso restent sur `cloudFetch` (jeton).
|
||||
|
||||
## État (au 24 nov. 2026)
|
||||
- **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261122140000_audit_hardening.sql` incluse.
|
||||
- **Notifications retirées (22 nov. 2026)** : plus de cloche ni de push. Table `notifications` gardée vide (des fonctions de listes partagées y font encore référence), `azuu_notify` ne fait plus rien. Ne pas les réintroduire sans demande.
|
||||
## État (au 28 nov. 2026)
|
||||
- **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261201110000_notification_prefs.sql` incluse (pg_net supprimée, index des notifications revus, réserve des notes Trakt ; notifications aux abonnés en une requête, quota vérifié une fois par envoi (trigger `*_quota_stmt`), fiche renvoyée à l'identique non réécrite).
|
||||
- **29 nov. 2026** : 123 avis du compte de Romain contenaient « Réalisation : … » (ancien import, `legacyImport.ts`, corrigé). Lignes retirées en base (la copie de sauvegarde a été supprimée le même jour, correction validée).
|
||||
- **Affiches** : une fiche garde l'**adresse** de l'affiche (TMDB w342 / AniList), jamais l'image copiée en base64 (≈ 50 Ko par fiche, renvoyés à chaque modification et chez les amis). Seule une image choisie dans la galerie (EditDetails, 360 px) est intégrée. Le 29 nov. 2026, 109 affiches intégrées (342 px, copies automatiques) ont été remplacées par leur adresse TMDB : base des fiches 5,95 Mo → 267 Ko.
|
||||
- **Cache (service worker, `vite.config.ts`)** : pré-téléchargement ~1 Mo (app + français). Les 17 autres langues (`assets/locale-*`) et les variantes de police sont mises en cache à la demande (`app-files`). Caches d'exécution : `posters` (petites images TMDB/AniList, 1500), `backdrops` (grandes images, 80) — réponses opaques acceptées (`posters-v2` / `backdrops-v2`, d'un essai abandonné, sont supprimés au lancement par `main.tsx`), `catalog` (fiches TMDB avec `append_to_response`, saisons, personnes, notes Trakt : StaleWhileRevalidate 14 j ; jamais `/tv/123` seul, recherche, sorties ni données perso). React est dans son propre fichier (`react-*.js`), gardé d'une version à l'autre.
|
||||
- **Chargés à la demande** (préchargés au repos par `preloadScreens`, gardés par le service worker) : fiche d'un titre (`TitleSheet`), recherche d'ajout (`AddTitle`), onglets Journal / Listes, listes partagées, assistant d'import (`ImportWizard`), dessin des cartes de partage (`shareCard` ; `shareImage.ts` reste léger), convertisseur des anciennes sauvegardes (`legacyImport`). Garder les petits composants partagés dans leur propre fichier (ex. `NewListForm.tsx`) : un import direct depuis un écran à la demande le ramène dans le fichier principal.
|
||||
- **Note Trakt** (`getPublicRatings` / `cachedPublicRatings` dans `catalogApi.ts`) : à part du reste de la fiche, gardée sur l'appareil (`azuucine:ratings`, 800 titres, rafraîchie après 2 jours) → affichage immédiat. Premier chargement : place réservée sans chiffre provisoire.
|
||||
- **Épisodes d'une saison** (`getTmdbSeasonEpisodes` / `cachedSeasonEpisodes`) : gardés sur l'appareil (`azuucine:seasons`, budget 400 Ko, rafraîchis après 12 h) ; images autour du prochain épisode chargées tout de suite (`episodeWindow`, `preloadImages`).
|
||||
- **Synchro** (`cloud/sync.ts`) : la réception relit la minute avant le curseur, sauf quand le curseur est « réglé » (inchangé depuis plus d'une minute, `itemsSettled` / `listsSettled`) — avant, les dernières fiches écrites (toute la bibliothèque après un import) étaient retéléchargées chaque minute. Rythme : chaque minute pendant 5 min après une activité, sinon toutes les 3 min, et tout de suite au retour sur l'app.
|
||||
- **Accueil** : « Dernières sorties » ne se met à jour que quand la rangée approche de l'écran (plusieurs centaines de requêtes TMDB) ; fiche et saisons d'une série partagées entre les deux mois (`sharedTmdb`). Bannière : seules l'image affichée, la suivante et la précédente sont chargées.
|
||||
- **Préchargement au toucher** : sur tout bouton qui ouvre une fiche de ma bibliothèque, `{...prefetchAttrs(item)}` (`src/lib/prefetch.ts` : fiche, note Trakt, saison en cours et ses images) ; sinon `data-prefetch={externalId}`. Écouteur global dans `App.tsx` (toucher / survol souris).
|
||||
- **Écrans à la demande** : toujours `lazyPreload` (`src/lib/lazyPreload.tsx`) et non `React.lazy` seul — avec `lazy`, la première ouverture d'un écran déjà téléchargé est retardée d'environ 300 ms par React. Ajouter l'écran à `preloadScreens` / `preloadSocial` / `preloadCatalogViews` (sauf l'admin).
|
||||
- **Compression** : `deploy/nginx/site.conf` active gzip (JS, CSS, JSON, SVG), avec `gzip_http_version 1.0` car le proxy en façade parle HTTP/1.0. Sans ça les fichiers partaient bruts. Mesure Lighthouse mobile (1re visite, 29 nov. 2026) : score 67 → 97, premier affichage 3,9 → 1,8 s, poids 789 → 248 Ko.
|
||||
- **Anciennes icônes installées depuis kino.rdacet.fr / azuucine.rdacet.fr** : ces adresses n'existent plus, l'app installée tourne sur sa copie (plus de mises à jour) et les fonctions serveur la refusent (CORS) → « Impossible de joindre le serveur ». Solution : supprimer l'icône et réinstaller depuis https://bobinoo.org. La date de la version est affichée en bas des Réglages.
|
||||
- **Notifications** (dans l'app, pas de push) : abonnements (`new_follower`, `follow_request`, `unfollow`, `follow_accepted`, trigger `follows_notify`), réaction / commentaire sur mon avis (`reaction`, `review_comment`, triggers sur `review_reactions` / `review_comments`), activité des comptes suivis (`friend_review`, `friend_started`, `friend_added`, trigger `items_notify` → `azuu_notify_followers`, rafales regroupées sur 3 h). Pas de notification pour les listes perso (privées). RPC `get_notifications` (avec le titre lié) / `unread_notifications` / `mark_notifications_read`. **Choix par type** (Réglages → Notifications, `NotificationSettings.tsx`) : `settings.notifOff` (synchronisé) ; le trigger `notifications_wanted` ne crée pas un type désactivé, et `get_notifications` / `unread_notifications` masquent ceux déjà reçus. La fonction Edge `send-push` répond 410 : à supprimer depuis le tableau de bord Supabase.
|
||||
- **Administration = console séparée** (`docs/admin.md`) : site `admin/` (build `npm run build:admin` → `dist-admin/`), jamais dans l'app publique. Servi par nginx sur https://admin.bobinoo.org (`deploy/nginx/admin.conf`, limite d'appels, CSP stricte). Appels → fonction Edge `admin` (secret `X-Admin-Gate` ajouté par nginx + jeton aal2 obligatoire + `admin.admins`) → schéma `admin` (non exposé par l'API) par connexion directe. Journal `admin.journal` en ajout seulement. Dans l'app : « Signaler » et « Signaler un bug » ouvrent un e-mail vers contact@bobinoo.org (`components/moderation/BugReport.tsx`). Après une mise à jour, une ancienne version qui ne trouve plus un fichier se recharge d'elle-même (`ErrorBoundary`).
|
||||
- **E-mails du compte** (inscription, mot de passe oublié, changement d'adresse) : envoyés par `contact@bobinoo.org` (OVH Zimbra Starter, SMTP `ssl0.ovh.net:465`, DKIM actif), modèles dans `docs/emails/`. Testé le 30 nov. 2026 : reçu en boîte de réception, lien de confirmation OK. Limite Supabase : 30 e-mails / heure. Messagerie : https://mail.bobinoo.org, interface Bobinoo de la boîte (`docs/mail.md` : site `mail/`, fonction Edge `mail` en IMAP/SMTP, mêmes verrous que la console). `contact@bobinoo.org` est aussi l'adresse de contact des pages légales, de « Signaler un bug » et du Play Store.
|
||||
- **Retirés (27-28 nov. 2026)** : défis, couleur d'accent au choix, apparences Nuit/Étoilé, notation sur 10 (les notes restent stockées sur 10 en interne, affichées sur 5 étoiles).
|
||||
- **Double authentification (TOTP)** : optionnelle, Réglages → Mon compte (`src/components/TwoFactor.tsx`, fonctions dans `src/lib/cloud/auth.ts`). À la connexion, `Root.tsx` demande le code (`MfaScreen`) si le compte a un facteur vérifié. Côté serveur, `azuu_mfa_ok()` : règles RLS restrictives « mfa required » (items, lists, settings, follows, profiles, activity), `is_admin()` et `azuu_me_active()` ; les fonctions Edge (`_shared/auth.ts`) refusent un jeton « aal1 » d'un compte protégé.
|
||||
- **Dépendances figées** : versions exactes dans `package.json` + `.npmrc` (`save-exact=true`), CI en `npm ci`.
|
||||
- **Chargement** : les écrans rares (stats, réglages, roulette, calendrier, écrans sociaux…) sont chargés à la demande puis préchargés au repos (`App.tsx` → `loaders`, `SocialProvider.tsx` → `socialLoaders`).
|
||||
- **Audit (22-24 nov. 2026)** : `20261122140000_audit_hardening.sql` versionne aussi les fonctions admin / « comptes suspendus » qui n'existaient qu'en ligne. Blocage = le compte bloquant devient invisible pour le bloqué ; fiches supprimées = `data` vidée (trigger `azuu_tombstone`) ; profils lisibles directement seulement par soi-même.
|
||||
- **Runner Gitea** : `kino` (étiquette `azuucine`), service `gitea-runner` dans le conteneur LXC `kino` du VPS. S'il est hors ligne, plus rien ne se déploie (voir `deploy/BACKUP.md` → « Runner arrêté ? »).
|
||||
- **Sauvegardes : pas encore actives** (au 25 nov. 2026) — secrets Gitea `SUPABASE_DB_URL` + `BACKUP_PASSPHRASE` à ajouter par Romain, préparation du VPS → `deploy/BACKUP.md`.
|
||||
- **Runner Gitea** : `bobinoo` (étiquette `bobinoo`), service `gitea-runner` dans le conteneur LXC `bobinoo` du VPS. S'il est hors ligne, plus rien ne se déploie (voir `deploy/RUNNER.md`).
|
||||
- **Sauvegardes de la base** : faites par Romain sur son VPS chaque soir (la sauvegarde via Gitea Actions a été retirée le 28 nov. 2026).
|
||||
- Leaked Password Protection (Supabase) demande l'offre payante : remplacée par la vérification HIBP côté client (`src/lib/pwned.ts`).
|
||||
@@ -1,198 +0,0 @@
|
||||
-- ════════════════════════════════════════════════════════════════════════════
|
||||
-- AzuuCine — Avis par titre, réactions et notifications (5 octobre 2026)
|
||||
-- 1. Voir tous les avis sur un titre (amis / autres).
|
||||
-- 2. Réagir aux avis (emoji).
|
||||
-- 3. Notifications (cloche) : abonnements, demandes acceptées, réactions reçues.
|
||||
--
|
||||
-- À coller dans Supabase → SQL Editor → Run. Idempotent (réexécutable sans risque).
|
||||
-- ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- ── Tables ──
|
||||
create table if not exists public.review_reactions (
|
||||
author_id uuid not null references auth.users(id) on delete cascade, -- auteur de l'avis
|
||||
item_id text not null,
|
||||
user_id uuid not null default auth.uid() references auth.users(id) on delete cascade, -- qui réagit
|
||||
emoji text not null,
|
||||
created_at timestamptz not null default now(),
|
||||
primary key (author_id, item_id, user_id)
|
||||
);
|
||||
create index if not exists review_reactions_target_idx on public.review_reactions (author_id, item_id);
|
||||
alter table public.review_reactions enable row level security;
|
||||
alter table public.review_reactions force row level security;
|
||||
revoke all on public.review_reactions from anon, authenticated;
|
||||
|
||||
create table if not exists public.notifications (
|
||||
id bigint generated always as identity primary key,
|
||||
user_id uuid not null references auth.users(id) on delete cascade, -- destinataire
|
||||
kind text not null check (kind in ('follow_request','follow_accepted','new_follower','reaction')),
|
||||
actor_id uuid references auth.users(id) on delete cascade,
|
||||
item_id text,
|
||||
emoji text,
|
||||
created_at timestamptz not null default now(),
|
||||
read_at timestamptz
|
||||
);
|
||||
create index if not exists notifications_user_idx on public.notifications (user_id, created_at desc);
|
||||
alter table public.notifications enable row level security;
|
||||
alter table public.notifications force row level security;
|
||||
revoke all on public.notifications from anon, authenticated;
|
||||
|
||||
-- ── Création de notifications + bornage de l'historique ──
|
||||
create or replace function public.azuu_notify(p_user uuid, p_kind text, p_actor uuid, p_item text default null, p_emoji text default null)
|
||||
returns void language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if p_user is null or p_actor is null or p_user = p_actor then return; end if;
|
||||
insert into public.notifications (user_id, kind, actor_id, item_id, emoji)
|
||||
values (p_user, p_kind, p_actor, p_item, p_emoji);
|
||||
delete from public.notifications
|
||||
where user_id = p_user and id not in (
|
||||
select id from public.notifications where user_id = p_user order by created_at desc limit 300
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- Abonnement / demande -> notifie le compte suivi ; demande acceptée -> notifie le demandeur
|
||||
create or replace function public.azuu_follow_notify()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if tg_op = 'INSERT' then
|
||||
perform public.azuu_notify(new.following_id,
|
||||
case when new.status = 'pending' then 'follow_request' else 'new_follower' end, new.follower_id);
|
||||
elsif tg_op = 'UPDATE' and old.status = 'pending' and new.status = 'accepted' then
|
||||
perform public.azuu_notify(new.follower_id, 'follow_accepted', new.following_id);
|
||||
end if;
|
||||
return null;
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists follows_notify on public.follows;
|
||||
create trigger follows_notify after insert or update on public.follows
|
||||
for each row execute function public.azuu_follow_notify();
|
||||
|
||||
-- Réaction reçue -> notifie l'auteur de l'avis
|
||||
create or replace function public.azuu_reaction_notify()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
perform public.azuu_notify(new.author_id, 'reaction', new.user_id, new.item_id, new.emoji);
|
||||
return null;
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists reactions_notify on public.review_reactions;
|
||||
create trigger reactions_notify after insert on public.review_reactions
|
||||
for each row execute function public.azuu_reaction_notify();
|
||||
|
||||
-- ── Réagir à un avis ──
|
||||
create or replace function public.react_to_review(p_author uuid, p_item text, p_emoji text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is null then raise exception 'auth'; end if;
|
||||
if p_author = auth.uid() then raise exception 'cannot react to your own review'; end if;
|
||||
if p_emoji is null or p_emoji <> all (array['👍','❤️','🔥','😂','😮','😢']) then raise exception 'bad emoji'; end if;
|
||||
if not public.can_view(p_author) or not exists (
|
||||
select 1 from public.items i join public.profiles pr on pr.id = i.user_id
|
||||
where i.user_id = p_author and i.id = p_item and not i.deleted
|
||||
and coalesce(i.data->>'notes','') <> '' and not pr.suspended
|
||||
) then
|
||||
raise exception 'review not found';
|
||||
end if;
|
||||
insert into public.review_reactions (author_id, item_id, user_id, emoji)
|
||||
values (p_author, p_item, auth.uid(), p_emoji)
|
||||
on conflict (author_id, item_id, user_id) do update set emoji = excluded.emoji, created_at = now();
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.unreact_review(p_author uuid, p_item text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is null then raise exception 'auth'; end if;
|
||||
delete from public.review_reactions where author_id = p_author and item_id = p_item and user_id = auth.uid();
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Tous les avis sur un titre (amis / autres) ──
|
||||
create or replace function public.title_reviews(p_external_id text, p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare me uuid := auth.uid(); res jsonb;
|
||||
begin
|
||||
if me is null or p_external_id !~ '^(tmdb:(movie|tv):[0-9]{1,10}|anilist:[0-9]{1,10})$' then
|
||||
return jsonb_build_object('friends', '[]'::jsonb, 'others', '[]'::jsonb);
|
||||
end if;
|
||||
with revs as (
|
||||
select i.user_id, i.id as item_id, i.updated_at,
|
||||
nullif(i.data->>'rating','')::numeric as rating,
|
||||
i.data->>'notes' as notes, pr,
|
||||
exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted') as friend
|
||||
from public.items i
|
||||
join public.profiles pr on pr.id = i.user_id
|
||||
where i.data->>'externalId' = p_external_id
|
||||
and not i.deleted and coalesce(i.data->>'notes','') <> ''
|
||||
and i.user_id <> me and not pr.suspended
|
||||
and (not pr.is_private
|
||||
or exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted'))
|
||||
),
|
||||
enriched as (
|
||||
select r.*,
|
||||
(select coalesce(jsonb_object_agg(e.emoji, e.c), '{}'::jsonb)
|
||||
from (select emoji, count(*) c from public.review_reactions rr
|
||||
where rr.author_id = r.user_id and rr.item_id = r.item_id group by emoji) e) as reactions,
|
||||
(select count(*) from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id) as total,
|
||||
(select emoji from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id and rr.user_id = me) as mine
|
||||
from revs r
|
||||
)
|
||||
select jsonb_build_object(
|
||||
'friends', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes,
|
||||
'reactions', reactions, 'total', total, 'mine', mine) entry, total, updated_at
|
||||
from enriched where friend offset greatest(p_offset, 0) limit 40) f), '[]'::jsonb),
|
||||
'others', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes,
|
||||
'reactions', reactions, 'total', total, 'mine', mine) entry, total, updated_at
|
||||
from enriched where not friend offset greatest(p_offset, 0) limit 40) o), '[]'::jsonb)
|
||||
) into res;
|
||||
return res;
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Notifications ──
|
||||
create or replace function public.get_notifications(p_offset integer default 0)
|
||||
returns jsonb language sql stable security definer set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(x order by created_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select n.id, n.kind, n.created_at, n.read_at, n.emoji, n.item_id,
|
||||
case when p.id is null then null else
|
||||
jsonb_build_object('username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url) end as actor,
|
||||
case when n.kind = 'reaction'
|
||||
then (select it.data->>'title' from public.items it where it.user_id = n.user_id and it.id = n.item_id) end as title
|
||||
from public.notifications n
|
||||
left join public.profiles p on p.id = n.actor_id
|
||||
where n.user_id = auth.uid()
|
||||
order by n.created_at desc
|
||||
offset greatest(p_offset, 0) limit 30
|
||||
) x
|
||||
$$;
|
||||
|
||||
create or replace function public.notifications_unread()
|
||||
returns integer language sql stable security definer set search_path = '' as $$
|
||||
select count(*)::int from public.notifications where user_id = auth.uid() and read_at is null
|
||||
$$;
|
||||
|
||||
create or replace function public.mark_notifications_read()
|
||||
returns void language sql security definer set search_path = '' as $$
|
||||
update public.notifications set read_at = now() where user_id = auth.uid() and read_at is null
|
||||
$$;
|
||||
|
||||
-- ── Droits (gate interne : auth.uid() / can_view) ──
|
||||
revoke all on function public.react_to_review(uuid, text, text) from public, anon;
|
||||
revoke all on function public.unreact_review(uuid, text) from public, anon;
|
||||
revoke all on function public.title_reviews(text, integer) from public, anon;
|
||||
revoke all on function public.get_notifications(integer) from public, anon;
|
||||
revoke all on function public.notifications_unread() from public, anon;
|
||||
revoke all on function public.mark_notifications_read() from public, anon;
|
||||
grant execute on function public.react_to_review(uuid, text, text) to authenticated;
|
||||
grant execute on function public.unreact_review(uuid, text) to authenticated;
|
||||
grant execute on function public.title_reviews(text, integer) to authenticated;
|
||||
grant execute on function public.get_notifications(integer) to authenticated;
|
||||
grant execute on function public.notifications_unread() to authenticated;
|
||||
grant execute on function public.mark_notifications_read() to authenticated;
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<title>Console Bobinoo</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,177 @@
|
||||
import { LogOut, ShieldCheck } from 'lucide-react'
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'
|
||||
import { ApiError, call, type Card } from './api'
|
||||
import { AuthError, expiresAt, signIn, signOut, verifyCode } from './auth'
|
||||
import { Comments, Dashboard, Journal, Members, Reviews } from './screens'
|
||||
|
||||
/** Déconnexion automatique après 15 minutes sans toucher à la console. */
|
||||
const IDLE_MS = 15 * 60_000
|
||||
|
||||
type Tab = 'dashboard' | 'members' | 'reviews' | 'comments' | 'journal'
|
||||
const TABS: { id: Tab; label: string }[] = [
|
||||
{ id: 'dashboard', label: 'Tableau de bord' },
|
||||
{ id: 'members', label: 'Membres' },
|
||||
{ id: 'reviews', label: 'Avis' },
|
||||
{ id: 'comments', label: 'Commentaires' },
|
||||
{ id: 'journal', label: 'Journal' },
|
||||
]
|
||||
|
||||
export default function App() {
|
||||
// Jeton gardé en mémoire seulement : recharger la page déconnecte
|
||||
const [session, setSession] = useState<{ token: string; me: Card }>()
|
||||
const [notice, setNotice] = useState<string>()
|
||||
|
||||
const logout = useCallback((why?: string) => {
|
||||
setSession((s) => {
|
||||
if (s) void signOut(s.token)
|
||||
return undefined
|
||||
})
|
||||
setNotice(why)
|
||||
}, [])
|
||||
|
||||
// Fin de validité du jeton, inactivité : retour à l'écran de connexion
|
||||
useEffect(() => {
|
||||
if (!session) return
|
||||
const end = window.setTimeout(() => logout('Session terminée (1 h) : reconnecte-toi.'), Math.max(0, expiresAt(session.token) - Date.now() - 30_000))
|
||||
let idle = window.setTimeout(() => logout('Déconnecté après 15 minutes sans activité.'), IDLE_MS)
|
||||
const touch = () => {
|
||||
window.clearTimeout(idle)
|
||||
idle = window.setTimeout(() => logout('Déconnecté après 15 minutes sans activité.'), IDLE_MS)
|
||||
}
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.addEventListener(ev, touch)
|
||||
return () => {
|
||||
window.clearTimeout(end)
|
||||
window.clearTimeout(idle)
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.removeEventListener(ev, touch)
|
||||
}
|
||||
}, [session, logout])
|
||||
|
||||
if (!session) return <Login notice={notice} onReady={(token, me) => (setNotice(undefined), setSession({ token, me }))} />
|
||||
return <Console token={session.token} me={session.me} onLogout={logout} />
|
||||
}
|
||||
|
||||
function Login({ notice, onReady }: { notice?: string; onReady: (token: string, me: Card) => void }) {
|
||||
const [step, setStep] = useState<{ token: string; factorId: string }>()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const codeRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
if (!step) {
|
||||
const r = await signIn(email, password)
|
||||
setPassword('')
|
||||
if (!r.factorId) {
|
||||
await signOut(r.token)
|
||||
throw new AuthError("Ce compte n'a pas la double authentification. Active-la d'abord dans l'app (Réglages → Mon compte), elle est obligatoire ici.")
|
||||
}
|
||||
setStep({ token: r.token, factorId: r.factorId })
|
||||
setTimeout(() => codeRef.current?.focus(), 0)
|
||||
} else {
|
||||
const token = await verifyCode(step.token, step.factorId, code.replace(/\s/g, ''))
|
||||
const me = await call<Card>(token, 'hello')
|
||||
onReady(token, me)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof AuthError || err instanceof ApiError ? err.message : 'Erreur inattendue.')
|
||||
if (step) setCode('')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh max-w-sm flex-col justify-center px-5 py-10">
|
||||
<div className="flex items-center gap-2 text-accent">
|
||||
<ShieldCheck size={22} />
|
||||
<span className="text-sm font-semibold uppercase tracking-wider">Console</span>
|
||||
</div>
|
||||
<h1 className="mt-2 text-3xl font-bold">Bobinoo</h1>
|
||||
<p className="mt-2 text-sm text-ink-3">Accès réservé. Chaque connexion est inscrite au journal et signalée par e-mail.</p>
|
||||
{notice && <p className="mt-5 border-s-2 border-accent ps-3 text-sm text-ink-2">{notice}</p>}
|
||||
<form onSubmit={submit} className="mt-7 space-y-3">
|
||||
{!step ? (
|
||||
<>
|
||||
<input className="field" type="email" autoComplete="username" placeholder="E-mail" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
<input className="field" type="password" autoComplete="current-password" placeholder="Mot de passe" value={password} onChange={(e) => setPassword(e.target.value)} required />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-ink-2">Code à 6 chiffres de ton application d'authentification :</p>
|
||||
<input
|
||||
ref={codeRef}
|
||||
className="field text-center text-2xl tracking-[0.4em]"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9 ]{6,7}"
|
||||
maxLength={7}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
<button className="btn btn-primary w-full" disabled={busy}>
|
||||
{busy ? '…' : step ? 'Valider le code' : 'Continuer'}
|
||||
</button>
|
||||
{step && (
|
||||
<button type="button" className="btn w-full text-ink-3" onClick={() => (void signOut(step.token), setStep(undefined), setCode(''))}>
|
||||
Annuler
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function Console({ token, me, onLogout }: { token: string; me: Card; onLogout: (why?: string) => void }) {
|
||||
const [tab, setTab] = useState<Tab>('dashboard')
|
||||
// Erreur de session renvoyée par le serveur : retour à la connexion
|
||||
const onAuthError = useCallback(
|
||||
(e: unknown) => {
|
||||
if (e instanceof ApiError && (e.status === 401 || e.status === 403)) onLogout(e.message)
|
||||
},
|
||||
[onLogout],
|
||||
)
|
||||
const props = { token, onAuthError }
|
||||
return (
|
||||
<div className="mx-auto min-h-dvh max-w-5xl px-4 pb-16 sm:px-6">
|
||||
<header className="sticky top-0 z-10 -mx-4 border-b border-line bg-bg px-4 pt-[max(0.75rem,env(safe-area-inset-top))] sm:-mx-6 sm:px-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<ShieldCheck size={20} className="text-accent" />
|
||||
<span className="font-bold">Console Bobinoo</span>
|
||||
<span className="ms-auto truncate text-sm text-ink-3">@{me.username}</span>
|
||||
<button onClick={() => onLogout('Déconnecté.')} className="grid size-9 place-items-center text-ink-2 active:text-ink" aria-label="Se déconnecter">
|
||||
<LogOut size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<nav className="-mx-1 mt-2 flex gap-1 overflow-x-auto pb-2">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => setTab(t.id)}
|
||||
className={`shrink-0 rounded-md px-3 py-1.5 text-sm font-medium ${tab === t.id ? 'bg-surface-2 text-ink' : 'text-ink-3'}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</header>
|
||||
<main className="pt-5">
|
||||
{tab === 'dashboard' && <Dashboard {...props} />}
|
||||
{tab === 'members' && <Members {...props} meId={me.id} />}
|
||||
{tab === 'reviews' && <Reviews {...props} />}
|
||||
{tab === 'comments' && <Comments {...props} />}
|
||||
{tab === 'journal' && <Journal {...props} />}
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/** Appels à la fonction serveur « admin », par le relais nginx du VPS (qui ajoute le secret). */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
const MESSAGES: Record<string, string> = {
|
||||
session: 'Session expirée : reconnecte-toi.',
|
||||
mfa: 'Code de double authentification requis : reconnecte-toi.',
|
||||
interdit: "Ce compte n'est pas administrateur.",
|
||||
'trop de requêtes': 'Trop de requêtes, patiente une minute.',
|
||||
}
|
||||
|
||||
export async function call<T>(token: string, action: string, params: Record<string, unknown> = {}): Promise<T> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch('/api/admin', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ action, ...params }),
|
||||
credentials: 'omit',
|
||||
cache: 'no-store',
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(0, 'Serveur injoignable. Vérifie ta connexion.')
|
||||
}
|
||||
if (res.status === 404) throw new ApiError(404, 'La console n\'est pas reliée au serveur (secret du VPS absent ou différent).')
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
if (!res.ok) throw new ApiError(res.status, MESSAGES[body.error ?? ''] ?? body.error ?? `Erreur ${res.status}`)
|
||||
return body as T
|
||||
}
|
||||
|
||||
export interface Card {
|
||||
id: string
|
||||
username: string
|
||||
display_name: string
|
||||
avatar_url?: string | null
|
||||
suspended: boolean
|
||||
}
|
||||
export interface Overview {
|
||||
members: number
|
||||
members_week: number
|
||||
active_week: number
|
||||
suspended: number
|
||||
private: number
|
||||
items: number
|
||||
reviews: number
|
||||
comments: number
|
||||
follows: number
|
||||
shared_lists: number
|
||||
latest: (Card & { created_at: string })[]
|
||||
}
|
||||
export interface Member extends Card {
|
||||
email: string
|
||||
created_at: string
|
||||
last_sign_in_at?: string | null
|
||||
items: number
|
||||
mfa: boolean
|
||||
is_admin: boolean
|
||||
}
|
||||
export interface Review {
|
||||
user: Card
|
||||
item_id: string
|
||||
title: string
|
||||
rating?: number | null
|
||||
spoiler: boolean
|
||||
notes: string
|
||||
updated_at: string
|
||||
comments: number
|
||||
}
|
||||
export interface Comment {
|
||||
id: number
|
||||
body: string
|
||||
created_at: string
|
||||
user: Card
|
||||
author: Card
|
||||
title?: string | null
|
||||
}
|
||||
export interface JournalEntry {
|
||||
id: number
|
||||
at: string
|
||||
action: string
|
||||
target?: string | null
|
||||
details: Record<string, unknown>
|
||||
admin?: string | null
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Connexion à la console : mot de passe, puis code de double authentification (obligatoire).
|
||||
* La session ne vit qu'en mémoire : recharger ou fermer l'onglet déconnecte. Pas de jeton de
|
||||
* renouvellement gardé : au bout d'une heure (durée du jeton Supabase), il faut se reconnecter.
|
||||
*/
|
||||
const URL = (import.meta.env.VITE_SUPABASE_URL ?? '').replace(/\/+$/, '')
|
||||
const KEY = import.meta.env.VITE_SUPABASE_ANON_KEY ?? ''
|
||||
|
||||
export class AuthError extends Error {}
|
||||
|
||||
type Json = Record<string, unknown>
|
||||
|
||||
async function gotrue(path: string, opts: { token?: string; body?: Json } = {}): Promise<Json> {
|
||||
if (!URL || !KEY) throw new AuthError('Console mal construite : adresse Supabase manquante.')
|
||||
const res = await fetch(`${URL}/auth/v1${path}`, {
|
||||
method: opts.body ? 'POST' : 'GET',
|
||||
headers: { apikey: KEY, 'Content-Type': 'application/json', ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}) },
|
||||
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
||||
credentials: 'omit',
|
||||
cache: 'no-store',
|
||||
})
|
||||
const data = (await res.json().catch(() => ({}))) as Json
|
||||
if (!res.ok) {
|
||||
const code = String(data.error_code ?? data.error ?? '')
|
||||
if (res.status === 400 && /invalid_credentials|invalid_grant/.test(code)) throw new AuthError('E-mail ou mot de passe incorrect.')
|
||||
if (res.status === 429) throw new AuthError('Trop de tentatives. Réessaie dans quelques minutes.')
|
||||
if (/mfa_verification_failed|invalid.*code/i.test(code + String(data.msg ?? ''))) throw new AuthError('Code incorrect ou expiré.')
|
||||
throw new AuthError(String(data.msg ?? data.message ?? data.error_description ?? `Erreur ${res.status}`))
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
/** Étape 1 : e-mail et mot de passe. Renvoie le facteur TOTP à valider (absent : pas de double authentification). */
|
||||
export async function signIn(email: string, password: string): Promise<{ token: string; factorId?: string }> {
|
||||
const d = await gotrue('/token?grant_type=password', { body: { email: email.trim().toLowerCase(), password } })
|
||||
const user = (d.user ?? {}) as { factors?: { id?: string; factor_type?: string; status?: string }[] }
|
||||
const factor = (user.factors ?? []).find((f) => f.factor_type === 'totp' && f.status === 'verified')
|
||||
if (typeof d.access_token !== 'string') throw new AuthError('Réponse inattendue du serveur.')
|
||||
return { token: d.access_token, factorId: factor?.id }
|
||||
}
|
||||
|
||||
/** Étape 2 : code à 6 chiffres → jeton « aal2 », le seul accepté par la console. */
|
||||
export async function verifyCode(token: string, factorId: string, code: string): Promise<string> {
|
||||
const ch = await gotrue(`/factors/${encodeURIComponent(factorId)}/challenge`, { token, body: {} })
|
||||
if (typeof ch.id !== 'string') throw new AuthError('Réponse inattendue du serveur.')
|
||||
const v = await gotrue(`/factors/${encodeURIComponent(factorId)}/verify`, { token, body: { challenge_id: ch.id, code } })
|
||||
if (typeof v.access_token !== 'string') throw new AuthError('Réponse inattendue du serveur.')
|
||||
return v.access_token
|
||||
}
|
||||
|
||||
/** Déconnexion : la session est aussi fermée côté serveur. */
|
||||
export async function signOut(token: string): Promise<void> {
|
||||
await gotrue('/logout?scope=local', { token, body: {} }).catch(() => {})
|
||||
}
|
||||
|
||||
/** Fin de validité du jeton (ms). */
|
||||
export function expiresAt(token: string): number {
|
||||
try {
|
||||
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
const { exp } = JSON.parse(atob(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '='))) as { exp?: number }
|
||||
return typeof exp === 'number' ? exp * 1000 : Date.now()
|
||||
} catch {
|
||||
return Date.now()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@fontsource-variable/epilogue/wght.css'
|
||||
import './styles.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,391 @@
|
||||
import { Search } from 'lucide-react'
|
||||
import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { ApiError, call, type Card, type Comment, type JournalEntry, type Member, type Overview, type Review } from './api'
|
||||
|
||||
interface ScreenProps {
|
||||
token: string
|
||||
onAuthError: (e: unknown) => void
|
||||
}
|
||||
|
||||
const dateTime = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium', timeStyle: 'short' })
|
||||
const date = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium' })
|
||||
const fmt = (d?: string | null, withTime = true) => (d ? (withTime ? dateTime : date).format(new Date(d)) : '—')
|
||||
|
||||
/** Liste paginée (« Voir plus ») avec recherche facultative. */
|
||||
function usePaged<T>(token: string, action: string, onAuthError: (e: unknown) => void, q = '') {
|
||||
const [rows, setRows] = useState<T[]>()
|
||||
const [more, setMore] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [tick, setTick] = useState(0)
|
||||
const load = useCallback(
|
||||
async (offset: number) => {
|
||||
setError(undefined)
|
||||
try {
|
||||
const page = await call<T[]>(token, action, { q, offset })
|
||||
setRows((prev) => (offset ? [...(prev ?? []), ...page] : page))
|
||||
setMore(page.length >= (action === 'members' || action === 'journal' ? 50 : 30))
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
}
|
||||
},
|
||||
[token, action, q, onAuthError],
|
||||
)
|
||||
useEffect(() => {
|
||||
void load(0)
|
||||
}, [load, tick])
|
||||
return { rows, more, error, loadMore: () => void load(rows?.length ?? 0), reload: () => setTick((n) => n + 1) }
|
||||
}
|
||||
|
||||
function Avatar({ card }: { card: Card }) {
|
||||
return card.avatar_url ? (
|
||||
<img src={card.avatar_url} alt="" className="size-9 shrink-0 rounded-full border border-line object-cover" />
|
||||
) : (
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-full border border-line bg-surface-2 text-sm font-bold text-ink-3">
|
||||
{(card.display_name || card.username || '?').charAt(0).toUpperCase()}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function Who({ card, sub }: { card: Card; sub?: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<Avatar card={card} />
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-semibold">
|
||||
{card.display_name || card.username} <span className="font-normal text-ink-3">@{card.username}</span>
|
||||
{card.suspended && <span className="badge ms-2 border-danger text-danger">suspendu</span>}
|
||||
</p>
|
||||
{sub && <p className="truncate text-xs text-ink-3">{sub}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Status({ rows, error, empty }: { rows?: unknown[]; error?: string; empty: string }) {
|
||||
if (error) return <p className="py-6 text-sm text-danger">{error}</p>
|
||||
if (!rows) return <p className="py-6 text-sm text-ink-3">Chargement…</p>
|
||||
if (!rows.length) return <p className="py-6 text-sm text-ink-3">{empty}</p>
|
||||
return null
|
||||
}
|
||||
|
||||
function SearchBar({ placeholder, onSearch }: { placeholder: string; onSearch: (q: string) => void }) {
|
||||
const [value, setValue] = useState('')
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
onSearch(value.trim())
|
||||
}
|
||||
return (
|
||||
<form onSubmit={submit} className="mb-4 flex gap-2">
|
||||
<input className="field" placeholder={placeholder} value={value} onChange={(e) => setValue(e.target.value.slice(0, 60))} enterKeyHint="search" />
|
||||
<button className="btn btn-ghost px-3" aria-label="Rechercher">
|
||||
<Search size={18} />
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function MoreButton({ more, onMore }: { more: boolean; onMore: () => void }) {
|
||||
return more ? (
|
||||
<button onClick={onMore} className="btn btn-ghost mt-4 w-full">
|
||||
Voir plus
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
|
||||
/** Action sensible : motif obligatoire (inscrit au journal et dans l'e-mail d'alerte). */
|
||||
function Confirm({
|
||||
title,
|
||||
text,
|
||||
confirmLabel,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
title: string
|
||||
text: ReactNode
|
||||
confirmLabel: string
|
||||
onConfirm: (reason: string) => Promise<void>
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [reason, setReason] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
await onConfirm(reason.trim())
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Erreur inattendue.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-scrim p-0 sm:items-center sm:p-4" onClick={onClose}>
|
||||
<form onSubmit={submit} onClick={(e) => e.stopPropagation()} className="w-full max-w-md border border-line-strong bg-surface p-5 pb-[max(1.25rem,env(safe-area-inset-bottom))]">
|
||||
<h2 className="text-lg font-bold">{title}</h2>
|
||||
<div className="mt-2 text-sm text-ink-2">{text}</div>
|
||||
<label className="mt-4 block text-sm font-medium">Motif (gardé dans le journal)</label>
|
||||
<textarea className="field mt-1.5 min-h-20" value={reason} onChange={(e) => setReason(e.target.value.slice(0, 500))} required minLength={3} autoFocus />
|
||||
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
|
||||
<div className="mt-4 flex gap-2">
|
||||
<button type="button" onClick={onClose} className="btn btn-ghost flex-1">
|
||||
Annuler
|
||||
</button>
|
||||
<button className="btn btn-danger flex-1" disabled={busy || reason.trim().length < 3}>
|
||||
{busy ? '…' : confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Tableau de bord ───
|
||||
|
||||
export function Dashboard({ token, onAuthError }: ScreenProps) {
|
||||
const [data, setData] = useState<Overview>()
|
||||
const [error, setError] = useState<string>()
|
||||
useEffect(() => {
|
||||
call<Overview>(token, 'overview')
|
||||
.then(setData)
|
||||
.catch((e) => {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
})
|
||||
}, [token, onAuthError])
|
||||
if (error) return <p className="text-sm text-danger">{error}</p>
|
||||
if (!data) return <p className="text-sm text-ink-3">Chargement…</p>
|
||||
const tiles: [string, number, string?][] = [
|
||||
['Membres', data.members, `+${data.members_week} cette semaine`],
|
||||
['Actifs (7 j)', data.active_week],
|
||||
['Fiches', data.items],
|
||||
['Avis', data.reviews],
|
||||
['Commentaires', data.comments],
|
||||
['Abonnements', data.follows],
|
||||
['Listes partagées', data.shared_lists],
|
||||
['Comptes privés', data.private],
|
||||
['Suspendus', data.suspended],
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
{tiles.map(([label, n, sub]) => (
|
||||
<div key={label} className="border border-line bg-surface p-4">
|
||||
<p className="text-xs text-ink-3">{label}</p>
|
||||
<p className="mt-1 text-2xl font-bold tabular-nums">{n.toLocaleString('fr-FR')}</p>
|
||||
{sub && <p className="mt-0.5 text-xs text-accent">{sub}</p>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<h2 className="mt-8 mb-3 font-bold">Dernières inscriptions</h2>
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{data.latest.map((c) => (
|
||||
<li key={c.id} className="py-3">
|
||||
<Who card={c} sub={`Inscrit le ${fmt(c.created_at)}`} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Membres ───
|
||||
|
||||
export function Members({ token, onAuthError, meId }: ScreenProps & { meId: string }) {
|
||||
const [q, setQ] = useState('')
|
||||
const { rows, more, error, loadMore, reload } = usePaged<Member>(token, 'members', onAuthError, q)
|
||||
const [target, setTarget] = useState<Member>()
|
||||
const [adminTarget, setAdminTarget] = useState<Member>()
|
||||
return (
|
||||
<>
|
||||
<SearchBar placeholder="Pseudo, nom ou e-mail" onSearch={setQ} />
|
||||
<Status rows={rows} error={error} empty="Aucun membre trouvé." />
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{rows?.map((m) => (
|
||||
<li key={m.id} className="flex flex-wrap items-center gap-3 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<Who card={m} sub={m.email} />
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5 ps-12 text-xs text-ink-3">
|
||||
<span>
|
||||
Inscrit le {fmt(m.created_at, false)} · vu le {fmt(m.last_sign_in_at, false)} · {m.items} fiche{m.items > 1 ? 's' : ''}
|
||||
</span>
|
||||
{m.mfa && <span className="badge">2FA</span>}
|
||||
{m.is_admin && <span className="badge border-accent text-accent">admin</span>}
|
||||
</div>
|
||||
</div>
|
||||
{m.id !== meId && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{/* Admin : double authentification obligatoire (sans elle, impossible d'entrer dans la console) */}
|
||||
{(m.is_admin || (m.mfa && !m.suspended)) && (
|
||||
<button onClick={() => setAdminTarget(m)} className="btn btn-ghost py-1.5">
|
||||
{m.is_admin ? 'Retirer admin' : 'Nommer admin'}
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => setTarget(m)} className={`btn ${m.suspended ? 'btn-ghost' : 'btn-danger'} py-1.5`}>
|
||||
{m.suspended ? 'Réactiver' : 'Suspendre'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 text-xs text-ink-3">Pour être nommé admin, un membre doit d'abord activer la double authentification dans l'app (Réglages → Mon compte).</p>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
{adminTarget && (
|
||||
<Confirm
|
||||
title={adminTarget.is_admin ? `Retirer @${adminTarget.username} des admins ?` : `Nommer @${adminTarget.username} admin ?`}
|
||||
text={
|
||||
adminTarget.is_admin
|
||||
? "Il ne pourra plus ouvrir la console."
|
||||
: "Il pourra ouvrir cette console : voir les membres et leurs e-mails, suspendre des comptes, retirer des avis et des commentaires, nommer d'autres admins. Ne nomme que quelqu'un de confiance."
|
||||
}
|
||||
confirmLabel={adminTarget.is_admin ? 'Retirer' : 'Nommer'}
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'set_admin', { user: adminTarget.id, value: !adminTarget.is_admin, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setAdminTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
{target && (
|
||||
<Confirm
|
||||
title={target.suspended ? `Réactiver @${target.username} ?` : `Suspendre @${target.username} ?`}
|
||||
text={
|
||||
target.suspended
|
||||
? 'Son profil, ses avis et ses commentaires redeviennent visibles.'
|
||||
: 'Son profil, ses avis et ses commentaires deviennent invisibles pour les autres, et il ne peut plus s\'abonner ni réagir. Il garde sa bibliothèque.'
|
||||
}
|
||||
confirmLabel={target.suspended ? 'Réactiver' : 'Suspendre'}
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'suspend', { user: target.id, value: !target.suspended, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Avis ───
|
||||
|
||||
export function Reviews({ token, onAuthError }: ScreenProps) {
|
||||
const [q, setQ] = useState('')
|
||||
const { rows, more, error, loadMore, reload } = usePaged<Review>(token, 'reviews', onAuthError, q)
|
||||
const [target, setTarget] = useState<Review>()
|
||||
return (
|
||||
<>
|
||||
<SearchBar placeholder="Pseudo ou titre" onSearch={setQ} />
|
||||
<Status rows={rows} error={error} empty="Aucun avis." />
|
||||
<ul className="space-y-3">
|
||||
{rows?.map((r) => (
|
||||
<li key={r.user.id + r.item_id} className="border border-line bg-surface p-4">
|
||||
<Who card={r.user} sub={`${r.title} · ${fmt(r.updated_at)}`} />
|
||||
<p className="mt-3 text-sm text-ink-2">
|
||||
{typeof r.rating === 'number' && <span className="me-2 font-semibold text-accent">★ {(r.rating / 2).toLocaleString('fr-FR')}/5</span>}
|
||||
{r.spoiler && <span className="badge me-2">spoiler</span>}
|
||||
{r.comments > 0 && <span className="text-xs text-ink-3">{r.comments} commentaire{r.comments > 1 ? 's' : ''}</span>}
|
||||
</p>
|
||||
<p className="mt-2 whitespace-pre-line text-sm leading-relaxed">{r.notes}</p>
|
||||
<button onClick={() => setTarget(r)} className="btn btn-danger mt-3 py-1.5">
|
||||
Retirer l'avis
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
{target && (
|
||||
<Confirm
|
||||
title={`Retirer l'avis de @${target.user.username} ?`}
|
||||
text={`Sur « ${target.title} ». La note et la fiche restent ; seul le texte est retiré (une copie est gardée dans le journal). Les commentaires sous l'avis sont supprimés.`}
|
||||
confirmLabel="Retirer"
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'clear_review', { user: target.user.id, item: target.item_id, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Commentaires ───
|
||||
|
||||
export function Comments({ token, onAuthError }: ScreenProps) {
|
||||
const { rows, more, error, loadMore, reload } = usePaged<Comment>(token, 'comments', onAuthError)
|
||||
const [target, setTarget] = useState<Comment>()
|
||||
return (
|
||||
<>
|
||||
<Status rows={rows} error={error} empty="Aucun commentaire." />
|
||||
<ul className="space-y-3">
|
||||
{rows?.map((c) => (
|
||||
<li key={c.id} className="border border-line bg-surface p-4">
|
||||
<Who card={c.user} sub={`Sur l'avis de @${c.author.username}${c.title ? ` (« ${c.title} »)` : ''} · ${fmt(c.created_at)}`} />
|
||||
<p className="mt-3 whitespace-pre-line text-sm leading-relaxed">{c.body}</p>
|
||||
<button onClick={() => setTarget(c)} className="btn btn-danger mt-3 py-1.5">
|
||||
Supprimer
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
{target && (
|
||||
<Confirm
|
||||
title={`Supprimer le commentaire de @${target.user.username} ?`}
|
||||
text="Une copie du texte est gardée dans le journal."
|
||||
confirmLabel="Supprimer"
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'delete_comment', { id: target.id, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Journal ───
|
||||
|
||||
/** « Mozilla/5.0 (iPhone; …) … Safari/… » → « Safari · iPhone » */
|
||||
function deviceLabel(ua: string): string {
|
||||
const os = /iPhone/.test(ua) ? 'iPhone' : /iPad/.test(ua) ? 'iPad' : /Android/.test(ua) ? 'Android' : /Windows/.test(ua) ? 'Windows' : /Mac OS X/.test(ua) ? 'Mac' : /Linux/.test(ua) ? 'Linux' : ''
|
||||
const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /OPR\//.test(ua) ? 'Opera' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : ''
|
||||
return [browser, os].filter(Boolean).join(' · ') || ua.slice(0, 80)
|
||||
}
|
||||
|
||||
export function Journal({ token, onAuthError }: ScreenProps) {
|
||||
const { rows, more, error, loadMore } = usePaged<JournalEntry>(token, 'journal', onAuthError)
|
||||
return (
|
||||
<>
|
||||
<p className="mb-4 text-sm text-ink-3">Connexions et actions de la console. Rien ne peut y être modifié ni effacé.</p>
|
||||
<Status rows={rows} error={error} empty="Journal vide." />
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{rows?.map((j) => (
|
||||
<li key={j.id} className="py-3 text-sm">
|
||||
<p>
|
||||
<span className="font-semibold">{j.action}</span>
|
||||
{j.target && <span className="text-ink-2"> · {j.target}</span>}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-ink-3">
|
||||
{fmt(j.at)}
|
||||
{j.admin && ` · par @${j.admin}`}
|
||||
</p>
|
||||
{Object.entries(j.details && typeof j.details === 'object' ? j.details : {}).map(([k, v]) => (
|
||||
<p key={k} className="mt-1 break-words text-xs text-ink-2">
|
||||
<span className="text-ink-3">{k} :</span> {k === 'appareil' && typeof v === 'string' ? deviceLabel(v) : String(v)}
|
||||
</p>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
/* Mêmes couleurs que l'app (thème sombre), coins droits */
|
||||
@theme {
|
||||
--font-sans: 'Epilogue Variable', 'Epilogue', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--color-bg: #090909;
|
||||
--color-surface: #121212;
|
||||
--color-surface-2: #1b1b1b;
|
||||
--color-line: #2b2b2b;
|
||||
--color-line-strong: #424242;
|
||||
--color-ink: #f2f2f0;
|
||||
--color-ink-2: #c4c4c4;
|
||||
--color-ink-3: #989898;
|
||||
--color-accent: #53bfb6;
|
||||
--color-on-accent: #062b28;
|
||||
--color-danger: #f97066;
|
||||
--color-on-danger: #2b0a06;
|
||||
--color-scrim: rgb(0 0 0 / 0.7);
|
||||
--radius-sm: 0.125rem;
|
||||
--radius-md: 0.125rem;
|
||||
--radius-lg: 0.125rem;
|
||||
--radius-xl: 0.125rem;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
background: var(--color-bg);
|
||||
color: var(--color-ink);
|
||||
color-scheme: dark;
|
||||
}
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
button,
|
||||
a {
|
||||
touch-action: manipulation;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.field {
|
||||
@apply w-full rounded-md border border-line-strong bg-surface px-3 py-2.5 text-ink outline-none placeholder:text-ink-3 focus:border-accent;
|
||||
}
|
||||
.btn {
|
||||
@apply inline-flex items-center justify-center gap-2 rounded-md px-4 py-2.5 text-sm font-semibold transition-colors disabled:opacity-50;
|
||||
}
|
||||
.btn-primary {
|
||||
@apply bg-accent text-on-accent active:opacity-80;
|
||||
}
|
||||
.btn-ghost {
|
||||
@apply border border-line-strong text-ink active:bg-surface-2;
|
||||
}
|
||||
.btn-danger {
|
||||
@apply border border-danger text-danger active:bg-danger active:text-on-danger;
|
||||
}
|
||||
.badge {
|
||||
@apply inline-flex items-center rounded-sm border border-line-strong px-1.5 py-0.5 text-[11px] font-medium text-ink-2;
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
# Sauvegardes automatiques de la base (Supabase → VPS)
|
||||
|
||||
Chaque nuit à 02:17 UTC, le workflow `.gitea/workflows/backup.yml` lance `deploy/backup.sh` sur le
|
||||
runner du VPS (runner Gitea `kino`, étiquette `azuucine`, service `gitea-runner` dans le conteneur LXC `kino`) :
|
||||
|
||||
1. `pg_dump` de toute la base (format custom compressé : tables, données, fonctions, policies RLS,
|
||||
comptes `auth.users`), via la connexion **Session pooler IPv4** de Supabase ;
|
||||
2. **contrôles** : taille minimale, dump lisible par `pg_restore`, présence des tables `items`,
|
||||
`profiles`, `follows`, `settings` et `auth.users` — sinon le job **échoue** (croix rouge dans Gitea) ;
|
||||
3. **chiffrement** gpg symétrique AES-256 avec `BACKUP_PASSPHRASE`, puis vérification que le fichier
|
||||
se déchiffre bien ;
|
||||
4. rangement dans `/srv/backups/azuucine/` (dossier en `700`) et **rotation** :
|
||||
7 quotidiennes, 4 hebdomadaires, 6 mensuelles (liens physiques : une même sauvegarde n'occupe
|
||||
la place qu'une fois).
|
||||
|
||||
Les secrets ne sont jamais dans le dépôt ni affichés dans les logs ; le mot de passe de la base passe
|
||||
par `PGPASSWORD` (pas sur la ligne de commande).
|
||||
|
||||
Pour restaurer : **`deploy/restore.md`**.
|
||||
|
||||
## Mise en place (une seule fois)
|
||||
|
||||
### 1. Chaîne de connexion Supabase
|
||||
|
||||
Supabase → projet `qfgnxonqwldcfdjqhhjz` → **Connect** → **Session pooler** (IPv4, port 5432).
|
||||
Le projet est en région `eu-west-1`, Postgres 17 ; la chaîne a cette forme (copier celle affichée par Supabase) :
|
||||
|
||||
```
|
||||
postgresql://postgres.qfgnxonqwldcfdjqhhjz:[YOUR-PASSWORD]@aws-0-eu-west-1.pooler.supabase.com:5432/postgres
|
||||
```
|
||||
|
||||
Remplacer `[YOUR-PASSWORD]` par le mot de passe de la base (Project Settings → Database → Reset
|
||||
database password si tu ne l'as plus ; **les caractères spéciaux doivent être encodés en %XX**,
|
||||
ex. `@` → `%40`, ou choisir un mot de passe sans caractères spéciaux, long).
|
||||
|
||||
> Pourquoi le *Session pooler* : la connexion directe `db.<ref>.supabase.co` est en IPv6 seulement ;
|
||||
> le pooler « session » est IPv4 et accepte `pg_dump` (le pooler « transaction », port 6543, non).
|
||||
|
||||
### 2. Phrase de chiffrement
|
||||
|
||||
Générer une phrase longue et la ranger **dans ton gestionnaire de mots de passe** (si le VPS meurt,
|
||||
c'est la seule façon de relire les sauvegardes copiées ailleurs) :
|
||||
|
||||
```bash
|
||||
openssl rand -base64 32
|
||||
```
|
||||
|
||||
### 3. Secrets Gitea
|
||||
|
||||
Dépôt `romain/kino` → **Paramètres → Actions → Secrets** :
|
||||
|
||||
| Nom | Valeur |
|
||||
| --- | --- |
|
||||
| `SUPABASE_DB_URL` | la chaîne de l'étape 1 |
|
||||
| `BACKUP_PASSPHRASE` | la phrase de l'étape 2 |
|
||||
|
||||
Optionnel, **Variables** : `BACKUP_DIR` (défaut `/srv/backups/azuucine`).
|
||||
|
||||
### 4. Préparer le VPS (en root, une fois)
|
||||
|
||||
Le runner tourne avec l'utilisateur `deploy` (sans sudo). Il lui faut un client Postgres **de la même
|
||||
version majeure que Supabase ou plus récent** (Supabase → Project Settings → Infrastructure ; 15 ou 17),
|
||||
`gpg`, et le dossier des sauvegardes :
|
||||
|
||||
```bash
|
||||
# Client Postgres officiel (dépôt PGDG), ex. version 17
|
||||
apt-get install -y gnupg postgresql-common
|
||||
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
|
||||
apt-get install -y postgresql-client-17
|
||||
|
||||
# Dossier dédié, hors de /srv/azuucine (qui est monté dans le conteneur web)
|
||||
install -d -m 700 -o deploy -g deploy /srv/backups/azuucine
|
||||
```
|
||||
|
||||
Alternative sans installer le client : si l'utilisateur `deploy` peut lancer Docker, le script utilise
|
||||
automatiquement l'image `postgres:17-alpine` quand le `pg_dump` local manque ou est trop ancien.
|
||||
|
||||
### 5. Premier lancement
|
||||
|
||||
Gitea → **Actions → backup → Run workflow**. Le log doit finir par :
|
||||
|
||||
```
|
||||
sauvegarde OK : azuucine-AAAAMMJJ-HHMMSS.dump.gpg (… octets chiffrés, … tables de données)
|
||||
daily : 1
|
||||
weekly : 1
|
||||
monthly : 1
|
||||
```
|
||||
|
||||
Puis **tester une restauration** dans une base jetable (`deploy/restore.md`, cas a). Une sauvegarde
|
||||
jamais testée n'est pas une sauvegarde.
|
||||
|
||||
## Runner arrêté ?
|
||||
|
||||
Si plus aucun déploiement ni sauvegarde ne part (jobs « en attente » dans Gitea → Actions) :
|
||||
|
||||
```bash
|
||||
lxc-attach -n kino
|
||||
systemctl status gitea-runner
|
||||
systemctl restart gitea-runner
|
||||
```
|
||||
|
||||
Depuis le 25 nov. 2026, `/etc/systemd/system/gitea-runner.service.d/relance.conf` (dans le conteneur `kino`)
|
||||
le fait réessayer toutes les 15 s sans limite après un redémarrage du VPS (avant, il abandonnait si
|
||||
le proxy n'était pas encore prêt : 3 semaines sans déploiement en novembre 2026).
|
||||
|
||||
## Surveillance
|
||||
|
||||
- Un échec rend le job rouge dans Gitea : active les **notifications par e-mail des Actions** dans
|
||||
ton profil Gitea (Paramètres → Notifications) pour être prévenu.
|
||||
- `/srv/backups/azuucine/.last-success` contient la date de la dernière sauvegarde réussie.
|
||||
- Le job ne touche pas aux sauvegardes existantes s'il échoue.
|
||||
|
||||
## Recommandé : une copie hors du VPS
|
||||
|
||||
Les sauvegardes sur le VPS protègent contre une erreur côté Supabase (fausse manip, projet supprimé),
|
||||
pas contre la perte du VPS. Les fichiers étant chiffrés, on peut les copier n'importe où sans risque,
|
||||
par exemple chaque semaine depuis un autre ordinateur :
|
||||
|
||||
```bash
|
||||
rsync -a deploy@<vps>:/srv/backups/azuucine/weekly/ ~/Sauvegardes/azuucine/
|
||||
```
|
||||
|
||||
## Lancer une sauvegarde à la main (sur le VPS)
|
||||
|
||||
```bash
|
||||
export SUPABASE_DB_URL='postgresql://…' # ou lu depuis un fichier en 600
|
||||
read -rs BACKUP_PASSPHRASE && export BACKUP_PASSPHRASE
|
||||
bash deploy/backup.sh
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
# Runner Gitea (déploiement)
|
||||
|
||||
Le runner `bobinoo` (étiquette `bobinoo`) tourne dans le conteneur LXC `bobinoo` du VPS. S'il est arrêté, plus rien ne se déploie.
|
||||
|
||||
## Runner arrêté ?
|
||||
|
||||
Si plus aucun déploiement ne part (jobs « en attente » dans Gitea → Actions) :
|
||||
|
||||
```bash
|
||||
lxc-attach -n bobinoo
|
||||
systemctl status gitea-runner
|
||||
systemctl restart gitea-runner
|
||||
```
|
||||
|
||||
Depuis le 25 nov. 2026, `/etc/systemd/system/gitea-runner.service.d/relance.conf` (dans le conteneur `bobinoo`)
|
||||
le fait réessayer toutes les 15 s sans limite après un redémarrage du VPS (avant, il abandonnait si
|
||||
le proxy n'était pas encore prêt : 3 semaines sans déploiement en novembre 2026).
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sauvegarde chiffrée de la base Supabase d'AzuuCine, avec rotation.
|
||||
# Lancé chaque nuit par .gitea/workflows/backup.yml (runner "azuucine", sur le VPS).
|
||||
#
|
||||
# Variables (secrets Gitea, JAMAIS dans le dépôt) :
|
||||
# SUPABASE_DB_URL postgresql://postgres.<ref>:<mot de passe>@aws-0-<région>.pooler.supabase.com:5432/postgres
|
||||
# (Supabase -> Connect -> « Session pooler », IPv4)
|
||||
# BACKUP_PASSPHRASE phrase de chiffrement (gpg symétrique AES-256) — à garder AUSSI hors du VPS
|
||||
# Optionnelles :
|
||||
# BACKUP_DIR dossier des sauvegardes (défaut : /srv/backups/azuucine)
|
||||
# PG_IMAGE image Docker du client Postgres si pg_dump local trop ancien (défaut : postgres:17-alpine)
|
||||
# KEEP_DAILY / KEEP_WEEKLY / KEEP_MONTHLY (défaut : 7 / 4 / 6)
|
||||
# MIN_DUMP_BYTES taille minimale d'un dump valide (défaut : 20000)
|
||||
#
|
||||
# Restauration : voir deploy/restore.md. Procédure complète : deploy/BACKUP.md.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
fail() { echo "ÉCHEC SAUVEGARDE : $*" >&2; exit 1; }
|
||||
trap 'fail "erreur inattendue (ligne $LINENO)"' ERR
|
||||
|
||||
: "${SUPABASE_DB_URL:?SUPABASE_DB_URL manquante (secret Gitea)}"
|
||||
: "${BACKUP_PASSPHRASE:?BACKUP_PASSPHRASE manquante (secret Gitea)}"
|
||||
[ "${#BACKUP_PASSPHRASE}" -ge 16 ] || fail "BACKUP_PASSPHRASE trop courte (16 caractères minimum)"
|
||||
BACKUP_DIR=${BACKUP_DIR:-/srv/backups/azuucine}
|
||||
PG_IMAGE=${PG_IMAGE:-postgres:17-alpine}
|
||||
KEEP_DAILY=${KEEP_DAILY:-7}
|
||||
KEEP_WEEKLY=${KEEP_WEEKLY:-4}
|
||||
KEEP_MONTHLY=${KEEP_MONTHLY:-6}
|
||||
MIN_DUMP_BYTES=${MIN_DUMP_BYTES:-20000}
|
||||
command -v gpg >/dev/null || fail "gpg absent (apt install gnupg)"
|
||||
|
||||
# ── Connexion : le mot de passe passe par PGPASSWORD, jamais sur la ligne de commande (visible dans ps) ──
|
||||
re='^(postgres(ql)?://)([^:/@]+):([^@]*)@(.+)$'
|
||||
[[ "$SUPABASE_DB_URL" =~ $re ]] || fail "SUPABASE_DB_URL mal formée (attendu postgresql://user:motdepasse@hôte:port/base)"
|
||||
DB_URL="${BASH_REMATCH[1]}${BASH_REMATCH[3]}@${BASH_REMATCH[5]}"
|
||||
pw=${BASH_REMATCH[4]}
|
||||
PGPASSWORD=$(printf '%b' "${pw//%/\\x}") # décodage des %XX éventuels
|
||||
export PGPASSWORD
|
||||
export PGSSLMODE=${PGSSLMODE:-require}
|
||||
export PGCONNECT_TIMEOUT=20
|
||||
unset pw
|
||||
|
||||
mkdir -p "$BACKUP_DIR"/{daily,weekly,monthly}
|
||||
chmod 700 "$BACKUP_DIR" "$BACKUP_DIR"/{daily,weekly,monthly}
|
||||
WORK=$(mktemp -d "$BACKUP_DIR/.work.XXXXXX")
|
||||
cleanup() { rm -rf "$WORK"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
# ── Client Postgres : pg_dump local s'il est assez récent (>= version du serveur), sinon Docker ──
|
||||
pg() { # pg <commande> <args…> — exécute un outil client Postgres
|
||||
if [ "${USE_DOCKER:-0}" = 1 ]; then
|
||||
docker run --rm -i --network host --user "$(id -u):$(id -g)" \
|
||||
-e PGPASSWORD -e PGSSLMODE -e PGCONNECT_TIMEOUT -v "$WORK:$WORK" -w "$WORK" "$PG_IMAGE" "$@"
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
server_major() { pg psql -X -At -d "$DB_URL" -c 'show server_version_num' | cut -c1-2; }
|
||||
|
||||
USE_DOCKER=0
|
||||
if command -v pg_dump >/dev/null && command -v psql >/dev/null; then
|
||||
local_major=$(pg_dump --version | grep -oE '[0-9]+' | head -1)
|
||||
srv=$(server_major) || fail "connexion à la base impossible (URL, mot de passe, réseau IPv4 ?)"
|
||||
if [ "$local_major" -lt "$srv" ]; then
|
||||
command -v docker >/dev/null || fail "pg_dump $local_major < serveur $srv et Docker absent : installe postgresql-client-$srv"
|
||||
USE_DOCKER=1
|
||||
fi
|
||||
else
|
||||
command -v docker >/dev/null || fail "ni pg_dump ni Docker : installe postgresql-client (même version que Supabase) ou Docker"
|
||||
USE_DOCKER=1
|
||||
srv=$(server_major) || fail "connexion à la base impossible (URL, mot de passe, réseau IPv4 ?)"
|
||||
fi
|
||||
echo "serveur Postgres $srv · client $([ "$USE_DOCKER" = 1 ] && echo "Docker $PG_IMAGE" || echo "local $local_major")"
|
||||
|
||||
# ── Dump (format « custom » : compressé, restauration sélective possible avec pg_restore) ──
|
||||
STAMP=$(date -u +%Y%m%d-%H%M%S)
|
||||
DUMP="$WORK/azuucine-$STAMP.dump"
|
||||
pg pg_dump -d "$DB_URL" --format=custom --compress=9 --no-owner --no-privileges \
|
||||
--exclude-table-data='auth.audit_log_entries' --file "$DUMP" \
|
||||
|| fail "pg_dump a échoué"
|
||||
|
||||
# ── Contrôles : le dump doit exister, avoir une taille plausible et contenir les tables de l'app ──
|
||||
[ -s "$DUMP" ] || fail "dump vide"
|
||||
size=$(stat -c %s "$DUMP")
|
||||
[ "$size" -ge "$MIN_DUMP_BYTES" ] || fail "dump trop petit ($size octets < $MIN_DUMP_BYTES) : base vide ou dump incomplet ?"
|
||||
pg pg_restore --list "$DUMP" > "$WORK/toc.txt" || fail "dump illisible par pg_restore"
|
||||
for tbl in items profiles follows settings; do
|
||||
grep -qE "TABLE DATA public $tbl " "$WORK/toc.txt" || fail "table public.$tbl absente du dump"
|
||||
done
|
||||
grep -qE "TABLE DATA auth users " "$WORK/toc.txt" || fail "table auth.users absente du dump"
|
||||
entries=$(grep -c 'TABLE DATA' "$WORK/toc.txt")
|
||||
|
||||
# ── Chiffrement (gpg symétrique AES-256 ; la phrase passe par un descripteur, pas par la ligne de commande) ──
|
||||
ENC="$DUMP.gpg"
|
||||
gpg --batch --yes --quiet --pinentry-mode loopback --passphrase-fd 3 \
|
||||
--symmetric --cipher-algo AES256 --s2k-digest-algo SHA512 --s2k-count 65011712 --compress-algo none \
|
||||
--output "$ENC" "$DUMP" 3<<<"$BACKUP_PASSPHRASE" || fail "chiffrement impossible"
|
||||
# Vérification : le fichier chiffré se déchiffre et redonne exactement le dump
|
||||
gpg --batch --quiet --pinentry-mode loopback --passphrase-fd 3 --decrypt "$ENC" 3<<<"$BACKUP_PASSPHRASE" \
|
||||
| cmp -s - "$DUMP" || fail "vérification du déchiffrement échouée"
|
||||
sha256sum "$ENC" | sed "s# .*/# #" > "$ENC.sha256"
|
||||
rm -f "$DUMP"
|
||||
|
||||
# ── Rangement + rotation (7 quotidiennes, 4 hebdomadaires, 6 mensuelles ; liens physiques = pas de doublon disque) ──
|
||||
name=$(basename "$ENC")
|
||||
mv "$ENC" "$ENC.sha256" "$BACKUP_DIR/daily/"
|
||||
newest() { { ls -1 "$1"/*.gpg 2>/dev/null || true; } | sort | tail -1; }
|
||||
age_days() { echo $(( ( $(date -u +%s) - $(stat -c %Y "$1") ) / 86400 )); }
|
||||
w=$(newest "$BACKUP_DIR/weekly")
|
||||
if [ -z "$w" ] || [ "$(age_days "$w")" -ge 7 ]; then
|
||||
ln -f "$BACKUP_DIR/daily/$name" "$BACKUP_DIR/weekly/$name"
|
||||
ln -f "$BACKUP_DIR/daily/$name.sha256" "$BACKUP_DIR/weekly/$name.sha256"
|
||||
fi
|
||||
m=$(newest "$BACKUP_DIR/monthly")
|
||||
if [ -z "$m" ] || [ "$(basename "$m" | cut -c10-15)" != "$(date -u +%Y%m)" ]; then
|
||||
ln -f "$BACKUP_DIR/daily/$name" "$BACKUP_DIR/monthly/$name"
|
||||
ln -f "$BACKUP_DIR/daily/$name.sha256" "$BACKUP_DIR/monthly/$name.sha256"
|
||||
fi
|
||||
prune() { # prune <dossier> <nombre à garder>
|
||||
{ ls -1 "$1"/*.gpg 2>/dev/null || true; } | sort -r | tail -n +$(( $2 + 1 )) | while read -r f; do rm -f "$f" "$f.sha256"; done
|
||||
}
|
||||
prune "$BACKUP_DIR/daily" "$KEEP_DAILY"
|
||||
prune "$BACKUP_DIR/weekly" "$KEEP_WEEKLY"
|
||||
prune "$BACKUP_DIR/monthly" "$KEEP_MONTHLY"
|
||||
|
||||
date -u +%FT%TZ > "$BACKUP_DIR/.last-success"
|
||||
echo "sauvegarde OK : $name ($(stat -c %s "$BACKUP_DIR/daily/$name") octets chiffrés, $entries tables de données)"
|
||||
for d in daily weekly monthly; do echo " $d : $({ ls -1 "$BACKUP_DIR/$d"/*.gpg 2>/dev/null || true; } | wc -l)"; done
|
||||
@@ -51,7 +51,7 @@ for (const [path, h] of blocks) {
|
||||
if (path.includes('*')) fail(`motif non géré : ${path}`)
|
||||
locations.push(
|
||||
`location = ${path} {`,
|
||||
' include /srv/azuucine/current/nginx/security-headers.conf;',
|
||||
' include /srv/bobinoo/current/nginx/security-headers.conf;',
|
||||
...add(h).map((l) => ` ${l}`),
|
||||
'}',
|
||||
)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Console d'administration (docs/admin.md) : https://admin.bobinoo.org. Incluse par site.conf, livrée avec chaque release.
|
||||
# Le HTTPS est assuré par le proxy en façade du VPS, comme pour bobinoo.org (il doit transmettre l'en-tête Host).
|
||||
# Protections : mot de passe + code de double authentification obligatoire, liste des admins, secret entre ce
|
||||
# serveur et la fonction Edge, nombre d'appels limité, journal et e-mail d'alerte à chaque connexion.
|
||||
|
||||
# Limite globale des appels à la console (tous visiteurs confondus) : 60 par minute, rafale de 30
|
||||
limit_req_zone $server_name zone=bobinoo_admin:1m rate=60r/m;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name admin.bobinoo.org;
|
||||
server_tokens off;
|
||||
|
||||
root /srv/bobinoo/current/admin;
|
||||
index index.html;
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data: https://qfgnxonqwldcfdjqhhjz.supabase.co; connect-src 'self' https://qfgnxonqwldcfdjqhhjz.supabase.co; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=63072000" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "no-referrer" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
|
||||
|
||||
# Relais vers la fonction serveur « admin » : nginx ajoute le secret partagé (en-tête X-Admin-Gate).
|
||||
# Le secret est dans /etc/nginx/bobinoo-admin-gate.conf, créé une fois sur le VPS, JAMAIS dans le dépôt :
|
||||
# proxy_set_header X-Admin-Gate "<secret de 64 caractères>";
|
||||
# Fichier absent : la fonction répond 404 (la console affiche « pas reliée au serveur »), le site n'est pas touché.
|
||||
location = /api/admin {
|
||||
limit_except POST { deny all; }
|
||||
limit_req zone=bobinoo_admin burst=30 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 16k;
|
||||
resolver 1.1.1.1 9.9.9.9 valid=300s ipv6=off;
|
||||
resolver_timeout 5s;
|
||||
set $supabase qfgnxonqwldcfdjqhhjz.supabase.co;
|
||||
proxy_pass https://$supabase/functions/v1/admin;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name $supabase;
|
||||
proxy_set_header Host $supabase;
|
||||
proxy_set_header Cookie "";
|
||||
proxy_set_header X-Forwarded-For "";
|
||||
include /etc/nginx/bobinoo-admin-gate*.conf;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
location = /robots.txt {
|
||||
default_type text/plain;
|
||||
return 200 "User-agent: *\nDisallow: /\n";
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
# Messagerie Bobinoo (docs/mail.md) : https://mail.bobinoo.org, interface de contact@bobinoo.org (boîte OVH Zimbra).
|
||||
# Incluse par site.conf, livrée avec chaque release. HTTPS assuré par le proxy en façade du VPS (en-tête Host transmis).
|
||||
# Mêmes protections que la console : compte Bobinoo admin + code de double authentification, secret entre ce serveur
|
||||
# et la fonction Edge « mail », nombre d'appels limité, journal.
|
||||
|
||||
limit_req_zone $server_name zone=bobinoo_mail:1m rate=120r/m;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name mail.bobinoo.org;
|
||||
server_tokens off;
|
||||
|
||||
root /srv/bobinoo/current/mail;
|
||||
index index.html;
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
# Styles en ligne autorisés : le contenu des e-mails en a besoin (il est affiché dans un cadre isolé, sans script).
|
||||
# Images https autorisées : bloquées par défaut par l'interface, chargées seulement sur « Afficher les images ».
|
||||
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob: https:; connect-src 'self' https://qfgnxonqwldcfdjqhhjz.supabase.co; frame-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=63072000" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "no-referrer" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
|
||||
|
||||
# Relais vers la fonction serveur « mail », avec le même secret que la console (/etc/nginx/bobinoo-admin-gate.conf)
|
||||
location = /api/mail {
|
||||
limit_except POST { deny all; }
|
||||
limit_req zone=bobinoo_mail burst=40 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 256k;
|
||||
resolver 1.1.1.1 9.9.9.9 valid=300s ipv6=off;
|
||||
resolver_timeout 5s;
|
||||
set $supabase qfgnxonqwldcfdjqhhjz.supabase.co;
|
||||
proxy_pass https://$supabase/functions/v1/mail;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name $supabase;
|
||||
proxy_set_header Host $supabase;
|
||||
proxy_set_header Cookie "";
|
||||
proxy_set_header X-Forwarded-For "";
|
||||
include /etc/nginx/bobinoo-admin-gate*.conf;
|
||||
proxy_read_timeout 60s;
|
||||
}
|
||||
|
||||
location = /robots.txt {
|
||||
default_type text/plain;
|
||||
return 200 "User-agent: *\nDisallow: /\n";
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
# Autre adresse : renvoie vers la messagerie
|
||||
server {
|
||||
listen 80;
|
||||
server_name webmail.bobinoo.org;
|
||||
server_tokens off;
|
||||
return 301 https://mail.bobinoo.org/;
|
||||
}
|
||||
@@ -1,35 +1,52 @@
|
||||
# Configuration nginx du site AzuuCine (conteneur azuucine-web).
|
||||
# Livrée avec chaque release (copiée par deploy/release.sh) et lue via /srv/azuucine/current/nginx/site.conf :
|
||||
# Configuration nginx du site Bobinoo (conteneur bobinoo).
|
||||
# Livrée avec chaque release (copiée par deploy/release.sh) et lue via /srv/bobinoo/current/nginx/site.conf :
|
||||
# la configuration vit donc dans le dépôt, et un conteneur recréé la récupère au premier déploiement.
|
||||
# Les en-têtes de sécurité (security-headers.conf, locations.conf) sont, eux, générés depuis dist/_headers.
|
||||
server {
|
||||
listen 80 default_server;
|
||||
server_name azuucine.rdacet.fr _;
|
||||
server_name bobinoo.org www.bobinoo.org _;
|
||||
server_tokens off;
|
||||
|
||||
root /srv/azuucine/current/dist;
|
||||
root /srv/bobinoo/current/dist;
|
||||
index index.html;
|
||||
|
||||
# Adresse inconnue : vraie réponse 404 avec une page dédiée
|
||||
error_page 404 /404.html;
|
||||
|
||||
# Compression : sans elle, l'app partait brute (fichier principal 387 Ko au lieu de ~116 Ko, React 223 → 69 Ko).
|
||||
# Réglée ici, au niveau du site (aucun doublon possible avec la config générale de nginx).
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
# Le proxy HTTPS en façade parle à ce serveur en HTTP/1.0 : par défaut, nginx ne compresse alors rien
|
||||
gzip_http_version 1.0;
|
||||
gzip_comp_level 6;
|
||||
gzip_min_length 1024;
|
||||
gzip_types text/css application/javascript text/javascript application/json application/manifest+json image/svg+xml text/plain;
|
||||
|
||||
# nginx ne connaît pas .webmanifest : sans cette ligne, le manifest du PWA est servi en octet-stream
|
||||
include /etc/nginx/mime.types;
|
||||
types { application/manifest+json webmanifest; }
|
||||
|
||||
# Règles par chemin issues de _headers (ex. /sw.js -> no-cache)
|
||||
include /srv/azuucine/current/nginx/locations.conf;
|
||||
include /srv/bobinoo/current/nginx/locations.conf;
|
||||
|
||||
# Fichiers hashés : cache immuable
|
||||
location /assets/ {
|
||||
include /srv/azuucine/current/nginx/security-headers.conf;
|
||||
include /srv/bobinoo/current/nginx/security-headers.conf;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
include /srv/azuucine/current/nginx/security-headers.conf;
|
||||
include /srv/bobinoo/current/nginx/security-headers.conf;
|
||||
add_header Cache-Control "public, max-age=0, must-revalidate" always;
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
}
|
||||
|
||||
# Console d'administration : https://admin.bobinoo.org (voir admin.conf et docs/admin.md)
|
||||
include /srv/bobinoo/current/nginx/admin.conf;
|
||||
|
||||
# Messagerie de contact@bobinoo.org : https://mail.bobinoo.org (voir mail.conf et docs/mail.md)
|
||||
include /srv/bobinoo/current/nginx/mail.conf;
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Publie dist/ de façon atomique dans /srv/azuucine/releases/<date>-<sha> puis bascule le lien "current".
|
||||
# Publie dist/ de façon atomique dans /srv/bobinoo/releases/<date>-<sha> puis bascule le lien "current".
|
||||
# Garde les 3 dernières versions. Lancé par le workflow (utilisateur "deploy", sans sudo).
|
||||
set -euo pipefail
|
||||
ROOT=${AZUUCINE_ROOT:-/srv/azuucine}
|
||||
ROOT=${BOBINOO_ROOT:-${AZUUCINE_ROOT:-/srv/bobinoo}}
|
||||
KEEP=3
|
||||
SRC=${1:?usage: release.sh <dist> <sha>}
|
||||
SHA=${2:?usage: release.sh <dist> <sha>}
|
||||
@@ -14,6 +14,12 @@ mkdir -p "$REL"
|
||||
cp -a "$SRC" "$REL/dist"
|
||||
node "$HERE/headers-to-nginx.mjs" "$REL/dist/_headers" "$REL/nginx"
|
||||
cp "$HERE/nginx/site.conf" "$REL/nginx/site.conf" # config nginx du site, versionnée dans le dépôt
|
||||
# Console d'administration (docs/admin.md) : https://admin.bobinoo.org
|
||||
cp "$HERE/nginx/admin.conf" "$REL/nginx/admin.conf"
|
||||
# Messagerie (docs/mail.md) : https://mail.bobinoo.org
|
||||
cp "$HERE/nginx/mail.conf" "$REL/nginx/mail.conf"
|
||||
if [ -f "$SRC/../dist-mail/index.html" ]; then cp -a "$SRC/../dist-mail" "$REL/mail"; else mkdir -p "$REL/mail"; fi
|
||||
if [ -f "$SRC/../dist-admin/index.html" ]; then cp -a "$SRC/../dist-admin" "$REL/admin"; else mkdir -p "$REL/admin"; fi
|
||||
|
||||
# bascule atomique : lien relatif temporaire puis rename
|
||||
ln -s "releases/$(basename "$REL")" "$ROOT/current.tmp"
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
# Restaurer une sauvegarde de la base AzuuCine
|
||||
|
||||
Les sauvegardes sont produites chaque nuit par `deploy/backup.sh` (workflow `.gitea/workflows/backup.yml`)
|
||||
dans `/srv/backups/azuucine/{daily,weekly,monthly}/` sur le VPS :
|
||||
|
||||
```
|
||||
azuucine-AAAAMMJJ-HHMMSS.dump.gpg dump pg_dump (format custom, compressé) chiffré AES-256 (gpg symétrique)
|
||||
azuucine-AAAAMMJJ-HHMMSS.dump.gpg.sha256 empreinte du fichier chiffré
|
||||
```
|
||||
|
||||
Il faut la **phrase de chiffrement** (`BACKUP_PASSPHRASE`, gardée dans ton gestionnaire de mots de passe) :
|
||||
sans elle, la sauvegarde est illisible — c'est voulu.
|
||||
|
||||
> ⚠️ Toujours **tester d'abord sur un projet Supabase de test** (ou une base Postgres locale), jamais
|
||||
> directement sur la production. Une restauration remplace des données : fais d'abord une sauvegarde
|
||||
> de l'état actuel (`bash deploy/backup.sh` à la main, voir BACKUP.md).
|
||||
|
||||
## 1. Récupérer et déchiffrer
|
||||
|
||||
```bash
|
||||
cd /srv/backups/azuucine/daily # ou weekly / monthly
|
||||
ls -1 # choisir le fichier
|
||||
F=azuucine-20261009-021703.dump.gpg
|
||||
sha256sum -c "$F.sha256" # doit afficher : OK
|
||||
|
||||
# Déchiffrer (la phrase est demandée ; rien n'est écrit dans l'historique du shell)
|
||||
umask 077
|
||||
gpg --decrypt --output /tmp/azuucine.dump "$F"
|
||||
|
||||
# Contenu du dump (liste des tables, fonctions, policies…)
|
||||
pg_restore --list /tmp/azuucine.dump | less
|
||||
```
|
||||
|
||||
Le client Postgres doit être **de la même version majeure que Supabase, ou plus récent**
|
||||
(`pg_restore --version`). Sinon, via Docker :
|
||||
`docker run --rm -it --network host -v /tmp:/tmp postgres:17-alpine pg_restore --list /tmp/azuucine.dump`
|
||||
|
||||
## 2. Cas courants
|
||||
|
||||
La connexion se fait avec la chaîne **Session pooler** (Supabase → Connect), mot de passe dans `PGPASSWORD` :
|
||||
|
||||
```bash
|
||||
export PGPASSWORD='…' # mot de passe de la base (pas dans l'URL)
|
||||
export PGSSLMODE=require
|
||||
DB='postgresql://postgres.<ref>@aws-0-<région>.pooler.supabase.com:5432/postgres'
|
||||
```
|
||||
|
||||
### a) Récupérer les données d'un seul compte ou d'une seule table (le plus fréquent)
|
||||
|
||||
Restaurer le dump dans une **base locale** jetable, puis copier ce qu'il faut :
|
||||
|
||||
```bash
|
||||
createdb azuu_restore
|
||||
pg_restore --no-owner --no-privileges -d azuu_restore --schema=public /tmp/azuucine.dump
|
||||
psql -d azuu_restore -c "select id, data->>'title' from public.items where user_id = '<uuid>'"
|
||||
```
|
||||
|
||||
(Les erreurs « role … does not exist » / « schema auth does not exist » sur une base locale sont normales :
|
||||
les tables `public` gardent leurs données.) Puis réinjecter les lignes voulues dans Supabase avec
|
||||
`\copy … to/from` ou un `insert … on conflict do update` ciblé.
|
||||
|
||||
### b) Restaurer tout le schéma `public` (après une fausse manip)
|
||||
|
||||
```bash
|
||||
# 1. sauvegarde de l'état actuel
|
||||
bash deploy/backup.sh
|
||||
# 2. restauration des tables de l'app (les comptes auth.users existent toujours)
|
||||
pg_restore --no-owner --no-privileges --clean --if-exists --schema=public -d "$DB" /tmp/azuucine.dump
|
||||
```
|
||||
|
||||
`--clean` supprime puis recrée les objets du schéma `public` (tables, fonctions, policies RLS).
|
||||
Relancer ensuite les migrations récentes si le dump est antérieur à l'une d'elles
|
||||
(`supabase/migrations/*.sql`, toutes idempotentes) dans **SQL Editor → Run**.
|
||||
|
||||
### c) Projet Supabase perdu (reconstruction complète dans un nouveau projet)
|
||||
|
||||
1. Créer un nouveau projet Supabase (même région), noter sa chaîne Session pooler.
|
||||
2. Restaurer d'abord les comptes, puis l'app :
|
||||
```bash
|
||||
pg_restore --no-owner --no-privileges --data-only --schema=auth --table=users --table=identities -d "$DB" /tmp/azuucine.dump
|
||||
pg_restore --no-owner --no-privileges --schema=public -d "$DB" /tmp/azuucine.dump
|
||||
pg_restore --no-owner --no-privileges --data-only --schema=storage --table=objects -d "$DB" /tmp/azuucine.dump
|
||||
```
|
||||
(Les fichiers du bucket `profile-media` ne sont **pas** dans le dump : seules leurs références le sont.
|
||||
Les photos de profil devront être re-téléversées, ou copiées depuis l'ancien projet s'il est accessible.)
|
||||
3. Rejouer les réglages hors base : bucket `profile-media` (public), edge functions `tmdb` et
|
||||
`delete-account` + leurs secrets (clé TMDB), fournisseurs d'auth (Google), URL du site.
|
||||
4. Mettre à jour `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` dans Gitea et redéployer.
|
||||
5. Remettre Romain admin : `insert into public.admins (user_id) values ('<uuid>') on conflict do nothing;`
|
||||
|
||||
## 3. Nettoyer
|
||||
|
||||
```bash
|
||||
shred -u /tmp/azuucine.dump 2>/dev/null || rm -f /tmp/azuucine.dump
|
||||
dropdb azuu_restore 2>/dev/null || true
|
||||
unset PGPASSWORD
|
||||
```
|
||||
@@ -1,9 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Revient à la version précédente (ou à celle donnée en argument). À lancer en root sur le VPS :
|
||||
# /srv/azuucine/rollback.sh -> version juste avant la courante
|
||||
# /srv/azuucine/rollback.sh <nom> -> une version précise (voir ls /srv/azuucine/releases)
|
||||
# /srv/bobinoo/rollback.sh -> version juste avant la courante
|
||||
# /srv/bobinoo/rollback.sh <nom> -> une version précise (voir ls /srv/bobinoo/releases)
|
||||
set -euo pipefail
|
||||
ROOT=${AZUUCINE_ROOT:-/srv/azuucine}
|
||||
ROOT=${BOBINOO_ROOT:-${AZUUCINE_ROOT:-/srv/bobinoo}}
|
||||
CUR=$(basename "$(readlink "$ROOT/current")")
|
||||
if [ -n "${1:-}" ]; then TARGET=$1
|
||||
else TARGET=$(ls -1 "$ROOT/releases" | sort -r | grep -A1 -x "$CUR" | tail -n1)
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# À lancer UNE FOIS, en root, dans un conteneur azuucine-web neuf (Debian 12) :
|
||||
# lxc-attach -n azuucine-web -- bash < deploy/web/bootstrap.sh
|
||||
# Prérequis : /srv/azuucine monté dans le conteneur (lxc.mount.entry ... srv/azuucine none bind,ro).
|
||||
# À lancer UNE FOIS, en root, dans un conteneur bobinoo neuf (Debian 12) :
|
||||
# lxc-attach -n bobinoo -- bash < deploy/web/bootstrap.sh
|
||||
# Prérequis : /srv/bobinoo monté dans le conteneur (lxc.mount.entry ... srv/bobinoo none bind,ro).
|
||||
# Ensuite, toute la configuration du site arrive avec les déploiements (deploy/nginx/site.conf).
|
||||
set -euo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq && apt-get install -y -qq nginx >/dev/null
|
||||
rm -f /etc/nginx/sites-enabled/default
|
||||
echo 'include /srv/azuucine/current/nginx/site.conf;' > /etc/nginx/conf.d/azuucine.conf
|
||||
cat > /etc/systemd/system/azuucine-reload.path <<UNIT
|
||||
echo 'include /srv/bobinoo/current/nginx/site.conf;' > /etc/nginx/conf.d/bobinoo.conf
|
||||
cat > /etc/systemd/system/bobinoo-reload.path <<UNIT
|
||||
[Unit]
|
||||
Description=Recharge nginx apres un deploiement AzuuCine
|
||||
Description=Recharge nginx apres un deploiement Bobinoo
|
||||
[Path]
|
||||
PathModified=/srv/azuucine/.deployed
|
||||
PathModified=/srv/bobinoo/.deployed
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
cat > /etc/systemd/system/azuucine-reload.service <<UNIT
|
||||
cat > /etc/systemd/system/bobinoo-reload.service <<UNIT
|
||||
[Unit]
|
||||
Description=Reload nginx (deploiement AzuuCine)
|
||||
Description=Reload nginx (deploiement Bobinoo)
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/sh -c "nginx -t && systemctl reload nginx"
|
||||
UNIT
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now azuucine-reload.path >/dev/null 2>&1
|
||||
systemctl enable --now bobinoo-reload.path >/dev/null 2>&1
|
||||
echo "ok : le premier déploiement (push sur main) activera le site"
|
||||
@@ -0,0 +1,79 @@
|
||||
# Console d'administration Bobinoo
|
||||
|
||||
**https://admin.bobinoo.org** : un site à part, jamais dans l'app publique, accessible de partout.
|
||||
|
||||
## Les verrous
|
||||
|
||||
1. **Compte + code** : mot de passe puis code de double authentification, obligatoire (jeton « aal2 »).
|
||||
Un compte sans double authentification ne peut pas entrer.
|
||||
2. **Liste des admins** : la table `admin.admins`, dans le schéma `admin`. Ce schéma n'est pas exposé par l'API Supabase :
|
||||
ni l'app ni un membre ne peuvent le lire. Seule la fonction Edge y accède, par connexion directe à la base.
|
||||
3. **Secret du VPS** : nginx ajoute l'en-tête `X-Admin-Gate` en relayant les appels vers la fonction Edge `admin`
|
||||
(fichier `/etc/nginx/bobinoo-admin-gate.conf`, hors dépôt). Le même secret est dans Supabase (`ADMIN_GATE_SECRET`).
|
||||
Sans lui, la fonction répond 404 : elle ne répond qu'à travers admin.bobinoo.org.
|
||||
4. **Nombre d'appels limité** : 60 par minute pour la console (nginx), 120 par minute et par compte (fonction).
|
||||
Supabase limite aussi les essais de mot de passe.
|
||||
5. **Alerte et journal** :
|
||||
- un e-mail part vers contact@bobinoo.org à chaque connexion, chaque refus et chaque action, si `SMTP_PASSWORD` est configuré ;
|
||||
- la table `admin.journal` garde tout, avec le motif et une copie du texte retiré ;
|
||||
- on peut y ajouter, jamais modifier ni effacer.
|
||||
|
||||
Session : en mémoire seulement. Recharger la page ou fermer l'onglet déconnecte. Le jeton expire au bout d'une heure, et la
|
||||
console se déconnecte après 15 minutes sans activité. La page n'est ni mise en cache, ni indexée, ni intégrable dans une autre page.
|
||||
|
||||
## Ce que fait la console
|
||||
|
||||
| Onglet | Contenu |
|
||||
|---|---|
|
||||
| Tableau de bord | Chiffres (membres, actifs, fiches, avis…), dernières inscriptions |
|
||||
| Membres | Recherche par pseudo, nom ou e-mail ; suspendre / réactiver ; nommer / retirer un admin (motif obligatoire) |
|
||||
| Avis | Recherche par pseudo ou titre ; retirer un avis (le texte va au journal) |
|
||||
| Commentaires | Derniers commentaires ; supprimer |
|
||||
| Journal | Connexions et actions |
|
||||
|
||||
## Fichiers
|
||||
|
||||
- `admin/` : le site (React). Construit par `npm run build:admin` dans `dist-admin/`.
|
||||
- `vite.admin.config.ts` : sa configuration de build.
|
||||
- `supabase/functions/admin/` : la fonction Edge, seule porte vers le schéma `admin`.
|
||||
- `supabase/migrations/20261130150000_admin_console.sql` : le schéma `admin` (tables, fonctions, journal verrouillé).
|
||||
- `deploy/nginx/admin.conf` : le serveur de la console (admin.bobinoo.org, CSP stricte, limite d'appels, relais avec secret).
|
||||
Il est inclus par `site.conf`.
|
||||
- `deploy/release.sh` : copie `dist-admin/` dans chaque release (`/srv/bobinoo/current/admin`).
|
||||
|
||||
## Installation (une fois)
|
||||
|
||||
1. **Double authentification** sur ton compte : dans l'app, Réglages → Mon compte.
|
||||
2. **DNS** (OVH, zone bobinoo.org) : enregistrement A `admin` → même adresse IP que `bobinoo.org` (193.168.145.214).
|
||||
3. **Proxy en façade du VPS** : ajouter `admin.bobinoo.org` comme pour `bobinoo.org` (même destination, en-tête Host transmis)
|
||||
et lui obtenir un certificat HTTPS.
|
||||
4. **Secret**, dans le conteneur web (`bobinoo`) :
|
||||
```bash
|
||||
S=$(openssl rand -hex 32)
|
||||
printf 'proxy_set_header X-Admin-Gate "%s";\n' "$S" > /etc/nginx/bobinoo-admin-gate.conf
|
||||
chmod 600 /etc/nginx/bobinoo-admin-gate.conf
|
||||
nginx -t && systemctl reload nginx
|
||||
echo "$S" # à copier UNE fois dans Supabase, puis effacer de l'écran
|
||||
```
|
||||
Dans Supabase → Edge Functions → Secrets : `ADMIN_GATE_SECRET` = ce secret.
|
||||
5. **Alertes par e-mail** (fortement conseillé) : secret Supabase `SMTP_PASSWORD` = mot de passe de contact@bobinoo.org.
|
||||
|
||||
Vérification : `curl -s -X POST https://admin.bobinoo.org/api/admin`
|
||||
- `{"error":"session"}` : tout est relié.
|
||||
- `Not found` : le secret est absent ou différent entre nginx et Supabase.
|
||||
- `502` : nginx n'arrive pas à joindre Supabase (DNS du conteneur).
|
||||
|
||||
## Gérer
|
||||
|
||||
- **Nommer ou retirer un admin** : console → Membres → « Nommer admin » / « Retirer admin ».
|
||||
- Le membre doit avoir activé la double authentification dans l'app.
|
||||
- Impossible sur son propre compte : il reste toujours au moins un admin.
|
||||
- L'action est inscrite au journal et déclenche une alerte e-mail.
|
||||
- **Secours, si plus aucun admin ne peut entrer**, dans Supabase → SQL Editor :
|
||||
`insert into admin.admins (user_id) select id from public.profiles where username = 'pseudo';`
|
||||
- **Changer le secret** : refaire l'étape 3 (nginx + Supabase).
|
||||
- **Téléphone perdu** :
|
||||
1. Change ton mot de passe.
|
||||
2. Réinitialise la double authentification depuis un autre appareil.
|
||||
3. Regarde le journal.
|
||||
- **Tout couper d'un coup** : supprimer le secret `ADMIN_GATE_SECRET` dans Supabase. La fonction répond alors 404 à tout le monde.
|
||||
@@ -0,0 +1,87 @@
|
||||
# Base de données Bobinoo (Supabase) — plan
|
||||
|
||||
Projet Supabase `qfgnxonqwldcfdjqhhjz`. Chaque table et chaque fonction porte une description en français,
|
||||
visible dans le tableau de bord (Table Editor, Database → Functions). Ce document en donne la carte.
|
||||
|
||||
Taille au 29 nov. 2026 : 14 Mo au total, dont 1,6 Mo pour les tables de l'app ; le reste, ce sont les tables
|
||||
système de Postgres et de Supabase. Les fiches (`items`) pèsent ~0,5 Mo pour 284 titres.
|
||||
|
||||
## Comment l'app y accède
|
||||
|
||||
- **Données perso** (`items`, `lists`, `settings`) : l'app les lit et les écrit directement, via la synchro
|
||||
(`src/lib/cloud/sync.ts`). La règle RLS limite chaque ligne à son propriétaire.
|
||||
- **Tout le reste** (social, listes partagées) passe par des **fonctions** (RPC). Les tables concernées n'ont
|
||||
aucune règle RLS : personne ne peut les lire ni les écrire en direct, seules les fonctions le peuvent.
|
||||
Les 8 alertes « RLS Enabled No Policy » du tableau de bord sont donc voulues.
|
||||
- **Double authentification** : la règle restrictive « mfa required » (via `azuu_mfa_ok()`) sur
|
||||
`items`, `lists`, `settings`, `follows`, `profiles` et `activity` bloque un compte protégé tant que le code n'est
|
||||
pas validé. Les fonctions font la même vérification.
|
||||
|
||||
## Tables
|
||||
|
||||
### Bibliothèque (synchronisée entre appareils)
|
||||
| Table | Contenu |
|
||||
|---|---|
|
||||
| `items` | Une fiche par titre et par compte. `data` = la fiche (JSON), `deleted` = supprimée (contenu vidé), `server_updated_at` = curseur de la synchro |
|
||||
| `lists` | Listes perso (privées) |
|
||||
| `settings` | Réglages de l'app (une ligne par compte) |
|
||||
|
||||
Triggers sur `items` / `lists` / `settings` :
|
||||
- `*_before_write` : refuse une version plus ancienne, pose la date serveur, ignore une ligne identique.
|
||||
- `*_atombstone` : une ligne supprimée est vidée.
|
||||
- `*_quota_stmt` : au plus 20 000 fiches et 300 listes par compte.
|
||||
- Sur `items` seulement :
|
||||
- `items_activity` : alimente le fil ;
|
||||
- `items_notify` : notifie les abonnés ;
|
||||
- `items_review_cleanup` : avis effacé → réactions et commentaires supprimés.
|
||||
|
||||
### Social
|
||||
| Table | Contenu |
|
||||
|---|---|
|
||||
| `profiles` | Profil public (pseudo, photo, bannière, bio, privé, suspendu). Créé à l'inscription |
|
||||
| `follows` | Abonnements (`pending` = demande à un compte privé, `accepted`) |
|
||||
| `blocks` | Blocages |
|
||||
| `activity` | Fil d'activité (fini, revu, noté) |
|
||||
| `notifications` | Notifications dans l'app (200 max par personne) |
|
||||
| `review_reactions`, `review_comments` | Réactions et commentaires sur un avis (l'avis = `author_id` + `item_id`) |
|
||||
| `shared_lists`, `shared_list_members`, `shared_list_items` | Listes partagées entre amis |
|
||||
|
||||
### Modération
|
||||
- **Console d'administration séparée** : voir `docs/admin.md`. Elle utilise le schéma `admin` (`admin.admins`, `admin.journal`),
|
||||
qui n'est pas exposé par l'API Supabase.
|
||||
- **Signalements et bugs** : ils arrivent par e-mail à contact@bobinoo.org. Dans l'app, « Signaler » et « Signaler un bug » ouvrent un e-mail pré-rempli.
|
||||
- **Suspendre un compte** : depuis la console (Membres), ou à la main dans Supabase (Table Editor → `profiles` → `suspended`). Le compte devient alors invisible pour les autres.
|
||||
- **Retirer un avis** : depuis la console (Avis).
|
||||
|
||||
### Réserve partagée
|
||||
| Table | Contenu |
|
||||
|---|---|
|
||||
| `title_ratings` | Notes Trakt de chaque titre, rafraîchies après 24 h, remplies par la fonction Edge `ratings` |
|
||||
|
||||
## Fonctions (65)
|
||||
|
||||
Les noms indiquent le rôle :
|
||||
- **Sans préfixe** (`get_feed`, `title_reviews`, `block_user`…) : appelées par l'app.
|
||||
- **`azuu_*`** : aides internes et triggers, jamais appelables par l'app.
|
||||
- **Règles** : `can_view`, `azuu_mfa_ok`, `azuu_me_active`.
|
||||
|
||||
La description de chacune est dans le tableau de bord (et dans les migrations `20261129200000_cleanup_and_comments.sql`, `20261130120000_remove_admin.sql`).
|
||||
|
||||
## Hors base
|
||||
|
||||
- **Stockage** : un seul bucket, `profile-media` (photos de profil et bannières, un dossier par compte).
|
||||
- **Fonctions Edge** (`supabase/functions/`) :
|
||||
- `tmdb` : proxy TMDB, la clé reste sur le serveur ;
|
||||
- `ratings` : notes Trakt ;
|
||||
- `delete-account` : suppression de compte.
|
||||
- **Extensions** : `pgcrypto`, `uuid-ossp` et `supabase_vault` sont installées d'office par Supabase. On ne s'en sert
|
||||
pas directement, mais on les laisse. `pg_stat_statements` sert à mesurer les requêtes lentes.
|
||||
|
||||
## Modifier la base
|
||||
|
||||
1. Écrire une migration **idempotente** dans `supabase/migrations/` (`create or replace`, `if not exists`, `drop … if exists`).
|
||||
2. Fonctions : `security definer` + `set search_path = ''` ; préfixer `public.` partout.
|
||||
3. Ajouter une description (`comment on …`) à toute nouvelle table ou fonction.
|
||||
4. Tester dans un bloc `do $$ … raise exception … $$` (tout est annulé à la fin) avant d'appliquer.
|
||||
5. Attention aux fonctions de trigger partagées entre tables : `azuu_before_write` sert à `items`, `lists` **et**
|
||||
`settings` (qui n'a pas de colonne `deleted`).
|
||||
@@ -0,0 +1,25 @@
|
||||
# E-mails du compte (Supabase Auth)
|
||||
|
||||
À coller dans Supabase → Authentication → Emails → Templates. Le lien `{{ .ConfirmationURL }}` est celui de Supabase : ne pas le modifier.
|
||||
|
||||
| Modèle Supabase | Objet | Fichier |
|
||||
| --- | --- | --- |
|
||||
| Confirm signup | Confirme ton adresse · Bobinoo | `confirmation.html` |
|
||||
| Reset password | Ton nouveau mot de passe · Bobinoo | `recovery.html` |
|
||||
| Change email address | Confirme ta nouvelle adresse · Bobinoo | `email-change.html` |
|
||||
|
||||
## Envoi depuis bobinoo.org (OVH, boîte Zimbra Starter)
|
||||
|
||||
SMTP personnalisé (Authentication → Emails → SMTP Settings) :
|
||||
- Hôte `ssl0.ovh.net`, port `465`
|
||||
- Utilisateur : `contact@bobinoo.org`, mot de passe : celui de la boîte (jamais dans le dépôt)
|
||||
- Expéditeur : `Bobinoo` · `contact@bobinoo.org`
|
||||
|
||||
DNS de bobinoo.org (zone OVH) : MX OVH (automatique), SPF `v=spf1 include:mx.ovh.com ~all`, DKIM activé dans l'espace client (Emails → DKIM),
|
||||
DMARC `_dmarc` TXT `v=DMARC1; p=none; rua=mailto:<adresse de la boîte>`.
|
||||
|
||||
## Lire la boîte
|
||||
|
||||
- **Navigateur** : https://mail.bobinoo.org, la messagerie Bobinoo (`docs/mail.md`).
|
||||
- **iPhone (app Mail)** : compte IMAP `imap.mail.ovh.net:993` (SSL), envoi `smtp.mail.ovh.net:465` (SSL), identifiant = l'adresse complète.
|
||||
- **Mot de passe changé** : le reporter aussi dans Supabase, dans Authentication → Emails → SMTP Settings et dans le secret Edge `SMTP_PASSWORD`.
|
||||
@@ -0,0 +1,33 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Bobinoo</title></head>
|
||||
<body style="margin:0;padding:0;background:#f4f3f1;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f3f1;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px;background:#fefdfb;border:1px solid #dbdbd8;border-radius:2px;font-family:Epilogue,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#0d0d0d;">
|
||||
<tr><td style="padding:28px 32px 0;">
|
||||
<div style="font-size:22px;font-weight:800;letter-spacing:-0.02em;">Bobinoo</div>
|
||||
<div style="height:3px;width:48px;background:#00746d;margin-top:10px;"></div>
|
||||
</td></tr>
|
||||
<tr><td style="padding:24px 32px 8px;">
|
||||
<h1 style="margin:0 0 12px;font-size:20px;line-height:1.3;font-weight:700;">Bienvenue sur Bobinoo !</h1>
|
||||
<p style="margin:0 0 24px;font-size:15px;line-height:1.6;color:#383838;">Il ne reste qu'une étape : confirme ton adresse e-mail pour activer ton compte.</p>
|
||||
<table role="presentation" cellpadding="0" cellspacing="0"><tr><td style="background:#00746d;border-radius:2px;">
|
||||
<a href="{{ .ConfirmationURL }}" style="display:inline-block;padding:13px 24px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;">Confirmer mon adresse</a>
|
||||
</td></tr></table>
|
||||
<p style="margin:20px 0 0;font-size:13px;line-height:1.6;color:#525252;">Tu n'as pas créé de compte ? Ignore simplement cet e-mail, rien ne sera activé.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:16px 32px 8px;"><div style="border-top:1px solid #dbdbd8;"></div></td></tr>
|
||||
<tr><td style="padding:8px 32px 8px;">
|
||||
<p style="margin:0 0 8px;font-size:14px;line-height:1.6;color:#383838;"><strong style="color:#0d0d0d;">Welcome to Bobinoo!</strong> Confirm your email address to activate your account: <a href="{{ .ConfirmationURL }}" style="color:#00746d;font-weight:700;">Confirm my email</a></p>
|
||||
<p style="margin:0;font-size:13px;line-height:1.6;color:#525252;">Didn't sign up? Just ignore this email.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px 28px;">
|
||||
<p style="margin:0;font-size:12px;line-height:1.6;color:#525252;">Le bouton ne marche pas ? Copie ce lien dans ton navigateur · Button not working? Copy this link:<br><a href="{{ .ConfirmationURL }}" style="color:#525252;word-break:break-all;">{{ .ConfirmationURL }}</a></p>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="margin:16px 0 0;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:12px;color:#525252;">Bobinoo · ton journal de films, séries, animes et dramas</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Bobinoo</title></head>
|
||||
<body style="margin:0;padding:0;background:#f4f3f1;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f3f1;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px;background:#fefdfb;border:1px solid #dbdbd8;border-radius:2px;font-family:Epilogue,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#0d0d0d;">
|
||||
<tr><td style="padding:28px 32px 0;">
|
||||
<div style="font-size:22px;font-weight:800;letter-spacing:-0.02em;">Bobinoo</div>
|
||||
<div style="height:3px;width:48px;background:#00746d;margin-top:10px;"></div>
|
||||
</td></tr>
|
||||
<tr><td style="padding:24px 32px 8px;">
|
||||
<h1 style="margin:0 0 12px;font-size:20px;line-height:1.3;font-weight:700;">Confirme ta nouvelle adresse</h1>
|
||||
<p style="margin:0 0 24px;font-size:15px;line-height:1.6;color:#383838;">Tu as demandé à changer l'adresse e-mail de ton compte Bobinoo pour {{ .NewEmail }}. Confirme ce changement :</p>
|
||||
<table role="presentation" cellpadding="0" cellspacing="0"><tr><td style="background:#00746d;border-radius:2px;">
|
||||
<a href="{{ .ConfirmationURL }}" style="display:inline-block;padding:13px 24px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;">Confirmer le changement</a>
|
||||
</td></tr></table>
|
||||
<p style="margin:20px 0 0;font-size:13px;line-height:1.6;color:#525252;">Ce n'est pas toi ? Ignore cet e-mail et change ton mot de passe par précaution.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:16px 32px 8px;"><div style="border-top:1px solid #dbdbd8;"></div></td></tr>
|
||||
<tr><td style="padding:8px 32px 8px;">
|
||||
<p style="margin:0 0 8px;font-size:14px;line-height:1.6;color:#383838;"><strong style="color:#0d0d0d;">Confirm your new email.</strong> You asked to change your Bobinoo email to {{ .NewEmail }}: <a href="{{ .ConfirmationURL }}" style="color:#00746d;font-weight:700;">Confirm the change</a></p>
|
||||
<p style="margin:0;font-size:13px;line-height:1.6;color:#525252;">Not you? Ignore this email and change your password to be safe.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px 28px;">
|
||||
<p style="margin:0;font-size:12px;line-height:1.6;color:#525252;">Le bouton ne marche pas ? Copie ce lien dans ton navigateur · Button not working? Copy this link:<br><a href="{{ .ConfirmationURL }}" style="color:#525252;word-break:break-all;">{{ .ConfirmationURL }}</a></p>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="margin:16px 0 0;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:12px;color:#525252;">Bobinoo · ton journal de films, séries, animes et dramas</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Bobinoo</title></head>
|
||||
<body style="margin:0;padding:0;background:#f4f3f1;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f3f1;padding:32px 16px;">
|
||||
<tr><td align="center">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px;background:#fefdfb;border:1px solid #dbdbd8;border-radius:2px;font-family:Epilogue,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#0d0d0d;">
|
||||
<tr><td style="padding:28px 32px 0;">
|
||||
<div style="font-size:22px;font-weight:800;letter-spacing:-0.02em;">Bobinoo</div>
|
||||
<div style="height:3px;width:48px;background:#00746d;margin-top:10px;"></div>
|
||||
</td></tr>
|
||||
<tr><td style="padding:24px 32px 8px;">
|
||||
<h1 style="margin:0 0 12px;font-size:20px;line-height:1.3;font-weight:700;">Nouveau mot de passe</h1>
|
||||
<p style="margin:0 0 24px;font-size:15px;line-height:1.6;color:#383838;">Tu as demandé à changer le mot de passe de ton compte Bobinoo. Ce lien est valable une heure.</p>
|
||||
<table role="presentation" cellpadding="0" cellspacing="0"><tr><td style="background:#00746d;border-radius:2px;">
|
||||
<a href="{{ .ConfirmationURL }}" style="display:inline-block;padding:13px 24px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;">Choisir un nouveau mot de passe</a>
|
||||
</td></tr></table>
|
||||
<p style="margin:20px 0 0;font-size:13px;line-height:1.6;color:#525252;">Ce n'est pas toi ? Ignore cet e-mail : ton mot de passe actuel reste inchangé.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:16px 32px 8px;"><div style="border-top:1px solid #dbdbd8;"></div></td></tr>
|
||||
<tr><td style="padding:8px 32px 8px;">
|
||||
<p style="margin:0 0 8px;font-size:14px;line-height:1.6;color:#383838;"><strong style="color:#0d0d0d;">Reset your password.</strong> You asked to change your Bobinoo password. This link is valid for one hour: <a href="{{ .ConfirmationURL }}" style="color:#00746d;font-weight:700;">Choose a new password</a></p>
|
||||
<p style="margin:0;font-size:13px;line-height:1.6;color:#525252;">Not you? Ignore this email, your password stays the same.</p>
|
||||
</td></tr>
|
||||
<tr><td style="padding:20px 32px 28px;">
|
||||
<p style="margin:0;font-size:12px;line-height:1.6;color:#525252;">Le bouton ne marche pas ? Copie ce lien dans ton navigateur · Button not working? Copy this link:<br><a href="{{ .ConfirmationURL }}" style="color:#525252;word-break:break-all;">{{ .ConfirmationURL }}</a></p>
|
||||
</td></tr>
|
||||
</table>
|
||||
<p style="margin:16px 0 0;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:12px;color:#525252;">Bobinoo · ton journal de films, séries, animes et dramas</p>
|
||||
</td></tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,55 @@
|
||||
# Messagerie Bobinoo
|
||||
|
||||
**https://mail.bobinoo.org** : l'interface de la boîte contact@bobinoo.org, aux couleurs de Bobinoo.
|
||||
La boîte reste chez OVH (Zimbra Starter) ; seule l'interface est la nôtre.
|
||||
|
||||
## Fonctionnement
|
||||
|
||||
- **Interface** : `mail/` (React), construite par `npm run build:mail` dans `dist-mail/`, servie par nginx
|
||||
(`deploy/nginx/mail.conf`).
|
||||
- **Serveur** : fonction Edge `mail` (`supabase/functions/mail/`).
|
||||
- Lecture en IMAP (`ssl0.ovh.net:993`, bibliothèque imapflow), envoi en SMTP (`ssl0.ovh.net:465`, nodemailer).
|
||||
- Chaque envoi est copié dans « Envoyés ».
|
||||
- Une réponse marque le message d'origine comme « répondu ».
|
||||
- **Mot de passe de la boîte** : secret Supabase `MAIL_PASSWORD` (sinon `SMTP_PASSWORD`). Il ne quitte jamais le serveur.
|
||||
|
||||
## Sécurité
|
||||
|
||||
Mêmes verrous que la console (`docs/admin.md`) :
|
||||
- compte Bobinoo **admin** + code de double authentification ;
|
||||
- secret `X-Admin-Gate` ajouté par nginx (même fichier `/etc/nginx/bobinoo-admin-gate.conf`) ;
|
||||
- nombre d'appels limité ;
|
||||
- connexions, envois et suppressions inscrits dans `admin.journal`.
|
||||
|
||||
Affichage des e-mails :
|
||||
- le HTML est nettoyé (DOMPurify : ni script, ni formulaire, ni cadre) puis affiché dans un cadre isolé, sans script ;
|
||||
- les **images distantes sont bloquées** par défaut, car elles servent à savoir qu'un message a été ouvert ;
|
||||
le bouton « Afficher les images » les charge ;
|
||||
- les liens s'ouvrent dans un nouvel onglet.
|
||||
|
||||
Session en mémoire seulement : 1 h maximum, déconnexion après 30 min sans activité.
|
||||
|
||||
## Ce qu'on peut faire
|
||||
|
||||
| Action | Détail |
|
||||
|---|---|
|
||||
| Dossiers | Réception, Envoyés, Brouillons, Indésirables, Corbeille, avec le nombre de non-lus |
|
||||
| Lire | Pièces jointes à télécharger (15 Mo maximum par fichier) |
|
||||
| Écrire, répondre, transférer | En texte simple ; les pièces jointes ne sont pas transférées |
|
||||
| Classer | Non lu, Indésirable, Corbeille, remettre en réception |
|
||||
| Supprimer définitivement | Depuis la Corbeille ou les Indésirables |
|
||||
| Rechercher | Expéditeur, destinataire, objet, texte |
|
||||
|
||||
La boîte vérifie les nouveaux messages chaque minute quand la page est ouverte.
|
||||
|
||||
## Installation (une fois)
|
||||
|
||||
1. **Secret Supabase** (Edge Functions → Secrets) : `MAIL_PASSWORD` = mot de passe de contact@bobinoo.org.
|
||||
Si `SMTP_PASSWORD` existe déjà avec ce mot de passe, il est utilisé.
|
||||
2. **DNS** : enregistrement A `mail` → 193.168.145.214.
|
||||
3. **Proxy en façade du VPS** : `mail.bobinoo.org` comme `admin.bobinoo.org` (en-tête Host transmis), avec certificat HTTPS.
|
||||
Le secret nginx de la console sert aussi ici.
|
||||
|
||||
**Mot de passe de la boîte changé** : le reporter dans Supabase, à deux endroits :
|
||||
- les secrets `MAIL_PASSWORD` / `SMTP_PASSWORD` ;
|
||||
- Authentication → Emails → SMTP Settings.
|
||||
@@ -0,0 +1,109 @@
|
||||
# Bobinoo — fiche Google Play (préparée le 28 nov. 2026)
|
||||
|
||||
Textes prêts à coller dans la Play Console, et réponses aux questionnaires.
|
||||
Adresses utiles : site https://bobinoo.org · confidentialité https://bobinoo.org/privacy.html ·
|
||||
conditions https://bobinoo.org/terms.html · suppression de compte https://bobinoo.org/supprimer-compte.html
|
||||
|
||||
---
|
||||
|
||||
## Fiche — français
|
||||
|
||||
**Nom de l'application** (30 caractères max)
|
||||
Bobinoo – Films, séries, anime
|
||||
|
||||
**Description courte** (80 caractères max)
|
||||
Ton journal de films, séries, animes et dramas : note, suis, partage.
|
||||
|
||||
**Description complète**
|
||||
Bobinoo, c'est ton journal de visionnage : tous les films, séries, animes, K-dramas et C-dramas que tu regardes, au même endroit.
|
||||
|
||||
• Coche tes épisodes en un geste et reprends exactement où tu t'étais arrêté.
|
||||
• Note en étoiles (avec demi-étoiles), saison par saison si tu veux, et écris tes avis — avec un mode spoiler.
|
||||
• Ta liste « À voir », tes listes perso et des listes partagées avec tes amis.
|
||||
• Un calendrier des sorties : nouveaux épisodes de tes séries, films au cinéma, animes de la saison.
|
||||
• Les dernières sorties sur l'accueil, et une roulette pour les soirs sans idée.
|
||||
• Tes stats : temps passé devant l'écran, épisodes vus, genres préférés, mois par mois.
|
||||
• Ton profil, ton Top 5 par catégorie, et le fil de tes amis : leurs notes et leurs avis, avec réactions et commentaires.
|
||||
• Où regarder chaque titre (plateformes de streaming).
|
||||
• Import depuis Letterboxd, TV Time, MyAnimeList et AniList, et export de ta bibliothèque à tout moment.
|
||||
• Clair ou sombre, 18 langues, fonctionne aussi hors connexion.
|
||||
|
||||
Gratuit, sans publicité, sans traceur. Tes données t'appartiennent : tu peux les exporter ou supprimer ton compte quand tu veux.
|
||||
|
||||
Les informations des œuvres proviennent de TMDB et d'AniList. Ce produit utilise l'API TMDB mais n'est ni approuvé ni certifié par TMDB.
|
||||
|
||||
---
|
||||
|
||||
## Listing — English
|
||||
|
||||
**App name** (30 chars max)
|
||||
Bobinoo: Movies, Shows, Anime
|
||||
|
||||
**Short description** (80 chars max)
|
||||
Your movie, TV, anime & drama diary: rate, track and share with friends.
|
||||
|
||||
**Full description**
|
||||
Bobinoo is your watch diary: every movie, TV show, anime, K-drama and C-drama you watch, in one place.
|
||||
|
||||
• Tick off episodes in one tap and pick up exactly where you left off.
|
||||
• Rate with stars (half-stars too), season by season if you like, and write reviews — with a spoiler mode.
|
||||
• Your watchlist, your own lists, and lists shared with friends.
|
||||
• A release calendar: new episodes of your shows, movies in theaters, this season's anime.
|
||||
• Latest releases on the home screen, and a roulette for nights with no idea.
|
||||
• Your stats: screen time, episodes watched, favourite genres, month by month.
|
||||
• Your profile, your Top 5 per category, and your friends' feed: their ratings and reviews, with reactions and comments.
|
||||
• Where to watch each title (streaming services).
|
||||
• Import from Letterboxd, TV Time, MyAnimeList and AniList, and export your library anytime.
|
||||
• Light or dark theme, 18 languages, works offline too.
|
||||
|
||||
Free, no ads, no trackers. Your data is yours: export it or delete your account whenever you want.
|
||||
|
||||
Title data comes from TMDB and AniList. This product uses the TMDB API but is not endorsed or certified by TMDB.
|
||||
|
||||
---
|
||||
|
||||
## Catégorie et coordonnées
|
||||
- Catégorie : **Divertissement** (Entertainment). Tags possibles : films, séries, anime.
|
||||
- Adresse e-mail de contact : **contact@bobinoo.org** (boîte OVH Zimbra Starter).
|
||||
- Site web : https://bobinoo.org
|
||||
|
||||
## Sécurité des données (Data safety)
|
||||
- **L'application collecte-t-elle des données ?** Oui.
|
||||
- **Données chiffrées en transit ?** Oui (HTTPS partout).
|
||||
- **Les utilisateurs peuvent-ils demander la suppression ?** Oui — dans l'app (Réglages → Zone sensible → Supprimer mon compte) et sur https://bobinoo.org/supprimer-compte.html
|
||||
- **Partage avec des tiers :** Non. (Supabase héberge les données pour le compte de l'éditeur : c'est un sous-traitant, pas un partage. TMDB et AniList ne reçoivent que les recherches et le chargement des images, jamais les données du compte.)
|
||||
- **Publicité / traceurs :** aucun.
|
||||
|
||||
| Catégorie Play | Donnée | Collectée | Obligatoire | Finalité |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Informations personnelles | Adresse e-mail | Oui | Oui (avec un compte) | Gestion du compte |
|
||||
| Informations personnelles | Nom (affiché, ou reçu de Google) | Oui | Non | Fonctionnalités de l'app, gestion du compte |
|
||||
| Photos et vidéos | Photo de profil, bannière | Oui | Non | Fonctionnalités de l'app |
|
||||
| Activité dans l'app | Autre contenu généré par l'utilisateur (bibliothèque, notes, avis, commentaires, listes) | Oui | Non | Fonctionnalités de l'app |
|
||||
| Activité dans l'app | Interactions (abonnements, réactions) | Oui | Non | Fonctionnalités de l'app |
|
||||
| Infos et performances de l'app | Journaux de plantage (message d'erreur, page, version, navigateur) | Oui | Non | Analyses / diagnostic |
|
||||
|
||||
Rien d'autre : pas de localisation, pas de contacts, pas d'identifiant publicitaire, pas de données financières ni de santé.
|
||||
|
||||
## Classification du contenu (questionnaire IARC)
|
||||
- Catégorie : « Toutes les autres applications » (pas un jeu).
|
||||
- Violence, sexe, langage, drogues, jeux d'argent : **non** (l'app affiche des affiches et résumés de films, sans contenu explicite propre).
|
||||
- **Les utilisateurs peuvent-ils interagir ou partager du contenu ?** **Oui** (avis, commentaires, profils publics). L'app propose le signalement, le blocage et une modération.
|
||||
- Partage de la localisation : non. Achats : non.
|
||||
|
||||
## Public cible
|
||||
- Tranches d'âge : **13-15 ans, 16-17 ans et 18 ans et plus** (âge minimum 13 ans dans les conditions, accord d'un parent avant 15 ans).
|
||||
- Ne pas cocher de tranche sous 13 ans : c'est ce qui soumettrait l'app aux règles « Familles » de Google. L'app ne s'adresse pas aux enfants.
|
||||
|
||||
## Accès à l'application (pour l'équipe de vérification Google)
|
||||
- Le mode « Explorer sans compte » permet de voir l'app sans se connecter.
|
||||
- La partie sociale demande un compte : fournir à Google un **compte de test** (e-mail + mot de passe) dédié, sans double authentification.
|
||||
|
||||
## Visuels (prêts dans `docs/store/`)
|
||||
- Icône 512 × 512 : `public/icons/icon-512.png`.
|
||||
- Bannière 1024 × 500 : `banniere-fr.png`, `banniere-en.png`.
|
||||
- Captures 1080 × 1920 : `fr-1…7-*.png` pour la fiche française, `en-1…7-*.png` pour l'anglaise (compte de démo, supprimé depuis).
|
||||
|
||||
## Avant publication
|
||||
- Fichier `/.well-known/assetlinks.json` avec l'empreinte SHA-256 de la clé de signature de l'app Android (pour qu'elle s'ouvre sans barre d'adresse).
|
||||
- Compte développeur personnel récent : test fermé avec au moins 12 testeurs pendant 14 jours avant la mise en production.
|
||||
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 539 KiB |
|
After Width: | Height: | Size: 740 KiB |
|
After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 368 KiB |
|
After Width: | Height: | Size: 520 KiB |
|
After Width: | Height: | Size: 538 KiB |
|
After Width: | Height: | Size: 735 KiB |
|
After Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 143 KiB |
|
After Width: | Height: | Size: 155 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 528 KiB |
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#14120f" />
|
||||
<meta name="theme-color" content="#090909" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<!-- Aucune info sur l'app n'est transmise aux sites d'images / API -->
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="theme-color" content="#090909" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-title" content="Bobinoo Mail" />
|
||||
<title>Bobinoo Mail</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,375 @@
|
||||
import { Inbox, Loader2, LogOut, Paperclip, PenSquare, RefreshCw, Search, Send, ShieldAlert, Trash2, FileText } from 'lucide-react'
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { AuthError, expiresAt, signIn, signOut, verifyCode } from '../../admin/src/auth'
|
||||
import { ApiError, call, FOLDER_LABEL, who, type Folder, type FolderId, type Message, type Summary } from './api'
|
||||
import Compose, { type Draft } from './Compose'
|
||||
import { fullDate, listDate } from './format'
|
||||
import Reader from './Reader'
|
||||
|
||||
/** Déconnexion automatique après 30 minutes sans activité. */
|
||||
const IDLE_MS = 30 * 60_000
|
||||
|
||||
const FOLDER_ICON: Record<FolderId, ReactNode> = {
|
||||
inbox: <Inbox size={17} />,
|
||||
sent: <Send size={17} />,
|
||||
drafts: <FileText size={17} />,
|
||||
junk: <ShieldAlert size={17} />,
|
||||
trash: <Trash2 size={17} />,
|
||||
}
|
||||
|
||||
function Logo() {
|
||||
return (
|
||||
<span className="text-lg font-bold tracking-tight">
|
||||
Bobin<span className="text-accent">oo</span> <span className="font-medium text-ink-2">Mail</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
// Jeton en mémoire seulement : recharger la page déconnecte
|
||||
const [session, setSession] = useState<{ token: string; mailbox: string }>()
|
||||
const [notice, setNotice] = useState<string>()
|
||||
|
||||
const logout = useCallback((why?: string) => {
|
||||
setSession((s) => {
|
||||
if (s) void signOut(s.token)
|
||||
return undefined
|
||||
})
|
||||
setNotice(why)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!session) return
|
||||
const end = window.setTimeout(() => logout('Session terminée (1 h) : reconnecte-toi.'), Math.max(0, expiresAt(session.token) - Date.now() - 30_000))
|
||||
let idle = window.setTimeout(() => logout('Déconnecté après 30 minutes sans activité.'), IDLE_MS)
|
||||
const touch = () => {
|
||||
window.clearTimeout(idle)
|
||||
idle = window.setTimeout(() => logout('Déconnecté après 30 minutes sans activité.'), IDLE_MS)
|
||||
}
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.addEventListener(ev, touch)
|
||||
return () => {
|
||||
window.clearTimeout(end)
|
||||
window.clearTimeout(idle)
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.removeEventListener(ev, touch)
|
||||
}
|
||||
}, [session, logout])
|
||||
|
||||
if (!session) return <Login notice={notice} onReady={(token, mailbox) => (setNotice(undefined), setSession({ token, mailbox }))} />
|
||||
return <Mailbox token={session.token} mailbox={session.mailbox} onLogout={logout} />
|
||||
}
|
||||
|
||||
function Login({ notice, onReady }: { notice?: string; onReady: (token: string, mailbox: string) => void }) {
|
||||
const [step, setStep] = useState<{ token: string; factorId: string }>()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const codeRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
if (!step) {
|
||||
const r = await signIn(email, password)
|
||||
setPassword('')
|
||||
if (!r.factorId) {
|
||||
await signOut(r.token)
|
||||
throw new AuthError("Ce compte n'a pas la double authentification. Active-la d'abord dans l'app Bobinoo (Réglages → Mon compte).")
|
||||
}
|
||||
setStep({ token: r.token, factorId: r.factorId })
|
||||
setTimeout(() => codeRef.current?.focus(), 0)
|
||||
} else {
|
||||
const token = await verifyCode(step.token, step.factorId, code.replace(/\s/g, ''))
|
||||
const r = await call<{ mailbox: string }>(token, 'hello')
|
||||
onReady(token, r.mailbox)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof AuthError || err instanceof ApiError ? err.message : 'Erreur inattendue.')
|
||||
if (step) setCode('')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh max-w-sm flex-col justify-center px-5 py-10">
|
||||
<Logo />
|
||||
<h1 className="mt-3 text-2xl font-bold">contact@bobinoo.org</h1>
|
||||
<p className="mt-2 text-sm text-ink-3">Connecte-toi avec ton compte Bobinoo (administrateur), puis ton code de double authentification.</p>
|
||||
{notice && <p className="mt-5 border-s-2 border-accent ps-3 text-sm text-ink-2">{notice}</p>}
|
||||
<form onSubmit={submit} className="mt-7 space-y-3">
|
||||
{!step ? (
|
||||
<>
|
||||
<input className="field" type="email" autoComplete="username" placeholder="E-mail du compte Bobinoo" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
<input className="field" type="password" autoComplete="current-password" placeholder="Mot de passe" value={password} onChange={(e) => setPassword(e.target.value)} required />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-ink-2">Code à 6 chiffres de ton application d'authentification :</p>
|
||||
<input
|
||||
ref={codeRef}
|
||||
className="field text-center text-2xl tracking-[0.4em]"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9 ]{6,7}"
|
||||
maxLength={7}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
<button className="btn btn-primary w-full" disabled={busy}>
|
||||
{busy ? '…' : step ? 'Ouvrir la boîte' : 'Continuer'}
|
||||
</button>
|
||||
{step && (
|
||||
<button type="button" className="btn w-full text-ink-3" onClick={() => (void signOut(step.token), setStep(undefined), setCode(''))}>
|
||||
Annuler
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
const quote = (text: string) =>
|
||||
text
|
||||
.slice(0, 20_000)
|
||||
.split('\n')
|
||||
.map((l) => `> ${l}`)
|
||||
.join('\n')
|
||||
|
||||
function Mailbox({ token, mailbox, onLogout }: { token: string; mailbox: string; onLogout: (why?: string) => void }) {
|
||||
const [folders, setFolders] = useState<Folder[]>([])
|
||||
const [folder, setFolder] = useState<FolderId>('inbox')
|
||||
const [list, setList] = useState<Summary[]>()
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(0)
|
||||
const [q, setQ] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [selected, setSelected] = useState<number>()
|
||||
const [draft, setDraft] = useState<Draft>()
|
||||
const [toast, setToast] = useState<string>()
|
||||
|
||||
const onAuthError = useCallback(
|
||||
(e: unknown) => {
|
||||
if (e instanceof ApiError && (e.status === 401 || (e.status === 403 && /double|interdit|réservé/i.test(e.message)))) onLogout(e.message)
|
||||
},
|
||||
[onLogout],
|
||||
)
|
||||
|
||||
const loadFolders = useCallback(() => {
|
||||
call<Folder[]>(token, 'folders').then(setFolders, onAuthError)
|
||||
}, [token, onAuthError])
|
||||
|
||||
const loadList = useCallback(
|
||||
async (p = 0, quiet = false) => {
|
||||
if (!quiet) setLoading(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
const r = await call<{ total: number; messages: Summary[] }>(token, 'list', { folder, page: p, q: query })
|
||||
setTotal(r.total)
|
||||
setPage(p)
|
||||
setList((prev) => (p ? [...(prev ?? []), ...r.messages] : r.messages))
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
},
|
||||
[token, folder, query, onAuthError],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setList(undefined)
|
||||
setSelected(undefined)
|
||||
void loadList(0)
|
||||
}, [loadList])
|
||||
useEffect(loadFolders, [loadFolders])
|
||||
|
||||
// Nouveaux messages : vérifiés chaque minute quand la page est affichée (première page, hors recherche)
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => {
|
||||
if (document.visibilityState !== 'visible' || query || page > 0) return
|
||||
loadFolders()
|
||||
void loadList(0, true)
|
||||
}, 60_000)
|
||||
return () => window.clearInterval(id)
|
||||
}, [loadFolders, loadList, query, page])
|
||||
|
||||
const unread = folders.find((f) => f.id === 'inbox')?.unseen ?? 0
|
||||
useEffect(() => {
|
||||
document.title = unread ? `(${unread}) Bobinoo Mail` : 'Bobinoo Mail'
|
||||
}, [unread])
|
||||
|
||||
const flash = (text: string) => {
|
||||
setToast(text)
|
||||
window.setTimeout(() => setToast(undefined), 2500)
|
||||
}
|
||||
|
||||
const reply = (m: Message) =>
|
||||
setDraft({
|
||||
to: (m.replyTo.length ? m.replyTo : [m.from]).map((a) => a.address).filter(Boolean).join(', '),
|
||||
cc: '',
|
||||
subject: /^re\s*:/i.test(m.subject) ? m.subject : `Re: ${m.subject}`,
|
||||
text: `\n\n\nLe ${fullDate(m.date)}, ${who(m.from)} a écrit :\n${quote(m.text)}`,
|
||||
inReplyTo: m.messageId ?? undefined,
|
||||
references: [...m.references, m.messageId ?? ''].filter(Boolean),
|
||||
answeredUid: m.uid,
|
||||
answeredFolder: folder,
|
||||
})
|
||||
|
||||
const forward = (m: Message) =>
|
||||
setDraft({
|
||||
to: '',
|
||||
cc: '',
|
||||
subject: /^(tr|fwd?)\s*:/i.test(m.subject) ? m.subject : `Tr: ${m.subject}`,
|
||||
text: `\n\n\n---------- Message transféré ----------\nDe : ${who(m.from)}${m.from.address ? ` <${m.from.address}>` : ''}\nDate : ${fullDate(m.date)}\nObjet : ${m.subject}\n\n${m.text.slice(0, 50_000)}${m.attachments.length ? '\n\n(Pièces jointes non transférées)' : ''}`,
|
||||
})
|
||||
|
||||
const search = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setQuery(q.trim())
|
||||
}
|
||||
|
||||
const listPane = (
|
||||
<section className={`min-w-0 ${selected ? 'hidden lg:block' : ''}`}>
|
||||
<form onSubmit={search} className="mb-3 flex gap-2">
|
||||
<input className="field py-2" placeholder={`Rechercher dans ${FOLDER_LABEL[folder].toLowerCase()}`} value={q} onChange={(e) => setQ(e.target.value.slice(0, 100))} enterKeyHint="search" />
|
||||
<button className="btn btn-ghost px-3" aria-label="Rechercher">
|
||||
<Search size={17} />
|
||||
</button>
|
||||
<button type="button" onClick={() => (loadFolders(), void loadList(0))} className="btn btn-ghost px-3" aria-label="Actualiser">
|
||||
{loading ? <Loader2 size={17} className="animate-spin" /> : <RefreshCw size={17} />}
|
||||
</button>
|
||||
</form>
|
||||
{query && (
|
||||
<p className="mb-2 text-xs text-ink-3">
|
||||
Résultats pour « {query} » ·{' '}
|
||||
<button onClick={() => (setQ(''), setQuery(''))} className="text-accent underline underline-offset-2">
|
||||
effacer
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{error && <p className="py-4 text-sm text-danger">{error}</p>}
|
||||
{!list && !error && <p className="py-4 text-sm text-ink-3">Chargement…</p>}
|
||||
{list && !list.length && <p className="py-4 text-sm text-ink-3">{query ? 'Aucun message trouvé.' : 'Aucun message.'}</p>}
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{list?.map((m) => {
|
||||
const person = folder === 'sent' || folder === 'drafts' ? `À : ${m.to.map(who).join(', ') || '—'}` : who(m.from)
|
||||
return (
|
||||
<li key={m.uid}>
|
||||
<button
|
||||
onClick={() => setSelected(m.uid)}
|
||||
className={`flex w-full gap-3 px-1 py-3 text-start transition-colors active:bg-surface-2 ${selected === m.uid ? 'bg-surface-2' : ''}`}
|
||||
>
|
||||
<span className={`mt-1.5 size-2 shrink-0 rounded-full ${m.seen ? 'bg-transparent' : 'bg-accent'}`} aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-baseline gap-2">
|
||||
<span className={`min-w-0 flex-1 truncate text-sm ${m.seen ? 'text-ink-2' : 'font-bold text-ink'}`}>{person}</span>
|
||||
<span className="shrink-0 text-xs text-ink-3">{listDate(m.date)}</span>
|
||||
</span>
|
||||
<span className={`mt-0.5 flex items-center gap-1.5 text-sm ${m.seen ? 'text-ink-3' : 'font-semibold text-ink'}`}>
|
||||
<span className="min-w-0 flex-1 truncate">{m.subject || '(sans objet)'}</span>
|
||||
{m.attachments && <Paperclip size={13} className="shrink-0 text-ink-3" />}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
{list && !query && list.length < total && (
|
||||
<button onClick={() => void loadList(page + 1)} className="btn btn-ghost mt-4 w-full" disabled={loading}>
|
||||
Messages plus anciens
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="mx-auto min-h-dvh max-w-7xl px-4 pb-16 sm:px-6">
|
||||
<header className="sticky top-0 z-20 -mx-4 border-b border-line bg-bg px-4 pt-[max(0.75rem,env(safe-area-inset-top))] sm:-mx-6 sm:px-6">
|
||||
<div className="flex items-center gap-3 pb-2">
|
||||
<Logo />
|
||||
<span className="ms-auto hidden truncate text-sm text-ink-3 sm:inline">{mailbox}</span>
|
||||
<button onClick={() => setDraft({ to: '', cc: '', subject: '', text: '' })} className="btn btn-primary ms-auto py-2 sm:ms-0">
|
||||
<PenSquare size={16} /> Écrire
|
||||
</button>
|
||||
<button onClick={() => onLogout('Déconnecté.')} className="grid size-9 place-items-center text-ink-2" aria-label="Se déconnecter">
|
||||
<LogOut size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<nav className={`-mx-1 flex gap-1 overflow-x-auto pb-2 lg:hidden ${selected ? 'hidden' : ''}`}>
|
||||
{folders.map((f) => (
|
||||
<FolderButton key={f.id} f={f} active={f.id === folder} onClick={() => setFolder(f.id)} />
|
||||
))}
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div className="pt-4 lg:grid lg:grid-cols-[12rem_minmax(0,26rem)_minmax(0,1fr)] lg:gap-6">
|
||||
<nav className="hidden flex-col gap-1 lg:flex">
|
||||
{folders.map((f) => (
|
||||
<FolderButton key={f.id} f={f} active={f.id === folder} onClick={() => setFolder(f.id)} />
|
||||
))}
|
||||
</nav>
|
||||
{listPane}
|
||||
{selected ? (
|
||||
<Reader
|
||||
key={`${folder}:${selected}`}
|
||||
token={token}
|
||||
folder={folder}
|
||||
uid={selected}
|
||||
onBack={() => setSelected(undefined)}
|
||||
onReply={reply}
|
||||
onForward={forward}
|
||||
onChanged={(removed) => {
|
||||
loadFolders()
|
||||
if (removed) {
|
||||
setList((l) => l?.filter((m) => m.uid !== selected))
|
||||
flash('Message déplacé')
|
||||
} else setList((l) => l?.map((m) => (m.uid === selected ? { ...m, seen: true } : m)))
|
||||
}}
|
||||
onAuthError={onAuthError}
|
||||
/>
|
||||
) : (
|
||||
<p className="hidden pt-10 text-center text-sm text-ink-3 lg:block">Choisis un message pour le lire.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{draft && (
|
||||
<Compose
|
||||
token={token}
|
||||
initial={draft}
|
||||
onClose={() => setDraft(undefined)}
|
||||
onSent={() => {
|
||||
setDraft(undefined)
|
||||
flash('Message envoyé')
|
||||
loadFolders()
|
||||
if (folder === 'sent') void loadList(0, true)
|
||||
}}
|
||||
onAuthError={onAuthError}
|
||||
/>
|
||||
)}
|
||||
{toast && <p className="fixed inset-x-0 bottom-[max(1.5rem,env(safe-area-inset-bottom))] z-50 mx-auto w-fit bg-ink px-4 py-2 text-sm font-medium text-bg">{toast}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderButton({ f, active, onClick }: { f: Folder; active: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button onClick={onClick} className={`flex shrink-0 items-center gap-2.5 rounded-md px-3 py-2 text-sm font-medium ${active ? 'bg-surface-2 text-ink' : 'text-ink-3'}`}>
|
||||
{FOLDER_ICON[f.id]}
|
||||
<span className="flex-1 text-start">{FOLDER_LABEL[f.id]}</span>
|
||||
{f.unseen > 0 && (f.id === 'inbox' || f.id === 'junk') && <span className="text-xs font-bold text-accent">{f.unseen}</span>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Loader2, Send, X } from 'lucide-react'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { ApiError, call, type FolderId } from './api'
|
||||
|
||||
export interface Draft {
|
||||
to: string
|
||||
cc: string
|
||||
subject: string
|
||||
text: string
|
||||
inReplyTo?: string
|
||||
references?: string[]
|
||||
/** Message auquel on répond : marqué « répondu » après l'envoi */
|
||||
answeredUid?: number
|
||||
answeredFolder?: FolderId
|
||||
}
|
||||
|
||||
/** Nouveau message, réponse ou transfert (texte simple, envoyé depuis contact@bobinoo.org). */
|
||||
export default function Compose({
|
||||
token,
|
||||
initial,
|
||||
onClose,
|
||||
onSent,
|
||||
onAuthError,
|
||||
}: {
|
||||
token: string
|
||||
initial: Draft
|
||||
onClose: () => void
|
||||
onSent: () => void
|
||||
onAuthError: (e: unknown) => void
|
||||
}) {
|
||||
const [d, setD] = useState(initial)
|
||||
const [showCc, setShowCc] = useState(!!initial.cc)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const set = (patch: Partial<Draft>) => setD((x) => ({ ...x, ...patch }))
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
if (!d.subject.trim() && !confirm('Envoyer sans objet ?')) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
await call(token, 'send', { ...d })
|
||||
onSent()
|
||||
} catch (err) {
|
||||
onAuthError(err)
|
||||
setError(err instanceof ApiError ? err.message : "L'envoi a échoué.")
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
const touched = d.text !== initial.text || d.to !== initial.to || d.subject !== initial.subject
|
||||
if (!touched || confirm('Abandonner ce message ?')) onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-stretch justify-center bg-scrim sm:items-center sm:p-6">
|
||||
<form onSubmit={submit} className="flex w-full max-w-2xl flex-col border-line-strong bg-surface sm:max-h-[90dvh] sm:border">
|
||||
<div className="flex items-center gap-2 border-b border-line px-4 pb-3 pt-[max(0.75rem,env(safe-area-inset-top))]">
|
||||
<button type="button" onClick={close} className="grid size-9 place-items-center text-ink-2" aria-label="Fermer">
|
||||
<X size={20} />
|
||||
</button>
|
||||
<span className="font-semibold">{initial.inReplyTo ? 'Réponse' : 'Nouveau message'}</span>
|
||||
<button className="btn btn-primary ms-auto py-2" disabled={busy}>
|
||||
{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />} Envoyer
|
||||
</button>
|
||||
</div>
|
||||
<div className="divide-y divide-line border-b border-line text-sm">
|
||||
<label className="flex items-center gap-2 px-4">
|
||||
<span className="w-10 shrink-0 text-ink-3">À</span>
|
||||
<input className="min-w-0 flex-1 bg-transparent py-3 outline-none" value={d.to} onChange={(e) => set({ to: e.target.value })} type="text" inputMode="email" autoComplete="off" required />
|
||||
{!showCc && (
|
||||
<button type="button" onClick={() => setShowCc(true)} className="text-xs text-ink-3">
|
||||
Cc
|
||||
</button>
|
||||
)}
|
||||
</label>
|
||||
{showCc && (
|
||||
<label className="flex items-center gap-2 px-4">
|
||||
<span className="w-10 shrink-0 text-ink-3">Cc</span>
|
||||
<input className="min-w-0 flex-1 bg-transparent py-3 outline-none" value={d.cc} onChange={(e) => set({ cc: e.target.value })} type="text" inputMode="email" autoComplete="off" />
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-center gap-2 px-4">
|
||||
<span className="w-10 shrink-0 text-ink-3">Objet</span>
|
||||
<input className="min-w-0 flex-1 bg-transparent py-3 outline-none" value={d.subject} onChange={(e) => set({ subject: e.target.value.slice(0, 300) })} />
|
||||
</label>
|
||||
</div>
|
||||
<textarea
|
||||
className="min-h-[50dvh] flex-1 resize-none bg-transparent px-4 py-3 text-[15px] leading-relaxed outline-none sm:min-h-80"
|
||||
value={d.text}
|
||||
onChange={(e) => set({ text: e.target.value })}
|
||||
autoFocus={!initial.inReplyTo}
|
||||
placeholder="Ton message…"
|
||||
/>
|
||||
{error && <p className="border-t border-line px-4 py-2 text-sm text-danger">{error}</p>}
|
||||
<p className="border-t border-line px-4 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] text-xs text-ink-3">
|
||||
Envoyé par Bobinoo <contact@bobinoo.org>, en texte simple. Plusieurs destinataires : sépare-les par une virgule.
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import DOMPurify from 'dompurify'
|
||||
import { Ban, ChevronLeft, CornerUpLeft, Forward, ImageOff, Inbox, MailOpen, Paperclip, Trash2 } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { ApiError, addrList, call, who, type FolderId, type Message } from './api'
|
||||
import { fullDate, sizeLabel } from './format'
|
||||
|
||||
const REMOTE = /^\s*(https?:)?\/\//i
|
||||
|
||||
/**
|
||||
* HTML d'un e-mail rendu sans danger : nettoyé par DOMPurify (ni script, ni formulaire, ni cadre), affiché dans un
|
||||
* cadre isolé (sandbox, sans scripts). Images distantes bloquées par défaut : elles permettent de savoir que le
|
||||
* message a été ouvert. Liens ouverts dans un nouvel onglet.
|
||||
*/
|
||||
function emailDocument(html: string, showImages: boolean): { doc: string; blocked: number } {
|
||||
const clean = DOMPurify.sanitize(html, {
|
||||
WHOLE_DOCUMENT: true,
|
||||
FORBID_TAGS: ['form', 'input', 'button', 'textarea', 'select', 'iframe', 'frame', 'object', 'embed', 'link', 'meta', 'base', 'audio', 'video'],
|
||||
FORBID_ATTR: ['srcset', 'ping', 'formaction'],
|
||||
})
|
||||
const d = new DOMParser().parseFromString(clean, 'text/html')
|
||||
let blocked = 0
|
||||
if (!showImages) {
|
||||
d.querySelectorAll('img').forEach((img) => {
|
||||
const src = img.getAttribute('src') ?? ''
|
||||
if (REMOTE.test(src)) {
|
||||
img.removeAttribute('src')
|
||||
img.setAttribute('alt', img.getAttribute('alt') || '')
|
||||
blocked++
|
||||
}
|
||||
})
|
||||
d.querySelectorAll('[background]').forEach((el) => {
|
||||
if (REMOTE.test(el.getAttribute('background') ?? '')) {
|
||||
el.removeAttribute('background')
|
||||
blocked++
|
||||
}
|
||||
})
|
||||
const noUrl = (css: string) => css.replace(/url\(\s*(['"]?)\s*(https?:)?\/\/[^)]*\)/gi, () => (blocked++, 'none'))
|
||||
d.querySelectorAll('[style]').forEach((el) => el.setAttribute('style', noUrl(el.getAttribute('style') ?? '')))
|
||||
d.querySelectorAll('style').forEach((s) => (s.textContent = noUrl(s.textContent ?? '')))
|
||||
}
|
||||
d.querySelectorAll('a[href]').forEach((a) => {
|
||||
a.setAttribute('target', '_blank')
|
||||
a.setAttribute('rel', 'noopener noreferrer')
|
||||
})
|
||||
const base = d.createElement('style')
|
||||
base.textContent =
|
||||
'html{background:#fff}body{margin:0;padding:16px;font:15px/1.5 -apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:#111;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{max-width:100%}pre{white-space:pre-wrap}'
|
||||
d.head.prepend(base)
|
||||
return { doc: '<!doctype html>' + d.documentElement.outerHTML, blocked }
|
||||
}
|
||||
|
||||
/** Texte brut avec liens cliquables. */
|
||||
function Linkified({ text }: { text: string }) {
|
||||
const parts = text.split(/(https?:\/\/[^\s<>"]+)/g)
|
||||
return (
|
||||
<>
|
||||
{parts.map((p, k) =>
|
||||
k % 2 ? (
|
||||
<a key={k} href={p} target="_blank" rel="noopener noreferrer" className="text-accent underline underline-offset-2">
|
||||
{p}
|
||||
</a>
|
||||
) : (
|
||||
p
|
||||
),
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function HtmlBody({ html, showImages }: { html: string; showImages: boolean }) {
|
||||
const frame = useRef<HTMLIFrameElement>(null)
|
||||
const { doc } = useMemo(() => emailDocument(html, showImages), [html, showImages])
|
||||
// Hauteur du cadre = hauteur du message (pas de double défilement), recalculée quand les images arrivent
|
||||
const fit = () => {
|
||||
const f = frame.current
|
||||
const body = f?.contentDocument?.body
|
||||
// Hauteur du contenu (et non du cadre : documentElement ne descend jamais sous la hauteur affichée)
|
||||
const h = body ? Math.ceil(body.getBoundingClientRect().height) : 0
|
||||
if (f && h) f.style.height = `${Math.max(h, 80) + 2}px`
|
||||
}
|
||||
const onLoad = () => {
|
||||
fit()
|
||||
frame.current?.contentDocument?.querySelectorAll('img').forEach((img) => img.addEventListener('load', fit))
|
||||
window.setTimeout(fit, 300)
|
||||
}
|
||||
useEffect(() => {
|
||||
window.addEventListener('resize', fit)
|
||||
return () => window.removeEventListener('resize', fit)
|
||||
}, [])
|
||||
return (
|
||||
<iframe
|
||||
ref={frame}
|
||||
title="Contenu du message"
|
||||
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
|
||||
srcDoc={doc}
|
||||
onLoad={onLoad}
|
||||
className="block h-40 w-full rounded-md border border-line bg-white"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Action({ icon, label, onClick, danger }: { icon: ReactNode; label: string; onClick: () => void; danger?: boolean }) {
|
||||
return (
|
||||
<button onClick={onClick} className={`btn btn-ghost px-3 py-1.5 ${danger ? 'text-danger' : ''}`} title={label}>
|
||||
{icon}
|
||||
<span className="hidden sm:inline">{label}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Reader({
|
||||
token,
|
||||
folder,
|
||||
uid,
|
||||
onBack,
|
||||
onReply,
|
||||
onForward,
|
||||
onChanged,
|
||||
onAuthError,
|
||||
}: {
|
||||
token: string
|
||||
folder: FolderId
|
||||
uid: number
|
||||
onBack: () => void
|
||||
onReply: (m: Message) => void
|
||||
onForward: (m: Message) => void
|
||||
onChanged: (removed: boolean) => void
|
||||
onAuthError: (e: unknown) => void
|
||||
}) {
|
||||
const [msg, setMsg] = useState<Message>()
|
||||
const [error, setError] = useState<string>()
|
||||
const [showImages, setShowImages] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
setMsg(undefined)
|
||||
setError(undefined)
|
||||
setShowImages(false)
|
||||
call<Message>(token, 'read', { folder, uid })
|
||||
.then((m) => {
|
||||
if (!alive) return
|
||||
setMsg(m)
|
||||
onChanged(false) // lu : compteurs à jour
|
||||
})
|
||||
.catch((e) => {
|
||||
onAuthError(e)
|
||||
if (alive) setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
})
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [token, folder, uid])
|
||||
|
||||
const blocked = useMemo(() => (msg?.html ? emailDocument(msg.html, false).blocked : 0), [msg])
|
||||
|
||||
const act = async (action: string, params: Record<string, unknown>, removed: boolean) => {
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await call(token, action, { folder, uid, ...params })
|
||||
onChanged(removed)
|
||||
if (removed) onBack()
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const download = async (index: number) => {
|
||||
try {
|
||||
const a = await call<{ filename: string; contentType: string; data: string }>(token, 'attachment', { folder, uid, index })
|
||||
const bytes = Uint8Array.from(atob(a.data), (c) => c.charCodeAt(0))
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: a.contentType }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = a.filename
|
||||
link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30_000)
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Téléchargement impossible.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="min-w-0">
|
||||
<div className="sticky top-0 z-10 -mx-4 flex flex-wrap items-center gap-1.5 border-b border-line bg-bg px-4 py-2 lg:static lg:mx-0 lg:border-0 lg:px-0 lg:pt-0">
|
||||
<button onClick={onBack} className="btn px-2 py-1.5 text-ink-2 lg:hidden" aria-label="Retour">
|
||||
<ChevronLeft size={20} />
|
||||
</button>
|
||||
{msg && (
|
||||
<>
|
||||
<Action icon={<CornerUpLeft size={16} />} label="Répondre" onClick={() => onReply(msg)} />
|
||||
<Action icon={<Forward size={16} />} label="Transférer" onClick={() => onForward(msg)} />
|
||||
<Action icon={<MailOpen size={16} />} label="Non lu" onClick={() => void act('seen', { value: false }, false).then(onBack)} />
|
||||
{folder !== 'junk' && folder !== 'trash' && <Action icon={<Ban size={16} />} label="Indésirable" onClick={() => void act('move', { to: 'junk' }, true)} />}
|
||||
{(folder === 'junk' || folder === 'trash') && <Action icon={<Inbox size={16} />} label="Remettre en réception" onClick={() => void act('move', { to: 'inbox' }, true)} />}
|
||||
{folder === 'trash' || folder === 'junk' ? (
|
||||
<Action
|
||||
icon={<Trash2 size={16} />}
|
||||
label="Supprimer définitivement"
|
||||
danger
|
||||
onClick={() => confirm('Supprimer définitivement ce message ?') && void act('delete', {}, true)}
|
||||
/>
|
||||
) : (
|
||||
<Action icon={<Trash2 size={16} />} label="Corbeille" danger onClick={() => void act('move', { to: 'trash' }, true)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <p className="py-6 text-sm text-danger">{error}</p>}
|
||||
{!msg && !error && <p className="py-6 text-sm text-ink-3">Chargement…</p>}
|
||||
{msg && (
|
||||
<div className="pt-4">
|
||||
<h1 className="text-xl font-bold leading-snug sm:text-2xl">{msg.subject || '(sans objet)'}</h1>
|
||||
<div className="mt-3 text-sm">
|
||||
<p>
|
||||
<span className="font-semibold">{who(msg.from)}</span> <span className="text-ink-3">{msg.from.address && msg.from.name ? `<${msg.from.address}>` : ''}</span>
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-ink-3">
|
||||
À : {addrList(msg.to) || '—'}
|
||||
{msg.cc.length > 0 && ` · Cc : ${addrList(msg.cc)}`}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-ink-3">{fullDate(msg.date)}</p>
|
||||
</div>
|
||||
|
||||
{msg.attachments.length > 0 && (
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{msg.attachments.map((a) => (
|
||||
<button key={a.index} onClick={() => void download(a.index)} className="badge gap-1.5 px-2.5 py-1.5 text-xs text-ink">
|
||||
<Paperclip size={13} /> {a.filename} <span className="text-ink-3">{sizeLabel(a.size)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{msg.html && blocked > 0 && !showImages && (
|
||||
<p className="mt-4 flex flex-wrap items-center gap-2 border border-line bg-surface px-3 py-2 text-xs text-ink-2">
|
||||
<ImageOff size={14} /> Images distantes bloquées (elles signalent à l'expéditeur que le message a été ouvert).
|
||||
<button onClick={() => setShowImages(true)} className="font-semibold text-accent underline underline-offset-2">
|
||||
Afficher les images
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-4">
|
||||
{msg.html ? (
|
||||
<HtmlBody html={msg.html} showImages={showImages} />
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap break-words text-[15px] leading-relaxed">
|
||||
<Linkified text={msg.text} />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/** Appels à la fonction serveur « mail », par le relais nginx de mail.bobinoo.org (qui ajoute le secret). */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
const MESSAGES: Record<string, string> = {
|
||||
session: 'Session expirée : reconnecte-toi.',
|
||||
mfa: 'Code de double authentification requis : reconnecte-toi.',
|
||||
interdit: 'Accès réservé aux administrateurs de Bobinoo.',
|
||||
'trop de requêtes': 'Trop de requêtes, patiente une minute.',
|
||||
}
|
||||
|
||||
export async function call<T>(token: string, action: string, params: Record<string, unknown> = {}): Promise<T> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch('/api/mail', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ action, ...params }),
|
||||
credentials: 'omit',
|
||||
cache: 'no-store',
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(0, 'Serveur injoignable. Vérifie ta connexion.')
|
||||
}
|
||||
if (res.status === 404) throw new ApiError(404, "La messagerie n'est pas reliée au serveur (secret du VPS absent ou différent).")
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
if (!res.ok) throw new ApiError(res.status, MESSAGES[body.error ?? ''] ?? body.error ?? `Erreur ${res.status}`)
|
||||
return body as T
|
||||
}
|
||||
|
||||
export type FolderId = 'inbox' | 'sent' | 'drafts' | 'junk' | 'trash'
|
||||
export interface Folder {
|
||||
id: FolderId
|
||||
total: number
|
||||
unseen: number
|
||||
}
|
||||
export interface Addr {
|
||||
name?: string
|
||||
address?: string
|
||||
}
|
||||
export interface Summary {
|
||||
uid: number
|
||||
subject: string
|
||||
from: Addr
|
||||
to: Addr[]
|
||||
date: string | null
|
||||
seen: boolean
|
||||
answered: boolean
|
||||
flagged: boolean
|
||||
attachments: boolean
|
||||
size: number
|
||||
}
|
||||
export interface Message {
|
||||
uid: number
|
||||
subject: string
|
||||
from: Addr
|
||||
to: Addr[]
|
||||
cc: Addr[]
|
||||
replyTo: Addr[]
|
||||
date: string | null
|
||||
messageId: string | null
|
||||
references: string[]
|
||||
html: string | null
|
||||
text: string
|
||||
attachments: { index: number; filename: string; contentType: string; size: number }[]
|
||||
}
|
||||
|
||||
export const FOLDER_LABEL: Record<FolderId, string> = {
|
||||
inbox: 'Réception',
|
||||
sent: 'Envoyés',
|
||||
drafts: 'Brouillons',
|
||||
junk: 'Indésirables',
|
||||
trash: 'Corbeille',
|
||||
}
|
||||
|
||||
export const who = (a?: Addr) => (a?.name || a?.address || 'Inconnu').trim()
|
||||
export const addrList = (l: Addr[]) => l.map((a) => (a.name ? `${a.name} <${a.address}>` : (a.address ?? ''))).join(', ')
|
||||
@@ -0,0 +1,22 @@
|
||||
const time = new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit' })
|
||||
const dayMonth = new Intl.DateTimeFormat('fr-FR', { day: 'numeric', month: 'short' })
|
||||
const short = new Intl.DateTimeFormat('fr-FR', { day: '2-digit', month: '2-digit', year: '2-digit' })
|
||||
const full = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'full', timeStyle: 'short' })
|
||||
|
||||
/** Date de la liste : l'heure aujourd'hui, « 12 nov. » cette année, sinon « 12/11/25 ». */
|
||||
export function listDate(d: string | null): string {
|
||||
if (!d) return ''
|
||||
const date = new Date(d)
|
||||
const now = new Date()
|
||||
if (date.toDateString() === now.toDateString()) return time.format(date)
|
||||
if (date.getFullYear() === now.getFullYear()) return dayMonth.format(date)
|
||||
return short.format(date)
|
||||
}
|
||||
|
||||
export const fullDate = (d: string | null) => (d ? full.format(new Date(d)) : '')
|
||||
|
||||
export function sizeLabel(n: number): string {
|
||||
if (n < 1024) return `${n} o`
|
||||
if (n < 1024 * 1024) return `${Math.round(n / 1024)} Ko`
|
||||
return `${(n / 1024 / 1024).toFixed(1).replace('.', ',')} Mo`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@fontsource-variable/epilogue/wght.css'
|
||||
import '../../admin/src/styles.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -1,27 +1,28 @@
|
||||
{
|
||||
"name": "azuucine",
|
||||
"name": "bobinoo",
|
||||
"version": "2.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "azuucine",
|
||||
"name": "bobinoo",
|
||||
"version": "2.2.0",
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.3.0",
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
"@fontsource-variable/epilogue": "5.3.0",
|
||||
"dompurify": "3.4.18",
|
||||
"lucide-react": "0.468.0",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.1.8",
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@vitejs/plugin-react": "^4.5.0",
|
||||
"tailwindcss": "^4.1.8",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^6.4.3",
|
||||
"vite-plugin-pwa": "^1.0.0"
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@vitejs/plugin-react": "4.7.0",
|
||||
"tailwindcss": "4.3.3",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "6.4.6",
|
||||
"vite-plugin-pwa": "1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@apideck/better-ajv-errors": {
|
||||
@@ -2057,10 +2058,10 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/inter": {
|
||||
"node_modules/@fontsource-variable/epilogue": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.3.0.tgz",
|
||||
"integrity": "sha512-RofMylZmjlJEfELXeNHFWBRcSs75rGU/6bV2S2jfnvv/3rPXPGe0LgUJTklcHZ9lM4OZmAVFhcJPnACfb91A3g==",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/epilogue/-/epilogue-5.3.0.tgz",
|
||||
"integrity": "sha512-atoQ7bIqgDLX+zlxbxmYpNZ7nqkwwZczkhJhWdaX+UBZufhPWP3vrcKaLVaNcCbRyHeSoX/y/HJNGjKhewEsAg==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
@@ -3002,7 +3003,7 @@
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react": {
|
||||
@@ -3529,6 +3530,15 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.4.18",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz",
|
||||
"integrity": "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
@@ -3836,9 +3846,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.8",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
|
||||
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
|
||||
"version": "3.1.9",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",
|
||||
"integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -5654,9 +5664,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/serialize-javascript": {
|
||||
"version": "7.1.2",
|
||||
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.2.tgz",
|
||||
"integrity": "sha512-GL2BWwVa6JydKO6l/ljVgjAZF4QJ3S7dWDWi53s5GZT8PJzD2fNxi67HANQGKAqPrwEpL5ba7gUBGi0Ls/sEoQ==",
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz",
|
||||
"integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
@@ -5845,13 +5855,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
|
||||
"integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/source-map-support": {
|
||||
@@ -6334,9 +6344,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "6.4.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
||||
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
|
||||
"version": "6.4.6",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz",
|
||||
"integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "azuucine",
|
||||
"name": "bobinoo",
|
||||
"private": true,
|
||||
"version": "2.2.0",
|
||||
"type": "module",
|
||||
@@ -10,22 +10,25 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"audit": "npm audit --omit=dev"
|
||||
"audit": "npm audit --omit=dev",
|
||||
"build:admin": "vite build --config vite.admin.config.ts",
|
||||
"build:mail": "vite build --config vite.mail.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.3.0",
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
"@fontsource-variable/epilogue": "5.3.0",
|
||||
"dompurify": "3.4.18",
|
||||
"lucide-react": "0.468.0",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.1.8",
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@vitejs/plugin-react": "^4.5.0",
|
||||
"tailwindcss": "^4.1.8",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^6.4.3",
|
||||
"vite-plugin-pwa": "^1.0.0"
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@vitejs/plugin-react": "4.7.0",
|
||||
"tailwindcss": "4.3.3",
|
||||
"typescript": "5.9.3",
|
||||
"vite": "6.4.6",
|
||||
"vite-plugin-pwa": "1.3.0"
|
||||
}
|
||||
}
|
||||
@@ -3,31 +3,19 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Bobinoo — Page introuvable</title>
|
||||
<title>Page introuvable — Bobinoo</title>
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100dvh; display: grid; place-items: center; background: #14120f; color: #f1eadd; font: 16px/1.6 system-ui, -apple-system, sans-serif; text-align: center; }
|
||||
main { padding: 48px 20px; max-width: 520px; }
|
||||
.code { font-size: clamp(6rem, 28vw, 11rem); font-weight: 800; letter-spacing: -.06em; line-height: 1; margin: 0; color: #2f2a23; }
|
||||
.code span { color: #f0a63a; }
|
||||
h1 { font-size: 1.5rem; margin: 20px 0 8px; }
|
||||
p { color: #bcb2a1; margin: 0 0 28px; }
|
||||
a.btn { display: inline-block; background: #f0a63a; color: #17130d; text-decoration: none; font-weight: 600; padding: 12px 22px; border-radius: 4px; }
|
||||
a.btn:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
|
||||
.en { margin-top: 36px; font-size: .85rem; color: #948a79; }
|
||||
.en a { color: #f0a63a; }
|
||||
</style>
|
||||
<link rel="stylesheet" href="/pages.css" />
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<body class="notfound">
|
||||
<main>
|
||||
<p class="code" aria-hidden="true">4<span>0</span>4</p>
|
||||
<h1>Cette scène a été coupée au montage</h1>
|
||||
<p>La page que tu cherches n'existe pas ou a été déplacée.</p>
|
||||
<a class="btn" href="/">Retour à Bobinoo</a>
|
||||
<p class="en">Page not found — <a href="/">back to Bobinoo</a></p>
|
||||
<p class="updated" style="margin-top:28px" lang="en">Page not found — <a href="/">back to Bobinoo</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Crédits — Bobinoo</title>
|
||||
<meta name="robots" content="index" />
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="stylesheet" href="/pages.css" />
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<a class="brand" href="/">Bobin<span>oo</span></a>
|
||||
<nav class="pages" aria-label="Pages d'information"><a href="/privacy.html">Confidentialité</a><a href="/terms.html">Conditions d'utilisation</a><a href="/legal.html">Mentions légales</a><a href="/credits.html" aria-current="page">Crédits</a><a href="/supprimer-compte.html">Supprimer mon compte</a></nav>
|
||||
<h1>Crédits</h1>
|
||||
<p class="updated">Mise à jour le 28 novembre 2026</p>
|
||||
<h2>Données des œuvres</h2>
|
||||
<p>Bobinoo ne possède pas sa propre base de films : les fiches viennent de services externes, utilisés directement par l'application (sans réglage à faire).</p>
|
||||
<ul>
|
||||
<li><strong>TMDB</strong> — <em>This product uses the TMDB API but is not endorsed or certified by TMDB.</em> Les informations et images des films et séries proviennent de <a href="https://www.themoviedb.org">The Movie Database (TMDB)</a>.</li>
|
||||
<li><strong>AniList</strong> — les informations et images des animes proviennent de <a href="https://anilist.co">AniList</a>.</li>
|
||||
<li><strong>JustWatch</strong> — les offres de streaming (« Où regarder ») proviennent de <a href="https://www.justwatch.com">JustWatch</a>, via TMDB.</li>
|
||||
</ul>
|
||||
<h2>Polices, icônes et logiciels</h2>
|
||||
<ul>
|
||||
<li><strong>Police Epilogue</strong> — Etcetera Type Co, licence SIL Open Font License 1.1.</li>
|
||||
<li><strong>Icônes Lucide</strong> — licence ISC.</li>
|
||||
<li><strong>Logiciels libres</strong> — React (MIT), Vite (MIT), Tailwind CSS (MIT), Workbox (MIT).</li>
|
||||
<li>Les affiches, images et marques des œuvres appartiennent à leurs ayants droit respectifs.</li>
|
||||
</ul>
|
||||
|
||||
<footer><a href="/">← Retour à Bobinoo</a></footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The Epilogue Project Authors (https://github.com/Etcetera-Type-Co/Epilogue) Epilogue-Italic[wght].ttf: Copyright 2020 The Epilogue Project Authors (https://github.com/Etcetera-Type-Co/Epilogue)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.2 KiB |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" rx="112" fill="#14120f"/><circle cx="256" cy="256" r="172.0" fill="#f0a63a"/><circle cx="256.0" cy="164.0" r="36.0" fill="#14120f"/><circle cx="343.5" cy="227.6" r="36.0" fill="#14120f"/><circle cx="310.1" cy="330.4" r="36.0" fill="#14120f"/><circle cx="201.9" cy="330.4" r="36.0" fill="#14120f"/><circle cx="168.5" cy="227.6" r="36.0" fill="#14120f"/><circle cx="256" cy="256" r="18.0" fill="#14120f"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" rx="112" fill="#0d0d0d"/><circle cx="256" cy="256" r="172.0" fill="#53bfb6"/><circle cx="256.0" cy="164.0" r="36.0" fill="#0d0d0d"/><circle cx="343.5" cy="227.6" r="36.0" fill="#0d0d0d"/><circle cx="310.1" cy="330.4" r="36.0" fill="#0d0d0d"/><circle cx="201.9" cy="330.4" r="36.0" fill="#0d0d0d"/><circle cx="168.5" cy="227.6" r="36.0" fill="#0d0d0d"/><circle cx="256" cy="256" r="18.0" fill="#0d0d0d"/></svg>
|
||||
|
Before Width: | Height: | Size: 502 B After Width: | Height: | Size: 502 B |
|
Before Width: | Height: | Size: 7.4 KiB After Width: | Height: | Size: 7.1 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 13 KiB |
@@ -3,76 +3,35 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Bobinoo — Mentions légales et conditions d'utilisation</title>
|
||||
<title>Mentions légales — Bobinoo</title>
|
||||
<meta name="robots" content="index" />
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
body { margin: 0; background: #14120f; color: #f1eadd; font: 16px/1.65 system-ui, -apple-system, sans-serif; }
|
||||
main { max-width: 680px; margin: 0 auto; padding: 48px 20px 80px; }
|
||||
h1 { font-size: 2rem; margin: 0 0 4px; }
|
||||
h1 span { color: #f0a63a; }
|
||||
h2 { font-size: 1.1rem; margin: 36px 0 8px; }
|
||||
h3 { font-size: 1rem; margin: 20px 0 4px; }
|
||||
p, li { color: #bcb2a1; }
|
||||
a { color: #f0a63a; }
|
||||
a:focus-visible { outline: 2px solid #f0a63a; outline-offset: 2px; }
|
||||
.muted { color: #948a79; font-size: .875rem; }
|
||||
hr { border: 0; border-top: 1px solid #222; margin: 48px 0; }
|
||||
nav a { margin-right: 16px; }
|
||||
</style>
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="stylesheet" href="/pages.css" />
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Ki<span>no</span></h1>
|
||||
<p class="muted">Mentions légales, conditions d'utilisation et crédits — mise à jour le 9 octobre 2026</p>
|
||||
<nav class="muted"><a href="#mentions">Mentions légales</a><a href="#conditions">Conditions d'utilisation</a><a href="#credits">Crédits</a><a href="/privacy.html">Confidentialité</a></nav>
|
||||
|
||||
<h2 id="mentions">Mentions légales</h2>
|
||||
<h3>Éditeur</h3>
|
||||
<p>Bobinoo est édité par <strong>Romain Dacet</strong>, particulier, à titre personnel et non commercial. Directeur de la publication : Romain Dacet. Contact : via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
<h3>Hébergement</h3>
|
||||
<a class="brand" href="/">Bobin<span>oo</span></a>
|
||||
<nav class="pages" aria-label="Pages d'information"><a href="/privacy.html">Confidentialité</a><a href="/terms.html">Conditions d'utilisation</a><a href="/legal.html" aria-current="page">Mentions légales</a><a href="/credits.html">Crédits</a><a href="/supprimer-compte.html">Supprimer mon compte</a></nav>
|
||||
<h1>Mentions légales</h1>
|
||||
<p class="updated">Mise à jour le 28 novembre 2026</p>
|
||||
<h2>Éditeur</h2>
|
||||
<p>Bobinoo est édité par <strong>Romain Dacet</strong>, particulier, à titre personnel et non commercial. Directeur de la publication : Romain Dacet. Contact : <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>.</p>
|
||||
<h2>Hébergement</h2>
|
||||
<ul>
|
||||
<li><strong>Site (fichiers de l'application)</strong> : OVH SAS, 2 rue Kellermann, 59100 Roubaix, France — <a href="https://www.ovhcloud.com">ovhcloud.com</a>.</li>
|
||||
<li><strong>Comptes et données</strong> (base de données, authentification, photos de profil) : Supabase Inc. — <a href="https://supabase.com">supabase.com</a>. Les données sont stockées dans l'Union européenne (Irlande).</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="conditions">Conditions d'utilisation</h2>
|
||||
<h3>Le service</h3>
|
||||
<p>Bobinoo permet de tenir le journal des films, séries, animes et dramas que tu regardes, de les noter, d'écrire des avis et de suivre d'autres membres. Le service est <strong>gratuit</strong>, sans publicité et sans achat : il n'y a donc ni conditions de vente, ni paiement, ni remboursement.</p>
|
||||
<h3>Âge minimum</h3>
|
||||
<p>Il faut avoir <strong>au moins 15 ans</strong> pour créer un compte. En dessous, l'accord d'un parent ou du titulaire de l'autorité parentale est nécessaire.</p>
|
||||
<h3>Ton compte</h3>
|
||||
<p>Tu es responsable de ton compte et de ton mot de passe. Tu peux exporter tes données ou supprimer ton compte à tout moment depuis <em>Réglages</em> (Sauvegarde, Zone sensible), sans démarche ni justification.</p>
|
||||
<h3>Ce que tu publies</h3>
|
||||
<p>Ton pseudo, ta photo, ta bio, tes notes et tes avis sont visibles par les autres membres (sauf si ton compte est privé). Tu restes propriétaire de ce que tu écris. Sont interdits : les contenus illégaux, haineux, harcelants, à caractère sexuel, l'usurpation d'identité, le spam et les révélations (spoilers) présentées de façon trompeuse. Un contenu qui ne respecte pas ces règles peut être retiré, et le compte concerné suspendu.</p>
|
||||
<p>Pour signaler un contenu, contacte l'éditeur via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
<h3>Informations sur les œuvres</h3>
|
||||
<p>Les fiches (titres, affiches, résumés, notes moyennes, casting, dates de sortie) proviennent de TMDB et d'AniList. Elles sont fournies telles quelles et peuvent contenir des erreurs ; les notes moyennes affichées sont celles de ces services, pas un avis de l'éditeur.</p>
|
||||
<h3>Disponibilité</h3>
|
||||
<p>Bobinoo est un projet personnel, proposé sans garantie de disponibilité permanente. L'éditeur fait de son mieux pour protéger tes données (voir la <a href="/privacy.html">politique de confidentialité</a>) et te conseille d'exporter régulièrement ta bibliothèque.</p>
|
||||
<h3>Droit applicable</h3>
|
||||
<p>Ces conditions sont soumises au droit français. Elles peuvent évoluer ; la date de mise à jour figure en haut de cette page.</p>
|
||||
|
||||
<h2 id="credits">Crédits et licences</h2>
|
||||
<ul>
|
||||
<li><strong>TMDB</strong> — <em>This product uses the TMDB API but is not endorsed or certified by TMDB.</em> Les informations et images des films et séries proviennent de <a href="https://www.themoviedb.org">The Movie Database (TMDB)</a>.</li>
|
||||
<li><strong>AniList</strong> — les informations et images des animes proviennent de <a href="https://anilist.co">AniList</a>.</li>
|
||||
<li><strong>JustWatch</strong> — les offres de streaming (« Où regarder ») proviennent de <a href="https://www.justwatch.com">JustWatch</a>, via TMDB.</li>
|
||||
<li><strong>Police Inter</strong> — Rasmus Andersson, licence SIL Open Font License 1.1.</li>
|
||||
<li><strong>Icônes Lucide</strong> — licence ISC.</li>
|
||||
<li><strong>Logiciels libres</strong> — React (MIT), Vite (MIT), Tailwind CSS (MIT), Workbox (MIT).</li>
|
||||
<li>Les affiches, images et marques des œuvres appartiennent à leurs ayants droit respectifs.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Accessibilité</h2>
|
||||
<p>L'application vise à être utilisable au clavier, avec un lecteur d'écran et avec des contrastes suffisants dans tous les thèmes. Si quelque chose te bloque, signale-le via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
<p>L'application vise à être utilisable au clavier, avec un lecteur d'écran et avec des contrastes suffisants dans tous les thèmes. Si quelque chose te bloque, écris à <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>.</p>
|
||||
<section class="en" lang="en">
|
||||
|
||||
<hr />
|
||||
<h2>Legal notice & terms (English summary)</h2>
|
||||
<p>Bobinoo is published by Romain Dacet, a private individual, on a personal, non-commercial basis (contact: <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>). The site is hosted by OVH SAS (2 rue Kellermann, 59100 Roubaix, France); accounts and data are hosted by Supabase Inc. in the European Union (Ireland). The service is free, with no ads and no purchases. You must be at least 13 years old to sign up, with a parent's consent if under 15. You own what you write; illegal, hateful, harassing or sexual content, impersonation and spam are forbidden and may be removed, and the account suspended. Title data comes from TMDB and AniList (streaming availability: JustWatch) and is provided as is. This product uses the TMDB API but is not endorsed or certified by TMDB. French law applies.</p>
|
||||
|
||||
<h1 style="font-size:1.4rem">Legal notice & terms (English summary)</h1>
|
||||
<p>Bobinoo is published by Romain Dacet, a private individual, on a personal, non-commercial basis (contact: <a href="https://rdacet.fr">rdacet.fr</a>). The site is hosted by OVH SAS (2 rue Kellermann, 59100 Roubaix, France); accounts and data are hosted by Supabase Inc. in the European Union (Ireland). The service is free, with no ads and no purchases. You must be at least 15 years old to sign up (or have a parent's consent). You own what you write; illegal, hateful, harassing or sexual content, impersonation and spam are forbidden and may be removed, and the account suspended. Title data comes from TMDB and AniList (streaming availability: JustWatch) and is provided as is. This product uses the TMDB API but is not endorsed or certified by TMDB. French law applies.</p>
|
||||
|
||||
<p class="muted"><a href="/">← Retour à Bobinoo</a></p>
|
||||
</section>
|
||||
<footer><a href="/">← Retour à Bobinoo</a></footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
/* Bobinoo — pages publiques (confidentialité, conditions, mentions, crédits, 404) : thème « Encre », clair ou sombre selon l'appareil */
|
||||
@font-face {
|
||||
font-family: 'Epilogue';
|
||||
src: url('/fonts/epilogue.woff2') format('woff2');
|
||||
font-weight: 100 900;
|
||||
font-display: swap;
|
||||
}
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--bg: #fefdfb;
|
||||
--ink: #0d0d0d;
|
||||
--ink-2: #383838;
|
||||
--ink-3: #525252;
|
||||
--line: #dbdbd8;
|
||||
--accent: #00746d;
|
||||
--on-accent: #ffffff;
|
||||
}
|
||||
/* Sombre : selon l'appareil, sauf si l'app a été réglée sur « Clair » ; ou si elle a été réglée sur « Sombre » */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme='light']) {
|
||||
--bg: #090909;
|
||||
--ink: #f2f2f0;
|
||||
--ink-2: #c4c4c4;
|
||||
--ink-3: #989898;
|
||||
--line: #2b2b2b;
|
||||
--accent: #53bfb6;
|
||||
--on-accent: #062b28;
|
||||
}
|
||||
}
|
||||
:root[data-theme='dark'] {
|
||||
--bg: #090909;
|
||||
--ink: #f2f2f0;
|
||||
--ink-2: #c4c4c4;
|
||||
--ink-3: #989898;
|
||||
--line: #2b2b2b;
|
||||
--accent: #53bfb6;
|
||||
--on-accent: #062b28;
|
||||
}
|
||||
:root[data-theme='light'] { color-scheme: light; }
|
||||
:root[data-theme='dark'] { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--bg); color: var(--ink); font: 16px/1.65 'Epilogue', system-ui, -apple-system, 'Segoe UI', sans-serif; -webkit-font-smoothing: antialiased; }
|
||||
main { max-width: 680px; margin: 0 auto; padding: 40px 20px 80px; }
|
||||
.brand { display: inline-block; font-size: 1.6rem; font-weight: 700; letter-spacing: -0.02em; color: var(--ink); text-decoration: none; }
|
||||
.brand span { color: var(--accent); }
|
||||
nav.pages { display: flex; flex-wrap: wrap; gap: 8px 20px; margin: 20px 0 36px; padding-bottom: 14px; border-bottom: 1px solid var(--ink); font-size: .9rem; }
|
||||
nav.pages a { color: var(--ink-3); text-decoration: none; }
|
||||
nav.pages a[aria-current='page'] { color: var(--ink); font-weight: 600; text-decoration: underline; text-underline-offset: 6px; text-decoration-color: var(--accent); }
|
||||
h1 { font-size: 2rem; line-height: 1.15; letter-spacing: -0.02em; margin: 0 0 6px; }
|
||||
.updated { color: var(--ink-3); font-size: .875rem; margin: 0 0 8px; }
|
||||
h2 { font-size: 1.15rem; margin: 40px 0 10px; padding-bottom: 6px; border-bottom: 1px solid var(--line); }
|
||||
h3 { font-size: 1rem; margin: 22px 0 4px; }
|
||||
p, li { color: var(--ink-2); }
|
||||
ul { padding-left: 1.2em; }
|
||||
li { margin: 6px 0; }
|
||||
strong { color: var(--ink); }
|
||||
a { color: var(--accent); }
|
||||
a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.en { margin-top: 48px; padding-top: 20px; border-top: 1px solid var(--line); font-size: .9rem; }
|
||||
.en h2 { border: 0; margin-top: 0; font-size: 1rem; }
|
||||
footer { margin-top: 48px; font-size: .9rem; }
|
||||
/* Page 404 */
|
||||
.notfound { min-height: 100dvh; display: grid; place-items: center; text-align: center; }
|
||||
.notfound main { padding: 48px 20px; max-width: 520px; }
|
||||
.code { font-size: clamp(6rem, 28vw, 11rem); font-weight: 800; letter-spacing: -0.06em; line-height: 1; margin: 0; color: var(--line); }
|
||||
.code span { color: var(--accent); }
|
||||
.btn { display: inline-block; margin-top: 8px; background: var(--accent); color: var(--on-accent); text-decoration: none; font-weight: 600; padding: 12px 22px; border-radius: 2px; }
|
||||
/* Tableaux (confidentialité) */
|
||||
.table-wrap { overflow-x: auto; margin: 12px 0; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: .9rem; }
|
||||
th, td { text-align: left; vertical-align: top; padding: 10px 12px 10px 0; border-bottom: 1px solid var(--line); color: var(--ink-2); }
|
||||
th { color: var(--ink); font-weight: 600; border-bottom-color: var(--ink); }
|
||||
@@ -3,44 +3,32 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Bobinoo — Confidentialité</title>
|
||||
<title>Confidentialité — Bobinoo</title>
|
||||
<meta name="robots" content="index" />
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
body { margin: 0; background: #14120f; color: #f1eadd; font: 16px/1.65 system-ui, -apple-system, sans-serif; }
|
||||
main { max-width: 680px; margin: 0 auto; padding: 48px 20px 80px; }
|
||||
h1 { font-size: 2rem; margin: 0 0 4px; }
|
||||
h1 span { color: #f0a63a; }
|
||||
h2 { font-size: 1.1rem; margin: 36px 0 8px; }
|
||||
p, li { color: #bcb2a1; }
|
||||
a { color: #f0a63a; }
|
||||
a:focus-visible { outline: 2px solid #f0a63a; outline-offset: 2px; }
|
||||
.muted { color: #948a79; font-size: .875rem; }
|
||||
hr { border: 0; border-top: 1px solid #222; margin: 48px 0; }
|
||||
nav a { margin-right: 16px; }
|
||||
table { border-collapse: collapse; width: 100%; font-size: .9rem; }
|
||||
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid #222; vertical-align: top; color: #bcb2a1; }
|
||||
th { color: #f1eadd; }
|
||||
</style>
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="stylesheet" href="/pages.css" />
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Ki<span>no</span></h1>
|
||||
<p class="muted">Politique de confidentialité — mise à jour le 9 octobre 2026</p>
|
||||
<nav class="muted"><a href="/legal.html#mentions">Mentions légales</a><a href="/legal.html#conditions">Conditions d'utilisation</a><a href="/legal.html#credits">Crédits</a></nav>
|
||||
<a class="brand" href="/">Bobin<span>oo</span></a>
|
||||
<nav class="pages" aria-label="Pages d'information"><a href="/privacy.html" aria-current="page">Confidentialité</a><a href="/terms.html">Conditions d'utilisation</a><a href="/legal.html">Mentions légales</a><a href="/credits.html">Crédits</a><a href="/supprimer-compte.html">Supprimer mon compte</a></nav>
|
||||
<h1>Confidentialité</h1>
|
||||
<p class="updated">Mise à jour le 28 novembre 2026</p>
|
||||
|
||||
<p>Bobinoo est une application gratuite et sans publicité pour tenir le journal des films, séries, animes et dramas que tu regardes. Elle est éditée par Romain Dacet, à titre personnel et non commercial, qui est le <strong>responsable du traitement</strong> de tes données (contact : <a href="https://rdacet.fr">rdacet.fr</a>).</p>
|
||||
|
||||
<p>Bobinoo est une application gratuite et sans publicité pour tenir le journal des films, séries, animes et dramas que tu regardes. Elle est éditée par Romain Dacet, à titre personnel et non commercial, qui est le <strong>responsable du traitement</strong> de tes données (contact : <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>).</p>
|
||||
|
||||
<p>Tu peux utiliser Bobinoo <strong>sans compte</strong> : tout reste alors uniquement sur ton appareil. Un compte n'est utile que pour synchroniser plusieurs appareils et pour la partie sociale.</p>
|
||||
|
||||
<h2>Ce qui est enregistré (et pourquoi)</h2>
|
||||
<table>
|
||||
<div class="table-wrap"><table>
|
||||
<tr><th>Donnée</th><th>Pourquoi</th><th>Base légale</th></tr>
|
||||
<tr><td>Adresse e-mail, mot de passe (chiffré, jamais visible par l'éditeur), nom si tu te connectes avec Google</td><td>Te connecter et sécuriser ton compte</td><td>Exécution du service (contrat)</td></tr>
|
||||
<tr><td>Bibliothèque : titres, statuts, épisodes vus, dates, notes, avis, listes, réglages</td><td>Faire fonctionner ton journal et le synchroniser</td><td>Contrat</td></tr>
|
||||
<tr><td>Profil : pseudo, nom affiché, bio, photo, bannière, top 5</td><td>Te présenter aux autres membres</td><td>Contrat</td></tr>
|
||||
<tr><td>Abonnements, demandes de suivi, réactions emoji aux avis</td><td>Fonctions sociales</td><td>Contrat</td></tr>
|
||||
</table>
|
||||
</table></div>
|
||||
<p>Rien d'autre n'est collecté : pas de date de naissance, pas de numéro de téléphone, pas de localisation, pas de contacts.</p>
|
||||
|
||||
<h2>Qui peut voir quoi</h2>
|
||||
@@ -57,7 +45,7 @@
|
||||
<h2>Où sont les données et qui les traite</h2>
|
||||
<ul>
|
||||
<li><strong>Supabase Inc.</strong> (base de données, authentification, stockage des photos) — sous-traitant, données hébergées dans l'<strong>Union européenne (Irlande)</strong>.</li>
|
||||
<li><strong>OVH SAS</strong> (Roubaix, France) — héberge les fichiers du site. Ce serveur ne reçoit aucune de tes données de compte ; comme tout serveur web, il voit ton adresse IP le temps de te servir les pages.</li>
|
||||
<li><strong>OVH SAS</strong> (Roubaix, France) — héberge les fichiers du site et envoie les e-mails du compte (confirmation d'adresse, mot de passe oublié) depuis l'adresse bobinoo.org. Pour ces e-mails, il reçoit uniquement ton adresse e-mail ; le serveur du site, lui, ne reçoit aucune donnée de compte et, comme tout serveur web, voit ton adresse IP le temps de te servir les pages.</li>
|
||||
<li><strong>TMDB et AniList</strong> — fournissent les fiches et les images des œuvres. Tes recherches leur sont transmises (pour TMDB via notre serveur, sans ton identité — ou directement si tu as renseigné ta propre clé TMDB dans les réglages), et ton navigateur télécharge les affiches directement chez eux, ce qui leur révèle ton adresse IP, comme n'importe quel site qui affiche leurs images. Aucune donnée de compte ne leur est envoyée. Les plateformes affichées dans « Où regarder » viennent de JustWatch (via TMDB) ; le pays choisi reste sur ton appareil, et un lien vers une plateforme n'est ouvert que si tu cliques dessus.</li>
|
||||
<li><strong>Have I Been Pwned</strong> — quand tu crées un compte ou changes ton mot de passe, l'app vérifie qu'il n'apparaît pas dans une fuite de données connue. Seuls les 5 premiers caractères d'une empreinte chiffrée du mot de passe sont envoyés : ni le mot de passe, ni ton e-mail, ni rien qui permette de le retrouver.</li>
|
||||
</ul>
|
||||
@@ -76,26 +64,26 @@
|
||||
</ul>
|
||||
|
||||
<h2>Âge minimum</h2>
|
||||
<p>Il faut avoir au moins <strong>15 ans</strong> pour créer un compte, ou l'accord d'un parent en dessous (article 7-1 de la loi Informatique et Libertés).</p>
|
||||
<p>Il faut avoir au moins <strong>13 ans</strong> pour créer un compte, et l'accord d'un parent avant 15 ans (article 7-1 de la loi Informatique et Libertés).</p>
|
||||
|
||||
<h2>Tes droits</h2>
|
||||
<p>Conformément au RGPD, tu as un droit d'<strong>accès</strong>, de <strong>rectification</strong>, d'<strong>effacement</strong>, de <strong>portabilité</strong>, d'<strong>opposition</strong> et de <strong>limitation</strong>. La plupart s'exercent directement dans l'app :</p>
|
||||
<ul>
|
||||
<li>modifier ton profil et ta bibliothèque à tout moment ;</li>
|
||||
<li><strong>exporter</strong> toutes tes données (fichier JSON) depuis Réglages → Sauvegarde → Exporter mes données ;</li>
|
||||
<li><strong>supprimer ton compte</strong> depuis Réglages → Zone sensible → Supprimer mon compte, sans justification.</li>
|
||||
<li><strong>supprimer ton compte</strong> depuis Réglages → Zone sensible → Supprimer mon compte, sans justification (voir aussi <a href="/supprimer-compte.html">Supprimer mon compte</a>, même sans accès à l'app).</li>
|
||||
</ul>
|
||||
<p>Pour toute autre demande, contacte l'éditeur via <a href="https://rdacet.fr">rdacet.fr</a> (réponse sous un mois). Si tu estimes que tes droits ne sont pas respectés, tu peux adresser une réclamation à la <a href="https://www.cnil.fr/fr/plaintes" rel="noopener">CNIL</a>.</p>
|
||||
<p>Pour toute autre demande, écris à <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a> (réponse sous un mois). Si tu estimes que tes droits ne sont pas respectés, tu peux adresser une réclamation à la <a href="https://www.cnil.fr/fr/plaintes" rel="noopener">CNIL</a>.</p>
|
||||
|
||||
<h2>Sécurité</h2>
|
||||
<p>Les échanges sont chiffrés (HTTPS). Chaque compte ne peut lire et modifier que ses propres données (règles d'accès appliquées par la base de données elle-même). Les mots de passe ne sont jamais stockés en clair.</p>
|
||||
<section class="en" lang="en">
|
||||
|
||||
<hr />
|
||||
<h2>Privacy policy (English summary)</h2>
|
||||
<p>Bobinoo is a free, ad-free personal watch journal published by Romain Dacet (data controller, contact: <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>). It works without an account (everything stays on your device). With an account, it stores your email (and your name if you sign in with Google), your library, ratings, reviews, profile, follows and emoji reactions, to provide the service (contract). Your email is never shown to other users; your profile is visible to signed-in users unless you make your account private. Data is hosted by Supabase in the EU (Ireland); the site files are served, and account emails (address confirmation, password reset) sent from bobinoo.org, by OVH (France). Title data and posters come from TMDB and AniList, which see your IP address when your browser loads their images, but never your account data. No cookies, no trackers, no ads, no marketing emails, nothing sold; on-device storage is strictly necessary. Data is kept while your account exists and deleted immediately and completely when you delete it. You must be 13 or older, with a parent's consent if under 15. You can access, correct, export or delete your data from Settings, contact the publisher for any other request, and complain to the CNIL.</p>
|
||||
|
||||
<h1 style="font-size:1.4rem">Privacy policy (English summary)</h1>
|
||||
<p>Bobinoo is a free, ad-free personal watch journal published by Romain Dacet (data controller, contact: <a href="https://rdacet.fr">rdacet.fr</a>). It works without an account (everything stays on your device). With an account, it stores your email (and your name if you sign in with Google), your library, ratings, reviews, profile, follows and emoji reactions, to provide the service (contract). Your email is never shown to other users; your profile is visible to signed-in users unless you make your account private. Data is hosted by Supabase in the EU (Ireland); the site files are served by OVH (France). Title data and posters come from TMDB and AniList, which see your IP address when your browser loads their images, but never your account data. No cookies, no trackers, no ads, no marketing emails, nothing sold; on-device storage is strictly necessary. Data is kept while your account exists and deleted immediately and completely when you delete it. You must be 15 or older (or have a parent's consent). You can access, correct, export or delete your data from Settings, contact the publisher for any other request, and complain to the CNIL.</p>
|
||||
|
||||
<p class="muted"><a href="/">← Retour à Bobinoo</a></p>
|
||||
</section>
|
||||
<footer><a href="/">← Retour à Bobinoo</a></footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,45 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Supprimer mon compte — Bobinoo</title>
|
||||
<meta name="robots" content="index" />
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="stylesheet" href="/pages.css" />
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<a class="brand" href="/">Bobin<span>oo</span></a>
|
||||
<nav class="pages" aria-label="Pages d'information"><a href="/privacy.html">Confidentialité</a><a href="/terms.html">Conditions d'utilisation</a><a href="/legal.html">Mentions légales</a><a href="/credits.html">Crédits</a><a href="/supprimer-compte.html" aria-current="page">Supprimer mon compte</a></nav>
|
||||
<h1>Supprimer mon compte</h1>
|
||||
<p class="updated">Mise à jour le 28 novembre 2026</p>
|
||||
<p>Tu peux supprimer ton compte Bobinoo à tout moment, gratuitement et sans justification. La suppression est <strong>immédiate et définitive</strong>.</p>
|
||||
|
||||
<h2>Depuis l'application</h2>
|
||||
<ol>
|
||||
<li>Ouvre Bobinoo et connecte-toi.</li>
|
||||
<li>Va dans <strong>Réglages</strong>.</li>
|
||||
<li>Dans <strong>Zone sensible</strong>, touche <strong>Supprimer mon compte</strong>, puis confirme.</li>
|
||||
</ol>
|
||||
<p>Avant, si tu veux garder une copie de ta bibliothèque : <strong>Réglages → Sauvegarde → Exporter mes données</strong>.</p>
|
||||
|
||||
<h2>Sans accès à l'application</h2>
|
||||
<p>Si tu ne peux plus te connecter, demande la suppression par e-mail à <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>, en indiquant l'adresse e-mail de ton compte. Une vérification peut t'être demandée pour s'assurer que la demande vient bien de toi. La suppression est faite sous un mois au plus tard.</p>
|
||||
|
||||
<h2>Ce qui est supprimé</h2>
|
||||
<ul>
|
||||
<li>ton compte (adresse e-mail, mot de passe, connexion Google, double authentification) ;</li>
|
||||
<li>ton profil (pseudo, nom, bio, photo, bannière) ;</li>
|
||||
<li>ta bibliothèque, tes notes, tes avis, tes listes et tes réglages ;</li>
|
||||
<li>tes abonnements, abonnés, réactions, commentaires, notifications et listes partagées que tu as créées.</li>
|
||||
</ul>
|
||||
<p>Rien n'est conservé dans l'application après la suppression. Les copies de sécurité techniques de la base de données sont remplacées au fil de leur rotation, puis effacées.</p>
|
||||
|
||||
<section class="en" lang="en"><h2>Delete your account (English)</h2>
|
||||
<p>You can delete your Bobinoo account at any time, for free and without giving a reason. Deletion is immediate and permanent. In the app: <strong>Settings → Danger zone → Delete my account</strong>, then confirm. If you can no longer sign in, email <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a> with your account's email address (handled within one month). Your account, profile, library, ratings, reviews, lists, follows, reactions, comments and notifications are all deleted; technical database backups are overwritten as they rotate.</p></section>
|
||||
<footer><a href="/">← Retour à Bobinoo</a></footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,42 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Conditions d'utilisation — Bobinoo</title>
|
||||
<meta name="robots" content="index" />
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="stylesheet" href="/pages.css" />
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<a class="brand" href="/">Bobin<span>oo</span></a>
|
||||
<nav class="pages" aria-label="Pages d'information"><a href="/privacy.html">Confidentialité</a><a href="/terms.html" aria-current="page">Conditions d'utilisation</a><a href="/legal.html">Mentions légales</a><a href="/credits.html">Crédits</a><a href="/supprimer-compte.html">Supprimer mon compte</a></nav>
|
||||
<h1>Conditions d'utilisation</h1>
|
||||
<p class="updated">Mise à jour le 28 novembre 2026</p>
|
||||
<h2>Le service</h2>
|
||||
<p>Bobinoo permet de tenir le journal des films, séries, animes et dramas que tu regardes, de les noter, d'écrire des avis et de suivre d'autres membres. Le service est <strong>gratuit</strong>, sans publicité et sans achat : il n'y a donc ni conditions de vente, ni paiement, ni remboursement.</p>
|
||||
<h2>Âge minimum</h2>
|
||||
<p>Il faut avoir <strong>au moins 13 ans</strong> pour créer un compte. Avant 15 ans, l'accord d'un parent ou du titulaire de l'autorité parentale est aussi nécessaire.</p>
|
||||
<h2>Ton compte</h2>
|
||||
<p>Tu es responsable de ton compte et de ton mot de passe. Tu peux exporter tes données ou supprimer ton compte à tout moment depuis <em>Réglages</em> (Sauvegarde, Zone sensible), sans démarche ni justification.</p>
|
||||
<h2>Ce que tu publies</h2>
|
||||
<p>Ton pseudo, ta photo, ta bio, tes notes et tes avis sont visibles par les autres membres (sauf si ton compte est privé). Tu restes propriétaire de ce que tu écris. Sont interdits : les contenus illégaux, haineux, harcelants, à caractère sexuel, l'usurpation d'identité, le spam et les révélations (spoilers) présentées de façon trompeuse. Un contenu qui ne respecte pas ces règles peut être retiré, et le compte concerné suspendu.</p>
|
||||
<p>Pour signaler un contenu, écris à <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>.</p>
|
||||
<h2>Informations sur les œuvres</h2>
|
||||
<p>Les fiches (titres, affiches, résumés, notes moyennes, casting, dates de sortie) proviennent de TMDB et d'AniList. Elles sont fournies telles quelles et peuvent contenir des erreurs ; les notes moyennes affichées sont celles de ces services, pas un avis de l'éditeur.</p>
|
||||
<h2>Disponibilité</h2>
|
||||
<p>Bobinoo est un projet personnel, proposé sans garantie de disponibilité permanente. L'éditeur fait de son mieux pour protéger tes données (voir la <a href="/privacy.html">politique de confidentialité</a>) et te conseille d'exporter régulièrement ta bibliothèque.</p>
|
||||
<h2>Droit applicable</h2>
|
||||
<p>Ces conditions sont soumises au droit français. Elles peuvent évoluer ; la date de mise à jour figure en haut de cette page.</p>
|
||||
<section class="en" lang="en">
|
||||
|
||||
<h2>Legal notice & terms (English summary)</h2>
|
||||
<p>Bobinoo is published by Romain Dacet, a private individual, on a personal, non-commercial basis (contact: <a href="mailto:contact@bobinoo.org">contact@bobinoo.org</a>). The site is hosted by OVH SAS (2 rue Kellermann, 59100 Roubaix, France); accounts and data are hosted by Supabase Inc. in the European Union (Ireland). The service is free, with no ads and no purchases. You must be at least 13 years old to sign up, with a parent's consent if under 15. You own what you write; illegal, hateful, harassing or sexual content, impersonation and spam are forbidden and may be removed, and the account suspended. Title data comes from TMDB and AniList (streaming availability: JustWatch) and is provided as is. This product uses the TMDB API but is not endorsed or certified by TMDB. French law applies.</p>
|
||||
|
||||
</section>
|
||||
<footer><a href="/">← Retour à Bobinoo</a></footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -10,7 +10,7 @@
|
||||
if (!theme) return
|
||||
document.documentElement.setAttribute('data-theme', theme)
|
||||
var meta = document.querySelector('meta[name="theme-color"]')
|
||||
if (meta) meta.setAttribute('content', theme === 'light' ? '#f1ebdf' : '#14120f')
|
||||
if (meta) meta.setAttribute('content', theme === 'light' ? '#fefdfb' : '#090909')
|
||||
var scheme = document.querySelector('meta[name="color-scheme"]')
|
||||
if (scheme) scheme.setAttribute('content', theme)
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,30 +1,37 @@
|
||||
import { SocialProvider } from './components/social/SocialProvider'
|
||||
import { preloadSocial, SocialProvider } from './components/social/SocialProvider'
|
||||
import { ToastProvider } from './components/Toast'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Suspense, startTransition, useCallback, useEffect, useState } from 'react'
|
||||
import BottomNav, { type Tab } from './components/BottomNav'
|
||||
import SideNav from './components/SideNav'
|
||||
import AddTitle from './components/title/AddTitle'
|
||||
import EditDetails from './components/title/EditDetails'
|
||||
import TitleSheet from './components/title/TitleSheet'
|
||||
import PersonSheet from './components/person/PersonSheet'
|
||||
import Roulette from './components/Roulette'
|
||||
import CalendarView from './components/CalendarView'
|
||||
import HomePage from './pages/HomePage'
|
||||
import CatalogPage from './pages/CatalogPage'
|
||||
import StatsPage from './pages/StatsPage'
|
||||
import SettingsPage from './pages/SettingsPage'
|
||||
import AdminPage from './pages/AdminPage'
|
||||
import NotFoundPage from './pages/NotFoundPage'
|
||||
import CatalogPage, { preloadCatalogViews } from './pages/CatalogPage'
|
||||
import { lazyPreload } from './lib/lazyPreload'
|
||||
import SyncIndicator from './components/SyncIndicator'
|
||||
import { useMedia } from './store'
|
||||
import type { SearchResult } from './lib/catalogApi'
|
||||
import { prefetchTitle, setPrefetchKey, type SearchResult } from './lib/catalogApi'
|
||||
import type { MediaItem } from './types'
|
||||
import type { Completion } from './lib/seasons'
|
||||
import { dropPushSubscription } from './lib/push'
|
||||
|
||||
// Écrans chargés à la demande (démarrage plus léger), puis préchargés quand l'app est au repos.
|
||||
// lazyPreload : un écran préchargé s'affiche sans aucune attente (React.lazy seul le retardait d'environ 300 ms).
|
||||
const TitleSheet = lazyPreload(() => import('./components/title/TitleSheet'))
|
||||
const AddTitle = lazyPreload(() => import('./components/title/AddTitle'))
|
||||
const EditDetails = lazyPreload(() => import('./components/title/EditDetails'))
|
||||
const PersonSheet = lazyPreload(() => import('./components/person/PersonSheet'))
|
||||
const Roulette = lazyPreload(() => import('./components/Roulette'))
|
||||
const CalendarView = lazyPreload(() => import('./components/CalendarView'))
|
||||
const StatsPage = lazyPreload(() => import('./pages/StatsPage'))
|
||||
const SettingsPage = lazyPreload(() => import('./pages/SettingsPage'))
|
||||
const NotFoundPage = lazyPreload(() => import('./pages/NotFoundPage'))
|
||||
function preloadScreens() {
|
||||
// Les plus utilisés d'abord
|
||||
for (const screen of [TitleSheet, AddTitle, StatsPage, SettingsPage, PersonSheet, CalendarView, Roulette, EditDetails, NotFoundPage]) void screen.preload().catch(() => {})
|
||||
preloadCatalogViews()
|
||||
preloadSocial()
|
||||
}
|
||||
|
||||
const TABS: Tab[] = ['home', 'catalog', 'stats', 'settings']
|
||||
// L'administration a sa propre route (#/admin), hors de la navigation principale
|
||||
type Route = Tab | 'admin' | 'notfound'
|
||||
type Route = Tab | 'notfound'
|
||||
|
||||
function routeFromHash(): Route {
|
||||
const hash = window.location.hash
|
||||
@@ -32,7 +39,6 @@ function routeFromHash(): Route {
|
||||
if (!hash.startsWith('#/')) return 'home'
|
||||
const h = hash.slice(2)
|
||||
if (h === '' || h.startsWith('u/')) return 'home'
|
||||
if (h === 'admin') return 'admin'
|
||||
return (TABS as string[]).includes(h) ? (h as Tab) : 'notfound'
|
||||
}
|
||||
|
||||
@@ -47,47 +53,75 @@ type Layer =
|
||||
let layerUid = 0
|
||||
|
||||
export default function App() {
|
||||
const { error } = useMedia()
|
||||
const { error, settings } = useMedia()
|
||||
|
||||
// Préchargement d'une fiche dès qu'on touche (ou survole à la souris) une affiche marquée data-prefetch :
|
||||
// infos TMDB et note Trakt arrivent pendant l'appui, la fiche s'ouvre avec tout déjà là
|
||||
useEffect(() => setPrefetchKey(settings.tmdbKey), [settings.tmdbKey])
|
||||
useEffect(() => {
|
||||
const onPointer = (e: PointerEvent) => {
|
||||
if (e.type === 'pointerover' && e.pointerType !== 'mouse') return
|
||||
const el = e.target instanceof Element ? e.target.closest('[data-prefetch]') : null
|
||||
if (el) prefetchTitle(el.getAttribute('data-prefetch'), Number(el.getAttribute('data-prefetch-season')) || undefined, Number(el.getAttribute('data-prefetch-ep')) || undefined)
|
||||
}
|
||||
document.addEventListener('pointerdown', onPointer, { capture: true, passive: true })
|
||||
document.addEventListener('pointerover', onPointer, { passive: true })
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onPointer, { capture: true })
|
||||
document.removeEventListener('pointerover', onPointer)
|
||||
}
|
||||
}, [])
|
||||
const [route, setRoute] = useState<Route>(routeFromHash)
|
||||
// Onglet surligné tout de suite ; l'écran, lui, est préparé sans bloquer le doigt (transition)
|
||||
const [navRoute, setNavRoute] = useState<Route>(route)
|
||||
const [layers, setLayers] = useState<(Layer & { uid: number })[]>([])
|
||||
const pushLayer = (l: Layer) => setLayers((ls) => [...ls.slice(-11), { ...l, uid: ++layerUid }])
|
||||
const pushLayer = useCallback((l: Layer) => setLayers((ls) => [...ls.slice(-11), { ...l, uid: ++layerUid }]), [])
|
||||
const closeLayer = (uid: number) => setLayers((ls) => ls.filter((x) => x.uid !== uid))
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [manual, setManual] = useState<string | null>(null)
|
||||
const [roulette, setRoulette] = useState(false)
|
||||
const [calendar, setCalendar] = useState(false)
|
||||
|
||||
// Notifications retirées : on résilie l'ancien abonnement push de cet appareil, s'il en reste un
|
||||
// Les écrans chargés à la demande arrivent en arrière-plan une fois l'app affichée : ils s'ouvrent ensuite sans attente
|
||||
useEffect(() => {
|
||||
void dropPushSubscription()
|
||||
const idle = window.requestIdleCallback ?? ((cb: () => void) => window.setTimeout(cb, 1500))
|
||||
idle(preloadScreens)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const onHash = () => setRoute(routeFromHash())
|
||||
const onHash = () => {
|
||||
const r = routeFromHash()
|
||||
setNavRoute(r)
|
||||
startTransition(() => setRoute(r))
|
||||
}
|
||||
window.addEventListener('hashchange', onHash)
|
||||
return () => window.removeEventListener('hashchange', onHash)
|
||||
}, [])
|
||||
|
||||
const go = (t: Route) => {
|
||||
const go = useCallback((t: Route) => {
|
||||
window.location.hash = `/${t}`
|
||||
window.scrollTo({ top: 0 })
|
||||
}
|
||||
// Dans la barre de navigation, l'administration reste rattachée à « Réglages »
|
||||
const navTab: Tab = route === 'admin' ? 'settings' : route === 'notfound' ? 'home' : route
|
||||
}, [])
|
||||
const navTab: Tab = navRoute === 'notfound' ? 'home' : navRoute
|
||||
|
||||
/** `focus` : saison (ou série) qu'on vient de finir avec +1 → la fiche s'ouvre sur la note */
|
||||
// Stable : les cartes mémorisées (MediaCard) ne se redessinent pas à chaque rendu de l'app
|
||||
const openItem = useCallback((item: MediaItem, focus?: Completion) => setLayers((ls) => [...ls.slice(-11), { kind: 'title', item, focus, uid: ++layerUid }]), [])
|
||||
const openSeed = (seed: SearchResult) => pushLayer({ kind: 'title', seed })
|
||||
const openPerson = (p: { id: string; name?: string; photo?: string }) => pushLayer({ kind: 'person', personId: p.id, name: p.name, photo: p.photo })
|
||||
const openNew = () => setAdding(true)
|
||||
const toSettings = () => {
|
||||
// Stables aussi : l'accueil et le catalogue (mémorisés) ne se redessinent pas à l'ouverture d'une fiche
|
||||
const openSeed = useCallback((seed: SearchResult) => pushLayer({ kind: 'title', seed }), [pushLayer])
|
||||
const openPerson = useCallback((p: { id: string; name?: string; photo?: string }) => pushLayer({ kind: 'person', personId: p.id, name: p.name, photo: p.photo }), [pushLayer])
|
||||
const openNew = useCallback(() => setAdding(true), [])
|
||||
const openRoulette = useCallback(() => setRoulette(true), [])
|
||||
const openCalendar = useCallback(() => setCalendar(true), [])
|
||||
/** « Valider » sur une fiche : ferme la recherche et toutes les fiches, puis revient à l'accueil */
|
||||
const backHome = () => {
|
||||
setLayers([])
|
||||
setAdding(false)
|
||||
setManual(null)
|
||||
// Laisse les fenêtres retirer leur entrée d'historique avant de changer d'onglet
|
||||
setTimeout(() => go('settings'), 50)
|
||||
setTimeout(() => go('home'), 50)
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
<SocialProvider onOpenOwnItem={openItem} onOpenSeed={openSeed}>
|
||||
@@ -95,44 +129,49 @@ export default function App() {
|
||||
<div className="mx-auto min-h-dvh max-w-2xl lg:max-w-none lg:ps-60">
|
||||
<main className="safe-top px-4 pb-32 lg:px-10 lg:pb-10 2xl:px-14">
|
||||
{error && <p className="mt-4 rounded-xl border border-accent p-3 text-sm text-ink">{error}</p>}
|
||||
{route === 'home' && <HomePage onOpen={openItem} onAdd={openNew} onNavigate={go} onRoulette={() => setRoulette(true)} onCalendar={() => setCalendar(true)} />}
|
||||
{route === 'home' && <HomePage onOpen={openItem} onAdd={openNew} onNavigate={go} onRoulette={openRoulette} onCalendar={openCalendar} onOpenSeed={openSeed} />}
|
||||
{route === 'catalog' && <CatalogPage onOpen={openItem} onAdd={openNew} />}
|
||||
{route === 'stats' && <StatsPage onOpen={openItem} />}
|
||||
{route === 'settings' && <SettingsPage onOpenAdmin={() => go('admin')} />}
|
||||
{route === 'admin' && <AdminPage onBack={() => go('settings')} />}
|
||||
<Suspense fallback={null}>
|
||||
{route === 'stats' && <StatsPage />}
|
||||
{route === 'settings' && <SettingsPage />}
|
||||
{route === 'notfound' && <NotFoundPage onHome={() => go('home')} />}
|
||||
</Suspense>
|
||||
</main>
|
||||
|
||||
<BottomNav current={navTab} onChange={go} onAdd={openNew} />
|
||||
<SyncIndicator />
|
||||
|
||||
<Suspense fallback={null}>
|
||||
{roulette && <Roulette onClose={() => setRoulette(false)} onOpen={openItem} />}
|
||||
{calendar && <CalendarView onClose={() => setCalendar(false)} onOpen={openItem} />}
|
||||
</Suspense>
|
||||
|
||||
{adding && (
|
||||
<Suspense fallback={null}>
|
||||
<AddTitle
|
||||
onClose={() => setAdding(false)}
|
||||
onPick={openSeed}
|
||||
onOpenItem={openItem}
|
||||
onOpenPerson={openPerson}
|
||||
onManual={(title) => setManual(title)}
|
||||
onGoToSettings={toSettings}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
{layers.map((l) =>
|
||||
l.kind === 'title' ? (
|
||||
<Suspense key={l.uid} fallback={null}>
|
||||
<TitleSheet
|
||||
key={l.uid}
|
||||
item={l.item}
|
||||
seed={l.seed}
|
||||
onClose={() => closeLayer(l.uid)}
|
||||
onGoToSettings={toSettings}
|
||||
onOpenPerson={openPerson}
|
||||
focus={l.item ? l.focus : undefined}
|
||||
onDone={backHome}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<Suspense key={l.uid} fallback={null}>
|
||||
<PersonSheet
|
||||
key={l.uid}
|
||||
personId={l.personId}
|
||||
name={l.name}
|
||||
photo={l.photo}
|
||||
@@ -140,9 +179,11 @@ export default function App() {
|
||||
onOpenItem={openItem}
|
||||
onOpenSeed={openSeed}
|
||||
/>
|
||||
</Suspense>
|
||||
),
|
||||
)}
|
||||
{manual !== null && (
|
||||
<Suspense fallback={null}>
|
||||
<EditDetails
|
||||
initialTitle={manual}
|
||||
onClose={() => setManual(null)}
|
||||
@@ -152,6 +193,7 @@ export default function App() {
|
||||
openItem(item)
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
</SocialProvider>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import App from './App'
|
||||
import AuthScreen, { NewPasswordScreen } from './components/AuthScreen'
|
||||
import AuthScreen, { MfaScreen, NewPasswordScreen } from './components/AuthScreen'
|
||||
import GuestPrompt, { GuestBanner } from './components/guest/GuestPrompt'
|
||||
import { consumeAuthRedirect, getSession, hasOAuthRedirect, onSessionChange, type Session } from './lib/cloud/auth'
|
||||
import { consumeAuthRedirect, getSession, hasOAuthRedirect, knownMfa, onSessionChange, pendingMfaFactor, sessionAal, type Session } from './lib/cloud/auth'
|
||||
import { cloudEnabled } from './lib/cloud/config'
|
||||
import { setScope } from './lib/scope'
|
||||
import { MediaProvider } from './store'
|
||||
@@ -40,12 +40,52 @@ export default function Root() {
|
||||
const [ask, setAsk] = useState(false)
|
||||
// Écran de connexion demandé depuis le mode découverte (« Se connecter » / « Créer un compte »)
|
||||
const [authMode, setAuthMode] = useState<'login' | 'signup'>('login')
|
||||
// Écran de connexion ouvert depuis le mode découverte : « retour » y ramène (au lieu de quitter le site)
|
||||
const [fromGuest, setFromGuest] = useState(false)
|
||||
const leaveGuest = (mode: 'login' | 'signup') => {
|
||||
writeGuest(false)
|
||||
setAsk(false)
|
||||
setAuthMode(mode)
|
||||
setFromGuest(true)
|
||||
setGuest(false)
|
||||
}
|
||||
const backToGuest = () => {
|
||||
writeGuest(true)
|
||||
setFromGuest(false)
|
||||
setGuest(true)
|
||||
}
|
||||
// Double authentification : un compte protégé doit saisir son code avant d'entrer.
|
||||
// Résultat de la vérification, rattaché au jeton vérifié : un nouveau jeton (connexion, code validé) est revérifié.
|
||||
const [mfa, setMfa] = useState<{ token: string; factor: string | null }>()
|
||||
// Réseau retrouvé : on revérifie (une session ouverte hors-ligne n'a pas pu l'être)
|
||||
const [onlineTick, setOnlineTick] = useState(0)
|
||||
useEffect(() => {
|
||||
const on = () => setOnlineTick((n) => n + 1)
|
||||
window.addEventListener('online', on)
|
||||
return () => window.removeEventListener('online', on)
|
||||
}, [])
|
||||
const accessToken = session?.accessToken
|
||||
useEffect(() => {
|
||||
if (!cloudEnabled || !accessToken || sessionAal() === 'aal2' || !navigator.onLine) return
|
||||
let alive = true
|
||||
pendingMfaFactor()
|
||||
.then((factor) => alive && setMfa({ token: accessToken, factor }))
|
||||
// Serveur injoignable : on laisse entrer (la base refuse de toute façon les données sans le code)
|
||||
.catch(() => alive && setMfa({ token: accessToken, factor: null }))
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [accessToken, onlineTick])
|
||||
// Calculé au rendu (pas d'effet) : l'app n'est jamais montée, même un instant, avant la vérification.
|
||||
// undefined = vérification en cours ; comptes connus sans double authentification : on entre tout de suite.
|
||||
const mfaFactor: string | null | undefined =
|
||||
!session || sessionAal() === 'aal2' || !navigator.onLine
|
||||
? null
|
||||
: mfa?.token === session.accessToken
|
||||
? mfa.factor
|
||||
: knownMfa() === false
|
||||
? null
|
||||
: undefined
|
||||
const userId = session?.user.id
|
||||
const userEmail = session?.user.email
|
||||
const user = useMemo(() => (userId ? { id: userId, email: userEmail ?? '' } : undefined), [userId, userEmail])
|
||||
@@ -97,6 +137,7 @@ export default function Root() {
|
||||
key={authMode}
|
||||
notice={notice}
|
||||
initialMode={authMode}
|
||||
onBack={fromGuest ? backToGuest : undefined}
|
||||
onExplore={() => {
|
||||
writeGuest(true)
|
||||
setGuest(true)
|
||||
@@ -105,6 +146,9 @@ export default function Root() {
|
||||
)
|
||||
}
|
||||
|
||||
if (mfaFactor === undefined) return <div className="min-h-dvh bg-bg" />
|
||||
if (mfaFactor) return <MfaScreen factorId={mfaFactor} />
|
||||
|
||||
// L'espace de stockage doit être choisi avant que le fournisseur de données ne lise quoi que ce soit
|
||||
setScope(session.user.id)
|
||||
return (
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import Avatar from './social/Avatar'
|
||||
import { useSocial } from './social/SocialProvider'
|
||||
import { t } from '../i18n'
|
||||
import { AlertTriangle, Check, CloudOff, KeyRound, Loader2, LogOut, RefreshCw, UserRound } from 'lucide-react'
|
||||
import { KeyRound, Loader2, LogOut, UserRound } from 'lucide-react'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { PASSWORD_MIN, updatePassword } from '../lib/cloud/auth'
|
||||
import { timeAgo } from '../lib/timeAgo'
|
||||
import type { AccountApi } from '../store'
|
||||
import { useSyncStatus, type AccountApi } from '../store'
|
||||
import ConfirmDialog from './ConfirmDialog'
|
||||
import { SectionTitle } from './ui'
|
||||
import { cx } from '../lib/utils'
|
||||
import TwoFactor from './TwoFactor'
|
||||
|
||||
/** Réglages → Mon compte : mot de passe, déconnexion. La synchro tourne en arrière-plan. */
|
||||
export default function AccountSection({ account, onMessage }: { account: AccountApi; onMessage: (kind: 'ok' | 'error', text: string) => void }) {
|
||||
const { sync } = account
|
||||
const sync = useSyncStatus() ?? { state: 'idle' as const, pending: 0 }
|
||||
const social = useSocial()
|
||||
const [pwOpen, setPwOpen] = useState(false)
|
||||
const [pw, setPw] = useState('')
|
||||
@@ -71,46 +70,6 @@ export default function AccountSection({ account, onMessage }: { account: Accoun
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* État de la synchronisation : visible, surtout quand quelque chose bloque */}
|
||||
<div className="flex items-center gap-3.5 px-4 py-3.5" role="status">
|
||||
<span className={cx('grid size-10 shrink-0 place-items-center rounded-full bg-surface-2', sync.state === 'error' ? 'text-accent' : 'text-ink-2')}>
|
||||
{sync.state === 'syncing' ? (
|
||||
<RefreshCw size={18} className="animate-spin" />
|
||||
) : sync.state === 'offline' ? (
|
||||
<CloudOff size={18} />
|
||||
) : sync.state === 'error' ? (
|
||||
<AlertTriangle size={18} />
|
||||
) : (
|
||||
<Check size={18} />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className={cx('block text-sm font-medium', sync.state === 'error' && 'text-accent')}>
|
||||
{sync.state === 'syncing'
|
||||
? t('sync.syncing')
|
||||
: sync.state === 'offline'
|
||||
? t('sync.offline')
|
||||
: sync.state === 'error'
|
||||
? t('sync.error')
|
||||
: sync.lastSyncAt
|
||||
? t('sync.synced', { when: timeAgo(sync.lastSyncAt) })
|
||||
: t('sync.never')}
|
||||
</span>
|
||||
{(sync.pending > 0 || (sync.state === 'error' && sync.error)) && (
|
||||
<span className="mt-0.5 block truncate text-xs text-ink-3">
|
||||
{[sync.pending > 0 ? t('sync.pending', { count: sync.pending }) : '', sync.state === 'error' ? sync.error : ''].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => void account.syncNow().catch(() => {})}
|
||||
disabled={sync.state === 'syncing' || sync.state === 'offline'}
|
||||
className="btn btn-ghost shrink-0 px-3 py-1.5 text-xs"
|
||||
>
|
||||
{t('sync.now')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())}
|
||||
className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2"
|
||||
@@ -155,6 +114,8 @@ export default function AccountSection({ account, onMessage }: { account: Accoun
|
||||
</button>
|
||||
)}
|
||||
|
||||
<TwoFactor onMessage={onMessage} />
|
||||
|
||||
<button onClick={() => logout(false)} disabled={busy === 'logout'} className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2">
|
||||
{busy === 'logout' ? <Loader2 size={19} className="animate-spin text-ink-2" /> : <LogOut size={19} className="text-ink-2" />}
|
||||
<span className="flex-1">
|
||||
|
||||
@@ -2,7 +2,8 @@ import { t } from '../i18n'
|
||||
import { LanguageSelect } from '../i18n/react'
|
||||
import { Eye, EyeOff, Loader2 } from 'lucide-react'
|
||||
import { useEffect, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signUp, updatePassword } from '../lib/cloud/auth'
|
||||
import { useBackToClose } from '../lib/backNav'
|
||||
import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signOut, signUp, updatePassword, verifyTotp } from '../lib/cloud/auth'
|
||||
import { USERNAME_RE } from '../lib/cloud/social'
|
||||
import { cx } from '../lib/utils'
|
||||
import { RANDOM_USERNAME } from './social/WelcomeProfile'
|
||||
@@ -33,10 +34,12 @@ function PasswordField({ value, onChange, placeholder, autoComplete }: { value:
|
||||
|
||||
function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }) {
|
||||
return (
|
||||
<div className="safe-top safe-bottom flex min-h-dvh flex-col items-center justify-center bg-bg px-5 py-10">
|
||||
// Marges du téléphone (encoche, barre d'accueil) à part : sinon elles remplaçaient l'espace du haut
|
||||
<div className="safe-top safe-bottom bg-bg">
|
||||
<div className="flex min-h-dvh flex-col items-center justify-center px-5 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<h1 className="text-center text-[2.4rem] font-bold leading-none">
|
||||
Ki<span className="text-accent">no</span>
|
||||
Bobin<span className="text-accent">oo</span>
|
||||
</h1>
|
||||
<p className="mt-3 text-center text-sm text-ink-3">{subtitle}</p>
|
||||
<div className="mt-9">{children}</div>
|
||||
@@ -45,11 +48,25 @@ function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Écran de connexion / inscription (affiché quand les comptes sont activés et qu'on n'est pas connecté). */
|
||||
export default function AuthScreen({ notice, onExplore, initialMode = 'login' }: { notice?: string; /** Mode découverte : regarder l'app sans compte */ onExplore?: () => void; initialMode?: 'login' | 'signup' }) {
|
||||
export default function AuthScreen({
|
||||
notice,
|
||||
onExplore,
|
||||
initialMode = 'login',
|
||||
onBack,
|
||||
}: {
|
||||
notice?: string
|
||||
/** Mode découverte : regarder l'app sans compte */
|
||||
onExplore?: () => void
|
||||
initialMode?: 'login' | 'signup'
|
||||
/** Ouvert depuis le mode découverte : le bouton « retour » du navigateur y ramène */
|
||||
onBack?: () => void
|
||||
}) {
|
||||
useBackToClose(() => onBack?.(), !!onBack)
|
||||
const [mode, setMode] = useState<Mode>(initialMode)
|
||||
const [email, setEmail] = useState('')
|
||||
const [username, setUsername] = useState('')
|
||||
@@ -203,11 +220,23 @@ export default function AuthScreen({ notice, onExplore, initialMode = 'login' }:
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Acceptation des conditions, avant de créer un compte (aussi valable pour « Continuer avec Google ») */}
|
||||
{mode !== 'forgot' && (
|
||||
<p className="text-center text-xs leading-relaxed text-ink-3">
|
||||
{t('auth.consent')}{' '}
|
||||
<a href="/terms.html" target="_blank" rel="noopener" className="underline underline-offset-2">
|
||||
{t('legal.terms')}
|
||||
</a>
|
||||
{' · '}
|
||||
<a href="/privacy.html" target="_blank" rel="noopener" className="underline underline-offset-2">
|
||||
{t('legal.privacy')}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={busy} className="btn btn-primary w-full py-3">
|
||||
{busy && <Loader2 size={17} className="animate-spin" />}
|
||||
{mode === 'login' ? t('auth.login') : mode === 'signup' ? t('auth.signup') : t('auth.sendLink')}
|
||||
</button>
|
||||
{mode === 'signup' && <p className="text-center text-xs leading-relaxed text-ink-3">{t('auth.consent')}</p>}
|
||||
</form>
|
||||
|
||||
{onExplore && mode !== 'forgot' && (
|
||||
@@ -279,13 +308,75 @@ export function NewPasswordScreen({ onDone }: { onDone: () => void }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Champ « code à 6 chiffres » (application d'authentification). */
|
||||
export function TotpField({ value, onChange, autoFocus }: { value: string; onChange: (v: string) => void; autoFocus?: boolean }) {
|
||||
return (
|
||||
<input
|
||||
className="field text-center text-xl tracking-[0.3em] tabular-nums placeholder:text-base placeholder:tracking-normal"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9 ]{6,7}"
|
||||
maxLength={7}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value.replace(/[^0-9 ]/g, ''))}
|
||||
placeholder={t('mfa.code')}
|
||||
aria-label={t('mfa.code')}
|
||||
autoFocus={autoFocus}
|
||||
required
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Connexion d'un compte protégé par la double authentification : code de l'application d'authentification. */
|
||||
export function MfaScreen({ factorId }: { factorId: string }) {
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
await verifyTotp(factorId, code)
|
||||
} catch (err) {
|
||||
setError((err as Error).message)
|
||||
setCode('')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Shell subtitle={t('mfa.title')}>
|
||||
<form onSubmit={submit} className="space-y-3">
|
||||
<p className="text-center text-sm text-ink-2">{t('mfa.loginText')}</p>
|
||||
<TotpField value={code} onChange={setCode} autoFocus />
|
||||
{error && (
|
||||
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" disabled={busy || code.replace(/\s/g, '').length !== 6} className="btn btn-primary w-full py-3">
|
||||
{busy && <Loader2 size={17} className="animate-spin" />}
|
||||
{t('mfa.confirm')}
|
||||
</button>
|
||||
<button type="button" onClick={() => void signOut()} className="w-full py-2 text-sm text-ink-3 underline underline-offset-4">
|
||||
{t('account.logout')}
|
||||
</button>
|
||||
</form>
|
||||
</Shell>
|
||||
)
|
||||
}
|
||||
|
||||
/** Liens vers les pages légales (statiques, hors de l'app). */
|
||||
export function LegalLinks() {
|
||||
return (
|
||||
<nav className="mt-4 flex flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] text-ink-3">
|
||||
<a href="/legal.html#conditions" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.terms')}</a>
|
||||
<a href="/terms.html" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.terms')}</a>
|
||||
<a href="/privacy.html" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.privacy')}</a>
|
||||
<a href="/legal.html#mentions" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.notice')}</a>
|
||||
<a href="/legal.html" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.notice')}</a>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -38,7 +38,7 @@ export default function BottomNav({ current, onChange, onAdd }: Props) {
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg/95 backdrop-blur-md lg:hidden">
|
||||
<nav className="bottom-nav safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg lg:hidden">
|
||||
<div className="mx-auto flex max-w-2xl items-center px-2">
|
||||
{ITEMS.slice(0, 2).map(button)}
|
||||
<div className="flex flex-1 justify-center">
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { locale, t } from '../i18n'
|
||||
import { dateFormat, locale, t } from '../i18n'
|
||||
import { Check, ChevronLeft, ChevronRight, Loader2, Plus, RefreshCw, X } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { loadAiring, refreshAiring, saveAiring } from '../lib/airing'
|
||||
import { findTmdbSeries, getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi'
|
||||
import type { GlobalRelease, ReleaseCategory } from '../lib/catalogApi'
|
||||
import { releaseToInput } from '../lib/releaseAdd'
|
||||
import { franchiseKey } from '../lib/franchise'
|
||||
import { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases'
|
||||
import { remotePosterToLocal } from '../lib/image'
|
||||
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
|
||||
import { readStorage } from '../lib/security'
|
||||
import { useBackToClose } from '../lib/backNav'
|
||||
@@ -14,12 +14,12 @@ import { useScrollLock } from '../lib/scrollLock'
|
||||
import { cx, normalizeText, todayISO } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
import { TYPE_BY_VALUE } from '../lib/constants'
|
||||
import type { MediaInput, MediaItem, MediaType } from '../types'
|
||||
import type { MediaItem, MediaType } from '../types'
|
||||
import { TypeBadge } from './Badges'
|
||||
import Poster from './Poster'
|
||||
|
||||
// Initiales des jours, du lundi au dimanche, dans la langue choisie (le 1er janvier 2024 est un lundi)
|
||||
const weekdays = () => Array.from({ length: 7 }, (_, k) => new Date(2024, 0, 1 + k).toLocaleDateString(locale(), { weekday: 'narrow' }))
|
||||
const weekdays = () => Array.from({ length: 7 }, (_, k) => dateFormat({ weekday: 'narrow' }).format(new Date(2024, 0, 1 + k)))
|
||||
const PER_DAY = 20
|
||||
const PREFS_KEY = 'azuucine:calendar-prefs'
|
||||
/** Jour local décalé de n jours (sans « + n × 24 h », faux aux changements d'heure). */
|
||||
@@ -29,7 +29,7 @@ const plusDays = (n: number) => {
|
||||
}
|
||||
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
const monthId = (d: Date) => iso(d).slice(0, 7)
|
||||
const niceDate = (d: string) => new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'long', day: 'numeric', month: 'long' })
|
||||
const niceDate = (d: string) => dateFormat({ weekday: 'long', day: 'numeric', month: 'long' }).format(new Date(d + 'T12:00:00'))
|
||||
|
||||
type Mode = 'all' | 'mine'
|
||||
|
||||
@@ -71,7 +71,7 @@ function EntryRow({ e, onOpen, onAdd, busy, added }: { e: Entry; onOpen: (i: Med
|
||||
)
|
||||
if (mine) {
|
||||
return (
|
||||
<button onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||
<button data-prefetch={e.item?.externalId} onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||
{body}
|
||||
<ChevronRight size={16} className="shrink-0 text-ink-3" />
|
||||
</button>
|
||||
@@ -307,34 +307,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
if (!r) return
|
||||
setBusy(e.key)
|
||||
try {
|
||||
let data: Partial<MediaInput> = {}
|
||||
let poster: string | undefined
|
||||
// Anime : on préfère la fiche TMDB, qui regroupe toutes les saisons (sinon chaque saison AniList ferait une fiche)
|
||||
const series = r.externalId.startsWith('anilist:') && hasKey ? await findTmdbSeries([r.title, r.originalTitle], settings.tmdbKey!).catch(() => undefined) : undefined
|
||||
if (series) {
|
||||
data = await getTmdbDetails(series, settings.tmdbKey!)
|
||||
poster = series.posterUrl ? await remotePosterToLocal(series.posterUrl) : undefined
|
||||
} else if (r.externalId.startsWith('anilist:')) {
|
||||
const res = await getAniListById(r.externalId)
|
||||
data = { ...res?.prefill }
|
||||
poster = res?.posterUrl ?? r.poster
|
||||
} else {
|
||||
const res = releaseToResult(r)
|
||||
if (res && hasKey) data = await getTmdbDetails(res, settings.tmdbKey!)
|
||||
poster = r.poster ? await remotePosterToLocal(r.poster) : undefined
|
||||
}
|
||||
await add({
|
||||
title: r.title,
|
||||
type: r.cat,
|
||||
status: 'a_voir',
|
||||
criteria: {},
|
||||
episodesWatched: 0,
|
||||
genres: [],
|
||||
year: r.year,
|
||||
externalId: r.externalId,
|
||||
...data,
|
||||
poster,
|
||||
})
|
||||
await add(await releaseToInput(r, settings.tmdbKey))
|
||||
setAdded((s) => new Set(s).add(r.externalId))
|
||||
} catch {
|
||||
/* réseau : le bouton reste disponible */
|
||||
@@ -416,7 +389,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
<button onClick={() => changeMonth(-1)} className="grid size-9 place-items-center rounded-full border border-line text-ink-2" aria-label={t('calendar.prevMonth')}>
|
||||
<ChevronLeft size={18} />
|
||||
</button>
|
||||
<span className="text-lg font-bold capitalize">{month.toLocaleDateString(locale(), { month: 'long', year: 'numeric' })}</span>
|
||||
<span className="text-lg font-bold capitalize">{dateFormat({ month: 'long', year: 'numeric' }).format(month)}</span>
|
||||
<button onClick={() => changeMonth(1)} className="grid size-9 place-items-center rounded-full border border-line text-ink-2" aria-label={t('calendar.nextMonth')}>
|
||||
<ChevronRight size={18} />
|
||||
</button>
|
||||
|
||||
@@ -10,10 +10,12 @@ interface Props {
|
||||
confirmLabel?: string
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
/** Action irréversible (effacer, supprimer, bloquer…) : bouton rouge */
|
||||
danger?: boolean
|
||||
}
|
||||
|
||||
/** Fenêtre « Êtes-vous sûr ? » intégrée à l'app (plus fiable que window.confirm sur mobile). */
|
||||
export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel }: Props) {
|
||||
export default function ConfirmDialog({ open, title, message, confirmLabel = t('common.confirm'), onConfirm, onCancel, danger }: Props) {
|
||||
useEscape(onCancel, open)
|
||||
useBackToClose(onCancel, open)
|
||||
const titleId = useId()
|
||||
@@ -36,7 +38,7 @@ export default function ConfirmDialog({ open, title, message, confirmLabel = t('
|
||||
<button onClick={onCancel} className="btn btn-ghost" autoFocus>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button onClick={onConfirm} className="btn btn-primary">
|
||||
<button onClick={onConfirm} className={danger ? 'btn bg-danger text-on-danger' : 'btn btn-primary'}>
|
||||
{confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Check, Loader2, Lock } from 'lucide-react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { locale, t } from '../i18n'
|
||||
import { getTmdbSeasonEpisodes, type EpisodeInfo } from '../lib/catalogApi'
|
||||
import { dateFormat, t } from '../i18n'
|
||||
import { cachedSeasonEpisodes, episodeWindow, getTmdbSeasonEpisodes, preloadImages, type EpisodeInfo } from '../lib/catalogApi'
|
||||
import { episodeCap, episodesBeforeSeason, seasonPosition } from '../lib/franchise'
|
||||
import { tmdbSized } from '../lib/tmdbImage'
|
||||
import { cx, todayISO } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
import type { MediaInput } from '../types'
|
||||
@@ -13,6 +14,8 @@ interface Props {
|
||||
aired?: number
|
||||
/** Nouveau nombre d'épisodes vus (et saison choisie) */
|
||||
onChange: (episodesWatched: number, season?: number) => void
|
||||
/** Grande image de la série : vignette des épisodes qui n'ont pas la leur */
|
||||
fallbackImage?: string
|
||||
}
|
||||
|
||||
const MAX_GENERIC = 500
|
||||
@@ -21,7 +24,7 @@ const MAX_GENERIC = 500
|
||||
* Liste des épisodes, saison par saison (façon plateforme de streaming).
|
||||
* Toucher un épisode le marque comme vu, ainsi que tous ceux d'avant ; retoucher le dernier vu l'annule.
|
||||
*/
|
||||
export default function EpisodeList({ form, aired, onChange }: Props) {
|
||||
export default function EpisodeList({ form, aired, onChange, fallbackImage }: Props) {
|
||||
const { settings } = useMedia()
|
||||
const seasons = form.seasons
|
||||
const pos = seasonPosition(form)
|
||||
@@ -32,7 +35,8 @@ export default function EpisodeList({ form, aired, onChange }: Props) {
|
||||
if (current) setViewSeason(current)
|
||||
}, [current])
|
||||
const viewSeason = seasons ? Math.min(Math.max(1, picked), seasons.length) : 1
|
||||
const [episodes, setEpisodes] = useState<EpisodeInfo[]>()
|
||||
// Liste reçue pour une saison donnée ; en attendant, la copie gardée sur l'appareil s'affiche tout de suite
|
||||
const [fetched, setFetched] = useState<{ key: string; list: EpisodeInfo[] }>()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const today = todayISO()
|
||||
@@ -46,23 +50,37 @@ export default function EpisodeList({ form, aired, onChange }: Props) {
|
||||
const extra = seasons && viewSeason === seasons.length ? Math.max(0, (episodeCap(form) ?? 0) - episodesBeforeSeason(seasons, seasons.length + 1)) : 0
|
||||
const size = seasons ? Math.min((seasons[viewSeason - 1] ?? 0) + extra, MAX_GENERIC) : Math.min(episodeCap(form) ?? 0, MAX_GENERIC)
|
||||
|
||||
const seasonNum = seasons ? viewSeason : 1
|
||||
const listKey = `${form.externalId}:${seasonNum}`
|
||||
const known = isTmdb ? cachedSeasonEpisodes(form.externalId, seasonNum) : undefined
|
||||
const shownList = fetched?.key === listKey ? fetched.list : known
|
||||
const episodes = shownList?.length ? shownList : undefined
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTmdb || !navigator.onLine) return setEpisodes(undefined)
|
||||
if (!isTmdb || !navigator.onLine) return
|
||||
let alive = true
|
||||
setLoading(true)
|
||||
getTmdbSeasonEpisodes(form.externalId!, seasons ? viewSeason : 1, key!)
|
||||
.then((list) => alive && setEpisodes(list.length ? list : undefined))
|
||||
.catch(() => alive && setEpisodes(undefined))
|
||||
// Indicateur seulement quand rien n'est encore affiché (sinon la liste gardée est remplacée sans bruit)
|
||||
if (!cachedSeasonEpisodes(form.externalId, seasonNum)?.length) setLoading(true)
|
||||
getTmdbSeasonEpisodes(form.externalId!, seasonNum, key!)
|
||||
.then((list) => alive && setFetched({ key: `${form.externalId}:${seasonNum}`, list }))
|
||||
.catch(() => {})
|
||||
.finally(() => alive && setLoading(false))
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [isTmdb, form.externalId, viewSeason, seasons, key])
|
||||
}, [isTmdb, form.externalId, seasonNum, key])
|
||||
|
||||
// Les infos TMDB complètent la liste ; sans elles (AniList, hors-ligne), on numérote simplement
|
||||
const count = Math.max(size, seasons ? 0 : (episodes?.length ?? 0))
|
||||
const rows: EpisodeInfo[] = Array.from({ length: count }, (_, k) => episodes?.find((e) => e.number === k + 1) ?? { number: k + 1 })
|
||||
const byNumber = new Map(episodes?.map((e) => [e.number, e]))
|
||||
const rows: EpisodeInfo[] = Array.from({ length: count }, (_, k) => byNumber.get(k + 1) ?? { number: k + 1 })
|
||||
const watchedHere = Math.max(0, Math.min(count, form.episodesWatched - before))
|
||||
// Épisodes visibles à l'ouverture (autour du prochain à voir) : images demandées tout de suite
|
||||
const visible = new Set(episodeWindow(rows, watchedHere + 1).map((e) => e.number))
|
||||
useEffect(() => {
|
||||
if (episodes) preloadImages(episodeWindow(episodes, watchedHere + 1).map((e) => e.still))
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [episodes])
|
||||
|
||||
// Ouvre la liste au niveau du prochain épisode à voir
|
||||
useLayoutEffect(() => {
|
||||
@@ -78,7 +96,7 @@ export default function EpisodeList({ form, aired, onChange }: Props) {
|
||||
onChange(Math.max(0, next), seasons ? viewSeason : undefined)
|
||||
}
|
||||
|
||||
const fmtDate = (d: string) => new Date(`${d}T12:00:00`).toLocaleDateString(locale(), { day: 'numeric', month: 'short', year: d.slice(0, 4) === today.slice(0, 4) ? undefined : 'numeric' })
|
||||
const fmtDate = (d: string) => dateFormat(d.slice(0, 4) === today.slice(0, 4) ? { day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short', year: 'numeric' }).format(new Date(`${d}T12:00:00`))
|
||||
|
||||
if (!count) return null
|
||||
|
||||
@@ -107,7 +125,7 @@ export default function EpisodeList({ form, aired, onChange }: Props) {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div ref={listRef} className="max-h-[26rem] space-y-1 overflow-y-auto lg:max-h-[60vh] overscroll-contain pe-1">
|
||||
<div ref={listRef} className="max-h-[26rem] space-y-1 overflow-y-auto lg:max-h-[60vh] pe-1">
|
||||
{rows.map((e) => {
|
||||
const seen = e.number <= watchedHere
|
||||
// Pas encore sorti : date à venir (TMDB), ou au-delà des épisodes diffusés
|
||||
@@ -122,11 +140,17 @@ export default function EpisodeList({ form, aired, onChange }: Props) {
|
||||
onClick={() => toggle(e.number)}
|
||||
disabled={locked}
|
||||
aria-pressed={seen}
|
||||
className={cx('flex w-full items-center gap-3 rounded-xl p-1.5 text-start transition-colors', locked ? 'cursor-not-allowed' : 'active:bg-surface-2', upcoming && 'opacity-50')}
|
||||
className={cx('ep-row flex w-full items-center gap-3 rounded-xl p-1.5 text-start transition-colors', locked ? 'cursor-not-allowed' : 'active:bg-surface-2', upcoming && 'opacity-50')}
|
||||
>
|
||||
<span className="relative aspect-video w-28 shrink-0 overflow-hidden rounded-lg border border-line bg-surface-2">
|
||||
{e.still ? (
|
||||
<img src={e.still} alt="" loading="lazy" className="size-full object-cover" />
|
||||
<img src={e.still} alt="" loading={visible.has(e.number) ? 'eager' : 'lazy'} decoding="async" className="size-full object-cover" />
|
||||
) : fallbackImage ? (
|
||||
// Pas d'image pour cet épisode : celle de la série, assombrie, avec le numéro par-dessus
|
||||
<>
|
||||
<img src={tmdbSized(fallbackImage, 'w300')} alt="" loading="lazy" decoding="async" className="size-full object-cover" />
|
||||
<span className="absolute inset-0 grid place-items-center bg-black/50 text-base font-bold text-white">{e.number}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="grid size-full place-items-center text-sm font-semibold text-ink-3">{e.number}</span>
|
||||
)}
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react'
|
||||
import { Component, type ReactNode } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { reportError } from '../lib/errorReporter'
|
||||
|
||||
/** Fichier d'un écran introuvable : une nouvelle version a été mise en ligne pendant que l'app était ouverte. */
|
||||
const isOutdatedFile = (e: unknown) =>
|
||||
/Importing a module script failed|Failed to fetch dynamically imported module|error loading dynamically imported module|Unable to preload CSS/i.test(
|
||||
String((e as Error)?.message ?? e),
|
||||
)
|
||||
|
||||
/** Recharge l'app une seule fois par minute (jamais en boucle si le problème est ailleurs). */
|
||||
function reloadOnce(): boolean {
|
||||
const KEY = 'azuucine:reloaded-at'
|
||||
try {
|
||||
const last = Number(sessionStorage.getItem(KEY) ?? 0)
|
||||
if (Date.now() - last < 60_000) return false
|
||||
sessionStorage.setItem(KEY, String(Date.now()))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
location.reload()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Filet de sécurité global : si l'affichage plante, on montre un écran propre
|
||||
* (« Oups… ») au lieu d'une page blanche, et l'erreur est remontée (sans donnée perso).
|
||||
* Filet de sécurité global : si l'affichage plante, on montre un écran propre (« Oups… ») au lieu d'une page blanche.
|
||||
* Cas fréquent après une mise à jour : l'ancienne version ouverte cherche un fichier qui n'existe plus →
|
||||
* l'app se recharge d'elle-même sur la nouvelle version.
|
||||
*/
|
||||
export default class ErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
|
||||
state = { failed: false }
|
||||
@@ -13,8 +33,8 @@ export default class ErrorBoundary extends Component<{ children: ReactNode }, {
|
||||
return { failed: true }
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: ErrorInfo) {
|
||||
reportError(error, 'render', info.componentStack ?? '')
|
||||
componentDidCatch(error: unknown) {
|
||||
if (isOutdatedFile(error)) reloadOnce()
|
||||
}
|
||||
|
||||
render() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Completion } from '../lib/seasons'
|
||||
import { Check, Info, Plus } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { TYPE_BY_VALUE } from '../lib/constants'
|
||||
import { canWatchMore, nextAirDate } from '../lib/airing'
|
||||
@@ -9,10 +9,11 @@ import { progressView } from '../lib/rewatch'
|
||||
import { genreLabel } from '../lib/genres'
|
||||
import { backdropSrcSet, tmdbSized } from '../lib/tmdbImage'
|
||||
import { cx, formatDate } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
import { useMediaActions } from '../store'
|
||||
import { useToast } from './Toast'
|
||||
import { FilmStrip } from './ui'
|
||||
import type { MediaItem } from '../types'
|
||||
import { prefetchAttrs } from '../lib/prefetch'
|
||||
|
||||
/** Où j'en suis : « S2 · É3 » (épisode suivant à voir) */
|
||||
export function nextEpisodeLabel(item: MediaItem): string | undefined {
|
||||
@@ -34,20 +35,24 @@ export function waitingLabel(item: MediaItem): string {
|
||||
function stripProgress(item: MediaItem): { done: number; total: number } | undefined {
|
||||
if (!TYPE_BY_VALUE[item.type].episodic) return undefined
|
||||
const view = progressView(item)
|
||||
// Saison de l'épisode suivant (saison finie : on montre la suivante à 0, pas « 9/9 »)
|
||||
const cap = episodeCap(view)
|
||||
const next = !cap || view.episodesWatched < cap ? seasonPosition({ ...view, episodesWatched: view.episodesWatched + 1, season: undefined }) : undefined
|
||||
if (next) return { done: next.episode - 1, total: next.size }
|
||||
const pos = seasonPosition(view)
|
||||
if (pos) return { done: pos.episode, total: pos.size }
|
||||
const cap = episodeCap(view)
|
||||
return cap ? { done: Math.min(view.episodesWatched, cap), total: cap } : undefined
|
||||
}
|
||||
|
||||
/** +1 depuis l'accueil : saison (ou série) finie → on ouvre la fiche sur la note ; revisionnage fini → petit message. */
|
||||
function usePlusOne(onOpen: (item: MediaItem, focus?: Completion) => void) {
|
||||
const { incrementEpisode } = useMedia()
|
||||
const { incrementEpisode } = useMediaActions()
|
||||
const toast = useToast()
|
||||
return (item: MediaItem) => {
|
||||
const cap = episodeCap(item)
|
||||
const endsRewatch = !!item.rewatch && !!cap && item.rewatch.episodes + 1 >= cap
|
||||
return incrementEpisode(item.id).then((done) => {
|
||||
if (done === false) return
|
||||
if (done) onOpen(item, done)
|
||||
else if (endsRewatch) toast.show(t('rewatch.finishedToast', { title: item.title }))
|
||||
})
|
||||
@@ -59,30 +64,74 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
||||
const plusOne = usePlusOne(onOpen)
|
||||
// On retient le titre affiché (et pas sa position) : la liste se réordonne quand on avance un épisode
|
||||
const [currentId, setCurrentId] = useState<string>()
|
||||
// Titre affiché juste avant : son image reste le temps du fondu
|
||||
const [previousId, setPreviousId] = useState<string>()
|
||||
const [pausedAt, setPausedAt] = useState(0)
|
||||
const touchX = useRef<number | null>(null)
|
||||
const section = useRef<HTMLElement>(null)
|
||||
const images = useRef(new Map<string, HTMLImageElement>())
|
||||
const count = items.length
|
||||
const current = Math.max(0, items.findIndex((i) => i.id === currentId))
|
||||
const item = items[current]
|
||||
const latest = useRef(items)
|
||||
latest.current = items
|
||||
const shownId = useRef(item?.id)
|
||||
shownId.current = item?.id
|
||||
|
||||
// Défilement automatique (toutes les 7 s), relancé après chaque action manuelle
|
||||
const show = (id: string | undefined) => {
|
||||
setPreviousId(shownId.current)
|
||||
setCurrentId(id)
|
||||
}
|
||||
|
||||
// Défilement automatique (toutes les 7 s), relancé après chaque action manuelle.
|
||||
// Pas de défilement si la bannière n'est pas à l'écran, ni si l'appareil demande moins d'animations.
|
||||
useEffect(() => {
|
||||
if (count < 2) return
|
||||
if (count < 2 || matchMedia('(prefers-reduced-motion: reduce)').matches) return
|
||||
let onScreen = true
|
||||
const io = new IntersectionObserver(([e]) => (onScreen = e.isIntersecting))
|
||||
if (section.current) io.observe(section.current)
|
||||
let cancelled = false
|
||||
const timer = setInterval(() => {
|
||||
if (document.visibilityState !== 'visible') return
|
||||
setCurrentId((id) => {
|
||||
if (document.visibilityState !== 'visible' || !onScreen) return
|
||||
const list = latest.current
|
||||
const k = Math.max(0, list.findIndex((i) => i.id === id))
|
||||
return list[(k + 1) % list.length]?.id
|
||||
const k = Math.max(0, list.findIndex((i) => i.id === shownId.current))
|
||||
const nextId = list[(k + 1) % list.length]?.id
|
||||
// L'image suivante est décodée avant d'être montrée (pas d'image à moitié affichée)
|
||||
const img = nextId ? images.current.get(nextId) : undefined
|
||||
void (img ? img.decode().catch(() => {}) : Promise.resolve()).then(() => {
|
||||
if (!cancelled) show(nextId)
|
||||
})
|
||||
}, 7000)
|
||||
return () => clearInterval(timer)
|
||||
return () => {
|
||||
cancelled = true
|
||||
clearInterval(timer)
|
||||
io.disconnect()
|
||||
}
|
||||
}, [count, pausedAt])
|
||||
|
||||
// Un titre sur deux lignes faisait sauter tout le bas de la bannière au défilement : si l'un des titres
|
||||
// en a besoin, la place de deux lignes est réservée pour tous (sinon, pas d'espace vide sous un titre court)
|
||||
const titleRef = useRef<HTMLHeadingElement>(null)
|
||||
const [twoLines, setTwoLines] = useState(false)
|
||||
const titles = items.map((i) => i.title).join('\n')
|
||||
useLayoutEffect(() => {
|
||||
const h = titleRef.current
|
||||
const ctx = h && document.createElement('canvas').getContext('2d')
|
||||
if (!h || !ctx) return
|
||||
const measure = () => {
|
||||
const cs = getComputedStyle(h)
|
||||
ctx.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`
|
||||
setTwoLines(titles.split('\n').some((title) => ctx.measureText(title).width > h.clientWidth))
|
||||
}
|
||||
measure()
|
||||
void document.fonts?.ready.then(measure)
|
||||
const ro = new ResizeObserver(measure)
|
||||
ro.observe(h)
|
||||
return () => ro.disconnect()
|
||||
}, [titles])
|
||||
|
||||
const go = (k: number) => {
|
||||
setCurrentId(items[((k % count) + count) % count]?.id)
|
||||
show(items[((k % count) + count) % count]?.id)
|
||||
setPausedAt(Date.now())
|
||||
}
|
||||
|
||||
@@ -95,9 +144,13 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
||||
|
||||
return (
|
||||
<section
|
||||
className="card overflow-hidden lg:grid lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]"
|
||||
ref={section}
|
||||
className="lg:grid lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)] lg:gap-8"
|
||||
aria-roledescription="carousel"
|
||||
onTouchStart={(e) => (touchX.current = e.touches[0].clientX)}
|
||||
onTouchStart={(e) => {
|
||||
touchX.current = e.touches[0].clientX
|
||||
setPausedAt(Date.now()) // pas de défilement automatique sous le doigt
|
||||
}}
|
||||
onTouchEnd={(e) => {
|
||||
const start = touchX.current
|
||||
touchX.current = null
|
||||
@@ -106,17 +159,24 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
||||
if (Math.abs(dx) > 45) go(current + (dx < 0 ? 1 : -1))
|
||||
}}
|
||||
>
|
||||
<button onClick={() => onOpen(item)} className="relative block aspect-video w-full overflow-hidden bg-surface-2 lg:aspect-auto lg:h-full lg:min-h-[22rem]" aria-label={t('card.open', { title: item.title })}>
|
||||
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="relative block aspect-video w-full overflow-hidden bg-surface-2 lg:aspect-auto lg:h-full lg:min-h-[22rem]" aria-label={t('card.open', { title: item.title })}>
|
||||
{items.map((it, k) => {
|
||||
const image = it.backdrop ?? it.poster
|
||||
return image ? (
|
||||
// Seules l'image affichée, la suivante (préparée) et la précédente (fondu) sont chargées
|
||||
const kept = k === current || k === (current + 1) % count || it.id === previousId
|
||||
return image && kept ? (
|
||||
<img
|
||||
key={it.id}
|
||||
ref={(el) => {
|
||||
if (el) images.current.set(it.id, el)
|
||||
else images.current.delete(it.id)
|
||||
}}
|
||||
src={it.backdrop ? tmdbSized(image, 'w1280') : image}
|
||||
srcSet={it.backdrop ? backdropSrcSet(image) : undefined}
|
||||
sizes="(min-width: 64rem) 60vw, 100vw"
|
||||
alt=""
|
||||
loading={k === 0 ? 'eager' : 'lazy'}
|
||||
decoding={k === current ? 'auto' : 'async'}
|
||||
fetchPriority={k === current ? 'high' : 'low'}
|
||||
className={cx(
|
||||
'absolute inset-0 size-full object-cover transition-opacity duration-500 motion-reduce:transition-none',
|
||||
!it.backdrop && 'scale-110 blur-md',
|
||||
@@ -126,14 +186,14 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
||||
) : null
|
||||
})}
|
||||
</button>
|
||||
<div className="flex min-w-0 flex-col p-4 sm:p-5 lg:p-8">
|
||||
<div className="flex min-w-0 flex-col pt-4 lg:py-2">
|
||||
<p className="flex flex-wrap gap-x-3 gap-y-0.5 text-sm text-ink-3">
|
||||
<span className="font-medium text-accent">{state}</span>
|
||||
{meta.map((m) => (
|
||||
<span key={m}>{m}</span>
|
||||
))}
|
||||
</p>
|
||||
<h2 className="mt-1.5 line-clamp-2 text-[1.9rem] leading-[1.08] lg:text-[2.5rem]">{item.title}</h2>
|
||||
<h2 ref={titleRef} className={cx('mt-1.5 line-clamp-2 text-[1.9rem] leading-[1.08] lg:text-[2.5rem]', twoLines && 'min-h-[2.16em]')}>{item.title}</h2>
|
||||
{progress && (
|
||||
<div className="mt-4">
|
||||
<div className="flex items-baseline justify-between gap-3 text-sm text-ink-2">
|
||||
@@ -160,7 +220,7 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
||||
<Check size={17} /> {waitingLabel(item)}
|
||||
</span>
|
||||
) : null}
|
||||
<button onClick={() => onOpen(item)} className="btn btn-ghost px-4">
|
||||
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="btn btn-ghost px-4">
|
||||
<Info size={17} /> {t('homeHero.details')}
|
||||
</button>
|
||||
</div>
|
||||
@@ -174,7 +234,7 @@ export default function HomeHero({ items, onOpen }: { items: MediaItem[]; onOpen
|
||||
aria-label={it.title}
|
||||
aria-current={k === current}
|
||||
>
|
||||
<span className={cx('block h-[3px] rounded-[1px] transition-all motion-reduce:transition-none', k === current ? 'w-6 bg-ink' : 'w-3 bg-line-strong')} />
|
||||
<span className={cx('block h-[3px] rounded-[1px] transition-colors motion-reduce:transition-none', k === current ? 'w-6 bg-ink' : 'w-3 bg-line-strong')} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -192,8 +252,8 @@ export function ContinueCard({ item, onOpen }: { item: MediaItem; onOpen: (item:
|
||||
|
||||
return (
|
||||
<article className="flex h-[5.5rem] w-72 shrink-0 overflow-hidden rounded-md border border-line bg-surface">
|
||||
<button onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-stretch text-start" aria-label={t('card.open', { title: item.title })}>
|
||||
<span className="block w-[3.6rem] shrink-0 bg-surface-2">{image && <img src={image} alt="" loading="lazy" className="size-full object-cover" />}</span>
|
||||
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-stretch text-start" aria-label={t('card.open', { title: item.title })}>
|
||||
<span className="block w-[3.6rem] shrink-0 bg-surface-2">{image && <img src={image} alt="" loading="lazy" decoding="async" className="size-full object-cover" />}</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col justify-center px-3">
|
||||
<span className="block truncate font-bold text-base leading-tight">{item.title}</span>
|
||||
<span className="mt-0.5 block truncate text-xs text-ink-3">
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Check, Loader2, Search } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { t, type TKey } from '../i18n'
|
||||
import { searchAll, type SearchResult } from '../lib/catalogApi'
|
||||
import { matchFor, type Match } from '../lib/import/resolve'
|
||||
import type { TextEntry } from '../lib/import/textList'
|
||||
import { cx } from '../lib/utils'
|
||||
import Poster from './Poster'
|
||||
import { RatingBadge } from './Rating'
|
||||
|
||||
/**
|
||||
* Vérification d'une liste collée : chaque ligne avec le titre trouvé.
|
||||
* On peut décocher une ligne, ou choisir un autre titre (recherche intégrée).
|
||||
*/
|
||||
export default function ImportTextReview({
|
||||
entries,
|
||||
matches,
|
||||
unsure,
|
||||
excluded,
|
||||
tmdbKey,
|
||||
onToggle,
|
||||
onChange,
|
||||
onContinue,
|
||||
}: {
|
||||
entries: TextEntry[]
|
||||
matches: Map<string, Match>
|
||||
unsure: Set<string>
|
||||
excluded: Set<string>
|
||||
tmdbKey?: string
|
||||
onToggle: (key: string) => void
|
||||
onChange: (key: string, match: Match) => void
|
||||
onContinue: () => void
|
||||
}) {
|
||||
const [editing, setEditing] = useState<string>()
|
||||
const kept = entries.filter((e) => !excluded.has(e.key) && matches.has(e.key)).length
|
||||
const toCheck = entries.filter((e) => !excluded.has(e.key) && (unsure.has(e.key) || !matches.has(e.key))).length
|
||||
// Les lignes à vérifier d'abord
|
||||
const ordered = [...entries].sort((a, b) => rank(a) - rank(b))
|
||||
function rank(e: TextEntry) {
|
||||
return !matches.has(e.key) ? 0 : unsure.has(e.key) ? 1 : 2
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<p className="text-sm text-ink-2">{t('import.text.reviewHint')}</p>
|
||||
{toCheck > 0 && <p className="mt-2 text-sm font-medium text-ink">{t('import.text.toCheck', { n: toCheck })}</p>}
|
||||
<ul className="mt-4 divide-y divide-line border-y border-line">
|
||||
{ordered.map((e) => {
|
||||
const m = matches.get(e.key)
|
||||
const off = excluded.has(e.key)
|
||||
const doubt = !m || unsure.has(e.key)
|
||||
return (
|
||||
<li key={e.key} className="py-3">
|
||||
<div className={cx('flex items-start gap-3', off && 'opacity-45')}>
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={!off && !!m}
|
||||
disabled={!m}
|
||||
onClick={() => onToggle(e.key)}
|
||||
aria-label={e.line}
|
||||
className={cx(
|
||||
'mt-1 grid size-6 shrink-0 place-items-center rounded-[2px] border',
|
||||
!off && m ? 'border-accent bg-accent-fill text-on-accent' : 'border-line-strong bg-surface',
|
||||
)}
|
||||
>
|
||||
{!off && m && <Check size={15} strokeWidth={3} />}
|
||||
</button>
|
||||
<div className="w-11 shrink-0">
|
||||
<Poster src={m?.result.thumb ?? m?.result.posterUrl} title={m?.result.title ?? e.title} className="rounded-[2px]" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-xs text-ink-3">{e.line}</p>
|
||||
{m ? (
|
||||
<p className="mt-0.5 font-semibold leading-snug">
|
||||
{m.result.title}
|
||||
<span className="font-normal text-ink-3">
|
||||
{' · '}
|
||||
{t(`type.${m.meta.type ?? m.result.typeGuess}` as TKey)}
|
||||
{m.result.year ? ` · ${m.result.year}` : ''}
|
||||
</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-0.5 font-semibold text-ink-2">{t('import.text.none')}</p>
|
||||
)}
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-2">
|
||||
<span>{t(`status.${e.status}` as TKey)}</span>
|
||||
<RatingBadge value={e.rating} />
|
||||
{e.notes && <span className="min-w-0 max-w-full truncate italic">« {e.notes} »</span>}
|
||||
</div>
|
||||
<div className="mt-1.5 flex items-center gap-3">
|
||||
{doubt && m && !off && <span className="text-xs font-semibold text-danger">{t('import.text.check')}</span>}
|
||||
<button type="button" onClick={() => setEditing(editing === e.key ? undefined : e.key)} className="text-xs font-semibold text-accent underline underline-offset-2">
|
||||
{m ? t('import.text.change') : t('import.text.search')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{editing === e.key && (
|
||||
<Picker
|
||||
initial={e.fullTitle ?? e.title}
|
||||
progressSeason={e.progress?.season}
|
||||
tmdbKey={tmdbKey}
|
||||
onPick={(match) => {
|
||||
onChange(e.key, match)
|
||||
setEditing(undefined)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
<button onClick={onContinue} disabled={kept === 0} className="btn btn-primary mt-6 w-full">
|
||||
{t('import.continue')} ({kept})
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/** Recherche d'un autre titre pour une ligne. */
|
||||
function Picker({ initial, progressSeason, tmdbKey, onPick }: { initial: string; progressSeason?: number; tmdbKey?: string; onPick: (m: Match) => void }) {
|
||||
const [q, setQ] = useState(initial)
|
||||
const [results, setResults] = useState<SearchResult[]>()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
|
||||
const run = async () => {
|
||||
const query = q.trim()
|
||||
if (!query || busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
setResults((await searchAll(query, tmdbKey?.trim() || undefined)).slice(0, 8))
|
||||
} catch (err) {
|
||||
setError((err as Error)?.message || t('search.offline'))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const pick = async (r: SearchResult) => {
|
||||
setBusy(true)
|
||||
try {
|
||||
onPick(await matchFor(r, tmdbKey?.trim() || undefined, progressSeason))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-3 rounded-[2px] border border-line bg-surface-2 p-3">
|
||||
<form
|
||||
className="flex gap-2"
|
||||
onSubmit={(ev) => {
|
||||
ev.preventDefault()
|
||||
void run()
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className="field min-w-0 flex-1"
|
||||
value={q}
|
||||
onChange={(ev) => setQ(ev.target.value.slice(0, 200))}
|
||||
aria-label={t('import.text.search')}
|
||||
enterKeyHint="search"
|
||||
autoFocus
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary px-4" disabled={busy || !q.trim()} aria-label={t('import.text.search')}>
|
||||
{busy ? <Loader2 size={18} className="animate-spin" /> : <Search size={18} />}
|
||||
</button>
|
||||
</form>
|
||||
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
|
||||
{results && !results.length && <p className="mt-2 text-sm text-ink-2">{t('import.text.none')}</p>}
|
||||
{results && results.length > 0 && (
|
||||
<ul className="mt-2 divide-y divide-line">
|
||||
{results.map((r) => (
|
||||
<li key={r.externalId}>
|
||||
<button type="button" disabled={busy} onClick={() => void pick(r)} className="flex w-full items-center gap-3 py-2 text-start">
|
||||
<div className="w-9 shrink-0">
|
||||
<Poster src={r.thumb ?? r.posterUrl} title={r.title} className="rounded-[2px]" />
|
||||
</div>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-semibold">{r.title}</span>
|
||||
<span className="block text-xs text-ink-3">
|
||||
{t(`type.${r.typeGuess}` as TKey)}
|
||||
{r.year ? ` · ${r.year}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,10 +2,12 @@ import { ArrowLeft, Check, ChevronDown, FileUp, Loader2, X } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'
|
||||
import { t, type TKey } from '../i18n'
|
||||
import { useBackToClose } from '../lib/backNav'
|
||||
import ImportTextReview from './ImportTextReview'
|
||||
import { useEscape } from '../lib/escape'
|
||||
import { ImportFileError, readImportFile, type TextFile } from '../lib/import/files'
|
||||
import { buildImportPlan, countByKind, type ImportPlan } from '../lib/import/merge'
|
||||
import { CancelledError, fetchAniListUser, isAniListUserName, resolveEntries, type CancelToken, type Match, type Progress } from '../lib/import/resolve'
|
||||
import { CancelledError, fetchAniListUser, isAniListUserName, resolveEntries, resolveTextEntries, withProgress, type CancelToken, type Match, type Progress } from '../lib/import/resolve'
|
||||
import { parseTextList, TEXT_MAX_CHARS, type TextEntry } from '../lib/import/textList'
|
||||
import { letterboxdRole, parseLetterboxd, parseMal, parseTvTime, type ImportEntry, type ImportSource } from '../lib/import/sources'
|
||||
import { useScrollLock } from '../lib/scrollLock'
|
||||
import { LIMITS } from '../lib/security'
|
||||
@@ -18,16 +20,18 @@ import { useMedia } from '../store'
|
||||
* Tout se passe sur l'appareil ; la synchro existante enverra ensuite les fiches au compte.
|
||||
*/
|
||||
|
||||
type Step = 'source' | 'input' | 'working' | 'preview' | 'done'
|
||||
type Step = 'source' | 'input' | 'working' | 'review' | 'preview' | 'done'
|
||||
|
||||
const SOURCES: { id: ImportSource; name: string; mark: string; accept?: string; multiple?: boolean }[] = [
|
||||
{ id: 'text', name: '', mark: 'Aa' },
|
||||
{ id: 'letterboxd', name: 'Letterboxd', mark: 'Lb', accept: '.zip,.csv,application/zip,text/csv', multiple: true },
|
||||
{ id: 'tvtime', name: 'TV Time', mark: 'TV', accept: '.zip,.csv,application/zip,text/csv', multiple: true },
|
||||
{ id: 'mal', name: 'MyAnimeList', mark: 'MAL', accept: '.xml,.gz,application/xml,text/xml,application/gzip' },
|
||||
{ id: 'anilist', name: 'AniList', mark: 'AL' },
|
||||
]
|
||||
|
||||
const NEEDS_TMDB: ImportSource[] = ['letterboxd', 'tvtime']
|
||||
const NEEDS_TMDB: ImportSource[] = ['text', 'letterboxd', 'tvtime']
|
||||
const sourceName = (s: { id: ImportSource; name: string }) => (s.id === 'text' ? t('import.text.name') : s.name)
|
||||
|
||||
/** Message lisible pour une erreur de lecture / de réseau. */
|
||||
function errorText(e: unknown): string {
|
||||
@@ -69,6 +73,11 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
const [showMissing, setShowMissing] = useState(false)
|
||||
const [result, setResult] = useState<{ added: number; updated: number; unchanged: number; notFound: number }>()
|
||||
const [dragging, setDragging] = useState(false)
|
||||
// Liste collée
|
||||
const [pasted, setPasted] = useState('')
|
||||
const [defaultStatus, setDefaultStatus] = useState<'termine' | 'a_voir'>('termine')
|
||||
const [unsure, setUnsure] = useState<Set<string>>(new Set())
|
||||
const [excluded, setExcluded] = useState<Set<string>>(new Set())
|
||||
const [now, setNow] = useState(Date.now())
|
||||
const token = useRef<CancelToken>({ cancelled: false })
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
@@ -93,10 +102,15 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
const info = SOURCES.find((s) => s.id === source)
|
||||
const hasTmdb = !!settings.tmdbKey?.trim()
|
||||
|
||||
const plan: ImportPlan | undefined = useMemo(
|
||||
() => (step === 'preview' ? buildImportPlan(entries, matches, items, { includeUnmatched }) : undefined),
|
||||
[step, entries, matches, items, includeUnmatched],
|
||||
)
|
||||
const plan: ImportPlan | undefined = useMemo(() => {
|
||||
if (step !== 'preview') return undefined
|
||||
// Liste collée : seulement les lignes gardées, avec la progression « S3E12 » convertie en épisodes
|
||||
const list =
|
||||
source === 'text'
|
||||
? (entries as TextEntry[]).filter((e) => !excluded.has(e.key) && matches.has(e.key)).map((e) => withProgress(e, matches.get(e.key)))
|
||||
: entries
|
||||
return buildImportPlan(list, matches, items, { includeUnmatched: source === 'text' ? false : includeUnmatched })
|
||||
}, [step, source, entries, matches, items, includeUnmatched, excluded])
|
||||
|
||||
const run = async (load: () => Promise<ImportEntry[]>) => {
|
||||
const tk = { cancelled: false }
|
||||
@@ -127,10 +141,36 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
const onFiles = (list: FileList | null | undefined) => {
|
||||
const files = Array.from(list ?? [])
|
||||
if (fileRef.current) fileRef.current.value = ''
|
||||
if (!files.length || !source || source === 'anilist') return
|
||||
if (!files.length || !source || source === 'anilist' || source === 'text') return
|
||||
void run(() => readEntries(source, files))
|
||||
}
|
||||
|
||||
const onText = () => {
|
||||
const list = parseTextList(pasted, { defaultStatus })
|
||||
if (!list.length) return setError(t('import.err.empty'))
|
||||
const tk = { cancelled: false }
|
||||
token.current = tk
|
||||
setError(undefined)
|
||||
setEntries(list)
|
||||
setStep('working')
|
||||
setPhase('resolving')
|
||||
setProgress({ done: 0, total: list.length })
|
||||
resolveTextEntries(list, { tmdbKey: settings.tmdbKey, token: tk, onProgress: (p) => !tk.cancelled && setProgress(p) })
|
||||
.then(({ found, unsure }) => {
|
||||
if (tk.cancelled) return
|
||||
setEntries([...list])
|
||||
setMatches(found)
|
||||
setUnsure(unsure)
|
||||
setExcluded(new Set())
|
||||
setStep('review')
|
||||
})
|
||||
.catch((e) => {
|
||||
if (e instanceof CancelledError || tk.cancelled) return
|
||||
setError(errorText(e))
|
||||
setStep('input')
|
||||
})
|
||||
}
|
||||
|
||||
const onAniList = () => {
|
||||
const name = userName.trim()
|
||||
if (!isAniListUserName(name)) return setError(t('import.err.user'))
|
||||
@@ -148,7 +188,7 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
setPhase('saving')
|
||||
try {
|
||||
await importItems([...plan.added, ...plan.updated], 'merge')
|
||||
setResult({ added: plan.added.length, updated: plan.updated.length, unchanged: plan.unchanged, notFound: includeUnmatched ? 0 : plan.notFound.length })
|
||||
setResult({ added: plan.added.length, updated: plan.updated.length, unchanged: plan.unchanged, notFound: includeUnmatched || source === 'text' ? 0 : plan.notFound.length })
|
||||
setStep('done')
|
||||
} catch (e) {
|
||||
setError(errorText(e))
|
||||
@@ -164,7 +204,7 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
|
||||
const back = () => {
|
||||
setError(undefined)
|
||||
setStep(step === 'preview' ? 'input' : 'source')
|
||||
setStep(step === 'preview' ? (source === 'text' ? 'review' : 'input') : step === 'review' ? 'input' : 'source')
|
||||
}
|
||||
|
||||
const pct = progress.total ? Math.round((progress.done / progress.total) * 100) : 0
|
||||
@@ -175,14 +215,14 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
<div className="sheet sheet-in z-[60]" role="dialog" aria-modal="true" aria-label={t('import.title')}>
|
||||
<header className="safe-top border-b border-line">
|
||||
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5 lg:max-w-none lg:px-10">
|
||||
{step === 'input' || step === 'preview' ? (
|
||||
{step === 'input' || step === 'review' || step === 'preview' ? (
|
||||
<button onClick={back} className="grid size-10 shrink-0 place-items-center rounded-full text-ink-2 rtl:-scale-x-100" aria-label={t('import.back')}>
|
||||
<ArrowLeft size={21} />
|
||||
</button>
|
||||
) : (
|
||||
<span className="size-10 shrink-0" />
|
||||
)}
|
||||
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{info && step !== 'source' ? info.name : t('import.title')}</h2>
|
||||
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{info && step !== 'source' ? sourceName(info) : t('import.title')}</h2>
|
||||
<button onClick={close} className="grid size-10 shrink-0 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
|
||||
<X size={22} />
|
||||
</button>
|
||||
@@ -207,7 +247,7 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
>
|
||||
<span className="grid size-12 shrink-0 place-items-center rounded-xl border border-line-strong bg-surface-2 text-sm font-bold tracking-tight text-ink">{s.mark}</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-semibold">{s.name}</span>
|
||||
<span className="block font-semibold">{sourceName(s)}</span>
|
||||
<span className="mt-0.5 block text-xs text-ink-3">{t(`import.src.${s.id}` as TKey)}</span>
|
||||
</span>
|
||||
<span className="text-ink-3 rtl:-scale-x-100">→</span>
|
||||
@@ -236,7 +276,36 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
<p className="mt-5 rounded-2xl border border-dashed border-line-strong p-3.5 text-xs leading-relaxed text-ink-2">{t('import.noTmdb')}</p>
|
||||
)}
|
||||
|
||||
{info.id === 'anilist' ? (
|
||||
{info.id === 'text' ? (
|
||||
<div className="mt-6">
|
||||
<textarea
|
||||
className="field min-h-56 w-full resize-y py-3 leading-relaxed"
|
||||
value={pasted}
|
||||
onChange={(e) => setPasted(e.target.value.slice(0, TEXT_MAX_CHARS))}
|
||||
placeholder={t('import.text.placeholder')}
|
||||
aria-label={t('import.text.name')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<p className="mt-4 text-sm font-medium">{t('import.text.default')}</p>
|
||||
<div className="mt-2 grid grid-cols-2 gap-2" role="radiogroup" aria-label={t('import.text.default')}>
|
||||
{(['termine', 'a_voir'] as const).map((st) => (
|
||||
<button
|
||||
key={st}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={defaultStatus === st}
|
||||
onClick={() => setDefaultStatus(st)}
|
||||
className={cx('btn', defaultStatus === st ? 'btn-primary' : 'btn-ghost')}
|
||||
>
|
||||
{st === 'termine' ? t('import.text.seen') : t('status.a_voir')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="button" onClick={onText} disabled={!pasted.trim()} className="btn btn-primary mt-5 w-full">
|
||||
{t('import.text.analyze')}
|
||||
</button>
|
||||
</div>
|
||||
) : info.id === 'anilist' ? (
|
||||
<form
|
||||
className="mt-6 flex gap-2"
|
||||
onSubmit={(e) => {
|
||||
@@ -312,6 +381,37 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'review' && source === 'text' && (
|
||||
<ImportTextReview
|
||||
entries={entries as TextEntry[]}
|
||||
matches={matches}
|
||||
unsure={unsure}
|
||||
excluded={excluded}
|
||||
tmdbKey={settings.tmdbKey}
|
||||
onToggle={(key) =>
|
||||
setExcluded((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (!next.delete(key)) next.add(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
onChange={(key, match) => {
|
||||
setMatches((prev) => new Map(prev).set(key, match))
|
||||
setUnsure((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(key)
|
||||
return next
|
||||
})
|
||||
setExcluded((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(key)
|
||||
return next
|
||||
})
|
||||
}}
|
||||
onContinue={() => setStep('preview')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 'preview' && plan && kinds && (
|
||||
<>
|
||||
<p className="text-sm text-ink-2">{t('import.found', { n: entries.length })}</p>
|
||||
@@ -336,7 +436,7 @@ export default function ImportWizard({ onClose }: { onClose: () => void }) {
|
||||
<Line label={t('import.notFound')} value={plan.notFound.length} accent={plan.notFound.length > 0} />
|
||||
</div>
|
||||
|
||||
{plan.notFound.length > 0 && (
|
||||
{source !== 'text' && plan.notFound.length > 0 && (
|
||||
<div className="mt-3">
|
||||
<button onClick={() => setShowMissing((v) => !v)} className="flex items-center gap-1.5 text-sm font-medium text-ink-2" aria-expanded={showMissing}>
|
||||
<ChevronDown size={16} className={cx('transition-transform', showMissing && 'rotate-180')} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { locale, t } from '../i18n'
|
||||
import { dateFormat, locale, t } from '../i18n'
|
||||
import { Star } from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { oneViewMinutes, rewatchMinutes, watchMinutes } from '../lib/stats'
|
||||
@@ -8,6 +8,7 @@ import type { MediaItem } from '../types'
|
||||
import { TypeBadge } from './Badges'
|
||||
import Poster from './Poster'
|
||||
import { EmptyState } from './ui'
|
||||
import { prefetchAttrs } from '../lib/prefetch'
|
||||
|
||||
type Kind = 'fini' | 'revu' | 'commence' | 'abandonne'
|
||||
|
||||
@@ -34,7 +35,7 @@ function buildEntries(items: MediaItem[]): Entry[] {
|
||||
|
||||
/** Onglet « Journal » du catalogue : chronologie groupée par mois. */
|
||||
export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => void }) {
|
||||
const { items, settings } = useMedia()
|
||||
const { items } = useMedia()
|
||||
const entries = useMemo(() => buildEntries(items), [items])
|
||||
const years = useMemo(() => [...new Set(entries.map((e) => e.date.slice(0, 4)))], [entries])
|
||||
const [year, setYear] = useState('')
|
||||
@@ -73,7 +74,7 @@ export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => v
|
||||
</div>
|
||||
|
||||
{months.slice(0, shown).map(([key, list]) => {
|
||||
const label = new Date(key + '-15T12:00:00').toLocaleDateString(locale(), { month: 'long', year: 'numeric' })
|
||||
const label = dateFormat({ month: 'long', year: 'numeric' }).format(new Date(key + '-15T12:00:00'))
|
||||
const minutes = list.reduce((s, e) => s + e.minutes, 0)
|
||||
const finished = list.filter((e) => e.kind === 'fini' || e.kind === 'revu').length
|
||||
return (
|
||||
@@ -90,10 +91,10 @@ export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => v
|
||||
const d = new Date(e.date + 'T12:00:00')
|
||||
return (
|
||||
<li key={e.item.id + e.date + e.kind}>
|
||||
<button onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||
<button {...prefetchAttrs(e.item)} onClick={() => onOpen(e.item)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||
<span className="w-9 shrink-0 text-center">
|
||||
<span className="block text-xl font-bold leading-none tabular-nums">{d.getDate()}</span>
|
||||
<span className="block text-[10px] text-ink-3">{d.toLocaleDateString(locale(), { weekday: 'short' }).replace('.', '')}</span>
|
||||
<span className="block text-[10px] text-ink-3">{dateFormat({ weekday: 'short' }).format(d).replace('.', '')}</span>
|
||||
</span>
|
||||
<div className="w-10 shrink-0">
|
||||
<Poster src={e.item.poster} title={e.item.title} />
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Check, Loader2, Plus } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { getAniListById, releaseToResult, type GlobalRelease, type SearchResult } from '../lib/catalogApi'
|
||||
import { cachedMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases'
|
||||
import { releaseToInput } from '../lib/releaseAdd'
|
||||
import { formatDate, localDay, normalizeText, todayISO } from '../lib/utils'
|
||||
import { GuestError, useMedia } from '../store'
|
||||
import Poster from './Poster'
|
||||
import { useToast } from './Toast'
|
||||
import { SectionTitle } from './ui'
|
||||
|
||||
const DAYS = 45
|
||||
const MAX = 20
|
||||
|
||||
/** Sorties récentes (≤ 45 jours) qui sont de vraies nouveautés : films, nouvelles séries et nouvelles saisons. */
|
||||
function pick(all: GlobalRelease[], owned: Set<string>, ownedTitles: Set<string>): GlobalRelease[] {
|
||||
const today = todayISO()
|
||||
const d = new Date()
|
||||
d.setDate(d.getDate() - DAYS)
|
||||
const from = localDay(d)
|
||||
const byId = new Map<string, GlobalRelease>()
|
||||
for (const r of all) {
|
||||
if (!r.premiere || r.date > today || r.date < from) continue
|
||||
if (owned.has(r.externalId) || ownedTitles.has(normalizeText(r.title)) || (r.originalTitle && ownedTitles.has(normalizeText(r.originalTitle)))) continue
|
||||
const cur = byId.get(r.externalId)
|
||||
if (!cur || r.date > cur.date) byId.set(r.externalId, r)
|
||||
}
|
||||
return [...byId.values()].sort((a, b) => b.date.localeCompare(a.date) || b.pop - a.pop).slice(0, MAX)
|
||||
}
|
||||
|
||||
const months = () => {
|
||||
const now = new Date()
|
||||
return [new Date(now.getFullYear(), now.getMonth(), 1), new Date(now.getFullYear(), now.getMonth() - 1, 1)]
|
||||
}
|
||||
|
||||
/** Accueil : « Dernières sorties », ajoutables à « À voir » en un geste. */
|
||||
export default function LatestReleases({ onOpenSeed }: { onOpenSeed: (seed: SearchResult) => void }) {
|
||||
const { items, settings, add } = useMedia()
|
||||
const toast = useToast()
|
||||
const [all, setAll] = useState<GlobalRelease[]>(() => months().flatMap(cachedMonth))
|
||||
const [busy, setBusy] = useState<string>()
|
||||
const [added, setAdded] = useState<Set<string>>(new Set())
|
||||
|
||||
// Mise à jour (cache de 12 h) seulement quand la rangée approche de l'écran : elle est tout en bas de
|
||||
// l'accueil et demande plusieurs centaines de requêtes, inutiles si l'on ne descend pas jusque-là
|
||||
const zone = useRef<HTMLDivElement>(null)
|
||||
const [near, setNear] = useState(false)
|
||||
useEffect(() => {
|
||||
const el = zone.current
|
||||
if (near || !el) return
|
||||
const io = new IntersectionObserver(([e]) => e?.isIntersecting && setNear(true), { rootMargin: '800px 0px' })
|
||||
io.observe(el)
|
||||
return () => io.disconnect()
|
||||
}, [near])
|
||||
useEffect(() => {
|
||||
if (!near || !navigator.onLine) return
|
||||
let alive = true
|
||||
const cats = RELEASE_CATEGORIES.map((c) => c.value)
|
||||
const id = window.setTimeout(() => {
|
||||
void Promise.all(months().map((m) => loadMonth(m, cats, settings.tmdbKey)))
|
||||
.then((res) => alive && setAll(res.flatMap((r) => r.releases)))
|
||||
.catch(() => {})
|
||||
}, 300)
|
||||
return () => {
|
||||
alive = false
|
||||
window.clearTimeout(id)
|
||||
}
|
||||
}, [near, settings.tmdbKey])
|
||||
|
||||
const owned = useMemo(() => new Set(items.map((i) => i.externalId).filter((x): x is string => !!x)), [items])
|
||||
const ownedTitles = useMemo(
|
||||
() => new Set(items.flatMap((i) => [i.title, i.originalTitle]).filter((s): s is string => !!s).map(normalizeText)),
|
||||
[items],
|
||||
)
|
||||
// Un titre ajouté depuis cette rangée y reste (avec sa coche) jusqu'au prochain affichage
|
||||
const list = useMemo(() => {
|
||||
const keep = all.filter((r) => added.has(r.externalId))
|
||||
const fresh = pick(all, owned, ownedTitles)
|
||||
return [...fresh, ...keep.filter((r) => !fresh.some((f) => f.externalId === r.externalId))].sort((a, b) => b.date.localeCompare(a.date))
|
||||
}, [all, owned, ownedTitles, added])
|
||||
|
||||
|
||||
const open = async (r: GlobalRelease) => {
|
||||
const seed = r.externalId.startsWith('anilist:') ? await getAniListById(r.externalId).catch(() => null) : releaseToResult(r)
|
||||
if (seed) onOpenSeed(seed)
|
||||
}
|
||||
|
||||
const addToWatchlist = async (r: GlobalRelease) => {
|
||||
setBusy(r.externalId)
|
||||
try {
|
||||
await add(await releaseToInput(r, settings.tmdbKey))
|
||||
setAdded((s) => new Set(s).add(r.externalId))
|
||||
} catch (e) {
|
||||
if (!(e instanceof GuestError)) toast.show((e as Error)?.message || t('reco.error'))
|
||||
} finally {
|
||||
setBusy(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
// Toujours le même repère (même vide), pour que l'observation ne se perde pas
|
||||
if (!list.length) return <div ref={zone} className="h-px" aria-hidden="true" />
|
||||
return (
|
||||
<div ref={zone}>
|
||||
<SectionTitle>{t('home.latestReleases')}</SectionTitle>
|
||||
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
|
||||
{list.map((r) => {
|
||||
const done = added.has(r.externalId)
|
||||
return (
|
||||
<div key={r.externalId} className="w-28 shrink-0">
|
||||
<div className="relative">
|
||||
<button data-prefetch={r.externalId} onClick={() => void open(r)} className="block w-full" aria-label={t('card.open', { title: r.title })}>
|
||||
<Poster src={r.poster} title={r.title} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => void addToWatchlist(r)}
|
||||
disabled={done || !!busy}
|
||||
className="absolute bottom-2 end-2 flex h-8 items-center gap-1 rounded-md bg-accent-fill px-2.5 text-xs font-semibold text-on-accent transition active:scale-90 disabled:opacity-90"
|
||||
aria-label={done ? t('reco.added', { title: r.title }) : t('reco.addLabel', { title: r.title })}
|
||||
>
|
||||
{busy === r.externalId ? <Loader2 size={13} className="animate-spin" /> : done ? <Check size={13} strokeWidth={3} /> : <Plus size={13} strokeWidth={3} />}
|
||||
{done ? t('reco.addedShort') : t('status.a_voir')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-2 line-clamp-2 text-xs font-medium leading-snug text-ink-2">{r.title}</p>
|
||||
<p className="truncate text-[11px] text-ink-3">{r.label}</p>
|
||||
<p className="text-[11px] text-ink-3">{formatDate(r.date)}</p>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import ConfirmDialog from './ConfirmDialog'
|
||||
import { MediaCard } from './MediaCard'
|
||||
import Poster from './Poster'
|
||||
import { EmptyState } from './ui'
|
||||
import { NewListForm } from './NewListForm'
|
||||
import { useLibraryActions } from './library/useLibraryActions'
|
||||
import { SharedListsSection } from './social/SharedLists'
|
||||
|
||||
@@ -28,38 +29,6 @@ function Mosaic({ items }: { items: MediaItem[] }) {
|
||||
)
|
||||
}
|
||||
|
||||
export function NewListForm({ onCreated, autoFocus }: { onCreated?: (list: CustomList) => void; autoFocus?: boolean }) {
|
||||
const { createList } = useMedia()
|
||||
const [name, setName] = useState('')
|
||||
// Pas de <form> ici : ce champ peut vivre à l'intérieur du formulaire d'une fiche
|
||||
const submit = () => {
|
||||
if (!name.trim()) return
|
||||
onCreated?.(createList(name))
|
||||
setName('')
|
||||
}
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
className="field"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
submit()
|
||||
}
|
||||
}}
|
||||
placeholder={t('lists.newListPh')}
|
||||
autoFocus={autoFocus}
|
||||
enterKeyHint="done"
|
||||
/>
|
||||
<button type="button" onClick={submit} disabled={!name.trim()} className="btn btn-light shrink-0 px-4 text-sm">
|
||||
{t('lists.create')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ListDetail({ list, onBack, onOpen }: { list: CustomList; onBack: () => void; onOpen: (item: MediaItem) => void }) {
|
||||
const { items, renameList, deleteList, toggleInList } = useMedia()
|
||||
const actions = useLibraryActions()
|
||||
@@ -172,6 +141,7 @@ function ListDetail({ list, onBack, onOpen }: { list: CustomList; onBack: () =>
|
||||
title={t('confirm.title')}
|
||||
message={t('lists.deleteConfirm', { name: list.name })}
|
||||
confirmLabel={t('common.delete')}
|
||||
danger
|
||||
onConfirm={async () => {
|
||||
setConfirm(false)
|
||||
await deleteList(list.id)
|
||||
|
||||
@@ -5,11 +5,12 @@ import { TYPE_BY_VALUE } from '../lib/constants'
|
||||
import { canWatchMore } from '../lib/airing'
|
||||
import { episodeCap, seasonPosition } from '../lib/franchise'
|
||||
import { progressView } from '../lib/rewatch'
|
||||
import { useMedia } from '../store'
|
||||
import { useMediaActions } from '../store'
|
||||
import type { MediaItem } from '../types'
|
||||
import { StatusPill, TypeBadge } from './Badges'
|
||||
import Poster from './Poster'
|
||||
import { RatingBadge } from './Rating'
|
||||
import { prefetchAttrs } from '../lib/prefetch'
|
||||
|
||||
function Progress({ item }: { item: MediaItem }) {
|
||||
const cap = episodeCap(item)
|
||||
@@ -27,7 +28,7 @@ function Progress({ item }: { item: MediaItem }) {
|
||||
{size ? `/${size}` : ''}
|
||||
</div>
|
||||
{size ? (
|
||||
<div className="mt-1.5 h-1 overflow-hidden rounded-[1px] bg-film-frame">
|
||||
<div className="mt-1.5 h-1 overflow-hidden rounded-[1px] bg-line">
|
||||
<div className="h-full bg-accent-fill" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
) : null}
|
||||
@@ -37,11 +38,11 @@ function Progress({ item }: { item: MediaItem }) {
|
||||
|
||||
/**
|
||||
* Carte verticale (grille du catalogue).
|
||||
* Mémorisée : taper dans la recherche ou cocher une fiche ne redessine plus toute la grille
|
||||
* (elle se redessine quand même si la bibliothèque ou les réglages changent, via useMedia).
|
||||
* Mémorisée : taper dans la recherche, cocher une fiche ou une synchro sans changement ne redessine
|
||||
* plus toute la grille (seules les cartes dont la fiche a changé se redessinent).
|
||||
*/
|
||||
export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) {
|
||||
const { settings, incrementEpisode } = useMedia()
|
||||
const { incrementEpisode } = useMediaActions()
|
||||
// Revisionnage en cours : la progression montrée est celle du revisionnage
|
||||
const view = progressView(item)
|
||||
const canIncrement =
|
||||
@@ -52,7 +53,7 @@ export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: Media
|
||||
return (
|
||||
<article>
|
||||
<div className="relative">
|
||||
<button onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
|
||||
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="block w-full transition-opacity active:opacity-80 motion-reduce:transition-none" aria-label={t('card.open', { title: item.title })}>
|
||||
<Poster src={item.poster} title={item.title} />
|
||||
</button>
|
||||
<TypeBadge item={item} className="pointer-events-none absolute start-2 top-2 border-transparent bg-bg/85" />
|
||||
@@ -69,7 +70,7 @@ export const MediaCard = memo(function MediaCard({ item, onOpen }: { item: Media
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button onClick={() => onOpen(item)} className="block w-full text-start">
|
||||
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="block w-full text-start">
|
||||
<h3 className="mt-2.5 line-clamp-2 font-sans text-sm font-semibold leading-snug tracking-normal">{item.title}</h3>
|
||||
<div className="mt-1 flex items-center justify-between gap-2">
|
||||
<StatusPill status={item.status} />
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useState } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { useMedia } from '../store'
|
||||
import type { CustomList } from '../types'
|
||||
|
||||
/**
|
||||
* Champ « Nouvelle liste » (onglet Listes, fiche d'un titre, sélection multiple).
|
||||
* Dans son propre fichier : l'importer n'embarque pas tout l'onglet Listes (chargé à la demande).
|
||||
*/
|
||||
export function NewListForm({ onCreated, autoFocus }: { onCreated?: (list: CustomList) => void; autoFocus?: boolean }) {
|
||||
const { createList } = useMedia()
|
||||
const [name, setName] = useState('')
|
||||
// Pas de <form> ici : ce champ peut vivre à l'intérieur du formulaire d'une fiche
|
||||
const submit = () => {
|
||||
if (!name.trim()) return
|
||||
onCreated?.(createList(name))
|
||||
setName('')
|
||||
}
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
className="field"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
submit()
|
||||
}
|
||||
}}
|
||||
placeholder={t('lists.newListPh')}
|
||||
autoFocus={autoFocus}
|
||||
enterKeyHint="done"
|
||||
/>
|
||||
<button type="button" onClick={submit} disabled={!name.trim()} className="btn btn-light shrink-0 px-4 text-sm">
|
||||
{t('lists.create')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { t, type TKey } from '../i18n'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
import { NOTIF_KINDS, type NotifKind } from '../types'
|
||||
import { SectionTitle } from './ui'
|
||||
|
||||
const GROUPS: { title: TKey; kinds: [NotifKind, TKey][] }[] = [
|
||||
{
|
||||
title: 'notifPrefs.follows',
|
||||
kinds: [
|
||||
['new_follower', 'notifPrefs.new_follower'],
|
||||
['follow_request', 'notifPrefs.follow_request'],
|
||||
['follow_accepted', 'notifPrefs.follow_accepted'],
|
||||
['unfollow', 'notifPrefs.unfollow'],
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'notifPrefs.reviews',
|
||||
kinds: [
|
||||
['reaction', 'notifPrefs.reaction'],
|
||||
['review_comment', 'notifPrefs.review_comment'],
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'notifPrefs.friends',
|
||||
kinds: [
|
||||
['friend_review', 'notifPrefs.friend_review'],
|
||||
['friend_started', 'notifPrefs.friend_started'],
|
||||
['friend_added', 'notifPrefs.friend_added'],
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Réglages → Notifications : ce qu'on veut recevoir dans la cloche.
|
||||
* Les types désactivés sont dans les réglages synchronisés (notifOff) : le serveur ne les crée plus
|
||||
* et masque ceux déjà reçus (migration 20261201110000_notification_prefs).
|
||||
*/
|
||||
export default function NotificationSettings() {
|
||||
const { settings, updateSettings } = useMedia()
|
||||
const off = new Set(settings.notifOff ?? [])
|
||||
const toggle = (kind: NotifKind) => {
|
||||
const next = new Set(off)
|
||||
if (next.has(kind)) next.delete(kind)
|
||||
else next.add(kind)
|
||||
updateSettings({ notifOff: NOTIF_KINDS.filter((k) => next.has(k)) })
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SectionTitle>{t('notif.title')}</SectionTitle>
|
||||
<p className="-mt-1 mb-3 text-xs text-ink-3">{t('notifPrefs.hint')}</p>
|
||||
<div className="card divide-y divide-line overflow-hidden">
|
||||
{GROUPS.map((g) => (
|
||||
<div key={g.title} className="px-4 pb-1.5 pt-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-ink-3">{t(g.title)}</p>
|
||||
{g.kinds.map(([kind, label]) => {
|
||||
const on = !off.has(kind)
|
||||
return (
|
||||
<button key={kind} type="button" role="switch" aria-checked={on} onClick={() => toggle(kind)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||
<span className="flex-1 text-sm">{t(label)}</span>
|
||||
<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', on ? 'start-[22px] bg-on-accent' : 'start-0.5 bg-ink')} />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export default function Poster({ src, title, className }: { src?: string; title:
|
||||
src={src}
|
||||
alt={title}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={() => setBroken(src)}
|
||||
className={cx('aspect-[2/3] w-full rounded-xl border border-line bg-surface-2 object-cover', className)}
|
||||
/>
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
import { t } from '../i18n'
|
||||
import { Check, Loader2, Plus } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { aniListRecommendations, getTmdbDetails, searchAniList, tmdbRecommendations, type SearchResult } from '../lib/catalogApi'
|
||||
import { remotePosterToLocal } from '../lib/image'
|
||||
import { normalizeText } from '../lib/utils'
|
||||
import { GuestError, useMedia } from '../store'
|
||||
import type { MediaInput, MediaItem } from '../types'
|
||||
import Poster from './Poster'
|
||||
import { useToast } from './Toast'
|
||||
import { LinkArrow, SectionTitle } from './ui'
|
||||
|
||||
// Cache en mémoire le temps de la session (évite de refaire les requêtes)
|
||||
const cache = new Map<string, SearchResult[]>()
|
||||
|
||||
const isLoved = (i: MediaItem) =>
|
||||
(i.status === 'termine' || i.status === 'en_cours') && !!i.externalId && (!!i.top || i.favorite || (i.rating ?? 0) >= 8)
|
||||
|
||||
async function recommendationsFor(seed: MediaItem, tmdbKey?: string): Promise<SearchResult[]> {
|
||||
const ext = seed.externalId!
|
||||
if (cache.has(seed.id)) return cache.get(seed.id)!
|
||||
let recs: SearchResult[] = []
|
||||
if (ext.startsWith('anilist:')) recs = await aniListRecommendations(ext)
|
||||
else if (tmdbKey) recs = await tmdbRecommendations(ext, tmdbKey)
|
||||
else if (seed.type === 'anime') {
|
||||
// Sans clé TMDB : on retrouve l'anime sur AniList par son titre
|
||||
const found = (await searchAniList(seed.originalTitle || seed.title))[0]
|
||||
if (found) recs = await aniListRecommendations(found.externalId)
|
||||
}
|
||||
cache.set(seed.id, recs)
|
||||
return recs
|
||||
}
|
||||
|
||||
/** « Si tu as aimé X » : suggestions à partir de mes titres préférés, ajoutables en un clic. */
|
||||
export default function Recommendations() {
|
||||
const { items, settings, add } = useMedia()
|
||||
const toast = useToast()
|
||||
const hasKey = !!settings.tmdbKey?.trim()
|
||||
|
||||
// Titres « graines » : mes préférés, dans un ordre aléatoire fixé pour la session
|
||||
const seeds = useMemo(() => {
|
||||
const loved = items.filter((i) => isLoved(i) && (hasKey || i.externalId!.startsWith('anilist:') || i.type === 'anime'))
|
||||
return loved.map((i) => ({ i, r: Math.random() })).sort((a, b) => a.r - b.r).map((x) => x.i)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [items.length, hasKey])
|
||||
|
||||
const [index, setIndex] = useState(0)
|
||||
const [recs, setRecs] = useState<SearchResult[]>()
|
||||
const [error, setError] = useState<string>()
|
||||
const [busy, setBusy] = useState<string>()
|
||||
const [added, setAdded] = useState<Set<string>>(new Set())
|
||||
const seed = seeds.length ? seeds[index % seeds.length] : undefined
|
||||
// Déjà dans ma bibliothèque : même identifiant, ou même titre (les fiches importées viennent parfois d'une autre base)
|
||||
const owned = useMemo(() => new Set(items.map((i) => i.externalId).filter(Boolean)), [items])
|
||||
const ownedTitles = useMemo(
|
||||
() => new Set(items.flatMap((i) => [i.title, i.originalTitle]).filter((s): s is string => !!s).map(normalizeText)),
|
||||
[items],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!seed || !navigator.onLine) return
|
||||
let alive = true
|
||||
setRecs(undefined)
|
||||
setError(undefined)
|
||||
recommendationsFor(seed, settings.tmdbKey)
|
||||
.then((r) => alive && setRecs(r))
|
||||
.catch(() => alive && setError(t('reco.error')))
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [seed, settings.tmdbKey])
|
||||
|
||||
if (!seed) {
|
||||
if (!hasKey && items.some((i) => (i.rating ?? 0) >= 8))
|
||||
return (
|
||||
<>
|
||||
<SectionTitle>{t('reco.title')}</SectionTitle>
|
||||
<p className="text-sm text-ink-3">{t('reco.needKey')}</p>
|
||||
</>
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const visible = (recs ?? [])
|
||||
.filter(
|
||||
(r) =>
|
||||
added.has(r.externalId) ||
|
||||
(!owned.has(r.externalId) && !ownedTitles.has(normalizeText(r.title)) && !(r.originalTitle && ownedTitles.has(normalizeText(r.originalTitle)))),
|
||||
)
|
||||
.slice(0, 10)
|
||||
|
||||
const addToWatchlist = async (r: SearchResult) => {
|
||||
setBusy(r.externalId)
|
||||
try {
|
||||
const data = r.source === 'tmdb' ? await getTmdbDetails(r, settings.tmdbKey!) : { ...r.prefill }
|
||||
const poster = r.posterUrl ? (r.source === 'tmdb' ? await remotePosterToLocal(r.posterUrl) : r.posterUrl) : undefined
|
||||
const input: MediaInput = {
|
||||
title: r.title,
|
||||
type: r.typeGuess,
|
||||
status: 'a_voir',
|
||||
criteria: {},
|
||||
episodesWatched: 0,
|
||||
genres: [],
|
||||
...data,
|
||||
poster,
|
||||
}
|
||||
await add(input)
|
||||
setAdded((s) => new Set(s).add(r.externalId))
|
||||
} catch (e) {
|
||||
// Hors ligne, TMDB injoignable, stockage plein… : on le dit (mode visiteur : déjà signalé ailleurs)
|
||||
if (!(e instanceof GuestError)) toast.show((e as Error)?.message || t('reco.error'))
|
||||
} finally {
|
||||
setBusy(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SectionTitle action={seeds.length > 1 ? <LinkArrow onClick={() => setIndex((i) => i + 1)}>{t('reco.other')}</LinkArrow> : undefined}>
|
||||
{t('reco.ifYouLiked')} <span className="text-accent">{seed.title}</span>
|
||||
</SectionTitle>
|
||||
|
||||
{error ? (
|
||||
<p className="text-sm text-ink-3">{error}</p>
|
||||
) : !recs ? (
|
||||
<p className="flex items-center gap-2 text-sm text-ink-3">
|
||||
<Loader2 size={14} className="animate-spin" /> {t('reco.loading')}
|
||||
</p>
|
||||
) : visible.length === 0 ? (
|
||||
<p className="text-sm text-ink-3">{t('reco.none')}</p>
|
||||
) : (
|
||||
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
|
||||
{visible.map((r) => {
|
||||
const done = added.has(r.externalId)
|
||||
return (
|
||||
<div key={r.externalId} className="w-28 shrink-0">
|
||||
<div className="relative">
|
||||
<Poster src={r.posterUrl ?? r.thumb} title={r.title} />
|
||||
<button
|
||||
onClick={() => addToWatchlist(r)}
|
||||
disabled={done || !!busy}
|
||||
className="absolute bottom-2 end-2 flex h-8 items-center gap-1 rounded-md bg-accent-fill px-2.5 text-xs font-semibold text-on-accent transition active:scale-90 disabled:opacity-90"
|
||||
aria-label={done ? t('reco.added', { title: r.title }) : t('reco.addLabel', { title: r.title })}
|
||||
>
|
||||
{busy === r.externalId ? <Loader2 size={13} className="animate-spin" /> : done ? <Check size={13} strokeWidth={3} /> : <Plus size={13} strokeWidth={3} />}
|
||||
{done ? t('reco.addedShort') : t('status.a_voir')}
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-2 line-clamp-2 text-xs font-medium leading-snug text-ink-2">{r.title}</p>
|
||||
<p className="text-[11px] text-ink-3">{[r.kindLabel, r.year].filter(Boolean).join(' · ')}</p>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ const shuffle = <T,>(arr: T[]) => {
|
||||
}
|
||||
|
||||
export default function Roulette({ onClose, onOpen }: Props) {
|
||||
const { items, settings, update, lists } = useMedia()
|
||||
const { items, update, lists } = useMedia()
|
||||
const [filters, setFilters] = useState<RouletteFilters>(loadFilters)
|
||||
const pool = useMemo(() => buildPool(items, filters), [items, filters])
|
||||
const base = useMemo(() => sourcePool(items, filters.sources, filters.listIds), [items, filters.sources, filters.listIds])
|
||||
|
||||
@@ -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'
|
||||
@@ -45,7 +45,7 @@ export default function SharePreview({ blob, filename, title, onClose }: Props)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="sheet-in fixed inset-0 z-[60] flex flex-col bg-bg/95 backdrop-blur-sm" role="dialog" aria-modal="true" aria-label={t('share.previewLabel')}>
|
||||
<div className="sheet-in fixed inset-0 z-[60] flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('share.previewLabel')}>
|
||||
<div className="safe-top flex items-center justify-between px-3 py-2.5">
|
||||
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
|
||||
<X size={22} />
|
||||
|
||||
@@ -2,7 +2,7 @@ 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'
|
||||
import { useMedia, useSyncStatus } from '../store'
|
||||
|
||||
function useOnline(): boolean {
|
||||
const [online, setOnline] = useState(() => navigator.onLine)
|
||||
@@ -25,14 +25,15 @@ 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.
|
||||
* L'état vient du moteur de synchro (useSyncStatus) : rien n'est recalculé ici.
|
||||
*/
|
||||
export default function SyncIndicator() {
|
||||
const { account } = useMedia()
|
||||
const sync = useSyncStatus()
|
||||
const online = useOnline()
|
||||
const pending = account?.sync.pending ?? 0
|
||||
const syncing = account?.sync.state === 'syncing'
|
||||
const failed = account?.sync.state === 'error'
|
||||
const pending = sync?.pending ?? 0
|
||||
const syncing = sync?.state === 'syncing'
|
||||
const failed = 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)
|
||||
|
||||
@@ -3,7 +3,6 @@ import { t } from '../i18n'
|
||||
import { Loader2, Plus, Share2 } from 'lucide-react'
|
||||
import { useState, type CSSProperties } from 'react'
|
||||
import { TOP_CATEGORIES } from '../lib/constants'
|
||||
import { renderTopCard, slug } from '../lib/shareCard'
|
||||
import { cx, formatRating } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
import type { MediaItem, TopCategory } from '../types'
|
||||
@@ -12,6 +11,7 @@ import { RatingBadge } from './Rating'
|
||||
import TopFiveEditor from './TopFiveEditor'
|
||||
import SharePreview from './SharePreview'
|
||||
import { LinkArrow, SectionTitle } from './ui'
|
||||
import { prefetchAttrs } from '../lib/prefetch'
|
||||
|
||||
/** Chiffre géant en contour (rouge pour le n°1, gris pour les autres). */
|
||||
function RankNumber({ rank, big }: { rank: number; big?: boolean }) {
|
||||
@@ -29,7 +29,9 @@ function RankNumber({ rank, big }: { rank: number; big?: boolean }) {
|
||||
)
|
||||
}
|
||||
|
||||
function EmptySlot({ rank, onClick, big }: { rank: number; onClick: () => void; big?: boolean }) {
|
||||
function EmptySlot({ rank, onClick, big }: { rank: number; onClick?: () => void; big?: boolean }) {
|
||||
// Top 5 d'un autre profil : simple emplacement vide
|
||||
if (!onClick) return <div aria-hidden className={cx('aspect-[2/3] rounded-xl border border-dashed border-line', big ? 'w-32 lg:w-40' : 'w-full')} />
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
@@ -44,9 +46,15 @@ function EmptySlot({ rank, onClick, big }: { rank: number; onClick: () => void;
|
||||
)
|
||||
}
|
||||
|
||||
export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void }) {
|
||||
const { items, settings } = useMedia()
|
||||
const cats = TOP_CATEGORIES.filter((c) => settings.topCategories.includes(c.value))
|
||||
/**
|
||||
* Top 5 par catégorie (n°1 en grand, 2 à 5 en dessous).
|
||||
* Le mien : modifiable et partageable. Celui d'un autre profil : `items` (ses fiches classées), en lecture seule.
|
||||
*/
|
||||
export default function TopFive({ onOpen, items: others }: { onOpen: (item: MediaItem) => void; items?: MediaItem[] }) {
|
||||
const { items: mine, settings } = useMedia()
|
||||
const readOnly = !!others
|
||||
const items = others ?? mine
|
||||
const cats = TOP_CATEGORIES.filter((c) => (readOnly ? items.some((i) => i.top?.category === c.value) : settings.topCategories.includes(c.value)))
|
||||
const [selected, setSelected] = useState<TopCategory>()
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [sharing, setSharing] = useState(false)
|
||||
@@ -60,8 +68,9 @@ export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void
|
||||
const share = async () => {
|
||||
setSharing(true)
|
||||
try {
|
||||
const { renderTopCard, slug } = await import('../lib/shareCard')
|
||||
const blob = await renderTopCard(current.plural, [1, 2, 3, 4, 5].map((r) => byRank.get(r)))
|
||||
setPreview({ blob, filename: `kino-top5-${slug(current.plural)}.png`, title: t('top.shareTitle', { category: current.plural }) })
|
||||
setPreview({ blob, filename: `bobinoo-top5-${slug(current.plural)}.png`, title: t('top.shareTitle', { category: current.plural }) })
|
||||
} finally {
|
||||
setSharing(false)
|
||||
}
|
||||
@@ -71,12 +80,14 @@ export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void
|
||||
<>
|
||||
<SectionTitle
|
||||
action={
|
||||
readOnly ? undefined : (
|
||||
<span className="flex items-center gap-4">
|
||||
<button onClick={share} disabled={sharing} className="flex items-center gap-1 text-xs font-medium text-ink-3" aria-label={t('top.shareLabel')}>
|
||||
{sharing ? <Loader2 size={13} className="animate-spin" /> : <Share2 size={13} />} {t('share.share')}
|
||||
</button>
|
||||
<LinkArrow onClick={edit}>{t('common.edit')}</LinkArrow>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('top.title')} <span className="text-accent">5</span>
|
||||
@@ -100,18 +111,18 @@ export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void
|
||||
<RankNumber rank={1} big />
|
||||
</span>
|
||||
{first ? (
|
||||
<button onClick={() => onOpen(first)} className="relative z-10 w-32 lg:w-40">
|
||||
<button {...prefetchAttrs(first)} onClick={() => onOpen(first)} className="relative z-10 w-32 lg:w-40">
|
||||
<Poster src={first.poster} title={first.title} />
|
||||
</button>
|
||||
) : (
|
||||
<EmptySlot rank={1} onClick={edit} big />
|
||||
<EmptySlot rank={1} onClick={readOnly ? undefined : edit} big />
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 pb-1 ps-4">
|
||||
<span className="eyebrow text-accent">{t('top.number', { rank: 1 })} · {current.plural}</span>
|
||||
{first ? (
|
||||
<>
|
||||
<button onClick={() => onOpen(first)} className="mt-1.5 block text-start text-lg font-bold leading-snug">
|
||||
<button {...prefetchAttrs(first)} onClick={() => onOpen(first)} className="mt-1.5 block text-start text-lg font-bold leading-snug">
|
||||
{first.title}
|
||||
</button>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-ink-3">
|
||||
@@ -121,7 +132,7 @@ export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void
|
||||
{first.genres.length > 0 && <p className="mt-2 line-clamp-1 text-xs text-ink-3">{first.genres.slice(0, 3).map(genreLabel).join(' · ')}</p>}
|
||||
</>
|
||||
) : (
|
||||
<p className="mt-1.5 text-sm text-ink-3">{t('top.pickFirst')}</p>
|
||||
<p className="mt-1.5 text-sm text-ink-3">{readOnly ? '—' : t('top.pickFirst')}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -139,11 +150,11 @@ export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void
|
||||
</span>
|
||||
<div className="relative z-10 ms-4">
|
||||
{item ? (
|
||||
<button onClick={() => onOpen(item)} className="block w-full">
|
||||
<button {...prefetchAttrs(item)} onClick={() => onOpen(item)} className="block w-full">
|
||||
<Poster src={item.poster} title={item.title} />
|
||||
</button>
|
||||
) : (
|
||||
<EmptySlot rank={rank} onClick={edit} />
|
||||
<EmptySlot rank={rank} onClick={readOnly ? undefined : edit} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Loader2, ShieldCheck } from 'lucide-react'
|
||||
import { useEffect, useState, type FormEvent } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { enrollTotp, listTotpFactors, removeTotp, verifyTotp } from '../lib/cloud/auth'
|
||||
import { TotpField } from './AuthScreen'
|
||||
import ConfirmDialog from './ConfirmDialog'
|
||||
|
||||
/** Réglages → Mon compte : activer / désactiver la double authentification (application d'authentification). */
|
||||
export default function TwoFactor({ onMessage }: { onMessage: (kind: 'ok' | 'error', text: string) => void }) {
|
||||
// undefined : chargement ; null : pas activée ; sinon l'identifiant du facteur
|
||||
const [factor, setFactor] = useState<string | null>()
|
||||
const [setup, setSetup] = useState<{ id: string; qr: string; secret: string }>()
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [confirmOff, setConfirmOff] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
listTotpFactors()
|
||||
.then((f) => alive && setFactor(f.find((x) => x.verified)?.id ?? null))
|
||||
.catch(() => alive && setFactor(null))
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const start = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
setSetup(await enrollTotp())
|
||||
setCode('')
|
||||
} catch (e) {
|
||||
onMessage('error', (e as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirm = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!setup || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await verifyTotp(setup.id, code)
|
||||
setFactor(setup.id)
|
||||
setSetup(undefined)
|
||||
onMessage('ok', t('mfa.enabled'))
|
||||
} catch (err) {
|
||||
onMessage('error', (err as Error).message)
|
||||
setCode('')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const disable = async () => {
|
||||
setConfirmOff(false)
|
||||
if (!factor) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await removeTotp(factor)
|
||||
setFactor(null)
|
||||
onMessage('ok', t('mfa.disabled'))
|
||||
} catch (e) {
|
||||
onMessage('error', (e as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-4">
|
||||
<div className="flex items-center gap-3.5">
|
||||
<ShieldCheck size={19} className={factor ? 'text-accent' : 'text-ink-2'} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-medium">{t('mfa.title')}</span>
|
||||
<span className="mt-0.5 block text-xs text-ink-3">{factor === undefined ? '…' : factor ? t('mfa.on') : t('mfa.off')}</span>
|
||||
</span>
|
||||
{factor !== undefined && !setup && (
|
||||
<button onClick={() => (factor ? setConfirmOff(true) : void start())} disabled={busy} className="btn btn-ghost shrink-0 px-3 py-1.5 text-sm">
|
||||
{busy && <Loader2 size={14} className="animate-spin" />}
|
||||
{factor ? t('mfa.disable') : t('mfa.enable')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{setup && (
|
||||
<form onSubmit={confirm} className="mt-4 space-y-3">
|
||||
<p className="text-sm text-ink-2">{t('mfa.scan')}</p>
|
||||
{setup.qr && (
|
||||
<div className="mx-auto w-48 bg-white p-2">
|
||||
<img src={setup.qr} alt="" className="size-full" />
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-ink-3">
|
||||
{t('mfa.secret')} <span className="code select-all break-all text-ink">{setup.secret}</span>
|
||||
</p>
|
||||
<TotpField value={code} onChange={setCode} />
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<button type="button" onClick={() => setSetup(undefined)} className="btn btn-ghost text-sm">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button type="submit" disabled={busy || code.replace(/\s/g, '').length !== 6} className="btn btn-primary text-sm">
|
||||
{busy && <Loader2 size={15} className="animate-spin" />}
|
||||
{t('mfa.confirm')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
<ConfirmDialog open={confirmOff} title={t('mfa.disable')} message={t('mfa.disableConfirm')} confirmLabel={t('mfa.disable')} onConfirm={() => void disable()} onCancel={() => setConfirmOff(false)} danger />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export default function GuestPrompt({ onSignIn, onSignUp, onClose }: { onSignIn:
|
||||
useEscape(onClose)
|
||||
useBackToClose(onClose)
|
||||
return (
|
||||
<div className="fixed inset-0 z-[80] flex items-end justify-center bg-black/60 sm:items-center" onClick={onClose}>
|
||||
<div className="fixed inset-0 z-[80] flex items-end justify-center bg-scrim sm:items-center" onClick={onClose}>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
@@ -20,14 +20,14 @@ export default function GuestPrompt({ onSignIn, onSignUp, onClose }: { onSignIn:
|
||||
<X size={18} />
|
||||
</button>
|
||||
<p className="text-2xl font-bold">
|
||||
Ki<span className="text-accent">no</span>
|
||||
Bobin<span className="text-accent">oo</span>
|
||||
</p>
|
||||
<h2 id="guest-prompt-title" className="mt-3 text-lg font-semibold">
|
||||
{t('guest.promptTitle')}
|
||||
</h2>
|
||||
<p className="mt-1.5 text-sm leading-relaxed text-ink-2">{t('guest.promptText')}</p>
|
||||
<div className="mt-6 space-y-2">
|
||||
<button onClick={onSignUp} className="btn btn-primary w-full py-3">
|
||||
<button onClick={onSignUp} className="btn btn-primary w-full py-3" autoFocus>
|
||||
{t('auth.signupTab')}
|
||||
</button>
|
||||
<button onClick={onSignIn} className="btn btn-ghost w-full py-3">
|
||||
|
||||