Repository Public
1"use client";2import { useCallback, useEffect, useRef, useState } from "react";3import { clsx, type ClassValue } from "clsx";4import { twMerge } from "tailwind-merge";56export const cn = (...a: ClassValue[]) => twMerge(clsx(a));78export type Status = "up" | "down" | "unknown";9export interface Channel { id: string; name: string; country: string | null; categories: string[]; languages: string[]; logo: string | null; status: Status; streams: number; web: boolean; hasGuide: boolean; firstSeen: number; fav?: boolean; hidden?: boolean }10export interface Prog { start: number; stop: number; title: string; subtitle: string | null; description: string | null; category: string | null }11export interface StreamInfo { id: number; url: string; quality: string | null; labels: string[]; feed: string | null; status: Status; httpStatus: number | null; checkError: string | null; checkedAt: number | null; cors: boolean | null; contentType: string | null; insecure: boolean; needsHeaders: boolean; kind: "hls" | "dash" | "other"; playOk: boolean | null; playAt: number | null; source: string; relay?: boolean; relayOnly?: boolean }1213/** Answer of POST /api/relay/open: a temporary playback address on the relay engine. */14export interface RelayOpen { url: string; token: string; mode: "copy" | "transcode" | "audio" | null; shared: boolean; bufferSec: number; timeshift: { base: string; windowSec: number } | null }1516export class ApiError extends Error { constructor(public status: number, message: string, public data?: Record<string, unknown>) { super(message); } }17export async function api<T = unknown>(path: string, init?: { method?: string; body?: unknown; signal?: AbortSignal }): Promise<T> {18 const res = await fetch(`/api${path}`, { method: init?.method ?? (init?.body ? "POST" : "GET"), signal: init?.signal, credentials: "same-origin",19 // A change made just before leaving the page (favourite, hidden, playback report) must still reach the server.20 keepalive: !!init?.method || !!init?.body,21 headers: init?.body ? { "content-type": "application/json" } : undefined, body: init?.body ? JSON.stringify(init.body) : undefined });22 const data = await res.json().catch(() => ({}));23 if (res.status === 401 && !path.startsWith("/auth/")) { location.href = `/connexion?next=${encodeURIComponent(location.pathname + location.search)}`; }24 if (!res.ok) throw new ApiError(res.status, data.error ?? `Erreur ${res.status}`, data);25 return data as T;26}2728/** Fetch on mount and whenever `path` changes; `reload()` refetches silently. */29export function useApi<T>(path: string | null) {30 const [data, setData] = useState<T | null>(null);31 const [error, setError] = useState<string | null>(null);32 const [loading, setLoading] = useState(!!path);33 const seq = useRef(0);34 const load = useCallback(async (silent = false) => {35 if (!path) return;36 const my = ++seq.current;37 if (!silent) setLoading(true);38 try { const d = await api<T>(path); if (my === seq.current) { setData(d); setError(null); } }39 catch (e) { if (my === seq.current) setError((e as Error).message); }40 finally { if (my === seq.current) setLoading(false); }41 }, [path]);42 useEffect(() => { load(); }, [load]);43 return { data, error, loading, reload: useCallback(() => load(true), [load]), setData };44}4546const CAT_FR: Record<string, string> = {47 animation: "Animation", auto: "Auto", business: "Affaires", classic: "Classiques", comedy: "Humour", cooking: "Cuisine", culture: "Culture", documentary: "Documentaires",48 education: "Éducation", entertainment: "Divertissement", family: "Famille", general: "Généraliste", interactive: "Interactif", kids: "Jeunesse", legislative: "Parlementaire", lifestyle: "Art de vivre", movies: "Films",49 music: "Musique", news: "Actualités", outdoor: "Plein air", public: "Service public", relax: "Détente", religious: "Religion", science: "Science", series: "Séries", shop: "Téléachat", sports: "Sports",50 travel: "Voyage", weather: "Météo", xxx: "Adulte",51};52export const categoryLabel = (id: string, fallback?: string) => CAT_FR[id] ?? fallback ?? id;53let regions: Intl.DisplayNames | undefined, langs: Intl.DisplayNames | undefined;54export function countryName(code: string | null, fallback?: string): string {55 if (!code) return "Pays inconnu";56 try { return (regions ??= new Intl.DisplayNames(["fr-CA"], { type: "region" })).of(code) ?? fallback ?? code; } catch { return fallback ?? code; }57}58export function languageName(code: string, fallback?: string): string {59 try { const n = (langs ??= new Intl.DisplayNames(["fr-CA"], { type: "language" })).of(code); return n && n !== code ? n.charAt(0).toUpperCase() + n.slice(1) : fallback ?? code; } catch { return fallback ?? code; }60}61export const flag = (code: string | null) => (code && /^[A-Z]{2}$/.test(code) ? String.fromCodePoint(...[...code].map((c) => 0x1f1e6 + c.charCodeAt(0) - 65)) : "🌐");62export const STATUS_LABEL: Record<Status, string> = { up: "Disponible lors du dernier test", down: "Indisponible lors du dernier test", unknown: "Non vérifié" };6364const tf = new Intl.DateTimeFormat("fr-CA", { hour: "2-digit", minute: "2-digit" });65const df = new Intl.DateTimeFormat("fr-CA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });66export const hm = (t: number) => tf.format(t);67export const dateTime = (t: number | null | undefined) => (t ? df.format(t) : "jamais");68export function ago(t: number | null | undefined): string {69 if (!t) return "jamais";70 const s = Math.max(0, (Date.now() - t) / 1000);71 if (s < 60) return "à l'instant"; if (s < 3600) return `il y a ${Math.floor(s / 60)} min`; if (s < 86400) return `il y a ${Math.floor(s / 3600)} h`;72 return `il y a ${Math.floor(s / 86400)} j`;73}74export function currentProg(list: Prog[] | undefined, at = Date.now()): { now?: Prog; next?: Prog } {75 if (!list) return {};76 const i = list.findIndex((p) => p.start <= at && p.stop > at);77 return i >= 0 ? { now: list[i], next: list[i + 1] } : { next: list.find((p) => p.start > at) };78}79/** Re-render every `ms` so clocks and progress bars move. */80export function useNow(ms = 30_000) { const [t, set] = useState(() => Date.now()); useEffect(() => { const i = setInterval(() => set(Date.now()), ms); return () => clearInterval(i); }, [ms]); return t; }81export function useDebounced<T>(value: T, ms: number): T { const [v, set] = useState(value); useEffect(() => { const t = setTimeout(() => set(value), ms); return () => clearTimeout(t); }, [value, ms]); return v; }8283// --- films & series -------------------------------------------------------------------------------------------------84export interface Title {85 id: number; kind: "movie" | "series"; title: string; original: string | null; year: number | null; runtime: number | null; genres: string[]; languages: string[]; countries: string[];86 poster: string | null; backdrop: string | null; documentary: boolean; animation: boolean; short: boolean; rights: "pd" | "cc" | "personal" | "official" | "provider"; source: string; library: boolean; addedAt: number;87 episodes: number; fav?: boolean; progress?: { position: number; duration: number | null; completed: boolean; mediaId: number; label?: string } | null;88}89export interface TitleFull extends Title { synopsis: string | null; synopsisSource: string | null; directors: string[]; cast: string[]; rightsBasis: string; rightsUrl: string | null; sourceUrl: string | null; tmdb?: string | null }90export interface MediaInfo { mediaId: number; duration: number | null; height: number | null; subtitles: string[]; audio: string[]; position: number; completed: boolean; playback: string }91export interface Episode extends MediaInfo { id: number; season: number; episode: number; name: string | null; synopsis: string | null; airDate: string | null }92export interface TitleDetail { title: TitleFull; media: MediaInfo | null; seasons: { season: number; episodes: Episode[] }[]; resume: { mediaId: number; position: number; label: string | null } | null }93export interface PlayInfo {94 mediaId: number; titleId: number; title: string; kind: "movie" | "series"; poster: string | null; episode: { season: number; episode: number; name: string | null } | null;95 embed: string | null; sourceUrl: string | null; sourceName: string; direct: string | null; hls: string | null; playback: string; container: string | null; external: boolean; duration: number | null; position: number;96 subtitles: { label: string; lang: string; url: string }[]; audio: { index: number; label: string; lang: string }[]; next: { mediaId: number; label: string } | null;97}98export const RIGHTS_LABEL: Record<Title["rights"], string> = { pd: "Domaine public", cc: "Licence libre", personal: "Bibliothèque personnelle", official: "Diffusion officielle gratuite", provider: "Fournisseur autorisé" };99export function duration(sec: number | null | undefined): string {100 if (!sec) return "";101 const h = Math.floor(sec / 3600), m = Math.round((sec % 3600) / 60);102 return h ? `${h} h ${String(m).padStart(2, "0")}` : `${Math.max(1, m)} min`;103}104export function clock(sec: number): string {105 if (!Number.isFinite(sec) || sec < 0) sec = 0;106 const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = Math.floor(sec % 60);107 return h ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;108}109export const langLabel = (code: string) => languageName(code, code.toUpperCase());110