Files
GridTV/index.php
T

1488 lines
50 KiB
PHP

<?php
// GridTV — index.php
$config_path = __DIR__ . "/config.json";
if (!file_exists($config_path)) {
header("Location: setup.php");
exit;
}
$config = json_decode(file_get_contents($config_path), true);
// ── Migration automatique ancien format → nouveau ─────────────────────────────
if (isset($config['epg_url']) && !isset($config['epg_sources'])) {
$config['epg_sources'] = [[
'name' => 'Main',
'epg_url' => $config['epg_url'],
'm3u_url' => $config['m3u_url'] ?? '',
]];
$config['allow_personal_epg'] = false;
unset($config['epg_url'], $config['m3u_url']);
file_put_contents($config_path, json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
// ─────────────────────────────────────────────────────────────────────────────
$group_name = htmlspecialchars($config['group_name'] ?? 'GridTV');
$epg_sources = $config['epg_sources'] ?? [];
$allow_personal_epg = !empty($config['allow_personal_epg']);
// Première source par défaut (pour compatibilité avec le reste du code)
$first_source = $epg_sources[0] ?? [];
$epg_url = htmlspecialchars($first_source['epg_url'] ?? '');
$m3u_url = htmlspecialchars($first_source['m3u_url'] ?? '');
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GridTV — <?= $group_name ?></title>
<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&family=Barlow+Condensed:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
/* Variables de base — surchargées par le fichier thème */
:root {
--bg: #0a0b0d;
--surface: #111318;
--surface2: #181b22;
--border: #232733;
--border-bright: #2e3444;
--accent: #e8c842;
--accent2: #4a9eff;
--accent-live: #ff4444;
--text: #c8cdd8;
--text-dim: #5a6070;
--text-bright: #eef0f5;
--prog-bg: #141820;
--prog-border: #1e2a3a;
--prog-live-bg: #0d2040;
--prog-live-border: #4a9eff;
--font-ui: 'Barlow Condensed', sans-serif;
--font-mono: 'Share Tech Mono', monospace;
--channel-w: 160px;
--row-h: 80px;
--header-h: 52px;
}
html, body { height: 100%; }
body {
background: var(--bg);
color: var(--text);
font-family: var(--font-ui);
font-size: 14px;
overflow: hidden;
display: flex;
flex-direction: column;
}
/* ═══════════════════════════════════════════
TOP BAR
═══════════════════════════════════════════ */
.topbar {
height: 50px;
background: var(--surface);
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
padding: 0 16px;
gap: 12px;
flex-shrink: 0;
position: relative;
z-index: 100;
}
.logo {
font-family: 'Share Tech Mono', monospace;
font-size: 13px;
color: var(--accent);
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.logo span { color: var(--text-dim); margin: 0 5px; }
.logo-sub { display: inline; }
.live-dot {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-family: 'Share Tech Mono', monospace;
color: var(--accent-live);
letter-spacing: 0.1em;
margin-left: auto;
flex-shrink: 0;
}
.live-dot::before {
content: '';
width: 7px; height: 7px;
background: var(--accent-live);
border-radius: 50%;
animation: pulse 1.4s ease-in-out infinite;
}
@keyframes pulse {
0%,100% { opacity:1; transform:scale(1); }
50% { opacity:0.3; transform:scale(0.7); }
}
.clock {
font-family: 'Share Tech Mono', monospace;
font-size: 20px;
color: var(--text-bright);
letter-spacing: 0.05em;
flex-shrink: 0;
}
.date-label {
font-family: 'Share Tech Mono', monospace;
font-size: 10px;
color: var(--text-dim);
letter-spacing: 0.1em;
text-transform: uppercase;
white-space: nowrap;
}
.nav-btns {
display: flex;
gap: 4px;
flex-shrink: 0;
}
.nav-btn {
background: var(--surface2);
border: 1px solid var(--border);
color: var(--text);
font-family: 'Barlow Condensed', sans-serif;
font-size: 12px;
letter-spacing: 0.06em;
padding: 4px 10px;
cursor: pointer;
text-transform: uppercase;
transition: all 0.15s;
white-space: nowrap;
}
.nav-btn:hover, .nav-btn.active {
background: var(--accent);
color: #000;
border-color: var(--accent);
}
.copy-btns {
display: flex;
gap: 4px;
flex-shrink: 0;
}
.copy-btn {
background: transparent;
border: 1px solid var(--border-bright);
color: var(--text-dim);
font-family: 'Share Tech Mono', monospace;
font-size: 10px;
letter-spacing: 0.1em;
padding: 4px 9px;
cursor: pointer;
text-transform: uppercase;
transition: all 0.15s;
white-space: nowrap;
position: relative;
}
.copy-btn:hover {
border-color: var(--accent2);
color: var(--accent2);
}
.copy-btn.copied {
border-color: var(--accent);
color: var(--accent);
}
/* ═══════════════════════════════════════════
GRID VIEW (desktop / tablet)
═══════════════════════════════════════════ */
.grid-wrapper {
flex: 1;
display: flex;
overflow: hidden;
position: relative;
min-height: 0;
}
.channels-col {
width: var(--channel-w);
flex-shrink: 0;
background: var(--surface);
border-right: 1px solid var(--border-bright);
z-index: 10;
display: flex;
flex-direction: column;
min-height: 0;
}
.channels-col-header {
height: var(--header-h);
border-bottom: 1px solid var(--border-bright);
display: flex;
align-items: center;
padding: 0 12px;
flex-shrink: 0;
}
.channels-col-header span {
font-family: 'Share Tech Mono', monospace;
font-size: 9px;
color: var(--text-dim);
letter-spacing: 0.15em;
text-transform: uppercase;
}
.channels-list {
overflow-y: auto;
flex: 1;
scrollbar-width: none;
}
.channels-list::-webkit-scrollbar { display: none; }
.channel-cell {
height: var(--row-h);
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
padding: 0 12px;
gap: 8px;
flex-shrink: 0;
}
.channel-logo {
width: 32px; height: 32px;
border-radius: 4px;
object-fit: contain;
background: var(--surface2);
flex-shrink: 0;
}
.channel-logo-placeholder {
width: 32px; height: 32px;
border-radius: 4px;
background: var(--surface2);
border: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: center;
font-family: 'Share Tech Mono', monospace;
font-size: 9px;
color: var(--text-dim);
flex-shrink: 0;
}
.channel-name {
font-size: 12px;
font-weight: 600;
color: var(--text-bright);
letter-spacing: 0.04em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-transform: uppercase;
}
.timeline-area {
flex: 1;
overflow: auto;
position: relative;
min-height: 0;
scrollbar-width: thin;
scrollbar-color: var(--border-bright) transparent;
}
.timeline-area::-webkit-scrollbar { height: 4px; width: 4px; }
.timeline-area::-webkit-scrollbar-track { background: transparent; }
.timeline-area::-webkit-scrollbar-thumb { background: var(--border-bright); border-radius: 2px; }
/* Conteneur unique — ruler + programmes scrollent ensemble */
.timeline-inner {
position: relative;
display: block;
min-width: 100%;
}
.time-ruler {
height: var(--header-h);
background: var(--surface);
border-bottom: 1px solid var(--border-bright);
position: sticky;
top: 0;
z-index: 20;
}
.time-ruler-inner {
position: relative;
height: 100%;
}
.time-tick {
position: absolute;
bottom: 0;
display: flex;
flex-direction: column;
align-items: flex-start;
}
.time-tick-label {
font-family: 'Share Tech Mono', monospace;
font-size: 10px;
color: var(--text-dim);
letter-spacing: 0.08em;
padding: 0 6px 6px;
white-space: nowrap;
}
.time-tick-label.hour { color: var(--text); font-size: 12px; }
.time-tick-line { width: 1px; height: 8px; background: var(--border-bright); }
.time-tick-line.hour { height: 14px; }
.now-line {
position: absolute;
top: 0;
width: 2px;
height: 100%;
background: var(--accent-live);
z-index: 50;
pointer-events: none;
}
.now-line::before {
content: '';
position: absolute;
top: 0; left: -4px;
width: 10px; height: 10px;
background: var(--accent-live);
border-radius: 50%;
}
.programs-inner {
position: relative;
background-image: repeating-linear-gradient(
to bottom,
transparent 0px, transparent 79px,
var(--border) 79px, var(--border) 80px
);
}
.program-row {
height: var(--row-h);
border-bottom: 1px solid var(--border);
position: absolute;
left: 0; right: 0;
}
.program-block {
position: absolute;
top: 5px; bottom: 5px;
background: var(--surface2);
border: 1px solid var(--border);
border-radius: 3px;
padding: 0 8px;
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
cursor: default;
transition: background 0.12s, border-color 0.12s;
min-width: 2px;
}
.program-block:hover { background: var(--surface); border-color: var(--accent2); z-index: 5; }
.program-block.is-live { border-color: var(--accent2); background: #0d1a2e; }
.program-block.is-live::after {
content: '';
position: absolute;
bottom: 0; left: 0;
height: 2px;
background: var(--accent2);
width: var(--progress, 0%);
transition: width 1s linear;
}
.program-block.is-past { opacity: 0.35; }
.program-title {
font-size: 12px;
font-weight: 600;
color: var(--text-bright);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
letter-spacing: 0.02em;
}
.program-time {
font-family: 'Share Tech Mono', monospace;
font-size: 9px;
color: var(--text-dim);
letter-spacing: 0.06em;
white-space: nowrap;
}
/* ═══════════════════════════════════════════
MOBILE LIST VIEW
═══════════════════════════════════════════ */
.mobile-view {
display: none;
flex: 1;
overflow-y: auto;
min-height: 0;
-webkit-overflow-scrolling: touch;
}
.mobile-channel {
border-bottom: 2px solid var(--border-bright);
}
.mobile-channel-header {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
background: var(--surface);
position: sticky;
top: 0;
z-index: 10;
border-bottom: 1px solid var(--border);
}
.mobile-programs {
padding: 6px 10px;
display: flex;
flex-direction: column;
gap: 4px;
}
.mobile-program {
display: flex;
align-items: stretch;
border-radius: 4px;
overflow: hidden;
border: 1px solid var(--border);
background: var(--surface2);
position: relative;
}
.mobile-program.is-live { border-color: var(--accent2); background: #0d1a2e; }
.mobile-program.is-past { opacity: 0.4; }
.mobile-program-progress {
position: absolute;
bottom: 0; left: 0;
height: 2px;
background: var(--accent2);
}
.mobile-program-time {
font-family: 'Share Tech Mono', monospace;
font-size: 10px;
color: var(--text-dim);
padding: 8px 10px;
background: var(--surface);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
min-width: 72px;
flex-shrink: 0;
gap: 2px;
}
.mobile-program.is-live .mobile-program-time { color: var(--accent2); }
.mobile-program-info {
padding: 8px 10px;
flex: 1;
min-width: 0;
}
.mobile-program-title {
font-size: 13px;
font-weight: 600;
color: var(--text-bright);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mobile-program-dur {
font-size: 10px;
color: var(--text-dim);
margin-top: 2px;
font-family: 'Share Tech Mono', monospace;
}
.mobile-live-badge {
font-family: 'Share Tech Mono', monospace;
font-size: 9px;
color: var(--accent-live);
background: rgba(255,68,68,0.12);
border: 1px solid var(--accent-live);
border-radius: 2px;
padding: 2px 5px;
letter-spacing: 0.1em;
align-self: center;
margin-right: 8px;
flex-shrink: 0;
}
/* TOOLTIP */
.tooltip {
position: fixed;
background: var(--surface);
border: 1px solid var(--accent2);
border-radius: 4px;
padding: 10px 14px;
z-index: 999;
pointer-events: none;
max-width: 300px;
opacity: 0;
transition: opacity 0.15s;
}
.tooltip.visible { opacity: 1; }
.tooltip-title { font-size: 14px; font-weight: 700; color: var(--text-bright); margin-bottom: 4px; }
.tooltip-time { font-family: 'Share Tech Mono', monospace; font-size: 10px; color: var(--accent2); margin-bottom: 6px; }
.tooltip-desc { font-size: 12px; color: var(--text); line-height: 1.4; max-height: 80px; overflow: hidden; }
/* LOADING */
.loading {
position: fixed; inset: 0;
background: var(--bg);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 1000;
gap: 20px;
}
.loading-text {
font-family: 'Share Tech Mono', monospace;
font-size: 12px;
color: var(--text-dim);
letter-spacing: 0.2em;
text-transform: uppercase;
}
.loading-bar {
width: 200px; height: 2px;
background: var(--border);
position: relative;
overflow: hidden;
}
.loading-bar::after {
content: '';
position: absolute;
top: 0; left: -60%;
width: 60%; height: 100%;
background: var(--accent);
animation: loading-anim 1.2s ease-in-out infinite;
}
@keyframes loading-anim { to { left: 110%; } }
.error-msg {
position: fixed; inset: 0;
background: var(--bg);
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 1000;
gap: 16px;
display: none;
padding: 20px;
}
.err-title { font-family: 'Share Tech Mono', monospace; font-size: 14px; color: var(--accent-live); letter-spacing: 0.1em; }
.err-sub { font-size: 13px; color: var(--text-dim); text-align: center; max-width: 400px; line-height: 1.5; }
.epg-input-bar { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; justify-content: center; }
.epg-input {
background: var(--surface2);
border: 1px solid var(--border-bright);
color: var(--text-bright);
font-family: 'Share Tech Mono', monospace;
font-size: 12px;
padding: 8px 12px;
width: 320px;
outline: none;
}
.epg-input:focus { border-color: var(--accent); }
.epg-btn {
background: var(--accent);
border: none; color: #000;
font-family: 'Barlow Condensed', sans-serif;
font-weight: 700; font-size: 13px;
letter-spacing: 0.1em;
text-transform: uppercase;
padding: 8px 18px;
cursor: pointer;
}
/* ═══════════════════════════════════════════
RESPONSIVE
═══════════════════════════════════════════ */
@media (max-width: 900px) {
:root { --channel-w: 110px; }
.logo-sub { display: none; }
.date-label { display: none; }
.clock { font-size: 16px; }
}
/* ═══════════════════════════════════════════
SÉLECTEUR DE THÈME
═══════════════════════════════════════════ */
.theme-select {
background: transparent;
border: 1px solid var(--border-bright);
color: var(--text-dim);
font-family: var(--font-mono);
font-size: 10px;
letter-spacing: 0.08em;
padding: 4px 8px;
cursor: pointer;
text-transform: uppercase;
transition: all 0.15s;
flex-shrink: 0;
-webkit-appearance: none;
appearance: none;
}
.theme-select:hover { border-color: var(--accent2); color: var(--accent2); }
.theme-select option { background: #111; color: #eee; font-family: sans-serif; }
@media (max-width: 600px) {
html, body { height: 100%; overflow: hidden; }
body { overflow: hidden; }
.topbar {
height: auto;
flex-wrap: wrap;
padding: 8px 12px;
gap: 8px;
}
.logo { font-size: 11px; }
.clock { font-size: 14px; }
.grid-wrapper { display: none; }
.mobile-view { display: block; }
.tooltip { display: none !important; }
#navBtns { display: none !important; }
}
/* ── MODAL PERSONAL EPG ─────────────────────────────────────────────────── */
.modal-overlay {
position: fixed; inset: 0; background: rgba(0,0,0,0.7);
z-index: 3000; display: none; align-items: center; justify-content: center;
}
.modal-overlay.visible { display: flex; }
.modal-card {
background: var(--surface); border: 1px solid var(--border-bright);
padding: 28px; width: 100%; max-width: 420px; margin: 16px;
}
.modal-title {
font-family: var(--font-mono); font-size: 13px; color: var(--accent);
letter-spacing: 0.1em; text-transform: uppercase; margin-bottom: 6px;
}
.modal-subtitle { font-size: 12px; color: var(--text-dim); margin-bottom: 20px; line-height: 1.5; }
.modal-field { margin-bottom: 14px; }
.modal-field label {
display: block; font-family: var(--font-mono); font-size: 10px;
letter-spacing: 0.1em; text-transform: uppercase; color: var(--text-dim); margin-bottom: 6px;
}
.modal-field input {
width: 100%; background: var(--surface2); border: 1px solid var(--border-bright);
color: var(--text-bright); font-family: var(--font-mono); font-size: 12px;
padding: 9px 10px; outline: none; transition: border-color 0.15s;
}
.modal-field input:focus { border-color: var(--accent); }
.modal-field input::placeholder { color: var(--text-dim); opacity: 0.4; }
.modal-actions { display: flex; gap: 10px; margin-top: 20px; justify-content: flex-end; }
.modal-btn-cancel {
background: none; border: 1px solid var(--border-bright); color: var(--text-dim);
font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.08em;
text-transform: uppercase; padding: 8px 16px; cursor: pointer; transition: border-color 0.15s;
}
.modal-btn-cancel:hover { border-color: var(--text-dim); color: var(--text); }
.modal-btn-apply {
background: var(--accent); border: none; color: #000;
font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.08em;
text-transform: uppercase; padding: 8px 20px; cursor: pointer; transition: opacity 0.15s;
}
.modal-btn-apply:hover { opacity: 0.85; }
/* ── SOURCE SELECTOR ─────────────────────────────────────────────────────── */
.source-select {
background: var(--surface2);
border: 1px solid var(--border-bright);
color: var(--text);
font-family: var(--font-mono);
font-size: 11px;
padding: 5px 8px;
cursor: pointer;
letter-spacing: 0.06em;
height: 28px;
outline: none;
transition: border-color 0.15s, color 0.15s;
max-width: 130px;
}
.source-select:hover { border-color: var(--accent2); color: var(--accent2); }
.source-select option { background: #111; color: #eee; font-family: sans-serif; }
/* ═══════════════════════════════════════════
PLAYER PiP
═══════════════════════════════════════════ */
.pip {
position: fixed;
bottom: 24px;
right: 24px;
width: 380px;
background: #000;
border: 1px solid var(--border-bright);
box-shadow: 0 8px 32px rgba(0,0,0,0.8);
z-index: 2000;
display: none;
flex-direction: column;
}
.pip.visible { display: flex; }
.pip-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 10px;
background: var(--surface);
border-bottom: 1px solid var(--border);
gap: 8px;
flex-shrink: 0;
}
.pip-channel {
font-family: var(--font-mono);
font-size: 11px;
color: var(--accent);
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
}
.pip-program {
font-size: 11px;
color: var(--text-dim);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 2;
text-align: center;
}
.pip-close {
background: none;
border: none;
color: var(--text-dim);
font-size: 18px;
cursor: pointer;
padding: 0 4px;
line-height: 1;
flex-shrink: 0;
transition: color 0.15s;
}
.pip-close:hover { color: var(--accent-live); }
.pip video {
width: 100%;
aspect-ratio: 16/9;
display: block;
background: #000;
}
.pip-error {
padding: 20px;
text-align: center;
font-family: var(--font-mono);
font-size: 11px;
color: var(--accent-live);
letter-spacing: 0.06em;
}
.channel-cell { cursor: pointer; }
.channel-cell:hover { background: var(--surface2); }
.program-block.is-live { cursor: pointer; }
@media (max-width: 600px) {
.pip { width: calc(100vw - 16px); bottom: 8px; right: 8px; left: 8px; }
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hls.js/1.4.12/hls.min.js"></script>
<link id="themeStylesheet" rel="stylesheet" href="themes/default.css">
</head>
<body>
<div class="loading" id="loading">
<div class="loading-text">Chargement du guide</div>
<div class="loading-bar"></div>
</div>
<div class="error-msg" id="errorMsg">
<div class="err-title">⚠ Impossible de charger l'EPG</div>
<div class="err-sub" id="errorDetail">Vérifiez l'URL de votre flux XMLTV.</div>
<div class="epg-input-bar">
<input class="epg-input" id="epgInput" type="text" placeholder="<?= $epg_url ?>" />
<button class="epg-btn" onclick="loadFromInput()">Charger</button>
</div>
</div>
<div class="tooltip" id="tooltip">
<div class="tooltip-title" id="tt-title"></div>
<div class="tooltip-time" id="tt-time"></div>
<div class="tooltip-desc" id="tt-desc"></div>
</div>
<div class="topbar">
<div class="logo"><?= $group_name ?> <span>/</span><span class="logo-sub"> GridTV</span></div>
<div class="date-label" id="dateLabel"></div>
<div class="clock" id="clock">00:00:00</div>
<div class="nav-btns" id="navBtns">
<button class="nav-btn" onclick="shiftView(-60)">◀ 1h</button>
<button class="nav-btn active" onclick="centerNow()">Maintenant</button>
<button class="nav-btn" onclick="shiftView(60)">1h ▶</button>
</div>
<div class="copy-btns">
<button class="copy-btn" onclick="copyUrl('epg')" title="Copier l'URL EPG">EPG</button>
<?php if (!empty($m3u_url)): ?>
<button class="copy-btn" onclick="copyUrl('m3u')" title="Copier l'URL M3U">M3U</button>
<?php endif; ?>
</div>
<?php if (count($epg_sources) > 1 || $allow_personal_epg): ?>
<select class="source-select" id="sourceSelect" onchange="switchSource(this.value)" title="Source EPG">
<?php foreach ($epg_sources as $i => $src): ?>
<option value="<?= $i ?>"><?= htmlspecialchars($src['name']) ?></option>
<?php endforeach; ?>
<?php if ($allow_personal_epg): ?>
<option value="personal">✏ Personal EPG</option>
<?php endif; ?>
</select>
<?php endif; ?>
<select class="theme-select" id="themeSelect" onchange="setTheme(this.value)" title="Thème">
<?php
$theme_dir = __DIR__ . '/themes';
$theme_files = glob($theme_dir . '/*.css');
// default en premier, puis le reste par ordre alphabétique
usort($theme_files, function($a, $b) {
$a_base = basename($a, '.css');
$b_base = basename($b, '.css');
if ($a_base === 'default') return -1;
if ($b_base === 'default') return 1;
return strcmp($a_base, $b_base);
});
foreach ($theme_files as $file) {
$slug = basename($file, '.css');
$css = file_get_contents($file);
// Lire @name et @emoji dans le premier bloc commentaire
preg_match('/@name\s+(.+)/u', $css, $m_name);
preg_match('/@emoji\s+(\S+)/u', $css, $m_emoji);
$name = isset($m_name[1]) ? trim($m_name[1]) : ucfirst($slug);
$emoji = isset($m_emoji[1]) ? trim($m_emoji[1]) : '🎨';
echo ' <option value="' . htmlspecialchars($slug) . '">' . $emoji . ' ' . $name . '</option>' . "\n";
}
?>
</select>
<div class="live-dot">LIVE</div>
</div>
<!-- PLAYER PiP -->
<div class="pip" id="pip">
<div class="pip-header">
<div class="pip-channel" id="pipChannel">—</div>
<div class="pip-program" id="pipProgram"></div>
<button class="pip-close" onclick="closePip()" title="Fermer">✕</button>
</div>
<video id="pipVideo" controls playsinline></video>
<div class="pip-error" id="pipError">⚠ Stream indisponible</div>
</div>
<!-- GRID (desktop/tablet) -->
<div class="grid-wrapper">
<div class="channels-col">
<div class="channels-col-header"><span>Chaînes</span></div>
<div class="channels-list" id="channelsList"></div>
</div>
<div class="timeline-area" id="timelineArea">
<div class="timeline-inner" id="timelineInner">
<div class="time-ruler" id="timeRuler">
<div class="time-ruler-inner" id="timeRulerInner"></div>
</div>
<div class="programs-inner" id="programsInner"></div>
</div>
</div>
</div>
<!-- LIST (mobile) -->
<div class="mobile-view" id="mobileView"></div>
<script>
const EPG_SOURCES = <?= json_encode(array_values($epg_sources)) ?>;
const ALLOW_PERSONAL_EPG = <?= $allow_personal_epg ? 'true' : 'false' ?>;
// Source active (index)
let activeSourceIndex = 0;
const DEFAULT_EPG_URL = EPG_SOURCES[0]?.epg_url ?? '';
const DEFAULT_M3U_URL = EPG_SOURCES[0]?.m3u_url ?? '';
const PX_PER_MIN = 5;
const GRID_HOURS = 72;
const CORS_PROXY = 'https://corsproxy.io/?';
// Ancre : 2h avant maintenant, arrondi au quart d'heure inférieur
const _d = new Date();
_d.setMinutes(Math.floor(_d.getMinutes()/15)*15, 0, 0);
const GRID_START = new Date(_d.getTime() - 2*3600000);
const GRID_END = new Date(GRID_START.getTime() + GRID_HOURS*3600000);
const TOTAL_WIDTH_PX = GRID_HOURS * 60 * PX_PER_MIN;
function msToX(ms) { return (ms - GRID_START.getTime()) / 60000 * PX_PER_MIN; }
let channels = [];
let programs = {};
let m3uStreams = {}; // slug normalisé → url stream
let scrollListenerAdded = false; // sync scroll vertical chaînes
function pad(n) { return String(n).padStart(2,'0'); }
function copyUrl(type) {
const url = type === 'epg' ? currentEpgUrl : currentM3uUrl;
if (!url) return;
navigator.clipboard.writeText(url).then(() => {
const btns = document.querySelectorAll('.copy-btn');
btns.forEach(b => { if (b.textContent.toLowerCase() === type) {
b.textContent = '✓ copié';
b.classList.add('copied');
setTimeout(() => { b.textContent = type.toUpperCase(); b.classList.remove('copied'); }, 1800);
}});
}).catch(() => {
prompt('Copiez cette URL :', url);
});
}
function fmtTime(d) { return `${pad(d.getHours())}:${pad(d.getMinutes())}`; }
function fmtTimeFull(d) { return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; }
function isMobile() { return window.innerWidth <= 600; }
function parseXMLTVDate(str) {
if (!str) return null;
const m = str.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\s*([+-]\d{4})?/);
if (!m) return null;
const offset = m[7] ? parseInt(m[7]) : 0;
const offsetMs = (Math.floor(Math.abs(offset)/100)*60 + (Math.abs(offset)%100)) * 60000 * (offset<0?-1:1);
return new Date(Date.UTC(+m[1],+m[2]-1,+m[3],+m[4],+m[5],+m[6]) - offsetMs);
}
function updateClock() {
const now = new Date();
document.getElementById('clock').textContent = fmtTimeFull(now);
const days=['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'];
const months=['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'];
document.getElementById('dateLabel').textContent =
`${days[now.getDay()]} ${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()}`;
}
setInterval(updateClock, 1000);
updateClock();
async function fetchXML(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return new DOMParser().parseFromString(await res.text(), 'text/xml');
}
async function loadEPG(url) {
document.getElementById('loading').style.display = 'flex';
document.getElementById('errorMsg').style.display = 'none';
try {
let doc;
try { doc = await fetchXML(url); }
catch(e) { doc = await fetchXML(CORS_PROXY + encodeURIComponent(url)); }
parseAndRender(doc);
document.getElementById('loading').style.display = 'none';
} catch(e) {
document.getElementById('loading').style.display = 'none';
document.getElementById('errorMsg').style.display = 'flex';
document.getElementById('errorDetail').textContent = `Erreur: ${e.message}`;
document.getElementById('epgInput').value = url;
}
}
function loadFromInput() {
const url = document.getElementById('epgInput').value.trim();
if (url) loadEPG(url);
}
function parseEpisode(p) {
// Format xmltv_ns : "S.E.part" (0-indexed) ex: "0.2.0/1" = S01E03
const ns = p.querySelector('episode-num[system="xmltv_ns"]')?.textContent;
if (ns) {
const parts = ns.split('.');
const s = parts[0] !== undefined && parts[0].trim() !== '' ? parseInt(parts[0].trim()) + 1 : null;
const ePart = parts[1] !== undefined ? parts[1].trim().split('/')[0] : '';
const e = ePart !== '' ? parseInt(ePart) + 1 : null;
if (s !== null || e !== null) return { season: s, episode: e };
}
// Format onscreen : "S01E03" ou "s1e3"
const os = p.querySelector('episode-num[system="onscreen"]')?.textContent;
if (os) {
const m = os.match(/[Ss](\d+)[Ee](\d+)/);
if (m) return { season: parseInt(m[1]), episode: parseInt(m[2]) };
const m2 = os.match(/[Ee][Pp]?\s*(\d+)/i);
if (m2) return { season: null, episode: parseInt(m2[1]) };
}
return { season: null, episode: null };
}
function fmtEpisode(season, episode) {
if (season !== null && episode !== null) return `S${String(season).padStart(2,'0')}E${String(episode).padStart(2,'0')}`;
if (episode !== null) return `E${String(episode).padStart(2,'0')}`;
return null;
}
function parseAndRender(doc) {
channels = []; programs = {};
doc.querySelectorAll('channel').forEach(ch => {
const id = ch.getAttribute('id');
const name = ch.querySelector('display-name')?.textContent || id;
const icon = ch.querySelector('icon')?.getAttribute('src') || null;
const num = parseInt(name.match(/^(\d+)/)?.[1] ?? '9999');
channels.push({ id, name, icon, num });
programs[id] = [];
});
channels.sort((a,b) => a.num - b.num);
doc.querySelectorAll('programme').forEach(p => {
const chId = p.getAttribute('channel');
if (!programs[chId]) programs[chId] = [];
const start = parseXMLTVDate(p.getAttribute('start'));
const stop = parseXMLTVDate(p.getAttribute('stop'));
const title = p.querySelector('title')?.textContent || '';
const desc = p.querySelector('desc')?.textContent || '';
const epInfo = parseEpisode(p);
if (start && stop) programs[chId].push({ start, stop, title, desc, ...epInfo });
});
Object.keys(programs).forEach(id => programs[id].sort((a,b) => a.start - b.start));
renderAll();
startLiveUpdates();
}
function renderAll() {
if (isMobile()) { renderMobile(); }
else { renderGrid(); setTimeout(centerNow, 150); }
}
// ── GRID ──────────────────────────────────────────────────────────────────────
function renderGrid() {
renderChannels(); renderRuler(); renderPrograms(); positionNowLine();
}
function makePlaceholder(name) {
const el = document.createElement('div');
el.className = 'channel-logo-placeholder';
el.textContent = name.substring(0,2).toUpperCase();
return el;
}
function renderChannels() {
const list = document.getElementById('channelsList');
list.innerHTML = '';
channels.forEach(ch => {
const cell = document.createElement('div');
cell.className = 'channel-cell';
if (ch.icon) {
const img = document.createElement('img');
img.className = 'channel-logo'; img.src = ch.icon;
img.onerror = () => img.replaceWith(makePlaceholder(ch.name));
cell.appendChild(img);
} else { cell.appendChild(makePlaceholder(ch.name)); }
const name = document.createElement('div');
name.className = 'channel-name'; name.textContent = ch.name; name.title = ch.name;
cell.appendChild(name);
cell.addEventListener('click', () => openPip(ch.name, getNowPlaying(ch.id)));
list.appendChild(cell);
});
}
function renderRuler() {
const ruler = document.getElementById('timeRulerInner');
ruler.innerHTML = ''; ruler.style.width = TOTAL_WIDTH_PX + 'px';
document.getElementById('timeRuler').style.width = TOTAL_WIDTH_PX + 'px';
let t = new Date(GRID_START); t.setSeconds(0,0);
const rem = t.getMinutes()%15; if (rem) t.setMinutes(t.getMinutes()+(15-rem));
while (t <= GRID_END) {
const x = msToX(t.getTime()); const isHour = t.getMinutes()===0;
const tick = document.createElement('div'); tick.className='time-tick'; tick.style.left=x+'px';
const lbl = document.createElement('div'); lbl.className='time-tick-label'+(isHour?' hour':''); lbl.textContent=fmtTime(t);
const line = document.createElement('div'); line.className='time-tick-line'+(isHour?' hour':'');
tick.appendChild(lbl); tick.appendChild(line); ruler.appendChild(tick);
t = new Date(t.getTime()+15*60000);
}
}
function renderPrograms() {
const ROW_H = 80;
const inner = document.getElementById('programsInner');
const totalH = channels.length * ROW_H;
inner.innerHTML = '';
inner.style.width = TOTAL_WIDTH_PX+'px';
inner.style.height = totalH+'px';
// Remettre la now-line (détruite par innerHTML='')
const nowLine = document.createElement('div');
nowLine.className = 'now-line'; nowLine.id = 'nowLine';
nowLine.style.height = totalH + 'px';
inner.appendChild(nowLine);
const now = new Date();
channels.forEach((ch, i) => {
const row = document.createElement('div');
row.className = 'program-row';
row.style.cssText = `top:${i*ROW_H}px;position:absolute;left:0;right:0;`;
(programs[ch.id]||[]).filter(p => p.stop>GRID_START && p.start<GRID_END).forEach(p => {
const x = Math.max(0, msToX(p.start.getTime()));
const w = Math.min(TOTAL_WIDTH_PX, msToX(p.stop.getTime())) - x;
if (w < 2) return;
const block = document.createElement('div'); block.className='program-block';
if (p.stop < now) block.classList.add('is-past');
if (p.start <= now && p.stop > now) {
block.classList.add('is-live');
block.style.setProperty('--progress',(((now-p.start)/(p.stop-p.start))*100).toFixed(1)+'%');
}
block.style.left=x+'px'; block.style.width=w+'px';
if (w>40) { const t=document.createElement('div'); t.className='program-title'; t.textContent=p.title; block.appendChild(t); }
if (w>80) {
const ep = fmtEpisode(p.season, p.episode);
const t=document.createElement('div'); t.className='program-time';
t.textContent = (ep ? ep + ' ' : '') + `${fmtTime(p.start)} — ${fmtTime(p.stop)}`;
block.appendChild(t);
}
block.addEventListener('mouseenter', e=>showTooltip(e,p));
block.addEventListener('mousemove', e=>moveTooltip(e));
block.addEventListener('mouseleave', hideTooltip);
if (p.start <= now && p.stop > now) {
block.addEventListener('click', () => openPip(ch.name, p.title));
}
row.appendChild(block);
});
inner.appendChild(row);
});
positionNowLine();
if (!scrollListenerAdded) {
scrollListenerAdded = true;
document.getElementById('timelineArea').addEventListener('scroll', function() {
document.getElementById('channelsList').scrollTop = this.scrollTop;
});
}
}
function positionNowLine() {
const x = msToX(Date.now());
const line = document.getElementById('nowLine');
if (line) line.style.left = x + 'px';
}
function centerNow() {
const area = document.getElementById('timelineArea');
area.scrollLeft = Math.max(0, msToX(Date.now()) - area.offsetWidth * 0.3);
document.querySelectorAll('.nav-btn').forEach((b,i) => b.classList.toggle('active', i===1));
}
function shiftView(mins) {
const area = document.getElementById('timelineArea');
area.scrollLeft = Math.max(0, area.scrollLeft + mins * PX_PER_MIN);
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
}
// ── MOBILE ────────────────────────────────────────────────────────────────────
function renderMobile() {
const container = document.getElementById('mobileView');
container.innerHTML = '';
const now = new Date();
const winStart = new Date(now.getTime() - 30*60000);
const winEnd = new Date(now.getTime() + 4*3600000);
channels.forEach(ch => {
const progs = (programs[ch.id]||[]).filter(p => p.stop>winStart && p.start<winEnd);
if (!progs.length) return;
const section = document.createElement('div'); section.className='mobile-channel';
const header = document.createElement('div'); header.className='mobile-channel-header';
if (ch.icon) {
const img = document.createElement('img'); img.className='channel-logo'; img.src=ch.icon;
img.onerror = () => img.replaceWith(makePlaceholder(ch.name));
header.appendChild(img);
} else { header.appendChild(makePlaceholder(ch.name)); }
const name = document.createElement('div'); name.className='channel-name'; name.textContent=ch.name;
header.appendChild(name); section.appendChild(header);
const list = document.createElement('div'); list.className='mobile-programs';
progs.forEach(p => {
const isLive = p.start<=now && p.stop>now;
const isPast = p.stop<now;
const dur = Math.round((p.stop-p.start)/60000);
const item = document.createElement('div');
item.className = 'mobile-program'+(isLive?' is-live':'')+(isPast?' is-past':'');
if (isLive) {
const bar = document.createElement('div'); bar.className='mobile-program-progress';
bar.style.width = (((now-p.start)/(p.stop-p.start))*100).toFixed(1)+'%';
item.appendChild(bar);
}
const timeCol = document.createElement('div'); timeCol.className='mobile-program-time';
timeCol.innerHTML = `<span>${fmtTime(p.start)}</span><span>${fmtTime(p.stop)}</span>`;
item.appendChild(timeCol);
const info = document.createElement('div'); info.className='mobile-program-info';
const ep = fmtEpisode(p.season, p.episode);
info.innerHTML = `<div class="mobile-program-title">${p.title}</div><div class="mobile-program-dur">${ep ? ep + ' · ' : ''}${dur} min</div>`;
item.appendChild(info);
if (isLive) {
const badge = document.createElement('div'); badge.className='mobile-live-badge'; badge.textContent='LIVE';
item.appendChild(badge);
}
list.appendChild(item);
});
section.appendChild(list); container.appendChild(section);
});
}
// ── HELPERS ──────────────────────────────────────────────────────────────────
function getNowPlaying(chId) {
const now = new Date();
const p = (programs[chId] || []).find(p => p.start <= now && p.stop > now);
return p ? p.title : null;
}
// ── TOOLTIP ───────────────────────────────────────────────────────────────────
function showTooltip(e, p) {
const ep = fmtEpisode(p.season, p.episode);
document.getElementById('tt-title').textContent = p.title + (ep ? ' ' + ep : '');
document.getElementById('tt-time').textContent = `${fmtTime(p.start)} — ${fmtTime(p.stop)} · ${Math.round((p.stop-p.start)/60000)} min`;
document.getElementById('tt-desc').textContent = p.desc || '—';
document.getElementById('tooltip').classList.add('visible');
moveTooltip(e);
}
function moveTooltip(e) {
const tt = document.getElementById('tooltip');
const x=e.clientX+16, y=e.clientY+16;
tt.style.left = (x+tt.offsetWidth >window.innerWidth ? x-tt.offsetWidth -32 : x)+'px';
tt.style.top = (y+tt.offsetHeight>window.innerHeight ? y-tt.offsetHeight-32 : y)+'px';
}
function hideTooltip() { document.getElementById('tooltip').classList.remove('visible'); }
// ── SOURCE SWITCHER ───────────────────────────────────────────────────────────
let currentEpgUrl = EPG_SOURCES[0]?.epg_url ?? '';
let currentM3uUrl = EPG_SOURCES[0]?.m3u_url ?? '';
function switchSource(value) {
if (value === 'personal') {
openPersonalEpgModal();
return;
}
const idx = parseInt(value);
const src = EPG_SOURCES[idx];
if (!src) return;
activeSourceIndex = idx;
currentEpgUrl = src.epg_url;
currentM3uUrl = src.m3u_url ?? '';
loadEPG(currentEpgUrl);
if (currentM3uUrl) loadM3U(currentM3uUrl);
// Mettre à jour les boutons copy
updateCopyButtons();
}
function updateCopyButtons() {
// Rien à faire visuellement, copyUrl() lit currentEpgUrl/currentM3uUrl
}
function openPersonalEpgModal() {
const saved_epg = localStorage.getItem('gridtv-personal-epg') ?? '';
const saved_m3u = localStorage.getItem('gridtv-personal-m3u') ?? '';
const modal = document.getElementById('personalEpgModal');
document.getElementById('personalEpgInput').value = saved_epg;
document.getElementById('personalM3uInput').value = saved_m3u;
modal.classList.add('visible');
}
function closePersonalEpgModal() {
document.getElementById('personalEpgModal').classList.remove('visible');
// Si annulé, remettre le select sur la source précédente
const sel = document.getElementById('sourceSelect');
if (sel) sel.value = activeSourceIndex;
}
function applyPersonalEpg() {
const epg = document.getElementById('personalEpgInput').value.trim();
const m3u = document.getElementById('personalM3uInput').value.trim();
if (!epg) { alert('URL EPG obligatoire'); return; }
localStorage.setItem('gridtv-personal-epg', epg);
localStorage.setItem('gridtv-personal-m3u', m3u);
currentEpgUrl = epg;
currentM3uUrl = m3u;
closePersonalEpgModal();
loadEPG(epg);
if (m3u) loadM3U(m3u);
}
// ── M3U PARSER ────────────────────────────────────────────────────────────────
function slugify(str) {
return str.toLowerCase()
.replace(/^\d+\s*/, '') // virer le numéro de chaîne en début
.replace(/[^a-z0-9]/g, ''); // garder que alphanum
}
async function loadM3U(url) {
if (!url) return;
try {
let text;
try {
const r = await fetch(url); text = await r.text();
} catch(e) {
const r = await fetch(CORS_PROXY + encodeURIComponent(url)); text = await r.text();
}
parseM3U(text);
} catch(e) { console.warn('M3U load failed:', e); }
}
function parseM3U(text) {
m3uStreams = {};
const lines = text.split('\n');
let currentName = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line.startsWith('#EXTINF')) {
// Extraire le nom : dernière partie après la virgule
const comma = line.lastIndexOf(',');
currentName = comma !== -1 ? line.slice(comma + 1).trim() : null;
} else if (line && !line.startsWith('#') && currentName) {
m3uStreams[slugify(currentName)] = line;
currentName = null;
}
}
console.log(`M3U: ${Object.keys(m3uStreams).length} streams chargés`);
}
function getStreamUrl(channelName) {
const slug = slugify(channelName);
let url = null;
if (m3uStreams[slug]) {
url = m3uStreams[slug];
} else {
// Fallback : chercher une clé qui contient le slug ou l'inverse
for (const [key, u] of Object.entries(m3uStreams)) {
if (key.includes(slug) || slug.includes(key)) { url = u; break; }
}
}
if (!url) return null;
// Passer par proxy.php pour éviter le mixed content HTTP/HTTPS
if (url.startsWith('http://')) {
return 'proxy.php?url=' + encodeURIComponent(url);
}
return url;
}
// ── PLAYER PiP ────────────────────────────────────────────────────────────────
let hlsInstance = null;
function openPip(channelName, programTitle) {
const url = getStreamUrl(channelName);
const pip = document.getElementById('pip');
const video = document.getElementById('pipVideo');
const err = document.getElementById('pipError');
document.getElementById('pipChannel').textContent = channelName;
document.getElementById('pipProgram').textContent = programTitle || '';
err.style.display = 'none';
pip.classList.add('visible');
// Détruire l'instance HLS précédente
if (hlsInstance) { hlsInstance.destroy(); hlsInstance = null; }
video.src = '';
if (!url) {
err.style.display = 'block';
err.textContent = '⚠ Aucun stream trouvé pour cette chaîne';
return;
}
if (Hls.isSupported()) {
hlsInstance = new Hls({ enableWorker: false, debug: false });
hlsInstance.loadSource(url);
hlsInstance.attachMedia(video);
hlsInstance.on(Hls.Events.MANIFEST_PARSED, () => {
console.log('[PiP] Manifest parsed, lecture...');
video.play().catch(e => console.warn('[PiP] play() refusé:', e));
});
hlsInstance.on(Hls.Events.ERROR, (e, data) => {
console.error('[PiP] HLS error:', data.type, data.details, data.fatal, data.response);
if (data.fatal) {
const detail = data.response ? ` (HTTP ${data.response.code})` : ` (${data.details})`;
err.style.display = 'block';
err.textContent = '⚠ Erreur de lecture du stream' + detail;
}
});
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// Safari natif HLS
video.src = url;
video.addEventListener('loadedmetadata', () => video.play().catch(() => {}));
} else {
err.style.display = 'block';
err.textContent = '⚠ HLS non supporté sur ce navigateur';
}
}
function closePip() {
const pip = document.getElementById('pip');
const video = document.getElementById('pipVideo');
pip.classList.remove('visible');
if (hlsInstance) { hlsInstance.destroy(); hlsInstance = null; }
video.pause(); video.src = '';
}
// ── THÈMES ────────────────────────────────────────────────────────────────────
function setTheme(theme) {
document.getElementById('themeStylesheet').href = 'themes/' + theme + '.css';
localStorage.setItem('gridtv-theme', theme);
document.getElementById('themeSelect').value = theme;
}
function initTheme() {
const saved = localStorage.getItem('gridtv-theme') || 'default';
setTheme(saved);
}
initTheme();
// ── LIVE UPDATES ──────────────────────────────────────────────────────────────
function startLiveUpdates() {
setInterval(() => { if (!isMobile()) positionNowLine(); }, 30000);
setInterval(() => { if (channels.length) renderAll(); }, 60000);
setInterval(() => loadEPG(DEFAULT_EPG_URL), 30*60*1000);
}
// ── RESPONSIVE SWITCH ─────────────────────────────────────────────────────────
let lastMobile = null;
window.addEventListener('resize', () => {
const m = isMobile();
if (m !== lastMobile) { lastMobile=m; scrollListenerAdded=false; if (channels.length) renderAll(); }
});
window.addEventListener('load', () => { loadEPG(DEFAULT_EPG_URL); loadM3U(DEFAULT_M3U_URL); });
</script>
<!-- MODAL PERSONAL EPG -->
<div class="modal-overlay" id="personalEpgModal">
<div class="modal-card">
<div class="modal-title">✏ Personal EPG</div>
<div class="modal-subtitle">Utilisez votre propre source EPG/M3U sur cette instance.</div>
<div class="modal-field">
<label>URL EPG (XMLTV) *</label>
<input type="url" id="personalEpgInput" placeholder="http://mon-serveur/xmltv.xml">
</div>
<div class="modal-field">
<label>URL M3U <span style="opacity:.5;font-size:10px">(optionnel)</span></label>
<input type="url" id="personalM3uInput" placeholder="http://mon-serveur/channels.m3u">
</div>
<div class="modal-actions">
<button class="modal-btn-cancel" onclick="closePersonalEpgModal()">Annuler</button>
<button class="modal-btn-apply" onclick="applyPersonalEpg()">Appliquer</button>
</div>
</div>
</div>
</body>
</html>