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

+4
View File
@@ -25,6 +25,7 @@ import { RatingInput } from '../Rating'
import SharePreview from '../SharePreview'
import EditDetails from './EditDetails'
import ReviewEditor from './ReviewEditor'
import WhereToWatch from './WhereToWatch'
/** Suivi « vide » d'un titre qu'on ajoute. */
const BLANK: Pick<MediaInput, 'criteria' | 'episodesWatched' | 'genres'> = { criteria: {}, episodesWatched: 0, genres: [] }
@@ -471,6 +472,9 @@ export default function TitleSheet({ item: initial, seed, onClose, onGoToSetting
</section>
)}
{/* Où regarder (plateformes de streaming) */}
<WhereToWatch extras={extras} />
{/* Casting */}
{extras && extras.cast.length > 0 && (
<section className="mt-8">
+150
View File
@@ -0,0 +1,150 @@
import { ChevronDown, ExternalLink, Globe } from 'lucide-react'
import { useMemo, type ReactNode } from 'react'
import { t } from '../../i18n'
import type { TitleExtras } from '../../lib/catalogApi'
import { tmdbSized } from '../../lib/tmdbImage'
import { countryName, defaultWatchRegion, OFFER_KINDS, setWatchRegion, useWatchRegion, type StreamLink, type WatchProvider } from '../../lib/watchProviders'
const JUSTWATCH = 'https://www.justwatch.com'
/**
* « Où regarder » sur la fiche d'un titre :
* - TMDB : offres du pays choisi (abonnement, gratuit, location, achat), données JustWatch ;
* - AniList : liens directs vers les plateformes de streaming.
* Rien de connu → rien n'est affiché.
*/
export default function WhereToWatch({ extras }: { extras?: TitleExtras }) {
if (extras?.watch && Object.keys(extras.watch).length > 0) return <TmdbOffers watch={extras.watch} />
if (extras?.streaming && extras.streaming.length > 0) return <StreamLinks links={extras.streaming} />
return null
}
function Section({ children, aside }: { children: ReactNode; aside?: ReactNode }) {
return (
<section className="mx-4 mt-8" aria-labelledby="where-to-watch">
<div className="mb-3 flex items-center justify-between gap-3">
<h3 id="where-to-watch" className="eyebrow text-ink-2">
{t('watch.title')}
</h3>
{aside}
</div>
{children}
</section>
)
}
function TmdbOffers({ watch }: { watch: NonNullable<TitleExtras['watch']> }) {
const country = useWatchRegion()
const offers = watch[country]
const rows = OFFER_KINDS.map((kind) => ({ kind, list: offers?.[kind] ?? [] })).filter((r) => r.list.length > 0)
// Pays proposés : ceux où le titre est disponible (+ le pays actuel), triés par nom
const countries = useMemo(() => {
const codes = new Set([...Object.keys(watch), country])
return [...codes].map((code) => ({ code, name: countryName(code) })).sort((a, b) => a.name.localeCompare(b.name))
}, [watch, country])
const picker = (
<label className="relative flex items-center gap-1 rounded-full border border-line py-1 pe-2 ps-2 text-xs text-ink-2 focus-within:border-line-strong">
<Globe size={13} className="shrink-0 text-ink-3" aria-hidden />
<span className="sr-only">{t('watch.country')}</span>
<select
value={country}
onChange={(e) => setWatchRegion(e.target.value === defaultWatchRegion() ? null : e.target.value)}
className="max-w-36 appearance-none truncate bg-transparent pe-0.5 text-xs font-medium text-ink outline-none"
>
{countries.map((c) => (
<option key={c.code} value={c.code} className="bg-surface text-ink">
{c.name}
</option>
))}
</select>
<ChevronDown size={12} className="pointer-events-none shrink-0 text-ink-3" aria-hidden />
</label>
)
return (
<Section aside={picker}>
{rows.length > 0 ? (
<div className="space-y-3">
{rows.map(({ kind, list }) => (
<div key={kind} className="flex items-start gap-3">
<span className="w-20 shrink-0 pt-3 text-xs text-ink-3">{t(`watch.${kind}`)}</span>
<ul className="flex min-w-0 flex-1 flex-wrap gap-2">
{list.map((p) => (
<li key={p.id}>
<ProviderLogo provider={p} href={offers?.link} />
</li>
))}
</ul>
</div>
))}
</div>
) : (
<p className="text-sm text-ink-3">{t('watch.none')}</p>
)}
<p className="mt-3 text-[11px] text-ink-3">
<a href={JUSTWATCH} target="_blank" rel="noopener noreferrer" className="underline-offset-2 hover:underline">
{t('watch.source')}
</a>
</p>
</Section>
)
}
function ProviderLogo({ provider, href }: { provider: WatchProvider; href?: string }) {
const logo = provider.logo ? (
<img
src={provider.logo}
srcSet={`${provider.logo} 1x, ${tmdbSized(provider.logo, 'w154')} 2x`}
alt={provider.name}
title={provider.name}
loading="lazy"
className="size-11 rounded-xl border border-line bg-surface-2 object-cover"
/>
) : (
<span title={provider.name} className="grid size-11 place-items-center rounded-xl border border-line bg-surface-2 text-sm font-semibold text-ink-2">
<span aria-hidden>{provider.name.charAt(0)}</span>
<span className="sr-only">{provider.name}</span>
</span>
)
if (!href) return logo
return (
<a href={href} target="_blank" rel="noopener noreferrer" aria-label={t('watch.open', { name: provider.name })} className="block rounded-xl transition-transform active:scale-95">
{logo}
</a>
)
}
function StreamLinks({ links }: { links: StreamLink[] }) {
return (
<Section>
<ul className="flex flex-wrap gap-2">
{links.map((l) => (
<li key={l.site}>
<a
href={l.url}
target="_blank"
rel="noopener noreferrer"
aria-label={t('watch.open', { name: l.site })}
title={l.language ? `${l.site} · ${l.language}` : l.site}
className="flex items-center gap-2 rounded-full border border-line py-1 pe-3 ps-1 text-sm font-medium text-ink transition-colors active:bg-surface-2"
>
{l.icon ? (
<span className="grid size-7 shrink-0 place-items-center rounded-full bg-surface-2" style={l.color ? { backgroundColor: l.color } : undefined}>
<img src={l.icon} alt="" loading="lazy" className="size-4 object-contain" />
</span>
) : (
<span className="grid size-7 shrink-0 place-items-center rounded-full bg-surface-2 text-xs font-semibold text-ink-2" aria-hidden>
{l.site.charAt(0)}
</span>
)}
{l.site}
<ExternalLink size={13} className="text-ink-3" aria-hidden />
</a>
</li>
))}
</ul>
</Section>
)
}
+10
View File
@@ -1035,6 +1035,16 @@ const dict: Translations = {
'sync.pending_two': "تعديلان في الانتظار",
'sync.pending_few': "{count} تعديلات في الانتظار",
'sync.pending_many': "{count} تعديلًا في الانتظار",
// — Où regarder —
'watch.title': "أين تشاهد",
'watch.flatrate': "اشتراك",
'watch.free': "مجاني",
'watch.rent': "استئجار",
'watch.buy': "شراء",
'watch.country': "البلد",
'watch.none': "غير متاح للبث في هذا البلد.",
'watch.source': "البيانات من JustWatch",
'watch.open': "شاهد على {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} Änderung ausstehend",
'sync.pending_other': "{count} Änderungen ausstehend",
'sync.now': "Jetzt synchronisieren",
// — Où regarder —
'watch.title': "Wo ansehen",
'watch.flatrate': "Abo",
'watch.free': "Kostenlos",
'watch.rent': "Leihen",
'watch.buy': "Kaufen",
'watch.country': "Land",
'watch.none': "In diesem Land nicht im Stream verfügbar.",
'watch.source': "Daten von JustWatch",
'watch.open': "Auf {name} ansehen",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} change waiting",
'sync.pending_other': "{count} changes waiting",
'sync.now': "Sync now",
// — Où regarder —
'watch.title': "Where to watch",
'watch.flatrate': "Stream",
'watch.free': "Free",
'watch.rent': "Rent",
'watch.buy': "Buy",
'watch.country': "Country",
'watch.none': "Not available to stream in this country.",
'watch.source': "Data by JustWatch",
'watch.open': "Watch on {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} cambio pendiente",
'sync.pending_other': "{count} cambios pendientes",
'sync.now': "Sincronizar",
// — Où regarder —
'watch.title': "Dónde ver",
'watch.flatrate': "Suscripción",
'watch.free': "Gratis",
'watch.rent': "Alquiler",
'watch.buy': "Compra",
'watch.country': "País",
'watch.none': "No disponible en streaming en este país.",
'watch.source': "Datos de JustWatch",
'watch.open': "Ver en {name}",
}
export default dict
+10
View File
@@ -899,6 +899,16 @@ const dict = {
'sync.pending_one': "{count} modification en attente",
'sync.pending_other': "{count} modifications en attente",
'sync.now': "Synchroniser",
// — Où regarder —
'watch.title': "Où regarder",
'watch.flatrate': "Abonnement",
'watch.free': "Gratuit",
'watch.rent': "Location",
'watch.buy': "Achat",
'watch.country': "Pays",
'watch.none': "Pas disponible en streaming dans ce pays.",
'watch.source': "Données JustWatch",
'watch.open': "Regarder sur {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} बदलाव बाकी",
'sync.pending_other': "{count} बदलाव बाकी",
'sync.now': "अभी सिंक करें",
// — Où regarder —
'watch.title': "कहाँ देखें",
'watch.flatrate': "सब्सक्रिप्शन",
'watch.free': "मुफ़्त",
'watch.rent': "किराया",
'watch.buy': "खरीदें",
'watch.country': "देश",
'watch.none': "इस देश में स्ट्रीमिंग पर उपलब्ध नहीं।",
'watch.source': "डेटा: JustWatch",
'watch.open': "{name} पर देखें",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} perubahan menunggu",
'sync.pending_other': "{count} perubahan menunggu",
'sync.now': "Sinkronkan",
// — Où regarder —
'watch.title': "Tempat menonton",
'watch.flatrate': "Langganan",
'watch.free': "Gratis",
'watch.rent': "Sewa",
'watch.buy': "Beli",
'watch.country': "Negara",
'watch.none': "Tidak tersedia untuk streaming di negara ini.",
'watch.source': "Data dari JustWatch",
'watch.open': "Tonton di {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} modifica in attesa",
'sync.pending_other': "{count} modifiche in attesa",
'sync.now': "Sincronizza",
// — Où regarder —
'watch.title': "Dove guardarlo",
'watch.flatrate': "Abbonamento",
'watch.free': "Gratis",
'watch.rent': "Noleggio",
'watch.buy': "Acquisto",
'watch.country': "Paese",
'watch.none': "Non disponibile in streaming in questo paese.",
'watch.source': "Dati JustWatch",
'watch.open': "Guarda su {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} 件の変更が保留中",
'sync.pending_other': "{count} 件の変更が保留中",
'sync.now': "今すぐ同期",
// — Où regarder —
'watch.title': "視聴方法",
'watch.flatrate': "定額見放題",
'watch.free': "無料",
'watch.rent': "レンタル",
'watch.buy': "購入",
'watch.country': "国",
'watch.none': "この国では配信されていません。",
'watch.source': "データ提供:JustWatch",
'watch.open': "{name}で見る",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "변경 {count}개 대기 중",
'sync.pending_other': "변경 {count}개 대기 중",
'sync.now': "지금 동기화",
// — Où regarder —
'watch.title': "볼 수 있는 곳",
'watch.flatrate': "구독",
'watch.free': "무료",
'watch.rent': "대여",
'watch.buy': "구매",
'watch.country': "국가",
'watch.none': "이 국가에서는 스트리밍되지 않아요.",
'watch.source': "데이터 제공: JustWatch",
'watch.open': "{name}에서 보기",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} wijziging in wachtrij",
'sync.pending_other': "{count} wijzigingen in wachtrij",
'sync.now': "Nu synchroniseren",
// — Où regarder —
'watch.title': "Waar te kijken",
'watch.flatrate': "Abonnement",
'watch.free': "Gratis",
'watch.rent': "Huren",
'watch.buy': "Kopen",
'watch.country': "Land",
'watch.none': "Niet te streamen in dit land.",
'watch.source': "Gegevens van JustWatch",
'watch.open': "Kijk op {name}",
}
export default dict
+10
View File
@@ -989,6 +989,16 @@ const dict: Translations = {
'sync.now': "Synchronizuj",
'sync.pending_few': "{count} zmiany oczekują",
'sync.pending_many': "{count} zmian oczekuje",
// — Où regarder —
'watch.title': "Gdzie obejrzeć",
'watch.flatrate': "Abonament",
'watch.free': "Za darmo",
'watch.rent': "Wypożyczenie",
'watch.buy': "Zakup",
'watch.country': "Kraj",
'watch.none': "Niedostępne w streamingu w tym kraju.",
'watch.source': "Dane: JustWatch",
'watch.open': "Oglądaj w {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} alteração pendente",
'sync.pending_other': "{count} alterações pendentes",
'sync.now': "Sincronizar",
// — Où regarder —
'watch.title': "Onde assistir",
'watch.flatrate': "Assinatura",
'watch.free': "Grátis",
'watch.rent': "Aluguel",
'watch.buy': "Compra",
'watch.country': "País",
'watch.none': "Indisponível em streaming neste país.",
'watch.source': "Dados do JustWatch",
'watch.open': "Assistir em {name}",
}
export default dict
+10
View File
@@ -989,6 +989,16 @@ const dict: Translations = {
'sync.now': "Синхронизировать",
'sync.pending_few': "{count} изменения ожидают",
'sync.pending_many': "{count} изменений ожидают",
// — Où regarder —
'watch.title': "Где смотреть",
'watch.flatrate': "Подписка",
'watch.free': "Бесплатно",
'watch.rent': "Аренда",
'watch.buy': "Покупка",
'watch.country': "Страна",
'watch.none': "Недоступно для просмотра онлайн в этой стране.",
'watch.source': "Данные JustWatch",
'watch.open': "Смотреть на {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "รอซิงค์ {count} รายการ",
'sync.pending_other': "รอซิงค์ {count} รายการ",
'sync.now': "ซิงค์ตอนนี้",
// — Où regarder —
'watch.title': "ดูได้ที่ไหน",
'watch.flatrate': "สมัครสมาชิก",
'watch.free': "ฟรี",
'watch.rent': "เช่า",
'watch.buy': "ซื้อ",
'watch.country': "ประเทศ",
'watch.none': "ไม่มีให้สตรีมในประเทศนี้",
'watch.source': "ข้อมูลจาก JustWatch",
'watch.open': "ดูบน {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} değişiklik bekliyor",
'sync.pending_other': "{count} değişiklik bekliyor",
'sync.now': "Şimdi eşitle",
// — Où regarder —
'watch.title': "Nerede izlenir",
'watch.flatrate': "Abonelik",
'watch.free': "Ücretsiz",
'watch.rent': "Kiralık",
'watch.buy': "Satın al",
'watch.country': "Ülke",
'watch.none': "Bu ülkede yayın platformlarında yok.",
'watch.source': "Veriler: JustWatch",
'watch.open': "{name} üzerinde izle",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} thay đổi đang chờ",
'sync.pending_other': "{count} thay đổi đang chờ",
'sync.now': "Đồng bộ ngay",
// — Où regarder —
'watch.title': "Xem ở đâu",
'watch.flatrate': "Gói thuê bao",
'watch.free': "Miễn phí",
'watch.rent': "Thuê",
'watch.buy': "Mua",
'watch.country': "Quốc gia",
'watch.none': "Không có trên nền tảng streaming ở quốc gia này.",
'watch.source': "Dữ liệu từ JustWatch",
'watch.open': "Xem trên {name}",
}
export default dict
+10
View File
@@ -897,6 +897,16 @@ const dict: Translations = {
'sync.pending_one': "{count} 项更改待上传",
'sync.pending_other': "{count} 项更改待上传",
'sync.now': "立即同步",
// — Où regarder —
'watch.title': "在哪里看",
'watch.flatrate': "订阅",
'watch.free': "免费",
'watch.rent': "租借",
'watch.buy': "购买",
'watch.country': "国家/地区",
'watch.none': "该国家/地区暂无在线播放。",
'watch.source': "数据来自 JustWatch",
'watch.open': "在 {name} 观看",
}
export default dict
+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
}
}