SPB Git

Repository Public

player.tsx 38.6 KB 477 lines tsx

1"use client";2import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";3import type Hls from "hls.js";4import {5  Airplay, AlertTriangle, ChevronDown, ChevronLeft, ChevronRight, Copy, List, Maximize, Minimize, Pause, PictureInPicture2, Play, RefreshCw, Settings2, Star,6  Volume2, VolumeX, X,7} from "lucide-react";8import { api, cn, countryName, currentProg, dateTime, flag, hm, STATUS_LABEL, useNow, type Channel, type Prog, type StreamInfo, type RelayOpen } from "@/lib/client";9import { Logo, StatusDot } from "./ui";1011// One <video> element for the whole app: it lives in the shell, so changing channel or page never reloads anything.12// Streams are played straight from their origin (hls.js, or the native player on Apple devices). Nothing is proxied.1314type Mode = "closed" | "mini" | "full";15interface PlayerApi { channel: Channel | null; mode: Mode; play: (c: Channel, queue?: Channel[], mode?: Mode) => void; close: () => void; onFavChange: (id: string, fav: boolean) => void; favVersion: number }16const PlayerCtx = createContext<PlayerApi | null>(null);17export const usePlayer = () => useContext(PlayerCtx)!;1819type Phase = "idle" | "loading" | "playing" | "paused" | "buffering" | "error";20interface Failure { title: string; detail: string; hints: string[] }21interface Detail { channel: Channel & { website: string | null; network: string | null }; streams: StreamInfo[]; programmes: Prog[]; lists: number[] }2223const nativeHls = () => typeof document !== "undefined" && !!document.createElement("video").canPlayType("application/vnd.apple.mpegurl");2425/** Says precisely why a stream cannot be played here, from what the browser reported and what the server-side test recorded. */26function explain(s: StreamInfo, client: string, code?: number): Failure {27  const hints: string[] = [];28  let title = "Lecture impossible", detail = client;29  if (s.insecure && location.protocol === "https:") {30    title = "Flux HTTP non chiffré";31    detail = "Ce flux est diffusé en HTTP. Les navigateurs bloquent ce contenu sur une page HTTPS (contenu mixte), et SP TV ne relaie pas la vidéo. Il reste lisible dans un lecteur externe (VLC, par exemple) avec son URL.";32  } else if (/DRM/.test(client)) {33    title = "Flux protégé (DRM)";34    detail = "Ce flux DASH est chiffré par son diffuseur et ne se lit que dans son propre service. SP TV ne contourne pas ces protections.";35  } else if (code === 403 || code === 451 || s.httpStatus === 403 || s.httpStatus === 451) {36    title = "Accès refusé par la source";37    detail = `La source refuse la lecture (HTTP ${code || s.httpStatus}). C'est le plus souvent une restriction géographique ou un contrôle d'accès du diffuseur ; SP TV ne les contourne pas.`;38  } else if (s.status === "down" && s.checkError) {39    title = "Flux indisponible";40    detail = `Lors du dernier test (${dateTime(s.checkedAt)}), la source a répondu : ${s.checkError}.`;41  } else if (s.cors === false && !nativeHls()) {42    title = "Lecture bloquée par la source (CORS)";43    detail = "La source n'autorise pas la lecture depuis un autre site dans ce navigateur (en-têtes CORS absents). Le lecteur natif de Safari (macOS, iPhone, iPad) n'a pas cette contrainte.";44  }45  if (s.needsHeaders) hints.push("La playlist indique que ce flux exige un Referer ou un User-Agent particulier, qu'un navigateur ne peut pas envoyer.");46  if (s.labels.some((l) => /geo/i.test(l))) hints.push("IPTV-org signale ce flux comme géobloqué.");47  if (s.labels.some((l) => /24\/7/i.test(l))) hints.push("IPTV-org signale que ce flux n'émet pas en continu.");48  if (s.status === "up" && title === "Lecture impossible") hints.push(`Le serveur répondait lors du dernier test (${dateTime(s.checkedAt)}) : le problème vient de ce navigateur ou du format du flux.`);49  if (s.status === "unknown") hints.push("Ce flux n'a pas encore été vérifié par le serveur.");50  return { title, detail, hints };51}5253function Btn({ label, onClick, children, className, active }: { label: string; onClick: () => void; children: React.ReactNode; className?: string; active?: boolean }) {54  return <button type="button" aria-label={label} title={label} onClick={onClick} className={cn("grid h-12 w-12 shrink-0 place-items-center rounded-full text-white transition hover:bg-white/15 active:scale-95", active && "bg-white/20", className)}>{children}</button>;55}5657export function PlayerProvider({ children }: { children: React.ReactNode }) {58  const [channel, setChannel] = useState<Channel | null>(null);59  const [queue, setQueue] = useState<Channel[]>([]);60  const [mode, setMode] = useState<Mode>("closed");61  const [favVersion, setFavVersion] = useState(0);62  const modeRef = useRef(mode); modeRef.current = mode;6364  const setFull = useCallback((on: boolean) => {65    if (on && modeRef.current !== "full") history.pushState({ sptv: "player" }, "");66    setMode(on ? "full" : "mini");67  }, []);68  const play = useCallback((c: Channel, q?: Channel[], m: Mode = "full") => {69    dispatchEvent(new Event("sptv:live-start")); // the on-demand player stops when live TV starts70    setChannel(c); if (q?.length) setQueue(q);71    if (m === "full") setFull(true); else setMode(m);72  }, [setFull]);73  const close = useCallback(() => { if (modeRef.current === "full") history.back(); setMode("closed"); setChannel(null); }, []);74  // The Back button (browser or remote) leaves the full-screen player without leaving the page.75  useEffect(() => {76    const onPop = () => { if (modeRef.current === "full") setMode("mini"); };77    addEventListener("popstate", onPop); return () => removeEventListener("popstate", onPop);78  }, []);79  const onFavChange = useCallback((id: string, fav: boolean) => {80    setChannel((c) => (c && c.id === id ? { ...c, fav } : c)); setQueue((q) => q.map((c) => (c.id === id ? { ...c, fav } : c))); setFavVersion((v) => v + 1);81  }, []);82  const value = useMemo(() => ({ channel, mode, play, close, onFavChange, favVersion }), [channel, mode, play, close, onFavChange, favVersion]);83  return (84    <PlayerCtx.Provider value={value}>85      {children}86      <PlayerView channel={channel} queue={queue} mode={mode} minimize={() => { if (modeRef.current === "full") history.back(); }} expand={() => setFull(true)} />87    </PlayerCtx.Provider>88  );89}9091function PlayerView({ channel, queue, mode, minimize, expand }: { channel: Channel | null; queue: Channel[]; mode: Mode; minimize: () => void; expand: () => void }) {92  const { play, close, onFavChange } = usePlayer();93  const video = useRef<HTMLVideoElement>(null);94  const box = useRef<HTMLDivElement>(null);95  const hls = useRef<Hls | null>(null);96  const dash = useRef<{ reset: () => void } | null>(null);97  const attempt = useRef(0);98  const reported = useRef<number | null>(null);99  const startTimer = useRef<ReturnType<typeof setTimeout>>(undefined);100  const relayTok = useRef<string | null>(null);101  const relayRetries = useRef(0);102  const [relay, setRelay] = useState<RelayOpen | null>(null);103  const [shift, setShift] = useState(0);104  const [detail, setDetail] = useState<Detail | null>(null);105  const [idx, setIdx] = useState(0);106  const [phase, setPhase] = useState<Phase>("idle");107  const [failure, setFailure] = useState<Failure | null>(null);108  const [skipped, setSkipped] = useState<string[]>([]);109  const [levels, setLevels] = useState<{ index: number; label: string }[]>([]);110  const [level, setLevel] = useState(-1);111  const [engine, setEngine] = useState<"hls.js" | "dash.js" | "natif" | null>(null);112  const [muted, setMuted] = useState(false);113  const [volume, setVolume] = useState(1);114  const [needsUnmute, setNeedsUnmute] = useState(false);115  const [chrome, setChrome] = useState(true);116  const [panel, setPanel] = useState<"none" | "list" | "settings">("none");117  const [airplay, setAirplay] = useState(false);118  const [isFs, setIsFs] = useState(false);119  const [testing, setTesting] = useState(false);120  const [copied, setCopied] = useState(false);121  const t = useNow(20_000);122  const full = mode === "full";123124  useEffect(() => {125    const v = Number(localStorage.getItem("sptv:volume") ?? "1"); const m = localStorage.getItem("sptv:muted") === "1";126    setVolume(Number.isFinite(v) ? v : 1); setMuted(m);127  }, []);128  useEffect(() => { const el = video.current; if (el) { el.volume = volume; el.muted = muted; } }, [volume, muted]);129130  const stopMedia = useCallback(() => {131    clearTimeout(startTimer.current);132    hls.current?.destroy(); hls.current = null;133    try { dash.current?.reset(); } catch { /* already gone */ } dash.current = null;134    const el = video.current; if (el) { el.pause(); el.removeAttribute("src"); el.load(); }135    setLevels([]); setLevel(-1); setEngine(null);136  }, []);137  const teardown = useCallback(() => {138    stopMedia();139    // Tell the relay engine this player is gone: the relay stops by itself once nobody reads it.140    if (relayTok.current) { api("/relay/close", { body: { token: relayTok.current } }).catch(() => {}); relayTok.current = null; }141    setRelay(null); setShift(0);142  }, [stopMedia]);143144  // Closing the tab or leaving the site: the relay session is released at once instead of waiting for the inactivity delay.145  useEffect(() => {146    const bye = () => { if (relayTok.current) navigator.sendBeacon("/api/relay/close", new Blob([JSON.stringify({ token: relayTok.current })], { type: "application/json" })); };147    window.addEventListener("pagehide", bye); return () => window.removeEventListener("pagehide", bye);148  }, []);149150  // Load the channel: streams in playback order, current programme, favourite lists.151  useEffect(() => {152    if (!channel) { teardown(); setDetail(null); setPhase("idle"); return; }153    let dead = false;154    teardown(); setDetail(null); setFailure(null); setSkipped([]); setPhase("loading"); setIdx(0); setPanel("none"); relayRetries.current = 0;155    api<Detail>(`/channels/${encodeURIComponent(channel.id)}`).then((d) => { if (!dead) setDetail(d); })156      .catch((e) => { if (!dead) { setPhase("error"); setFailure({ title: "Chaîne indisponible", detail: (e as Error).message, hints: [] }); } });157    return () => { dead = true; };158  }, [channel?.id]); // eslint-disable-line react-hooks/exhaustive-deps159160  const report = useCallback((s: StreamInfo, ok: boolean, error?: string) => {161    if (!channel || (ok && reported.current === s.id)) return;162    if (ok) reported.current = s.id;163    api(`/channels/${encodeURIComponent(channel.id)}/played`, { body: { streamId: s.id, ok, error: error?.slice(0, 280) } }).catch(() => {});164  }, [channel]);165166  // Start (or restart) the selected stream.167  useEffect(() => {168    const el = video.current; const streams = detail?.streams;169    if (!el || !streams || !channel) return;170    if (!streams.length) { setPhase("error"); setFailure({ title: "Aucun flux", detail: "Cette chaîne n'a plus de flux dans les sources synchronisées.", hints: [] }); return; }171    const s = streams[idx]; if (!s) return;172    const my = ++attempt.current; let recoveries = 0;173    teardown(); setPhase("loading"); setFailure(null); setNeedsUnmute(false);174175    const fail = (client: string, code?: number) => {176      if (my !== attempt.current) return;177      // A relay session that was cut (network change, long pause, restart of the engine) is reopened by itself, twice at most.178      if (relayTok.current && relayRetries.current < 2) {179        relayRetries.current++; teardown(); setPhase("buffering");180        setTimeout(() => { if (my === attempt.current) setDetail((d) => (d ? { ...d } : d)); }, 1500);181        return;182      }183      const f = explain(s, client, code);184      report(s, false, `${f.title} — ${client}`);185      teardown();186      // Another source for the same channel: try it before giving up.187      if (idx + 1 < streams.length) { setSkipped((k) => [...k, `Source ${idx + 1} : ${f.title.toLowerCase()}`]); setIdx(idx + 1); return; }188      setFailure(f); setPhase("error");189    };190    const startPlayback = () => {191      el.play().catch((e: DOMException) => {192        if (my !== attempt.current || e.name !== "NotAllowedError") return;193        // Autoplay with sound refused by the browser: start muted and offer one tap to restore the sound.194        el.muted = true; setNeedsUnmute(true); el.play().catch(() => { if (my === attempt.current) setPhase("paused"); });195      });196    };197    if (!s.relay && s.insecure && location.protocol === "https:") { fail("Contenu mixte bloqué par le navigateur"); return; }198199    // A relay that has to connect to its source (and maybe start an encoder) gets more time before the first picture.200    startTimer.current = setTimeout(() => fail(s.relay ? "Aucune image reçue du relais après 45 secondes" : "Aucune image reçue après 25 secondes"), s.relay ? 45_000 : 25_000);201202    let cancelled = false;203    const launch = (src: string, kind: StreamInfo["kind"], viaRelay?: RelayOpen) => {204    const useNative = () => { setEngine("natif"); el.src = src; startPlayback(); };205    // MPEG-DASH without DRM: dash.js. A protected stream fails here and is reported as such — nothing is circumvented.206    if (kind === "dash") {207      import("dashjs").then((mod) => {208        if (cancelled || my !== attempt.current) return;209        const d = mod.MediaPlayer().create(); dash.current = d; setEngine("dash.js");210        d.on("error", (e: { error?: { code?: number; message?: string } | string }) => {211          if (my !== attempt.current) return; const err = typeof e.error === "object" ? e.error : undefined;212          fail(err?.code && err.code >= 100 && err.code < 120 ? "Flux DASH protégé par DRM (lecture non autorisée hors du service d'origine)" : `Erreur DASH${err?.message ? ` : ${err.message}` : ""}`);213        });214        d.on("keyError" as never, () => { if (my === attempt.current) fail("Flux DASH protégé par DRM (lecture non autorisée hors du service d'origine)"); });215        d.initialize(el, src, true);216      }).catch(() => fail("Le lecteur DASH n'a pas pu être chargé"));217    } else218    if (kind === "hls" && nativeHls()) useNative();219    else if (kind === "hls" || kind === "other") {220      import("hls.js").then(({ default: HlsCtor }) => {221        if (cancelled || my !== attempt.current) return;222        if (!HlsCtor.isSupported()) { if (kind === "other") useNative(); else fail("Ce navigateur ne prend pas en charge la lecture HLS"); return; }223        if (kind === "other" && !/mpegurl/i.test(s.contentType ?? "") && /^(video|audio)\//.test(s.contentType ?? "")) { useNative(); return; }224        const h = new HlsCtor({ enableWorker: true, lowLatencyMode: false, backBufferLength: 30, manifestLoadingMaxRetry: 1, manifestLoadingTimeOut: 12_000, levelLoadingMaxRetry: 3, fragLoadingMaxRetry: 4,225          // Through the relay, stay the configured buffer behind the live edge: short source hiccups are absorbed without a stall.226          ...(viaRelay ? { liveSyncDuration: viaRelay.bufferSec, liveMaxLatencyDuration: viaRelay.bufferSec + 5 } : {}) });227        hls.current = h; setEngine("hls.js");228        h.on(HlsCtor.Events.MANIFEST_PARSED, (_e, data) => {229          const seen = new Set<number>();230          setLevels(data.levels.map((l, i) => ({ index: i, label: l.height ? `${l.height}p` : `${Math.round(l.bitrate / 1000)} kb/s`, h: l.height || 0, b: l.bitrate }))231            .sort((a, b) => b.h - a.h || b.b - a.b).filter((l) => (l.h && seen.has(l.h) ? false : (seen.add(l.h), true))).map(({ index, label }) => ({ index, label })));232          startPlayback();233        });234        h.on(HlsCtor.Events.ERROR, (_e, data) => {235          if (!data.fatal || my !== attempt.current) return;236          const code = data.response?.code;237          if (data.type === HlsCtor.ErrorTypes.MEDIA_ERROR && recoveries < 2) { recoveries++; h.recoverMediaError(); return; }238          if (data.type === HlsCtor.ErrorTypes.NETWORK_ERROR && !/manifest/i.test(data.details) && recoveries < 3) { recoveries++; setPhase("buffering"); setTimeout(() => { if (my === attempt.current) h.startLoad(); }, 1500 * recoveries); return; }239          fail(code ? `Erreur réseau HTTP ${code} (${data.details})` : `${data.type === HlsCtor.ErrorTypes.NETWORK_ERROR ? "Erreur réseau" : "Erreur de décodage"} (${data.details})`, code || undefined);240        });241        h.loadSource(src); h.attachMedia(el);242      }).catch(() => fail("Le lecteur HLS n'a pas pu être chargé"));243    }244    };245    if (s.relay) {246      api<RelayOpen>("/relay/open", { body: { streamId: s.id } }).then((r) => {247        if (cancelled || my !== attempt.current) { api("/relay/close", { body: { token: r.token } }).catch(() => {}); return; }248        relayTok.current = r.token; setRelay(r); launch(r.url, "hls", r);249      }).catch((e) => {250        if (cancelled || my !== attempt.current) return;251        // The relay is a convenience for sources that also play directly; for a home channel it is the only way.252        if (s.relayOnly || !s.url) fail(`Relais indisponible : ${(e as Error).message}`); else launch(s.url, s.kind);253      });254    } else launch(s.url, s.kind);255256    // A live stream whose source stops sending data must not spin forever: after 25 s without progress it is a failure.257    let stall: ReturnType<typeof setTimeout> | undefined;258    let steady: ReturnType<typeof setTimeout> | undefined;259    const onPlaying = () => { if (my !== attempt.current) return; clearTimeout(startTimer.current); clearTimeout(stall); setPhase("playing"); report(s, true); clearTimeout(steady); steady = setTimeout(() => { relayRetries.current = 0; }, 30_000); };260    const onWaiting = () => {261      if (my !== attempt.current) return;262      setPhase((p) => (p === "playing" ? "buffering" : p));263      clearTimeout(stall); stall = setTimeout(() => fail("La source n'envoie plus de données depuis 25 secondes (flux interrompu)"), 25_000);264    };265    const onPause = () => { if (my === attempt.current && !el.ended) setPhase((p) => (p === "playing" || p === "buffering" ? "paused" : p)); };266    const onError = () => {267      if (my !== attempt.current || hls.current || dash.current) return; // hls.js and dash.js report their own errors268      const c = el.error?.code;269      fail(c === 4 ? "Format ou source non pris en charge par ce navigateur" : c === 2 ? "Erreur réseau pendant la lecture" : c === 3 ? "Erreur de décodage" : "Erreur de lecture");270    };271    el.addEventListener("playing", onPlaying); el.addEventListener("waiting", onWaiting); el.addEventListener("pause", onPause); el.addEventListener("error", onError);272    return () => { cancelled = true; clearTimeout(stall); clearTimeout(steady); el.removeEventListener("playing", onPlaying); el.removeEventListener("waiting", onWaiting); el.removeEventListener("pause", onPause); el.removeEventListener("error", onError); };273  }, [detail, idx]); // eslint-disable-line react-hooks/exhaustive-deps274  useEffect(() => () => teardown(), [teardown]);275276  // Zapping within the list the channel was opened from.277  const zap = useCallback((dir: 1 | -1) => {278    if (!channel || queue.length < 2) return;279    const i = queue.findIndex((c) => c.id === channel.id);280    play(queue[(i + dir + queue.length) % queue.length], undefined, mode === "closed" ? "full" : mode);281  }, [channel, queue, play, mode]);282283  const toggle = useCallback(() => { const el = video.current; if (!el) return; if (el.paused) el.play().catch(() => {}); else el.pause(); }, []);284  const setVol = (v: number) => { setVolume(v); setMuted(v === 0); localStorage.setItem("sptv:volume", String(v)); localStorage.setItem("sptv:muted", v === 0 ? "1" : "0"); setNeedsUnmute(false); };285  const toggleMute = useCallback(() => { setMuted((m) => { localStorage.setItem("sptv:muted", m ? "0" : "1"); return !m; }); setNeedsUnmute(false); }, []);286  const fullscreen = useCallback(() => {287    const el = video.current as (HTMLVideoElement & { webkitEnterFullscreen?: () => void }) | null;288    if (document.fullscreenElement) document.exitFullscreen();289    else if (box.current?.requestFullscreen) box.current.requestFullscreen().catch(() => {});290    else el?.webkitEnterFullscreen?.(); // iPhone: only the video element can go full screen291  }, []);292  useEffect(() => { const f = () => setIsFs(!!document.fullscreenElement); document.addEventListener("fullscreenchange", f); return () => document.removeEventListener("fullscreenchange", f); }, []);293  useEffect(() => {294    const el = video.current as (HTMLVideoElement & { webkitShowPlaybackTargetPicker?: () => void }) | null;295    if (!el || !("WebKitPlaybackTargetAvailabilityEvent" in window)) return;296    const f = (e: Event) => setAirplay((e as Event & { availability: string }).availability === "available");297    el.addEventListener("webkitplaybacktargetavailabilitychanged", f); return () => el.removeEventListener("webkitplaybacktargetavailabilitychanged", f);298  }, []);299300  // Controls fade away while watching; any key, tap or pointer movement brings them back.301  const wake = useCallback(() => setChrome(true), []);302  useEffect(() => {303    if (!full || !chrome || phase !== "playing" || panel !== "none") return;304    const id = setTimeout(() => setChrome(false), 4000); return () => clearTimeout(id);305  }, [full, chrome, phase, panel, t]);306307  useEffect(() => {308    if (!full) return;309    const onKey = (e: KeyboardEvent) => {310      const tag = (e.target as HTMLElement).tagName;311      if (tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA") { if (e.key === "Escape") (e.target as HTMLElement).blur(); return; }312      wake();313      const k = e.key;314      if (k === "Escape" || k === "Backspace" || k === "BrowserBack" || k === "GoBack") { e.preventDefault(); if (panel !== "none") setPanel("none"); else if (document.fullscreenElement) document.exitFullscreen(); else minimize(); }315      else if (panel !== "none") return; // panels use normal focus navigation316      else if (k === "ArrowUp" || k === "PageUp" || k === "ChannelUp" || k === "MediaTrackNext") { e.preventDefault(); zap(1); }317      else if (k === "ArrowDown" || k === "PageDown" || k === "ChannelDown" || k === "MediaTrackPrevious") { e.preventDefault(); zap(-1); }318      else if ((k === " " || k === "MediaPlayPause" || k === "k") && (e.target as HTMLElement).tagName !== "BUTTON") { e.preventDefault(); toggle(); }319      else if (k === "f") fullscreen(); else if (k === "m") toggleMute(); else if (k === "l") setPanel("list");320    };321    addEventListener("keydown", onKey, true); return () => removeEventListener("keydown", onKey, true);322  }, [full, panel, zap, toggle, fullscreen, toggleMute, minimize, wake]);323324  // Lock screen / hardware media keys.325  useEffect(() => {326    if (!("mediaSession" in navigator) || !channel) return;327    navigator.mediaSession.metadata = new MediaMetadata({ title: channel.name, artist: "SP TV", artwork: channel.logo ? [{ src: channel.logo }] : [] });328    navigator.mediaSession.setActionHandler("previoustrack", () => zap(-1)); navigator.mediaSession.setActionHandler("nexttrack", () => zap(1));329  }, [channel, zap]);330331  const s = detail?.streams[idx];332  const isFav = channel?.fav ?? false;333  const toggleFav = async () => {334    if (!channel) return;335    onFavChange(channel.id, !isFav);336    await api("/favorites", { body: { channelId: channel.id, on: !isFav } }).catch(() => onFavChange(channel.id, isFav));337  };338  const testNow = async () => {339    if (!channel) return; setTesting(true);340    try { const r = await api<{ streams: StreamInfo[] }>(`/channels/${encodeURIComponent(channel.id)}/check`, { method: "POST" }); setDetail((d) => (d ? { ...d, streams: r.streams } : d)); setSkipped([]); setIdx(0); }341    catch (e) { setFailure((f) => (f ? { ...f, hints: [...f.hints, (e as Error).message] } : f)); }342    finally { setTesting(false); }343  };344  const hide = async () => { if (!channel) return; await api("/hidden", { body: { channelId: channel.id, on: true } }).catch(() => {}); onFavChange(channel.id, !!channel.fav); if (queue.length > 1) zap(1); else close(); };345  const copyUrl = async () => { if (!s) return; try { await navigator.clipboard.writeText(s.url); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch { /* clipboard unavailable */ } };346  // Timeshift (sources that allow recording): the last minutes are replayed from the relay's recording, then playback returns to live.347  const goLive = () => { setShift(0); setDetail((d) => (d ? { ...d } : d)); };348  const goBack = (sec: number) => {349    const el = video.current; if (!el || !relay?.timeshift) return;350    stopMedia(); setShift(sec); setPhase("loading"); setEngine("natif");351    // One absolute instant for the whole clip: Safari fetches it in several range requests.352    el.src = `${relay.timeshift.base}/get.mp4?start=${Date.now() - sec * 1000}&duration=${sec}`; el.play().catch(() => {});353  };354  const pickLevel = (i: number) => { if (hls.current) { hls.current.currentLevel = i; setLevel(i); } };355  const { now: prog, next } = currentProg(detail?.programmes, t);356  const show = full ? chrome || phase !== "playing" || panel !== "none" : true;357358  return (359    <div360      ref={box} data-player={mode} hidden={mode === "closed"}361      onPointerMove={wake} onPointerDown={wake}362      className={cn("z-50 overflow-hidden bg-black", full ? "fixed inset-0" : "fixed bottom-[calc(5.4rem+env(safe-area-inset-bottom))] right-3 w-[min(22rem,calc(100vw-1.5rem))] rounded-2xl shadow-2xl ring-1 ring-white/15 lg:bottom-5 lg:right-5 lg:w-96", full && !show && "cursor-none")}363    >364      <div className={cn("relative bg-black", full ? "h-full w-full" : "aspect-video w-full")}>365        <video ref={video} playsInline x-webkit-airplay="allow" className="h-full w-full bg-black object-contain" onEnded={() => { if (shift) goLive(); }} onClick={() => (full ? (chrome ? toggle() : wake()) : expand())} />366367        {(phase === "loading" || phase === "buffering") && <div className="pointer-events-none absolute inset-0 grid place-items-center" role="status" aria-label="Chargement du flux"><div className="spinner" /></div>}368369        {phase === "error" && failure && full && (370          <div className="absolute inset-0 grid place-items-center overflow-y-auto bg-black/85 p-5" role="alert">371            <div className="w-full max-w-xl rounded-3xl bg-panel p-6 ring-1 ring-line">372              <div className="flex items-start gap-3"><AlertTriangle className="mt-0.5 h-6 w-6 shrink-0 text-amber-400" /><div><h2 className="text-lg font-semibold">{failure.title}</h2><p className="mt-1 text-sm leading-relaxed text-dim">{failure.detail}</p></div></div>373              {(failure.hints.length > 0 || skipped.length > 0) && <ul className="mt-4 list-disc space-y-1 pl-9 text-sm text-dim">{skipped.map((h) => <li key={h}>{h}</li>)}{failure.hints.map((h) => <li key={h}>{h}</li>)}</ul>}374              <div className="mt-5 flex flex-wrap gap-2">375                <button autoFocus onClick={() => { setSkipped([]); setIdx(0); setDetail((d) => (d ? { ...d } : d)); }} className="grad inline-flex h-11 items-center gap-2 rounded-full px-5 text-sm font-semibold"><RefreshCw className="h-4 w-4" />Réessayer</button>376                <button onClick={testNow} disabled={testing} className="inline-flex h-11 items-center gap-2 rounded-full bg-white/10 px-5 text-sm font-medium hover:bg-white/15 disabled:opacity-50">{testing ? "Test en cours…" : "Tester le flux maintenant"}</button>377                {s && <button onClick={copyUrl} className="inline-flex h-11 items-center gap-2 rounded-full bg-white/10 px-5 text-sm font-medium hover:bg-white/15"><Copy className="h-4 w-4" />{copied ? "URL copiée" : "Copier l'URL du flux"}</button>}378                {queue.length > 1 && <button onClick={() => zap(1)} className="inline-flex h-11 items-center gap-2 rounded-full bg-white/10 px-5 text-sm font-medium hover:bg-white/15">Chaîne suivante<ChevronRight className="h-4 w-4" /></button>}379              </div>380            </div>381          </div>382        )}383        {phase === "error" && failure && !full && <button onClick={expand} className="absolute inset-0 grid place-items-center bg-black/80 p-3 text-center text-xs text-dim"><span><AlertTriangle className="mx-auto mb-1 h-5 w-5 text-amber-400" />{failure.title}</span></button>}384385        {needsUnmute && phase !== "error" && <button onClick={() => { setMuted(false); setNeedsUnmute(false); const el = video.current; if (el) el.muted = false; }} className={cn("absolute left-1/2 -translate-x-1/2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-black shadow-xl", full ? "top-24" : "top-2 text-xs")}><VolumeX className="mr-1.5 inline h-4 w-4" />Activer le son</button>}386387        {/* Mini player bar */}388        {!full && channel && (389          <div className="absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/90 to-transparent p-2 pt-8">390            <button onClick={expand} className="flex min-w-0 flex-1 items-center gap-2 rounded-lg text-left" aria-label={`Agrandir ${channel.name}`}><span className="truncate text-sm font-semibold">{channel.name}</span></button>391            <Btn label={phase === "playing" || phase === "buffering" ? "Pause" : "Lecture"} onClick={toggle} className="h-10 w-10">{phase === "playing" || phase === "buffering" ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5" />}</Btn>392            <Btn label="Agrandir" onClick={expand} className="h-10 w-10"><Maximize className="h-5 w-5" /></Btn>393            <Btn label="Fermer le lecteur" onClick={close} className="h-10 w-10"><X className="h-5 w-5" /></Btn>394          </div>395        )}396397        {/* Full player chrome */}398        {full && channel && (399          <div className={cn("pointer-events-none absolute inset-0 flex flex-col justify-between transition-opacity duration-300", show ? "opacity-100" : "opacity-0")} aria-hidden={!show}>400            <div className="pointer-events-auto flex items-center gap-3 bg-gradient-to-b from-black/85 to-transparent p-3 pb-10 pt-[max(0.75rem,env(safe-area-inset-top))] sm:p-5 sm:pb-12">401              <Btn label="Réduire le lecteur (Retour)" onClick={minimize}><ChevronDown className="h-7 w-7" /></Btn>402              <Logo channel={channel} className="h-12 w-16 shrink-0 rounded-xl" />403              <div className="min-w-0 flex-1">404                <h2 className="flex items-center gap-2 truncate text-lg font-semibold sm:text-xl"><span className="truncate">{channel.name}</span><StatusDot status={s?.status ?? channel.status} /></h2>405                <p className="truncate text-sm text-dim">{prog ? <>{hm(prog.start)} – {hm(prog.stop)} · <span className="text-ink">{prog.title}</span></> : <>{flag(channel.country)} {countryName(channel.country)} · {detail && !detail.programmes.length ? "Programme indisponible" : ""}</>}</p>406              </div>407              <Btn label={isFav ? "Retirer des favoris" : "Ajouter aux favoris"} onClick={toggleFav}><Star className={cn("h-6 w-6", isFav && "fill-amber-300 text-amber-300")} /></Btn>408            </div>409410            <div className="pointer-events-auto bg-gradient-to-t from-black/90 to-transparent p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-12 sm:p-5 sm:pt-14">411              {prog && <div className="mb-3 px-1"><div className="h-1 overflow-hidden rounded-full bg-white/20"><div className="grad h-full" style={{ width: `${Math.min(100, ((t - prog.start) / (prog.stop - prog.start)) * 100)}%` }} /></div>{next && <p className="mt-1.5 truncate text-xs text-dim">À suivre · {hm(next.start)} {next.title}</p>}</div>}412              <div className="flex items-center gap-1 sm:gap-2">413                <Btn label="Chaîne précédente (↓)" onClick={() => zap(-1)} className={cn(queue.length < 2 && "invisible")}><ChevronLeft className="h-7 w-7" /></Btn>414                <Btn label={phase === "playing" || phase === "buffering" ? "Pause" : "Lecture"} onClick={toggle} className="h-14 w-14 bg-white text-black hover:bg-white/90">{phase === "playing" || phase === "buffering" ? <Pause className="h-7 w-7 fill-current" /> : <Play className="h-7 w-7 fill-current" />}</Btn>415                <Btn label="Chaîne suivante (↑)" onClick={() => zap(1)} className={cn(queue.length < 2 && "invisible")}><ChevronRight className="h-7 w-7" /></Btn>416                <Btn label={muted ? "Rétablir le son" : "Couper le son"} onClick={toggleMute}>{muted || volume === 0 ? <VolumeX className="h-6 w-6" /> : <Volume2 className="h-6 w-6" />}</Btn>417                <input type="range" min={0} max={1} step={0.05} value={muted ? 0 : volume} onChange={(e) => setVol(Number(e.target.value))} aria-label="Volume" className="hidden w-28 sm:block" />418                <div className="flex-1" />419                {relay?.timeshift && phase !== "error" && <span className="flex items-center gap-1" data-timeshift>420                  <button onClick={() => goBack(30)} aria-label="Revenir 30 secondes en arrière" className="h-10 whitespace-nowrap rounded-full bg-white/10 px-3 text-xs font-semibold hover:bg-white/20">−30 s</button>421                  <button onClick={() => goBack(300)} aria-label="Revenir 5 minutes en arrière" className="hidden h-10 rounded-full bg-white/10 px-3 text-xs font-semibold hover:bg-white/20 sm:block">−5 min</button>422                  {shift > 0 && <button onClick={goLive} aria-label="Revenir au direct" className="h-10 whitespace-nowrap rounded-full bg-live px-3 text-xs font-semibold hover:bg-live/85">Direct</button>}423                </span>}424                {skipped.length > 0 && phase !== "error" && <span className="hidden text-xs text-dim md:block">Source {idx + 1}/{detail?.streams.length}</span>}425                <Btn label="Liste des chaînes" onClick={() => setPanel(panel === "list" ? "none" : "list")} active={panel === "list"}><List className="h-6 w-6" /></Btn>426                <Btn label="Qualité et source" onClick={() => setPanel(panel === "settings" ? "none" : "settings")} active={panel === "settings"}><Settings2 className="h-6 w-6" /></Btn>427                {airplay && <Btn label="AirPlay" onClick={() => (video.current as HTMLVideoElement & { webkitShowPlaybackTargetPicker?: () => void })?.webkitShowPlaybackTargetPicker?.()}><Airplay className="h-6 w-6" /></Btn>}428                {typeof document !== "undefined" && document.pictureInPictureEnabled && <Btn label="Image dans l'image" onClick={() => { if (document.pictureInPictureElement) document.exitPictureInPicture(); else video.current?.requestPictureInPicture().catch(() => {}); }} className="hidden sm:grid"><PictureInPicture2 className="h-6 w-6" /></Btn>}429                <Btn label={isFs ? "Quitter le plein écran" : "Plein écran"} onClick={fullscreen}>{isFs ? <Minimize className="h-6 w-6" /> : <Maximize className="h-6 w-6" />}</Btn>430              </div>431            </div>432          </div>433        )}434435        {/* Side panels */}436        {full && panel !== "none" && (437          <div className="glass absolute inset-y-0 right-0 flex w-full max-w-sm flex-col ring-1 ring-line fadein">438            <div className="flex items-center justify-between p-4 pt-[max(1rem,env(safe-area-inset-top))]"><h3 className="text-base font-semibold">{panel === "list" ? "Chaînes" : "Qualité et source"}</h3><Btn label="Fermer" onClick={() => setPanel("none")}><X className="h-5 w-5" /></Btn></div>439            {panel === "list" && (440              <div className="flex-1 space-y-1 overflow-y-auto p-2 pb-6">441                {queue.length === 0 && <p className="p-4 text-sm text-dim">Ouvrez une chaîne depuis une liste pour zapper dans cette liste.</p>}442                {queue.map((c) => (443                  <button key={c.id} autoFocus={c.id === channel?.id} onClick={() => { play(c); setPanel("none"); }} className={cn("flex w-full items-center gap-3 rounded-xl p-2 text-left hover:bg-white/10", c.id === channel?.id && "bg-white/15")}>444                    <Logo channel={c} className="h-10 w-14 shrink-0 rounded-lg" /><span className="min-w-0 flex-1 truncate text-sm font-medium">{c.name}</span><StatusDot status={c.status} />445                  </button>446                ))}447              </div>448            )}449            {panel === "settings" && (450              <div className="flex-1 space-y-5 overflow-y-auto p-4 pb-6 text-sm">451                <section><h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-faint">Qualité</h4>452                  {engine === "natif" && <p className="text-dim">Lecteur natif : la qualité est choisie automatiquement par l'appareil.</p>}453                  {engine === "dash.js" && <p className="text-dim">Flux MPEG-DASH : qualité adaptative automatique.</p>}454                  {engine === "hls.js" && levels.length <= 1 && <p className="text-dim">Ce flux ne propose qu'une seule qualité{levels[0] ? ` (${levels[0].label})` : ""}.</p>}455                  {engine === "hls.js" && levels.length > 1 && <div className="flex flex-wrap gap-2">{[{ index: -1, label: "Auto" }, ...levels].map((l) => <button key={l.index} onClick={() => pickLevel(l.index)} className={cn("h-10 rounded-full px-4 font-medium", level === l.index ? "bg-white text-black" : "bg-white/10 hover:bg-white/15")}>{l.label}</button>)}</div>}456                </section>457                {relay && <section data-relay-info><h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-faint">Moteur de relais</h4>458                  <p className="text-dim">Diffusé par votre serveur ({relay.mode === "transcode" ? "transcodage en H.264" : relay.mode === "audio" ? "audio seul" : "copie sans réencodage"}{relay.shared ? ", flux partagé entre vos écrans" : ""}), tampon de {relay.bufferSec} s.{relay.timeshift ? ` Différé possible sur ${Math.round(relay.timeshift.windowSec / 60)} min.` : ""}{shift ? ` Lecture en différé (−${shift >= 60 ? `${Math.round(shift / 60)} min` : `${shift} s`}).` : ""}</p>459                </section>}460                <section><h4 className="mb-2 text-xs font-semibold uppercase tracking-wide text-faint">Sources de cette chaîne</h4>461                  <div className="space-y-2">{detail?.streams.map((st, i) => (462                    <button key={st.id} onClick={() => { setSkipped([]); setIdx(i); setDetail((d) => (d ? { ...d } : d)); }} className={cn("block w-full rounded-xl p-3 text-left ring-1 ring-line hover:bg-white/10", i === idx && "bg-white/10 ring-white/40")}>463                      <span className="flex items-center gap-2 font-medium"><StatusDot status={st.status} />Source {i + 1}{st.quality ? ` · ${st.quality}` : ""}{st.insecure && !st.relay ? " · HTTP" : ""}{st.kind === "dash" ? " · DASH" : ""}{st.relay ? " · Relais" : ""}</span>464                      <span className="mt-1 block text-xs text-dim">{STATUS_LABEL[st.status]}{st.checkedAt ? ` (${dateTime(st.checkedAt)})` : ""}{st.checkError ? ` — ${st.checkError}` : ""}</span>465                      <span className="mt-0.5 block text-xs text-faint">{st.source}{st.labels.length ? ` · ${st.labels.join(", ")}` : ""}{st.playOk ? ` · lue ici le ${dateTime(st.playAt)}` : ""}</span>466                    </button>))}</div>467                </section>468                <div className="flex flex-wrap gap-2"><button onClick={testNow} disabled={testing} className="h-10 rounded-full bg-white/10 px-4 font-medium hover:bg-white/15 disabled:opacity-50">{testing ? "Test en cours…" : "Tester maintenant"}</button><button onClick={copyUrl} className="h-10 rounded-full bg-white/10 px-4 font-medium hover:bg-white/15">{copied ? "URL copiée" : "Copier l'URL"}</button><button onClick={hide} className="h-10 rounded-full bg-white/10 px-4 font-medium hover:bg-white/15">Masquer cette chaîne</button></div>469              </div>470            )}471          </div>472        )}473      </div>474    </div>475  );476}477
Files main
Menu

Theme