Fiche : « Où regarder » (plateformes de streaming)

- TMDB : offres par pays (abonnement, gratuit/avec pub, location, achat) via
  append_to_response=credits,watch/providers dans getTitleExtras (une seule requête),
  logos en rangée, lien vers la page TMDB/JustWatch, mention « Données JustWatch ».
- Pays : langue du navigateur, sinon pays de l'app, sinon FR ; sélecteur sur la fiche
  (mémorisé dans le localStorage, try/catch).
- AniList : liens externalLinks de type STREAMING (icône, couleur, lien direct).
- Données nettoyées (liens HTTPS, hôtes d'images autorisés, couleurs #rrggbb).
- Proxy tmdb : append_to_response accepte une combinaison des valeurs déjà permises ;
  repli sur « credits » seul tant que la fonction n'est pas redéployée.
- Crédit JustWatch dans legal.html et privacy.html ; textes dans les 18 langues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-10-09 15:07:36 +00:00
1 parent c246b16e7e
commit 3c0ffe40c6
26 files changed
+526 -5

No files matched your search

+16 -1
View File
@@ -6,6 +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'
/**
* Recherche dans les bases publiques :
@@ -1041,6 +1042,10 @@ export interface TitleExtras {
tagline?: string
runtime?: number
seasons?: number
/** Où regarder, par pays (TMDB / JustWatch). Absent = inconnu (ex. proxy pas encore à jour). */
watch?: Record<string, WatchRegion>
/** Liens directs vers les plateformes de streaming (AniList) */
streaming?: StreamLink[]
}
interface TmdbExtras {
@@ -1056,13 +1061,19 @@ interface TmdbExtras {
cast?: { name?: string; character?: string; profile_path?: string | null; order?: number }[]
crew?: { name?: string; job?: string }[]
}
'watch/providers'?: unknown
}
const extrasCache = new Map<string, Promise<TitleExtras>>()
async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras> {
const [, kind, id] = externalId.split(':') as ['tmdb', 'movie' | 'tv', string]
const d = await tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
// 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
return tmdbFetch<TmdbExtras>(`/${kind}/${id}`, key, { append_to_response: 'credits' })
})
const cast = (Array.isArray(d.credits?.cast) ? d.credits!.cast! : [])
.slice()
.sort((a, b) => (a.order ?? 99) - (b.order ?? 99))
@@ -1088,6 +1099,7 @@ async function tmdbExtras(externalId: string, key: string): Promise<TitleExtras>
tagline: cleanText(d.tagline, 200),
runtime: count(kind === 'movie' ? d.runtime : d.episode_run_time?.[0], 6000),
seasons: kind === 'tv' ? count(d.number_of_seasons, 500) : undefined,
watch: parseTmdbProviders(d['watch/providers']),
}
}
@@ -1105,6 +1117,7 @@ query ($id: Int) {
}
}
staff(sort: [RELEVANCE], perPage: 12) { edges { role node { name { full } } } }
externalLinks { site url type language color icon }
}
}`
@@ -1115,6 +1128,7 @@ interface AniExtras {
stats?: { scoreDistribution?: { score?: number; amount?: number }[] | null } | null
characters?: { edges?: { node?: { name?: { full?: string }; image?: { medium?: string } }; voiceActors?: { name?: { full?: string } }[] }[] } | null
staff?: { edges?: { role?: string; node?: { name?: { full?: string } } }[] } | null
externalLinks?: unknown
}
async function aniListExtras(externalId: string): Promise<TitleExtras> {
@@ -1153,6 +1167,7 @@ async function aniListExtras(externalId: string): Promise<TitleExtras> {
directors: names(staff.filter((s) => /^Director$/i.test(s.role ?? '')).map((s) => s.node?.name?.full), 3),
directorKind: 'director',
runtime: count(m.duration, 6000),
streaming: parseAniListLinks(m.externalLinks),
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
const TMDB_SIZED = /^(https:\/\/image\.tmdb\.org\/t\/p\/)(w\d{2,4}|original)(\/[A-Za-z0-9_-]{1,100}\.(?:jpg|jpeg|png|webp))$/i
/** Même image TMDB dans une autre largeur (autres images : inchangées). */
export function tmdbSized(url: string | undefined, size: 'w300' | 'w780' | 'w1280' | 'original'): string | undefined {
export function tmdbSized(url: string | undefined, size: 'w92' | 'w154' | 'w300' | 'w780' | 'w1280' | 'original'): string | undefined {
const m = url && TMDB_SIZED.exec(url)
return m ? `${m[1]}${size}${m[3]}` : url
}
+170
View File
@@ -0,0 +1,170 @@
import { useSyncExternalStore } from 'react'
import { locale, region } from '../i18n'
import { cleanText, isHexColor, isPlainObject, isSafeTmdbPath, remoteImage, storageGet, storageSet } from './security'
/**
* « Où regarder » : plateformes de streaming d'un titre.
* - TMDB fournit, pour chaque pays, les offres d'abonnement / location / achat / gratuites (données JustWatch).
* - AniList fournit des liens directs vers les plateformes (Crunchyroll, Netflix, ADN…).
* Les réponses des API ne sont pas fiables : chaque champ est vérifié et borné.
*/
export interface WatchProvider {
id: number
name: string
/** Logo carré (image.tmdb.org) */
logo?: string
}
export type OfferKind = 'flatrate' | 'free' | 'rent' | 'buy'
export const OFFER_KINDS: OfferKind[] = ['flatrate', 'free', 'rent', 'buy']
export interface WatchRegion {
/** Page « Où regarder » de TMDB pour ce pays (liens JustWatch vers chaque plateforme) */
link?: string
flatrate: WatchProvider[]
free: WatchProvider[]
rent: WatchProvider[]
buy: WatchProvider[]
}
/** Lien direct vers une plateforme (AniList). */
export interface StreamLink {
site: string
url: string
icon?: string
color?: string
language?: string
}
const TMDB_IMG = 'https://image.tmdb.org/t/p'
const MAX_PER_KIND = 24
const MAX_REGIONS = 250
/** Lien HTTPS « propre » (sans identifiants ni port exotique), d'un site autorisé si une liste est donnée. */
export function safeLink(value: unknown, hosts?: string[]): string | undefined {
if (typeof value !== 'string' || value.length > 400) return undefined
try {
const u = new URL(value.trim())
if (u.protocol !== 'https:' || u.username || u.password || u.port) return undefined
if (hosts && !hosts.includes(u.hostname)) return undefined
return u.toString()
} catch {
return undefined
}
}
function providers(list: unknown): WatchProvider[] {
if (!Array.isArray(list)) return []
const out: (WatchProvider & { order: number })[] = []
for (const p of list.slice(0, 60)) {
if (!isPlainObject(p)) continue
const id = p.provider_id
const name = cleanText(p.provider_name, 60)
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0 || !name || out.some((x) => x.id === id)) continue
const logo = isSafeTmdbPath(p.logo_path) ? `${TMDB_IMG}/w92${p.logo_path}` : undefined
out.push({ id, name, logo, order: typeof p.display_priority === 'number' ? p.display_priority : 999 })
}
// Ordre de TMDB (les plateformes les plus courantes du pays d'abord)
return out
.sort((a, b) => a.order - b.order)
.slice(0, MAX_PER_KIND)
.map(({ id, name, logo }) => ({ id, name, logo }))
}
/** Réponse TMDB `watch/providers` → offres par pays (codes ISO à 2 lettres). */
export function parseTmdbProviders(raw: unknown): Record<string, WatchRegion> | undefined {
const results = isPlainObject(raw) && isPlainObject(raw.results) ? raw.results : undefined
if (!results) return undefined
const out: Record<string, WatchRegion> = {}
let n = 0
for (const [code, r] of Object.entries(results)) {
if (n >= MAX_REGIONS) break
if (!/^[A-Z]{2}$/.test(code) || !isPlainObject(r)) continue
const free = providers([...(Array.isArray(r.free) ? r.free : []), ...(Array.isArray(r.ads) ? r.ads : [])])
const region: WatchRegion = {
link: safeLink(r.link, ['www.themoviedb.org', 'themoviedb.org']),
flatrate: providers(r.flatrate),
free,
rent: providers(r.rent),
buy: providers(r.buy),
}
if (OFFER_KINDS.some((k) => region[k].length)) {
out[code] = region
n++
}
}
return out
}
/** `externalLinks` d'AniList → liens de streaming (dédoublonnés par site). */
export function parseAniListLinks(raw: unknown): StreamLink[] {
if (!Array.isArray(raw)) return []
const out: StreamLink[] = []
for (const l of raw.slice(0, 40)) {
if (!isPlainObject(l) || l.type !== 'STREAMING') continue
const site = cleanText(l.site, 40)
const url = safeLink(l.url)
if (!site || !url) continue
const language = cleanText(l.language, 30)
// Même plateforme dans plusieurs langues : une seule pastille (la première donnée par AniList)
if (out.some((x) => x.site === site)) continue
out.push({ site, url, icon: remoteImage(l.icon), color: isHexColor(l.color) ? l.color : undefined, language })
if (out.length >= 16) break
}
return out
}
// ─────────────────────────── Pays choisi ───────────────────────────
const STORAGE_KEY = 'azuucine:watchRegion'
const listeners = new Set<() => void>()
/** Pays par défaut : celui de la langue du navigateur (« fr-BE » → BE), sinon celui de l'app, sinon la France. */
export function defaultWatchRegion(): string {
try {
for (const tag of navigator.languages?.length ? navigator.languages : [navigator.language]) {
const m = /^[a-z]{2,3}[-_]([A-Z]{2})\b/i.exec(tag ?? '')
if (m) return m[1].toUpperCase()
}
} catch {
/* ignore */
}
const r = region()
return r && /^[A-Z]{2}$/.test(r) ? r : 'FR'
}
/** Pays choisi à la main (ou undefined = automatique). */
function chosenRegion(): string | undefined {
const v = storageGet(STORAGE_KEY)
return v && /^[A-Z]{2}$/.test(v) ? v : undefined
}
export const getWatchRegion = () => chosenRegion() ?? defaultWatchRegion()
/** Change le pays (null = revenir au pays automatique). */
export function setWatchRegion(code: string | null) {
storageSet(STORAGE_KEY, code && /^[A-Z]{2}$/.test(code) ? code : null)
listeners.forEach((f) => f())
}
/** Pays utilisé pour « Où regarder », mis à jour quand on le change. */
export function useWatchRegion(): string {
return useSyncExternalStore(
(f) => {
listeners.add(f)
return () => listeners.delete(f)
},
getWatchRegion,
getWatchRegion,
)
}
/** Nom du pays dans la langue de l'app (« FR » → « France »). */
export function countryName(code: string): string {
try {
return new Intl.DisplayNames([locale()], { type: 'region' }).of(code) ?? code
} catch {
return code
}
}