Initial commit

This commit is contained in:
Romain committed 2026-10-02 18:50:49 +02:00
commit 459e93d314
100 files changed
+26594

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# Copie ce fichier en « .env » (jamais publié grâce au .gitignore) et remplis les 2 valeurs
# depuis Supabase → Project Settings → API.
#
# Ces deux valeurs sont PUBLIQUES par nature (elles finissent dans l'app, visibles par tous) :
# la sécurité vient des règles de la base (RLS), pas du secret de ces clés.
# ⚠️ Ne mets JAMAIS ici ta clé TMDB ni la clé « service_role » : elles vont dans les
# secrets Supabase (voir README → Comptes).
VITE_SUPABASE_URL=https://xxxxxxxxxxxx.supabase.co
VITE_SUPABASE_ANON_KEY=sb_publishable_xxxxxxxxxxxxxxxxxxxx
+2
View File
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
+12
View File
@@ -0,0 +1,12 @@
node_modules
dist
dev-dist
*.local
.DS_Store
.env
.env.*
!.env.example
supabase/.temp
supabase/.branches
_to_delete
.env.deploy
+230
View File
@@ -0,0 +1,230 @@
# AzuuCine
Application personnelle (PWA) pour suivre, noter et organiser mes visionnages : films, séries, animes, K-dramas, C-dramas et autres.
Deux modes :
- **Avec comptes** (si le fichier `.env` est rempli) : chacun crée son compte, ses données sont enregistrées dans une base
Supabase où **personne d'autre ne peut les lire**, synchronisées entre ses appareils, et gardées aussi sur le téléphone
pour fonctionner sans internet. La clé TMDB reste sur le serveur.
- **100 % local** (sans `.env`) : comme avant, tout reste dans le navigateur de l'appareil.
## Stack
- **Vite + React 19 + TypeScript**
- **Tailwind CSS v4** (thème sombre par défaut)
- **vite-plugin-pwa** : manifeste, icônes, service worker (fonctionne hors-ligne)
- **IndexedDB** via un petit wrapper maison (`src/lib/db.ts`), sans dépendance
- **lucide-react** pour les icônes
- Police **Inter** embarquée via `@fontsource` (aucun appel à Google Fonts)
- Recherche en ligne : **TMDB** (films, séries, dramas) et **AniList** (animes)
- Comptes : **Supabase** (Auth + Postgres + Edge Functions), appelé sans dépendance (`src/lib/cloud/`)
## Design
Fond noir + une couleur d'accent au choix (Réglages → Thème : 12 couleurs prêtes ou couleur libre, rouge par défaut), sobre, typographie simple façon Letterboxd (Inter partout, petites capitales grises pour les sections),
boutons en pilule, filets de 1px, **aucun dégradé ni ombre**. Les couleurs sont définies dans `src/index.css` (`@theme`).
## Arborescence
```
AzuuCine/
├── index.html # méta iOS/Android (plein écran, icône, barre d'état)
├── vite.config.ts # config Vite + manifeste PWA
├── public/icons/ # icônes de l'app (192, 512, maskable, apple-touch)
└── src/
├── main.tsx # point d'entrée + enregistrement du service worker
├── Root.tsx # écran de connexion si les comptes sont activés
├── App.tsx # navigation par onglets (#/home, #/catalog…)
├── store.tsx # service de données : CRUD, +1 épisode, import (React Context)
├── types.ts # modèle MediaItem
├── index.css # thème Tailwind + composants (.field, .chip, .btn…)
├── lib/
│ ├── db.ts # IndexedDB (une base par compte)
│ ├── cloud/ # comptes : connexion, synchronisation, proxy TMDB
│ ├── backup.ts # export / import JSON + validation des fiches
│ ├── catalogApi.ts # recherche TMDB + AniList, détection du type (K-drama, anime…)
│ ├── stats.ts # statistiques et estimation du temps passé
│ ├── constants.ts # types, statuts, critères, genres, plateformes
│ ├── image.ts # compression des affiches importées depuis la galerie
│ └── utils.ts
├── components/ # BottomNav, MediaCard, MediaForm, Rating, TagInput, Poster…
└── pages/ # Accueil, Catalogue, Statistiques, Réglages
supabase/
├── migrations/…_azuucine.sql # tables + règles de sécurité (RLS) à exécuter une fois
└── functions/ # fonctions serveur : tmdb (proxy avec ta clé), delete-account
```
## Sécurité
**Code public, données privées.** Tu peux publier le code sans risque : rien de secret n'est dedans.
- **Ce qui est public (normal)** : `VITE_SUPABASE_URL` et `VITE_SUPABASE_ANON_KEY` finissent dans l'app, donc lisibles par
n'importe qui. C'est prévu ainsi : elles ne donnent accès qu'à ce que les règles de la base autorisent.
- **Ce qui est secret** : ta clé TMDB (`TMDB_API_KEY`) et la clé `service_role` vivent **uniquement dans les secrets
Supabase**, côté serveur. Elles ne sont ni dans le code, ni dans `.env`, ni dans l'app. ⚠️ Ne mets jamais une clé
secrète dans une variable `VITE_…` : tout ce qui commence par `VITE_` est envoyé au navigateur.
- **Isolation des comptes** : Row Level Security sur toutes les tables (`user_id = auth.uid()`), vérifiée par la base
elle-même. Même avec la clé publique, impossible de lire ou modifier les données d'un autre compte.
- **Profils** : les autres membres ne lisent jamais les tables directement, seulement via des fonctions SQL qui vérifient
l'accès (profil public, ou abonné accepté pour un compte privé) et retirent les avis non publics et les listes perso.
Les photos ne peuvent être envoyées que dans le dossier de leur propriétaire (JPEG/PNG/WebP, 2 Mo max) ; le pseudo de
départ est aléatoire (l'email n'est jamais montré). Les visiteurs non
connectés n'ont accès à rien. Quotas par compte (20 000 fiches, 300 listes) et taille maximale par fiche.
- **Conflits** : la modification la plus récente gagne, vérifiée par un trigger côté serveur (un appareil resté
hors-ligne ne peut pas écraser une version plus récente).
- **Proxy TMDB** : seuls les comptes connectés peuvent l'utiliser, uniquement pour quelques adresses et paramètres
précis (liste blanche), avec une limite de requêtes par compte et une liste d'origines autorisées (`ALLOWED_ORIGINS`).
- **Mots de passe** : gérés par Supabase Auth (hachés, jamais stockés dans l'app). Seule la session (jetons renouvelés
automatiquement) est gardée sur l'appareil. Déconnexion = données du compte retirées de l'appareil.
- **Données reçues** : tout ce qui vient du serveur, d'un fichier importé ou des API est revalidé et borné
(`src/lib/security.ts`, `normalizeItem`) avant d'être affiché ou enregistré.
- **Images** : seules les images embarquées (`data:image/…`, SVG exclu) et celles de TMDB / AniList sont acceptées ;
les photos de la galerie sont ré-encodées (les métadonnées EXIF/GPS disparaissent).
- **Affichage** : React échappe tout le texte (pas d'injection HTML possible) ; aucun `innerHTML`, aucun `eval`.
- **Politique de sécurité du contenu (CSP)** ajoutée à la version publiée : seuls les scripts de l'app s'exécutent et
seuls TMDB / AniList / ton projet Supabase peuvent être contactés. Le fichier `_headers` généré au build ajoute les
en-têtes de sécurité sur Netlify / Cloudflare Pages (anti-iframe, HSTS, pas de référent…).
- **Serveur de développement** : `npm run dev` n'est accessible que depuis ton PC. `npm run dev:mobile` l'ouvre à ton
réseau Wi-Fi, à utiliser seulement chez toi et à couper après.
- **Dépendances** : lance `npm run audit` de temps en temps et `npm update` pour les correctifs.
## Comptes : mise en place de Supabase (une seule fois, ~15 min)
1. **Crée le projet** : https://supabase.com → *New project* (gratuit). Région : *West EU (Paris)* ou *Frankfurt*.
Garde le mot de passe de la base quelque part (tu n'en auras pas besoin dans l'app).
2. **Crée les tables** : *SQL Editor* → *New query* → colle tout le fichier
`supabase/migrations/20260930120000_azuucine.sql` → **Run**. (Tu peux le relancer sans risque.)
3. **Réglages de connexion** : *Authentication* →
- *Sign In / Providers* → **Email** activé, **Confirm email** activé (recommandé), longueur minimale du mot de passe : 8.
- *URL Configuration* → **Site URL** = l'adresse de ton app en ligne (ex. `https://azuucine.netlify.app`),
et dans **Redirect URLs** ajoute aussi `http://localhost:5173`. Les liens des emails (confirmation, mot de passe
oublié) renvoient vers ces adresses.
4. **Le fichier `.env`** : copie `.env.example` en `.env`, puis remplis les 2 valeurs depuis *Project Settings* →
*API* (ou *API Keys*) : **Project URL** et la clé **publishable** (ou **anon** si ton projet utilise les anciennes clés).
Le `.env` n'est jamais publié (il est dans `.gitignore`).
5. **Les fonctions serveur + ta clé TMDB** (dans le dossier du projet, PowerShell) :
```powershell
npx.cmd supabase login
npx.cmd supabase link --project-ref <l'identifiant du projet, dans l'adresse du tableau de bord>
npx.cmd supabase secrets set TMDB_API_KEY=<ta clé ou ton jeton TMDB> ALLOWED_ORIGINS=https://azuucine.netlify.app,http://localhost:5173
npx.cmd supabase functions deploy tmdb --no-verify-jwt
npx.cmd supabase functions deploy delete-account --no-verify-jwt
```
(`--no-verify-jwt` : la connexion est vérifiée dans le code de chaque fonction.) Pour changer la clé TMDB plus tard,
relance juste la commande `secrets set`.
5 bis. **Profils et abonnements** : dans *SQL Editor*, colle et lance aussi `supabase/migrations/20261002120000_social.sql`
(tables des profils, abonnements, fil d'activité, et stockage des photos). Relance ensuite
`npx.cmd supabase functions deploy delete-account --project-ref <id> --no-verify-jwt --use-api` pour que la suppression
d'un compte efface aussi ses photos.
6. **Relance l'app** (`npm run dev`) : l'écran de connexion apparaît. Crée ton compte ; dans *Réglages*, AzuuCine te
propose d'ajouter à ton compte les titres déjà présents sur l'appareil.
7. **En ligne** : sur Netlify / Cloudflare Pages, ajoute `VITE_SUPABASE_URL` et `VITE_SUPABASE_ANON_KEY` dans les
variables d'environnement du site (le `.env` n'y est pas envoyé), ou fais `npm run build` sur ton PC avec le `.env`
et glisse le dossier `dist/`.
À savoir : sur l'offre gratuite, un projet Supabase **sans aucune visite pendant 7 jours** est mis en pause (rien n'est
perdu, tu le relances depuis le tableau de bord). L'app continue de marcher hors-ligne en attendant.
## 1. Lancer l'app sur ton PC
Prérequis : [Node.js](https://nodejs.org) 20 ou plus récent.
```bash
cd AzuuCine
npm install
npm run dev
```
Ouvre ensuite `http://localhost:5173` dans ton navigateur (mode mobile des outils de développement conseillé : F12 → icône téléphone).
> Pour un test rapide sur ton téléphone connecté au même Wi-Fi, lance `npm run dev:mobile` puis ouvre l'adresse « Network » affichée dans le terminal (ex. `http://192.168.1.20:5173`).
> Attention : en `http://`, le mode hors-ligne et l'installation « vraie » ne fonctionnent pas — c'est normal, il faut du HTTPS (étape 2).
## Recherche dans les bases de films
Quand tu ajoutes un titre, un champ **« Remplir depuis une base »** permet de le chercher et de préremplir la fiche
(titres, type, année, genres, synopsis, nombre et durée des épisodes, durée du film, plateforme en France, affiche).
Ta note, ton statut, tes épisodes vus et ton avis ne sont jamais écrasés.
- **Animes → AniList** : fonctionne tout de suite, sans compte. Les synopsis sont en anglais.
- **Films, séries, K-dramas, C-dramas → TMDB** : il faut une clé gratuite.
1. Crée un compte sur https://www.themoviedb.org
2. Paramètres du compte → **API** → demande une clé (usage personnel).
3. Copie la **« Clé d'API »** (ou le « Jeton d'accès en lecture ») dans AzuuCine → Réglages → Bases de films → Valider.
La clé reste sur l'appareil (à saisir sur chaque téléphone) et n'est jamais incluse dans les exports.
Seul le texte recherché est envoyé à TMDB / AniList ; ta bibliothèque reste locale.
## 2. Mettre l'app en ligne (gratuit, HTTPS)
Une PWA installable a besoin d'être servie en **HTTPS**. L'hébergeur ne sert que les fichiers de l'app
(les données sont dans Supabase avec les comptes, ou sur le téléphone en mode local).
```bash
npm run build
```
Cela crée un dossier `dist/`. Le plus simple :
1. Va sur **https://app.netlify.com/drop** (compte gratuit).
2. Glisse-dépose le dossier `dist/` sur la page.
3. Tu obtiens une adresse du type `https://azuucine-xxxx.netlify.app` (tu peux la renommer dans les réglages du site).
Pour mettre à jour l'app plus tard : `npm run build`, puis re-glisse `dist/` dans l'onglet *Deploys* du site. L'app installée se met à jour toute seule au lancement suivant.
Alternatives : Cloudflare Pages, Vercel, GitHub Pages (dans ce dernier cas, mets `base: '/nom-du-repo/'` dans `vite.config.ts`).
## 3. Installer sur l'écran d'accueil
### iPhone (Safari obligatoire)
1. Ouvre l'adresse HTTPS de ton app dans **Safari**.
2. Touche le bouton **Partager** (carré avec une flèche vers le haut).
3. Choisis **« Sur l'écran d'accueil »**, puis **Ajouter**.
4. Lance AzuuCine depuis l'icône : elle s'ouvre en plein écran, comme une app.
### Android (Chrome)
1. Ouvre l'adresse HTTPS dans **Chrome**.
2. Touche le menu **⋮** → **« Installer l'application »** (ou « Ajouter à l'écran d'accueil »).
3. Confirme : l'icône AzuuCine apparaît dans tes applications.
## ⚠️ À savoir sur les données
- **Avec un compte** : tes données sont dans ton compte et sur chaque appareil connecté. Les modifications faites
hors-ligne partent dès que le réseau revient (Réglages → Mon compte indique l'état). L'export JSON reste utile comme
sauvegarde personnelle.
- **En mode local** : les données sont propres à chaque appareil et à chaque navigateur ; désinstaller l'app ou effacer les
données du navigateur supprime la bibliothèque, pense à exporter régulièrement.
- Sur iPhone, l'app installée sur l'écran d'accueil a **son propre stockage**, distinct de Safari. Utilise toujours l'app installée.
## Fonctionnalités
- **Profils et abonnements** (avec un compte) : photo de profil, bannière, nom, pseudo et bio ; s'abonner à d'autres membres comme sur Letterboxd ; leur profil montre leur Top 5, leurs derniers visionnages, leurs stats et leur bibliothèque (avis écrits privés, sauf ceux cochés « Afficher cet avis sur mon profil ») ; compte privé avec demandes d'abonnement ; fil « Mes abonnements » sur l'accueil ; recherche par pseudo ; lien de profil à partager (`…/#/u/pseudo`)
- **9 langues** (Réglages → Langue, détectée automatiquement au premier lancement) : français, anglais, espagnol, italien, allemand, portugais (Brésil), chinois simplifié, japonais, coréen. Les dates, les nombres et les infos TMDB suivent la langue choisie. Les textes sont dans `src/i18n/locales/` (le français fait référence).
- **Comptes** : inscription par email, synchronisation automatique entre appareils, fonctionne hors-ligne, mot de passe oublié, suppression du compte
- Fiches : titre + titre original, type (Film, Série, Anime, K-Drama, C-Drama, Autre + précision), année, affiche (photo de la galerie compressée ou URL)
- Statut : À voir / En cours / Terminé / En pause / Abandonné (dates de début/fin remplies automatiquement)
- Note sur 5 étoiles (demi-étoiles) ou sur 10, au choix dans les réglages, + 4 critères détaillés optionnels + coup de cœur
- Suivi des épisodes : vus / total, saison, durée par épisode, bouton **+1** depuis l'accueil et le catalogue (passe en « Terminé » au dernier épisode)
- Genres/tags libres avec suggestions, plateforme, avis personnel
- Accueil : stats rapides, **roulette** (tirage au sort animé parmi « À voir », « En pause » ou mes préférés à revoir, filtrable par type, temps dispo, genre, plateforme), « En cours », Top 5, « À voir », « Récemment terminés »
- Catalogue : recherche instantanée (titre, titre original, tag, plateforme — sans tenir compte des accents), filtres type/statut/genre/note/coups de cœur, tris
- **Suggestions « Si tu as aimé… »** à partir de tes titres préférés, ajout en un clic à « À voir »
- **Listes perso** (Catalogue → Listes), utilisables aussi comme source de la roulette
- **Carrousels** utilisables à la souris sur ordinateur (molette ou glisser)
- **Statistiques visuelles** : filtre par année, onglets Vue d'ensemble / Habitudes / Goûts, heures, types, mois par mois, records, notes, genres, pays
- **Partage en image** d'une fiche ou d'un Top 5 (story / message)
- **Calendrier des sorties** (bouton en haut de l'accueil) : toutes les sorties à venir — films au cinéma en France, épisodes des séries et K/C-dramas les plus suivis (TMDB), tous les épisodes d'animes diffusés (AniList) — filtrables par catégorie, avec ajout en un clic à « À voir ». Onglet « Mes titres » pour ne voir que ta bibliothèque
- **Journal** (Catalogue → Journal) : ton historique de visionnage mois par mois, avec les **revisionnages** (section « Revisionnages » d'une fiche terminée)
- **Moi vs le public** (Stats → Goûts) : ta note comparée à la moyenne TMDB / AniList, écart moyen, titres que tu as plus ou moins aimés que tout le monde
- Export / import JSON (fusion ou remplacement), validation des fichiers importés
## Scripts
| Commande | Rôle |
|---|---|
| `npm run dev` | serveur de développement (uniquement sur ce PC) |
| `npm run dev:mobile` | serveur de développement ouvert au Wi-Fi (test sur téléphone) |
| `npm run audit` | vérifie les failles connues des dépendances |
| `npm run build` | build de production dans `dist/` |
| `npm run preview` | prévisualiser le build |
| `npm run typecheck` | vérification TypeScript |
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="fr" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0a0a0a" />
<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" />
<!-- iOS : mode application plein écran une fois ajoutée à l'écran d'accueil -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="AzuuCine" />
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
<link rel="icon" type="image/svg+xml" href="/icons/favicon.svg" />
<title>AzuuCine</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+9
View File
@@ -0,0 +1,9 @@
# Netlify construit le site lui-même : `npm run build`, puis publie le dossier dist.
# Les deux variables VITE_SUPABASE_* (publiques) sont réglées dans Netlify → Environment variables.
# La clé TMDB n'est JAMAIS ici : elle reste un secret Supabase.
[build]
command = "npm run build"
publish = "dist"
[build.environment]
NODE_VERSION = "22"
+6841
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
{
"name": "azuucine",
"private": true,
"version": "2.2.0",
"type": "module",
"description": "AzuuCine — suivi personnel et privé de films, séries, animes et dramas (PWA, comptes synchronisés ou 100 % locale)",
"scripts": {
"dev": "vite",
"dev:mobile": "vite --host",
"build": "vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"audit": "npm audit --omit=dev"
},
"dependencies": {
"@fontsource/inter": "^5.2.5",
"lucide-react": "^0.468.0",
"react": "^19.1.0",
"react-dom": "^19.1.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"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTphYmRiNzY0OS03MDcxLTQwNWEtYTIzOC03NDYzM2ZlNWE4ZTkAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaIQ8N/jTHplc4ECqmGQsBegAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDpiNTFjOTc5ZC01NDQ4LTRkYzItODE2Zi0xYmM3ZTYxMzgzZGNscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoKlG7dGX93hpJo9k2tdPNRAAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggvJwk+8QJ23EiQFBKMjcnfdAPsyZsN/sVoYlzr5J7StOkZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRoaXMgZmlsZSBhdCB0aGUgcmVxdWVzdCBvZiBhIHVzZXIgYW5kIG1heSBoYXZlIGNyZWF0ZWQgb3IgbW9kaWZpZWQgdGhlIGZpbGUgY29udGVudHMubXNvZnR3YXJlQWdlbnShZG5hbWVmQ2xhdWRlcmFsbEFjdGlvbnNJbmNsdWRlZPUAAADIanVtYgAAAEBqdW1kY2JvcgARABCAAACqADibcRNjMnBhLmhhc2guZGF0YQAAAAAYYzJzaHQaMtIx8J2QjAVfOUrPjUwAAACAY2JvcqVjYWxnZnNoYTI1NmNwYWRNAAAAAAAAAAAAAAAAAGRoYXNoWCBDcd1cV6whnuhaCbBEDcWMhbN2t3ArUWdonF98BIbQeWRuYW1lbmp1bWJmIG1hbmlmZXN0amV4Y2x1c2lvbnOBomVzdGFydBh9Zmxlbmd0aBkeBAAAAj5qdW1iAAAAJ2p1bWRjMmNsABEAEIAAAKoAOJtxA2MycGEuY2xhaW0udjIAAAACD2Nib3KlY2FsZ2ZzaGEyNTZpc2lnbmF0dXJleE1zZWxmI2p1bWJmPS9jMnBhL3VybjpjMnBhOmFiZGI3NjQ5LTcwNzEtNDA1YS1hMjM4LTc0NjMzZmU1YThlOS9jMnBhLnNpZ25hdHVyZWppbnN0YW5jZUlEeCx4bXA6aWlkOmFmODc4MDNmLWNmNWEtNGY0NC05ZjczLTU4ZDIzZjIzNTQwZHJjcmVhdGVkX2Fzc2VydGlvbnODomN1cmx4LXNlbGYjanVtYmY9YzJwYS5hc3NlcnRpb25zL2MycGEuaW5ncmVkaWVudC52M2RoYXNoWCC8nCT7xAnbcSJAUEoyNyd90A+zJmw3+xWhiXOvkntK06JjdXJseCpzZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmFjdGlvbnMudjJkaGFzaFggQtH5FB/fab3deIdjHUKFeBXSMU+K0Fz6zmtvjlK8FiKiY3VybHgpc2VsZiNqdW1iZj1jMnBhLmFzc2VydGlvbnMvYzJwYS5oYXNoLmRhdGFkaGFzaFggK4VboMqXzq1tMfsGhATQv4/AKSGj74+MvnsTCIWQJ2h0Y2xhaW1fZ2VuZXJhdG9yX2luZm+jZG5hbWVvQW50aHJvcGljIEZpbGVzZ3ZlcnNpb25lMS4wLjBrc3BlY1ZlcnNpb25lMi40LjAAABA4anVtYgAAAChqdW1kYzJjcwARABCAAACqADibcQNjMnBhLnNpZ25hdHVyZQAAABAIY2JvctKEWQISogEmGCFZAgowggIGMIIBjaADAgECAhRA5aAK7sI50L64g/oGQgU9Z1UTADAKBggqhkjOPQQDAzBJMRcwFQYDVQQKEw5BbnRocm9waWMsIFBCQzEuMCwGA1UEAxMlQW50aHJvcGljIENvbnRlbnQgQ3JlZGVudGlhbHMgUm9vdCBDQTAeFw0yNjA4MDcxODQzNTZaFw0yODA4MDYxOTQzNTZaMEQxFzAVBgNVBAoTDkFudGhyb3BpYywgUEJDMSkwJwYDVQQDEyBBbnRocm9waWMgQ2xhdWRlIENvbnRlbnQgU2lnbmluZzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJh6CmvLUBgFFNU0vUKlOVtE6djd17L5SuwX0LemFisBM3dkd/3cyjxFA3Qo5S46fX0/ihY0VZ7mfb9KF703t5OjWDBWMA4GA1UdDwEB/wQEAwIHgDAVBgNVHSUEDjAMBgorBgEEAYPoXgIBMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUzlHiBIFOZFsj+OPEz5o+nMHXXMIwCgYIKoZIzj0EAwMDZwAwZAIwMXMdFJ4BetLLVY7ORuE9noqbbAZOZn/aArXyTwFAZfKrPzxF2vPoJNf1+UCdg1XGAjBwX1zd9WGqYkqmL5SFqw1QySjr1zJfpJM9+1rdDwSPLMOPOjKuiXjoU/pUUeG9RwmhY3BhZFkNngAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+75
View File
@@ -0,0 +1,75 @@
import { SocialProvider } from './components/social/SocialProvider'
import { useEffect, useState } from 'react'
import BottomNav, { type Tab } from './components/BottomNav'
import MediaForm from './components/MediaForm'
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 { useMedia } from './store'
import type { MediaItem } from './types'
const TABS: Tab[] = ['home', 'catalog', 'stats', 'settings']
function tabFromHash(): Tab {
const h = window.location.hash.replace('#/', '') as Tab
return TABS.includes(h) ? h : 'home'
}
/** Formulaire ouvert : null = fermé, 'new' = ajout, sinon la fiche à éditer. */
export type EditorState = null | 'new' | MediaItem
export default function App() {
const { error } = useMedia()
const [tab, setTab] = useState<Tab>(tabFromHash)
const [editor, setEditor] = useState<EditorState>(null)
const [roulette, setRoulette] = useState(false)
const [calendar, setCalendar] = useState(false)
useEffect(() => {
const onHash = () => setTab(tabFromHash())
window.addEventListener('hashchange', onHash)
return () => window.removeEventListener('hashchange', onHash)
}, [])
const go = (t: Tab) => {
window.location.hash = `/${t}`
window.scrollTo({ top: 0 })
}
const openItem = (item: MediaItem) => setEditor(item)
const openNew = () => setEditor('new')
return (
<SocialProvider onOpenOwnItem={openItem}>
<div className="mx-auto min-h-dvh max-w-2xl">
<main className="safe-top px-4 pb-32">
{error && <p className="mt-4 rounded-xl border border-accent p-3 text-sm text-ink">{error}</p>}
{tab === 'home' && <HomePage onOpen={openItem} onAdd={openNew} onNavigate={go} onRoulette={() => setRoulette(true)} onCalendar={() => setCalendar(true)} />}
{tab === 'catalog' && <CatalogPage onOpen={openItem} onAdd={openNew} />}
{tab === 'stats' && <StatsPage />}
{tab === 'settings' && <SettingsPage />}
</main>
<BottomNav current={tab} onChange={go} onAdd={openNew} />
{roulette && <Roulette onClose={() => setRoulette(false)} onOpen={openItem} />}
{calendar && <CalendarView onClose={() => setCalendar(false)} onOpen={openItem} />}
{editor && (
<MediaForm
key={editor === 'new' ? 'new' : editor.id}
item={editor === 'new' ? undefined : editor}
onClose={() => setEditor(null)}
onGoToSettings={() => {
setEditor(null)
go('settings')
}}
/>
)}
</div>
</SocialProvider>
)
}
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useMemo, useState } from 'react'
import App from './App'
import AuthScreen, { NewPasswordScreen } from './components/AuthScreen'
import { consumeAuthRedirect, getSession, onSessionChange, type Session } from './lib/cloud/auth'
import { cloudEnabled } from './lib/cloud/config'
import { setScope } from './lib/scope'
import { MediaProvider } from './store'
/**
* Point d'entrée : sans configuration Supabase, l'app reste 100 % locale.
* Avec, il faut être connecté ; chaque compte a son propre espace sur l'appareil.
*/
export default function Root() {
const [session, setSession] = useState<Session | null>(() => (cloudEnabled ? getSession() : null))
// Lien reçu par email en cours de traitement (#access_token=…)
const [redirect, setRedirect] = useState<'checking' | 'recovery' | 'none'>(() =>
cloudEnabled && /(^#|&)(access_token|error)=/.test(location.hash) ? 'checking' : 'none',
)
const [notice, setNotice] = useState<string>()
const userId = session?.user.id
const userEmail = session?.user.email
const user = useMemo(() => (userId ? { id: userId, email: userEmail ?? '' } : undefined), [userId, userEmail])
useEffect(() => {
if (!cloudEnabled) return
const off = onSessionChange(setSession)
if (redirect === 'checking') {
consumeAuthRedirect().then((r) => {
if (r.error) setNotice(r.error)
setRedirect(r.type === 'recovery' ? 'recovery' : 'none')
setSession(getSession())
})
}
return () => {
off()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
if (!cloudEnabled) {
setScope(null)
return (
<MediaProvider>
<App />
</MediaProvider>
)
}
if (redirect === 'checking') return <div className="min-h-dvh bg-bg" />
if (redirect === 'recovery' && session) return <NewPasswordScreen onDone={() => setRedirect('none')} />
if (!session) {
setScope(null)
return <AuthScreen notice={notice} />
}
// 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 (
<MediaProvider key={session.user.id} cloudUser={user}>
<App />
</MediaProvider>
)
}
+196
View File
@@ -0,0 +1,196 @@
import Avatar from './social/Avatar'
import { useSocial } from './social/SocialProvider'
import { locale, t } from '../i18n'
import { CloudOff, KeyRound, Loader2, LogOut, RefreshCw, UserRound } from 'lucide-react'
import { useEffect, useState, type FormEvent } from 'react'
import { PASSWORD_MIN, updatePassword } from '../lib/cloud/auth'
import { cx } from '../lib/utils'
import type { AccountApi } from '../store'
import ConfirmDialog from './ConfirmDialog'
import { SectionTitle } from './ui'
function ago(iso?: string): string {
if (!iso) return t('time.never')
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000)
if (s < 60) return t('time.justNow')
if (s < 3600) return t('time.minutesAgo', { n: Math.floor(s / 60) })
if (s < 86400) return t('time.hoursAgo', { n: Math.floor(s / 3600) })
return t('time.onDate', { date: new Date(iso).toLocaleDateString(locale(), { day: 'numeric', month: 'short' }) })
}
/** Réglages → Mon compte : état de la synchro, mot de passe, déconnexion. */
export default function AccountSection({ account, onMessage }: { account: AccountApi; onMessage: (kind: 'ok' | 'error', text: string) => void }) {
const { sync } = account
const social = useSocial()
const [, tick] = useState(0)
const [pwOpen, setPwOpen] = useState(false)
const [pw, setPw] = useState('')
const [busy, setBusy] = useState<'pw' | 'logout' | 'import' | null>(null)
const [confirmLogout, setConfirmLogout] = useState(false)
// Rafraîchit « il y a x min »
useEffect(() => {
const timer = setInterval(() => tick((n) => n + 1), 30_000)
return () => clearInterval(timer)
}, [])
const statusText =
sync.state === 'syncing'
? t('account.syncing')
: sync.state === 'offline'
? t('account.offline')
: sync.state === 'error'
? t('account.syncError')
: t('account.synced', { when: ago(sync.lastSyncAt) })
const changePassword = async (e: FormEvent) => {
e.preventDefault()
setBusy('pw')
try {
await updatePassword(pw)
setPw('')
setPwOpen(false)
onMessage('ok', t('account.passwordChanged'))
} catch (err) {
onMessage('error', (err as Error).message)
} finally {
setBusy(null)
}
}
const logout = async (force = false) => {
setBusy('logout')
try {
const r = await account.logout(force)
if (r === 'pending') setConfirmLogout(true)
} finally {
setBusy(null)
}
}
const importDevice = async () => {
setBusy('import')
try {
const n = await account.importDeviceData()
onMessage('ok', t('account.imported', { count: n }))
} catch {
onMessage('error', t('account.importFailed'))
} finally {
setBusy(null)
}
}
return (
<>
<SectionTitle>{t('account.title')}</SectionTitle>
<div className="card divide-y divide-line overflow-hidden">
<div className="flex items-center gap-3.5 px-4 py-4">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-surface-2 text-ink-2">
<UserRound size={19} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{account.email}</span>
<span className={cx('mt-0.5 flex items-center gap-1.5 text-xs', sync.state === 'error' ? 'text-accent' : 'text-ink-3')}>
{sync.state === 'offline' && <CloudOff size={12} />}
{statusText}
{sync.pending > 0 && sync.state !== 'syncing' && ` · ${t('account.pending', { count: sync.pending })}`}
</span>
</span>
<button
onClick={() => account.syncNow()}
disabled={sync.state === 'syncing'}
className="grid size-10 shrink-0 place-items-center rounded-full border border-line text-ink-2"
aria-label={t('account.syncNow')}
>
{sync.state === 'syncing' ? <Loader2 size={17} className="animate-spin" /> : <RefreshCw size={17} />}
</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-left transition-colors active:bg-surface-2"
>
<Avatar url={social.me?.avatarUrl} name={social.me?.displayName ?? account.email} size={22} />
<span className="flex-1">
<span className="block font-medium">{t('social.myProfile')}</span>
{social.me && <span className="mt-0.5 block text-xs text-ink-3">@{social.me.username}</span>}
</span>
{social.requests.length > 0 && <span className="rounded-full bg-accent-fill px-2 text-[11px] font-bold text-on-accent">{social.requests.length}</span>}
<span className="text-ink-3">→</span>
</button>
{pwOpen ? (
<form onSubmit={changePassword} className="space-y-2.5 px-4 py-4">
<input
className="field"
type="password"
value={pw}
onChange={(e) => setPw(e.target.value)}
placeholder={t('account.newPasswordPh', { n: PASSWORD_MIN })}
autoComplete="new-password"
minLength={PASSWORD_MIN}
maxLength={72}
required
/>
<div className="grid grid-cols-2 gap-2">
<button type="button" onClick={() => setPwOpen(false)} className="btn btn-ghost text-sm">
{t('common.cancel')}
</button>
<button type="submit" disabled={busy === 'pw'} className="btn btn-light text-sm">
{busy === 'pw' && <Loader2 size={15} className="animate-spin" />}
{t('common.save')}
</button>
</div>
</form>
) : (
<button onClick={() => setPwOpen(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2">
<KeyRound size={19} className="text-ink-2" />
<span className="flex-1 font-medium">{t('account.changePassword')}</span>
<span className="text-ink-3">→</span>
</button>
)}
<button onClick={() => logout(false)} disabled={busy === 'logout'} className="flex w-full items-center gap-3.5 px-4 py-4 text-left 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">
<span className="block font-medium">{t('account.logout')}</span>
<span className="mt-0.5 block text-xs text-ink-3">{t('account.logoutHint')}</span>
</span>
<span className="text-ink-3">→</span>
</button>
</div>
{account.deviceData && (
<div className="card mt-3 space-y-3 border-ink p-4">
<p className="text-sm">
{account.deviceData.lists > 0
? t('account.deviceDataWithLists', { titles: t('account.nTitles', { count: account.deviceData.items }), lists: t('account.nLists', { count: account.deviceData.lists }) })
: t('account.deviceData', { titles: t('account.nTitles', { count: account.deviceData.items }) })}
</p>
<div className="grid grid-cols-2 gap-2">
<button onClick={importDevice} disabled={busy === 'import'} className="btn btn-light text-sm">
{busy === 'import' && <Loader2 size={15} className="animate-spin" />}
{t('common.add')}
</button>
<button onClick={account.dismissDeviceData} className="btn btn-ghost text-sm">
{t('account.ignore')}
</button>
</div>
<p className="text-xs text-ink-3">{t('account.deviceHint')}</p>
</div>
)}
<ConfirmDialog
open={confirmLogout}
title={t('account.unsentTitle')}
message={t('account.unsentMessage', { count: sync.pending })}
confirmLabel={t('account.logoutAnyway')}
onConfirm={() => {
setConfirmLogout(false)
void logout(true)
}}
onCancel={() => setConfirmLogout(false)}
/>
</>
)
}
+212
View File
@@ -0,0 +1,212 @@
import { t } from '../i18n'
import { LanguageSelect } from '../i18n/react'
import { Eye, EyeOff, Loader2 } from 'lucide-react'
import { useState, type FormEvent, type ReactNode } from 'react'
import { PASSWORD_MIN, requestPasswordReset, signIn, signUp, updatePassword } from '../lib/cloud/auth'
import { cx } from '../lib/utils'
type Mode = 'login' | 'signup' | 'forgot'
function PasswordField({ value, onChange, placeholder, autoComplete }: { value: string; onChange: (v: string) => void; placeholder: string; autoComplete: string }) {
const [show, setShow] = useState(false)
return (
<div className="relative">
<input
className="field pr-11"
type={show ? 'text' : 'password'}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
autoComplete={autoComplete}
minLength={PASSWORD_MIN}
maxLength={72}
required
/>
<button type="button" onClick={() => setShow((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={show ? t('auth.hidePassword') : t('auth.showPassword')}>
{show ? <EyeOff size={17} /> : <Eye size={17} />}
</button>
</div>
)
}
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">
<div className="w-full max-w-sm">
<h1 className="text-center text-[2.4rem] font-bold leading-none">
Azuu<span className="text-accent">Cine</span>
</h1>
<p className="mt-3 text-center text-sm text-ink-3">{subtitle}</p>
<div className="mt-9">{children}</div>
<div className="mt-10 flex justify-center">
<LanguageSelect className="rounded-full border border-line bg-transparent px-3 py-1.5 text-xs text-ink-3" />
</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 }: { notice?: string }) {
const [mode, setMode] = useState<Mode>('login')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const [info, setInfo] = useState<string | undefined>(notice)
const switchTo = (m: Mode) => {
setMode(m)
setError(undefined)
setInfo(undefined)
}
const submit = async (e: FormEvent) => {
e.preventDefault()
setError(undefined)
setInfo(undefined)
if (mode === 'signup' && password !== confirm) return setError(t('auth.mismatch'))
setBusy(true)
try {
if (mode === 'login') await signIn(email, password)
else if (mode === 'signup') {
const needsConfirm = await signUp(email, password)
if (needsConfirm) {
setInfo(t('auth.created', { email: email.trim() }))
setMode('login')
setPassword('')
setConfirm('')
}
} else {
await requestPasswordReset(email)
setInfo(t('auth.resetSent'))
setMode('login')
}
} catch (err) {
setError((err as Error).message)
} finally {
setBusy(false)
}
}
return (
<Shell subtitle={t('auth.tagline')}>
{mode !== 'forgot' && (
<div className="mb-5 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
{(['login', 'signup'] as const).map((m) => (
<button
key={m}
type="button"
onClick={() => switchTo(m)}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', mode === m ? 'bg-ink text-bg' : 'text-ink-3')}
>
{m === 'login' ? t('auth.loginTab') : t('auth.signupTab')}
</button>
))}
</div>
)}
<form onSubmit={submit} className="space-y-3">
{mode === 'forgot' && <h2 className="mb-1 text-lg font-semibold">{t('auth.forgotTitle')}</h2>}
<input
className="field"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t('auth.email')}
autoComplete="email"
inputMode="email"
autoCapitalize="off"
spellCheck={false}
maxLength={320}
required
/>
{mode !== 'forgot' && (
<PasswordField value={password} onChange={setPassword} placeholder={t('auth.password')} autoComplete={mode === 'login' ? 'current-password' : 'new-password'} />
)}
{mode === 'signup' && (
<>
<PasswordField value={confirm} onChange={setConfirm} placeholder={t('auth.confirmPassword')} autoComplete="new-password" />
<p className="text-xs text-ink-3">{t('auth.minChars', { n: PASSWORD_MIN })}</p>
</>
)}
{error && (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm text-ink">
{error}
</p>
)}
{info && (
<p role="status" className="rounded-xl border border-line-strong px-3 py-2.5 text-sm text-ink-2">
{info}
</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>
</form>
<div className="mt-5 text-center text-sm">
{mode === 'login' && (
<button type="button" onClick={() => switchTo('forgot')} className="text-ink-3">
{t('auth.forgot')}
</button>
)}
{mode === 'forgot' && (
<button type="button" onClick={() => switchTo('login')} className="text-ink-3">
← {t('auth.backToLogin')}
</button>
)}
</div>
<p className="mt-10 text-center text-[11px] leading-relaxed text-ink-3">
{t('auth.privacy')}
</p>
</Shell>
)
}
/** Choix d'un nouveau mot de passe (après le lien « mot de passe oublié »). */
export function NewPasswordScreen({ onDone }: { onDone: () => void }) {
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
const submit = async (e: FormEvent) => {
e.preventDefault()
if (password !== confirm) return setError(t('auth.mismatch'))
setBusy(true)
setError(undefined)
try {
await updatePassword(password)
onDone()
} catch (err) {
setError((err as Error).message)
} finally {
setBusy(false)
}
}
return (
<Shell subtitle={t('auth.newPasswordTitle')}>
<form onSubmit={submit} className="space-y-3">
<PasswordField value={password} onChange={setPassword} placeholder={t('auth.newPassword')} autoComplete="new-password" />
<PasswordField value={confirm} onChange={setConfirm} placeholder={t('auth.confirmPassword')} autoComplete="new-password" />
<p className="text-xs text-ink-3">{t('auth.minChars', { n: PASSWORD_MIN })}</p>
{error && (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm">
{error}
</p>
)}
<button type="submit" disabled={busy} className="btn btn-primary w-full py-3">
{busy && <Loader2 size={17} className="animate-spin" />}
{t('common.save')}
</button>
</form>
</Shell>
)
}
+27
View File
@@ -0,0 +1,27 @@
import { STATUS_BY_VALUE, TYPE_BY_VALUE } from '../lib/constants'
import { subtypeLabel } from '../lib/genres'
import { cx } from '../lib/utils'
import type { MediaItem, WatchStatus } from '../types'
/** Type du média en petite étiquette sobre (pas de couleur). */
export function TypeBadge({ item, className }: { item: Pick<MediaItem, 'type' | 'subtype'>; className?: string }) {
const info = TYPE_BY_VALUE[item.type]
return (
<span className={cx('inline-flex items-center rounded-full border border-line-strong px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-ink-2', className)}>
{item.type === 'autre' && item.subtype ? subtypeLabel(item.subtype) : info.label}
</span>
)
}
export function StatusDot({ status, className }: { status: WatchStatus; className?: string }) {
return <span className={cx('inline-block size-1.5 shrink-0 rounded-full', STATUS_BY_VALUE[status].dot, className)} />
}
export function StatusPill({ status }: { status: WatchStatus }) {
return (
<span className="inline-flex items-center gap-1.5 text-xs text-ink-2">
<StatusDot status={status} />
{STATUS_BY_VALUE[status].label}
</span>
)
}
+57
View File
@@ -0,0 +1,57 @@
import { t } from '../i18n'
import { BarChart3, Home, LibraryBig, Plus, Settings } from 'lucide-react'
import { cx } from '../lib/utils'
export type Tab = 'home' | 'catalog' | 'stats' | 'settings'
const ITEMS: { tab: Tab; readonly label: string; Icon: typeof Home }[] = [
{ tab: 'home', get label() { return t('nav.home') }, Icon: Home },
{ tab: 'catalog', get label() { return t('nav.catalog') }, Icon: LibraryBig },
{ tab: 'stats', get label() { return t('nav.stats') }, Icon: BarChart3 },
{ tab: 'settings', get label() { return t('nav.settings') }, Icon: Settings },
]
interface Props {
current: Tab
onChange: (tab: Tab) => void
onAdd: () => void
}
export default function BottomNav({ current, onChange, onAdd }: Props) {
const button = ({ tab, label, Icon }: (typeof ITEMS)[number]) => {
const active = current === tab
return (
<button
key={tab}
onClick={() => onChange(tab)}
aria-current={active ? 'page' : undefined}
className={cx('flex flex-1 flex-col items-center gap-1 pb-1.5 pt-2.5 text-[11px] font-medium transition-colors', active ? 'text-ink' : 'text-ink-3')}
>
<Icon size={21} strokeWidth={active ? 2.2 : 1.6} />
<span className="relative">
{label}
{/* soulignement fin, comme le lien actif de rdacet.fr */}
<span className={cx('absolute -bottom-1 left-0 h-px w-full bg-accent transition-opacity', active ? 'opacity-100' : 'opacity-0')} />
</span>
</button>
)
}
return (
<nav className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg/95 backdrop-blur-md">
<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">
<button
onClick={onAdd}
aria-label={t('nav.addTitle')}
className="grid size-12 place-items-center rounded-full bg-accent-fill text-on-accent transition active:scale-95"
>
<Plus size={24} strokeWidth={2.2} />
</button>
</div>
{ITEMS.slice(2).map(button)}
</div>
</nav>
)
}
+477
View File
@@ -0,0 +1,477 @@
import { 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 { getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi'
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 { cx, normalizeText, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput, 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 PER_DAY = 20
const PREFS_KEY = 'azuucine:calendar-prefs'
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' })
type Mode = 'all' | 'mine'
interface Entry {
key: string
date: string
title: string
poster?: string
label: string
type: MediaType
item?: MediaItem
release?: GlobalRelease
pop: number
}
function loadPrefs(): { mode: Mode; cats: ReleaseCategory[] } {
const raw = readStorage(PREFS_KEY, {}) as { mode?: unknown; cats?: unknown }
const valid = RELEASE_CATEGORIES.map((c) => c.value)
const cats = Array.isArray(raw?.cats) ? valid.filter((c) => (raw.cats as unknown[]).includes(c)) : valid
return { mode: raw?.mode === 'mine' ? 'mine' : 'all', cats: cats.length ? cats : valid }
}
function EntryRow({ e, onOpen, onAdd, busy, added }: { e: Entry; onOpen: (i: MediaItem) => void; onAdd: (e: Entry) => void; busy: boolean; added: boolean }) {
const mine = !!e.item
const body = (
<>
<div className="w-11 shrink-0">
<Poster src={e.item?.poster ?? e.poster} title={e.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{e.title}</p>
<p className={cx('mt-0.5 truncate text-xs', mine ? 'text-accent' : 'text-ink-2')}>{e.label}</p>
<div className="mt-1 flex items-center gap-1.5">
<TypeBadge item={{ type: e.type, subtype: e.item?.subtype }} />
{mine && <span className="text-[10px] font-semibold uppercase tracking-[0.04em] text-accent">{t('calendar.inMyList')}</span>}
</div>
</div>
</>
)
if (mine) {
return (
<button onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-left">
{body}
<ChevronRight size={16} className="shrink-0 text-ink-3" />
</button>
)
}
return (
<div className="flex w-full items-center gap-3 py-2.5">
{body}
<button
onClick={() => onAdd(e)}
disabled={busy || added}
className={cx(
'flex h-8 shrink-0 items-center gap-1 rounded-full px-2.5 text-xs font-semibold transition active:scale-95',
added ? 'text-accent' : 'border border-line-strong text-ink-2',
)}
aria-label={added ? t('reco.added', { title: e.title }) : t('reco.addLabel', { title: e.title })}
>
{busy ? <Loader2 size={13} className="animate-spin" /> : added ? <Check size={13} strokeWidth={3} /> : <Plus size={13} strokeWidth={3} />}
{added ? t('reco.addedShort') : t('status.a_voir')}
</button>
</div>
)
}
/** Calendrier des sorties : toutes les sorties (films, séries, animes, dramas) + celles de ma bibliothèque. */
export default function CalendarView({ onClose, onOpen }: { onClose: () => void; onOpen: (item: MediaItem) => void }) {
const { items, settings, patchMany, add } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
const [prefs, setPrefs] = useState(loadPrefs)
const [releases, setReleases] = useState(loadReleases)
const [loadingMine, setLoadingMine] = useState(false)
const today = todayISO()
const [month, setMonth] = useState(() => {
const d = new Date()
return new Date(d.getFullYear(), d.getMonth(), 1)
})
const [selected, setSelected] = useState<string>()
const [global, setGlobal] = useState<GlobalRelease[]>([])
const [loadingGlobal, setLoadingGlobal] = useState(false)
const [failed, setFailed] = useState(false)
const [expanded, setExpanded] = useState<Set<string>>(new Set())
const [busy, setBusy] = useState<string>()
const [added, setAdded] = useState<Set<string>>(new Set())
const request = useRef(0)
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
useEffect(() => {
try {
localStorage.setItem(PREFS_KEY, JSON.stringify(prefs))
} catch {
/* ignore */
}
}, [prefs])
// Mes titres : prochains épisodes suivis + sorties de « À voir »
const refreshMine = useCallback(
async (force = false) => {
if (!navigator.onLine) return
setLoadingMine(true)
try {
const [airing, rel] = await Promise.all([refreshAiring(items, loadAiring(), settings.tmdbKey, force), refreshReleases(items, settings.tmdbKey, force)])
saveAiring(airing)
setReleases(rel)
const patches = items
.filter((i) => i.status !== 'termine' && airing[i.id] && airing[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: airing[i.id].aired } }))
if (patches.length) await patchMany(patches)
} finally {
setLoadingMine(false)
}
},
[items, settings.tmdbKey, patchMany],
)
// Toutes les sorties du mois affiché (+ le mois suivant quand on regarde le mois en cours, pour les 2 prochaines semaines)
const monthsToLoad = useMemo(() => {
const list = [month]
if (monthId(month) === todayISO().slice(0, 7)) list.push(new Date(month.getFullYear(), month.getMonth() + 1, 1))
return list
}, [month])
const refreshGlobal = useCallback(
async (force = false) => {
const id = ++request.current
setGlobal(monthsToLoad.flatMap(cachedMonth))
setFailed(false)
setLoadingGlobal(true)
try {
const all: GlobalRelease[] = []
let anyFailed = false
for (const m of monthsToLoad) {
if (!isBrowsableMonth(monthId(m))) continue
const res = await loadMonth(
m,
RELEASE_CATEGORIES.map((c) => c.value),
settings.tmdbKey,
force,
)
if (id !== request.current) return
all.push(...res.releases)
anyFailed ||= res.failed.length > 0
setGlobal([...all, ...monthsToLoad.slice(monthsToLoad.indexOf(m) + 1).flatMap(cachedMonth)])
}
setFailed(anyFailed)
} finally {
if (id === request.current) setLoadingGlobal(false)
}
},
[monthsToLoad, settings.tmdbKey],
)
useEffect(() => {
void refreshMine(false)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
void refreshGlobal(false)
}, [refreshGlobal])
// Correspondance avec ma bibliothèque (identifiant de base, sinon titre)
const byExt = useMemo(() => new Map(items.filter((i) => i.externalId).map((i) => [i.externalId!, i])), [items])
const byTitle = useMemo(() => {
const m = new Map<string, MediaItem>()
for (const i of items) for (const t of [i.title, i.originalTitle]) if (t) m.set(normalizeText(t), i)
return m
}, [items])
const entries = useMemo(() => {
const map = new Map<string, Entry>()
for (const ev of calendarEvents(items, releases)) {
const key = `${ev.item.externalId ?? ev.item.id}|${ev.date}`
map.set(key, { key, date: ev.date, title: ev.item.title, label: ev.label, type: ev.item.type, item: ev.item, pop: 200 })
}
for (const r of global) {
const key = `${r.externalId}|${r.date}`
const item = byExt.get(r.externalId) ?? byTitle.get(normalizeText(r.title)) ?? (r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined)
map.set(key, {
key,
date: r.date,
title: item?.title ?? r.title,
poster: r.poster,
label: r.label,
type: item?.type ?? r.cat,
item,
release: r,
pop: item ? 200 : r.pop,
})
}
const cats = new Set<string>(prefs.cats)
return [...map.values()]
.filter((e) => (prefs.mode === 'mine' ? !!e.item : true))
.filter((e) => e.type === 'autre' || cats.has(e.type))
.sort((a, b) => a.date.localeCompare(b.date) || b.pop - a.pop || a.title.localeCompare(b.title, locale()))
}, [items, releases, global, byExt, byTitle, prefs])
const byDay = useMemo(() => {
const m = new Map<string, Entry[]>()
for (const e of entries) m.set(e.date, [...(m.get(e.date) ?? []), e])
return m
}, [entries])
// Grille du mois (semaines commençant le lundi)
const cells = useMemo(() => {
const first = new Date(month)
const offset = (first.getDay() + 6) % 7
const start = new Date(first.getFullYear(), first.getMonth(), 1 - offset)
return Array.from({ length: 42 }, (_, k) => {
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + k)
return { date: iso(d), day: d.getDate(), inMonth: d.getMonth() === month.getMonth() }
}).filter((c, k, all) => k < 35 || all.slice(35).some((x) => x.inMonth))
}, [month])
const mid = monthId(month)
const isCurrent = mid === today.slice(0, 7)
// Mois en cours : les 14 prochains jours (même s'ils débordent sur le mois suivant) ; sinon tout le mois
const lastDay = isCurrent ? iso(new Date(Date.now() + 13 * 86400000)) : `${mid}-31`
const days = [...byDay.keys()].filter((d) => (isCurrent ? d >= today : d.startsWith(mid)) && d <= lastDay).sort()
const tomorrow = iso(new Date(Date.now() + 86400000))
const dayTitle = (d: string) => (d === today ? t('time.today') : d === tomorrow ? t('time.tomorrow') : niceDate(d))
const changeMonth = (delta: number) => {
setSelected(undefined)
setExpanded(new Set())
setMonth((m) => new Date(m.getFullYear(), m.getMonth() + delta, 1))
}
const toggleCat = (c: ReleaseCategory) =>
setPrefs((p) => {
const on = p.cats.includes(c)
const cats = on ? p.cats.filter((x) => x !== c) : [...p.cats, c]
return { ...p, cats: cats.length ? cats : p.cats }
})
const addToWatchlist = async (e: Entry) => {
const r = e.release
if (!r) return
setBusy(e.key)
try {
let data: Partial<MediaInput> = {}
let poster: string | undefined
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,
})
setAdded((s) => new Set(s).add(r.externalId))
} catch {
/* réseau : le bouton reste disponible */
} finally {
setBusy(undefined)
}
}
const renderList = (list: Entry[], day: string) => {
const open = expanded.has(day)
const shown = open ? list : list.slice(0, PER_DAY)
return (
<>
<div className="divide-y divide-line">
{shown.map((e) => (
<EntryRow key={e.key} e={e} onOpen={onOpen} onAdd={addToWatchlist} busy={busy === e.key} added={!!e.release && added.has(e.release.externalId)} />
))}
</div>
{list.length > shown.length && (
<button onClick={() => setExpanded((s) => new Set(s).add(day))} className="mt-1 w-full py-2 text-xs font-medium text-ink-3">
{t('calendar.seeMore', { count: list.length - shown.length })} <span className="text-accent">→</span>
</button>
)}
</>
)
}
const loading = loadingGlobal || loadingMine
const browsable = isBrowsableMonth(mid)
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('calendar.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">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="flex-1 text-center text-base font-semibold">
{t('calendar.heading')}<span className="text-accent">{t('calendar.headingAccent')}</span>
</h2>
<button
onClick={() => {
void refreshMine(true)
void refreshGlobal(true)
}}
disabled={loading}
className="grid size-10 place-items-center rounded-full text-ink-2"
aria-label={t('calendar.refresh')}
>
{loading ? <Loader2 size={18} className="animate-spin" /> : <RefreshCw size={18} />}
</button>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="safe-bottom mx-auto max-w-2xl px-4 pb-16 pt-4">
{/* Toutes les sorties / mes titres */}
<div className="mb-3 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
{(['all', 'mine'] as const).map((m) => (
<button
key={m}
onClick={() => setPrefs((p) => ({ ...p, mode: m }))}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', prefs.mode === m ? 'bg-ink text-bg' : 'text-ink-3')}
>
{m === 'all' ? t('calendar.all') : t('calendar.mine')}
</button>
))}
</div>
<div className="no-scrollbar -mx-4 mb-5 flex gap-2 overflow-x-auto px-4">
{RELEASE_CATEGORIES.map((c) => (
<button key={c.value} onClick={() => toggleCat(c.value)} className={cx('chip shrink-0 py-1! text-[13px]', prefs.cats.includes(c.value) && 'chip-on')}>
{c.label}
</button>
))}
</div>
{/* Mois */}
<div className="mb-3 flex items-center justify-between">
<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>
<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>
</div>
<div className="grid grid-cols-7 gap-1 text-center">
{weekdays().map((w, k) => (
<span key={k} className="eyebrow py-1">
{w}
</span>
))}
{cells.map((c) => {
const evs = byDay.get(c.date) ?? []
const mine = evs.filter((e) => e.item).length
const isSel = c.date === selected
const isToday = c.date === today
return (
<button
key={c.date}
onClick={() => setSelected(isSel ? undefined : c.date)}
className={cx(
'relative flex aspect-square flex-col items-center justify-center rounded-xl text-sm transition-colors',
!c.inMonth && 'text-ink-3/50',
c.inMonth && !isSel && 'text-ink-2',
isSel && 'bg-ink font-bold text-bg',
!isSel && isToday && 'border border-accent font-bold text-ink',
!isSel && evs.length > 0 && 'bg-surface-2',
!isSel && mine > 0 && 'font-bold text-ink',
)}
aria-label={evs.length ? `${c.date} : ${t('calendar.releases', { count: evs.length })}` : c.date}
>
{c.day}
{evs.length > 0 && (
<span className="absolute bottom-1.5 flex gap-0.5">
{Array.from({ length: Math.min(3, evs.length) }, (_, k) => (
<span key={k} className={cx('size-1 rounded-full', isSel ? 'bg-bg' : k < mine ? 'bg-accent' : 'bg-ink-3')} />
))}
</span>
)}
</button>
)
})}
</div>
<p className="mt-2 flex items-center justify-center gap-4 text-[11px] text-ink-3">
<span className="flex items-center gap-1.5">
<span className="size-1.5 rounded-full bg-accent" /> {t('calendar.inMyListLegend')}
</span>
{prefs.mode === 'all' && (
<span className="flex items-center gap-1.5">
<span className="size-1.5 rounded-full bg-ink-3" /> {t('calendar.others')}
</span>
)}
</p>
{prefs.mode === 'all' && !hasKey && (
<p className="mt-4 rounded-xl border border-line px-3 py-2.5 text-xs leading-relaxed text-ink-2">
{t('calendar.needKey')}
</p>
)}
{prefs.mode === 'all' && !browsable && (
<p className="mt-4 text-center text-xs text-ink-3">{t('calendar.range')}</p>
)}
{failed && <p className="mt-4 text-center text-xs text-ink-3">{t('calendar.failed')}</p>}
{/* Détail du jour choisi, ou liste jour par jour */}
{selected ? (
<section className="mt-6">
<h3 className="mb-1 border-b border-line pb-2 text-sm font-bold first-letter:uppercase">{dayTitle(selected)}</h3>
{byDay.get(selected)?.length ? renderList(byDay.get(selected)!, selected) : <p className="py-3 text-sm text-ink-3">{t('calendar.nothingThatDay')}</p>}
</section>
) : days.length ? (
<>
{isCurrent && <h3 className="eyebrow mt-7 text-ink-2">{t('calendar.next14')}</h3>}
{days.map((d) => (
<section key={d} className="mt-6">
<h3 className="mb-1 flex items-baseline justify-between border-b border-line pb-2">
<span className="text-sm font-bold first-letter:uppercase">{dayTitle(d)}</span>
<span className="text-xs font-semibold text-accent">{byDay.get(d)!.length}</span>
</h3>
{renderList(byDay.get(d)!, d)}
</section>
))}
</>
) : (
<p className="mt-8 flex items-center justify-center gap-2 text-center text-sm text-ink-3">
{loading ? (
<>
<Loader2 size={14} className="animate-spin" /> {t('calendar.loading')}
</>
) : prefs.mode === 'mine' ? (
isCurrent ? t('calendar.noneMine14') : t('calendar.noneMineMonth')
) : (
isCurrent ? t('calendar.none14') : t('calendar.noneMonth')
)}
</p>
)}
<p className="mt-8 text-xs leading-relaxed text-ink-3">
{t('calendar.footer')}
</p>
</div>
</div>
</div>
)
}
+47
View File
@@ -0,0 +1,47 @@
import { t } from '../i18n'
import { useEffect } from 'react'
interface Props {
open: boolean
title: string
message?: string
confirmLabel?: string
onConfirm: () => void
onCancel: () => void
}
/** 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) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onCancel()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onCancel])
if (!open) return null
return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 p-4 sm:items-center" onClick={onCancel}>
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="confirm-title"
className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5"
onClick={(e) => e.stopPropagation()}
>
<h2 id="confirm-title" className="text-lg">
{title}
</h2>
{message && <p className="mt-2 text-sm leading-relaxed text-ink-2">{message}</p>}
<div className="mt-5 grid grid-cols-2 gap-2">
<button onClick={onCancel} className="btn btn-ghost">
{t('common.cancel')}
</button>
<button onClick={onConfirm} className="btn btn-primary" autoFocus>
{confirmLabel}
</button>
</div>
</div>
</div>
)
}
+176
View File
@@ -0,0 +1,176 @@
import { t } from '../i18n'
import { Check, Loader2, Search } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { getTmdbDetails, searchAniList, searchTmdb, type SearchResult, type Source } from '../lib/catalogApi'
import { remotePosterToLocal } from '../lib/image'
import { cx } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput } from '../types'
interface Props {
/** Reçoit les métadonnées trouvées (titre, type, genres, épisodes, affiche…). */
onPick: (data: Partial<MediaInput>) => void
initialQuery?: string
/** Identifiant externe de la fiche en cours d'édition (pour ne pas la signaler comme doublon). */
currentExternalId?: string
onGoToSettings?: () => void
}
const SOURCES: { value: Source; readonly label: string; hint: string }[] = [
{ value: 'tmdb', get label() { return t('search.moviesSeries') }, hint: 'TMDB' },
{ value: 'anilist', get label() { return t('typePlural.anime') }, hint: 'AniList' },
]
/** Recherche un titre dans TMDB ou AniList et remplit la fiche automatiquement. */
export default function DatabaseSearch({ onPick, initialQuery = '', currentExternalId, onGoToSettings }: Props) {
const { items, settings } = useMedia()
const hasKey = !!settings.tmdbKey?.trim()
const [source, setSource] = useState<Source>(hasKey ? 'tmdb' : 'anilist')
const [query, setQuery] = useState(initialQuery)
const [results, setResults] = useState<SearchResult[]>([])
const [loading, setLoading] = useState(false)
const [picking, setPicking] = useState<string>()
const [error, setError] = useState<string>()
const requestId = useRef(0)
const existing = new Set(items.map((i) => i.externalId).filter((id) => id && id !== currentExternalId))
// Recherche avec un petit délai pendant la frappe
useEffect(() => {
const q = query.trim()
setError(undefined)
if (q.length < 2 || (source === 'tmdb' && !hasKey)) {
setResults([])
setLoading(false)
return
}
const id = ++requestId.current
setLoading(true)
const timer = setTimeout(async () => {
try {
const res = source === 'tmdb' ? await searchTmdb(q, settings.tmdbKey!) : await searchAniList(q)
if (id === requestId.current) setResults(res)
} catch (e) {
if (id === requestId.current) {
setResults([])
setError(navigator.onLine ? (e as Error).message : t('search.offline'))
}
} finally {
if (id === requestId.current) setLoading(false)
}
}, 450)
return () => clearTimeout(timer)
}, [query, source, hasKey, settings.tmdbKey])
const pick = async (r: SearchResult) => {
setPicking(r.externalId)
setError(undefined)
try {
const data = r.source === 'tmdb' ? await getTmdbDetails(r, settings.tmdbKey!) : { ...r.prefill }
// TMDB autorise la copie locale de l'affiche (visible hors-ligne) ; AniList non, on garde l'URL.
if (r.posterUrl) data.poster = r.source === 'tmdb' ? await remotePosterToLocal(r.posterUrl) : r.posterUrl
onPick(data)
setResults([])
setQuery('')
} catch (e) {
setError((e as Error).message)
} finally {
setPicking(undefined)
}
}
return (
<div className="card p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<span className="eyebrow">{t('search.fillFrom')}</span>
<div className="flex rounded-full border border-line p-0.5">
{SOURCES.map((s) => (
<button
key={s.value}
type="button"
onClick={() => setSource(s.value)}
className={cx('rounded-full px-3 py-1 text-xs font-medium transition-colors', source === s.value ? 'bg-ink text-bg' : 'text-ink-3')}
>
{s.label}
</button>
))}
</div>
</div>
{source === 'tmdb' && !hasKey ? (
<div className="rounded-xl border border-dashed border-line-strong p-3.5 text-sm text-ink-2">
{t('search.needKey')}
{onGoToSettings && (
<button type="button" onClick={onGoToSettings} className="mt-2 block font-medium text-ink">
{t('search.openSettings')} <span className="text-accent">→</span>
</button>
)}
</div>
) : (
<div className="relative">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={source === 'tmdb' ? 'Parasite, Crash Landing on You…' : 'Frieren, One Piece…'}
className="field pl-10"
enterKeyHint="search"
autoComplete="off"
/>
{loading && <Loader2 size={17} className="absolute right-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
)}
{error && <p className="mt-2 text-sm text-accent">{error}</p>}
{results.length > 0 && (
<ul className="-mx-1 mt-3 max-h-[22rem] divide-y divide-line overflow-y-auto overscroll-contain">
{results.map((r) => {
const already = existing.has(r.externalId)
return (
<li key={r.externalId}>
<button
type="button"
onClick={() => pick(r)}
disabled={!!picking}
className="flex w-full items-center gap-3 rounded-lg px-1 py-2.5 text-left transition-colors active:bg-surface-2 disabled:opacity-60"
>
{r.thumb ? (
<img src={r.thumb} alt="" loading="lazy" className="h-[4.2rem] w-11 shrink-0 rounded-md border border-line object-cover" />
) : (
<span className="grid h-[4.2rem] w-11 shrink-0 place-items-center rounded-md border border-line bg-surface-2 text-ink-3">
{r.title.charAt(0)}
</span>
)}
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{r.title}</span>
{r.originalTitle && <span className="block truncate text-xs text-ink-3">{r.originalTitle}</span>}
<span className="mt-1 block text-[10.5px] uppercase text-ink-3">
{[r.kindLabel, r.year].filter(Boolean).join(' · ')}
{already && <span className="text-accent"> · {t('search.already')}</span>}
</span>
</span>
{picking === r.externalId ? (
<Loader2 size={18} className="shrink-0 animate-spin text-ink-3" />
) : (
<span className="shrink-0 text-accent">→</span>
)}
</button>
</li>
)
})}
</ul>
)}
{!loading && !error && query.trim().length >= 2 && results.length === 0 && !(source === 'tmdb' && !hasKey) && (
<p className="mt-3 text-sm text-ink-3">{t('search.noResults')}</p>
)}
<p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-ink-3">
<Check size={12} className="mt-0.5 shrink-0" />
{t('search.privacy', { source: source === 'tmdb' ? 'TMDB' : 'AniList' })}
</p>
</div>
)
}
+143
View File
@@ -0,0 +1,143 @@
import { t } from '../i18n'
import { Loader2, RefreshCw } from 'lucide-react'
import { useMemo, useState } from 'react'
import { fetchPublicRatings, missingPublic } from '../lib/publicRatings'
import { cx, formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem, RatingScale } from '../types'
import Poster from './Poster'
import { SectionTitle } from './ui'
/** Écart signé, arrondi au dixième dans l'échelle choisie (« 0 » plutôt que « +0,0 »). */
const signed = (v: number, scale: RatingScale) => {
const r = Math.round((scale === '5' ? v / 2 : v) * 10) / 10
if (r === 0) return '0'
return `${r > 0 ? '+' : '−'}${String(Math.abs(r)).replace('.', t('common.decimalSep'))}`
}
function Row({ item, scale }: { item: MediaItem; scale: RatingScale }) {
const gap = item.rating! - item.publicRating!
// barre centrée : moitié gauche = moins aimé, moitié droite = plus aimé (écart max affiché : 5 points /10)
const width = Math.min(50, (Math.abs(gap) / 5) * 50)
return (
<li className="flex items-center gap-3 py-2.5">
<div className="w-9 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{item.title}</p>
<p className="text-[11px] text-ink-3">
{t('public.me')} <span className="text-ink-2">{formatRating(item.rating, scale)}</span> · {t('public.label')} <span className="text-ink-2">{formatRating(item.publicRating, scale)}</span>
</p>
<div className="relative mt-1.5 h-1.5 rounded-full bg-surface-2">
<span className="absolute inset-y-0 left-1/2 w-px bg-line" />
<span
className={cx('absolute inset-y-0 rounded-full', gap >= 0 ? 'bg-accent' : 'bg-ink-3')}
style={gap >= 0 ? { left: '50%', width: `${width}%` } : { right: '50%', width: `${width}%` }}
/>
</div>
</div>
<span className={cx('w-11 shrink-0 text-right text-sm font-bold tabular-nums', gap >= 0 ? 'text-accent' : 'text-ink-2')}>{signed(gap, scale)}</span>
</li>
)
}
/** Stats « Moi vs le public » : écarts entre mes notes et la moyenne TMDB / AniList. */
export default function Disagreements({ scoped }: { scoped: MediaItem[] }) {
const { items, settings, patchMany } = useMedia()
const scale = settings.ratingScale
const [progress, setProgress] = useState<[number, number]>()
const [message, setMessage] = useState<string>()
const compared = useMemo(() => scoped.filter((i) => i.rating != null && i.publicRating != null), [scoped])
const rated = useMemo(() => items.filter((i) => i.rating != null), [items])
const missing = useMemo(() => missingPublic(rated, settings.tmdbKey).length, [rated, settings.tmdbKey, progress])
const run = async () => {
if (!navigator.onLine) return setMessage(t('common.offline'))
setMessage(undefined)
setProgress([0, missing])
try {
const patches = await fetchPublicRatings(rated, settings.tmdbKey, (done, total) => setProgress([done, total]))
if (patches.length) await patchMany(patches)
setMessage(patches.length ? t('public.added', { count: patches.length }) : t('public.noneFound'))
} finally {
setProgress(undefined)
}
}
const gaps = compared.map((i) => i.rating! - i.publicRating!)
const avg = gaps.length ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0
const agree = gaps.length ? Math.round((gaps.filter((g) => Math.abs(g) <= 1).length / gaps.length) * 100) : 0
const sorted = [...compared].sort((a, b) => b.rating! - b.publicRating! - (a.rating! - a.publicRating!))
const loved = sorted.filter((i) => i.rating! - i.publicRating! >= 1).slice(0, 5)
const hated = sorted.filter((i) => i.rating! - i.publicRating! <= -1).reverse().slice(0, 5)
const fetchButton =
missing > 0 || progress ? (
<button onClick={run} disabled={!!progress} className="flex shrink-0 items-center gap-1.5 text-xs font-medium text-ink-3 transition-colors hover:text-ink">
{progress ? <Loader2 size={13} className="animate-spin" /> : <RefreshCw size={13} className="text-accent" />}
{progress ? `${progress[0]}/${progress[1]}` : t('public.fetch', { n: missing })}
</button>
) : undefined
return (
<>
<SectionTitle action={fetchButton}>{t('public.title')}</SectionTitle>
{message && <p className="-mt-2 mb-3 text-xs text-ink-3">{message}</p>}
{compared.length === 0 ? (
<p className="text-sm text-ink-3">
{missing > 0
? t('public.hintFetch')
: settings.tmdbKey
? t('public.hintNone')
: t('public.hintKey')}
</p>
) : (
<>
<div className="grid grid-cols-2 gap-3">
<div className="card p-4">
<div className="eyebrow">{t('public.avgGap')}</div>
<div className={cx('mt-2 text-2xl font-bold leading-none tabular-nums', avg >= 0.3 && 'text-accent')}>{signed(avg, scale)}</div>
<div className="mt-1.5 text-xs text-ink-3">{Math.abs(avg) < 0.3 ? t('public.average') : avg > 0 ? t('public.generous') : t('public.harsh')}</div>
</div>
<div className="card p-4">
<div className="eyebrow">{t('public.agreeTitle')}</div>
<div className="mt-2 text-2xl font-bold leading-none tabular-nums">{agree} %</div>
<div className="mt-1.5 text-xs text-ink-3">
{scale === '5' ? t('public.within5', { count: compared.length }) : t('public.within10', { count: compared.length })}
</div>
</div>
</div>
{loved.length > 0 && (
<div className="card mt-3 px-4 pb-1.5 pt-4">
<h3 className="text-sm font-semibold">
{t('public.lovedPre')}<span className="text-accent">{t('public.lovedAccent')}</span>{t('public.lovedPost')}
</h3>
<ul className="divide-y divide-line">
{loved.map((i) => (
<Row key={i.id} item={i} scale={scale} />
))}
</ul>
</div>
)}
{hated.length > 0 && (
<div className="card mt-3 px-4 pb-1.5 pt-4">
<h3 className="text-sm font-semibold">
{t('public.hatedPre')}<span className="text-ink-2">{t('public.hatedAccent')}</span>{t('public.hatedPost')}
</h3>
<ul className="divide-y divide-line">
{hated.map((i) => (
<Row key={i.id} item={i} scale={scale} />
))}
</ul>
</div>
)}
{!loved.length && !hated.length && <p className="mt-3 text-sm text-ink-3">{t('public.allAgree')}</p>}
</>
)}
</>
)
}
+131
View File
@@ -0,0 +1,131 @@
import { locale, t } from '../i18n'
import { Star } from 'lucide-react'
import { useMemo, useState } from 'react'
import { DEFAULT_FILM_MINUTES, TYPE_BY_VALUE } from '../lib/constants'
import { watchMinutes } from '../lib/stats'
import { cx, formatDuration, formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { EmptyState } from './ui'
type Kind = 'fini' | 'revu' | 'commence' | 'abandonne'
interface Entry {
date: string
item: MediaItem
kind: Kind
minutes: number
}
const kindLabel = (k: Kind) => (k === 'fini' ? t('status.termine') : k === 'revu' ? t('journal.rewatched') : k === 'commence' ? t('journal.started') : t('status.abandonne'))
/** Toutes les dates de visionnage de la bibliothèque, de la plus récente à la plus ancienne. */
function buildEntries(items: MediaItem[]): Entry[] {
const out: Entry[] = []
for (const item of items) {
if (item.status === 'termine' && item.endDate) out.push({ date: item.endDate, item, kind: 'fini', minutes: watchMinutes(item) - rewatchMinutes(item) })
else if ((item.status === 'en_cours' || item.status === 'pause') && item.startDate) out.push({ date: item.startDate, item, kind: 'commence', minutes: 0 })
else if (item.status === 'abandonne' && (item.endDate || item.startDate)) out.push({ date: (item.endDate || item.startDate)!, item, kind: 'abandonne', minutes: 0 })
for (const d of item.rewatchDates ?? []) out.push({ date: d, item, kind: 'revu', minutes: TYPE_BY_VALUE[item.type].episodic ? 0 : item.duration || DEFAULT_FILM_MINUTES })
}
return out.sort((a, b) => b.date.localeCompare(a.date) || a.item.title.localeCompare(b.item.title, locale()))
}
const rewatchMinutes = (i: MediaItem) => (TYPE_BY_VALUE[i.type].episodic ? 0 : (i.rewatchDates?.length ?? 0) * (i.duration || DEFAULT_FILM_MINUTES))
/** Onglet « Journal » du catalogue : chronologie groupée par mois. */
export default function JournalView({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, settings } = 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('')
const [shown, setShown] = useState(6)
const months = useMemo(() => {
const list = year ? entries.filter((e) => e.date.startsWith(year)) : entries
const map = new Map<string, Entry[]>()
for (const e of list) map.set(e.date.slice(0, 7), [...(map.get(e.date.slice(0, 7)) ?? []), e])
return [...map.entries()]
}, [entries, year])
if (!entries.length) {
return <EmptyState title={t('journal.emptyTitle')} text={t('journal.emptyText')} />
}
return (
<div className="mt-2">
<div className="no-scrollbar -mx-4 mb-2 flex gap-2 overflow-x-auto px-4">
{['', ...years].map((y) => (
<button
key={y || 'all'}
onClick={() => {
setYear(y)
setShown(6)
}}
className={cx('chip py-1! text-[13px]', year === y && 'chip-on')}
>
{y || t('common.all')}
</button>
))}
</div>
{months.slice(0, shown).map(([key, list]) => {
const label = new Date(key + '-15T12:00:00').toLocaleDateString(locale(), { month: 'long', year: 'numeric' })
const minutes = list.reduce((s, e) => s + e.minutes, 0)
const finished = list.filter((e) => e.kind === 'fini' || e.kind === 'revu').length
return (
<section key={key} className="mt-7">
<div className="mb-1 flex items-baseline justify-between border-b border-line pb-2">
<h3 className="text-lg font-bold capitalize">{label}</h3>
<span className="text-xs text-ink-3">
{t('journal.seen', { count: finished })}
{minutes > 0 && ` · ${formatDuration(minutes)}`}
</span>
</div>
<ul className="divide-y divide-line">
{list.map((e) => {
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-left">
<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] uppercase text-ink-3">{d.toLocaleDateString(locale(), { weekday: 'short' }).replace('.', '')}</span>
</span>
<div className="w-10 shrink-0">
<Poster src={e.item.poster} title={e.item.title} />
</div>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-semibold">{e.item.title}</span>
<span className="mt-1 flex flex-wrap items-center gap-1.5">
<TypeBadge item={e.item} />
{e.kind !== 'fini' && (
<span className={cx('text-[11px] font-semibold', e.kind === 'revu' ? 'text-accent' : 'text-ink-3')}>{kindLabel(e.kind)}</span>
)}
</span>
</span>
{e.item.rating ? (
<span className="flex shrink-0 items-center gap-1 text-xs font-semibold">
<Star size={12} className="fill-accent text-accent" />
{formatRating(e.item.rating, settings.ratingScale)}
</span>
) : null}
</button>
</li>
)
})}
</ul>
</section>
)
})}
{months.length > shown && (
<button onClick={() => setShown((n) => n + 6)} className="btn btn-ghost mt-6 w-full">
{t('journal.more')}
</button>
)}
</div>
)
}
+233
View File
@@ -0,0 +1,233 @@
import { locale, t } from '../i18n'
import { ArrowLeft, Check, Pencil, Plus, Search, Trash2 } from 'lucide-react'
import { useMemo, useState } from 'react'
import { cx, normalizeText } from '../lib/utils'
import { useMedia } from '../store'
import type { CustomList, MediaItem } from '../types'
import { TypeBadge } from './Badges'
import ConfirmDialog from './ConfirmDialog'
import { MediaCard } from './MediaCard'
import Poster from './Poster'
import { EmptyState } from './ui'
/** Mosaïque 2×2 des premières affiches d'une liste. */
function Mosaic({ items }: { items: MediaItem[] }) {
const cells = [0, 1, 2, 3].map((i) => items[i])
return (
<div className="grid grid-cols-2 gap-0.5 overflow-hidden rounded-xl border border-line bg-surface-2">
{cells.map((item, i) =>
item?.poster ? (
<img key={i} src={item.poster} alt="" loading="lazy" className="aspect-[2/3] w-full object-cover" />
) : (
<div key={i} className="aspect-[2/3] w-full bg-surface-2" />
),
)}
</div>
)
}
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 [renaming, setRenaming] = useState(false)
const [name, setName] = useState(list.name)
const [adding, setAdding] = useState(false)
const [query, setQuery] = useState('')
const [confirm, setConfirm] = useState(false)
const members = items.filter((i) => i.listIds?.includes(list.id))
const candidates = useMemo(() => {
const q = normalizeText(query)
return items
.filter((i) => !q || normalizeText(`${i.title} ${i.originalTitle ?? ''}`).includes(q))
.sort((a, b) => a.title.localeCompare(b.title, locale()))
.slice(0, 80)
}, [items, query])
return (
<>
<button onClick={onBack} className="mt-2 flex items-center gap-1.5 text-sm text-ink-3">
<ArrowLeft size={16} /> {t('lists.myLists')}
</button>
<div className="mb-5 mt-3 flex items-start justify-between gap-3">
{renaming ? (
<form
className="flex flex-1 gap-2"
onSubmit={(e) => {
e.preventDefault()
renameList(list.id, name)
setRenaming(false)
}}
>
<input className="field" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
<button className="btn btn-light shrink-0 px-4 text-sm">OK</button>
</form>
) : (
<div className="min-w-0">
<h2 className="text-2xl leading-tight">{list.name}</h2>
<p className="mt-1 text-sm text-ink-3">
{t('account.nTitles', { count: members.length })}
</p>
</div>
)}
{!renaming && (
<div className="flex shrink-0 gap-1">
<button onClick={() => setRenaming(true)} className="grid size-10 place-items-center rounded-full border border-line text-ink-2" aria-label={t('lists.rename')}>
<Pencil size={16} />
</button>
<button onClick={() => setConfirm(true)} className="grid size-10 place-items-center rounded-full border border-line text-ink-2" aria-label={t('lists.delete')}>
<Trash2 size={16} />
</button>
</div>
)}
</div>
<button onClick={() => setAdding((v) => !v)} className={cx('chip mb-4', adding && 'chip-on')}>
{adding ? <Check size={14} /> : <Plus size={14} />}
{adding ? t('lists.done') : t('lists.addRemove')}
</button>
{adding ? (
<div>
<div className="relative mb-2">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('lists.searchLibrary')} className="field pl-10" autoFocus />
</div>
<ul className="divide-y divide-line">
{candidates.map((item) => {
const inList = item.listIds?.includes(list.id)
return (
<li key={item.id}>
<button onClick={() => toggleInList(item.id, list.id)} className="flex w-full items-center gap-3 py-2.5 text-left">
<div className="w-9 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{item.title}</p>
<div className="mt-1">
<TypeBadge item={item} />
</div>
</div>
<span
className={cx(
'grid size-7 shrink-0 place-items-center rounded-full border',
inList ? 'border-accent-fill bg-accent-fill text-on-accent' : 'border-line-strong text-transparent',
)}
>
<Check size={14} strokeWidth={3} />
</span>
</button>
</li>
)
})}
</ul>
</div>
) : members.length ? (
<div className="grid grid-cols-2 gap-x-3.5 gap-y-6 sm:grid-cols-3">
{members.map((item) => (
<MediaCard key={item.id} item={item} onOpen={onOpen} />
))}
</div>
) : (
<EmptyState title={t('lists.emptyTitle')} text={t('lists.emptyText')} />
)}
<ConfirmDialog
open={confirm}
title={t('confirm.title')}
message={t('lists.deleteConfirm', { name: list.name })}
confirmLabel={t('common.delete')}
onConfirm={async () => {
setConfirm(false)
await deleteList(list.id)
onBack()
}}
onCancel={() => setConfirm(false)}
/>
</>
)
}
/** Onglet « Listes » du catalogue. */
export default function ListsView({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, lists } = useMedia()
const [openId, setOpenId] = useState<string>()
const [creating, setCreating] = useState(false)
const open = lists.find((l) => l.id === openId)
if (open) return <ListDetail list={open} onBack={() => setOpenId(undefined)} onOpen={onOpen} />
return (
<div className="mt-2">
{creating ? (
<div className="mb-5">
<NewListForm
autoFocus
onCreated={(l) => {
setCreating(false)
setOpenId(l.id)
}}
/>
</div>
) : (
<button onClick={() => setCreating(true)} className="chip mb-5">
<Plus size={14} /> {t('lists.newList')}
</button>
)}
{lists.length === 0 ? (
<EmptyState
title={t('lists.noneTitle')}
text={t('lists.noneText')}
/>
) : (
<div className="grid grid-cols-2 gap-x-3.5 gap-y-6 sm:grid-cols-3">
{lists.map((l) => {
const members = items.filter((i) => i.listIds?.includes(l.id))
return (
<button key={l.id} onClick={() => setOpenId(l.id)} className="text-left">
<Mosaic items={members} />
<p className="mt-2 truncate text-sm font-semibold">{l.name}</p>
<p className="text-xs text-ink-3">
{t('account.nTitles', { count: members.length })}
</p>
</button>
)
})}
</div>
)}
</div>
)
}
+102
View File
@@ -0,0 +1,102 @@
import { t } from '../i18n'
import { Heart, Plus } from 'lucide-react'
import { TYPE_BY_VALUE } from '../lib/constants'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { StatusPill, TypeBadge } from './Badges'
import Poster from './Poster'
import { RatingBadge } from './Rating'
function Progress({ item }: { item: MediaItem }) {
if (!TYPE_BY_VALUE[item.type].episodic || (!item.episodesWatched && !item.episodesTotal)) return null
const pct = item.episodesTotal ? Math.min(100, (item.episodesWatched / item.episodesTotal) * 100) : 0
return (
<div className="mt-1.5">
<div className="flex justify-between text-[10.5px] text-ink-3">
<span>
{item.season ? `S${item.season} · ` : ''}{t('card.ep', { n: item.episodesWatched })}
{item.episodesTotal ? `/${item.episodesTotal}` : ''}
</span>
</div>
{item.episodesTotal ? (
<div className="mt-1.5 h-[3px] overflow-hidden rounded-full bg-line">
<div className="h-full rounded-full bg-accent" style={{ width: `${pct}%` }} />
</div>
) : null}
</div>
)
}
/** Carte verticale (grille du catalogue). */
export function MediaCard({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) {
const { settings, incrementEpisode } = useMedia()
const canIncrement =
TYPE_BY_VALUE[item.type].episodic &&
item.status === 'en_cours' &&
(!item.episodesTotal || item.episodesWatched < item.episodesTotal)
return (
<article>
<div className="relative">
<button onClick={() => onOpen(item)} className="block w-full" aria-label={t('card.open', { title: item.title })}>
<Poster src={item.poster} title={item.title} />
</button>
<TypeBadge item={item} className="pointer-events-none absolute left-2 top-2 border-transparent bg-bg/85" />
{item.favorite && (
<Heart size={15} className="pointer-events-none absolute right-2 top-2 fill-accent text-accent" />
)}
{canIncrement && (
<button
onClick={() => incrementEpisode(item.id)}
className="absolute bottom-2 right-2 flex h-8 items-center gap-0.5 rounded-full bg-accent-fill px-3 text-xs font-medium text-on-accent transition active:scale-90"
aria-label={t('card.plusOne', { title: item.title })}
>
<Plus size={13} strokeWidth={2.5} />1
</button>
)}
</div>
<button onClick={() => onOpen(item)} className="block w-full text-left">
<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} />
<RatingBadge value={item.rating} scale={settings.ratingScale} />
</div>
<Progress item={item} />
</button>
</article>
)
}
/** Ligne horizontale (accueil : « En cours »), avec compteur +1. */
export function MediaRow({ item, onOpen }: { item: MediaItem; onOpen: (item: MediaItem) => void }) {
const { settings, incrementEpisode } = useMedia()
const episodic = TYPE_BY_VALUE[item.type].episodic
const done = !!item.episodesTotal && item.episodesWatched >= item.episodesTotal
return (
<article className="card flex items-center gap-3.5 p-3">
<button onClick={() => onOpen(item)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<div className="w-14 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<TypeBadge item={item} />
<RatingBadge value={item.rating} scale={settings.ratingScale} />
</div>
<h3 className="mt-1.5 truncate text-[15px] font-semibold leading-tight">{item.title}</h3>
{episodic ? <Progress item={item} /> : <StatusPill status={item.status} />}
</div>
</button>
{episodic && !done && (
<button
onClick={() => incrementEpisode(item.id)}
className="flex h-10 shrink-0 items-center gap-0.5 rounded-full border border-accent px-3.5 text-sm text-accent transition-colors active:bg-accent-fill active:text-on-accent"
aria-label={t('card.plusOne', { title: item.title })}
>
<Plus size={14} strokeWidth={2.5} />1
</button>
)}
</article>
)
}
+555
View File
@@ -0,0 +1,555 @@
import { locale, t } from '../i18n'
import { Check, Heart, ImagePlus, Loader2, Minus, Plus, Share2, Trash2, X } from 'lucide-react'
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { CRITERIA, DEFAULT_FILM_MINUTES, MEDIA_TYPES, platformSuggestions as defaultPlatforms, STATUSES, TYPE_BY_VALUE } from '../lib/constants'
import { canonicalGenre, canonicalSubtype, genreLabel, genreSuggestions as defaultGenres, subtypeLabel, subtypeSuggestions } from '../lib/genres'
import { fileToPosterDataURL } from '../lib/image'
import { getTmdbCredits } from '../lib/catalogApi'
import { renderItemCard, slug } from '../lib/shareCard'
import { cx, formatRating, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaInput, MediaItem, RatingScale, WatchStatus } from '../types'
import { StatusDot } from './Badges'
import ConfirmDialog from './ConfirmDialog'
import SharePreview from './SharePreview'
import DatabaseSearch from './DatabaseSearch'
import { NewListForm } from './ListsView'
import Poster from './Poster'
import { RatingInput } from './Rating'
import TagInput from './TagInput'
const EMPTY: MediaInput = {
title: '',
type: 'film',
status: 'a_voir',
criteria: {},
episodesWatched: 0,
genres: [],
}
/** Champs « catalogue » qu'une recherche TMDB/AniList peut remplir. Le reste (statut, note, avis…) n'est jamais touché. */
const METADATA_KEYS = [
'title',
'originalTitle',
'type',
'subtype',
'year',
'overview',
'duration',
'episodesTotal',
'episodeDuration',
'poster',
'externalId',
'countries',
'publicRating',
] as const
function Section({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="space-y-3">
<h3 className="eyebrow text-ink-2">{title}</h3>
{children}
</section>
)
}
function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="block">
<span className="label">{label}</span>
{children}
</label>
)
}
/** input number → nombre ou undefined si vide */
const toNum = (v: string) => (v === '' ? undefined : Math.max(0, Number(v)))
interface Props {
item?: MediaItem
onClose: () => void
onGoToSettings?: () => void
}
/** « Moi vs le public » : ma note comparée à la moyenne TMDB / AniList. */
function PublicCompare({ mine, pub, scale, source }: { mine?: number; pub: number; scale: RatingScale; source: string }) {
const gap = mine != null ? mine - pub : undefined
const show = (v: number) => formatRating(v, scale) + (scale === '5' ? '/5' : '/10')
const gapText =
gap == null
? undefined
: Math.abs(gap) < 0.5
? t('public.agree')
: gap > 0
? t('public.more', { gap: formatRating(Math.abs(gap), scale) })
: t('public.less', { gap: formatRating(Math.abs(gap), scale) })
return (
<div className="flex items-center justify-between gap-3 rounded-xl border border-line px-3 py-2.5 text-sm">
<span className="text-ink-2">
{t('public.label')} <span className="font-semibold text-ink">{show(pub)}</span> <span className="text-xs text-ink-3">· {source}</span>
</span>
{gapText && <span className={cx('text-right text-xs font-semibold', gap! >= 0.5 ? 'text-accent' : 'text-ink-3')}>{gapText}</span>}
</div>
)
}
/** Liste des dates de revisionnage (films comme séries). */
function Rewatches({ dates, onChange }: { dates: string[]; onChange: (d: string[]) => void }) {
const [draft, setDraft] = useState(todayISO())
const add = () => {
if (!/^\d{4}-\d{2}-\d{2}$/.test(draft) || dates.length >= 100) return
onChange([...dates, draft].sort().reverse())
}
return (
<div className="card p-4">
{dates.length > 0 ? (
<ul className="mb-3 divide-y divide-line">
{dates.map((d, k) => (
<li key={d + k} className="flex items-center justify-between py-2 text-sm">
<span className="capitalize">{new Date(d + 'T12:00:00').toLocaleDateString(locale(), { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' })}</span>
<button type="button" onClick={() => onChange(dates.filter((_, j) => j !== k))} className="grid size-8 place-items-center rounded-full text-ink-3" aria-label={t('form.removeRewatch')}>
<X size={16} />
</button>
</li>
))}
</ul>
) : (
<p className="mb-3 text-sm text-ink-3">{t('form.rewatchHint')}</p>
)}
<div className="flex gap-2">
<input className="field flex-1" type="date" value={draft} max={todayISO()} onChange={(e) => setDraft(e.target.value)} aria-label={t('form.rewatchDate')} />
<button type="button" onClick={add} className="btn btn-ghost shrink-0">
<Plus size={16} /> {t('journal.rewatched')}
</button>
</div>
</div>
)
}
export default function MediaForm({ item, onClose, onGoToSettings }: Props) {
const { add, update, remove, items, settings, lists, account } = useMedia()
const [form, setForm] = useState<MediaInput>(() => {
if (!item) return EMPTY
const { id: _id, createdAt: _c, updatedAt: _u, ...rest } = item
return rest
})
const [saving, setSaving] = useState(false)
const [criteriaOpen] = useState(() => Object.keys(item?.criteria ?? {}).length > 0)
const [showSearch, setShowSearch] = useState(!item)
const [filledFrom, setFilledFrom] = useState<string>()
const [posterError, setPosterError] = useState<string>()
const fileRef = useRef<HTMLInputElement>(null)
const typeInfo = TYPE_BY_VALUE[form.type]
// Bloque le défilement de la page derrière la feuille
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
const set = <K extends keyof MediaInput>(key: K, value: MediaInput[K]) => setForm((f) => ({ ...f, [key]: value }))
// Suggestions = listes par défaut + ce que j'ai déjà utilisé
const genreSuggestions = useMemo(() => [...new Set([...items.flatMap((i) => i.genres.map(genreLabel)), ...defaultGenres()])], [items])
const platformSuggestions = useMemo(
() => [...new Set([...items.map((i) => i.platform).filter(Boolean), ...defaultPlatforms()])] as string[],
[items],
)
/** Applique les infos trouvées en ligne sans écraser mon suivi (statut, note, épisodes vus, avis…). */
const applyMetadata = (data: Partial<MediaInput>) => {
setForm((f) => {
const next: MediaInput = { ...f }
for (const key of METADATA_KEYS) {
if (data[key] !== undefined) (next as unknown as Record<string, unknown>)[key] = data[key]
}
if (data.type && data.type !== 'autre') next.subtype = undefined
if (data.genres?.length) next.genres = [...new Set([...f.genres, ...data.genres])]
if (data.platform && !f.platform) next.platform = data.platform
if (next.episodesTotal && next.episodesWatched > next.episodesTotal) next.episodesWatched = next.episodesTotal
return next
})
setFilledFrom(data.externalId?.startsWith('anilist') ? 'AniList' : 'TMDB')
setShowSearch(false)
}
const setStatus = (status: WatchStatus) =>
setForm((f) => {
const next = { ...f, status }
if (status === 'en_cours' && !f.startDate) next.startDate = todayISO()
if (status === 'termine') {
if (!f.endDate) next.endDate = todayISO()
if (f.episodesTotal && TYPE_BY_VALUE[f.type].episodic) next.episodesWatched = f.episodesTotal
}
return next
})
const changeEpisodes = (delta: number) =>
setForm((f) => {
let n = Math.max(0, f.episodesWatched + delta)
if (f.episodesTotal) n = Math.min(n, f.episodesTotal)
return { ...f, episodesWatched: n }
})
const onPickImage = async (file?: File) => {
if (!file) return
setPosterError(undefined)
try {
set('poster', await fileToPosterDataURL(file))
} catch (e) {
setPosterError((e as Error).message)
}
}
const submit = async () => {
if (!form.title.trim()) return
setSaving(true)
const clean: MediaInput = {
...form,
title: form.title.trim(),
originalTitle: form.originalTitle?.trim() || undefined,
subtype: form.type === 'autre' ? (form.subtype?.trim() ? canonicalSubtype(form.subtype) : undefined) : undefined,
platform: form.platform?.trim() || undefined,
notes: form.notes?.trim() || undefined,
poster: form.poster?.trim() || undefined,
overview: form.overview?.trim() || undefined,
}
try {
if (item) await update(item.id, clean)
else await add(clean)
onClose()
} finally {
setSaving(false)
}
}
const [confirmDelete, setConfirmDelete] = useState(false)
const [sharing, setSharing] = useState(false)
const [preview, setPreview] = useState<{ blob: Blob; filename: string }>()
const shareCard = async () => {
if (!item) return
setSharing(true)
try {
// Générique (réalisation, production, casting) depuis TMDB si possible
let credits
if (settings.tmdbKey && form.externalId?.startsWith('tmdb:') && navigator.onLine) {
credits = await getTmdbCredits(form.externalId, settings.tmdbKey).catch(() => undefined)
}
const blob = await renderItemCard({ ...item, ...form }, settings.ratingScale, credits)
setPreview({ blob, filename: `azuucine-${slug(form.title)}.png` })
} finally {
setSharing(false)
}
}
const onDelete = async () => {
if (!item) return
setConfirmDelete(false)
await remove(item.id)
onClose()
}
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={item ? t('common.edit') : t('common.add')}>
{/* En-tête */}
<header className="safe-top border-b border-line bg-bg">
<div className="mx-auto flex max-w-2xl items-center gap-2 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} />
</button>
<h2 className="flex-1 text-center text-base font-semibold">
{item ? t('form.editTitle') : t('form.newTitle')}
<span className="text-accent">{item ? t('form.editAccent') : t('form.newAccent')}</span>
</h2>
<button onClick={submit} disabled={!form.title.trim() || saving} className="btn btn-light px-4 py-2 text-sm">
{t('common.save')}
</button>
</div>
</header>
<form
className="flex-1 overflow-y-auto overscroll-contain"
onSubmit={(e) => {
e.preventDefault()
void submit()
}}
>
<div className="safe-bottom mx-auto max-w-2xl space-y-9 px-4 py-6 pb-16">
{/* Recherche en ligne */}
{showSearch ? (
<DatabaseSearch
onPick={applyMetadata}
initialQuery={item ? form.title : ''}
currentExternalId={item?.externalId}
onGoToSettings={onGoToSettings}
/>
) : (
<button
type="button"
onClick={() => setShowSearch(true)}
className="flex w-full items-center justify-between rounded-2xl border border-dashed border-line-strong px-4 py-3 text-left text-sm text-ink-2"
>
<span>
{filledFrom ? (
<>
{t('form.filledFrom')} <span className="text-ink">{filledFrom}</span> — {t('form.canEdit')}
</>
) : (
t('form.fillFromDb')
)}
</span>
<span className="text-accent">→</span>
</button>
)}
{/* Affiche + titres */}
<div className="flex gap-4">
<div className="w-28 shrink-0">
<button type="button" onClick={() => fileRef.current?.click()} className="relative block w-full" aria-label={t('form.pickPoster')}>
<Poster src={form.poster} title={form.title || '?'} />
<span className="absolute bottom-2 right-2 grid size-8 place-items-center rounded-full bg-bg/85 text-ink">
<ImagePlus size={15} />
</span>
</button>
<input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => onPickImage(e.target.files?.[0])} />
{form.poster && (
<button type="button" onClick={() => set('poster', undefined)} className="mt-2 w-full text-xs text-ink-3">
{t('form.removeImage')}
</button>
)}
</div>
<div className="min-w-0 flex-1 space-y-4">
<Field label={t('form.title')}>
<input className="field" value={form.title} onChange={(e) => set('title', e.target.value)} placeholder={t('form.titlePh')} required />
</Field>
<Field label={t('form.originalTitle')}>
<input className="field" value={form.originalTitle ?? ''} onChange={(e) => set('originalTitle', e.target.value)} placeholder={t('form.originalTitlePh')} />
</Field>
</div>
</div>
{form.overview && (
<details className="-mt-3 text-sm text-ink-2">
<summary className="eyebrow cursor-pointer select-none">{t('form.synopsis')}</summary>
<p className="mt-2 whitespace-pre-line leading-relaxed">{form.overview}</p>
</details>
)}
{/* Type */}
<Section title={t('form.type')}>
<div className="flex flex-wrap gap-2">
{MEDIA_TYPES.map((mt) => (
<button key={mt.value} type="button" onClick={() => set('type', mt.value)} className={cx('chip', form.type === mt.value && 'chip-on')}>
{mt.label}
</button>
))}
</div>
{form.type === 'autre' && (
<Field label={t('form.subtype')}>
<input className="field" list="subtypes" value={form.subtype ? subtypeLabel(form.subtype) : ''} onChange={(e) => set('subtype', e.target.value)} placeholder={t('form.subtypePh')} />
<datalist id="subtypes">
{subtypeSuggestions().map((s) => (
<option key={s} value={s} />
))}
</datalist>
</Field>
)}
</Section>
{/* Statut */}
<Section title={t('form.status')}>
<div className="flex flex-wrap gap-2">
{STATUSES.map((s) => (
<button key={s.value} type="button" onClick={() => setStatus(s.value)} className={cx('chip', form.status === s.value && 'chip-on')}>
<StatusDot status={s.value} />
{s.label}
</button>
))}
</div>
</Section>
{/* Note */}
<Section title={t('form.myRating')}>
<div className="card space-y-4 p-4">
<RatingInput value={form.rating} onChange={(v) => set('rating', v)} scale={settings.ratingScale} />
{form.publicRating != null && <PublicCompare mine={form.rating} pub={form.publicRating} scale={settings.ratingScale} source={form.externalId?.startsWith('anilist:') ? 'AniList' : 'TMDB'} />}
<button type="button" onClick={() => set('favorite', !form.favorite)} className={cx('chip', form.favorite && 'border-accent text-ink')}>
<Heart size={15} className={form.favorite ? 'fill-accent text-accent' : ''} />
{t('form.favorite')}
</button>
<details className="border-t border-line pt-3" open={criteriaOpen}>
<summary className="cursor-pointer select-none text-sm text-ink-2">{t('form.criteria')}</summary>
<div className="mt-4 space-y-4">
{CRITERIA.map((c) => (
<div key={c.key}>
<span className="eyebrow mb-1.5 block">{c.label}</span>
<RatingInput
size="sm"
label={c.label}
scale={settings.ratingScale}
value={form.criteria[c.key]}
onChange={(v) =>
setForm((f) => {
const criteria = { ...f.criteria }
if (v == null) delete criteria[c.key]
else criteria[c.key] = v
return { ...f, criteria }
})
}
/>
</div>
))}
</div>
</details>
</div>
</Section>
{/* Épisodes / durée */}
{typeInfo.episodic ? (
<Section title={t('form.episodes')}>
<div className="card space-y-5 p-4">
<div className="flex items-center justify-between">
<span className="text-sm text-ink-2">{t('home.episodesSeen')}</span>
<div className="flex items-center gap-3">
<button type="button" onClick={() => changeEpisodes(-1)} className="grid size-10 place-items-center rounded-full border border-line-strong text-ink-2" aria-label={t('form.minusEp')}>
<Minus size={17} />
</button>
<span className="min-w-16 text-center text-2xl font-bold tabular-nums">
{form.episodesWatched}
{form.episodesTotal ? <span className="text-base text-ink-3">/{form.episodesTotal}</span> : null}
</span>
<button type="button" onClick={() => changeEpisodes(1)} className="grid size-10 place-items-center rounded-full bg-accent-fill text-on-accent" aria-label={t('form.plusEp')}>
<Plus size={17} strokeWidth={2.5} />
</button>
</div>
</div>
<div className="grid grid-cols-3 gap-3">
<Field label={t('form.total')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodesTotal ?? ''} onChange={(e) => set('episodesTotal', toNum(e.target.value))} placeholder="?" />
</Field>
<Field label={t('form.season')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.season ?? ''} onChange={(e) => set('season', toNum(e.target.value))} placeholder="1" />
</Field>
<Field label={t('form.minPerEp')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.episodeDuration ?? ''} onChange={(e) => set('episodeDuration', toNum(e.target.value))} placeholder={String(typeInfo.episodeMinutes)} />
</Field>
</div>
</div>
</Section>
) : (
<Section title={t('form.duration')}>
<Field label={t('form.durationMin')}>
<input className="field" type="number" inputMode="numeric" min={0} value={form.duration ?? ''} onChange={(e) => set('duration', toNum(e.target.value))} placeholder={String(DEFAULT_FILM_MINUTES)} />
</Field>
</Section>
)}
{/* Infos */}
<Section title={t('form.info')}>
<div className="grid grid-cols-2 gap-3">
<Field label={t('form.start')}>
<input className="field" type="date" value={form.startDate ?? ''} onChange={(e) => set('startDate', e.target.value || undefined)} />
</Field>
<Field label={t('form.end')}>
<input className="field" type="date" value={form.endDate ?? ''} onChange={(e) => set('endDate', e.target.value || undefined)} />
</Field>
<Field label={t('form.year')}>
<input className="field" type="number" inputMode="numeric" value={form.year ?? ''} onChange={(e) => set('year', toNum(e.target.value))} placeholder="2024" />
</Field>
<Field label={t('form.platform')}>
<input className="field" list="platforms" value={form.platform ?? ''} onChange={(e) => set('platform', e.target.value)} placeholder="Netflix…" />
<datalist id="platforms">
{platformSuggestions.map((p) => (
<option key={p} value={p} />
))}
</datalist>
</Field>
</div>
<div>
<span className="label">{t('form.genres')}</span>
<TagInput
value={form.genres}
onChange={(g) => set('genres', g)}
suggestions={genreSuggestions}
placeholder={t('form.genresPh')}
display={genreLabel}
normalize={canonicalGenre}
/>
</div>
</Section>
{(form.status === 'termine' || (form.rewatchDates?.length ?? 0) > 0) && (
<Section title={t('form.rewatches')}>
<Rewatches dates={form.rewatchDates ?? []} onChange={(d) => set('rewatchDates', d.length ? d : undefined)} />
</Section>
)}
<Section title={t('lists.myLists')}>
{lists.length > 0 && (
<div className="flex flex-wrap gap-2">
{lists.map((l) => {
const on = form.listIds?.includes(l.id)
return (
<button
key={l.id}
type="button"
onClick={() =>
set('listIds', on ? form.listIds!.filter((x) => x !== l.id) : [...(form.listIds ?? []), l.id])
}
className={cx('chip', on && 'chip-on')}
>
{on && <Check size={14} />}
{l.name}
</button>
)
})}
</div>
)}
<NewListForm onCreated={(l) => set('listIds', [...(form.listIds ?? []), l.id])} />
</Section>
<Section title={t('form.review')}>
<textarea className="field min-h-32 resize-y" value={form.notes ?? ''} onChange={(e) => set('notes', e.target.value)} placeholder={t('form.reviewPh')} />
{account && (
<label className="mt-3 flex items-start gap-2.5 text-sm text-ink-2">
<input type="checkbox" className="mt-0.5 size-4 accent-[var(--color-accent)]" checked={!!form.notesPublic} onChange={(e) => set('notesPublic', e.target.checked || undefined)} />
<span>
{t('form.reviewPublic')}
<span className="block text-xs text-ink-3">{t('form.reviewPublicHint')}</span>
</span>
</label>
)}
</Section>
<div className="space-y-2 border-t border-line pt-6">
<button type="submit" disabled={!form.title.trim() || saving} className="btn btn-primary w-full py-3">
{item ? t('form.saveChanges') : t('form.addToLibrary')} <span aria-hidden>→</span>
</button>
{item && (
<button type="button" onClick={shareCard} disabled={sharing} className="btn btn-ghost w-full">
{sharing ? <Loader2 size={17} className="animate-spin" /> : <Share2 size={17} />} {t('form.shareImage')}
</button>
)}
{item && (
<button type="button" onClick={() => setConfirmDelete(true)} className="btn w-full text-ink-3">
<Trash2 size={17} /> {t('form.delete')}
</button>
)}
</div>
</div>
</form>
{preview && <SharePreview blob={preview.blob} filename={preview.filename} title={form.title} onClose={() => setPreview(undefined)} />}
<ConfirmDialog
open={confirmDelete}
title={t('confirm.title')}
message={item ? t('form.deleteConfirm', { title: item.title }) : undefined}
confirmLabel={t('common.delete')}
onConfirm={onDelete}
onCancel={() => setConfirmDelete(false)}
/>
</div>
)
}
+120
View File
@@ -0,0 +1,120 @@
import { locale, t } from '../i18n'
import { Loader2, RefreshCw } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { loadAiring, needsCheck, novelties, refreshAiring, saveAiring, trackable, type AiringCache } from '../lib/airing'
import { formatDate, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import Poster from './Poster'
import { SectionTitle } from './ui'
const dayLabel = (iso: string) => {
const d = new Date(iso + 'T12:00:00')
const diff = Math.round((d.getTime() - new Date(todayISO() + 'T12:00:00').getTime()) / 86400000)
if (diff <= 0) return t('time.today')
if (diff === 1) return t('time.tomorrow')
if (diff < 7) return d.toLocaleDateString(locale(), { weekday: 'long' })
return t('time.onDate', { date: formatDate(iso) })
}
/** Section « Nouveautés » de l'accueil : nouveaux épisodes et nouvelles saisons. */
export default function NewEpisodes({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, loading, settings, patchMany, update } = useMedia()
const [cache, setCache] = useState<AiringCache>(loadAiring)
const [checking, setChecking] = useState(false)
const started = useRef(false)
const check = useCallback(
async (force = false) => {
setChecking(true)
try {
const next = await refreshAiring(items, loadAiring(), settings.tmdbKey, force)
saveAiring(next)
setCache(next)
// Met à jour le nombre total d'épisodes des séries en cours si de nouveaux sont sortis
const patches = trackable(items)
.filter((i) => i.status !== 'termine' && next[i.id] && next[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: next[i.id].aired } }))
if (patches.length) await patchMany(patches)
} finally {
setChecking(false)
}
},
[items, settings.tmdbKey, patchMany],
)
// Vérification automatique au plus toutes les 12 h, au lancement
useEffect(() => {
if (loading || started.current || !navigator.onLine) return
started.current = true
const c = loadAiring()
if (trackable(items).some((i) => needsCheck(i, c))) void check()
}, [loading, items, check])
const list = useMemo(() => novelties(items, cache), [items, cache])
const tracked = trackable(items).length
const hasAniList = trackable(items).some((i) => i.externalId!.startsWith('anilist:'))
if (!tracked) return null
const resume = (item: MediaItem, aired: number) =>
update(item.id, { status: 'en_cours', episodesTotal: aired, startDate: item.startDate ?? todayISO(), endDate: undefined })
return (
<>
<SectionTitle
action={
<button onClick={() => check(true)} disabled={checking} className="flex items-center gap-1.5 text-xs font-medium text-ink-3">
{checking ? <Loader2 size={13} className="animate-spin" /> : <RefreshCw size={13} />}
{checking ? t('settings.checking') : t('newEp.check')}
</button>
}
>
{t('newEp.title')}
</SectionTitle>
{list.length === 0 ? (
<p className="text-sm text-ink-3">
{checking
? t('newEp.checking')
: !settings.tmdbKey && !hasAniList
? t('newEp.needKey')
: t('newEp.nothing', { count: tracked })}
{!checking && !settings.tmdbKey && hasAniList && ` ${t('newEp.needKeyAlso')}`}
</p>
) : (
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{list.map(({ item, info, unwatched, kind }) => (
<div key={item.id} className="card flex w-64 shrink-0 gap-3 p-2.5">
<button onClick={() => onOpen(item)} className="w-14 shrink-0">
<Poster src={item.poster} title={item.title} />
</button>
<div className="flex min-w-0 flex-1 flex-col">
<span className="eyebrow text-accent">
{kind === 'new_season' ? t('newEp.newSeason') : kind === 'new_episodes' ? t('newEp.catchUp') : t('newEp.soon')}
</span>
<button onClick={() => onOpen(item)} className="mt-1 truncate text-left text-sm font-semibold">
{item.title}
</button>
<span className="mt-0.5 text-xs text-ink-2">
{kind === 'upcoming'
? t('newEp.epWhen', { ep: info.next!.episode, when: dayLabel(info.next!.date) })
: t('newEp.available', { count: unwatched })}
</span>
{kind !== 'upcoming' && info.next && (
<span className="text-[11px] text-ink-3">
{t('newEp.next', { ep: info.next.episode, when: dayLabel(info.next.date) })}
</span>
)}
{kind === 'new_season' && (
<button onClick={() => resume(item, info.aired)} className="mt-auto self-start pt-1.5 text-xs font-semibold text-accent">
{t('newEp.resume')} →
</button>
)}
</div>
</div>
))}
</div>
)}
</>
)
}
+25
View File
@@ -0,0 +1,25 @@
import { useState } from 'react'
import { cx } from '../lib/utils'
/** Affiche du média, ou une vignette sobre (aplat + initiale en serif) si aucune image. */
export default function Poster({ src, title, className }: { src?: string; title: string; className?: string }) {
const [broken, setBroken] = useState(false)
if (src && !broken) {
return (
<img
src={src}
alt=""
loading="lazy"
onError={() => setBroken(true)}
className={cx('aspect-[2/3] w-full rounded-xl border border-line bg-surface-2 object-cover', className)}
/>
)
}
const initial = title.trim().charAt(0).toUpperCase() || '?'
return (
<div className={cx('relative grid aspect-[2/3] w-full place-items-center overflow-hidden rounded-xl border border-line bg-surface-2', className)}>
<span className="text-3xl font-bold text-ink-3">{initial}</span>
<span className="absolute bottom-0 left-0 h-[3px] w-1/3 bg-accent-fill" />
</div>
)
}
+99
View File
@@ -0,0 +1,99 @@
import { t } from '../i18n'
import { Star, X } from 'lucide-react'
import type { MouseEvent } from 'react'
import { cx, formatRating } from '../lib/utils'
import type { RatingScale } from '../types'
/** Petite note compacte (étoile + valeur) pour les cartes. */
export function RatingBadge({ value, scale }: { value?: number; scale: RatingScale }) {
if (value == null || value === 0) return null
return (
<span className="inline-flex items-center gap-1 text-xs font-semibold text-ink">
<Star size={12} className="fill-accent text-accent" />
{formatRating(value, scale)}
<span className="font-normal text-ink-3">/{scale}</span>
</span>
)
}
interface InputProps {
/** Valeur interne sur 10 */
value?: number
onChange: (value: number | undefined) => void
scale: RatingScale
size?: 'lg' | 'sm'
label?: string
}
/**
* Saisie de note.
* - Échelle 5 : étoiles avec demi-étoiles (touche la moitié gauche d'une étoile pour ½).
* - Échelle 10 : curseur au pas de 0,5.
* La valeur est toujours stockée sur 10.
*/
export function RatingInput({ value, onChange, scale, size = 'lg', label }: InputProps) {
const px = size === 'lg' ? 34 : 24
if (scale === '10') {
return (
<div className="flex items-center gap-3">
<input
type="range"
min={0}
max={10}
step={0.5}
value={value ?? 0}
aria-label={label ?? t('rating.outOf10')}
onChange={(e) => {
const v = Number(e.target.value)
onChange(v === 0 ? undefined : v)
}}
className="h-2 flex-1 accent-accent-fill"
/>
<span className={cx('w-14 text-right font-semibold tabular-nums', size === 'lg' ? 'text-xl' : 'text-sm')}>
{value ? formatRating(value, '10') : '—'}
<span className="text-xs font-normal text-ink-3">/10</span>
</span>
</div>
)
}
const stars = (value ?? 0) / 2
const pick = (e: MouseEvent<HTMLButtonElement>, index: number) => {
const rect = e.currentTarget.getBoundingClientRect()
const half = e.clientX - rect.left < rect.width / 2
const next = (index + (half ? 0.5 : 1)) * 2
onChange(next === value ? undefined : next) // retoucher la même valeur efface la note
}
return (
<div className="flex items-center gap-1" role="group" aria-label={label ?? 'Note sur 5'}>
{Array.from({ length: 5 }, (_, i) => {
const fill = Math.max(0, Math.min(1, stars - i))
return (
<button
key={i}
type="button"
onClick={(e) => pick(e, i)}
className="relative transition active:scale-90"
style={{ width: px, height: px }}
aria-label={t('rating.stars', { count: i + 1 })}
>
<Star size={px} strokeWidth={1.5} className="absolute inset-0 text-ink-3" />
<span className="absolute inset-0 overflow-hidden" style={{ width: `${fill * 100}%` }}>
<Star size={px} strokeWidth={1.5} className="fill-accent text-accent" />
</span>
</button>
)
})}
<span className={cx('ml-2 tabular-nums text-ink-2', size === 'lg' ? 'text-base' : 'text-xs')}>
{value ? formatRating(value, '5') : ''}
</span>
{value != null && size === 'lg' && (
<button type="button" onClick={() => onChange(undefined)} className="ml-auto p-1 text-ink-3" aria-label={t('rating.clear')}>
<X size={18} />
</button>
)}
</div>
)
}
+153
View File
@@ -0,0 +1,153 @@
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 { useMedia } from '../store'
import type { MediaInput, MediaItem } from '../types'
import Poster from './Poster'
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 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))
} 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="normal-case tracking-normal 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 right-2 flex h-8 items-center gap-1 rounded-full 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>
)}
</>
)
}
+391
View File
@@ -0,0 +1,391 @@
import { genreLabel } from '../lib/genres'
import { locale, t } from '../i18n'
import { Check, Dices, RotateCcw, X } from 'lucide-react'
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type TransitionEvent } from 'react'
import { MEDIA_TYPES, TYPE_BY_VALUE } from '../lib/constants'
import {
buildPool,
loadFilters,
pickRandom,
saveFilters,
sessionMinutes,
SOURCES,
sourcePool,
TIME_OPTIONS,
type RouletteFilters,
} from '../lib/roulette'
import { cx, formatDuration, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
import { RatingBadge } from './Rating'
const CARD = 112 // largeur d'une affiche dans le rouleau (w-28)
const GAP = 12
const STEP = CARD + GAP
const TARGET = 30 // position du gagnant dans le rouleau
const SPIN_MS = 3800
interface Props {
onClose: () => void
onOpen: (item: MediaItem) => void
}
const shuffle = <T,>(arr: T[]) => {
const a = [...arr]
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[a[i], a[j]] = [a[j], a[i]]
}
return a
}
export default function Roulette({ onClose, onOpen }: Props) {
const { items, settings, 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])
const genres = useMemo(() => [...new Set(base.flatMap((i) => i.genres))].sort((a, b) => a.localeCompare(b, locale())), [base])
const platforms = useMemo(() => [...new Set(base.map((i) => i.platform).filter(Boolean) as string[])].sort(), [base])
const [reel, setReel] = useState<MediaItem[]>([])
const [offset, setOffset] = useState(0)
const [animate, setAnimate] = useState(false)
const [spinning, setSpinning] = useState(false)
const [result, setResult] = useState<MediaItem>()
const [started, setStarted] = useState(false)
const rolled = useRef(new Set<string>())
const viewport = useRef<HTMLDivElement>(null)
const pending = useRef<MediaItem | undefined>(undefined)
const spinningRef = useRef(false)
const resultRef = useRef<MediaItem | undefined>(undefined)
resultRef.current = result
const xFor = (index: number, jitter = 0) => {
const w = viewport.current?.clientWidth ?? 360
return w / 2 - (index * STEP + CARD / 2) + jitter
}
// Bloque le défilement derrière + mémorise les filtres
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
useEffect(() => saveFilters(filters), [filters])
// Changer les filtres efface le tirage en cours
useEffect(() => {
setResult(undefined)
setStarted(false)
}, [filters])
// Rouleau « au repos » : les affiches possibles, centrées (sans toucher à un tirage affiché)
useLayoutEffect(() => {
if (spinning || resultRef.current) return
if (!pool.length) {
setReel([])
return
}
let idle = shuffle(pool)
while (idle.length < 9) idle = idle.concat(shuffle(pool))
setAnimate(false)
setReel(idle)
setOffset(xFor(4))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pool, result === undefined])
const setF = (patch: Partial<RouletteFilters>) => setFilters((f) => ({ ...f, ...patch }))
const toggle = <T,>(list: T[], v: T) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v])
const spin = () => {
const winner = pickRandom(pool, rolled.current)
if (!winner || spinning) return
rolled.current.add(winner.id)
pending.current = winner
setResult(undefined)
setStarted(false)
const strip = Array.from({ length: TARGET + 5 }, () => pool[Math.floor(Math.random() * pool.length)])
strip[TARGET] = winner
setReel(strip)
// L'animation est le cœur de la roulette : on la joue toujours,
// même si Windows / le téléphone a les « effets d'animation » désactivés.
setSpinning(true)
spinningRef.current = true
setAnimate(false)
setOffset(xFor(2))
// On place le rouleau au départ, puis on lance l'animation juste après
window.setTimeout(() => {
setAnimate(true)
setOffset(xFor(TARGET, (Math.random() - 0.5) * (CARD - 30)))
}, 40)
// Filet de sécurité si l'événement de fin d'animation n'arrive pas (onglet en arrière-plan…)
window.setTimeout(finishSpin, SPIN_MS + 400)
}
const finishSpin = () => {
if (!spinningRef.current) return
spinningRef.current = false
setSpinning(false)
setResult(pending.current)
navigator.vibrate?.(35)
}
const onSpinEnd = (e: TransitionEvent<HTMLDivElement>) => {
if (e.target !== e.currentTarget || e.propertyName !== 'transform') return
finishSpin()
}
const watchIt = async () => {
if (!result) return
if (result.status === 'a_voir' || result.status === 'pause') {
await update(result.id, { status: 'en_cours', startDate: result.startDate ?? todayISO() })
}
setStarted(true)
}
const winnerIndex = result ? reel.indexOf(result, reel.length > TARGET ? TARGET : 0) : -1
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('roulette.name')}>
<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">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="flex-1 text-center text-base font-semibold">
{t('roulette.heading')}<span className="text-accent">{t('roulette.headingAccent')}</span>
</h2>
<span className="size-10" />
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="safe-bottom mx-auto max-w-2xl pb-16">
{/* Rouleau d'affiches */}
<div ref={viewport} className="relative mt-6 h-[184px] overflow-hidden">
{reel.length > 0 ? (
<div
className="flex gap-3"
style={{
transform: `translateX(${offset}px)`,
transition: animate ? `transform ${SPIN_MS}ms cubic-bezier(0.12, 0.72, 0.1, 1)` : 'none',
}}
onTransitionEnd={onSpinEnd}
>
{reel.map((item, i) => (
<div
key={i}
className={cx(
'w-28 shrink-0 transition-opacity duration-300',
result && i !== winnerIndex && 'opacity-30',
)}
>
<div className={cx('rounded-xl', result && i === winnerIndex && 'ring-2 ring-accent ring-offset-2 ring-offset-bg')}>
<Poster src={item.poster} title={item.title} />
</div>
</div>
))}
</div>
) : (
<div className="flex h-full items-center justify-center gap-3 opacity-40">
{[0, 1, 2].map((k) => (
<div key={k} className="grid aspect-[2/3] w-28 place-items-center rounded-xl border border-dashed border-line-strong text-3xl font-bold text-ink-3">
?
</div>
))}
</div>
)}
{/* Repère central */}
<div className="pointer-events-none absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-accent/70" />
<div className="pointer-events-none absolute left-1/2 top-0 size-0 -translate-x-1/2 border-x-[7px] border-t-[9px] border-x-transparent border-t-accent" />
<div className="pointer-events-none absolute bottom-0 left-1/2 size-0 -translate-x-1/2 border-x-[7px] border-b-[9px] border-x-transparent border-b-accent" />
</div>
<div className="space-y-8 px-4">
{/* Bouton / résultat */}
{result && !spinning ? (
<div className="sheet-in card mt-6 p-4">
<span className="eyebrow text-accent">{t('roulette.tonight')}</span>
<h3 className="mt-2 text-xl leading-tight">{result.title}</h3>
{result.originalTitle && <p className="text-sm text-ink-3">{result.originalTitle}</p>}
<div className="mt-2.5 flex flex-wrap items-center gap-2 text-xs text-ink-3">
<TypeBadge item={result} />
{result.year && <span>{result.year}</span>}
<span>
{TYPE_BY_VALUE[result.type].episodic
? `${result.episodesTotal ? `${t('roulette.nEps', { n: result.episodesTotal })} · ` : ''}${t('roulette.perEp', { duration: formatDuration(sessionMinutes(result)) })}`
: formatDuration(sessionMinutes(result))}
</span>
{result.platform && <span>· {result.platform}</span>}
<RatingBadge value={result.rating} scale={settings.ratingScale} />
</div>
{result.status === 'pause' && (
<p className="mt-2 text-xs text-ink-2">
{result.episodesTotal
? t('roulette.stoppedAtOf', { ep: result.episodesWatched, total: result.episodesTotal })
: t('roulette.stoppedAt', { ep: result.episodesWatched })}
</p>
)}
{result.overview && <p className="mt-3 line-clamp-4 text-sm leading-relaxed text-ink-2">{result.overview}</p>}
{result.genres.length > 0 && <p className="mt-2 text-xs text-ink-3">{result.genres.slice(0, 4).map(genreLabel).join(' · ')}</p>}
{started ? (
<div className="mt-4 flex items-center justify-between gap-2 rounded-xl bg-surface-2 p-3 text-sm">
<span className="flex items-center gap-2">
<Check size={16} className="text-accent" /> {t('roulette.enjoy')}
</span>
<button onClick={onClose} className="font-medium text-ink">
{t('common.close')} <span className="text-accent">→</span>
</button>
</div>
) : (
<div className="mt-4 grid grid-cols-2 gap-2">
<button onClick={watchIt} className="btn btn-primary">
{t('roulette.watchIt')}
</button>
<button onClick={spin} className="btn btn-ghost">
<RotateCcw size={16} /> {t('roulette.again')}
</button>
</div>
)}
<button onClick={() => onOpen(result)} className="mt-3 w-full text-center text-xs font-medium text-ink-3">
{t('roulette.seeItem')}
</button>
</div>
) : (
<div className="mt-6 text-center">
<button onClick={spin} disabled={!pool.length || spinning} className="btn btn-primary px-8 py-3.5 text-base">
<Dices size={20} className={spinning ? 'animate-spin' : ''} />
{spinning ? t('roulette.spinning') : t('roulette.spin')}
</button>
<p className="mt-2.5 text-xs text-ink-3">
{pool.length
? t('roulette.poolSize', { count: pool.length })
: t('roulette.empty')}
</p>
</div>
)}
{/* Filtres */}
<section className="space-y-5 border-t border-line pt-6">
<h3 className="eyebrow text-ink-2">{t('roulette.inside')}</h3>
<div>
<span className="label">{t('roulette.pickFrom')}</span>
<div className="flex flex-wrap gap-2">
{SOURCES.map((s) => {
const on = filters.sources.includes(s.value)
const count = sourcePool(items, [s.value]).length
return (
<button
key={s.value}
onClick={() => {
const next = toggle(filters.sources, s.value)
if (next.length || filters.listIds.length) setF({ sources: next, genre: '', platform: '' })
}}
disabled={spinning}
className={cx('chip', on && 'chip-on')}
aria-pressed={on}
>
{s.label}
<span className={cx('text-xs', on ? 'opacity-60' : 'text-ink-3')}>{count}</span>
</button>
)
})}
{lists.map((l) => {
const on = filters.listIds.includes(l.id)
const count = items.filter((i) => i.listIds?.includes(l.id)).length
return (
<button
key={l.id}
onClick={() => {
const next = toggle(filters.listIds, l.id)
if (next.length || filters.sources.length) setF({ listIds: next, genre: '', platform: '' })
}}
disabled={spinning}
className={cx('chip', on && 'chip-on')}
aria-pressed={on}
>
{l.name}
<span className={cx('text-xs', on ? 'opacity-60' : 'text-ink-3')}>{count}</span>
</button>
)
})}
</div>
<p className="mt-1.5 text-[11px] text-ink-3">{t('roulette.rewatchHint')}</p>
</div>
<div>
<span className="label">{t('form.type')}</span>
<div className="flex flex-wrap gap-2">
<button onClick={() => setF({ types: [] })} disabled={spinning} className={cx('chip', !filters.types.length && 'chip-on')}>
{t('catalog.all')}
</button>
{MEDIA_TYPES.map((mt) => (
<button
key={mt.value}
onClick={() => setF({ types: toggle(filters.types, mt.value) })}
disabled={spinning}
className={cx('chip', filters.types.includes(mt.value) && 'chip-on')}
>
{mt.label}
</button>
))}
</div>
</div>
<div>
<span className="label">{t('roulette.time')}</span>
<div className="grid grid-cols-4 gap-1 rounded-full border border-line p-1">
{TIME_OPTIONS.map((o) => (
<button
key={o.value}
onClick={() => setF({ time: o.value })}
disabled={spinning}
className={cx('rounded-full py-2 text-xs font-medium transition-colors', filters.time === o.value ? 'bg-ink text-bg' : 'text-ink-3')}
>
{o.label}
</button>
))}
</div>
</div>
{(genres.length > 0 || platforms.length > 0) && (
<div className="grid grid-cols-2 gap-3">
<label className="block">
<span className="label">{t('catalog.genre')}</span>
<select className="field" value={filters.genre} onChange={(e) => setF({ genre: e.target.value })} disabled={spinning}>
<option value="">{t('catalog.all')}</option>
{genres.map((g) => (
<option key={g} value={g}>
{genreLabel(g)}
</option>
))}
</select>
</label>
<label className="block">
<span className="label">{t('form.platform')}</span>
<select className="field" value={filters.platform} onChange={(e) => setF({ platform: e.target.value })} disabled={spinning}>
<option value="">{t('catalog.allRatings')}</option>
{platforms.map((p) => (
<option key={p} value={p}>
{p}
</option>
))}
</select>
</label>
</div>
)}
</section>
</div>
</div>
</div>
</div>
)
}
+66
View File
@@ -0,0 +1,66 @@
import { t } from '../i18n'
import { Download, Share2, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { shareImage } from '../lib/shareCard'
interface Props {
blob: Blob
filename: string
title: string
onClose: () => void
}
/** Aperçu de l'image générée avant de la partager ou de l'enregistrer. */
export default function SharePreview({ blob, filename, title, onClose }: Props) {
const [url, setUrl] = useState<string>()
const [busy, setBusy] = useState(false)
const canShare = useMemo(() => {
try {
return !!navigator.canShare?.({ files: [new File([blob], filename, { type: 'image/png' })] })
} catch {
return false
}
}, [blob, filename])
// L'adresse temporaire de l'image est créée puis libérée avec l'aperçu
useEffect(() => {
const u = URL.createObjectURL(blob)
setUrl(u)
return () => URL.revokeObjectURL(u)
}, [blob])
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const go = async () => {
setBusy(true)
try {
await shareImage(blob, filename, title)
} finally {
setBusy(false)
}
}
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="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} />
</button>
<span className="text-sm font-semibold">{t('share.preview')}</span>
<span className="size-10" />
</div>
<div className="flex min-h-0 flex-1 items-center justify-center px-6">
{url && <img src={url} alt={t('share.posterAlt', { title })} className="max-h-full max-w-full rounded-2xl border border-line object-contain" />}
</div>
<div className="safe-bottom mx-auto grid w-full max-w-md grid-cols-1 gap-2 px-4 pb-4 pt-4">
<button onClick={go} disabled={busy} className="btn btn-primary py-3">
{canShare ? <Share2 size={18} /> : <Download size={18} />}
{canShare ? t('share.share') : t('share.saveImage')}
</button>
</div>
</div>
)
}
+74
View File
@@ -0,0 +1,74 @@
import { t } from '../i18n'
import { X } from 'lucide-react'
import { useMemo, useState } from 'react'
import { normalizeText } from '../lib/utils'
interface Props {
value: string[]
onChange: (tags: string[]) => void
suggestions: string[]
placeholder?: string
/** Texte affiché pour une valeur enregistrée (ex. genre traduit) */
display?: (value: string) => string
/** Valeur enregistrée à partir du texte saisi (ex. nom de référence d'un genre) */
normalize?: (input: string) => string
}
/** Saisie de tags libres avec suggestions tapables. */
export default function TagInput({ value, onChange, suggestions, placeholder, display = (v) => v, normalize = (v) => v }: Props) {
const [text, setText] = useState('')
const add = (raw: string) => {
const typed = raw.trim().replace(/,$/, '').trim()
if (!typed) return
const tag = normalize(typed)
if (!value.some((v) => normalizeText(v) === normalizeText(tag))) onChange([...value, tag])
setText('')
}
const filtered = useMemo(() => {
const q = normalizeText(text)
const taken = new Set(value.map((v) => normalizeText(display(v))))
return suggestions.filter((s) => !taken.has(normalizeText(s)) && (!q || normalizeText(s).includes(q))).slice(0, 12)
}, [text, value, suggestions])
return (
<div>
<div className="field flex flex-wrap items-center gap-1.5 py-2!">
{value.map((tag) => (
<span key={tag} className="inline-flex items-center gap-1 rounded-full border border-line-strong py-1 pl-3 pr-1.5 text-sm text-ink">
{display(tag)}
<button type="button" onClick={() => onChange(value.filter((v) => v !== tag))} aria-label={t('common.removeX', { name: display(tag) })} className="text-ink-3">
<X size={14} />
</button>
</span>
))}
<input
value={text}
onChange={(e) => (e.target.value.endsWith(',') ? add(e.target.value) : setText(e.target.value))}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
add(text)
} else if (e.key === 'Backspace' && !text && value.length) {
onChange(value.slice(0, -1))
}
}}
onBlur={() => add(text)}
placeholder={value.length ? '' : placeholder}
className="min-w-24 flex-1 bg-transparent py-0.5 outline-none placeholder:text-ink-3"
enterKeyHint="done"
/>
</div>
{filtered.length > 0 && (
<div className="no-scrollbar -mx-1 mt-2 flex gap-1.5 overflow-x-auto px-1 pb-1">
{filtered.map((s) => (
<button key={s} type="button" onMouseDown={(e) => e.preventDefault()} onClick={() => add(s)} className="chip py-1! text-xs">
+ {s}
</button>
))}
</div>
)}
</div>
)
}
+162
View File
@@ -0,0 +1,162 @@
import { genreLabel } from '../lib/genres'
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'
import Poster from './Poster'
import { RatingBadge } from './Rating'
import TopFiveEditor from './TopFiveEditor'
import SharePreview from './SharePreview'
import { LinkArrow, SectionTitle } from './ui'
/** Chiffre géant en contour (rouge pour le n°1, gris pour les autres). */
function RankNumber({ rank, big }: { rank: number; big?: boolean }) {
const style: CSSProperties = {
WebkitTextStroke: big ? '2.5px var(--color-accent)' : '2px var(--color-ink-3)',
color: 'transparent',
fontSize: big ? '10rem' : '5.5rem',
lineHeight: 0.8,
letterSpacing: '-0.06em',
}
return (
<span aria-hidden className="pointer-events-none select-none font-black" style={style}>
{rank}
</span>
)
}
function EmptySlot({ rank, onClick, big }: { rank: number; onClick: () => void; big?: boolean }) {
return (
<button
onClick={onClick}
className={cx(
'grid aspect-[2/3] place-items-center rounded-xl border border-dashed border-line-strong text-ink-3 transition-colors active:bg-surface-2',
big ? 'w-32' : 'w-full',
)}
aria-label={t('top.pick', { rank })}
>
<Plus size={big ? 22 : 18} />
</button>
)
}
export default function TopFive({ onOpen }: { onOpen: (item: MediaItem) => void }) {
const { items, settings } = useMedia()
const cats = TOP_CATEGORIES.filter((c) => settings.topCategories.includes(c.value))
const [selected, setSelected] = useState<TopCategory>()
const [editing, setEditing] = useState(false)
const [sharing, setSharing] = useState(false)
const [preview, setPreview] = useState<{ blob: Blob; filename: string; title: string }>()
if (!cats.length) return null
const current = cats.find((c) => c.value === selected) ?? cats[0]
const byRank = new Map(items.filter((i) => i.top?.category === current.value).map((i) => [i.top!.rank, i]))
const first = byRank.get(1)
const edit = () => setEditing(true)
const share = async () => {
setSharing(true)
try {
const blob = await renderTopCard(current.plural, [1, 2, 3, 4, 5].map((r) => byRank.get(r)))
setPreview({ blob, filename: `azuucine-top5-${slug(current.plural)}.png`, title: t('top.shareTitle', { category: current.plural }) })
} finally {
setSharing(false)
}
}
return (
<>
<SectionTitle
action={
<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>
</SectionTitle>
{/* Choix de la catégorie */}
{cats.length > 1 && (
<div className="no-scrollbar -mx-4 mb-5 flex gap-2 overflow-x-auto px-4">
{cats.map((c) => (
<button key={c.value} onClick={() => setSelected(c.value)} className={cx('chip py-1! text-[13px]', current.value === c.value && 'chip-on')}>
{c.plural}
</button>
))}
</div>
)}
{/* N°1 : grand chiffre rouge + affiche + infos */}
<div className="flex items-end">
<div className="relative flex shrink-0 items-end">
<span className="-mr-3 mb-1">
<RankNumber rank={1} big />
</span>
{first ? (
<button onClick={() => onOpen(first)} className="relative z-10 w-32">
<Poster src={first.poster} title={first.title} />
</button>
) : (
<EmptySlot rank={1} onClick={edit} big />
)}
</div>
<div className="min-w-0 flex-1 pb-1 pl-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-left 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">
{first.year && <span>{first.year}</span>}
<RatingBadge value={first.rating} scale={settings.ratingScale} />
</div>
{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>
)}
</div>
</div>
{/* N°2 à 5 : chiffres en contour qui dépassent derrière les affiches */}
<div className="mt-14 grid grid-cols-4 gap-x-2">
{[2, 3, 4, 5].map((rank) => {
const item = byRank.get(rank)
return (
<div key={rank} className="min-w-0">
<div className="relative">
<span className="absolute -left-1 -top-9 z-0">
<RankNumber rank={rank} />
</span>
<div className="relative z-10 ml-4">
{item ? (
<button onClick={() => onOpen(item)} className="block w-full">
<Poster src={item.poster} title={item.title} />
</button>
) : (
<EmptySlot rank={rank} onClick={edit} />
)}
</div>
</div>
<p className="ml-4 mt-1.5 truncate text-[11px] font-medium text-ink-2" title={item?.title}>
{item ? item.title : '—'}
</p>
{item?.rating ? <p className="ml-4 text-[10px] text-ink-3">{formatRating(item.rating, settings.ratingScale)}/{settings.ratingScale}</p> : null}
</div>
)
})}
</div>
{preview && <SharePreview {...preview} onClose={() => setPreview(undefined)} />}
{editing && <TopFiveEditor category={current.value} onClose={() => setEditing(false)} />}
</>
)
}
+186
View File
@@ -0,0 +1,186 @@
import { locale, t } from '../i18n'
import { ChevronDown, ChevronUp, Search, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { TOP_CATEGORIES } from '../lib/constants'
import { cx, formatRating, normalizeText } from '../lib/utils'
import { useMedia } from '../store'
import type { TopCategory } from '../types'
import { TypeBadge } from './Badges'
import Poster from './Poster'
interface Props {
category: TopCategory
onClose: () => void
}
/** Composer son Top 5 : 5 places, ajout depuis la bibliothèque, réordonnancement. */
export default function TopFiveEditor({ category: initialCategory, onClose }: Props) {
const { items, settings, setTopList } = useMedia()
const [category, setCategory] = useState(initialCategory)
const currentIds = (cat: TopCategory) =>
items
.filter((i) => i.top?.category === cat)
.sort((a, b) => a.top!.rank - b.top!.rank)
.map((i) => i.id)
const [ids, setIds] = useState<string[]>(() => currentIds(initialCategory))
const [query, setQuery] = useState('')
const [allTypes, setAllTypes] = useState(false)
const [saving, setSaving] = useState(false)
const catInfo = TOP_CATEGORIES.find((c) => c.value === category)!
const byId = useMemo(() => new Map(items.map((i) => [i.id, i])), [items])
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = prev
}
}, [])
/** Changer de catégorie enregistre d'abord celle en cours. */
const switchCategory = async (cat: TopCategory) => {
if (cat === category) return
await setTopList(category, ids)
setCategory(cat)
setIds(currentIds(cat).filter((id) => !ids.includes(id)))
setQuery('')
}
const candidates = useMemo(() => {
const q = normalizeText(query)
return items
.filter((i) => !ids.includes(i.id))
.filter((i) => allTypes || q || i.type === category)
.filter((i) => !q || normalizeText(`${i.title} ${i.originalTitle ?? ''}`).includes(q))
.sort((a, b) => Number(b.type === category) - Number(a.type === category) || (b.rating ?? -1) - (a.rating ?? -1) || a.title.localeCompare(b.title, locale()))
.slice(0, 60)
}, [items, ids, query, allTypes, category])
const move = (index: number, delta: number) =>
setIds((prev) => {
const next = [...prev]
const target = index + delta
if (target < 0 || target >= next.length) return prev
;[next[index], next[target]] = [next[target], next[index]]
return next
})
const save = async () => {
setSaving(true)
await setTopList(category, ids)
setSaving(false)
onClose()
}
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('top.editLabel')}>
<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">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="flex-1 text-center text-base font-semibold">
Top <span className="text-accent">5</span> · {catInfo.plural}
</h2>
<button onClick={save} disabled={saving} className="btn btn-light px-4 py-2 text-sm">
{t('common.save')}
</button>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="safe-bottom mx-auto max-w-2xl space-y-6 px-4 py-5 pb-16">
<div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4">
{TOP_CATEGORIES.map((c) => (
<button key={c.value} onClick={() => switchCategory(c.value)} className={cx('chip py-1! text-[13px]', category === c.value && 'chip-on')}>
{c.plural}
</button>
))}
</div>
{/* Les 5 places */}
<ol className="space-y-2">
{[0, 1, 2, 3, 4].map((index) => {
const item = ids[index] ? byId.get(ids[index]) : undefined
return (
<li key={index} className={cx('flex items-center gap-3 rounded-2xl border p-2.5', item ? 'border-line bg-surface' : 'border-dashed border-line-strong')}>
<span className={cx('w-8 text-center text-3xl font-black', index === 0 ? 'text-accent' : 'text-ink-3')}>{index + 1}</span>
{item ? (
<>
<div className="w-10 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold">{item.title}</p>
<p className="text-xs text-ink-3">
{[item.year, item.rating ? `${formatRating(item.rating, settings.ratingScale)}/${settings.ratingScale}` : null].filter(Boolean).join(' · ')}
</p>
</div>
<div className="flex shrink-0 items-center">
<button onClick={() => move(index, -1)} disabled={index === 0} className="grid size-9 place-items-center text-ink-2 disabled:opacity-20" aria-label={t('common.moveUp')}>
<ChevronUp size={18} />
</button>
<button onClick={() => move(index, 1)} disabled={index >= ids.length - 1} className="grid size-9 place-items-center text-ink-2 disabled:opacity-20" aria-label={t('common.moveDown')}>
<ChevronDown size={18} />
</button>
<button onClick={() => setIds((p) => p.filter((id) => id !== item.id))} className="grid size-9 place-items-center text-ink-3" aria-label={t('common.removeX', { name: item.title })}>
<X size={17} />
</button>
</div>
</>
) : (
<span className="py-3 text-sm text-ink-3">{t('top.freeSlot')}</span>
)}
</li>
)
})}
</ol>
{/* Ajout depuis la bibliothèque */}
<div>
<div className="mb-3 flex items-center justify-between">
<h3 className="eyebrow text-ink-2">{t('top.addFromLibrary')}</h3>
<button onClick={() => setAllTypes((v) => !v)} className={cx('chip py-0.5! text-xs', allTypes && 'chip-on')}>
{t('top.allTypes')}
</button>
</div>
<div className="relative mb-2">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('top.searchTitle')} className="field pl-10" />
</div>
{ids.length >= 5 && <p className="py-2 text-xs text-ink-3">{t('top.full')}</p>}
<ul className="divide-y divide-line">
{candidates.map((item) => (
<li key={item.id}>
<button
onClick={() => setIds((p) => (p.length < 5 ? [...p, item.id] : p))}
disabled={ids.length >= 5}
className="flex w-full items-center gap-3 py-2.5 text-left disabled:opacity-40"
>
<div className="w-9 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{item.title}</p>
<div className="mt-1 flex items-center gap-2 text-xs text-ink-3">
<TypeBadge item={item} />
{item.rating ? `${formatRating(item.rating, settings.ratingScale)}/${settings.ratingScale}` : ''}
{item.top && item.top.category !== category && (
<span className="text-accent">
{t('top.number', { rank: item.top.rank })} {TOP_CATEGORIES.find((c) => c.value === item.top!.category)?.plural}
</span>
)}
</div>
</div>
<span className="text-accent">+</span>
</button>
</li>
))}
{candidates.length === 0 && <li className="py-4 text-sm text-ink-3">{t('top.noCandidates')}</li>}
</ul>
</div>
</div>
</div>
</div>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { cx } from '../../lib/utils'
/** Photo de profil ronde, ou initiale sur fond neutre. */
export default function Avatar({ url, name, size = 40, className }: { url?: string; name: string; size?: number; className?: string }) {
const style = { width: size, height: size }
if (url) return <img src={url} alt="" style={style} className={cx('shrink-0 rounded-full border border-line bg-surface-2 object-cover', className)} />
return (
<span style={{ ...style, fontSize: size * 0.42 }} className={cx('grid shrink-0 place-items-center rounded-full border border-line bg-surface-2 font-bold text-ink-2', className)}>
{(name.trim().charAt(0) || '?').toUpperCase()}
</span>
)
}
+176
View File
@@ -0,0 +1,176 @@
import { Camera, ImagePlus, Loader2, Lock, Trash2 } from 'lucide-react'
import { useRef, useState } from 'react'
import { t } from '../../i18n'
import { deleteProfileImage, updateProfile, uploadProfileImage, USERNAME_RE, type ProfilePatch } from '../../lib/cloud/social'
import { cropImageToJpeg } from '../../lib/image'
import { cx } from '../../lib/utils'
import Avatar from './Avatar'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
/** Modifier mon profil : photo, bannière, nom, pseudo, bio, compte privé. */
export default function EditProfile({ onClose }: { onClose: () => void }) {
const { me, refresh } = useSocial()
const [displayName, setDisplayName] = useState(me?.displayName ?? '')
const [username, setUsername] = useState(me?.username ?? '')
const [bio, setBio] = useState(me?.bio ?? '')
const [isPrivate, setIsPrivate] = useState(me?.isPrivate ?? false)
const [avatar, setAvatar] = useState<{ blob?: Blob; preview?: string; removed?: boolean }>({ preview: me?.avatarUrl })
const [banner, setBanner] = useState<{ blob?: Blob; preview?: string; removed?: boolean }>({ preview: me?.bannerUrl })
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string>()
const avatarInput = useRef<HTMLInputElement>(null)
const bannerInput = useRef<HTMLInputElement>(null)
const cleanUsername = username.trim().toLowerCase().replace(/^@/, '')
const usernameOk = USERNAME_RE.test(cleanUsername)
const nameOk = displayName.trim().length >= 1 && displayName.trim().length <= 40
const pick = async (kind: 'avatar' | 'banner', file?: File) => {
if (!file) return
setError(undefined)
try {
const blob = kind === 'avatar' ? await cropImageToJpeg(file, 400, 400) : await cropImageToJpeg(file, 1500, 500, 0.84)
const preview = URL.createObjectURL(blob)
if (kind === 'avatar') setAvatar({ blob, preview })
else setBanner({ blob, preview })
} catch (e) {
setError((e as Error).message)
}
}
const save = async () => {
if (!me || !usernameOk || !nameOk) return
setSaving(true)
setError(undefined)
const uploaded: string[] = []
try {
const patch: ProfilePatch = {}
if (displayName.trim() !== me.displayName) patch.display_name = displayName.trim()
if (cleanUsername !== me.username) patch.username = cleanUsername
if (bio.trim() !== me.bio) patch.bio = bio.trim()
if (isPrivate !== me.isPrivate) patch.is_private = isPrivate
if (avatar.blob) {
patch.avatar_url = await uploadProfileImage('avatar', avatar.blob)
uploaded.push(patch.avatar_url)
} else if (avatar.removed) patch.avatar_url = null
if (banner.blob) {
patch.banner_url = await uploadProfileImage('banner', banner.blob)
uploaded.push(patch.banner_url)
} else if (banner.removed) patch.banner_url = null
if (Object.keys(patch).length) await updateProfile(patch)
// Les anciennes images ne servent plus
if ('avatar_url' in patch) await deleteProfileImage(me.avatarUrl)
if ('banner_url' in patch) await deleteProfileImage(me.bannerUrl)
await refresh()
onClose()
} catch (e) {
for (const url of uploaded) await deleteProfileImage(url)
setError((e as Error).message)
} finally {
setSaving(false)
}
}
if (!me) {
return (
<Sheet label={t('social.editProfile')} title={t('social.editProfile')} onClose={onClose}>
<p className="px-4 py-12 text-center text-sm text-ink-3">{t('social.loadError')}</p>
</Sheet>
)
}
return (
<Sheet
label={t('social.editProfile')}
title={t('social.editProfile')}
onClose={onClose}
right={
<button onClick={save} disabled={saving || !usernameOk || !nameOk} className="btn btn-light px-3 py-1.5 text-sm">
{saving ? <Loader2 size={15} className="animate-spin" /> : t('common.save')}
</button>
}
>
{/* Bannière */}
<button type="button" onClick={() => bannerInput.current?.click()} className="relative block aspect-[3/1] w-full overflow-hidden bg-surface-2" aria-label={t('social.changeBanner')}>
{banner.preview && !banner.removed && <img src={banner.preview} alt="" className="size-full object-cover" />}
<span className="absolute inset-0 grid place-items-center bg-black/25">
<span className="flex items-center gap-2 rounded-full bg-bg/85 px-3 py-1.5 text-xs font-semibold">
<ImagePlus size={14} /> {t('social.changeBanner')}
</span>
</span>
</button>
<input ref={bannerInput} type="file" accept="image/*" hidden onChange={(e) => pick('banner', e.target.files?.[0])} />
<div className="px-4">
<div className="-mt-11 flex items-end gap-3">
<button type="button" onClick={() => avatarInput.current?.click()} className="relative rounded-full" aria-label={t('social.changeAvatar')}>
<Avatar url={avatar.removed ? undefined : avatar.preview} name={displayName || me.username} size={88} className="border-4 border-bg" />
<span className="absolute bottom-1 right-1 grid size-7 place-items-center rounded-full bg-accent-fill text-on-accent">
<Camera size={14} />
</span>
</button>
<input ref={avatarInput} type="file" accept="image/*" hidden onChange={(e) => pick('avatar', e.target.files?.[0])} />
<div className="mb-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-3">
{avatar.preview && !avatar.removed && (
<button type="button" onClick={() => setAvatar({ removed: true })} className="flex items-center gap-1">
<Trash2 size={12} /> {t('social.removeAvatar')}
</button>
)}
{banner.preview && !banner.removed && (
<button type="button" onClick={() => setBanner({ removed: true })} className="flex items-center gap-1">
<Trash2 size={12} /> {t('social.removeBanner')}
</button>
)}
</div>
</div>
<div className="mt-6 space-y-4">
<label className="block">
<span className="label">{t('social.displayName')}</span>
<input className="field" value={displayName} onChange={(e) => setDisplayName(e.target.value)} maxLength={40} required />
</label>
<label className="block">
<span className="label">{t('social.username')}</span>
<div className="relative">
<span className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3">@</span>
<input
className={cx('field pl-8', username && !usernameOk && 'border-accent!')}
value={username}
onChange={(e) => setUsername(e.target.value.toLowerCase())}
maxLength={21}
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
/>
</div>
<span className={cx('mt-1.5 block text-xs', usernameOk ? 'text-ink-3' : 'text-accent')}>{t('social.usernameRule')}</span>
</label>
<label className="block">
<span className="label">{t('social.bio')}</span>
<textarea className="field min-h-24 resize-y" value={bio} onChange={(e) => setBio(e.target.value)} maxLength={300} placeholder={t('social.bioPh')} />
<span className="mt-1 block text-right text-[11px] text-ink-3">{bio.length}/300</span>
</label>
<button type="button" onClick={() => setIsPrivate((v) => !v)} className="flex w-full items-center gap-3 rounded-2xl border border-line px-4 py-3.5 text-left">
<Lock size={18} className="shrink-0 text-ink-2" />
<span className="flex-1">
<span className="block text-sm font-medium">{t('social.privateAccount')}</span>
<span className="mt-0.5 block text-xs text-ink-3">{t('social.privateHint')}</span>
</span>
<span className={cx('relative h-6 w-11 shrink-0 rounded-full transition-colors', isPrivate ? 'bg-accent-fill' : 'bg-surface-2 border border-line-strong')}>
<span className={cx('absolute top-0.5 size-5 rounded-full bg-ink transition-all', isPrivate ? 'left-[22px] bg-on-accent' : 'left-0.5')} />
</span>
</button>
{error && (
<p role="alert" className="rounded-xl border border-accent px-3 py-2.5 text-sm">
{error}
</p>
)}
<p className="text-xs leading-relaxed text-ink-3">{t('social.publicHint')}</p>
</div>
</div>
</Sheet>
)
}
+96
View File
@@ -0,0 +1,96 @@
import { Loader2 } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { acceptFollower, getFollowList, removeFollower, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { cx } from '../../lib/utils'
import PersonRow from './PersonRow'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
type Tab = 'followers' | 'following' | 'requests'
/** Abonnés / abonnements d'un profil ; pour le mien, aussi les demandes en attente. */
export default function FollowList({ profile, initial, onClose }: { profile: Profile; initial: 'followers' | 'following'; onClose: () => void }) {
const social = useSocial()
const showRequests = profile.isMe && social.requests.length > 0
const [tab, setTab] = useState<Tab>(showRequests && initial === 'followers' ? 'requests' : initial)
const [list, setList] = useState<ProfileCard[]>()
const [busy, setBusy] = useState<string>()
useEffect(() => {
if (tab === 'requests') return setList(social.requests)
let alive = true
setList(undefined)
getFollowList(profile.id, tab)
.then((l) => alive && setList(l))
.catch(() => alive && setList([]))
return () => {
alive = false
}
}, [tab, profile.id, social.requests])
const act = async (person: ProfileCard, action: 'accept' | 'remove') => {
setBusy(person.id)
try {
if (action === 'accept') await acceptFollower(person.id)
else await removeFollower(person.id)
setList((l) => l?.filter((p) => p.id !== person.id))
await social.refresh()
} finally {
setBusy(undefined)
}
}
const tabs: Tab[] = showRequests ? ['requests', 'followers', 'following'] : ['followers', 'following']
return (
<Sheet label={profile.displayName} title={profile.displayName} onClose={onClose}>
<div className="px-4 pt-4">
<div className={cx('grid gap-1 rounded-full border border-line p-1', tabs.length === 3 ? 'grid-cols-3' : 'grid-cols-2')}>
{tabs.map((v) => (
<button key={v} onClick={() => setTab(v)} className={cx('rounded-full py-2 text-xs font-semibold transition-colors', tab === v ? 'bg-ink text-bg' : 'text-ink-3')}>
{v === 'requests'
? t('social.requestsTab', { count: social.requests.length })
: v === 'followers'
? t('social.followers', { count: profile.followers })
: t('social.followingCount', { count: profile.following })}
</button>
))}
</div>
{list === undefined ? (
<p className="flex justify-center py-10">
<Loader2 size={16} className="animate-spin text-ink-3" />
</p>
) : list.length === 0 ? (
<p className="py-10 text-center text-sm text-ink-3">{tab === 'following' ? t('social.noFollowing') : t('social.noFollowers')}</p>
) : (
<div className="mt-3 divide-y divide-line">
{list.map((p) => (
<PersonRow
key={p.id}
person={p}
actions={
tab === 'requests' ? (
<span className="flex shrink-0 gap-1.5">
<button onClick={() => act(p, 'accept')} disabled={!!busy} className="h-8 rounded-full bg-accent-fill px-3 text-xs font-semibold text-on-accent">
{t('social.accept')}
</button>
<button onClick={() => act(p, 'remove')} disabled={!!busy} className="h-8 rounded-full border border-line-strong px-3 text-xs font-semibold text-ink-2">
{t('social.decline')}
</button>
</span>
) : profile.isMe && tab === 'followers' ? (
<button onClick={() => act(p, 'remove')} disabled={!!busy} className="h-8 shrink-0 rounded-full border border-line-strong px-3 text-xs font-semibold text-ink-2">
{t('social.removeFollower')}
</button>
) : undefined
}
/>
))}
</div>
)}
</div>
</Sheet>
)
}
+113
View File
@@ -0,0 +1,113 @@
import { Loader2, Star, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { t } from '../../i18n'
import { getFeed, type FeedEntry } from '../../lib/cloud/social'
import { timeAgo } from '../../lib/timeAgo'
import { formatRating } from '../../lib/utils'
import { useMedia } from '../../store'
import Poster from '../Poster'
import { LinkArrow, SectionTitle } from '../ui'
import Avatar from './Avatar'
import { useSocial } from './SocialProvider'
const VERB = { finished: 'feed.finished', started: 'feed.started', rewatched: 'feed.rewatched', added: 'feed.added' } as const
/** Accueil : ce que regardent mes abonnements. */
export default function FriendsFeed() {
const social = useSocial()
const { settings } = useMedia()
const [entries, setEntries] = useState<FeedEntry[]>()
const [more, setMore] = useState(false)
const [loadingMore, setLoadingMore] = useState(false)
const [shown, setShown] = useState(6)
const load = useCallback(async () => {
try {
const list = await getFeed()
setEntries(list)
setMore(list.length >= 30)
} catch {
setEntries([])
}
}, [])
useEffect(() => {
if (social.enabled && navigator.onLine) void load()
}, [social.enabled, load])
if (!social.enabled) return null
const loadMore = async () => {
if (!entries) return
if (shown < entries.length) return setShown((n) => n + 10)
setLoadingMore(true)
try {
const next = await getFeed(entries[entries.length - 1]?.createdAt)
setEntries([...entries, ...next])
setMore(next.length >= 30)
setShown((n) => n + 10)
} finally {
setLoadingMore(false)
}
}
return (
<>
<SectionTitle action={<LinkArrow onClick={social.openSearch}>{t('social.findFriends')}</LinkArrow>}>{t('feed.title')}</SectionTitle>
{entries === undefined ? (
<p className="flex items-center gap-2 text-sm text-ink-3">
<Loader2 size={14} className="animate-spin" /> {t('social.loading')}
</p>
) : entries.length === 0 ? (
<button onClick={social.openSearch} className="flex w-full items-center gap-3 rounded-2xl border border-dashed border-line-strong p-4 text-left">
<span className="grid size-10 shrink-0 place-items-center rounded-full bg-surface-2 text-accent">
<UserPlus size={18} />
</span>
<span className="text-sm text-ink-2">{t('feed.empty')}</span>
</button>
) : (
<>
<ul className="divide-y divide-line">
{entries.slice(0, shown).map((e) => (
<li key={`${e.id}-${e.createdAt}`} className="flex items-center gap-3 py-2.5">
<button onClick={() => social.openProfile(e.user.username)} aria-label={e.user.displayName}>
<Avatar url={e.user.avatarUrl} name={e.user.displayName} size={36} />
</button>
<button onClick={() => social.openItem(e.item, e.user)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<span className="min-w-0 flex-1">
<span className="line-clamp-2 text-sm leading-snug text-ink-2">
<span className="font-semibold text-ink">{e.user.displayName}</span> {t(VERB[e.kind])}{' '}
<span className="font-semibold text-ink">{e.item.title}</span>
</span>
<span className="mt-0.5 flex items-center gap-2 text-[11px] text-ink-3">
{e.item.rating != null && e.kind !== 'added' && (
<span className="flex items-center gap-0.5 font-semibold text-ink-2">
<Star size={10} className="fill-accent text-accent" />
{formatRating(e.item.rating, settings.ratingScale)}
</span>
)}
{e.item.notes && e.item.notesPublic && <span>{t('feed.review')}</span>}
<span>{timeAgo(e.createdAt)}</span>
</span>
</span>
<span className="w-10 shrink-0">
<Poster src={e.item.poster} title={e.item.title} />
</span>
</button>
</li>
))}
</ul>
{(shown < entries.length || more) && (
<button onClick={loadMore} disabled={loadingMore} className="mt-2 w-full py-2 text-xs font-medium text-ink-3">
{loadingMore ? <Loader2 size={13} className="mx-auto animate-spin" /> : (
<>
{t('social.loadMore')} <span className="text-accent">→</span>
</>
)}
</button>
)}
</>
)}
</>
)
}
+122
View File
@@ -0,0 +1,122 @@
import { Check, Loader2, Plus, Star } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { genreLabel } from '../../lib/genres'
import { cx, formatDate, formatRating, normalizeText } from '../../lib/utils'
import { useMedia } from '../../store'
import type { MediaInput, MediaItem } from '../../types'
import { StatusPill, TypeBadge } from '../Badges'
import Poster from '../Poster'
import Avatar from './Avatar'
export interface PeekOwner {
username: string
displayName: string
avatarUrl?: string
}
/** Aperçu d'un titre de quelqu'un d'autre : sa note, son avis public, et ajout à ma liste « À voir ». */
export default function ItemPeek({ item, owner, onClose }: { item: MediaItem; owner?: PeekOwner; onClose: () => void }) {
const { items, add, settings } = useMedia()
const [busy, setBusy] = useState(false)
const [added, setAdded] = useState(false)
const owned = items.some(
(i) => (item.externalId && i.externalId === item.externalId) || normalizeText(i.title) === normalizeText(item.title),
)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const addToWatchlist = async () => {
setBusy(true)
try {
const input: MediaInput = {
title: item.title,
originalTitle: item.originalTitle,
type: item.type,
subtype: item.subtype,
year: item.year,
status: 'a_voir',
criteria: {},
episodesWatched: 0,
episodesTotal: item.episodesTotal,
episodeDuration: item.episodeDuration,
duration: item.duration,
genres: item.genres,
platform: item.platform,
poster: item.poster,
overview: item.overview,
externalId: item.externalId,
countries: item.countries,
publicRating: item.publicRating,
}
await add(input)
setAdded(true)
} finally {
setBusy(false)
}
}
return (
<div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/70 sm:items-center sm:p-4" onClick={onClose}>
<div
role="dialog"
aria-modal="true"
aria-label={item.title}
className="sheet-in safe-bottom max-h-[88dvh] w-full max-w-md overflow-y-auto rounded-t-3xl border border-line-strong bg-surface p-5 sm:rounded-3xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex gap-4">
<div className="w-24 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0 flex-1">
<h2 className="text-lg font-bold leading-snug">{item.title}</h2>
{item.originalTitle && <p className="truncate text-sm text-ink-3">{item.originalTitle}</p>}
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-ink-3">
<TypeBadge item={item} />
{item.year && <span>{item.year}</span>}
</div>
{item.genres.length > 0 && <p className="mt-2 line-clamp-1 text-xs text-ink-3">{item.genres.slice(0, 3).map(genreLabel).join(' · ')}</p>}
</div>
</div>
{owner && (
<div className="mt-5 rounded-2xl border border-line p-3.5">
<div className="flex items-center gap-2.5">
<Avatar url={owner.avatarUrl} name={owner.displayName} size={28} />
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{owner.displayName}</span>
{item.rating != null && (
<span className="flex items-center gap-1 text-sm font-semibold">
<Star size={14} className="fill-accent text-accent" />
{formatRating(item.rating, settings.ratingScale)}
</span>
)}
</div>
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-ink-3">
<StatusPill status={item.status} />
{item.endDate && item.status === 'termine' && <span>{formatDate(item.endDate)}</span>}
{item.favorite && <span className="text-accent">♥ {t('form.favorite')}</span>}
</div>
{item.notes && <p className="mt-3 whitespace-pre-line text-sm leading-relaxed text-ink-2">{item.notes}</p>}
</div>
)}
{item.overview && <p className="mt-4 line-clamp-5 text-sm leading-relaxed text-ink-2">{item.overview}</p>}
<div className="mt-5 grid grid-cols-2 gap-2">
<button onClick={onClose} className="btn btn-ghost">
{t('common.close')}
</button>
<button onClick={addToWatchlist} disabled={busy || added || owned} className={cx('btn', added || owned ? 'btn-ghost' : 'btn-primary')}>
{busy ? <Loader2 size={16} className="animate-spin" /> : added || owned ? <Check size={16} /> : <Plus size={16} />}
{added ? t('reco.addedShort') : owned ? t('social.inLibrary') : t('social.addToWatch')}
</button>
</div>
</div>
</div>
)
}
+89
View File
@@ -0,0 +1,89 @@
import { Loader2, Search } from 'lucide-react'
import { useEffect, useState } from 'react'
import { t } from '../../i18n'
import { profileLink, searchProfiles, type ProfileCard } from '../../lib/cloud/social'
import PersonRow from './PersonRow'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
/** Trouver des amis par pseudo ou par nom. */
export default function PeopleSearch({ onClose }: { onClose: () => void }) {
const { me } = useSocial()
const [q, setQ] = useState('')
const [results, setResults] = useState<ProfileCard[]>([])
const [loading, setLoading] = useState(false)
const [copied, setCopied] = useState(false)
useEffect(() => {
const term = q.trim()
if (term.length < 2) return setResults([])
let alive = true
setLoading(true)
const timer = setTimeout(() => {
searchProfiles(term)
.then((r) => alive && setResults(r))
.catch(() => alive && setResults([]))
.finally(() => alive && setLoading(false))
}, 300)
return () => {
alive = false
clearTimeout(timer)
}
}, [q])
const invite = async () => {
if (!me) return
const url = profileLink(me.username)
try {
if (navigator.share && window.matchMedia?.('(pointer: coarse)').matches) await navigator.share({ title: 'AzuuCine', text: t('social.inviteText'), url })
else {
await navigator.clipboard.writeText(url)
setCopied(true)
}
} catch {
/* annulé */
}
}
return (
<Sheet label={t('social.findFriends')} title={t('social.findFriends')} onClose={onClose}>
<div className="px-4 pt-4">
<div className="relative">
<Search size={17} className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder={t('social.searchPh')}
className="field pl-10"
autoFocus
autoCapitalize="off"
autoComplete="off"
spellCheck={false}
enterKeyHint="search"
/>
{loading && <Loader2 size={17} className="absolute right-3.5 top-1/2 -translate-y-1/2 animate-spin text-ink-3" />}
</div>
{results.length > 0 ? (
<div className="mt-3 divide-y divide-line">
{results.map((p) => (
<PersonRow key={p.id} person={p} />
))}
</div>
) : (
q.trim().length >= 2 && !loading && <p className="py-8 text-center text-sm text-ink-3">{t('social.noResults')}</p>
)}
{me && (
<div className="mt-8 rounded-2xl border border-dashed border-line-strong p-4 text-sm">
<p className="text-ink-2">{t('social.inviteHint')}</p>
<button onClick={invite} className="mt-2 font-medium text-ink">
{copied ? t('social.linkCopied') : t('social.shareMyProfile')} <span className="text-accent">→</span>
</button>
</div>
)}
</div>
</Sheet>
)
}
+59
View File
@@ -0,0 +1,59 @@
import { Check, Loader2, Lock } from 'lucide-react'
import { useState, type ReactNode } from 'react'
import { t } from '../../i18n'
import { follow, unfollow, type ProfileCard } from '../../lib/cloud/social'
import { cx } from '../../lib/utils'
import Avatar from './Avatar'
import { useSocial } from './SocialProvider'
/** Ligne « personne » : photo, nom, @pseudo, et bouton d'abonnement (ou actions personnalisées). */
export default function PersonRow({ person, actions }: { person: ProfileCard; actions?: ReactNode }) {
const social = useSocial()
const [relation, setRelation] = useState(person.relation)
const [busy, setBusy] = useState(false)
const isMe = social.me?.id === person.id
const toggle = async () => {
setBusy(true)
try {
if (relation === 'none') setRelation(await follow(person.id))
else {
await unfollow(person.id)
setRelation('none')
}
} catch {
/* réseau : rien ne change */
} finally {
setBusy(false)
}
}
return (
<div className="flex items-center gap-3 py-2.5">
<button onClick={() => social.openProfile(person.username)} className="flex min-w-0 flex-1 items-center gap-3 text-left">
<Avatar url={person.avatarUrl} name={person.displayName} size={44} />
<span className="min-w-0">
<span className="block truncate text-sm font-semibold">{person.displayName}</span>
<span className="flex items-center gap-1 text-xs text-ink-3">
@{person.username}
{person.isPrivate && <Lock size={10} />}
</span>
</span>
</button>
{actions ??
(!isMe && (
<button
onClick={toggle}
disabled={busy}
className={cx(
'flex h-8 shrink-0 items-center gap-1 rounded-full px-3 text-xs font-semibold transition active:scale-95',
relation === 'none' ? 'bg-accent-fill text-on-accent' : 'border border-line-strong text-ink-2',
)}
>
{busy ? <Loader2 size={13} className="animate-spin" /> : relation === 'accepted' ? <Check size={13} /> : null}
{relation === 'accepted' ? t('social.following') : relation === 'pending' ? t('social.requested') : t('social.follow')}
</button>
))}
</div>
)
}
+383
View File
@@ -0,0 +1,383 @@
import { Check, Loader2, Lock, Share2, Star, UserPlus } from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { t } from '../../i18n'
import { follow, getProfile, getProfileItems, profileLink, unfollow, type Profile } from '../../lib/cloud/social'
import { STATUSES, TOP_CATEGORIES } from '../../lib/constants'
import { cx, formatRating } from '../../lib/utils'
import { useMedia } from '../../store'
import type { MediaItem, WatchStatus } from '../../types'
import ConfirmDialog from '../ConfirmDialog'
import Poster from '../Poster'
import { EmptyState, SectionTitle } from '../ui'
import Avatar from './Avatar'
import Sheet from './Sheet'
import { useSocial } from './SocialProvider'
function PosterTile({ item, onOpen, caption }: { item: MediaItem; onOpen: () => void; caption?: string }) {
const { settings } = useMedia()
return (
<button onClick={onOpen} className="block w-full text-left">
<Poster src={item.poster} title={item.title} />
<p className="mt-1.5 truncate text-[11px] font-medium text-ink-2">{item.title}</p>
<p className="flex h-4 items-center gap-1 text-[11px] text-ink-3">
{item.rating != null && (
<>
<Star size={10} className="fill-accent text-accent" />
{formatRating(item.rating, settings.ratingScale)}
</>
)}
{caption && <span className="truncate">{caption}</span>}
</p>
</button>
)
}
function Stat({ value, label, onClick }: { value?: number; label: string; onClick?: () => void }) {
const body = (
<>
<span className="block text-lg font-bold tabular-nums leading-tight">{value == null ? '—' : value.toLocaleString()}</span>
<span className="block text-[11px] text-ink-3">{label}</span>
</>
)
return onClick ? (
<button onClick={onClick} className="flex-1 text-center">
{body}
</button>
) : (
<div className="flex-1 text-center">{body}</div>
)
}
/** Page de profil (la mienne ou celle d'un autre). */
export default function ProfileView({ username, onClose }: { username: string; onClose: () => void }) {
const social = useSocial()
const [profile, setProfile] = useState<Profile | null>()
const [error, setError] = useState<string>()
const [tab, setTab] = useState<'profile' | 'library'>('profile')
const [busy, setBusy] = useState(false)
const [confirmUnfollow, setConfirmUnfollow] = useState(false)
const [toast, setToast] = useState<string>()
const load = useCallback(async () => {
setError(undefined)
try {
setProfile(await getProfile(username))
} catch (e) {
setError((e as Error).message)
setProfile(null)
}
}, [username])
useEffect(() => {
void load()
}, [load])
// Mon profil a changé (modification) : on recharge
useEffect(() => {
if (profile?.isMe && social.me) setProfile(social.me)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [social.me])
useEffect(() => {
if (!toast) return
const timer = setTimeout(() => setToast(undefined), 2500)
return () => clearTimeout(timer)
}, [toast])
const owner = profile ? { username: profile.username, displayName: profile.displayName, avatarUrl: profile.avatarUrl } : undefined
const openItem = (item: MediaItem) => social.openItem(item, profile?.isMe ? undefined : owner)
const share = async () => {
if (!profile) return
const url = profileLink(profile.username)
try {
if (navigator.share && window.matchMedia?.('(pointer: coarse)').matches) await navigator.share({ title: profile.displayName, url })
else {
await navigator.clipboard.writeText(url)
setToast(t('social.linkCopied'))
}
} catch {
/* partage annulé */
}
}
const toggleFollow = async () => {
if (!profile) return
if (profile.relation !== 'none') return setConfirmUnfollow(true)
setBusy(true)
try {
await follow(profile.id)
await load()
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const doUnfollow = async () => {
if (!profile) return
setConfirmUnfollow(false)
setBusy(true)
try {
await unfollow(profile.id)
await load()
} catch (e) {
setToast((e as Error).message)
} finally {
setBusy(false)
}
}
const topByCategory = useMemo(() => {
const out: { label: string; items: MediaItem[] }[] = []
for (const c of TOP_CATEGORIES) {
const list = (profile?.top ?? []).filter((i) => i.top?.category === c.value).sort((a, b) => a.top!.rank - b.top!.rank)
if (list.length) out.push({ label: c.plural, items: list })
}
return out
}, [profile])
return (
<Sheet
label={t('social.profile')}
title={profile ? `@${profile.username}` : ''}
onClose={onClose}
right={
profile ? (
<button onClick={share} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('social.shareProfile')}>
<Share2 size={18} />
</button>
) : undefined
}
>
{profile === undefined ? (
<p className="flex items-center justify-center gap-2 py-16 text-sm text-ink-3">
<Loader2 size={16} className="animate-spin" /> {t('social.loading')}
</p>
) : profile === null ? (
<div className="px-4">
<EmptyState title={error ? t('social.loadError') : t('social.notFound')} text={error ?? t('social.notFoundHint', { username })} />
</div>
) : (
<>
{/* Bannière + photo */}
<div className="relative aspect-[3/1] w-full overflow-hidden bg-surface-2">
{profile.bannerUrl && <img src={profile.bannerUrl} alt="" className="size-full object-cover" />}
</div>
<div className="px-4">
<div className="relative -mt-11 flex items-end justify-between gap-3">
<Avatar url={profile.avatarUrl} name={profile.displayName} size={88} className="border-4 border-bg" />
{profile.isMe ? (
<button onClick={social.openEdit} className="btn btn-ghost mb-1 px-4 py-2 text-sm">
{t('social.editProfile')}
</button>
) : (
<button
onClick={toggleFollow}
disabled={busy}
className={cx('btn mb-1 px-4 py-2 text-sm', profile.relation === 'none' ? 'btn-primary' : 'btn-ghost')}
>
{busy ? (
<Loader2 size={15} className="animate-spin" />
) : profile.relation === 'accepted' ? (
<Check size={15} />
) : profile.relation === 'none' ? (
<UserPlus size={15} />
) : null}
{profile.relation === 'accepted'
? t('social.following')
: profile.relation === 'pending'
? t('social.requested')
: profile.followsMe
? t('social.followBack')
: t('social.follow')}
</button>
)}
</div>
<h1 className="mt-3 text-2xl font-bold leading-tight">{profile.displayName}</h1>
<p className="mt-0.5 flex items-center gap-1.5 text-sm text-ink-3">
@{profile.username}
{profile.isPrivate && <Lock size={12} aria-label={t('social.private')} />}
{profile.followsMe && !profile.isMe && (
<span className="rounded-full bg-surface-2 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.04em] text-ink-2">
{t('social.followsYou')}
</span>
)}
</p>
{profile.bio && <p className="mt-3 whitespace-pre-line text-sm leading-relaxed text-ink-2">{profile.bio}</p>}
<div className="mt-5 flex divide-x divide-line rounded-2xl border border-line py-3">
<Stat value={profile.visible ? (profile.stats?.finished ?? 0) : undefined} label={t('social.seen')} />
<Stat value={profile.followers} label={t('social.followers', { count: profile.followers })} onClick={profile.visible ? () => social.openFollowList(profile, 'followers') : undefined} />
<Stat value={profile.following} label={t('social.followingCount', { count: profile.following })} onClick={profile.visible ? () => social.openFollowList(profile, 'following') : undefined} />
</div>
{profile.isMe && social.requests.length > 0 && (
<button onClick={() => social.openFollowList(profile, 'followers')} className="mt-3 flex w-full items-center justify-between rounded-2xl border border-accent px-4 py-3 text-sm">
<span>{t('social.requests', { count: social.requests.length })}</span>
<span className="text-accent">→</span>
</button>
)}
{!profile.visible ? (
<div className="mt-8 flex flex-col items-center rounded-2xl border border-line px-6 py-10 text-center">
<Lock size={26} className="text-ink-3" />
<p className="mt-3 font-semibold">{t('social.privateTitle')}</p>
<p className="mt-1 text-sm text-ink-3">{t('social.privateText')}</p>
</div>
) : (
<>
<div className="mt-6 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
{(['profile', 'library'] as const).map((v) => (
<button
key={v}
onClick={() => setTab(v)}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', tab === v ? 'bg-ink text-bg' : 'text-ink-3')}
>
{v === 'profile' ? t('social.tabProfile') : t('social.tabLibrary')}
</button>
))}
</div>
{tab === 'profile' ? (
<ProfileTab profile={profile} topByCategory={topByCategory} onOpen={openItem} />
) : (
<LibraryTab profile={profile} onOpen={openItem} />
)}
</>
)}
</div>
</>
)}
{toast && (
<p role="status" className="sheet-in fixed inset-x-4 bottom-8 z-[70] mx-auto max-w-md rounded-2xl border border-line-strong bg-surface-2 p-3.5 text-center text-sm">
{toast}
</p>
)}
<ConfirmDialog
open={confirmUnfollow}
title={profile?.relation === 'pending' ? t('social.cancelRequestTitle') : t('social.unfollowTitle', { name: profile?.displayName ?? '' })}
message={profile?.isPrivate && profile.relation === 'accepted' ? t('social.unfollowPrivate') : undefined}
confirmLabel={profile?.relation === 'pending' ? t('social.cancelRequest') : t('social.unfollow')}
onConfirm={doUnfollow}
onCancel={() => setConfirmUnfollow(false)}
/>
</Sheet>
)
}
function ProfileTab({ profile, topByCategory, onOpen }: { profile: Profile; topByCategory: { label: string; items: MediaItem[] }[]; onOpen: (i: MediaItem) => void }) {
const s = profile.stats
return (
<>
{topByCategory.map((c) => (
<section key={c.label}>
<SectionTitle>
{t('social.top5')} · {c.label}
</SectionTitle>
<div className="grid grid-cols-5 gap-2">
{c.items.map((item) => (
<div key={item.id} className="relative">
<PosterTile item={item} onOpen={() => onOpen(item)} />
<span className="absolute left-1 top-1 grid size-5 place-items-center rounded-full bg-bg/85 text-[10px] font-bold">{item.top!.rank}</span>
</div>
))}
</div>
</section>
))}
<SectionTitle>{t('social.recent')}</SectionTitle>
{profile.recent.length ? (
<div className="grid grid-cols-4 gap-2.5">
{profile.recent.map((item) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} />
))}
</div>
) : (
<p className="text-sm text-ink-3">{t('social.noRecent')}</p>
)}
{s && (
<>
<SectionTitle>{t('nav.stats')}</SectionTitle>
<div className="grid grid-cols-2 gap-3">
{[
[s.finishedYear, t('social.statYear')],
[s.films, t('social.statFilms')],
[s.series, t('social.statSeries')],
[s.episodes, t('home.episodesSeen')],
].map(([v, label]) => (
<div key={label as string} className="card p-4">
<div className="eyebrow">{label}</div>
<div className="mt-2 text-2xl font-bold tabular-nums leading-none">{(v as number).toLocaleString()}</div>
</div>
))}
</div>
</>
)}
</>
)
}
function LibraryTab({ profile, onOpen }: { profile: Profile; onOpen: (i: MediaItem) => void }) {
const [status, setStatus] = useState<WatchStatus | ''>('')
const [list, setList] = useState<MediaItem[]>([])
const [loading, setLoading] = useState(false)
const [done, setDone] = useState(false)
const loadPage = useCallback(
async (reset: boolean) => {
setLoading(true)
try {
const page = await getProfileItems(profile.id, status || null, reset ? 0 : list.length)
setList((prev) => (reset ? page : [...prev, ...page]))
setDone(page.length < 48)
} finally {
setLoading(false)
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[profile.id, status, list.length],
)
useEffect(() => {
void loadPage(true)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [profile.id, status])
return (
<div className="mt-5">
<div className="no-scrollbar -mx-4 mb-4 flex gap-2 overflow-x-auto px-4">
<button onClick={() => setStatus('')} className={cx('chip shrink-0 py-1! text-[13px]', !status && 'chip-on')}>
{t('catalog.all')}
</button>
{STATUSES.map((s) => (
<button key={s.value} onClick={() => setStatus(s.value)} className={cx('chip shrink-0 py-1! text-[13px]', status === s.value && 'chip-on')}>
{s.label}
</button>
))}
</div>
{list.length ? (
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4">
{list.map((item) => (
<PosterTile key={item.id} item={item} onOpen={() => onOpen(item)} />
))}
</div>
) : (
!loading && <p className="py-6 text-center text-sm text-ink-3">{t('social.emptyLibrary')}</p>
)}
{loading && (
<p className="flex items-center justify-center gap-2 py-6 text-sm text-ink-3">
<Loader2 size={14} className="animate-spin" />
</p>
)}
{!loading && !done && list.length > 0 && (
<button onClick={() => loadPage(false)} className="btn btn-ghost mt-5 w-full">
{t('social.loadMore')}
</button>
)}
</div>
)
}
+33
View File
@@ -0,0 +1,33 @@
import { X } from 'lucide-react'
import { useEffect, type ReactNode } from 'react'
import { t } from '../../i18n'
/** Écran plein (profil, recherche…) avec en-tête et bouton fermer. */
export default function Sheet({ title, onClose, right, children, label }: { title: ReactNode; onClose: () => void; right?: ReactNode; children: ReactNode; label: string }) {
useEffect(() => {
const prev = document.body.style.overflow
document.body.style.overflow = 'hidden'
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => {
document.body.style.overflow = prev
window.removeEventListener('keydown', onKey)
}
}, [onClose])
return (
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={label}>
<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">
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
<X size={22} />
</button>
<h2 className="min-w-0 flex-1 truncate text-center text-base font-semibold">{title}</h2>
<span className="flex size-10 items-center justify-end">{right}</span>
</div>
</header>
<div className="flex-1 overflow-y-auto overscroll-contain">
<div className="safe-bottom mx-auto max-w-2xl pb-16">{children}</div>
</div>
</div>
)
}
+133
View File
@@ -0,0 +1,133 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { getFollowRequests, getMyProfile, type Profile, type ProfileCard } from '../../lib/cloud/social'
import { useMedia } from '../../store'
import type { MediaItem } from '../../types'
import EditProfile from './EditProfile'
import FollowList from './FollowList'
import ItemPeek, { type PeekOwner } from './ItemPeek'
import PeopleSearch from './PeopleSearch'
import ProfileView from './ProfileView'
interface SocialApi {
/** Réseau disponible (compte connecté) */
enabled: boolean
me: Profile | null
requests: ProfileCard[]
refresh: () => Promise<void>
openProfile: (username: string) => void
openSearch: () => void
openEdit: () => void
openFollowList: (profile: Profile, kind: 'followers' | 'following') => void
peek: (item: MediaItem, owner?: PeekOwner) => void
/** Ouvre la fiche si elle est à moi, sinon l'aperçu */
openItem: (item: MediaItem, owner?: PeekOwner) => void
}
const SocialContext = createContext<SocialApi>({
enabled: false,
me: null,
requests: [],
refresh: async () => {},
openProfile: () => {},
openSearch: () => {},
openEdit: () => {},
openFollowList: () => {},
peek: () => {},
openItem: () => {},
})
export const useSocial = () => useContext(SocialContext)
type Overlay =
| { kind: 'profile'; username: string }
| { kind: 'search' }
| { kind: 'edit' }
| { kind: 'follows'; profile: Profile; list: 'followers' | 'following' }
/** Profils, recherche et aperçus : affichés par-dessus l'app, empilés (le bouton fermer revient au précédent). */
export function SocialProvider({ children, onOpenOwnItem }: { children: ReactNode; onOpenOwnItem: (item: MediaItem) => void }) {
const { account, items } = useMedia()
const enabled = !!account
const [me, setMe] = useState<Profile | null>(null)
const [requests, setRequests] = useState<ProfileCard[]>([])
const [stack, setStack] = useState<Overlay[]>([])
const [peeked, setPeeked] = useState<{ item: MediaItem; owner?: PeekOwner }>()
const refresh = useCallback(async () => {
if (!enabled || !navigator.onLine) return
try {
const [p, r] = await Promise.all([getMyProfile(), getFollowRequests()])
setMe(p)
setRequests(r)
} catch {
/* hors-ligne / serveur pas encore à jour : le reste de l'app fonctionne */
}
}, [enabled])
useEffect(() => {
void refresh()
}, [refresh])
const push = useCallback((o: Overlay) => setStack((s) => [...s.slice(-8), o]), [])
const pop = useCallback(() => setStack((s) => s.slice(0, -1)), [])
// Lien partagé « #/u/pseudo »
useEffect(() => {
if (!enabled) return
const check = () => {
const m = location.hash.match(/^#\/u\/([a-z0-9_]{3,20})$/i)
if (!m) return
history.replaceState(null, '', `${location.pathname}${location.search}#/home`)
push({ kind: 'profile', username: m[1].toLowerCase() })
}
check()
window.addEventListener('hashchange', check)
return () => window.removeEventListener('hashchange', check)
}, [enabled, push])
const openItem = useCallback(
(item: MediaItem, owner?: PeekOwner) => {
const mine = !owner || owner.username === me?.username
const local = mine ? items.find((i) => i.id === item.id) : undefined
if (local) onOpenOwnItem(local)
else setPeeked({ item, owner })
},
[items, me?.username, onOpenOwnItem],
)
const api = useMemo<SocialApi>(
() => ({
enabled,
me,
requests,
refresh,
openProfile: (username) => push({ kind: 'profile', username }),
openSearch: () => push({ kind: 'search' }),
openEdit: () => push({ kind: 'edit' }),
openFollowList: (profile, list) => push({ kind: 'follows', profile, list }),
peek: (item, owner) => setPeeked({ item, owner }),
openItem,
}),
[enabled, me, requests, refresh, push, openItem],
)
return (
<SocialContext.Provider value={api}>
{/* Les écrans sociaux sont placés avant l'app : une fiche ouverte depuis un profil passe au-dessus */}
{enabled &&
stack.map((o, k) =>
o.kind === 'profile' ? (
<ProfileView key={k} username={o.username} onClose={pop} />
) : o.kind === 'search' ? (
<PeopleSearch key={k} onClose={pop} />
) : o.kind === 'edit' ? (
<EditProfile key={k} onClose={pop} />
) : (
<FollowList key={k} profile={o.profile} initial={o.list} onClose={pop} />
),
)}
{children}
{enabled && peeked && <ItemPeek item={peeked.item} owner={peeked.owner} onClose={() => setPeeked(undefined)} />}
</SocialContext.Provider>
)
}
+78
View File
@@ -0,0 +1,78 @@
import { t } from '../i18n'
import type { ReactNode } from 'react'
import { cx } from '../lib/utils'
/** En-tête de page : titre en gras, moitié blanc / moitié rouge. */
export function PageHeader({ title, accent, subtitle, action }: { title: string; accent?: string; subtitle?: string; action?: ReactNode }) {
return (
<header className="flex items-end justify-between gap-3 pb-5 pt-7">
<div className="min-w-0">
<h1 className="text-[1.9rem] leading-tight">
{title}
{accent && <span className="text-accent">{accent}</span>}
</h1>
{subtitle && <p className="mt-1 text-sm text-ink-3">{subtitle}</p>}
</div>
{action}
</header>
)
}
export function StatTile({ label, value, hint, className }: { label: string; value: ReactNode; hint?: string; className?: string }) {
return (
<div className={cx('card p-4', className)}>
<div className="eyebrow">{label}</div>
<div className="mt-2 text-2xl font-bold leading-none tabular-nums">{value}</div>
{hint && <div className="mt-1.5 text-xs text-ink-3">{hint}</div>}
</div>
)
}
/** Titre de section façon Letterboxd : petites capitales grises + filet. */
export function SectionTitle({ children, action }: { children: ReactNode; action?: ReactNode }) {
return (
<div className="mb-4 mt-9 flex items-center justify-between gap-3 border-b border-line pb-2">
<h2 className="eyebrow text-ink-2">{children}</h2>
{action}
</div>
)
}
export function LinkArrow({ onClick, children }: { onClick: () => void; children: ReactNode }) {
return (
<button onClick={onClick} className="shrink-0 text-xs font-medium text-ink-3 transition-colors hover:text-ink">
{children} <span className="text-accent">→</span>
</button>
)
}
/** Liste de barres horizontales (une seule série → une seule couleur, valeurs écrites en clair). */
export function BarList({ data, format = String }: { data: { label: string; value: number }[]; format?: (v: number) => string }) {
const max = Math.max(1, ...data.map((d) => d.value))
if (!data.some((d) => d.value > 0)) return <p className="text-sm text-ink-3">{t('common.noData')}</p>
return (
<ul className="space-y-3">
{data.map((d) => (
<li key={d.label} className="text-sm" title={`${d.label} : ${format(d.value)}`}>
<div className="mb-1.5 flex justify-between gap-2">
<span className="truncate text-ink-2">{d.label}</span>
<span className="shrink-0 text-xs tabular-nums text-ink">{format(d.value)}</span>
</div>
<div className="h-1 rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${(d.value / max) * 100}%`, minWidth: d.value ? 4 : 0 }} />
</div>
</li>
))}
</ul>
)
}
export function EmptyState({ title, text, action }: { title: string; text?: string; action?: ReactNode }) {
return (
<div className="card mt-4 flex flex-col items-center px-6 py-12 text-center">
<p className="text-lg font-semibold">{title}</p>
{text && <p className="mt-2 max-w-xs text-sm text-ink-2">{text}</p>}
{action && <div className="mt-6">{action}</div>}
</div>
)
}
+121
View File
@@ -0,0 +1,121 @@
import fr from './locales/fr'
/**
* Traductions de l'interface, sans dépendance.
* - Le français est la langue de référence (src/i18n/locales/fr.ts) : chaque clé existe dans toutes les langues.
* - Les autres langues sont chargées à la demande (une seule à la fois).
* - Pluriels : clés « xxx_one » / « xxx_other » (+ « _zero », « _few », « _many » si besoin), choisies avec Intl.PluralRules.
* - Variables : « {name} » dans le texte, remplacées par t(key, { name }).
*/
export type Dict = typeof fr
type RawKey = keyof Dict
/** Clés plurielles appelées sans suffixe : t('titles', { count }) */
type PluralBase = RawKey extends infer K ? (K extends `${infer B}_other` ? B : never) : never
type SuffixedPlural = RawKey extends infer K ? (K extends `${string}_${'zero' | 'one' | 'two' | 'few' | 'many' | 'other'}` ? K : never) : never
export type TKey = Exclude<RawKey, SuffixedPlural> | PluralBase
export type Translations = { [K in RawKey]: string }
export type Lang = 'fr' | 'en' | 'es' | 'it' | 'de' | 'pt' | 'zh' | 'ja' | 'ko'
export interface LangInfo {
code: Lang
/** Nom de la langue dans cette langue */
label: string
/** Format des dates et nombres */
locale: string
/** Langue demandée à TMDB (titres, résumés) */
tmdb: string
}
export const LANGS: LangInfo[] = [
{ code: 'fr', label: 'Français', locale: 'fr-FR', tmdb: 'fr-FR' },
{ code: 'en', label: 'English', locale: 'en-US', tmdb: 'en-US' },
{ code: 'es', label: 'Español', locale: 'es-ES', tmdb: 'es-ES' },
{ code: 'it', label: 'Italiano', locale: 'it-IT', tmdb: 'it-IT' },
{ code: 'de', label: 'Deutsch', locale: 'de-DE', tmdb: 'de-DE' },
{ code: 'pt', label: 'Português', locale: 'pt-BR', tmdb: 'pt-BR' },
{ code: 'zh', label: '中文', locale: 'zh-CN', tmdb: 'zh-CN' },
{ code: 'ja', label: '日本語', locale: 'ja-JP', tmdb: 'ja-JP' },
{ code: 'ko', label: '한국어', locale: 'ko-KR', tmdb: 'ko-KR' },
]
const BY_CODE = Object.fromEntries(LANGS.map((l) => [l.code, l])) as Record<Lang, LangInfo>
const loaders: Record<Exclude<Lang, 'fr'>, () => Promise<{ default: Translations }>> = {
en: () => import('./locales/en'),
es: () => import('./locales/es'),
it: () => import('./locales/it'),
de: () => import('./locales/de'),
pt: () => import('./locales/pt'),
zh: () => import('./locales/zh'),
ja: () => import('./locales/ja'),
ko: () => import('./locales/ko'),
}
const STORAGE_KEY = 'azuucine:lang'
export const isLang = (v: unknown): v is Lang => typeof v === 'string' && v in BY_CODE
/** Langue enregistrée, sinon celle du téléphone, sinon le français. */
export function initialLang(): Lang {
try {
const saved = localStorage.getItem(STORAGE_KEY)
if (isLang(saved)) return saved
} catch {
/* ignore */
}
for (const l of navigator.languages ?? [navigator.language]) {
const code = l?.slice(0, 2).toLowerCase()
if (isLang(code)) return code
}
return 'fr'
}
let current: Lang = 'fr'
let dict: Partial<Translations> = fr
let plural = new Intl.PluralRules('fr-FR')
export const getLang = () => current
export const langInfo = () => BY_CODE[current]
/** Locale BCP 47 pour toLocaleDateString / Intl */
export const locale = () => BY_CODE[current].locale
export const tmdbLanguage = () => BY_CODE[current].tmdb
/** Charge la langue et l'active (à attendre avant d'afficher l'interface). */
export async function loadLang(code: Lang): Promise<void> {
const next = code === 'fr' ? fr : (await loaders[code]()).default
current = code
dict = next
plural = new Intl.PluralRules(BY_CODE[code].locale)
document.documentElement.lang = code
try {
localStorage.setItem(STORAGE_KEY, code)
} catch {
/* ignore */
}
}
function lookup(key: string): string | undefined {
return (dict as Record<string, string>)[key] ?? (fr as Record<string, string>)[key]
}
/** Texte traduit. Les variables {x} sont remplacées ; « count » choisit la forme plurielle. */
export function t(key: TKey, vars?: Record<string, string | number>): string {
let text: string | undefined
if (vars && typeof vars.count === 'number') {
const n = vars.count
text = (n === 0 ? lookup(`${key}_zero`) : undefined) ?? lookup(`${key}_${plural.select(n)}`) ?? lookup(`${key}_other`)
}
text ??= lookup(key) ?? key
if (!vars) return text
return text.replace(/\{(\w+)\}/g, (m, name: string) => (name in vars ? formatVar(name, vars[name]) : m))
}
// Seuls les compteurs sont formatés (« 1 234 ») ; une année reste « 2026 »
const formatVar = (name: string, v: string | number) => (typeof v === 'number' && (name === 'count' || name === 'n') ? v.toLocaleString(locale()) : String(v))
/** Nombre formaté dans la langue active (espaces, virgules…). */
export const fmtNumber = (n: number, opts?: Intl.NumberFormatOptions) => n.toLocaleString(locale(), opts)
/** Pays associé à la langue (plateformes de streaming, sorties cinéma) : FR, US, ES… */
export const region = () => BY_CODE[current].locale.split('-')[1]
+750
View File
@@ -0,0 +1,750 @@
/** Deutsch */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': 'Abbrechen',
'common.confirm': 'Bestätigen',
'common.close': 'Schließen',
'common.save': 'Speichern',
'common.add': 'Hinzufügen',
'common.delete': 'Löschen',
'common.all': 'Alle',
'common.none': 'Keine',
'common.noData': 'Noch keine Daten.',
'common.retry': 'Nochmal versuchen',
'common.back': 'Zurück',
'common.offline': 'Keine Internetverbindung.',
'common.minutes': '{n} Min.',
'common.hours': '{h} Std.',
'common.hoursMinutes': '{h} Std. {m} Min.',
'common.daysHours': '{d} T. {h} Std.',
'common.decimalSep': ',',
'common.removeX': '{name} entfernen',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': 'Bearbeiten',
'common.moveUp': 'Nach oben',
'common.moveDown': 'Nach unten',
'nav.home': 'Start',
'nav.catalog': 'Katalog',
'nav.stats': 'Stats',
'nav.settings': 'Einstellungen',
'nav.addTitle': 'Titel hinzufügen',
'type.film': 'Film',
'type.serie': 'Serie',
'type.anime': 'Anime',
'type.kdrama': 'K-Drama',
'type.cdrama': 'C-Drama',
'type.autre': 'Sonstiges',
'typePlural.film': 'Filme',
'typePlural.serie': 'Serien',
'typePlural.anime': 'Animes',
'typePlural.kdrama': 'K-Dramas',
'typePlural.cdrama': 'C-Dramas',
'status.a_voir': 'Geplant',
'status.en_cours': 'Am Schauen',
'status.termine': 'Beendet',
'status.pause': 'Pausiert',
'status.abandonne': 'Abgebrochen',
'criteria.story': 'Drehbuch / Story',
'criteria.cast': 'Figuren / Besetzung',
'criteria.direction': 'Regie / Animation',
'criteria.ost': 'Soundtrack (OST)',
'subtype.documentary': 'Doku',
'subtype.reality': 'Reality-TV',
'subtype.show': 'TV-Show',
'subtype.short': 'Kurzfilm',
'subtype.stage': 'Bühnenshow',
'subtype.miniseries': 'Miniserie',
'platform.cinema': 'Kino',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'TV',
'genre.action': 'Action',
'genre.adventure': 'Abenteuer',
'genre.comedy': 'Komödie',
'genre.drama': 'Drama',
'genre.romance': 'Liebesfilm',
'genre.romcom': 'Rom-Com',
'genre.thriller': 'Thriller',
'genre.horror': 'Horror',
'genre.mystery': 'Mystery',
'genre.crime': 'Krimi',
'genre.scifi': 'Sci-Fi',
'genre.fantasy': 'Fantasy',
'genre.historical': 'Historie',
'genre.sliceOfLife': 'Slice of Life',
'genre.shonen': 'Shōnen',
'genre.shojo': 'Shōjo',
'genre.seinen': 'Seinen',
'genre.isekai': 'Isekai',
'genre.mecha': 'Mecha',
'genre.sports': 'Sport',
'genre.musical': 'Musical',
'genre.medical': 'Medizin',
'genre.legal': 'Justiz',
'genre.wuxia': 'Wuxia',
'genre.xianxia': 'Xianxia',
'genre.family': 'Familie',
'genre.animation': 'Animation',
'genre.psychological': 'Psycho',
'genre.supernatural': 'Übernatürlich',
'genre.romanticComedy': 'Liebeskomödie',
'genre.documentary': 'Dokumentarfilm',
'genre.war': 'Kriegsfilm',
'genre.western': 'Western',
'genre.music': 'Musik',
'genre.ecchi': 'Ecchi',
'genre.kids': 'Kinder',
'genre.news': 'News',
'genre.reality': 'Reality-TV',
'genre.talk': 'Talkshow',
'genre.soap': 'Soap',
'genre.politics': 'Politik',
'genre.tvMovie': 'TV-Film',
'genre.anime': 'Anime',
'genre.magicalGirl': 'Magical Girl',
'confirm.title': 'Bist du sicher?',
'err.tmdbRefused': 'TMDB-Anfrage abgelehnt.',
'err.tmdbKeyRefused': 'TMDB-Schlüssel abgelehnt. Prüf ihn in den Einstellungen.',
'err.tmdbStatus': 'TMDB hat mit {status} geantwortet.',
'err.tmdbRef': 'Ungültige TMDB-Referenz.',
'err.anilistRate': 'AniList begrenzt die Anfragen, versuch’s in einer Minute nochmal.',
'err.anilistStatus': 'AniList hat mit {status} geantwortet.',
'err.searchRate': 'Zu viele Suchen, versuch’s in ein paar Minuten nochmal.',
'anilist.short': 'Kurz-Anime',
'anilist.movie': 'Animationsfilm',
'anilist.special': 'Special',
'anilist.music': 'Musikvideo',
'release.cinema': 'Im Kino',
'release.online': 'Als VOD / Stream',
'release.release': 'Release',
'release.season': 'Staffel {season}',
'release.episode': 'Folge {ep}',
'release.newEpisode': 'Neue Folge',
'release.firstEpisode': 'Erste Folge',
'release.newSeriesN': 'Neue Serie · {count} Folgen',
'release.seasonN': 'Staffel {season} · {count} Folgen',
'release.seasonEp1': 'Staffel {season} · Folge 1',
'release.episodes': 'Folgen {first}–{last}',
'release.sEpisodes': 'S{season} · Folgen {first}–{last}',
'release.sEpisode': 'S{season} · Folge {ep}',
'release.episodeFinal': 'Folge {ep} · Finale',
'release.filmJapan': 'Film in Japan',
'card.ep': 'Ep. {n}',
'card.plusOne': '+1 Folge für {title}',
'card.open': '{title} öffnen',
'rating.outOf10': 'Bewertung von 10',
'rating.stars_one': '{count} Stern',
'rating.stars_other': '{count} Sterne',
'rating.clear': 'Bewertung löschen',
'share.previewLabel': 'Bildvorschau',
'share.preview': 'Vorschau',
'share.posterAlt': 'Poster {title}',
'share.share': 'Teilen',
'share.saveImage': 'Bild speichern',
'share.err.create': 'Bild konnte nicht erstellt werden',
'share.minutesLong': '{n} Minuten',
'share.createdBy': 'Erdacht von',
'share.directedBy': 'Regie',
'share.producedBy': 'Produziert von',
'share.starring': 'Mit',
'share.genres': 'Genres',
'share.myRating': 'Meine Bewertung',
'share.myTop': 'Meine Top',
'auth.hidePassword': 'Passwort verbergen',
'auth.showPassword': 'Passwort anzeigen',
'auth.mismatch': 'Die beiden Passwörter stimmen nicht überein.',
'auth.created': 'Konto erstellt! Öffne den Link, den wir an {email} geschickt haben, um es zu aktivieren, und melde dich dann an.',
'auth.resetSent': 'Falls es ein Konto mit dieser Adresse gibt, wurde gerade ein Link zum Festlegen eines neuen Passworts verschickt.',
'auth.tagline': 'Dein Tagebuch für Filme, Serien, Animes und Dramas.',
'auth.loginTab': 'Anmelden',
'auth.signupTab': 'Registrieren',
'auth.forgotTitle': 'Passwort vergessen',
'auth.email': 'E-Mail-Adresse',
'auth.password': 'Passwort',
'auth.confirmPassword': 'Passwort bestätigen',
'auth.minChars': 'Mindestens {n} Zeichen.',
'auth.login': 'Anmelden',
'auth.signup': 'Konto erstellen',
'auth.sendLink': 'Link senden',
'auth.forgot': 'Passwort vergessen?',
'auth.backToLogin': 'Zurück zur Anmeldung',
'auth.privacy': 'Deine Daten sind mit deinem Konto verknüpft und nur für dich sichtbar. Sie bleiben außerdem auf deinem Gerät, damit alles auch ohne Internet funktioniert.',
'auth.newPasswordTitle': 'Wähl dein neues Passwort.',
'auth.newPassword': 'Neues Passwort',
'auth.err.credentials': 'E-Mail oder Passwort falsch.',
'auth.err.notConfirmed': 'Bestätige zuerst deine Adresse über den Link in der E-Mail.',
'auth.err.exists': 'Mit dieser E-Mail gibt es schon ein Konto.',
'auth.err.weak': 'Passwort zu schwach (mindestens {n} Zeichen, Buchstaben und Zahlen gemischt).',
'auth.err.samePassword': 'Das neue Passwort muss sich vom alten unterscheiden.',
'auth.err.emailRate': 'Zu viele Anfragen. Versuch’s in ein paar Minuten nochmal.',
'auth.err.rate': 'Zu viele Versuche. Versuch’s in ein paar Minuten nochmal.',
'auth.err.signupDisabled': 'Registrierungen sind gerade geschlossen.',
'auth.err.emailInvalid': 'Ungültige E-Mail-Adresse.',
'auth.err.invalid': 'Ungültige E-Mail-Adresse oder ungültiges Passwort.',
'auth.err.session': 'Sitzung abgelaufen, melde dich neu an.',
'auth.err.status': 'Der Server hat die Anfrage abgelehnt ({status}).',
'auth.err.response': 'Ungültige Serverantwort.',
'auth.err.linkExpired': 'Dieser Link ist abgelaufen. Fordere einen neuen an.',
'auth.err.linkUsed': 'Dieser Link ist ungültig oder wurde schon benutzt.',
'auth.err.linkInvalid': 'Dieser Link ist ungültig.',
'settings.language': 'Sprache',
'settings.backupShared': 'Backup geteilt.',
'settings.backupDownloaded': 'Backup heruntergeladen.',
'settings.exportFailed': 'Export fehlgeschlagen.',
'settings.noValidItems': 'Die Datei enthält keinen gültigen Eintrag.',
'settings.imported_one': '{count} Eintrag importiert.',
'settings.imported_other': '{count} Einträge importiert.',
'settings.importedSkipped': '{n} Eintrag/Einträge importiert, {skipped} übersprungen.',
'settings.cleared': 'Bibliothek gelöscht.',
'settings.pageTitle': 'Meine ',
'settings.pageAccent': 'Einstellungen',
'settings.languageHint': 'Sprache der App, der Datumsangaben und der Infos von TMDB (Titel, Inhaltsangaben).',
'settings.rating': 'Bewertung',
'settings.scale5': '★ von 5',
'settings.scale10': 'Von 10',
'settings.ratingHint': 'Halbe Sterne bei 5, oder 0,5er-Schritte bei 10. Bestehende Bewertungen werden automatisch umgerechnet.',
'settings.theme': 'Design',
'settings.themeX': 'Design {name}',
'settings.pickColor': 'Eigene Farbe wählen',
'settings.freeColor': 'Eigene Farbe',
'settings.freeColorHint': 'Jede Farbe geht: Der Text passt sich an, damit er lesbar bleibt.',
'settings.databases': 'Filmdatenbanken',
'settings.anilistActive': 'Animes · aktiv',
'settings.noConfig': 'Keine Einrichtung nötig.',
'settings.tmdbActive': 'Filme & Serien · aktiv',
'settings.checking': 'Wird geprüft…',
'settings.offline': 'Offline',
'settings.proxyMissingKey': 'TMDB-Schlüssel fehlt',
'settings.proxyNotDeployed': 'Server nicht eingerichtet',
'settings.unavailable': 'Nicht verfügbar',
'settings.proxyMissingKeyHint': 'Die Serverfunktion ist eingerichtet, aber dein TMDB-Schlüssel ist nicht hinterlegt (Secret TMDB_API_KEY in Supabase) oder wird von TMDB abgelehnt.',
'settings.proxyNotDeployedHint': 'Die Funktion „tmdb“ ist noch nicht auf Supabase deployt (siehe README → Konten, Schritt 5).',
'settings.proxyErrorHint': 'Der Server antwortet gerade nicht richtig.',
'settings.proxyOkHint': 'Kommt vom Server der App: Du musst keinen Schlüssel eingeben.',
'settings.recheck': 'Neu prüfen',
'settings.keyRefused': 'Schlüssel abgelehnt',
'settings.notConfigured': 'Nicht eingerichtet',
'settings.tmdbHelp': 'Filme, Serien, K-Dramas, C-Dramas. Erstell ein kostenloses Konto auf themoviedb.org, dann Einstellungen → API, und füge deinen „API-Schlüssel“ oder dein „API-Lesezugriffstoken“ ein.',
'settings.tmdbKey': 'TMDB-Schlüssel',
'settings.hideKey': 'Schlüssel verbergen',
'settings.showKey': 'Schlüssel anzeigen',
'settings.validate': 'Übernehmen',
'settings.remove': 'Entfernen',
'settings.keyLocal': 'Der Schlüssel bleibt auf diesem Gerät und landet nie in Backups.',
'settings.topHint': 'Kategorien auf der Startseite.',
'settings.topNone': 'Keine Kategorie: Der Top-5-Bereich ist ausgeblendet.',
'settings.backup': 'Backup',
'settings.export': 'Meine Daten exportieren',
'settings.exportHint_one': '{count} Eintrag · JSON-Datei, am besten regelmäßig',
'settings.exportHint_other': '{count} Einträge · JSON-Datei, am besten regelmäßig',
'settings.import': 'Backup importieren',
'settings.importHint': 'Aus einer .json-Datei wiederherstellen',
'settings.legacyDetected': 'Backup der alten App erkannt',
'settings.found_one': '{count} Eintrag gefunden. Wie willst du ihn importieren?',
'settings.found_other': '{count} Einträge gefunden. Wie willst du sie importieren?',
'settings.foundSkipped': '{n} Eintrag/Einträge gefunden ({skipped} ungültige übersprungen). Wie willst du sie importieren?',
'settings.merge': 'Zusammenführen',
'settings.replaceAll': 'Alles ersetzen',
'settings.mergeHint': '„Zusammenführen“ fügt die Einträge hinzu und aktualisiert vorhandene (gleiche ID).',
'settings.storage': 'Speicher',
'settings.used': 'Belegter Speicher',
'settings.storageCloud': 'Deine Daten werden in deinem Konto gespeichert und zusätzlich auf diesem Gerät behalten, damit alles auch ohne Internet funktioniert. Sobald du Netz hast, synchronisieren sie sich automatisch.',
'settings.storageLocal': 'Deine Daten liegen nur in diesem Browser auf diesem Gerät. Wenn du die Browserdaten löschst oder die App deinstallierst, sind sie weg: Exportier regelmäßig ein Backup.',
'settings.danger': 'Gefahrenzone',
'settings.clearAll': 'Ganze Bibliothek löschen',
'settings.clearAllHint_one': '{count} Titel',
'settings.clearAllHint_other': '{count} Titel',
'settings.clearAllHintCloud_one': '{count} Titel · auf all deinen Geräten',
'settings.clearAllHintCloud_other': '{count} Titel · auf all deinen Geräten',
'settings.deleting': 'Wird gelöscht…',
'settings.deleteAccount': 'Mein Konto löschen',
'settings.deleteAccountHint': 'Konto und Daten werden endgültig gelöscht',
'settings.footerCloud': 'Konto synchronisiert',
'settings.footerLocal': '100 % lokal',
'settings.clearConfirm_one': '{count} Titel wird endgültig gelöscht. Denk daran, vorher ein Backup zu exportieren.',
'settings.clearConfirm_other': 'Deine {count} Titel werden endgültig gelöscht. Denk daran, vorher ein Backup zu exportieren.',
'settings.clearConfirmCloud_one': '{count} Titel wird endgültig gelöscht, auf all deinen Geräten. Denk daran, vorher ein Backup zu exportieren.',
'settings.clearConfirmCloud_other': 'Deine {count} Titel werden endgültig gelöscht, auf all deinen Geräten. Denk daran, vorher ein Backup zu exportieren.',
'settings.clearAllConfirm': 'Alles löschen',
'settings.deleteAccountTitle': 'Dein Konto löschen?',
'settings.deleteAccountMessage': 'Dein Konto und alle deine Daten (Titel, Listen, Einstellungen) werden endgültig vom Server und von diesem Gerät gelöscht. Denk daran, vorher ein Backup zu exportieren. Das lässt sich nicht rückgängig machen.',
'settings.deleteForever': 'Endgültig löschen',
'settings.replaceConfirm': 'Deine ganze aktuelle Bibliothek wird durch den Inhalt dieser Datei ersetzt.',
'settings.replace': 'Ersetzen',
'sync.err.push': 'Senden abgelehnt ({status})',
'sync.err.pull': 'Abrufen abgelehnt ({status})',
'store.dbError': 'Lokale Datenbank lässt sich nicht öffnen: {error}',
'store.invalidItem': 'Ungültiger Eintrag',
'lists.newList': 'Neue Liste',
'lists.newListPh': 'Neue Liste…',
'lists.myLists': 'Meine Listen',
'lists.rename': 'Umbenennen',
'lists.delete': 'Liste löschen',
'lists.done': 'Fertig',
'lists.addRemove': 'Titel hinzufügen / entfernen',
'lists.searchLibrary': 'In meiner Bibliothek suchen…',
'lists.emptyTitle': 'Leere Liste',
'lists.emptyText': 'Füg Titel über den Button oben hinzu oder direkt aus dem Eintrag eines Titels.',
'lists.deleteConfirm': 'Die Liste „{name}“ wird gelöscht. Die Titel bleiben in deiner Bibliothek.',
'lists.noneTitle': 'Noch keine Listen',
'lists.noneText': 'Erstell Listen, wie du willst: „Mit Freunden schauen“, „Horrorfilme im Oktober“, „Wohlfühl-Dramas“…',
'lists.create': 'Erstellen',
'account.err.deleteRate': 'Zu viele Versuche, versuch’s in einer Minute nochmal.',
'account.err.delete': 'Löschen fehlgeschlagen. Versuch’s später nochmal.',
'account.title': 'Mein Konto',
'account.syncing': 'Synchronisiere…',
'account.offline': 'Offline — alles bleibt auf diesem Gerät gespeichert',
'account.syncError': 'Synchronisierung gerade nicht möglich',
'account.synced': 'Synchronisiert {when}',
'account.passwordChanged': 'Passwort geändert.',
'account.imported_one': '{count} Titel zu deinem Konto hinzugefügt.',
'account.imported_other': '{count} Titel zu deinem Konto hinzugefügt.',
'account.importFailed': 'Import fehlgeschlagen.',
'account.pending_one': '{count} ausstehend',
'account.pending_other': '{count} ausstehend',
'account.syncNow': 'Jetzt synchronisieren',
'account.newPasswordPh': 'Neues Passwort (min. {n} Zeichen)',
'account.changePassword': 'Passwort ändern',
'account.logout': 'Abmelden',
'account.logoutHint': 'Deine Daten bleiben in deinem Konto und werden von diesem Gerät entfernt.',
'account.ignore': 'Ignorieren',
'account.deviceHint': 'Sie werden in dein Konto verschoben und auf all deinen Geräten synchronisiert.',
'account.unsentTitle': 'Nicht gesendete Änderungen',
'account.logoutAnyway': 'Trotzdem abmelden',
'account.unsentMessage_one': '{count} Änderung wurde noch nicht gesendet (keine Verbindung?). Wenn du dich jetzt abmeldest, geht sie verloren.',
'account.unsentMessage_other': '{count} Änderungen wurden noch nicht gesendet (keine Verbindung?). Wenn du dich jetzt abmeldest, gehen sie verloren.',
'account.nTitles_one': '{count} Titel',
'account.nTitles_other': '{count} Titel',
'account.nLists_one': '{count} Liste',
'account.nLists_other': '{count} Listen',
'account.deviceData': 'Auf diesem Gerät gibt es {titles}, die vor deinem Konto erstellt wurden. Zu deinem Konto hinzufügen?',
'account.deviceDataWithLists': 'Auf diesem Gerät gibt es {titles} und {lists}, die vor deinem Konto erstellt wurden. Zu deinem Konto hinzufügen?',
'time.never': 'nie',
'time.justNow': 'gerade eben',
'time.minutesAgo': 'vor {n} Min.',
'time.hoursAgo': 'vor {n} Std.',
'time.onDate': 'am {date}',
'time.today': 'heute',
'time.tomorrow': 'morgen',
'time.daysAgo': 'vor {n} Tg.',
'theme.red': 'Rot',
'theme.orange': 'Orange',
'theme.yellow': 'Gelb',
'theme.lime': 'Limette',
'theme.green': 'Grün',
'theme.mint': 'Mint',
'theme.cyan': 'Cyan',
'theme.blue': 'Blau',
'theme.indigo': 'Indigo',
'theme.violet': 'Violett',
'theme.pink': 'Rosa',
'theme.white': 'Weiß',
'home.seeAll': 'Alle ansehen',
'home.subtitle': 'Mein Watch-Tagebuch',
'home.calendarSoon_one': 'Release-Kalender: {count} diese Woche',
'home.calendarSoon_other': 'Release-Kalender: {count} diese Woche',
'home.emptyTitle': 'Deine Bibliothek ist leer',
'home.emptyCloud': 'Füg deinen ersten Film, Anime oder dein erstes Drama hinzu. Er wird in deinem Konto gespeichert.',
'home.emptyLocal': 'Füg deinen ersten Film, Anime oder dein erstes Drama hinzu. Alles bleibt nur auf diesem Handy.',
'home.completed': 'Beendet',
'home.thisYear_one': '{count} dieses Jahr',
'home.thisYear_other': '{count} dieses Jahr',
'home.toWatchN_one': '{count} geplant',
'home.toWatchN_other': '{count} geplant',
'home.screenTime': 'Bildschirmzeit',
'home.estimate': 'geschätzt',
'home.episodesSeen': 'Gesehene Folgen',
'home.noIdea': 'Keine Idee?',
'home.rouletteHint_one': 'Zufallsauswahl aus deinem geplanten Titel',
'home.rouletteHint_other': 'Zufallsauswahl aus deinen {count} geplanten Titeln',
'home.rouletteHintAll': 'Zufallsauswahl aus deiner Bibliothek',
'home.recentlyFinished': 'Kürzlich beendet',
'calendar.title': 'Release-Kalender',
'calendar.inMyList': 'In meiner Liste',
'calendar.inMyListLegend': 'In meiner Liste',
'calendar.seeMore_one': 'Den anderen ansehen',
'calendar.seeMore_other': 'Die {count} anderen ansehen',
'calendar.heading': 'Release-',
'calendar.headingAccent': 'Kalender',
'calendar.refresh': 'Aktualisieren',
'calendar.all': 'Alle Releases',
'calendar.mine': 'Meine Titel',
'calendar.prevMonth': 'Vorheriger Monat',
'calendar.nextMonth': 'Nächster Monat',
'calendar.releases_one': '{count} Release',
'calendar.releases_other': '{count} Releases',
'calendar.others': 'Weitere Releases',
'calendar.needKey': 'Ohne TMDB-Schlüssel werden nur Animes angezeigt. Füg deinen Schlüssel in den Einstellungen hinzu, um auch Filme, Serien und Dramas zu sehen.',
'calendar.range': 'Releases gibt es vom letzten Monat bis 6 Monate im Voraus.',
'calendar.failed': 'Einige Releases konnten nicht geladen werden. Versuch’s nochmal mit ↻.',
'calendar.nothingThatDay': 'An diesem Tag ist nichts geplant.',
'calendar.next14': 'Die nächsten 14 Tage',
'calendar.loading': 'Suche Releases…',
'calendar.noneMine14': 'Keine angekündigten Releases für deine Titel in den nächsten 14 Tagen.',
'calendar.noneMineMonth': 'Keine angekündigten Releases für deine Titel in diesem Monat.',
'calendar.none14': 'Keine Releases in den nächsten 14 Tagen.',
'calendar.noneMonth': 'Keine Releases in diesem Monat gefunden.',
'calendar.footer': 'Kinofilme in deinem Land, Folgen der meistverfolgten Serien und Dramas (TMDB) und aller in Japan ausgestrahlten Animes (AniList). Titel aus deiner Bibliothek sind farbig markiert; tipp auf „Geplant“, um ein Release zu deiner Liste hinzuzufügen.',
'roulette.name': 'Roulette',
'roulette.rewatch': 'Nochmal sehen',
'roulette.anyTime': 'Egal',
'roulette.heading': 'Das ',
'roulette.headingAccent': 'Roulette',
'roulette.tonight': 'Heute Abend gibt’s…',
'roulette.nEps': '{n} Ep.',
'roulette.perEp': '{duration} / Ep.',
'roulette.stoppedAt': 'Du warst bei Folge {ep} stehen geblieben.',
'roulette.stoppedAtOf': 'Du warst bei Folge {ep} von {total} stehen geblieben.',
'roulette.enjoy': 'Viel Spaß beim Schauen!',
'roulette.again': 'Nochmal',
'roulette.spinning': 'Dreht sich…',
'roulette.spin': 'Roulette drehen',
'roulette.poolSize_one': 'Auswahl aus {count} Titel',
'roulette.poolSize_other': 'Auswahl aus {count} Titeln',
'roulette.empty': 'Kein Titel passt: Erweitere die Filter unten.',
'roulette.inside': 'Im Roulette',
'roulette.pickFrom': 'Auswählen aus',
'roulette.rewatchHint': '„Nochmal sehen“ = deine beendeten Titel mit 4/5 oder mehr, Lieblinge und Top 5.',
'roulette.time': 'Verfügbare Zeit (Film oder 1 Folge)',
'roulette.seeItem': 'Ganzen Eintrag ansehen',
'roulette.watchIt': 'Den schau ich',
'newEp.check': 'Prüfen',
'newEp.title': 'Neuheiten',
'newEp.checking': 'Ich schau, was rausgekommen ist…',
'newEp.needKey': 'Füg deinen TMDB-Schlüssel in den Einstellungen hinzu, um über neue Folgen und Staffeln informiert zu werden.',
'newEp.nothing_one': 'Nichts Neues bei deiner verfolgten Serie oder deinem Anime.',
'newEp.nothing_other': 'Nichts Neues bei deinen {count} verfolgten Serien und Animes.',
'newEp.needKeyAlso': '(Füg deinen TMDB-Schlüssel in den Einstellungen hinzu, um auch Serien und Dramas zu verfolgen.)',
'newEp.newSeason': 'Neue Staffel',
'newEp.catchUp': 'Nachholen',
'newEp.soon': 'Bald',
'newEp.epWhen': 'Ep. {ep} {when}',
'newEp.available_one': '{count} Folge verfügbar',
'newEp.available_other': '{count} Folgen verfügbar',
'newEp.next': 'Nächste: Ep. {ep} {when}',
'newEp.resume': 'Weiterschauen',
'top.pick': 'Platz {rank} wählen',
'top.shareTitle': 'Meine Top 5 {category}',
'top.shareLabel': 'Diese Top 5 als Bild teilen',
'top.title': 'Meine Top',
'top.number': 'Nr. {rank}',
'top.pickFirst': 'Wähl deine Nr. 1.',
'top.editLabel': 'Top 5 bearbeiten',
'top.freeSlot': 'Freier Platz — wähl unten einen Titel',
'top.addFromLibrary': 'Aus meiner Bibliothek hinzufügen',
'top.allTypes': 'Alle Typen',
'top.searchTitle': 'Titel suchen…',
'top.full': 'Deine Top 5 sind voll: Entfern einen Titel, um einen anderen hinzuzufügen.',
'top.noCandidates': 'Keine Titel. Probier „Alle Typen“ oder eine andere Suche.',
'reco.error': 'Vorschläge können gerade nicht geladen werden.',
'reco.title': 'Vorschläge',
'reco.needKey': 'Füg deinen TMDB-Schlüssel in den Einstellungen hinzu, um Vorschläge passend zu deinen Lieblingstiteln zu bekommen.',
'reco.other': 'Anderer Titel',
'reco.ifYouLiked': 'Wenn dir gefallen hat',
'reco.loading': 'Suche Vorschläge…',
'reco.none': 'Du hast schon alles, was diesem Titel ähnelt. Probier „Anderer Titel“.',
'reco.added': '{title} hinzugefügt',
'reco.addLabel': '{title} zu Geplant hinzufügen',
'reco.addedShort': 'Hinzugefügt',
'search.moviesSeries': 'Filme & Serien',
'search.offline': 'Keine Internetverbindung: Für die Suche brauchst du Netz.',
'search.fillFrom': 'Aus einer Datenbank ausfüllen',
'search.needKey': 'Um Filme, Serien und Dramas zu suchen, füg deinen kostenlosen TMDB-Schlüssel in den Einstellungen hinzu.',
'search.openSettings': 'Einstellungen öffnen',
'search.already': 'schon hinzugefügt',
'search.noResults': 'Keine Ergebnisse. Du kannst den Eintrag unten von Hand ausfüllen.',
'search.privacy': 'Nur der gesuchte Titel wird an {source} gesendet. Deine Bibliothek bleibt auf deinem Handy.',
'catalog.sortRecent': 'Zuletzt bearbeitet',
'catalog.sortWatched': 'Gesehen am',
'catalog.sortRating': 'Beste Bewertung',
'catalog.sortTitle': 'Titel (A→Z)',
'catalog.pageTitle': 'Mein ',
'catalog.pageAccent': 'Katalog',
'catalog.journalSubtitle': 'Dein Watch-Verlauf',
'catalog.filteredCount_one': '{count} Titel (gefiltert)',
'catalog.filteredCount_other': '{count} Titel (gefiltert)',
'catalog.titles': 'Titel',
'catalog.journal': 'Tagebuch',
'catalog.lists': 'Listen',
'catalog.searchPh': 'Titel, Genre, Plattform…',
'catalog.moreFilters': 'Mehr Filter',
'catalog.all': 'Alle',
'catalog.genre': 'Genre',
'catalog.minRating': 'Mindestbewertung',
'catalog.allRatings': 'Alle',
'catalog.sortBy': 'Sortieren nach',
'catalog.favorites': 'Lieblinge',
'catalog.reset': 'Zurücksetzen',
'catalog.noResults': 'Keine Ergebnisse',
'catalog.nothingYet': 'Noch nichts da',
'catalog.noResultsHint': 'Probier eine andere Suche oder entfern Filter.',
'catalog.nothingYetHint': 'Füg deinen ersten Titel mit dem +-Button hinzu.',
'catalog.clearFilters': 'Filter löschen',
'public.agree': 'Genau wie das Publikum',
'public.more': '+{gap} mehr als das Publikum',
'public.less': '−{gap} weniger als das Publikum',
'public.label': 'Publikum',
'public.me': 'Ich',
'public.added_one': '{count} Publikumsbewertung hinzugefügt.',
'public.added_other': '{count} Publikumsbewertungen hinzugefügt.',
'public.noneFound': 'Keine neuen Bewertungen gefunden.',
'public.fetch': 'Abrufen ({n})',
'public.title': 'Ich vs. Publikum',
'public.hintFetch': 'Hol dir die TMDB- / AniList-Durchschnittsbewertung deiner bewerteten Titel, um zu sehen, wo du vom Publikum abweichst.',
'public.hintNone': 'Keine Publikumsbewertung für deine bewerteten Titel in diesem Zeitraum.',
'public.hintKey': 'Füg deinen TMDB-Schlüssel in den Einstellungen hinzu (oder Animes mit AniList-Verknüpfung), um dich mit dem Publikum zu vergleichen.',
'public.avgGap': 'Ø Abweichung',
'public.average': 'Im Durchschnitt',
'public.generous': 'Großzügiger als das Publikum',
'public.harsh': 'Strenger als das Publikum',
'public.agreeTitle': 'Einig',
'public.within5_one': 'auf ½ Stern genau, bei {count} Titel',
'public.within5_other': 'auf ½ Stern genau, bei {count} Titeln',
'public.within10_one': 'auf 1 Punkt genau, bei {count} Titel',
'public.within10_other': 'auf 1 Punkt genau, bei {count} Titeln',
'public.lovedPre': 'Hat mir ',
'public.lovedAccent': 'besser gefallen',
'public.lovedPost': ' als dem Publikum',
'public.hatedPre': 'Hat mir ',
'public.hatedAccent': 'schlechter gefallen',
'public.hatedPost': ' als dem Publikum',
'public.allAgree': 'Du bist bei all deinen Titeln einer Meinung mit dem Publikum. Selten!',
'form.rewatchHint': 'Nochmal gesehen? Trag jedes erneute Schauen ein, es erscheint dann in deinem Tagebuch.',
'form.editTitle': 'Eintrag ',
'form.editAccent': 'bearbeiten',
'form.newTitle': 'Neuer ',
'form.newAccent': 'Titel',
'form.filledFrom': 'Ausgefüllt aus',
'form.canEdit': 'du kannst alles ändern',
'form.fillFromDb': 'Aus TMDB / AniList ergänzen',
'form.pickPoster': 'Poster wählen',
'form.removeImage': 'Bild entfernen',
'form.title': 'Titel *',
'form.titlePh': 'z. B. Your Name',
'form.originalTitle': 'Originaltitel',
'form.originalTitlePh': 'z. B. 君の名は。',
'form.synopsis': 'Inhalt',
'form.type': 'Typ',
'form.subtype': 'Art',
'form.subtypePh': 'Doku, Reality-TV…',
'form.status': 'Status',
'form.myRating': 'Meine Bewertung',
'form.favorite': 'Liebling',
'form.criteria': 'Detailkriterien (optional)',
'form.episodes': 'Folgen',
'form.minusEp': '-1 Folge',
'form.plusEp': '+1 Folge',
'form.total': 'Gesamt',
'form.season': 'Staffel',
'form.minPerEp': 'Min. / Ep.',
'form.duration': 'Dauer',
'form.durationMin': 'Dauer (Minuten)',
'form.info': 'Infos',
'form.start': 'Start / gesehen am',
'form.end': 'Ende',
'form.year': 'Jahr',
'form.platform': 'Plattform',
'form.genres': 'Genres / Tags',
'form.genresPh': 'Liebesfilm, Sci-Fi…',
'form.rewatches': 'Rewatches',
'form.review': 'Meine Meinung',
'form.reviewPh': 'Was ich davon halte, starke Szenen…',
'form.saveChanges': 'Änderungen speichern',
'form.addToLibrary': 'Zur Bibliothek hinzufügen',
'form.shareImage': 'Als Bild teilen',
'form.delete': 'Titel löschen',
'form.deleteConfirm': '„{title}“ wird endgültig gelöscht.',
'form.removeRewatch': 'Rewatch entfernen',
'form.rewatchDate': 'Datum des Rewatches',
'form.reviewPublic': 'Diese Meinung auf meinem Profil zeigen',
'form.reviewPublicHint': 'Sonst siehst nur du sie.',
'journal.rewatched': 'Nochmal gesehen',
'journal.started': 'Angefangen',
'journal.emptyTitle': 'Leeres Tagebuch',
'journal.emptyText': 'Deine Sichtungen erscheinen hier, sobald deine Einträge ein Start- oder Enddatum haben.',
'journal.seen_one': '{count} gesehen',
'journal.seen_other': '{count} gesehen',
'journal.more': 'Frühere Monate anzeigen',
'stats.overview': 'Überblick',
'stats.habits': 'Gewohnheiten',
'stats.tastes': 'Geschmack',
'stats.pageTitle': 'Meine ',
'stats.pageAccent': 'Stats',
'stats.emptyTitle': 'Noch keine Statistiken',
'stats.emptyText': 'Sie erscheinen, sobald du Titel hinzugefügt hast.',
'stats.sinceStart': 'seit Beginn',
'stats.subtitle_one': '{count} Titel in meiner Bibliothek',
'stats.subtitle_other': '{count} Titel in meiner Bibliothek',
'stats.subtitleYear_one': '{count} Titel in {year}',
'stats.subtitleYear_other': '{count} Titel in {year}',
'stats.hours_one': 'Stunde',
'stats.hours_other': 'Stunden',
'stats.nonStopPre': 'also ',
'stats.nonStopPost': ' am Stück',
'stats.days_one': '{count} Tag',
'stats.days_other': '{count} Tage',
'stats.finishedN_one': '{count} beendet',
'stats.finishedN_other': '{count} beendet',
'stats.episodesN_one': '{count} Folge',
'stats.episodesN_other': '{count} Folgen',
'stats.timeByType': 'Zeit nach Typ',
'stats.noTime': 'In diesem Zeitraum noch keine Zeit erfasst.',
'stats.avgRating': 'Ø Bewertung',
'stats.rated_one': '{count} bewerteter Titel',
'stats.rated_other': '{count} bewertete Titel',
'stats.inYear': 'in {year}',
'stats.statuses': 'Status',
'stats.hoursTab': 'Stunden',
'stats.monthByMonth': 'Monat für Monat · {year}',
'stats.last12': 'Letzte 12 Monate',
'stats.monthFinished_one': '{count} Titel beendet',
'stats.monthFinished_other': '{count} Titel beendet',
'stats.busiest': 'Vollster Monat:',
'stats.records': 'Rekorde',
'stats.marathon': 'Größter Marathon',
'stats.longestFilm': 'Längster Film',
'stats.noRecords': 'In diesem Zeitraum noch keine Rekorde.',
'stats.platforms': 'Plattformen',
'stats.bestRated': 'Meine Bestbewerteten',
'stats.myRatings': 'Meine Bewertungen',
'stats.noRatings': 'Keine Bewertungen in diesem Zeitraum.',
'stats.favGenres': 'Lieblingsgenres',
'stats.noGenres': 'Noch keine Genres.',
'stats.countries': 'Länder',
'stats.noCountry_one': '{count} Titel ohne Land: Ergänz es über „Aus TMDB / AniList ergänzen“ im Eintrag.',
'stats.noCountry_other': '{count} Titel ohne Land: Ergänz sie über „Aus TMDB / AniList ergänzen“ im Eintrag.',
'stats.noCountryLegacy_one': '{count} Titel ohne Land: Ergänz es über „Aus TMDB / AniList ergänzen“ im Eintrag oder importier das Backup deiner alten App erneut („Zusammenführen“).',
'stats.noCountryLegacy_other': '{count} Titel ohne Land: Ergänz sie über „Aus TMDB / AniList ergänzen“ im Eintrag oder importier das Backup deiner alten App erneut („Zusammenführen“).',
'stats.byType': 'Nach Typ',
'stats.footnote': 'Zeit geschätzt aus gesehenen Folgen und eingetragenen Laufzeiten (sonst: Film 1 Std. 50 Min., Anime-Folge 24 Min., Serie 45 Min., K-Drama 1 Std., C-Drama 45 Min.). Ein Titel zählt für das Jahr, in dem ich ihn beendet habe.',
'stats.ratedAs_one': 'mit {rating} bewertet',
'stats.ratedAs_other': 'mit {rating} bewertet',
'backup.shareTitle': 'AzuuCine-Backup',
'backup.tooBig': 'Datei zu groß (max. 30 MB).',
'backup.notJson': 'Diese Datei ist kein gültiges JSON.',
'backup.noItems': 'In dieser Datei wurden keine Einträge gefunden.',
'backup.tooMany': 'Zu viele Einträge (max. {n}).',
'image.canvas': 'Canvas nicht verfügbar',
'image.unreadable': 'Bild nicht lesbar',
'image.notImage': 'Diese Datei ist kein Bild.',
'image.tooBig': 'Bild zu groß (max. 25 MB).',
'social.err.server': 'Der Server hat mit {status} geantwortet.',
'social.err.usernameTaken': 'Dieser Username ist schon vergeben.',
'social.err.usernameReserved': 'Dieser Username ist nicht verfügbar.',
'social.err.invalid': 'Einer der Werte ist ungültig.',
'social.inLibrary': 'In meiner Bibliothek',
'social.addToWatch': 'Zu „Geplant“ hinzufügen',
'social.linkCopied': 'Link kopiert!',
'social.profile': 'Profil',
'social.shareProfile': 'Profil teilen',
'social.loading': 'Lädt…',
'social.loadError': 'Profil konnte nicht geladen werden.',
'social.notFound': 'Profil nicht gefunden',
'social.notFoundHint': 'Es gibt kein Profil namens @{username}.',
'social.editProfile': 'Profil bearbeiten',
'social.following': 'Gefolgt',
'social.requested': 'Angefragt',
'social.followBack': 'Zurückfolgen',
'social.follow': 'Folgen',
'social.private': 'Privates Konto',
'social.followsYou': 'Folgt dir',
'social.seen': 'Gesehen',
'social.followers_one': 'Follower',
'social.followers_other': 'Follower',
'social.followingCount_one': 'Gefolgt',
'social.followingCount_other': 'Gefolgt',
'social.requests_one': '{count} Follower-Anfrage',
'social.requests_other': '{count} Follower-Anfragen',
'social.privateTitle': 'Dieses Konto ist privat',
'social.privateText': 'Folge, um gesehene Titel, Bewertungen und Top 5 zu sehen.',
'social.tabProfile': 'Profil',
'social.tabLibrary': 'Bibliothek',
'social.cancelRequestTitle': 'Follower-Anfrage zurückziehen?',
'social.unfollowTitle': '{name} nicht mehr folgen?',
'social.unfollowPrivate': 'Dieses Konto ist privat: Du musst erneut anfragen, um das Profil wieder zu sehen.',
'social.cancelRequest': 'Anfrage zurückziehen',
'social.unfollow': 'Nicht mehr folgen',
'social.top5': 'Top 5',
'social.recent': 'Zuletzt gesehen',
'social.noRecent': 'Noch nichts abgeschlossen.',
'social.statYear': 'Dieses Jahr gesehen',
'social.statFilms': 'Filme gesehen',
'social.statSeries': 'Serien & Animes gesehen',
'social.emptyLibrary': 'Hier gibt’s keine Titel.',
'social.loadMore': 'Mehr anzeigen',
'social.changeBanner': 'Banner ändern',
'social.changeAvatar': 'Foto ändern',
'social.removeAvatar': 'Foto entfernen',
'social.removeBanner': 'Banner entfernen',
'social.displayName': 'Anzeigename',
'social.username': 'Username',
'social.usernameRule': '3–20 Zeichen: Kleinbuchstaben, Ziffern oder _',
'social.bio': 'Bio',
'social.bioPh': 'Was du gern schaust, deine Lieblingsgenres…',
'social.privateAccount': 'Privates Konto',
'social.privateHint': 'Nur Follower, die du bestätigst, sehen, was du schaust.',
'social.publicHint': 'Dein Name, Username, Foto, Banner und deine Bio sind für alle Mitglieder sichtbar. Deine Meinungen bleiben privat, außer denen, die du auf deinem Profil zeigst.',
'social.requestsTab_one': 'Anfrage',
'social.requestsTab_other': 'Anfragen ({count})',
'social.noFollowing': 'Du folgst noch niemandem.',
'social.noFollowers': 'Noch keine Follower.',
'social.accept': 'Annehmen',
'social.decline': 'Ablehnen',
'social.removeFollower': 'Entfernen',
'social.findFriends': 'Freunde finden',
'social.searchPh': 'Username oder Name…',
'social.noResults': 'Niemand gefunden.',
'social.inviteHint': 'Deine Freunde sind noch nicht auf AzuuCine? Schick ihnen den Link zu deinem Profil.',
'social.shareMyProfile': 'Mein Profil teilen',
'social.inviteText': 'Folge mir auf AzuuCine!',
'social.myProfile': 'Mein Profil',
'feed.title': 'Mein Feed',
'feed.empty': 'Folge Freunden, um hier zu sehen, was sie schauen und was sie davon halten.',
'feed.finished': 'sah',
'feed.started': 'begann',
'feed.rewatched': 'sah erneut',
'feed.added': 'plant',
'feed.review': 'Meinung',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** English */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': 'Cancel',
'common.confirm': 'Confirm',
'common.close': 'Close',
'common.save': 'Save',
'common.add': 'Add',
'common.delete': 'Delete',
'common.all': 'All',
'common.none': 'None',
'common.noData': 'No data yet.',
'common.retry': 'Try again',
'common.back': 'Back',
'common.offline': 'No internet connection.',
'common.minutes': '{n} min',
'common.hours': '{h} h',
'common.hoursMinutes': '{h} h {m}',
'common.daysHours': '{d} d {h} h',
'common.decimalSep': '.',
'common.removeX': 'Remove {name}',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': 'Edit',
'common.moveUp': 'Move up',
'common.moveDown': 'Move down',
'nav.home': 'Home',
'nav.catalog': 'Catalog',
'nav.stats': 'Stats',
'nav.settings': 'Settings',
'nav.addTitle': 'Add a title',
'type.film': 'Movie',
'type.serie': 'Series',
'type.anime': 'Anime',
'type.kdrama': 'K-Drama',
'type.cdrama': 'C-Drama',
'type.autre': 'Other',
'typePlural.film': 'Movies',
'typePlural.serie': 'Series',
'typePlural.anime': 'Anime',
'typePlural.kdrama': 'K-Dramas',
'typePlural.cdrama': 'C-Dramas',
'status.a_voir': 'To watch',
'status.en_cours': 'Watching',
'status.termine': 'Finished',
'status.pause': 'On hold',
'status.abandonne': 'Dropped',
'criteria.story': 'Story / Plot',
'criteria.cast': 'Characters / Cast',
'criteria.direction': 'Directing / Animation',
'criteria.ost': 'Soundtrack (OST)',
'subtype.documentary': 'Documentary',
'subtype.reality': 'Reality TV',
'subtype.show': 'TV show',
'subtype.short': 'Short film',
'subtype.stage': 'Stage show',
'subtype.miniseries': 'Miniseries',
'platform.cinema': 'Theater',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'TV',
'genre.action': 'Action',
'genre.adventure': 'Adventure',
'genre.comedy': 'Comedy',
'genre.drama': 'Drama',
'genre.romance': 'Romance',
'genre.romcom': 'Rom-com',
'genre.thriller': 'Thriller',
'genre.horror': 'Horror',
'genre.mystery': 'Mystery',
'genre.crime': 'Crime',
'genre.scifi': 'Sci-Fi',
'genre.fantasy': 'Fantasy',
'genre.historical': 'Historical',
'genre.sliceOfLife': 'Slice of Life',
'genre.shonen': 'Shōnen',
'genre.shojo': 'Shōjo',
'genre.seinen': 'Seinen',
'genre.isekai': 'Isekai',
'genre.mecha': 'Mecha',
'genre.sports': 'Sports',
'genre.musical': 'Musical',
'genre.medical': 'Medical',
'genre.legal': 'Legal',
'genre.wuxia': 'Wuxia',
'genre.xianxia': 'Xianxia',
'genre.family': 'Family',
'genre.animation': 'Animation',
'genre.psychological': 'Psychological',
'genre.supernatural': 'Supernatural',
'genre.romanticComedy': 'Romantic comedy',
'genre.documentary': 'Documentary',
'genre.war': 'War',
'genre.western': 'Western',
'genre.music': 'Music',
'genre.ecchi': 'Ecchi',
'genre.kids': 'Kids',
'genre.news': 'News',
'genre.reality': 'Reality',
'genre.talk': 'Talk show',
'genre.soap': 'Soap',
'genre.politics': 'Politics',
'genre.tvMovie': 'TV movie',
'genre.anime': 'Anime',
'genre.magicalGirl': 'Magical Girl',
'confirm.title': 'Are you sure?',
'err.tmdbRefused': 'TMDB request refused.',
'err.tmdbKeyRefused': 'TMDB key refused. Check it in Settings.',
'err.tmdbStatus': 'TMDB responded {status}.',
'err.tmdbRef': 'Invalid TMDB reference.',
'err.anilistRate': 'AniList is rate-limiting requests, try again in a minute.',
'err.anilistStatus': 'AniList responded {status}.',
'err.searchRate': 'Too many searches, try again in a few minutes.',
'anilist.short': 'Short anime',
'anilist.movie': 'Animated movie',
'anilist.special': 'Special',
'anilist.music': 'Music video',
'release.cinema': 'In theaters',
'release.online': 'On VOD / streaming',
'release.release': 'Release',
'release.season': 'Season {season}',
'release.episode': 'Episode {ep}',
'release.newEpisode': 'New episode',
'release.firstEpisode': 'First episode',
'release.newSeriesN': 'New series · {count} episodes',
'release.seasonN': 'Season {season} · {count} episodes',
'release.seasonEp1': 'Season {season} · Episode 1',
'release.episodes': 'Episodes {first}–{last}',
'release.sEpisodes': 'S{season} · Episodes {first}–{last}',
'release.sEpisode': 'S{season} · Episode {ep}',
'release.episodeFinal': 'Episode {ep} · finale',
'release.filmJapan': 'Movie in Japan',
'card.ep': 'Ep. {n}',
'card.plusOne': '+1 episode for {title}',
'card.open': 'Open {title}',
'rating.outOf10': 'Rating out of 10',
'rating.stars_one': '{count} star',
'rating.stars_other': '{count} stars',
'rating.clear': 'Clear rating',
'share.previewLabel': 'Image preview',
'share.preview': 'Preview',
'share.posterAlt': '{title} poster',
'share.share': 'Share',
'share.saveImage': 'Save image',
'share.err.create': 'Couldn’t create the image',
'share.minutesLong': '{n} minutes',
'share.createdBy': 'Created by',
'share.directedBy': 'Directed by',
'share.producedBy': 'Produced by',
'share.starring': 'Starring',
'share.genres': 'Genres',
'share.myRating': 'My rating',
'share.myTop': 'My Top',
'auth.hidePassword': 'Hide password',
'auth.showPassword': 'Show password',
'auth.mismatch': 'The passwords don’t match.',
'auth.created': 'Account created! Open the link sent to {email} to activate it, then log in.',
'auth.resetSent': 'If an account exists with this address, we just sent a link to set a new password.',
'auth.tagline': 'Your journal for movies, series, anime and dramas.',
'auth.loginTab': 'Log in',
'auth.signupTab': 'Sign up',
'auth.forgotTitle': 'Forgot password',
'auth.email': 'Email address',
'auth.password': 'Password',
'auth.confirmPassword': 'Confirm password',
'auth.minChars': 'At least {n} characters.',
'auth.login': 'Log in',
'auth.signup': 'Create my account',
'auth.sendLink': 'Send link',
'auth.forgot': 'Forgot your password?',
'auth.backToLogin': 'Back to login',
'auth.privacy': 'Your data is tied to your account and only visible to you. It also stays on your device so the app works offline.',
'auth.newPasswordTitle': 'Pick your new password.',
'auth.newPassword': 'New password',
'auth.err.credentials': 'Wrong email or password.',
'auth.err.notConfirmed': 'Confirm your address first with the link we emailed you.',
'auth.err.exists': 'An account already exists with this email.',
'auth.err.weak': 'Password too weak (at least {n} characters, mix letters and numbers).',
'auth.err.samePassword': 'Your new password must be different from the old one.',
'auth.err.emailRate': 'Too many requests. Try again in a few minutes.',
'auth.err.rate': 'Too many attempts. Try again in a few minutes.',
'auth.err.signupDisabled': 'Sign-ups are closed for now.',
'auth.err.emailInvalid': 'Invalid email address.',
'auth.err.invalid': 'Invalid email address or password.',
'auth.err.session': 'Session expired, please log in again.',
'auth.err.status': 'The server refused the request ({status}).',
'auth.err.response': 'Invalid server response.',
'auth.err.linkExpired': 'This link has expired. Request a new one.',
'auth.err.linkUsed': 'This link is invalid or has already been used.',
'auth.err.linkInvalid': 'This link is invalid.',
'settings.language': 'Language',
'settings.backupShared': 'Backup shared.',
'settings.backupDownloaded': 'Backup downloaded.',
'settings.exportFailed': 'Export failed.',
'settings.noValidItems': 'The file has no valid entries.',
'settings.imported_one': '{count} entry imported.',
'settings.imported_other': '{count} entries imported.',
'settings.importedSkipped': '{n} entry(ies) imported, {skipped} skipped.',
'settings.cleared': 'Library cleared.',
'settings.pageTitle': 'My ',
'settings.pageAccent': 'settings',
'settings.languageHint': 'Language for the app, dates and info fetched from TMDB (titles, synopses).',
'settings.rating': 'Ratings',
'settings.scale5': '★ out of 5',
'settings.scale10': 'Out of 10',
'settings.ratingHint': 'Half stars out of 5, or 0.5 steps out of 10. Existing ratings are converted automatically.',
'settings.theme': 'Theme',
'settings.themeX': '{name} theme',
'settings.pickColor': 'Pick a custom color',
'settings.freeColor': 'Custom color',
'settings.freeColorHint': 'Any color works: text adjusts to stay readable.',
'settings.databases': 'Movie databases',
'settings.anilistActive': 'Anime · active',
'settings.noConfig': 'No setup needed.',
'settings.tmdbActive': 'Movies & series · active',
'settings.checking': 'Checking…',
'settings.offline': 'Offline',
'settings.proxyMissingKey': 'TMDB key missing',
'settings.proxyNotDeployed': 'Server not set up',
'settings.unavailable': 'Unavailable',
'settings.proxyMissingKeyHint': 'The server function is in place but your TMDB key isn’t saved (TMDB_API_KEY secret in Supabase), or TMDB is refusing it.',
'settings.proxyNotDeployedHint': 'The “tmdb” function isn’t deployed on Supabase yet (see README → Accounts, step 5).',
'settings.proxyErrorHint': 'The server isn’t responding properly right now.',
'settings.proxyOkHint': 'Provided by the app’s server: no key needed.',
'settings.recheck': 'Check again',
'settings.keyRefused': 'Key refused',
'settings.notConfigured': 'Not set up',
'settings.tmdbHelp': 'Movies, series, K-dramas, C-dramas. Create a free account on themoviedb.org, then go to Settings → API and paste your “API Key” or “API Read Access Token”.',
'settings.tmdbKey': 'TMDB key',
'settings.hideKey': 'Hide key',
'settings.showKey': 'Show key',
'settings.validate': 'Save',
'settings.remove': 'Remove',
'settings.keyLocal': 'The key stays on this device and is never included in backups.',
'settings.topHint': 'Categories shown on the home screen.',
'settings.topNone': 'No categories: the Top 5 section is hidden.',
'settings.backup': 'Backup',
'settings.export': 'Export my data',
'settings.exportHint_one': '{count} entry · JSON file, do it regularly',
'settings.exportHint_other': '{count} entries · JSON file, do it regularly',
'settings.import': 'Import a backup',
'settings.importHint': 'Restore from a .json file',
'settings.legacyDetected': 'Backup from the old app detected',
'settings.found_one': '{count} entry found. How do you want to import it?',
'settings.found_other': '{count} entries found. How do you want to import them?',
'settings.foundSkipped': '{n} entry(ies) found ({skipped} invalid skipped). How do you want to import them?',
'settings.merge': 'Merge',
'settings.replaceAll': 'Replace all',
'settings.mergeHint': '“Merge” adds entries and updates the ones that already exist (same ID).',
'settings.storage': 'Storage',
'settings.used': 'Space used',
'settings.storageCloud': 'Your data is saved to your account and also kept on this device so the app works offline. It syncs automatically whenever you’re online.',
'settings.storageLocal': 'Your data is stored only in this browser, on this device. If you clear browser data or uninstall the app, it’s gone: export a backup regularly.',
'settings.danger': 'Danger zone',
'settings.clearAll': 'Clear the whole library',
'settings.clearAllHint_one': '{count} title',
'settings.clearAllHint_other': '{count} titles',
'settings.clearAllHintCloud_one': '{count} title · on all your devices',
'settings.clearAllHintCloud_other': '{count} titles · on all your devices',
'settings.deleting': 'Deleting…',
'settings.deleteAccount': 'Delete my account',
'settings.deleteAccountHint': 'Account and data permanently erased',
'settings.footerCloud': 'synced account',
'settings.footerLocal': '100% local',
'settings.clearConfirm_one': '{count} title will be permanently deleted. Consider exporting a backup first.',
'settings.clearConfirm_other': 'Your {count} titles will be permanently deleted. Consider exporting a backup first.',
'settings.clearConfirmCloud_one': '{count} title will be permanently deleted on all your devices. Consider exporting a backup first.',
'settings.clearConfirmCloud_other': 'Your {count} titles will be permanently deleted on all your devices. Consider exporting a backup first.',
'settings.clearAllConfirm': 'Clear everything',
'settings.deleteAccountTitle': 'Delete your account?',
'settings.deleteAccountMessage': 'Your account and all your data (titles, lists, settings) will be permanently erased from the server and this device. Consider exporting a backup first. This can’t be undone.',
'settings.deleteForever': 'Delete forever',
'settings.replaceConfirm': 'Your entire current library will be replaced with the contents of this file.',
'settings.replace': 'Replace',
'sync.err.push': 'Upload refused ({status})',
'sync.err.pull': 'Download refused ({status})',
'store.dbError': 'Couldn’t open the local database: {error}',
'store.invalidItem': 'Invalid entry',
'lists.newList': 'New list',
'lists.newListPh': 'New list…',
'lists.myLists': 'My lists',
'lists.rename': 'Rename',
'lists.delete': 'Delete list',
'lists.done': 'Done',
'lists.addRemove': 'Add / remove titles',
'lists.searchLibrary': 'Search my library…',
'lists.emptyTitle': 'Empty list',
'lists.emptyText': 'Add titles with the button above, or from a title’s page.',
'lists.deleteConfirm': 'The list “{name}” will be deleted. The titles stay in your library.',
'lists.noneTitle': 'No lists yet',
'lists.noneText': 'Make lists your way: “Watch with friends”, “October horror movies”, “Comfort dramas”…',
'lists.create': 'Create',
'account.err.deleteRate': 'Too many attempts, try again in a minute.',
'account.err.delete': 'Deletion failed. Try again later.',
'account.title': 'My account',
'account.syncing': 'Syncing…',
'account.offline': 'Offline — everything is kept on this device',
'account.syncError': 'Can’t sync right now',
'account.synced': 'Synced {when}',
'account.passwordChanged': 'Password changed.',
'account.imported_one': '{count} title added to your account.',
'account.imported_other': '{count} titles added to your account.',
'account.importFailed': 'Import failed.',
'account.pending_one': '{count} pending',
'account.pending_other': '{count} pending',
'account.syncNow': 'Sync now',
'account.newPasswordPh': 'New password ({n} characters min.)',
'account.changePassword': 'Change password',
'account.logout': 'Log out',
'account.logoutHint': 'Your data stays in your account and is removed from this device.',
'account.ignore': 'Ignore',
'account.deviceHint': 'They’ll be moved to your account and synced across all your devices.',
'account.unsentTitle': 'Unsent changes',
'account.logoutAnyway': 'Log out anyway',
'account.unsentMessage_one': '{count} change hasn’t been sent yet (no connection?). If you log out now, it’ll be lost.',
'account.unsentMessage_other': '{count} changes haven’t been sent yet (no connection?). If you log out now, they’ll be lost.',
'account.nTitles_one': '{count} title',
'account.nTitles_other': '{count} titles',
'account.nLists_one': '{count} list',
'account.nLists_other': '{count} lists',
'account.deviceData': 'This device has {titles} created before your account. Add them to your account?',
'account.deviceDataWithLists': 'This device has {titles} and {lists} created before your account. Add them to your account?',
'time.never': 'never',
'time.justNow': 'just now',
'time.minutesAgo': '{n} min ago',
'time.hoursAgo': '{n} h ago',
'time.onDate': 'on {date}',
'time.today': 'today',
'time.tomorrow': 'tomorrow',
'time.daysAgo': '{n} d ago',
'theme.red': 'Red',
'theme.orange': 'Orange',
'theme.yellow': 'Yellow',
'theme.lime': 'Lime',
'theme.green': 'Green',
'theme.mint': 'Mint',
'theme.cyan': 'Cyan',
'theme.blue': 'Blue',
'theme.indigo': 'Indigo',
'theme.violet': 'Violet',
'theme.pink': 'Pink',
'theme.white': 'White',
'home.seeAll': 'See all',
'home.subtitle': 'My watch journal',
'home.calendarSoon_one': 'Release calendar: {count} this week',
'home.calendarSoon_other': 'Release calendar: {count} this week',
'home.emptyTitle': 'Your library is empty',
'home.emptyCloud': 'Add your first movie, anime or drama. It’ll be saved to your account.',
'home.emptyLocal': 'Add your first movie, anime or drama. Everything stays stored only on this phone.',
'home.completed': 'Finished',
'home.thisYear_one': '{count} this year',
'home.thisYear_other': '{count} this year',
'home.toWatchN_one': '{count} to watch',
'home.toWatchN_other': '{count} to watch',
'home.screenTime': 'Screen time',
'home.estimate': 'estimate',
'home.episodesSeen': 'Episodes watched',
'home.noIdea': 'Can’t decide?',
'home.rouletteHint_one': 'Random pick from your title to watch',
'home.rouletteHint_other': 'Random pick from your {count} titles to watch',
'home.rouletteHintAll': 'Random pick from your library',
'home.recentlyFinished': 'Recently finished',
'calendar.title': 'Release calendar',
'calendar.inMyList': 'In my list',
'calendar.inMyListLegend': 'In my list',
'calendar.seeMore_one': 'See the other one',
'calendar.seeMore_other': 'See the {count} others',
'calendar.heading': 'Release ',
'calendar.headingAccent': 'calendar',
'calendar.refresh': 'Refresh',
'calendar.all': 'All releases',
'calendar.mine': 'My titles',
'calendar.prevMonth': 'Previous month',
'calendar.nextMonth': 'Next month',
'calendar.releases_one': '{count} release',
'calendar.releases_other': '{count} releases',
'calendar.others': 'Other releases',
'calendar.needKey': 'Without a TMDB key, only anime is shown. Add your key in Settings to see movies, series and dramas too.',
'calendar.range': 'Releases are available from last month up to 6 months ahead.',
'calendar.failed': 'Some releases couldn’t be loaded. Try again with ↻.',
'calendar.nothingThatDay': 'Nothing scheduled that day.',
'calendar.next14': 'Next 14 days',
'calendar.loading': 'Looking for releases…',
'calendar.noneMine14': 'No releases announced for your titles in the next 14 days.',
'calendar.noneMineMonth': 'No releases announced for your titles this month.',
'calendar.none14': 'No releases in the next 14 days.',
'calendar.noneMonth': 'No releases found for this month.',
'calendar.footer': 'Movies in theaters in your country, episodes of the most followed series and dramas (TMDB) and of all anime airing in Japan (AniList). Titles in your library are highlighted; tap “To watch” to add a release to your list.',
'roulette.name': 'Roulette',
'roulette.rewatch': 'To rewatch',
'roulette.anyTime': 'Any',
'roulette.heading': 'The ',
'roulette.headingAccent': 'roulette',
'roulette.tonight': 'Tonight, it’s…',
'roulette.nEps': '{n} eps',
'roulette.perEp': '{duration} / ep.',
'roulette.stoppedAt': 'You left off at episode {ep}.',
'roulette.stoppedAtOf': 'You left off at episode {ep} of {total}.',
'roulette.enjoy': 'Enjoy the show!',
'roulette.again': 'Spin again',
'roulette.spinning': 'Spinning…',
'roulette.spin': 'Spin the roulette',
'roulette.poolSize_one': 'Picking from {count} title',
'roulette.poolSize_other': 'Picking from {count} titles',
'roulette.empty': 'No titles match: widen the filters below.',
'roulette.inside': 'In the roulette',
'roulette.pickFrom': 'Pick from',
'roulette.rewatchHint': '“To rewatch” = your finished titles rated 4/5 or higher, favorites and Top 5.',
'roulette.time': 'Time available (movie or 1 episode)',
'roulette.seeItem': 'See full details',
'roulette.watchIt': 'I’ll watch it',
'newEp.check': 'Check',
'newEp.title': 'What’s new',
'newEp.checking': 'Checking what’s out…',
'newEp.needKey': 'Add your TMDB key in Settings to get notified about new episodes and seasons.',
'newEp.nothing_one': 'Nothing new for your tracked show.',
'newEp.nothing_other': 'Nothing new for your {count} tracked shows.',
'newEp.needKeyAlso': '(Add your TMDB key in Settings to track series and dramas too.)',
'newEp.newSeason': 'New season',
'newEp.catchUp': 'To catch up',
'newEp.soon': 'Coming soon',
'newEp.epWhen': 'Ep. {ep} {when}',
'newEp.available_one': '{count} episode available',
'newEp.available_other': '{count} episodes available',
'newEp.next': 'Next: ep. {ep} {when}',
'newEp.resume': 'Resume',
'top.pick': 'Pick #{rank}',
'top.shareTitle': 'My Top 5 {category}',
'top.shareLabel': 'Share this Top 5 as an image',
'top.title': 'My Top',
'top.number': '#{rank}',
'top.pickFirst': 'Pick your #1.',
'top.editLabel': 'Edit Top 5',
'top.freeSlot': 'Free spot — pick a title below',
'top.addFromLibrary': 'Add from my library',
'top.allTypes': 'All types',
'top.searchTitle': 'Search for a title…',
'top.full': 'Your Top 5 is full: remove a title to add another one.',
'top.noCandidates': 'No titles. Try “All types” or a different search.',
'reco.error': 'Can’t load suggestions right now.',
'reco.title': 'Suggestions',
'reco.needKey': 'Add your TMDB key in Settings to get suggestions based on your favorite titles.',
'reco.other': 'Another title',
'reco.ifYouLiked': 'If you liked',
'reco.loading': 'Looking for suggestions…',
'reco.none': 'You already have everything similar to this title. Try “Another title”.',
'reco.added': '{title} added',
'reco.addLabel': 'Add {title} to watch',
'reco.addedShort': 'Added',
'search.moviesSeries': 'Movies & series',
'search.offline': 'No internet connection: search needs the network.',
'search.fillFrom': 'Fill in from a database',
'search.needKey': 'To search movies, series and dramas, add your free TMDB key in Settings.',
'search.openSettings': 'Open Settings',
'search.already': 'already added',
'search.noResults': 'No results. You can fill in the entry by hand below.',
'search.privacy': 'Only the title you search for is sent to {source}. Your library stays on your phone.',
'catalog.sortRecent': 'Recently edited',
'catalog.sortWatched': 'Watch date',
'catalog.sortRating': 'Top rated',
'catalog.sortTitle': 'Title (A→Z)',
'catalog.pageTitle': 'My ',
'catalog.pageAccent': 'catalog',
'catalog.journalSubtitle': 'Your watch history',
'catalog.filteredCount_one': '{count} title (filtered)',
'catalog.filteredCount_other': '{count} titles (filtered)',
'catalog.titles': 'Titles',
'catalog.journal': 'Journal',
'catalog.lists': 'Lists',
'catalog.searchPh': 'Title, genre, platform…',
'catalog.moreFilters': 'More filters',
'catalog.all': 'All',
'catalog.genre': 'Genre',
'catalog.minRating': 'Minimum rating',
'catalog.allRatings': 'Any',
'catalog.sortBy': 'Sort by',
'catalog.favorites': 'Favorites',
'catalog.reset': 'Reset',
'catalog.noResults': 'No results',
'catalog.nothingYet': 'Nothing here yet',
'catalog.noResultsHint': 'Try a different search or remove some filters.',
'catalog.nothingYetHint': 'Add your first title with the + button.',
'catalog.clearFilters': 'Clear filters',
'public.agree': 'Right in line with the audience',
'public.more': '+{gap} higher than the audience',
'public.less': '−{gap} lower than the audience',
'public.label': 'Audience',
'public.me': 'Me',
'public.added_one': '{count} audience rating added.',
'public.added_other': '{count} audience ratings added.',
'public.noneFound': 'No new ratings found.',
'public.fetch': 'Fetch ({n})',
'public.title': 'Me vs the audience',
'public.hintFetch': 'Fetch the average TMDB / AniList rating for your rated titles to see where you stand out from the audience.',
'public.hintNone': 'No audience ratings available for your rated titles in this period.',
'public.hintKey': 'Add your TMDB key in Settings (or link anime to AniList) to compare yourself with the audience.',
'public.avgGap': 'Average gap',
'public.average': 'Right on average',
'public.generous': 'More generous than the audience',
'public.harsh': 'Harsher than the audience',
'public.agreeTitle': 'In agreement',
'public.within5_one': 'within ½ star, on {count} title',
'public.within5_other': 'within ½ star, on {count} titles',
'public.within10_one': 'within 1 point, on {count} title',
'public.within10_other': 'within 1 point, on {count} titles',
'public.lovedPre': 'I ',
'public.lovedAccent': 'liked more',
'public.lovedPost': ' than the audience',
'public.hatedPre': 'I ',
'public.hatedAccent': 'liked less',
'public.hatedPost': ' than the audience',
'public.allAgree': 'You agree with the audience on all your titles. Rare!',
'form.rewatchHint': 'Watched it again? Log each rewatch and it’ll show up in your journal.',
'form.editTitle': 'Edit ',
'form.editAccent': 'entry',
'form.newTitle': 'New ',
'form.newAccent': 'title',
'form.filledFrom': 'Filled in from',
'form.canEdit': 'you can edit everything',
'form.fillFromDb': 'Fill in from TMDB / AniList',
'form.pickPoster': 'Pick a poster',
'form.removeImage': 'Remove image',
'form.title': 'Title *',
'form.titlePh': 'e.g. Your Name',
'form.originalTitle': 'Original title',
'form.originalTitlePh': 'e.g. 君の名は。',
'form.synopsis': 'Synopsis',
'form.type': 'Type',
'form.subtype': 'Kind',
'form.subtypePh': 'Documentary, Reality TV…',
'form.status': 'Status',
'form.myRating': 'My rating',
'form.favorite': 'Favorite',
'form.criteria': 'Detailed criteria (optional)',
'form.episodes': 'Episodes',
'form.minusEp': '-1 episode',
'form.plusEp': '+1 episode',
'form.total': 'Total',
'form.season': 'Season',
'form.minPerEp': 'Min / ep.',
'form.duration': 'Runtime',
'form.durationMin': 'Runtime (minutes)',
'form.info': 'Info',
'form.start': 'Started / watched on',
'form.end': 'Finished',
'form.year': 'Year',
'form.platform': 'Platform',
'form.genres': 'Genres / tags',
'form.genresPh': 'Romance, Sci-Fi…',
'form.rewatches': 'Rewatches',
'form.review': 'My review',
'form.reviewPh': 'What I thought, memorable scenes…',
'form.saveChanges': 'Save changes',
'form.addToLibrary': 'Add to my library',
'form.shareImage': 'Share as image',
'form.delete': 'Delete this title',
'form.deleteConfirm': '“{title}” will be permanently deleted.',
'form.removeRewatch': 'Remove this rewatch',
'form.rewatchDate': 'Rewatch date',
'form.reviewPublic': 'Show this review on my profile',
'form.reviewPublicHint': 'Otherwise, only you can see it.',
'journal.rewatched': 'Rewatched',
'journal.started': 'Started',
'journal.emptyTitle': 'Empty journal',
'journal.emptyText': 'Your watches will show up here once your entries have start or finish dates.',
'journal.seen_one': '{count} watched',
'journal.seen_other': '{count} watched',
'journal.more': 'Show earlier months',
'stats.overview': 'Overview',
'stats.habits': 'Habits',
'stats.tastes': 'Tastes',
'stats.pageTitle': 'My ',
'stats.pageAccent': 'stats',
'stats.emptyTitle': 'No stats yet',
'stats.emptyText': 'They’ll show up once you’ve added some titles.',
'stats.sinceStart': 'all time',
'stats.subtitle_one': '{count} title in my library',
'stats.subtitle_other': '{count} titles in my library',
'stats.subtitleYear_one': '{count} title in {year}',
'stats.subtitleYear_other': '{count} titles in {year}',
'stats.hours_one': 'hour',
'stats.hours_other': 'hours',
'stats.nonStopPre': 'that’s ',
'stats.nonStopPost': ' non-stop',
'stats.days_one': '{count} day',
'stats.days_other': '{count} days',
'stats.finishedN_one': '{count} finished',
'stats.finishedN_other': '{count} finished',
'stats.episodesN_one': '{count} episode',
'stats.episodesN_other': '{count} episodes',
'stats.timeByType': 'Time by type',
'stats.noTime': 'No time logged in this period yet.',
'stats.avgRating': 'Average rating',
'stats.rated_one': '{count} title rated',
'stats.rated_other': '{count} titles rated',
'stats.inYear': 'in {year}',
'stats.statuses': 'Statuses',
'stats.hoursTab': 'Hours',
'stats.monthByMonth': 'Month by month · {year}',
'stats.last12': 'Last 12 months',
'stats.monthFinished_one': '{count} title finished',
'stats.monthFinished_other': '{count} titles finished',
'stats.busiest': 'Busiest month:',
'stats.records': 'Records',
'stats.marathon': 'Biggest marathon',
'stats.longestFilm': 'Longest movie',
'stats.noRecords': 'No records in this period yet.',
'stats.platforms': 'Platforms',
'stats.bestRated': 'My top rated',
'stats.myRatings': 'My ratings',
'stats.noRatings': 'No ratings in this period.',
'stats.favGenres': 'Favorite genres',
'stats.noGenres': 'No genres yet.',
'stats.countries': 'Countries',
'stats.noCountry_one': '{count} title has no country: fill it in with “Fill in from TMDB / AniList” on its page.',
'stats.noCountry_other': '{count} titles have no country: fill them in with “Fill in from TMDB / AniList” on their pages.',
'stats.noCountryLegacy_one': '{count} title has no country: fill it in with “Fill in from TMDB / AniList” on its page, or re-import your old app’s backup (“Merge”).',
'stats.noCountryLegacy_other': '{count} titles have no country: fill them in with “Fill in from TMDB / AniList” on their pages, or re-import your old app’s backup (“Merge”).',
'stats.byType': 'By type',
'stats.footnote': 'Time estimated from episodes watched and runtimes entered (otherwise: movie 1 h 50, anime episode 24 min, series 45 min, K-drama 1 h, C-drama 45 min). A title counts toward the year I finished it.',
'stats.ratedAs_one': 'rated {rating}',
'stats.ratedAs_other': 'rated {rating}',
'backup.shareTitle': 'AzuuCine backup',
'backup.tooBig': 'File too large (30 MB max).',
'backup.notJson': 'This file isn’t valid JSON.',
'backup.noItems': 'No entries found in this file.',
'backup.tooMany': 'Too many entries ({n} max).',
'image.canvas': 'Canvas unavailable',
'image.unreadable': 'Unreadable image',
'image.notImage': 'This file isn’t an image.',
'image.tooBig': 'Image too large (25 MB max).',
'social.err.server': 'The server responded {status}.',
'social.err.usernameTaken': 'That username’s already taken.',
'social.err.usernameReserved': 'That username isn’t available.',
'social.err.invalid': 'One of the values isn’t valid.',
'social.inLibrary': 'In my library',
'social.addToWatch': 'Add to To watch',
'social.linkCopied': 'Link copied!',
'social.profile': 'Profile',
'social.shareProfile': 'Share profile',
'social.loading': 'Loading…',
'social.loadError': 'Couldn’t load the profile.',
'social.notFound': 'Profile not found',
'social.notFoundHint': 'There’s no profile called @{username}.',
'social.editProfile': 'Edit profile',
'social.following': 'Following',
'social.requested': 'Requested',
'social.followBack': 'Follow back',
'social.follow': 'Follow',
'social.private': 'Private account',
'social.followsYou': 'Follows you',
'social.seen': 'Watched',
'social.followers_one': 'Follower',
'social.followers_other': 'Followers',
'social.followingCount_one': 'Following',
'social.followingCount_other': 'Following',
'social.requests_one': '{count} follow request',
'social.requests_other': '{count} follow requests',
'social.privateTitle': 'This account is private',
'social.privateText': 'Follow them to see their watches, ratings and Top 5.',
'social.tabProfile': 'Profile',
'social.tabLibrary': 'Library',
'social.cancelRequestTitle': 'Cancel follow request?',
'social.unfollowTitle': 'Unfollow {name}?',
'social.unfollowPrivate': 'This account is private: you’ll have to send a new request to see their profile again.',
'social.cancelRequest': 'Cancel request',
'social.unfollow': 'Unfollow',
'social.top5': 'Top 5',
'social.recent': 'Recently watched',
'social.noRecent': 'Nothing finished yet.',
'social.statYear': 'Watched this year',
'social.statFilms': 'Movies watched',
'social.statSeries': 'Series & anime watched',
'social.emptyLibrary': 'No titles here.',
'social.loadMore': 'Show more',
'social.changeBanner': 'Change banner',
'social.changeAvatar': 'Change photo',
'social.removeAvatar': 'Remove photo',
'social.removeBanner': 'Remove banner',
'social.displayName': 'Display name',
'social.username': 'Username',
'social.usernameRule': '3–20 characters: lowercase letters, numbers or _',
'social.bio': 'Bio',
'social.bioPh': 'What you love to watch, your favorite genres…',
'social.privateAccount': 'Private account',
'social.privateHint': 'Only followers you approve can see what you watch.',
'social.publicHint': 'Your name, username, photo, banner and bio are visible to all members. Your written reviews stay private, except the ones you choose to show on your profile.',
'social.requestsTab_one': 'Request',
'social.requestsTab_other': 'Requests ({count})',
'social.noFollowing': 'Not following anyone yet.',
'social.noFollowers': 'No followers yet.',
'social.accept': 'Accept',
'social.decline': 'Decline',
'social.removeFollower': 'Remove',
'social.findFriends': 'Find friends',
'social.searchPh': 'Username or name…',
'social.noResults': 'No one matches.',
'social.inviteHint': 'Your friends aren’t on AzuuCine yet? Send them a link to your profile.',
'social.shareMyProfile': 'Share my profile',
'social.inviteText': 'Follow me on AzuuCine!',
'social.myProfile': 'My profile',
'feed.title': 'Following',
'feed.empty': 'Follow friends to see what they’re watching and what they think of it here.',
'feed.finished': 'watched',
'feed.started': 'started',
'feed.rewatched': 'rewatched',
'feed.added': 'wants to watch',
'feed.review': 'review',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** Español */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': 'Cancelar',
'common.confirm': 'Confirmar',
'common.close': 'Cerrar',
'common.save': 'Guardar',
'common.add': 'Añadir',
'common.delete': 'Eliminar',
'common.all': 'Todo',
'common.none': 'Ninguno',
'common.noData': 'Aún no hay datos.',
'common.retry': 'Reintentar',
'common.back': 'Volver',
'common.offline': 'Sin conexión a internet.',
'common.minutes': '{n} min',
'common.hours': '{h} h',
'common.hoursMinutes': '{h} h {m}',
'common.daysHours': '{d} d {h} h',
'common.decimalSep': ',',
'common.removeX': 'Quitar {name}',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': 'Editar',
'common.moveUp': 'Subir',
'common.moveDown': 'Bajar',
'nav.home': 'Inicio',
'nav.catalog': 'Catálogo',
'nav.stats': 'Estadísticas',
'nav.settings': 'Ajustes',
'nav.addTitle': 'Añadir un título',
'type.film': 'Película',
'type.serie': 'Serie',
'type.anime': 'Anime',
'type.kdrama': 'K-Drama',
'type.cdrama': 'C-Drama',
'type.autre': 'Otro',
'typePlural.film': 'Películas',
'typePlural.serie': 'Series',
'typePlural.anime': 'Animes',
'typePlural.kdrama': 'K-Dramas',
'typePlural.cdrama': 'C-Dramas',
'status.a_voir': 'Por ver',
'status.en_cours': 'Viendo',
'status.termine': 'Terminado',
'status.pause': 'En pausa',
'status.abandonne': 'Abandonado',
'criteria.story': 'Guion / Historia',
'criteria.cast': 'Personajes / Reparto',
'criteria.direction': 'Dirección / Animación',
'criteria.ost': 'Banda sonora (OST)',
'subtype.documentary': 'Documental',
'subtype.reality': 'Reality show',
'subtype.show': 'Programa de TV',
'subtype.short': 'Cortometraje',
'subtype.stage': 'Espectáculo',
'subtype.miniseries': 'Miniserie',
'platform.cinema': 'Cine',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'TV',
'genre.action': 'Acción',
'genre.adventure': 'Aventura',
'genre.comedy': 'Comedia',
'genre.drama': 'Drama',
'genre.romance': 'Romance',
'genre.romcom': 'Rom-com',
'genre.thriller': 'Thriller',
'genre.horror': 'Terror',
'genre.mystery': 'Misterio',
'genre.crime': 'Crimen',
'genre.scifi': 'Ciencia ficción',
'genre.fantasy': 'Fantasía',
'genre.historical': 'Histórico',
'genre.sliceOfLife': 'Slice of Life',
'genre.shonen': 'Shōnen',
'genre.shojo': 'Shōjo',
'genre.seinen': 'Seinen',
'genre.isekai': 'Isekai',
'genre.mecha': 'Mecha',
'genre.sports': 'Deportes',
'genre.musical': 'Musical',
'genre.medical': 'Médico',
'genre.legal': 'Judicial',
'genre.wuxia': 'Wuxia',
'genre.xianxia': 'Xianxia',
'genre.family': 'Familia',
'genre.animation': 'Animación',
'genre.psychological': 'Psicológico',
'genre.supernatural': 'Sobrenatural',
'genre.romanticComedy': 'Comedia romántica',
'genre.documentary': 'Documental',
'genre.war': 'Bélica',
'genre.western': 'Western',
'genre.music': 'Música',
'genre.ecchi': 'Ecchi',
'genre.kids': 'Infantil',
'genre.news': 'Noticias',
'genre.reality': 'Reality',
'genre.talk': 'Talk show',
'genre.soap': 'Telenovela',
'genre.politics': 'Política',
'genre.tvMovie': 'Película de TV',
'genre.anime': 'Anime',
'genre.magicalGirl': 'Magical Girl',
'confirm.title': '¿Seguro?',
'err.tmdbRefused': 'Solicitud a TMDB rechazada.',
'err.tmdbKeyRefused': 'Clave de TMDB rechazada. Revísala en Ajustes.',
'err.tmdbStatus': 'TMDB respondió {status}.',
'err.tmdbRef': 'Referencia de TMDB no válida.',
'err.anilistRate': 'AniList está limitando las solicitudes, vuelve a intentarlo en un minuto.',
'err.anilistStatus': 'AniList respondió {status}.',
'err.searchRate': 'Demasiadas búsquedas, vuelve a intentarlo en unos minutos.',
'anilist.short': 'Anime corto',
'anilist.movie': 'Película de animación',
'anilist.special': 'Especial',
'anilist.music': 'Videoclip',
'release.cinema': 'En cines',
'release.online': 'En VOD / streaming',
'release.release': 'Estreno',
'release.season': 'Temporada {season}',
'release.episode': 'Episodio {ep}',
'release.newEpisode': 'Nuevo episodio',
'release.firstEpisode': 'Primer episodio',
'release.newSeriesN': 'Nueva serie · {count} episodios',
'release.seasonN': 'Temporada {season} · {count} episodios',
'release.seasonEp1': 'Temporada {season} · Episodio 1',
'release.episodes': 'Episodios {first}–{last}',
'release.sEpisodes': 'T{season} · Episodios {first}–{last}',
'release.sEpisode': 'T{season} · Episodio {ep}',
'release.episodeFinal': 'Episodio {ep} · final',
'release.filmJapan': 'Película en Japón',
'card.ep': 'Ep. {n}',
'card.plusOne': '+1 episodio de {title}',
'card.open': 'Abrir {title}',
'rating.outOf10': 'Nota sobre 10',
'rating.stars_one': '{count} estrella',
'rating.stars_other': '{count} estrellas',
'rating.clear': 'Borrar la nota',
'share.previewLabel': 'Vista previa de la imagen',
'share.preview': 'Vista previa',
'share.posterAlt': 'Póster de {title}',
'share.share': 'Compartir',
'share.saveImage': 'Guardar la imagen',
'share.err.create': 'No se pudo crear la imagen',
'share.minutesLong': '{n} minutos',
'share.createdBy': 'Creado por',
'share.directedBy': 'Dirigido por',
'share.producedBy': 'Producido por',
'share.starring': 'Con',
'share.genres': 'Géneros',
'share.myRating': 'Mi nota',
'share.myTop': 'Mi Top',
'auth.hidePassword': 'Ocultar la contraseña',
'auth.showPassword': 'Mostrar la contraseña',
'auth.mismatch': 'Las dos contraseñas no coinciden.',
'auth.created': '¡Cuenta creada! Abre el enlace enviado a {email} para activarla y luego inicia sesión.',
'auth.resetSent': 'Si existe una cuenta con esta dirección, te acabamos de enviar un enlace para elegir una nueva contraseña.',
'auth.tagline': 'Tu diario de películas, series, animes y dramas.',
'auth.loginTab': 'Iniciar sesión',
'auth.signupTab': 'Crear una cuenta',
'auth.forgotTitle': 'Contraseña olvidada',
'auth.email': 'Correo electrónico',
'auth.password': 'Contraseña',
'auth.confirmPassword': 'Confirma la contraseña',
'auth.minChars': 'Al menos {n} caracteres.',
'auth.login': 'Iniciar sesión',
'auth.signup': 'Crear mi cuenta',
'auth.sendLink': 'Enviar el enlace',
'auth.forgot': '¿Olvidaste tu contraseña?',
'auth.backToLogin': 'Volver a iniciar sesión',
'auth.privacy': 'Tus datos están vinculados a tu cuenta y solo tú puedes verlos. También se quedan en tu dispositivo para funcionar sin internet.',
'auth.newPasswordTitle': 'Elige tu nueva contraseña.',
'auth.newPassword': 'Nueva contraseña',
'auth.err.credentials': 'Correo o contraseña incorrectos.',
'auth.err.notConfirmed': 'Primero confirma tu dirección con el enlace que recibiste por correo.',
'auth.err.exists': 'Ya existe una cuenta con este correo.',
'auth.err.weak': 'Contraseña demasiado débil (al menos {n} caracteres, mezcla letras y números).',
'auth.err.samePassword': 'La nueva contraseña tiene que ser distinta de la anterior.',
'auth.err.emailRate': 'Demasiadas solicitudes. Vuelve a intentarlo en unos minutos.',
'auth.err.rate': 'Demasiados intentos. Vuelve a intentarlo en unos minutos.',
'auth.err.signupDisabled': 'Los registros están cerrados por ahora.',
'auth.err.emailInvalid': 'Correo electrónico no válido.',
'auth.err.invalid': 'Correo o contraseña no válidos.',
'auth.err.session': 'Sesión caducada, vuelve a iniciar sesión.',
'auth.err.status': 'El servidor rechazó la solicitud ({status}).',
'auth.err.response': 'Respuesta del servidor no válida.',
'auth.err.linkExpired': 'Este enlace ha caducado. Pide uno nuevo.',
'auth.err.linkUsed': 'Este enlace no es válido o ya se ha usado.',
'auth.err.linkInvalid': 'Este enlace no es válido.',
'settings.language': 'Idioma',
'settings.backupShared': 'Copia de seguridad compartida.',
'settings.backupDownloaded': 'Copia de seguridad descargada.',
'settings.exportFailed': 'La exportación falló.',
'settings.noValidItems': 'El archivo no contiene ninguna ficha válida.',
'settings.imported_one': '{count} ficha importada.',
'settings.imported_other': '{count} fichas importadas.',
'settings.importedSkipped': '{n} ficha(s) importada(s), {skipped} omitida(s).',
'settings.cleared': 'Biblioteca borrada.',
'settings.pageTitle': 'Mis ',
'settings.pageAccent': 'ajustes',
'settings.languageHint': 'Idioma de la app, de las fechas y de la info obtenida de TMDB (títulos, sinopsis).',
'settings.rating': 'Puntuación',
'settings.scale5': '★ sobre 5',
'settings.scale10': 'Sobre 10',
'settings.ratingHint': 'Medias estrellas sobre 5, o pasos de 0,5 sobre 10. Las notas existentes se convierten automáticamente.',
'settings.theme': 'Tema',
'settings.themeX': 'Tema {name}',
'settings.pickColor': 'Elegir un color libre',
'settings.freeColor': 'Color libre',
'settings.freeColorHint': 'Cualquier color: el texto se adapta para seguir siendo legible.',
'settings.databases': 'Bases de datos de películas',
'settings.anilistActive': 'Animes · activo',
'settings.noConfig': 'No hace falta configurar nada.',
'settings.tmdbActive': 'Películas y series · activo',
'settings.checking': 'Comprobando…',
'settings.offline': 'Sin conexión',
'settings.proxyMissingKey': 'Falta la clave de TMDB',
'settings.proxyNotDeployed': 'Servidor no instalado',
'settings.unavailable': 'No disponible',
'settings.proxyMissingKeyHint': 'La función del servidor está lista, pero tu clave de TMDB no está guardada (secreto TMDB_API_KEY en Supabase) o TMDB la rechaza.',
'settings.proxyNotDeployedHint': 'La función «tmdb» aún no está desplegada en Supabase (ver README → Cuentas, paso 5).',
'settings.proxyErrorHint': 'El servidor no responde correctamente por ahora.',
'settings.proxyOkHint': 'Lo proporciona el servidor de la app: no tienes que introducir ninguna clave.',
'settings.recheck': 'Volver a comprobar',
'settings.keyRefused': 'Clave rechazada',
'settings.notConfigured': 'Sin configurar',
'settings.tmdbHelp': 'Películas, series, K-dramas, C-dramas. Crea una cuenta gratis en themoviedb.org, luego Ajustes → API, y pega tu «Clave de la API» o tu «Token de acceso de lectura».',
'settings.tmdbKey': 'Clave de TMDB',
'settings.hideKey': 'Ocultar la clave',
'settings.showKey': 'Mostrar la clave',
'settings.validate': 'Validar',
'settings.remove': 'Quitar',
'settings.keyLocal': 'La clave se queda en este dispositivo y nunca se incluye en las copias de seguridad.',
'settings.topHint': 'Categorías que se muestran en el inicio.',
'settings.topNone': 'Ninguna categoría: la sección Top 5 está oculta.',
'settings.backup': 'Copia de seguridad',
'settings.export': 'Exportar mis datos',
'settings.exportHint_one': '{count} ficha · archivo JSON, hazlo con regularidad',
'settings.exportHint_other': '{count} fichas · archivo JSON, hazlo con regularidad',
'settings.import': 'Importar una copia de seguridad',
'settings.importHint': 'Restaurar desde un archivo .json',
'settings.legacyDetected': 'Copia de seguridad de la app antigua reconocida',
'settings.found_one': '{count} ficha encontrada. ¿Cómo quieres importarla?',
'settings.found_other': '{count} fichas encontradas. ¿Cómo quieres importarlas?',
'settings.foundSkipped': '{n} ficha(s) encontrada(s) ({skipped} no válida(s) omitida(s)). ¿Cómo quieres importarlas?',
'settings.merge': 'Combinar',
'settings.replaceAll': 'Reemplazar todo',
'settings.mergeHint': '«Combinar» añade las fichas y actualiza las que ya existen (mismo identificador).',
'settings.storage': 'Almacenamiento',
'settings.used': 'Espacio usado',
'settings.storageCloud': 'Tus datos se guardan en tu cuenta y también en este dispositivo para funcionar sin internet. Se sincronizan automáticamente en cuanto tienes conexión.',
'settings.storageLocal': 'Tus datos se guardan solo en este navegador, en este dispositivo. Si borras los datos del navegador o desinstalas la app, desaparecerán: exporta una copia de seguridad con regularidad.',
'settings.danger': 'Zona de peligro',
'settings.clearAll': 'Borrar toda la biblioteca',
'settings.clearAllHint_one': '{count} título',
'settings.clearAllHint_other': '{count} títulos',
'settings.clearAllHintCloud_one': '{count} título · en todos tus dispositivos',
'settings.clearAllHintCloud_other': '{count} títulos · en todos tus dispositivos',
'settings.deleting': 'Eliminando…',
'settings.deleteAccount': 'Eliminar mi cuenta',
'settings.deleteAccountHint': 'Cuenta y datos borrados para siempre',
'settings.footerCloud': 'cuenta sincronizada',
'settings.footerLocal': '100 % local',
'settings.clearConfirm_one': '{count} título se borrará para siempre. Acuérdate de exportar una copia de seguridad antes.',
'settings.clearConfirm_other': 'Tus {count} títulos se borrarán para siempre. Acuérdate de exportar una copia de seguridad antes.',
'settings.clearConfirmCloud_one': '{count} título se borrará para siempre, en todos tus dispositivos. Acuérdate de exportar una copia de seguridad antes.',
'settings.clearConfirmCloud_other': 'Tus {count} títulos se borrarán para siempre, en todos tus dispositivos. Acuérdate de exportar una copia de seguridad antes.',
'settings.clearAllConfirm': 'Borrar todo',
'settings.deleteAccountTitle': '¿Eliminar tu cuenta?',
'settings.deleteAccountMessage': 'Tu cuenta y todos tus datos (títulos, listas, ajustes) se borrarán para siempre del servidor y de este dispositivo. Acuérdate de exportar una copia de seguridad antes. Esta acción no se puede deshacer.',
'settings.deleteForever': 'Eliminar para siempre',
'settings.replaceConfirm': 'Toda tu biblioteca actual se reemplazará por el contenido de este archivo.',
'settings.replace': 'Reemplazar',
'sync.err.push': 'Envío rechazado ({status})',
'sync.err.pull': 'Lectura rechazada ({status})',
'store.dbError': 'No se pudo abrir la base de datos local: {error}',
'store.invalidItem': 'Ficha no válida',
'lists.newList': 'Nueva lista',
'lists.newListPh': 'Nueva lista…',
'lists.myLists': 'Mis listas',
'lists.rename': 'Renombrar',
'lists.delete': 'Eliminar la lista',
'lists.done': 'Listo',
'lists.addRemove': 'Añadir / quitar títulos',
'lists.searchLibrary': 'Buscar en mi biblioteca…',
'lists.emptyTitle': 'Lista vacía',
'lists.emptyText': 'Añade títulos con el botón de arriba o desde la ficha de un título.',
'lists.deleteConfirm': 'Se eliminará la lista «{name}». Los títulos se quedan en tu biblioteca.',
'lists.noneTitle': 'Aún no hay listas',
'lists.noneText': 'Crea listas a tu manera: «Para ver con amigos», «Pelis de terror de octubre», «Dramas reconfortantes»…',
'lists.create': 'Crear',
'account.err.deleteRate': 'Demasiados intentos, vuelve a intentarlo en un minuto.',
'account.err.delete': 'No se pudo eliminar. Vuelve a intentarlo más tarde.',
'account.title': 'Mi cuenta',
'account.syncing': 'Sincronizando…',
'account.offline': 'Sin conexión — todo se guarda en este dispositivo',
'account.syncError': 'No se puede sincronizar por ahora',
'account.synced': 'Sincronizado {when}',
'account.passwordChanged': 'Contraseña cambiada.',
'account.imported_one': '{count} título añadido a tu cuenta.',
'account.imported_other': '{count} títulos añadidos a tu cuenta.',
'account.importFailed': 'La importación falló.',
'account.pending_one': '{count} pendiente',
'account.pending_other': '{count} pendientes',
'account.syncNow': 'Sincronizar ahora',
'account.newPasswordPh': 'Nueva contraseña (mín. {n} caracteres)',
'account.changePassword': 'Cambiar la contraseña',
'account.logout': 'Cerrar sesión',
'account.logoutHint': 'Tus datos se quedan en tu cuenta y se quitan de este dispositivo.',
'account.ignore': 'Ignorar',
'account.deviceHint': 'Se moverán a tu cuenta y se sincronizarán en todos tus dispositivos.',
'account.unsentTitle': 'Cambios sin enviar',
'account.logoutAnyway': 'Cerrar sesión de todos modos',
'account.unsentMessage_one': '{count} cambio aún no se ha enviado (¿sin conexión?). Si cierras sesión ahora, se perderá.',
'account.unsentMessage_other': '{count} cambios aún no se han enviado (¿sin conexión?). Si cierras sesión ahora, se perderán.',
'account.nTitles_one': '{count} título',
'account.nTitles_other': '{count} títulos',
'account.nLists_one': '{count} lista',
'account.nLists_other': '{count} listas',
'account.deviceData': 'Este dispositivo tiene {titles} creados antes de tu cuenta. ¿Añadirlos a tu cuenta?',
'account.deviceDataWithLists': 'Este dispositivo tiene {titles} y {lists} creados antes de tu cuenta. ¿Añadirlos a tu cuenta?',
'time.never': 'nunca',
'time.justNow': 'ahora mismo',
'time.minutesAgo': 'hace {n} min',
'time.hoursAgo': 'hace {n} h',
'time.onDate': 'el {date}',
'time.today': 'hoy',
'time.tomorrow': 'mañana',
'time.daysAgo': 'hace {n} d',
'theme.red': 'Rojo',
'theme.orange': 'Naranja',
'theme.yellow': 'Amarillo',
'theme.lime': 'Lima',
'theme.green': 'Verde',
'theme.mint': 'Menta',
'theme.cyan': 'Cian',
'theme.blue': 'Azul',
'theme.indigo': 'Índigo',
'theme.violet': 'Violeta',
'theme.pink': 'Rosa',
'theme.white': 'Blanco',
'home.seeAll': 'Ver todo',
'home.subtitle': 'Mi diario de lo que veo',
'home.calendarSoon_one': 'Calendario de estrenos: {count} esta semana',
'home.calendarSoon_other': 'Calendario de estrenos: {count} esta semana',
'home.emptyTitle': 'Tu biblioteca está vacía',
'home.emptyCloud': 'Añade tu primera película, anime o drama. Se guardará en tu cuenta.',
'home.emptyLocal': 'Añade tu primera película, anime o drama. Todo se guarda solo en este teléfono.',
'home.completed': 'Terminados',
'home.thisYear_one': '{count} este año',
'home.thisYear_other': '{count} este año',
'home.toWatchN_one': '{count} por ver',
'home.toWatchN_other': '{count} por ver',
'home.screenTime': 'Tiempo frente a la pantalla',
'home.estimate': 'estimación',
'home.episodesSeen': 'Episodios vistos',
'home.noIdea': '¿Sin ideas?',
'home.rouletteHint_one': 'Sorteo entre tu título por ver',
'home.rouletteHint_other': 'Sorteo entre tus {count} títulos por ver',
'home.rouletteHintAll': 'Sorteo en tu biblioteca',
'home.recentlyFinished': 'Terminados hace poco',
'calendar.title': 'Calendario de estrenos',
'calendar.inMyList': 'En mi lista',
'calendar.inMyListLegend': 'En mi lista',
'calendar.seeMore_one': 'Ver el otro',
'calendar.seeMore_other': 'Ver los otros {count}',
'calendar.heading': 'Calendario de ',
'calendar.headingAccent': 'estrenos',
'calendar.refresh': 'Actualizar',
'calendar.all': 'Todos los estrenos',
'calendar.mine': 'Mis títulos',
'calendar.prevMonth': 'Mes anterior',
'calendar.nextMonth': 'Mes siguiente',
'calendar.releases_one': '{count} estreno',
'calendar.releases_other': '{count} estrenos',
'calendar.others': 'Otros estrenos',
'calendar.needKey': 'Sin clave de TMDB solo se muestran los animes. Añade tu clave en Ajustes para ver también películas, series y dramas.',
'calendar.range': 'Los estrenos están disponibles desde el mes pasado hasta 6 meses vista.',
'calendar.failed': 'Algunos estrenos no se pudieron cargar. Vuelve a intentarlo con ↻.',
'calendar.nothingThatDay': 'Nada previsto ese día.',
'calendar.next14': 'Los próximos 14 días',
'calendar.loading': 'Buscando estrenos…',
'calendar.noneMine14': 'No hay estrenos anunciados para tus títulos en los próximos 14 días.',
'calendar.noneMineMonth': 'No hay estrenos anunciados para tus títulos este mes.',
'calendar.none14': 'No hay estrenos en los próximos 14 días.',
'calendar.noneMonth': 'No se encontraron estrenos este mes.',
'calendar.footer': 'Películas en cines de tu país, episodios de las series y dramas más seguidos (TMDB) y de todos los animes emitidos en Japón (AniList). Los títulos de tu biblioteca aparecen destacados; toca «Por ver» para añadir un estreno a tu lista.',
'roulette.name': 'Ruleta',
'roulette.rewatch': 'Para volver a ver',
'roulette.anyTime': 'Da igual',
'roulette.heading': 'La ',
'roulette.headingAccent': 'ruleta',
'roulette.tonight': 'Esta noche toca…',
'roulette.nEps': '{n} ep.',
'roulette.perEp': '{duration} / ep.',
'roulette.stoppedAt': 'Te quedaste en el episodio {ep}.',
'roulette.stoppedAtOf': 'Te quedaste en el episodio {ep} de {total}.',
'roulette.enjoy': '¡Que lo disfrutes!',
'roulette.again': 'Otra vez',
'roulette.spinning': 'Girando…',
'roulette.spin': 'Girar la ruleta',
'roulette.poolSize_one': 'Sorteo entre {count} título',
'roulette.poolSize_other': 'Sorteo entre {count} títulos',
'roulette.empty': 'Ningún título coincide: amplía los filtros de abajo.',
'roulette.inside': 'En la ruleta',
'roulette.pickFrom': 'Elegir entre',
'roulette.rewatchHint': '«Para volver a ver» = tus títulos terminados con 4/5 o más, favoritos y Top 5.',
'roulette.time': 'Tiempo disponible (película o 1 episodio)',
'roulette.seeItem': 'Ver la ficha completa',
'roulette.watchIt': 'Lo veo',
'newEp.check': 'Comprobar',
'newEp.title': 'Novedades',
'newEp.checking': 'Mirando qué ha salido…',
'newEp.needKey': 'Añade tu clave de TMDB en Ajustes para enterarte de los nuevos episodios y temporadas.',
'newEp.nothing_one': 'Nada nuevo para tu serie o anime en seguimiento.',
'newEp.nothing_other': 'Nada nuevo para tus {count} series y animes en seguimiento.',
'newEp.needKeyAlso': '(Añade tu clave de TMDB en Ajustes para seguir también series y dramas.)',
'newEp.newSeason': 'Nueva temporada',
'newEp.catchUp': 'Por ponerte al día',
'newEp.soon': 'Próximamente',
'newEp.epWhen': 'Ep. {ep} {when}',
'newEp.available_one': '{count} episodio disponible',
'newEp.available_other': '{count} episodios disponibles',
'newEp.next': 'Siguiente: ep. {ep} {when}',
'newEp.resume': 'Continuar',
'top.pick': 'Elegir el n.º {rank}',
'top.shareTitle': 'Mi Top 5 {category}',
'top.shareLabel': 'Compartir este Top 5 como imagen',
'top.title': 'Mis Top',
'top.number': 'N.º {rank}',
'top.pickFirst': 'Elige tu n.º 1.',
'top.editLabel': 'Editar el Top 5',
'top.freeSlot': 'Hueco libre — elige un título abajo',
'top.addFromLibrary': 'Añadir desde mi biblioteca',
'top.allTypes': 'Todos los tipos',
'top.searchTitle': 'Buscar un título…',
'top.full': 'Tu Top 5 está completo: quita un título para añadir otro.',
'top.noCandidates': 'Ningún título. Prueba «Todos los tipos» u otra búsqueda.',
'reco.error': 'No se pueden cargar las sugerencias por ahora.',
'reco.title': 'Sugerencias',
'reco.needKey': 'Añade tu clave de TMDB en Ajustes para recibir sugerencias basadas en tus títulos favoritos.',
'reco.other': 'Otro título',
'reco.ifYouLiked': 'Si te gustó',
'reco.loading': 'Buscando sugerencias…',
'reco.none': 'Ya tienes todo lo que se parece a este título. Prueba «Otro título».',
'reco.added': '{title} añadido',
'reco.addLabel': 'Añadir {title} a por ver',
'reco.addedShort': 'Añadido',
'search.moviesSeries': 'Películas y series',
'search.offline': 'Sin conexión a internet: la búsqueda necesita red.',
'search.fillFrom': 'Rellenar desde una base de datos',
'search.needKey': 'Para buscar películas, series y dramas, añade tu clave gratuita de TMDB en Ajustes.',
'search.openSettings': 'Abrir Ajustes',
'search.already': 'ya añadido',
'search.noResults': 'Sin resultados. Puedes rellenar la ficha a mano abajo.',
'search.privacy': 'Solo se envía a {source} el título que buscas. Tu biblioteca se queda en tu teléfono.',
'catalog.sortRecent': 'Editados recientemente',
'catalog.sortWatched': 'Fecha de visionado',
'catalog.sortRating': 'Mejor nota',
'catalog.sortTitle': 'Título (A→Z)',
'catalog.pageTitle': 'Mi ',
'catalog.pageAccent': 'catálogo',
'catalog.journalSubtitle': 'Tu historial de visionado',
'catalog.filteredCount_one': '{count} título (filtrado)',
'catalog.filteredCount_other': '{count} títulos (filtrados)',
'catalog.titles': 'Títulos',
'catalog.journal': 'Diario',
'catalog.lists': 'Listas',
'catalog.searchPh': 'Título, género, plataforma…',
'catalog.moreFilters': 'Más filtros',
'catalog.all': 'Todos',
'catalog.genre': 'Género',
'catalog.minRating': 'Nota mínima',
'catalog.allRatings': 'Todas',
'catalog.sortBy': 'Ordenar por',
'catalog.favorites': 'Favoritos',
'catalog.reset': 'Restablecer',
'catalog.noResults': 'Sin resultados',
'catalog.nothingYet': 'Nada por ahora',
'catalog.noResultsHint': 'Prueba otra búsqueda o quita filtros.',
'catalog.nothingYetHint': 'Añade tu primer título con el botón +.',
'catalog.clearFilters': 'Borrar filtros',
'public.agree': 'Clavado a la opinión del público',
'public.more': '+{gap} más que el público',
'public.less': '−{gap} menos que el público',
'public.label': 'Público',
'public.me': 'Yo',
'public.added_one': '{count} nota del público añadida.',
'public.added_other': '{count} notas del público añadidas.',
'public.noneFound': 'No se encontraron notas nuevas.',
'public.fetch': 'Obtener ({n})',
'public.title': 'Yo vs. el público',
'public.hintFetch': 'Obtén la nota media de TMDB / AniList de tus títulos puntuados para ver en qué te diferencias del público.',
'public.hintNone': 'No hay notas públicas disponibles para tus títulos puntuados en este periodo.',
'public.hintKey': 'Añade tu clave de TMDB en Ajustes (o animes vinculados a AniList) para compararte con el público.',
'public.avgGap': 'Diferencia media',
'public.average': 'En la media',
'public.generous': 'Más generoso que el público',
'public.harsh': 'Más exigente que el público',
'public.agreeTitle': 'De acuerdo',
'public.within5_one': 'con ½ estrella de margen, en {count} título',
'public.within5_other': 'con ½ estrella de margen, en {count} títulos',
'public.within10_one': 'con 1 punto de margen, en {count} título',
'public.within10_other': 'con 1 punto de margen, en {count} títulos',
'public.lovedPre': 'Me ',
'public.lovedAccent': 'gustó más',
'public.lovedPost': ' que al público',
'public.hatedPre': 'Me ',
'public.hatedAccent': 'gustó menos',
'public.hatedPost': ' que al público',
'public.allAgree': 'Estás de acuerdo con el público en todos tus títulos. ¡Qué raro!',
'form.rewatchHint': '¿Lo volviste a ver? Anota cada revisionado y aparecerá en tu diario.',
'form.editTitle': 'Editar la ',
'form.editAccent': 'ficha',
'form.newTitle': 'Nuevo ',
'form.newAccent': 'título',
'form.filledFrom': 'Rellenado desde',
'form.canEdit': 'puedes editarlo todo',
'form.fillFromDb': 'Completar desde TMDB / AniList',
'form.pickPoster': 'Elegir un póster',
'form.removeImage': 'Quitar la imagen',
'form.title': 'Título *',
'form.titlePh': 'ej. Your Name',
'form.originalTitle': 'Título original',
'form.originalTitlePh': 'ej. 君の名は。',
'form.synopsis': 'Sinopsis',
'form.type': 'Tipo',
'form.subtype': 'Subtipo',
'form.subtypePh': 'Documental, Reality show…',
'form.status': 'Estado',
'form.myRating': 'Mi nota',
'form.favorite': 'Favorito',
'form.criteria': 'Criterios detallados (opcional)',
'form.episodes': 'Episodios',
'form.minusEp': '-1 episodio',
'form.plusEp': '+1 episodio',
'form.total': 'Total',
'form.season': 'Temporada',
'form.minPerEp': 'Min / ep.',
'form.duration': 'Duración',
'form.durationMin': 'Duración (minutos)',
'form.info': 'Información',
'form.start': 'Inicio / visto el',
'form.end': 'Fin',
'form.year': 'Año',
'form.platform': 'Plataforma',
'form.genres': 'Géneros / etiquetas',
'form.genresPh': 'Romance, Ciencia ficción…',
'form.rewatches': 'Revisionados',
'form.review': 'Mi opinión',
'form.reviewPh': 'Lo que me pareció, escenas que me marcaron…',
'form.saveChanges': 'Guardar los cambios',
'form.addToLibrary': 'Añadir a mi biblioteca',
'form.shareImage': 'Compartir como imagen',
'form.delete': 'Eliminar este título',
'form.deleteConfirm': '«{title}» se eliminará para siempre.',
'form.removeRewatch': 'Quitar este revisionado',
'form.rewatchDate': 'Fecha del revisionado',
'form.reviewPublic': 'Mostrar esta opinión en mi perfil',
'form.reviewPublicHint': 'Si no, solo la verás tú.',
'journal.rewatched': 'Vuelto a ver',
'journal.started': 'Empezado',
'journal.emptyTitle': 'Diario vacío',
'journal.emptyText': 'Lo que veas aparecerá aquí en cuanto tus fichas tengan fechas de inicio o de fin.',
'journal.seen_one': '{count} visto',
'journal.seen_other': '{count} vistos',
'journal.more': 'Mostrar los meses anteriores',
'stats.overview': 'Resumen',
'stats.habits': 'Hábitos',
'stats.tastes': 'Gustos',
'stats.pageTitle': 'Mis ',
'stats.pageAccent': 'estadísticas',
'stats.emptyTitle': 'Aún no hay estadísticas',
'stats.emptyText': 'Aparecerán en cuanto hayas añadido títulos.',
'stats.sinceStart': 'desde el principio',
'stats.subtitle_one': '{count} título en mi biblioteca',
'stats.subtitle_other': '{count} títulos en mi biblioteca',
'stats.subtitleYear_one': '{count} título en {year}',
'stats.subtitleYear_other': '{count} títulos en {year}',
'stats.hours_one': 'hora',
'stats.hours_other': 'horas',
'stats.nonStopPre': 'o sea, ',
'stats.nonStopPost': ' sin parar',
'stats.days_one': '{count} día',
'stats.days_other': '{count} días',
'stats.finishedN_one': '{count} terminado',
'stats.finishedN_other': '{count} terminados',
'stats.episodesN_one': '{count} episodio',
'stats.episodesN_other': '{count} episodios',
'stats.timeByType': 'Tiempo por tipo',
'stats.noTime': 'Aún no hay tiempo registrado en este periodo.',
'stats.avgRating': 'Nota media',
'stats.rated_one': '{count} título puntuado',
'stats.rated_other': '{count} títulos puntuados',
'stats.inYear': 'en {year}',
'stats.statuses': 'Estados',
'stats.hoursTab': 'Horas',
'stats.monthByMonth': 'Mes a mes · {year}',
'stats.last12': 'Últimos 12 meses',
'stats.monthFinished_one': '{count} título terminado',
'stats.monthFinished_other': '{count} títulos terminados',
'stats.busiest': 'Mes más intenso:',
'stats.records': 'Récords',
'stats.marathon': 'Mayor maratón',
'stats.longestFilm': 'Película más larga',
'stats.noRecords': 'Aún no hay récords en este periodo.',
'stats.platforms': 'Plataformas',
'stats.bestRated': 'Mis mejor puntuados',
'stats.myRatings': 'Mis notas',
'stats.noRatings': 'No hay notas en este periodo.',
'stats.favGenres': 'Géneros favoritos',
'stats.noGenres': 'Aún no hay géneros.',
'stats.countries': 'Países',
'stats.noCountry_one': '{count} título sin país: complétalo con «Completar desde TMDB / AniList» en la ficha.',
'stats.noCountry_other': '{count} títulos sin país: complétalos con «Completar desde TMDB / AniList» en la ficha.',
'stats.noCountryLegacy_one': '{count} título sin país: complétalo con «Completar desde TMDB / AniList» en la ficha, o vuelve a importar la copia de seguridad de tu app antigua («Combinar»).',
'stats.noCountryLegacy_other': '{count} títulos sin país: complétalos con «Completar desde TMDB / AniList» en la ficha, o vuelve a importar la copia de seguridad de tu app antigua («Combinar»).',
'stats.byType': 'Por tipo',
'stats.footnote': 'Tiempo estimado a partir de los episodios vistos y las duraciones indicadas (si no: película 1 h 50, episodio de anime 24 min, serie 45 min, K-drama 1 h, C-drama 45 min). Un título cuenta para el año en que lo terminé.',
'stats.ratedAs_one': 'puntuado {rating}',
'stats.ratedAs_other': 'puntuados {rating}',
'backup.shareTitle': 'Copia de seguridad de AzuuCine',
'backup.tooBig': 'Archivo demasiado grande (30 MB como máximo).',
'backup.notJson': 'Este archivo no es un JSON válido.',
'backup.noItems': 'No se encontró ninguna ficha en este archivo.',
'backup.tooMany': 'Demasiadas fichas ({n} como máximo).',
'image.canvas': 'Canvas no disponible',
'image.unreadable': 'Imagen ilegible',
'image.notImage': 'Este archivo no es una imagen.',
'image.tooBig': 'Imagen demasiado pesada (25 MB como máximo).',
'social.err.server': 'El servidor respondió {status}.',
'social.err.usernameTaken': 'Ese nombre de usuario ya está en uso.',
'social.err.usernameReserved': 'Ese nombre de usuario no está disponible.',
'social.err.invalid': 'Uno de los valores no es válido.',
'social.inLibrary': 'En mi biblioteca',
'social.addToWatch': 'Añadir a Por ver',
'social.linkCopied': '¡Enlace copiado!',
'social.profile': 'Perfil',
'social.shareProfile': 'Compartir perfil',
'social.loading': 'Cargando…',
'social.loadError': 'No se pudo cargar el perfil.',
'social.notFound': 'Perfil no encontrado',
'social.notFoundHint': 'Ningún perfil se llama @{username}.',
'social.editProfile': 'Editar perfil',
'social.following': 'Siguiendo',
'social.requested': 'Solicitud enviada',
'social.followBack': 'Seguir también',
'social.follow': 'Seguir',
'social.private': 'Cuenta privada',
'social.followsYou': 'Te sigue',
'social.seen': 'Vistos',
'social.followers_one': 'Seguidor',
'social.followers_other': 'Seguidores',
'social.followingCount_one': 'Siguiendo',
'social.followingCount_other': 'Siguiendo',
'social.requests_one': '{count} solicitud de seguimiento',
'social.requests_other': '{count} solicitudes de seguimiento',
'social.privateTitle': 'Esta cuenta es privada',
'social.privateText': 'Síguela para ver lo que ve, sus notas y su Top 5.',
'social.tabProfile': 'Perfil',
'social.tabLibrary': 'Biblioteca',
'social.cancelRequestTitle': '¿Cancelar la solicitud de seguimiento?',
'social.unfollowTitle': '¿Dejar de seguir a {name}?',
'social.unfollowPrivate': 'Esta cuenta es privada: tendrás que volver a enviar una solicitud para ver su perfil.',
'social.cancelRequest': 'Cancelar solicitud',
'social.unfollow': 'Dejar de seguir',
'social.top5': 'Top 5',
'social.recent': 'Vistos recientemente',
'social.noRecent': 'Nada terminado por ahora.',
'social.statYear': 'Vistos este año',
'social.statFilms': 'Películas vistas',
'social.statSeries': 'Series y animes vistos',
'social.emptyLibrary': 'No hay ningún título aquí.',
'social.loadMore': 'Ver más',
'social.changeBanner': 'Cambiar el banner',
'social.changeAvatar': 'Cambiar la foto',
'social.removeAvatar': 'Quitar la foto',
'social.removeBanner': 'Quitar el banner',
'social.displayName': 'Nombre visible',
'social.username': 'Nombre de usuario',
'social.usernameRule': 'De 3 a 20 caracteres: letras minúsculas, números o _',
'social.bio': 'Bio',
'social.bioPh': 'Lo que te gusta ver, tus géneros favoritos…',
'social.privateAccount': 'Cuenta privada',
'social.privateHint': 'Solo los seguidores que aceptes ven lo que ves.',
'social.publicHint': 'Tu nombre, tu nombre de usuario, tu foto, tu banner y tu bio son visibles para todos los miembros. Tus opiniones escritas siguen siendo privadas, salvo las que decidas mostrar en tu perfil.',
'social.requestsTab_one': 'Solicitud',
'social.requestsTab_other': 'Solicitudes ({count})',
'social.noFollowing': 'Todavía no sigues a nadie.',
'social.noFollowers': 'Todavía no tienes seguidores.',
'social.accept': 'Aceptar',
'social.decline': 'Rechazar',
'social.removeFollower': 'Eliminar',
'social.findFriends': 'Buscar amigos',
'social.searchPh': 'Usuario o nombre…',
'social.noResults': 'No hay nadie que coincida.',
'social.inviteHint': '¿Tus amigos aún no están en AzuuCine? Envíales el enlace de tu perfil.',
'social.shareMyProfile': 'Compartir mi perfil',
'social.inviteText': '¡Sígueme en AzuuCine!',
'social.myProfile': 'Mi perfil',
'feed.title': 'A quién sigo',
'feed.empty': 'Sigue a tus amigos para ver aquí lo que ven y lo que opinan.',
'feed.finished': 'vio',
'feed.started': 'empezó',
'feed.rewatched': 'volvió a ver',
'feed.added': 'quiere ver',
'feed.review': 'opinión',
}
export default dict
+752
View File
@@ -0,0 +1,752 @@
/**
* Français — langue de référence : toutes les clés sont définies ici.
* « {x} » = variable ; « _one » / « _other » = formes du pluriel (choisies selon le nombre « count »).
*/
const dict = {
'common.cancel': 'Annuler',
'common.confirm': 'Confirmer',
'common.close': 'Fermer',
'common.save': 'Enregistrer',
'common.add': 'Ajouter',
'common.delete': 'Supprimer',
'common.all': 'Tout',
'common.none': 'Aucun',
'common.noData': 'Pas encore de données.',
'common.retry': 'Réessayer',
'common.back': 'Retour',
'common.offline': 'Pas de connexion internet.',
'common.minutes': '{n} min',
'common.hours': '{h} h',
'common.hoursMinutes': '{h} h {m}',
'common.daysHours': '{d} j {h} h',
'common.decimalSep': ',',
'common.removeX': 'Retirer {name}',
'common.kb': '{n} Ko',
'common.mb': '{n} Mo',
'common.edit': 'Modifier',
'common.moveUp': 'Monter',
'common.moveDown': 'Descendre',
'nav.home': 'Accueil',
'nav.catalog': 'Catalogue',
'nav.stats': 'Stats',
'nav.settings': 'Réglages',
'nav.addTitle': 'Ajouter un titre',
'type.film': 'Film',
'type.serie': 'Série',
'type.anime': 'Anime',
'type.kdrama': 'K-Drama',
'type.cdrama': 'C-Drama',
'type.autre': 'Autre',
'typePlural.film': 'Films',
'typePlural.serie': 'Séries',
'typePlural.anime': 'Animes',
'typePlural.kdrama': 'K-Dramas',
'typePlural.cdrama': 'C-Dramas',
'status.a_voir': 'À voir',
'status.en_cours': 'En cours',
'status.termine': 'Terminé',
'status.pause': 'En pause',
'status.abandonne': 'Abandonné',
'criteria.story': 'Scénario / Histoire',
'criteria.cast': 'Personnages / Casting',
'criteria.direction': 'Réalisation / Animation',
'criteria.ost': 'Bande originale (OST)',
'subtype.documentary': 'Documentaire',
'subtype.reality': 'Télé-réalité',
'subtype.show': 'Émission',
'subtype.short': 'Court-métrage',
'subtype.stage': 'Spectacle',
'subtype.miniseries': 'Mini-série',
'platform.cinema': 'Cinéma',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'TV',
'genre.action': 'Action',
'genre.adventure': 'Aventure',
'genre.comedy': 'Comédie',
'genre.drama': 'Drame',
'genre.romance': 'Romance',
'genre.romcom': 'Rom-com',
'genre.thriller': 'Thriller',
'genre.horror': 'Horreur',
'genre.mystery': 'Mystère',
'genre.crime': 'Policier',
'genre.scifi': 'Sci-Fi',
'genre.fantasy': 'Fantasy',
'genre.historical': 'Historique',
'genre.sliceOfLife': 'Slice of Life',
'genre.shonen': 'Shōnen',
'genre.shojo': 'Shōjo',
'genre.seinen': 'Seinen',
'genre.isekai': 'Isekai',
'genre.mecha': 'Mecha',
'genre.sports': 'Sport',
'genre.musical': 'Musical',
'genre.medical': 'Médical',
'genre.legal': 'Juridique',
'genre.wuxia': 'Wuxia',
'genre.xianxia': 'Xianxia',
'genre.family': 'Famille',
'genre.animation': 'Animation',
'genre.psychological': 'Psychologique',
'genre.supernatural': 'Surnaturel',
'genre.romanticComedy': 'Comédie romantique',
'genre.documentary': 'Documentaire',
'genre.war': 'Guerre',
'genre.western': 'Western',
'genre.music': 'Musique',
'genre.ecchi': 'Ecchi',
'genre.kids': 'Enfants',
'genre.news': 'Actualités',
'genre.reality': 'Télé-réalité',
'genre.talk': 'Talk-show',
'genre.soap': 'Feuilleton',
'genre.politics': 'Politique',
'genre.tvMovie': 'Téléfilm',
'genre.anime': 'Anime',
'genre.magicalGirl': 'Magical Girl',
'confirm.title': 'Êtes-vous sûr ?',
'err.tmdbRefused': 'Requête TMDB refusée.',
'err.tmdbKeyRefused': 'Clé TMDB refusée. Vérifie-la dans Réglages.',
'err.tmdbStatus': 'TMDB a répondu {status}.',
'err.tmdbRef': 'Référence TMDB invalide.',
'err.anilistRate': 'AniList limite les requêtes, réessaie dans une minute.',
'err.anilistStatus': 'AniList a répondu {status}.',
'err.searchRate': 'Trop de recherches, réessaie dans quelques minutes.',
'anilist.short': 'Anime court',
'anilist.movie': 'Film d’animation',
'anilist.special': 'Spécial',
'anilist.music': 'Clip',
'release.cinema': 'Au cinéma',
'release.online': 'En VOD / streaming',
'release.release': 'Sortie',
'release.season': 'Saison {season}',
'release.episode': 'Épisode {ep}',
'release.newEpisode': 'Nouvel épisode',
'release.firstEpisode': 'Premier épisode',
'release.newSeriesN': 'Nouvelle série · {count} épisodes',
'release.seasonN': 'Saison {season} · {count} épisodes',
'release.seasonEp1': 'Saison {season} · Épisode 1',
'release.episodes': 'Épisodes {first}–{last}',
'release.sEpisodes': 'S{season} · Épisodes {first}–{last}',
'release.sEpisode': 'S{season} · Épisode {ep}',
'release.episodeFinal': 'Épisode {ep} · final',
'release.filmJapan': 'Film au Japon',
'card.ep': 'Ép. {n}',
'card.plusOne': '+1 épisode pour {title}',
'card.open': 'Ouvrir {title}',
'rating.outOf10': 'Note sur 10',
'rating.stars_one': '{count} étoile',
'rating.stars_other': '{count} étoiles',
'rating.clear': 'Effacer la note',
'share.previewLabel': 'Aperçu de l\'image',
'share.preview': 'Aperçu',
'share.posterAlt': 'Affiche {title}',
'share.share': 'Partager',
'share.saveImage': 'Enregistrer l\'image',
'share.err.create': 'Image impossible à créer',
'share.minutesLong': '{n} minutes',
'share.createdBy': 'Créé par',
'share.directedBy': 'Réalisé par',
'share.producedBy': 'Produit par',
'share.starring': 'Avec',
'share.genres': 'Genres',
'share.myRating': 'Ma note',
'share.myTop': 'Mon Top',
'auth.hidePassword': 'Masquer le mot de passe',
'auth.showPassword': 'Afficher le mot de passe',
'auth.mismatch': 'Les deux mots de passe ne sont pas identiques.',
'auth.created': 'Compte créé ! Ouvre le lien envoyé à {email} pour l\'activer, puis connecte-toi.',
'auth.resetSent': 'Si un compte existe avec cette adresse, un lien pour choisir un nouveau mot de passe vient d’être envoyé.',
'auth.tagline': 'Ton journal de films, séries, animes et dramas.',
'auth.loginTab': 'Connexion',
'auth.signupTab': 'Créer un compte',
'auth.forgotTitle': 'Mot de passe oublié',
'auth.email': 'Adresse email',
'auth.password': 'Mot de passe',
'auth.confirmPassword': 'Confirme le mot de passe',
'auth.minChars': 'Au moins {n} caractères.',
'auth.login': 'Se connecter',
'auth.signup': 'Créer mon compte',
'auth.sendLink': 'Envoyer le lien',
'auth.forgot': 'Mot de passe oublié ?',
'auth.backToLogin': 'Retour à la connexion',
'auth.privacy': 'Tes données sont liées à ton compte et visibles uniquement par toi. Elles restent aussi sur ton appareil pour fonctionner sans internet.',
'auth.newPasswordTitle': 'Choisis ton nouveau mot de passe.',
'auth.newPassword': 'Nouveau mot de passe',
'auth.err.credentials': 'Email ou mot de passe incorrect.',
'auth.err.notConfirmed': 'Confirme d\'abord ton adresse avec le lien reçu par email.',
'auth.err.exists': 'Un compte existe déjà avec cet email.',
'auth.err.weak': 'Mot de passe trop faible (au moins {n} caractères, mélange lettres et chiffres).',
'auth.err.samePassword': 'Le nouveau mot de passe doit être différent de l\'ancien.',
'auth.err.emailRate': 'Trop de demandes. Réessaie dans quelques minutes.',
'auth.err.rate': 'Trop de tentatives. Réessaie dans quelques minutes.',
'auth.err.signupDisabled': 'Les inscriptions sont fermées pour le moment.',
'auth.err.emailInvalid': 'Adresse email invalide.',
'auth.err.invalid': 'Adresse email ou mot de passe invalide.',
'auth.err.session': 'Session expirée, reconnecte-toi.',
'auth.err.status': 'Le serveur a refusé la demande ({status}).',
'auth.err.response': 'Réponse du serveur invalide.',
'auth.err.linkExpired': 'Ce lien a expiré. Demande-en un nouveau.',
'auth.err.linkUsed': 'Ce lien est invalide ou a déjà été utilisé.',
'auth.err.linkInvalid': 'Ce lien est invalide.',
'settings.language': 'Langue',
'settings.backupShared': 'Sauvegarde partagée.',
'settings.backupDownloaded': 'Sauvegarde téléchargée.',
'settings.exportFailed': 'L\'export a échoué.',
'settings.noValidItems': 'Le fichier ne contient aucune fiche valide.',
'settings.imported_one': '{count} fiche importée.',
'settings.imported_other': '{count} fiches importées.',
'settings.importedSkipped': '{n} fiche(s) importée(s), {skipped} ignorée(s).',
'settings.cleared': 'Bibliothèque effacée.',
'settings.pageTitle': 'Mes ',
'settings.pageAccent': 'réglages',
'settings.languageHint': 'Langue de l\'app, des dates et des infos récupérées sur TMDB (titres, résumés).',
'settings.rating': 'Notation',
'settings.scale5': '★ sur 5',
'settings.scale10': 'Sur 10',
'settings.ratingHint': 'Demi-étoiles sur 5, ou pas de 0,5 sur 10. Les notes existantes sont converties automatiquement.',
'settings.theme': 'Thème',
'settings.themeX': 'Thème {name}',
'settings.pickColor': 'Choisir une couleur libre',
'settings.freeColor': 'Couleur libre',
'settings.freeColorHint': 'N\'importe quelle couleur : le texte s\'adapte pour rester lisible.',
'settings.databases': 'Bases de films',
'settings.anilistActive': 'Animes · actif',
'settings.noConfig': 'Aucune configuration nécessaire.',
'settings.tmdbActive': 'Films & séries · actif',
'settings.checking': 'Vérification…',
'settings.offline': 'Hors-ligne',
'settings.proxyMissingKey': 'Clé TMDB manquante',
'settings.proxyNotDeployed': 'Serveur non installé',
'settings.unavailable': 'Indisponible',
'settings.proxyMissingKeyHint': 'La fonction serveur est en place mais ta clé TMDB n\'est pas enregistrée (secret TMDB_API_KEY dans Supabase), ou elle est refusée par TMDB.',
'settings.proxyNotDeployedHint': 'La fonction « tmdb » n\'est pas encore déployée sur Supabase (voir README → Comptes, étape 5).',
'settings.proxyErrorHint': 'Le serveur ne répond pas correctement pour le moment.',
'settings.proxyOkHint': 'Fourni par le serveur de l\'app : aucune clé à saisir.',
'settings.recheck': 'Revérifier',
'settings.keyRefused': 'Clé refusée',
'settings.notConfigured': 'Non configuré',
'settings.tmdbHelp': 'Films, séries, K-dramas, C-dramas. Crée un compte gratuit sur themoviedb.org, puis Paramètres → API, et colle ta « Clé d\'API » ou ton « Jeton d\'accès en lecture ».',
'settings.tmdbKey': 'Clé TMDB',
'settings.hideKey': 'Masquer la clé',
'settings.showKey': 'Afficher la clé',
'settings.validate': 'Valider',
'settings.remove': 'Retirer',
'settings.keyLocal': 'La clé reste sur cet appareil et n\'est jamais incluse dans les sauvegardes.',
'settings.topHint': 'Catégories affichées sur l\'accueil.',
'settings.topNone': 'Aucune catégorie : la section Top 5 est masquée.',
'settings.backup': 'Sauvegarde',
'settings.export': 'Exporter mes données',
'settings.exportHint_one': '{count} fiche · fichier JSON, à faire régulièrement',
'settings.exportHint_other': '{count} fiches · fichier JSON, à faire régulièrement',
'settings.import': 'Importer une sauvegarde',
'settings.importHint': 'Restaurer depuis un fichier .json',
'settings.legacyDetected': 'Sauvegarde de l\'ancienne appli reconnue',
'settings.found_one': '{count} fiche trouvée. Comment l\'importer ?',
'settings.found_other': '{count} fiches trouvées. Comment les importer ?',
'settings.foundSkipped': '{n} fiche(s) trouvée(s) ({skipped} invalide(s) ignorée(s)). Comment les importer ?',
'settings.merge': 'Fusionner',
'settings.replaceAll': 'Tout remplacer',
'settings.mergeHint': '« Fusionner » ajoute les fiches et met à jour celles qui existent déjà (même identifiant).',
'settings.storage': 'Stockage',
'settings.used': 'Espace utilisé',
'settings.storageCloud': 'Tes données sont enregistrées dans ton compte et gardées aussi sur cet appareil pour fonctionner sans internet. Elles se synchronisent automatiquement dès que tu as du réseau.',
'settings.storageLocal': 'Tes données sont stockées uniquement dans ce navigateur, sur cet appareil. Si tu effaces les données du navigateur ou désinstalles l\'app, elles disparaissent : exporte une sauvegarde régulièrement.',
'settings.danger': 'Zone sensible',
'settings.clearAll': 'Effacer toute la bibliothèque',
'settings.clearAllHint_one': '{count} titre',
'settings.clearAllHint_other': '{count} titres',
'settings.clearAllHintCloud_one': '{count} titre · sur tous tes appareils',
'settings.clearAllHintCloud_other': '{count} titres · sur tous tes appareils',
'settings.deleting': 'Suppression…',
'settings.deleteAccount': 'Supprimer mon compte',
'settings.deleteAccountHint': 'Compte et données effacés définitivement',
'settings.footerCloud': 'compte synchronisé',
'settings.footerLocal': '100 % local',
'settings.clearConfirm_one': '{count} titre sera effacé définitivement. Pense à exporter une sauvegarde avant.',
'settings.clearConfirm_other': 'Tes {count} titres seront effacés définitivement. Pense à exporter une sauvegarde avant.',
'settings.clearConfirmCloud_one': '{count} titre sera effacé définitivement, sur tous tes appareils. Pense à exporter une sauvegarde avant.',
'settings.clearConfirmCloud_other': 'Tes {count} titres seront effacés définitivement, sur tous tes appareils. Pense à exporter une sauvegarde avant.',
'settings.clearAllConfirm': 'Tout effacer',
'settings.deleteAccountTitle': 'Supprimer ton compte ?',
'settings.deleteAccountMessage': 'Ton compte et toutes tes données (titres, listes, réglages) seront effacés définitivement du serveur et de cet appareil. Pense à exporter une sauvegarde avant. Cette action est irréversible.',
'settings.deleteForever': 'Supprimer définitivement',
'settings.replaceConfirm': 'Toute ta bibliothèque actuelle sera remplacée par le contenu de ce fichier.',
'settings.replace': 'Remplacer',
'sync.err.push': 'Envoi refusé ({status})',
'sync.err.pull': 'Lecture refusée ({status})',
'store.dbError': 'Impossible d\'ouvrir la base locale : {error}',
'store.invalidItem': 'Fiche invalide',
'lists.newList': 'Nouvelle liste',
'lists.newListPh': 'Nouvelle liste…',
'lists.myLists': 'Mes listes',
'lists.rename': 'Renommer',
'lists.delete': 'Supprimer la liste',
'lists.done': 'Terminé',
'lists.addRemove': 'Ajouter / retirer des titres',
'lists.searchLibrary': 'Chercher dans ma bibliothèque…',
'lists.emptyTitle': 'Liste vide',
'lists.emptyText': 'Ajoute des titres avec le bouton ci-dessus, ou depuis la fiche d\'un titre.',
'lists.deleteConfirm': 'La liste « {name} » sera supprimée. Les titres restent dans ta bibliothèque.',
'lists.noneTitle': 'Aucune liste pour l\'instant',
'lists.noneText': 'Crée des listes à ta façon : « À voir avec des potes », « Films d\'horreur d\'octobre », « Dramas réconfortants »…',
'lists.create': 'Créer',
'account.err.deleteRate': 'Trop de tentatives, réessaie dans une minute.',
'account.err.delete': 'La suppression a échoué. Réessaie plus tard.',
'account.title': 'Mon compte',
'account.syncing': 'Synchronisation…',
'account.offline': 'Hors-ligne — tout est gardé sur cet appareil',
'account.syncError': 'Synchronisation impossible pour le moment',
'account.synced': 'Synchronisé {when}',
'account.passwordChanged': 'Mot de passe modifié.',
'account.imported_one': '{count} titre ajouté à ton compte.',
'account.imported_other': '{count} titres ajoutés à ton compte.',
'account.importFailed': 'L\'import a échoué.',
'account.pending_one': '{count} en attente',
'account.pending_other': '{count} en attente',
'account.syncNow': 'Synchroniser maintenant',
'account.newPasswordPh': 'Nouveau mot de passe ({n} caractères min.)',
'account.changePassword': 'Changer le mot de passe',
'account.logout': 'Se déconnecter',
'account.logoutHint': 'Tes données restent dans ton compte et sont retirées de cet appareil.',
'account.ignore': 'Ignorer',
'account.deviceHint': 'Ils seront déplacés dans ton compte et synchronisés sur tous tes appareils.',
'account.unsentTitle': 'Modifications non envoyées',
'account.logoutAnyway': 'Se déconnecter quand même',
'account.unsentMessage_one': '{count} modification n\'a pas encore été envoyée (pas de connexion ?). Si tu te déconnectes maintenant, elle sera perdue.',
'account.unsentMessage_other': '{count} modifications n\'ont pas encore été envoyées (pas de connexion ?). Si tu te déconnectes maintenant, elles seront perdues.',
'account.nTitles_one': '{count} titre',
'account.nTitles_other': '{count} titres',
'account.nLists_one': '{count} liste',
'account.nLists_other': '{count} listes',
'account.deviceData': 'Cet appareil contient {titles} créés avant ton compte. Les ajouter à ton compte ?',
'account.deviceDataWithLists': 'Cet appareil contient {titles} et {lists} créés avant ton compte. Les ajouter à ton compte ?',
'time.never': 'jamais',
'time.justNow': 'à l\'instant',
'time.minutesAgo': 'il y a {n} min',
'time.hoursAgo': 'il y a {n} h',
'time.onDate': 'le {date}',
'time.today': 'aujourd\'hui',
'time.tomorrow': 'demain',
'time.daysAgo': 'il y a {n} j',
'theme.red': 'Rouge',
'theme.orange': 'Orange',
'theme.yellow': 'Jaune',
'theme.lime': 'Citron',
'theme.green': 'Vert',
'theme.mint': 'Menthe',
'theme.cyan': 'Cyan',
'theme.blue': 'Bleu',
'theme.indigo': 'Indigo',
'theme.violet': 'Violet',
'theme.pink': 'Rose',
'theme.white': 'Blanc',
'home.seeAll': 'Tout voir',
'home.subtitle': 'Mon journal de visionnage',
'home.calendarSoon_one': 'Calendrier des sorties : {count} cette semaine',
'home.calendarSoon_other': 'Calendrier des sorties : {count} cette semaine',
'home.emptyTitle': 'Ta bibliothèque est vide',
'home.emptyCloud': 'Ajoute ton premier film, anime ou drama. Il sera enregistré dans ton compte.',
'home.emptyLocal': 'Ajoute ton premier film, anime ou drama. Tout reste stocké uniquement sur ce téléphone.',
'home.completed': 'Terminés',
'home.thisYear_one': '{count} cette année',
'home.thisYear_other': '{count} cette année',
'home.toWatchN_one': '{count} à voir',
'home.toWatchN_other': '{count} à voir',
'home.screenTime': 'Temps devant l\'écran',
'home.estimate': 'estimation',
'home.episodesSeen': 'Épisodes vus',
'home.noIdea': 'Pas d\'idée ?',
'home.rouletteHint_one': 'Tirage au sort parmi ton titre à voir',
'home.rouletteHint_other': 'Tirage au sort parmi tes {count} titres à voir',
'home.rouletteHintAll': 'Tirage au sort dans ta bibliothèque',
'home.recentlyFinished': 'Récemment terminés',
'calendar.title': 'Calendrier des sorties',
'calendar.inMyList': 'Dans ma liste',
'calendar.inMyListLegend': 'Dans ma liste',
'calendar.seeMore_one': 'Voir l\'autre',
'calendar.seeMore_other': 'Voir les {count} autres',
'calendar.heading': 'Calendrier des ',
'calendar.headingAccent': 'sorties',
'calendar.refresh': 'Actualiser',
'calendar.all': 'Toutes les sorties',
'calendar.mine': 'Mes titres',
'calendar.prevMonth': 'Mois précédent',
'calendar.nextMonth': 'Mois suivant',
'calendar.releases_one': '{count} sortie',
'calendar.releases_other': '{count} sorties',
'calendar.others': 'Autres sorties',
'calendar.needKey': 'Sans clé TMDB, seuls les animes sont affichés. Ajoute ta clé dans les Réglages pour voir aussi les films, séries et dramas.',
'calendar.range': 'Les sorties sont disponibles du mois dernier jusqu\'à 6 mois à l\'avance.',
'calendar.failed': 'Certaines sorties n\'ont pas pu être chargées. Réessaie avec ↻.',
'calendar.nothingThatDay': 'Rien de prévu ce jour-là.',
'calendar.next14': 'Les 14 prochains jours',
'calendar.loading': 'Recherche des sorties…',
'calendar.noneMine14': 'Aucune sortie annoncée dans les 14 prochains jours pour tes titres.',
'calendar.noneMineMonth': 'Aucune sortie annoncée ce mois-ci pour tes titres.',
'calendar.none14': 'Aucune sortie dans les 14 prochains jours.',
'calendar.noneMonth': 'Aucune sortie trouvée pour ce mois.',
'calendar.footer': 'Films au cinéma dans ton pays, épisodes des séries et dramas les plus suivis (TMDB) et de tous les animes diffusés au Japon (AniList). Les titres de ta bibliothèque sont mis en couleur ; appuie sur « À voir » pour ajouter une sortie à ta liste.',
'roulette.name': 'Roulette',
'roulette.rewatch': 'À revoir',
'roulette.anyTime': 'Peu importe',
'roulette.heading': 'La ',
'roulette.headingAccent': 'roulette',
'roulette.tonight': 'Ce soir, ce sera…',
'roulette.nEps': '{n} ép.',
'roulette.perEp': '{duration} / ép.',
'roulette.stoppedAt': 'Tu t\'étais arrêté à l\'épisode {ep}.',
'roulette.stoppedAtOf': 'Tu t\'étais arrêté à l\'épisode {ep} sur {total}.',
'roulette.enjoy': 'Bon visionnage !',
'roulette.again': 'Relancer',
'roulette.spinning': 'Ça tourne…',
'roulette.spin': 'Lancer la roulette',
'roulette.poolSize_one': 'Tirage parmi {count} titre',
'roulette.poolSize_other': 'Tirage parmi {count} titres',
'roulette.empty': 'Aucun titre ne correspond : élargis les filtres ci-dessous.',
'roulette.inside': 'Dans la roulette',
'roulette.pickFrom': 'Piocher dans',
'roulette.rewatchHint': '« À revoir » = tes titres terminés notés 4/5 et plus, coups de cœur et Top 5.',
'roulette.time': 'Temps disponible (film ou 1 épisode)',
'roulette.seeItem': 'Voir la fiche complète',
'roulette.watchIt': 'Je le regarde',
'newEp.check': 'Vérifier',
'newEp.title': 'Nouveautés',
'newEp.checking': 'Je regarde ce qui est sorti…',
'newEp.needKey': 'Ajoute ta clé TMDB dans les Réglages pour être prévenu des nouveaux épisodes et des nouvelles saisons.',
'newEp.nothing_one': 'Rien de neuf pour ta série ou ton anime suivi.',
'newEp.nothing_other': 'Rien de neuf pour tes {count} séries et animes suivis.',
'newEp.needKeyAlso': '(Ajoute ta clé TMDB dans les Réglages pour suivre aussi les séries et dramas.)',
'newEp.newSeason': 'Nouvelle saison',
'newEp.catchUp': 'À rattraper',
'newEp.soon': 'Bientôt',
'newEp.epWhen': 'Ép. {ep} {when}',
'newEp.available_one': '{count} épisode dispo',
'newEp.available_other': '{count} épisodes dispos',
'newEp.next': 'Prochain : ép. {ep} {when}',
'newEp.resume': 'Reprendre',
'top.pick': 'Choisir le n°{rank}',
'top.shareTitle': 'Mon Top 5 {category}',
'top.shareLabel': 'Partager ce Top 5 en image',
'top.title': 'Mes Top',
'top.number': 'N°{rank}',
'top.pickFirst': 'Choisis ton n°1.',
'top.editLabel': 'Modifier le Top 5',
'top.freeSlot': 'Place libre — choisis un titre ci-dessous',
'top.addFromLibrary': 'Ajouter depuis ma bibliothèque',
'top.allTypes': 'Tous les types',
'top.searchTitle': 'Chercher un titre…',
'top.full': 'Ton Top 5 est complet : retire un titre pour en ajouter un autre.',
'top.noCandidates': 'Aucun titre. Essaie « Tous les types » ou une autre recherche.',
'reco.error': 'Impossible de charger les suggestions pour le moment.',
'reco.title': 'Suggestions',
'reco.needKey': 'Ajoute ta clé TMDB dans les Réglages pour recevoir des suggestions basées sur tes titres préférés.',
'reco.other': 'Autre titre',
'reco.ifYouLiked': 'Si tu as aimé',
'reco.loading': 'Recherche de suggestions…',
'reco.none': 'Tu as déjà tout ce qui ressemble à ce titre. Essaie « Autre titre ».',
'reco.added': '{title} ajouté',
'reco.addLabel': 'Ajouter {title} à voir',
'reco.addedShort': 'Ajouté',
'search.moviesSeries': 'Films & séries',
'search.offline': 'Pas de connexion Internet : la recherche nécessite le réseau.',
'search.fillFrom': 'Remplir depuis une base',
'search.needKey': 'Pour chercher films, séries et dramas, ajoute ta clé TMDB gratuite dans les Réglages.',
'search.openSettings': 'Ouvrir les Réglages',
'search.already': 'déjà ajouté',
'search.noResults': 'Aucun résultat. Tu peux remplir la fiche à la main ci-dessous.',
'search.privacy': 'Seul le titre recherché est envoyé à {source}. Ta bibliothèque reste sur ton téléphone.',
'catalog.sortRecent': 'Modifiés récemment',
'catalog.sortWatched': 'Date de visionnage',
'catalog.sortRating': 'Meilleure note',
'catalog.sortTitle': 'Titre (A→Z)',
'catalog.pageTitle': 'Mon ',
'catalog.pageAccent': 'catalogue',
'catalog.journalSubtitle': 'Ton historique de visionnage',
'catalog.filteredCount_one': '{count} titre (filtré)',
'catalog.filteredCount_other': '{count} titres (filtrés)',
'catalog.titles': 'Titres',
'catalog.journal': 'Journal',
'catalog.lists': 'Listes',
'catalog.searchPh': 'Titre, genre, plateforme…',
'catalog.moreFilters': 'Plus de filtres',
'catalog.all': 'Tous',
'catalog.genre': 'Genre',
'catalog.minRating': 'Note minimale',
'catalog.allRatings': 'Toutes',
'catalog.sortBy': 'Trier par',
'catalog.favorites': 'Coups de cœur',
'catalog.reset': 'Réinitialiser',
'catalog.noResults': 'Aucun résultat',
'catalog.nothingYet': 'Rien pour le moment',
'catalog.noResultsHint': 'Essaie une autre recherche ou retire des filtres.',
'catalog.nothingYetHint': 'Ajoute ton premier titre avec le bouton +.',
'catalog.clearFilters': 'Effacer les filtres',
'public.agree': 'Pile dans l\'avis du public',
'public.more': '+{gap} de plus que le public',
'public.less': '−{gap} de moins que le public',
'public.label': 'Public',
'public.me': 'Moi',
'public.added_one': '{count} note du public ajoutée.',
'public.added_other': '{count} notes du public ajoutées.',
'public.noneFound': 'Aucune nouvelle note trouvée.',
'public.fetch': 'Récupérer ({n})',
'public.title': 'Moi vs le public',
'public.hintFetch': 'Récupère la note moyenne TMDB / AniList de tes titres notés pour voir où tu te démarques du public.',
'public.hintNone': 'Aucune note publique disponible pour tes titres notés sur cette période.',
'public.hintKey': 'Ajoute ta clé TMDB dans les Réglages (ou des animes liés à AniList) pour te comparer au public.',
'public.avgGap': 'Écart moyen',
'public.average': 'Dans la moyenne',
'public.generous': 'Plus généreux que le public',
'public.harsh': 'Plus sévère que le public',
'public.agreeTitle': 'D\'accord',
'public.within5_one': 'à ½ étoile près, sur {count} titre',
'public.within5_other': 'à ½ étoile près, sur {count} titres',
'public.within10_one': 'à 1 point près, sur {count} titre',
'public.within10_other': 'à 1 point près, sur {count} titres',
'public.lovedPre': 'J\'ai ',
'public.lovedAccent': 'plus aimé',
'public.lovedPost': ' que le public',
'public.hatedPre': 'J\'ai ',
'public.hatedAccent': 'moins aimé',
'public.hatedPost': ' que le public',
'public.allAgree': 'Tu es d\'accord avec le public sur tous tes titres. Rare !',
'form.rewatchHint': 'Tu l\'as revu ? Note chaque revisionnage, il apparaîtra dans ton journal.',
'form.editTitle': 'Modifier la ',
'form.editAccent': 'fiche',
'form.newTitle': 'Nouveau ',
'form.newAccent': 'titre',
'form.filledFrom': 'Rempli depuis',
'form.canEdit': 'tu peux tout modifier',
'form.fillFromDb': 'Compléter depuis TMDB / AniList',
'form.pickPoster': 'Choisir une affiche',
'form.removeImage': 'Retirer l\'image',
'form.title': 'Titre *',
'form.titlePh': 'ex. Your Name',
'form.originalTitle': 'Titre original',
'form.originalTitlePh': 'ex. 君の名は。',
'form.synopsis': 'Synopsis',
'form.type': 'Type',
'form.subtype': 'Précision',
'form.subtypePh': 'Documentaire, Télé-réalité…',
'form.status': 'Statut',
'form.myRating': 'Ma note',
'form.favorite': 'Coup de cœur',
'form.criteria': 'Critères détaillés (optionnel)',
'form.episodes': 'Épisodes',
'form.minusEp': '-1 épisode',
'form.plusEp': '+1 épisode',
'form.total': 'Total',
'form.season': 'Saison',
'form.minPerEp': 'Min / ép.',
'form.duration': 'Durée',
'form.durationMin': 'Durée (minutes)',
'form.info': 'Informations',
'form.start': 'Début / vu le',
'form.end': 'Fin',
'form.year': 'Année',
'form.platform': 'Plateforme',
'form.genres': 'Genres / tags',
'form.genresPh': 'Romance, Sci-Fi…',
'form.rewatches': 'Revisionnages',
'form.review': 'Mon avis',
'form.reviewPh': 'Ce que j\'en ai pensé, scènes marquantes…',
'form.saveChanges': 'Enregistrer les modifications',
'form.addToLibrary': 'Ajouter à ma bibliothèque',
'form.shareImage': 'Partager en image',
'form.delete': 'Supprimer ce titre',
'form.deleteConfirm': '« {title} » sera supprimé définitivement.',
'form.removeRewatch': 'Retirer ce revisionnage',
'form.rewatchDate': 'Date du revisionnage',
'form.reviewPublic': 'Afficher cet avis sur mon profil',
'form.reviewPublicHint': 'Sinon, il reste visible par toi seul.',
'journal.rewatched': 'Revu',
'journal.started': 'Commencé',
'journal.emptyTitle': 'Journal vide',
'journal.emptyText': 'Tes visionnages apparaîtront ici dès que tu auras des dates de début ou de fin sur tes fiches.',
'journal.seen_one': '{count} vu',
'journal.seen_other': '{count} vus',
'journal.more': 'Afficher les mois précédents',
'stats.overview': 'Vue d\'ensemble',
'stats.habits': 'Habitudes',
'stats.tastes': 'Goûts',
'stats.pageTitle': 'Mes ',
'stats.pageAccent': 'stats',
'stats.emptyTitle': 'Pas encore de statistiques',
'stats.emptyText': 'Elles apparaîtront dès que tu auras ajouté des titres.',
'stats.sinceStart': 'depuis le début',
'stats.subtitle_one': '{count} titre dans ma bibliothèque',
'stats.subtitle_other': '{count} titres dans ma bibliothèque',
'stats.subtitleYear_one': '{count} titre en {year}',
'stats.subtitleYear_other': '{count} titres en {year}',
'stats.hours_one': 'heure',
'stats.hours_other': 'heures',
'stats.nonStopPre': 'soit ',
'stats.nonStopPost': ' non-stop',
'stats.days_one': '{count} jour',
'stats.days_other': '{count} jours',
'stats.finishedN_one': '{count} terminé',
'stats.finishedN_other': '{count} terminés',
'stats.episodesN_one': '{count} épisode',
'stats.episodesN_other': '{count} épisodes',
'stats.timeByType': 'Temps par type',
'stats.noTime': 'Pas encore de temps enregistré sur cette période.',
'stats.avgRating': 'Note moyenne',
'stats.rated_one': '{count} titre noté',
'stats.rated_other': '{count} titres notés',
'stats.inYear': 'en {year}',
'stats.statuses': 'Statuts',
'stats.hoursTab': 'Heures',
'stats.monthByMonth': 'Mois par mois · {year}',
'stats.last12': '12 derniers mois',
'stats.monthFinished_one': '{count} titre terminé',
'stats.monthFinished_other': '{count} titres terminés',
'stats.busiest': 'Mois le plus chargé :',
'stats.records': 'Records',
'stats.marathon': 'Plus gros marathon',
'stats.longestFilm': 'Film le plus long',
'stats.noRecords': 'Pas encore de records sur cette période.',
'stats.platforms': 'Plateformes',
'stats.bestRated': 'Mes mieux notés',
'stats.myRatings': 'Mes notes',
'stats.noRatings': 'Aucune note sur cette période.',
'stats.favGenres': 'Genres préférés',
'stats.noGenres': 'Pas encore de genres.',
'stats.countries': 'Pays',
'stats.noCountry_one': '{count} titre sans pays : complète-le via « Compléter depuis TMDB / AniList » dans la fiche.',
'stats.noCountry_other': '{count} titres sans pays : complète-les via « Compléter depuis TMDB / AniList » dans la fiche.',
'stats.noCountryLegacy_one': '{count} titre sans pays : complète-le via « Compléter depuis TMDB / AniList » dans la fiche, ou réimporte la sauvegarde de ton ancienne appli (« Fusionner »).',
'stats.noCountryLegacy_other': '{count} titres sans pays : complète-les via « Compléter depuis TMDB / AniList » dans la fiche, ou réimporte la sauvegarde de ton ancienne appli (« Fusionner »).',
'stats.byType': 'Par type',
'stats.footnote': 'Temps estimé à partir des épisodes vus et des durées renseignées (sinon : film 1 h 50, épisode d\'anime 24 min, série 45 min, K-drama 1 h, C-drama 45 min). Un titre compte pour l\'année où je l\'ai terminé.',
'stats.ratedAs_one': 'noté {rating}',
'stats.ratedAs_other': 'notés {rating}',
'backup.shareTitle': 'Sauvegarde AzuuCine',
'backup.tooBig': 'Fichier trop volumineux (30 Mo maximum).',
'backup.notJson': 'Ce fichier n\'est pas un JSON valide.',
'backup.noItems': 'Aucune fiche trouvée dans ce fichier.',
'backup.tooMany': 'Trop de fiches ({n} maximum).',
'image.canvas': 'Canvas indisponible',
'image.unreadable': 'Image illisible',
'image.notImage': 'Ce fichier n\'est pas une image.',
'image.tooBig': 'Image trop lourde (25 Mo maximum).',
'social.err.server': 'Le serveur a répondu {status}.',
'social.err.usernameTaken': 'Ce pseudo est déjà pris.',
'social.err.usernameReserved': 'Ce pseudo n\'est pas disponible.',
'social.err.invalid': 'Une des valeurs n\'est pas valide.',
'social.inLibrary': 'Dans ma bibliothèque',
'social.addToWatch': 'Ajouter à À voir',
'social.linkCopied': 'Lien copié !',
'social.profile': 'Profil',
'social.shareProfile': 'Partager le profil',
'social.loading': 'Chargement…',
'social.loadError': 'Impossible de charger le profil.',
'social.notFound': 'Profil introuvable',
'social.notFoundHint': 'Aucun profil ne s\'appelle @{username}.',
'social.editProfile': 'Modifier le profil',
'social.following': 'Abonné',
'social.requested': 'Demande envoyée',
'social.followBack': 'S\'abonner en retour',
'social.follow': 'S\'abonner',
'social.private': 'Compte privé',
'social.followsYou': 'Te suit',
'social.seen': 'Vus',
'social.followers_one': 'Abonné',
'social.followers_other': 'Abonnés',
'social.followingCount_one': 'Abonnement',
'social.followingCount_other': 'Abonnements',
'social.requests_one': '{count} demande d\'abonnement',
'social.requests_other': '{count} demandes d\'abonnement',
'social.privateTitle': 'Ce compte est privé',
'social.privateText': 'Abonne-toi pour voir ses visionnages, ses notes et son Top 5.',
'social.tabProfile': 'Profil',
'social.tabLibrary': 'Bibliothèque',
'social.cancelRequestTitle': 'Annuler la demande d\'abonnement ?',
'social.unfollowTitle': 'Se désabonner de {name} ?',
'social.unfollowPrivate': 'Ce compte est privé : il faudra refaire une demande pour revoir son profil.',
'social.cancelRequest': 'Annuler la demande',
'social.unfollow': 'Se désabonner',
'social.top5': 'Top 5',
'social.recent': 'Vus récemment',
'social.noRecent': 'Rien de terminé pour l\'instant.',
'social.statYear': 'Vus cette année',
'social.statFilms': 'Films vus',
'social.statSeries': 'Séries & animes vus',
'social.emptyLibrary': 'Aucun titre ici.',
'social.loadMore': 'Voir plus',
'social.changeBanner': 'Changer la bannière',
'social.changeAvatar': 'Changer la photo',
'social.removeAvatar': 'Retirer la photo',
'social.removeBanner': 'Retirer la bannière',
'social.displayName': 'Nom affiché',
'social.username': 'Pseudo',
'social.usernameRule': '3 à 20 caractères : lettres minuscules, chiffres ou _',
'social.bio': 'Bio',
'social.bioPh': 'Ce que tu aimes regarder, tes genres préférés…',
'social.privateAccount': 'Compte privé',
'social.privateHint': 'Seuls les abonnés que tu acceptes voient tes visionnages.',
'social.publicHint': 'Ton nom, ton pseudo, ta photo, ta bannière et ta bio sont visibles par tous les membres. Tes avis écrits restent privés, sauf ceux que tu choisis d\'afficher sur ton profil.',
'social.requestsTab_one': 'Demande',
'social.requestsTab_other': 'Demandes ({count})',
'social.noFollowing': 'Aucun abonnement pour l\'instant.',
'social.noFollowers': 'Aucun abonné pour l\'instant.',
'social.accept': 'Accepter',
'social.decline': 'Refuser',
'social.removeFollower': 'Retirer',
'social.findFriends': 'Trouver des amis',
'social.searchPh': 'Pseudo ou nom…',
'social.noResults': 'Personne ne correspond.',
'social.inviteHint': 'Tes amis ne sont pas encore sur AzuuCine ? Envoie-leur le lien de ton profil.',
'social.shareMyProfile': 'Partager mon profil',
'social.inviteText': 'Suis-moi sur AzuuCine !',
'social.myProfile': 'Mon profil',
'feed.title': 'Mes abonnements',
'feed.empty': 'Abonne-toi à des amis pour voir ici ce qu\'ils regardent et ce qu\'ils en pensent.',
'feed.finished': 'a vu',
'feed.started': 'a commencé',
'feed.rewatched': 'a revu',
'feed.added': 'veut voir',
'feed.review': 'avis',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** Italiano */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': 'Annulla',
'common.confirm': 'Conferma',
'common.close': 'Chiudi',
'common.save': 'Salva',
'common.add': 'Aggiungi',
'common.delete': 'Elimina',
'common.all': 'Tutto',
'common.none': 'Nessuno',
'common.noData': 'Ancora nessun dato.',
'common.retry': 'Riprova',
'common.back': 'Indietro',
'common.offline': 'Nessuna connessione internet.',
'common.minutes': '{n} min',
'common.hours': '{h} h',
'common.hoursMinutes': '{h} h {m}',
'common.daysHours': '{d} g {h} h',
'common.decimalSep': ',',
'common.removeX': 'Rimuovi {name}',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': 'Modifica',
'common.moveUp': 'Sposta su',
'common.moveDown': 'Sposta giù',
'nav.home': 'Home',
'nav.catalog': 'Catalogo',
'nav.stats': 'Statistiche',
'nav.settings': 'Impostazioni',
'nav.addTitle': 'Aggiungi un titolo',
'type.film': 'Film',
'type.serie': 'Serie',
'type.anime': 'Anime',
'type.kdrama': 'K-Drama',
'type.cdrama': 'C-Drama',
'type.autre': 'Altro',
'typePlural.film': 'Film',
'typePlural.serie': 'Serie',
'typePlural.anime': 'Anime',
'typePlural.kdrama': 'K-Drama',
'typePlural.cdrama': 'C-Drama',
'status.a_voir': 'Da vedere',
'status.en_cours': 'In corso',
'status.termine': 'Finito',
'status.pause': 'In pausa',
'status.abandonne': 'Abbandonato',
'criteria.story': 'Sceneggiatura / Storia',
'criteria.cast': 'Personaggi / Cast',
'criteria.direction': 'Regia / Animazione',
'criteria.ost': 'Colonna sonora (OST)',
'subtype.documentary': 'Documentario',
'subtype.reality': 'Reality',
'subtype.show': 'Programma TV',
'subtype.short': 'Cortometraggio',
'subtype.stage': 'Spettacolo',
'subtype.miniseries': 'Miniserie',
'platform.cinema': 'Cinema',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'TV',
'genre.action': 'Azione',
'genre.adventure': 'Avventura',
'genre.comedy': 'Commedia',
'genre.drama': 'Dramma',
'genre.romance': 'Romantico',
'genre.romcom': 'Rom-com',
'genre.thriller': 'Thriller',
'genre.horror': 'Horror',
'genre.mystery': 'Mistero',
'genre.crime': 'Crime',
'genre.scifi': 'Fantascienza',
'genre.fantasy': 'Fantasy',
'genre.historical': 'Storico',
'genre.sliceOfLife': 'Slice of Life',
'genre.shonen': 'Shōnen',
'genre.shojo': 'Shōjo',
'genre.seinen': 'Seinen',
'genre.isekai': 'Isekai',
'genre.mecha': 'Mecha',
'genre.sports': 'Sport',
'genre.musical': 'Musical',
'genre.medical': 'Medico',
'genre.legal': 'Giudiziario',
'genre.wuxia': 'Wuxia',
'genre.xianxia': 'Xianxia',
'genre.family': 'Famiglia',
'genre.animation': 'Animazione',
'genre.psychological': 'Psicologico',
'genre.supernatural': 'Soprannaturale',
'genre.romanticComedy': 'Commedia romantica',
'genre.documentary': 'Documentario',
'genre.war': 'Guerra',
'genre.western': 'Western',
'genre.music': 'Musica',
'genre.ecchi': 'Ecchi',
'genre.kids': 'Bambini',
'genre.news': 'Notizie',
'genre.reality': 'Reality',
'genre.talk': 'Talk show',
'genre.soap': 'Soap opera',
'genre.politics': 'Politica',
'genre.tvMovie': 'Film TV',
'genre.anime': 'Anime',
'genre.magicalGirl': 'Magical Girl',
'confirm.title': 'Sei sicuro?',
'err.tmdbRefused': 'Richiesta TMDB rifiutata.',
'err.tmdbKeyRefused': 'Chiave TMDB rifiutata. Controllala in Impostazioni.',
'err.tmdbStatus': 'TMDB ha risposto {status}.',
'err.tmdbRef': 'Riferimento TMDB non valido.',
'err.anilistRate': 'AniList limita le richieste, riprova tra un minuto.',
'err.anilistStatus': 'AniList ha risposto {status}.',
'err.searchRate': 'Troppe ricerche, riprova tra qualche minuto.',
'anilist.short': 'Anime breve',
'anilist.movie': 'Film d’animazione',
'anilist.special': 'Speciale',
'anilist.music': 'Video musicale',
'release.cinema': 'Al cinema',
'release.online': 'In VOD / streaming',
'release.release': 'Uscita',
'release.season': 'Stagione {season}',
'release.episode': 'Episodio {ep}',
'release.newEpisode': 'Nuovo episodio',
'release.firstEpisode': 'Primo episodio',
'release.newSeriesN': 'Nuova serie · {count} episodi',
'release.seasonN': 'Stagione {season} · {count} episodi',
'release.seasonEp1': 'Stagione {season} · Episodio 1',
'release.episodes': 'Episodi {first}–{last}',
'release.sEpisodes': 'S{season} · Episodi {first}–{last}',
'release.sEpisode': 'S{season} · Episodio {ep}',
'release.episodeFinal': 'Episodio {ep} · finale',
'release.filmJapan': 'Film in Giappone',
'card.ep': 'Ep. {n}',
'card.plusOne': '+1 episodio per {title}',
'card.open': 'Apri {title}',
'rating.outOf10': 'Voto su 10',
'rating.stars_one': '{count} stella',
'rating.stars_other': '{count} stelle',
'rating.clear': 'Cancella il voto',
'share.previewLabel': 'Anteprima dell’immagine',
'share.preview': 'Anteprima',
'share.posterAlt': 'Locandina {title}',
'share.share': 'Condividi',
'share.saveImage': 'Salva l’immagine',
'share.err.create': 'Impossibile creare l’immagine',
'share.minutesLong': '{n} minuti',
'share.createdBy': 'Creato da',
'share.directedBy': 'Regia di',
'share.producedBy': 'Prodotto da',
'share.starring': 'Con',
'share.genres': 'Generi',
'share.myRating': 'Il mio voto',
'share.myTop': 'La mia Top',
'auth.hidePassword': 'Nascondi la password',
'auth.showPassword': 'Mostra la password',
'auth.mismatch': 'Le due password non coincidono.',
'auth.created': 'Account creato! Apri il link inviato a {email} per attivarlo, poi accedi.',
'auth.resetSent': 'Se esiste un account con questo indirizzo, ti abbiamo appena inviato un link per scegliere una nuova password.',
'auth.tagline': 'Il tuo diario di film, serie, anime e drama.',
'auth.loginTab': 'Accedi',
'auth.signupTab': 'Crea un account',
'auth.forgotTitle': 'Password dimenticata',
'auth.email': 'Indirizzo email',
'auth.password': 'Password',
'auth.confirmPassword': 'Conferma la password',
'auth.minChars': 'Almeno {n} caratteri.',
'auth.login': 'Accedi',
'auth.signup': 'Crea il mio account',
'auth.sendLink': 'Invia il link',
'auth.forgot': 'Password dimenticata?',
'auth.backToLogin': 'Torna all’accesso',
'auth.privacy': 'I tuoi dati sono collegati al tuo account e visibili solo a te. Restano anche sul tuo dispositivo per funzionare senza internet.',
'auth.newPasswordTitle': 'Scegli la tua nuova password.',
'auth.newPassword': 'Nuova password',
'auth.err.credentials': 'Email o password errata.',
'auth.err.notConfirmed': 'Prima conferma il tuo indirizzo con il link ricevuto via email.',
'auth.err.exists': 'Esiste già un account con questa email.',
'auth.err.weak': 'Password troppo debole (almeno {n} caratteri, mescola lettere e numeri).',
'auth.err.samePassword': 'La nuova password deve essere diversa da quella vecchia.',
'auth.err.emailRate': 'Troppe richieste. Riprova tra qualche minuto.',
'auth.err.rate': 'Troppi tentativi. Riprova tra qualche minuto.',
'auth.err.signupDisabled': 'Le iscrizioni sono chiuse per il momento.',
'auth.err.emailInvalid': 'Indirizzo email non valido.',
'auth.err.invalid': 'Indirizzo email o password non validi.',
'auth.err.session': 'Sessione scaduta, accedi di nuovo.',
'auth.err.status': 'Il server ha rifiutato la richiesta ({status}).',
'auth.err.response': 'Risposta del server non valida.',
'auth.err.linkExpired': 'Questo link è scaduto. Richiedine uno nuovo.',
'auth.err.linkUsed': 'Questo link non è valido o è già stato usato.',
'auth.err.linkInvalid': 'Questo link non è valido.',
'settings.language': 'Lingua',
'settings.backupShared': 'Backup condiviso.',
'settings.backupDownloaded': 'Backup scaricato.',
'settings.exportFailed': 'L’esportazione non è riuscita.',
'settings.noValidItems': 'Il file non contiene nessuna scheda valida.',
'settings.imported_one': '{count} scheda importata.',
'settings.imported_other': '{count} schede importate.',
'settings.importedSkipped': '{n} schede importate, {skipped} ignorate.',
'settings.cleared': 'Libreria cancellata.',
'settings.pageTitle': 'Le mie ',
'settings.pageAccent': 'impostazioni',
'settings.languageHint': 'Lingua dell’app, delle date e delle info recuperate da TMDB (titoli, trame).',
'settings.rating': 'Voti',
'settings.scale5': '★ su 5',
'settings.scale10': 'Su 10',
'settings.ratingHint': 'Mezze stelle su 5, o passi di 0,5 su 10. I voti esistenti vengono convertiti automaticamente.',
'settings.theme': 'Tema',
'settings.themeX': 'Tema {name}',
'settings.pickColor': 'Scegli un colore libero',
'settings.freeColor': 'Colore libero',
'settings.freeColorHint': 'Qualsiasi colore: il testo si adatta per restare leggibile.',
'settings.databases': 'Database di film',
'settings.anilistActive': 'Anime · attivo',
'settings.noConfig': 'Nessuna configurazione necessaria.',
'settings.tmdbActive': 'Film e serie · attivo',
'settings.checking': 'Verifica…',
'settings.offline': 'Offline',
'settings.proxyMissingKey': 'Chiave TMDB mancante',
'settings.proxyNotDeployed': 'Server non installato',
'settings.unavailable': 'Non disponibile',
'settings.proxyMissingKeyHint': 'La funzione server è attiva ma la tua chiave TMDB non è salvata (secret TMDB_API_KEY in Supabase), oppure TMDB la rifiuta.',
'settings.proxyNotDeployedHint': 'La funzione «tmdb» non è ancora stata pubblicata su Supabase (vedi README → Account, passo 5).',
'settings.proxyErrorHint': 'Il server non risponde correttamente al momento.',
'settings.proxyOkHint': 'Fornito dal server dell’app: nessuna chiave da inserire.',
'settings.recheck': 'Verifica di nuovo',
'settings.keyRefused': 'Chiave rifiutata',
'settings.notConfigured': 'Non configurato',
'settings.tmdbHelp': 'Film, serie, K-drama, C-drama. Crea un account gratuito su themoviedb.org, poi Impostazioni → API, e incolla la tua «Chiave API» o il tuo «Token di accesso in lettura».',
'settings.tmdbKey': 'Chiave TMDB',
'settings.hideKey': 'Nascondi la chiave',
'settings.showKey': 'Mostra la chiave',
'settings.validate': 'Conferma',
'settings.remove': 'Rimuovi',
'settings.keyLocal': 'La chiave resta su questo dispositivo e non viene mai inclusa nei backup.',
'settings.topHint': 'Categorie mostrate nella home.',
'settings.topNone': 'Nessuna categoria: la sezione Top 5 è nascosta.',
'settings.backup': 'Backup',
'settings.export': 'Esporta i miei dati',
'settings.exportHint_one': '{count} scheda · file JSON, da fare regolarmente',
'settings.exportHint_other': '{count} schede · file JSON, da fare regolarmente',
'settings.import': 'Importa un backup',
'settings.importHint': 'Ripristina da un file .json',
'settings.legacyDetected': 'Riconosciuto un backup della vecchia app',
'settings.found_one': '{count} scheda trovata. Come vuoi importarla?',
'settings.found_other': '{count} schede trovate. Come vuoi importarle?',
'settings.foundSkipped': '{n} schede trovate ({skipped} non valide ignorate). Come vuoi importarle?',
'settings.merge': 'Unisci',
'settings.replaceAll': 'Sostituisci tutto',
'settings.mergeHint': '«Unisci» aggiunge le schede e aggiorna quelle che esistono già (stesso identificativo).',
'settings.storage': 'Archiviazione',
'settings.used': 'Spazio usato',
'settings.storageCloud': 'I tuoi dati sono salvati nel tuo account e conservati anche su questo dispositivo per funzionare senza internet. Si sincronizzano automaticamente appena hai rete.',
'settings.storageLocal': 'I tuoi dati sono salvati solo in questo browser, su questo dispositivo. Se cancelli i dati del browser o disinstalli l’app, spariscono: esporta un backup regolarmente.',
'settings.danger': 'Zona pericolosa',
'settings.clearAll': 'Cancella tutta la libreria',
'settings.clearAllHint_one': '{count} titolo',
'settings.clearAllHint_other': '{count} titoli',
'settings.clearAllHintCloud_one': '{count} titolo · su tutti i tuoi dispositivi',
'settings.clearAllHintCloud_other': '{count} titoli · su tutti i tuoi dispositivi',
'settings.deleting': 'Eliminazione…',
'settings.deleteAccount': 'Elimina il mio account',
'settings.deleteAccountHint': 'Account e dati cancellati per sempre',
'settings.footerCloud': 'account sincronizzato',
'settings.footerLocal': '100% locale',
'settings.clearConfirm_one': '{count} titolo verrà cancellato per sempre. Ricordati di esportare prima un backup.',
'settings.clearConfirm_other': 'I tuoi {count} titoli verranno cancellati per sempre. Ricordati di esportare prima un backup.',
'settings.clearConfirmCloud_one': '{count} titolo verrà cancellato per sempre, su tutti i tuoi dispositivi. Ricordati di esportare prima un backup.',
'settings.clearConfirmCloud_other': 'I tuoi {count} titoli verranno cancellati per sempre, su tutti i tuoi dispositivi. Ricordati di esportare prima un backup.',
'settings.clearAllConfirm': 'Cancella tutto',
'settings.deleteAccountTitle': 'Eliminare il tuo account?',
'settings.deleteAccountMessage': 'Il tuo account e tutti i tuoi dati (titoli, liste, impostazioni) verranno cancellati per sempre dal server e da questo dispositivo. Ricordati di esportare prima un backup. L’operazione è irreversibile.',
'settings.deleteForever': 'Elimina per sempre',
'settings.replaceConfirm': 'Tutta la tua libreria attuale verrà sostituita dal contenuto di questo file.',
'settings.replace': 'Sostituisci',
'sync.err.push': 'Invio rifiutato ({status})',
'sync.err.pull': 'Lettura rifiutata ({status})',
'store.dbError': 'Impossibile aprire il database locale: {error}',
'store.invalidItem': 'Scheda non valida',
'lists.newList': 'Nuova lista',
'lists.newListPh': 'Nuova lista…',
'lists.myLists': 'Le mie liste',
'lists.rename': 'Rinomina',
'lists.delete': 'Elimina la lista',
'lists.done': 'Fatto',
'lists.addRemove': 'Aggiungi / rimuovi titoli',
'lists.searchLibrary': 'Cerca nella mia libreria…',
'lists.emptyTitle': 'Lista vuota',
'lists.emptyText': 'Aggiungi titoli con il pulsante qui sopra, o dalla scheda di un titolo.',
'lists.deleteConfirm': 'La lista «{name}» verrà eliminata. I titoli restano nella tua libreria.',
'lists.noneTitle': 'Ancora nessuna lista',
'lists.noneText': 'Crea liste a modo tuo: «Da vedere con gli amici», «Horror di ottobre», «Drama che scaldano il cuore»…',
'lists.create': 'Crea',
'account.err.deleteRate': 'Troppi tentativi, riprova tra un minuto.',
'account.err.delete': 'L’eliminazione non è riuscita. Riprova più tardi.',
'account.title': 'Il mio account',
'account.syncing': 'Sincronizzazione…',
'account.offline': 'Offline — è tutto salvato su questo dispositivo',
'account.syncError': 'Sincronizzazione non possibile al momento',
'account.synced': 'Sincronizzato {when}',
'account.passwordChanged': 'Password modificata.',
'account.imported_one': '{count} titolo aggiunto al tuo account.',
'account.imported_other': '{count} titoli aggiunti al tuo account.',
'account.importFailed': 'L’importazione non è riuscita.',
'account.pending_one': '{count} in attesa',
'account.pending_other': '{count} in attesa',
'account.syncNow': 'Sincronizza ora',
'account.newPasswordPh': 'Nuova password (min. {n} caratteri)',
'account.changePassword': 'Cambia la password',
'account.logout': 'Esci',
'account.logoutHint': 'I tuoi dati restano nel tuo account e vengono rimossi da questo dispositivo.',
'account.ignore': 'Ignora',
'account.deviceHint': 'Verranno spostati nel tuo account e sincronizzati su tutti i tuoi dispositivi.',
'account.unsentTitle': 'Modifiche non inviate',
'account.logoutAnyway': 'Esci comunque',
'account.unsentMessage_one': '{count} modifica non è ancora stata inviata (niente connessione?). Se esci adesso, andrà persa.',
'account.unsentMessage_other': '{count} modifiche non sono ancora state inviate (niente connessione?). Se esci adesso, andranno perse.',
'account.nTitles_one': '{count} titolo',
'account.nTitles_other': '{count} titoli',
'account.nLists_one': '{count} lista',
'account.nLists_other': '{count} liste',
'account.deviceData': 'Questo dispositivo contiene {titles} creati prima del tuo account. Vuoi aggiungerli al tuo account?',
'account.deviceDataWithLists': 'Questo dispositivo contiene {titles} e {lists} creati prima del tuo account. Vuoi aggiungerli al tuo account?',
'time.never': 'mai',
'time.justNow': 'proprio ora',
'time.minutesAgo': '{n} min fa',
'time.hoursAgo': '{n} h fa',
'time.onDate': 'il {date}',
'time.today': 'oggi',
'time.tomorrow': 'domani',
'time.daysAgo': '{n} g fa',
'theme.red': 'Rosso',
'theme.orange': 'Arancione',
'theme.yellow': 'Giallo',
'theme.lime': 'Lime',
'theme.green': 'Verde',
'theme.mint': 'Menta',
'theme.cyan': 'Ciano',
'theme.blue': 'Blu',
'theme.indigo': 'Indaco',
'theme.violet': 'Viola',
'theme.pink': 'Rosa',
'theme.white': 'Bianco',
'home.seeAll': 'Vedi tutto',
'home.subtitle': 'Il mio diario di visione',
'home.calendarSoon_one': 'Calendario delle uscite: {count} questa settimana',
'home.calendarSoon_other': 'Calendario delle uscite: {count} questa settimana',
'home.emptyTitle': 'La tua libreria è vuota',
'home.emptyCloud': 'Aggiungi il tuo primo film, anime o drama. Verrà salvato nel tuo account.',
'home.emptyLocal': 'Aggiungi il tuo primo film, anime o drama. Resta tutto salvato solo su questo telefono.',
'home.completed': 'Finiti',
'home.thisYear_one': '{count} quest’anno',
'home.thisYear_other': '{count} quest’anno',
'home.toWatchN_one': '{count} da vedere',
'home.toWatchN_other': '{count} da vedere',
'home.screenTime': 'Tempo davanti allo schermo',
'home.estimate': 'stima',
'home.episodesSeen': 'Episodi visti',
'home.noIdea': 'Nessuna idea?',
'home.rouletteHint_one': 'Estrazione a sorte tra il tuo titolo da vedere',
'home.rouletteHint_other': 'Estrazione a sorte tra i tuoi {count} titoli da vedere',
'home.rouletteHintAll': 'Estrazione a sorte dalla tua libreria',
'home.recentlyFinished': 'Finiti di recente',
'calendar.title': 'Calendario delle uscite',
'calendar.inMyList': 'Nella mia lista',
'calendar.inMyListLegend': 'Nella mia lista',
'calendar.seeMore_one': 'Vedi l’altra',
'calendar.seeMore_other': 'Vedi le altre {count}',
'calendar.heading': 'Calendario delle ',
'calendar.headingAccent': 'uscite',
'calendar.refresh': 'Aggiorna',
'calendar.all': 'Tutte le uscite',
'calendar.mine': 'I miei titoli',
'calendar.prevMonth': 'Mese precedente',
'calendar.nextMonth': 'Mese successivo',
'calendar.releases_one': '{count} uscita',
'calendar.releases_other': '{count} uscite',
'calendar.others': 'Altre uscite',
'calendar.needKey': 'Senza chiave TMDB vengono mostrati solo gli anime. Aggiungi la tua chiave nelle Impostazioni per vedere anche film, serie e drama.',
'calendar.range': 'Le uscite sono disponibili dal mese scorso fino a 6 mesi in avanti.',
'calendar.failed': 'Alcune uscite non sono state caricate. Riprova con ↻.',
'calendar.nothingThatDay': 'Niente in programma quel giorno.',
'calendar.next14': 'I prossimi 14 giorni',
'calendar.loading': 'Cerco le uscite…',
'calendar.noneMine14': 'Nessuna uscita annunciata nei prossimi 14 giorni per i tuoi titoli.',
'calendar.noneMineMonth': 'Nessuna uscita annunciata questo mese per i tuoi titoli.',
'calendar.none14': 'Nessuna uscita nei prossimi 14 giorni.',
'calendar.noneMonth': 'Nessuna uscita trovata per questo mese.',
'calendar.footer': 'Film al cinema nel tuo paese, episodi delle serie e dei drama più seguiti (TMDB) e di tutti gli anime trasmessi in Giappone (AniList). I titoli della tua libreria sono evidenziati; tocca «Da vedere» per aggiungere un’uscita alla tua lista.',
'roulette.name': 'Roulette',
'roulette.rewatch': 'Da rivedere',
'roulette.anyTime': 'Qualsiasi',
'roulette.heading': 'La ',
'roulette.headingAccent': 'roulette',
'roulette.tonight': 'Stasera si guarda…',
'roulette.nEps': '{n} ep.',
'roulette.perEp': '{duration} / ep.',
'roulette.stoppedAt': 'Ti eri fermato all’episodio {ep}.',
'roulette.stoppedAtOf': 'Ti eri fermato all’episodio {ep} di {total}.',
'roulette.enjoy': 'Buona visione!',
'roulette.again': 'Rilancia',
'roulette.spinning': 'Gira…',
'roulette.spin': 'Gira la roulette',
'roulette.poolSize_one': 'Estrazione tra {count} titolo',
'roulette.poolSize_other': 'Estrazione tra {count} titoli',
'roulette.empty': 'Nessun titolo corrisponde: allarga i filtri qui sotto.',
'roulette.inside': 'Nella roulette',
'roulette.pickFrom': 'Pesca da',
'roulette.rewatchHint': '«Da rivedere» = i tuoi titoli finiti con voto 4/5 o più, preferiti e Top 5.',
'roulette.time': 'Tempo disponibile (film o 1 episodio)',
'roulette.seeItem': 'Vedi la scheda completa',
'roulette.watchIt': 'Lo guardo',
'newEp.check': 'Controlla',
'newEp.title': 'Novità',
'newEp.checking': 'Controllo cosa è uscito…',
'newEp.needKey': 'Aggiungi la tua chiave TMDB nelle Impostazioni per essere avvisato di nuovi episodi e nuove stagioni.',
'newEp.nothing_one': 'Niente di nuovo per la serie o l’anime che segui.',
'newEp.nothing_other': 'Niente di nuovo per le {count} serie e anime che segui.',
'newEp.needKeyAlso': '(Aggiungi la tua chiave TMDB nelle Impostazioni per seguire anche serie e drama.)',
'newEp.newSeason': 'Nuova stagione',
'newEp.catchUp': 'Da recuperare',
'newEp.soon': 'A breve',
'newEp.epWhen': 'Ep. {ep} {when}',
'newEp.available_one': '{count} episodio disponibile',
'newEp.available_other': '{count} episodi disponibili',
'newEp.next': 'Prossimo: ep. {ep} {when}',
'newEp.resume': 'Riprendi',
'top.pick': 'Scegli il n°{rank}',
'top.shareTitle': 'La mia Top 5 {category}',
'top.shareLabel': 'Condividi questa Top 5 come immagine',
'top.title': 'Le mie Top',
'top.number': 'N°{rank}',
'top.pickFirst': 'Scegli il tuo n°1.',
'top.editLabel': 'Modifica la Top 5',
'top.freeSlot': 'Posto libero — scegli un titolo qui sotto',
'top.addFromLibrary': 'Aggiungi dalla mia libreria',
'top.allTypes': 'Tutti i tipi',
'top.searchTitle': 'Cerca un titolo…',
'top.full': 'La tua Top 5 è completa: togli un titolo per aggiungerne un altro.',
'top.noCandidates': 'Nessun titolo. Prova «Tutti i tipi» o un’altra ricerca.',
'reco.error': 'Impossibile caricare i suggerimenti al momento.',
'reco.title': 'Suggerimenti',
'reco.needKey': 'Aggiungi la tua chiave TMDB nelle Impostazioni per ricevere suggerimenti basati sui tuoi titoli preferiti.',
'reco.other': 'Altro titolo',
'reco.ifYouLiked': 'Se ti è piaciuto',
'reco.loading': 'Cerco suggerimenti…',
'reco.none': 'Hai già tutto ciò che somiglia a questo titolo. Prova «Altro titolo».',
'reco.added': '{title} aggiunto',
'reco.addLabel': 'Aggiungi {title} a da vedere',
'reco.addedShort': 'Aggiunto',
'search.moviesSeries': 'Film e serie',
'search.offline': 'Nessuna connessione internet: la ricerca ha bisogno della rete.',
'search.fillFrom': 'Compila da un database',
'search.needKey': 'Per cercare film, serie e drama, aggiungi la tua chiave TMDB gratuita nelle Impostazioni.',
'search.openSettings': 'Apri le Impostazioni',
'search.already': 'già aggiunto',
'search.noResults': 'Nessun risultato. Puoi compilare la scheda a mano qui sotto.',
'search.privacy': 'Viene inviato a {source} solo il titolo cercato. La tua libreria resta sul tuo telefono.',
'catalog.sortRecent': 'Modificati di recente',
'catalog.sortWatched': 'Data di visione',
'catalog.sortRating': 'Voto più alto',
'catalog.sortTitle': 'Titolo (A→Z)',
'catalog.pageTitle': 'Il mio ',
'catalog.pageAccent': 'catalogo',
'catalog.journalSubtitle': 'La tua cronologia di visione',
'catalog.filteredCount_one': '{count} titolo (filtrato)',
'catalog.filteredCount_other': '{count} titoli (filtrati)',
'catalog.titles': 'Titoli',
'catalog.journal': 'Diario',
'catalog.lists': 'Liste',
'catalog.searchPh': 'Titolo, genere, piattaforma…',
'catalog.moreFilters': 'Altri filtri',
'catalog.all': 'Tutti',
'catalog.genre': 'Genere',
'catalog.minRating': 'Voto minimo',
'catalog.allRatings': 'Tutti',
'catalog.sortBy': 'Ordina per',
'catalog.favorites': 'Preferiti',
'catalog.reset': 'Reimposta',
'catalog.noResults': 'Nessun risultato',
'catalog.nothingYet': 'Ancora niente',
'catalog.noResultsHint': 'Prova un’altra ricerca o togli qualche filtro.',
'catalog.nothingYetHint': 'Aggiungi il tuo primo titolo con il pulsante +.',
'catalog.clearFilters': 'Cancella i filtri',
'public.agree': 'In linea con il pubblico',
'public.more': '+{gap} in più del pubblico',
'public.less': '−{gap} in meno del pubblico',
'public.label': 'Pubblico',
'public.me': 'Io',
'public.added_one': '{count} voto del pubblico aggiunto.',
'public.added_other': '{count} voti del pubblico aggiunti.',
'public.noneFound': 'Nessun nuovo voto trovato.',
'public.fetch': 'Recupera ({n})',
'public.title': 'Io vs il pubblico',
'public.hintFetch': 'Recupera il voto medio TMDB / AniList dei tuoi titoli votati per vedere dove ti distingui dal pubblico.',
'public.hintNone': 'Nessun voto pubblico disponibile per i tuoi titoli votati in questo periodo.',
'public.hintKey': 'Aggiungi la tua chiave TMDB nelle Impostazioni (o anime collegati ad AniList) per confrontarti con il pubblico.',
'public.avgGap': 'Scarto medio',
'public.average': 'Nella media',
'public.generous': 'Più generoso del pubblico',
'public.harsh': 'Più severo del pubblico',
'public.agreeTitle': 'D’accordo',
'public.within5_one': 'entro ½ stella, su {count} titolo',
'public.within5_other': 'entro ½ stella, su {count} titoli',
'public.within10_one': 'entro 1 punto, su {count} titolo',
'public.within10_other': 'entro 1 punto, su {count} titoli',
'public.lovedPre': 'Mi sono piaciuti ',
'public.lovedAccent': 'di più',
'public.lovedPost': ' che al pubblico',
'public.hatedPre': 'Mi sono piaciuti ',
'public.hatedAccent': 'di meno',
'public.hatedPost': ' che al pubblico',
'public.allAgree': 'Sei d’accordo con il pubblico su tutti i tuoi titoli. Raro!',
'form.rewatchHint': 'L’hai rivisto? Segna ogni nuova visione, comparirà nel tuo diario.',
'form.editTitle': 'Modifica ',
'form.editAccent': 'scheda',
'form.newTitle': 'Nuovo ',
'form.newAccent': 'titolo',
'form.filledFrom': 'Compilato da',
'form.canEdit': 'puoi modificare tutto',
'form.fillFromDb': 'Completa da TMDB / AniList',
'form.pickPoster': 'Scegli una locandina',
'form.removeImage': 'Rimuovi l’immagine',
'form.title': 'Titolo *',
'form.titlePh': 'es. Your Name',
'form.originalTitle': 'Titolo originale',
'form.originalTitlePh': 'es. 君の名は。',
'form.synopsis': 'Trama',
'form.type': 'Tipo',
'form.subtype': 'Dettaglio',
'form.subtypePh': 'Documentario, Reality…',
'form.status': 'Stato',
'form.myRating': 'Il mio voto',
'form.favorite': 'Preferito',
'form.criteria': 'Criteri dettagliati (facoltativo)',
'form.episodes': 'Episodi',
'form.minusEp': '-1 episodio',
'form.plusEp': '+1 episodio',
'form.total': 'Totale',
'form.season': 'Stagione',
'form.minPerEp': 'Min / ep.',
'form.duration': 'Durata',
'form.durationMin': 'Durata (minuti)',
'form.info': 'Informazioni',
'form.start': 'Inizio / visto il',
'form.end': 'Fine',
'form.year': 'Anno',
'form.platform': 'Piattaforma',
'form.genres': 'Generi / tag',
'form.genresPh': 'Romantico, Fantascienza…',
'form.rewatches': 'Nuove visioni',
'form.review': 'La mia opinione',
'form.reviewPh': 'Cosa ne ho pensato, scene memorabili…',
'form.saveChanges': 'Salva le modifiche',
'form.addToLibrary': 'Aggiungi alla mia libreria',
'form.shareImage': 'Condividi come immagine',
'form.delete': 'Elimina questo titolo',
'form.deleteConfirm': '«{title}» verrà eliminato per sempre.',
'form.removeRewatch': 'Rimuovi questa visione',
'form.rewatchDate': 'Data della nuova visione',
'form.reviewPublic': 'Mostra questa opinione sul mio profilo',
'form.reviewPublicHint': 'Altrimenti resta visibile solo a te.',
'journal.rewatched': 'Rivisto',
'journal.started': 'Iniziato',
'journal.emptyTitle': 'Diario vuoto',
'journal.emptyText': 'Le tue visioni compariranno qui appena avrai date di inizio o fine nelle tue schede.',
'journal.seen_one': '{count} visto',
'journal.seen_other': '{count} visti',
'journal.more': 'Mostra i mesi precedenti',
'stats.overview': 'Panoramica',
'stats.habits': 'Abitudini',
'stats.tastes': 'Gusti',
'stats.pageTitle': 'Le mie ',
'stats.pageAccent': 'statistiche',
'stats.emptyTitle': 'Ancora nessuna statistica',
'stats.emptyText': 'Compariranno appena avrai aggiunto dei titoli.',
'stats.sinceStart': 'dall’inizio',
'stats.subtitle_one': '{count} titolo nella mia libreria',
'stats.subtitle_other': '{count} titoli nella mia libreria',
'stats.subtitleYear_one': '{count} titolo nel {year}',
'stats.subtitleYear_other': '{count} titoli nel {year}',
'stats.hours_one': 'ora',
'stats.hours_other': 'ore',
'stats.nonStopPre': 'cioè ',
'stats.nonStopPost': ' non-stop',
'stats.days_one': '{count} giorno',
'stats.days_other': '{count} giorni',
'stats.finishedN_one': '{count} finito',
'stats.finishedN_other': '{count} finiti',
'stats.episodesN_one': '{count} episodio',
'stats.episodesN_other': '{count} episodi',
'stats.timeByType': 'Tempo per tipo',
'stats.noTime': 'Ancora nessun tempo registrato in questo periodo.',
'stats.avgRating': 'Voto medio',
'stats.rated_one': '{count} titolo votato',
'stats.rated_other': '{count} titoli votati',
'stats.inYear': 'nel {year}',
'stats.statuses': 'Stati',
'stats.hoursTab': 'Ore',
'stats.monthByMonth': 'Mese per mese · {year}',
'stats.last12': 'Ultimi 12 mesi',
'stats.monthFinished_one': '{count} titolo finito',
'stats.monthFinished_other': '{count} titoli finiti',
'stats.busiest': 'Mese più intenso:',
'stats.records': 'Record',
'stats.marathon': 'Maratona più lunga',
'stats.longestFilm': 'Film più lungo',
'stats.noRecords': 'Ancora nessun record in questo periodo.',
'stats.platforms': 'Piattaforme',
'stats.bestRated': 'I miei più votati',
'stats.myRatings': 'I miei voti',
'stats.noRatings': 'Nessun voto in questo periodo.',
'stats.favGenres': 'Generi preferiti',
'stats.noGenres': 'Ancora nessun genere.',
'stats.countries': 'Paesi',
'stats.noCountry_one': '{count} titolo senza paese: completalo con «Completa da TMDB / AniList» nella scheda.',
'stats.noCountry_other': '{count} titoli senza paese: completali con «Completa da TMDB / AniList» nella scheda.',
'stats.noCountryLegacy_one': '{count} titolo senza paese: completalo con «Completa da TMDB / AniList» nella scheda, o reimporta il backup della tua vecchia app («Unisci»).',
'stats.noCountryLegacy_other': '{count} titoli senza paese: completali con «Completa da TMDB / AniList» nella scheda, o reimporta il backup della tua vecchia app («Unisci»).',
'stats.byType': 'Per tipo',
'stats.footnote': 'Tempo stimato in base agli episodi visti e alle durate inserite (altrimenti: film 1 h 50, episodio anime 24 min, serie 45 min, K-drama 1 h, C-drama 45 min). Un titolo conta per l’anno in cui l’ho finito.',
'stats.ratedAs_one': 'votato {rating}',
'stats.ratedAs_other': 'votati {rating}',
'backup.shareTitle': 'Backup AzuuCine',
'backup.tooBig': 'File troppo grande (massimo 30 MB).',
'backup.notJson': 'Questo file non è un JSON valido.',
'backup.noItems': 'Nessuna scheda trovata in questo file.',
'backup.tooMany': 'Troppe schede (massimo {n}).',
'image.canvas': 'Canvas non disponibile',
'image.unreadable': 'Immagine illeggibile',
'image.notImage': 'Questo file non è un’immagine.',
'image.tooBig': 'Immagine troppo pesante (massimo 25 MB).',
'social.err.server': 'Il server ha risposto {status}.',
'social.err.usernameTaken': 'Questo username è già preso.',
'social.err.usernameReserved': 'Questo username non è disponibile.',
'social.err.invalid': 'Uno dei valori non è valido.',
'social.inLibrary': 'Nella mia libreria',
'social.addToWatch': 'Aggiungi a Da vedere',
'social.linkCopied': 'Link copiato!',
'social.profile': 'Profilo',
'social.shareProfile': 'Condividi il profilo',
'social.loading': 'Caricamento…',
'social.loadError': 'Impossibile caricare il profilo.',
'social.notFound': 'Profilo non trovato',
'social.notFoundHint': 'Nessun profilo si chiama @{username}.',
'social.editProfile': 'Modifica profilo',
'social.following': 'Segui già',
'social.requested': 'Richiesta inviata',
'social.followBack': 'Ricambia',
'social.follow': 'Segui',
'social.private': 'Account privato',
'social.followsYou': 'Ti segue',
'social.seen': 'Visti',
'social.followers_one': 'Follower',
'social.followers_other': 'Follower',
'social.followingCount_one': 'Seguito',
'social.followingCount_other': 'Seguiti',
'social.requests_one': '{count} richiesta di follow',
'social.requests_other': '{count} richieste di follow',
'social.privateTitle': 'Questo account è privato',
'social.privateText': 'Seguilo per vedere le sue visioni, i suoi voti e la sua Top 5.',
'social.tabProfile': 'Profilo',
'social.tabLibrary': 'Libreria',
'social.cancelRequestTitle': 'Annullare la richiesta di follow?',
'social.unfollowTitle': 'Smettere di seguire {name}?',
'social.unfollowPrivate': 'Questo account è privato: dovrai inviare una nuova richiesta per rivedere il suo profilo.',
'social.cancelRequest': 'Annulla la richiesta',
'social.unfollow': 'Smetti di seguire',
'social.top5': 'Top 5',
'social.recent': 'Visti di recente',
'social.noRecent': 'Ancora niente di finito.',
'social.statYear': 'Visti quest’anno',
'social.statFilms': 'Film visti',
'social.statSeries': 'Serie e anime visti',
'social.emptyLibrary': 'Nessun titolo qui.',
'social.loadMore': 'Mostra altro',
'social.changeBanner': 'Cambia il banner',
'social.changeAvatar': 'Cambia la foto',
'social.removeAvatar': 'Rimuovi la foto',
'social.removeBanner': 'Rimuovi il banner',
'social.displayName': 'Nome visualizzato',
'social.username': 'Username',
'social.usernameRule': 'Da 3 a 20 caratteri: lettere minuscole, numeri o _',
'social.bio': 'Bio',
'social.bioPh': 'Cosa ti piace guardare, i tuoi generi preferiti…',
'social.privateAccount': 'Account privato',
'social.privateHint': 'Solo i follower che accetti vedono le tue visioni.',
'social.publicHint': 'Il tuo nome, username, foto, banner e bio sono visibili a tutti gli utenti. Le tue opinioni scritte restano private, tranne quelle che scegli di mostrare sul tuo profilo.',
'social.requestsTab_one': 'Richiesta',
'social.requestsTab_other': 'Richieste ({count})',
'social.noFollowing': 'Non segui ancora nessuno.',
'social.noFollowers': 'Ancora nessun follower.',
'social.accept': 'Accetta',
'social.decline': 'Rifiuta',
'social.removeFollower': 'Rimuovi',
'social.findFriends': 'Trova amici',
'social.searchPh': 'Username o nome…',
'social.noResults': 'Nessun risultato.',
'social.inviteHint': 'I tuoi amici non sono ancora su AzuuCine? Mandagli il link del tuo profilo.',
'social.shareMyProfile': 'Condividi il mio profilo',
'social.inviteText': 'Seguimi su AzuuCine!',
'social.myProfile': 'Il mio profilo',
'feed.title': 'Persone che segui',
'feed.empty': 'Segui degli amici per vedere qui cosa guardano e cosa ne pensano.',
'feed.finished': 'ha visto',
'feed.started': 'ha iniziato',
'feed.rewatched': 'ha rivisto',
'feed.added': 'vuole vedere',
'feed.review': 'opinione',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** 日本語 */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': 'キャンセル',
'common.confirm': '確認',
'common.close': '閉じる',
'common.save': '保存',
'common.add': '追加',
'common.delete': '削除',
'common.all': 'すべて',
'common.none': 'なし',
'common.noData': 'まだデータがありません。',
'common.retry': '再試行',
'common.back': '戻る',
'common.offline': 'インターネットに接続されていません。',
'common.minutes': '{n}分',
'common.hours': '{h}時間',
'common.hoursMinutes': '{h}時間{m}分',
'common.daysHours': '{d}日{h}時間',
'common.decimalSep': '.',
'common.removeX': '{name}を外す',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': '編集',
'common.moveUp': '上へ',
'common.moveDown': '下へ',
'nav.home': 'ホーム',
'nav.catalog': 'カタログ',
'nav.stats': '統計',
'nav.settings': '設定',
'nav.addTitle': '作品を追加',
'type.film': '映画',
'type.serie': 'ドラマ',
'type.anime': 'アニメ',
'type.kdrama': '韓国ドラマ',
'type.cdrama': '中国ドラマ',
'type.autre': 'その他',
'typePlural.film': '映画',
'typePlural.serie': 'ドラマ',
'typePlural.anime': 'アニメ',
'typePlural.kdrama': '韓国ドラマ',
'typePlural.cdrama': '中国ドラマ',
'status.a_voir': '見たい',
'status.en_cours': '視聴中',
'status.termine': '見終わった',
'status.pause': '一時停止',
'status.abandonne': '視聴中止',
'criteria.story': '脚本・ストーリー',
'criteria.cast': 'キャラクター・キャスト',
'criteria.direction': '演出・作画',
'criteria.ost': 'サウンドトラック(OST)',
'subtype.documentary': 'ドキュメンタリー',
'subtype.reality': 'リアリティ番組',
'subtype.show': 'バラエティ番組',
'subtype.short': '短編映画',
'subtype.stage': '舞台',
'subtype.miniseries': 'ミニシリーズ',
'platform.cinema': '映画館',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'テレビ',
'genre.action': 'アクション',
'genre.adventure': 'アドベンチャー',
'genre.comedy': 'コメディ',
'genre.drama': 'ドラマ',
'genre.romance': 'ロマンス',
'genre.romcom': 'ラブコメ',
'genre.thriller': 'スリラー',
'genre.horror': 'ホラー',
'genre.mystery': 'ミステリー',
'genre.crime': '犯罪',
'genre.scifi': 'SF',
'genre.fantasy': 'ファンタジー',
'genre.historical': '歴史',
'genre.sliceOfLife': '日常系',
'genre.shonen': '少年',
'genre.shojo': '少女',
'genre.seinen': '青年',
'genre.isekai': '異世界',
'genre.mecha': 'メカ',
'genre.sports': 'スポーツ',
'genre.musical': 'ミュージカル',
'genre.medical': '医療',
'genre.legal': '法廷',
'genre.wuxia': '武侠',
'genre.xianxia': '仙侠',
'genre.family': 'ファミリー',
'genre.animation': 'アニメーション',
'genre.psychological': 'サイコ',
'genre.supernatural': '超常',
'genre.romanticComedy': 'ロマンティック・コメディ',
'genre.documentary': 'ドキュメンタリー',
'genre.war': '戦争',
'genre.western': '西部劇',
'genre.music': '音楽',
'genre.ecchi': 'お色気',
'genre.kids': 'キッズ',
'genre.news': 'ニュース',
'genre.reality': 'リアリティ番組',
'genre.talk': 'トーク番組',
'genre.soap': '連続ドラマ',
'genre.politics': '政治',
'genre.tvMovie': 'テレビ映画',
'genre.anime': 'アニメ',
'genre.magicalGirl': '魔法少女',
'confirm.title': '本当によろしいですか?',
'err.tmdbRefused': 'TMDBへのリクエストが拒否されました。',
'err.tmdbKeyRefused': 'TMDBキーが拒否されました。設定で確認してください。',
'err.tmdbStatus': 'TMDBの応答:{status}',
'err.tmdbRef': 'TMDBの参照が無効です。',
'err.anilistRate': 'AniListのリクエスト制限中です。1分後にもう一度お試しください。',
'err.anilistStatus': 'AniListの応答:{status}',
'err.searchRate': '検索が多すぎます。数分後にもう一度お試しください。',
'anilist.short': '短編アニメ',
'anilist.movie': 'アニメ映画',
'anilist.special': 'スペシャル',
'anilist.music': 'MV',
'release.cinema': '劇場公開',
'release.online': '配信開始',
'release.release': '公開',
'release.season': 'シーズン{season}',
'release.episode': '第{ep}話',
'release.newEpisode': '新エピソード',
'release.firstEpisode': '第1話',
'release.newSeriesN': '新シリーズ・全{count}話',
'release.seasonN': 'シーズン{season}・全{count}話',
'release.seasonEp1': 'シーズン{season}・第1話',
'release.episodes': '第{first}–{last}話',
'release.sEpisodes': 'S{season}・第{first}–{last}話',
'release.sEpisode': 'S{season}・第{ep}話',
'release.episodeFinal': '第{ep}話・最終話',
'release.filmJapan': '日本で劇場公開',
'card.ep': '第{n}話',
'card.plusOne': '{title}に+1話',
'card.open': '{title}を開く',
'rating.outOf10': '10点満点で評価',
'rating.stars_one': '星{count}つ',
'rating.stars_other': '星{count}つ',
'rating.clear': '評価を消す',
'share.previewLabel': '画像のプレビュー',
'share.preview': 'プレビュー',
'share.posterAlt': '{title}のポスター',
'share.share': 'シェア',
'share.saveImage': '画像を保存',
'share.err.create': '画像を作成できませんでした',
'share.minutesLong': '{n}分',
'share.createdBy': '原作・制作',
'share.directedBy': '監督',
'share.producedBy': 'プロデューサー',
'share.starring': '出演',
'share.genres': 'ジャンル',
'share.myRating': 'マイ評価',
'share.myTop': 'マイトップ',
'auth.hidePassword': 'パスワードを隠す',
'auth.showPassword': 'パスワードを表示',
'auth.mismatch': 'パスワードが一致しません。',
'auth.created': 'アカウントを作成しました!{email}に届いたリンクを開いて有効化してから、ログインしてください。',
'auth.resetSent': 'このアドレスのアカウントがあれば、新しいパスワードを設定するリンクを送信しました。',
'auth.tagline': '映画・ドラマ・アニメの視聴記録アプリ。',
'auth.loginTab': 'ログイン',
'auth.signupTab': 'アカウント作成',
'auth.forgotTitle': 'パスワードを忘れた場合',
'auth.email': 'メールアドレス',
'auth.password': 'パスワード',
'auth.confirmPassword': 'パスワード(確認)',
'auth.minChars': '{n}文字以上。',
'auth.login': 'ログイン',
'auth.signup': 'アカウントを作成',
'auth.sendLink': 'リンクを送信',
'auth.forgot': 'パスワードをお忘れですか?',
'auth.backToLogin': 'ログインに戻る',
'auth.privacy': 'データはあなたのアカウントに紐づき、あなただけが見られます。オフラインでも使えるよう、端末にも保存されます。',
'auth.newPasswordTitle': '新しいパスワードを設定してください。',
'auth.newPassword': '新しいパスワード',
'auth.err.credentials': 'メールアドレスまたはパスワードが違います。',
'auth.err.notConfirmed': '先にメールで届いたリンクからアドレスを確認してください。',
'auth.err.exists': 'このメールアドレスのアカウントはすでに存在します。',
'auth.err.weak': 'パスワードが弱すぎます({n}文字以上、英字と数字を組み合わせてください)。',
'auth.err.samePassword': '新しいパスワードは以前のものと違うものにしてください。',
'auth.err.emailRate': 'リクエストが多すぎます。数分後にもう一度お試しください。',
'auth.err.rate': '試行回数が多すぎます。数分後にもう一度お試しください。',
'auth.err.signupDisabled': '現在、新規登録を受け付けていません。',
'auth.err.emailInvalid': 'メールアドレスが無効です。',
'auth.err.invalid': 'メールアドレスまたはパスワードが無効です。',
'auth.err.session': 'セッションが切れました。もう一度ログインしてください。',
'auth.err.status': 'サーバーがリクエストを拒否しました({status})。',
'auth.err.response': 'サーバーの応答が無効です。',
'auth.err.linkExpired': 'このリンクは期限切れです。新しいリンクをリクエストしてください。',
'auth.err.linkUsed': 'このリンクは無効か、すでに使用されています。',
'auth.err.linkInvalid': 'このリンクは無効です。',
'settings.language': '言語',
'settings.backupShared': 'バックアップを共有しました。',
'settings.backupDownloaded': 'バックアップをダウンロードしました。',
'settings.exportFailed': 'エクスポートに失敗しました。',
'settings.noValidItems': 'ファイルに有効な作品データがありません。',
'settings.imported_one': '{count}件をインポートしました。',
'settings.imported_other': '{count}件をインポートしました。',
'settings.importedSkipped': '{n}件をインポート、{skipped}件をスキップしました。',
'settings.cleared': 'ライブラリを消去しました。',
'settings.pageTitle': 'マイ',
'settings.pageAccent': '設定',
'settings.languageHint': 'アプリ、日付、TMDBから取得する情報(タイトル、あらすじ)の言語です。',
'settings.rating': '評価方式',
'settings.scale5': '★ 5段階',
'settings.scale10': '10点満点',
'settings.ratingHint': '5段階は星半分刻み、10点満点は0.5刻みです。既存の評価は自動で変換されます。',
'settings.theme': 'テーマ',
'settings.themeX': '{name}テーマ',
'settings.pickColor': '好きな色を選ぶ',
'settings.freeColor': 'カスタムカラー',
'settings.freeColorHint': 'どんな色でもOK。文字は読みやすいように自動で調整されます。',
'settings.databases': '作品データベース',
'settings.anilistActive': 'アニメ・有効',
'settings.noConfig': '設定は不要です。',
'settings.tmdbActive': '映画・ドラマ・有効',
'settings.checking': '確認中…',
'settings.offline': 'オフライン',
'settings.proxyMissingKey': 'TMDBキーがありません',
'settings.proxyNotDeployed': 'サーバー未設定',
'settings.unavailable': '利用できません',
'settings.proxyMissingKeyHint': 'サーバー機能は動いていますが、TMDBキーが登録されていない(SupabaseのシークレットTMDB_API_KEY)か、TMDBに拒否されています。',
'settings.proxyNotDeployedHint': '「tmdb」関数がまだSupabaseにデプロイされていません(README → アカウント、手順5を参照)。',
'settings.proxyErrorHint': '現在、サーバーが正しく応答していません。',
'settings.proxyOkHint': 'アプリのサーバーが提供しています。キーの入力は不要です。',
'settings.recheck': '再確認',
'settings.keyRefused': 'キーが拒否されました',
'settings.notConfigured': '未設定',
'settings.tmdbHelp': '映画、ドラマ、韓国ドラマ、中国ドラマ用。themoviedb.orgで無料アカウントを作成し、設定 → APIから「APIキー」または「APIリードアクセストークン」を貼り付けてください。',
'settings.tmdbKey': 'TMDBキー',
'settings.hideKey': 'キーを隠す',
'settings.showKey': 'キーを表示',
'settings.validate': '確定',
'settings.remove': '削除',
'settings.keyLocal': 'キーはこの端末にのみ保存され、バックアップには含まれません。',
'settings.topHint': 'ホームに表示するカテゴリー。',
'settings.topNone': 'カテゴリーなし:トップ5は非表示になります。',
'settings.backup': 'バックアップ',
'settings.export': 'データをエクスポート',
'settings.exportHint_one': '{count}件・JSONファイル。定期的に保存しましょう',
'settings.exportHint_other': '{count}件・JSONファイル。定期的に保存しましょう',
'settings.import': 'バックアップをインポート',
'settings.importHint': '.jsonファイルから復元',
'settings.legacyDetected': '旧アプリのバックアップを検出しました',
'settings.found_one': '{count}件見つかりました。どのようにインポートしますか?',
'settings.found_other': '{count}件見つかりました。どのようにインポートしますか?',
'settings.foundSkipped': '{n}件見つかりました(無効な{skipped}件はスキップ)。どのようにインポートしますか?',
'settings.merge': '統合',
'settings.replaceAll': 'すべて置き換え',
'settings.mergeHint': '「統合」は作品を追加し、既存のもの(同じID)を更新します。',
'settings.storage': 'ストレージ',
'settings.used': '使用容量',
'settings.storageCloud': 'データはアカウントに保存され、オフラインでも使えるようこの端末にも保存されます。ネットにつながると自動で同期されます。',
'settings.storageLocal': 'データはこの端末のこのブラウザにのみ保存されています。ブラウザのデータを消去したりアプリを削除したりすると消えてしまうので、定期的にバックアップをエクスポートしてください。',
'settings.danger': '危険な操作',
'settings.clearAll': 'ライブラリをすべて消去',
'settings.clearAllHint_one': '{count}作品',
'settings.clearAllHint_other': '{count}作品',
'settings.clearAllHintCloud_one': '{count}作品・すべての端末から',
'settings.clearAllHintCloud_other': '{count}作品・すべての端末から',
'settings.deleting': '削除中…',
'settings.deleteAccount': 'アカウントを削除',
'settings.deleteAccountHint': 'アカウントとデータを完全に削除します',
'settings.footerCloud': 'アカウント同期',
'settings.footerLocal': '100%ローカル',
'settings.clearConfirm_one': '{count}作品が完全に削除されます。先にバックアップをエクスポートしておきましょう。',
'settings.clearConfirm_other': '{count}作品が完全に削除されます。先にバックアップをエクスポートしておきましょう。',
'settings.clearConfirmCloud_one': '{count}作品がすべての端末から完全に削除されます。先にバックアップをエクスポートしておきましょう。',
'settings.clearConfirmCloud_other': '{count}作品がすべての端末から完全に削除されます。先にバックアップをエクスポートしておきましょう。',
'settings.clearAllConfirm': 'すべて消去',
'settings.deleteAccountTitle': 'アカウントを削除しますか?',
'settings.deleteAccountMessage': 'アカウントとすべてのデータ(作品、リスト、設定)がサーバーとこの端末から完全に削除されます。先にバックアップをエクスポートしておきましょう。この操作は取り消せません。',
'settings.deleteForever': '完全に削除',
'settings.replaceConfirm': '現在のライブラリはすべて、このファイルの内容で置き換えられます。',
'settings.replace': '置き換え',
'sync.err.push': '送信が拒否されました({status})',
'sync.err.pull': '読み込みが拒否されました({status})',
'store.dbError': 'ローカルデータベースを開けません:{error}',
'store.invalidItem': '無効な作品データ',
'lists.newList': '新しいリスト',
'lists.newListPh': '新しいリスト…',
'lists.myLists': 'マイリスト',
'lists.rename': '名前を変更',
'lists.delete': 'リストを削除',
'lists.done': '完了',
'lists.addRemove': '作品を追加・削除',
'lists.searchLibrary': 'ライブラリを検索…',
'lists.emptyTitle': '空のリスト',
'lists.emptyText': '上のボタンか、作品ページから追加してください。',
'lists.deleteConfirm': 'リスト「{name}」を削除します。作品はライブラリに残ります。',
'lists.noneTitle': 'まだリストがありません',
'lists.noneText': '自分だけのリストを作りましょう:「友達と見たい」「10月のホラー映画」「癒やし系ドラマ」…',
'lists.create': '作成',
'account.err.deleteRate': '試行回数が多すぎます。1分後にもう一度お試しください。',
'account.err.delete': '削除に失敗しました。しばらくしてからもう一度お試しください。',
'account.title': 'マイアカウント',
'account.syncing': '同期中…',
'account.offline': 'オフライン — すべてこの端末に保存されています',
'account.syncError': '現在、同期できません',
'account.synced': '最終同期:{when}',
'account.passwordChanged': 'パスワードを変更しました。',
'account.imported_one': '{count}作品をアカウントに追加しました。',
'account.imported_other': '{count}作品をアカウントに追加しました。',
'account.importFailed': 'インポートに失敗しました。',
'account.pending_one': '{count}件待機中',
'account.pending_other': '{count}件待機中',
'account.syncNow': '今すぐ同期',
'account.newPasswordPh': '新しいパスワード({n}文字以上)',
'account.changePassword': 'パスワードを変更',
'account.logout': 'ログアウト',
'account.logoutHint': 'データはアカウントに残り、この端末からは削除されます。',
'account.ignore': '無視',
'account.deviceHint': 'アカウントに移動され、すべての端末で同期されます。',
'account.unsentTitle': '未送信の変更',
'account.logoutAnyway': 'それでもログアウト',
'account.unsentMessage_one': '{count}件の変更がまだ送信されていません(オフラインかも?)。今ログアウトすると失われます。',
'account.unsentMessage_other': '{count}件の変更がまだ送信されていません(オフラインかも?)。今ログアウトすると失われます。',
'account.nTitles_one': '{count}作品',
'account.nTitles_other': '{count}作品',
'account.nLists_one': '{count}リスト',
'account.nLists_other': '{count}リスト',
'account.deviceData': 'この端末にはアカウント作成前の{titles}があります。アカウントに追加しますか?',
'account.deviceDataWithLists': 'この端末にはアカウント作成前の{titles}と{lists}があります。アカウントに追加しますか?',
'time.never': 'なし',
'time.justNow': 'たった今',
'time.minutesAgo': '{n}分前',
'time.hoursAgo': '{n}時間前',
'time.onDate': '{date}',
'time.today': '今日',
'time.tomorrow': '明日',
'time.daysAgo': '{n}日前',
'theme.red': 'レッド',
'theme.orange': 'オレンジ',
'theme.yellow': 'イエロー',
'theme.lime': 'ライム',
'theme.green': 'グリーン',
'theme.mint': 'ミント',
'theme.cyan': 'シアン',
'theme.blue': 'ブルー',
'theme.indigo': 'インディゴ',
'theme.violet': 'バイオレット',
'theme.pink': 'ピンク',
'theme.white': 'ホワイト',
'home.seeAll': 'すべて見る',
'home.subtitle': 'わたしの視聴記録',
'home.calendarSoon_one': '公開カレンダー:今週{count}件',
'home.calendarSoon_other': '公開カレンダー:今週{count}件',
'home.emptyTitle': 'ライブラリは空です',
'home.emptyCloud': '最初の映画、アニメ、ドラマを追加しましょう。アカウントに保存されます。',
'home.emptyLocal': '最初の映画、アニメ、ドラマを追加しましょう。データはこのスマホにのみ保存されます。',
'home.completed': '見終わった',
'home.thisYear_one': '今年{count}本',
'home.thisYear_other': '今年{count}本',
'home.toWatchN_one': '見たい{count}本',
'home.toWatchN_other': '見たい{count}本',
'home.screenTime': '視聴時間',
'home.estimate': '推定',
'home.episodesSeen': '視聴エピソード',
'home.noIdea': '何を見るか迷ったら?',
'home.rouletteHint_one': '見たい作品からランダムに選びます',
'home.rouletteHint_other': '見たい{count}作品からランダムに選びます',
'home.rouletteHintAll': 'ライブラリからランダムに選びます',
'home.recentlyFinished': '最近見終わった作品',
'calendar.title': '公開カレンダー',
'calendar.inMyList': 'マイリストにあり',
'calendar.inMyListLegend': 'マイリストにあり',
'calendar.seeMore_one': 'ほかの1件を見る',
'calendar.seeMore_other': 'ほかの{count}件を見る',
'calendar.heading': '公開',
'calendar.headingAccent': 'カレンダー',
'calendar.refresh': '更新',
'calendar.all': 'すべての公開',
'calendar.mine': 'マイ作品',
'calendar.prevMonth': '前の月',
'calendar.nextMonth': '次の月',
'calendar.releases_one': '{count}件',
'calendar.releases_other': '{count}件',
'calendar.others': 'その他の公開',
'calendar.needKey': 'TMDBキーがないとアニメのみ表示されます。設定でキーを追加すると、映画やドラマも表示されます。',
'calendar.range': '先月から6か月先までの公開情報を表示できます。',
'calendar.failed': '一部の公開情報を読み込めませんでした。↻でもう一度お試しください。',
'calendar.nothingThatDay': 'この日の予定はありません。',
'calendar.next14': '今後14日間',
'calendar.loading': '公開情報を検索中…',
'calendar.noneMine14': '今後14日間、あなたの作品の公開予定はありません。',
'calendar.noneMineMonth': '今月、あなたの作品の公開予定はありません。',
'calendar.none14': '今後14日間の公開予定はありません。',
'calendar.noneMonth': '今月の公開情報は見つかりませんでした。',
'calendar.footer': 'あなたの国で劇場公開される映画、人気のドラマのエピソード(TMDB)、日本で放送中のすべてのアニメ(AniList)を表示しています。ライブラリにある作品は色付きで表示されます。「見たい」をタップするとリストに追加できます。',
'roulette.name': 'ルーレット',
'roulette.rewatch': 'もう一度見たい',
'roulette.anyTime': '指定なし',
'roulette.heading': 'おまかせ',
'roulette.headingAccent': 'ルーレット',
'roulette.tonight': '今夜はこれ…',
'roulette.nEps': '{n}話',
'roulette.perEp': '1話{duration}',
'roulette.stoppedAt': '第{ep}話まで見ています。',
'roulette.stoppedAtOf': '全{total}話中、第{ep}話まで見ています。',
'roulette.enjoy': '楽しんでね!',
'roulette.again': 'もう一回',
'roulette.spinning': '回転中…',
'roulette.spin': 'ルーレットを回す',
'roulette.poolSize_one': '{count}作品から選びます',
'roulette.poolSize_other': '{count}作品から選びます',
'roulette.empty': '条件に合う作品がありません。下のフィルターを広げてください。',
'roulette.inside': 'ルーレットの対象',
'roulette.pickFrom': '選ぶ対象',
'roulette.rewatchHint': '「もう一度見たい」=見終わった作品のうち、評価4/5以上・お気に入り・トップ5の作品です。',
'roulette.time': '使える時間(映画または1話)',
'roulette.seeItem': '詳細を見る',
'roulette.watchIt': 'これを見る',
'newEp.check': 'チェック',
'newEp.title': '新着',
'newEp.checking': '新着をチェック中…',
'newEp.needKey': '設定でTMDBキーを追加すると、新しいエピソードやシーズンをお知らせします。',
'newEp.nothing_one': 'フォロー中のドラマ・アニメに新着はありません。',
'newEp.nothing_other': 'フォロー中の{count}作品に新着はありません。',
'newEp.needKeyAlso': '(設定でTMDBキーを追加すると、ドラマもフォローできます。)',
'newEp.newSeason': '新シーズン',
'newEp.catchUp': '未視聴あり',
'newEp.soon': '近日公開',
'newEp.epWhen': '第{ep}話・{when}',
'newEp.available_one': '{count}話配信中',
'newEp.available_other': '{count}話配信中',
'newEp.next': '次回:第{ep}話・{when}',
'newEp.resume': '続きを見る',
'top.pick': '{rank}位を選ぶ',
'top.shareTitle': 'マイトップ5 {category}',
'top.shareLabel': 'このトップ5を画像でシェア',
'top.title': 'マイトップ',
'top.number': '{rank}位',
'top.pickFirst': '1位を選んでください。',
'top.editLabel': 'トップ5を編集',
'top.freeSlot': '空き枠 — 下から作品を選んでください',
'top.addFromLibrary': 'ライブラリから追加',
'top.allTypes': 'すべてのタイプ',
'top.searchTitle': '作品を検索…',
'top.full': 'トップ5が埋まっています。別の作品を追加するには1つ外してください。',
'top.noCandidates': '作品がありません。「すべてのタイプ」や別のキーワードで試してください。',
'reco.error': '現在、おすすめを読み込めません。',
'reco.title': 'おすすめ',
'reco.needKey': '設定でTMDBキーを追加すると、お気に入りの作品をもとにおすすめを表示します。',
'reco.other': '別の作品',
'reco.ifYouLiked': 'これが好きなら',
'reco.loading': 'おすすめを検索中…',
'reco.none': '似た作品はすべて追加済みです。「別の作品」を試してください。',
'reco.added': '{title}を追加しました',
'reco.addLabel': '{title}を見たいに追加',
'reco.addedShort': '追加済み',
'search.moviesSeries': '映画・ドラマ',
'search.offline': 'インターネットに接続されていません。検索にはネット接続が必要です。',
'search.fillFrom': 'データベースから入力',
'search.needKey': '映画やドラマを検索するには、設定で無料のTMDBキーを追加してください。',
'search.openSettings': '設定を開く',
'search.already': '追加済み',
'search.noResults': '結果がありません。下から手動で入力できます。',
'search.privacy': '{source}に送信されるのは検索したタイトルだけです。ライブラリはスマホに残ります。',
'catalog.sortRecent': '最近の更新順',
'catalog.sortWatched': '視聴日',
'catalog.sortRating': '評価が高い順',
'catalog.sortTitle': 'タイトル(A→Z)',
'catalog.pageTitle': 'マイ',
'catalog.pageAccent': 'カタログ',
'catalog.journalSubtitle': 'あなたの視聴履歴',
'catalog.filteredCount_one': '{count}作品(絞り込み中)',
'catalog.filteredCount_other': '{count}作品(絞り込み中)',
'catalog.titles': '作品',
'catalog.journal': '視聴記録',
'catalog.lists': 'リスト',
'catalog.searchPh': 'タイトル、ジャンル、配信サービス…',
'catalog.moreFilters': 'その他のフィルター',
'catalog.all': 'すべて',
'catalog.genre': 'ジャンル',
'catalog.minRating': '最低評価',
'catalog.allRatings': 'すべて',
'catalog.sortBy': '並べ替え',
'catalog.favorites': 'お気に入り',
'catalog.reset': 'リセット',
'catalog.noResults': '結果なし',
'catalog.nothingYet': 'まだ何もありません',
'catalog.noResultsHint': '別のキーワードで検索するか、フィルターを外してください。',
'catalog.nothingYetHint': '+ボタンで最初の作品を追加しましょう。',
'catalog.clearFilters': 'フィルターを解除',
'public.agree': 'みんなの評価とぴったり一致',
'public.more': 'みんなより+{gap}高い',
'public.less': 'みんなより−{gap}低い',
'public.label': 'みんな',
'public.me': 'わたし',
'public.added_one': 'みんなの評価を{count}件追加しました。',
'public.added_other': 'みんなの評価を{count}件追加しました。',
'public.noneFound': '新しい評価は見つかりませんでした。',
'public.fetch': '取得({n})',
'public.title': 'わたし vs みんな',
'public.hintFetch': '評価済み作品のTMDB / AniList平均評価を取得して、みんなとの違いを見てみましょう。',
'public.hintNone': 'この期間に評価した作品には、みんなの評価がありません。',
'public.hintKey': '設定でTMDBキーを追加する(またはAniListと連携したアニメを追加する)と、みんなと比較できます。',
'public.avgGap': '平均の差',
'public.average': '平均的',
'public.generous': 'みんなより甘め',
'public.harsh': 'みんなより辛め',
'public.agreeTitle': '一致',
'public.within5_one': '差が星½以内、{count}作品中',
'public.within5_other': '差が星½以内、{count}作品中',
'public.within10_one': '差が1点以内、{count}作品中',
'public.within10_other': '差が1点以内、{count}作品中',
'public.lovedPre': 'みんなより',
'public.lovedAccent': '高く評価',
'public.lovedPost': 'した作品',
'public.hatedPre': 'みんなより',
'public.hatedAccent': '低く評価',
'public.hatedPost': 'した作品',
'public.allAgree': 'すべての作品でみんなと同じ評価です。珍しい!',
'form.rewatchHint': 'もう一度見ましたか?再視聴を記録すると視聴記録に表示されます。',
'form.editTitle': '作品を',
'form.editAccent': '編集',
'form.newTitle': '新しい',
'form.newAccent': '作品',
'form.filledFrom': '取得元',
'form.canEdit': 'すべて編集できます',
'form.fillFromDb': 'TMDB / AniListから補完',
'form.pickPoster': 'ポスターを選ぶ',
'form.removeImage': '画像を削除',
'form.title': 'タイトル *',
'form.titlePh': '例:Your Name',
'form.originalTitle': '原題',
'form.originalTitlePh': '例:君の名は。',
'form.synopsis': 'あらすじ',
'form.type': 'タイプ',
'form.subtype': '詳細',
'form.subtypePh': 'ドキュメンタリー、リアリティ番組…',
'form.status': 'ステータス',
'form.myRating': 'マイ評価',
'form.favorite': 'お気に入り',
'form.criteria': '詳細評価(任意)',
'form.episodes': 'エピソード',
'form.minusEp': '-1話',
'form.plusEp': '+1話',
'form.total': '全話数',
'form.season': 'シーズン',
'form.minPerEp': '分/話',
'form.duration': '時間',
'form.durationMin': '上映時間(分)',
'form.info': '情報',
'form.start': '開始日・視聴日',
'form.end': '終了日',
'form.year': '年',
'form.platform': '配信サービス',
'form.genres': 'ジャンル・タグ',
'form.genresPh': 'ロマンス、SF…',
'form.rewatches': '再視聴',
'form.review': 'マイレビュー',
'form.reviewPh': '感想、印象に残ったシーン…',
'form.saveChanges': '変更を保存',
'form.addToLibrary': 'ライブラリに追加',
'form.shareImage': '画像でシェア',
'form.delete': 'この作品を削除',
'form.deleteConfirm': '「{title}」を完全に削除します。',
'form.removeRewatch': 'この再視聴を削除',
'form.rewatchDate': '再視聴日',
'form.reviewPublic': 'このレビューをプロフィールに表示',
'form.reviewPublicHint': '表示しない場合は、あなただけが見られます。',
'journal.rewatched': '再視聴',
'journal.started': '視聴開始',
'journal.emptyTitle': '視聴記録は空です',
'journal.emptyText': '作品に開始日や終了日を入力すると、ここに表示されます。',
'journal.seen_one': '{count}本視聴',
'journal.seen_other': '{count}本視聴',
'journal.more': '前の月を表示',
'stats.overview': '概要',
'stats.habits': '視聴傾向',
'stats.tastes': '好み',
'stats.pageTitle': 'マイ',
'stats.pageAccent': '統計',
'stats.emptyTitle': 'まだ統計がありません',
'stats.emptyText': '作品を追加すると表示されます。',
'stats.sinceStart': 'これまでの合計',
'stats.subtitle_one': 'ライブラリに{count}作品',
'stats.subtitle_other': 'ライブラリに{count}作品',
'stats.subtitleYear_one': '{year}年に{count}作品',
'stats.subtitleYear_other': '{year}年に{count}作品',
'stats.hours_one': '時間',
'stats.hours_other': '時間',
'stats.nonStopPre': 'ノンストップで',
'stats.nonStopPost': '分',
'stats.days_one': '{count}日',
'stats.days_other': '{count}日',
'stats.finishedN_one': '{count}本見終わった',
'stats.finishedN_other': '{count}本見終わった',
'stats.episodesN_one': '{count}話',
'stats.episodesN_other': '{count}話',
'stats.timeByType': 'タイプ別の視聴時間',
'stats.noTime': 'この期間の視聴時間はまだありません。',
'stats.avgRating': '平均評価',
'stats.rated_one': '{count}作品を評価',
'stats.rated_other': '{count}作品を評価',
'stats.inYear': '{year}年',
'stats.statuses': 'ステータス',
'stats.hoursTab': '時間',
'stats.monthByMonth': '月別・{year}年',
'stats.last12': '過去12か月',
'stats.monthFinished_one': '{count}作品を見終わった',
'stats.monthFinished_other': '{count}作品を見終わった',
'stats.busiest': '一番見た月:',
'stats.records': '記録',
'stats.marathon': '最長の一気見',
'stats.longestFilm': '最長の映画',
'stats.noRecords': 'この期間の記録はまだありません。',
'stats.platforms': '配信サービス',
'stats.bestRated': '高評価の作品',
'stats.myRatings': 'マイ評価',
'stats.noRatings': 'この期間の評価はありません。',
'stats.favGenres': '好きなジャンル',
'stats.noGenres': 'まだジャンルがありません。',
'stats.countries': '国',
'stats.noCountry_one': '国が未設定の作品が{count}件あります。作品ページの「TMDB / AniListから補完」で追加してください。',
'stats.noCountry_other': '国が未設定の作品が{count}件あります。作品ページの「TMDB / AniListから補完」で追加してください。',
'stats.noCountryLegacy_one': '国が未設定の作品が{count}件あります。作品ページの「TMDB / AniListから補完」で追加するか、旧アプリのバックアップを再インポート(「統合」)してください。',
'stats.noCountryLegacy_other': '国が未設定の作品が{count}件あります。作品ページの「TMDB / AniListから補完」で追加するか、旧アプリのバックアップを再インポート(「統合」)してください。',
'stats.byType': 'タイプ別',
'stats.footnote': '視聴時間は視聴したエピソード数と入力された上映時間から推定しています(未入力の場合:映画1時間50分、アニメ1話24分、ドラマ45分、韓国ドラマ1時間、中国ドラマ45分)。作品は見終わった年にカウントされます。',
'stats.ratedAs_one': '評価{rating}',
'stats.ratedAs_other': '評価{rating}',
'backup.shareTitle': 'AzuuCineのバックアップ',
'backup.tooBig': 'ファイルが大きすぎます(最大30 MB)。',
'backup.notJson': 'このファイルは有効なJSONではありません。',
'backup.noItems': 'このファイルに作品データが見つかりません。',
'backup.tooMany': '作品数が多すぎます(最大{n}件)。',
'image.canvas': 'Canvasが使用できません',
'image.unreadable': '画像を読み込めません',
'image.notImage': 'このファイルは画像ではありません。',
'image.tooBig': '画像が大きすぎます(最大25 MB)。',
'social.err.server': 'サーバーが{status}を返しました。',
'social.err.usernameTaken': 'このユーザー名はすでに使われています。',
'social.err.usernameReserved': 'このユーザー名は使用できません。',
'social.err.invalid': '入力内容に無効な値があります。',
'social.inLibrary': 'ライブラリにあります',
'social.addToWatch': '「見たい」に追加',
'social.linkCopied': 'リンクをコピーしました!',
'social.profile': 'プロフィール',
'social.shareProfile': 'プロフィールをシェア',
'social.loading': '読み込み中…',
'social.loadError': 'プロフィールを読み込めません。',
'social.notFound': 'プロフィールが見つかりません',
'social.notFoundHint': '@{username}というプロフィールは存在しません。',
'social.editProfile': 'プロフィールを編集',
'social.following': 'フォロー中',
'social.requested': 'リクエスト済み',
'social.followBack': 'フォローバック',
'social.follow': 'フォロー',
'social.private': '非公開アカウント',
'social.followsYou': 'フォローされています',
'social.seen': '視聴済み',
'social.followers_one': 'フォロワー',
'social.followers_other': 'フォロワー',
'social.followingCount_one': 'フォロー',
'social.followingCount_other': 'フォロー',
'social.requests_one': 'フォローリクエスト{count}件',
'social.requests_other': 'フォローリクエスト{count}件',
'social.privateTitle': 'このアカウントは非公開です',
'social.privateText': 'フォローすると、視聴記録や評価、トップ5が見られます。',
'social.tabProfile': 'プロフィール',
'social.tabLibrary': 'ライブラリ',
'social.cancelRequestTitle': 'フォローリクエストを取り消しますか?',
'social.unfollowTitle': '{name}のフォローを解除しますか?',
'social.unfollowPrivate': 'このアカウントは非公開です。再びプロフィールを見るには、もう一度リクエストが必要です。',
'social.cancelRequest': 'リクエストを取り消す',
'social.unfollow': 'フォロー解除',
'social.top5': 'トップ5',
'social.recent': '最近見た作品',
'social.noRecent': 'まだ見終わった作品はありません。',
'social.statYear': '今年見た作品',
'social.statFilms': '見た映画',
'social.statSeries': '見たドラマ・アニメ',
'social.emptyLibrary': 'ここには作品がありません。',
'social.loadMore': 'もっと見る',
'social.changeBanner': 'バナーを変更',
'social.changeAvatar': '写真を変更',
'social.removeAvatar': '写真を削除',
'social.removeBanner': 'バナーを削除',
'social.displayName': '表示名',
'social.username': 'ユーザー名',
'social.usernameRule': '3〜20文字:半角小文字、数字、_',
'social.bio': '自己紹介',
'social.bioPh': '好きな作品や好きなジャンルなど…',
'social.privateAccount': '非公開アカウント',
'social.privateHint': 'あなたが承認したフォロワーだけが視聴記録を見られます。',
'social.publicHint': '名前、ユーザー名、写真、バナー、自己紹介はすべてのメンバーに公開されます。書いたレビューは非公開のままです(プロフィールに表示すると選んだものを除く)。',
'social.requestsTab_one': 'リクエスト',
'social.requestsTab_other': 'リクエスト({count})',
'social.noFollowing': 'まだ誰もフォローしていません。',
'social.noFollowers': 'まだフォロワーはいません。',
'social.accept': '承認',
'social.decline': '拒否',
'social.removeFollower': '削除',
'social.findFriends': '友だちを探す',
'social.searchPh': 'ユーザー名または名前…',
'social.noResults': '該当するユーザーはいません。',
'social.inviteHint': '友だちがまだAzuuCineを使っていませんか?プロフィールのリンクを送りましょう。',
'social.shareMyProfile': 'マイプロフィールをシェア',
'social.inviteText': 'AzuuCineでフォローしてね!',
'social.myProfile': 'マイプロフィール',
'feed.title': 'フォロー中',
'feed.empty': '友だちをフォローすると、見ている作品や感想がここに表示されます。',
'feed.finished': 'が観た:',
'feed.started': 'が見始めた:',
'feed.rewatched': 'が再視聴:',
'feed.added': 'が見たい:',
'feed.review': 'レビュー',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** 한국어 */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': '취소',
'common.confirm': '확인',
'common.close': '닫기',
'common.save': '저장',
'common.add': '추가',
'common.delete': '삭제',
'common.all': '전체',
'common.none': '없음',
'common.noData': '아직 데이터가 없어요.',
'common.retry': '다시 시도',
'common.back': '뒤로',
'common.offline': '인터넷에 연결되어 있지 않아요.',
'common.minutes': '{n}분',
'common.hours': '{h}시간',
'common.hoursMinutes': '{h}시간 {m}분',
'common.daysHours': '{d}일 {h}시간',
'common.decimalSep': '.',
'common.removeX': '{name} 빼기',
'common.kb': '{n}KB',
'common.mb': '{n}MB',
'common.edit': '수정',
'common.moveUp': '위로 이동',
'common.moveDown': '아래로 이동',
'nav.home': '홈',
'nav.catalog': '카탈로그',
'nav.stats': '통계',
'nav.settings': '설정',
'nav.addTitle': '작품 추가',
'type.film': '영화',
'type.serie': '시리즈',
'type.anime': '애니',
'type.kdrama': 'K-드라마',
'type.cdrama': 'C-드라마',
'type.autre': '기타',
'typePlural.film': '영화',
'typePlural.serie': '시리즈',
'typePlural.anime': '애니',
'typePlural.kdrama': 'K-드라마',
'typePlural.cdrama': 'C-드라마',
'status.a_voir': '볼 예정',
'status.en_cours': '보는 중',
'status.termine': '다 봤어요',
'status.pause': '잠시 멈춤',
'status.abandonne': '하차',
'criteria.story': '각본 / 스토리',
'criteria.cast': '캐릭터 / 캐스팅',
'criteria.direction': '연출 / 작화',
'criteria.ost': '음악 (OST)',
'subtype.documentary': '다큐멘터리',
'subtype.reality': '리얼리티',
'subtype.show': '예능',
'subtype.short': '단편 영화',
'subtype.stage': '공연',
'subtype.miniseries': '미니시리즈',
'platform.cinema': '극장',
'platform.dvd': 'DVD / 블루레이',
'platform.tv': 'TV',
'genre.action': '액션',
'genre.adventure': '어드벤처',
'genre.comedy': '코미디',
'genre.drama': '드라마',
'genre.romance': '로맨스',
'genre.romcom': '로코',
'genre.thriller': '스릴러',
'genre.horror': '공포',
'genre.mystery': '미스터리',
'genre.crime': '범죄',
'genre.scifi': 'SF',
'genre.fantasy': '판타지',
'genre.historical': '사극',
'genre.sliceOfLife': '일상',
'genre.shonen': '소년',
'genre.shojo': '소녀',
'genre.seinen': '청년',
'genre.isekai': '이세계',
'genre.mecha': '메카',
'genre.sports': '스포츠',
'genre.musical': '뮤지컬',
'genre.medical': '메디컬',
'genre.legal': '법정',
'genre.wuxia': '무협',
'genre.xianxia': '선협',
'genre.family': '가족',
'genre.animation': '애니메이션',
'genre.psychological': '심리',
'genre.supernatural': '초자연',
'genre.romanticComedy': '로맨틱 코미디',
'genre.documentary': '다큐멘터리',
'genre.war': '전쟁',
'genre.western': '서부',
'genre.music': '음악',
'genre.ecchi': '에치',
'genre.kids': '키즈',
'genre.news': '뉴스',
'genre.reality': '리얼리티',
'genre.talk': '토크쇼',
'genre.soap': '연속극',
'genre.politics': '정치',
'genre.tvMovie': 'TV 영화',
'genre.anime': '애니',
'genre.magicalGirl': '마법소녀',
'confirm.title': '정말 진행할까요?',
'err.tmdbRefused': 'TMDB 요청이 거부됐어요.',
'err.tmdbKeyRefused': 'TMDB 키가 거부됐어요. 설정에서 확인해 주세요.',
'err.tmdbStatus': 'TMDB 응답: {status}',
'err.tmdbRef': 'TMDB 참조가 올바르지 않아요.',
'err.anilistRate': 'AniList 요청 한도에 걸렸어요. 1분 뒤에 다시 시도해 주세요.',
'err.anilistStatus': 'AniList 응답: {status}',
'err.searchRate': '검색이 너무 많아요. 몇 분 뒤에 다시 시도해 주세요.',
'anilist.short': '단편 애니',
'anilist.movie': '애니메이션 영화',
'anilist.special': '스페셜',
'anilist.music': '뮤직비디오',
'release.cinema': '극장 개봉',
'release.online': 'VOD / 스트리밍',
'release.release': '공개',
'release.season': '시즌 {season}',
'release.episode': '{ep}화',
'release.newEpisode': '새 에피소드',
'release.firstEpisode': '첫 방송',
'release.newSeriesN': '새 시리즈 · {count}화',
'release.seasonN': '시즌 {season} · {count}화',
'release.seasonEp1': '시즌 {season} · 1화',
'release.episodes': '{first}–{last}화',
'release.sEpisodes': 'S{season} · {first}–{last}화',
'release.sEpisode': 'S{season} · {ep}화',
'release.episodeFinal': '{ep}화 · 최종화',
'release.filmJapan': '일본 개봉 영화',
'card.ep': '{n}화',
'card.plusOne': '{title} +1화',
'card.open': '{title} 열기',
'rating.outOf10': '10점 만점 평점',
'rating.stars_one': '별 {count}개',
'rating.stars_other': '별 {count}개',
'rating.clear': '평점 지우기',
'share.previewLabel': '이미지 미리보기',
'share.preview': '미리보기',
'share.posterAlt': '{title} 포스터',
'share.share': '공유',
'share.saveImage': '이미지 저장',
'share.err.create': '이미지를 만들 수 없어요',
'share.minutesLong': '{n}분',
'share.createdBy': '제작',
'share.directedBy': '감독',
'share.producedBy': '프로듀서',
'share.starring': '출연',
'share.genres': '장르',
'share.myRating': '내 평점',
'share.myTop': '나의 TOP',
'auth.hidePassword': '비밀번호 숨기기',
'auth.showPassword': '비밀번호 보기',
'auth.mismatch': '두 비밀번호가 일치하지 않아요.',
'auth.created': '계정이 만들어졌어요! {email}(으)로 보낸 링크를 열어 계정을 활성화한 뒤 로그인해 주세요.',
'auth.resetSent': '이 주소로 가입된 계정이 있다면 새 비밀번호를 설정할 수 있는 링크를 보냈어요.',
'auth.tagline': '영화, 시리즈, 애니, 드라마를 기록하는 나만의 일지.',
'auth.loginTab': '로그인',
'auth.signupTab': '회원가입',
'auth.forgotTitle': '비밀번호 찾기',
'auth.email': '이메일 주소',
'auth.password': '비밀번호',
'auth.confirmPassword': '비밀번호 확인',
'auth.minChars': '{n}자 이상 입력해 주세요.',
'auth.login': '로그인',
'auth.signup': '계정 만들기',
'auth.sendLink': '링크 보내기',
'auth.forgot': '비밀번호를 잊으셨나요?',
'auth.backToLogin': '로그인으로 돌아가기',
'auth.privacy': '데이터는 내 계정에 연결되며 나만 볼 수 있어요. 인터넷 없이도 쓸 수 있도록 기기에도 저장돼요.',
'auth.newPasswordTitle': '새 비밀번호를 정해 주세요.',
'auth.newPassword': '새 비밀번호',
'auth.err.credentials': '이메일 또는 비밀번호가 올바르지 않아요.',
'auth.err.notConfirmed': '먼저 이메일로 받은 링크로 주소를 인증해 주세요.',
'auth.err.exists': '이미 이 이메일로 가입된 계정이 있어요.',
'auth.err.weak': '비밀번호가 너무 약해요 ({n}자 이상, 영문과 숫자를 섞어 주세요).',
'auth.err.samePassword': '새 비밀번호는 이전 비밀번호와 달라야 해요.',
'auth.err.emailRate': '요청이 너무 많아요. 몇 분 뒤에 다시 시도해 주세요.',
'auth.err.rate': '시도 횟수가 너무 많아요. 몇 분 뒤에 다시 시도해 주세요.',
'auth.err.signupDisabled': '지금은 회원가입을 받지 않고 있어요.',
'auth.err.emailInvalid': '이메일 주소가 올바르지 않아요.',
'auth.err.invalid': '이메일 주소 또는 비밀번호가 올바르지 않아요.',
'auth.err.session': '세션이 만료됐어요. 다시 로그인해 주세요.',
'auth.err.status': '서버가 요청을 거부했어요 ({status}).',
'auth.err.response': '서버 응답이 올바르지 않아요.',
'auth.err.linkExpired': '링크가 만료됐어요. 새 링크를 요청해 주세요.',
'auth.err.linkUsed': '유효하지 않거나 이미 사용된 링크예요.',
'auth.err.linkInvalid': '유효하지 않은 링크예요.',
'settings.language': '언어',
'settings.backupShared': '백업을 공유했어요.',
'settings.backupDownloaded': '백업을 다운로드했어요.',
'settings.exportFailed': '내보내기에 실패했어요.',
'settings.noValidItems': '파일에 유효한 항목이 없어요.',
'settings.imported_one': '{count}개 항목을 가져왔어요.',
'settings.imported_other': '{count}개 항목을 가져왔어요.',
'settings.importedSkipped': '{n}개 항목을 가져왔고, {skipped}개는 건너뛰었어요.',
'settings.cleared': '라이브러리를 비웠어요.',
'settings.pageTitle': '내 ',
'settings.pageAccent': '설정',
'settings.languageHint': '앱, 날짜, TMDB에서 가져오는 정보(제목, 줄거리)에 적용되는 언어예요.',
'settings.rating': '평점',
'settings.scale5': '★ 5점 만점',
'settings.scale10': '10점 만점',
'settings.ratingHint': '5점 만점은 별 반 개 단위, 10점 만점은 0.5점 단위예요. 기존 평점은 자동으로 변환돼요.',
'settings.theme': '테마',
'settings.themeX': '{name} 테마',
'settings.pickColor': '원하는 색 고르기',
'settings.freeColor': '사용자 지정 색',
'settings.freeColorHint': '어떤 색이든 괜찮아요. 글자 색이 자동으로 맞춰져 잘 읽혀요.',
'settings.databases': '작품 데이터베이스',
'settings.anilistActive': '애니 · 사용 중',
'settings.noConfig': '따로 설정할 필요 없어요.',
'settings.tmdbActive': '영화 & 시리즈 · 사용 중',
'settings.checking': '확인 중…',
'settings.offline': '오프라인',
'settings.proxyMissingKey': 'TMDB 키 없음',
'settings.proxyNotDeployed': '서버 미설치',
'settings.unavailable': '사용 불가',
'settings.proxyMissingKeyHint': '서버 함수는 준비됐지만 TMDB 키가 등록되지 않았거나(Supabase의 TMDB_API_KEY 시크릿) TMDB에서 거부됐어요.',
'settings.proxyNotDeployedHint': '‘tmdb’ 함수가 아직 Supabase에 배포되지 않았어요 (README → 계정, 5단계 참고).',
'settings.proxyErrorHint': '지금은 서버가 제대로 응답하지 않아요.',
'settings.proxyOkHint': '앱 서버에서 제공돼요. 키를 입력할 필요 없어요.',
'settings.recheck': '다시 확인',
'settings.keyRefused': '키 거부됨',
'settings.notConfigured': '설정 안 됨',
'settings.tmdbHelp': '영화, 시리즈, K-드라마, C-드라마용이에요. themoviedb.org에서 무료 계정을 만든 뒤 설정 → API에서 ‘API 키’ 또는 ‘API 읽기 액세스 토큰’을 복사해 붙여 넣으세요.',
'settings.tmdbKey': 'TMDB 키',
'settings.hideKey': '키 숨기기',
'settings.showKey': '키 보기',
'settings.validate': '확인',
'settings.remove': '삭제',
'settings.keyLocal': '키는 이 기기에만 저장되고 백업에는 절대 포함되지 않아요.',
'settings.topHint': '홈에 표시할 카테고리예요.',
'settings.topNone': '카테고리가 없어서 TOP 5 섹션이 숨겨져요.',
'settings.backup': '백업',
'settings.export': '데이터 내보내기',
'settings.exportHint_one': '{count}개 항목 · JSON 파일, 주기적으로 해 두세요',
'settings.exportHint_other': '{count}개 항목 · JSON 파일, 주기적으로 해 두세요',
'settings.import': '백업 가져오기',
'settings.importHint': '.json 파일에서 복원',
'settings.legacyDetected': '이전 앱의 백업이에요',
'settings.found_one': '{count}개 항목을 찾았어요. 어떻게 가져올까요?',
'settings.found_other': '{count}개 항목을 찾았어요. 어떻게 가져올까요?',
'settings.foundSkipped': '{n}개 항목을 찾았어요 (유효하지 않은 {skipped}개는 건너뜀). 어떻게 가져올까요?',
'settings.merge': '병합',
'settings.replaceAll': '전부 바꾸기',
'settings.mergeHint': '‘병합’은 새 항목을 추가하고, 이미 있는 항목(같은 ID)은 업데이트해요.',
'settings.storage': '저장 공간',
'settings.used': '사용 중인 공간',
'settings.storageCloud': '데이터는 내 계정에 저장되고, 인터넷 없이도 쓸 수 있도록 이 기기에도 보관돼요. 네트워크에 연결되면 자동으로 동기화돼요.',
'settings.storageLocal': '데이터는 이 기기의 이 브라우저에만 저장돼요. 브라우저 데이터를 지우거나 앱을 삭제하면 사라지니까 주기적으로 백업을 내보내 주세요.',
'settings.danger': '위험 구역',
'settings.clearAll': '라이브러리 전체 삭제',
'settings.clearAllHint_one': '작품 {count}개',
'settings.clearAllHint_other': '작품 {count}개',
'settings.clearAllHintCloud_one': '작품 {count}개 · 모든 기기에서',
'settings.clearAllHintCloud_other': '작품 {count}개 · 모든 기기에서',
'settings.deleting': '삭제 중…',
'settings.deleteAccount': '계정 삭제',
'settings.deleteAccountHint': '계정과 데이터가 영구적으로 삭제돼요',
'settings.footerCloud': '계정 동기화',
'settings.footerLocal': '100% 로컬',
'settings.clearConfirm_one': '작품 {count}개가 영구적으로 삭제돼요. 그 전에 백업을 내보내 두세요.',
'settings.clearConfirm_other': '작품 {count}개가 모두 영구적으로 삭제돼요. 그 전에 백업을 내보내 두세요.',
'settings.clearConfirmCloud_one': '작품 {count}개가 모든 기기에서 영구적으로 삭제돼요. 그 전에 백업을 내보내 두세요.',
'settings.clearConfirmCloud_other': '작품 {count}개가 모든 기기에서 모두 영구적으로 삭제돼요. 그 전에 백업을 내보내 두세요.',
'settings.clearAllConfirm': '전부 삭제',
'settings.deleteAccountTitle': '계정을 삭제할까요?',
'settings.deleteAccountMessage': '계정과 모든 데이터(작품, 리스트, 설정)가 서버와 이 기기에서 영구적으로 삭제돼요. 그 전에 백업을 내보내 두세요. 되돌릴 수 없어요.',
'settings.deleteForever': '영구 삭제',
'settings.replaceConfirm': '지금 라이브러리 전체가 이 파일의 내용으로 바뀌어요.',
'settings.replace': '바꾸기',
'sync.err.push': '업로드 거부됨 ({status})',
'sync.err.pull': '불러오기 거부됨 ({status})',
'store.dbError': '로컬 데이터베이스를 열 수 없어요: {error}',
'store.invalidItem': '유효하지 않은 항목',
'lists.newList': '새 리스트',
'lists.newListPh': '새 리스트…',
'lists.myLists': '내 리스트',
'lists.rename': '이름 바꾸기',
'lists.delete': '리스트 삭제',
'lists.done': '완료',
'lists.addRemove': '작품 추가 / 빼기',
'lists.searchLibrary': '내 라이브러리에서 검색…',
'lists.emptyTitle': '빈 리스트',
'lists.emptyText': '위 버튼이나 작품 정보 화면에서 작품을 추가해 보세요.',
'lists.deleteConfirm': '‘{name}’ 리스트가 삭제돼요. 작품은 라이브러리에 그대로 남아요.',
'lists.noneTitle': '아직 리스트가 없어요',
'lists.noneText': '나만의 리스트를 만들어 보세요: ‘친구들이랑 볼 것’, ‘10월 공포 영화’, ‘힐링 드라마’…',
'lists.create': '만들기',
'account.err.deleteRate': '시도 횟수가 너무 많아요. 1분 뒤에 다시 시도해 주세요.',
'account.err.delete': '삭제에 실패했어요. 나중에 다시 시도해 주세요.',
'account.title': '내 계정',
'account.syncing': '동기화 중…',
'account.offline': '오프라인 — 모든 데이터는 이 기기에 저장돼 있어요',
'account.syncError': '지금은 동기화할 수 없어요',
'account.synced': '{when} 동기화됨',
'account.passwordChanged': '비밀번호를 변경했어요.',
'account.imported_one': '작품 {count}개를 계정에 추가했어요.',
'account.imported_other': '작품 {count}개를 계정에 추가했어요.',
'account.importFailed': '가져오기에 실패했어요.',
'account.pending_one': '{count}개 대기 중',
'account.pending_other': '{count}개 대기 중',
'account.syncNow': '지금 동기화',
'account.newPasswordPh': '새 비밀번호 (최소 {n}자)',
'account.changePassword': '비밀번호 변경',
'account.logout': '로그아웃',
'account.logoutHint': '데이터는 계정에 그대로 남고 이 기기에서만 지워져요.',
'account.ignore': '무시',
'account.deviceHint': '계정으로 옮겨져 모든 기기에 동기화돼요.',
'account.unsentTitle': '전송되지 않은 변경 사항',
'account.logoutAnyway': '그래도 로그아웃',
'account.unsentMessage_one': '변경 사항 {count}개가 아직 전송되지 않았어요 (인터넷 연결을 확인해 주세요). 지금 로그아웃하면 사라져요.',
'account.unsentMessage_other': '변경 사항 {count}개가 아직 전송되지 않았어요 (인터넷 연결을 확인해 주세요). 지금 로그아웃하면 사라져요.',
'account.nTitles_one': '작품 {count}개',
'account.nTitles_other': '작품 {count}개',
'account.nLists_one': '리스트 {count}개',
'account.nLists_other': '리스트 {count}개',
'account.deviceData': '이 기기에 계정을 만들기 전에 추가한 {titles}가 있어요. 계정에 추가할까요?',
'account.deviceDataWithLists': '이 기기에 계정을 만들기 전에 추가한 {titles}와 {lists}가 있어요. 계정에 추가할까요?',
'time.never': '없음',
'time.justNow': '방금',
'time.minutesAgo': '{n}분 전',
'time.hoursAgo': '{n}시간 전',
'time.onDate': '{date}',
'time.today': '오늘',
'time.tomorrow': '내일',
'time.daysAgo': '{n}일 전',
'theme.red': '빨강',
'theme.orange': '주황',
'theme.yellow': '노랑',
'theme.lime': '라임',
'theme.green': '초록',
'theme.mint': '민트',
'theme.cyan': '청록',
'theme.blue': '파랑',
'theme.indigo': '남색',
'theme.violet': '보라',
'theme.pink': '분홍',
'theme.white': '하양',
'home.seeAll': '전체 보기',
'home.subtitle': '나의 시청 일지',
'home.calendarSoon_one': '공개 캘린더: 이번 주 {count}개',
'home.calendarSoon_other': '공개 캘린더: 이번 주 {count}개',
'home.emptyTitle': '라이브러리가 비어 있어요',
'home.emptyCloud': '첫 영화, 애니, 드라마를 추가해 보세요. 내 계정에 저장돼요.',
'home.emptyLocal': '첫 영화, 애니, 드라마를 추가해 보세요. 모든 데이터는 이 휴대폰에만 저장돼요.',
'home.completed': '다 본 작품',
'home.thisYear_one': '올해 {count}개',
'home.thisYear_other': '올해 {count}개',
'home.toWatchN_one': '볼 예정 {count}개',
'home.toWatchN_other': '볼 예정 {count}개',
'home.screenTime': '시청 시간',
'home.estimate': '추정치',
'home.episodesSeen': '본 에피소드',
'home.noIdea': '뭘 볼지 고민돼요?',
'home.rouletteHint_one': '볼 예정인 작품 중에서 뽑기',
'home.rouletteHint_other': '볼 예정인 작품 {count}개 중에서 뽑기',
'home.rouletteHintAll': '라이브러리 전체에서 뽑기',
'home.recentlyFinished': '최근에 다 본 작품',
'calendar.title': '공개 캘린더',
'calendar.inMyList': '내 리스트에 있음',
'calendar.inMyListLegend': '내 리스트에 있음',
'calendar.seeMore_one': '1개 더 보기',
'calendar.seeMore_other': '{count}개 더 보기',
'calendar.heading': '공개 ',
'calendar.headingAccent': '캘린더',
'calendar.refresh': '새로고침',
'calendar.all': '모든 공개작',
'calendar.mine': '내 작품',
'calendar.prevMonth': '이전 달',
'calendar.nextMonth': '다음 달',
'calendar.releases_one': '공개 {count}건',
'calendar.releases_other': '공개 {count}건',
'calendar.others': '다른 공개작',
'calendar.needKey': 'TMDB 키가 없으면 애니만 표시돼요. 설정에서 키를 추가하면 영화, 시리즈, 드라마도 볼 수 있어요.',
'calendar.range': '지난달부터 6개월 뒤까지의 공개 일정을 볼 수 있어요.',
'calendar.failed': '일부 공개 일정을 불러오지 못했어요. ↻로 다시 시도해 주세요.',
'calendar.nothingThatDay': '이날은 예정된 게 없어요.',
'calendar.next14': '앞으로 14일',
'calendar.loading': '공개 일정을 찾는 중…',
'calendar.noneMine14': '앞으로 14일 동안 내 작품의 공개 소식이 없어요.',
'calendar.noneMineMonth': '이번 달에는 내 작품의 공개 소식이 없어요.',
'calendar.none14': '앞으로 14일 동안 공개 일정이 없어요.',
'calendar.noneMonth': '이번 달 공개 일정을 찾지 못했어요.',
'calendar.footer': '내 나라의 극장 개봉 영화, 인기 시리즈와 드라마(TMDB), 일본에서 방영 중인 모든 애니(AniList)의 에피소드예요. 내 라이브러리에 있는 작품은 색으로 표시돼요. ‘볼 예정’을 누르면 리스트에 추가할 수 있어요.',
'roulette.name': '룰렛',
'roulette.rewatch': '다시 볼 작품',
'roulette.anyTime': '상관없음',
'roulette.heading': '오늘의 ',
'roulette.headingAccent': '룰렛',
'roulette.tonight': '오늘 밤 볼 작품은…',
'roulette.nEps': '{n}화',
'roulette.perEp': '화당 {duration}',
'roulette.stoppedAt': '{ep}화까지 봤어요.',
'roulette.stoppedAtOf': '{total}화 중 {ep}화까지 봤어요.',
'roulette.enjoy': '즐겁게 보세요!',
'roulette.again': '다시 돌리기',
'roulette.spinning': '돌아가는 중…',
'roulette.spin': '룰렛 돌리기',
'roulette.poolSize_one': '작품 {count}개 중에서 뽑기',
'roulette.poolSize_other': '작품 {count}개 중에서 뽑기',
'roulette.empty': '조건에 맞는 작품이 없어요. 아래 필터를 넓혀 보세요.',
'roulette.inside': '룰렛에 넣을 작품',
'roulette.pickFrom': '뽑을 범위',
'roulette.rewatchHint': '‘다시 볼 작품’ = 다 본 작품 중 4/5점 이상, 최애 작품, TOP 5예요.',
'roulette.time': '볼 수 있는 시간 (영화 또는 1화)',
'roulette.seeItem': '작품 정보 전체 보기',
'roulette.watchIt': '이거 볼래요',
'newEp.check': '확인',
'newEp.title': '새 소식',
'newEp.checking': '새로 나온 게 있는지 보는 중…',
'newEp.needKey': '설정에서 TMDB 키를 추가하면 새 에피소드와 새 시즌 소식을 받을 수 있어요.',
'newEp.nothing_one': '보고 있는 시리즈나 애니에 새 소식이 없어요.',
'newEp.nothing_other': '보고 있는 시리즈와 애니 {count}개에 새 소식이 없어요.',
'newEp.needKeyAlso': '(설정에서 TMDB 키를 추가하면 시리즈와 드라마도 챙겨 볼 수 있어요.)',
'newEp.newSeason': '새 시즌',
'newEp.catchUp': '따라잡기',
'newEp.soon': '곧 공개',
'newEp.epWhen': '{ep}화 {when}',
'newEp.available_one': '{count}화 시청 가능',
'newEp.available_other': '{count}화 시청 가능',
'newEp.next': '다음: {ep}화 {when}',
'newEp.resume': '이어 보기',
'top.pick': '{rank}위 고르기',
'top.shareTitle': '나의 {category} TOP 5',
'top.shareLabel': '이 TOP 5를 이미지로 공유',
'top.title': '나의 TOP',
'top.number': '{rank}위',
'top.pickFirst': '1위를 골라 주세요.',
'top.editLabel': 'TOP 5 수정',
'top.freeSlot': '빈자리 — 아래에서 작품을 골라 주세요',
'top.addFromLibrary': '내 라이브러리에서 추가',
'top.allTypes': '모든 유형',
'top.searchTitle': '작품 검색…',
'top.full': 'TOP 5가 꽉 찼어요. 다른 작품을 넣으려면 하나를 빼 주세요.',
'top.noCandidates': '작품이 없어요. ‘모든 유형’을 선택하거나 다르게 검색해 보세요.',
'reco.error': '지금은 추천을 불러올 수 없어요.',
'reco.title': '추천',
'reco.needKey': '설정에서 TMDB 키를 추가하면 좋아하는 작품을 바탕으로 추천을 받을 수 있어요.',
'reco.other': '다른 작품',
'reco.ifYouLiked': '이 작품을 좋아했다면',
'reco.loading': '추천 작품을 찾는 중…',
'reco.none': '이 작품과 비슷한 건 이미 다 있어요. ‘다른 작품’을 눌러 보세요.',
'reco.added': '{title} 추가됨',
'reco.addLabel': '{title}을(를) 볼 예정에 추가',
'reco.addedShort': '추가됨',
'search.moviesSeries': '영화 & 시리즈',
'search.offline': '인터넷에 연결되어 있지 않아요. 검색하려면 네트워크가 필요해요.',
'search.fillFrom': '데이터베이스에서 채우기',
'search.needKey': '영화, 시리즈, 드라마를 검색하려면 설정에서 무료 TMDB 키를 추가해 주세요.',
'search.openSettings': '설정 열기',
'search.already': '이미 추가됨',
'search.noResults': '결과가 없어요. 아래에서 직접 입력할 수 있어요.',
'search.privacy': '검색한 제목만 {source}(으)로 전송돼요. 라이브러리는 휴대폰에 그대로 남아요.',
'catalog.sortRecent': '최근 수정순',
'catalog.sortWatched': '시청 날짜순',
'catalog.sortRating': '평점 높은 순',
'catalog.sortTitle': '제목순 (A→Z)',
'catalog.pageTitle': '내 ',
'catalog.pageAccent': '카탈로그',
'catalog.journalSubtitle': '나의 시청 기록',
'catalog.filteredCount_one': '작품 {count}개 (필터 적용)',
'catalog.filteredCount_other': '작품 {count}개 (필터 적용)',
'catalog.titles': '작품',
'catalog.journal': '일지',
'catalog.lists': '리스트',
'catalog.searchPh': '제목, 장르, 플랫폼…',
'catalog.moreFilters': '필터 더 보기',
'catalog.all': '전체',
'catalog.genre': '장르',
'catalog.minRating': '최소 평점',
'catalog.allRatings': '전체',
'catalog.sortBy': '정렬',
'catalog.favorites': '최애',
'catalog.reset': '초기화',
'catalog.noResults': '결과 없음',
'catalog.nothingYet': '아직 아무것도 없어요',
'catalog.noResultsHint': '다르게 검색하거나 필터를 줄여 보세요.',
'catalog.nothingYetHint': '+ 버튼으로 첫 작품을 추가해 보세요.',
'catalog.clearFilters': '필터 지우기',
'public.agree': '관객 평가와 딱 일치',
'public.more': '관객보다 +{gap}',
'public.less': '관객보다 −{gap}',
'public.label': '관객',
'public.me': '나',
'public.added_one': '관객 평점 {count}개를 추가했어요.',
'public.added_other': '관객 평점 {count}개를 추가했어요.',
'public.noneFound': '새 평점을 찾지 못했어요.',
'public.fetch': '가져오기 ({n})',
'public.title': '나 vs 관객',
'public.hintFetch': '평점을 매긴 작품의 TMDB / AniList 평균 평점을 가져와서 내 취향이 관객과 어디서 갈리는지 확인해 보세요.',
'public.hintNone': '이 기간에 평점을 매긴 작품 중 관객 평점이 있는 작품이 없어요.',
'public.hintKey': '설정에서 TMDB 키를 추가하면(또는 AniList와 연결된 애니가 있으면) 관객과 비교할 수 있어요.',
'public.avgGap': '평균 차이',
'public.average': '평균 수준',
'public.generous': '관객보다 후한 편',
'public.harsh': '관객보다 깐깐한 편',
'public.agreeTitle': '의견 일치',
'public.within5_one': '작품 {count}개 중 별 ½개 이내',
'public.within5_other': '작품 {count}개 중 별 ½개 이내',
'public.within10_one': '작품 {count}개 중 1점 이내',
'public.within10_other': '작품 {count}개 중 1점 이내',
'public.lovedPre': '관객보다 ',
'public.lovedAccent': '더 좋아한',
'public.lovedPost': ' 작품',
'public.hatedPre': '관객보다 ',
'public.hatedAccent': '덜 좋아한',
'public.hatedPost': ' 작품',
'public.allAgree': '모든 작품에서 관객과 의견이 같아요. 흔치 않은 일이에요!',
'form.rewatchHint': '다시 봤나요? 다시 본 기록을 남기면 일지에 표시돼요.',
'form.editTitle': '작품 정보 ',
'form.editAccent': '수정',
'form.newTitle': '새 ',
'form.newAccent': '작품',
'form.filledFrom': '가져온 곳',
'form.canEdit': '모두 수정할 수 있어요',
'form.fillFromDb': 'TMDB / AniList에서 채우기',
'form.pickPoster': '포스터 선택',
'form.removeImage': '이미지 삭제',
'form.title': '제목 *',
'form.titlePh': '예: Your Name',
'form.originalTitle': '원제',
'form.originalTitlePh': '예: 君の名は。',
'form.synopsis': '줄거리',
'form.type': '유형',
'form.subtype': '세부 유형',
'form.subtypePh': '다큐멘터리, 리얼리티…',
'form.status': '상태',
'form.myRating': '내 평점',
'form.favorite': '최애',
'form.criteria': '세부 평가 (선택)',
'form.episodes': '에피소드',
'form.minusEp': '-1화',
'form.plusEp': '+1화',
'form.total': '전체',
'form.season': '시즌',
'form.minPerEp': '화당 분',
'form.duration': '러닝타임',
'form.durationMin': '러닝타임 (분)',
'form.info': '정보',
'form.start': '시작 / 본 날짜',
'form.end': '종료',
'form.year': '연도',
'form.platform': '플랫폼',
'form.genres': '장르 / 태그',
'form.genresPh': '로맨스, SF…',
'form.rewatches': '다시 본 기록',
'form.review': '내 감상',
'form.reviewPh': '어땠는지, 기억에 남는 장면…',
'form.saveChanges': '변경 사항 저장',
'form.addToLibrary': '라이브러리에 추가',
'form.shareImage': '이미지로 공유',
'form.delete': '이 작품 삭제',
'form.deleteConfirm': '‘{title}’이(가) 영구적으로 삭제돼요.',
'form.removeRewatch': '이 기록 삭제',
'form.rewatchDate': '다시 본 날짜',
'form.reviewPublic': '이 감상을 내 프로필에 표시',
'form.reviewPublicHint': '표시하지 않으면 나만 볼 수 있어요.',
'journal.rewatched': '다시 봄',
'journal.started': '시작',
'journal.emptyTitle': '일지가 비어 있어요',
'journal.emptyText': '작품에 시작일이나 종료일을 입력하면 여기에 시청 기록이 표시돼요.',
'journal.seen_one': '{count}개 시청',
'journal.seen_other': '{count}개 시청',
'journal.more': '이전 달 보기',
'stats.overview': '한눈에 보기',
'stats.habits': '시청 습관',
'stats.tastes': '취향',
'stats.pageTitle': '내 ',
'stats.pageAccent': '통계',
'stats.emptyTitle': '아직 통계가 없어요',
'stats.emptyText': '작품을 추가하면 바로 표시돼요.',
'stats.sinceStart': '처음부터',
'stats.subtitle_one': '내 라이브러리의 작품 {count}개',
'stats.subtitle_other': '내 라이브러리의 작품 {count}개',
'stats.subtitleYear_one': '{year}년 작품 {count}개',
'stats.subtitleYear_other': '{year}년 작품 {count}개',
'stats.hours_one': '시간',
'stats.hours_other': '시간',
'stats.nonStopPre': '쉬지 않고 ',
'stats.nonStopPost': ' 동안 본 셈',
'stats.days_one': '{count}일',
'stats.days_other': '{count}일',
'stats.finishedN_one': '{count}개 완료',
'stats.finishedN_other': '{count}개 완료',
'stats.episodesN_one': '{count}화',
'stats.episodesN_other': '{count}화',
'stats.timeByType': '유형별 시간',
'stats.noTime': '이 기간에는 아직 기록된 시간이 없어요.',
'stats.avgRating': '평균 평점',
'stats.rated_one': '평점 매긴 작품 {count}개',
'stats.rated_other': '평점 매긴 작품 {count}개',
'stats.inYear': '{year}년',
'stats.statuses': '상태',
'stats.hoursTab': '시간',
'stats.monthByMonth': '월별 · {year}년',
'stats.last12': '최근 12개월',
'stats.monthFinished_one': '다 본 작품 {count}개',
'stats.monthFinished_other': '다 본 작품 {count}개',
'stats.busiest': '가장 많이 본 달:',
'stats.records': '기록',
'stats.marathon': '최장 정주행',
'stats.longestFilm': '가장 긴 영화',
'stats.noRecords': '이 기간에는 아직 기록이 없어요.',
'stats.platforms': '플랫폼',
'stats.bestRated': '내 최고 평점 작품',
'stats.myRatings': '내 평점',
'stats.noRatings': '이 기간에는 평점이 없어요.',
'stats.favGenres': '좋아하는 장르',
'stats.noGenres': '아직 장르가 없어요.',
'stats.countries': '국가',
'stats.noCountry_one': '국가 정보가 없는 작품 {count}개: 작품 정보에서 ‘TMDB / AniList에서 채우기’로 채워 주세요.',
'stats.noCountry_other': '국가 정보가 없는 작품 {count}개: 작품 정보에서 ‘TMDB / AniList에서 채우기’로 채워 주세요.',
'stats.noCountryLegacy_one': '국가 정보가 없는 작품 {count}개: 작품 정보에서 ‘TMDB / AniList에서 채우기’로 채우거나, 이전 앱의 백업을 다시 가져오세요(‘병합’).',
'stats.noCountryLegacy_other': '국가 정보가 없는 작품 {count}개: 작품 정보에서 ‘TMDB / AniList에서 채우기’로 채우거나, 이전 앱의 백업을 다시 가져오세요(‘병합’).',
'stats.byType': '유형별',
'stats.footnote': '본 에피소드 수와 입력한 러닝타임으로 추정한 시간이에요 (입력하지 않으면 영화 1시간 50분, 애니 1화 24분, 시리즈 45분, K-드라마 1시간, C-드라마 45분). 작품은 다 본 연도에 집계돼요.',
'stats.ratedAs_one': '평점 {rating}',
'stats.ratedAs_other': '평점 {rating}',
'backup.shareTitle': 'AzuuCine 백업',
'backup.tooBig': '파일이 너무 커요 (최대 30MB).',
'backup.notJson': '올바른 JSON 파일이 아니에요.',
'backup.noItems': '이 파일에서 항목을 찾지 못했어요.',
'backup.tooMany': '항목이 너무 많아요 (최대 {n}개).',
'image.canvas': 'Canvas를 사용할 수 없어요',
'image.unreadable': '이미지를 읽을 수 없어요',
'image.notImage': '이미지 파일이 아니에요.',
'image.tooBig': '이미지가 너무 커요 (최대 25MB).',
'social.err.server': '서버 응답: {status}',
'social.err.usernameTaken': '이미 사용 중인 아이디예요.',
'social.err.usernameReserved': '사용할 수 없는 아이디예요.',
'social.err.invalid': '올바르지 않은 값이 있어요.',
'social.inLibrary': '내 라이브러리에 있음',
'social.addToWatch': '‘볼 예정’에 추가',
'social.linkCopied': '링크를 복사했어요!',
'social.profile': '프로필',
'social.shareProfile': '프로필 공유',
'social.loading': '불러오는 중…',
'social.loadError': '프로필을 불러올 수 없어요.',
'social.notFound': '프로필을 찾을 수 없어요',
'social.notFoundHint': '@{username}(이)라는 프로필이 없어요.',
'social.editProfile': '프로필 수정',
'social.following': '팔로잉',
'social.requested': '요청됨',
'social.followBack': '맞팔로우',
'social.follow': '팔로우',
'social.private': '비공개 계정',
'social.followsYou': '나를 팔로우함',
'social.seen': '본 작품',
'social.followers_one': '팔로워',
'social.followers_other': '팔로워',
'social.followingCount_one': '팔로잉',
'social.followingCount_other': '팔로잉',
'social.requests_one': '팔로우 요청 {count}개',
'social.requests_other': '팔로우 요청 {count}개',
'social.privateTitle': '비공개 계정이에요',
'social.privateText': '팔로우하면 이 사람의 시청 기록, 평점, Top 5를 볼 수 있어요.',
'social.tabProfile': '프로필',
'social.tabLibrary': '라이브러리',
'social.cancelRequestTitle': '팔로우 요청을 취소할까요?',
'social.unfollowTitle': '{name} 님을 언팔로우할까요?',
'social.unfollowPrivate': '비공개 계정이라 프로필을 다시 보려면 팔로우 요청을 다시 보내야 해요.',
'social.cancelRequest': '요청 취소',
'social.unfollow': '언팔로우',
'social.top5': 'Top 5',
'social.recent': '최근 본 작품',
'social.noRecent': '아직 다 본 작품이 없어요.',
'social.statYear': '올해 본 작품',
'social.statFilms': '본 영화',
'social.statSeries': '본 시리즈 & 애니',
'social.emptyLibrary': '여기엔 작품이 없어요.',
'social.loadMore': '더 보기',
'social.changeBanner': '배너 변경',
'social.changeAvatar': '사진 변경',
'social.removeAvatar': '사진 삭제',
'social.removeBanner': '배너 삭제',
'social.displayName': '표시 이름',
'social.username': '아이디',
'social.usernameRule': '3~20자: 영문 소문자, 숫자, _',
'social.bio': '소개',
'social.bioPh': '즐겨 보는 것, 좋아하는 장르…',
'social.privateAccount': '비공개 계정',
'social.privateHint': '내가 수락한 팔로워만 내 시청 기록을 볼 수 있어요.',
'social.publicHint': '이름, 아이디, 사진, 배너, 소개는 모든 회원이 볼 수 있어요. 작성한 감상은 비공개로 유지되고, 프로필에 표시하기로 한 감상만 공개돼요.',
'social.requestsTab_one': '요청',
'social.requestsTab_other': '요청 ({count})',
'social.noFollowing': '아직 팔로우한 사람이 없어요.',
'social.noFollowers': '아직 팔로워가 없어요.',
'social.accept': '수락',
'social.decline': '거절',
'social.removeFollower': '삭제',
'social.findFriends': '친구 찾기',
'social.searchPh': '아이디 또는 이름…',
'social.noResults': '일치하는 사람이 없어요.',
'social.inviteHint': '친구가 아직 AzuuCine에 없나요? 내 프로필 링크를 보내 보세요.',
'social.shareMyProfile': '내 프로필 공유',
'social.inviteText': 'AzuuCine에서 나를 팔로우해 주세요!',
'social.myProfile': '내 프로필',
'feed.title': '팔로잉',
'feed.empty': '친구를 팔로우하면 친구가 뭘 보고 어떻게 생각하는지 여기서 볼 수 있어요.',
'feed.finished': '님이 봤어요:',
'feed.started': '님이 보기 시작했어요:',
'feed.rewatched': '님이 다시 봤어요:',
'feed.added': '님이 보고 싶어 해요:',
'feed.review': '감상',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** Português (Brasil) */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': 'Cancelar',
'common.confirm': 'Confirmar',
'common.close': 'Fechar',
'common.save': 'Salvar',
'common.add': 'Adicionar',
'common.delete': 'Excluir',
'common.all': 'Tudo',
'common.none': 'Nenhum',
'common.noData': 'Ainda não há dados.',
'common.retry': 'Tentar de novo',
'common.back': 'Voltar',
'common.offline': 'Sem conexão com a internet.',
'common.minutes': '{n} min',
'common.hours': '{h} h',
'common.hoursMinutes': '{h} h {m}',
'common.daysHours': '{d} d {h} h',
'common.decimalSep': ',',
'common.removeX': 'Remover {name}',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': 'Editar',
'common.moveUp': 'Subir',
'common.moveDown': 'Descer',
'nav.home': 'Início',
'nav.catalog': 'Catálogo',
'nav.stats': 'Estatísticas',
'nav.settings': 'Ajustes',
'nav.addTitle': 'Adicionar um título',
'type.film': 'Filme',
'type.serie': 'Série',
'type.anime': 'Anime',
'type.kdrama': 'K-Drama',
'type.cdrama': 'C-Drama',
'type.autre': 'Outro',
'typePlural.film': 'Filmes',
'typePlural.serie': 'Séries',
'typePlural.anime': 'Animes',
'typePlural.kdrama': 'K-Dramas',
'typePlural.cdrama': 'C-Dramas',
'status.a_voir': 'Quero ver',
'status.en_cours': 'Assistindo',
'status.termine': 'Concluído',
'status.pause': 'Pausado',
'status.abandonne': 'Abandonado',
'criteria.story': 'Roteiro / História',
'criteria.cast': 'Personagens / Elenco',
'criteria.direction': 'Direção / Animação',
'criteria.ost': 'Trilha sonora (OST)',
'subtype.documentary': 'Documentário',
'subtype.reality': 'Reality show',
'subtype.show': 'Programa de TV',
'subtype.short': 'Curta-metragem',
'subtype.stage': 'Espetáculo',
'subtype.miniseries': 'Minissérie',
'platform.cinema': 'Cinema',
'platform.dvd': 'DVD / Blu-ray',
'platform.tv': 'TV',
'genre.action': 'Ação',
'genre.adventure': 'Aventura',
'genre.comedy': 'Comédia',
'genre.drama': 'Drama',
'genre.romance': 'Romance',
'genre.romcom': 'Rom-com',
'genre.thriller': 'Suspense',
'genre.horror': 'Terror',
'genre.mystery': 'Mistério',
'genre.crime': 'Crime',
'genre.scifi': 'Sci-Fi',
'genre.fantasy': 'Fantasia',
'genre.historical': 'Histórico',
'genre.sliceOfLife': 'Slice of Life',
'genre.shonen': 'Shōnen',
'genre.shojo': 'Shōjo',
'genre.seinen': 'Seinen',
'genre.isekai': 'Isekai',
'genre.mecha': 'Mecha',
'genre.sports': 'Esporte',
'genre.musical': 'Musical',
'genre.medical': 'Médico',
'genre.legal': 'Jurídico',
'genre.wuxia': 'Wuxia',
'genre.xianxia': 'Xianxia',
'genre.family': 'Família',
'genre.animation': 'Animação',
'genre.psychological': 'Psicológico',
'genre.supernatural': 'Sobrenatural',
'genre.romanticComedy': 'Comédia romântica',
'genre.documentary': 'Documentário',
'genre.war': 'Guerra',
'genre.western': 'Faroeste',
'genre.music': 'Música',
'genre.ecchi': 'Ecchi',
'genre.kids': 'Infantil',
'genre.news': 'Notícias',
'genre.reality': 'Reality show',
'genre.talk': 'Talk show',
'genre.soap': 'Novela',
'genre.politics': 'Política',
'genre.tvMovie': 'Telefilme',
'genre.anime': 'Anime',
'genre.magicalGirl': 'Magical Girl',
'confirm.title': 'Tem certeza?',
'err.tmdbRefused': 'Requisição ao TMDB recusada.',
'err.tmdbKeyRefused': 'Chave do TMDB recusada. Confira em Ajustes.',
'err.tmdbStatus': 'O TMDB respondeu {status}.',
'err.tmdbRef': 'Referência do TMDB inválida.',
'err.anilistRate': 'O AniList está limitando as requisições, tente de novo em um minuto.',
'err.anilistStatus': 'O AniList respondeu {status}.',
'err.searchRate': 'Muitas buscas, tente de novo em alguns minutos.',
'anilist.short': 'Anime curto',
'anilist.movie': 'Filme de animação',
'anilist.special': 'Especial',
'anilist.music': 'Clipe',
'release.cinema': 'Nos cinemas',
'release.online': 'Em VOD / streaming',
'release.release': 'Lançamento',
'release.season': 'Temporada {season}',
'release.episode': 'Episódio {ep}',
'release.newEpisode': 'Novo episódio',
'release.firstEpisode': 'Primeiro episódio',
'release.newSeriesN': 'Nova série · {count} episódios',
'release.seasonN': 'Temporada {season} · {count} episódios',
'release.seasonEp1': 'Temporada {season} · Episódio 1',
'release.episodes': 'Episódios {first}–{last}',
'release.sEpisodes': 'T{season} · Episódios {first}–{last}',
'release.sEpisode': 'T{season} · Episódio {ep}',
'release.episodeFinal': 'Episódio {ep} · final',
'release.filmJapan': 'Filme no Japão',
'card.ep': 'Ep. {n}',
'card.plusOne': '+1 episódio de {title}',
'card.open': 'Abrir {title}',
'rating.outOf10': 'Nota de 0 a 10',
'rating.stars_one': '{count} estrela',
'rating.stars_other': '{count} estrelas',
'rating.clear': 'Apagar a nota',
'share.previewLabel': 'Prévia da imagem',
'share.preview': 'Prévia',
'share.posterAlt': 'Pôster de {title}',
'share.share': 'Compartilhar',
'share.saveImage': 'Salvar a imagem',
'share.err.create': 'Não foi possível criar a imagem',
'share.minutesLong': '{n} minutos',
'share.createdBy': 'Criado por',
'share.directedBy': 'Dirigido por',
'share.producedBy': 'Produzido por',
'share.starring': 'Com',
'share.genres': 'Gêneros',
'share.myRating': 'Minha nota',
'share.myTop': 'Meu Top',
'auth.hidePassword': 'Ocultar a senha',
'auth.showPassword': 'Mostrar a senha',
'auth.mismatch': 'As duas senhas não são iguais.',
'auth.created': 'Conta criada! Abra o link enviado para {email} para ativá-la e depois entre.',
'auth.resetSent': 'Se existir uma conta com esse endereço, acabamos de enviar um link para você escolher uma nova senha.',
'auth.tagline': 'Seu diário de filmes, séries, animes e doramas.',
'auth.loginTab': 'Entrar',
'auth.signupTab': 'Criar conta',
'auth.forgotTitle': 'Esqueci a senha',
'auth.email': 'E-mail',
'auth.password': 'Senha',
'auth.confirmPassword': 'Confirme a senha',
'auth.minChars': 'Pelo menos {n} caracteres.',
'auth.login': 'Entrar',
'auth.signup': 'Criar minha conta',
'auth.sendLink': 'Enviar o link',
'auth.forgot': 'Esqueceu a senha?',
'auth.backToLogin': 'Voltar para o login',
'auth.privacy': 'Seus dados ficam vinculados à sua conta e só você pode vê-los. Eles também ficam no seu aparelho para funcionar sem internet.',
'auth.newPasswordTitle': 'Escolha sua nova senha.',
'auth.newPassword': 'Nova senha',
'auth.err.credentials': 'E-mail ou senha incorretos.',
'auth.err.notConfirmed': 'Primeiro confirme seu endereço com o link que você recebeu por e-mail.',
'auth.err.exists': 'Já existe uma conta com esse e-mail.',
'auth.err.weak': 'Senha muito fraca (pelo menos {n} caracteres, misturando letras e números).',
'auth.err.samePassword': 'A nova senha precisa ser diferente da antiga.',
'auth.err.emailRate': 'Muitas solicitações. Tente de novo em alguns minutos.',
'auth.err.rate': 'Muitas tentativas. Tente de novo em alguns minutos.',
'auth.err.signupDisabled': 'Os cadastros estão fechados no momento.',
'auth.err.emailInvalid': 'E-mail inválido.',
'auth.err.invalid': 'E-mail ou senha inválidos.',
'auth.err.session': 'Sessão expirada, entre de novo.',
'auth.err.status': 'O servidor recusou a solicitação ({status}).',
'auth.err.response': 'Resposta do servidor inválida.',
'auth.err.linkExpired': 'Este link expirou. Peça um novo.',
'auth.err.linkUsed': 'Este link é inválido ou já foi usado.',
'auth.err.linkInvalid': 'Este link é inválido.',
'settings.language': 'Idioma',
'settings.backupShared': 'Backup compartilhado.',
'settings.backupDownloaded': 'Backup baixado.',
'settings.exportFailed': 'A exportação falhou.',
'settings.noValidItems': 'O arquivo não contém nenhuma ficha válida.',
'settings.imported_one': '{count} ficha importada.',
'settings.imported_other': '{count} fichas importadas.',
'settings.importedSkipped': '{n} ficha(s) importada(s), {skipped} ignorada(s).',
'settings.cleared': 'Biblioteca apagada.',
'settings.pageTitle': 'Meus ',
'settings.pageAccent': 'ajustes',
'settings.languageHint': 'Idioma do app, das datas e das informações buscadas no TMDB (títulos, sinopses).',
'settings.rating': 'Avaliação',
'settings.scale5': '★ de 0 a 5',
'settings.scale10': 'De 0 a 10',
'settings.ratingHint': 'Meias estrelas de 0 a 5, ou passos de 0,5 de 0 a 10. As notas existentes são convertidas automaticamente.',
'settings.theme': 'Tema',
'settings.themeX': 'Tema {name}',
'settings.pickColor': 'Escolher uma cor livre',
'settings.freeColor': 'Cor livre',
'settings.freeColorHint': 'Qualquer cor: o texto se adapta para continuar legível.',
'settings.databases': 'Bases de filmes',
'settings.anilistActive': 'Animes · ativo',
'settings.noConfig': 'Nenhuma configuração necessária.',
'settings.tmdbActive': 'Filmes e séries · ativo',
'settings.checking': 'Verificando…',
'settings.offline': 'Offline',
'settings.proxyMissingKey': 'Chave do TMDB ausente',
'settings.proxyNotDeployed': 'Servidor não instalado',
'settings.unavailable': 'Indisponível',
'settings.proxyMissingKeyHint': 'A função do servidor está no ar, mas sua chave do TMDB não foi salva (secret TMDB_API_KEY no Supabase) ou foi recusada pelo TMDB.',
'settings.proxyNotDeployedHint': 'A função “tmdb” ainda não foi implantada no Supabase (veja README → Contas, etapa 5).',
'settings.proxyErrorHint': 'O servidor não está respondendo corretamente no momento.',
'settings.proxyOkHint': 'Fornecido pelo servidor do app: nenhuma chave para digitar.',
'settings.recheck': 'Verificar de novo',
'settings.keyRefused': 'Chave recusada',
'settings.notConfigured': 'Não configurado',
'settings.tmdbHelp': 'Filmes, séries, K-dramas, C-dramas. Crie uma conta grátis em themoviedb.org, depois vá em Configurações → API e cole sua “Chave da API” ou seu “Token de leitura da API”.',
'settings.tmdbKey': 'Chave do TMDB',
'settings.hideKey': 'Ocultar a chave',
'settings.showKey': 'Mostrar a chave',
'settings.validate': 'Validar',
'settings.remove': 'Remover',
'settings.keyLocal': 'A chave fica neste aparelho e nunca é incluída nos backups.',
'settings.topHint': 'Categorias exibidas no início.',
'settings.topNone': 'Nenhuma categoria: a seção Top 5 fica oculta.',
'settings.backup': 'Backup',
'settings.export': 'Exportar meus dados',
'settings.exportHint_one': '{count} ficha · arquivo JSON, faça com frequência',
'settings.exportHint_other': '{count} fichas · arquivo JSON, faça com frequência',
'settings.import': 'Importar um backup',
'settings.importHint': 'Restaurar a partir de um arquivo .json',
'settings.legacyDetected': 'Backup do app antigo reconhecido',
'settings.found_one': '{count} ficha encontrada. Como você quer importá-la?',
'settings.found_other': '{count} fichas encontradas. Como você quer importá-las?',
'settings.foundSkipped': '{n} ficha(s) encontrada(s) ({skipped} inválida(s) ignorada(s)). Como você quer importá-las?',
'settings.merge': 'Mesclar',
'settings.replaceAll': 'Substituir tudo',
'settings.mergeHint': '“Mesclar” adiciona as fichas e atualiza as que já existem (mesmo identificador).',
'settings.storage': 'Armazenamento',
'settings.used': 'Espaço usado',
'settings.storageCloud': 'Seus dados ficam salvos na sua conta e também neste aparelho para funcionar sem internet. Eles sincronizam automaticamente assim que você tiver conexão.',
'settings.storageLocal': 'Seus dados ficam guardados só neste navegador, neste aparelho. Se você apagar os dados do navegador ou desinstalar o app, eles somem: exporte um backup com frequência.',
'settings.danger': 'Zona de perigo',
'settings.clearAll': 'Apagar toda a biblioteca',
'settings.clearAllHint_one': '{count} título',
'settings.clearAllHint_other': '{count} títulos',
'settings.clearAllHintCloud_one': '{count} título · em todos os seus aparelhos',
'settings.clearAllHintCloud_other': '{count} títulos · em todos os seus aparelhos',
'settings.deleting': 'Excluindo…',
'settings.deleteAccount': 'Excluir minha conta',
'settings.deleteAccountHint': 'Conta e dados apagados para sempre',
'settings.footerCloud': 'conta sincronizada',
'settings.footerLocal': '100% local',
'settings.clearConfirm_one': '{count} título será apagado para sempre. Lembre-se de exportar um backup antes.',
'settings.clearConfirm_other': 'Seus {count} títulos serão apagados para sempre. Lembre-se de exportar um backup antes.',
'settings.clearConfirmCloud_one': '{count} título será apagado para sempre, em todos os seus aparelhos. Lembre-se de exportar um backup antes.',
'settings.clearConfirmCloud_other': 'Seus {count} títulos serão apagados para sempre, em todos os seus aparelhos. Lembre-se de exportar um backup antes.',
'settings.clearAllConfirm': 'Apagar tudo',
'settings.deleteAccountTitle': 'Excluir sua conta?',
'settings.deleteAccountMessage': 'Sua conta e todos os seus dados (títulos, listas, ajustes) serão apagados para sempre do servidor e deste aparelho. Lembre-se de exportar um backup antes. Essa ação não pode ser desfeita.',
'settings.deleteForever': 'Excluir para sempre',
'settings.replaceConfirm': 'Toda a sua biblioteca atual será substituída pelo conteúdo deste arquivo.',
'settings.replace': 'Substituir',
'sync.err.push': 'Envio recusado ({status})',
'sync.err.pull': 'Leitura recusada ({status})',
'store.dbError': 'Não foi possível abrir a base local: {error}',
'store.invalidItem': 'Ficha inválida',
'lists.newList': 'Nova lista',
'lists.newListPh': 'Nova lista…',
'lists.myLists': 'Minhas listas',
'lists.rename': 'Renomear',
'lists.delete': 'Excluir a lista',
'lists.done': 'Pronto',
'lists.addRemove': 'Adicionar / remover títulos',
'lists.searchLibrary': 'Buscar na minha biblioteca…',
'lists.emptyTitle': 'Lista vazia',
'lists.emptyText': 'Adicione títulos com o botão acima ou pela ficha de um título.',
'lists.deleteConfirm': 'A lista “{name}” será excluída. Os títulos continuam na sua biblioteca.',
'lists.noneTitle': 'Nenhuma lista por enquanto',
'lists.noneText': 'Crie listas do seu jeito: “Para ver com os amigos”, “Filmes de terror de outubro”, “Doramas para o coração”…',
'lists.create': 'Criar',
'account.err.deleteRate': 'Muitas tentativas, tente de novo em um minuto.',
'account.err.delete': 'A exclusão falhou. Tente de novo mais tarde.',
'account.title': 'Minha conta',
'account.syncing': 'Sincronizando…',
'account.offline': 'Offline — tudo fica salvo neste aparelho',
'account.syncError': 'Não foi possível sincronizar no momento',
'account.synced': 'Sincronizado {when}',
'account.passwordChanged': 'Senha alterada.',
'account.imported_one': '{count} título adicionado à sua conta.',
'account.imported_other': '{count} títulos adicionados à sua conta.',
'account.importFailed': 'A importação falhou.',
'account.pending_one': '{count} pendente',
'account.pending_other': '{count} pendentes',
'account.syncNow': 'Sincronizar agora',
'account.newPasswordPh': 'Nova senha (mín. {n} caracteres)',
'account.changePassword': 'Alterar a senha',
'account.logout': 'Sair',
'account.logoutHint': 'Seus dados continuam na sua conta e são removidos deste aparelho.',
'account.ignore': 'Ignorar',
'account.deviceHint': 'Eles serão movidos para sua conta e sincronizados em todos os seus aparelhos.',
'account.unsentTitle': 'Alterações não enviadas',
'account.logoutAnyway': 'Sair mesmo assim',
'account.unsentMessage_one': '{count} alteração ainda não foi enviada (sem conexão?). Se você sair agora, ela será perdida.',
'account.unsentMessage_other': '{count} alterações ainda não foram enviadas (sem conexão?). Se você sair agora, elas serão perdidas.',
'account.nTitles_one': '{count} título',
'account.nTitles_other': '{count} títulos',
'account.nLists_one': '{count} lista',
'account.nLists_other': '{count} listas',
'account.deviceData': 'Este aparelho tem {titles} criados antes da sua conta. Adicionar à sua conta?',
'account.deviceDataWithLists': 'Este aparelho tem {titles} e {lists} criados antes da sua conta. Adicionar à sua conta?',
'time.never': 'nunca',
'time.justNow': 'agora mesmo',
'time.minutesAgo': 'há {n} min',
'time.hoursAgo': 'há {n} h',
'time.onDate': 'em {date}',
'time.today': 'hoje',
'time.tomorrow': 'amanhã',
'time.daysAgo': 'há {n} d',
'theme.red': 'Vermelho',
'theme.orange': 'Laranja',
'theme.yellow': 'Amarelo',
'theme.lime': 'Lima',
'theme.green': 'Verde',
'theme.mint': 'Menta',
'theme.cyan': 'Ciano',
'theme.blue': 'Azul',
'theme.indigo': 'Índigo',
'theme.violet': 'Violeta',
'theme.pink': 'Rosa',
'theme.white': 'Branco',
'home.seeAll': 'Ver tudo',
'home.subtitle': 'Meu diário do que assisto',
'home.calendarSoon_one': 'Calendário de lançamentos: {count} nesta semana',
'home.calendarSoon_other': 'Calendário de lançamentos: {count} nesta semana',
'home.emptyTitle': 'Sua biblioteca está vazia',
'home.emptyCloud': 'Adicione seu primeiro filme, anime ou dorama. Ele ficará salvo na sua conta.',
'home.emptyLocal': 'Adicione seu primeiro filme, anime ou dorama. Tudo fica guardado só neste celular.',
'home.completed': 'Concluídos',
'home.thisYear_one': '{count} este ano',
'home.thisYear_other': '{count} este ano',
'home.toWatchN_one': '{count} para ver',
'home.toWatchN_other': '{count} para ver',
'home.screenTime': 'Tempo de tela',
'home.estimate': 'estimativa',
'home.episodesSeen': 'Episódios vistos',
'home.noIdea': 'Sem ideia?',
'home.rouletteHint_one': 'Sorteio entre o seu título para ver',
'home.rouletteHint_other': 'Sorteio entre os seus {count} títulos para ver',
'home.rouletteHintAll': 'Sorteio na sua biblioteca',
'home.recentlyFinished': 'Concluídos recentemente',
'calendar.title': 'Calendário de lançamentos',
'calendar.inMyList': 'Na minha lista',
'calendar.inMyListLegend': 'Na minha lista',
'calendar.seeMore_one': 'Ver o outro',
'calendar.seeMore_other': 'Ver os outros {count}',
'calendar.heading': 'Calendário de ',
'calendar.headingAccent': 'lançamentos',
'calendar.refresh': 'Atualizar',
'calendar.all': 'Todos os lançamentos',
'calendar.mine': 'Meus títulos',
'calendar.prevMonth': 'Mês anterior',
'calendar.nextMonth': 'Próximo mês',
'calendar.releases_one': '{count} lançamento',
'calendar.releases_other': '{count} lançamentos',
'calendar.others': 'Outros lançamentos',
'calendar.needKey': 'Sem chave do TMDB, só os animes aparecem. Adicione sua chave em Ajustes para ver também filmes, séries e doramas.',
'calendar.range': 'Os lançamentos ficam disponíveis do mês passado até 6 meses à frente.',
'calendar.failed': 'Alguns lançamentos não puderam ser carregados. Tente de novo com ↻.',
'calendar.nothingThatDay': 'Nada previsto para esse dia.',
'calendar.next14': 'Próximos 14 dias',
'calendar.loading': 'Buscando lançamentos…',
'calendar.noneMine14': 'Nenhum lançamento anunciado nos próximos 14 dias para os seus títulos.',
'calendar.noneMineMonth': 'Nenhum lançamento anunciado este mês para os seus títulos.',
'calendar.none14': 'Nenhum lançamento nos próximos 14 dias.',
'calendar.noneMonth': 'Nenhum lançamento encontrado para este mês.',
'calendar.footer': 'Filmes nos cinemas do seu país, episódios das séries e doramas mais acompanhados (TMDB) e de todos os animes exibidos no Japão (AniList). Os títulos da sua biblioteca aparecem destacados; toque em “Quero ver” para adicionar um lançamento à sua lista.',
'roulette.name': 'Roleta',
'roulette.rewatch': 'Para rever',
'roulette.anyTime': 'Tanto faz',
'roulette.heading': 'A ',
'roulette.headingAccent': 'roleta',
'roulette.tonight': 'Hoje à noite vai ser…',
'roulette.nEps': '{n} ep.',
'roulette.perEp': '{duration} / ep.',
'roulette.stoppedAt': 'Você parou no episódio {ep}.',
'roulette.stoppedAtOf': 'Você parou no episódio {ep} de {total}.',
'roulette.enjoy': 'Bom filme!',
'roulette.again': 'Girar de novo',
'roulette.spinning': 'Girando…',
'roulette.spin': 'Girar a roleta',
'roulette.poolSize_one': 'Sorteio entre {count} título',
'roulette.poolSize_other': 'Sorteio entre {count} títulos',
'roulette.empty': 'Nenhum título corresponde: amplie os filtros abaixo.',
'roulette.inside': 'Na roleta',
'roulette.pickFrom': 'Sortear entre',
'roulette.rewatchHint': '“Para rever” = seus títulos concluídos com nota 4/5 ou mais, favoritos e Top 5.',
'roulette.time': 'Tempo disponível (filme ou 1 episódio)',
'roulette.seeItem': 'Ver a ficha completa',
'roulette.watchIt': 'Vou assistir',
'newEp.check': 'Verificar',
'newEp.title': 'Novidades',
'newEp.checking': 'Vendo o que saiu…',
'newEp.needKey': 'Adicione sua chave do TMDB em Ajustes para ser avisado de novos episódios e novas temporadas.',
'newEp.nothing_one': 'Nada de novo na sua série ou anime acompanhado.',
'newEp.nothing_other': 'Nada de novo nas suas {count} séries e animes acompanhados.',
'newEp.needKeyAlso': '(Adicione sua chave do TMDB em Ajustes para acompanhar também séries e doramas.)',
'newEp.newSeason': 'Nova temporada',
'newEp.catchUp': 'Para colocar em dia',
'newEp.soon': 'Em breve',
'newEp.epWhen': 'Ep. {ep} {when}',
'newEp.available_one': '{count} episódio disponível',
'newEp.available_other': '{count} episódios disponíveis',
'newEp.next': 'Próximo: ep. {ep} {when}',
'newEp.resume': 'Continuar',
'top.pick': 'Escolher o nº {rank}',
'top.shareTitle': 'Meu Top 5 {category}',
'top.shareLabel': 'Compartilhar este Top 5 como imagem',
'top.title': 'Meus Top',
'top.number': 'Nº {rank}',
'top.pickFirst': 'Escolha seu nº 1.',
'top.editLabel': 'Editar o Top 5',
'top.freeSlot': 'Vaga livre — escolha um título abaixo',
'top.addFromLibrary': 'Adicionar da minha biblioteca',
'top.allTypes': 'Todos os tipos',
'top.searchTitle': 'Buscar um título…',
'top.full': 'Seu Top 5 está completo: remova um título para adicionar outro.',
'top.noCandidates': 'Nenhum título. Tente “Todos os tipos” ou outra busca.',
'reco.error': 'Não foi possível carregar as sugestões no momento.',
'reco.title': 'Sugestões',
'reco.needKey': 'Adicione sua chave do TMDB em Ajustes para receber sugestões com base nos seus títulos favoritos.',
'reco.other': 'Outro título',
'reco.ifYouLiked': 'Se você gostou de',
'reco.loading': 'Buscando sugestões…',
'reco.none': 'Você já tem tudo o que se parece com este título. Tente “Outro título”.',
'reco.added': '{title} adicionado',
'reco.addLabel': 'Adicionar {title} a “Quero ver”',
'reco.addedShort': 'Adicionado',
'search.moviesSeries': 'Filmes e séries',
'search.offline': 'Sem conexão com a internet: a busca precisa de rede.',
'search.fillFrom': 'Preencher a partir de uma base',
'search.needKey': 'Para buscar filmes, séries e doramas, adicione sua chave grátis do TMDB em Ajustes.',
'search.openSettings': 'Abrir Ajustes',
'search.already': 'já adicionado',
'search.noResults': 'Nenhum resultado. Você pode preencher a ficha à mão abaixo.',
'search.privacy': 'Só o título buscado é enviado para {source}. Sua biblioteca fica no seu celular.',
'catalog.sortRecent': 'Editados recentemente',
'catalog.sortWatched': 'Data em que assisti',
'catalog.sortRating': 'Melhor nota',
'catalog.sortTitle': 'Título (A→Z)',
'catalog.pageTitle': 'Meu ',
'catalog.pageAccent': 'catálogo',
'catalog.journalSubtitle': 'Seu histórico do que assistiu',
'catalog.filteredCount_one': '{count} título (filtrado)',
'catalog.filteredCount_other': '{count} títulos (filtrados)',
'catalog.titles': 'Títulos',
'catalog.journal': 'Diário',
'catalog.lists': 'Listas',
'catalog.searchPh': 'Título, gênero, plataforma…',
'catalog.moreFilters': 'Mais filtros',
'catalog.all': 'Todos',
'catalog.genre': 'Gênero',
'catalog.minRating': 'Nota mínima',
'catalog.allRatings': 'Todas',
'catalog.sortBy': 'Ordenar por',
'catalog.favorites': 'Favoritos',
'catalog.reset': 'Redefinir',
'catalog.noResults': 'Nenhum resultado',
'catalog.nothingYet': 'Nada por enquanto',
'catalog.noResultsHint': 'Tente outra busca ou remova alguns filtros.',
'catalog.nothingYetHint': 'Adicione seu primeiro título com o botão +.',
'catalog.clearFilters': 'Limpar os filtros',
'public.agree': 'Igualzinho ao público',
'public.more': '+{gap} acima do público',
'public.less': '−{gap} abaixo do público',
'public.label': 'Público',
'public.me': 'Eu',
'public.added_one': '{count} nota do público adicionada.',
'public.added_other': '{count} notas do público adicionadas.',
'public.noneFound': 'Nenhuma nota nova encontrada.',
'public.fetch': 'Buscar ({n})',
'public.title': 'Eu vs o público',
'public.hintFetch': 'Busque a nota média do TMDB / AniList dos seus títulos avaliados para ver onde você se diferencia do público.',
'public.hintNone': 'Nenhuma nota do público disponível para os seus títulos avaliados neste período.',
'public.hintKey': 'Adicione sua chave do TMDB em Ajustes (ou animes vinculados ao AniList) para se comparar com o público.',
'public.avgGap': 'Diferença média',
'public.average': 'Na média',
'public.generous': 'Mais generoso que o público',
'public.harsh': 'Mais exigente que o público',
'public.agreeTitle': 'De acordo',
'public.within5_one': 'com até ½ estrela de diferença, em {count} título',
'public.within5_other': 'com até ½ estrela de diferença, em {count} títulos',
'public.within10_one': 'com até 1 ponto de diferença, em {count} título',
'public.within10_other': 'com até 1 ponto de diferença, em {count} títulos',
'public.lovedPre': 'Gostei ',
'public.lovedAccent': 'mais',
'public.lovedPost': ' que o público',
'public.hatedPre': 'Gostei ',
'public.hatedAccent': 'menos',
'public.hatedPost': ' que o público',
'public.allAgree': 'Você concorda com o público em todos os seus títulos. Que raro!',
'form.rewatchHint': 'Assistiu de novo? Registre cada revisão, ela vai aparecer no seu diário.',
'form.editTitle': 'Editar ',
'form.editAccent': 'ficha',
'form.newTitle': 'Novo ',
'form.newAccent': 'título',
'form.filledFrom': 'Preenchido a partir de',
'form.canEdit': 'você pode editar tudo',
'form.fillFromDb': 'Completar pelo TMDB / AniList',
'form.pickPoster': 'Escolher um pôster',
'form.removeImage': 'Remover a imagem',
'form.title': 'Título *',
'form.titlePh': 'ex.: Your Name',
'form.originalTitle': 'Título original',
'form.originalTitlePh': 'ex.: 君の名は。',
'form.synopsis': 'Sinopse',
'form.type': 'Tipo',
'form.subtype': 'Categoria',
'form.subtypePh': 'Documentário, Reality show…',
'form.status': 'Status',
'form.myRating': 'Minha nota',
'form.favorite': 'Favorito',
'form.criteria': 'Critérios detalhados (opcional)',
'form.episodes': 'Episódios',
'form.minusEp': '-1 episódio',
'form.plusEp': '+1 episódio',
'form.total': 'Total',
'form.season': 'Temporada',
'form.minPerEp': 'Min / ep.',
'form.duration': 'Duração',
'form.durationMin': 'Duração (minutos)',
'form.info': 'Informações',
'form.start': 'Início / visto em',
'form.end': 'Fim',
'form.year': 'Ano',
'form.platform': 'Plataforma',
'form.genres': 'Gêneros / tags',
'form.genresPh': 'Romance, Sci-Fi…',
'form.rewatches': 'Revisões',
'form.review': 'Minha opinião',
'form.reviewPh': 'O que achei, cenas marcantes…',
'form.saveChanges': 'Salvar as alterações',
'form.addToLibrary': 'Adicionar à minha biblioteca',
'form.shareImage': 'Compartilhar como imagem',
'form.delete': 'Excluir este título',
'form.deleteConfirm': '“{title}” será excluído para sempre.',
'form.removeRewatch': 'Remover esta revisão',
'form.rewatchDate': 'Data da revisão',
'form.reviewPublic': 'Mostrar esta opinião no meu perfil',
'form.reviewPublicHint': 'Se não, ela fica visível só para você.',
'journal.rewatched': 'Revisto',
'journal.started': 'Começado',
'journal.emptyTitle': 'Diário vazio',
'journal.emptyText': 'O que você assistiu vai aparecer aqui assim que suas fichas tiverem datas de início ou de fim.',
'journal.seen_one': '{count} visto',
'journal.seen_other': '{count} vistos',
'journal.more': 'Mostrar meses anteriores',
'stats.overview': 'Visão geral',
'stats.habits': 'Hábitos',
'stats.tastes': 'Gostos',
'stats.pageTitle': 'Minhas ',
'stats.pageAccent': 'estatísticas',
'stats.emptyTitle': 'Ainda sem estatísticas',
'stats.emptyText': 'Elas vão aparecer assim que você adicionar títulos.',
'stats.sinceStart': 'desde o início',
'stats.subtitle_one': '{count} título na minha biblioteca',
'stats.subtitle_other': '{count} títulos na minha biblioteca',
'stats.subtitleYear_one': '{count} título em {year}',
'stats.subtitleYear_other': '{count} títulos em {year}',
'stats.hours_one': 'hora',
'stats.hours_other': 'horas',
'stats.nonStopPre': 'ou seja, ',
'stats.nonStopPost': ' sem parar',
'stats.days_one': '{count} dia',
'stats.days_other': '{count} dias',
'stats.finishedN_one': '{count} concluído',
'stats.finishedN_other': '{count} concluídos',
'stats.episodesN_one': '{count} episódio',
'stats.episodesN_other': '{count} episódios',
'stats.timeByType': 'Tempo por tipo',
'stats.noTime': 'Ainda não há tempo registrado neste período.',
'stats.avgRating': 'Nota média',
'stats.rated_one': '{count} título avaliado',
'stats.rated_other': '{count} títulos avaliados',
'stats.inYear': 'em {year}',
'stats.statuses': 'Status',
'stats.hoursTab': 'Horas',
'stats.monthByMonth': 'Mês a mês · {year}',
'stats.last12': 'Últimos 12 meses',
'stats.monthFinished_one': '{count} título concluído',
'stats.monthFinished_other': '{count} títulos concluídos',
'stats.busiest': 'Mês mais movimentado:',
'stats.records': 'Recordes',
'stats.marathon': 'Maior maratona',
'stats.longestFilm': 'Filme mais longo',
'stats.noRecords': 'Ainda não há recordes neste período.',
'stats.platforms': 'Plataformas',
'stats.bestRated': 'Meus mais bem avaliados',
'stats.myRatings': 'Minhas notas',
'stats.noRatings': 'Nenhuma nota neste período.',
'stats.favGenres': 'Gêneros favoritos',
'stats.noGenres': 'Ainda não há gêneros.',
'stats.countries': 'Países',
'stats.noCountry_one': '{count} título sem país: complete-o com “Completar pelo TMDB / AniList” na ficha.',
'stats.noCountry_other': '{count} títulos sem país: complete-os com “Completar pelo TMDB / AniList” na ficha.',
'stats.noCountryLegacy_one': '{count} título sem país: complete-o com “Completar pelo TMDB / AniList” na ficha ou importe de novo o backup do seu app antigo (“Mesclar”).',
'stats.noCountryLegacy_other': '{count} títulos sem país: complete-os com “Completar pelo TMDB / AniList” na ficha ou importe de novo o backup do seu app antigo (“Mesclar”).',
'stats.byType': 'Por tipo',
'stats.footnote': 'Tempo estimado a partir dos episódios vistos e das durações informadas (senão: filme 1 h 50, episódio de anime 24 min, série 45 min, K-drama 1 h, C-drama 45 min). Um título conta para o ano em que o concluí.',
'stats.ratedAs_one': 'nota {rating}',
'stats.ratedAs_other': 'nota {rating}',
'backup.shareTitle': 'Backup do AzuuCine',
'backup.tooBig': 'Arquivo grande demais (máximo de 30 MB).',
'backup.notJson': 'Este arquivo não é um JSON válido.',
'backup.noItems': 'Nenhuma ficha encontrada neste arquivo.',
'backup.tooMany': 'Fichas demais (máximo de {n}).',
'image.canvas': 'Canvas indisponível',
'image.unreadable': 'Imagem ilegível',
'image.notImage': 'Este arquivo não é uma imagem.',
'image.tooBig': 'Imagem pesada demais (máximo de 25 MB).',
'social.err.server': 'O servidor respondeu {status}.',
'social.err.usernameTaken': 'Esse nome de usuário já está em uso.',
'social.err.usernameReserved': 'Esse nome de usuário não está disponível.',
'social.err.invalid': 'Um dos valores não é válido.',
'social.inLibrary': 'Na minha biblioteca',
'social.addToWatch': 'Adicionar a Quero ver',
'social.linkCopied': 'Link copiado!',
'social.profile': 'Perfil',
'social.shareProfile': 'Compartilhar o perfil',
'social.loading': 'Carregando…',
'social.loadError': 'Não foi possível carregar o perfil.',
'social.notFound': 'Perfil não encontrado',
'social.notFoundHint': 'Nenhum perfil se chama @{username}.',
'social.editProfile': 'Editar perfil',
'social.following': 'Seguindo',
'social.requested': 'Solicitado',
'social.followBack': 'Seguir de volta',
'social.follow': 'Seguir',
'social.private': 'Conta privada',
'social.followsYou': 'Segue você',
'social.seen': 'Vistos',
'social.followers_one': 'Seguidor',
'social.followers_other': 'Seguidores',
'social.followingCount_one': 'Seguindo',
'social.followingCount_other': 'Seguindo',
'social.requests_one': '{count} solicitação para seguir',
'social.requests_other': '{count} solicitações para seguir',
'social.privateTitle': 'Esta conta é privada',
'social.privateText': 'Siga para ver o que essa pessoa assistiu, as notas e o Top 5 dela.',
'social.tabProfile': 'Perfil',
'social.tabLibrary': 'Biblioteca',
'social.cancelRequestTitle': 'Cancelar a solicitação para seguir?',
'social.unfollowTitle': 'Deixar de seguir {name}?',
'social.unfollowPrivate': 'Esta conta é privada: você vai precisar solicitar de novo para ver o perfil.',
'social.cancelRequest': 'Cancelar solicitação',
'social.unfollow': 'Deixar de seguir',
'social.top5': 'Top 5',
'social.recent': 'Vistos recentemente',
'social.noRecent': 'Nada concluído por enquanto.',
'social.statYear': 'Vistos este ano',
'social.statFilms': 'Filmes vistos',
'social.statSeries': 'Séries e animes vistos',
'social.emptyLibrary': 'Nenhum título aqui.',
'social.loadMore': 'Ver mais',
'social.changeBanner': 'Trocar o banner',
'social.changeAvatar': 'Trocar a foto',
'social.removeAvatar': 'Remover a foto',
'social.removeBanner': 'Remover o banner',
'social.displayName': 'Nome de exibição',
'social.username': 'Nome de usuário',
'social.usernameRule': 'De 3 a 20 caracteres: letras minúsculas, números ou _',
'social.bio': 'Bio',
'social.bioPh': 'O que você gosta de assistir, seus gêneros favoritos…',
'social.privateAccount': 'Conta privada',
'social.privateHint': 'Só os seguidores que você aceitar veem o que você assiste.',
'social.publicHint': 'Seu nome, nome de usuário, foto, banner e bio ficam visíveis para todos os membros. Suas opiniões escritas continuam privadas, exceto as que você escolher mostrar no seu perfil.',
'social.requestsTab_one': 'Solicitação',
'social.requestsTab_other': 'Solicitações ({count})',
'social.noFollowing': 'Você ainda não segue ninguém.',
'social.noFollowers': 'Nenhum seguidor por enquanto.',
'social.accept': 'Aceitar',
'social.decline': 'Recusar',
'social.removeFollower': 'Remover',
'social.findFriends': 'Encontrar amigos',
'social.searchPh': 'Nome de usuário ou nome…',
'social.noResults': 'Ninguém encontrado.',
'social.inviteHint': 'Seus amigos ainda não estão no AzuuCine? Mande para eles o link do seu perfil.',
'social.shareMyProfile': 'Compartilhar meu perfil',
'social.inviteText': 'Me siga no AzuuCine!',
'social.myProfile': 'Meu perfil',
'feed.title': 'Quem eu sigo',
'feed.empty': 'Siga amigos para ver aqui o que eles assistem e o que acharam.',
'feed.finished': 'assistiu',
'feed.started': 'começou',
'feed.rewatched': 'reviu',
'feed.added': 'quer ver',
'feed.review': 'opinião',
}
export default dict
+750
View File
@@ -0,0 +1,750 @@
/** 简体中文 */
import type { Translations } from '..'
const dict: Translations = {
'common.cancel': '取消',
'common.confirm': '确认',
'common.close': '关闭',
'common.save': '保存',
'common.add': '添加',
'common.delete': '删除',
'common.all': '全部',
'common.none': '无',
'common.noData': '还没有数据。',
'common.retry': '重试',
'common.back': '返回',
'common.offline': '没有网络连接。',
'common.minutes': '{n}分钟',
'common.hours': '{h}小时',
'common.hoursMinutes': '{h}小时{m}分',
'common.daysHours': '{d}天{h}小时',
'common.decimalSep': '.',
'common.removeX': '移除{name}',
'common.kb': '{n} KB',
'common.mb': '{n} MB',
'common.edit': '编辑',
'common.moveUp': '上移',
'common.moveDown': '下移',
'nav.home': '首页',
'nav.catalog': '片库',
'nav.stats': '统计',
'nav.settings': '设置',
'nav.addTitle': '添加作品',
'type.film': '电影',
'type.serie': '剧集',
'type.anime': '动画',
'type.kdrama': '韩剧',
'type.cdrama': '华语剧',
'type.autre': '其他',
'typePlural.film': '电影',
'typePlural.serie': '剧集',
'typePlural.anime': '动画',
'typePlural.kdrama': '韩剧',
'typePlural.cdrama': '华语剧',
'status.a_voir': '想看',
'status.en_cours': '在看',
'status.termine': '看完了',
'status.pause': '暂停',
'status.abandonne': '弃坑',
'criteria.story': '剧本 / 故事',
'criteria.cast': '角色 / 演员',
'criteria.direction': '导演 / 作画',
'criteria.ost': '原声音乐(OST)',
'subtype.documentary': '纪录片',
'subtype.reality': '真人秀',
'subtype.show': '综艺节目',
'subtype.short': '短片',
'subtype.stage': '舞台演出',
'subtype.miniseries': '迷你剧',
'platform.cinema': '电影院',
'platform.dvd': 'DVD / 蓝光',
'platform.tv': '电视',
'genre.action': '动作',
'genre.adventure': '冒险',
'genre.comedy': '喜剧',
'genre.drama': '剧情',
'genre.romance': '爱情',
'genre.romcom': '爱情喜剧',
'genre.thriller': '惊悚',
'genre.horror': '恐怖',
'genre.mystery': '悬疑',
'genre.crime': '犯罪',
'genre.scifi': '科幻',
'genre.fantasy': '奇幻',
'genre.historical': '历史',
'genre.sliceOfLife': '日常',
'genre.shonen': '少年',
'genre.shojo': '少女',
'genre.seinen': '青年',
'genre.isekai': '异世界',
'genre.mecha': '机甲',
'genre.sports': '运动',
'genre.musical': '歌舞',
'genre.medical': '医疗',
'genre.legal': '律政',
'genre.wuxia': '武侠',
'genre.xianxia': '仙侠',
'genre.family': '家庭',
'genre.animation': '动画',
'genre.psychological': '心理',
'genre.supernatural': '超自然',
'genre.romanticComedy': '浪漫喜剧',
'genre.documentary': '纪录片',
'genre.war': '战争',
'genre.western': '西部',
'genre.music': '音乐',
'genre.ecchi': 'Ecchi',
'genre.kids': '儿童',
'genre.news': '新闻',
'genre.reality': '真人秀',
'genre.talk': '脱口秀',
'genre.soap': '肥皂剧',
'genre.politics': '政治',
'genre.tvMovie': '电视电影',
'genre.anime': '动漫',
'genre.magicalGirl': '魔法少女',
'confirm.title': '确定吗?',
'err.tmdbRefused': 'TMDB 请求被拒绝。',
'err.tmdbKeyRefused': 'TMDB 密钥被拒绝,请在「设置」中检查。',
'err.tmdbStatus': 'TMDB 返回了 {status}。',
'err.tmdbRef': 'TMDB 编号无效。',
'err.anilistRate': 'AniList 限制了请求频率,一分钟后再试吧。',
'err.anilistStatus': 'AniList 返回了 {status}。',
'err.searchRate': '搜索太频繁了,过几分钟再试吧。',
'anilist.short': '动画短片',
'anilist.movie': '动画电影',
'anilist.special': '特别篇',
'anilist.music': 'MV',
'release.cinema': '院线上映',
'release.online': '点播 / 流媒体',
'release.release': '上映',
'release.season': '第{season}季',
'release.episode': '第{ep}集',
'release.newEpisode': '新一集',
'release.firstEpisode': '首集',
'release.newSeriesN': '新剧 · 共{count}集',
'release.seasonN': '第{season}季 · 共{count}集',
'release.seasonEp1': '第{season}季 · 第1集',
'release.episodes': '第{first}–{last}集',
'release.sEpisodes': 'S{season} · 第{first}–{last}集',
'release.sEpisode': 'S{season} · 第{ep}集',
'release.episodeFinal': '第{ep}集 · 大结局',
'release.filmJapan': '日本上映电影',
'card.ep': '第{n}集',
'card.plusOne': '《{title}》+1集',
'card.open': '打开《{title}》',
'rating.outOf10': '10分制评分',
'rating.stars_one': '{count}星',
'rating.stars_other': '{count}星',
'rating.clear': '清除评分',
'share.previewLabel': '图片预览',
'share.preview': '预览',
'share.posterAlt': '《{title}》海报',
'share.share': '分享',
'share.saveImage': '保存图片',
'share.err.create': '无法生成图片',
'share.minutesLong': '{n}分钟',
'share.createdBy': '主创',
'share.directedBy': '导演',
'share.producedBy': '制作',
'share.starring': '主演',
'share.genres': '类型',
'share.myRating': '我的评分',
'share.myTop': '我的 Top',
'auth.hidePassword': '隐藏密码',
'auth.showPassword': '显示密码',
'auth.mismatch': '两次输入的密码不一致。',
'auth.created': '账号已创建!打开发送到 {email} 的链接激活账号,然后登录。',
'auth.resetSent': '如果该邮箱已注册,我们已发送一个用于设置新密码的链接。',
'auth.tagline': '你的电影、剧集、动画和电视剧观影日记。',
'auth.loginTab': '登录',
'auth.signupTab': '注册账号',
'auth.forgotTitle': '忘记密码',
'auth.email': '邮箱地址',
'auth.password': '密码',
'auth.confirmPassword': '确认密码',
'auth.minChars': '至少{n}个字符。',
'auth.login': '登录',
'auth.signup': '创建账号',
'auth.sendLink': '发送链接',
'auth.forgot': '忘记密码?',
'auth.backToLogin': '返回登录',
'auth.privacy': '你的数据与账号绑定,只有你自己能看到。数据也会保存在你的设备上,没网也能用。',
'auth.newPasswordTitle': '设置你的新密码。',
'auth.newPassword': '新密码',
'auth.err.credentials': '邮箱或密码错误。',
'auth.err.notConfirmed': '请先通过邮件里的链接验证你的邮箱。',
'auth.err.exists': '该邮箱已注册账号。',
'auth.err.weak': '密码太弱(至少{n}个字符,需混合字母和数字)。',
'auth.err.samePassword': '新密码不能与旧密码相同。',
'auth.err.emailRate': '请求太频繁了,过几分钟再试吧。',
'auth.err.rate': '尝试次数太多,过几分钟再试吧。',
'auth.err.signupDisabled': '暂时关闭注册。',
'auth.err.emailInvalid': '邮箱地址无效。',
'auth.err.invalid': '邮箱地址或密码无效。',
'auth.err.session': '登录已过期,请重新登录。',
'auth.err.status': '服务器拒绝了请求({status})。',
'auth.err.response': '服务器响应无效。',
'auth.err.linkExpired': '链接已过期,请重新申请。',
'auth.err.linkUsed': '链接无效或已被使用。',
'auth.err.linkInvalid': '链接无效。',
'settings.language': '语言',
'settings.backupShared': '备份已分享。',
'settings.backupDownloaded': '备份已下载。',
'settings.exportFailed': '导出失败。',
'settings.noValidItems': '文件中没有有效的条目。',
'settings.imported_one': '已导入{count}个条目。',
'settings.imported_other': '已导入{count}个条目。',
'settings.importedSkipped': '已导入{n}个条目,跳过{skipped}个。',
'settings.cleared': '片库已清空。',
'settings.pageTitle': '我的',
'settings.pageAccent': '设置',
'settings.languageHint': '应用界面、日期以及从 TMDB 获取的信息(标题、简介)所使用的语言。',
'settings.rating': '评分',
'settings.scale5': '★ 5分制',
'settings.scale10': '10分制',
'settings.ratingHint': '5分制可打半星,10分制以0.5分为单位。已有评分会自动换算。',
'settings.theme': '主题',
'settings.themeX': '{name}主题',
'settings.pickColor': '自选颜色',
'settings.freeColor': '自定义颜色',
'settings.freeColorHint': '任意颜色都行:文字会自动调整,保持清晰可读。',
'settings.databases': '影视数据库',
'settings.anilistActive': '动画 · 已启用',
'settings.noConfig': '无需任何配置。',
'settings.tmdbActive': '电影和剧集 · 已启用',
'settings.checking': '检查中…',
'settings.offline': '离线',
'settings.proxyMissingKey': '缺少 TMDB 密钥',
'settings.proxyNotDeployed': '服务器未部署',
'settings.unavailable': '不可用',
'settings.proxyMissingKeyHint': '服务器函数已部署,但你的 TMDB 密钥还没保存(Supabase 中的 TMDB_API_KEY 密钥),或被 TMDB 拒绝了。',
'settings.proxyNotDeployedHint': '「tmdb」函数还没部署到 Supabase(见 README → 账号,第5步)。',
'settings.proxyErrorHint': '服务器暂时无法正常响应。',
'settings.proxyOkHint': '由应用服务器提供:无需输入密钥。',
'settings.recheck': '重新检查',
'settings.keyRefused': '密钥被拒绝',
'settings.notConfigured': '未配置',
'settings.tmdbHelp': '电影、剧集、韩剧、华语剧。在 themoviedb.org 免费注册账号,然后进入「设置」→「API」,粘贴你的「API 密钥」或「API 读访问令牌」。',
'settings.tmdbKey': 'TMDB 密钥',
'settings.hideKey': '隐藏密钥',
'settings.showKey': '显示密钥',
'settings.validate': '确认',
'settings.remove': '移除',
'settings.keyLocal': '密钥只保存在这台设备上,永远不会包含在备份中。',
'settings.topHint': '在首页显示的分类。',
'settings.topNone': '未选择分类:Top 5 区域将被隐藏。',
'settings.backup': '备份',
'settings.export': '导出我的数据',
'settings.exportHint_one': '{count}个条目 · JSON 文件,建议定期备份',
'settings.exportHint_other': '{count}个条目 · JSON 文件,建议定期备份',
'settings.import': '导入备份',
'settings.importHint': '从 .json 文件恢复',
'settings.legacyDetected': '识别到旧版应用的备份',
'settings.found_one': '找到{count}个条目。要怎么导入?',
'settings.found_other': '找到{count}个条目。要怎么导入?',
'settings.foundSkipped': '找到{n}个条目(已跳过{skipped}个无效条目)。要怎么导入?',
'settings.merge': '合并',
'settings.replaceAll': '全部替换',
'settings.mergeHint': '「合并」会添加新条目,并更新已存在的条目(ID 相同)。',
'settings.storage': '存储',
'settings.used': '已用空间',
'settings.storageCloud': '你的数据保存在账号中,同时也保存在这台设备上,没网也能用。一有网络就会自动同步。',
'settings.storageLocal': '你的数据只保存在这台设备的浏览器中。如果清除浏览器数据或卸载应用,数据就会丢失:记得定期导出备份。',
'settings.danger': '危险操作',
'settings.clearAll': '清空整个片库',
'settings.clearAllHint_one': '{count}部作品',
'settings.clearAllHint_other': '{count}部作品',
'settings.clearAllHintCloud_one': '{count}部作品 · 所有设备',
'settings.clearAllHintCloud_other': '{count}部作品 · 所有设备',
'settings.deleting': '删除中…',
'settings.deleteAccount': '删除我的账号',
'settings.deleteAccountHint': '账号和数据将被永久删除',
'settings.footerCloud': '账号已同步',
'settings.footerLocal': '100% 本地',
'settings.clearConfirm_one': '{count}部作品将被永久删除。记得先导出备份。',
'settings.clearConfirm_other': '你的{count}部作品将被永久删除。记得先导出备份。',
'settings.clearConfirmCloud_one': '{count}部作品将在你的所有设备上被永久删除。记得先导出备份。',
'settings.clearConfirmCloud_other': '你的{count}部作品将在你的所有设备上被永久删除。记得先导出备份。',
'settings.clearAllConfirm': '全部清空',
'settings.deleteAccountTitle': '删除你的账号?',
'settings.deleteAccountMessage': '你的账号和所有数据(作品、片单、设置)将从服务器和这台设备上永久删除。记得先导出备份。此操作无法撤销。',
'settings.deleteForever': '永久删除',
'settings.replaceConfirm': '你当前的整个片库将被这个文件的内容替换。',
'settings.replace': '替换',
'sync.err.push': '上传被拒绝({status})',
'sync.err.pull': '读取被拒绝({status})',
'store.dbError': '无法打开本地数据库:{error}',
'store.invalidItem': '无效条目',
'lists.newList': '新建片单',
'lists.newListPh': '新片单…',
'lists.myLists': '我的片单',
'lists.rename': '重命名',
'lists.delete': '删除片单',
'lists.done': '完成',
'lists.addRemove': '添加 / 移除作品',
'lists.searchLibrary': '在我的片库中搜索…',
'lists.emptyTitle': '片单是空的',
'lists.emptyText': '用上方的按钮添加作品,或者在作品详情页里添加。',
'lists.deleteConfirm': '片单「{name}」将被删除。作品仍会保留在你的片库中。',
'lists.noneTitle': '还没有片单',
'lists.noneText': '按你的喜好创建片单:「和朋友一起看」「十月恐怖片」「治愈系电视剧」…',
'lists.create': '创建',
'account.err.deleteRate': '尝试次数太多,一分钟后再试吧。',
'account.err.delete': '删除失败,请稍后再试。',
'account.title': '我的账号',
'account.syncing': '同步中…',
'account.offline': '离线 — 所有内容都保存在这台设备上',
'account.syncError': '暂时无法同步',
'account.synced': '已同步 · {when}',
'account.passwordChanged': '密码已修改。',
'account.imported_one': '已将{count}部作品添加到你的账号。',
'account.imported_other': '已将{count}部作品添加到你的账号。',
'account.importFailed': '导入失败。',
'account.pending_one': '{count}项待同步',
'account.pending_other': '{count}项待同步',
'account.syncNow': '立即同步',
'account.newPasswordPh': '新密码(至少{n}个字符)',
'account.changePassword': '修改密码',
'account.logout': '退出登录',
'account.logoutHint': '你的数据会保留在账号中,并从这台设备上移除。',
'account.ignore': '忽略',
'account.deviceHint': '它们会被移到你的账号中,并同步到你的所有设备。',
'account.unsentTitle': '有未上传的修改',
'account.logoutAnyway': '仍然退出',
'account.unsentMessage_one': '有{count}项修改还没上传(没网吗?)。现在退出的话,这些修改会丢失。',
'account.unsentMessage_other': '有{count}项修改还没上传(没网吗?)。现在退出的话,这些修改会丢失。',
'account.nTitles_one': '{count}部作品',
'account.nTitles_other': '{count}部作品',
'account.nLists_one': '{count}个片单',
'account.nLists_other': '{count}个片单',
'account.deviceData': '这台设备上有注册账号前创建的{titles}。要添加到你的账号吗?',
'account.deviceDataWithLists': '这台设备上有注册账号前创建的{titles}和{lists}。要添加到你的账号吗?',
'time.never': '从未',
'time.justNow': '刚刚',
'time.minutesAgo': '{n}分钟前',
'time.hoursAgo': '{n}小时前',
'time.onDate': '{date}',
'time.today': '今天',
'time.tomorrow': '明天',
'time.daysAgo': '{n}天前',
'theme.red': '红色',
'theme.orange': '橙色',
'theme.yellow': '黄色',
'theme.lime': '青柠',
'theme.green': '绿色',
'theme.mint': '薄荷',
'theme.cyan': '青色',
'theme.blue': '蓝色',
'theme.indigo': '靛蓝',
'theme.violet': '紫色',
'theme.pink': '粉色',
'theme.white': '白色',
'home.seeAll': '查看全部',
'home.subtitle': '我的观影日记',
'home.calendarSoon_one': '上映日历:本周{count}部',
'home.calendarSoon_other': '上映日历:本周{count}部',
'home.emptyTitle': '你的片库是空的',
'home.emptyCloud': '添加你的第一部电影、动画或电视剧吧,它会保存在你的账号中。',
'home.emptyLocal': '添加你的第一部电影、动画或电视剧吧,所有内容只保存在这台手机上。',
'home.completed': '已看完',
'home.thisYear_one': '今年{count}部',
'home.thisYear_other': '今年{count}部',
'home.toWatchN_one': '{count}部想看',
'home.toWatchN_other': '{count}部想看',
'home.screenTime': '观看时长',
'home.estimate': '估算',
'home.episodesSeen': '已看集数',
'home.noIdea': '不知道看什么?',
'home.rouletteHint_one': '从你想看的作品中随机抽一部',
'home.rouletteHint_other': '从你想看的{count}部作品中随机抽一部',
'home.rouletteHintAll': '从你的片库中随机抽一部',
'home.recentlyFinished': '最近看完',
'calendar.title': '上映日历',
'calendar.inMyList': '在我的片库中',
'calendar.inMyListLegend': '在我的片库中',
'calendar.seeMore_one': '查看另一部',
'calendar.seeMore_other': '查看其余{count}部',
'calendar.heading': '上映',
'calendar.headingAccent': '日历',
'calendar.refresh': '刷新',
'calendar.all': '全部上映',
'calendar.mine': '我的作品',
'calendar.prevMonth': '上个月',
'calendar.nextMonth': '下个月',
'calendar.releases_one': '{count}部上映',
'calendar.releases_other': '{count}部上映',
'calendar.others': '其他上映',
'calendar.needKey': '没有 TMDB 密钥时只显示动画。在「设置」中添加密钥,就能同时看到电影、剧集和电视剧。',
'calendar.range': '可查看从上个月到未来6个月的上映信息。',
'calendar.failed': '部分上映信息加载失败,点 ↻ 重试。',
'calendar.nothingThatDay': '这天没有安排。',
'calendar.next14': '未来14天',
'calendar.loading': '正在查找上映信息…',
'calendar.noneMine14': '未来14天你的作品没有上映计划。',
'calendar.noneMineMonth': '本月你的作品没有上映计划。',
'calendar.none14': '未来14天没有上映。',
'calendar.noneMonth': '本月没有找到上映信息。',
'calendar.footer': '你所在国家/地区的院线电影、最热门剧集和电视剧的播出集数(TMDB),以及日本所有在播动画(AniList)。你片库中的作品会高亮显示;点「想看」即可把上映作品加入你的片单。',
'roulette.name': '轮盘',
'roulette.rewatch': '值得重温',
'roulette.anyTime': '不限',
'roulette.heading': '命运',
'roulette.headingAccent': '轮盘',
'roulette.tonight': '今晚就看…',
'roulette.nEps': '{n}集',
'roulette.perEp': '{duration}/集',
'roulette.stoppedAt': '你上次看到第{ep}集。',
'roulette.stoppedAtOf': '你上次看到第{ep}集(共{total}集)。',
'roulette.enjoy': '观影愉快!',
'roulette.again': '再转一次',
'roulette.spinning': '转动中…',
'roulette.spin': '转动轮盘',
'roulette.poolSize_one': '从{count}部作品中抽取',
'roulette.poolSize_other': '从{count}部作品中抽取',
'roulette.empty': '没有符合条件的作品:放宽下方的筛选条件试试。',
'roulette.inside': '轮盘内容',
'roulette.pickFrom': '抽取范围',
'roulette.rewatchHint': '「值得重温」= 你已看完且评分在4/5及以上的作品、心头好和 Top 5。',
'roulette.time': '可用时间(电影或1集)',
'roulette.seeItem': '查看完整详情',
'roulette.watchIt': '就看这个',
'newEp.check': '检查',
'newEp.title': '最新更新',
'newEp.checking': '正在查看有什么新内容…',
'newEp.needKey': '在「设置」中添加你的 TMDB 密钥,就能收到新集和新季的提醒。',
'newEp.nothing_one': '你追的剧集或动画暂无更新。',
'newEp.nothing_other': '你追的{count}部剧集和动画暂无更新。',
'newEp.needKeyAlso': '(在「设置」中添加你的 TMDB 密钥,就能同时追剧集和电视剧。)',
'newEp.newSeason': '新一季',
'newEp.catchUp': '待补',
'newEp.soon': '即将播出',
'newEp.epWhen': '第{ep}集 {when}',
'newEp.available_one': '{count}集可看',
'newEp.available_other': '{count}集可看',
'newEp.next': '下一集:第{ep}集 {when}',
'newEp.resume': '继续看',
'top.pick': '选择第{rank}名',
'top.shareTitle': '我的{category} Top 5',
'top.shareLabel': '将这个 Top 5 分享为图片',
'top.title': '我的 Top',
'top.number': '第{rank}名',
'top.pickFirst': '选出你的第1名。',
'top.editLabel': '编辑 Top 5',
'top.freeSlot': '空位 — 从下方选择一部作品',
'top.addFromLibrary': '从我的片库添加',
'top.allTypes': '所有类型',
'top.searchTitle': '搜索作品…',
'top.full': '你的 Top 5 已满:移除一部作品才能添加新的。',
'top.noCandidates': '没有作品。试试「所有类型」或换个搜索词。',
'reco.error': '暂时无法加载推荐。',
'reco.title': '推荐',
'reco.needKey': '在「设置」中添加你的 TMDB 密钥,就能根据你最爱的作品获得推荐。',
'reco.other': '换一部',
'reco.ifYouLiked': '如果你喜欢',
'reco.loading': '正在查找推荐…',
'reco.none': '和这部作品相似的你都已经有了。试试「换一部」。',
'reco.added': '已添加《{title}》',
'reco.addLabel': '将《{title}》加入想看',
'reco.addedShort': '已添加',
'search.moviesSeries': '电影和剧集',
'search.offline': '没有网络连接:搜索需要联网。',
'search.fillFrom': '从数据库填写',
'search.needKey': '要搜索电影、剧集和电视剧,请在「设置」中添加你的免费 TMDB 密钥。',
'search.openSettings': '打开「设置」',
'search.already': '已添加',
'search.noResults': '没有结果。你可以在下方手动填写。',
'search.privacy': '只有搜索的标题会发送给 {source}。你的片库仍保留在手机上。',
'catalog.sortRecent': '最近修改',
'catalog.sortWatched': '观看日期',
'catalog.sortRating': '评分最高',
'catalog.sortTitle': '标题(A→Z)',
'catalog.pageTitle': '我的',
'catalog.pageAccent': '片库',
'catalog.journalSubtitle': '你的观看记录',
'catalog.filteredCount_one': '{count}部作品(已筛选)',
'catalog.filteredCount_other': '{count}部作品(已筛选)',
'catalog.titles': '作品',
'catalog.journal': '日记',
'catalog.lists': '片单',
'catalog.searchPh': '标题、类型、平台…',
'catalog.moreFilters': '更多筛选',
'catalog.all': '全部',
'catalog.genre': '类型',
'catalog.minRating': '最低评分',
'catalog.allRatings': '全部',
'catalog.sortBy': '排序方式',
'catalog.favorites': '心头好',
'catalog.reset': '重置',
'catalog.noResults': '没有结果',
'catalog.nothingYet': '暂时还没有内容',
'catalog.noResultsHint': '换个搜索词或移除一些筛选条件试试。',
'catalog.nothingYetHint': '点 + 按钮添加你的第一部作品。',
'catalog.clearFilters': '清除筛选',
'public.agree': '和大众评价完全一致',
'public.more': '比大众高 +{gap}',
'public.less': '比大众低 −{gap}',
'public.label': '大众',
'public.me': '我',
'public.added_one': '已添加{count}个大众评分。',
'public.added_other': '已添加{count}个大众评分。',
'public.noneFound': '没有找到新的评分。',
'public.fetch': '获取({n})',
'public.title': '我 vs 大众',
'public.hintFetch': '获取你已评分作品在 TMDB / AniList 上的平均分,看看你和大众哪里不一样。',
'public.hintNone': '这段时间内你已评分的作品暂无大众评分。',
'public.hintKey': '在「设置」中添加你的 TMDB 密钥(或关联 AniList 的动画),就能和大众对比。',
'public.avgGap': '平均差距',
'public.average': '与大众持平',
'public.generous': '比大众更宽容',
'public.harsh': '比大众更严格',
'public.agreeTitle': '意见一致',
'public.within5_one': '相差 ½ 星以内,共{count}部作品',
'public.within5_other': '相差 ½ 星以内,共{count}部作品',
'public.within10_one': '相差1分以内,共{count}部作品',
'public.within10_other': '相差1分以内,共{count}部作品',
'public.lovedPre': '我比大众',
'public.lovedAccent': '更喜欢',
'public.lovedPost': '',
'public.hatedPre': '我比大众',
'public.hatedAccent': '更不喜欢',
'public.hatedPost': '',
'public.allAgree': '你对所有作品的看法都和大众一致。真少见!',
'form.rewatchHint': '又看了一遍?记录每次重温,它会出现在你的日记里。',
'form.editTitle': '编辑',
'form.editAccent': '条目',
'form.newTitle': '新增',
'form.newAccent': '作品',
'form.filledFrom': '数据来自',
'form.canEdit': '所有内容都可以修改',
'form.fillFromDb': '从 TMDB / AniList 补全',
'form.pickPoster': '选择海报',
'form.removeImage': '移除图片',
'form.title': '标题 *',
'form.titlePh': '例如 Your Name',
'form.originalTitle': '原标题',
'form.originalTitlePh': '例如 君の名は。',
'form.synopsis': '简介',
'form.type': '类别',
'form.subtype': '细分',
'form.subtypePh': '纪录片、真人秀…',
'form.status': '状态',
'form.myRating': '我的评分',
'form.favorite': '心头好',
'form.criteria': '详细评分(可选)',
'form.episodes': '集数',
'form.minusEp': '-1集',
'form.plusEp': '+1集',
'form.total': '总集数',
'form.season': '季',
'form.minPerEp': '分钟/集',
'form.duration': '时长',
'form.durationMin': '时长(分钟)',
'form.info': '信息',
'form.start': '开始 / 观看日期',
'form.end': '结束',
'form.year': '年份',
'form.platform': '平台',
'form.genres': '类型 / 标签',
'form.genresPh': '爱情、科幻…',
'form.rewatches': '重温记录',
'form.review': '我的短评',
'form.reviewPh': '我的感想、印象深刻的场景…',
'form.saveChanges': '保存修改',
'form.addToLibrary': '添加到我的片库',
'form.shareImage': '分享为图片',
'form.delete': '删除这部作品',
'form.deleteConfirm': '《{title}》将被永久删除。',
'form.removeRewatch': '移除这次重温',
'form.rewatchDate': '重温日期',
'form.reviewPublic': '在我的主页上显示这条短评',
'form.reviewPublicHint': '否则只有你自己能看到。',
'journal.rewatched': '重温',
'journal.started': '开始看',
'journal.emptyTitle': '日记是空的',
'journal.emptyText': '只要你的作品填写了开始或结束日期,观看记录就会显示在这里。',
'journal.seen_one': '看了{count}部',
'journal.seen_other': '看了{count}部',
'journal.more': '显示更早的月份',
'stats.overview': '概览',
'stats.habits': '习惯',
'stats.tastes': '口味',
'stats.pageTitle': '我的',
'stats.pageAccent': '统计',
'stats.emptyTitle': '还没有统计数据',
'stats.emptyText': '添加作品后,统计数据就会出现在这里。',
'stats.sinceStart': '从开始至今',
'stats.subtitle_one': '我的片库中有{count}部作品',
'stats.subtitle_other': '我的片库中有{count}部作品',
'stats.subtitleYear_one': '{year}年{count}部作品',
'stats.subtitleYear_other': '{year}年{count}部作品',
'stats.hours_one': '小时',
'stats.hours_other': '小时',
'stats.nonStopPre': '相当于连续看了',
'stats.nonStopPost': '',
'stats.days_one': '{count}天',
'stats.days_other': '{count}天',
'stats.finishedN_one': '看完{count}部',
'stats.finishedN_other': '看完{count}部',
'stats.episodesN_one': '{count}集',
'stats.episodesN_other': '{count}集',
'stats.timeByType': '各类别时长',
'stats.noTime': '这段时间内还没有记录时长。',
'stats.avgRating': '平均评分',
'stats.rated_one': '已评分{count}部',
'stats.rated_other': '已评分{count}部',
'stats.inYear': '{year}年',
'stats.statuses': '状态',
'stats.hoursTab': '时长',
'stats.monthByMonth': '逐月统计 · {year}',
'stats.last12': '最近12个月',
'stats.monthFinished_one': '看完{count}部作品',
'stats.monthFinished_other': '看完{count}部作品',
'stats.busiest': '最忙的月份:',
'stats.records': '纪录',
'stats.marathon': '最长马拉松',
'stats.longestFilm': '最长的电影',
'stats.noRecords': '这段时间内还没有纪录。',
'stats.platforms': '平台',
'stats.bestRated': '我的最高分',
'stats.myRatings': '我的评分',
'stats.noRatings': '这段时间内没有评分。',
'stats.favGenres': '最爱类型',
'stats.noGenres': '还没有类型。',
'stats.countries': '国家/地区',
'stats.noCountry_one': '{count}部作品缺少国家/地区:在详情页中通过「从 TMDB / AniList 补全」补上吧。',
'stats.noCountry_other': '{count}部作品缺少国家/地区:在详情页中通过「从 TMDB / AniList 补全」补上吧。',
'stats.noCountryLegacy_one': '{count}部作品缺少国家/地区:在详情页中通过「从 TMDB / AniList 补全」补上,或重新导入旧版应用的备份(「合并」)。',
'stats.noCountryLegacy_other': '{count}部作品缺少国家/地区:在详情页中通过「从 TMDB / AniList 补全」补上,或重新导入旧版应用的备份(「合并」)。',
'stats.byType': '按类别',
'stats.footnote': '时长根据已看集数和填写的时长估算(未填写时:电影1小时50分,动画每集24分钟,剧集每集45分钟,韩剧每集1小时,华语剧每集45分钟)。作品计入我看完它的那一年。',
'stats.ratedAs_one': '评分{rating}',
'stats.ratedAs_other': '评分{rating}',
'backup.shareTitle': 'AzuuCine 备份',
'backup.tooBig': '文件太大(最大30 MB)。',
'backup.notJson': '这个文件不是有效的 JSON。',
'backup.noItems': '这个文件中没有找到任何条目。',
'backup.tooMany': '条目太多(最多{n}个)。',
'image.canvas': 'Canvas 不可用',
'image.unreadable': '无法读取图片',
'image.notImage': '这个文件不是图片。',
'image.tooBig': '图片太大(最大25 MB)。',
'social.err.server': '服务器返回了 {status}。',
'social.err.usernameTaken': '这个用户名已被占用。',
'social.err.usernameReserved': '这个用户名不可用。',
'social.err.invalid': '有一项内容无效。',
'social.inLibrary': '在我的片库中',
'social.addToWatch': '加入「想看」',
'social.linkCopied': '链接已复制!',
'social.profile': '主页',
'social.shareProfile': '分享主页',
'social.loading': '加载中…',
'social.loadError': '无法加载主页。',
'social.notFound': '找不到这个主页',
'social.notFoundHint': '没有用户名为 @{username} 的主页。',
'social.editProfile': '编辑主页',
'social.following': '已关注',
'social.requested': '已申请',
'social.followBack': '回关',
'social.follow': '关注',
'social.private': '私密账号',
'social.followsYou': '关注了你',
'social.seen': '看过',
'social.followers_one': '粉丝',
'social.followers_other': '粉丝',
'social.followingCount_one': '关注',
'social.followingCount_other': '关注',
'social.requests_one': '{count}条关注申请',
'social.requests_other': '{count}条关注申请',
'social.privateTitle': '这是私密账号',
'social.privateText': '关注后即可查看 Ta 的观看记录、评分和 Top 5。',
'social.tabProfile': '主页',
'social.tabLibrary': '片库',
'social.cancelRequestTitle': '取消关注申请?',
'social.unfollowTitle': '取消关注{name}?',
'social.unfollowPrivate': '这是私密账号:之后想再看 Ta 的主页需要重新申请。',
'social.cancelRequest': '取消申请',
'social.unfollow': '取消关注',
'social.top5': 'Top 5',
'social.recent': '最近看过',
'social.noRecent': '暂时还没有看完的作品。',
'social.statYear': '今年看过',
'social.statFilms': '看过的电影',
'social.statSeries': '看过的剧集和动画',
'social.emptyLibrary': '这里还没有作品。',
'social.loadMore': '查看更多',
'social.changeBanner': '更换横幅',
'social.changeAvatar': '更换头像',
'social.removeAvatar': '移除头像',
'social.removeBanner': '移除横幅',
'social.displayName': '昵称',
'social.username': '用户名',
'social.usernameRule': '3–20 个字符:小写字母、数字或 _',
'social.bio': '简介',
'social.bioPh': '你喜欢看什么、最爱的类型…',
'social.privateAccount': '私密账号',
'social.privateHint': '只有你同意的粉丝才能看到你的观看记录。',
'social.publicHint': '你的昵称、用户名、头像、横幅和简介对所有用户可见。你写的短评保持私密,除非你选择在主页上显示。',
'social.requestsTab_one': '申请',
'social.requestsTab_other': '申请({count})',
'social.noFollowing': '还没有关注任何人。',
'social.noFollowers': '还没有粉丝。',
'social.accept': '同意',
'social.decline': '拒绝',
'social.removeFollower': '移除',
'social.findFriends': '寻找好友',
'social.searchPh': '用户名或昵称…',
'social.noResults': '没有找到匹配的人。',
'social.inviteHint': '你的朋友还没用 AzuuCine?把你的主页链接发给他们吧。',
'social.shareMyProfile': '分享我的主页',
'social.inviteText': '来 AzuuCine 关注我吧!',
'social.myProfile': '我的主页',
'feed.title': '我的关注',
'feed.empty': '关注好友后,就能在这里看到他们在看什么、有什么感想。',
'feed.finished': '看完了',
'feed.started': '开始看',
'feed.rewatched': '重温了',
'feed.added': '想看',
'feed.review': '短评',
}
export default dict
+55
View File
@@ -0,0 +1,55 @@
import { Fragment, createContext, useCallback, useContext, useState, type ReactNode } from 'react'
import { getLang, LANGS, loadLang, t, type Lang } from '.'
interface LangApi {
lang: Lang
setLang: (l: Lang) => Promise<void>
}
const LangContext = createContext<LangApi>({ lang: 'fr', setLang: async () => {} })
// Caches qui contiennent du texte déjà traduit (libellés des sorties) : à refaire dans la nouvelle langue
const TRANSLATED_CACHES = ['azuucine:releases', 'azuucine:global-releases']
/** Langue active. Changer de langue ré-affiche toute l'app (les données ne bougent pas). */
export function LangProvider({ children }: { children: ReactNode }) {
const [lang, setState] = useState<Lang>(getLang)
const setLang = useCallback(async (l: Lang) => {
if (l === getLang()) return
await loadLang(l)
for (const k of TRANSLATED_CACHES) {
try {
localStorage.removeItem(k)
} catch {
/* ignore */
}
}
setState(l)
}, [])
return (
<LangContext.Provider value={{ lang, setLang }}>
<Fragment key={lang}>{children}</Fragment>
</LangContext.Provider>
)
}
export const useLang = () => useContext(LangContext)
/** Sélecteur de langue (noms dans leur propre langue). */
export function LanguageSelect({ className }: { className?: string }) {
const { lang, setLang } = useLang()
return (
<select
value={lang}
onChange={(e) => void setLang(e.target.value as Lang)}
className={className ?? 'field'}
aria-label={t('settings.language')}
>
{LANGS.map((l) => (
<option key={l.code} value={l.code}>
{l.label}
</option>
))}
</select>
)
}
+133
View File
@@ -0,0 +1,133 @@
@import 'tailwindcss';
/*
* Thème AzuuCine — fond noir + une couleur d'accent (rouge par défaut, modifiable dans Réglages → Thème).
* Pas de dégradés ni d'ombres : aplats, filets de 1px, boutons pilule.
* Une seule police (Inter), comme une appli type Letterboxd.
*/
@theme {
--color-bg: #0a0a0a;
--color-surface: #111110;
--color-surface-2: #181817;
--color-line: #262624;
--color-line-strong: #3a3936;
--color-ink: #f4f2ee;
--color-ink-2: #b3b0a8;
--color-ink-3: #8a8781;
/* Rouge pour texte / icônes / filets sur fond noir */
--color-accent: #ef4444;
/* Rouge plein (boutons), avec texte blanc */
--color-accent-fill: #d11f2f;
/* Texte posé sur un bouton plein (blanc ou noir selon le thème) */
--color-on-accent: #ffffff;
--font-sans: 'Inter', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
}
@layer base {
html,
body,
#root {
min-height: 100%;
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;
overscroll-behavior-y: none;
}
h1,
h2,
h3 {
font-weight: 700;
letter-spacing: -0.01em;
}
/* Évite le zoom automatique d'iOS sur les champs (police >= 16px) */
input,
select,
textarea {
font-size: 16px;
}
button {
cursor: pointer;
}
::selection {
background: var(--color-accent-fill);
color: var(--color-on-accent);
}
}
/* Petite étiquette en capitales (titres de section, libellés de champs) */
@utility eyebrow {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--color-ink-3);
}
@layer components {
.field {
@apply w-full rounded-xl border border-line bg-surface px-3.5 py-2.5 text-ink placeholder:text-ink-3 outline-none transition-colors focus:border-accent;
}
.label {
@apply eyebrow mb-2 block;
}
.chip {
@apply inline-flex shrink-0 items-center gap-1.5 rounded-full border border-line px-3.5 py-1.5 text-sm text-ink-2 transition-colors active:scale-[0.97];
}
.chip-on {
@apply border-ink bg-ink text-bg;
}
.btn {
@apply inline-flex items-center justify-center gap-2 rounded-full px-5 py-2.5 text-[15px] font-medium transition-colors active:scale-[0.98] disabled:opacity-40;
}
.btn-primary {
@apply bg-accent-fill text-on-accent;
}
.btn-light {
@apply bg-ink text-bg;
}
.btn-ghost {
@apply border border-ink/80 text-ink;
}
.card {
@apply rounded-2xl border border-line bg-surface;
}
.no-scrollbar {
scrollbar-width: none;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
}
.safe-top {
padding-top: env(safe-area-inset-top);
}
.safe-bottom {
padding-bottom: env(safe-area-inset-bottom);
}
/* Apparition douce des feuilles (formulaire, recherche) — pas de fondu de couleur */
@keyframes sheet-in {
from {
transform: translateY(16px);
opacity: 0;
}
to {
transform: none;
opacity: 1;
}
}
.sheet-in {
animation: sheet-in 0.22s ease-out;
}
@media (prefers-reduced-motion: reduce) {
.sheet-in {
animation: none;
}
}
+223
View File
@@ -0,0 +1,223 @@
import { tmdbLanguage } from '../i18n'
import type { MediaItem } from '../types'
import { CLOUD_TMDB, isPlausibleTmdbKey } from './catalogApi'
import { tmdbViaCloud } from './cloud/api'
import { TYPE_BY_VALUE } from './constants'
import { isPlainObject, isSafeExternalId, isSafeId, readStorage, safeDay, safeIso } from './security'
/**
* Suivi des nouveaux épisodes.
* Pour chaque série / anime suivi, on demande à TMDB ou AniList combien d'épisodes
* sont déjà sortis, et quand sort le prochain. Le résultat est gardé en cache local.
*/
export interface AiringInfo {
/** Épisodes déjà diffusés */
aired: number
/** Prochain épisode annoncé */
next?: { episode: number; season?: number; date: string }
/** Série terminée / annulée : plus besoin de vérifier souvent */
ended: boolean
seasons?: number
checkedAt: string
}
export type AiringCache = Record<string, AiringInfo>
const KEY = 'azuucine:airing'
const RECHECK_MS = 12 * 3600 * 1000
const RECHECK_ENDED_MS = 30 * 24 * 3600 * 1000
const n0 = (v: unknown, max = 100000) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v)) : 0)
/** Relit le cache en ne gardant que des entrées bien formées. */
export function loadAiring(): AiringCache {
const raw = readStorage(KEY, {})
const out: AiringCache = {}
if (!isPlainObject(raw)) return out
for (const [id, v] of Object.entries(raw)) {
if (!isSafeId(id) || !isPlainObject(v)) continue
const checkedAt = safeIso(v.checkedAt)
if (!checkedAt) continue
const next = isPlainObject(v.next) && safeDay(v.next.date) ? { episode: n0(v.next.episode), season: n0(v.next.season) || undefined, date: v.next.date as string } : undefined
out[id] = { aired: n0(v.aired), ended: v.ended === true, seasons: n0(v.seasons) || undefined, next, checkedAt }
}
return out
}
/** Émis quand le cache des sorties change (pastille du calendrier). */
export const CACHE_EVENT = 'azuucine:schedule'
export function saveAiring(cache: AiringCache) {
try {
localStorage.setItem(KEY, JSON.stringify(cache))
} catch {
/* ignore */
}
window.dispatchEvent(new Event(CACHE_EVENT))
}
/** Fiches à surveiller : séries/animes liés à TMDB ou AniList, en cours, en pause ou terminés. */
export function trackable(items: MediaItem[]): MediaItem[] {
return items.filter(
(i) =>
TYPE_BY_VALUE[i.type].episodic &&
(i.status === 'en_cours' || i.status === 'pause' || i.status === 'termine') &&
isSafeExternalId(i.externalId) &&
(i.externalId.startsWith('tmdb:tv:') || i.externalId.startsWith('anilist:')),
)
}
export function needsCheck(item: MediaItem, cache: AiringCache, force = false): boolean {
const info = cache[item.id]
if (!info || force) return true
const age = Date.now() - new Date(info.checkedAt).getTime()
return age > (info.ended ? RECHECK_ENDED_MS : RECHECK_MS)
}
// ───────── TMDB ─────────
interface TmdbTv {
number_of_episodes?: number
number_of_seasons?: number
status?: string
last_episode_to_air?: { season_number: number; episode_number: number } | null
next_episode_to_air?: { season_number: number; episode_number: number; air_date?: string } | null
seasons?: { season_number: number; episode_count: number }[]
}
async function checkTmdb(tvId: string, key: string): Promise<Omit<AiringInfo, 'checkedAt'>> {
const k = key.trim()
if (!/^\d{1,10}$/.test(tvId) || (k !== CLOUD_TMDB && !isPlausibleTmdbKey(k))) throw new Error('Requête refusée')
let d: TmdbTv
if (k === CLOUD_TMDB) {
d = await tmdbViaCloud<TmdbTv>(`/tv/${tvId}`, { language: tmdbLanguage() })
} else {
const bearer = k.length > 40
const url = new URL(`https://api.themoviedb.org/3/tv/${tvId}`)
url.searchParams.set('language', tmdbLanguage())
if (!bearer) url.searchParams.set('api_key', k)
const res = await fetch(url, { headers: bearer ? { Authorization: `Bearer ${k}` } : {}, referrerPolicy: 'no-referrer', credentials: 'omit' })
if (!res.ok) throw new Error(`TMDB ${res.status}`)
d = (await res.json()) as TmdbTv
}
// Épisodes diffusés = épisodes des saisons terminées + position du dernier épisode diffusé
let aired = n0(d.number_of_episodes)
const last = d.last_episode_to_air
if (last && Array.isArray(d.seasons) && d.seasons.length) {
aired = n0(
d.seasons
.filter((s) => n0(s.season_number) > 0 && n0(s.season_number) < n0(last.season_number))
.reduce((sum, s) => sum + n0(s.episode_count), 0) + n0(last.episode_number),
)
}
const nx = d.next_episode_to_air
const nextDate = safeDay(nx?.air_date)
return {
aired,
seasons: n0(d.number_of_seasons) || undefined,
ended: d.status === 'Ended' || d.status === 'Canceled',
next: nx && nextDate ? { episode: n0(nx.episode_number), season: n0(nx.season_number) || undefined, date: nextDate } : undefined,
}
}
// ───────── AniList (une seule requête pour tous les animes) ─────────
async function checkAniList(ids: number[]): Promise<Map<number, Omit<AiringInfo, 'checkedAt'>>> {
const out = new Map<number, Omit<AiringInfo, 'checkedAt'>>()
for (let i = 0; i < ids.length; i += 50) {
const chunk = ids.slice(i, i + 50)
const res = await fetch('https://graphql.anilist.co', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
body: JSON.stringify({
query: `query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id episodes status nextAiringEpisode { episode airingAt } } } }`,
variables: { ids: chunk },
}),
})
if (!res.ok) throw new Error(`AniList ${res.status}`)
const json = (await res.json()) as {
data?: { Page?: { media?: { id: number; episodes?: number | null; status?: string; nextAiringEpisode?: { episode: number; airingAt: number } | null }[] } }
}
const media = json.data?.Page?.media
for (const m of Array.isArray(media) ? media : []) {
if (!Number.isInteger(m?.id)) continue
const nx = m.nextAiringEpisode
const ts = n0(nx?.airingAt, 4102444800) // borne : an 2100
out.set(m.id, {
aired: nx ? Math.max(0, n0(nx.episode) - 1) : n0(m.episodes),
ended: m.status === 'FINISHED' || m.status === 'CANCELLED',
next: nx && ts ? { episode: n0(nx.episode), date: new Date(ts * 1000).toISOString().slice(0, 10) } : undefined,
})
}
}
return out
}
/** Vérifie les fiches qui en ont besoin et renvoie le cache mis à jour. */
export async function refreshAiring(items: MediaItem[], cache: AiringCache, tmdbKey?: string, force = false): Promise<AiringCache> {
const now = new Date().toISOString()
const next: AiringCache = { ...cache }
const todo = trackable(items).filter((i) => needsCheck(i, cache, force))
const ani = todo.filter((i) => i.externalId!.startsWith('anilist:')).slice(0, 500)
if (ani.length) {
try {
const res = await checkAniList(ani.map((i) => Number(i.externalId!.split(':')[1])))
for (const i of ani) {
const info = res.get(Number(i.externalId!.split(':')[1]))
if (info) next[i.id] = { ...info, checkedAt: now }
}
} catch {
/* réseau indisponible : on réessaiera plus tard */
}
}
if (tmdbKey?.trim()) {
const tv = todo.filter((i) => i.externalId!.startsWith('tmdb:tv:')).slice(0, 300)
// 4 requêtes en parallèle maximum
for (let i = 0; i < tv.length; i += 4) {
await Promise.all(
tv.slice(i, i + 4).map(async (item) => {
try {
next[item.id] = { ...(await checkTmdb(item.externalId!.split(':')[2], tmdbKey)), checkedAt: now }
} catch {
/* ignore cette fiche */
}
}),
)
}
}
return next
}
export interface Novelty {
item: MediaItem
info: AiringInfo
/** Épisodes sortis que je n'ai pas encore vus */
unwatched: number
kind: 'new_episodes' | 'new_season' | 'upcoming'
}
/** Ce qu'il faut signaler sur l'accueil. */
export function novelties(items: MediaItem[], cache: AiringCache): Novelty[] {
const out: Novelty[] = []
const soon = Date.now() + 14 * 24 * 3600 * 1000
for (const item of trackable(items)) {
const info = cache[item.id]
if (!info) continue
const unwatched = Math.max(0, info.aired - item.episodesWatched)
if (item.status === 'termine') {
// Terminé de mon côté, mais de nouveaux épisodes sont sortis depuis → nouvelle saison
if (unwatched > 0 && item.episodesTotal && info.aired > item.episodesTotal) out.push({ item, info, unwatched, kind: 'new_season' })
} else if (unwatched > 0) {
out.push({ item, info, unwatched, kind: 'new_episodes' })
} else if (info.next && new Date(info.next.date).getTime() < soon) {
out.push({ item, info, unwatched: 0, kind: 'upcoming' })
}
}
const order = { new_season: 0, new_episodes: 1, upcoming: 2 }
return out.sort((a, b) => order[a.kind] - order[b.kind] || (a.info.next?.date ?? '').localeCompare(b.info.next?.date ?? ''))
}
+199
View File
@@ -0,0 +1,199 @@
import { t } from '../i18n'
import type { BackupFile, Criteria, CustomList, MediaItem, MediaType, Settings, TopCategory, TopEntry, WatchStatus } from '../types'
import { ALL_TOP_CATEGORIES, MEDIA_TYPES, STATUSES } from './constants'
import { convertLegacyBackup, isLegacyBackup } from './legacyImport'
import {
cleanText,
isHexColor,
isPlainObject,
isSafeExternalId,
isSafeId,
LIMITS,
safeCountries,
safeDay,
safeIso,
safePosterUrl,
safeStringList,
} from './security'
import { todayISO, uid } from './utils'
const TYPES = new Set<string>(MEDIA_TYPES.map((t) => t.value))
const STATUS_SET = new Set<string>(STATUSES.map((s) => s.value))
const num = (v: unknown, min = 0, max = 1e6): number | undefined => {
const n = typeof v === 'string' && v.length < 20 ? Number(v) : v
return typeof n === 'number' && Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : undefined
}
const int = (v: unknown, min = 0, max = 1e6) => {
const n = num(v, min, max)
return n == null ? undefined : Math.round(n)
}
const rating = (v: unknown) => {
const n = num(v, 0, 10)
return n == null || n === 0 ? undefined : Math.round(n * 2) / 2
}
const isTopCategory = (v: unknown): v is TopCategory => ALL_TOP_CATEGORIES.includes(v as TopCategory)
function normalizeTop(v: unknown): TopEntry | undefined {
if (!isPlainObject(v)) return undefined
const rank = Number(v.rank)
return isTopCategory(v.category) && Number.isInteger(rank) && rank >= 1 && rank <= 5 ? { category: v.category, rank } : undefined
}
export function normalizeLists(v: unknown): CustomList[] | undefined {
if (!Array.isArray(v)) return undefined
const out: CustomList[] = []
for (const l of v.slice(0, LIMITS.lists)) {
if (!isPlainObject(l) || !isSafeId(l.id) || out.some((x) => x.id === l.id)) continue
const name = cleanText(l.name, LIMITS.shortText)
if (name) out.push({ id: l.id, name, createdAt: safeIso(l.createdAt) ?? new Date().toISOString() })
}
return out
}
/** Liste de dates AAAA-MM-JJ valides, triées, sans doublon (200 max). */
function safeDates(v: unknown): string[] | undefined {
if (!Array.isArray(v)) return undefined
const out = [...new Set(v.slice(0, 500).map(safeDay).filter((d): d is string => !!d))].sort().slice(-200)
return out.length ? out : undefined
}
/** Valide et nettoie une fiche venant d'un fichier importé. Renvoie null si inutilisable. */
export function normalizeItem(raw: unknown): MediaItem | null {
if (!isPlainObject(raw)) return null
const r = raw
const title = cleanText(r.title, LIMITS.title)
if (!title) return null
const now = new Date().toISOString()
const criteriaRaw = isPlainObject(r.criteria) ? r.criteria : {}
const criteria: Criteria = {}
for (const k of ['story', 'cast', 'direction', 'ost'] as const) {
const v = rating(criteriaRaw[k])
if (v != null) criteria[k] = v
}
const type = (TYPES.has(r.type as string) ? r.type : 'autre') as MediaType
const episodesTotal = int(r.episodesTotal, 0, 100000) || undefined
let episodesWatched = int(r.episodesWatched, 0, 100000) ?? 0
if (episodesTotal && episodesWatched > episodesTotal) episodesWatched = episodesTotal
const listIds = safeStringList(r.listIds, LIMITS.lists, 64).filter(isSafeId)
return {
id: isSafeId(r.id) ? r.id : uid(),
title,
originalTitle: cleanText(r.originalTitle, LIMITS.title),
type,
subtype: type === 'autre' ? cleanText(r.subtype, LIMITS.shortText) : undefined,
year: int(r.year, 1870, 2200),
status: (STATUS_SET.has(r.status as string) ? r.status : 'a_voir') as WatchStatus,
rating: rating(r.rating),
criteria,
favorite: r.favorite === true || undefined,
episodesWatched,
episodesTotal,
season: int(r.season, 0, 1000) || undefined,
episodeDuration: int(r.episodeDuration, 0, 1440) || undefined,
duration: int(r.duration, 0, 6000) || undefined,
startDate: safeDay(r.startDate),
endDate: safeDay(r.endDate),
genres: safeStringList(r.genres, LIMITS.genres),
platform: cleanText(r.platform, LIMITS.shortText),
notes: cleanText(r.notes, LIMITS.notes),
notesPublic: r.notesPublic === true || undefined,
poster: safePosterUrl(r.poster),
overview: cleanText(r.overview, LIMITS.overview),
externalId: isSafeExternalId(r.externalId) ? r.externalId : undefined,
top: normalizeTop(r.top),
listIds: listIds.length ? listIds : undefined,
countries: safeCountries(r.countries),
rewatchDates: safeDates(r.rewatchDates),
publicRating: (() => {
const n = num(r.publicRating, 0, 10)
return n ? Math.round(n * 10) / 10 : undefined
})(),
createdAt: safeIso(r.createdAt) ?? now,
updatedAt: safeIso(r.updatedAt) ?? now,
}
}
/** Réglages importés : seules les valeurs connues et valides sont gardées. */
export function normalizeSettings(raw: unknown): Partial<Settings> | undefined {
if (!isPlainObject(raw)) return undefined
const out: Partial<Settings> = {}
if (raw.ratingScale === '5' || raw.ratingScale === '10') out.ratingScale = raw.ratingScale
if (Array.isArray(raw.topCategories)) out.topCategories = ALL_TOP_CATEGORIES.filter((c) => (raw.topCategories as unknown[]).includes(c))
if (isHexColor(raw.accentColor)) out.accentColor = raw.accentColor.toLowerCase()
return out
}
/** Garde une seule fiche par identifiant (la dernière). */
function dedupe(items: MediaItem[]): MediaItem[] {
return [...new Map(items.map((i) => [i.id, i])).values()]
}
export function buildBackup(items: MediaItem[], settings: Settings, lists: CustomList[] = []): BackupFile {
// La clé TMDB n'est jamais incluse dans la sauvegarde
const { tmdbKey: _omit, ...safeSettings } = settings
return { app: 'AzuuCine', version: 1, exportedAt: new Date().toISOString(), settings: safeSettings, items, lists }
}
/**
* Enregistre la sauvegarde. Sur mobile, ouvre la feuille de partage si possible
* (iOS : « Enregistrer dans Fichiers »), sinon télécharge le fichier.
*/
export async function exportBackup(items: MediaItem[], settings: Settings, lists: CustomList[] = []): Promise<'shared' | 'downloaded'> {
const json = JSON.stringify(buildBackup(items, settings, lists), null, 2)
const filename = `azuucine-sauvegarde-${todayISO()}.json`
const file = new File([json], filename, { type: 'application/json' })
const isTouch = window.matchMedia?.('(pointer: coarse)').matches
if (isTouch && navigator.canShare?.({ files: [file] })) {
try {
await navigator.share({ files: [file], title: t('backup.shareTitle') })
return 'shared'
} catch (e) {
if ((e as DOMException)?.name === 'AbortError') throw e
/* sinon : on retombe sur le téléchargement */
}
}
const url = URL.createObjectURL(file)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
return 'downloaded'
}
export interface ParsedBackup {
items: MediaItem[]
settings?: Partial<Settings>
lists?: CustomList[]
skipped: number
/** Format reconnu */
format: 'azuucine' | 'legacy'
}
/** Accepte le format AzuuCine, un simple tableau de fiches, ou une sauvegarde de l'ancienne appli. */
export async function parseBackupFile(file: File): Promise<ParsedBackup> {
if (file.size > LIMITS.importFileBytes) throw new Error(t('backup.tooBig'))
const text = await file.text()
let data: unknown
try {
data = JSON.parse(text)
} catch {
throw new Error(t('backup.notJson'))
}
if (isLegacyBackup(data)) {
const legacy = convertLegacyBackup(data)
return { items: dedupe(legacy.items), skipped: legacy.skipped, format: 'legacy' }
}
const rawItems = Array.isArray(data) ? data : isPlainObject(data) && Array.isArray(data.items) ? data.items : null
if (!rawItems) throw new Error(t('backup.noItems'))
if (rawItems.length > LIMITS.items) throw new Error(t('backup.tooMany', { n: LIMITS.items }))
const items = dedupe(rawItems.map(normalizeItem).filter((i): i is MediaItem => i !== null))
const settings = isPlainObject(data) ? normalizeSettings(data.settings) : undefined
const lists = isPlainObject(data) ? normalizeLists(data.lists) : undefined
return { items, settings, lists, skipped: rawItems.length - items.length, format: 'azuucine' }
}
+909
View File
@@ -0,0 +1,909 @@
import type { MediaInput, MediaType } from '../types'
import { region, t, tmdbLanguage } from '../i18n'
import { tmdbViaCloud } from './cloud/api'
import { TYPE_BY_VALUE } from './constants'
import { subtypeLabel, tmdbGenres } from './genres'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safePosterUrl, safeStringList } from './security'
/**
* Recherche dans les bases publiques :
* - TMDB : films, séries, K-dramas, C-dramas, documentaires… (clé API gratuite requise)
* - AniList : animes (aucune clé nécessaire)
* Seul le texte recherché est envoyé ; la bibliothèque reste sur l'appareil.
*/
export type Source = 'tmdb' | 'anilist'
export interface SearchResult {
source: Source
/** ex. « tmdb:movie:496243 », « tmdb:tv:1396 », « anilist:154587 » */
externalId: string
title: string
originalTitle?: string
year?: number
/** Petite image pour la liste de résultats */
thumb?: string
kindLabel: string
typeGuess: MediaType
/** Données déjà complètes (AniList) — sinon on va chercher le détail */
prefill?: Partial<MediaInput>
/** URL de l'affiche en bonne qualité */
posterUrl?: string
}
// ─────────────────────────── Nettoyage des réponses ───────────────────────────
const TYPES = new Set<MediaType>(['film', 'serie', 'anime', 'kdrama', 'cdrama', 'autre'])
const count = (n: unknown, max: number) => (typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.min(max, Math.round(n)) : undefined)
/** Les réponses des API sont non fiables : on borne et on filtre chaque champ. */
export function sanitizeMeta(d: Partial<MediaInput>): Partial<MediaInput> {
const genres = safeStringList(d.genres, LIMITS.genres)
return {
title: cleanText(d.title, LIMITS.title),
originalTitle: cleanText(d.originalTitle, LIMITS.title),
type: d.type && TYPES.has(d.type) ? d.type : undefined,
subtype: cleanText(d.subtype, LIMITS.shortText),
year: typeof d.year === 'number' && d.year >= 1870 && d.year <= 2200 ? Math.round(d.year) : undefined,
overview: cleanText(d.overview, LIMITS.overview),
genres: genres.length ? genres : undefined,
platform: cleanText(d.platform, LIMITS.shortText),
duration: count(d.duration, 6000),
episodesTotal: count(d.episodesTotal, 100000),
episodeDuration: count(d.episodeDuration, 1440),
externalId: isSafeExternalId(d.externalId) ? d.externalId : undefined,
countries: safeCountries(d.countries),
poster: safePosterUrl(d.poster),
publicRating:
typeof d.publicRating === 'number' && d.publicRating > 0 && d.publicRating <= 10 ? Math.round(d.publicRating * 10) / 10 : undefined,
}
}
/** Note TMDB sur 10, seulement s'il y a assez de votes pour qu'elle veuille dire quelque chose. */
export function tmdbPublicRating(avg?: number, count?: number): number | undefined {
return typeof avg === 'number' && avg > 0 && avg <= 10 && (count ?? 0) >= 20 ? Math.round(avg * 10) / 10 : undefined
}
function safeResult(r: SearchResult): SearchResult | null {
const title = cleanText(r.title, LIMITS.title)
if (!title || !isSafeExternalId(r.externalId)) return null
return {
...r,
title,
originalTitle: cleanText(r.originalTitle, LIMITS.title),
year: typeof r.year === 'number' && r.year >= 1870 && r.year <= 2200 ? r.year : undefined,
thumb: safePosterUrl(r.thumb),
posterUrl: safePosterUrl(r.posterUrl),
kindLabel: cleanText(r.kindLabel, 40) ?? '',
prefill: r.prefill ? sanitizeMeta(r.prefill) : undefined,
}
}
// ─────────────────────────── TMDB ───────────────────────────
const TMDB = 'https://api.themoviedb.org/3'
const TMDB_IMG = 'https://image.tmdb.org/t/p'
interface TmdbItem {
id: number
media_type?: 'movie' | 'tv' | 'person'
title?: string
name?: string
original_title?: string
original_name?: string
release_date?: string
first_air_date?: string
poster_path?: string | null
genre_ids?: number[]
origin_country?: string[]
original_language?: string
vote_average?: number
vote_count?: number
popularity?: number
}
/** Clé v3 (32 caractères hexadécimaux) ou jeton de lecture v4 (JWT). */
export function isPlausibleTmdbKey(key: string): boolean {
const k = key.trim()
return /^[a-f0-9]{32}$/i.test(k) || /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(k)
}
/** Seules ces adresses de l'API TMDB peuvent être appelées. */
const TMDB_PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?)$/
/** « Clé » spéciale : avec un compte, les requêtes passent par le serveur qui détient la vraie clé TMDB. */
export const CLOUD_TMDB = 'cloud-proxy'
async function tmdbFetch<T>(path: string, key: string, params: Record<string, string> = {}): Promise<T> {
const k = key.trim()
if (!TMDB_PATHS.test(path)) throw new Error(t('err.tmdbRefused'))
if (k === CLOUD_TMDB) return tmdbViaCloud<T>(path, { language: tmdbLanguage(), ...params })
if (!isPlausibleTmdbKey(k)) throw new Error(t('err.tmdbKeyRefused'))
const isBearer = k.length > 40 // jeton de lecture v4 (JWT) vs clé v3 (32 caractères)
const url = new URL(TMDB + path)
url.searchParams.set('language', tmdbLanguage())
for (const [p, v] of Object.entries(params)) url.searchParams.set(p, v)
if (!isBearer) url.searchParams.set('api_key', k)
const res = await fetch(url, {
headers: isBearer ? { Authorization: `Bearer ${k}` } : {},
referrerPolicy: 'no-referrer',
credentials: 'omit',
})
if (res.status === 401) throw new Error(t('err.tmdbKeyRefused'))
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
return res.json() as Promise<T>
}
const yearOf = (d?: string) => (d && /^\d{4}/.test(d) ? Number(d.slice(0, 4)) : undefined)
/** Devine le type AzuuCine à partir des métadonnées TMDB. */
function guessTmdbType(kind: 'movie' | 'tv', genreIds: number[], countries: string[], lang?: string): { type: MediaType; subtype?: string } {
const has = (c: string) => countries.includes(c)
if (genreIds.includes(99)) return { type: 'autre', subtype: 'Documentaire' }
if (kind === 'movie') return { type: 'film' }
if (genreIds.includes(10764)) return { type: 'autre', subtype: 'Télé-réalité' }
if (genreIds.includes(16) && (has('JP') || lang === 'ja')) return { type: 'anime' }
if (has('KR') || lang === 'ko') return { type: 'kdrama' }
if (has('CN') || has('TW') || has('HK') || lang === 'zh' || lang === 'cn') return { type: 'cdrama' }
return { type: 'serie' }
}
const kindLabel = (type: MediaType, subtype?: string) => (subtype ? subtypeLabel(subtype) : TYPE_BY_VALUE[type].label)
function tmdbToResult(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null {
if (!Number.isInteger(r.id)) return null
const poster = isSafeTmdbPath(r.poster_path) ? r.poster_path : undefined
const guess = guessTmdbType(kind, r.genre_ids ?? [], r.origin_country ?? [], r.original_language)
const title = (kind === 'movie' ? r.title : r.name) ?? '?'
const original = kind === 'movie' ? r.original_title : r.original_name
return safeResult({
source: 'tmdb',
externalId: `tmdb:${kind}:${r.id}`,
title,
originalTitle: original && original !== title ? original : undefined,
year: yearOf(kind === 'movie' ? r.release_date : r.first_air_date),
thumb: poster ? `${TMDB_IMG}/w92${poster}` : undefined,
posterUrl: poster ? `${TMDB_IMG}/w342${poster}` : undefined,
kindLabel: kindLabel(guess.type, guess.subtype),
typeGuess: guess.type,
})
}
export async function searchTmdb(query: string, key: string): Promise<SearchResult[]> {
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: query.slice(0, LIMITS.searchQuery), include_adult: 'false' })
return (Array.isArray(data.results) ? data.results : [])
.filter((r) => r.media_type === 'movie' || r.media_type === 'tv')
.slice(0, 15)
.map((r) => tmdbToResult(r, r.media_type as 'movie' | 'tv'))
.filter((r): r is SearchResult => r !== null)
}
/** Titres recommandés par TMDB à partir d'un film / d'une série. */
export async function tmdbRecommendations(externalId: string, key: string): Promise<SearchResult[]> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return []
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const data = await tmdbFetch<{ results: TmdbItem[] }>(`/${kind}/${id}/recommendations`, key)
return (Array.isArray(data.results) ? data.results : [])
.filter((r) => r.poster_path)
.slice(0, 15)
.map((r) => tmdbToResult(r, r.media_type === 'movie' || r.media_type === 'tv' ? r.media_type : kind))
.filter((r): r is SearchResult => r !== null)
}
interface TmdbDetails {
title?: string
name?: string
original_title?: string
original_name?: string
overview?: string
runtime?: number
episode_run_time?: number[]
number_of_episodes?: number
number_of_seasons?: number
genres?: { id: number; name: string }[]
origin_country?: string[]
production_countries?: { iso_3166_1: string }[]
original_language?: string
release_date?: string
first_air_date?: string
poster_path?: string | null
last_episode_to_air?: { runtime?: number } | null
vote_average?: number
vote_count?: number
'watch/providers'?: { results?: Record<string, { flatrate?: { provider_name: string }[] }> }
}
const PROVIDER_NAMES: Record<string, string> = {
'Amazon Prime Video': 'Prime Video',
'Amazon Prime Video with Ads': 'Prime Video',
'Disney Plus': 'Disney+',
'Apple TV Plus': 'Apple TV+',
'Apple TV+': 'Apple TV+',
'Canal+ Séries': 'Canal+',
'Paramount Plus': 'Paramount+',
'Netflix Standard with Ads': 'Netflix',
'Netflix basic with Ads': 'Netflix',
'Rakuten Viki': 'Viki',
'Animation Digital Network': 'ADN',
}
const GENRE_ALIASES: Record<string, string> = {
'Science-Fiction': 'Sci-Fi',
'Science Fiction': 'Sci-Fi',
'Sci-Fi': 'Sci-Fi',
Adventure: 'Aventure',
Fantasy: 'Fantasy',
Fantastique: 'Fantasy',
War: 'Guerre',
Politics: 'Politique',
Kids: 'Enfants',
Musique: 'Musical',
Crime: 'Policier',
}
/**
* Découpe les genres combinés de TMDB (« Science-Fiction & Fantastique », « Action & Adventure »),
* harmonise les noms et retire les doublons.
*/
export function splitGenres(names: string[], keepAnimation = false): string[] {
const out = new Set<string>()
for (const n of names) {
for (const part of n.split('&')) {
const g = part.trim()
if (!g) continue
if (g === 'Animation' && !keepAnimation) continue // déjà exprimé par le type
out.add(GENRE_ALIASES[g] ?? g)
}
}
return [...out]
}
export async function getTmdbDetails(result: SearchResult, key: string): Promise<Partial<MediaInput>> {
if (!isSafeExternalId(result.externalId) || !result.externalId.startsWith('tmdb:')) throw new Error(t('err.tmdbRef'))
const [, kind, id] = result.externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbDetails>(`/${kind}/${id}`, key, { append_to_response: 'watch/providers' })
const guess = guessTmdbType(kind, (d.genres ?? []).map((g) => g.id), d.origin_country ?? [], d.original_language)
const providers = d['watch/providers']?.results
const provider = (providers?.[region()] ?? providers?.FR)?.flatrate?.[0]?.provider_name
const title = (kind === 'movie' ? d.title : d.name) ?? result.title
const original = kind === 'movie' ? d.original_title : d.original_name
const epRuntime = d.episode_run_time?.[0] || d.last_episode_to_air?.runtime || undefined
return sanitizeMeta({
title,
originalTitle: original && original !== title ? original : undefined,
type: guess.type,
subtype: guess.subtype,
year: yearOf(kind === 'movie' ? d.release_date : d.first_air_date),
overview: d.overview || undefined,
genres: tmdbGenres((d.genres ?? []).map((g) => g.id)).filter((g) => guess.type === 'film' || g !== 'Animation'),
platform: provider ? (PROVIDER_NAMES[provider] ?? provider) : undefined,
duration: kind === 'movie' ? d.runtime || undefined : undefined,
episodesTotal: kind === 'tv' ? d.number_of_episodes || undefined : undefined,
episodeDuration: kind === 'tv' ? epRuntime : undefined,
externalId: result.externalId,
countries: d.origin_country?.length ? d.origin_country : d.production_countries?.map((c) => c.iso_3166_1).slice(0, 3),
publicRating: tmdbPublicRating(d.vote_average, d.vote_count),
})
}
/** Vérifie qu'une clé TMDB fonctionne. */
export async function testTmdbKey(key: string): Promise<boolean> {
try {
await tmdbFetch('/configuration', key)
return true
} catch {
return false
}
}
// ─────────────────────────── AniList ───────────────────────────
const ANILIST = 'https://graphql.anilist.co'
const ANILIST_FIELDS = `
id
format
episodes
duration
genres
seasonYear
startDate { year }
title { romaji english native }
coverImage { medium large }
countryOfOrigin
averageScore
description(asHtml: false)`
const ANILIST_QUERY = `
query ($search: String) {
Page(perPage: 15) {
media(search: $search, type: ANIME, sort: SEARCH_MATCH, isAdult: false) {${ANILIST_FIELDS}
}
}
}`
interface AniMedia {
id: number
format?: string | null
episodes?: number | null
duration?: number | null
genres?: string[]
seasonYear?: number | null
startDate?: { year?: number | null }
title: { romaji?: string | null; english?: string | null; native?: string | null }
coverImage?: { medium?: string | null; large?: string | null }
description?: string | null
countryOfOrigin?: string | null
averageScore?: number | null
}
const ANILIST_GENRES: Record<string, string> = {
Action: 'Action',
Adventure: 'Aventure',
Comedy: 'Comédie',
Drama: 'Drame',
Ecchi: 'Ecchi',
Fantasy: 'Fantasy',
Horror: 'Horreur',
'Mahou Shoujo': 'Magical Girl',
Mecha: 'Mecha',
Music: 'Musical',
Mystery: 'Mystère',
Psychological: 'Psychologique',
Romance: 'Romance',
'Sci-Fi': 'Sci-Fi',
'Slice of Life': 'Slice of Life',
Sports: 'Sport',
Supernatural: 'Surnaturel',
Thriller: 'Thriller',
}
const aniFormat = (f?: string | null): string =>
f === 'TV_SHORT' ? t('anilist.short') : f === 'MOVIE' ? t('anilist.movie') : f === 'SPECIAL' ? t('anilist.special') : f === 'MUSIC' ? t('anilist.music') : f === 'OVA' || f === 'ONA' ? f : t('type.anime')
function cleanDescription(html?: string | null): string | undefined {
if (!html) return undefined
return html
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<[^>]+>/g, '')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
export async function searchAniList(query: string): Promise<SearchResult[]> {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ query: ANILIST_QUERY, variables: { search: query.slice(0, LIMITS.searchQuery) } }),
referrerPolicy: 'no-referrer',
credentials: 'omit',
})
if (res.status === 429) throw new Error(t('err.anilistRate'))
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Page?: { media?: AniMedia[] } } }
const list = Array.isArray(json.data?.Page?.media) ? json.data!.Page!.media! : []
return list.map(aniToResult).filter((r): r is SearchResult => r !== null)
}
function aniToResult(m: AniMedia): SearchResult | null {
if (!m || !Number.isInteger(m.id)) return null
const isMovie = m.format === 'MOVIE'
const title = m.title.english || m.title.romaji || m.title.native || '?'
const original = m.title.native || m.title.romaji || undefined
const year = m.seasonYear ?? m.startDate?.year ?? undefined
const type: MediaType = isMovie ? 'film' : 'anime'
return safeResult({
source: 'anilist' as const,
externalId: `anilist:${m.id}`,
title,
originalTitle: original && original !== title ? original : undefined,
year: year ?? undefined,
thumb: m.coverImage?.medium ?? undefined,
posterUrl: m.coverImage?.large ?? m.coverImage?.medium ?? undefined,
kindLabel: aniFormat(m.format),
typeGuess: type,
prefill: {
title,
originalTitle: original && original !== title ? original : undefined,
type,
year: year ?? undefined,
overview: cleanDescription(m.description),
genres: [...(isMovie ? ['Anime'] : []), ...(m.genres ?? []).map((g) => ANILIST_GENRES[g] ?? g)],
episodesTotal: isMovie ? undefined : (m.episodes ?? undefined),
episodeDuration: isMovie ? undefined : (m.duration ?? undefined),
duration: isMovie ? (m.duration ?? undefined) : undefined,
externalId: `anilist:${m.id}`,
countries: m.countryOfOrigin ? [m.countryOfOrigin] : undefined,
publicRating: typeof m.averageScore === 'number' && m.averageScore > 0 ? m.averageScore / 10 : undefined,
},
})
}
/** Animes recommandés par AniList à partir d'un anime. */
export async function aniListRecommendations(externalId: string): Promise<SearchResult[]> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('anilist:')) return []
const id = Number(externalId.split(':')[1])
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
query: `query ($id: Int) { Media(id: $id) { recommendations(sort: RATING_DESC, perPage: 15) { nodes { mediaRecommendation { ${ANILIST_FIELDS} } } } } }`,
variables: { id },
}),
referrerPolicy: 'no-referrer',
credentials: 'omit',
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: { recommendations?: { nodes?: { mediaRecommendation?: AniMedia | null }[] } } } }
const nodes = json.data?.Media?.recommendations?.nodes
return (Array.isArray(nodes) ? nodes : [])
.map((n) => n.mediaRecommendation)
.filter((m): m is AniMedia => !!m)
.map(aniToResult)
.filter((r): r is SearchResult => r !== null)
}
// ─────────────────────────── Générique (pour les affiches partagées) ───────────────────────────
export interface Credits {
/** Réalisateur·rices (films) ou créateur·rices (séries) */
directors: string[]
producers: string[]
cast: string[]
runtime?: number
/** Image de scène (paysage) en haute définition, sinon l'affiche en HD */
image?: string
}
interface TmdbCredits {
runtime?: number
backdrop_path?: string | null
poster_path?: string | null
created_by?: { name?: string }[]
credits?: {
cast?: { name?: string; order?: number }[]
crew?: { name?: string; job?: string }[]
}
}
const names = (list: (string | undefined)[], max: number) =>
[...new Set(list.map((n) => cleanText(n, 60)).filter((n): n is string => !!n))].slice(0, max)
/** Réalisation, production et casting principal depuis TMDB. */
export async function getTmdbCredits(externalId: string, key: string): Promise<Credits | undefined> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return undefined
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbCredits>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
const crew = Array.isArray(d.credits?.crew) ? d.credits!.crew! : []
const cast = Array.isArray(d.credits?.cast) ? d.credits!.cast! : []
return {
directors:
kind === 'movie'
? names(crew.filter((c) => c.job === 'Director').map((c) => c.name), 2)
: names((Array.isArray(d.created_by) ? d.created_by : []).map((c) => c.name), 2),
producers: names(crew.filter((c) => c.job === 'Producer').map((c) => c.name), 3),
cast: names([...cast].sort((a, b) => (a.order ?? 99) - (b.order ?? 99)).map((c) => c.name), 4),
runtime: typeof d.runtime === 'number' && d.runtime > 0 && d.runtime < 6000 ? Math.round(d.runtime) : undefined,
image: isSafeTmdbPath(d.backdrop_path)
? `${TMDB_IMG}/w1280${d.backdrop_path}`
: isSafeTmdbPath(d.poster_path)
? `${TMDB_IMG}/w780${d.poster_path}`
: undefined,
}
}
// ─────────────────────────── Notes du public ───────────────────────────
/** Note moyenne TMDB d'un film / d'une série (undefined si trop peu de votes). */
export async function getTmdbPublicRating(externalId: string, key: string): Promise<number | undefined> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return undefined
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbDetails>(`/${kind}/${id}`, key)
return tmdbPublicRating(d.vote_average, d.vote_count)
}
/** Notes moyennes AniList (sur 10) pour plusieurs animes d'un coup. */
export async function getAniListPublicRatings(ids: number[]): Promise<Map<number, number>> {
const out = new Map<number, number>()
const clean = ids.filter((n) => Number.isInteger(n) && n > 0).slice(0, 500)
for (let i = 0; i < clean.length; i += 50) {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
body: JSON.stringify({
query: 'query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id averageScore } } }',
variables: { ids: clean.slice(i, i + 50) },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Page?: { media?: { id: number; averageScore?: number | null }[] } } }
const media = json.data?.Page?.media
for (const m of Array.isArray(media) ? media : []) {
if (Number.isInteger(m?.id) && typeof m.averageScore === 'number' && m.averageScore > 0 && m.averageScore <= 100) {
out.set(m.id, Math.round(m.averageScore) / 10)
}
}
}
return out
}
// ─────────────────────────── Dates de sortie (calendrier) ───────────────────────────
export interface ReleaseInfo {
date: string // AAAA-MM-JJ
label: string
}
interface TmdbReleaseDetails {
release_date?: string
first_air_date?: string
next_episode_to_air?: { air_date?: string; episode_number?: number; season_number?: number } | null
release_dates?: { results?: { iso_3166_1?: string; release_dates?: { release_date?: string; type?: number }[] }[] }
}
const day = (v?: string) => (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v) ? v.slice(0, 10) : undefined)
/** Prochaine date utile pour un titre « à voir » : sortie ciné en France, sortie en ligne, 1er épisode… */
export async function getTmdbRelease(externalId: string, key: string): Promise<ReleaseInfo | undefined> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('tmdb:')) return undefined
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
if (kind === 'movie') {
const d = await tmdbFetch<TmdbReleaseDetails>(`/movie/${id}`, key, { append_to_response: 'release_dates' })
const results = Array.isArray(d.release_dates?.results) ? d.release_dates!.results! : []
const local = results.find((r) => r.iso_3166_1 === region())?.release_dates ?? []
const pick = (type: number) => day(local.filter((r) => r.type === type).map((r) => r.release_date ?? '').sort()[0])
const cinema = pick(3) ?? pick(2)
const online = pick(4)
const today = new Date().toISOString().slice(0, 10)
if (cinema && cinema >= today) return { date: cinema, label: t('release.cinema') }
if (online && online >= today) return { date: online, label: t('release.online') }
const primary = day(d.release_date)
return cinema ? { date: cinema, label: t('release.cinema') } : primary ? { date: primary, label: t('release.release') } : undefined
}
const d = await tmdbFetch<TmdbReleaseDetails>(`/tv/${id}`, key)
const nx = d.next_episode_to_air
const nextDay = day(nx?.air_date)
if (nextDay) {
const ep = Number.isInteger(nx?.episode_number) ? nx!.episode_number! : undefined
const season = Number.isInteger(nx?.season_number) ? nx!.season_number! : undefined
return { date: nextDay, label: ep === 1 && season ? t('release.season', { season }) : ep ? t('release.episode', { ep }) : t('release.newEpisode') }
}
const first = day(d.first_air_date)
return first ? { date: first, label: t('release.firstEpisode') } : undefined
}
/** Dates de sortie AniList (1er épisode ou prochain épisode) pour plusieurs animes. */
export async function getAniListReleases(ids: number[]): Promise<Map<number, ReleaseInfo>> {
const out = new Map<number, ReleaseInfo>()
const clean = ids.filter((n) => Number.isInteger(n) && n > 0).slice(0, 500)
for (let i = 0; i < clean.length; i += 50) {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
body: JSON.stringify({
query:
'query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id startDate { year month day } nextAiringEpisode { episode airingAt } } } }',
variables: { ids: clean.slice(i, i + 50) },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
type M = { id: number; startDate?: { year?: number; month?: number; day?: number }; nextAiringEpisode?: { episode?: number; airingAt?: number } | null }
const json = (await res.json()) as { data?: { Page?: { media?: M[] } } }
const media = json.data?.Page?.media
for (const m of Array.isArray(media) ? media : []) {
if (!Number.isInteger(m?.id)) continue
const nx = m.nextAiringEpisode
if (nx && typeof nx.airingAt === 'number' && nx.airingAt > 0 && nx.airingAt < 4102444800) {
out.set(m.id, { date: new Date(nx.airingAt * 1000).toISOString().slice(0, 10), label: nx.episode === 1 ? t('release.firstEpisode') : nx.episode ? t('release.episode', { ep: nx.episode }) : t('release.newEpisode') })
} else if (m.startDate?.year && m.startDate.month && m.startDate.day) {
const d = `${m.startDate.year}-${String(m.startDate.month).padStart(2, '0')}-${String(m.startDate.day).padStart(2, '0')}`
if (day(d)) out.set(m.id, { date: d, label: t('release.firstEpisode') })
}
}
}
return out
}
// ─────────────────────────── Sorties globales (calendrier) ───────────────────────────
export type ReleaseCategory = 'film' | 'serie' | 'anime' | 'kdrama' | 'cdrama'
/** Une sortie (film au cinéma ou épisode) venant des bases publiques, pas forcément dans ma bibliothèque. */
export interface GlobalRelease {
date: string // AAAA-MM-JJ (heure locale)
externalId: string
title: string
originalTitle?: string
year?: number
poster?: string
label: string
cat: ReleaseCategory
/** Popularité normalisée 0–100, pour trier les sorties d'un même jour */
pop: number
}
const localDay = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
function safeRelease(r: GlobalRelease): GlobalRelease | null {
const title = cleanText(r.title, LIMITS.title)
const date = day(r.date)
if (!title || !date || !isSafeExternalId(r.externalId)) return null
return {
date,
externalId: r.externalId,
title,
originalTitle: cleanText(r.originalTitle, LIMITS.title),
year: typeof r.year === 'number' && r.year >= 1870 && r.year <= 2200 ? r.year : undefined,
poster: safePosterUrl(r.poster),
label: cleanText(r.label, 40) ?? '',
cat: r.cat,
pop: Math.max(0, Math.min(100, Math.round(r.pop || 0))),
}
}
export { safeRelease }
const popScore = (p?: number) => (typeof p === 'number' && p > 0 ? Math.min(100, Math.log10(p + 1) * 30) : 0)
/** Films qui sortent au cinéma en France entre deux dates (les plus attendus d'abord). */
export async function tmdbMovieReleases(key: string, from: string, to: string, pages = 2): Promise<GlobalRelease[]> {
const out: GlobalRelease[] = []
const toCheck: TmdbItem[] = []
for (let page = 1; page <= pages; page++) {
const data = await tmdbFetch<{ results?: TmdbItem[]; total_pages?: number }>('/discover/movie', key, {
region: region(),
'release_date.gte': from,
'release_date.lte': to,
with_release_type: '2|3',
sort_by: 'popularity.desc',
include_adult: 'false',
page: String(page),
})
for (const r of Array.isArray(data.results) ? data.results : []) {
if (!Number.isInteger(r.id) || (r.genre_ids ?? []).includes(99)) continue
const primary = day(r.release_date)
if (primary && primary >= from && primary <= to) out.push(movieRelease(r, primary))
else toCheck.push(r)
}
if ((data.total_pages ?? 1) <= page) break
}
// Date de sortie française quand elle diffère de la date mondiale
for (let k = 0; k < Math.min(toCheck.length, 24); k += 4) {
await Promise.all(
toCheck.slice(k, k + 4).map(async (r) => {
try {
const info = await getTmdbRelease(`tmdb:movie:${r.id}`, key)
if (info && info.date >= from && info.date <= to) out.push(movieRelease(r, info.date))
} catch {
/* ignore ce film */
}
}),
)
}
return out.map(safeRelease).filter((x): x is GlobalRelease => !!x)
}
function movieRelease(r: TmdbItem, date: string): GlobalRelease {
const poster = isSafeTmdbPath(r.poster_path) ? `${TMDB_IMG}/w342${r.poster_path}` : undefined
return {
date,
externalId: `tmdb:movie:${r.id}`,
title: r.title ?? '?',
originalTitle: r.original_title !== r.title ? r.original_title : undefined,
year: yearOf(r.release_date),
poster,
label: t('release.cinema'),
cat: 'film',
pop: popScore(r.popularity),
}
}
const TV_FILTERS: Record<'serie' | 'kdrama' | 'cdrama', { countries: string; shows: number }> = {
serie: { countries: 'US|GB|FR|CA|AU|IE|NZ|ES|DE|IT|BE|SE|DK|NO', shows: 20 },
kdrama: { countries: 'KR', shows: 12 },
cdrama: { countries: 'CN|TW|HK', shows: 12 },
}
interface TmdbEpisode {
air_date?: string
episode_number?: number
season_number?: number
}
/** Épisodes des séries populaires (ou K-dramas / C-dramas) diffusés entre deux dates. */
export async function tmdbEpisodeReleases(
key: string,
cat: 'serie' | 'kdrama' | 'cdrama',
from: string,
to: string,
): Promise<GlobalRelease[]> {
const f = TV_FILTERS[cat]
const data = await tmdbFetch<{ results?: TmdbItem[] }>('/discover/tv', key, {
'air_date.gte': from,
'air_date.lte': to,
with_origin_country: f.countries,
without_genres: '16|10763|10764|10767',
sort_by: 'popularity.desc',
include_adult: 'false',
})
const shows = (Array.isArray(data.results) ? data.results : []).filter((r) => Number.isInteger(r.id)).slice(0, f.shows)
const out: GlobalRelease[] = []
for (let k = 0; k < shows.length; k += 4) {
await Promise.all(
shows.slice(k, k + 4).map(async (show) => {
try {
const d = await tmdbFetch<{ next_episode_to_air?: TmdbEpisode | null; last_episode_to_air?: TmdbEpisode | null }>(`/tv/${show.id}`, key)
const seasons = new Set<number>()
for (const e of [d.last_episode_to_air, d.next_episode_to_air]) {
const dd = day(e?.air_date)
if (e && Number.isInteger(e.season_number) && e.season_number! > 0 && dd && dd >= shiftDay(from, -120)) seasons.add(e.season_number!)
}
for (const n of [...seasons].slice(0, 2)) {
const season = await tmdbFetch<{ episodes?: TmdbEpisode[] }>(`/tv/${show.id}/season/${n}`, key)
// Regroupe les épisodes sortis le même jour (séries mises en ligne d'un bloc)
const byDay = new Map<string, number[]>()
for (const e of Array.isArray(season.episodes) ? season.episodes : []) {
const dd = day(e.air_date)
if (!dd || dd < from || dd > to || !Number.isInteger(e.episode_number)) continue
byDay.set(dd, [...(byDay.get(dd) ?? []), e.episode_number!])
}
for (const [date, eps] of byDay) out.push(episodeRelease(show, cat, date, n, eps))
}
} catch {
/* ignore cette série */
}
}),
)
}
return out.map(safeRelease).filter((x): x is GlobalRelease => !!x)
}
function shiftDay(d: string, days: number) {
const x = new Date(d + 'T12:00:00')
x.setDate(x.getDate() + days)
return localDay(x)
}
function episodeLabel(season: number | undefined, eps: number[]): string {
const sorted = [...eps].sort((a, b) => a - b)
const first = sorted[0]
const last = sorted[sorted.length - 1]
if (first === 1 && season === 1) return sorted.length > 1 ? t('release.newSeriesN', { count: sorted.length }) : t('release.firstEpisode')
if (first === 1) return sorted.length > 1 ? t('release.seasonN', { season: season ?? 1, count: sorted.length }) : t('release.seasonEp1', { season: season ?? 1 })
if (!season) return sorted.length > 1 ? t('release.episodes', { first, last }) : t('release.episode', { ep: first })
return sorted.length > 1 ? t('release.sEpisodes', { season, first, last }) : t('release.sEpisode', { season, ep: first })
}
function episodeRelease(show: TmdbItem, cat: ReleaseCategory, date: string, season: number, eps: number[]): GlobalRelease {
return {
date,
externalId: `tmdb:tv:${show.id}`,
title: show.name ?? '?',
originalTitle: show.original_name !== show.name ? show.original_name : undefined,
year: yearOf(show.first_air_date),
poster: isSafeTmdbPath(show.poster_path) ? `${TMDB_IMG}/w342${show.poster_path}` : undefined,
label: episodeLabel(season, eps),
cat,
pop: popScore(show.popularity),
}
}
/** Tous les épisodes d'anime diffusés entre deux dates (AniList, sans clé). */
export async function aniListAiring(from: string, to: string, minPopularity = 4000): Promise<GlobalRelease[]> {
const start = Math.floor(new Date(from + 'T00:00:00').getTime() / 1000) - 1
const end = Math.floor(new Date(to + 'T23:59:59').getTime() / 1000) + 1
type S = {
airingAt?: number
episode?: number
media?: {
id?: number
title?: { romaji?: string | null; english?: string | null; native?: string | null }
coverImage?: { large?: string | null; medium?: string | null }
popularity?: number
isAdult?: boolean
countryOfOrigin?: string
format?: string
episodes?: number | null
seasonYear?: number | null
}
}
const byKey = new Map<string, { s: S; eps: number[] }>()
for (let page = 1; page <= 12; page++) {
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
body: JSON.stringify({
query: `query ($start: Int, $end: Int, $page: Int) { Page(page: $page, perPage: 50) { pageInfo { hasNextPage }
airingSchedules(airingAt_greater: $start, airingAt_lesser: $end, sort: TIME) { airingAt episode
media { id title { romaji english native } coverImage { large medium } popularity isAdult countryOfOrigin format episodes seasonYear } } } }`,
variables: { start, end, page },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Page?: { pageInfo?: { hasNextPage?: boolean }; airingSchedules?: S[] } } }
const list = json.data?.Page?.airingSchedules
for (const s of Array.isArray(list) ? list : []) {
const m = s.media
if (!m || !Number.isInteger(m.id) || m.isAdult || m.countryOfOrigin !== 'JP' || (m.popularity ?? 0) < minPopularity) continue
if (typeof s.airingAt !== 'number' || !Number.isInteger(s.episode)) continue
const date = localDay(new Date(s.airingAt * 1000))
const k = `${m.id}|${date}`
const cur = byKey.get(k)
if (cur) cur.eps.push(s.episode!)
else byKey.set(k, { s, eps: [s.episode!] })
}
if (!json.data?.Page?.pageInfo?.hasNextPage) break
}
const out: GlobalRelease[] = []
for (const [k, { s, eps }] of byKey) {
const m = s.media!
const sorted = eps.sort((a, b) => a - b)
const total = Number.isInteger(m.episodes) ? m.episodes! : undefined
const isFinal = total != null && sorted[sorted.length - 1] === total
const label =
m.format === 'MOVIE'
? t('release.filmJapan')
: sorted[0] === 1
? t('release.firstEpisode')
: sorted.length > 1
? t('release.episodes', { first: sorted[0], last: sorted[sorted.length - 1] })
: isFinal
? t('release.episodeFinal', { ep: sorted[0] })
: t('release.episode', { ep: sorted[0] })
out.push({
date: k.split('|')[1],
externalId: `anilist:${m.id}`,
title: m.title?.english || m.title?.romaji || m.title?.native || '?',
originalTitle: m.title?.romaji || undefined,
year: m.seasonYear ?? undefined,
poster: m.coverImage?.large ?? m.coverImage?.medium ?? undefined,
label,
cat: 'anime',
pop: popScore(m.popularity) - 20,
})
}
return out.map(safeRelease).filter((x): x is GlobalRelease => !!x)
}
/** Fiche AniList complète à partir de son identifiant (ajout depuis le calendrier). */
export async function getAniListById(externalId: string): Promise<SearchResult | null> {
if (!isSafeExternalId(externalId) || !externalId.startsWith('anilist:')) return null
const res = await fetch(ANILIST, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
referrerPolicy: 'no-referrer',
credentials: 'omit',
body: JSON.stringify({
query: `query ($id: Int) { Media(id: $id, type: ANIME) {${ANILIST_FIELDS} } }`,
variables: { id: Number(externalId.split(':')[1]) },
}),
})
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
const json = (await res.json()) as { data?: { Media?: AniMedia } }
return json.data?.Media ? aniToResult(json.data.Media) : null
}
/** Résultat « recherche » TMDB minimal à partir d'une sortie (pour l'ajout rapide). */
export function releaseToResult(r: GlobalRelease): SearchResult | null {
if (!r.externalId.startsWith('tmdb:')) return null
const type: MediaType = r.cat
return safeResult({
source: 'tmdb',
externalId: r.externalId,
title: r.title,
originalTitle: r.originalTitle,
year: r.year,
thumb: r.poster,
posterUrl: r.poster,
kindLabel: kindLabel(type),
typeGuess: type,
})
}
+46
View File
@@ -0,0 +1,46 @@
import { t } from '../../i18n'
import { AuthError, getAccessToken } from './auth'
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
/** Appel authentifié à Supabase (base de données ou fonctions serveur). Réessaie une fois si le jeton a expiré. */
export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> {
for (let attempt = 0; attempt < 2; attempt++) {
const token = await getAccessToken(attempt > 0)
if (!token) throw new AuthError(t('auth.err.session'))
const res = await fetch(SUPABASE_URL + path, {
...init,
headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },
credentials: 'omit',
referrerPolicy: 'no-referrer',
})
if (res.status !== 401) return res
}
throw new AuthError(t('auth.err.session'))
}
/** Proxy TMDB : la clé TMDB reste sur le serveur. */
export async function tmdbViaCloud<T>(path: string, params: Record<string, string>): Promise<T> {
const q = new URLSearchParams({ path, ...params })
const res = await cloudFetch(`/functions/v1/tmdb?${q}`)
if (res.status === 429) throw new Error(t('err.searchRate'))
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
return res.json() as Promise<T>
}
export type ProxyState = 'ok' | 'missing-key' | 'not-deployed' | 'offline' | 'error'
/** Vérifie que le proxy TMDB est déployé et que la clé TMDB est bien enregistrée côté serveur. */
export async function checkTmdbProxy(): Promise<ProxyState> {
if (!navigator.onLine) return 'offline'
try {
const res = await cloudFetch(`/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`)
if (res.ok) return 'ok'
if (res.status === 404) return 'not-deployed'
const body = (await res.json().catch(() => ({}))) as { error?: string; status?: number }
if (res.status === 500 && body.error?.includes('TMDB_API_KEY')) return 'missing-key'
if (res.status === 502 && body.status === 401) return 'missing-key'
return 'error'
} catch {
return navigator.onLine ? 'not-deployed' : 'offline'
}
}
+260
View File
@@ -0,0 +1,260 @@
import { t, type TKey } from '../../i18n'
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
/**
* Connexion aux comptes (Supabase Auth), sans dépendance.
* La session (jetons) est gardée sur l'appareil pour que l'app s'ouvre même hors-ligne ;
* le mot de passe, lui, n'est jamais stocké.
*/
export interface Session {
accessToken: string
refreshToken: string
/** Expiration du jeton d'accès (ms) */
expiresAt: number
user: { id: string; email: string }
}
export class AuthError extends Error {}
const KEY = 'azuucine:session'
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const TOKEN = /^[A-Za-z0-9._~+/=-]{10,8192}$/
export const PASSWORD_MIN = 8
function isSession(v: unknown): v is Session {
if (!v || typeof v !== 'object') return false
const s = v as Session
return (
typeof s.accessToken === 'string' &&
TOKEN.test(s.accessToken) &&
typeof s.refreshToken === 'string' &&
/^[A-Za-z0-9._~+/=-]{4,1024}$/.test(s.refreshToken) &&
typeof s.expiresAt === 'number' &&
Number.isFinite(s.expiresAt) &&
!!s.user &&
typeof s.user.id === 'string' &&
UUID.test(s.user.id) &&
typeof s.user.email === 'string' &&
s.user.email.length <= 320
)
}
function load(): Session | null {
try {
const raw = localStorage.getItem(KEY)
const parsed = raw ? JSON.parse(raw) : null
return isSession(parsed) ? parsed : null
} catch {
return null
}
}
let current: Session | null = load()
const listeners = new Set<(s: Session | null) => void>()
function setSession(s: Session | null) {
const changedUser = current?.user.id !== s?.user.id
current = s
try {
if (s) localStorage.setItem(KEY, JSON.stringify(s))
else localStorage.removeItem(KEY)
} catch {
/* ignore */
}
if (changedUser) for (const fn of listeners) fn(s)
}
// Connexion / déconnexion dans un autre onglet
if (typeof window !== 'undefined') {
window.addEventListener('storage', (e) => {
if (e.key !== KEY) return
const next = load()
const changedUser = current?.user.id !== next?.user.id
current = next
if (changedUser) for (const fn of listeners) fn(next)
})
}
export const getSession = () => current
export function onSessionChange(fn: (s: Session | null) => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
// ───────────────────────────── Appels à Supabase Auth ─────────────────────────────
const CODE_KEYS: Record<string, TKey> = {
invalid_credentials: 'auth.err.credentials',
invalid_grant: 'auth.err.credentials',
email_not_confirmed: 'auth.err.notConfirmed',
user_already_exists: 'auth.err.exists',
email_exists: 'auth.err.exists',
weak_password: 'auth.err.weak',
same_password: 'auth.err.samePassword',
over_email_send_rate_limit: 'auth.err.emailRate',
over_request_rate_limit: 'auth.err.rate',
signup_disabled: 'auth.err.signupDisabled',
email_address_invalid: 'auth.err.emailInvalid',
validation_failed: 'auth.err.invalid',
session_not_found: 'auth.err.session',
refresh_token_not_found: 'auth.err.session',
refresh_token_already_used: 'auth.err.session',
}
const msg = (code: string) => (CODE_KEYS[code] ? t(CODE_KEYS[code], { n: PASSWORD_MIN }) : undefined)
async function gotrue(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<Record<string, unknown>> {
let res: Response
try {
res = await fetch(`${SUPABASE_URL}/auth/v1${path}`, {
method: init.method ?? 'POST',
headers: {
apikey: SUPABASE_ANON_KEY,
'Content-Type': 'application/json',
...(init.token ? { Authorization: `Bearer ${init.token}` } : {}),
},
body: init.body ? JSON.stringify(init.body) : undefined,
credentials: 'omit',
referrerPolicy: 'no-referrer',
})
} catch {
throw new Error(t('common.offline'))
}
let data: Record<string, unknown> = {}
try {
data = (await res.json()) as Record<string, unknown>
} catch {
/* réponse vide */
}
if (!res.ok) {
const code = String(data.error_code ?? data.code ?? data.error ?? '')
const err = new AuthError(msg(code) ?? (res.status === 429 ? t('auth.err.rate') : t('auth.err.status', { status: res.status })))
;(err as AuthError & { status: number; code: string }).status = res.status
;(err as AuthError & { status: number; code: string }).code = code
throw err
}
return data
}
function toSession(data: Record<string, unknown>): Session | null {
const user = data.user as { id?: unknown; email?: unknown } | undefined
const expiresIn = typeof data.expires_in === 'number' ? data.expires_in : 3600
const s = {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: typeof data.expires_at === 'number' ? data.expires_at * 1000 : Date.now() + expiresIn * 1000,
user: { id: user?.id, email: typeof user?.email === 'string' ? user.email : '' },
}
return isSession(s) ? s : null
}
const cleanEmail = (email: string) => email.trim().toLowerCase().slice(0, 320)
const appUrl = () => `${location.origin}${location.pathname}`
export async function signIn(email: string, password: string): Promise<void> {
const data = await gotrue('/token?grant_type=password', { body: { email: cleanEmail(email), password } })
const s = toSession(data)
if (!s) throw new AuthError(t('auth.err.response'))
setSession(s)
}
/** Crée un compte. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). */
export async function signUp(email: string, password: string): Promise<boolean> {
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
const data = await gotrue(`/signup?redirect_to=${encodeURIComponent(appUrl())}`, { body: { email: cleanEmail(email), password } })
const s = toSession(data)
if (s) {
setSession(s)
return false
}
return true
}
export async function requestPasswordReset(email: string): Promise<void> {
await gotrue(`/recover?redirect_to=${encodeURIComponent(appUrl())}`, { body: { email: cleanEmail(email) } })
}
export async function updatePassword(password: string): Promise<void> {
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
const token = await getAccessToken()
if (!token) throw new AuthError(t('auth.err.session'))
await gotrue('/user', { method: 'PUT', body: { password }, token })
}
/** Déconnexion : invalide la session côté serveur (si possible) et l'efface de l'appareil. */
export async function signOut(): Promise<void> {
const s = current
setSession(null)
if (s && navigator.onLine) {
try {
await gotrue('/logout?scope=local', { token: s.accessToken })
} catch {
/* jeton déjà expiré : rien à faire */
}
}
}
let refreshing: Promise<Session | null> | null = null
async function refresh(): Promise<Session | null> {
const s = current
if (!s) return null
refreshing ??= (async () => {
try {
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: s.refreshToken } })
const next = toSession(data)
if (next && next.user.id === s.user.id) setSession(next)
return next
} catch (e) {
// Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte
const status = (e as { status?: number }).status
if (status === 400 || status === 401 || status === 403) setSession(null)
return null
} finally {
refreshing = null
}
})()
return refreshing
}
/** Jeton d'accès valide (renouvelé si besoin). null si déconnecté ou hors-ligne avec un jeton expiré. */
export async function getAccessToken(force = false): Promise<string | null> {
const s = current
if (!s) return null
if (!force && s.expiresAt - 60_000 > Date.now()) return s.accessToken
const next = await refresh()
return next?.accessToken ?? null
}
/**
* Liens reçus par email (confirmation d'inscription, mot de passe oublié) :
* Supabase renvoie vers l'app avec les jetons après le « # ». On ouvre la session puis on nettoie l'adresse.
*/
export async function consumeAuthRedirect(): Promise<{ type?: string; error?: string }> {
const hash = location.hash.startsWith('#') ? location.hash.slice(1) : ''
if (!/(^|&)(access_token|error)=/.test(hash)) return {}
const params = new URLSearchParams(hash)
history.replaceState(null, '', `${location.pathname}${location.search}#/`)
const error = params.get('error_description') ?? params.get('error')
if (error) {
const code = params.get('error_code') ?? ''
return { error: code === 'otp_expired' ? t('auth.err.linkExpired') : t('auth.err.linkUsed') }
}
const accessToken = params.get('access_token') ?? ''
try {
const user = await gotrue('/user', { method: 'GET', token: accessToken })
const s = toSession({
access_token: accessToken,
refresh_token: params.get('refresh_token'),
expires_at: Number(params.get('expires_at')) || undefined,
expires_in: Number(params.get('expires_in')) || 3600,
user,
})
if (!s) return { error: t('auth.err.linkInvalid') }
setSession(s)
return { type: params.get('type') ?? undefined }
} catch (e) {
return { error: (e as Error).message }
}
}
+19
View File
@@ -0,0 +1,19 @@
/**
* Configuration des comptes (Supabase), lue dans le fichier .env au moment de la compilation.
* Sans .env, l'app fonctionne comme avant : 100 % locale, sans compte.
*/
// On accepte aussi une adresse copiée avec « /rest/v1/ » (ou autre chemin) à la fin
const rawUrl = (import.meta.env.VITE_SUPABASE_URL ?? '').trim().replace(/^(https?:\/\/[^/]+).*$/, '$1')
const rawKey = (import.meta.env.VITE_SUPABASE_ANON_KEY ?? '').trim()
const validUrl = /^https:\/\/[a-z0-9-]+\.supabase\.(co|in)$/i.test(rawUrl) || /^http:\/\/(localhost|127\.0\.0\.1):\d+$/.test(rawUrl)
const validKey = /^(sb_publishable_[A-Za-z0-9_-]{10,200}|[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.test(rawKey)
export const SUPABASE_URL = validUrl ? rawUrl : ''
export const SUPABASE_ANON_KEY = validKey ? rawKey : ''
/** Les comptes sont activés quand le .env contient une configuration valide. */
export const cloudEnabled = !!(SUPABASE_URL && SUPABASE_ANON_KEY)
if (!cloudEnabled && (rawUrl || rawKey)) {
console.warn('[AzuuCine] .env incomplet ou invalide : les comptes sont désactivés (mode local). Vérifie VITE_SUPABASE_URL et VITE_SUPABASE_ANON_KEY.')
}
+279
View File
@@ -0,0 +1,279 @@
import { t } from '../../i18n'
import type { MediaItem } from '../../types'
import { normalizeItem } from '../backup'
import { cleanText, isPlainObject, safeIso } from '../security'
import { cloudFetch } from './api'
import { getSession } from './auth'
import { SUPABASE_URL } from './config'
/**
* Profils, abonnements et fil d'activité.
* Toutes les lectures passent par les fonctions de la base (get_profile, get_feed…) qui vérifient
* les droits d'accès ; tout ce qui revient du serveur est revalidé ici avant d'être affiché.
*/
export type Relation = 'none' | 'pending' | 'accepted'
export interface ProfileCard {
id: string
username: string
displayName: string
avatarUrl?: string
isPrivate: boolean
relation: Relation
}
export interface ProfileStats {
total: number
finished: number
finishedYear: number
films: number
series: number
episodes: number
rated: number
}
export interface Profile extends ProfileCard {
bio: string
bannerUrl?: string
isMe: boolean
followsMe: boolean
followers: number
following: number
visible: boolean
stats?: ProfileStats
top: MediaItem[]
recent: MediaItem[]
}
export interface FeedEntry {
id: number
kind: 'finished' | 'started' | 'rewatched' | 'added'
createdAt: string
user: { username: string; displayName: string; avatarUrl?: string }
item: MediaItem
}
export const USERNAME_RE = /^[a-z0-9_]{3,20}$/
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const MEDIA_PREFIX = () => `${SUPABASE_URL}/storage/v1/object/public/profile-media/`
/** Photo / bannière : uniquement depuis le stockage de l'app. */
export function safeMediaUrl(v: unknown): string | undefined {
if (typeof v !== 'string' || v.length > 500 || !SUPABASE_URL) return undefined
const prefix = MEDIA_PREFIX()
if (!v.startsWith(prefix)) return undefined
return /^[0-9a-f-]{36}\/[A-Za-z0-9_.-]{1,80}$/i.test(v.slice(prefix.length)) ? v : undefined
}
const count = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(Math.round(v), 10_000_000) : 0)
const relation = (v: unknown): Relation => (v === 'pending' || v === 'accepted' ? v : 'none')
const username = (v: unknown) => (typeof v === 'string' && USERNAME_RE.test(v) ? v : undefined)
function toCard(raw: unknown): ProfileCard | null {
if (!isPlainObject(raw) || typeof raw.id !== 'string' || !UUID.test(raw.id)) return null
const name = username(raw.username)
if (!name) return null
return {
id: raw.id,
username: name,
displayName: cleanText(raw.display_name, 40) ?? name,
avatarUrl: safeMediaUrl(raw.avatar_url),
isPrivate: raw.is_private === true,
relation: relation(raw.relation),
}
}
const toItems = (v: unknown): MediaItem[] =>
Array.isArray(v) ? v.slice(0, 200).map(normalizeItem).filter((i): i is MediaItem => i !== null) : []
function toProfile(raw: unknown): Profile | null {
const card = toCard(raw)
if (!card || !isPlainObject(raw)) return null
const s = isPlainObject(raw.stats) ? raw.stats : null
return {
...card,
bio: cleanText(raw.bio, 300) ?? '',
bannerUrl: safeMediaUrl(raw.banner_url),
isMe: raw.is_me === true,
followsMe: raw.follows_me === true,
followers: count(raw.followers),
following: count(raw.following),
visible: raw.visible === true,
stats: s
? {
total: count(s.total),
finished: count(s.finished),
finishedYear: count(s.finished_year),
films: count(s.films),
series: count(s.series),
episodes: count(s.episodes),
rated: count(s.rated),
}
: undefined,
top: toItems(raw.top),
recent: toItems(raw.recent),
}
}
function me(): string {
const id = getSession()?.user.id
if (!id) throw new Error(t('auth.err.session'))
return id
}
async function rpc(name: string, args: Record<string, unknown> = {}): Promise<unknown> {
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(args),
})
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
return res.json()
}
// ─── Lecture ───
export async function getProfile(name: string): Promise<Profile | null> {
const clean = name.trim().toLowerCase().replace(/^@/, '')
if (!USERNAME_RE.test(clean)) return null
return toProfile(await rpc('get_profile', { p_username: clean }))
}
/** Mon profil (pseudo, nom, photo…) — lu directement dans la table. */
export async function getMyProfile(): Promise<Profile | null> {
const res = await cloudFetch(`/rest/v1/profiles?id=eq.${me()}&select=username`)
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
const [row] = (await res.json()) as { username?: string }[]
return row?.username ? getProfile(row.username) : null
}
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<MediaItem[]> {
if (!UUID.test(userId)) return []
return toItems(await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: 48 }))
}
export async function getFeed(before?: string): Promise<FeedEntry[]> {
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: 30 })
if (!Array.isArray(raw)) return []
const out: FeedEntry[] = []
for (const r of raw.slice(0, 50)) {
if (!isPlainObject(r) || !isPlainObject(r.user)) continue
const item = normalizeItem(r.item)
const name = username(r.user.username)
const createdAt = safeIso(r.created_at)
const kind = r.kind
if (!item || !name || !createdAt || (kind !== 'finished' && kind !== 'started' && kind !== 'rewatched' && kind !== 'added')) continue
out.push({
id: typeof r.id === 'number' ? r.id : out.length,
kind,
createdAt,
user: { username: name, displayName: cleanText(r.user.display_name, 40) ?? name, avatarUrl: safeMediaUrl(r.user.avatar_url) },
item,
})
}
return out
}
const toCards = (raw: unknown) => (Array.isArray(raw) ? raw.slice(0, 100).map(toCard).filter((c): c is ProfileCard => c !== null) : [])
export const searchProfiles = async (q: string) => (q.trim().length < 2 ? [] : toCards(await rpc('search_profiles', { q: q.trim().slice(0, 40) })))
export const getFollowList = async (userId: string, kind: 'followers' | 'following', offset = 0) =>
UUID.test(userId) ? toCards(await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })) : []
export const getFollowRequests = async () => toCards(await rpc('get_follow_requests'))
// ─── Abonnements ───
async function ok(res: Response) {
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
}
/** S'abonner. Renvoie « pending » si le compte est privé (demande envoyée). */
export async function follow(userId: string): Promise<Relation> {
if (!UUID.test(userId)) return 'none'
const res = await cloudFetch('/rest/v1/follows', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Prefer: 'return=representation' },
body: JSON.stringify({ following_id: userId }),
})
if (res.status !== 409) await ok(res)
const rows =
res.status === 409
? await (await cloudFetch(`/rest/v1/follows?follower_id=eq.${me()}&following_id=eq.${userId}&select=status`)).json()
: await res.json().catch(() => [])
const [row] = (Array.isArray(rows) ? rows : []) as { status?: string }[]
return relation(row?.status)
}
/** Se désabonner (ou annuler une demande). */
export async function unfollow(userId: string) {
if (!UUID.test(userId)) return
await ok(await cloudFetch(`/rest/v1/follows?follower_id=eq.${me()}&following_id=eq.${userId}`, { method: 'DELETE' }))
}
/** Retirer un abonné (ou refuser sa demande). */
export async function removeFollower(userId: string) {
if (!UUID.test(userId)) return
await ok(await cloudFetch(`/rest/v1/follows?follower_id=eq.${userId}&following_id=eq.${me()}`, { method: 'DELETE' }))
}
export async function acceptFollower(userId: string) {
if (!UUID.test(userId)) return
await ok(
await cloudFetch(`/rest/v1/follows?follower_id=eq.${userId}&following_id=eq.${me()}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'accepted' }),
}),
)
}
// ─── Modifier mon profil ───
export interface ProfilePatch {
username?: string
display_name?: string
bio?: string
is_private?: boolean
avatar_url?: string | null
banner_url?: string | null
}
export async function updateProfile(patch: ProfilePatch): Promise<void> {
const res = await cloudFetch(`/rest/v1/profiles?id=eq.${me()}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', Prefer: 'return=minimal' },
body: JSON.stringify(patch),
})
if (res.ok) return
const body = (await res.json().catch(() => ({}))) as { code?: string; message?: string }
if (body.code === '23505') throw new Error(t('social.err.usernameTaken'))
if (body.message?.includes('reserved')) throw new Error(t('social.err.usernameReserved'))
if (body.code === '23514') throw new Error(t('social.err.invalid'))
throw new Error(t('social.err.server', { status: res.status }))
}
/** Envoie une photo (déjà recadrée) dans mon dossier et renvoie son adresse publique. */
export async function uploadProfileImage(kind: 'avatar' | 'banner', blob: Blob): Promise<string> {
const path = `${me()}/${kind}-${Date.now()}.jpg`
const res = await cloudFetch(`/storage/v1/object/profile-media/${path}`, {
method: 'POST',
headers: { 'Content-Type': 'image/jpeg', 'Cache-Control': '31536000' },
body: blob,
})
if (res.status === 413) throw new Error(t('image.tooBig'))
await ok(res)
return MEDIA_PREFIX() + path
}
/** Supprime une ancienne photo (sans erreur si elle n'existe plus). */
export async function deleteProfileImage(url?: string) {
const safe = safeMediaUrl(url)
if (!safe) return
const path = safe.slice(MEDIA_PREFIX().length)
if (!path.startsWith(me() + '/')) return
await cloudFetch(`/storage/v1/object/profile-media/${path}`, { method: 'DELETE' }).catch(() => undefined)
}
/** Lien public vers un profil. */
export const profileLink = (name: string) => `${location.origin}${location.pathname}#/u/${name}`
+378
View File
@@ -0,0 +1,378 @@
import { t } from '../../i18n'
import type { CustomList, MediaItem, Settings } from '../../types'
import { normalizeItem, normalizeLists, normalizeSettings } from '../backup'
import { mediaDB, onMediaChange } from '../db'
import { blobToPosterDataURL } from '../image'
import { isPlainObject, isSafeId, safeIso } from '../security'
import { scopedKey } from '../scope'
import { cloudFetch } from './api'
/**
* Synchronisation hors-ligne ↔ compte :
* - toutes les modifications sont d'abord écrites sur l'appareil (l'app marche sans réseau),
* - elles sont notées dans une « boîte d'envoi » puis envoyées dès que possible,
* - on récupère ensuite ce qui a changé ailleurs (autre téléphone, ordinateur…).
* En cas de conflit, la modification la plus récente gagne (vérifié aussi par la base).
*/
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor'>
export interface SyncHooks {
getLists: () => CustomList[]
applyLists: (lists: CustomList[]) => void
getSettings: () => SyncedSettings
applySettings: (s: Partial<SyncedSettings>) => void
itemsChanged: () => void
}
export interface SyncStatus {
state: 'idle' | 'syncing' | 'offline' | 'error'
lastSyncAt?: string
pending: number
error?: string
}
interface SyncMeta {
itemsCursor?: string
listsCursor?: string
settingsAt?: string
lastSyncAt?: string
/** clé (« i:<id> », « l:<id> », « s ») → horodatage de la modification locale */
outbox: Record<string, string>
}
const PAGE = 500
const MAX_ROW_BYTES = 380_000
const MAX_BATCH_BYTES = 1_500_000
const OVERLAP_MS = 60_000
const jsonHeaders = { 'Content-Type': 'application/json' }
export interface SyncEngine {
start: () => void
stop: () => void
syncNow: () => Promise<void>
markList: (id: string) => void
markSettings: () => void
status: () => SyncStatus
subscribe: (fn: (s: SyncStatus) => void) => () => void
}
export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
const META_KEY = scopedKey('sync', userId)
const loadMeta = (): SyncMeta => {
try {
const raw = JSON.parse(localStorage.getItem(META_KEY) ?? '{}') as unknown
if (!isPlainObject(raw)) return { outbox: {} }
const outbox: Record<string, string> = {}
if (isPlainObject(raw.outbox)) {
for (const [k, v] of Object.entries(raw.outbox)) {
if ((k === 's' || /^[il]:[A-Za-z0-9_-]{1,64}$/.test(k)) && safeIso(v)) outbox[k] = v as string
}
}
return {
itemsCursor: safeIso(raw.itemsCursor),
listsCursor: safeIso(raw.listsCursor),
settingsAt: safeIso(raw.settingsAt),
lastSyncAt: safeIso(raw.lastSyncAt),
outbox,
}
} catch {
return { outbox: {} }
}
}
let meta = loadMeta()
const saveMeta = () => {
try {
localStorage.setItem(META_KEY, JSON.stringify(meta))
} catch {
/* ignore */
}
}
let status: SyncStatus = { state: 'idle', lastSyncAt: meta.lastSyncAt, pending: Object.keys(meta.outbox).length }
const listeners = new Set<(s: SyncStatus) => void>()
const setStatus = (patch: Partial<SyncStatus>) => {
status = { ...status, ...patch, pending: Object.keys(meta.outbox).length }
for (const fn of listeners) fn(status)
}
const mark = (key: string) => {
meta.outbox[key] = new Date().toISOString()
saveMeta()
setStatus({})
schedule()
}
// ─── Envoi ───
/** Réduit une fiche trop lourde (affiche importée en très haute qualité) avant envoi. */
async function fitForUpload(item: MediaItem): Promise<MediaItem> {
if (JSON.stringify(item).length <= MAX_ROW_BYTES) return item
if (item.poster?.startsWith('data:image')) {
try {
const blob = await (await fetch(item.poster)).blob()
const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) }
if (JSON.stringify(smaller).length <= MAX_ROW_BYTES) return smaller
} catch {
/* image illisible */
}
}
const { poster: _poster, ...rest } = item
const stripped = rest as MediaItem
return JSON.stringify(stripped).length <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined }
}
async function upsert(table: 'items' | 'lists', rows: { id: string; data: unknown; deleted: boolean; updated_at: string }[]) {
// Envoi par paquets de taille raisonnable
let batch: typeof rows = []
let size = 0
const flush = async () => {
if (!batch.length) return
const res = await cloudFetch(`/rest/v1/${table}?on_conflict=user_id,id`, {
method: 'POST',
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify(batch.map((r) => ({ ...r, user_id: userId }))),
})
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
batch = []
size = 0
}
for (const r of rows) {
const bytes = JSON.stringify(r).length
if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush()
batch.push(r)
size += bytes
}
await flush()
}
async function push() {
const snapshot = { ...meta.outbox }
const keys = Object.keys(snapshot)
if (!keys.length) return
const itemIds = keys.filter((k) => k.startsWith('i:')).map((k) => k.slice(2))
if (itemIds.length) {
const rows = []
for (const id of itemIds) {
const item = await mediaDB.get(id)
if (item) {
const data = await fitForUpload(item)
rows.push({ id, data, deleted: false, updated_at: item.updatedAt })
} else {
rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] })
}
}
await upsert('items', rows)
}
const listIds = keys.filter((k) => k.startsWith('l:')).map((k) => k.slice(2))
if (listIds.length) {
const current = new Map(hooks.getLists().map((l) => [l.id, l]))
await upsert(
'lists',
listIds.map((id) => {
const l = current.get(id)
return { id, data: l ?? null, deleted: !l, updated_at: snapshot[`l:${id}`] }
}),
)
}
if (snapshot.s) {
const res = await cloudFetch('/rest/v1/settings?on_conflict=user_id', {
method: 'POST',
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify({ user_id: userId, data: hooks.getSettings(), updated_at: snapshot.s }),
})
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
meta.settingsAt = snapshot.s
}
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
for (const k of keys) if (meta.outbox[k] === snapshot[k]) delete meta.outbox[k]
saveMeta()
}
// ─── Réception ───
type Row = { id: string; data: unknown; deleted: boolean; updated_at: string; server_updated_at: string }
async function fetchChanges(table: 'items' | 'lists', cursor?: string): Promise<{ rows: Row[]; cursor?: string }> {
const rows: Row[] = []
let after = cursor ? new Date(new Date(cursor).getTime() - OVERLAP_MS).toISOString() : undefined
let last = cursor
for (let page = 0; page < 200; page++) {
const q = new URLSearchParams({ select: 'id,data,deleted,updated_at,server_updated_at', order: 'server_updated_at.asc,id.asc', limit: String(PAGE) })
if (after) q.set('server_updated_at', `gt.${after}`)
const res = await cloudFetch(`/rest/v1/${table}?${q}`)
if (!res.ok) throw new Error(t('sync.err.pull', { status: res.status }))
const list = (await res.json()) as unknown
if (!Array.isArray(list)) throw new Error(t('auth.err.response'))
for (const r of list) {
if (!isPlainObject(r) || !isSafeId(r.id) || !safeIso(r.updated_at) || !safeIso(r.server_updated_at)) continue
rows.push(r as unknown as Row)
last = r.server_updated_at as string
}
if (list.length < PAGE) break
after = last
}
return { rows, cursor: last }
}
async function pullItems() {
const { rows, cursor } = await fetchChanges('items', meta.itemsCursor)
const toPut: MediaItem[] = []
const toRemove: string[] = []
for (const r of rows) {
if (meta.outbox[`i:${r.id}`]) continue // modification locale en attente : elle passera en priorité
const local = await mediaDB.get(r.id)
if (r.deleted) {
if (local) toRemove.push(r.id)
continue
}
const item = normalizeItem(r.data)
if (!item || item.id !== r.id) continue
if (local && local.updatedAt > item.updatedAt) continue
// Même version : on garde l'affiche locale si le serveur ne l'a pas (fiche allégée à l'envoi)
if (local && local.updatedAt === item.updatedAt && !item.poster && local.poster) item.poster = local.poster
if (local && JSON.stringify(local) === JSON.stringify(item)) continue
toPut.push(item)
}
await mediaDB.putMany(toPut, { silent: true })
await mediaDB.removeMany(toRemove, { silent: true })
meta.itemsCursor = safeIso(cursor)
saveMeta()
if (toPut.length || toRemove.length) hooks.itemsChanged()
}
async function pullLists() {
const { rows, cursor } = await fetchChanges('lists', meta.listsCursor)
if (rows.length) {
const map = new Map(hooks.getLists().map((l) => [l.id, l]))
let changed = false
for (const r of rows) {
if (meta.outbox[`l:${r.id}`]) continue
if (r.deleted) {
changed = map.delete(r.id) || changed
continue
}
const [l] = normalizeLists([r.data]) ?? []
if (l && l.id === r.id && JSON.stringify(map.get(l.id)) !== JSON.stringify(l)) {
map.set(l.id, l)
changed = true
}
}
if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)))
}
meta.listsCursor = safeIso(cursor)
saveMeta()
}
async function pullSettings() {
if (meta.outbox.s) return
const res = await cloudFetch('/rest/v1/settings?select=data,updated_at&limit=1')
if (!res.ok) throw new Error(t('sync.err.pull', { status: res.status }))
const [row] = (await res.json()) as { data?: unknown; updated_at?: string }[]
const at = safeIso(row?.updated_at)
if (!row || !at || (meta.settingsAt && at <= meta.settingsAt)) return
const s = normalizeSettings(row.data)
if (s) hooks.applySettings(s)
meta.settingsAt = at
saveMeta()
}
// ─── Orchestration ───
let running: Promise<void> | null = null
let again = false
let stopped = true
let timer: ReturnType<typeof setTimeout> | undefined
let interval: ReturnType<typeof setInterval> | undefined
async function cycle() {
if (!navigator.onLine) {
setStatus({ state: 'offline' })
return
}
setStatus({ state: 'syncing', error: undefined })
try {
await push()
await pullItems()
await pullLists()
await pullSettings()
meta.lastSyncAt = new Date().toISOString()
saveMeta()
setStatus({ state: 'idle', lastSyncAt: meta.lastSyncAt })
} catch (e) {
setStatus({ state: navigator.onLine ? 'error' : 'offline', error: (e as Error).message })
}
}
function syncNow(): Promise<void> {
if (stopped) return Promise.resolve()
if (running) {
again = true
return running
}
running = (async () => {
do {
again = false
await cycle()
} while (again && !stopped)
})().finally(() => {
running = null
})
return running
}
function schedule(delay = 1500) {
if (stopped) return
clearTimeout(timer)
timer = setTimeout(() => void syncNow(), delay)
}
const onOnline = () => schedule(300)
const onOffline = () => setStatus({ state: 'offline' })
const onVisible = () => document.visibilityState === 'visible' && schedule(300)
let unsubscribeDB: (() => void) | undefined
return {
start() {
if (!stopped) return
stopped = false
unsubscribeDB = onMediaChange((c) => {
const now = new Date().toISOString()
for (const i of c.put) meta.outbox[`i:${i.id}`] = now
for (const id of c.removed) meta.outbox[`i:${id}`] = now
saveMeta()
setStatus({})
schedule()
})
window.addEventListener('online', onOnline)
window.addEventListener('offline', onOffline)
document.addEventListener('visibilitychange', onVisible)
interval = setInterval(() => document.visibilityState === 'visible' && void syncNow(), 60_000)
void syncNow()
},
stop() {
stopped = true
clearTimeout(timer)
clearInterval(interval)
unsubscribeDB?.()
window.removeEventListener('online', onOnline)
window.removeEventListener('offline', onOffline)
document.removeEventListener('visibilitychange', onVisible)
},
syncNow,
markList: (id) => mark(`l:${id}`),
markSettings: () => mark('s'),
status: () => status,
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
}
}
+64
View File
@@ -0,0 +1,64 @@
import { t } from '../i18n'
import type { CriteriaKey, MediaType, TopCategory, WatchStatus } from '../types'
export interface MediaTypeInfo {
value: MediaType
/** Nom affiché (dans la langue choisie) */
readonly label: string
/** Minutes par épisode par défaut, pour l'estimation du temps passé. */
episodeMinutes: number
/** Le format a-t-il des épisodes ? */
episodic: boolean
}
export const MEDIA_TYPES: MediaTypeInfo[] = [
{ value: 'film', get label() { return t('type.film') }, episodeMinutes: 0, episodic: false },
{ value: 'serie', get label() { return t('type.serie') }, episodeMinutes: 45, episodic: true },
{ value: 'anime', get label() { return t('type.anime') }, episodeMinutes: 24, episodic: true },
{ value: 'kdrama', get label() { return t('type.kdrama') }, episodeMinutes: 60, episodic: true },
{ value: 'cdrama', get label() { return t('type.cdrama') }, episodeMinutes: 45, episodic: true },
{ value: 'autre', get label() { return t('type.autre') }, episodeMinutes: 45, episodic: true },
]
export const TYPE_BY_VALUE = Object.fromEntries(MEDIA_TYPES.map((t) => [t.value, t])) as Record<MediaType, MediaTypeInfo>
export const DEFAULT_FILM_MINUTES = 110
export interface StatusInfo {
value: WatchStatus
readonly label: string
dot: string
}
export const STATUSES: StatusInfo[] = [
{ value: 'a_voir', get label() { return t('status.a_voir') }, dot: 'border border-ink-3' },
{ value: 'en_cours', get label() { return t('status.en_cours') }, dot: 'bg-accent' },
{ value: 'termine', get label() { return t('status.termine') }, dot: 'bg-ink' },
{ value: 'pause', get label() { return t('status.pause') }, dot: 'bg-ink-3' },
{ value: 'abandonne', get label() { return t('status.abandonne') }, dot: 'bg-line-strong' },
]
export const STATUS_BY_VALUE = Object.fromEntries(STATUSES.map((s) => [s.value, s])) as Record<WatchStatus, StatusInfo>
export const CRITERIA: { key: CriteriaKey; readonly label: string }[] = [
{ key: 'story', get label() { return t('criteria.story') } },
{ key: 'cast', get label() { return t('criteria.cast') } },
{ key: 'direction', get label() { return t('criteria.direction') } },
{ key: 'ost', get label() { return t('criteria.ost') } },
]
export const PLATFORM_SUGGESTIONS = [
'Netflix', 'Prime Video', 'Disney+', 'Crunchyroll', 'ADN', 'Viki', 'Apple TV+', 'Max',
'Canal+', 'Paramount+', 'YouTube', 'iQIYI', 'WeTV', 'Youku',
]
export const platformSuggestions = () => [...PLATFORM_SUGGESTIONS, t('platform.cinema'), t('platform.dvd'), t('platform.tv')]
export const TOP_CATEGORIES: { value: TopCategory; readonly label: string; readonly plural: string }[] = [
{ value: 'film', get label() { return t('type.film') }, get plural() { return t('typePlural.film') } },
{ value: 'serie', get label() { return t('type.serie') }, get plural() { return t('typePlural.serie') } },
{ value: 'anime', get label() { return t('type.anime') }, get plural() { return t('typePlural.anime') } },
{ value: 'kdrama', get label() { return t('type.kdrama') }, get plural() { return t('typePlural.kdrama') } },
{ value: 'cdrama', get label() { return t('type.cdrama') }, get plural() { return t('typePlural.cdrama') } },
]
export const ALL_TOP_CATEGORIES: TopCategory[] = TOP_CATEGORIES.map((c) => c.value)
+144
View File
@@ -0,0 +1,144 @@
import type { MediaItem } from '../types'
import { dbNameFor, getScope } from './scope'
/**
* Mini-wrapper IndexedDB sans dépendance.
* Une base par compte (ou « azuucine » sans compte) : deux comptes sur le même appareil ne se mélangent jamais.
*/
const DB_VERSION = 1
const STORE = 'media'
let dbPromise: Promise<IDBDatabase> | null = null
let dbName = ''
function open(name: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const req = indexedDB.open(name, DB_VERSION)
req.onupgradeneeded = () => {
const db = req.result
if (!db.objectStoreNames.contains(STORE)) {
const store = db.createObjectStore(STORE, { keyPath: 'id' })
store.createIndex('type', 'type')
store.createIndex('status', 'status')
store.createIndex('updatedAt', 'updatedAt')
}
}
req.onsuccess = () => resolve(req.result)
req.onerror = () => reject(req.error)
})
}
function openDB(): Promise<IDBDatabase> {
const name = dbNameFor(getScope())
if (!dbPromise || dbName !== name) {
closeDB()
dbName = name
dbPromise = open(name).catch((e) => {
dbPromise = null
throw e
})
}
return dbPromise
}
/** Ferme la base ouverte (changement de compte, suppression). */
export function closeDB() {
const p = dbPromise
dbPromise = null
dbName = ''
p?.then((db) => db.close()).catch(() => {})
}
async function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T> | void, db?: IDBDatabase): Promise<T> {
const database = db ?? (await openDB())
return new Promise<T>((resolve, reject) => {
const tx = database.transaction(STORE, mode)
const req = fn(tx.objectStore(STORE))
tx.oncomplete = () => resolve(req ? req.result : (undefined as T))
tx.onerror = () => reject(tx.error)
tx.onabort = () => reject(tx.error)
})
}
// ─── Notification des modifications (pour la synchronisation) ───
export interface MediaChange {
put: MediaItem[]
removed: string[]
}
const listeners = new Set<(c: MediaChange) => void>()
export function onMediaChange(fn: (c: MediaChange) => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
const notify = (c: MediaChange, silent?: boolean) => {
if (!silent) for (const fn of listeners) fn(c)
}
interface Opts {
/** Écriture venant de la synchro : ne pas la renvoyer au serveur */
silent?: boolean
}
export const mediaDB = {
getAll: () => run<MediaItem[]>('readonly', (s) => s.getAll() as IDBRequest<MediaItem[]>),
get: (id: string) => run<MediaItem | undefined>('readonly', (s) => s.get(id) as IDBRequest<MediaItem | undefined>),
put: async (item: MediaItem, opts: Opts = {}) => {
await run('readwrite', (s) => void s.put(item))
notify({ put: [item], removed: [] }, opts.silent)
},
putMany: async (items: MediaItem[], opts: Opts = {}) => {
if (!items.length) return
await run('readwrite', (s) => {
for (const item of items) s.put(item)
})
notify({ put: items, removed: [] }, opts.silent)
},
remove: async (id: string, opts: Opts = {}) => {
await run('readwrite', (s) => void s.delete(id))
notify({ put: [], removed: [id] }, opts.silent)
},
removeMany: async (ids: string[], opts: Opts = {}) => {
if (!ids.length) return
await run('readwrite', (s) => {
for (const id of ids) s.delete(id)
})
notify({ put: [], removed: ids }, opts.silent)
},
clear: async (opts: Opts = {}) => {
const ids = await run<IDBValidKey[]>('readonly', (s) => s.getAllKeys())
await run('readwrite', (s) => void s.clear())
notify({ put: [], removed: ids.map(String) }, opts.silent)
},
}
/** Lit toutes les fiches d'une autre base (ex. les données « sans compte » de cet appareil). */
export async function readOtherDatabase(name: string): Promise<MediaItem[]> {
const exists = (await indexedDB.databases?.())?.some((d) => d.name === name)
if (exists === false) return []
const db = await open(name)
try {
return await run<MediaItem[]>('readonly', (s) => s.getAll() as IDBRequest<MediaItem[]>, db)
} finally {
db.close()
}
}
/** Supprime complètement une base de l'appareil. */
export function deleteDatabase(name: string): Promise<void> {
if (name === dbName) closeDB()
return new Promise((resolve) => {
const req = indexedDB.deleteDatabase(name)
req.onsuccess = req.onerror = req.onblocked = () => resolve()
})
}
/** Demande au navigateur de ne pas effacer les données automatiquement (utile sur iOS). */
export async function requestPersistentStorage(): Promise<boolean> {
try {
if (navigator.storage?.persisted && (await navigator.storage.persisted())) return true
if (navigator.storage?.persist) return await navigator.storage.persist()
} catch {
/* non supporté */
}
return false
}
+79
View File
@@ -0,0 +1,79 @@
/**
* Carrousels horizontaux sur ordinateur : sans écran tactile, on ne peut pas les faire défiler
* (la barre de défilement est masquée et la molette fait défiler la page).
* On ajoute donc, pour tous les carrousels de l'app :
* - la molette verticale → défilement horizontal quand la souris est sur un carrousel,
* - le glisser-déposer à la souris (un simple clic reste un clic).
*/
function scroller(target: EventTarget | null): HTMLElement | null {
let el = target instanceof Element ? (target as HTMLElement) : null
while (el && el !== document.body) {
if (el.scrollWidth > el.clientWidth + 1) {
const ox = getComputedStyle(el).overflowX
if (ox === 'auto' || ox === 'scroll') return el
}
el = el.parentElement
}
return null
}
export function enableDesktopCarousels() {
// Molette
window.addEventListener(
'wheel',
(e) => {
if (e.ctrlKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return
const el = scroller(e.target)
if (!el) return
const max = el.scrollWidth - el.clientWidth
const canMove = (e.deltaY > 0 && el.scrollLeft < max - 1) || (e.deltaY < 0 && el.scrollLeft > 1)
if (!canMove) return // au bout du carrousel : la page reprend la main
e.preventDefault()
el.scrollLeft += e.deltaY
},
{ passive: false },
)
// Glisser à la souris
let drag: { el: HTMLElement; x: number; left: number; moved: boolean; id: number } | null = null
window.addEventListener('pointerdown', (e) => {
if (e.pointerType !== 'mouse' || e.button !== 0) return
if ((e.target as Element).closest?.('input, textarea, select')) return
const el = scroller(e.target)
if (el) drag = { el, x: e.clientX, left: el.scrollLeft, moved: false, id: e.pointerId }
})
window.addEventListener('pointermove', (e) => {
if (!drag || e.pointerId !== drag.id) return
const dx = e.clientX - drag.x
if (!drag.moved && Math.abs(dx) < 6) return
if (!drag.moved) {
drag.moved = true
drag.el.style.cursor = 'grabbing'
drag.el.style.userSelect = 'none'
}
drag.el.scrollLeft = drag.left - dx
})
const end = () => {
if (!drag) return
const { el, moved } = drag
el.style.cursor = ''
el.style.userSelect = ''
drag = null
if (moved) {
// Le relâchement après un glissement ne doit pas ouvrir la fiche sous la souris
const stop = (ev: Event) => {
ev.stopPropagation()
ev.preventDefault()
}
window.addEventListener('click', stop, { capture: true, once: true })
setTimeout(() => window.removeEventListener('click', stop, { capture: true }), 0)
}
}
window.addEventListener('pointerup', end)
window.addEventListener('pointercancel', end)
// Les images ne doivent pas être « attrapées » par le navigateur pendant le glissement
window.addEventListener('dragstart', (e) => {
if (scroller(e.target)) e.preventDefault()
})
}
+143
View File
@@ -0,0 +1,143 @@
import { t, type TKey } from '../i18n'
import { normalizeText } from './utils'
/**
* Genres : ils sont enregistrés sous un nom de référence (français, pour rester compatibles avec
* les anciennes fiches et sauvegardes) et affichés dans la langue choisie.
*/
const CANONICAL: [string, TKey][] = [
['Action', 'genre.action'],
['Aventure', 'genre.adventure'],
['Animation', 'genre.animation'],
['Anime', 'genre.anime'],
['Comédie', 'genre.comedy'],
['Comédie romantique', 'genre.romanticComedy'],
['Rom-com', 'genre.romcom'],
['Policier', 'genre.crime'],
['Documentaire', 'genre.documentary'],
['Drame', 'genre.drama'],
['Famille', 'genre.family'],
['Fantasy', 'genre.fantasy'],
['Historique', 'genre.historical'],
['Horreur', 'genre.horror'],
['Musical', 'genre.musical'],
['Musique', 'genre.music'],
['Mystère', 'genre.mystery'],
['Romance', 'genre.romance'],
['Sci-Fi', 'genre.scifi'],
['Téléfilm', 'genre.tvMovie'],
['Thriller', 'genre.thriller'],
['Guerre', 'genre.war'],
['Western', 'genre.western'],
['Enfants', 'genre.kids'],
['Actualités', 'genre.news'],
['Télé-réalité', 'genre.reality'],
['Feuilleton', 'genre.soap'],
['Talk-show', 'genre.talk'],
['Politique', 'genre.politics'],
['Ecchi', 'genre.ecchi'],
['Magical Girl', 'genre.magicalGirl'],
['Mecha', 'genre.mecha'],
['Psychologique', 'genre.psychological'],
['Slice of Life', 'genre.sliceOfLife'],
['Sport', 'genre.sports'],
['Surnaturel', 'genre.supernatural'],
['Shōnen', 'genre.shonen'],
['Shōjo', 'genre.shojo'],
['Seinen', 'genre.seinen'],
['Isekai', 'genre.isekai'],
['Médical', 'genre.medical'],
['Juridique', 'genre.legal'],
['Wuxia', 'genre.wuxia'],
['Xianxia', 'genre.xianxia'],
]
// Anciennes variantes rencontrées dans les fiches
const ALIASES: Record<string, string> = {
familial: 'Famille',
histoire: 'Historique',
crime: 'Policier',
'science-fiction': 'Sci-Fi',
fantastique: 'Fantasy',
}
const KEY_BY_NAME = new Map(CANONICAL.map(([name, key]) => [normalizeText(name), key]))
/** Nom affiché d'un genre enregistré (inchangé si le genre est inconnu, ex. saisi à la main). */
export function genreLabel(stored: string): string {
const n = normalizeText(stored)
const key = KEY_BY_NAME.get(n) ?? KEY_BY_NAME.get(normalizeText(ALIASES[n] ?? ''))
return key ? t(key) : stored
}
/** Nom de référence à enregistrer, à partir d'un texte saisi dans n'importe quelle langue de l'app. */
export function canonicalGenre(input: string): string {
const n = normalizeText(input)
for (const [name, key] of CANONICAL) if (normalizeText(t(key)) === n || normalizeText(name) === n) return name
return ALIASES[n] ?? input.trim()
}
/** Genres TMDB (identifiants universels) → noms de référence */
const TMDB_GENRES: Record<number, string[]> = {
28: ['Action'],
12: ['Aventure'],
16: ['Animation'],
35: ['Comédie'],
80: ['Policier'],
99: ['Documentaire'],
18: ['Drame'],
10751: ['Famille'],
14: ['Fantasy'],
36: ['Historique'],
27: ['Horreur'],
10402: ['Musique'],
9648: ['Mystère'],
10749: ['Romance'],
878: ['Sci-Fi'],
10770: ['Téléfilm'],
53: ['Thriller'],
10752: ['Guerre'],
37: ['Western'],
10759: ['Action', 'Aventure'],
10762: ['Enfants'],
10763: ['Actualités'],
10764: ['Télé-réalité'],
10765: ['Sci-Fi', 'Fantasy'],
10766: ['Feuilleton'],
10767: ['Talk-show'],
10768: ['Guerre', 'Politique'],
}
export function tmdbGenres(ids: number[]): string[] {
return [...new Set(ids.flatMap((id) => TMDB_GENRES[id] ?? []))]
}
/** Suggestions proposées à la saisie (dans la langue choisie) */
export const genreSuggestions = () =>
[
'Action', 'Aventure', 'Comédie', 'Drame', 'Romance', 'Rom-com', 'Thriller', 'Horreur', 'Mystère', 'Policier', 'Sci-Fi', 'Fantasy',
'Historique', 'Slice of Life', 'Shōnen', 'Shōjo', 'Seinen', 'Isekai', 'Mecha', 'Sport', 'Musical', 'Médical', 'Juridique', 'Wuxia',
'Xianxia', 'Famille', 'Animation', 'Psychologique', 'Surnaturel', 'Comédie romantique', 'Documentaire',
].map(genreLabel)
/** Sous-types « Autre » : enregistrés en français, affichés dans la langue choisie. */
const SUBTYPES: [string, TKey][] = [
['Documentaire', 'subtype.documentary'],
['Télé-réalité', 'subtype.reality'],
['Émission', 'subtype.show'],
['Court-métrage', 'subtype.short'],
['Spectacle', 'subtype.stage'],
['Mini-série', 'subtype.miniseries'],
]
const SUBTYPE_KEY = new Map(SUBTYPES.map(([name, key]) => [normalizeText(name), key]))
export const subtypeLabel = (stored: string) => {
const key = SUBTYPE_KEY.get(normalizeText(stored))
return key ? t(key) : stored
}
export const canonicalSubtype = (input: string) => {
const n = normalizeText(input)
for (const [name, key] of SUBTYPES) if (normalizeText(t(key)) === n || normalizeText(name) === n) return name
return input.trim()
}
export const subtypeSuggestions = () => SUBTYPES.map(([, key]) => t(key))
+132
View File
@@ -0,0 +1,132 @@
import { t } from '../i18n'
import { aniListAiring, safeRelease, tmdbEpisodeReleases, tmdbMovieReleases, type GlobalRelease, type ReleaseCategory } from './catalogApi'
import { isPlainObject, readStorage, safeIso } from './security'
/**
* Sorties « globales » du calendrier : films au cinéma en France, épisodes des séries populaires,
* des K-dramas / C-dramas (TMDB) et de tous les animes diffusés (AniList).
* Mises en cache par mois et par catégorie sur l'appareil (12 h pour le mois en cours et à venir).
*/
export const RELEASE_CATEGORIES: { value: ReleaseCategory; readonly label: string; needsKey: boolean }[] = [
{ value: 'film', get label() { return t('typePlural.film') }, needsKey: true },
{ value: 'serie', get label() { return t('typePlural.serie') }, needsKey: true },
{ value: 'anime', get label() { return t('typePlural.anime') }, needsKey: false },
{ value: 'kdrama', get label() { return t('typePlural.kdrama') }, needsKey: true },
{ value: 'cdrama', get label() { return t('typePlural.cdrama') }, needsKey: true },
]
const CAT_SET = new Set<string>(RELEASE_CATEGORIES.map((c) => c.value))
const KEY = 'azuucine:global-releases'
const FRESH_MS = 12 * 3600 * 1000
const PAST_FRESH_MS = 7 * 24 * 3600 * 1000
/** Mois consultables : le précédent et les 6 suivants. */
export const MONTHS_BACK = 1
export const MONTHS_AHEAD = 6
const inflight = new Map<string, Promise<GlobalRelease[]>>()
type Cache = Record<string, Partial<Record<ReleaseCategory, { at: string; list: GlobalRelease[] }>>>
const monthKey = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
function monthOffset(key: string): number {
const [y, m] = key.split('-').map(Number)
const now = new Date()
return (y - now.getFullYear()) * 12 + (m - 1 - now.getMonth())
}
export const isBrowsableMonth = (key: string) => {
const o = monthOffset(key)
return o >= -MONTHS_BACK && o <= MONTHS_AHEAD
}
function load(): Cache {
const raw = readStorage(KEY, {})
const out: Cache = {}
if (!isPlainObject(raw)) return out
for (const [month, cats] of Object.entries(raw)) {
if (!/^\d{4}-\d{2}$/.test(month) || !isPlainObject(cats)) continue
for (const [cat, v] of Object.entries(cats)) {
if (!CAT_SET.has(cat) || !isPlainObject(v) || !Array.isArray(v.list)) continue
const at = safeIso(v.at)
if (!at) continue
const list = v.list
.slice(0, 800)
.map((r) => (isPlainObject(r) ? safeRelease({ ...(r as unknown as GlobalRelease), cat: cat as ReleaseCategory }) : null))
.filter((r): r is GlobalRelease => !!r && r.date.startsWith(month))
;(out[month] ??= {})[cat as ReleaseCategory] = { at, list }
}
}
return out
}
function save(cache: Cache) {
// On ne garde que les mois consultables
for (const m of Object.keys(cache)) if (!isBrowsableMonth(m)) delete cache[m]
try {
localStorage.setItem(KEY, JSON.stringify(cache))
} catch {
// stockage plein : on repart d'un cache vide plutôt que de bloquer
try {
localStorage.removeItem(KEY)
} catch {
/* ignore */
}
}
}
/** Sorties déjà en cache pour un mois (affichage immédiat). */
export function cachedMonth(month: Date): GlobalRelease[] {
const entry = load()[monthKey(month)] ?? {}
return Object.values(entry).flatMap((v) => v?.list ?? [])
}
/** Récupère (si besoin) les sorties d'un mois pour les catégories demandées. */
export async function loadMonth(
month: Date,
cats: ReleaseCategory[],
tmdbKey: string | undefined,
force = false,
): Promise<{ releases: GlobalRelease[]; failed: ReleaseCategory[] }> {
const key = monthKey(month)
const cache = load()
const entry = (cache[key] ??= {})
const failed: ReleaseCategory[] = []
if (isBrowsableMonth(key) && navigator.onLine) {
const ttl = monthOffset(key) < 0 ? PAST_FRESH_MS : FRESH_MS
const from = `${key}-01`
const last = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate()
const to = `${key}-${String(last).padStart(2, '0')}`
const stale = cats.filter((c) => {
const e = entry[c]
if (c !== 'anime' && !tmdbKey) return false
return force || !e || Date.now() - new Date(e.at).getTime() > ttl
})
const fetchCat = async (c: ReleaseCategory) => {
// Une seule requête à la fois par mois et par catégorie (double ouverture, double rendu…)
const id = `${key}|${c}`
let job: Promise<GlobalRelease[]> | undefined = inflight.get(id)
if (!job) {
const created = c === 'anime' ? aniListAiring(from, to) : c === 'film' ? tmdbMovieReleases(tmdbKey!, from, to) : tmdbEpisodeReleases(tmdbKey!, c, from, to)
inflight.set(id, created)
created.finally(() => inflight.delete(id)).catch(() => {})
job = created
}
try {
entry[c] = { at: new Date().toISOString(), list: await job }
} catch {
failed.push(c)
}
}
// AniList en parallèle ; les requêtes TMDB les unes après les autres pour rester raisonnable
await Promise.all([
stale.includes('anime') ? fetchCat('anime') : Promise.resolve(),
(async () => {
for (const c of stale.filter((x) => x !== 'anime')) await fetchCat(c)
})(),
])
if (stale.length) save(cache)
}
return { releases: cats.flatMap((c) => entry[c]?.list ?? []), failed }
}
+94
View File
@@ -0,0 +1,94 @@
import { t } from '../i18n'
import { LIMITS, safePosterUrl } from './security'
/**
* Convertit une image (photo de la galerie, affiche téléchargée…) en petit JPEG
* compressé (data URL), pour garder la base légère et 100 % hors-ligne.
*/
export function blobToPosterDataURL(blob: Blob, maxWidth = 360, quality = 0.8): Promise<string> {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(blob)
const img = new Image()
img.onload = () => {
const ratio = Math.min(1, maxWidth / img.width)
const w = Math.round(img.width * ratio)
const h = Math.round(img.height * ratio)
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
if (!ctx) {
URL.revokeObjectURL(url)
reject(new Error(t('image.canvas')))
return
}
ctx.drawImage(img, 0, 0, w, h)
URL.revokeObjectURL(url)
resolve(canvas.toDataURL('image/jpeg', quality))
}
img.onerror = () => {
URL.revokeObjectURL(url)
reject(new Error(t('image.unreadable')))
}
img.src = url
})
}
/** Photo choisie par l'utilisateur : uniquement des images, taille raisonnable. */
export function fileToPosterDataURL(file: File) {
if (!file.type.startsWith('image/') || file.type === 'image/svg+xml') return Promise.reject(new Error(t('image.notImage')))
if (file.size > LIMITS.imageFileBytes) return Promise.reject(new Error(t('image.tooBig')))
// Le passage par un canvas ré-encode l'image en JPEG : aucune donnée cachée (EXIF, GPS…) n'est conservée
return blobToPosterDataURL(file)
}
/**
* Télécharge une affiche distante et la garde en local (visible hors-ligne).
* Si le serveur refuse (CORS, réseau), on garde simplement l'URL.
*/
export async function remotePosterToLocal(url: string): Promise<string | undefined> {
const safe = safePosterUrl(url)
if (!safe || safe.startsWith('data:')) return safe
try {
const res = await fetch(safe, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer' })
const blob = await res.blob()
if (!res.ok || !blob.type.startsWith('image/') || blob.size > LIMITS.imageFileBytes) return safe
return await blobToPosterDataURL(blob)
} catch {
return safe
}
}
/**
* Photo de profil ou bannière : recadrée au centre aux dimensions voulues et ré-encodée en JPEG
* (aucune métadonnée cachée n'est conservée).
*/
export function cropImageToJpeg(file: File, width: number, height: number, quality = 0.86): Promise<Blob> {
if (!file.type.startsWith('image/') || file.type === 'image/svg+xml') return Promise.reject(new Error(t('image.notImage')))
if (file.size > LIMITS.imageFileBytes) return Promise.reject(new Error(t('image.tooBig')))
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(file)
const img = new Image()
img.onload = () => {
URL.revokeObjectURL(url)
const scale = Math.max(width / img.width, height / img.height)
const sw = width / scale
const sh = height / scale
const sx = (img.width - sw) / 2
const sy = (img.height - sh) / 2
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
if (!ctx) return reject(new Error(t('image.canvas')))
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(img, sx, sy, sw, sh, 0, 0, width, height)
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(t('image.unreadable')))), 'image/jpeg', quality)
}
img.onerror = () => {
URL.revokeObjectURL(url)
reject(new Error(t('image.unreadable')))
}
img.src = url
})
}
+212
View File
@@ -0,0 +1,212 @@
import type { MediaItem, MediaType, TopCategory, TopEntry, WatchStatus } from '../types'
import { ALL_TOP_CATEGORIES } from './constants'
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safeDay, safeIso, safeStringList } from './security'
import { splitGenres } from './catalogApi'
import { normalizeText } from './utils'
/**
* Conversion des sauvegardes de l'ancienne appli (format TMDB) :
* { items: [...], episodes: [...], tags: [...], item_tags: [...], top5: [...] }
*/
interface LegacyItem {
id: number
tmdb_id?: number
media_type?: 'movie' | 'tv' | string
title?: string
original_title?: string
poster_path?: string | null
overview?: string
release_date?: string
note?: number
comment?: string
date_added?: string
runtime?: number
genres?: string | string[]
countries?: string | string[]
status?: string
director?: string
number_of_seasons?: number
number_of_episodes?: number
watch_date?: string
}
interface LegacyEpisode {
item_id: number
season_number?: number
episode_number?: number
watched?: number | boolean
watch_date?: string
}
interface LegacyFile {
items: LegacyItem[]
episodes?: LegacyEpisode[]
tags?: { id: number; name: string }[]
item_tags?: { item_id: number; tag_id: number }[]
top5?: { category: string; position: number; item_id: number }[]
}
/** Reconnaît le format de l'ancienne appli. */
export function isLegacyBackup(data: unknown): data is LegacyFile {
if (!data || typeof data !== 'object' || Array.isArray(data)) return false
const items = (data as LegacyFile).items
return Array.isArray(items) && items.length > 0 && typeof items[0] === 'object' && items[0] !== null && ('tmdb_id' in items[0] || 'media_type' in items[0] || 'poster_path' in items[0])
}
const parseList = (v: unknown): string[] => {
if (Array.isArray(v)) return v.filter((x): x is string => typeof x === 'string')
if (typeof v === 'string' && v.trim() && v.length < 20000) {
try {
const parsed = JSON.parse(v)
return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string') : []
} catch {
return v.split(',').map((s) => s.trim()).filter(Boolean)
}
}
return []
}
/** « 2026-07-26 17:57:29 » ou « 2026-07-29T13:38:42.905588 » → ISO */
const toISO = (v?: string): string | undefined =>
typeof v === 'string' ? safeIso(v.includes('T') ? v : v.replace(' ', 'T')) : undefined
const toDay = (v?: string) => (typeof v === 'string' ? safeDay(v.slice(0, 10)) : undefined)
const positive = (n?: number, max = 100000) => (typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.min(max, Math.round(n)) : undefined)
function mapStatus(raw?: string): WatchStatus {
const s = normalizeText(typeof raw === 'string' ? raw.slice(0, 40) : '')
if (s === 'vu' || s.startsWith('termin') || s === 'fini' || s === 'watched') return 'termine'
if (s.includes('cours') || s === 'watching') return 'en_cours'
if (s.includes('pause')) return 'pause'
if (s.includes('aband') || s === 'dropped') return 'abandonne'
return 'a_voir' // wishlist, à voir…
}
function guessType(kind: string | undefined, countries: string[], genres: string[]): { type: MediaType; subtype?: string } {
const has = (g: string) => genres.some((x) => x.includes(g))
if (has('Documentaire')) return { type: 'autre', subtype: 'Documentaire' }
if (has('Télé-réalité') || has('Reality')) return { type: 'autre', subtype: 'Télé-réalité' }
if (kind === 'movie') return { type: 'film' }
const main = countries[0]
if (has('Animation') && countries.includes('JP')) return { type: 'anime' }
if (main === 'KR') return { type: 'kdrama' }
if (main === 'CN' || main === 'TW' || main === 'HK') return { type: 'cdrama' }
return { type: 'serie' }
}
export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; skipped: number } {
const now = new Date().toISOString()
// Épisodes vus par fiche
const eps = new Map<number, LegacyEpisode[]>()
for (const e of data.episodes ?? []) {
if (!e || !(e.watched === 1 || e.watched === true)) continue
const list = eps.get(e.item_id) ?? []
list.push(e)
eps.set(e.item_id, list)
}
// Tags perso
const tagNames = new Map(
(Array.isArray(data.tags) ? data.tags : [])
.filter((t) => t && Number.isInteger(t.id))
.map((t) => [t.id, cleanText(t.name, LIMITS.shortText)] as const),
)
const itemTags = new Map<number, string[]>()
for (const it of data.item_tags ?? []) {
const name = tagNames.get(it.tag_id)
if (!name) continue
itemTags.set(it.item_id, [...(itemTags.get(it.item_id) ?? []), name])
}
// Tops 5 par catégorie
const tops = new Map<number, TopEntry>()
for (const t of data.top5 ?? []) {
if (ALL_TOP_CATEGORIES.includes(t.category as TopCategory) && t.position >= 1 && t.position <= 5) {
tops.set(t.item_id, { category: t.category as TopCategory, rank: t.position })
}
}
const items: MediaItem[] = []
let skipped = 0
for (const r of data.items.slice(0, LIMITS.items)) {
if (!r || typeof r !== 'object' || !Number.isInteger(r.id) || r.id < 0) {
skipped++
continue
}
const title = cleanText(r.title, LIMITS.title)
if (!title) {
skipped++
continue
}
const rawGenres = safeStringList(parseList(r.genres), LIMITS.genres)
const countries = safeCountries(parseList(r.countries)) ?? []
const { type, subtype } = guessType(r.media_type, countries, rawGenres)
const status = mapStatus(r.status)
const isFilm = type === 'film' || r.media_type === 'movie'
const watched = eps.get(r.id) ?? []
const epDates = watched.map((e) => toDay(e.watch_date)).filter((d): d is string => !!d).sort()
const total = isFilm ? undefined : positive(r.number_of_episodes)
let episodesWatched = watched.length
if (!isFilm && status === 'termine' && episodesWatched === 0 && total) episodesWatched = total
if (total && episodesWatched > total) episodesWatched = total
const currentSeason = watched.reduce((m, e) => Math.max(m, e.season_number ?? 0), 0)
const watchDay = toDay(r.watch_date)
const lastEp = epDates[epDates.length - 1]
let startDate: string | undefined
let endDate: string | undefined
if (status === 'termine') {
// date de fin = la plus récente entre la date « vu » et le dernier épisode coché
endDate = [watchDay, lastEp].filter((d): d is string => !!d).sort().pop()
startDate = epDates[0] && endDate && epDates[0] < endDate ? epDates[0] : undefined
} else if (status !== 'a_voir') {
startDate = epDates[0] ?? watchDay
}
const genres = splitGenres(rawGenres, isFilm)
if (isFilm && type === 'film' && countries.includes('JP') && rawGenres.includes('Animation')) genres.unshift('Anime')
for (const t of itemTags.get(r.id) ?? []) if (!genres.includes(t) && genres.length < LIMITS.genres) genres.push(t)
const note = typeof r.note === 'number' && Number.isFinite(r.note) && r.note > 0 ? Math.min(10, Math.round(r.note * 2 * 2) / 2) : undefined
const created = toISO(r.date_added) ?? now
items.push({
id: `legacy-${r.id}`,
title,
originalTitle: r.original_title && r.original_title !== title ? r.original_title : undefined,
type,
subtype,
year: r.release_date && /^\d{4}/.test(r.release_date) ? Number(r.release_date.slice(0, 4)) : undefined,
status,
rating: note,
criteria: {},
top: tops.get(r.id),
countries: countries.length ? countries : undefined,
episodesWatched: isFilm ? 0 : episodesWatched,
episodesTotal: total,
season: !isFilm && currentSeason > 0 ? currentSeason : undefined,
episodeDuration: isFilm ? undefined : positive(r.runtime),
duration: isFilm ? positive(r.runtime) : undefined,
startDate,
endDate,
genres,
notes: cleanText(
[cleanText(r.comment, LIMITS.notes), cleanText(r.director, LIMITS.shortText) ? `Réalisation : ${cleanText(r.director, LIMITS.shortText)}` : '']
.filter(Boolean)
.join('\n\n'),
LIMITS.notes,
),
poster: isSafeTmdbPath(r.poster_path) ? `https://image.tmdb.org/t/p/w342${r.poster_path}` : undefined,
overview: cleanText(r.overview, LIMITS.overview),
externalId: (() => {
const ext = `tmdb:${r.media_type}:${r.tmdb_id}`
return isSafeExternalId(ext) ? ext : undefined
})(),
createdAt: created,
updatedAt: toISO(r.watch_date) ?? created,
})
}
return { items, skipped }
}
+90
View File
@@ -0,0 +1,90 @@
import type { MediaInput, MediaItem } from '../types'
import { getAniListPublicRatings, getTmdbPublicRating } from './catalogApi'
import { isSafeExternalId, readStorage } from './security'
/**
* Récupère la note moyenne du public (TMDB / AniList) pour les fiches qui n'en ont pas.
* Les titres sans note fiable (trop peu de votes) sont mémorisés pour ne pas être redemandés à chaque fois.
*/
const CHECKED_KEY = 'azuucine:public-checked'
const RECHECK_MS = 30 * 24 * 3600 * 1000
function loadChecked(): Record<string, number> {
const raw = readStorage(CHECKED_KEY, {})
const out: Record<string, number> = {}
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) if (typeof v === 'number') out[k] = v
}
return out
}
function saveChecked(c: Record<string, number>) {
try {
localStorage.setItem(CHECKED_KEY, JSON.stringify(c))
} catch {
/* ignore */
}
}
/** Fiches notées par moi, reliées à une base, sans note publique (et pas vérifiées récemment). */
export function missingPublic(items: MediaItem[], tmdbKey?: string): MediaItem[] {
const checked = loadChecked()
const now = Date.now()
return items.filter(
(i) =>
i.publicRating == null &&
isSafeExternalId(i.externalId) &&
(i.externalId.startsWith('anilist:') || !!tmdbKey) &&
!(checked[i.id] && now - checked[i.id] < RECHECK_MS),
)
}
export async function fetchPublicRatings(
items: MediaItem[],
tmdbKey: string | undefined,
onProgress?: (done: number, total: number) => void,
): Promise<{ id: string; patch: Partial<MediaInput> }[]> {
const todo = missingPublic(items, tmdbKey).slice(0, 400)
const patches: { id: string; patch: Partial<MediaInput> }[] = []
const checked = loadChecked()
let done = 0
const total = todo.length
const ani = todo.filter((i) => i.externalId!.startsWith('anilist:'))
if (ani.length) {
try {
const map = await getAniListPublicRatings(ani.map((i) => Number(i.externalId!.split(':')[1])))
for (const i of ani) {
const r = map.get(Number(i.externalId!.split(':')[1]))
if (r) patches.push({ id: i.id, patch: { publicRating: r } })
checked[i.id] = Date.now()
}
} catch {
/* réseau : on réessaiera */
}
done += ani.length
onProgress?.(done, total)
}
if (tmdbKey) {
const tmdb = todo.filter((i) => i.externalId!.startsWith('tmdb:'))
for (let k = 0; k < tmdb.length; k += 4) {
await Promise.all(
tmdb.slice(k, k + 4).map(async (i) => {
try {
const r = await getTmdbPublicRating(i.externalId!, tmdbKey)
if (r) patches.push({ id: i.id, patch: { publicRating: r } })
checked[i.id] = Date.now()
} catch {
/* ignore ce titre */
}
}),
)
done += tmdb.slice(k, k + 4).length
onProgress?.(done, total)
}
}
saveChecked(checked)
return patches
}
+113
View File
@@ -0,0 +1,113 @@
import { locale, t } from '../i18n'
import type { MediaItem } from '../types'
import { loadAiring, trackable, CACHE_EVENT } from './airing'
import { getAniListReleases, getTmdbRelease, type ReleaseInfo } from './catalogApi'
import { isPlainObject, isSafeExternalId, isSafeId, readStorage, safeDay, safeIso } from './security'
import { todayISO } from './utils'
/**
* Calendrier des sorties :
* - prochains épisodes des séries / animes suivis (cache du suivi des épisodes),
* - dates de sortie des titres « À voir » (films au cinéma / en ligne, séries, animes).
*/
export interface CalendarEvent {
date: string // AAAA-MM-JJ
item: MediaItem
label: string
kind: 'episode' | 'release'
}
type ReleaseCache = Record<string, ReleaseInfo & { checkedAt: string }>
const KEY = 'azuucine:releases'
const RECHECK_MS = 3 * 24 * 3600 * 1000
export function loadReleases(): ReleaseCache {
const raw = readStorage(KEY, {})
const out: ReleaseCache = {}
if (!isPlainObject(raw)) return out
for (const [id, v] of Object.entries(raw)) {
if (!isSafeId(id) || !isPlainObject(v)) continue
const date = safeDay(v.date)
const checkedAt = safeIso(v.checkedAt)
const label = typeof v.label === 'string' ? v.label.slice(0, 40) : ''
if (date && checkedAt) out[id] = { date, label, checkedAt }
}
return out
}
function saveReleases(c: ReleaseCache) {
try {
localStorage.setItem(KEY, JSON.stringify(c))
} catch {
/* ignore */
}
window.dispatchEvent(new Event(CACHE_EVENT))
}
/** Titres « À voir » récents ou à venir, reliés à une base. */
function watchlistCandidates(items: MediaItem[]): MediaItem[] {
const year = new Date().getFullYear()
return items.filter((i) => i.status === 'a_voir' && isSafeExternalId(i.externalId) && (!i.year || i.year >= year - 1))
}
export async function refreshReleases(items: MediaItem[], tmdbKey?: string, force = false): Promise<ReleaseCache> {
const cache = loadReleases()
const now = new Date().toISOString()
const todo = watchlistCandidates(items).filter(
(i) => force || !cache[i.id] || Date.now() - new Date(cache[i.id].checkedAt).getTime() > RECHECK_MS,
)
const ani = todo.filter((i) => i.externalId!.startsWith('anilist:'))
if (ani.length) {
try {
const map = await getAniListReleases(ani.map((i) => Number(i.externalId!.split(':')[1])))
for (const i of ani) {
const r = map.get(Number(i.externalId!.split(':')[1]))
if (r) cache[i.id] = { ...r, checkedAt: now }
}
} catch {
/* réseau */
}
}
if (tmdbKey) {
const tmdb = todo.filter((i) => i.externalId!.startsWith('tmdb:')).slice(0, 200)
for (let k = 0; k < tmdb.length; k += 4) {
await Promise.all(
tmdb.slice(k, k + 4).map(async (i) => {
try {
const r = await getTmdbRelease(i.externalId!, tmdbKey)
if (r) cache[i.id] = { ...r, checkedAt: now }
} catch {
/* ignore */
}
}),
)
}
}
saveReleases(cache)
return cache
}
/** Tous les évènements connus, triés par date (à partir d'il y a 7 jours). */
export function calendarEvents(items: MediaItem[], releases: ReleaseCache = loadReleases()): CalendarEvent[] {
const from = new Date(Date.now() - 7 * 86400000).toISOString().slice(0, 10)
const airing = loadAiring()
const events: CalendarEvent[] = []
for (const item of trackable(items)) {
const nx = airing[item.id]?.next
if (nx && nx.date >= from) {
const label = nx.episode === 1 && nx.season ? t('release.season', { season: nx.season }) : t('release.episode', { ep: nx.episode })
events.push({ date: nx.date, item, label, kind: 'episode' })
}
}
const byId = new Map(items.map((i) => [i.id, i]))
for (const [id, r] of Object.entries(releases)) {
const item = byId.get(id)
if (item && item.status === 'a_voir' && r.date >= from) events.push({ date: r.date, item, label: r.label, kind: 'release' })
}
return events.sort((a, b) => a.date.localeCompare(b.date) || a.item.title.localeCompare(b.item.title, locale()))
}
export const isToday = (d: string) => d === todayISO()
+101
View File
@@ -0,0 +1,101 @@
import { formatDuration } from './utils'
import { t } from '../i18n'
import type { MediaItem, MediaType } from '../types'
import { DEFAULT_FILM_MINUTES, MEDIA_TYPES, TYPE_BY_VALUE } from './constants'
import { cleanText, isPlainObject, isSafeId, LIMITS, readStorage } from './security'
/** D'où viennent les titres proposés par la roulette. */
export type RouletteSource = 'a_voir' | 'pause' | 'coups_de_coeur'
/** Temps disponible, en minutes (0 = peu importe). */
export type TimeBudget = 0 | 60 | 90 | 150
export interface RouletteFilters {
sources: RouletteSource[]
/** Listes perso à inclure */
listIds: string[]
types: MediaType[] // vide = tous
time: TimeBudget
genre: string // '' = tous
platform: string // '' = toutes
}
export const DEFAULT_FILTERS: RouletteFilters = { sources: ['a_voir'], listIds: [], types: [], time: 0, genre: '', platform: '' }
export const SOURCES: { value: RouletteSource; readonly label: string }[] = [
{ value: 'a_voir', get label() { return t('status.a_voir') } },
{ value: 'pause', get label() { return t('status.pause') } },
{ value: 'coups_de_coeur', get label() { return t('roulette.rewatch') } },
]
export const TIME_OPTIONS: { value: TimeBudget; readonly label: string }[] = [
{ value: 0, get label() { return t('roulette.anyTime') } },
{ value: 60, get label() { return `< ${formatDuration(60)}` } },
{ value: 90, get label() { return `< ${formatDuration(90)}` } },
{ value: 150, get label() { return `< ${formatDuration(150)}` } },
]
const STORAGE_KEY = 'azuucine:roulette'
export function loadFilters(): RouletteFilters {
const raw = readStorage(STORAGE_KEY, null)
if (!isPlainObject(raw)) return DEFAULT_FILTERS
const arr = (v: unknown) => (Array.isArray(v) ? v : [])
const sources = SOURCES.map((s) => s.value).filter((v) => arr(raw.sources).includes(v))
const listIds = arr(raw.listIds).filter(isSafeId).slice(0, 100)
const types = MEDIA_TYPES.map((t) => t.value).filter((v) => arr(raw.types).includes(v))
const time = TIME_OPTIONS.some((o) => o.value === raw.time) ? (raw.time as TimeBudget) : 0
return {
sources: sources.length || listIds.length ? sources : DEFAULT_FILTERS.sources,
listIds,
types,
time,
genre: cleanText(raw.genre, LIMITS.shortText) ?? '',
platform: cleanText(raw.platform, LIMITS.shortText) ?? '',
}
}
export function saveFilters(f: RouletteFilters) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(f))
} catch {
/* ignore */
}
}
/** Durée d'une « séance » : le film entier, ou un épisode. */
export function sessionMinutes(item: MediaItem): number {
if (!TYPE_BY_VALUE[item.type].episodic) return item.duration || DEFAULT_FILM_MINUTES
return item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes
}
const isLoved = (i: MediaItem) => i.status === 'termine' && (i.favorite || !!i.top || (i.rating ?? 0) >= 8)
/** Titres correspondant aux sources choisies (avant les autres filtres). */
export function sourcePool(items: MediaItem[], sources: RouletteSource[], listIds: string[] = []): MediaItem[] {
return items.filter(
(i) =>
(listIds.length > 0 && !!i.listIds?.some((l) => listIds.includes(l))) ||
(sources.includes('a_voir') && i.status === 'a_voir') ||
(sources.includes('pause') && i.status === 'pause') ||
(sources.includes('coups_de_coeur') && isLoved(i)),
)
}
export function buildPool(items: MediaItem[], f: RouletteFilters): MediaItem[] {
return sourcePool(items, f.sources, f.listIds).filter(
(i) =>
(!f.types.length || f.types.includes(i.type)) &&
(!f.time || sessionMinutes(i) <= f.time) &&
(!f.genre || i.genres.includes(f.genre)) &&
(!f.platform || i.platform === f.platform),
)
}
/** Tire un titre au hasard en évitant ceux déjà sortis (sauf s'il n'y a plus le choix). */
export function pickRandom(pool: MediaItem[], avoid: Set<string>): MediaItem | undefined {
if (!pool.length) return undefined
const fresh = pool.filter((i) => !avoid.has(i.id))
const from = fresh.length ? fresh : pool
return from[Math.floor(Math.random() * from.length)]
}
+16
View File
@@ -0,0 +1,16 @@
/**
* Espace de stockage de l'appareil : chaque compte a ses propres clés (réglages, listes, synchro)
* et sa propre base IndexedDB. Sans compte (mode local), on garde les anciens noms.
*/
let scope: string | null = null
export const getScope = () => scope
export const setScope = (userId: string | null) => {
scope = userId && /^[0-9a-f-]{36}$/i.test(userId) ? userId : null
}
/** Nom de clé localStorage pour l'espace actif : « azuucine:lists » ou « azuucine:<id>:lists ». */
export const scopedKey = (name: string, userId: string | null = scope) => (userId ? `azuucine:${userId}:${name}` : `azuucine:${name}`)
/** Nom de la base IndexedDB pour un espace. */
export const dbNameFor = (userId: string | null = scope) => (userId ? `azuucine-${userId}` : 'azuucine')
+127
View File
@@ -0,0 +1,127 @@
/**
* Garde-fous de sécurité.
*
* Tout ce qui vient de l'extérieur est considéré comme non fiable :
* - fichiers JSON importés (sauvegardes, ancienne appli),
* - réponses de TMDB / AniList,
* - contenu du localStorage (peut avoir été modifié à la main).
*
* React échappe déjà le texte affiché (pas d'injection HTML possible) ; ces fonctions
* empêchent en plus les URLs piégées, les identifiants détournés et les données énormes.
*/
/** Hôtes autorisés pour les images distantes (doit rester cohérent avec la CSP). */
const IMAGE_HOSTS = ['image.tmdb.org', 's4.anilist.co']
/** Types d'images acceptés en data URL. */
const DATA_IMAGE = /^data:image\/(png|jpe?g|webp|gif|avif);base64,[a-z0-9+/]+=*$/i
export const LIMITS = {
importFileBytes: 30 * 1024 * 1024, // 30 Mo
imageFileBytes: 25 * 1024 * 1024, // photo choisie dans la galerie
items: 20000,
lists: 500,
title: 300,
shortText: 120, // plateforme, sous-type, genre, nom de liste…
notes: 20000,
overview: 10000,
genres: 40,
posterDataUrl: 3 * 1024 * 1024, // ~3 Mo par affiche en data URL
searchQuery: 200,
}
/** Coupe une chaîne trop longue et retire les caractères de contrôle invisibles. */
export function cleanText(value: unknown, max: number): string | undefined {
if (typeof value !== 'string') return undefined
// eslint-disable-next-line no-control-regex
const s = value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '').trim()
return s ? s.slice(0, max) : undefined
}
/** Identifiant interne : lettres, chiffres, tirets, max 64 caractères. */
export function isSafeId(value: unknown): value is string {
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value)
}
/**
* Référence vers une base externe. Format strict pour qu'un fichier piégé ne puisse pas
* faire appeler une autre adresse de l'API (ex. « tmdb:tv:../../account »).
*/
export function isSafeExternalId(value: unknown): value is string {
return typeof value === 'string' && /^(tmdb:(movie|tv):\d{1,10}|anilist:\d{1,10})$/.test(value)
}
/** Chemin d'affiche TMDB (« /abc123.jpg »). */
export function isSafeTmdbPath(value: unknown): value is string {
return typeof value === 'string' && /^\/[A-Za-z0-9_-]{1,100}\.(jpg|jpeg|png|webp)$/i.test(value)
}
/**
* Affiche acceptée : image embarquée (data:image/…) de taille raisonnable,
* ou image HTTPS venant uniquement de TMDB / AniList. Tout le reste est ignoré
* (pas de javascript:, pas de pistage via une image d'un autre site…).
*/
export function safePosterUrl(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined
const v = value.trim()
if (v.startsWith('data:')) return v.length <= LIMITS.posterDataUrl && DATA_IMAGE.test(v) ? v : undefined
try {
const u = new URL(v)
if (u.protocol !== 'https:' || u.username || u.password || u.port) return undefined
return IMAGE_HOSTS.includes(u.hostname) ? u.toString() : undefined
} catch {
return undefined
}
}
/** Date au format AAAA-MM-JJ valide. */
export function safeDay(value: unknown): string | undefined {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return undefined
const d = new Date(value + 'T12:00:00')
return Number.isNaN(d.getTime()) ? undefined : value
}
/** Date-heure ISO valide (ou undefined). */
export function safeIso(value: unknown): string | undefined {
if (typeof value !== 'string' || value.length > 40) return undefined
const d = new Date(value)
return Number.isNaN(d.getTime()) ? undefined : d.toISOString()
}
/** Liste de chaînes courtes, dédoublonnée et limitée. */
export function safeStringList(value: unknown, maxItems: number, maxLen = LIMITS.shortText): string[] {
if (!Array.isArray(value)) return []
const out: string[] = []
for (const v of value) {
const s = cleanText(v, maxLen)
if (s && !out.includes(s)) out.push(s)
if (out.length >= maxItems) break
}
return out
}
/** Codes pays ISO (2 lettres majuscules). */
export function safeCountries(value: unknown): string[] | undefined {
const list = safeStringList(value, 10, 3)
.filter((c) => /^[A-Za-z]{2}$/.test(c))
.map((c) => c.toUpperCase())
return list.length ? list : undefined
}
/** Couleur hexadécimale #rrggbb. */
export const isHexColor = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v)
/** Lecture JSON sûre depuis le localStorage (valeur par défaut si absent ou corrompu). */
export function readStorage<T>(key: string, fallback: T): unknown | T {
try {
const raw = localStorage.getItem(key)
if (!raw || raw.length > 5 * 1024 * 1024) return fallback
return JSON.parse(raw) as unknown
} catch {
return fallback
}
}
/** Objet « simple » (pas un tableau, pas null). */
export const isPlainObject = (v: unknown): v is Record<string, unknown> =>
typeof v === 'object' && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype
+462
View File
@@ -0,0 +1,462 @@
import { genreLabel } from './genres'
import { t } from '../i18n'
import type { MediaItem, RatingScale } from '../types'
import { TYPE_BY_VALUE } from './constants'
import { safePosterUrl } from './security'
import { formatRating } from './utils'
/**
* Génère des images à partager (story / message) directement dans le navigateur,
* avec un <canvas> : fiche d'un titre, ou Top 5.
*/
const W = 1080
const H = 1350
const FONT = "'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"
function cssVar(name: string, fallback: string) {
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim()
return v || fallback
}
function colors() {
return {
bg: '#0a0a0a',
surface: '#161615',
line: '#2a2a28',
ink: '#f4f2ee',
ink2: '#b3b0a8',
ink3: '#8a8781',
accent: cssVar('--color-accent', '#ef4444'),
fill: cssVar('--color-accent-fill', '#d11f2f'),
}
}
/** Charge une image utilisable dans le canvas (null si le serveur l'interdit). */
async function loadImage(raw?: string): Promise<HTMLImageElement | null> {
const src = safePosterUrl(raw)
if (!src) return null
try {
let url = src
let revoke = false
if (!src.startsWith('data:')) {
const res = await fetch(src, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer' })
if (!res.ok) return null
url = URL.createObjectURL(await res.blob())
revoke = true
}
const img = new Image()
img.src = url
await img.decode()
if (revoke) setTimeout(() => URL.revokeObjectURL(url), 5000)
return img
} catch {
return null
}
}
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath()
ctx.moveTo(x + r, y)
ctx.arcTo(x + w, y, x + w, y + h, r)
ctx.arcTo(x + w, y + h, x, y + h, r)
ctx.arcTo(x, y + h, x, y, r)
ctx.arcTo(x, y, x + w, y, r)
ctx.closePath()
}
/** Affiche en « cover » dans un rectangle arrondi (ou vignette avec l'initiale). */
function drawPoster(
ctx: CanvasRenderingContext2D,
img: HTMLImageElement | null,
title: string,
x: number,
y: number,
w: number,
h: number,
r = 24,
/** Point de cadrage vertical (0 = haut, 0,5 = centre) */
focusY = 0.5,
) {
const c = colors()
ctx.save()
roundRect(ctx, x, y, w, h, r)
ctx.clip()
if (img) {
const scale = Math.max(w / img.width, h / img.height)
const iw = img.width * scale
const ih = img.height * scale
ctx.drawImage(img, x + (w - iw) / 2, y + (h - ih) * focusY, iw, ih)
} else {
ctx.fillStyle = c.surface
ctx.fillRect(x, y, w, h)
ctx.fillStyle = c.ink3
ctx.font = `700 ${Math.round(w * 0.35)}px ${FONT}`
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(title.trim().charAt(0).toUpperCase() || '?', x + w / 2, y + h / 2)
ctx.fillStyle = c.fill
ctx.fillRect(x, y + h - 8, w / 3, 8)
}
ctx.restore()
ctx.strokeStyle = c.line
ctx.lineWidth = 2
roundRect(ctx, x, y, w, h, r)
ctx.stroke()
}
/** Coupe un texte en lignes qui tiennent dans maxWidth (avec « … » si trop long). */
function wrap(ctx: CanvasRenderingContext2D, text: string, maxWidth: number, maxLines: number): string[] {
const words = text.replace(/\s+/g, ' ').trim().split(' ')
const lines: string[] = []
let line = ''
for (const word of words) {
const test = line ? `${line} ${word}` : word
if (ctx.measureText(test).width <= maxWidth) line = test
else {
if (line) lines.push(line)
line = word
if (lines.length === maxLines) break
}
}
if (lines.length < maxLines && line) lines.push(line)
if (lines.length === maxLines && words.join(' ').length > lines.join(' ').length) {
let last = lines[maxLines - 1]
while (ctx.measureText(last + '…').width > maxWidth && last.length) last = last.slice(0, -1)
lines[maxLines - 1] = last.trimEnd() + '…'
}
return lines
}
function drawStar(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number) {
ctx.beginPath()
for (let i = 0; i < 10; i++) {
const rad = i % 2 === 0 ? r : r * 0.45
const a = -Math.PI / 2 + (i * Math.PI) / 5
ctx.lineTo(cx + rad * Math.cos(a), cy + rad * Math.sin(a))
}
ctx.closePath()
}
/** 5 étoiles avec demi-étoiles, ou « 8,5/10 ». Renvoie la largeur dessinée. */
function drawRating(ctx: CanvasRenderingContext2D, rating: number, scale: RatingScale, x: number, y: number, size: number): number {
const c = colors()
if (scale === '10') {
ctx.font = `700 ${size}px ${FONT}`
ctx.fillStyle = c.accent
ctx.textAlign = 'left'
ctx.textBaseline = 'middle'
const t = `${formatRating(rating, '10')}/10`
ctx.fillText(t, x, y)
return ctx.measureText(t).width
}
const stars = rating / 2
const gap = size * 0.25
for (let i = 0; i < 5; i++) {
const cx = x + size / 2 + i * (size + gap)
const fill = Math.max(0, Math.min(1, stars - i))
drawStar(ctx, cx, y, size / 2)
ctx.fillStyle = c.line
ctx.fill()
if (fill > 0) {
ctx.save()
ctx.beginPath()
ctx.rect(cx - size / 2, y - size / 2, size * fill, size)
ctx.clip()
drawStar(ctx, cx, y, size / 2)
ctx.fillStyle = c.accent
ctx.fill()
ctx.restore()
}
}
return 5 * size + 4 * gap
}
function drawBrand(ctx: CanvasRenderingContext2D, y: number) {
const c = colors()
ctx.textBaseline = 'alphabetic'
ctx.textAlign = 'left'
ctx.font = `700 34px ${FONT}`
const a = 'Azuu'
const total = ctx.measureText('AzuuCine').width
const x = (W - total) / 2
ctx.fillStyle = c.ink
ctx.fillText(a, x, y)
ctx.fillStyle = c.accent
ctx.fillText('Cine', x + ctx.measureText(a).width, y)
}
async function newCanvas() {
try {
await Promise.all([document.fonts.load(`700 40px Inter`), document.fonts.load(`400 40px Inter`), document.fonts.load(`600 40px Inter`)])
} catch {
/* police système en secours */
}
const canvas = document.createElement('canvas')
canvas.width = W
canvas.height = H
const ctx = canvas.getContext('2d')!
ctx.fillStyle = colors().bg
ctx.fillRect(0, 0, W, H)
return { canvas, ctx }
}
const toBlob = (canvas: HTMLCanvasElement) =>
new Promise<Blob>((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(t('share.err.create')))), 'image/png'))
/** Texte en capitales avec un léger espacement (si le navigateur le permet). */
function setTracking(ctx: CanvasRenderingContext2D, px: number) {
const c = ctx as CanvasRenderingContext2D & { letterSpacing?: string }
if ('letterSpacing' in c) c.letterSpacing = `${px}px`
}
/** Plus grande taille de police (≤ max) pour que le texte tienne sur une ligne ; sinon null. */
function fitSize(ctx: CanvasRenderingContext2D, text: string, weight: number, max: number, min: number, width: number): number | null {
for (let size = max; size >= min; size -= 2) {
ctx.font = `${weight} ${size}px ${FONT}`
if (ctx.measureText(text).width <= width) return size
}
return null
}
export interface CardCredits {
directors: string[]
producers: string[]
cast: string[]
runtime?: number
image?: string
}
/** Pour les affiches TMDB déjà en ligne, on demande une version plus grande (plus nette). */
const hiRes = (url?: string) => (url?.startsWith('https://image.tmdb.org/t/p/w342/') ? url.replace('/w342/', '/w780/') : url)
/**
* Affiche d'une fiche, façon « poster minimaliste » :
* image en haut, gros titre en capitales + année, puis une fiche technique
* (durée, réalisation, production, casting, genres, ma note) — aux couleurs d'AzuuCine.
*/
export async function renderItemCard(item: MediaItem, scale: RatingScale, credits?: CardCredits): Promise<Blob> {
const { canvas, ctx } = await newCanvas()
const c = colors()
// Image de scène HD si TMDB en fournit une, sinon l'affiche (en HD si possible)
const poster = (credits?.image ? await loadImage(credits.image) : null) ?? (await loadImage(hiRes(item.poster))) ?? (await loadImage(item.poster))
const isScene = !!credits?.image?.includes('/w1280/')
// Carte
const cx = 56
const cy = 56
const cw = W - 112
const ch = H - 112
ctx.fillStyle = c.surface
roundRect(ctx, cx, cy, cw, ch, 40)
ctx.fill()
// Fiche technique
const episodic = TYPE_BY_VALUE[item.type].episodic
const minutes = credits?.runtime ?? item.duration
const rows: [string, string][] = []
if (episodic && item.episodesTotal) {
rows.push([t('form.episodes'), `${t('stats.episodesN', { count: item.episodesTotal })}${item.episodeDuration ? ` · ${t('common.minutes', { n: item.episodeDuration })}` : ''}`])
} else if (!episodic && minutes) {
rows.push([t('form.duration'), t('share.minutesLong', { n: minutes })])
}
const notesDirector = item.notes?.match(/Réalisation\s*:\s*(.+)/)?.[1]
const directors = credits?.directors.length ? credits.directors : notesDirector ? [notesDirector.trim()] : []
if (directors.length) rows.push([episodic ? t('share.createdBy') : t('share.directedBy'), directors.join(' · ')])
if (credits?.producers.length) rows.push([t('share.producedBy'), credits.producers.join(' · ')])
if (credits?.cast.length) rows.push([t('share.starring'), credits.cast.join(' · ')])
if (item.genres.length) rows.push([t('share.genres'), item.genres.slice(0, 3).map(genreLabel).join(' · ')])
if (!credits?.cast.length && item.platform) rows.push([t('form.platform'), item.platform])
// Image (cadrée sur le haut de l'affiche, là où sont souvent les visages).
// Moins il y a de lignes d'infos, plus l'image est grande : pas de vide en bas de carte.
const pad = 44
const ix = cx + pad
const iy = cy + pad
const iw = cw - pad * 2
const ih = Math.min(840, 690 + Math.max(0, 5 - rows.length) * 46)
drawPoster(ctx, poster, item.title, ix, iy, iw, ih, 22, isScene ? 0.5 : 0.28)
// Titre + année
const title = item.title.toUpperCase()
const year = item.year ? String(item.year) : ''
ctx.textBaseline = 'alphabetic'
ctx.textAlign = 'left'
setTracking(ctx, -2)
ctx.font = `600 42px ${FONT}`
const yearW = year ? ctx.measureText(year).width + 16 : 0
let y = iy + ih + 118
const size = fitSize(ctx, title, 900, 104, 64, iw - yearW)
ctx.fillStyle = c.ink
if (size) {
ctx.font = `900 ${size}px ${FONT}`
ctx.fillText(title, ix, y)
const tw = ctx.measureText(title).width
if (year) {
setTracking(ctx, 0)
ctx.font = `600 42px ${FONT}`
ctx.fillStyle = c.accent
ctx.fillText(year, ix + tw + 16, y)
}
} else {
// Titre très long : deux lignes plus petites
ctx.font = `900 62px ${FONT}`
const lines = wrap(ctx, title, iw, 2)
y -= 58
lines.forEach((l, i) => ctx.fillText(l, ix, y + i * 64))
y += (lines.length - 1) * 64
if (year) {
setTracking(ctx, 0)
const last = lines[lines.length - 1]
const lw = ctx.measureText(last).width
ctx.font = `600 36px ${FONT}`
ctx.fillStyle = c.accent
ctx.fillText(year, Math.min(ix + lw + 14, ix + iw - ctx.measureText(year).width), y)
}
}
setTracking(ctx, 0)
const labelW = 220
const valueX = ix + labelW
const valueW = iw - labelW
y += 58
const bottom = cy + ch - 120
for (const [label, value] of rows) {
if (y > bottom) break
ctx.font = `600 22px ${FONT}`
setTracking(ctx, 1.5)
ctx.fillStyle = c.ink3
ctx.fillText(label.toUpperCase(), ix, y)
ctx.font = `700 25px ${FONT}`
setTracking(ctx, 0.5)
ctx.fillStyle = c.ink
const lines = wrap(ctx, value.toUpperCase(), valueW, 2)
lines.forEach((l, i) => ctx.fillText(l, valueX, y + i * 32))
y += 32 * lines.length + 16
}
setTracking(ctx, 0)
// Pied de carte : ma note à gauche, marque à droite
const fy = cy + ch - 56
if (item.rating) {
ctx.font = `600 22px ${FONT}`
setTracking(ctx, 1.5)
ctx.fillStyle = c.ink3
ctx.fillText(t('share.myRating').toUpperCase(), ix, fy + 9)
setTracking(ctx, 0)
drawRating(ctx, item.rating, scale, valueX, fy, 34)
}
ctx.textAlign = 'left'
ctx.textBaseline = 'alphabetic'
ctx.font = `800 30px ${FONT}`
const brandW = ctx.measureText('AzuuCine').width
const bx = ix + iw - brandW
ctx.fillStyle = c.ink
ctx.fillText('Azuu', bx, fy + 11)
ctx.fillStyle = c.accent
ctx.fillText('Cine', bx + ctx.measureText('Azuu').width, fy + 11)
return toBlob(canvas)
}
/** Image d'un Top 5 : n°1 en grand, n°2 à 5 à côté. */
export async function renderTopCard(title: string, entries: (MediaItem | undefined)[]): Promise<Blob> {
const { canvas, ctx } = await newCanvas()
const c = colors()
const imgs = await Promise.all(entries.map((e) => loadImage(e?.poster)))
// Titre « Mon Top 5 · Films »
ctx.textAlign = 'left'
ctx.textBaseline = 'alphabetic'
ctx.font = `700 72px ${FONT}`
let x = 80
ctx.fillStyle = c.ink
const heading = `${t('share.myTop')} `
ctx.fillText(heading, x, 150)
x += ctx.measureText(heading).width
ctx.fillStyle = c.accent
ctx.fillText('5', x, 150)
ctx.fillStyle = c.ink3
ctx.font = `600 30px ${FONT}`
ctx.fillText(title.toUpperCase(), 80, 205)
// N°1
const bigW = 460
const bigH = 690
const top = 270
ctx.font = `900 300px ${FONT}`
ctx.lineWidth = 5
ctx.strokeStyle = c.accent
ctx.textBaseline = 'alphabetic'
ctx.strokeText('1', 50, top + 520)
drawPoster(ctx, imgs[0], entries[0]?.title ?? '?', 150, top, bigW - 90, bigH - 135, 24)
ctx.fillStyle = c.ink
ctx.font = `700 34px ${FONT}`
const t1 = wrap(ctx, entries[0]?.title ?? '—', bigW - 90, 2)
t1.forEach((l, i) => ctx.fillText(l, 150, top + bigH - 85 + i * 42))
// N°2 à 5 en grille 2×2
const gx = 590
const cw = 200
const ch = 300
const cells = [
[gx, top],
[gx + cw + 30, top],
[gx, top + ch + 110],
[gx + cw + 30, top + ch + 110],
]
cells.forEach(([cx, cy], k) => {
const idx = k + 1
const e = entries[idx]
drawPoster(ctx, imgs[idx], e?.title ?? '?', cx, cy, cw, ch, 18)
// numéro dans une pastille
ctx.fillStyle = c.bg
ctx.beginPath()
ctx.arc(cx + 34, cy + 34, 26, 0, Math.PI * 2)
ctx.fill()
ctx.fillStyle = c.ink
ctx.font = `800 30px ${FONT}`
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(String(idx + 1), cx + 34, cy + 35)
ctx.textAlign = 'left'
ctx.textBaseline = 'alphabetic'
ctx.fillStyle = c.ink2
ctx.font = `600 24px ${FONT}`
ctx.fillText(wrap(ctx, e?.title ?? '—', cw, 1)[0] ?? '', cx, cy + ch + 38)
})
drawBrand(ctx, H - 60)
return toBlob(canvas)
}
/** Ouvre la feuille de partage (mobile) ou télécharge l'image. */
export async function shareImage(blob: Blob, filename: string, title: string): Promise<'shared' | 'downloaded'> {
const file = new File([blob], filename, { type: 'image/png' })
if (navigator.canShare?.({ files: [file] })) {
try {
await navigator.share({ files: [file], title })
return 'shared'
} catch (e) {
if ((e as DOMException)?.name === 'AbortError') return 'shared'
}
}
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 2000)
return 'downloaded'
}
export const slug = (s: string) =>
s
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 40) || 'azuucine'
+205
View File
@@ -0,0 +1,205 @@
import { locale } from '../i18n'
import type { MediaItem, MediaType, WatchStatus } from '../types'
import { DEFAULT_FILM_MINUTES, MEDIA_TYPES, STATUSES, TYPE_BY_VALUE } from './constants'
/** Temps estimé (minutes) passé sur une fiche. */
export function watchMinutes(item: MediaItem): number {
const epMin = item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes
if (item.type === 'film') return item.status === 'termine' ? (item.duration || DEFAULT_FILM_MINUTES) * (1 + (item.rewatchDates?.length ?? 0)) : 0
if (item.episodesWatched > 0) return item.episodesWatched * epMin
if (item.status === 'termine') return item.episodesTotal ? item.episodesTotal * epMin : item.duration || 0
return 0
}
export interface Count {
label: string
value: number
}
export interface LibraryStats {
total: number
completed: number
inProgress: number
toWatch: number
totalMinutes: number
episodesWatched: number
avgRating?: number
ratedCount: number
byType: (Count & { type: MediaType; completed: number; minutes: number })[]
byStatus: (Count & { status: WatchStatus })[]
topGenres: Count[]
topPlatforms: Count[]
/** Répartition des notes : 10 tranches sur l'échelle /10 (0,5–1, 1,5–2, …). */
ratingBuckets: number[]
completedThisYear: number
}
function top(map: Map<string, number>, n: number): Count[] {
return [...map.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, n)
.map(([label, value]) => ({ label, value }))
}
export function computeStats(items: MediaItem[]): LibraryStats {
const year = String(new Date().getFullYear())
const genres = new Map<string, number>()
const platforms = new Map<string, number>()
const ratingBuckets = new Array(10).fill(0) as number[]
let totalMinutes = 0
let episodesWatched = 0
let ratingSum = 0
let ratedCount = 0
let completedThisYear = 0
const byType = MEDIA_TYPES.map((t) => ({ type: t.value, label: t.label, value: 0, completed: 0, minutes: 0 }))
const typeIndex = Object.fromEntries(byType.map((t, i) => [t.type, i]))
const byStatus = STATUSES.map((s) => ({ status: s.value, label: s.label, value: 0 }))
const statusIndex = Object.fromEntries(byStatus.map((s, i) => [s.status, i]))
for (const item of items) {
const minutes = watchMinutes(item)
totalMinutes += minutes
episodesWatched += item.episodesWatched
const t = byType[typeIndex[item.type]]
t.value++
t.minutes += minutes
if (item.status === 'termine') {
t.completed++
if ((item.endDate ?? item.updatedAt).startsWith(year)) completedThisYear++
}
byStatus[statusIndex[item.status]].value++
if (item.status !== 'a_voir') {
for (const g of item.genres) genres.set(g, (genres.get(g) ?? 0) + 1)
if (item.platform) platforms.set(item.platform, (platforms.get(item.platform) ?? 0) + 1)
}
if (item.rating != null && item.rating > 0) {
ratingSum += item.rating
ratedCount++
ratingBuckets[Math.min(9, Math.ceil(item.rating) - 1)]++
}
}
return {
total: items.length,
completed: byStatus[statusIndex.termine].value,
inProgress: byStatus[statusIndex.en_cours].value,
toWatch: byStatus[statusIndex.a_voir].value,
totalMinutes,
episodesWatched,
avgRating: ratedCount ? ratingSum / ratedCount : undefined,
ratedCount,
byType,
byStatus,
topGenres: top(genres, 8),
topPlatforms: top(platforms, 6),
ratingBuckets,
completedThisYear,
}
}
/** Date à laquelle je rattache un visionnage (fin si terminé, sinon début). */
export function watchDate(item: MediaItem): string | undefined {
if (item.status === 'termine') return item.endDate ?? item.startDate ?? item.updatedAt.slice(0, 10)
if (item.status === 'a_voir') return undefined
return item.startDate ?? item.updatedAt.slice(0, 10)
}
/** Années pour lesquelles j'ai des visionnages, de la plus récente à la plus ancienne. */
export function availableYears(items: MediaItem[]): string[] {
return [...new Set(items.map((i) => watchDate(i)?.slice(0, 4)).filter((y): y is string => !!y))].sort().reverse()
}
/** Garde les fiches rattachées à l'année (ou toutes si year = ''). « À voir » compte toujours. */
export function itemsForPeriod(items: MediaItem[], year: string): MediaItem[] {
if (!year) return items
return items.filter((i) => watchDate(i)?.startsWith(year))
}
export interface MonthBucket {
key: string // AAAA-MM
label: string // « janv. »
initial: string // « J »
count: number
minutes: number
}
/** Titres terminés et temps par mois : les 12 mois de l'année choisie, ou les 12 derniers mois. */
export function monthly(items: MediaItem[], year: string): MonthBucket[] {
const months: string[] = []
if (year) {
for (let m = 1; m <= 12; m++) months.push(`${year}-${String(m).padStart(2, '0')}`)
} else {
const d = new Date()
d.setDate(1)
for (let k = 11; k >= 0; k--) {
const x = new Date(d.getFullYear(), d.getMonth() - k, 1)
months.push(`${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, '0')}`)
}
}
return months.map((key) => {
const date = new Date(`${key}-15T12:00:00`)
const inMonth = items.filter((i) => i.status === 'termine' && watchDate(i)?.startsWith(key))
const label = date.toLocaleDateString(locale(), { month: 'short' })
return {
key,
label,
// Initiale du mois (J, F, M…) ; chiffre du mois pour les langues sans alphabet latin (1月…)
initial: /^\p{Script=Latin}/u.test(label) ? label.charAt(0).toUpperCase() : String(date.getMonth() + 1),
count: inMonth.length,
minutes: inMonth.reduce((s, i) => s + watchMinutes(i), 0),
}
})
}
export interface CountryCount {
code: string
name: string
flag: string
count: number
}
const flagOf = (code: string) =>
/^[A-Z]{2}$/.test(code) ? String.fromCodePoint(...[...code].map((c) => 0x1f1e6 + c.charCodeAt(0) - 65)) : '🏳️'
/** Pays d'origine (premier pays de chaque fiche vue). */
export function countries(items: MediaItem[]): { list: CountryCount[]; missing: number } {
const names = typeof Intl !== 'undefined' && 'DisplayNames' in Intl ? new Intl.DisplayNames([locale()], { type: 'region' }) : null
const map = new Map<string, number>()
let missing = 0
for (const i of items) {
if (i.status === 'a_voir') continue
const c = i.countries?.[0]?.toUpperCase()
if (!c) {
missing++
continue
}
map.set(c, (map.get(c) ?? 0) + 1)
}
const list = [...map.entries()]
.sort((a, b) => b[1] - a[1])
.map(([code, count]) => ({ code, count, flag: flagOf(code), name: names?.of(code) ?? code }))
return { list, missing }
}
export interface Records {
marathon?: { item: MediaItem; episodes: number }
longestFilm?: MediaItem
bestRated?: MediaItem[]
}
export function records(items: MediaItem[]): Records {
const seen = items.filter((i) => i.status !== 'a_voir')
const series = seen.filter((i) => TYPE_BY_VALUE[i.type].episodic && i.episodesWatched > 0)
const marathonItem = series.sort((a, b) => b.episodesWatched - a.episodesWatched)[0]
const films = seen.filter((i) => i.type === 'film' && i.status === 'termine' && i.duration)
return {
marathon: marathonItem ? { item: marathonItem, episodes: marathonItem.episodesWatched } : undefined,
longestFilm: films.sort((a, b) => (b.duration ?? 0) - (a.duration ?? 0))[0],
bestRated: seen
.filter((i) => (i.rating ?? 0) > 0)
.sort((a, b) => (b.rating ?? 0) - (a.rating ?? 0) || (watchDate(b) ?? '').localeCompare(watchDate(a) ?? ''))
.slice(0, 12),
}
}
+85
View File
@@ -0,0 +1,85 @@
import { t } from '../i18n'
/**
* Thèmes de couleur : à partir d'une seule couleur, on calcule
* - accent : version lisible sur fond noir (texte, icônes, filets)
* - accentFill : la couleur choisie, pour les boutons pleins
* - onAccent : texte blanc ou noir sur ces boutons, selon ce qui se lit le mieux
*/
export const DEFAULT_ACCENT = '#d11f2f'
export const THEME_PRESETS: { readonly name: string; color: string; accent?: string }[] = [
{ get name() { return t('theme.red') }, color: '#d11f2f', accent: '#ef4444' },
{ get name() { return t('theme.orange') }, color: '#f97316' },
{ get name() { return t('theme.yellow') }, color: '#facc15' },
{ get name() { return t('theme.lime') }, color: '#a3e635' },
{ get name() { return t('theme.green') }, color: '#22c55e' },
{ get name() { return t('theme.mint') }, color: '#2dd4bf' },
{ get name() { return t('theme.cyan') }, color: '#06b6d4' },
{ get name() { return t('theme.blue') }, color: '#3b82f6' },
{ get name() { return t('theme.indigo') }, color: '#6366f1' },
{ get name() { return t('theme.violet') }, color: '#8b5cf6' },
{ get name() { return t('theme.pink') }, color: '#ec4899' },
{ get name() { return t('theme.white') }, color: '#e7e5e4' },
]
const BG = '#0a0a0a'
export const isHexColor = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v)
function rgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1), 16)
return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
}
function hex([r, g, b]: [number, number, number]): string {
return '#' + [r, g, b].map((v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')).join('')
}
function luminance(color: string): number {
const [r, g, b] = rgb(color).map((v) => {
const c = v / 255
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
})
return 0.2126 * r + 0.7152 * g + 0.0722 * b
}
export function contrast(a: string, b: string): number {
const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m)
return (x + 0.05) / (y + 0.05)
}
/** Éclaircit la couleur vers le blanc jusqu'à être lisible sur le fond noir. */
function readableOnBlack(color: string): string {
let c = color
const base = rgb(color)
for (let t = 0; t <= 1 && contrast(c, BG) < 4.8; t += 0.05) {
c = hex(base.map((v) => v + (255 - v) * t) as [number, number, number])
}
return c
}
export interface ThemeColors {
accent: string
accentFill: string
onAccent: string
}
export function themeFromColor(color: string): ThemeColors {
const fill = isHexColor(color) ? color.toLowerCase() : DEFAULT_ACCENT
const preset = THEME_PRESETS.find((p) => p.color === fill)
return {
accent: preset?.accent ?? readableOnBlack(fill),
accentFill: fill,
onAccent: contrast('#ffffff', fill) >= contrast(BG, fill) ? '#ffffff' : BG,
}
}
/** Applique le thème à toute l'app (les classes Tailwind lisent ces variables). */
export function applyTheme(color: string) {
const t = themeFromColor(color)
const root = document.documentElement.style
root.setProperty('--color-accent', t.accent)
root.setProperty('--color-accent-fill', t.accentFill)
root.setProperty('--color-on-accent', t.onAccent)
}
+11
View File
@@ -0,0 +1,11 @@
import { locale, t } from '../i18n'
/** « à l'instant », « il y a 5 min », « il y a 3 h », « il y a 2 j », puis la date. */
export function timeAgo(iso: string): string {
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000)
if (s < 60) return t('time.justNow')
if (s < 3600) return t('time.minutesAgo', { n: Math.floor(s / 60) })
if (s < 86400) return t('time.hoursAgo', { n: Math.floor(s / 3600) })
if (s < 7 * 86400) return t('time.daysAgo', { n: Math.floor(s / 86400) })
return new Date(iso).toLocaleDateString(locale(), { day: 'numeric', month: 'short' })
}
+52
View File
@@ -0,0 +1,52 @@
import { locale, t } from '../i18n'
import type { RatingScale } from '../types'
export function uid(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
try {
return crypto.randomUUID()
} catch {
/* contexte non sécurisé (http sur réseau local) */
}
}
return Date.now().toString(36) + Math.random().toString(36).slice(2, 10)
}
export function todayISO(): string {
const d = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}
export function cx(...classes: (string | false | null | undefined)[]): string {
return classes.filter(Boolean).join(' ')
}
/** Note interne (sur 10) → texte affiché selon l'échelle choisie. */
export function formatRating(value: number | undefined, scale: RatingScale): string {
if (value == null) return '—'
const v = scale === '5' ? value / 2 : value
return (Number.isInteger(v) ? String(v) : v.toFixed(1)).replace('.', t('common.decimalSep'))
}
export function formatDuration(minutes: number): string {
const total = Math.round(minutes)
if (total < 60) return t('common.minutes', { n: total })
const days = Math.floor(total / 1440)
const hours = Math.floor((total % 1440) / 60)
const mins = total % 60
if (days > 0) return t('common.daysHours', { d: days, h: hours })
return mins ? t('common.hoursMinutes', { h: hours, m: mins }) : t('common.hours', { h: hours })
}
export function formatDate(iso?: string): string {
if (!iso) return ''
const d = new Date(iso.length === 10 ? iso + 'T12:00:00' : iso)
if (Number.isNaN(d.getTime())) return iso
return d.toLocaleDateString(locale(), { day: 'numeric', month: 'short', year: 'numeric' })
}
/** Recherche insensible à la casse et aux accents. */
export function normalizeText(s: string): string {
return s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
}
+32
View File
@@ -0,0 +1,32 @@
import { enableDesktopCarousels } from './lib/dragScroll'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { registerSW } from 'virtual:pwa-register'
import { initialLang, loadLang } from './i18n'
import { LangProvider } from './i18n/react'
import Root from './Root'
// Polices embarquées dans l'app (jeu « latin », suffisant pour le français) : aucun appel à Google Fonts, fonctionne hors-ligne
import '@fontsource/inter/latin-400.css'
import '@fontsource/inter/latin-500.css'
import '@fontsource/inter/latin-600.css'
import '@fontsource/inter/latin-700.css'
import './index.css'
// Service worker : cache l'app pour un fonctionnement hors-ligne et la met à jour automatiquement.
registerSW({ immediate: true })
// Carrousels : molette et glisser à la souris sur ordinateur
enableDesktopCarousels()
// La langue est chargée avant le premier affichage (le français est inclus, les autres arrivent en un instant)
loadLang(initialLang())
.catch(() => loadLang('fr'))
.finally(() => {
createRoot(document.getElementById('root')!).render(
<StrictMode>
<LangProvider>
<Root />
</LangProvider>
</StrictMode>,
)
})
+238
View File
@@ -0,0 +1,238 @@
import { genreLabel, subtypeLabel } from '../lib/genres'
import { locale, t } from '../i18n'
import { Heart, Search, SlidersHorizontal, X } from 'lucide-react'
import { useMemo, useState } from 'react'
import { StatusDot } from '../components/Badges'
import JournalView from '../components/JournalView'
import ListsView from '../components/ListsView'
import { MediaCard } from '../components/MediaCard'
import { EmptyState, PageHeader } from '../components/ui'
import { MEDIA_TYPES, STATUSES } from '../lib/constants'
import { cx, normalizeText } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem, MediaType, WatchStatus } from '../types'
type SortKey = 'recent' | 'rating' | 'title' | 'watched'
const SORTS: { value: SortKey; readonly label: string }[] = [
{ value: 'recent', get label() { return t('catalog.sortRecent') } },
{ value: 'watched', get label() { return t('catalog.sortWatched') } },
{ value: 'rating', get label() { return t('catalog.sortRating') } },
{ value: 'title', get label() { return t('catalog.sortTitle') } },
]
interface Props {
onOpen: (item: MediaItem) => void
onAdd: () => void
}
export default function CatalogPage({ onOpen, onAdd }: Props) {
const { items, settings, lists } = useMedia()
const [view, setView] = useState<'titles' | 'journal' | 'lists'>('titles')
const [query, setQuery] = useState('')
const [types, setTypes] = useState<Set<MediaType>>(new Set())
const [status, setStatus] = useState<WatchStatus | ''>('')
const [genre, setGenre] = useState('')
const [minRating, setMinRating] = useState(0)
const [favOnly, setFavOnly] = useState(false)
const [sort, setSort] = useState<SortKey>('recent')
const [showFilters, setShowFilters] = useState(false)
const allGenres = useMemo(
() => [...new Set(items.flatMap((i) => i.genres))].sort((a, b) => a.localeCompare(b, locale())),
[items],
)
const toggleType = (t: MediaType) =>
setTypes((prev) => {
const next = new Set(prev)
if (next.has(t)) next.delete(t)
else next.add(t)
return next
})
const results = useMemo(() => {
const q = normalizeText(query)
const filtered = items.filter((i) => {
if (types.size && !types.has(i.type)) return false
if (status && i.status !== status) return false
if (genre && !i.genres.includes(genre)) return false
if (minRating && (i.rating ?? 0) < minRating) return false
if (favOnly && !i.favorite) return false
if (q) {
const haystack = normalizeText([i.title, i.originalTitle, i.subtype, i.subtype && subtypeLabel(i.subtype), i.platform, ...i.genres, ...i.genres.map(genreLabel)].filter(Boolean).join(' '))
if (!haystack.includes(q)) return false
}
return true
})
const sorted = [...filtered]
if (sort === 'rating') sorted.sort((a, b) => (b.rating ?? -1) - (a.rating ?? -1))
else if (sort === 'title') sorted.sort((a, b) => a.title.localeCompare(b.title, locale()))
else if (sort === 'watched')
sorted.sort((a, b) => (b.endDate ?? b.startDate ?? '').localeCompare(a.endDate ?? a.startDate ?? ''))
return sorted
}, [items, query, types, status, genre, minRating, favOnly, sort])
const activeAdvanced = (genre ? 1 : 0) + (minRating ? 1 : 0) + (favOnly ? 1 : 0)
const anyFilter = query || types.size || status || activeAdvanced
const resetAll = () => {
setQuery('')
setTypes(new Set())
setStatus('')
setGenre('')
setMinRating(0)
setFavOnly(false)
}
// Options de note minimale selon l'échelle affichée (valeurs internes sur 10)
const ratingOptions = settings.ratingScale === '5' ? [2, 4, 6, 8, 9, 10] : [5, 6, 7, 8, 9, 10]
return (
<>
<PageHeader
title={t('catalog.pageTitle')}
accent={t('catalog.pageAccent')}
subtitle={
view === 'journal'
? t('catalog.journalSubtitle')
: view === 'lists'
? t('account.nLists', { count: lists.length })
: anyFilter
? t('catalog.filteredCount', { count: results.length })
: t('account.nTitles', { count: results.length })
}
/>
<div className="mb-3 grid grid-cols-3 gap-1 rounded-full border border-line p-1">
{(['titles', 'journal', 'lists'] as const).map((v) => (
<button
key={v}
onClick={() => setView(v)}
className={cx('rounded-full py-2 text-sm font-medium transition-colors', view === v ? 'bg-ink text-bg' : 'text-ink-3')}
>
{v === 'titles' ? t('catalog.titles') : v === 'journal' ? t('catalog.journal') : t('catalog.lists')}
</button>
))}
</div>
{view === 'journal' ? (
<JournalView onOpen={onOpen} />
) : view === 'lists' ? (
<ListsView onOpen={onOpen} />
) : (
<>
{/* Recherche + filtres (collants en haut) */}
<div className="sticky top-0 z-20 -mx-4 space-y-3 bg-bg/90 px-4 pb-3 pt-[max(0.5rem,env(safe-area-inset-top))] backdrop-blur-xl">
<div className="flex gap-2">
<div className="relative flex-1">
<Search size={18} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('catalog.searchPh')}
className="field pl-10"
enterKeyHint="search"
/>
</div>
<button
onClick={() => setShowFilters((v) => !v)}
className={cx('relative grid w-12 place-items-center rounded-xl border border-line bg-surface transition-colors', showFilters && 'border-ink text-ink')}
aria-label={t('catalog.moreFilters')}
aria-expanded={showFilters}
>
<SlidersHorizontal size={18} />
{activeAdvanced > 0 && (
<span className="absolute -right-1.5 -top-1.5 grid size-5 place-items-center rounded-full bg-accent-fill text-[10px] text-on-accent">{activeAdvanced}</span>
)}
</button>
</div>
<div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4">
<button onClick={() => setTypes(new Set())} className={cx('chip', types.size === 0 && 'chip-on')}>
{t('catalog.all')}
</button>
{MEDIA_TYPES.map((mt) => (
<button key={mt.value} onClick={() => toggleType(mt.value)} className={cx('chip', types.has(mt.value) && 'chip-on')}>
{mt.label}
</button>
))}
</div>
<div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4">
{STATUSES.map((s) => (
<button key={s.value} onClick={() => setStatus(status === s.value ? '' : s.value)} className={cx('chip text-xs', status === s.value && 'chip-on')}>
<StatusDot status={s.value} />
{s.label}
</button>
))}
</div>
{showFilters && (
<div className="card grid grid-cols-2 gap-3 p-3">
<label className="block">
<span className="label">{t('catalog.genre')}</span>
<select className="field" value={genre} onChange={(e) => setGenre(e.target.value)}>
<option value="">{t('catalog.all')}</option>
{allGenres.map((g) => (
<option key={g} value={g}>
{genreLabel(g)}
</option>
))}
</select>
</label>
<label className="block">
<span className="label">{t('catalog.minRating')}</span>
<select className="field" value={minRating} onChange={(e) => setMinRating(Number(e.target.value))}>
<option value={0}>{t('catalog.allRatings')}</option>
{ratingOptions.map((r) => (
<option key={r} value={r}>
≥ {settings.ratingScale === '5' ? r / 2 : r}/{settings.ratingScale}
</option>
))}
</select>
</label>
<label className="col-span-2 block">
<span className="label">{t('catalog.sortBy')}</span>
<select className="field" value={sort} onChange={(e) => setSort(e.target.value as SortKey)}>
{SORTS.map((s) => (
<option key={s.value} value={s.value}>
{s.label}
</option>
))}
</select>
</label>
<button onClick={() => setFavOnly((v) => !v)} className={cx('chip justify-center', favOnly && 'chip-on')}>
<Heart size={14} className={favOnly ? 'fill-accent-fill text-accent-fill' : ''} /> {t('catalog.favorites')}
</button>
<button onClick={resetAll} className="chip justify-center">
<X size={14} /> {t('catalog.reset')}
</button>
</div>
)}
</div>
{results.length === 0 ? (
<EmptyState
title={items.length ? t('catalog.noResults') : t('catalog.nothingYet')}
text={items.length ? t('catalog.noResultsHint') : t('catalog.nothingYetHint')}
action={
items.length ? (
<button onClick={resetAll} className="btn btn-ghost">{t('catalog.clearFilters')}</button>
) : (
<button onClick={onAdd} className="btn btn-primary">{t('nav.addTitle')}</button>
)
}
/>
) : (
<div className="mt-3 grid grid-cols-2 gap-x-3.5 gap-y-6 sm:grid-cols-3">
{results.map((item) => (
<MediaCard key={item.id} item={item} onOpen={onOpen} />
))}
</div>
)}
</>
)}
</>
)
}
+189
View File
@@ -0,0 +1,189 @@
import { useSocial } from '../components/social/SocialProvider'
import { t } from '../i18n'
import { CalendarDays, Dices, Plus } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { MediaRow } from '../components/MediaCard'
import Avatar from '../components/social/Avatar'
import FriendsFeed from '../components/social/FriendsFeed'
import Poster from '../components/Poster'
import TopFive from '../components/TopFive'
import Recommendations from '../components/Recommendations'
import type { Tab } from '../components/BottomNav'
import { EmptyState, LinkArrow, PageHeader, SectionTitle, StatTile } from '../components/ui'
import { CACHE_EVENT, loadAiring, needsCheck, refreshAiring, saveAiring, trackable } from '../lib/airing'
import { calendarEvents } from '../lib/releases'
import { computeStats } from '../lib/stats'
import { formatDuration, todayISO } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem } from '../types'
interface Props {
onOpen: (item: MediaItem) => void
onAdd: () => void
onNavigate: (tab: Tab) => void
onRoulette: () => void
onCalendar: () => void
}
function PosterStrip({ items, onOpen }: { items: MediaItem[]; onOpen: (item: MediaItem) => void }) {
return (
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{items.map((item) => (
<button key={item.id} onClick={() => onOpen(item)} className="w-24 shrink-0 text-left">
<Poster src={item.poster} title={item.title} />
<p className="mt-2 line-clamp-2 text-xs font-medium leading-snug text-ink-2">{item.title}</p>
</button>
))}
</div>
)
}
export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCalendar }: Props) {
const { items, loading, account, settings, patchMany } = useMedia()
const social = useSocial()
const stats = useMemo(() => computeStats(items), [items])
// Sorties dans les 7 prochains jours (pastille sur l'icône calendrier)
// Vérification discrète des nouveaux épisodes (au plus toutes les 12 h) : pastille du calendrier et nombre d'épisodes à jour
const airingStarted = useRef(false)
useEffect(() => {
if (loading || airingStarted.current || !navigator.onLine) return
airingStarted.current = true
const cache = loadAiring()
if (!trackable(items).some((i) => needsCheck(i, cache))) return
void refreshAiring(items, cache, settings.tmdbKey)
.then((next) => {
saveAiring(next)
const patches = trackable(items)
.filter((i) => i.status !== 'termine' && next[i.id] && next[i.id].aired > (i.episodesTotal ?? 0))
.map((i) => ({ id: i.id, patch: { episodesTotal: next[i.id].aired } }))
if (patches.length) return patchMany(patches)
})
.catch(() => {})
}, [loading, items, settings.tmdbKey, patchMany])
const [cacheVersion, setCacheVersion] = useState(0)
useEffect(() => {
const bump = () => setCacheVersion((v) => v + 1)
window.addEventListener(CACHE_EVENT, bump)
return () => window.removeEventListener(CACHE_EVENT, bump)
}, [])
const soon = useMemo(() => {
const today = todayISO()
const d = new Date(Date.now() + 7 * 86400000)
const end = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
return calendarEvents(items).filter((e) => e.date >= today && e.date <= end).length
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, cacheVersion])
const inProgress = items.filter((i) => i.status === 'en_cours')
const toWatch = items.filter((i) => i.status === 'a_voir').slice(0, 12)
const recent = items
.filter((i) => i.status === 'termine')
.sort((a, b) => (b.endDate ?? b.updatedAt).localeCompare(a.endDate ?? a.updatedAt))
.slice(0, 12)
const seeAll = <LinkArrow onClick={() => onNavigate('catalog')}>{t('home.seeAll')}</LinkArrow>
return (
<>
<PageHeader
title="Azuu"
accent="Cine"
subtitle={t('home.subtitle')}
action={
<span className="flex shrink-0 items-center gap-2">
<button
onClick={onCalendar}
className="relative grid size-11 shrink-0 place-items-center rounded-full border border-line text-ink-2 transition-colors active:bg-surface-2"
aria-label={soon ? t('home.calendarSoon', { count: soon }) : t('calendar.title')}
>
<CalendarDays size={20} />
{soon > 0 && (
<span className="absolute -right-1 -top-1 grid min-w-5 place-items-center rounded-full bg-accent-fill px-1 text-[10px] font-bold text-on-accent">{soon}</span>
)}
</button>
{social.enabled && (
<button onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())} className="relative shrink-0 rounded-full" aria-label={t('social.myProfile')}>
<Avatar url={social.me?.avatarUrl} name={social.me?.displayName ?? '?'} size={44} />
{social.requests.length > 0 && (
<span className="absolute -right-1 -top-1 grid min-w-5 place-items-center rounded-full bg-accent-fill px-1 text-[10px] font-bold text-on-accent">{social.requests.length}</span>
)}
</button>
)}
</span>
}
/>
{!loading && items.length === 0 ? (
<>
<EmptyState
title={t('home.emptyTitle')}
text={account ? t('home.emptyCloud') : t('home.emptyLocal')}
action={
<button onClick={onAdd} className="btn btn-primary">
<Plus size={18} /> {t('nav.addTitle')}
</button>
}
/>
<FriendsFeed />
</>
) : (
<>
<div className="grid grid-cols-2 gap-3">
<StatTile label={t('home.completed')} value={stats.completed} hint={t('home.thisYear', { count: stats.completedThisYear })} />
<StatTile label={t('status.en_cours')} value={stats.inProgress} hint={t('home.toWatchN', { count: stats.toWatch })} />
<StatTile label={t('home.screenTime')} value={formatDuration(stats.totalMinutes)} hint={t('home.estimate')} />
<StatTile label={t('home.episodesSeen')} value={stats.episodesWatched} />
</div>
{/* Roulette : pour les soirs sans idée */}
<button onClick={onRoulette} className="card mt-3 flex w-full items-center gap-4 p-4 text-left transition-colors active:bg-surface-2">
<span className="grid size-12 shrink-0 place-items-center rounded-full bg-accent-fill text-on-accent">
<Dices size={24} />
</span>
<span className="min-w-0 flex-1">
<span className="block font-semibold">
{t('home.noIdea')} <span className="text-accent">{t('roulette.name')}</span>
</span>
<span className="mt-0.5 block text-xs text-ink-3">
{stats.toWatch ? t('home.rouletteHint', { count: stats.toWatch }) : t('home.rouletteHintAll')}
</span>
</span>
<span className="text-accent">→</span>
</button>
<FriendsFeed />
{inProgress.length > 0 && (
<>
<SectionTitle>{t('status.en_cours')}</SectionTitle>
<div className="space-y-2.5">
{inProgress.map((item) => (
<MediaRow key={item.id} item={item} onOpen={onOpen} />
))}
</div>
</>
)}
<TopFive onOpen={onOpen} />
<Recommendations />
{toWatch.length > 0 && (
<>
<SectionTitle action={seeAll}>{t('status.a_voir')}</SectionTitle>
<PosterStrip items={toWatch} onOpen={onOpen} />
</>
)}
{recent.length > 0 && (
<>
<SectionTitle action={seeAll}>{t('home.recentlyFinished')}</SectionTitle>
<PosterStrip items={recent} onOpen={onOpen} />
</>
)}
</>
)}
</>
)
}
+403
View File
@@ -0,0 +1,403 @@
import { t } from '../i18n'
import { LanguageSelect } from '../i18n/react'
import { Check, Download, Eye, EyeOff, HardDrive, Trash2, Upload, UserX } from 'lucide-react'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import AccountSection from '../components/AccountSection'
import ConfirmDialog from '../components/ConfirmDialog'
import { PageHeader, SectionTitle } from '../components/ui'
import { exportBackup, parseBackupFile, type ParsedBackup } from '../lib/backup'
import { testTmdbKey } from '../lib/catalogApi'
import { checkTmdbProxy, type ProxyState } from '../lib/cloud/api'
import { ALL_TOP_CATEGORIES, TOP_CATEGORIES } from '../lib/constants'
import { isHexColor, THEME_PRESETS } from '../lib/theme'
import { cx } from '../lib/utils'
import { useMedia } from '../store'
type Message = { kind: 'ok' | 'error'; text: string }
function Row({ icon, title, hint, onClick, danger }: { icon: ReactNode; title: string; hint?: string; onClick: () => void; danger?: boolean }) {
return (
<button onClick={onClick} className={cx('flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2', danger && 'text-accent')}>
<span className={danger ? 'text-accent' : 'text-ink-2'}>{icon}</span>
<span className="flex-1">
<span className="block font-medium">{title}</span>
{hint && <span className="mt-0.5 block text-xs text-ink-3">{hint}</span>}
</span>
<span className={danger ? 'text-accent' : 'text-ink-3'}>→</span>
</button>
)
}
export default function SettingsPage() {
const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account } = useMedia()
const fileRef = useRef<HTMLInputElement>(null)
const [pending, setPending] = useState<ParsedBackup>()
const [message, setMessage] = useState<Message>()
const [confirm, setConfirm] = useState<null | 'reset' | 'replace' | 'delete-account'>(null)
const [deleting, setDeleting] = useState(false)
const [usage, setUsage] = useState<string>()
const [keyDraft, setKeyDraft] = useState(settings.tmdbKey ?? '')
const [showKey, setShowKey] = useState(false)
const [keyState, setKeyState] = useState<'idle' | 'testing' | 'ok' | 'bad'>(settings.tmdbKey ? 'ok' : 'idle')
useEffect(() => {
navigator.storage
?.estimate?.()
.then(({ usage: u }) => u != null && setUsage(u < 1e6 ? t('common.kb', { n: Math.max(1, Math.round(u / 1e3)) }) : t('common.mb', { n: (u / 1e6).toFixed(1).replace('.', t('common.decimalSep')) })))
.catch(() => {})
}, [items.length])
// Avec un compte : vérifie que le proxy TMDB fonctionne vraiment
const [proxy, setProxy] = useState<ProxyState | 'checking'>('checking')
const runProxyCheck = async () => {
setProxy('checking')
setProxy(await checkTmdbProxy())
}
useEffect(() => {
if (account) void runProxyCheck()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [!!account])
const saveKey = async () => {
const key = keyDraft.trim()
if (!key) {
updateSettings({ tmdbKey: undefined })
setKeyState('idle')
return
}
setKeyState('testing')
const ok = await testTmdbKey(key)
setKeyState(ok ? 'ok' : 'bad')
if (ok) updateSettings({ tmdbKey: key })
}
const onExport = async () => {
try {
const how = await exportBackup(items, settings, lists)
setMessage({ kind: 'ok', text: how === 'shared' ? t('settings.backupShared') : t('settings.backupDownloaded') })
} catch (e) {
if ((e as DOMException)?.name !== 'AbortError') setMessage({ kind: 'error', text: t('settings.exportFailed') })
}
}
const onFile = async (file?: File) => {
if (fileRef.current) fileRef.current.value = ''
if (!file) return
try {
const parsed = await parseBackupFile(file)
if (!parsed.items.length) throw new Error(t('settings.noValidItems'))
setPending(parsed)
setMessage(undefined)
} catch (e) {
setMessage({ kind: 'error', text: (e as Error).message })
}
}
// Le message s'affiche en bas de l'écran puis disparaît (visible même en bas de page)
useEffect(() => {
if (!message) return
const timer = setTimeout(() => setMessage(undefined), 3500)
return () => clearTimeout(timer)
}, [message])
const confirmImport = async (mode: 'merge' | 'replace') => {
if (!pending) return
setConfirm(null)
await importItems(pending.items, mode)
if (pending.settings) updateSettings(pending.settings)
if (pending.lists) mergeLists(pending.lists, mode)
setMessage({
kind: 'ok',
text: pending.skipped ? t('settings.importedSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.imported', { count: pending.items.length }),
})
setPending(undefined)
}
const onDeleteAccount = async () => {
if (!account) return
setConfirm(null)
setDeleting(true)
try {
await account.deleteAccount()
} catch (e) {
setMessage({ kind: 'error', text: (e as Error).message })
setDeleting(false)
}
}
const onReset = async () => {
setConfirm(null)
await clearAll()
setMessage({ kind: 'ok', text: t('settings.cleared') })
}
return (
<>
<PageHeader title={t('settings.pageTitle')} accent={t('settings.pageAccent')} />
{message && (
<p
role="status"
className={cx(
'sheet-in fixed inset-x-4 bottom-24 z-40 mx-auto max-w-md rounded-2xl border bg-surface-2 p-3.5 text-sm text-ink',
message.kind === 'ok' ? 'border-line-strong' : 'border-accent',
)}
>
{message.text}
</p>
)}
{account && <AccountSection account={account} onMessage={(kind, text) => setMessage({ kind, text })} />}
<SectionTitle>{t('settings.language')}</SectionTitle>
<LanguageSelect />
<p className="mt-2.5 text-xs text-ink-3">{t('settings.languageHint')}</p>
<SectionTitle>{t('settings.rating')}</SectionTitle>
<div className="grid grid-cols-2 gap-1 rounded-full border border-line p-1">
{(['5', '10'] as const).map((scale) => (
<button
key={scale}
onClick={() => updateSettings({ ratingScale: scale })}
className={cx('rounded-full py-2.5 text-sm font-medium transition-colors', settings.ratingScale === scale ? 'bg-ink text-bg' : 'text-ink-3')}
>
{scale === '5' ? t('settings.scale5') : t('settings.scale10')}
</button>
))}
</div>
<p className="mt-2.5 text-xs text-ink-3">{t('settings.ratingHint')}</p>
<SectionTitle>{t('settings.theme')}</SectionTitle>
<div className="grid grid-cols-6 gap-3">
{THEME_PRESETS.map((p) => {
const on = settings.accentColor.toLowerCase() === p.color
return (
<button
key={p.color}
onClick={() => updateSettings({ accentColor: p.color })}
className="flex flex-col items-center gap-1.5"
aria-pressed={on}
aria-label={t('settings.themeX', { name: p.name })}
>
<span
className={cx('grid size-10 place-items-center rounded-full transition', on ? 'ring-2 ring-ink ring-offset-2 ring-offset-bg' : '')}
style={{ background: p.color }}
>
{on && <Check size={17} strokeWidth={3} className="text-on-accent" />}
</span>
<span className={cx('text-[11px]', on ? 'text-ink' : 'text-ink-3')}>{p.name}</span>
</button>
)
})}
</div>
<label className="mt-4 flex items-center gap-3 rounded-2xl border border-line px-4 py-3">
<span className="relative size-8 shrink-0 overflow-hidden rounded-full border border-line-strong" style={{ background: settings.accentColor }}>
<input
type="color"
value={settings.accentColor}
onChange={(e) => isHexColor(e.target.value) && updateSettings({ accentColor: e.target.value })}
className="absolute inset-0 size-full cursor-pointer opacity-0"
aria-label={t('settings.pickColor')}
/>
</span>
<span className="flex-1 text-sm">
{t('settings.freeColor')}
<span className="block text-xs text-ink-3">{t('settings.freeColorHint')}</span>
</span>
<span className="text-xs uppercase text-ink-3">{settings.accentColor}</span>
</label>
<SectionTitle>{t('settings.databases')}</SectionTitle>
<div className="card space-y-4 p-4">
<div>
<div className="flex items-center justify-between">
<span className="font-medium">AniList</span>
<span className="eyebrow">{t('settings.anilistActive')}</span>
</div>
<p className="mt-1 text-xs text-ink-3">{t('settings.noConfig')}</p>
</div>
{account ? (
<div className="border-t border-line pt-4">
<div className="flex items-center justify-between">
<span className="font-medium">TMDB</span>
<span className={cx('eyebrow', proxy === 'ok' && 'text-ink', (proxy === 'missing-key' || proxy === 'not-deployed' || proxy === 'error') && 'text-accent')}>
{proxy === 'ok'
? t('settings.tmdbActive')
: proxy === 'checking'
? t('settings.checking')
: proxy === 'offline'
? t('settings.offline')
: proxy === 'missing-key'
? t('settings.proxyMissingKey')
: proxy === 'not-deployed'
? t('settings.proxyNotDeployed')
: t('settings.unavailable')}
</span>
</div>
<p className="mt-1 text-xs text-ink-3">
{proxy === 'missing-key'
? t('settings.proxyMissingKeyHint')
: proxy === 'not-deployed'
? t('settings.proxyNotDeployedHint')
: proxy === 'error'
? t('settings.proxyErrorHint')
: t('settings.proxyOkHint')}
</p>
{proxy !== 'ok' && proxy !== 'checking' && (
<button onClick={() => void runProxyCheck()} className="mt-2 text-xs font-medium text-ink-3">
{t('settings.recheck')} <span className="text-accent">→</span>
</button>
)}
</div>
) : (
<div className="border-t border-line pt-4">
<div className="flex items-center justify-between">
<span className="font-medium">TMDB</span>
<span className={cx('eyebrow', keyState === 'ok' && 'text-ink', keyState === 'bad' && 'text-accent')}>
{keyState === 'ok' ? t('settings.tmdbActive') : keyState === 'bad' ? t('settings.keyRefused') : keyState === 'testing' ? t('settings.checking') : t('settings.notConfigured')}
</span>
</div>
<p className="mt-1 text-xs leading-relaxed text-ink-3">
{t('settings.tmdbHelp')}
</p>
<div className="mt-3 flex gap-2">
<div className="relative flex-1">
<input
className="field pr-11 text-sm"
type={showKey ? 'text' : 'password'}
value={keyDraft}
onChange={(e) => {
setKeyDraft(e.target.value)
setKeyState('idle')
}}
placeholder={t('settings.tmdbKey')}
autoComplete="off"
autoCapitalize="off"
spellCheck={false}
/>
<button type="button" onClick={() => setShowKey((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={showKey ? t('settings.hideKey') : t('settings.showKey')}>
{showKey ? <EyeOff size={17} /> : <Eye size={17} />}
</button>
</div>
<button onClick={saveKey} disabled={keyState === 'testing'} className="btn btn-light px-4 text-sm">
{keyDraft.trim() ? t('settings.validate') : t('settings.remove')}
</button>
</div>
<p className="mt-2 text-[11px] text-ink-3">{t('settings.keyLocal')}</p>
</div>
)}
</div>
<SectionTitle>Top 5</SectionTitle>
<p className="mb-3 text-xs text-ink-3">{t('settings.topHint')}</p>
<div className="flex flex-wrap gap-2">
{TOP_CATEGORIES.map((c) => {
const on = settings.topCategories.includes(c.value)
return (
<button
key={c.value}
onClick={() =>
updateSettings({
topCategories: on
? settings.topCategories.filter((v) => v !== c.value)
: ALL_TOP_CATEGORIES.filter((v) => v === c.value || settings.topCategories.includes(v)),
})
}
className={cx('chip', on && 'chip-on')}
aria-pressed={on}
>
{on && <Check size={14} />}
{c.plural}
</button>
)
})}
</div>
{settings.topCategories.length === 0 && <p className="mt-2 text-xs text-ink-3">{t('settings.topNone')}</p>}
<SectionTitle>{t('settings.backup')}</SectionTitle>
<div className="card divide-y divide-line overflow-hidden">
<Row icon={<Download size={19} />} title={t('settings.export')} hint={t('settings.exportHint', { count: items.length })} onClick={onExport} />
<Row icon={<Upload size={19} />} title={t('settings.import')} hint={t('settings.importHint')} onClick={() => fileRef.current?.click()} />
<input ref={fileRef} type="file" accept="application/json,.json" hidden onChange={(e) => onFile(e.target.files?.[0])} />
</div>
{pending && (
<div className="card mt-3 space-y-3 border-ink p-4">
<p className="text-sm">
{pending.format === 'legacy' && <span className="eyebrow mb-2 block text-ink">{t('settings.legacyDetected')}</span>}
{pending.skipped ? t('settings.foundSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.found', { count: pending.items.length })}
</p>
<div className="grid grid-cols-2 gap-2">
<button onClick={() => confirmImport('merge')} className="btn btn-light text-sm">
{t('settings.merge')}
</button>
<button onClick={() => setConfirm('replace')} className="btn btn-ghost text-sm">
{t('settings.replaceAll')}
</button>
</div>
<p className="text-xs text-ink-3">{t('settings.mergeHint')}</p>
<button onClick={() => setPending(undefined)} className="w-full text-xs text-ink-3">
{t('common.cancel')}
</button>
</div>
)}
<SectionTitle>{t('settings.storage')}</SectionTitle>
<div className="card space-y-3.5 p-4 text-sm">
<div className="flex items-center gap-3">
<HardDrive size={18} className="text-ink-3" />
<span className="flex-1 text-ink-2">{t('settings.used')}</span>
<span className="text-xs">{usage ?? '—'}</span>
</div>
<p className="border-t border-line pt-3.5 text-xs leading-relaxed text-ink-3">
{account
? t('settings.storageCloud')
: t('settings.storageLocal')}
</p>
</div>
<SectionTitle>{t('settings.danger')}</SectionTitle>
<div className="card overflow-hidden">
<Row icon={<Trash2 size={19} />} title={t('settings.clearAll')} hint={account ? t('settings.clearAllHintCloud', { count: items.length }) : t('settings.clearAllHint', { count: items.length })} onClick={() => setConfirm('reset')} danger />
{account && (
<div className="border-t border-line">
<Row
icon={<UserX size={19} />}
title={deleting ? t('settings.deleting') : t('settings.deleteAccount')}
hint={t('settings.deleteAccountHint')}
onClick={() => !deleting && setConfirm('delete-account')}
danger
/>
</div>
)}
</div>
<p className="mt-10 text-center text-xs text-ink-3">AzuuCine v2.2 · {account ? t('settings.footerCloud') : t('settings.footerLocal')}</p>
<ConfirmDialog
open={confirm === 'reset'}
title={t('confirm.title')}
message={account ? t('settings.clearConfirmCloud', { count: items.length }) : t('settings.clearConfirm', { count: items.length })}
confirmLabel={t('settings.clearAllConfirm')}
onConfirm={onReset}
onCancel={() => setConfirm(null)}
/>
<ConfirmDialog
open={confirm === 'delete-account'}
title={t('settings.deleteAccountTitle')}
message={t('settings.deleteAccountMessage')}
confirmLabel={t('settings.deleteForever')}
onConfirm={onDeleteAccount}
onCancel={() => setConfirm(null)}
/>
<ConfirmDialog
open={confirm === 'replace'}
title={t('confirm.title')}
message={t('settings.replaceConfirm')}
confirmLabel={t('settings.replace')}
onConfirm={() => confirmImport('replace')}
onCancel={() => setConfirm(null)}
/>
</>
)
}
+429
View File
@@ -0,0 +1,429 @@
import { genreLabel } from '../lib/genres'
import { locale, t } from '../i18n'
import { Star } from 'lucide-react'
import { useMemo, useState, type ReactNode } from 'react'
import Disagreements from '../components/Disagreements'
import Poster from '../components/Poster'
import { EmptyState, PageHeader, SectionTitle } from '../components/ui'
import { MEDIA_TYPES, STATUSES } from '../lib/constants'
import { availableYears, computeStats, countries, itemsForPeriod, monthly, records, watchMinutes } from '../lib/stats'
import { cx, formatDuration, formatRating } from '../lib/utils'
import { useMedia } from '../store'
import type { MediaItem, MediaType } from '../types'
/** Couleurs des types (palette catégorielle validée pour fond sombre, ordre fixe). */
const TYPE_COLORS: Record<MediaType, string> = {
film: '#3987e5',
serie: '#d95926',
anime: '#199e70',
kdrama: '#c98500',
cdrama: '#d55181',
autre: '#008300',
}
type Tab = 'overview' | 'habits' | 'tastes'
const TABS: { value: Tab; readonly label: string }[] = [
{ value: 'overview', get label() { return t('stats.overview') } },
{ value: 'habits', get label() { return t('stats.habits') } },
{ value: 'tastes', get label() { return t('stats.tastes') } },
]
const fmtInt = (n: number) => n.toLocaleString(locale())
/** Colonnes verticales d'une seule couleur ; toucher une colonne affiche sa valeur. */
function Columns({
data,
format,
height = 140,
selected,
onSelect,
}: {
data: { key: string; label: string; value: number }[]
format: (v: number) => string
height?: number
selected?: string
onSelect: (key: string) => void
}) {
const max = Math.max(1, ...data.map((d) => d.value))
return (
<div>
<div className="flex items-end gap-1.5" style={{ height }}>
{data.map((d) => {
const on = d.key === selected
return (
<button
key={d.key}
onClick={() => onSelect(d.key)}
className="group relative flex h-full flex-1 items-end"
aria-label={`${d.label} : ${format(d.value)}`}
title={`${d.label} : ${format(d.value)}`}
>
<span
className={cx('w-full rounded-t-[4px] transition-colors', on ? 'bg-accent' : 'bg-accent/45')}
style={{ height: `${(d.value / max) * 100}%`, minHeight: d.value ? 3 : 0 }}
/>
</button>
)
})}
</div>
<div className="mt-2 flex gap-1.5 border-t border-line pt-1.5">
{data.map((d) => (
<span key={d.key} className={cx('flex-1 text-center text-[10px]', d.key === selected ? 'font-semibold text-ink' : 'text-ink-3')}>
{d.label}
</span>
))}
</div>
</div>
)
}
function Tile({ label, value, hint }: { label: string; value: ReactNode; hint?: string }) {
return (
<div className="card p-4">
<div className="eyebrow">{label}</div>
<div className="mt-2 text-2xl font-bold leading-none tabular-nums">{value}</div>
{hint && <div className="mt-1.5 text-xs text-ink-3">{hint}</div>}
</div>
)
}
function MiniPoster({ item, caption }: { item: MediaItem; caption: string }) {
return (
<div className="flex items-center gap-3">
<div className="w-12 shrink-0">
<Poster src={item.poster} title={item.title} />
</div>
<div className="min-w-0">
<p className="truncate text-sm font-semibold">{item.title}</p>
<p className="text-xs text-ink-3">{caption}</p>
</div>
</div>
)
}
export default function StatsPage() {
const { items, settings, loading } = useMedia()
const scale = settings.ratingScale
const years = useMemo(() => availableYears(items), [items])
const [year, setYear] = useState('')
const [tab, setTab] = useState<Tab>('overview')
const [metric, setMetric] = useState<'count' | 'minutes'>('count')
const [month, setMonth] = useState<string>()
const [ratingBin, setRatingBin] = useState<string>()
const scoped = useMemo(() => itemsForPeriod(items, year), [items, year])
const s = useMemo(() => computeStats(scoped), [scoped])
const months = useMemo(() => monthly(items, year), [items, year])
const geo = useMemo(() => countries(scoped), [scoped])
const rec = useMemo(() => records(scoped), [scoped])
if (loading) return <PageHeader title={t('stats.pageTitle')} accent={t('stats.pageAccent')} />
if (items.length === 0) {
return (
<>
<PageHeader title={t('stats.pageTitle')} accent={t('stats.pageAccent')} />
<EmptyState title={t('stats.emptyTitle')} text={t('stats.emptyText')} />
</>
)
}
const hours = Math.round(s.totalMinutes / 60)
const days = s.totalMinutes / 1440
const typeTotal = s.byType.reduce((sum, bt) => sum + bt.minutes, 0)
const typeRows = s.byType.filter((bt) => bt.value > 0).sort((a, b) => b.minutes - a.minutes)
// Mois sélectionné par défaut : le plus chargé
const busiest = months.reduce((best, m) => (m[metric] > best[metric] ? m : best), months[0])
const shownMonth = months.find((m) => m.key === month) ?? busiest
// Histogramme des notes
const ratingCols =
scale === '5'
? s.ratingBuckets.map((v, i) => ({ key: String(i), label: formatRating(i + 1, '5'), value: v }))
: s.ratingBuckets.map((v, i) => ({ key: String(i), label: String(i + 1), value: v }))
const shownRating = ratingCols.find((c) => c.key === ratingBin) ?? ratingCols.reduce((a, b) => (b.value > a.value ? b : a), ratingCols[0])
const maxGenre = Math.max(1, ...s.topGenres.map((g) => g.value))
const maxCountry = Math.max(1, ...geo.list.map((c) => c.count))
const periodLabel = year || t('stats.sinceStart')
return (
<>
<PageHeader title={t('stats.pageTitle')} accent={t('stats.pageAccent')} subtitle={year ? t('stats.subtitleYear', { count: s.total, year }) : t('stats.subtitle', { count: s.total })} />
{/* Période + onglets, collants en haut */}
<div className="sticky top-0 z-20 -mx-4 space-y-2.5 bg-bg/95 px-4 pb-3 pt-[max(0.5rem,env(safe-area-inset-top))] backdrop-blur-md">
<div className="no-scrollbar -mx-4 flex gap-2 overflow-x-auto px-4">
{['', ...years].map((y) => (
<button key={y || 'all'} onClick={() => setYear(y)} className={cx('chip py-1! text-[13px]', year === y && 'chip-on')}>
{y || t('common.all')}
</button>
))}
</div>
<div className="grid grid-cols-3 gap-1 rounded-full border border-line p-1">
{TABS.map((tb) => (
<button
key={tb.value}
onClick={() => setTab(tb.value)}
className={cx('rounded-full py-2 text-xs font-semibold transition-colors', tab === tb.value ? 'bg-ink text-bg' : 'text-ink-3')}
>
{tb.label}
</button>
))}
</div>
</div>
{tab === 'overview' && (
<>
{/* Le grand chiffre */}
<div className="card mt-3 p-5">
<span className="eyebrow">{t('home.screenTime')} · {periodLabel}</span>
<div className="mt-2 flex items-baseline gap-2">
<span className="text-5xl font-bold tabular-nums leading-none">{fmtInt(hours)}</span>
<span className="text-xl font-semibold text-accent">{t('stats.hours', { count: hours })}</span>
</div>
<p className="mt-2 text-sm text-ink-2">
{t('stats.nonStopPre')}
<span className="font-semibold text-ink">{days >= 1 ? t('stats.days', { count: Math.round(days) }) : formatDuration(s.totalMinutes)}</span>
{t('stats.nonStopPost')}
{' · '}
{t('stats.finishedN', { count: s.completed })} · {t('stats.episodesN', { count: s.episodesWatched })}
</p>
</div>
{/* Répartition par type : barre empilée + légende */}
<SectionTitle>{t('stats.timeByType')}</SectionTitle>
{typeTotal > 0 ? (
<>
<div className="flex h-4 gap-[2px] overflow-hidden rounded-full">
{typeRows.map((row) =>
row.minutes > 0 ? (
<span key={row.type} style={{ flexGrow: row.minutes, background: TYPE_COLORS[row.type] }} title={`${row.label} : ${formatDuration(row.minutes)}`} />
) : null,
)}
</div>
<ul className="mt-4 space-y-2.5">
{typeRows.map((row) => (
<li key={row.type} className="flex items-center gap-3 text-sm">
<span className="size-3 shrink-0 rounded-full" style={{ background: TYPE_COLORS[row.type] }} />
<span className="flex-1 text-ink-2">{row.label}</span>
<span className="text-xs text-ink-3">{t('journal.seen', { count: row.completed })}</span>
<span className="w-16 text-right text-xs font-semibold tabular-nums">{formatDuration(row.minutes)}</span>
<span className="w-10 text-right text-xs tabular-nums text-ink-3">{Math.round((row.minutes / typeTotal) * 100)} %</span>
</li>
))}
</ul>
</>
) : (
<p className="text-sm text-ink-3">{t('stats.noTime')}</p>
)}
<div className="mt-8 grid grid-cols-2 gap-3">
<Tile
label={t('stats.avgRating')}
value={
s.avgRating != null ? (
<span className="flex items-center gap-1.5">
<Star size={20} className="fill-accent text-accent" />
{formatRating(Math.round(s.avgRating * 10) / 10, scale)}
<span className="text-sm font-normal text-ink-3">/{scale}</span>
</span>
) : (
'—'
)
}
hint={t('stats.rated', { count: s.ratedCount })}
/>
<Tile label={t('home.completed')} value={fmtInt(s.completed)} hint={year ? t('stats.inYear', { year }) : t('home.thisYear', { count: s.completedThisYear })} />
</div>
{/* Statuts en pastilles */}
<SectionTitle>{t('stats.statuses')}</SectionTitle>
<div className="grid grid-cols-5 gap-2 text-center">
{s.byStatus.map((st) => (
<div key={st.status} className="rounded-2xl border border-line py-3">
<div className="text-lg font-bold tabular-nums">{st.value}</div>
<div className="mt-0.5 text-[10px] leading-tight text-ink-3">{STATUSES.find((x) => x.value === st.status)?.label}</div>
</div>
))}
</div>
</>
)}
{tab === 'habits' && (
<>
<SectionTitle
action={
<div className="flex rounded-full border border-line p-0.5">
{(['count', 'minutes'] as const).map((m) => (
<button
key={m}
onClick={() => setMetric(m)}
className={cx('rounded-full px-2.5 py-0.5 text-[11px] font-semibold', metric === m ? 'bg-ink text-bg' : 'text-ink-3')}
>
{m === 'count' ? t('catalog.titles') : t('stats.hoursTab')}
</button>
))}
</div>
}
>
{year ? t('stats.monthByMonth', { year }) : t('stats.last12')}
</SectionTitle>
<div className="card p-4">
<p className="mb-4 text-sm">
<span className="font-semibold capitalize">{new Date(`${shownMonth.key}-15T12:00:00`).toLocaleDateString(locale(), { month: 'long', year: 'numeric' })}</span>
<span className="text-ink-2">
{' · '}
{t('stats.monthFinished', { count: shownMonth.count })} · {formatDuration(shownMonth.minutes)}
</span>
</p>
<Columns
data={months.map((m) => ({ key: m.key, label: m.initial, value: metric === 'count' ? m.count : m.minutes }))}
format={(v) => (metric === 'count' ? t('account.nTitles', { count: v }) : formatDuration(v))}
selected={shownMonth.key}
onSelect={setMonth}
/>
{busiest[metric] > 0 && (
<p className="mt-3 text-xs text-ink-3">
{t('stats.busiest')} <span className="text-ink">{new Date(`${busiest.key}-15T12:00:00`).toLocaleDateString(locale(), { month: 'long', year: 'numeric' })}</span>
</p>
)}
</div>
<SectionTitle>{t('stats.records')}</SectionTitle>
<div className="space-y-3">
{rec.marathon && (
<div className="card p-3.5">
<span className="eyebrow text-accent">{t('stats.marathon')}</span>
<div className="mt-2">
<MiniPoster item={rec.marathon.item} caption={`${t('stats.episodesN', { count: rec.marathon.episodes })} · ${formatDuration(watchMinutes(rec.marathon.item))}`} />
</div>
</div>
)}
{rec.longestFilm && (
<div className="card p-3.5">
<span className="eyebrow text-accent">{t('stats.longestFilm')}</span>
<div className="mt-2">
<MiniPoster item={rec.longestFilm} caption={formatDuration(rec.longestFilm.duration ?? 0)} />
</div>
</div>
)}
{!rec.marathon && !rec.longestFilm && <p className="text-sm text-ink-3">{t('stats.noRecords')}</p>}
</div>
{s.topPlatforms.length > 0 && (
<>
<SectionTitle>{t('stats.platforms')}</SectionTitle>
<div className="flex flex-wrap gap-2">
{s.topPlatforms.map((p, i) => (
<span key={p.label} className={cx('chip', i === 0 && 'chip-on')}>
{p.label}
<span className="text-xs opacity-60">{p.value}</span>
</span>
))}
</div>
</>
)}
</>
)}
{tab === 'tastes' && (
<>
{rec.bestRated && rec.bestRated.length > 0 && (
<>
<SectionTitle>{t('stats.bestRated')} · {periodLabel}</SectionTitle>
<div className="no-scrollbar -mx-4 flex gap-3 overflow-x-auto px-4 pb-1">
{rec.bestRated.map((item) => (
<div key={item.id} className="w-24 shrink-0">
<Poster src={item.poster} title={item.title} />
<p className="mt-1.5 truncate text-xs font-medium text-ink-2">{item.title}</p>
<p className="flex items-center gap-1 text-[11px] text-ink-3">
<Star size={10} className="fill-accent text-accent" />
{formatRating(item.rating, scale)}
</p>
</div>
))}
</div>
</>
)}
<SectionTitle>{t('stats.myRatings')}</SectionTitle>
{s.ratedCount > 0 ? (
<div className="card p-4">
<p className="mb-4 text-sm">
<span className="font-semibold">{t('account.nTitles', { count: shownRating.value })}</span>
<span className="text-ink-2"> {t('stats.ratedAs', { count: shownRating.value, rating: `${shownRating.label}${scale === '5' ? ' ★' : '/10'}` })}</span>
</p>
<Columns data={ratingCols} format={(v) => t('account.nTitles', { count: v })} height={110} selected={shownRating.key} onSelect={setRatingBin} />
</div>
) : (
<p className="text-sm text-ink-3">{t('stats.noRatings')}</p>
)}
<Disagreements scoped={scoped} />
<SectionTitle>{t('stats.favGenres')}</SectionTitle>
{s.topGenres.length ? (
<div className="flex flex-wrap items-baseline gap-x-4 gap-y-2">
{s.topGenres.map((g, i) => {
const r = g.value / maxGenre
return (
<span
key={g.label}
className={cx('font-bold leading-tight', i === 0 ? 'text-accent' : r > 0.6 ? 'text-ink' : 'text-ink-2')}
style={{ fontSize: `${0.85 + r * 1.15}rem` }}
title={t('account.nTitles', { count: g.value })}
>
{genreLabel(g.label)}
<sup className="ml-0.5 text-[10px] font-medium text-ink-3">{g.value}</sup>
</span>
)
})}
</div>
) : (
<p className="text-sm text-ink-3">{t('stats.noGenres')}</p>
)}
<SectionTitle>{t('stats.countries')}</SectionTitle>
{geo.list.length ? (
<ul className="space-y-3">
{geo.list.slice(0, 8).map((c) => (
<li key={c.code} className="flex items-center gap-3 text-sm">
<span className="w-7 text-center text-xl leading-none">{c.flag}</span>
<span className="w-28 truncate text-ink-2">{c.name}</span>
<span className="h-2 flex-1 overflow-hidden rounded-full bg-surface-2">
<span className="block h-full rounded-full bg-accent" style={{ width: `${(c.count / maxCountry) * 100}%` }} />
</span>
<span className="w-8 text-right text-xs font-semibold tabular-nums">{c.count}</span>
</li>
))}
</ul>
) : null}
{geo.missing > 0 && (
<p className="mt-3 text-xs text-ink-3">
{geo.list.length === 0 ? t('stats.noCountryLegacy', { count: geo.missing }) : t('stats.noCountry', { count: geo.missing })}
</p>
)}
<SectionTitle>{t('stats.byType')}</SectionTitle>
<div className="grid grid-cols-3 gap-2">
{MEDIA_TYPES.map((mt) => {
const row = s.byType.find((b) => b.type === mt.value)!
return (
<div key={mt.value} className="rounded-2xl border border-line p-3">
<span className="mb-2 block h-1 w-6 rounded-full" style={{ background: TYPE_COLORS[mt.value] }} />
<div className="text-xl font-bold tabular-nums">{row.value}</div>
<div className="text-[11px] text-ink-3">{mt.label}</div>
</div>
)
})}
</div>
</>
)}
<p className="mt-8 text-xs text-ink-3">
{t('stats.footnote')}
</p>
</>
)
}
+438
View File
@@ -0,0 +1,438 @@
import { t } from './i18n'
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import type { CustomList, MediaInput, MediaItem, Settings, TopCategory } from './types'
import { ALL_TOP_CATEGORIES } from './lib/constants'
import { applyTheme, DEFAULT_ACCENT } from './lib/theme'
import { normalizeItem, normalizeLists, normalizeSettings } from './lib/backup'
import { CLOUD_TMDB, isPlausibleTmdbKey } from './lib/catalogApi'
import { createSync, type SyncEngine, type SyncStatus } from './lib/cloud/sync'
import { deleteDatabase, readOtherDatabase } from './lib/db'
import { cloudFetch } from './lib/cloud/api'
import { signOut } from './lib/cloud/auth'
import { dbNameFor, scopedKey } from './lib/scope'
import { isPlainObject, LIMITS, readStorage } from './lib/security'
import { mediaDB, requestPersistentStorage } from './lib/db'
import { todayISO, uid } from './lib/utils'
// Clés propres à l'espace actif (compte connecté, ou appareil sans compte)
const settingsKey = () => scopedKey('settings')
const listsKey = () => scopedKey('lists')
function loadLists(): CustomList[] {
return normalizeLists(readStorage(listsKey(), [])) ?? []
}
function persistLists(lists: CustomList[]) {
try {
localStorage.setItem(listsKey(), JSON.stringify(lists))
} catch {
/* ignore */
}
}
const DEFAULT_SETTINGS: Settings = { ratingScale: '5', topCategories: ALL_TOP_CATEGORIES, accentColor: DEFAULT_ACCENT }
/** Relit les réglages en ne gardant que des valeurs valides (le localStorage peut avoir été modifié). */
function loadSettings(): Settings {
const raw = readStorage(settingsKey(), {})
const clean = normalizeSettings(raw) ?? {}
const key = isPlainObject(raw) && typeof raw.tmdbKey === 'string' && isPlausibleTmdbKey(raw.tmdbKey) ? raw.tmdbKey.trim() : undefined
return { ...DEFAULT_SETTINGS, ...clean, tmdbKey: key }
}
interface MediaStore {
items: MediaItem[]
loading: boolean
error?: string
settings: Settings
updateSettings: (patch: Partial<Settings>) => void
add: (input: MediaInput) => Promise<MediaItem>
update: (id: string, patch: Partial<MediaInput>) => Promise<void>
remove: (id: string) => Promise<void>
incrementEpisode: (id: string, delta?: number) => Promise<void>
importItems: (items: MediaItem[], mode: 'merge' | 'replace') => Promise<void>
/** Remplace le Top 5 d'une catégorie par ces fiches, dans l'ordre (max 5). */
setTopList: (category: TopCategory, orderedIds: string[]) => Promise<void>
clearAll: () => Promise<void>
/** Met à jour plusieurs fiches d'un coup (sans changer leur date de modification). */
patchMany: (patches: { id: string; patch: Partial<MediaInput> }[]) => Promise<void>
// Listes perso
lists: CustomList[]
createList: (name: string) => CustomList
renameList: (id: string, name: string) => void
deleteList: (id: string) => Promise<void>
toggleInList: (itemId: string, listId: string) => Promise<void>
mergeLists: (incoming: CustomList[], mode: 'merge' | 'replace') => void
/** Compte connecté (absent en mode 100 % local) */
account?: AccountApi
}
export interface AccountApi {
email: string
sync: SyncStatus
syncNow: () => Promise<void>
/** Déconnexion. Renvoie « pending » s'il reste des modifications non envoyées (sauf si force). */
logout: (force?: boolean) => Promise<'pending' | 'done'>
deleteAccount: () => Promise<void>
/** Données créées sur cet appareil avant les comptes (mode local) */
deviceData: { items: number; lists: number } | null
importDeviceData: () => Promise<number>
dismissDeviceData: () => void
}
/** Efface de l'appareil tout ce qui appartient à un compte (base, réglages, synchro, caches). */
async function wipeAccountFromDevice(userId: string) {
await deleteDatabase(dbNameFor(userId))
for (const name of ['settings', 'lists', 'sync', 'device-import']) {
try {
localStorage.removeItem(scopedKey(name, userId))
} catch {
/* ignore */
}
}
for (const k of ['azuucine:airing', 'azuucine:releases', 'azuucine:public-checked']) {
try {
localStorage.removeItem(k)
} catch {
/* ignore */
}
}
}
const MediaContext = createContext<MediaStore | null>(null)
const byUpdatedDesc = (a: MediaItem, b: MediaItem) => b.updatedAt.localeCompare(a.updatedAt)
/**
* Service de données : l'état React est la copie de travail,
* IndexedDB est la source persistante (chaque écriture y est répercutée).
*/
export function MediaProvider({ children, cloudUser }: { children: ReactNode; cloudUser?: { id: string; email: string } }) {
const [items, setItems] = useState<MediaItem[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string>()
const [settings, setSettings] = useState<Settings>(loadSettings)
const [lists, setListsState] = useState<CustomList[]>(loadLists)
const syncRef = useRef<SyncEngine | null>(null)
const listsRef = useRef(lists)
listsRef.current = lists
const settingsRef = useRef(settings)
settingsRef.current = settings
const setLists = useCallback((updater: (prev: CustomList[]) => CustomList[], silent = false) => {
setListsState((prev) => {
const next = updater(prev)
persistLists(next)
if (!silent && syncRef.current) {
// Listes ajoutées, renommées ou supprimées → à envoyer
const before = new Map(prev.map((l) => [l.id, JSON.stringify(l)]))
const after = new Map(next.map((l) => [l.id, JSON.stringify(l)]))
for (const [id, v] of after) if (before.get(id) !== v) syncRef.current.markList(id)
for (const id of before.keys()) if (!after.has(id)) syncRef.current.markList(id)
}
return next
})
}, [])
const reloadItems = useCallback(async () => {
const all = await mediaDB.getAll()
setItems(all.map(normalizeItem).filter((i): i is MediaItem => i !== null).sort(byUpdatedDesc))
}, [])
useEffect(() => {
mediaDB
.getAll()
.then((all) => setItems(all.map(normalizeItem).filter((i): i is MediaItem => i !== null).sort(byUpdatedDesc)))
.catch((e) => setError(t('store.dbError', { error: String(e?.message ?? e) })))
.finally(() => setLoading(false))
void requestPersistentStorage()
}, [])
// ─── Compte : synchronisation avec le serveur ───
const [syncStatus, setSyncStatus] = useState<SyncStatus>({ state: 'idle', pending: 0 })
const [deviceData, setDeviceData] = useState<{ items: number; lists: number } | null>(null)
useEffect(() => {
if (!cloudUser) return
const engine = createSync(cloudUser.id, {
getLists: () => listsRef.current,
applyLists: (next) => setLists(() => next, true),
getSettings: () => {
const { ratingScale, topCategories, accentColor } = settingsRef.current
return { ratingScale, topCategories, accentColor }
},
applySettings: (patch) => updateSettingsRef.current(patch, true),
itemsChanged: () => void reloadItems(),
})
syncRef.current = engine
const off = engine.subscribe(setSyncStatus)
setSyncStatus(engine.status())
engine.start()
// Données créées sur cet appareil avant les comptes : proposer de les rapatrier
let alive = true
if (localStorage.getItem(scopedKey('device-import', cloudUser.id)) !== 'done') {
readOtherDatabase(dbNameFor(null))
.then((old) => {
const oldLists = normalizeLists(readStorage(scopedKey('lists', null), [])) ?? []
if (alive && (old.length || oldLists.length)) setDeviceData({ items: old.length, lists: oldLists.length })
})
.catch(() => {})
}
return () => {
alive = false
off()
engine.stop()
syncRef.current = null
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cloudUser?.id])
// Thème de couleur appliqué avant l'affichage (pas de flash de rouge)
useLayoutEffect(() => applyTheme(settings.accentColor), [settings.accentColor])
const updateSettings = useCallback((patch: Partial<Settings>, silent = false) => {
if (!silent && syncRef.current && ('ratingScale' in patch || 'topCategories' in patch || 'accentColor' in patch)) syncRef.current.markSettings()
setSettings((prev) => {
const next = { ...prev, ...patch }
try {
localStorage.setItem(settingsKey(), JSON.stringify(cloudUser ? { ...next, tmdbKey: undefined } : next))
} catch {
/* ignore */
}
return next
})
}, [])
const updateSettingsRef = useRef(updateSettings)
updateSettingsRef.current = updateSettings
/** Toute écriture passe par la même validation que l'import (dernière ligne de défense). */
const save = useCallback(async (raw: MediaItem) => {
const item = normalizeItem(raw)
if (!item) throw new Error(t('store.invalidItem'))
await mediaDB.put(item)
setItems((prev) => [item, ...prev.filter((i) => i.id !== item.id)].sort(byUpdatedDesc))
}, [])
const add = useCallback(
async (input: MediaInput) => {
const now = new Date().toISOString()
const item: MediaItem = { ...input, id: uid(), createdAt: now, updatedAt: now }
await save(item)
return item
},
[save],
)
const update = useCallback(
async (id: string, patch: Partial<MediaInput>) => {
const current = items.find((i) => i.id === id)
if (!current) return
await save({ ...current, ...patch, updatedAt: new Date().toISOString() })
},
[items, save],
)
const remove = useCallback(async (id: string) => {
await mediaDB.remove(id)
setItems((prev) => prev.filter((i) => i.id !== id))
}, [])
const incrementEpisode = useCallback(
async (id: string, delta = 1) => {
const item = items.find((i) => i.id === id)
if (!item) return
let next = Math.max(0, item.episodesWatched + delta)
if (item.episodesTotal) next = Math.min(next, item.episodesTotal)
if (next === item.episodesWatched) return
const patch: Partial<MediaInput> = { episodesWatched: next }
if (delta > 0 && (item.status === 'a_voir' || item.status === 'pause')) {
patch.status = 'en_cours'
if (!item.startDate) patch.startDate = todayISO()
}
if (item.episodesTotal && next === item.episodesTotal && delta > 0) {
patch.status = 'termine'
if (!item.endDate) patch.endDate = todayISO()
}
await update(id, patch)
},
[items, update],
)
const importItems = useCallback(async (incoming: MediaItem[], mode: 'merge' | 'replace') => {
if (mode === 'replace') await mediaDB.clear()
await mediaDB.putMany(incoming)
const all = await mediaDB.getAll()
setItems(all.sort(byUpdatedDesc))
}, [])
const setTopList = useCallback(
async (category: TopCategory, orderedIds: string[]) => {
const ids = orderedIds.slice(0, 5)
const now = new Date().toISOString()
const changed: MediaItem[] = []
for (const item of items) {
const rank = ids.indexOf(item.id) + 1
const wasHere = item.top?.category === category
if (rank > 0) {
if (!wasHere || item.top?.rank !== rank) changed.push({ ...item, top: { category, rank }, updatedAt: now })
} else if (wasHere) {
changed.push({ ...item, top: undefined, updatedAt: now })
}
}
if (!changed.length) return
await mediaDB.putMany(changed)
const byId = new Map(changed.map((c) => [c.id, c]))
setItems((prev) => prev.map((i) => byId.get(i.id) ?? i))
},
[items],
)
const clearAll = useCallback(async () => {
await mediaDB.clear()
setItems([])
}, [])
const patchMany = useCallback(
async (patches: { id: string; patch: Partial<MediaInput> }[]) => {
const byId = new Map(items.map((i) => [i.id, i]))
const changed = patches.flatMap(({ id, patch }) => {
const cur = byId.get(id)
const next = cur ? normalizeItem({ ...cur, ...patch }) : null
return next ? [next] : []
})
if (!changed.length) return
await mediaDB.putMany(changed)
const map = new Map(changed.map((c) => [c.id, c]))
setItems((prev) => prev.map((i) => map.get(i.id) ?? i))
},
[items],
)
const createList = useCallback(
(name: string) => {
const list: CustomList = { id: uid(), name: name.trim().slice(0, LIMITS.shortText) || t('lists.newList'), createdAt: new Date().toISOString() }
setLists((prev) => [...prev, list])
return list
},
[setLists],
)
const renameList = useCallback(
(id: string, name: string) => setLists((prev) => prev.map((l) => (l.id === id ? { ...l, name: name.trim().slice(0, LIMITS.shortText) || l.name } : l))),
[setLists],
)
const deleteList = useCallback(
async (id: string) => {
setLists((prev) => prev.filter((l) => l.id !== id))
const changed = items.filter((i) => i.listIds?.includes(id)).map((i) => ({ ...i, listIds: i.listIds!.filter((x) => x !== id) }))
if (changed.length) {
await mediaDB.putMany(changed)
const map = new Map(changed.map((c) => [c.id, c]))
setItems((prev) => prev.map((i) => map.get(i.id) ?? i))
}
},
[items, setLists],
)
const toggleInList = useCallback(
async (itemId: string, listId: string) => {
const item = items.find((i) => i.id === itemId)
if (!item) return
const has = item.listIds?.includes(listId)
const listIds = has ? item.listIds!.filter((x) => x !== listId) : [...(item.listIds ?? []), listId]
const next = { ...item, listIds }
await mediaDB.put(next)
setItems((prev) => prev.map((i) => (i.id === itemId ? next : i)))
},
[items],
)
const mergeLists = useCallback(
(incoming: CustomList[], mode: 'merge' | 'replace') =>
setLists((prev) => {
if (mode === 'replace') return incoming
const ids = new Set(prev.map((l) => l.id))
return [...prev, ...incoming.filter((l) => !ids.has(l.id))]
}),
[setLists],
)
const account = useMemo<AccountApi | undefined>(() => {
if (!cloudUser) return undefined
const userId = cloudUser.id
return {
email: cloudUser.email,
sync: syncStatus,
syncNow: () => syncRef.current?.syncNow() ?? Promise.resolve(),
async logout(force = false) {
const engine = syncRef.current
if (engine && navigator.onLine) await engine.syncNow()
if (!force && engine && engine.status().pending > 0) return 'pending'
engine?.stop()
await wipeAccountFromDevice(userId)
await signOut()
return 'done'
},
async deleteAccount() {
const res = await cloudFetch('/functions/v1/delete-account', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ confirm: 'SUPPRIMER' }),
})
if (!res.ok) throw new Error(res.status === 429 ? t('account.err.deleteRate') : t('account.err.delete'))
syncRef.current?.stop()
await wipeAccountFromDevice(userId)
await signOut()
},
deviceData,
async importDeviceData() {
const old = (await readOtherDatabase(dbNameFor(null))).map(normalizeItem).filter((i): i is MediaItem => i !== null)
const current = new Map((await mediaDB.getAll()).map((i) => [i.id, i]))
const incoming = old.filter((i) => !current.has(i.id) || current.get(i.id)!.updatedAt < i.updatedAt)
await mediaDB.putMany(incoming)
const oldLists = normalizeLists(readStorage(scopedKey('lists', null), [])) ?? []
if (oldLists.length) setLists((prev) => [...prev, ...oldLists.filter((l) => !prev.some((p) => p.id === l.id))])
const oldSettings = normalizeSettings(readStorage(scopedKey('settings', null), {}))
if (oldSettings && Object.keys(oldSettings).length) updateSettings(oldSettings)
await reloadItems()
// Les données sont maintenant dans le compte : on retire la copie « sans compte » de l'appareil
await deleteDatabase(dbNameFor(null))
for (const name of ['settings', 'lists']) localStorage.removeItem(scopedKey(name, null))
localStorage.setItem(scopedKey('device-import', userId), 'done')
setDeviceData(null)
return incoming.length
},
dismissDeviceData() {
localStorage.setItem(scopedKey('device-import', userId), 'done')
setDeviceData(null)
},
}
}, [cloudUser, syncStatus, deviceData, reloadItems, setLists, updateSettings])
// Avec un compte, TMDB passe par le serveur (la clé n'est jamais sur l'appareil)
const exposedSettings = useMemo<Settings>(() => (cloudUser ? { ...settings, tmdbKey: CLOUD_TMDB } : settings), [settings, cloudUser])
const value = useMemo<MediaStore>(
() => ({
items, loading, error, settings: exposedSettings, updateSettings, add, update, remove, incrementEpisode, importItems, setTopList, clearAll,
patchMany, lists, createList, renameList, deleteList, toggleInList, mergeLists, account,
}),
[
items, loading, error, exposedSettings, updateSettings, add, update, remove, incrementEpisode, importItems, setTopList, clearAll,
patchMany, lists, createList, renameList, deleteList, toggleInList, mergeLists, account,
],
)
return <MediaContext.Provider value={value}>{children}</MediaContext.Provider>
}
export function useMedia(): MediaStore {
const ctx = useContext(MediaContext)
if (!ctx) throw new Error('useMedia doit être utilisé dans <MediaProvider>')
return ctx
}
+96
View File
@@ -0,0 +1,96 @@
export type MediaType = 'film' | 'serie' | 'anime' | 'kdrama' | 'cdrama' | 'autre'
export type WatchStatus = 'a_voir' | 'en_cours' | 'termine' | 'pause' | 'abandonne'
export type CriteriaKey = 'story' | 'cast' | 'direction' | 'ost'
/** Toutes les notes sont stockées sur 10 (pas de 0,5), quel que soit l'affichage choisi. */
export type Criteria = Partial<Record<CriteriaKey, number>>
export interface MediaItem {
id: string
title: string
originalTitle?: string
type: MediaType
/** Précision pour « Autre » : Documentaire, Télé-réalité… */
subtype?: string
year?: number
status: WatchStatus
rating?: number
criteria: Criteria
favorite?: boolean
// Suivi des épisodes (formats longs)
episodesWatched: number
episodesTotal?: number
season?: number
/** Durée d'un épisode en minutes (sinon valeur par défaut selon le type). */
episodeDuration?: number
/** Durée totale en minutes (films / formats uniques). */
duration?: number
startDate?: string // AAAA-MM-JJ
endDate?: string // AAAA-MM-JJ
genres: string[]
platform?: string
notes?: string
/** Avis visible sur mon profil public (sinon il reste privé) */
notesPublic?: boolean
/** URL d'image ou image compressée en data URL (reste locale). */
poster?: string
/** Synopsis (rempli depuis TMDB / AniList). */
overview?: string
/** Référence dans une base externe, ex. « tmdb:tv:1396 » ou « anilist:154587 ». */
externalId?: string
/** Place dans un Top 5 (ex. { category: 'anime', rank: 1 }). */
top?: TopEntry
/** Listes perso auxquelles appartient la fiche. */
listIds?: string[]
/** Pays d'origine (codes ISO, ex. ['KR']). */
countries?: string[]
/** Dates de revisionnage (AAAA-MM-JJ), en plus du premier visionnage. */
rewatchDates?: string[]
/** Note moyenne du public sur 10 (TMDB ou AniList). */
publicRating?: number
createdAt: string // ISO
updatedAt: string // ISO
}
export type MediaInput = Omit<MediaItem, 'id' | 'createdAt' | 'updatedAt'>
export type RatingScale = '5' | '10'
/** Catégories de Top 5 */
export type TopCategory = 'film' | 'serie' | 'anime' | 'kdrama' | 'cdrama'
export interface TopEntry {
category: TopCategory
/** 1 à 5 */
rank: number
}
export interface Settings {
ratingScale: RatingScale
/** Clé API TMDB (v3) ou jeton de lecture (v4). Reste sur l'appareil, jamais exportée. */
tmdbKey?: string
/** Catégories de Top 5 affichées sur l'accueil (toutes par défaut). */
topCategories: TopCategory[]
/** Couleur du thème (hex), rouge par défaut. */
accentColor: string
}
export interface CustomList {
id: string
name: string
createdAt: string
}
export interface BackupFile {
app: 'AzuuCine'
version: 1
exportedAt: string
settings: Omit<Settings, 'tmdbKey'>
items: MediaItem[]
lists?: CustomList[]
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
/** Adresse du projet Supabase (publique) */
readonly VITE_SUPABASE_URL?: string
/** Clé publique « anon » / « publishable » de Supabase (publique par nature, protégée par les règles RLS) */
readonly VITE_SUPABASE_ANON_KEY?: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
+11
View File
@@ -0,0 +1,11 @@
project_id = "azuucine"
# Réglages des fonctions serveur (utilisés par `supabase functions deploy`).
# Le jeton de connexion est vérifié dans le code de chaque fonction (compatible avec
# les anciennes et les nouvelles clés d'API Supabase).
[functions.tmdb]
verify_jwt = false
[functions.delete-account]
verify_jwt = false
+59
View File
@@ -0,0 +1,59 @@
// Outils partagés par les fonctions serveur d'AzuuCine (Deno / Supabase Edge Functions).
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? ''
const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY') ?? ''
/** Origines autorisées à appeler les fonctions (ton site), séparées par des virgules. */
const ALLOWED = (Deno.env.get('ALLOWED_ORIGINS') ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
export function corsHeaders(req: Request): Record<string, string> {
const origin = req.headers.get('Origin') ?? ''
const ok = ALLOWED.length === 0 ? /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin) : ALLOWED.includes(origin)
return {
...(ok ? { 'Access-Control-Allow-Origin': origin } : {}),
'Access-Control-Allow-Headers': 'authorization, apikey, content-type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Max-Age': '600',
Vary: 'Origin',
}
}
export function json(req: Request, status: number, body: unknown, extra: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders(req), 'Content-Type': 'application/json; charset=utf-8', 'X-Content-Type-Options': 'nosniff', ...extra },
})
}
// Petit cache jeton → utilisateur (évite de revérifier le même jeton à chaque requête)
const verified = new Map<string, { id: string; until: number }>()
/** Vérifie le jeton de connexion auprès de Supabase Auth. Renvoie l'id de l'utilisateur, ou null. */
export async function getUserId(req: Request): Promise<string | null> {
const auth = req.headers.get('Authorization') ?? ''
const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : ''
if (!token || token.length > 4096 || token === ANON_KEY) return null
const cached = verified.get(token)
if (cached && cached.until > Date.now()) return cached.id
const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, { headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` } })
if (!res.ok) return null
const user = (await res.json()) as { id?: string }
if (typeof user.id !== 'string') return null
if (verified.size > 5000) verified.clear()
verified.set(token, { id: user.id, until: Date.now() + 60_000 })
return user.id
}
// Limite de requêtes par compte (fenêtre glissante, par instance)
const hits = new Map<string, number[]>()
export function rateLimited(userId: string, max: number, windowMs: number): boolean {
const now = Date.now()
const list = (hits.get(userId) ?? []).filter((t) => now - t < windowMs)
list.push(now)
hits.set(userId, list)
if (hits.size > 10000) hits.clear()
return list.length > max
}
@@ -0,0 +1,48 @@
// Suppression définitive du compte connecté (et de toutes ses données, par cascade).
// Utilise la clé « service role », disponible uniquement côté serveur.
import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts'
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? ''
const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
Deno.serve(async (req) => {
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(req) })
if (req.method !== 'POST') return json(req, 405, { error: 'method' })
const userId = await getUserId(req)
if (!userId) return json(req, 401, { error: 'auth' })
if (rateLimited('delete:' + userId, 3, 60_000)) return json(req, 429, { error: 'rate' })
let body: { confirm?: unknown } = {}
try {
body = await req.json()
} catch {
/* corps vide */
}
if (body.confirm !== 'SUPPRIMER') return json(req, 400, { error: 'confirm' })
// Photos de profil et bannières (le stockage n'est pas effacé automatiquement avec le compte)
try {
const admin = { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}`, 'Content-Type': 'application/json' }
const list = await fetch(`${SUPABASE_URL}/storage/v1/object/list/profile-media`, {
method: 'POST',
headers: admin,
body: JSON.stringify({ prefix: userId, limit: 1000 }),
})
const files = list.ok ? ((await list.json()) as { name?: string }[]) : []
const prefixes = files.filter((f) => typeof f.name === 'string').map((f) => `${userId}/${f.name}`)
if (prefixes.length) {
await fetch(`${SUPABASE_URL}/storage/v1/object/profile-media`, { method: 'DELETE', headers: admin, body: JSON.stringify({ prefixes }) })
}
} catch {
/* on supprime le compte quand même */
}
const res = await fetch(`${SUPABASE_URL}/auth/v1/admin/users/${encodeURIComponent(userId)}`, {
method: 'DELETE',
headers: { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}` },
})
if (!res.ok) return json(req, 500, { error: 'delete' })
return json(req, 200, { ok: true })
})
+68
View File
@@ -0,0 +1,68 @@
// Proxy TMDB : l'app appelle cette fonction, qui ajoute TA clé TMDB côté serveur.
// La clé est un « secret » Supabase (supabase secrets set TMDB_API_KEY=...) : elle n'est
// jamais dans le code, jamais envoyée au navigateur, et seuls les comptes connectés peuvent s'en servir.
import { corsHeaders, getUserId, json, rateLimited } from '../_shared/auth.ts'
const TMDB_KEY = Deno.env.get('TMDB_API_KEY') ?? ''
// Mêmes adresses que dans l'app — tout le reste est refusé
const PATHS = /^\/(search\/multi|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?)$/
// Paramètres autorisés et forme de leur valeur
const PARAMS: Record<string, RegExp> = {
language: /^(fr-FR|en-US|es-ES|it-IT|de-DE|pt-BR|zh-CN|ja-JP|ko-KR)$/,
query: /^[^\u0000-\u001f]{1,100}$/,
include_adult: /^false$/,
page: /^[1-9]\d?$/,
append_to_response: /^(watch\/providers|credits|release_dates)$/,
region: /^[A-Z]{2}$/,
'release_date.gte': /^\d{4}-\d{2}-\d{2}$/,
'release_date.lte': /^\d{4}-\d{2}-\d{2}$/,
'air_date.gte': /^\d{4}-\d{2}-\d{2}$/,
'air_date.lte': /^\d{4}-\d{2}-\d{2}$/,
with_release_type: /^[1-6](\|[1-6]){0,5}$/,
sort_by: /^popularity\.desc$/,
with_origin_country: /^[A-Z]{2}(\|[A-Z]{2}){0,20}$/,
without_genres: /^\d{1,6}(\|\d{1,6}){0,10}$/,
}
Deno.serve(async (req) => {
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(req) })
if (req.method !== 'GET') return json(req, 405, { error: 'method' })
if (!TMDB_KEY) return json(req, 500, { error: 'TMDB_API_KEY manquante' })
const userId = await getUserId(req)
if (!userId) return json(req, 401, { error: 'auth' })
if (rateLimited(userId, 600, 10 * 60_000)) return json(req, 429, { error: 'rate' })
const url = new URL(req.url)
const path = url.searchParams.get('path') ?? ''
if (!PATHS.test(path)) return json(req, 400, { error: 'path' })
const target = new URL('https://api.themoviedb.org/3' + path)
for (const [k, v] of url.searchParams) {
if (k === 'path') continue
const rule = PARAMS[k]
if (!rule || !rule.test(v)) return json(req, 400, { error: 'param', name: k.slice(0, 40) })
target.searchParams.set(k, v)
}
// Clé v3 (32 caractères) en paramètre, jeton v4 en en-tête
const isBearer = TMDB_KEY.length > 40
if (!isBearer) target.searchParams.set('api_key', TMDB_KEY)
const res = await fetch(target, { headers: isBearer ? { Authorization: `Bearer ${TMDB_KEY}` } : {} })
if (!res.ok) return json(req, res.status === 404 ? 404 : 502, { error: 'tmdb', status: res.status })
const body = await res.text()
if (body.length > 2_000_000) return json(req, 502, { error: 'size' })
return new Response(body, {
status: 200,
headers: {
...corsHeaders(req),
'Content-Type': 'application/json; charset=utf-8',
'X-Content-Type-Options': 'nosniff',
// Le navigateur garde la réponse 1 h (moins de requêtes vers TMDB)
'Cache-Control': 'private, max-age=3600',
},
})
})
@@ -0,0 +1,130 @@
-- ─────────────────────────────────────────────────────────────────────────────
-- AzuuCine — base de données (Supabase / Postgres)
--
-- Chaque utilisateur ne voit et ne modifie QUE ses propres lignes :
-- c'est garanti par la base elle-même (Row Level Security), pas par l'app.
-- Même avec la clé publique de l'app, personne ne peut lire les données d'un autre compte.
--
-- À coller une fois dans Supabase → SQL Editor → Run (ou `supabase db push`).
-- ─────────────────────────────────────────────────────────────────────────────
-- Fiches (films, séries, animes…) : le contenu est stocké tel quel (JSON), l'app le valide à la lecture.
create table if not exists public.items (
user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
id text not null check (id ~ '^[A-Za-z0-9_-]{1,64}$'),
data jsonb check (data is null or (jsonb_typeof(data) = 'object' and octet_length(data::text) <= 400000)),
deleted boolean not null default false,
updated_at timestamptz not null,
server_updated_at timestamptz not null default clock_timestamp(),
primary key (user_id, id),
check (deleted or data is not null)
);
-- Listes perso
create table if not exists public.lists (
user_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
id text not null check (id ~ '^[A-Za-z0-9_-]{1,64}$'),
data jsonb check (data is null or (jsonb_typeof(data) = 'object' and octet_length(data::text) <= 4000)),
deleted boolean not null default false,
updated_at timestamptz not null,
server_updated_at timestamptz not null default clock_timestamp(),
primary key (user_id, id),
check (deleted or data is not null)
);
-- Réglages (note sur 5 ou 10, thème, Top 5…) — une ligne par compte
create table if not exists public.settings (
user_id uuid primary key default auth.uid() references auth.users (id) on delete cascade,
data jsonb not null check (jsonb_typeof(data) = 'object' and octet_length(data::text) <= 4000),
updated_at timestamptz not null,
server_updated_at timestamptz not null default clock_timestamp()
);
create index if not exists items_sync_idx on public.items (user_id, server_updated_at);
create index if not exists lists_sync_idx on public.lists (user_id, server_updated_at);
-- ─── Écritures : « la modification la plus récente gagne » + horodatage serveur ───
create or replace function public.azuu_before_write()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
-- Un appareil resté hors-ligne ne peut pas écraser une version plus récente
if tg_op = 'UPDATE' and new.updated_at < old.updated_at then
return null;
end if;
-- Personne ne peut déplacer une ligne vers un autre compte
if tg_op = 'UPDATE' and new.user_id <> old.user_id then
raise exception 'user_id is immutable';
end if;
-- Date venant du client bornée (pas de date dans le futur lointain qui bloquerait les mises à jour)
if new.updated_at > now() + interval '1 day' then
new.updated_at := now();
end if;
new.server_updated_at := clock_timestamp();
return new;
end;
$$;
drop trigger if exists items_before_write on public.items;
create trigger items_before_write before insert or update on public.items
for each row execute function public.azuu_before_write();
drop trigger if exists lists_before_write on public.lists;
create trigger lists_before_write before insert or update on public.lists
for each row execute function public.azuu_before_write();
drop trigger if exists settings_before_write on public.settings;
create trigger settings_before_write before insert or update on public.settings
for each row execute function public.azuu_before_write();
-- ─── Quotas par compte (évite qu'un compte remplisse la base) ───
create or replace function public.azuu_quota()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
n integer;
max_rows integer := case tg_table_name when 'items' then 20000 else 300 end;
begin
execute format('select count(*) from public.%I where user_id = $1', tg_table_name) into n using new.user_id;
if n >= max_rows then
raise exception 'quota exceeded for %', tg_table_name;
end if;
return new;
end;
$$;
drop trigger if exists items_quota on public.items;
create trigger items_quota before insert on public.items for each row execute function public.azuu_quota();
drop trigger if exists lists_quota on public.lists;
create trigger lists_quota before insert on public.lists for each row execute function public.azuu_quota();
-- ─── Sécurité au niveau des lignes (RLS) ───
alter table public.items enable row level security;
alter table public.lists enable row level security;
alter table public.settings enable row level security;
alter table public.items force row level security;
alter table public.lists force row level security;
alter table public.settings force row level security;
-- Les visiteurs non connectés n'ont accès à rien
revoke all on public.items, public.lists, public.settings from anon;
grant select, insert, update, delete on public.items, public.lists, public.settings to authenticated;
drop policy if exists "own items" on public.items;
create policy "own items" on public.items for all to authenticated
using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
drop policy if exists "own lists" on public.lists;
create policy "own lists" on public.lists for all to authenticated
using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
drop policy if exists "own settings" on public.settings;
create policy "own settings" on public.settings for all to authenticated
using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
-- Les fonctions internes ne sont pas appelables depuis l'API
revoke all on function public.azuu_before_write() from public, anon, authenticated;
revoke all on function public.azuu_quota() from public, anon, authenticated;
@@ -0,0 +1,580 @@
-- ─────────────────────────────────────────────────────────────────────────────
-- AzuuCine — profils, abonnements et fil d'activité
--
-- À coller dans Supabase → SQL Editor → Run, APRÈS le premier fichier (…_azuucine.sql).
-- Peut être relancé sans risque.
--
-- Principes de confidentialité :
-- - Les tables de données (items, lists, settings) restent visibles uniquement par leur propriétaire.
-- - Les autres ne voient un profil QUE via les fonctions ci-dessous (get_profile, get_feed…),
-- qui vérifient l'accès (profil public, ou abonné accepté pour un compte privé) et retirent
-- les infos privées : avis écrits (sauf ceux marqués publics), listes perso.
-- - Les pseudos sont choisis par chacun ; aucun email n'est jamais exposé.
-- ─────────────────────────────────────────────────────────────────────────────
-- ═════════════════════════════ Profils ═════════════════════════════
create table if not exists public.profiles (
id uuid primary key references auth.users (id) on delete cascade,
username text not null unique check (username ~ '^[a-z0-9_]{3,20}$'),
display_name text not null check (char_length(display_name) between 1 and 40),
bio text not null default '' check (char_length(bio) <= 300),
avatar_url text check (avatar_url is null or char_length(avatar_url) <= 500),
banner_url text check (banner_url is null or char_length(banner_url) <= 500),
is_private boolean not null default false,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index if not exists profiles_display_name_idx on public.profiles (lower(display_name));
-- Pseudo de départ aléatoire (l'email n'est jamais utilisé : il resterait visible de tous)
create or replace function public.azuu_random_username()
returns text
language plpgsql
set search_path = ''
as $$
declare
candidate text;
begin
loop
candidate := 'cinephile_' || substr(md5(random()::text || clock_timestamp()::text), 1, 6);
exit when not exists (select 1 from public.profiles where username = candidate);
end loop;
return candidate;
end;
$$;
-- Création automatique du profil à l'inscription
create or replace function public.azuu_new_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
u text := public.azuu_random_username();
begin
insert into public.profiles (id, username, display_name) values (new.id, u, u) on conflict (id) do nothing;
return new;
end;
$$;
drop trigger if exists azuu_on_auth_user_created on auth.users;
create trigger azuu_on_auth_user_created after insert on auth.users
for each row execute function public.azuu_new_user();
-- Profils des comptes déjà existants
insert into public.profiles (id, username, display_name)
select u.id, x.name, x.name
from auth.users u
cross join lateral (select public.azuu_random_username() as name) x
where not exists (select 1 from public.profiles p where p.id = u.id);
-- Contrôles à chaque modification de profil
create or replace function public.azuu_profile_guard()
returns trigger
language plpgsql
set search_path = ''
as $$
declare
media text := '^https?://[^/?#]+/storage/v1/object/public/profile-media/' || new.id::text || '/[A-Za-z0-9_.-]{1,80}$';
begin
if tg_op = 'UPDATE' and new.id <> old.id then
raise exception 'id is immutable';
end if;
new.username := lower(trim(new.username));
new.display_name := trim(regexp_replace(new.display_name, '[[:cntrl:]]', '', 'g'));
new.bio := trim(regexp_replace(new.bio, '[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', 'g'));
if new.username in ('admin', 'administrator', 'azuucine', 'support', 'moderator', 'root', 'system', 'null', 'undefined', 'me', 'settings') then
raise exception 'username reserved';
end if;
-- Les images ne peuvent venir que du dossier de l'utilisateur dans le stockage de l'app
if new.avatar_url is not null and new.avatar_url !~ media then
raise exception 'invalid avatar url';
end if;
if new.banner_url is not null and new.banner_url !~ media then
raise exception 'invalid banner url';
end if;
new.updated_at := now();
return new;
end;
$$;
drop trigger if exists profiles_guard on public.profiles;
create trigger profiles_guard before insert or update on public.profiles
for each row execute function public.azuu_profile_guard();
-- ═════════════════════════════ Abonnements ═════════════════════════════
create table if not exists public.follows (
follower_id uuid not null default auth.uid() references auth.users (id) on delete cascade,
following_id uuid not null references auth.users (id) on delete cascade,
status text not null default 'pending' check (status in ('pending', 'accepted')),
created_at timestamptz not null default now(),
primary key (follower_id, following_id),
check (follower_id <> following_id)
);
create index if not exists follows_following_idx on public.follows (following_id, status);
create or replace function public.azuu_follow_guard()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
target_private boolean;
begin
if tg_op = 'INSERT' then
-- On ne peut s'abonner qu'en son propre nom ; l'acceptation dépend du compte suivi
new.follower_id := auth.uid();
select is_private into target_private from public.profiles where id = new.following_id;
if not found then
raise exception 'profile not found';
end if;
new.status := case when target_private then 'pending' else 'accepted' end;
new.created_at := now();
if (select count(*) from public.follows where follower_id = new.follower_id) >= 2000 then
raise exception 'too many follows';
end if;
return new;
end if;
-- UPDATE : seul le compte suivi peut accepter une demande, et rien d'autre ne peut changer
if new.follower_id <> old.follower_id or new.following_id <> old.following_id then
raise exception 'immutable';
end if;
if auth.uid() is distinct from old.following_id then
raise exception 'only the followed account can accept';
end if;
new.status := 'accepted';
new.created_at := old.created_at;
return new;
end;
$$;
drop trigger if exists follows_guard on public.follows;
create trigger follows_guard before insert or update on public.follows
for each row execute function public.azuu_follow_guard();
-- Passer son compte en public accepte les demandes en attente
create or replace function public.azuu_profile_public()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
if old.is_private and not new.is_private then
update public.follows set status = 'accepted' where following_id = new.id and status = 'pending';
end if;
return new;
end;
$$;
drop trigger if exists profiles_public on public.profiles;
create trigger profiles_public after update of is_private on public.profiles
for each row execute function public.azuu_profile_public();
-- ═════════════════════════════ Activité ═════════════════════════════
-- Seulement « qui a fait quoi et quand » : le contenu (titre, affiche, note) est relu sur la fiche
-- au moment de l'affichage, donc une fiche supprimée disparaît aussi du fil.
create table if not exists public.activity (
id bigint generated always as identity primary key,
user_id uuid not null references auth.users (id) on delete cascade,
item_id text not null,
kind text not null check (kind in ('finished', 'started', 'rewatched', 'added')),
created_at timestamptz not null default now()
);
create index if not exists activity_user_idx on public.activity (user_id, created_at desc);
create or replace function public.azuu_day(v text)
returns date
language plpgsql
immutable
set search_path = ''
as $$
begin
if v ~ '^\d{4}-\d{2}-\d{2}$' then
return v::date;
end if;
return null;
exception when others then
return null;
end;
$$;
create or replace function public.azuu_log(p_user uuid, p_item text, p_kind text)
returns void
language plpgsql
security definer
set search_path = ''
as $$
begin
-- Pas de doublon pour la même fiche dans la journée
delete from public.activity
where user_id = p_user and item_id = p_item and kind = p_kind and created_at > now() - interval '1 day';
insert into public.activity (user_id, item_id, kind) values (p_user, p_item, p_kind);
-- On garde les 500 dernières activités par compte
delete from public.activity
where user_id = p_user and id in (
select id from public.activity where user_id = p_user order by created_at desc offset 500
);
end;
$$;
-- Déduit l'activité des modifications de fiches (les vieux titres importés ne remplissent pas le fil)
create or replace function public.azuu_item_activity()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
st text;
old_st text;
recent date := current_date - 7;
rw_new int := 0;
rw_old int := 0;
begin
if new.deleted or new.data is null then
return new;
end if;
st := new.data->>'status';
if jsonb_typeof(new.data->'rewatchDates') = 'array' then
rw_new := jsonb_array_length(new.data->'rewatchDates');
end if;
if tg_op = 'UPDATE' then
if not old.deleted and old.data is not null then
old_st := old.data->>'status';
if jsonb_typeof(old.data->'rewatchDates') = 'array' then
rw_old := jsonb_array_length(old.data->'rewatchDates');
end if;
end if;
end if;
if st = 'termine' and old_st is distinct from 'termine'
and coalesce(public.azuu_day(new.data->>'endDate'), current_date) >= recent then
perform public.azuu_log(new.user_id, new.id, 'finished');
elsif st = 'en_cours' and old_st is distinct from 'en_cours'
and coalesce(public.azuu_day(new.data->>'startDate'), current_date) >= recent then
perform public.azuu_log(new.user_id, new.id, 'started');
elsif st = 'a_voir' and tg_op = 'INSERT' and new.updated_at > now() - interval '2 days' then
perform public.azuu_log(new.user_id, new.id, 'added');
end if;
if tg_op = 'UPDATE' and rw_new > rw_old then
perform public.azuu_log(new.user_id, new.id, 'rewatched');
end if;
return new;
end;
$$;
drop trigger if exists items_activity on public.items;
create trigger items_activity after insert or update on public.items
for each row execute function public.azuu_item_activity();
-- ═════════════════════════════ Accès (RLS) ═════════════════════════════
alter table public.profiles enable row level security;
alter table public.follows enable row level security;
alter table public.activity enable row level security;
alter table public.profiles force row level security;
alter table public.follows force row level security;
alter table public.activity force row level security;
revoke all on public.profiles, public.follows, public.activity from anon;
grant select, update on public.profiles to authenticated;
grant select, insert, update, delete on public.follows to authenticated;
grant select on public.activity to authenticated;
-- Pseudo, nom, photo, bannière et bio sont visibles des comptes connectés (comme sur Letterboxd,
-- même pour un compte privé) ; seul le propriétaire peut modifier son profil.
drop policy if exists "profiles readable" on public.profiles;
create policy "profiles readable" on public.profiles for select to authenticated using (true);
drop policy if exists "own profile update" on public.profiles;
create policy "own profile update" on public.profiles for update to authenticated
using ((select auth.uid()) = id) with check ((select auth.uid()) = id);
-- Abonnements : chacun voit ceux qui le concernent ; les listes publiques passent par les fonctions
drop policy if exists "own follows read" on public.follows;
create policy "own follows read" on public.follows for select to authenticated
using ((select auth.uid()) in (follower_id, following_id));
drop policy if exists "follow someone" on public.follows;
create policy "follow someone" on public.follows for insert to authenticated
with check ((select auth.uid()) = follower_id);
drop policy if exists "accept request" on public.follows;
create policy "accept request" on public.follows for update to authenticated
using ((select auth.uid()) = following_id) with check ((select auth.uid()) = following_id);
drop policy if exists "unfollow or remove follower" on public.follows;
create policy "unfollow or remove follower" on public.follows for delete to authenticated
using ((select auth.uid()) in (follower_id, following_id));
drop policy if exists "own activity read" on public.activity;
create policy "own activity read" on public.activity for select to authenticated
using ((select auth.uid()) = user_id);
-- ═════════════════════════════ Fonctions de lecture ═════════════════════════════
-- Ai-je le droit de voir le contenu de ce profil ?
create or replace function public.can_view(owner uuid)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select auth.uid() is not null and (
owner = auth.uid()
or exists (select 1 from public.profiles p where p.id = owner and not p.is_private)
or exists (select 1 from public.follows f where f.follower_id = auth.uid() and f.following_id = owner and f.status = 'accepted')
)
$$;
-- Version publique d'une fiche : sans avis privé, sans listes perso, sans affiche trop lourde
create or replace function public.public_item(d jsonb)
returns jsonb
language sql
immutable
set search_path = ''
as $$
select case when length(coalesce(x->>'poster', '')) > 150000 then x - 'poster' else x end
from (select (case when d->>'notesPublic' = 'true' then d else d - 'notes' end) - 'listIds' as x) s
$$;
create or replace function public.profile_card(p public.profiles)
returns jsonb
language sql
stable
security definer
set search_path = ''
as $$
select jsonb_build_object(
'id', p.id, 'username', p.username, 'display_name', p.display_name,
'avatar_url', p.avatar_url, 'is_private', p.is_private,
'relation', coalesce((select f.status from public.follows f where f.follower_id = auth.uid() and f.following_id = p.id), 'none')
)
$$;
-- Profil complet par pseudo
create or replace function public.get_profile(p_username text)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
p public.profiles;
me uuid := auth.uid();
res jsonb;
begin
if me is null then
return null;
end if;
select * into p from public.profiles where username = lower(trim(p_username));
if not found then
return null;
end if;
res := public.profile_card(p) || jsonb_build_object(
'bio', p.bio,
'banner_url', p.banner_url,
'is_me', p.id = me,
'follows_me', exists (select 1 from public.follows where follower_id = p.id and following_id = me and status = 'accepted'),
'followers', (select count(*) from public.follows where following_id = p.id and status = 'accepted'),
'following', (select count(*) from public.follows where follower_id = p.id and status = 'accepted'),
'visible', public.can_view(p.id)
);
if public.can_view(p.id) then
res := res || jsonb_build_object(
'stats', (
select jsonb_build_object(
'total', count(*),
'finished', count(*) filter (where data->>'status' = 'termine'),
'finished_year', count(*) filter (where data->>'status' = 'termine' and left(data->>'endDate', 4) = to_char(now(), 'YYYY')),
'films', count(*) filter (where data->>'status' = 'termine' and data->>'type' = 'film'),
'series', count(*) filter (where data->>'status' = 'termine' and data->>'type' <> 'film'),
'episodes', coalesce(sum(case when data->>'episodesWatched' ~ '^\d{1,6}$' then (data->>'episodesWatched')::int else 0 end), 0),
'rated', count(*) filter (where data ? 'rating')
)
from public.items where user_id = p.id and not deleted
),
'top', (
select coalesce(jsonb_agg(public.public_item(data) order by data->'top'->>'category', (data->'top'->>'rank')), '[]'::jsonb)
from public.items where user_id = p.id and not deleted and jsonb_typeof(data->'top') = 'object'
),
'recent', (
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc), '[]'::jsonb)
from (
select data, coalesce(data->>'endDate', left(data->>'updatedAt', 10)) as k
from public.items
where user_id = p.id and not deleted and data->>'status' = 'termine'
order by k desc nulls last
limit 12
) s
)
);
end if;
return res;
end;
$$;
-- Bibliothèque d'un profil (par pages)
create or replace function public.get_profile_items(p_user uuid, p_status text default null, p_offset int default 0, p_limit int default 48)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
begin
if not public.can_view(p_user) then
return '[]'::jsonb;
end if;
return (
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last, s.id), '[]'::jsonb)
from (
select id, data, coalesce(data->>'endDate', data->>'startDate', left(data->>'updatedAt', 10)) as k
from public.items
where user_id = p_user and not deleted
and (p_status is null or data->>'status' = p_status)
order by k desc nulls last, id
offset greatest(p_offset, 0)
limit least(greatest(p_limit, 1), 60)
) s
);
end;
$$;
-- Fil d'activité de mes abonnements
create or replace function public.get_feed(p_before timestamptz default null, p_limit int default 30)
returns jsonb
language sql
stable
security definer
set search_path = ''
as $$
select coalesce(jsonb_agg(entry order by created_at desc), '[]'::jsonb)
from (
select a.created_at,
jsonb_build_object(
'id', a.id, 'kind', a.kind, 'created_at', a.created_at,
'user', jsonb_build_object('username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url),
'item', public.public_item(i.data)
) as entry
from public.activity a
join public.follows f on f.following_id = a.user_id and f.follower_id = auth.uid() and f.status = 'accepted'
join public.profiles p on p.id = a.user_id
join public.items i on i.user_id = a.user_id and i.id = a.item_id and not i.deleted
where p_before is null or a.created_at < p_before
order by a.created_at desc
limit least(greatest(p_limit, 1), 50)
) s
$$;
-- Recherche de profils (pseudo ou nom)
create or replace function public.search_profiles(q text)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
declare
term text := lower(trim(coalesce(q, '')));
pattern text;
begin
if auth.uid() is null or char_length(term) < 2 or char_length(term) > 40 then
return '[]'::jsonb;
end if;
pattern := replace(replace(replace(ltrim(term, '@'), '\', '\\'), '%', '\%'), '_', '\_');
return (
select coalesce(jsonb_agg(public.profile_card(p) order by (p.username = ltrim(term, '@')) desc, p.username), '[]'::jsonb)
from (
select * from public.profiles
where id <> auth.uid() and (username like pattern || '%' or lower(display_name) like '%' || pattern || '%')
order by username
limit 20
) p
);
end;
$$;
-- Abonnés / abonnements d'un profil
create or replace function public.get_follow_list(p_user uuid, p_kind text, p_offset int default 0)
returns jsonb
language plpgsql
stable
security definer
set search_path = ''
as $$
begin
if not public.can_view(p_user) or p_kind not in ('followers', 'following') then
return '[]'::jsonb;
end if;
return (
select coalesce(jsonb_agg(public.profile_card(p) order by s.created_at desc), '[]'::jsonb)
from (
select case when p_kind = 'followers' then f.follower_id else f.following_id end as uid, f.created_at
from public.follows f
where f.status = 'accepted' and (case when p_kind = 'followers' then f.following_id else f.follower_id end) = p_user
order by f.created_at desc
offset greatest(p_offset, 0)
limit 50
) s
join public.profiles p on p.id = s.uid
);
end;
$$;
-- Demandes d'abonnement reçues (compte privé)
create or replace function public.get_follow_requests()
returns jsonb
language sql
stable
security definer
set search_path = ''
as $$
select coalesce(jsonb_agg(public.profile_card(p) order by f.created_at desc), '[]'::jsonb)
from public.follows f
join public.profiles p on p.id = f.follower_id
where f.following_id = auth.uid() and f.status = 'pending'
$$;
-- Les fonctions de lecture ne sont utilisables que par les comptes connectés
revoke all on function public.can_view(uuid), public.public_item(jsonb), public.profile_card(public.profiles),
public.get_profile(text), public.get_profile_items(uuid, text, int, int), public.get_feed(timestamptz, int),
public.search_profiles(text), public.get_follow_list(uuid, text, int), public.get_follow_requests()
from public, anon;
grant execute on function public.get_profile(text), public.get_profile_items(uuid, text, int, int), public.get_feed(timestamptz, int),
public.search_profiles(text), public.get_follow_list(uuid, text, int), public.get_follow_requests()
to authenticated;
-- Outils internes des fonctions ci-dessus : jamais appelables directement depuis l'API
revoke all on function public.can_view(uuid), public.public_item(jsonb), public.profile_card(public.profiles)
from public, anon, authenticated;
-- Fonctions internes : jamais appelables depuis l'API
revoke all on function public.azuu_random_username(), public.azuu_new_user(), public.azuu_profile_guard(),
public.azuu_follow_guard(), public.azuu_profile_public(), public.azuu_day(text), public.azuu_log(uuid, text, text),
public.azuu_item_activity()
from public, anon, authenticated;
-- ═════════════════════════════ Photos de profil et bannières ═════════════════════════════
insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
values ('profile-media', 'profile-media', true, 2097152, array['image/jpeg', 'image/webp', 'image/png'])
on conflict (id) do update
set public = true, file_size_limit = excluded.file_size_limit, allowed_mime_types = excluded.allowed_mime_types;
-- Chacun ne peut écrire que dans son propre dossier « <id>/… » ; la lecture passe par l'adresse publique
drop policy if exists "profile media read own" on storage.objects;
create policy "profile media read own" on storage.objects for select to authenticated
using (bucket_id = 'profile-media' and (storage.foldername(name))[1] = (select auth.uid())::text);
drop policy if exists "profile media upload own" on storage.objects;
create policy "profile media upload own" on storage.objects for insert to authenticated
with check (
bucket_id = 'profile-media'
and (storage.foldername(name))[1] = (select auth.uid())::text
and name ~ '^[0-9a-f-]{36}/(avatar|banner)-[0-9]{1,15}\.(jpg|webp|png)$'
);
drop policy if exists "profile media delete own" on storage.objects;
create policy "profile media delete own" on storage.objects for delete to authenticated
using (bucket_id = 'profile-media' and (storage.foldername(name))[1] = (select auth.uid())::text);
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"isolatedModules": true,
"skipLibCheck": true,
"allowImportingTsExtensions": false,
"types": ["vite/client", "vite-plugin-pwa/client"]
},
"include": ["src", "vite.config.ts"]
}
+120
View File
@@ -0,0 +1,120 @@
import { defineConfig, loadEnv, type Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { VitePWA } from 'vite-plugin-pwa'
/**
* Politique de sécurité du contenu (CSP) : le navigateur n'exécute que les scripts de l'app,
* et ne contacte que TMDB / AniList. Même si une donnée piégée arrivait à s'afficher,
* elle ne pourrait ni lancer de code, ni envoyer tes données ailleurs.
*/
export const buildCsp = (supabaseUrl = '') => [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
`img-src 'self' data: blob: https://image.tmdb.org https://s4.anilist.co${supabaseUrl ? ' ' + supabaseUrl : ''}`,
"font-src 'self'",
`connect-src 'self' https://api.themoviedb.org https://graphql.anilist.co https://image.tmdb.org https://s4.anilist.co${supabaseUrl ? ' ' + supabaseUrl : ''}`,
"manifest-src 'self'",
"worker-src 'self'",
"media-src 'none'",
"object-src 'none'",
"frame-src 'none'",
"base-uri 'none'",
"form-action 'none'",
'upgrade-insecure-requests',
].join('; ')
/**
* Ajoute la CSP dans index.html et génère _headers, uniquement pour la version publiée
* (le mode dev a besoin de plus de souplesse). L'adresse Supabase du .env y est ajoutée si présente.
*/
function contentSecurityPolicy(supabaseUrl: string): Plugin {
const csp = buildCsp(supabaseUrl)
return {
name: 'azuucine-csp',
apply: 'build',
transformIndexHtml: (html) =>
html.replace('<meta charset="UTF-8" />', `<meta charset="UTF-8" />\n <meta http-equiv="Content-Security-Policy" content="${csp}" />`),
// En-têtes de sécurité pour l'hébergement (Netlify et Cloudflare Pages lisent ce fichier)
generateBundle() {
this.emitFile({
type: 'asset',
fileName: '_headers',
source: [
'/*',
` Content-Security-Policy: ${csp}; frame-ancestors 'none'`,
' X-Frame-Options: DENY',
' X-Content-Type-Options: nosniff',
' Referrer-Policy: no-referrer',
' Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=(), bluetooth=(), interest-cohort=()',
' Cross-Origin-Opener-Policy: same-origin',
' Cross-Origin-Resource-Policy: same-origin',
' Strict-Transport-Security: max-age=63072000; includeSubDomains',
'',
'# Le service worker doit toujours être revérifié pour que les mises à jour arrivent',
'/sw.js',
' Cache-Control: no-cache',
'',
].join('\n'),
})
},
}
}
// Si tu héberges l'app dans un sous-dossier (ex. GitHub Pages : /azuucine/),
// remplace base: '/' par base: '/azuucine/'.
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, '.', 'VITE_')
const origin = (env.VITE_SUPABASE_URL ?? '').trim().replace(/^(https?:\/\/[^/]+).*$/, '$1')
const supabaseUrl = /^https:\/\/[a-z0-9-]+\.supabase\.(co|in)$/i.test(origin) ? origin : ''
return {
base: '/',
// Le serveur de dev n'écoute que sur ce PC (voir « npm run dev:mobile » pour tester sur le téléphone)
server: { host: 'localhost', strictPort: false },
preview: { host: 'localhost' },
build: { sourcemap: false },
plugins: [
contentSecurityPolicy(supabaseUrl),
react(),
tailwindcss(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['icons/apple-touch-icon.png', 'icons/favicon.svg'],
manifest: {
name: 'AzuuCine',
short_name: 'AzuuCine',
description: 'Mon journal privé de films, séries, animes et dramas',
lang: 'fr',
theme_color: '#0a0a0a',
background_color: '#0a0a0a',
display: 'standalone',
orientation: 'portrait',
start_url: '.',
scope: '.',
icons: [
{ src: 'icons/icon-192.png', sizes: '192x192', type: 'image/png' },
{ src: 'icons/icon-512.png', sizes: '512x512', type: 'image/png' },
{ src: 'icons/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
},
workbox: {
globPatterns: ['**/*.{js,css,html,svg,png,ico,webmanifest,woff2}'],
// Les affiches AniList ne peuvent pas être copiées dans la base (CORS) :
// on les garde en cache après le premier affichage pour les voir hors-ligne.
runtimeCaching: [
{
urlPattern: /^https:\/\/(s4\.anilist\.co|image\.tmdb\.org)\//,
handler: 'CacheFirst',
options: {
cacheName: 'posters',
expiration: { maxEntries: 800, maxAgeSeconds: 60 * 60 * 24 * 365 },
cacheableResponse: { statuses: [0, 200] },
},
},
],
},
}),
],
}
})