Initial commit

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

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
import { t } from '../../i18n'
import { AuthError, getAccessToken } from './auth'
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
/** Appel authentifié à Supabase (base de données ou fonctions serveur). Réessaie une fois si le jeton a expiré. */
export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> {
for (let attempt = 0; attempt < 2; attempt++) {
const token = await getAccessToken(attempt > 0)
if (!token) throw new AuthError(t('auth.err.session'))
const res = await fetch(SUPABASE_URL + path, {
...init,
headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },
credentials: 'omit',
referrerPolicy: 'no-referrer',
})
if (res.status !== 401) return res
}
throw new AuthError(t('auth.err.session'))
}
/** Proxy TMDB : la clé TMDB reste sur le serveur. */
export async function tmdbViaCloud<T>(path: string, params: Record<string, string>): Promise<T> {
const q = new URLSearchParams({ path, ...params })
const res = await cloudFetch(`/functions/v1/tmdb?${q}`)
if (res.status === 429) throw new Error(t('err.searchRate'))
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
return res.json() as Promise<T>
}
export type ProxyState = 'ok' | 'missing-key' | 'not-deployed' | 'offline' | 'error'
/** Vérifie que le proxy TMDB est déployé et que la clé TMDB est bien enregistrée côté serveur. */
export async function checkTmdbProxy(): Promise<ProxyState> {
if (!navigator.onLine) return 'offline'
try {
const res = await cloudFetch(`/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`)
if (res.ok) return 'ok'
if (res.status === 404) return 'not-deployed'
const body = (await res.json().catch(() => ({}))) as { error?: string; status?: number }
if (res.status === 500 && body.error?.includes('TMDB_API_KEY')) return 'missing-key'
if (res.status === 502 && body.status === 401) return 'missing-key'
return 'error'
} catch {
return navigator.onLine ? 'not-deployed' : 'offline'
}
}
+260
View File
@@ -0,0 +1,260 @@
import { t, type TKey } from '../../i18n'
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
/**
* Connexion aux comptes (Supabase Auth), sans dépendance.
* La session (jetons) est gardée sur l'appareil pour que l'app s'ouvre même hors-ligne ;
* le mot de passe, lui, n'est jamais stocké.
*/
export interface Session {
accessToken: string
refreshToken: string
/** Expiration du jeton d'accès (ms) */
expiresAt: number
user: { id: string; email: string }
}
export class AuthError extends Error {}
const KEY = 'azuucine:session'
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const TOKEN = /^[A-Za-z0-9._~+/=-]{10,8192}$/
export const PASSWORD_MIN = 8
function isSession(v: unknown): v is Session {
if (!v || typeof v !== 'object') return false
const s = v as Session
return (
typeof s.accessToken === 'string' &&
TOKEN.test(s.accessToken) &&
typeof s.refreshToken === 'string' &&
/^[A-Za-z0-9._~+/=-]{4,1024}$/.test(s.refreshToken) &&
typeof s.expiresAt === 'number' &&
Number.isFinite(s.expiresAt) &&
!!s.user &&
typeof s.user.id === 'string' &&
UUID.test(s.user.id) &&
typeof s.user.email === 'string' &&
s.user.email.length <= 320
)
}
function load(): Session | null {
try {
const raw = localStorage.getItem(KEY)
const parsed = raw ? JSON.parse(raw) : null
return isSession(parsed) ? parsed : null
} catch {
return null
}
}
let current: Session | null = load()
const listeners = new Set<(s: Session | null) => void>()
function setSession(s: Session | null) {
const changedUser = current?.user.id !== s?.user.id
current = s
try {
if (s) localStorage.setItem(KEY, JSON.stringify(s))
else localStorage.removeItem(KEY)
} catch {
/* ignore */
}
if (changedUser) for (const fn of listeners) fn(s)
}
// Connexion / déconnexion dans un autre onglet
if (typeof window !== 'undefined') {
window.addEventListener('storage', (e) => {
if (e.key !== KEY) return
const next = load()
const changedUser = current?.user.id !== next?.user.id
current = next
if (changedUser) for (const fn of listeners) fn(next)
})
}
export const getSession = () => current
export function onSessionChange(fn: (s: Session | null) => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
// ───────────────────────────── Appels à Supabase Auth ─────────────────────────────
const CODE_KEYS: Record<string, TKey> = {
invalid_credentials: 'auth.err.credentials',
invalid_grant: 'auth.err.credentials',
email_not_confirmed: 'auth.err.notConfirmed',
user_already_exists: 'auth.err.exists',
email_exists: 'auth.err.exists',
weak_password: 'auth.err.weak',
same_password: 'auth.err.samePassword',
over_email_send_rate_limit: 'auth.err.emailRate',
over_request_rate_limit: 'auth.err.rate',
signup_disabled: 'auth.err.signupDisabled',
email_address_invalid: 'auth.err.emailInvalid',
validation_failed: 'auth.err.invalid',
session_not_found: 'auth.err.session',
refresh_token_not_found: 'auth.err.session',
refresh_token_already_used: 'auth.err.session',
}
const msg = (code: string) => (CODE_KEYS[code] ? t(CODE_KEYS[code], { n: PASSWORD_MIN }) : undefined)
async function gotrue(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<Record<string, unknown>> {
let res: Response
try {
res = await fetch(`${SUPABASE_URL}/auth/v1${path}`, {
method: init.method ?? 'POST',
headers: {
apikey: SUPABASE_ANON_KEY,
'Content-Type': 'application/json',
...(init.token ? { Authorization: `Bearer ${init.token}` } : {}),
},
body: init.body ? JSON.stringify(init.body) : undefined,
credentials: 'omit',
referrerPolicy: 'no-referrer',
})
} catch {
throw new Error(t('common.offline'))
}
let data: Record<string, unknown> = {}
try {
data = (await res.json()) as Record<string, unknown>
} catch {
/* réponse vide */
}
if (!res.ok) {
const code = String(data.error_code ?? data.code ?? data.error ?? '')
const err = new AuthError(msg(code) ?? (res.status === 429 ? t('auth.err.rate') : t('auth.err.status', { status: res.status })))
;(err as AuthError & { status: number; code: string }).status = res.status
;(err as AuthError & { status: number; code: string }).code = code
throw err
}
return data
}
function toSession(data: Record<string, unknown>): Session | null {
const user = data.user as { id?: unknown; email?: unknown } | undefined
const expiresIn = typeof data.expires_in === 'number' ? data.expires_in : 3600
const s = {
accessToken: data.access_token,
refreshToken: data.refresh_token,
expiresAt: typeof data.expires_at === 'number' ? data.expires_at * 1000 : Date.now() + expiresIn * 1000,
user: { id: user?.id, email: typeof user?.email === 'string' ? user.email : '' },
}
return isSession(s) ? s : null
}
const cleanEmail = (email: string) => email.trim().toLowerCase().slice(0, 320)
const appUrl = () => `${location.origin}${location.pathname}`
export async function signIn(email: string, password: string): Promise<void> {
const data = await gotrue('/token?grant_type=password', { body: { email: cleanEmail(email), password } })
const s = toSession(data)
if (!s) throw new AuthError(t('auth.err.response'))
setSession(s)
}
/** Crée un compte. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). */
export async function signUp(email: string, password: string): Promise<boolean> {
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
const data = await gotrue(`/signup?redirect_to=${encodeURIComponent(appUrl())}`, { body: { email: cleanEmail(email), password } })
const s = toSession(data)
if (s) {
setSession(s)
return false
}
return true
}
export async function requestPasswordReset(email: string): Promise<void> {
await gotrue(`/recover?redirect_to=${encodeURIComponent(appUrl())}`, { body: { email: cleanEmail(email) } })
}
export async function updatePassword(password: string): Promise<void> {
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
const token = await getAccessToken()
if (!token) throw new AuthError(t('auth.err.session'))
await gotrue('/user', { method: 'PUT', body: { password }, token })
}
/** Déconnexion : invalide la session côté serveur (si possible) et l'efface de l'appareil. */
export async function signOut(): Promise<void> {
const s = current
setSession(null)
if (s && navigator.onLine) {
try {
await gotrue('/logout?scope=local', { token: s.accessToken })
} catch {
/* jeton déjà expiré : rien à faire */
}
}
}
let refreshing: Promise<Session | null> | null = null
async function refresh(): Promise<Session | null> {
const s = current
if (!s) return null
refreshing ??= (async () => {
try {
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: s.refreshToken } })
const next = toSession(data)
if (next && next.user.id === s.user.id) setSession(next)
return next
} catch (e) {
// Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte
const status = (e as { status?: number }).status
if (status === 400 || status === 401 || status === 403) setSession(null)
return null
} finally {
refreshing = null
}
})()
return refreshing
}
/** Jeton d'accès valide (renouvelé si besoin). null si déconnecté ou hors-ligne avec un jeton expiré. */
export async function getAccessToken(force = false): Promise<string | null> {
const s = current
if (!s) return null
if (!force && s.expiresAt - 60_000 > Date.now()) return s.accessToken
const next = await refresh()
return next?.accessToken ?? null
}
/**
* Liens reçus par email (confirmation d'inscription, mot de passe oublié) :
* Supabase renvoie vers l'app avec les jetons après le « # ». On ouvre la session puis on nettoie l'adresse.
*/
export async function consumeAuthRedirect(): Promise<{ type?: string; error?: string }> {
const hash = location.hash.startsWith('#') ? location.hash.slice(1) : ''
if (!/(^|&)(access_token|error)=/.test(hash)) return {}
const params = new URLSearchParams(hash)
history.replaceState(null, '', `${location.pathname}${location.search}#/`)
const error = params.get('error_description') ?? params.get('error')
if (error) {
const code = params.get('error_code') ?? ''
return { error: code === 'otp_expired' ? t('auth.err.linkExpired') : t('auth.err.linkUsed') }
}
const accessToken = params.get('access_token') ?? ''
try {
const user = await gotrue('/user', { method: 'GET', token: accessToken })
const s = toSession({
access_token: accessToken,
refresh_token: params.get('refresh_token'),
expires_at: Number(params.get('expires_at')) || undefined,
expires_in: Number(params.get('expires_in')) || 3600,
user,
})
if (!s) return { error: t('auth.err.linkInvalid') }
setSession(s)
return { type: params.get('type') ?? undefined }
} catch (e) {
return { error: (e as Error).message }
}
}
+19
View File
@@ -0,0 +1,19 @@
/**
* Configuration des comptes (Supabase), lue dans le fichier .env au moment de la compilation.
* Sans .env, l'app fonctionne comme avant : 100 % locale, sans compte.
*/
// On accepte aussi une adresse copiée avec « /rest/v1/ » (ou autre chemin) à la fin
const rawUrl = (import.meta.env.VITE_SUPABASE_URL ?? '').trim().replace(/^(https?:\/\/[^/]+).*$/, '$1')
const rawKey = (import.meta.env.VITE_SUPABASE_ANON_KEY ?? '').trim()
const validUrl = /^https:\/\/[a-z0-9-]+\.supabase\.(co|in)$/i.test(rawUrl) || /^http:\/\/(localhost|127\.0\.0\.1):\d+$/.test(rawUrl)
const validKey = /^(sb_publishable_[A-Za-z0-9_-]{10,200}|[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.test(rawKey)
export const SUPABASE_URL = validUrl ? rawUrl : ''
export const SUPABASE_ANON_KEY = validKey ? rawKey : ''
/** Les comptes sont activés quand le .env contient une configuration valide. */
export const cloudEnabled = !!(SUPABASE_URL && SUPABASE_ANON_KEY)
if (!cloudEnabled && (rawUrl || rawKey)) {
console.warn('[AzuuCine] .env incomplet ou invalide : les comptes sont désactivés (mode local). Vérifie VITE_SUPABASE_URL et VITE_SUPABASE_ANON_KEY.')
}
+279
View File
@@ -0,0 +1,279 @@
import { t } from '../../i18n'
import type { MediaItem } from '../../types'
import { normalizeItem } from '../backup'
import { cleanText, isPlainObject, safeIso } from '../security'
import { cloudFetch } from './api'
import { getSession } from './auth'
import { SUPABASE_URL } from './config'
/**
* Profils, abonnements et fil d'activité.
* Toutes les lectures passent par les fonctions de la base (get_profile, get_feed…) qui vérifient
* les droits d'accès ; tout ce qui revient du serveur est revalidé ici avant d'être affiché.
*/
export type Relation = 'none' | 'pending' | 'accepted'
export interface ProfileCard {
id: string
username: string
displayName: string
avatarUrl?: string
isPrivate: boolean
relation: Relation
}
export interface ProfileStats {
total: number
finished: number
finishedYear: number
films: number
series: number
episodes: number
rated: number
}
export interface Profile extends ProfileCard {
bio: string
bannerUrl?: string
isMe: boolean
followsMe: boolean
followers: number
following: number
visible: boolean
stats?: ProfileStats
top: MediaItem[]
recent: MediaItem[]
}
export interface FeedEntry {
id: number
kind: 'finished' | 'started' | 'rewatched' | 'added'
createdAt: string
user: { username: string; displayName: string; avatarUrl?: string }
item: MediaItem
}
export const USERNAME_RE = /^[a-z0-9_]{3,20}$/
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const MEDIA_PREFIX = () => `${SUPABASE_URL}/storage/v1/object/public/profile-media/`
/** Photo / bannière : uniquement depuis le stockage de l'app. */
export function safeMediaUrl(v: unknown): string | undefined {
if (typeof v !== 'string' || v.length > 500 || !SUPABASE_URL) return undefined
const prefix = MEDIA_PREFIX()
if (!v.startsWith(prefix)) return undefined
return /^[0-9a-f-]{36}\/[A-Za-z0-9_.-]{1,80}$/i.test(v.slice(prefix.length)) ? v : undefined
}
const count = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.min(Math.round(v), 10_000_000) : 0)
const relation = (v: unknown): Relation => (v === 'pending' || v === 'accepted' ? v : 'none')
const username = (v: unknown) => (typeof v === 'string' && USERNAME_RE.test(v) ? v : undefined)
function toCard(raw: unknown): ProfileCard | null {
if (!isPlainObject(raw) || typeof raw.id !== 'string' || !UUID.test(raw.id)) return null
const name = username(raw.username)
if (!name) return null
return {
id: raw.id,
username: name,
displayName: cleanText(raw.display_name, 40) ?? name,
avatarUrl: safeMediaUrl(raw.avatar_url),
isPrivate: raw.is_private === true,
relation: relation(raw.relation),
}
}
const toItems = (v: unknown): MediaItem[] =>
Array.isArray(v) ? v.slice(0, 200).map(normalizeItem).filter((i): i is MediaItem => i !== null) : []
function toProfile(raw: unknown): Profile | null {
const card = toCard(raw)
if (!card || !isPlainObject(raw)) return null
const s = isPlainObject(raw.stats) ? raw.stats : null
return {
...card,
bio: cleanText(raw.bio, 300) ?? '',
bannerUrl: safeMediaUrl(raw.banner_url),
isMe: raw.is_me === true,
followsMe: raw.follows_me === true,
followers: count(raw.followers),
following: count(raw.following),
visible: raw.visible === true,
stats: s
? {
total: count(s.total),
finished: count(s.finished),
finishedYear: count(s.finished_year),
films: count(s.films),
series: count(s.series),
episodes: count(s.episodes),
rated: count(s.rated),
}
: undefined,
top: toItems(raw.top),
recent: toItems(raw.recent),
}
}
function me(): string {
const id = getSession()?.user.id
if (!id) throw new Error(t('auth.err.session'))
return id
}
async function rpc(name: string, args: Record<string, unknown> = {}): Promise<unknown> {
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(args),
})
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
return res.json()
}
// ─── Lecture ───
export async function getProfile(name: string): Promise<Profile | null> {
const clean = name.trim().toLowerCase().replace(/^@/, '')
if (!USERNAME_RE.test(clean)) return null
return toProfile(await rpc('get_profile', { p_username: clean }))
}
/** Mon profil (pseudo, nom, photo…) — lu directement dans la table. */
export async function getMyProfile(): Promise<Profile | null> {
const res = await cloudFetch(`/rest/v1/profiles?id=eq.${me()}&select=username`)
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
const [row] = (await res.json()) as { username?: string }[]
return row?.username ? getProfile(row.username) : null
}
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<MediaItem[]> {
if (!UUID.test(userId)) return []
return toItems(await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: 48 }))
}
export async function getFeed(before?: string): Promise<FeedEntry[]> {
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: 30 })
if (!Array.isArray(raw)) return []
const out: FeedEntry[] = []
for (const r of raw.slice(0, 50)) {
if (!isPlainObject(r) || !isPlainObject(r.user)) continue
const item = normalizeItem(r.item)
const name = username(r.user.username)
const createdAt = safeIso(r.created_at)
const kind = r.kind
if (!item || !name || !createdAt || (kind !== 'finished' && kind !== 'started' && kind !== 'rewatched' && kind !== 'added')) continue
out.push({
id: typeof r.id === 'number' ? r.id : out.length,
kind,
createdAt,
user: { username: name, displayName: cleanText(r.user.display_name, 40) ?? name, avatarUrl: safeMediaUrl(r.user.avatar_url) },
item,
})
}
return out
}
const toCards = (raw: unknown) => (Array.isArray(raw) ? raw.slice(0, 100).map(toCard).filter((c): c is ProfileCard => c !== null) : [])
export const searchProfiles = async (q: string) => (q.trim().length < 2 ? [] : toCards(await rpc('search_profiles', { q: q.trim().slice(0, 40) })))
export const getFollowList = async (userId: string, kind: 'followers' | 'following', offset = 0) =>
UUID.test(userId) ? toCards(await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })) : []
export const getFollowRequests = async () => toCards(await rpc('get_follow_requests'))
// ─── Abonnements ───
async function ok(res: Response) {
if (!res.ok) throw new Error(t('social.err.server', { status: res.status }))
}
/** S'abonner. Renvoie « pending » si le compte est privé (demande envoyée). */
export async function follow(userId: string): Promise<Relation> {
if (!UUID.test(userId)) return 'none'
const res = await cloudFetch('/rest/v1/follows', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Prefer: 'return=representation' },
body: JSON.stringify({ following_id: userId }),
})
if (res.status !== 409) await ok(res)
const rows =
res.status === 409
? await (await cloudFetch(`/rest/v1/follows?follower_id=eq.${me()}&following_id=eq.${userId}&select=status`)).json()
: await res.json().catch(() => [])
const [row] = (Array.isArray(rows) ? rows : []) as { status?: string }[]
return relation(row?.status)
}
/** Se désabonner (ou annuler une demande). */
export async function unfollow(userId: string) {
if (!UUID.test(userId)) return
await ok(await cloudFetch(`/rest/v1/follows?follower_id=eq.${me()}&following_id=eq.${userId}`, { method: 'DELETE' }))
}
/** Retirer un abonné (ou refuser sa demande). */
export async function removeFollower(userId: string) {
if (!UUID.test(userId)) return
await ok(await cloudFetch(`/rest/v1/follows?follower_id=eq.${userId}&following_id=eq.${me()}`, { method: 'DELETE' }))
}
export async function acceptFollower(userId: string) {
if (!UUID.test(userId)) return
await ok(
await cloudFetch(`/rest/v1/follows?follower_id=eq.${userId}&following_id=eq.${me()}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'accepted' }),
}),
)
}
// ─── Modifier mon profil ───
export interface ProfilePatch {
username?: string
display_name?: string
bio?: string
is_private?: boolean
avatar_url?: string | null
banner_url?: string | null
}
export async function updateProfile(patch: ProfilePatch): Promise<void> {
const res = await cloudFetch(`/rest/v1/profiles?id=eq.${me()}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', Prefer: 'return=minimal' },
body: JSON.stringify(patch),
})
if (res.ok) return
const body = (await res.json().catch(() => ({}))) as { code?: string; message?: string }
if (body.code === '23505') throw new Error(t('social.err.usernameTaken'))
if (body.message?.includes('reserved')) throw new Error(t('social.err.usernameReserved'))
if (body.code === '23514') throw new Error(t('social.err.invalid'))
throw new Error(t('social.err.server', { status: res.status }))
}
/** Envoie une photo (déjà recadrée) dans mon dossier et renvoie son adresse publique. */
export async function uploadProfileImage(kind: 'avatar' | 'banner', blob: Blob): Promise<string> {
const path = `${me()}/${kind}-${Date.now()}.jpg`
const res = await cloudFetch(`/storage/v1/object/profile-media/${path}`, {
method: 'POST',
headers: { 'Content-Type': 'image/jpeg', 'Cache-Control': '31536000' },
body: blob,
})
if (res.status === 413) throw new Error(t('image.tooBig'))
await ok(res)
return MEDIA_PREFIX() + path
}
/** Supprime une ancienne photo (sans erreur si elle n'existe plus). */
export async function deleteProfileImage(url?: string) {
const safe = safeMediaUrl(url)
if (!safe) return
const path = safe.slice(MEDIA_PREFIX().length)
if (!path.startsWith(me() + '/')) return
await cloudFetch(`/storage/v1/object/profile-media/${path}`, { method: 'DELETE' }).catch(() => undefined)
}
/** Lien public vers un profil. */
export const profileLink = (name: string) => `${location.origin}${location.pathname}#/u/${name}`
+378
View File
@@ -0,0 +1,378 @@
import { t } from '../../i18n'
import type { CustomList, MediaItem, Settings } from '../../types'
import { normalizeItem, normalizeLists, normalizeSettings } from '../backup'
import { mediaDB, onMediaChange } from '../db'
import { blobToPosterDataURL } from '../image'
import { isPlainObject, isSafeId, safeIso } from '../security'
import { scopedKey } from '../scope'
import { cloudFetch } from './api'
/**
* Synchronisation hors-ligne ↔ compte :
* - toutes les modifications sont d'abord écrites sur l'appareil (l'app marche sans réseau),
* - elles sont notées dans une « boîte d'envoi » puis envoyées dès que possible,
* - on récupère ensuite ce qui a changé ailleurs (autre téléphone, ordinateur…).
* En cas de conflit, la modification la plus récente gagne (vérifié aussi par la base).
*/
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor'>
export interface SyncHooks {
getLists: () => CustomList[]
applyLists: (lists: CustomList[]) => void
getSettings: () => SyncedSettings
applySettings: (s: Partial<SyncedSettings>) => void
itemsChanged: () => void
}
export interface SyncStatus {
state: 'idle' | 'syncing' | 'offline' | 'error'
lastSyncAt?: string
pending: number
error?: string
}
interface SyncMeta {
itemsCursor?: string
listsCursor?: string
settingsAt?: string
lastSyncAt?: string
/** clé (« i:<id> », « l:<id> », « s ») → horodatage de la modification locale */
outbox: Record<string, string>
}
const PAGE = 500
const MAX_ROW_BYTES = 380_000
const MAX_BATCH_BYTES = 1_500_000
const OVERLAP_MS = 60_000
const jsonHeaders = { 'Content-Type': 'application/json' }
export interface SyncEngine {
start: () => void
stop: () => void
syncNow: () => Promise<void>
markList: (id: string) => void
markSettings: () => void
status: () => SyncStatus
subscribe: (fn: (s: SyncStatus) => void) => () => void
}
export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
const META_KEY = scopedKey('sync', userId)
const loadMeta = (): SyncMeta => {
try {
const raw = JSON.parse(localStorage.getItem(META_KEY) ?? '{}') as unknown
if (!isPlainObject(raw)) return { outbox: {} }
const outbox: Record<string, string> = {}
if (isPlainObject(raw.outbox)) {
for (const [k, v] of Object.entries(raw.outbox)) {
if ((k === 's' || /^[il]:[A-Za-z0-9_-]{1,64}$/.test(k)) && safeIso(v)) outbox[k] = v as string
}
}
return {
itemsCursor: safeIso(raw.itemsCursor),
listsCursor: safeIso(raw.listsCursor),
settingsAt: safeIso(raw.settingsAt),
lastSyncAt: safeIso(raw.lastSyncAt),
outbox,
}
} catch {
return { outbox: {} }
}
}
let meta = loadMeta()
const saveMeta = () => {
try {
localStorage.setItem(META_KEY, JSON.stringify(meta))
} catch {
/* ignore */
}
}
let status: SyncStatus = { state: 'idle', lastSyncAt: meta.lastSyncAt, pending: Object.keys(meta.outbox).length }
const listeners = new Set<(s: SyncStatus) => void>()
const setStatus = (patch: Partial<SyncStatus>) => {
status = { ...status, ...patch, pending: Object.keys(meta.outbox).length }
for (const fn of listeners) fn(status)
}
const mark = (key: string) => {
meta.outbox[key] = new Date().toISOString()
saveMeta()
setStatus({})
schedule()
}
// ─── Envoi ───
/** Réduit une fiche trop lourde (affiche importée en très haute qualité) avant envoi. */
async function fitForUpload(item: MediaItem): Promise<MediaItem> {
if (JSON.stringify(item).length <= MAX_ROW_BYTES) return item
if (item.poster?.startsWith('data:image')) {
try {
const blob = await (await fetch(item.poster)).blob()
const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) }
if (JSON.stringify(smaller).length <= MAX_ROW_BYTES) return smaller
} catch {
/* image illisible */
}
}
const { poster: _poster, ...rest } = item
const stripped = rest as MediaItem
return JSON.stringify(stripped).length <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined }
}
async function upsert(table: 'items' | 'lists', rows: { id: string; data: unknown; deleted: boolean; updated_at: string }[]) {
// Envoi par paquets de taille raisonnable
let batch: typeof rows = []
let size = 0
const flush = async () => {
if (!batch.length) return
const res = await cloudFetch(`/rest/v1/${table}?on_conflict=user_id,id`, {
method: 'POST',
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify(batch.map((r) => ({ ...r, user_id: userId }))),
})
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
batch = []
size = 0
}
for (const r of rows) {
const bytes = JSON.stringify(r).length
if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush()
batch.push(r)
size += bytes
}
await flush()
}
async function push() {
const snapshot = { ...meta.outbox }
const keys = Object.keys(snapshot)
if (!keys.length) return
const itemIds = keys.filter((k) => k.startsWith('i:')).map((k) => k.slice(2))
if (itemIds.length) {
const rows = []
for (const id of itemIds) {
const item = await mediaDB.get(id)
if (item) {
const data = await fitForUpload(item)
rows.push({ id, data, deleted: false, updated_at: item.updatedAt })
} else {
rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] })
}
}
await upsert('items', rows)
}
const listIds = keys.filter((k) => k.startsWith('l:')).map((k) => k.slice(2))
if (listIds.length) {
const current = new Map(hooks.getLists().map((l) => [l.id, l]))
await upsert(
'lists',
listIds.map((id) => {
const l = current.get(id)
return { id, data: l ?? null, deleted: !l, updated_at: snapshot[`l:${id}`] }
}),
)
}
if (snapshot.s) {
const res = await cloudFetch('/rest/v1/settings?on_conflict=user_id', {
method: 'POST',
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
body: JSON.stringify({ user_id: userId, data: hooks.getSettings(), updated_at: snapshot.s }),
})
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
meta.settingsAt = snapshot.s
}
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
for (const k of keys) if (meta.outbox[k] === snapshot[k]) delete meta.outbox[k]
saveMeta()
}
// ─── Réception ───
type Row = { id: string; data: unknown; deleted: boolean; updated_at: string; server_updated_at: string }
async function fetchChanges(table: 'items' | 'lists', cursor?: string): Promise<{ rows: Row[]; cursor?: string }> {
const rows: Row[] = []
let after = cursor ? new Date(new Date(cursor).getTime() - OVERLAP_MS).toISOString() : undefined
let last = cursor
for (let page = 0; page < 200; page++) {
const q = new URLSearchParams({ select: 'id,data,deleted,updated_at,server_updated_at', order: 'server_updated_at.asc,id.asc', limit: String(PAGE) })
if (after) q.set('server_updated_at', `gt.${after}`)
const res = await cloudFetch(`/rest/v1/${table}?${q}`)
if (!res.ok) throw new Error(t('sync.err.pull', { status: res.status }))
const list = (await res.json()) as unknown
if (!Array.isArray(list)) throw new Error(t('auth.err.response'))
for (const r of list) {
if (!isPlainObject(r) || !isSafeId(r.id) || !safeIso(r.updated_at) || !safeIso(r.server_updated_at)) continue
rows.push(r as unknown as Row)
last = r.server_updated_at as string
}
if (list.length < PAGE) break
after = last
}
return { rows, cursor: last }
}
async function pullItems() {
const { rows, cursor } = await fetchChanges('items', meta.itemsCursor)
const toPut: MediaItem[] = []
const toRemove: string[] = []
for (const r of rows) {
if (meta.outbox[`i:${r.id}`]) continue // modification locale en attente : elle passera en priorité
const local = await mediaDB.get(r.id)
if (r.deleted) {
if (local) toRemove.push(r.id)
continue
}
const item = normalizeItem(r.data)
if (!item || item.id !== r.id) continue
if (local && local.updatedAt > item.updatedAt) continue
// Même version : on garde l'affiche locale si le serveur ne l'a pas (fiche allégée à l'envoi)
if (local && local.updatedAt === item.updatedAt && !item.poster && local.poster) item.poster = local.poster
if (local && JSON.stringify(local) === JSON.stringify(item)) continue
toPut.push(item)
}
await mediaDB.putMany(toPut, { silent: true })
await mediaDB.removeMany(toRemove, { silent: true })
meta.itemsCursor = safeIso(cursor)
saveMeta()
if (toPut.length || toRemove.length) hooks.itemsChanged()
}
async function pullLists() {
const { rows, cursor } = await fetchChanges('lists', meta.listsCursor)
if (rows.length) {
const map = new Map(hooks.getLists().map((l) => [l.id, l]))
let changed = false
for (const r of rows) {
if (meta.outbox[`l:${r.id}`]) continue
if (r.deleted) {
changed = map.delete(r.id) || changed
continue
}
const [l] = normalizeLists([r.data]) ?? []
if (l && l.id === r.id && JSON.stringify(map.get(l.id)) !== JSON.stringify(l)) {
map.set(l.id, l)
changed = true
}
}
if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)))
}
meta.listsCursor = safeIso(cursor)
saveMeta()
}
async function pullSettings() {
if (meta.outbox.s) return
const res = await cloudFetch('/rest/v1/settings?select=data,updated_at&limit=1')
if (!res.ok) throw new Error(t('sync.err.pull', { status: res.status }))
const [row] = (await res.json()) as { data?: unknown; updated_at?: string }[]
const at = safeIso(row?.updated_at)
if (!row || !at || (meta.settingsAt && at <= meta.settingsAt)) return
const s = normalizeSettings(row.data)
if (s) hooks.applySettings(s)
meta.settingsAt = at
saveMeta()
}
// ─── Orchestration ───
let running: Promise<void> | null = null
let again = false
let stopped = true
let timer: ReturnType<typeof setTimeout> | undefined
let interval: ReturnType<typeof setInterval> | undefined
async function cycle() {
if (!navigator.onLine) {
setStatus({ state: 'offline' })
return
}
setStatus({ state: 'syncing', error: undefined })
try {
await push()
await pullItems()
await pullLists()
await pullSettings()
meta.lastSyncAt = new Date().toISOString()
saveMeta()
setStatus({ state: 'idle', lastSyncAt: meta.lastSyncAt })
} catch (e) {
setStatus({ state: navigator.onLine ? 'error' : 'offline', error: (e as Error).message })
}
}
function syncNow(): Promise<void> {
if (stopped) return Promise.resolve()
if (running) {
again = true
return running
}
running = (async () => {
do {
again = false
await cycle()
} while (again && !stopped)
})().finally(() => {
running = null
})
return running
}
function schedule(delay = 1500) {
if (stopped) return
clearTimeout(timer)
timer = setTimeout(() => void syncNow(), delay)
}
const onOnline = () => schedule(300)
const onOffline = () => setStatus({ state: 'offline' })
const onVisible = () => document.visibilityState === 'visible' && schedule(300)
let unsubscribeDB: (() => void) | undefined
return {
start() {
if (!stopped) return
stopped = false
unsubscribeDB = onMediaChange((c) => {
const now = new Date().toISOString()
for (const i of c.put) meta.outbox[`i:${i.id}`] = now
for (const id of c.removed) meta.outbox[`i:${id}`] = now
saveMeta()
setStatus({})
schedule()
})
window.addEventListener('online', onOnline)
window.addEventListener('offline', onOffline)
document.addEventListener('visibilitychange', onVisible)
interval = setInterval(() => document.visibilityState === 'visible' && void syncNow(), 60_000)
void syncNow()
},
stop() {
stopped = true
clearTimeout(timer)
clearInterval(interval)
unsubscribeDB?.()
window.removeEventListener('online', onOnline)
window.removeEventListener('offline', onOffline)
document.removeEventListener('visibilitychange', onVisible)
},
syncNow,
markList: (id) => mark(`l:${id}`),
markSettings: () => mark('s'),
status: () => status,
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
}
}