Ripristinato per intero lo stato del commit 24391c4, che sull'iPhone
con l'icona installata si vedeva correttamente. Le modifiche dei commit
successivi restano nella storia per essere riprese una per volta.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
800 lines
33 KiB
JavaScript
800 lines
33 KiB
JavaScript
/**
|
|
* RPIGroup Play - logica dell'app
|
|
*
|
|
* Router cambio pagina via AJAX (le pagine stanno in pages/page/*.php), history, voce di menu attiva
|
|
* Player dock della radio fisso in basso: resta mentre si naviga; HLS (hls.js o nativo) con riserva MP3/AAC,
|
|
* brano in onda (API nowplaying di AzuraCast), Media Session, volume
|
|
* TV flusso video HLS della pagina playtv/{id}
|
|
* Podcast elenco e puntata aperta in un iframe (pagina contentrpigplay/podcast del sito)
|
|
* Offline avviso a schermo intero quando manca la rete
|
|
*/
|
|
(function () {
|
|
'use strict';
|
|
|
|
var BASE = window.BASE_PATH || '';
|
|
var content = document.getElementById('content');
|
|
var html = document.documentElement;
|
|
var body = document.body;
|
|
|
|
function $(sel, root) { return (root || document).querySelector(sel); }
|
|
function $$(sel, root) { return Array.prototype.slice.call((root || document).querySelectorAll(sel)); }
|
|
function store(key, value) {
|
|
try {
|
|
if (value === undefined) return localStorage.getItem(key);
|
|
if (value === null) localStorage.removeItem(key); else localStorage.setItem(key, value);
|
|
} catch (e) { /* archivio del browser non disponibile */ }
|
|
return null;
|
|
}
|
|
|
|
/* =====================================================================
|
|
Router
|
|
===================================================================== */
|
|
|
|
function pageFromLocation() {
|
|
var path = window.location.pathname;
|
|
if (BASE && path.indexOf(BASE) === 0) path = path.substring(BASE.length);
|
|
path = path.replace(/^\/+|\/+$/g, '');
|
|
if (path === 'index.php') path = '';
|
|
if (path.indexOf('index.php/') === 0) path = path.substring('index.php/'.length);
|
|
if (!path) {
|
|
var redirect = new URLSearchParams(window.location.search).get('redirect');
|
|
if (redirect) return redirect.replace(/^\/+|\/+$/g, '') || 'home';
|
|
}
|
|
return path || 'home';
|
|
}
|
|
|
|
function urlFor(page) {
|
|
return page === 'home' ? BASE + '/' : BASE + '/' + page;
|
|
}
|
|
|
|
function sectionOf(page) {
|
|
if (page.indexOf('play/') === 0) return 'radio';
|
|
if (page.indexOf('playtv/') === 0) return 'tv';
|
|
if (['home', 'radio', 'tv', 'podcast'].indexOf(page) !== -1) return page;
|
|
return '';
|
|
}
|
|
|
|
var Router = {
|
|
current: pageFromLocation(),
|
|
controller: null,
|
|
progressTimer: null,
|
|
|
|
progressStart: function () {
|
|
var bar = $('#route-progress');
|
|
if (!bar) return;
|
|
clearTimeout(this.progressTimer);
|
|
// Compare solo se il caricamento dura più di un attimo
|
|
this.progressTimer = setTimeout(function () {
|
|
bar.classList.remove('is-done');
|
|
bar.classList.add('is-loading');
|
|
}, 120);
|
|
},
|
|
|
|
progressEnd: function () {
|
|
var bar = $('#route-progress');
|
|
clearTimeout(this.progressTimer);
|
|
if (!bar) return;
|
|
if (bar.classList.contains('is-loading')) {
|
|
bar.classList.remove('is-loading');
|
|
bar.classList.add('is-done');
|
|
setTimeout(function () { bar.classList.remove('is-done'); }, 600);
|
|
}
|
|
},
|
|
|
|
load: function (page, options) {
|
|
var self = this;
|
|
var opts = options || {};
|
|
if (this.controller) this.controller.abort();
|
|
var controller = new AbortController();
|
|
this.controller = controller;
|
|
this.progressStart();
|
|
|
|
fetch(BASE + '/index.php/' + page, {
|
|
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
signal: controller.signal,
|
|
credentials: 'same-origin'
|
|
}).then(function (res) {
|
|
return res.text().then(function (text) { return { ok: res.ok, status: res.status, text: text }; });
|
|
}).then(function (res) {
|
|
if (controller.signal.aborted) return;
|
|
Pages.teardown();
|
|
content.innerHTML = res.ok ? res.text : self.errorHtml('Impossibile caricare la pagina (codice ' + res.status + ').');
|
|
self.current = page;
|
|
if (opts.push !== false) history.pushState({ page: page }, '', urlFor(page));
|
|
content.scrollTop = 0;
|
|
self.updateNav(page);
|
|
self.animateIn();
|
|
Pages.init(page);
|
|
}).catch(function (err) {
|
|
if (err && err.name === 'AbortError') return;
|
|
Pages.teardown();
|
|
content.innerHTML = self.errorHtml('Controlla la connessione a internet e riprova.');
|
|
self.animateIn();
|
|
}).then(function () {
|
|
if (self.controller === controller) {
|
|
self.controller = null;
|
|
self.progressEnd();
|
|
}
|
|
});
|
|
},
|
|
|
|
errorHtml: function (message) {
|
|
return '<div class="page"><div class="container"><div class="card load-error">' +
|
|
'<h2>Qualcosa non va</h2><p>' + message + '</p>' +
|
|
'<a href="' + urlFor('home') + '" data-page="home" class="btn btn-accent">Torna alla home</a>' +
|
|
'</div></div></div>';
|
|
},
|
|
|
|
animateIn: function () {
|
|
content.classList.remove('is-entering');
|
|
// Forza il riavvio dell'animazione
|
|
void content.offsetWidth;
|
|
content.classList.add('is-entering');
|
|
setTimeout(function () { content.classList.remove('is-entering'); }, 400);
|
|
},
|
|
|
|
updateNav: function (page) {
|
|
var section = sectionOf(page);
|
|
$$('[data-nav]').forEach(function (a) {
|
|
var active = a.getAttribute('data-nav') === section;
|
|
a.classList.toggle('is-active', active);
|
|
if (active) a.setAttribute('aria-current', 'page'); else a.removeAttribute('aria-current');
|
|
});
|
|
},
|
|
|
|
init: function () {
|
|
var self = this;
|
|
history.replaceState({ page: this.current }, '', urlFor(this.current) + window.location.search.replace(/[?&]redirect=[^&]*/, '').replace(/^&/, '?'));
|
|
|
|
// Un solo gestore per tutti i link interni, anche quelli caricati dopo
|
|
document.addEventListener('click', function (e) {
|
|
var a = e.target.closest('a[data-page]');
|
|
if (!a || e.defaultPrevented) return;
|
|
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
|
e.preventDefault();
|
|
var page = a.getAttribute('data-page');
|
|
if (page === self.current) {
|
|
content.scrollTo({ top: 0, behavior: 'smooth' });
|
|
return;
|
|
}
|
|
self.load(page);
|
|
});
|
|
|
|
window.addEventListener('popstate', function (e) {
|
|
var state = e.state || {};
|
|
var page = state.page || pageFromLocation();
|
|
// Puntata podcast aperta/chiusa con il tasto indietro
|
|
if (page === self.current && self.current === 'podcast') {
|
|
if (!state.podcast) Podcast.close(false);
|
|
return;
|
|
}
|
|
if (page !== self.current) self.load(page, { push: false });
|
|
});
|
|
|
|
this.updateNav(this.current);
|
|
Pages.init(this.current);
|
|
}
|
|
};
|
|
|
|
/* =====================================================================
|
|
Pagine: avvio e pulizia dei componenti di ogni pagina
|
|
===================================================================== */
|
|
|
|
var Pages = {
|
|
init: function (page) {
|
|
var view = $('[data-station]', content);
|
|
if (view) {
|
|
try {
|
|
var station = JSON.parse(view.getAttribute('data-station'));
|
|
// Chi arriva qui con un tocco su una radio vuole ascoltarla: parte subito
|
|
Player.load(station, { autoplay: true });
|
|
} catch (e) { console.error('Dati stazione non validi', e); }
|
|
}
|
|
|
|
var video = $('#tvVideoPlayer', content);
|
|
if (video) TV.init(video);
|
|
|
|
if (page === 'podcast') Podcast.reset();
|
|
},
|
|
|
|
teardown: function () {
|
|
TV.destroy();
|
|
Podcast.closeIframe();
|
|
}
|
|
};
|
|
|
|
/* =====================================================================
|
|
Player della radio (dock)
|
|
===================================================================== */
|
|
|
|
var Player = {
|
|
dock: $('#player-dock'),
|
|
audio: $('#radio-audio'),
|
|
station: null,
|
|
hls: null,
|
|
format: 'hls', // 'hls' oppure 'direct' (MP3/AAC)
|
|
fallbackTried: false,
|
|
networkRetries: 0,
|
|
pollTimer: null,
|
|
nowPlaying: null,
|
|
stopping: false,
|
|
|
|
ui: {
|
|
play: $('#dock-play'),
|
|
link: $('#dock-link'),
|
|
cover: $('#dock-cover'),
|
|
title: $('#dock-title'),
|
|
artist: $('#dock-artist'),
|
|
format: $('#dock-format'),
|
|
mute: $('#dock-mute'),
|
|
volume: $('#dock-volume'),
|
|
close: $('#dock-close')
|
|
},
|
|
|
|
hlsConfig: {
|
|
debug: false,
|
|
enableWorker: true,
|
|
lowLatencyMode: false,
|
|
backBufferLength: 90,
|
|
maxBufferLength: 30,
|
|
liveDurationInfinity: true,
|
|
xhrSetup: function (xhr) { xhr.withCredentials = false; }
|
|
},
|
|
|
|
/** Mostra il dock con i dati della stazione; se è un'altra stazione, la sostituisce */
|
|
load: function (station, options) {
|
|
var opts = options || {};
|
|
if (this.station && this.station.id === station.id) {
|
|
this.show();
|
|
if (opts.autoplay && this.audio.paused) this.play();
|
|
return;
|
|
}
|
|
this.stop();
|
|
this.station = station;
|
|
this.nowPlaying = null;
|
|
this.fallbackTried = false;
|
|
this.networkRetries = 0;
|
|
this.format = (!station.streamhls) ? 'direct' : (store('rpi-format-' + station.id) || 'hls');
|
|
if (!station.stream && station.streamhls) this.format = 'hls';
|
|
|
|
this.ui.link.setAttribute('href', urlFor('play/' + station.id));
|
|
this.ui.link.setAttribute('data-page', 'play/' + station.id);
|
|
this.ui.link.setAttribute('aria-label', 'Apri ' + station.name);
|
|
this.ui.format.hidden = !(station.stream && station.streamhls);
|
|
this.paintFormat();
|
|
this.paintNowPlaying();
|
|
this.setState('paused');
|
|
this.show();
|
|
this.startPolling();
|
|
if (opts.autoplay) this.play();
|
|
},
|
|
|
|
show: function () {
|
|
this.dock.hidden = false;
|
|
body.classList.add('has-player');
|
|
},
|
|
|
|
hide: function () {
|
|
this.dock.hidden = true;
|
|
body.classList.remove('has-player');
|
|
},
|
|
|
|
/** Prepara la sorgente in base al formato scelto (HLS con hls.js, HLS nativo su Safari, oppure diretto) */
|
|
prepare: function () {
|
|
var st = this.station;
|
|
this.destroyHls();
|
|
var useHls = this.format === 'hls' && st.streamhls;
|
|
|
|
if (useHls && window.Hls && window.Hls.isSupported()) {
|
|
var self = this;
|
|
var hls = new window.Hls(this.hlsConfig);
|
|
this.hls = hls;
|
|
hls.on(window.Hls.Events.MANIFEST_PARSED, function (event, data) {
|
|
// Si parte dal livello di qualità più alto
|
|
if (data.levels && data.levels.length > 1) hls.startLevel = data.levels.length - 1;
|
|
});
|
|
hls.on(window.Hls.Events.ERROR, function (event, data) {
|
|
if (!data.fatal) return;
|
|
switch (data.type) {
|
|
case window.Hls.ErrorTypes.NETWORK_ERROR:
|
|
if (self.networkRetries++ < 3) { hls.startLoad(); break; }
|
|
self.onError();
|
|
break;
|
|
case window.Hls.ErrorTypes.MEDIA_ERROR:
|
|
hls.recoverMediaError();
|
|
break;
|
|
default:
|
|
self.onError();
|
|
}
|
|
});
|
|
hls.loadSource(st.streamhls);
|
|
hls.attachMedia(this.audio);
|
|
return;
|
|
}
|
|
|
|
if (useHls && this.audio.canPlayType('application/vnd.apple.mpegurl')) {
|
|
this.audio.src = st.streamhls;
|
|
return;
|
|
}
|
|
|
|
this.audio.src = st.stream || st.streamhls;
|
|
},
|
|
|
|
play: function () {
|
|
if (!this.station) return;
|
|
var self = this;
|
|
// Una cosa alla volta: il video della TV si ferma
|
|
TV.pause();
|
|
|
|
if (!this.hls && !this.audio.getAttribute('src')) {
|
|
this.prepare();
|
|
} else if (this.hls) {
|
|
// Diretta: dopo una pausa si riparte dal vivo
|
|
if (this.hls.liveSyncPosition) this.audio.currentTime = this.hls.liveSyncPosition;
|
|
} else {
|
|
this.audio.load();
|
|
}
|
|
|
|
this.setState('buffering');
|
|
var promise = this.audio.play();
|
|
if (promise && promise.catch) {
|
|
promise.catch(function (err) {
|
|
if (!err) return;
|
|
if (err.name === 'NotAllowedError') {
|
|
// Il browser vuole un tocco dell'utente: il dock resta pronto con il tasto play
|
|
self.setState('paused');
|
|
} else if (err.name !== 'AbortError') {
|
|
self.onError();
|
|
}
|
|
});
|
|
}
|
|
},
|
|
|
|
pause: function () {
|
|
if (!this.audio.paused) this.audio.pause();
|
|
},
|
|
|
|
toggle: function () {
|
|
if (!this.station) return;
|
|
if (this.audio.paused) this.play(); else this.pause();
|
|
},
|
|
|
|
/** Ferma tutto e libera la sorgente (cambio stazione, chiusura) */
|
|
stop: function () {
|
|
this.stopping = true;
|
|
this.stopPolling();
|
|
this.pause();
|
|
this.destroyHls();
|
|
this.audio.removeAttribute('src');
|
|
this.audio.load();
|
|
this.stopping = false;
|
|
this.setState('paused');
|
|
},
|
|
|
|
close: function () {
|
|
this.stop();
|
|
this.station = null;
|
|
this.hide();
|
|
if ('mediaSession' in navigator) {
|
|
navigator.mediaSession.metadata = null;
|
|
navigator.mediaSession.playbackState = 'none';
|
|
}
|
|
},
|
|
|
|
destroyHls: function () {
|
|
if (this.hls) {
|
|
try { this.hls.destroy(); } catch (e) { /* già distrutta */ }
|
|
this.hls = null;
|
|
}
|
|
},
|
|
|
|
setFormat: function (format) {
|
|
if (!this.station || format === this.format) return;
|
|
var wasPlaying = !this.audio.paused;
|
|
this.format = format;
|
|
this.fallbackTried = false;
|
|
this.networkRetries = 0;
|
|
store('rpi-format-' + this.station.id, format);
|
|
this.paintFormat();
|
|
this.pause();
|
|
this.destroyHls();
|
|
this.audio.removeAttribute('src');
|
|
this.audio.load();
|
|
if (wasPlaying) this.play();
|
|
},
|
|
|
|
paintFormat: function () {
|
|
var label = this.format === 'hls' ? 'HLS' : 'MP3';
|
|
this.ui.format.textContent = label;
|
|
this.ui.format.setAttribute('aria-label', 'Formato audio: ' + label + '. Tocca per cambiare');
|
|
},
|
|
|
|
onError: function () {
|
|
if (this.stopping || !this.station) return;
|
|
// Prima riserva: dal flusso HLS si passa a quello diretto, una volta sola
|
|
if (!this.fallbackTried && this.format === 'hls' && this.station.stream) {
|
|
this.fallbackTried = true;
|
|
this.destroyHls();
|
|
this.audio.src = this.station.stream;
|
|
var self = this;
|
|
this.setState('buffering');
|
|
var p = this.audio.play();
|
|
if (p && p.catch) p.catch(function (err) { if (!err || err.name !== 'AbortError') self.showError(); });
|
|
return;
|
|
}
|
|
this.showError();
|
|
},
|
|
|
|
showError: function () {
|
|
this.pause();
|
|
this.setState('error');
|
|
this.ui.title.textContent = 'Diretta non disponibile al momento';
|
|
this.ui.artist.textContent = 'Riprova tra qualche istante';
|
|
},
|
|
|
|
/** Stato visivo: paused | buffering | playing | error (classi su dock e <html>) */
|
|
setState: function (state) {
|
|
this.dock.classList.toggle('is-playing', state === 'playing');
|
|
this.dock.classList.toggle('is-buffering', state === 'buffering');
|
|
this.dock.classList.toggle('is-error', state === 'error');
|
|
html.classList.toggle('is-playing', state === 'playing' || state === 'buffering');
|
|
this.ui.play.setAttribute('aria-label', state === 'playing' || state === 'buffering' ? 'Metti in pausa' : 'Ascolta');
|
|
if ('mediaSession' in navigator && this.station) {
|
|
navigator.mediaSession.playbackState = state === 'playing' ? 'playing' : 'paused';
|
|
}
|
|
},
|
|
|
|
/* ---- Brano in onda ---- */
|
|
|
|
startPolling: function () {
|
|
var self = this;
|
|
this.stopPolling();
|
|
if (!this.station || !this.station.api) return;
|
|
var tick = function () {
|
|
fetch(self.station.api, { cache: 'no-store' })
|
|
.then(function (r) { return r.json(); })
|
|
.then(function (data) {
|
|
var song = data && data.now_playing && data.now_playing.song;
|
|
if (!song) return;
|
|
self.nowPlaying = { title: song.title || '', artist: song.artist || '', art: song.art || '' };
|
|
self.paintNowPlaying();
|
|
})
|
|
.catch(function () { /* il dato arriverà al prossimo giro */ });
|
|
};
|
|
tick();
|
|
this.pollTimer = setInterval(tick, 10000);
|
|
},
|
|
|
|
stopPolling: function () {
|
|
if (this.pollTimer) { clearInterval(this.pollTimer); this.pollTimer = null; }
|
|
},
|
|
|
|
paintNowPlaying: function () {
|
|
var st = this.station;
|
|
if (!st) return;
|
|
var np = this.nowPlaying || {};
|
|
var title = np.title || st.name;
|
|
var artist = np.artist || st.slogan || '';
|
|
var cover = np.art || st.logo;
|
|
|
|
if (this.dock.classList.contains('is-error')) return;
|
|
this.ui.title.textContent = title;
|
|
this.ui.artist.textContent = artist;
|
|
if (this.ui.cover.getAttribute('src') !== cover) this.ui.cover.src = cover;
|
|
|
|
// Elementi della pagina della radio (scheda senza iframe)
|
|
$$('[data-np="title"]', content).forEach(function (el) { el.textContent = title; });
|
|
$$('[data-np="artist"]', content).forEach(function (el) { el.textContent = artist; });
|
|
$$('[data-np="cover"]', content).forEach(function (el) { if (el.getAttribute('src') !== cover) el.src = cover; });
|
|
|
|
this.updateMediaSession(title, artist, cover);
|
|
},
|
|
|
|
updateMediaSession: function (title, artist, cover) {
|
|
if (!('mediaSession' in navigator) || !this.station) return;
|
|
var self = this;
|
|
try {
|
|
navigator.mediaSession.metadata = new MediaMetadata({
|
|
title: title,
|
|
artist: artist,
|
|
album: this.station.name,
|
|
artwork: cover ? [{ src: cover, sizes: '512x512', type: 'image/png' }] : []
|
|
});
|
|
navigator.mediaSession.setActionHandler('play', function () { self.play(); });
|
|
navigator.mediaSession.setActionHandler('pause', function () { self.pause(); });
|
|
navigator.mediaSession.setActionHandler('stop', function () { self.pause(); });
|
|
['seekbackward', 'seekforward', 'previoustrack', 'nexttrack'].forEach(function (a) {
|
|
try { navigator.mediaSession.setActionHandler(a, null); } catch (e) { /* non supportato */ }
|
|
});
|
|
} catch (e) { /* Media Session non disponibile */ }
|
|
},
|
|
|
|
/* ---- Volume (computer) ---- */
|
|
|
|
paintVolume: function () {
|
|
var muted = this.audio.muted || this.audio.volume === 0;
|
|
var value = muted ? 0 : this.audio.volume;
|
|
this.dock.classList.toggle('is-muted', muted);
|
|
this.ui.mute.setAttribute('aria-label', muted ? "Riattiva l'audio" : "Disattiva l'audio");
|
|
this.ui.volume.value = String(value);
|
|
this.ui.volume.style.setProperty('--val', (value * 100) + '%');
|
|
store('rpi-volume', String(value));
|
|
},
|
|
|
|
init: function () {
|
|
var self = this;
|
|
var audio = this.audio;
|
|
|
|
this.ui.play.addEventListener('click', function () { self.toggle(); });
|
|
this.ui.close.addEventListener('click', function () { self.close(); });
|
|
this.ui.format.addEventListener('click', function () {
|
|
self.setFormat(self.format === 'hls' ? 'direct' : 'hls');
|
|
});
|
|
|
|
audio.addEventListener('playing', function () { self.setState('playing'); });
|
|
audio.addEventListener('waiting', function () { if (!audio.paused) self.setState('buffering'); });
|
|
audio.addEventListener('pause', function () {
|
|
if (!self.dock.classList.contains('is-error')) self.setState('paused');
|
|
});
|
|
audio.addEventListener('ended', function () { self.setState('paused'); });
|
|
audio.addEventListener('error', function () {
|
|
if (self.stopping || !audio.getAttribute('src')) return;
|
|
self.onError();
|
|
});
|
|
|
|
// Pulsanti "Ascolta" nelle pagine
|
|
document.addEventListener('click', function (e) {
|
|
var btn = e.target.closest('[data-play-toggle]');
|
|
if (!btn) return;
|
|
e.preventDefault();
|
|
if (self.station) {
|
|
self.toggle();
|
|
} else {
|
|
var view = $('[data-station]', content);
|
|
if (view) self.load(JSON.parse(view.getAttribute('data-station')), { autoplay: true });
|
|
}
|
|
});
|
|
|
|
// Volume
|
|
this.ui.mute.addEventListener('click', function () {
|
|
audio.muted = !audio.muted;
|
|
if (!audio.muted && audio.volume === 0) audio.volume = 0.7;
|
|
self.paintVolume();
|
|
});
|
|
this.ui.volume.addEventListener('input', function () {
|
|
audio.volume = parseFloat(self.ui.volume.value);
|
|
audio.muted = audio.volume === 0;
|
|
self.paintVolume();
|
|
});
|
|
var saved = parseFloat(store('rpi-volume'));
|
|
if (saved >= 0 && saved <= 1) {
|
|
audio.volume = saved;
|
|
audio.muted = saved === 0;
|
|
}
|
|
this.paintVolume();
|
|
|
|
// Tasti: spazio = play/pausa quando non si sta scrivendo
|
|
document.addEventListener('keydown', function (e) {
|
|
if (e.key !== ' ' || !self.station) return;
|
|
var t = e.target;
|
|
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'BUTTON' || t.tagName === 'A' || t.isContentEditable)) return;
|
|
e.preventDefault();
|
|
self.toggle();
|
|
});
|
|
}
|
|
};
|
|
|
|
/* =====================================================================
|
|
TV (flusso video HLS)
|
|
===================================================================== */
|
|
|
|
var TV = {
|
|
hls: null,
|
|
video: null,
|
|
|
|
init: function (video) {
|
|
this.destroy();
|
|
this.video = video;
|
|
var self = this;
|
|
var src = video.getAttribute('data-src');
|
|
var errorEl = $('.tv-error', video.parentNode);
|
|
|
|
function showError(msg) {
|
|
if (!errorEl) return;
|
|
errorEl.textContent = msg;
|
|
errorEl.hidden = false;
|
|
}
|
|
function start() {
|
|
var p = video.play();
|
|
if (p && p.catch) p.catch(function () { /* autoplay bloccato: l'utente premerà play */ });
|
|
}
|
|
|
|
if (!src) { showError('Nessun flusso video configurato per questo canale.'); return; }
|
|
|
|
// Una cosa alla volta: quando parte il video la radio si ferma
|
|
video.addEventListener('play', function () { Player.pause(); });
|
|
|
|
if (window.Hls && window.Hls.isSupported()) {
|
|
var hls = new window.Hls({ debug: false, enableWorker: true, liveDurationInfinity: true, backBufferLength: 30 });
|
|
this.hls = hls;
|
|
hls.on(window.Hls.Events.MANIFEST_PARSED, start);
|
|
hls.on(window.Hls.Events.ERROR, function (event, data) {
|
|
if (!data.fatal) return;
|
|
switch (data.type) {
|
|
case window.Hls.ErrorTypes.NETWORK_ERROR:
|
|
if (data.details === window.Hls.ErrorDetails.MANIFEST_LOAD_ERROR) {
|
|
showError('La diretta video non è disponibile al momento. Riprova tra poco.');
|
|
} else {
|
|
hls.startLoad();
|
|
}
|
|
break;
|
|
case window.Hls.ErrorTypes.MEDIA_ERROR:
|
|
hls.recoverMediaError();
|
|
break;
|
|
default:
|
|
showError('Errore nella riproduzione del video.');
|
|
self.destroy();
|
|
}
|
|
});
|
|
hls.loadSource(src);
|
|
hls.attachMedia(video);
|
|
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
|
|
video.src = src;
|
|
video.addEventListener('loadedmetadata', start, { once: true });
|
|
video.addEventListener('error', function () { showError('Errore nella riproduzione del video.'); });
|
|
} else {
|
|
showError('Il tuo browser non supporta questo flusso video.');
|
|
}
|
|
},
|
|
|
|
pause: function () {
|
|
if (this.video && !this.video.paused) this.video.pause();
|
|
},
|
|
|
|
destroy: function () {
|
|
if (this.hls) {
|
|
try { this.hls.destroy(); } catch (e) { /* già distrutta */ }
|
|
this.hls = null;
|
|
}
|
|
if (this.video) {
|
|
try {
|
|
this.video.pause();
|
|
this.video.removeAttribute('src');
|
|
this.video.load();
|
|
} catch (e) { /* elemento già rimosso */ }
|
|
this.video = null;
|
|
}
|
|
}
|
|
};
|
|
|
|
/* =====================================================================
|
|
Podcast
|
|
===================================================================== */
|
|
|
|
var Podcast = {
|
|
open: function (url, title, source) {
|
|
var list = $('#podcast-list');
|
|
var detail = $('#podcast-detail');
|
|
var iframe = $('#podcast-iframe');
|
|
var page = $('#podcast-page');
|
|
if (!list || !detail || !iframe) return;
|
|
|
|
// La puntata ha il suo audio: la radio si ferma
|
|
Player.pause();
|
|
|
|
$('#podcast-detail-title').textContent = title || 'Puntata';
|
|
$('#podcast-detail-source').textContent = source || '';
|
|
iframe.src = url;
|
|
list.hidden = true;
|
|
detail.hidden = false;
|
|
if (page) page.classList.add('is-detail');
|
|
content.scrollTop = 0;
|
|
|
|
// Il tasto indietro del telefono o del browser torna all'elenco
|
|
if (!(history.state && history.state.podcast)) {
|
|
history.pushState({ page: 'podcast', podcast: true }, '', window.location.href);
|
|
}
|
|
},
|
|
|
|
close: function (viaHistory) {
|
|
var list = $('#podcast-list');
|
|
var detail = $('#podcast-detail');
|
|
var page = $('#podcast-page');
|
|
this.closeIframe();
|
|
if (detail) detail.hidden = true;
|
|
if (list) list.hidden = false;
|
|
if (page) page.classList.remove('is-detail');
|
|
if (viaHistory !== false && history.state && history.state.podcast) history.back();
|
|
},
|
|
|
|
closeIframe: function () {
|
|
var iframe = $('#podcast-iframe');
|
|
if (iframe && iframe.getAttribute('src') !== 'about:blank') iframe.src = 'about:blank';
|
|
},
|
|
|
|
reset: function () {
|
|
// Pagina appena caricata: elenco visibile
|
|
var page = $('#podcast-page');
|
|
if (page) page.classList.remove('is-detail');
|
|
},
|
|
|
|
init: function () {
|
|
var self = this;
|
|
function openFrom(el) {
|
|
self.open(el.getAttribute('data-podcast-url'), el.getAttribute('data-podcast-title'), el.getAttribute('data-podcast-source'));
|
|
}
|
|
document.addEventListener('click', function (e) {
|
|
var closeBtn = e.target.closest('[data-podcast-close]');
|
|
if (closeBtn) { e.preventDefault(); self.close(); return; }
|
|
var item = e.target.closest('[data-podcast-url]');
|
|
if (item) { e.preventDefault(); openFrom(item); }
|
|
});
|
|
document.addEventListener('keydown', function (e) {
|
|
if (e.key !== 'Enter' && e.key !== ' ') return;
|
|
var item = e.target.closest && e.target.closest('[data-podcast-url]');
|
|
if (item) { e.preventDefault(); openFrom(item); }
|
|
});
|
|
}
|
|
};
|
|
|
|
// Compatibilità con eventuali chiamate esterne (vecchie pagine)
|
|
window.openPodcast = function (url, title) { Podcast.open(url, title, ''); };
|
|
window.closePodcast = function () { Podcast.close(); };
|
|
|
|
/* =====================================================================
|
|
Offline
|
|
===================================================================== */
|
|
|
|
var Offline = {
|
|
init: function () {
|
|
var overlay = document.createElement('div');
|
|
overlay.id = 'offlineOverlay';
|
|
overlay.className = 'offline-overlay';
|
|
overlay.innerHTML =
|
|
'<div class="offline-content">' +
|
|
'<svg class="icon offline-icon" viewBox="0 0 24 24" width="72" height="72" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 2 22 22"/><path d="M8.5 16.5a5 5 0 0 1 7 0"/><path d="M2 8.82a15 15 0 0 1 4.17-2.65"/><path d="M10.66 5c4.01-.36 8.14.9 11.34 3.76"/><path d="M16.85 11.25a10 10 0 0 1 2.22 1.68"/><path d="M5 13a10 10 0 0 1 5.24-2.76"/><path d="M12 20h.01"/></svg>' +
|
|
'<h2 class="offline-title">Nessuna connessione</h2>' +
|
|
'<p class="offline-desc">Sembra che tu sia offline. Controlla la connessione a internet per continuare ad ascoltare RPIGroup Play.</p>' +
|
|
'<button type="button" class="btn btn-accent btn-lg offline-btn" id="offlineRetryBtn">' +
|
|
'<svg class="icon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>' +
|
|
'<span>Riprova</span></button></div>';
|
|
body.appendChild(overlay);
|
|
|
|
var btn = $('#offlineRetryBtn');
|
|
btn.addEventListener('click', function () {
|
|
btn.disabled = true;
|
|
btn.querySelector('.icon').classList.add('is-spinning');
|
|
btn.querySelector('span').textContent = 'Verifica in corso…';
|
|
fetch(BASE + '/robots.txt', { cache: 'no-store' })
|
|
.then(function () { overlay.classList.remove('active'); window.location.reload(); })
|
|
.catch(function () {
|
|
setTimeout(function () {
|
|
btn.disabled = false;
|
|
btn.querySelector('.icon').classList.remove('is-spinning');
|
|
btn.querySelector('span').textContent = 'Riprova';
|
|
}, 1000);
|
|
});
|
|
});
|
|
|
|
window.addEventListener('offline', function () { overlay.classList.add('active'); });
|
|
window.addEventListener('online', function () { overlay.classList.remove('active'); });
|
|
if (!navigator.onLine) overlay.classList.add('active');
|
|
}
|
|
};
|
|
|
|
/* =====================================================================
|
|
Avvio
|
|
===================================================================== */
|
|
|
|
function init() {
|
|
if (!content) return;
|
|
Offline.init();
|
|
Player.init();
|
|
Podcast.init();
|
|
Router.init();
|
|
}
|
|
|
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
|
|
else init();
|
|
})();
|