Audit : corrections de bugs, sécurité et performances (sans changement de fonctionnement)
Données et synchro - Import « remplacer » atomique (plus de bibliothèque vidée si l'écriture échoue). - Deux onglets sur le même compte : mise à jour croisée, file d'envoi partagée sans perte. - Réception : une modification locale faite pendant la synchro n'est plus écrasée ; une seule transaction. - Envoi : file vidée paquet par paquet, fiche invalide isolée (quota : gardée en attente), taille en octets réels, délai proportionnel à la taille ; grandes affiches décodées sans fetch (bloqué par la CSP). - Plus d'écriture dans la base d'un autre compte après déconnexion ; base fermée proprement (iOS). - Revisionnages journalisés à part (rewatchLog) : les défis ne sous-estiment plus le 1er visionnage ; décocher des épisodes un autre jour ne gonfle plus les défis. Comptes et social - Renouvellement de session : plus de déconnexion de tous les onglets avec un jeton déjà utilisé, plus de rafale de renouvellements, déconnexion qui révoque bien la session serveur. - Délais maximum sur les appels réseau, écran blanc évité au retour de Google. - Abonnés/abonnements au-delà de 50, pagination du fil et des profils, fil hors-ligne, listes bloquées. - Code mort retiré (CommentsSheet et options jamais utilisées). Interface et logique - Toast qui ne disparaissait plus, focus sur « Annuler » dans les confirmations, Échap pendant la saisie IME. - Demi-étoile en arabe, flèches RTL, fonds d'overlay en jeton de thème, couleur du thème étoilé. - Séries en cours sans total connu : les nouveaux épisodes se cochent à nouveau ; épisodes spéciaux ignorés. - Catalogue, accueil et calendrier plus rapides sur les grosses bibliothèques. Sources externes - Proxy TMDB : les 18 langues acceptées (9 étaient refusées), 429 transmis, délais, paramètres durcis. - Contenus adultes AniList filtrés des recommandations, cache d'import borné, imports plus sûrs. Serveur (migration 20261122140000_audit_hardening.sql, déjà appliquée en ligne) - Fonctions admin et « comptes suspendus » versionnées ; blocage effectif ; avis robustes ; fiches supprimées vidées ; comptes suspendus sans abonnement ni réaction ; objets morts supprimés. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
73 files changed
+2074
-2162
No files matched your search
+24
-20
@@ -39,21 +39,21 @@ const SEASONS_SINCE = '2026-10-04T10:00:00.000Z'
|
||||
|
||||
const n0 = (v: unknown, max = 100000) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(max, Math.round(v)) : 0)
|
||||
|
||||
// Dernière lecture (le cache est relu par chaque carte : on évite de le réanalyser à chaque fois)
|
||||
let memo: { raw: string | null; cache: AiringCache } | undefined
|
||||
// Cache gardé en mémoire : loadAiring() est appelé par chaque carte à chaque rendu, on évite de relire
|
||||
// (et réanalyser) le stockage à chaque fois. Invalidé à l'enregistrement, sur CACHE_EVENT et quand
|
||||
// un autre onglet modifie le stockage.
|
||||
let memo: AiringCache | undefined
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key === null || e.key === KEY) memo = undefined
|
||||
})
|
||||
}
|
||||
|
||||
/** Relit le cache en ne gardant que des entrées bien formées. */
|
||||
export function loadAiring(): AiringCache {
|
||||
let text: string | null = null
|
||||
try {
|
||||
text = localStorage.getItem(KEY)
|
||||
} catch {
|
||||
/* stockage indisponible */
|
||||
}
|
||||
if (memo && memo.raw === text) return memo.cache
|
||||
const cache = parseAiring()
|
||||
memo = { raw: text, cache }
|
||||
return cache
|
||||
memo ??= parseAiring()
|
||||
return memo
|
||||
}
|
||||
|
||||
function parseAiring(): AiringCache {
|
||||
@@ -73,12 +73,15 @@ function parseAiring(): AiringCache {
|
||||
/** Émis quand le cache des sorties change (pastille du calendrier). */
|
||||
export const CACHE_EVENT = 'azuucine:schedule'
|
||||
|
||||
if (typeof window !== 'undefined') window.addEventListener(CACHE_EVENT, () => (memo = undefined))
|
||||
|
||||
export function saveAiring(cache: AiringCache) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(cache))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
memo = undefined
|
||||
window.dispatchEvent(new Event(CACHE_EVENT))
|
||||
}
|
||||
|
||||
@@ -183,17 +186,18 @@ async function checkTmdb(tvId: string, key: string): Promise<Omit<AiringInfo, 'c
|
||||
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é
|
||||
// Épisodes diffusés = épisodes des saisons terminées + position du dernier épisode diffusé.
|
||||
// Les épisodes spéciaux (saison 0) ne comptent pas : un spécial diffusé en dernier ramenait
|
||||
// le compte à son numéro (ex. 1). On se fie alors au prochain épisode régulier annoncé.
|
||||
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 before = (season: number) =>
|
||||
(d.seasons ?? []).filter((s) => n0(s.season_number) > 0 && n0(s.season_number) < season).reduce((sum, s) => sum + n0(s.episode_count), 0)
|
||||
if (last && Array.isArray(d.seasons) && d.seasons.length) {
|
||||
if (n0(last.season_number) > 0) aired = n0(before(n0(last.season_number)) + n0(last.episode_number))
|
||||
else if (nx && n0(nx.season_number) > 0 && n0(nx.episode_number) > 0) aired = n0(before(n0(nx.season_number)) + n0(nx.episode_number) - 1)
|
||||
}
|
||||
const nextDate = safeDay(nx?.air_date)
|
||||
// Rien encore diffusé (série annoncée) : les épisodes prévus ne sont pas « sortis »
|
||||
if (!last && (nx || d.status === 'Planned' || d.status === 'In Production')) aired = 0
|
||||
|
||||
+7
-1
@@ -34,6 +34,11 @@ const int = (v: unknown, min = 0, max = 1e6) => {
|
||||
const n = num(v, min, max)
|
||||
return n == null ? undefined : Math.round(n)
|
||||
}
|
||||
/** Année plausible, sinon absente (une valeur aberrante n'est pas ramenée à 1870 ou 2200). */
|
||||
const year = (v: unknown) => {
|
||||
const n = num(v, -Infinity, Infinity)
|
||||
return n != null && n >= 1870 && n <= 2200 ? Math.round(n) : undefined
|
||||
}
|
||||
const rating = (v: unknown) => {
|
||||
const n = num(v, 0, 10)
|
||||
return n == null || n === 0 ? undefined : Math.round(n * 2) / 2
|
||||
@@ -108,7 +113,7 @@ export function normalizeItem(raw: unknown): MediaItem | null {
|
||||
originalTitle: cleanText(r.originalTitle, LIMITS.title),
|
||||
type,
|
||||
subtype: type === 'autre' ? cleanText(r.subtype, LIMITS.shortText) : undefined,
|
||||
year: int(r.year, 1870, 2200),
|
||||
year: year(r.year),
|
||||
status: (STATUS_SET.has(r.status as string) ? r.status : 'a_voir') as WatchStatus,
|
||||
rating: rating(r.rating),
|
||||
criteria,
|
||||
@@ -137,6 +142,7 @@ export function normalizeItem(raw: unknown): MediaItem | null {
|
||||
rewatch: normalizeRewatch(r.rewatch),
|
||||
seasonRatings: normalizeSeasonRatings(r.seasonRatings),
|
||||
episodeLog: normalizeEpisodeLog(r.episodeLog),
|
||||
rewatchLog: normalizeEpisodeLog(r.rewatchLog),
|
||||
publicRating: (() => {
|
||||
const n = num(r.publicRating, 0, 10)
|
||||
return n ? Math.round(n * 10) / 10 : undefined
|
||||
|
||||
+40
-16
@@ -6,7 +6,7 @@ import { subtypeLabel, tmdbGenres } from './genres'
|
||||
import { franchiseKey } from './franchise'
|
||||
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, remoteImage, safeCountries, safeDay, safePosterUrl, safeSeasons, safeStringList } from './security'
|
||||
import { localDay } from './utils'
|
||||
import { parseAniListLinks, parseTmdbProviders, type StreamLink, type WatchRegion } from './watchProviders'
|
||||
import { getWatchRegion, parseAniListLinks, parseTmdbProviders, type StreamLink, type WatchRegion } from './watchProviders'
|
||||
|
||||
/**
|
||||
* Recherche dans les bases publiques :
|
||||
@@ -120,12 +120,21 @@ export function isPlausibleTmdbKey(key: string): boolean {
|
||||
/** Seules ces adresses de l'API TMDB peuvent être appelées. */
|
||||
const TMDB_PATHS = /^\/(search\/(multi|person)|configuration|discover\/(movie|tv)|(movie|tv)\/\d{1,10}(\/recommendations|\/season\/\d{1,3})?|find\/(tt)?\d{1,10}|person\/\d{1,10})$/
|
||||
|
||||
/** Délai max d'une requête vers TMDB / AniList (réseau lent ou serveur muet). */
|
||||
const FETCH_TIMEOUT = 12_000
|
||||
const timeout = () => AbortSignal.timeout(FETCH_TIMEOUT)
|
||||
|
||||
/** Texte recherché : sans caractères de contrôle, et pas plus long que ce qu'accepte le proxy (100 caractères). */
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const searchText = (q: string) => q.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 100)
|
||||
|
||||
/** « 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 (typeof params.query === 'string') params = { ...params, query: searchText(params.query) }
|
||||
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)
|
||||
@@ -137,6 +146,7 @@ async function tmdbFetch<T>(path: string, key: string, params: Record<string, st
|
||||
headers: isBearer ? { Authorization: `Bearer ${k}` } : {},
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
})
|
||||
if (res.status === 401) throw new Error(t('err.tmdbKeyRefused'))
|
||||
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
|
||||
@@ -179,7 +189,7 @@ function tmdbToResult(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null {
|
||||
}
|
||||
|
||||
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' })
|
||||
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: searchText(query), include_adult: 'false' })
|
||||
return (Array.isArray(data.results) ? data.results : [])
|
||||
.filter((r) => r.media_type === 'movie' || r.media_type === 'tv')
|
||||
.slice(0, 15)
|
||||
@@ -275,7 +285,8 @@ export async function getTmdbDetails(result: SearchResult, key: string): Promise
|
||||
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
|
||||
// Même pays que « Où regarder » (choisi à la main, sinon celui du navigateur)
|
||||
const provider = (providers?.[getWatchRegion()] ?? 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
|
||||
@@ -403,11 +414,13 @@ interface AniMedia {
|
||||
genres?: string[]
|
||||
seasonYear?: number | null
|
||||
startDate?: { year?: number | null }
|
||||
title: { romaji?: string | null; english?: string | null; native?: string | null }
|
||||
title?: { romaji?: string | null; english?: string | null; native?: string | null } | null
|
||||
coverImage?: { medium?: string | null; large?: string | null }
|
||||
description?: string | null
|
||||
countryOfOrigin?: string | null
|
||||
averageScore?: number | null
|
||||
/** Demandé seulement par certaines requêtes (recommandations, fiche par id) */
|
||||
isAdult?: boolean
|
||||
}
|
||||
|
||||
const ANILIST_GENRES: Record<string, string> = {
|
||||
@@ -450,6 +463,7 @@ export async function searchAniList(query: string): Promise<SearchResult[]> {
|
||||
body: JSON.stringify({ query: ANILIST_QUERY, variables: { search: query.slice(0, LIMITS.searchQuery) } }),
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
})
|
||||
if (res.status === 429) throw new Error(t('err.anilistRate'))
|
||||
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
|
||||
@@ -462,8 +476,8 @@ export async function searchAniList(query: string): Promise<SearchResult[]> {
|
||||
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 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({
|
||||
@@ -471,7 +485,7 @@ function aniToResult(m: AniMedia): SearchResult | null {
|
||||
externalId: `anilist:${m.id}`,
|
||||
title,
|
||||
originalTitle: original && original !== title ? original : undefined,
|
||||
altTitles: [m.title.romaji, m.title.english, m.title.native].filter((x): x is string => !!x).slice(0, 3),
|
||||
altTitles: [m.title?.romaji, m.title?.english, m.title?.native].filter((x): x is string => !!x).slice(0, 3),
|
||||
year: year ?? undefined,
|
||||
thumb: m.coverImage?.medium ?? undefined,
|
||||
posterUrl: m.coverImage?.large ?? m.coverImage?.medium ?? undefined,
|
||||
@@ -540,18 +554,20 @@ export async function aniListRecommendations(externalId: string): Promise<Search
|
||||
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} } } } } }`,
|
||||
query: `query ($id: Int) { Media(id: $id) { recommendations(sort: RATING_DESC, perPage: 15) { nodes { mediaRecommendation { isAdult ${ANILIST_FIELDS} } } } } }`,
|
||||
variables: { id },
|
||||
}),
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
})
|
||||
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)
|
||||
// Pas de contenu adulte (comme la recherche, qui demande isAdult: false)
|
||||
.filter((m): m is AniMedia => !!m && !m.isAdult)
|
||||
.map(aniToResult)
|
||||
.filter((r): r is SearchResult => r !== null)
|
||||
}
|
||||
@@ -675,6 +691,7 @@ export async function getAniListReleases(ids: number[]): Promise<Map<number, Rel
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
body: JSON.stringify({
|
||||
query:
|
||||
'query ($ids: [Int]) { Page(perPage: 50) { media(id_in: $ids, type: ANIME) { id startDate { year month day } nextAiringEpisode { episode airingAt } } } }',
|
||||
@@ -907,6 +924,7 @@ export async function aniListAiring(from: string, to: string, minPopularity = 40
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
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
|
||||
@@ -968,14 +986,16 @@ export async function getAniListById(externalId: string): Promise<SearchResult |
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
body: JSON.stringify({
|
||||
query: `query ($id: Int) { Media(id: $id, type: ANIME) {${ANILIST_FIELDS} } }`,
|
||||
query: `query ($id: Int) { Media(id: $id, type: ANIME) { isAdult ${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
|
||||
const m = json.data?.Media
|
||||
return m && !m.isAdult ? aniToResult(m) : null
|
||||
}
|
||||
|
||||
/** Résultat « recherche » TMDB minimal à partir d'une sortie (pour l'ajout rapide). */
|
||||
@@ -1060,7 +1080,8 @@ async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras>
|
||||
// Une seule requête pour le casting et « Où regarder ». Si le proxy n'accepte pas encore la combinaison
|
||||
// (fonction serveur pas redéployée), on retombe sur le casting seul.
|
||||
const d = await tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits,watch/providers' }).catch((e: unknown) => {
|
||||
if (key.trim() !== CLOUD_TMDB) throw e
|
||||
// Seul un refus du paramètre (400) justifie le second essai : hors ligne, 429, 5xx… on ne double pas la requête
|
||||
if (key.trim() !== CLOUD_TMDB || !(e instanceof Error) || e.message !== t('err.tmdbStatus', { status: 400 })) throw e
|
||||
return tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
|
||||
})
|
||||
const cast = (Array.isArray(d.credits?.cast) ? d.credits!.cast! : [])
|
||||
@@ -1133,6 +1154,7 @@ async function aniListExtras(externalId: string): Promise<TitleExtras> {
|
||||
body: JSON.stringify({ query: ANILIST_EXTRAS, variables: { id } }),
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: timeout(),
|
||||
})
|
||||
if (res.status === 429) throw new Error(t('err.anilistRate'))
|
||||
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
|
||||
@@ -1175,11 +1197,13 @@ export function getTitleExtras(externalId: string, tmdbKey?: string): Promise<Ti
|
||||
if (!isSafeExternalId(externalId)) return Promise.reject(new Error(t('err.tmdbRef')))
|
||||
const isTmdb = externalId.startsWith('tmdb:')
|
||||
if (isTmdb && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly')))
|
||||
const cached = extrasCache.get(externalId)
|
||||
// La langue fait partie de la clé : changer de langue ne doit pas resservir l'ancienne version
|
||||
const cacheKey = `${externalId}:${tmdbLanguage()}`
|
||||
const cached = extrasCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
const p = isTmdb ? tmdbExtras(externalId, tmdbKey!) : aniListExtras(externalId)
|
||||
extrasCache.set(externalId, p)
|
||||
p.catch(() => extrasCache.delete(externalId))
|
||||
extrasCache.set(cacheKey, p)
|
||||
p.catch(() => extrasCache.delete(cacheKey))
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -1210,7 +1234,7 @@ function tmdbWithPrefill(r: TmdbItem, kind: 'movie' | 'tv'): SearchResult | null
|
||||
|
||||
/** Recherche TMDB (films et séries) avec métadonnées de base, dans l'ordre de pertinence de TMDB. */
|
||||
export async function tmdbImportSearch(query: string, key: string): Promise<SearchResult[]> {
|
||||
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: query.slice(0, 100), include_adult: 'false' })
|
||||
const data = await tmdbFetch<{ results: TmdbItem[] }>('/search/multi', key, { query: searchText(query), include_adult: 'false' })
|
||||
return (Array.isArray(data.results) ? data.results : [])
|
||||
.filter((r) => r && (r.media_type === 'movie' || r.media_type === 'tv'))
|
||||
.slice(0, 20)
|
||||
|
||||
+55
-14
@@ -88,13 +88,25 @@ export const newChallengeId = () => Math.random().toString(36).slice(2, 12).padE
|
||||
|
||||
const LOG_MAX_DAYS = 400
|
||||
|
||||
/** Nouveau journal après un changement du nombre d'épisodes vus (aujourd'hui). */
|
||||
/**
|
||||
* Nouveau journal après un changement du nombre d'épisodes vus (aujourd'hui).
|
||||
* Épisodes décochés : on les retire des jours les plus récents d'abord (sinon cocher 10 un jour,
|
||||
* en décocher 5 le lendemain puis les recocher compterait 15 épisodes).
|
||||
*/
|
||||
export function logEpisodes(log: Record<string, number> | undefined, delta: number, day = localDay()): Record<string, number> | undefined {
|
||||
if (!delta) return log
|
||||
const next = { ...(log ?? {}) }
|
||||
const value = Math.max(0, (next[day] ?? 0) + delta)
|
||||
if (value) next[day] = Math.min(value, 100000)
|
||||
else delete next[day]
|
||||
if (delta > 0) next[day] = Math.min((next[day] ?? 0) + delta, 100000)
|
||||
else {
|
||||
let rest = -delta
|
||||
for (const d of Object.keys(next).sort().reverse()) {
|
||||
if (rest <= 0) break
|
||||
const take = Math.min(rest, next[d])
|
||||
rest -= take
|
||||
if (next[d] - take > 0) next[d] -= take
|
||||
else delete next[d]
|
||||
}
|
||||
}
|
||||
const days = Object.keys(next).sort()
|
||||
for (const d of days.slice(0, Math.max(0, days.length - LOG_MAX_DAYS))) delete next[d]
|
||||
return Object.keys(next).length ? next : undefined
|
||||
@@ -143,12 +155,21 @@ export interface ChallengeProgress {
|
||||
|
||||
const matches = (item: MediaItem, media: Media) => media === 'all' || item.type === media
|
||||
|
||||
/** Nombre compté par jour (pour la date de réussite et le rythme). */
|
||||
/**
|
||||
* Nombre compté par jour (pour la date de réussite et le rythme) : valeurs ponctuelles (`perDay`)
|
||||
* et, pour les estimations réparties sur une période, variations du débit quotidien (`rateDelta`,
|
||||
* +débit au premier jour, −débit le lendemain du dernier) au lieu d'une valeur par jour.
|
||||
*/
|
||||
function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, items: MediaItem[]) {
|
||||
const s = toNum(c.start)
|
||||
const e = toNum(c.end)
|
||||
const perDay = new Map<number, number>()
|
||||
const rateDelta = new Map<number, number>()
|
||||
const add = (day: number, n: number) => perDay.set(day, (perDay.get(day) ?? 0) + n)
|
||||
const addRange = (lo: number, hi: number, rate: number) => {
|
||||
rateDelta.set(lo, (rateDelta.get(lo) ?? 0) + rate)
|
||||
rateDelta.set(hi + 1, (rateDelta.get(hi + 1) ?? 0) - rate)
|
||||
}
|
||||
const entries: CountedEntry[] = []
|
||||
let estimated = false
|
||||
|
||||
@@ -169,7 +190,7 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
|
||||
}
|
||||
|
||||
// Épisodes (les films n'en ont pas)
|
||||
if (!TYPE_BY_VALUE[item.type].episodic || item.episodesWatched <= 0) continue
|
||||
if (!TYPE_BY_VALUE[item.type].episodic || (item.episodesWatched <= 0 && !item.rewatchLog)) continue
|
||||
let amount = 0
|
||||
let last = ''
|
||||
let partEstimated = false
|
||||
@@ -184,10 +205,18 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
|
||||
if (d > last) last = d
|
||||
}
|
||||
}
|
||||
// Épisodes revus : comptés le jour où ils ont été vus, sans toucher à l'estimation du premier visionnage
|
||||
for (const [d, n] of Object.entries(item.rewatchLog ?? {})) {
|
||||
if (d >= c.start && d <= c.end) {
|
||||
amount += n
|
||||
add(toNum(d), n)
|
||||
if (d > last) last = d
|
||||
}
|
||||
}
|
||||
const unlogged = Math.max(0, item.episodesWatched - logged)
|
||||
const from = item.startDate ?? item.endDate
|
||||
if (unlogged > 0 && from) {
|
||||
let to = item.endDate ?? (logDays[0] ? fromNum(toNum(logDays[0]) - 1) : item.updatedAt.slice(0, 10))
|
||||
let to = item.endDate ?? (logDays[0] ? fromNum(toNum(logDays[0]) - 1) : localDay(new Date(item.updatedAt)))
|
||||
if (!safeDay(to) || to < from) to = from
|
||||
const a = toNum(from)
|
||||
const b = toNum(to)
|
||||
@@ -195,7 +224,7 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
|
||||
const hi = Math.min(b, e)
|
||||
if (hi >= lo) {
|
||||
const rate = unlogged / (b - a + 1)
|
||||
for (let d = lo; d <= hi; d++) add(d, rate)
|
||||
addRange(lo, hi, rate)
|
||||
amount += rate * (hi - lo + 1)
|
||||
partEstimated = true
|
||||
const lastEst = fromNum(hi)
|
||||
@@ -207,22 +236,34 @@ function dailyCounts(c: Pick<Challenge, 'media' | 'unit' | 'start' | 'end'>, ite
|
||||
entries.push({ item, date: last, amount: partEstimated ? Math.max(1, Math.round(amount)) : amount, estimated: partEstimated })
|
||||
}
|
||||
}
|
||||
return { perDay, entries, estimated }
|
||||
return { perDay, rateDelta, entries, estimated }
|
||||
}
|
||||
|
||||
export function computeProgress(c: Challenge, items: MediaItem[], today = localDay()): ChallengeProgress {
|
||||
const { perDay, entries, estimated } = dailyCounts(c, items)
|
||||
const { perDay, rateDelta, entries, estimated } = dailyCounts(c, items)
|
||||
const s = toNum(c.start)
|
||||
const e = toNum(c.end)
|
||||
const now = toNum(today)
|
||||
|
||||
// Cumul jour par jour : date de réussite
|
||||
// Cumul jour par jour : date de réussite. Le total affiché est arrondi : l'objectif est atteint
|
||||
// dès que le cumul arrondi y arrive (même règle que `count`, sinon la date ne correspondrait pas).
|
||||
const goal = c.target - 0.5 - 1e-6
|
||||
let total = 0
|
||||
let rate = 0
|
||||
let next: number | undefined // premier jour pas encore compté
|
||||
let doneAt: string | undefined
|
||||
const days = [...perDay.keys()].sort((a, b) => a - b)
|
||||
const days = [...new Set([...perDay.keys(), ...rateDelta.keys()])].sort((a, b) => a - b)
|
||||
for (const d of days) {
|
||||
total += perDay.get(d)!
|
||||
if (!doneAt && total + 1e-6 >= c.target) doneAt = fromNum(d)
|
||||
// Jours sans événement depuis le précédent : seul le débit estimé s'ajoute
|
||||
if (next !== undefined && d > next && rate > 1e-12) {
|
||||
const span = d - next
|
||||
if (!doneAt && total + rate * span >= goal) doneAt = fromNum(next + Math.max(1, Math.ceil((goal - total) / rate)) - 1)
|
||||
total += rate * span
|
||||
}
|
||||
rate += rateDelta.get(d) ?? 0
|
||||
total += (perDay.get(d) ?? 0) + Math.max(0, rate)
|
||||
if (!doneAt && total >= goal) doneAt = fromNum(d)
|
||||
next = d + 1
|
||||
}
|
||||
const count = Math.round(total)
|
||||
const done = count >= c.target
|
||||
|
||||
+36
-8
@@ -1,19 +1,37 @@
|
||||
import { t } from '../../i18n'
|
||||
import { AuthError, getAccessToken } from './auth'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
|
||||
import { AuthError, getAccessToken, getSession } from './auth'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL, TimeoutError, withTimeout } from './config'
|
||||
|
||||
/** fetch avec un délai maximal (le serveur qui ne répond pas ne bloque jamais l'app). */
|
||||
async function timedFetch(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
try {
|
||||
// Délai proportionnel à la taille de l'envoi (photo, grosse synchro sur une connexion lente : ~5 Ko/s minimum),
|
||||
// et long pour la suppression de compte (le serveur efface tout avant de répondre)
|
||||
const bytes = init.body instanceof Blob ? init.body.size : typeof init.body === 'string' ? init.body.length : 0
|
||||
const ms = url.includes('/functions/v1/delete-account') ? 120_000 : Math.max(20_000, 20_000 + bytes / 5)
|
||||
return await withTimeout((signal) => fetch(url, { ...init, signal }), init.signal, ms)
|
||||
} catch (e) {
|
||||
if (e instanceof TimeoutError) throw new Error(t('common.offline'))
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
let failed: string | undefined
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const token = await getAccessToken(attempt > 0)
|
||||
// Après un refus : on ne force le renouvellement que si le jeton refusé est toujours le jeton courant
|
||||
// (plusieurs appels refusés en même temps ne déclenchent qu'un renouvellement, les autres reprennent le nouveau)
|
||||
const token = await getAccessToken(failed !== undefined && getSession()?.accessToken === failed)
|
||||
if (!token) throw new AuthError(t('auth.err.session'))
|
||||
const res = await fetch(SUPABASE_URL + path, {
|
||||
const res = await timedFetch(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
|
||||
failed = token
|
||||
}
|
||||
throw new AuthError(t('auth.err.session'))
|
||||
}
|
||||
@@ -24,7 +42,7 @@ export async function tmdbViaCloud<T>(path: string, params: Record<string, strin
|
||||
// Sans compte (mode découverte) : appel anonyme, limité côté serveur par adresse IP
|
||||
const res = (await getAccessToken())
|
||||
? await cloudFetch(`/functions/v1/tmdb?${q}`)
|
||||
: await fetch(`${SUPABASE_URL}/functions/v1/tmdb?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
: await timedFetch(`${SUPABASE_URL}/functions/v1/tmdb?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
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>
|
||||
@@ -36,14 +54,24 @@ export type ProxyState = 'ok' | 'missing-key' | 'not-deployed' | 'offline' | 'er
|
||||
export async function checkTmdbProxy(): Promise<ProxyState> {
|
||||
if (!navigator.onLine) return 'offline'
|
||||
try {
|
||||
const res = await cloudFetch(`/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`)
|
||||
const path = `/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`
|
||||
let res: Response
|
||||
try {
|
||||
res = await cloudFetch(path)
|
||||
} catch (e) {
|
||||
// Pas de session valable : ce n'est pas le proxy qui manque, on le teste sans compte (comme la recherche)
|
||||
if (!(e instanceof AuthError)) throw e
|
||||
res = await timedFetch(SUPABASE_URL + path, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
}
|
||||
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'
|
||||
} catch (e) {
|
||||
if (!navigator.onLine) return 'offline'
|
||||
// Échec réseau (fonction absente) ; un serveur qui ne répond pas à temps n'est pas « non déployé »
|
||||
return e instanceof TypeError ? 'not-deployed' : 'error'
|
||||
}
|
||||
}
|
||||
+98
-28
@@ -1,5 +1,5 @@
|
||||
import { t, type TKey } from '../../i18n'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL, withTimeout } from './config'
|
||||
import { isPwnedPassword } from '../pwned'
|
||||
|
||||
/**
|
||||
@@ -108,17 +108,21 @@ const msg = (code: string) => (CODE_KEYS[code] ? t(CODE_KEYS[code], { n: PASSWOR
|
||||
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',
|
||||
})
|
||||
// Délai maximal : sans réponse, on fait comme hors-ligne plutôt que d'attendre indéfiniment
|
||||
res = await withTimeout((signal) =>
|
||||
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',
|
||||
signal,
|
||||
}),
|
||||
)
|
||||
} catch {
|
||||
throw new Error(t('common.offline'))
|
||||
}
|
||||
@@ -131,8 +135,7 @@ async function gotrue(path: string, init: { method?: string; body?: unknown; tok
|
||||
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
|
||||
;(err as AuthError & { status: number }).status = res.status
|
||||
throw err
|
||||
}
|
||||
return data
|
||||
@@ -160,8 +163,9 @@ export async function signIn(email: string, password: string): Promise<void> {
|
||||
setSession(s)
|
||||
}
|
||||
|
||||
/** Crée un compte. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). */
|
||||
/** Inscription. Le pseudo choisi est repris par la base à la création du profil (s'il est libre). */
|
||||
/**
|
||||
* Inscription. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). Le pseudo choisi est repris par la base à la création du profil (s'il est libre).
|
||||
*/
|
||||
export async function signUp(email: string, password: string, username?: string): Promise<boolean> {
|
||||
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
|
||||
if (await isPwnedPassword(password)) throw new AuthError(t('auth.err.pwned'))
|
||||
@@ -190,7 +194,17 @@ export async function updatePassword(password: string): Promise<void> {
|
||||
|
||||
/** 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
|
||||
let s = current
|
||||
// Jeton d'accès expiré (ou presque) : on tente d'abord de le renouveler, sinon le serveur refuserait
|
||||
// la déconnexion et la session resterait ouverte côté serveur. Effacée sur l'appareil quoi qu'il arrive.
|
||||
if (s && navigator.onLine && s.expiresAt - 60_000 <= Date.now()) {
|
||||
try {
|
||||
const next = await refresh()
|
||||
if (next && next.user.id === s.user.id) s = next
|
||||
} catch {
|
||||
/* au mieux */
|
||||
}
|
||||
}
|
||||
setSession(null)
|
||||
if (s && navigator.onLine) {
|
||||
try {
|
||||
@@ -226,17 +240,34 @@ export async function signInWithGoogle(): Promise<void> {
|
||||
location.assign(`${SUPABASE_URL}/auth/v1/authorize?${params}`)
|
||||
}
|
||||
|
||||
/** Retour de Google : adresse avec ?code=… (ou ?error=…). */
|
||||
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search)
|
||||
/** Vérificateur gardé pendant l'aller-retour vers Google (null s'il n'y en a pas). */
|
||||
function readVerifier(): { verifier?: unknown; at?: unknown } | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(VERIFIER_KEY)
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : null
|
||||
return parsed && typeof parsed === 'object' ? (parsed as { verifier?: unknown; at?: unknown }) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retour de Google : adresse avec ?code=… (ou ?error=…), seulement si une connexion Google a été lancée
|
||||
* depuis cet appareil (vérificateur présent) — une autre adresse avec ?code= n'est pas un retour de Google.
|
||||
*/
|
||||
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search) && readVerifier() !== null
|
||||
|
||||
async function consumeOAuthRedirect(): Promise<{ error?: string }> {
|
||||
const params = new URLSearchParams(location.search)
|
||||
const code = params.get('code') ?? ''
|
||||
const oauthError = params.get('error_description') ?? params.get('error')
|
||||
history.replaceState(null, '', `${location.pathname}#/`)
|
||||
let saved: { verifier?: string; at?: number } = {}
|
||||
const stored = readVerifier()
|
||||
const saved = {
|
||||
verifier: typeof stored?.verifier === 'string' ? stored.verifier : undefined,
|
||||
at: typeof stored?.at === 'number' ? stored.at : undefined,
|
||||
}
|
||||
try {
|
||||
saved = JSON.parse(localStorage.getItem(VERIFIER_KEY) ?? '{}')
|
||||
localStorage.removeItem(VERIFIER_KEY)
|
||||
} catch {
|
||||
/* ignore */
|
||||
@@ -260,26 +291,65 @@ async function consumeOAuthRedirect(): Promise<{ error?: string }> {
|
||||
|
||||
let refreshing: Promise<Session | null> | null = null
|
||||
|
||||
/**
|
||||
* Session plus récente laissée par un autre onglet (même compte, jeton de renouvellement différent,
|
||||
* ou nouveau jeton d'accès encore valable) : à reprendre plutôt que de renouveler avec un jeton périmé.
|
||||
*/
|
||||
function newerStored(s: Session): Session | null {
|
||||
const stored = load()
|
||||
if (!stored || stored.user.id !== s.user.id) return null
|
||||
// Seulement une session plus récente que la nôtre (si notre propre écriture avait échoué, le stockage est en retard)
|
||||
if (stored.expiresAt <= s.expiresAt) return null
|
||||
if (stored.refreshToken !== s.refreshToken) return stored
|
||||
if (stored.accessToken !== s.accessToken && stored.expiresAt - 60_000 > Date.now()) return stored
|
||||
return null
|
||||
}
|
||||
|
||||
async function refresh(): Promise<Session | null> {
|
||||
const s = current
|
||||
if (!s) return null
|
||||
if (!current) return null
|
||||
refreshing ??= (async () => {
|
||||
const s = current
|
||||
if (!s) return null
|
||||
// Un autre onglet a peut-être déjà renouvelé la session (le jeton de renouvellement ne sert qu'une fois)
|
||||
const adopted = newerStored(s)
|
||||
if (adopted) {
|
||||
setSession(adopted)
|
||||
return adopted
|
||||
}
|
||||
const sent = s.refreshToken
|
||||
try {
|
||||
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: s.refreshToken } })
|
||||
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: sent } })
|
||||
const next = toSession(data)
|
||||
// Déconnexion (ou autre compte) pendant le renouvellement : on ne ressuscite pas l'ancienne session
|
||||
if (!next || next.user.id !== s.user.id || current?.user.id !== s.user.id) return null
|
||||
// Session plus récente entre-temps (nouvelle connexion, autre onglet) : on ne l'écrase pas
|
||||
if (current.refreshToken !== sent) return current
|
||||
setSession(next)
|
||||
return next
|
||||
} catch (e) {
|
||||
// Un autre onglet a renouvelé pendant ce temps : notre jeton était simplement périmé
|
||||
if (current?.user.id === s.user.id && current.refreshToken !== sent) return current
|
||||
const adoptedLate = newerStored(s)
|
||||
if (adoptedLate && current?.user.id === s.user.id) {
|
||||
setSession(adoptedLate)
|
||||
return adoptedLate
|
||||
}
|
||||
// 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) && current?.user.id === s.user.id) setSession(null)
|
||||
const stored = load()
|
||||
if (
|
||||
(status === 400 || status === 401 || status === 403) &&
|
||||
current?.user.id === s.user.id &&
|
||||
current.refreshToken === sent &&
|
||||
(!stored || stored.refreshToken === sent)
|
||||
) {
|
||||
setSession(null)
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
refreshing = null
|
||||
}
|
||||
})()
|
||||
})().finally(() => {
|
||||
refreshing = null
|
||||
})
|
||||
return refreshing
|
||||
}
|
||||
|
||||
|
||||
@@ -17,3 +17,35 @@ export const cloudEnabled = !!(SUPABASE_URL && SUPABASE_ANON_KEY)
|
||||
if (!cloudEnabled && (rawUrl || rawKey)) {
|
||||
console.warn('[Kino] .env incomplet ou invalide : les comptes sont désactivés (mode local). Vérifie VITE_SUPABASE_URL et VITE_SUPABASE_ANON_KEY.')
|
||||
}
|
||||
|
||||
/** Délai maximal d'attente d'une réponse du serveur (la déconnexion ou la synchro ne doivent jamais rester bloquées). */
|
||||
export const CLOUD_TIMEOUT_MS = 20_000
|
||||
|
||||
/**
|
||||
* Lance `run` avec un signal qui s'interrompt au bout de `ms` (ou si `signal`, celui de l'appelant, s'interrompt).
|
||||
* Le délai ne court que jusqu'à l'arrivée des en-têtes : la lecture d'une longue réponse n'est pas coupée.
|
||||
* `timedOut()` indique si c'est le délai (et non l'appelant) qui a interrompu l'appel.
|
||||
*/
|
||||
export async function withTimeout<T>(run: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal | null, ms = CLOUD_TIMEOUT_MS): Promise<T> {
|
||||
const ctrl = new AbortController()
|
||||
let expired = false
|
||||
const onAbort = () => ctrl.abort(signal?.reason)
|
||||
if (signal?.aborted) ctrl.abort(signal.reason)
|
||||
else signal?.addEventListener('abort', onAbort, { once: true })
|
||||
const timer = setTimeout(() => {
|
||||
expired = true
|
||||
ctrl.abort()
|
||||
}, ms)
|
||||
try {
|
||||
return await run(ctrl.signal)
|
||||
} catch (e) {
|
||||
if (expired) throw new TimeoutError()
|
||||
throw e
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
}
|
||||
}
|
||||
|
||||
/** Le serveur n'a pas répondu à temps. */
|
||||
export class TimeoutError extends Error {}
|
||||
+15
-15
@@ -28,15 +28,8 @@ export const REPORT_DETAILS_MAX = 500
|
||||
export const BUG_DESCRIPTION_MIN = 10
|
||||
export const BUG_DESCRIPTION_MAX = 2000
|
||||
|
||||
/** Erreur renvoyée par le serveur, avec son code court (« rate limited », « not found »…). */
|
||||
export class ModerationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly code: string,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
/** Erreur renvoyée par le serveur (message déjà traduit). */
|
||||
export class ModerationError extends Error {}
|
||||
|
||||
async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
|
||||
@@ -49,7 +42,7 @@ async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise
|
||||
const code = typeof body.message === 'string' ? body.message.slice(0, 40) : `http ${res.status}`
|
||||
const msg =
|
||||
code === 'rate limited' ? t('report.errRate') : code === 'not found' ? t('report.errNotFound') : res.status === 404 ? t('report.errUnavailable') : t('social.err.server', { status: res.status })
|
||||
throw new ModerationError(msg, code)
|
||||
throw new ModerationError(msg)
|
||||
}
|
||||
const text = await res.text()
|
||||
return (text ? JSON.parse(text) : null) as T
|
||||
@@ -88,13 +81,18 @@ const listeners = new Set<() => void>()
|
||||
const emit = () => listeners.forEach((fn) => fn())
|
||||
|
||||
/** Charge (une fois par session) la liste des comptes que j'ai bloqués. Silencieux si le serveur n'est pas à jour. */
|
||||
export function loadBlocks(force = false): Promise<void> {
|
||||
export function loadBlocks(): Promise<void> {
|
||||
const uid = getSession()?.user.id
|
||||
if (loaded && !force && loadedFor === uid) return loaded
|
||||
if (loaded && loadedFor === uid) return loaded
|
||||
if (loadedFor !== uid) blocked = []
|
||||
loadedFor = uid
|
||||
loaded = rpc<unknown>('my_blocks')
|
||||
const p: Promise<void> = rpc<unknown>('my_blocks')
|
||||
.then((rows) => {
|
||||
// Réponse arrivée après un changement de compte : elle ne concerne plus le compte ouvert
|
||||
if (loadedFor !== uid || getSession()?.user.id !== uid) {
|
||||
if (loaded === p) loaded = null
|
||||
return
|
||||
}
|
||||
blocked = (Array.isArray(rows) ? rows : []).flatMap((r) => {
|
||||
if (!isPlainObject(r) || typeof r.id !== 'string' || !UUID.test(r.id)) return []
|
||||
const username = cleanText(r.username, 20) ?? ''
|
||||
@@ -103,9 +101,11 @@ export function loadBlocks(force = false): Promise<void> {
|
||||
emit()
|
||||
})
|
||||
.catch(() => {
|
||||
/* fonction pas encore déployée / hors-ligne : rien n'est masqué */
|
||||
/* fonction pas encore déployée / hors-ligne : rien n'est masqué, on réessaiera au prochain affichage */
|
||||
if (loaded === p) loaded = null
|
||||
})
|
||||
return loaded
|
||||
loaded = p
|
||||
return p
|
||||
}
|
||||
|
||||
export const isBlocked = (userId: string | undefined | null) => !!userId && loadedFor === getSession()?.user.id && blocked.some((b) => b.id === userId)
|
||||
|
||||
+31
-9
@@ -162,16 +162,32 @@ export async function getMyProfile(): Promise<Profile | null> {
|
||||
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 }))
|
||||
/** Nombre de lignes renvoyées par le serveur (avant le tri des lignes invalides) : sert au décalage de la page suivante. */
|
||||
const rawCount = (v: unknown) => (Array.isArray(v) ? v.length : 0)
|
||||
|
||||
export const PROFILE_ITEMS_PAGE = 48
|
||||
|
||||
/** Une page de la bibliothèque d'un profil. `received` : lignes reçues du serveur (pour la page suivante). */
|
||||
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<{ items: MediaItem[]; received: number }> {
|
||||
if (!UUID.test(userId)) return { items: [], received: 0 }
|
||||
const raw = await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: PROFILE_ITEMS_PAGE })
|
||||
return { items: toItems(raw), received: rawCount(raw) }
|
||||
}
|
||||
|
||||
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 []
|
||||
export const FEED_PAGE = 30
|
||||
|
||||
/**
|
||||
* Une page du fil. `received` : lignes reçues du serveur ; `cursor` : date de la dernière ligne reçue
|
||||
* (même invalide), d'où repartir pour la page suivante.
|
||||
*/
|
||||
export async function getFeed(before?: string): Promise<{ entries: FeedEntry[]; received: number; cursor?: string }> {
|
||||
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: FEED_PAGE })
|
||||
if (!Array.isArray(raw)) return { entries: [], received: 0 }
|
||||
const out: FeedEntry[] = []
|
||||
let cursor: string | undefined
|
||||
for (const r of raw.slice(0, 50)) {
|
||||
// Date brute du serveur (précision à la microseconde) : rien n'est sauté ni répété d'une page à l'autre
|
||||
if (isPlainObject(r) && safeIso(r.created_at)) cursor = r.created_at as string
|
||||
if (!isPlainObject(r) || !isPlainObject(r.user)) continue
|
||||
const item = othersItem(r.item)
|
||||
const name = username(r.user.username)
|
||||
@@ -186,14 +202,20 @@ export async function getFeed(before?: string): Promise<FeedEntry[]> {
|
||||
item,
|
||||
})
|
||||
}
|
||||
return out
|
||||
return { entries: out, received: raw.length, cursor }
|
||||
}
|
||||
|
||||
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 })) : []
|
||||
/** Le serveur renvoie au plus 50 comptes à la fois */
|
||||
export const FOLLOW_PAGE = 50
|
||||
/** Une page d'abonnés / d'abonnements. `received` : lignes reçues du serveur (pour la page suivante). */
|
||||
export async function getFollowList(userId: string, kind: 'followers' | 'following', offset = 0): Promise<{ cards: ProfileCard[]; received: number }> {
|
||||
if (!UUID.test(userId)) return { cards: [], received: 0 }
|
||||
const raw = await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })
|
||||
return { cards: toCards(raw), received: rawCount(raw) }
|
||||
}
|
||||
export const getFollowRequests = async () => toCards(await rpc('get_follow_requests'))
|
||||
|
||||
// ─── Abonnements ───
|
||||
|
||||
+176
-46
@@ -1,10 +1,10 @@
|
||||
import { t } from '../../i18n'
|
||||
import type { CustomList, MediaItem, Settings } from '../../types'
|
||||
import { normalizeItem, normalizeLists, normalizeSettings } from '../backup'
|
||||
import { mediaDB, onMediaChange } from '../db'
|
||||
import { mediaDB, onMediaChange, type RemoteDecision } from '../db'
|
||||
import { blobToPosterDataURL } from '../image'
|
||||
import { isPlainObject, isSafeId, safeIso } from '../security'
|
||||
import { scopedKey } from '../scope'
|
||||
import { getScope, scopedKey } from '../scope'
|
||||
import { cloudFetch } from './api'
|
||||
|
||||
/**
|
||||
@@ -42,12 +42,48 @@ interface SyncMeta {
|
||||
}
|
||||
|
||||
const PAGE = 500
|
||||
/** Limite d'une fiche côté serveur : 400 000 octets (texte jsonb, un peu plus long que JSON.stringify) → marge. */
|
||||
const MAX_ROW_BYTES = 380_000
|
||||
const MAX_BATCH_BYTES = 1_500_000
|
||||
const OVERLAP_MS = 60_000
|
||||
|
||||
const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
|
||||
/** Taille réelle en octets (UTF-8 : un accent ou un emoji compte pour plusieurs). */
|
||||
const encoder = new TextEncoder()
|
||||
const byteSize = (v: unknown) => encoder.encode(JSON.stringify(v)).length
|
||||
|
||||
/** Data URL → Blob sans fetch (la CSP n'autorise pas `data:` en connect-src). */
|
||||
function dataURLToBlob(url: string): Blob {
|
||||
const comma = url.indexOf(',')
|
||||
const head = url.slice(0, comma)
|
||||
const body = url.slice(comma + 1)
|
||||
const type = head.slice(5).split(';')[0] || 'application/octet-stream'
|
||||
if (!/;base64$/i.test(head)) return new Blob([decodeURIComponent(body)], { type })
|
||||
const bin = atob(body)
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
return new Blob([bytes], { type })
|
||||
}
|
||||
|
||||
/** Refus du serveur propre à une ligne (et non session expirée, limite de débit…) : inutile de la renvoyer. */
|
||||
const isRowRejected = (e: PushError) =>
|
||||
e.status >= 400 && e.status < 500 && ![401, 403, 404, 408, 429].includes(e.status) &&
|
||||
// Quota du compte atteint : ce n'est pas la fiche qui pose problème, on la garde en attente (elle partira plus tard)
|
||||
!/quota/i.test(e.detail)
|
||||
|
||||
/** Erreur d'envoi, avec le code HTTP. */
|
||||
class PushError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly detail = '',
|
||||
) {
|
||||
super(t('sync.err.push', { status }))
|
||||
}
|
||||
}
|
||||
|
||||
const maxIso = (a?: string, b?: string) => (a && b ? (a > b ? a : b) : (a ?? b))
|
||||
|
||||
export interface SyncEngine {
|
||||
start: () => void
|
||||
stop: () => void
|
||||
@@ -84,14 +120,51 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
}
|
||||
|
||||
let meta = loadMeta()
|
||||
const saveMeta = () => {
|
||||
/** Entrées de la boîte d'envoi envoyées par cet onglet (clé → horodatage envoyé). */
|
||||
const sent = new Map<string, string>()
|
||||
|
||||
/** Toujours le même compte, pas déconnecté : sinon on n'écrit plus rien sur l'appareil. */
|
||||
const alive = () => !stopped && getScope() === userId
|
||||
|
||||
/**
|
||||
* Un autre onglet du même compte partage cette boîte d'envoi : on relit ce qui est enregistré et on
|
||||
* fusionne (sans écraser ses entrées en attente, sans ressusciter celles que cet onglet a envoyées).
|
||||
*/
|
||||
const mergeStored = () => {
|
||||
const stored = loadMeta()
|
||||
for (const [k, v] of Object.entries(stored.outbox)) {
|
||||
if (sent.get(k) === v) continue
|
||||
if (!meta.outbox[k] || meta.outbox[k] < v) meta.outbox[k] = v
|
||||
}
|
||||
meta.itemsCursor = maxIso(meta.itemsCursor, stored.itemsCursor)
|
||||
meta.listsCursor = maxIso(meta.listsCursor, stored.listsCursor)
|
||||
meta.settingsAt = maxIso(meta.settingsAt, stored.settingsAt)
|
||||
meta.lastSyncAt = maxIso(meta.lastSyncAt, stored.lastSyncAt)
|
||||
}
|
||||
|
||||
const saveMeta = (cursors?: Pick<SyncMeta, 'itemsCursor' | 'listsCursor'>) => {
|
||||
if (!alive()) return
|
||||
try {
|
||||
mergeStored()
|
||||
// Curseur volontairement reculé (fiches à relire) : il ne doit pas être ré-avancé par la fusion
|
||||
if (cursors) Object.assign(meta, cursors)
|
||||
localStorage.setItem(META_KEY, JSON.stringify(meta))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/** Retire de la boîte d'envoi ce qui vient de partir (sauf si re-modifié entre-temps). */
|
||||
const done = (keys: string[], snapshot: Record<string, string>) => {
|
||||
for (const k of keys) {
|
||||
if (meta.outbox[k] !== snapshot[k]) continue
|
||||
delete meta.outbox[k]
|
||||
sent.set(k, snapshot[k])
|
||||
}
|
||||
saveMeta()
|
||||
setStatus({})
|
||||
}
|
||||
|
||||
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>) => {
|
||||
@@ -110,38 +183,68 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
|
||||
/** 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 (byteSize(item) <= MAX_ROW_BYTES) return item
|
||||
if (item.poster?.startsWith('data:image')) {
|
||||
try {
|
||||
const blob = await (await fetch(item.poster)).blob()
|
||||
const blob = dataURLToBlob(item.poster)
|
||||
const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) }
|
||||
if (JSON.stringify(smaller).length <= MAX_ROW_BYTES) return smaller
|
||||
if (byteSize(smaller) <= 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 }
|
||||
return byteSize(stripped) <= 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 }[]) {
|
||||
type UpRow = { id: string; data: unknown; deleted: boolean; updated_at: string }
|
||||
|
||||
async function send(table: 'items' | 'lists', rows: UpRow[]) {
|
||||
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(rows.map((r) => ({ ...r, user_id: userId }))),
|
||||
})
|
||||
if (!res.ok) throw new PushError(res.status, (await res.text().catch(() => '')).slice(0, 500))
|
||||
}
|
||||
|
||||
/** Envoi par paquets ; chaque paquet accepté est aussitôt retiré de la boîte d'envoi (`sentRows`). */
|
||||
async function upsert(table: 'items' | 'lists', rows: UpRow[], sentRows: (rows: UpRow[]) => void) {
|
||||
// Envoi par paquets de taille raisonnable
|
||||
let batch: typeof rows = []
|
||||
let batch: UpRow[] = []
|
||||
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 }))
|
||||
const current = batch
|
||||
batch = []
|
||||
size = 0
|
||||
try {
|
||||
await send(table, current)
|
||||
} catch (e) {
|
||||
if (!(e instanceof PushError) || !isRowRejected(e)) throw e
|
||||
// Paquet refusé : on renvoie ligne par ligne, une fiche invalide ne bloque pas les autres
|
||||
for (const r of current) {
|
||||
let status = e.status
|
||||
try {
|
||||
if (current.length > 1) {
|
||||
await send(table, [r])
|
||||
sentRows([r])
|
||||
continue
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof PushError) || !isRowRejected(err)) throw err
|
||||
status = err.status
|
||||
}
|
||||
console.warn(`[sync] ${table}/${r.id} refusé par le serveur (${status}), ignoré`)
|
||||
sentRows([r])
|
||||
}
|
||||
return
|
||||
}
|
||||
sentRows(current)
|
||||
}
|
||||
for (const r of rows) {
|
||||
const bytes = JSON.stringify(r).length
|
||||
const bytes = byteSize(r)
|
||||
if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush()
|
||||
batch.push(r)
|
||||
size += bytes
|
||||
@@ -150,13 +253,15 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
}
|
||||
|
||||
async function push() {
|
||||
// Entrées ajoutées par un autre onglet du même compte : envoyées aussi
|
||||
if (alive()) mergeStored()
|
||||
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 = []
|
||||
const rows: UpRow[] = []
|
||||
for (const id of itemIds) {
|
||||
const item = await mediaDB.get(id)
|
||||
if (item) {
|
||||
@@ -166,7 +271,7 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] })
|
||||
}
|
||||
}
|
||||
await upsert('items', rows)
|
||||
await upsert('items', rows, (sentRows) => done(sentRows.map((r) => `i:${r.id}`), snapshot))
|
||||
}
|
||||
|
||||
const listIds = keys.filter((k) => k.startsWith('l:')).map((k) => k.slice(2))
|
||||
@@ -178,6 +283,7 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
const l = current.get(id)
|
||||
return { id, data: l ?? null, deleted: !l, updated_at: snapshot[`l:${id}`] }
|
||||
}),
|
||||
(sentRows) => done(sentRows.map((r) => `l:${r.id}`), snapshot),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -187,13 +293,11 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
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
|
||||
if (!res.ok) throw new PushError(res.status)
|
||||
meta.settingsAt = maxIso(meta.settingsAt, snapshot.s)
|
||||
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
|
||||
done(['s'], snapshot)
|
||||
}
|
||||
|
||||
// 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 ───
|
||||
@@ -222,39 +326,61 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
return { rows, cursor: last }
|
||||
}
|
||||
|
||||
/**
|
||||
* Curseur après une réception : les lignes ignorées car une modification locale était en attente sont
|
||||
* relues la prochaine fois (si l'envoi local est refusé par le serveur — version distante plus récente —,
|
||||
* c'est elle qu'il faudra récupérer).
|
||||
*/
|
||||
const heldCursor = (cursor: string | undefined, held: string[]) => {
|
||||
const first = held.length ? held.reduce((a, b) => (a < b ? a : b)) : undefined
|
||||
return first && (!cursor || first < cursor) ? first : undefined
|
||||
}
|
||||
|
||||
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
|
||||
if (!alive()) return
|
||||
const remote = new Map<string, Row>()
|
||||
for (const r of rows) remote.set(r.id, r) // la plus récente (ordre du serveur) l'emporte
|
||||
const held: string[] = []
|
||||
// Décision prise dans la transaction d'écriture (une seule pour toutes les fiches) : la boîte d'envoi
|
||||
// et la version locale sont relues au dernier moment, une modification faite pendant la réception gagne.
|
||||
const decide = (id: string, local: MediaItem | undefined): RemoteDecision => {
|
||||
const r = remote.get(id)!
|
||||
if (!alive()) return null
|
||||
if (meta.outbox[`i:${id}`]) {
|
||||
held.push(r.server_updated_at) // modification locale en attente : elle passera en priorité
|
||||
return null
|
||||
}
|
||||
if (r.deleted) return local ? 'remove' : null
|
||||
const item = normalizeItem(r.data)
|
||||
if (!item || item.id !== r.id) continue
|
||||
if (local && local.updatedAt > item.updatedAt) continue
|
||||
if (!item || item.id !== id) return null
|
||||
if (local && local.updatedAt > item.updatedAt) return null
|
||||
// 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)
|
||||
if (local && JSON.stringify(local) === JSON.stringify(item)) return null
|
||||
return { put: item }
|
||||
}
|
||||
await mediaDB.putMany(toPut, { silent: true })
|
||||
await mediaDB.removeMany(toRemove, { silent: true })
|
||||
const change = await mediaDB.mergeRemote([...remote.keys()], decide)
|
||||
if (!alive()) return
|
||||
meta.itemsCursor = safeIso(cursor)
|
||||
saveMeta()
|
||||
if (toPut.length || toRemove.length) hooks.itemsChanged()
|
||||
const back = heldCursor(meta.itemsCursor, held)
|
||||
if (back) meta.itemsCursor = back
|
||||
saveMeta(back ? { itemsCursor: back } : undefined)
|
||||
if (change.put.length || change.removed.length) hooks.itemsChanged()
|
||||
}
|
||||
|
||||
async function pullLists() {
|
||||
const { rows, cursor } = await fetchChanges('lists', meta.listsCursor)
|
||||
if (!alive()) return
|
||||
const held: string[] = []
|
||||
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 (meta.outbox[`l:${r.id}`]) {
|
||||
held.push(r.server_updated_at)
|
||||
continue
|
||||
}
|
||||
if (r.deleted) {
|
||||
changed = map.delete(r.id) || changed
|
||||
continue
|
||||
@@ -268,7 +394,9 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)))
|
||||
}
|
||||
meta.listsCursor = safeIso(cursor)
|
||||
saveMeta()
|
||||
const back = heldCursor(meta.listsCursor, held)
|
||||
if (back) meta.listsCursor = back
|
||||
saveMeta(back ? { listsCursor: back } : undefined)
|
||||
}
|
||||
|
||||
async function pullSettings() {
|
||||
@@ -279,6 +407,8 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
const at = safeIso(row?.updated_at)
|
||||
if (!row || !at || (meta.settingsAt && at <= meta.settingsAt)) return
|
||||
const s = normalizeSettings(row.data)
|
||||
if (!alive()) return
|
||||
// Les appareils à jour envoient toujours la liste des mois masqués ([] = aucun) ; absente = ancienne version, on n'y touche pas
|
||||
if (s) hooks.applySettings(s)
|
||||
meta.settingsAt = at
|
||||
saveMeta()
|
||||
@@ -306,12 +436,12 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
} catch (e) {
|
||||
pushError = e
|
||||
}
|
||||
// Déconnexion pendant la synchro : on n'écrit plus rien dans la base de cet utilisateur
|
||||
if (stopped) return
|
||||
// Déconnexion (ou changement de compte) pendant la synchro : on n'écrit plus rien sur l'appareil
|
||||
if (!alive()) return
|
||||
await pullItems()
|
||||
if (stopped) return
|
||||
if (!alive()) return
|
||||
await pullLists()
|
||||
if (stopped) return
|
||||
if (!alive()) return
|
||||
await pullSettings()
|
||||
if (pushError) throw pushError
|
||||
meta.lastSyncAt = new Date().toISOString()
|
||||
|
||||
+197
-31
@@ -1,5 +1,5 @@
|
||||
import type { MediaItem } from '../types'
|
||||
import { dbNameFor, getScope } from './scope'
|
||||
import { dbNameFor, getScope, scopeEpoch } from './scope'
|
||||
|
||||
/**
|
||||
* Mini-wrapper IndexedDB sans dépendance.
|
||||
@@ -10,6 +10,34 @@ const STORE = 'media'
|
||||
|
||||
let dbPromise: Promise<IDBDatabase> | null = null
|
||||
let dbName = ''
|
||||
/** Base ouverte en cache (pour l'oublier si le navigateur la ferme) */
|
||||
let opened: IDBDatabase | null = null
|
||||
|
||||
/** Bases supprimées → « époque » de l'espace et heure de la suppression (voir isWiped). */
|
||||
const wiped = new Map<string, { epoch: number; at: number }>()
|
||||
/** Une écriture tardive arrive dans les secondes qui suivent ; au-delà (reconnexion…), la base peut renaître. */
|
||||
const WIPE_GUARD_MS = 15_000
|
||||
const markWiped = (name: string) => wiped.set(name, { epoch: scopeEpoch(), at: Date.now() })
|
||||
|
||||
/**
|
||||
* Une écriture tardive (synchro, onglet resté ouvert…) juste après une déconnexion ne doit pas
|
||||
* recréer la base supprimée : tant que l'espace n'a pas changé depuis la suppression, elle reste fermée.
|
||||
*/
|
||||
function isWiped(name: string): boolean {
|
||||
const w = wiped.get(name)
|
||||
if (!w) return false
|
||||
if (w.epoch === scopeEpoch() && Date.now() - w.at < WIPE_GUARD_MS) return true
|
||||
wiped.delete(name) // l'espace a changé depuis, ou la suppression est ancienne : la base peut renaître normalement
|
||||
return false
|
||||
}
|
||||
|
||||
/** Oublie la base en cache si c'est celle-ci (fermée par le navigateur ou par un autre onglet). */
|
||||
function forget(db: IDBDatabase) {
|
||||
if (opened !== db) return
|
||||
opened = null
|
||||
dbPromise = null
|
||||
dbName = ''
|
||||
}
|
||||
|
||||
function open(name: string): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -23,7 +51,16 @@ function open(name: string): Promise<IDBDatabase> {
|
||||
store.createIndex('updatedAt', 'updatedAt')
|
||||
}
|
||||
}
|
||||
req.onsuccess = () => resolve(req.result)
|
||||
req.onsuccess = () => {
|
||||
const db = req.result
|
||||
// Suppression / mise à jour demandée ailleurs (autre onglet) : on libère la base pour ne pas la bloquer
|
||||
db.onversionchange = () => {
|
||||
db.close()
|
||||
forget(db)
|
||||
}
|
||||
db.onclose = () => forget(db)
|
||||
resolve(db)
|
||||
}
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
}
|
||||
@@ -33,10 +70,17 @@ function openDB(): Promise<IDBDatabase> {
|
||||
if (!dbPromise || dbName !== name) {
|
||||
closeDB()
|
||||
dbName = name
|
||||
dbPromise = open(name).catch((e) => {
|
||||
dbPromise = null
|
||||
throw e
|
||||
})
|
||||
const p: Promise<IDBDatabase> = open(name).then(
|
||||
(db) => {
|
||||
if (dbPromise === p) opened = db
|
||||
return db
|
||||
},
|
||||
(e) => {
|
||||
if (dbPromise === p) dbPromise = null
|
||||
throw e
|
||||
},
|
||||
)
|
||||
dbPromise = p
|
||||
}
|
||||
return dbPromise
|
||||
}
|
||||
@@ -46,13 +90,24 @@ export function closeDB() {
|
||||
const p = dbPromise
|
||||
dbPromise = null
|
||||
dbName = ''
|
||||
opened = null
|
||||
p?.then((db) => db.close()).catch(() => {})
|
||||
}
|
||||
|
||||
async function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T> | void, db?: IDBDatabase): Promise<T> {
|
||||
async function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T> | void, db?: IDBDatabase, retried = false): Promise<T> {
|
||||
const database = db ?? (await openDB())
|
||||
let tx: IDBTransaction
|
||||
try {
|
||||
tx = database.transaction(STORE, mode)
|
||||
} catch (e) {
|
||||
// Base fermée entre-temps (navigateur, autre onglet) : on la rouvre une fois
|
||||
if (!db && !retried && (e as DOMException)?.name === 'InvalidStateError') {
|
||||
forget(database)
|
||||
return run(mode, fn, undefined, true)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
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)
|
||||
@@ -70,49 +125,158 @@ 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)
|
||||
const notify = (c: MediaChange) => {
|
||||
for (const fn of listeners) fn(c)
|
||||
}
|
||||
|
||||
interface Opts {
|
||||
/** Écriture venant de la synchro : ne pas la renvoyer au serveur */
|
||||
silent?: boolean
|
||||
// ─── Autres onglets du même appareil ───
|
||||
// Chaque écriture prévient les autres onglets ouverts sur la même base, qui relisent alors leurs fiches.
|
||||
let channel: BroadcastChannel | null | undefined
|
||||
function getChannel(): BroadcastChannel | null {
|
||||
if (channel === undefined) {
|
||||
try {
|
||||
channel = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel('azuucine-db')
|
||||
} catch {
|
||||
channel = null
|
||||
}
|
||||
}
|
||||
return channel
|
||||
}
|
||||
const broadcast = (name: string, wipe = false) => {
|
||||
try {
|
||||
getChannel()?.postMessage({ db: name, wipe })
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/** Écriture faite par un autre onglet dans la base de l'espace actif. */
|
||||
export function onExternalChange(fn: () => void): () => void {
|
||||
const ch = getChannel()
|
||||
if (!ch) return () => {}
|
||||
const handler = (e: MessageEvent) => {
|
||||
const data = e.data as { db?: unknown; wipe?: unknown } | null
|
||||
if (!data || data.db !== dbNameFor(getScope())) return
|
||||
// Base supprimée par un autre onglet (déconnexion) : cet onglet ne doit pas la recréer non plus
|
||||
if (data.wipe === true) {
|
||||
markWiped(data.db)
|
||||
if (data.db === dbName) closeDB()
|
||||
}
|
||||
fn()
|
||||
}
|
||||
ch.addEventListener('message', handler)
|
||||
return () => ch.removeEventListener('message', handler)
|
||||
}
|
||||
|
||||
/** Compteur d'écritures dans cet onglet (début et fin) : une lecture qui l'a vu changer peut être périmée. */
|
||||
let writes = 0
|
||||
export const writeVersion = () => writes
|
||||
|
||||
/** Écriture dans la base active, sauf si elle vient d'être supprimée (no-op). */
|
||||
async function write(fn: (store: IDBObjectStore) => IDBRequest | void, changed: () => boolean = () => true): Promise<boolean> {
|
||||
const name = dbNameFor(getScope())
|
||||
if (isWiped(name)) return false
|
||||
writes++
|
||||
try {
|
||||
await run('readwrite', fn)
|
||||
} finally {
|
||||
writes++ // une lecture commencée pendant l'écriture est aussi périmée
|
||||
}
|
||||
// Rien n'a changé (réception sans nouveauté) : inutile de faire recharger les autres onglets
|
||||
if (changed()) broadcast(name)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Lecture : une base supprimée reste vide (on ne la recrée pas en l'ouvrant). */
|
||||
const read = <T,>(fn: (store: IDBObjectStore) => IDBRequest<T>, empty: T): Promise<T> =>
|
||||
isWiped(dbNameFor(getScope())) ? Promise.resolve(empty) : run<T>('readonly', fn)
|
||||
|
||||
/** Décision pour une fiche reçue du serveur, prise dans la transaction d'écriture (voir mergeRemote). */
|
||||
export type RemoteDecision = { put: MediaItem } | 'remove' | null
|
||||
|
||||
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)
|
||||
getAll: () => read<MediaItem[]>((s) => s.getAll() as IDBRequest<MediaItem[]>, []),
|
||||
get: (id: string) => read<MediaItem | undefined>((s) => s.get(id) as IDBRequest<MediaItem | undefined>, undefined),
|
||||
put: async (item: MediaItem) => {
|
||||
if (await write((s) => void s.put(item))) notify({ put: [item], removed: [] })
|
||||
},
|
||||
putMany: async (items: MediaItem[], opts: Opts = {}) => {
|
||||
putMany: async (items: MediaItem[]) => {
|
||||
if (!items.length) return
|
||||
await run('readwrite', (s) => {
|
||||
const ok = await write((s) => {
|
||||
for (const item of items) s.put(item)
|
||||
})
|
||||
notify({ put: items, removed: [] }, opts.silent)
|
||||
if (ok) notify({ put: items, removed: [] })
|
||||
},
|
||||
remove: async (id: string, opts: Opts = {}) => {
|
||||
await run('readwrite', (s) => void s.delete(id))
|
||||
notify({ put: [], removed: [id] }, opts.silent)
|
||||
remove: async (id: string) => {
|
||||
if (await write((s) => void s.delete(id))) notify({ put: [], removed: [id] })
|
||||
},
|
||||
removeMany: async (ids: string[], opts: Opts = {}) => {
|
||||
removeMany: async (ids: string[]) => {
|
||||
if (!ids.length) return
|
||||
await run('readwrite', (s) => {
|
||||
const ok = await write((s) => {
|
||||
for (const id of ids) s.delete(id)
|
||||
})
|
||||
notify({ put: [], removed: ids }, opts.silent)
|
||||
if (ok) notify({ put: [], removed: ids })
|
||||
},
|
||||
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)
|
||||
/** Vide la base (clés lues et effacées dans la même transaction). */
|
||||
clear: async () => {
|
||||
let ids: IDBValidKey[] = []
|
||||
const ok = await write((s) => {
|
||||
const req = s.getAllKeys()
|
||||
req.onsuccess = () => {
|
||||
ids = req.result
|
||||
s.clear()
|
||||
}
|
||||
})
|
||||
if (ok) notify({ put: [], removed: ids.map(String) })
|
||||
},
|
||||
/**
|
||||
* Remplace tout le contenu en une seule transaction : si une écriture échoue, rien n'est effacé.
|
||||
* La synchro n'est prévenue qu'une fois la transaction terminée.
|
||||
*/
|
||||
replaceAll: async (items: MediaItem[]) => {
|
||||
let ids: IDBValidKey[] = []
|
||||
const ok = await write((s) => {
|
||||
const req = s.getAllKeys()
|
||||
req.onsuccess = () => {
|
||||
ids = req.result
|
||||
s.clear()
|
||||
for (const item of items) s.put(item)
|
||||
}
|
||||
})
|
||||
if (!ok) return
|
||||
const kept = new Set(items.map((i) => i.id))
|
||||
notify({ put: items, removed: ids.map(String).filter((id) => !kept.has(id)) })
|
||||
},
|
||||
/**
|
||||
* Fusion de fiches reçues du serveur, en une seule transaction : chaque fiche locale est lue puis
|
||||
* `decide` choisit (au moment de l'écriture, donc après toute modification locale déjà enregistrée)
|
||||
* de l'écraser, de la supprimer ou de la garder. Écriture silencieuse (rien à renvoyer au serveur).
|
||||
*/
|
||||
mergeRemote: async (ids: string[], decide: (id: string, local: MediaItem | undefined) => RemoteDecision): Promise<MediaChange> => {
|
||||
const change: MediaChange = { put: [], removed: [] }
|
||||
if (!ids.length) return change
|
||||
await write((s) => {
|
||||
for (const id of ids) {
|
||||
const req = s.get(id) as IDBRequest<MediaItem | undefined>
|
||||
req.onsuccess = () => {
|
||||
const d = decide(id, req.result)
|
||||
if (d === 'remove') {
|
||||
s.delete(id)
|
||||
change.removed.push(id)
|
||||
} else if (d) {
|
||||
s.put(d.put)
|
||||
change.put.push(d.put)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, () => change.put.length + change.removed.length > 0)
|
||||
return change
|
||||
},
|
||||
}
|
||||
|
||||
/** 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[]> {
|
||||
if (isWiped(name)) return []
|
||||
const exists = (await indexedDB.databases?.())?.some((d) => d.name === name)
|
||||
if (exists === false) return []
|
||||
const db = await open(name)
|
||||
@@ -125,7 +289,9 @@ export async function readOtherDatabase(name: string): Promise<MediaItem[]> {
|
||||
|
||||
/** Supprime complètement une base de l'appareil. */
|
||||
export function deleteDatabase(name: string): Promise<void> {
|
||||
markWiped(name)
|
||||
if (name === dbName) closeDB()
|
||||
broadcast(name, true)
|
||||
return new Promise((resolve) => {
|
||||
const req = indexedDB.deleteDatabase(name)
|
||||
req.onsuccess = req.onerror = req.onblocked = () => resolve()
|
||||
|
||||
@@ -9,6 +9,8 @@ const stack: { current: () => void }[] = []
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Escape' || !stack.length) return
|
||||
// Échap pendant une saisie composée (IME : japonais, chinois…) annule la composition, pas la fenêtre
|
||||
if (e.isComposing || e.keyCode === 229) return
|
||||
e.preventDefault()
|
||||
stack[stack.length - 1].current()
|
||||
})
|
||||
|
||||
@@ -63,15 +63,17 @@ export function seasonPosition(item: Pick<MediaItem, 'episodesWatched' | 'season
|
||||
const start = episodesBeforeSeason(seasons, chosen)
|
||||
if (item.episodesWatched === start) return { season: chosen, episode: 0, size: seasons[chosen - 1], before: start }
|
||||
}
|
||||
let before = 0
|
||||
for (let k = 0; k < seasons.length; k++) {
|
||||
const at = (k: number, before: number): SeasonPosition => {
|
||||
const size = seasons[k]
|
||||
if (item.episodesWatched <= before + size || k === seasons.length - 1) {
|
||||
return { season: k + 1, episode: Math.min(size, Math.max(0, item.episodesWatched - before)), size, before }
|
||||
}
|
||||
before += size
|
||||
return { season: k + 1, episode: Math.min(size, Math.max(0, item.episodesWatched - before)), size, before }
|
||||
}
|
||||
return undefined
|
||||
let before = 0
|
||||
for (let k = 0; k < seasons.length - 1; k++) {
|
||||
if (item.episodesWatched <= before + seasons[k]) return at(k, before)
|
||||
before += seasons[k]
|
||||
}
|
||||
// Au-delà : dernière saison
|
||||
return at(seasons.length - 1, before)
|
||||
}
|
||||
|
||||
/** Nombre d'épisodes vus au début de la saison n (1 = première). */
|
||||
|
||||
@@ -93,6 +93,8 @@ export async function loadMonth(
|
||||
const cache = load()
|
||||
const entry = (cache[key] ??= {})
|
||||
const failed: ReleaseCategory[] = []
|
||||
// Catégories récupérées pendant cet appel (fusionnées au cache le plus récent à l'enregistrement)
|
||||
const fetched: Partial<Record<ReleaseCategory, { at: string; list: GlobalRelease[] }>> = {}
|
||||
if (isBrowsableMonth(key) && navigator.onLine) {
|
||||
const ttl = monthOffset(key) < 0 ? PAST_FRESH_MS : FRESH_MS
|
||||
const from = `${key}-01`
|
||||
@@ -114,7 +116,7 @@ export async function loadMonth(
|
||||
job = created
|
||||
}
|
||||
try {
|
||||
entry[c] = { at: new Date().toISOString(), list: await job }
|
||||
entry[c] = fetched[c] = { at: new Date().toISOString(), list: await job }
|
||||
} catch {
|
||||
failed.push(c)
|
||||
}
|
||||
@@ -126,7 +128,13 @@ export async function loadMonth(
|
||||
for (const c of stale.filter((x) => x !== 'anime')) await fetchCat(c)
|
||||
})(),
|
||||
])
|
||||
if (stale.length) save(cache)
|
||||
// Deux chargements en parallèle (deux mois, double rendu…) : chacun relit le cache juste avant
|
||||
// d'enregistrer, sinon le dernier à finir effaçait ce que l'autre venait d'ajouter
|
||||
if (Object.keys(fetched).length) {
|
||||
const latest = load()
|
||||
latest[key] = { ...latest[key], ...fetched }
|
||||
save(latest)
|
||||
}
|
||||
}
|
||||
return { releases: cats.flatMap((c) => entry[c]?.list ?? []), failed }
|
||||
}
|
||||
+8
-2
@@ -50,9 +50,15 @@ export async function remotePosterToLocal(url: string): Promise<string | undefin
|
||||
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 res = await fetch(safe, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(15_000) })
|
||||
// Réponse en erreur ou annoncée trop grosse : on ne lit pas le corps
|
||||
const announced = Number(res.headers.get('Content-Length'))
|
||||
if (!res.ok || (Number.isFinite(announced) && announced > LIMITS.imageFileBytes)) {
|
||||
await res.body?.cancel().catch(() => {})
|
||||
return safe
|
||||
}
|
||||
const blob = await res.blob()
|
||||
if (!res.ok || !blob.type.startsWith('image/') || blob.size > LIMITS.imageFileBytes) return safe
|
||||
if (!blob.type.startsWith('image/') || blob.size > LIMITS.imageFileBytes) return safe
|
||||
return await blobToPosterDataURL(blob)
|
||||
} catch {
|
||||
return safe
|
||||
|
||||
+100
-23
@@ -1,5 +1,5 @@
|
||||
import { t } from '../../i18n'
|
||||
import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi'
|
||||
import { ANILIST, ANILIST_FIELDS, aniToResult, CLOUD_TMDB, getTmdbDetails, sanitizeMeta, tmdbFindExternal, tmdbImportSearch, type AniMedia, type SearchResult } from '../catalogApi'
|
||||
import type { MediaInput } from '../../types'
|
||||
import { anilistEntries, titleKey, type AniListEntry, type ImportEntry } from './sources'
|
||||
|
||||
@@ -35,17 +35,59 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
|
||||
// ─── Cache des correspondances (données publiques uniquement) ───
|
||||
|
||||
const CACHE_KEY = 'azuucine:import-match'
|
||||
const CACHE_MAX = 4000
|
||||
let cache: Record<string, SearchResult> | null = null
|
||||
const CACHE_MAX = 1500
|
||||
/** Taille max du cache une fois sérialisé (caractères) : il ne doit pas remplir le stockage de l'appli. */
|
||||
const CACHE_BUDGET = 1_000_000
|
||||
/** Une correspondance plus vieille que 30 jours est oubliée (titres, affiches et saisons évoluent). */
|
||||
const CACHE_TTL = 30 * 24 * 3600_000
|
||||
|
||||
function loadCache(): Record<string, SearchResult> {
|
||||
/** Forme compacte en cache : juste de quoi reconstruire la correspondance (pas de vignette, pas de doublons). */
|
||||
interface CachedMatch {
|
||||
id: string
|
||||
t: string
|
||||
o?: string
|
||||
y?: number
|
||||
p?: string
|
||||
g: SearchResult['typeGuess']
|
||||
m?: Partial<MediaInput>
|
||||
/** Titres alternatifs (rapprochement des franchises à la fusion) */
|
||||
a?: string[]
|
||||
at: number
|
||||
}
|
||||
|
||||
let cache: Record<string, CachedMatch> | null = null
|
||||
|
||||
function compact(r: SearchResult, at = Date.now()): CachedMatch {
|
||||
// Ces champs sont déjà dans le résultat : inutile de les garder deux fois
|
||||
const { title: _t, originalTitle: _o, year: _y, externalId: _e, poster: _p, ...rest } = r.prefill ?? {}
|
||||
void [_t, _o, _y, _e, _p]
|
||||
return { id: r.externalId, t: r.title, o: r.originalTitle, y: r.year, p: r.posterUrl, g: r.typeGuess, m: r.prefill ? rest : undefined, a: r.altTitles?.length ? r.altTitles : undefined, at }
|
||||
}
|
||||
|
||||
function expand(c: CachedMatch): SearchResult {
|
||||
const prefill = c.m ? sanitizeMeta({ ...c.m, title: c.t, originalTitle: c.o, year: c.y, externalId: c.id, poster: c.p }) : undefined
|
||||
return { source: 'tmdb', externalId: c.id, title: c.t, originalTitle: c.o, year: c.y, posterUrl: c.p, kindLabel: '', typeGuess: c.g, altTitles: Array.isArray(c.a) ? c.a.filter((x): x is string => typeof x === 'string').slice(0, 3) : undefined, prefill }
|
||||
}
|
||||
|
||||
const isCached = (v: unknown): v is CachedMatch => {
|
||||
const c = v as CachedMatch
|
||||
return !!c && typeof c === 'object' && typeof c.id === 'string' && c.id.startsWith('tmdb:') && typeof c.t === 'string' && typeof c.at === 'number' && typeof c.g === 'string'
|
||||
}
|
||||
|
||||
function loadCache(): Record<string, CachedMatch> {
|
||||
if (cache) return cache
|
||||
cache = Object.create(null) as Record<string, SearchResult>
|
||||
cache = Object.create(null) as Record<string, CachedMatch>
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(CACHE_KEY) ?? '{}') as unknown
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
const now = Date.now()
|
||||
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (v && typeof v === 'object' && typeof (v as SearchResult).externalId === 'string') cache[k] = v as SearchResult
|
||||
if (isCached(v)) {
|
||||
if (now - v.at < CACHE_TTL) cache[k] = v
|
||||
} else if (v && typeof v === 'object' && typeof (v as SearchResult).externalId === 'string' && (v as SearchResult).externalId.startsWith('tmdb:') && typeof (v as SearchResult).title === 'string') {
|
||||
// Ancien format (résultat complet) : converti, et compté comme récent
|
||||
cache[k] = compact(v as SearchResult, now)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -57,9 +99,20 @@ function loadCache(): Record<string, SearchResult> {
|
||||
function saveCache() {
|
||||
if (!cache) return
|
||||
try {
|
||||
const keys = Object.keys(cache)
|
||||
if (keys.length > CACHE_MAX) for (const k of keys.slice(0, keys.length - CACHE_MAX)) delete cache[k]
|
||||
localStorage.setItem(CACHE_KEY, JSON.stringify(cache))
|
||||
const now = Date.now()
|
||||
for (const [k, v] of Object.entries(cache)) if (now - v.at >= CACHE_TTL) delete cache[k]
|
||||
// Les plus anciennes d'abord : ce sont elles qu'on retire quand c'est trop gros
|
||||
const keys = Object.keys(cache).sort((a, b) => cache![a].at - cache![b].at)
|
||||
let drop = Math.max(0, keys.length - CACHE_MAX)
|
||||
for (;;) {
|
||||
for (const k of keys.splice(0, drop)) delete cache[k]
|
||||
const json = JSON.stringify(cache)
|
||||
if (json.length <= CACHE_BUDGET || !keys.length) {
|
||||
localStorage.setItem(CACHE_KEY, json)
|
||||
return
|
||||
}
|
||||
drop = Math.max(1, Math.ceil(keys.length / 5))
|
||||
}
|
||||
} catch {
|
||||
/* stockage plein ou bloqué : tant pis pour le cache */
|
||||
}
|
||||
@@ -94,10 +147,17 @@ const isRateError = (e: unknown) => {
|
||||
/** Exécute les tâches avec au plus `size` en parallèle. */
|
||||
async function pool<T>(list: T[], size: number, token: CancelToken, fn: (x: T) => Promise<void>) {
|
||||
let i = 0
|
||||
// Un travailleur en échec (ex. hors ligne) arrête les autres : inutile de continuer à vider la liste
|
||||
let failed = false
|
||||
const worker = async () => {
|
||||
while (i < list.length) {
|
||||
if (token.cancelled) throw new CancelledError()
|
||||
await fn(list[i++])
|
||||
if (token.cancelled || failed) throw new CancelledError()
|
||||
try {
|
||||
await fn(list[i++])
|
||||
} catch (e) {
|
||||
failed = true
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(size, list.length) }, worker))
|
||||
@@ -117,7 +177,8 @@ export function bestTmdbMatch(results: SearchResult[], entry: Pick<ImportEntry,
|
||||
const close = cands.filter((r) => r.year != null && Math.abs(r.year - y) <= 1)
|
||||
return exact.find(same) ?? close.find(same) ?? exact[0] ?? close[0]
|
||||
}
|
||||
return cands.find(same) ?? cands[0]
|
||||
// Sans année, le premier résultat venu peut être n'importe quoi : on exige le même titre
|
||||
return cands.find(same)
|
||||
}
|
||||
|
||||
/** Requête TMDB avec reprise automatique quand la limite de débit est atteinte. */
|
||||
@@ -150,6 +211,7 @@ async function anilistPost<T>(query: string, variables: Record<string, unknown>)
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
body: JSON.stringify({ query, variables }),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
})
|
||||
if (res.status === 429) throw new Error('rate')
|
||||
const json = (await res.json().catch(() => ({}))) as { data?: T; errors?: { message?: string; status?: number }[] }
|
||||
@@ -267,26 +329,38 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
|
||||
const c = loadCache()
|
||||
let sinceSave = 0
|
||||
const lang = document.documentElement.lang || 'x'
|
||||
// Jeton interne : annulé par l'utilisateur, ou dès qu'un travailleur échoue (hors ligne) pour que les autres
|
||||
// arrêtent d'attendre / de réessayer. Le jeton de l'appelant n'est pas modifié : l'erreur reste affichée.
|
||||
let stopped = false
|
||||
const tk: CancelToken = {
|
||||
get cancelled() {
|
||||
return token.cancelled || stopped
|
||||
},
|
||||
set cancelled(v: boolean) {
|
||||
token.cancelled = v
|
||||
},
|
||||
}
|
||||
|
||||
await pool(viaTmdb, 4, token, async (e) => {
|
||||
await pool(viaTmdb, 4, tk, async (e) => {
|
||||
try {
|
||||
const cacheKey = e.tvdbId ? `tvdb:${e.tvdbId}:${lang}` : e.imdbId ? `imdb:${e.imdbId}:${lang}` : `${e.kind}:${titleKey(e.title)}|${e.year ?? ''}:${lang}`
|
||||
let result: SearchResult | undefined = c[cacheKey]
|
||||
const hit = c[cacheKey]
|
||||
let result: SearchResult | undefined = hit ? expand(hit) : undefined
|
||||
if (!result && (e.tvdbId || e.imdbId)) {
|
||||
await rate(token)
|
||||
result = await withRetry(() => tmdbFindExternal(e.tvdbId ?? e.imdbId!, e.tvdbId ? 'tvdb_id' : 'imdb_id', key), token, onWait).catch((err) => {
|
||||
await rate(tk)
|
||||
result = await withRetry(() => tmdbFindExternal(e.tvdbId ?? e.imdbId!, e.tvdbId ? 'tvdb_id' : 'imdb_id', key), tk, onWait).catch((err) => {
|
||||
if (err instanceof CancelledError) throw err
|
||||
return undefined // ancien serveur sans /find, ou identifiant inconnu : recherche par titre
|
||||
})
|
||||
}
|
||||
if (!result && !e.title.startsWith('#')) {
|
||||
await rate(token)
|
||||
const list = await withRetry(() => tmdbImportSearch(e.title, key), token, onWait)
|
||||
await rate(tk)
|
||||
const list = await withRetry(() => tmdbImportSearch(e.title, key), tk, onWait)
|
||||
result = bestTmdbMatch(list, e)
|
||||
}
|
||||
if (!result) return
|
||||
if (!c[cacheKey]) {
|
||||
c[cacheKey] = result
|
||||
if (!hit) {
|
||||
c[cacheKey] = compact(result)
|
||||
if (++sinceSave >= 25) {
|
||||
sinceSave = 0
|
||||
saveCache()
|
||||
@@ -295,8 +369,8 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
|
||||
let meta: Partial<MediaInput> = { ...result.prefill, poster: result.posterUrl }
|
||||
// Séries : saisons et nombre d'épisodes, pour reprendre la progression
|
||||
if (result.externalId.startsWith('tmdb:tv:')) {
|
||||
await rate(token)
|
||||
const details = await withRetry(() => getTmdbDetails(result!, key), token, onWait).catch((err) => {
|
||||
await rate(tk)
|
||||
const details = await withRetry(() => getTmdbDetails(result!, key), tk, onWait).catch((err) => {
|
||||
if (err instanceof CancelledError) throw err
|
||||
return undefined
|
||||
})
|
||||
@@ -305,7 +379,10 @@ export async function resolveEntries(entries: ImportEntry[], opts: ResolveOption
|
||||
found.set(e.key, { result, meta })
|
||||
} catch (err) {
|
||||
if (err instanceof CancelledError) throw err
|
||||
if (!navigator.onLine) throw new Error(t('search.offline'))
|
||||
if (!navigator.onLine) {
|
||||
stopped = true
|
||||
throw new Error(t('search.offline'))
|
||||
}
|
||||
// Erreur ponctuelle sur un titre : il sera compté comme « non trouvé »
|
||||
} finally {
|
||||
step()
|
||||
|
||||
+13
-6
@@ -2,6 +2,8 @@ import type { MediaItem, MediaType, TopCategory, TopEntry, WatchStatus } from '.
|
||||
import { ALL_TOP_CATEGORIES } from './constants'
|
||||
import { cleanText, isSafeExternalId, isSafeTmdbPath, LIMITS, safeCountries, safeDay, safeIso, safeStringList } from './security'
|
||||
import { splitGenres } from './catalogApi'
|
||||
// Import circulaire sans risque : normalizeItem n'est appelée qu'à l'exécution, jamais au chargement du module
|
||||
import { normalizeItem } from './backup'
|
||||
import { normalizeText } from './utils'
|
||||
|
||||
/**
|
||||
@@ -99,7 +101,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
|
||||
|
||||
// Épisodes vus par fiche
|
||||
const eps = new Map<number, LegacyEpisode[]>()
|
||||
for (const e of data.episodes ?? []) {
|
||||
// Fichier non fiable : chaque liste peut manquer ou ne pas être un tableau
|
||||
for (const e of Array.isArray(data.episodes) ? data.episodes : []) {
|
||||
if (!e || !(e.watched === 1 || e.watched === true)) continue
|
||||
const list = eps.get(e.item_id) ?? []
|
||||
list.push(e)
|
||||
@@ -113,7 +116,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
|
||||
.map((t) => [t.id, cleanText(t.name, LIMITS.shortText)] as const),
|
||||
)
|
||||
const itemTags = new Map<number, string[]>()
|
||||
for (const it of data.item_tags ?? []) {
|
||||
for (const it of Array.isArray(data.item_tags) ? data.item_tags : []) {
|
||||
if (!it || typeof it !== 'object') continue
|
||||
const name = tagNames.get(it.tag_id)
|
||||
if (!name) continue
|
||||
itemTags.set(it.item_id, [...(itemTags.get(it.item_id) ?? []), name])
|
||||
@@ -121,8 +125,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
|
||||
|
||||
// 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) {
|
||||
for (const t of Array.isArray(data.top5) ? data.top5 : []) {
|
||||
if (t && typeof t === 'object' && 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 })
|
||||
}
|
||||
}
|
||||
@@ -173,7 +177,8 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
|
||||
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({
|
||||
// Même validation que les sauvegardes Kino (bornes, formats, champs inconnus retirés)
|
||||
const item = normalizeItem({
|
||||
id: `legacy-${r.id}`,
|
||||
title,
|
||||
originalTitle: r.original_title && r.original_title !== title ? r.original_title : undefined,
|
||||
@@ -208,7 +213,9 @@ export function convertLegacyBackup(data: LegacyFile): { items: MediaItem[]; ski
|
||||
})(),
|
||||
createdAt: created,
|
||||
updatedAt: toISO(r.watch_date) ?? created,
|
||||
})
|
||||
} satisfies MediaItem)
|
||||
if (item) items.push(item)
|
||||
else skipped++
|
||||
}
|
||||
return { items, skipped }
|
||||
}
|
||||
+8
-5
@@ -1,4 +1,4 @@
|
||||
import { t } from '../i18n'
|
||||
import { t, tmdbLanguage } from '../i18n'
|
||||
import { ANILIST, ANILIST_FIELDS, aniToResult, tmdbFetch, tmdbToResult, TMDB_IMG, type AniMedia, type SearchResult, type TmdbItem } from './catalogApi'
|
||||
import { cleanText, isSafeTmdbPath, safePosterUrl } from './security'
|
||||
|
||||
@@ -78,7 +78,7 @@ interface TmdbPersonHit {
|
||||
}
|
||||
|
||||
async function searchTmdbPeople(query: string, key: string): Promise<PersonHit[]> {
|
||||
const data = await tmdbFetch<{ results?: TmdbPersonHit[] }>('/search/person', key, { query: query.slice(0, 100), include_adult: 'false' })
|
||||
const data = await tmdbFetch<{ results?: TmdbPersonHit[] }>('/search/person', key, { query, include_adult: 'false' })
|
||||
return (Array.isArray(data.results) ? data.results : [])
|
||||
.slice(0, 12)
|
||||
.map((p): PersonHit | null => {
|
||||
@@ -105,6 +105,7 @@ async function aniQuery<T>(query: string, variables: Record<string, unknown>): P
|
||||
body: JSON.stringify({ query, variables }),
|
||||
referrerPolicy: 'no-referrer',
|
||||
credentials: 'omit',
|
||||
signal: AbortSignal.timeout(12_000),
|
||||
})
|
||||
if (res.status === 429) throw new Error(t('err.anilistRate'))
|
||||
if (!res.ok) throw new Error(t('err.anilistStatus', { status: res.status }))
|
||||
@@ -333,11 +334,13 @@ const personCache = new Map<string, Promise<PersonDetails>>()
|
||||
export function getPerson(id: string, tmdbKey?: string): Promise<PersonDetails> {
|
||||
if (!isPersonId(id)) return Promise.reject(new Error(t('person.notFound')))
|
||||
if (id.startsWith('tmdbp:') && !tmdbKey?.trim()) return Promise.reject(new Error(t('search.animeOnly')))
|
||||
const cached = personCache.get(id)
|
||||
// Clé avec la langue : biographie et titres changent avec elle
|
||||
const cacheKey = `${id}:${tmdbLanguage()}`
|
||||
const cached = personCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
const p = id.startsWith('tmdbp:') ? tmdbPerson(id, tmdbKey!) : aniPerson(id)
|
||||
personCache.set(id, p)
|
||||
p.catch(() => personCache.delete(id))
|
||||
personCache.set(cacheKey, p)
|
||||
p.catch(() => personCache.delete(cacheKey))
|
||||
return p
|
||||
}
|
||||
|
||||
+5
-2
@@ -21,7 +21,8 @@ export function episodesPatch(
|
||||
const today = todayISO()
|
||||
|
||||
if (watched > 0) {
|
||||
if (!item.startDate || item.episodesWatched === 0) patch.startDate = item.episodesWatched === 0 ? today : item.startDate ?? today
|
||||
// Premier épisode coché (ou date de début manquante) : début aujourd'hui
|
||||
if (!item.startDate || item.episodesWatched === 0) patch.startDate = today
|
||||
if (item.status === 'a_voir' || item.status === 'pause') patch.status = 'en_cours'
|
||||
} else {
|
||||
patch.startDate = undefined
|
||||
@@ -33,7 +34,9 @@ export function episodesPatch(
|
||||
patch.status = 'termine'
|
||||
// Date de fin = le jour où l'on coche le dernier épisode
|
||||
patch.endDate = item.status === 'termine' && item.endDate ? item.endDate : today
|
||||
} else if (watched > 0 && item.status === 'termine' && watched < item.episodesWatched) {
|
||||
} else if (watched > 0 && item.status === 'termine' && (watched < item.episodesWatched || (cap && watched > item.episodesWatched))) {
|
||||
// Terminé, puis un épisode décoché… ou coché alors que de nouveaux épisodes sont sortis
|
||||
// (série en cours dont le total a augmenté) : la fiche repasse « En cours »
|
||||
patch.status = 'en_cours'
|
||||
patch.endDate = undefined
|
||||
}
|
||||
|
||||
+11
-4
@@ -15,7 +15,6 @@ export interface CalendarEvent {
|
||||
date: string // AAAA-MM-JJ
|
||||
item: MediaItem
|
||||
label: string
|
||||
kind: 'episode' | 'release'
|
||||
}
|
||||
|
||||
type ReleaseCache = Record<string, ReleaseInfo & { checkedAt: string }>
|
||||
@@ -86,26 +85,34 @@ export async function refreshReleases(items: MediaItem[], tmdbKey?: string, forc
|
||||
)
|
||||
}
|
||||
}
|
||||
// Fiches retirées de la bibliothèque : leurs sorties ne servent plus (le cache ne grossit plus sans fin)
|
||||
// (bibliothèque vide = pas encore chargée : on ne touche à rien)
|
||||
if (items.length) {
|
||||
const ids = new Set(items.map((i) => i.id))
|
||||
for (const id of Object.keys(cache)) if (!ids.has(id)) delete cache[id]
|
||||
}
|
||||
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 = localDay(new Date(Date.now() - 7 * 86400000))
|
||||
// Il y a 7 jours (calcul en jours du calendrier : juste aux changements d'heure)
|
||||
const now = new Date()
|
||||
const from = localDay(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7))
|
||||
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' })
|
||||
events.push({ date: nx.date, item, label })
|
||||
}
|
||||
}
|
||||
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' })
|
||||
if (item && item.status === 'a_voir' && r.date >= from) events.push({ date: r.date, item, label: r.label })
|
||||
}
|
||||
return events.sort((a, b) => a.date.localeCompare(b.date) || a.item.title.localeCompare(b.item.title, locale()))
|
||||
}
|
||||
|
||||
+12
-2
@@ -58,12 +58,22 @@ export function rewatchEpisodesPatch(item: MediaItem, n: number): { patch: Parti
|
||||
return { patch: { rewatch: { ...item.rewatch, episodes } }, finished: false }
|
||||
}
|
||||
|
||||
/**
|
||||
* Revisionnage terminé par ce changement (dernier épisode, ou « Revu en entier ») : il disparaît en même temps
|
||||
* qu'une date rejoint l'historique. Un simple abandon (`stopRewatch`) ne touche pas aux dates.
|
||||
* On regarde le patch et non le nombre de dates : une date déjà présente ce jour-là (ou le plafond de
|
||||
* MAX_REWATCHES) ne l'allonge pas, alors que le revisionnage est bien terminé.
|
||||
*/
|
||||
export const isRewatchFinish = (current: Pick<MediaItem, 'rewatch'>, patch: Partial<MediaInput>) =>
|
||||
!!current.rewatch && 'rewatch' in patch && !patch.rewatch && 'rewatchDates' in patch
|
||||
|
||||
/** Épisodes vus en plus pendant un revisionnage (pour le journal des défis). */
|
||||
export function rewatchEpisodeDelta(current: MediaItem, next: MediaItem): number {
|
||||
export function rewatchEpisodeDelta(current: MediaItem, next: MediaItem, finished?: boolean): number {
|
||||
const before = current.rewatch?.episodes ?? 0
|
||||
if (next.rewatch) return next.rewatch.episodes - before
|
||||
// Revisionnage terminé : les derniers épisodes jusqu'à la fin comptent
|
||||
if (current.rewatch && (next.rewatchDates?.length ?? 0) > (current.rewatchDates?.length ?? 0)) {
|
||||
const done = finished ?? (!!current.rewatch && (next.rewatchDates?.length ?? 0) > (current.rewatchDates?.length ?? 0))
|
||||
if (current.rewatch && done) {
|
||||
const cap = episodeCap(current)
|
||||
return cap ? Math.max(0, cap - before) : 0
|
||||
}
|
||||
|
||||
+6
-1
@@ -3,11 +3,16 @@
|
||||
* et sa propre base IndexedDB. Sans compte (mode local), on garde les anciens noms.
|
||||
*/
|
||||
let scope: string | null = null
|
||||
/** Compteur de changements d'espace (connexion, déconnexion, changement de compte). */
|
||||
let epoch = 0
|
||||
|
||||
export const getScope = () => scope
|
||||
export const scopeEpoch = () => epoch
|
||||
export const setScope = (userId: string | null) => {
|
||||
// Un compte (identifiant), ou « guest » : l'espace vide du mode découverte, séparé de tout le reste
|
||||
scope = userId && (/^[0-9a-f-]{36}$/i.test(userId) || userId === 'guest') ? userId : null
|
||||
const next = userId && (/^[0-9a-f-]{36}$/i.test(userId) || userId === 'guest') ? userId : null
|
||||
if (next !== scope) epoch++
|
||||
scope = next
|
||||
}
|
||||
|
||||
/** Nom de clé localStorage pour l'espace actif : « azuucine:lists » ou « azuucine:<id>:lists ». */
|
||||
|
||||
@@ -37,22 +37,24 @@ function colors() {
|
||||
async function loadImage(raw?: string): Promise<HTMLImageElement | null> {
|
||||
const src = safePosterUrl(raw)
|
||||
if (!src) return null
|
||||
let objectUrl: string | undefined
|
||||
try {
|
||||
let url = src
|
||||
let revoke = false
|
||||
if (!src.startsWith('data:')) {
|
||||
const res = await fetch(src, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
// Délai max : une affiche qui ne vient pas ne doit pas bloquer la création de l'image
|
||||
const res = await fetch(src, { mode: 'cors', credentials: 'omit', referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(12_000) })
|
||||
if (!res.ok) return null
|
||||
url = URL.createObjectURL(await res.blob())
|
||||
revoke = true
|
||||
url = objectUrl = URL.createObjectURL(await res.blob())
|
||||
}
|
||||
const img = new Image()
|
||||
img.src = url
|
||||
await img.decode()
|
||||
if (revoke) setTimeout(() => URL.revokeObjectURL(url), 5000)
|
||||
return img
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
// Une image déjà décodée reste dessinable : l'adresse temporaire peut être libérée, même en cas d'échec
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-1
@@ -24,7 +24,11 @@ function firstViewMinutes(item: MediaItem): number {
|
||||
export function oneViewMinutes(item: MediaItem): number {
|
||||
if (!TYPE_BY_VALUE[item.type].episodic) return item.duration || DEFAULT_FILM_MINUTES
|
||||
const cap = episodeCap(item)
|
||||
return cap ? cap * (item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes) : 0
|
||||
const epMin = item.episodeDuration || TYPE_BY_VALUE[item.type].episodeMinutes
|
||||
// Nombre d'épisodes inconnu : on compte ceux vus au premier visionnage, sinon la durée saisie
|
||||
// (avant, un revisionnage d'une telle série valait 0 min)
|
||||
if (cap) return cap * epMin
|
||||
return item.episodesWatched > 0 ? item.episodesWatched * epMin : item.duration || 0
|
||||
}
|
||||
|
||||
/** Temps passé à revoir le titre : revisionnages terminés + épisodes du revisionnage en cours. */
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ const CANVAS: Record<Exclude<ThemeMode, 'auto'>, string> = {
|
||||
light: '#ffffff',
|
||||
dark: '#0a0a0a',
|
||||
night: '#000000',
|
||||
starfield: '#0a1230',
|
||||
starfield: '#070b1c',
|
||||
}
|
||||
|
||||
export const isHexColor = (v: unknown): v is string => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v)
|
||||
|
||||
Reference in new issue
Block a user