Initial commit
This commit is contained in:
commit
459e93d314
100 files changed
+26594
No files matched your search
@@ -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 ?? ''))
|
||||
}
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -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.')
|
||||
}
|
||||
@@ -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}`
|
||||
@@ -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)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
|
||||
})
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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)]
|
||||
}
|
||||
@@ -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')
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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' })
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
Reference in new issue
Block a user