push
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
async function request(path, params) {
|
||||
const url = new URL(SR.config.getBase() + path);
|
||||
if (params) {
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
url.searchParams.set(key, String(value));
|
||||
}
|
||||
}
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url.toString());
|
||||
} catch (e) {
|
||||
throw new Error(`cannot reach the API at ${SR.config.getBase()} — check the base URL in Settings`);
|
||||
}
|
||||
let data = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch (e) {
|
||||
/* non-JSON body */
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error((data && data.error) || `API error: HTTP ${res.status}`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// route a media/subtitle URL through the API proxy (CORS, headers, m3u8 rewrite)
|
||||
function proxyUrl(target, headers) {
|
||||
const q = new URLSearchParams();
|
||||
q.set('url', target);
|
||||
q.set('h', JSON.stringify(headers || {}));
|
||||
return SR.config.getBase() + '/proxy/media?' + q.toString();
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.api = {
|
||||
request,
|
||||
proxyUrl,
|
||||
search: (q) => request('/search', { q }),
|
||||
trending: (type, timeWindow) => request('/trending', { type, window: timeWindow }),
|
||||
details: (type, id) => request(`/${type}/${id}`),
|
||||
seasons: (id) => request(`/tv/${id}/seasons`),
|
||||
episodes: (id, season) => request(`/tv/${id}/seasons/${season}`),
|
||||
streams: ({ tmdb, type, season, episode }) => request('/streams', { tmdb, type, season, episode }),
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
APP — shared chrome for every page: settings dialog, footer API label,
|
||||
toast notifications.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function initChrome() {
|
||||
const modal = document.getElementById('settingsModal');
|
||||
const openBtn = document.getElementById('settingsBtn');
|
||||
const input = document.getElementById('apiBaseInput');
|
||||
|
||||
if (openBtn && modal && input) {
|
||||
const close = () => {
|
||||
modal.hidden = true;
|
||||
};
|
||||
openBtn.addEventListener('click', () => {
|
||||
input.value = SR.config.getBase();
|
||||
modal.hidden = false;
|
||||
input.focus();
|
||||
input.select();
|
||||
});
|
||||
const closeBtn = document.getElementById('settingsClose');
|
||||
if (closeBtn) closeBtn.addEventListener('click', close);
|
||||
modal.addEventListener('click', (e) => {
|
||||
if (e.target === modal) close();
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && !modal.hidden) close();
|
||||
});
|
||||
const saveBtn = document.getElementById('apiBaseSave');
|
||||
if (saveBtn) {
|
||||
saveBtn.addEventListener('click', () => {
|
||||
SR.config.setBase(input.value);
|
||||
location.reload();
|
||||
});
|
||||
}
|
||||
const resetBtn = document.getElementById('apiBaseReset');
|
||||
if (resetBtn) {
|
||||
resetBtn.addEventListener('click', () => {
|
||||
SR.config.clearBase();
|
||||
location.reload();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const label = document.getElementById('apiBaseLabel');
|
||||
if (label) {
|
||||
const base = SR.config.getBase();
|
||||
label.textContent = base;
|
||||
label.href = base;
|
||||
}
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
|
||||
function toast(message, isError) {
|
||||
let el = document.getElementById('toast');
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = 'toast';
|
||||
el.className = 'toast';
|
||||
el.setAttribute('role', 'status');
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
el.textContent = message;
|
||||
el.classList.toggle('toast--error', !!isError);
|
||||
el.classList.add('toast--show');
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => el.classList.remove('toast--show'), 4500);
|
||||
}
|
||||
|
||||
function showError(err, fallback) {
|
||||
toast(err && err.message ? err.message : fallback || 'Something went wrong', true);
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.app = { initChrome, toast, showError };
|
||||
})();
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
CARDS — renders poster cards, rows (carousels) and grids.
|
||||
Items can come straight from the API ({tmdb_id, type, name, year, poster})
|
||||
or from storage records; normalizeItem() handles both.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const { escapeHtml: esc, tmdbResize, formatSeconds } = SR.util;
|
||||
|
||||
function normalizeItem(r) {
|
||||
return {
|
||||
tmdbId: r.tmdb_id != null ? r.tmdb_id : r.tmdbId,
|
||||
type: r.type,
|
||||
season: r.season,
|
||||
episode: r.episode,
|
||||
name: r.name || r.title || '',
|
||||
year: r.year || '',
|
||||
poster: r.poster || r.poster_url || '',
|
||||
overview: r.overview || '',
|
||||
};
|
||||
}
|
||||
|
||||
function watchHref(item) {
|
||||
const p = new URLSearchParams();
|
||||
p.set('id', item.tmdbId);
|
||||
p.set('type', item.type);
|
||||
if (item.type === 'tv') {
|
||||
if (item.season != null) p.set('s', item.season);
|
||||
if (item.episode != null) p.set('e', item.episode);
|
||||
}
|
||||
return `watch.html?${p.toString()}`;
|
||||
}
|
||||
|
||||
function card(item, opts = {}) {
|
||||
const el = document.createElement('a');
|
||||
el.className = 'card';
|
||||
el.href = opts.href || watchHref(item);
|
||||
const poster = tmdbResize(item.poster, 'w342');
|
||||
const progress =
|
||||
opts.progress != null
|
||||
? `<span class="card__progress"><i style="width:${Math.round(Math.min(1, opts.progress) * 100)}%"></i></span>`
|
||||
: '';
|
||||
const meta =
|
||||
item.meta ||
|
||||
(item.year
|
||||
? `${item.year} · ${item.type === 'tv' ? 'TV' : 'Movie'}`
|
||||
: item.type === 'tv'
|
||||
? 'TV'
|
||||
: 'Movie');
|
||||
el.innerHTML = `
|
||||
<span class="card__poster${poster ? '' : ' card__poster--empty'}">
|
||||
${poster ? `<img src="${poster}" alt="" loading="lazy">` : '?'}
|
||||
${progress}
|
||||
</span>
|
||||
<span class="card__title">${esc(item.name)}</span>
|
||||
<span class="card__meta">${esc(meta)}</span>`;
|
||||
return el;
|
||||
}
|
||||
|
||||
function row(title, items) {
|
||||
const section = document.createElement('section');
|
||||
section.className = 'row';
|
||||
section.innerHTML = `<div class="row__header"><h2 class="row__title">${esc(title)}</h2></div>`;
|
||||
const scroll = document.createElement('div');
|
||||
scroll.className = 'row__scroll';
|
||||
for (const item of items) scroll.appendChild(card(item));
|
||||
section.appendChild(scroll);
|
||||
return section;
|
||||
}
|
||||
|
||||
function grid(items) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'grid';
|
||||
for (const item of items) el.appendChild(card(item));
|
||||
return el;
|
||||
}
|
||||
|
||||
function emptyState(title, hint) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'empty';
|
||||
el.innerHTML = `<h3>${esc(title)}</h3>${hint ? `<p>${esc(hint)}</p>` : ''}`;
|
||||
return el;
|
||||
}
|
||||
|
||||
// "Continue watching" row: latest record per show, with progress bar
|
||||
function continueRow() {
|
||||
const recs = SR.storage.latestPerShow();
|
||||
if (!recs.length) return null;
|
||||
const items = recs.map((r) => ({
|
||||
tmdbId: r.tmdbId,
|
||||
type: r.type,
|
||||
season: r.season,
|
||||
episode: r.episode,
|
||||
name: r.show || r.title || '',
|
||||
poster: r.poster || '',
|
||||
meta:
|
||||
r.type === 'tv'
|
||||
? `S${r.season}E${r.episode}${r.title ? ` · ${r.title}` : ''} · ${formatSeconds(Math.max(0, r.d - r.t))} left`
|
||||
: `Movie · ${formatSeconds(Math.max(0, r.d - r.t))} left`,
|
||||
progress: r.d ? r.t / r.d : 0,
|
||||
}));
|
||||
return row('Continue watching', items);
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.cards = { normalizeItem, card, row, grid, emptyState, continueRow };
|
||||
})();
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
CONFIG — where the API lives. Resolution order:
|
||||
1. ?api=<url> query param on any page (session override)
|
||||
2. localStorage (saved from the Settings dialog)
|
||||
3. built-in default
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const DEFAULT_BASE = 'https://bug-api-test.tuns.sh';
|
||||
const STORAGE_KEY = 'streamreverse.apiBase.v1';
|
||||
|
||||
function normalize(value) {
|
||||
let v = String(value || '').trim();
|
||||
if (!v) return '';
|
||||
if (!/^https?:\/\//i.test(v)) v = `https://${v}`;
|
||||
return v.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
function getBase() {
|
||||
const fromQuery = SR.util.getParam('api');
|
||||
if (fromQuery) return normalize(fromQuery);
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) return normalize(stored);
|
||||
} catch (e) {
|
||||
/* private mode etc. */
|
||||
}
|
||||
return DEFAULT_BASE;
|
||||
}
|
||||
|
||||
function setBase(value) {
|
||||
const v = normalize(value);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, v);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function clearBase() {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.config = { DEFAULT_BASE, STORAGE_KEY, getBase, setBase, clearBase };
|
||||
})();
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
HOME — hero with search + continue-watching row + trending rows.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// quick-search chips in the hero — edit freely
|
||||
const QUICK_SEARCHES = ['Action', 'Comedy', 'Sci-Fi', 'Drama', 'Horror', 'Animation', 'Crime'];
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const sections = document.getElementById('sections');
|
||||
|
||||
const form = document.getElementById('heroForm');
|
||||
const input = document.getElementById('heroInput');
|
||||
if (form && input) {
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const q = input.value.trim();
|
||||
location.href = q ? `search.html?q=${encodeURIComponent(q)}` : 'search.html';
|
||||
});
|
||||
}
|
||||
|
||||
const chips = document.getElementById('heroChips');
|
||||
if (chips) {
|
||||
for (const term of QUICK_SEARCHES) {
|
||||
const a = document.createElement('a');
|
||||
a.className = 'chip';
|
||||
a.href = `search.html?q=${encodeURIComponent(term)}`;
|
||||
a.textContent = term;
|
||||
chips.appendChild(a);
|
||||
}
|
||||
}
|
||||
|
||||
const cont = SR.cards.continueRow();
|
||||
if (cont) sections.appendChild(cont);
|
||||
|
||||
function appendRow(data, title) {
|
||||
if (!data || !data.count) return;
|
||||
sections.appendChild(SR.cards.row(title, data.results.map(SR.cards.normalizeItem)));
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
appendRow(await SR.api.trending('movie', 'day'), 'Trending movies today');
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'could not load trending movies');
|
||||
}
|
||||
try {
|
||||
appendRow(await SR.api.trending('tv', 'week'), 'Trending shows this week');
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'could not load trending shows');
|
||||
}
|
||||
})();
|
||||
})();
|
||||
@@ -0,0 +1,180 @@
|
||||
/*
|
||||
PLAYER — plays a stream in a <video> element and supports switching
|
||||
sources mid-watch without losing your place.
|
||||
|
||||
Pipeline per stream:
|
||||
- hls.js for .m3u8 when available
|
||||
- native HLS for Safari (canPlayType check)
|
||||
- direct <video src> for mp4/webm
|
||||
- everything else (DASH, mkv, magnet, …) → friendly error
|
||||
|
||||
Every media + subtitle URL is routed through the API proxy.
|
||||
On source switch we carry over currentTime, playbackRate, volume, muted
|
||||
and the playing state, clamped to the new duration.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function create(video, handlers = {}) {
|
||||
const onStatus = handlers.onStatus || (() => {});
|
||||
const onError = handlers.onError || (() => {});
|
||||
const onReady = handlers.onReady || (() => {});
|
||||
|
||||
let hls = null;
|
||||
let token = 0; // guards against overlapping loads
|
||||
let networkRetry = false;
|
||||
|
||||
function teardown() {
|
||||
token++;
|
||||
if (hls) {
|
||||
try {
|
||||
hls.destroy();
|
||||
} catch (e) {
|
||||
/* already destroyed */
|
||||
}
|
||||
hls = null;
|
||||
}
|
||||
for (const track of video.querySelectorAll('track')) track.remove();
|
||||
video.removeAttribute('src');
|
||||
try {
|
||||
video.load();
|
||||
} catch (e) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function capture() {
|
||||
const v = video;
|
||||
return {
|
||||
time: isFinite(v.currentTime) && v.currentTime > 0 ? v.currentTime : 0,
|
||||
rate: v.playbackRate || 1,
|
||||
volume: v.volume,
|
||||
muted: v.muted,
|
||||
playing: !v.paused && !v.ended,
|
||||
};
|
||||
}
|
||||
|
||||
function restore(st) {
|
||||
const v = video;
|
||||
v.playbackRate = st.rate;
|
||||
v.volume = st.volume;
|
||||
v.muted = st.muted;
|
||||
const seek = () => {
|
||||
const d = v.duration;
|
||||
let t = st.time;
|
||||
if (isFinite(d) && d > 0) t = Math.min(t, Math.max(0, d - 5));
|
||||
if (t > 10) v.currentTime = t;
|
||||
if (st.playing) v.play().catch(() => {});
|
||||
};
|
||||
if (isFinite(v.duration) && v.duration > 0) seek();
|
||||
else v.addEventListener('loadedmetadata', seek, { once: true });
|
||||
}
|
||||
|
||||
function attachSubtitles(stream) {
|
||||
for (const sub of stream.subtitles || []) {
|
||||
let resolved;
|
||||
try {
|
||||
resolved = new URL(sub.url, stream.url).toString();
|
||||
} catch (e) {
|
||||
continue;
|
||||
}
|
||||
const track = document.createElement('track');
|
||||
track.kind = 'subtitles';
|
||||
track.srclang = sub.language || 'en';
|
||||
track.label = sub.name || sub.language || 'Subtitles';
|
||||
track.src = SR.api.proxyUrl(resolved, stream.headers);
|
||||
video.appendChild(track);
|
||||
}
|
||||
}
|
||||
|
||||
function load(stream, opts = {}) {
|
||||
const st = capture();
|
||||
if (typeof opts.resumeAt === 'number' && opts.resumeAt > 10) st.time = opts.resumeAt;
|
||||
|
||||
teardown();
|
||||
networkRetry = false;
|
||||
const myToken = token;
|
||||
const guarded = (fn) => () => {
|
||||
if (myToken === token) fn();
|
||||
};
|
||||
|
||||
const url = stream.url || '';
|
||||
const isHls = stream.type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
|
||||
const isDash = stream.type === 'dash' || /\.mpd($|\?)/i.test(url);
|
||||
const isDirect =
|
||||
stream.type === 'mp4' ||
|
||||
stream.type === 'webm' ||
|
||||
/\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
|
||||
|
||||
if (isDash) {
|
||||
onError('DASH streams are not supported yet — pick another source.');
|
||||
return;
|
||||
}
|
||||
if (!isHls && !isDirect) {
|
||||
onError(`The browser can't play ${stream.type} files directly — pick an MP4 or HLS source.`);
|
||||
return;
|
||||
}
|
||||
|
||||
attachSubtitles(stream);
|
||||
const proxied = SR.api.proxyUrl(url, stream.headers);
|
||||
|
||||
if (isHls && window.Hls && Hls.isSupported()) {
|
||||
onStatus('Loading stream…');
|
||||
const h = new Hls({ enableWorker: true });
|
||||
hls = h;
|
||||
h.loadSource(proxied);
|
||||
h.attachMedia(video);
|
||||
h.on(Hls.Events.MANIFEST_PARSED, guarded(() => {
|
||||
restore(st);
|
||||
onReady(st.time > 10 ? st.time : 0);
|
||||
}));
|
||||
h.on(Hls.Events.ERROR, (evt, data) => {
|
||||
if (myToken !== token || !data.fatal) return;
|
||||
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
|
||||
if (!networkRetry) {
|
||||
networkRetry = true;
|
||||
setTimeout(() => {
|
||||
networkRetry = false;
|
||||
if (myToken === token && hls === h) h.startLoad();
|
||||
}, 2000);
|
||||
}
|
||||
} else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
|
||||
h.recoverMediaError();
|
||||
} else {
|
||||
onError('Playback failed: ' + (data.details || 'unknown stream error'));
|
||||
teardown();
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// native HLS (Safari) or direct file
|
||||
onStatus('Loading stream…');
|
||||
video.src = proxied;
|
||||
video.addEventListener(
|
||||
'loadedmetadata',
|
||||
guarded(() => {
|
||||
restore(st);
|
||||
onReady(st.time > 10 ? st.time : 0);
|
||||
}),
|
||||
{ once: true }
|
||||
);
|
||||
video.addEventListener(
|
||||
'error',
|
||||
guarded(() => {
|
||||
onError('Could not load this stream — try another source.');
|
||||
}),
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
teardown();
|
||||
}
|
||||
|
||||
return { load, destroy };
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.player = { create };
|
||||
})();
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
SEARCH — debounced live search with client-side type filter.
|
||||
URL ?q= is kept in sync so results are shareable/bookmarkable.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const input = document.getElementById('searchInput');
|
||||
const chipsEl = document.getElementById('typeChips');
|
||||
const resultsEl = document.getElementById('results');
|
||||
const countEl = document.getElementById('searchCount');
|
||||
|
||||
const state = { type: 'all', results: [] };
|
||||
|
||||
function render() {
|
||||
resultsEl.replaceChildren();
|
||||
const filtered = state.type === 'all' ? state.results : state.results.filter((i) => i.type === state.type);
|
||||
if (!state.results.length) {
|
||||
countEl.textContent = '';
|
||||
resultsEl.appendChild(
|
||||
SR.cards.emptyState('Nothing found', 'Check the spelling or try a different name.')
|
||||
);
|
||||
return;
|
||||
}
|
||||
countEl.textContent = `${filtered.length} of ${state.results.length} result${state.results.length === 1 ? '' : 's'}`;
|
||||
if (!filtered.length) {
|
||||
resultsEl.appendChild(SR.cards.emptyState('No matches for this filter', 'Try the All filter, or a different search.'));
|
||||
return;
|
||||
}
|
||||
resultsEl.appendChild(SR.cards.grid(filtered));
|
||||
}
|
||||
|
||||
async function runSearch(q) {
|
||||
q = (q || '').trim();
|
||||
if (!q) {
|
||||
state.results = [];
|
||||
countEl.textContent = '';
|
||||
resultsEl.replaceChildren(SR.cards.emptyState('Search the catalog', 'Type a movie or show name above.'));
|
||||
return;
|
||||
}
|
||||
countEl.textContent = 'Searching…';
|
||||
try {
|
||||
const data = await SR.api.search(q);
|
||||
state.results = data.results.map(SR.cards.normalizeItem);
|
||||
render();
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'search failed');
|
||||
countEl.textContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
const LABELS = { all: 'All', movie: 'Movies', tv: 'TV' };
|
||||
for (const t of ['all', 'movie', 'tv']) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = t === 'all' ? 'chip chip--active' : 'chip';
|
||||
b.textContent = LABELS[t];
|
||||
b.addEventListener('click', () => {
|
||||
state.type = t;
|
||||
for (const c of chipsEl.querySelectorAll('.chip')) c.classList.remove('chip--active');
|
||||
b.classList.add('chip--active');
|
||||
render();
|
||||
});
|
||||
chipsEl.appendChild(b);
|
||||
}
|
||||
|
||||
input.addEventListener(
|
||||
'input',
|
||||
SR.util.debounce(() => {
|
||||
const q = input.value.trim();
|
||||
history.replaceState(null, '', q ? `?q=${encodeURIComponent(q)}` : 'search.html');
|
||||
runSearch(q);
|
||||
}, 450)
|
||||
);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
runSearch(input.value.trim());
|
||||
}
|
||||
});
|
||||
|
||||
const initialQ = SR.util.getParam('q') || '';
|
||||
input.value = initialQ;
|
||||
if (initialQ) runSearch(initialQ);
|
||||
else input.focus();
|
||||
})();
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
STORAGE — resume points, kept in localStorage (survives restarts, no size
|
||||
worries like cookies, no per-request overhead).
|
||||
|
||||
A "record" looks like:
|
||||
{
|
||||
key: "m:603" | "t:1396:s1:e2",
|
||||
type: "movie" | "tv",
|
||||
tmdbId: 1396,
|
||||
season: 1, // tv only
|
||||
episode: 2, // tv only
|
||||
show: "Show name",
|
||||
title: "Episode name", // tv only
|
||||
poster: "https://…/w342/…",
|
||||
t: 934.2, // seconds played
|
||||
d: 2710.5, // duration seconds
|
||||
at: 1712345678901,
|
||||
provider: "cineby"
|
||||
}
|
||||
|
||||
One record per (movie) or (show, season, episode). The home page collapses
|
||||
to the most recent record per show.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const KEY = 'streamreverse.resume.v1';
|
||||
const MAX_RECORDS = 200;
|
||||
|
||||
function readAll() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(KEY) || '{}');
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeAll(all) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(all));
|
||||
} catch (e) {
|
||||
/* storage full/blocked — resume just won't persist */
|
||||
}
|
||||
}
|
||||
|
||||
function keyFor({ type, tmdbId, season, episode }) {
|
||||
return type === 'tv' ? `t:${tmdbId}:s${season}:e${episode}` : `m:${tmdbId}`;
|
||||
}
|
||||
|
||||
function get(key) {
|
||||
return readAll()[key] || null;
|
||||
}
|
||||
|
||||
function save(record) {
|
||||
const all = readAll();
|
||||
all[record.key] = record;
|
||||
const keys = Object.keys(all).sort((a, b) => (all[a].at || 0) - (all[b].at || 0));
|
||||
while (keys.length > MAX_RECORDS) delete all[keys.shift()];
|
||||
writeAll(all);
|
||||
}
|
||||
|
||||
function remove(key) {
|
||||
const all = readAll();
|
||||
if (all[key]) {
|
||||
delete all[key];
|
||||
writeAll(all);
|
||||
}
|
||||
}
|
||||
|
||||
function list() {
|
||||
return Object.values(readAll());
|
||||
}
|
||||
|
||||
// one entry per movie/show: the most recently watched record wins
|
||||
function latestPerShow() {
|
||||
const byShow = new Map();
|
||||
for (const rec of list().sort((a, b) => (a.at || 0) - (b.at || 0))) {
|
||||
const showKey = rec.type === 'tv' ? `t:${rec.tmdbId}` : `m:${rec.tmdbId}`;
|
||||
byShow.set(showKey, rec);
|
||||
}
|
||||
return [...byShow.values()].sort((a, b) => (b.at || 0) - (a.at || 0));
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.storage = { KEY, keyFor, get, save, remove, list, latestPerShow };
|
||||
})();
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
UTIL — small shared helpers. No dependencies.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? '' : value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function getParam(name) {
|
||||
return new URLSearchParams(location.search).get(name);
|
||||
}
|
||||
|
||||
// 95 -> "1:35", 3675 -> "1:01:15"
|
||||
function formatSeconds(sec) {
|
||||
sec = Math.max(0, Math.floor(sec || 0));
|
||||
const h = Math.floor(sec / 3600);
|
||||
const m = Math.floor((sec % 3600) / 60);
|
||||
const s = sec % 60;
|
||||
const mm = h ? String(m).padStart(2, '0') : String(m);
|
||||
const ss = String(s).padStart(2, '0');
|
||||
return h ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
|
||||
}
|
||||
|
||||
// 141 -> "2h 21m"
|
||||
function runtimeLabel(mins) {
|
||||
if (!mins || mins <= 0) return '';
|
||||
const h = Math.floor(mins / 60);
|
||||
const m = mins % 60;
|
||||
return h ? (m ? `${h}h ${m}m` : `${h}h`) : `${m}m`;
|
||||
}
|
||||
|
||||
function debounce(fn, wait) {
|
||||
let timer = null;
|
||||
return function (...args) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn.apply(this, args), wait);
|
||||
};
|
||||
}
|
||||
|
||||
// resize a full TMDB image URL (…/t/p/<size>/path) to another size
|
||||
function tmdbResize(url, size) {
|
||||
if (!url) return '';
|
||||
return url.replace(/\/t\/p\/[A-Za-z0-9._-]+/, `/t/p/${size}`);
|
||||
}
|
||||
|
||||
window.SR = window.SR || {};
|
||||
SR.util = { escapeHtml, getParam, formatSeconds, runtimeLabel, debounce, tmdbResize };
|
||||
})();
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
/*
|
||||
WATCH — hero, player, source list (switch mid-watch), episodes.
|
||||
|
||||
URL params: ?id=<tmdb id>&type=<movie|tv>
|
||||
TV adds &s=<season>&e=<episode> as playback progresses.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const params = new URLSearchParams(location.search);
|
||||
const id = (params.get('id') || '').trim();
|
||||
const type = params.get('type') === 'tv' ? 'tv' : 'movie';
|
||||
|
||||
SR.app.initChrome();
|
||||
|
||||
const content = document.getElementById('content');
|
||||
if (!id || !/^\d+$/.test(id)) {
|
||||
content.replaceChildren(SR.cards.emptyState('Missing ?id=', 'This page needs a TMDB id, e.g. watch.html?id=1396&type=tv'));
|
||||
return;
|
||||
}
|
||||
|
||||
const video = document.getElementById('video');
|
||||
const statusEl = document.getElementById('playerStatus');
|
||||
const sourceLabel = document.getElementById('sourceLabel');
|
||||
const resumeNote = document.getElementById('resumeNote');
|
||||
const sourcesPanel = document.getElementById('sourcesPanel');
|
||||
const changeSourceBtn = document.getElementById('changeSourceBtn');
|
||||
const episodeSection = document.getElementById('episodes');
|
||||
const seasonSelect = document.getElementById('seasonSelect');
|
||||
const episodeGrid = document.getElementById('episodeGrid');
|
||||
const prevBtn = document.getElementById('prevEpisode');
|
||||
const nextBtn = document.getElementById('nextEpisode');
|
||||
|
||||
const state = {
|
||||
details: null,
|
||||
seasons: [],
|
||||
episodes: [],
|
||||
streams: [],
|
||||
sourceIndex: -1,
|
||||
season: null,
|
||||
episode: null,
|
||||
};
|
||||
|
||||
/* ---- status overlay ------------------------------------------------------ */
|
||||
|
||||
function showStatus(msg, isError) {
|
||||
statusEl.hidden = false;
|
||||
statusEl.innerHTML = isError
|
||||
? `<h3>Playback problem</h3><p>${SR.util.escapeHtml(msg)}</p>`
|
||||
: `<div class="spinner"></div><p>${SR.util.escapeHtml(msg)}</p>`;
|
||||
}
|
||||
|
||||
function hideStatus() {
|
||||
statusEl.hidden = true;
|
||||
}
|
||||
|
||||
/* ---- player --------------------------------------------------------------- */
|
||||
|
||||
const player = SR.player.create(video, {
|
||||
onStatus: (msg) => showStatus(msg),
|
||||
onReady: (resumeAt) => {
|
||||
hideStatus();
|
||||
if (resumeAt > 10) resumeNote.textContent = `Resuming at ${SR.util.formatSeconds(resumeAt)}`;
|
||||
},
|
||||
onError: (msg) => {
|
||||
showStatus(msg, true);
|
||||
SR.app.toast(msg, true);
|
||||
},
|
||||
});
|
||||
|
||||
/* ---- hero ------------------------------------------------------------------ */
|
||||
|
||||
function renderHero(d) {
|
||||
document.title = `${d.name || d.title} — bug.tv`;
|
||||
const isTv = type === 'tv';
|
||||
const year = String((isTv ? d.first_air_date : d.release_date) || '').slice(0, 4);
|
||||
const facts = [
|
||||
isTv ? `${d.number_of_seasons || 0} seasons` : SR.util.runtimeLabel(d.runtime),
|
||||
year,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.map(SR.util.escapeHtml)
|
||||
.join('<span>·</span>');
|
||||
const rating = d.vote_average
|
||||
? `<span class="watch-hero__rating">★ ${Number(d.vote_average).toFixed(1)}</span>`
|
||||
: '';
|
||||
const genres = (d.genres || [])
|
||||
.map((g) => `<span class="tag">${SR.util.escapeHtml(g.name)}</span>`)
|
||||
.join('');
|
||||
const poster = SR.util.tmdbResize(d.poster_url, 'w500');
|
||||
const backdrop = SR.util.tmdbResize(d.backdrop_url, 'w1280');
|
||||
document.getElementById('hero').innerHTML = `
|
||||
${backdrop ? `<div class="watch-hero__backdrop"><img src="${backdrop}" alt=""></div>` : ''}
|
||||
${poster ? `<div class="watch-hero__poster"><img src="${poster}" alt=""></div>` : ''}
|
||||
<div class="watch-hero__body">
|
||||
<h1 class="watch-hero__title">${SR.util.escapeHtml(d.name || d.title)}</h1>
|
||||
<div class="watch-hero__facts">${rating}${rating && facts ? '<span>·</span>' : ''}${facts}</div>
|
||||
${genres ? `<div class="watch-hero__genres">${genres}</div>` : ''}
|
||||
${d.overview ? `<p class="watch-hero__overview">${SR.util.escapeHtml(d.overview)}</p>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/* ---- url -------------------------------------------------------------------- */
|
||||
|
||||
function syncUrl() {
|
||||
const p = new URLSearchParams();
|
||||
p.set('id', id);
|
||||
p.set('type', type);
|
||||
if (type === 'tv') {
|
||||
if (state.season != null) p.set('s', state.season);
|
||||
if (state.episode != null) p.set('e', state.episode);
|
||||
}
|
||||
history.replaceState(null, '', `?${p.toString()}`);
|
||||
}
|
||||
|
||||
/* ---- streams ------------------------------------------------------------------ */
|
||||
|
||||
function keyFor() {
|
||||
return SR.storage.keyFor({ type, tmdbId: Number(id), season: state.season, episode: state.episode });
|
||||
}
|
||||
|
||||
async function loadStreams() {
|
||||
const query = { tmdb: id, type };
|
||||
if (type === 'tv') {
|
||||
if (state.season == null || state.episode == null) return;
|
||||
query.season = state.season;
|
||||
query.episode = state.episode;
|
||||
}
|
||||
sourcesPanel.hidden = true;
|
||||
changeSourceBtn.textContent = 'Change source';
|
||||
showStatus('Finding streams…');
|
||||
sourceLabel.textContent = '';
|
||||
resumeNote.textContent = '';
|
||||
try {
|
||||
const data = await SR.api.streams(query);
|
||||
state.streams = data.streams || [];
|
||||
renderSources();
|
||||
changeSourceBtn.hidden = state.streams.length === 0;
|
||||
if (state.streams.length) playSource(0);
|
||||
else showStatus('No streams found for this title.', true);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'stream lookup failed');
|
||||
showStatus('Stream lookup failed.', true);
|
||||
}
|
||||
}
|
||||
|
||||
function renderSources() {
|
||||
const list = document.getElementById('sourceList');
|
||||
list.replaceChildren();
|
||||
state.streams.forEach((s, i) => {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = i === state.sourceIndex ? 'source-item source-item--active' : 'source-item';
|
||||
const meta = [s.provider, s.quality, s.audio].filter(Boolean).join(' · ');
|
||||
b.innerHTML = `
|
||||
<span class="source-item__rank">${i + 1}</span>
|
||||
<span class="source-item__name">${SR.util.escapeHtml(s.name)}</span>
|
||||
<span class="source-item__meta">${SR.util.escapeHtml(meta)}</span>`;
|
||||
b.addEventListener('click', () => playSource(i));
|
||||
list.appendChild(b);
|
||||
});
|
||||
document.getElementById('sourcesCount').textContent =
|
||||
`${state.streams.length} source${state.streams.length === 1 ? '' : 's'}`;
|
||||
}
|
||||
|
||||
function playSource(i) {
|
||||
const s = state.streams[i];
|
||||
if (!s) return;
|
||||
state.sourceIndex = i;
|
||||
renderSources();
|
||||
sourceLabel.textContent = `${s.name} — ${[s.quality, s.provider].filter(Boolean).join(', ')}`;
|
||||
const rec = SR.storage.get(keyFor());
|
||||
player.load(s, { resumeAt: rec && rec.t > 10 ? rec.t : null });
|
||||
}
|
||||
|
||||
changeSourceBtn.addEventListener('click', () => {
|
||||
sourcesPanel.hidden = !sourcesPanel;
|
||||
changeSourceBtn.textContent = sourcesPanel.hidden ? 'Change source' : 'Hide sources';
|
||||
});
|
||||
|
||||
/* ---- resume persistence ---------------------------------------------------------- */
|
||||
|
||||
let lastPersist = 0;
|
||||
|
||||
function persistProgress(force) {
|
||||
const d = video.duration;
|
||||
if (!d || !isFinite(d)) return;
|
||||
const t = video.currentTime;
|
||||
if (t < 10) return;
|
||||
const key = keyFor();
|
||||
if (t >= d - 15 || t / d >= 0.95) {
|
||||
SR.storage.remove(key);
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (!force && now - lastPersist < 3000) return;
|
||||
lastPersist = now;
|
||||
const ep = state.episodes.find((e) => e.episode_number === state.episode);
|
||||
SR.storage.save({
|
||||
key,
|
||||
type,
|
||||
tmdbId: Number(id),
|
||||
season: state.season,
|
||||
episode: state.episode,
|
||||
show: state.details ? state.details.name || state.details.title : '',
|
||||
title: ep ? ep.name || '' : '',
|
||||
poster: state.details ? SR.util.tmdbResize(state.details.poster_url, 'w342') : '',
|
||||
t,
|
||||
d,
|
||||
at: now,
|
||||
provider: state.streams[state.sourceIndex] ? state.streams[state.sourceIndex].provider : '',
|
||||
});
|
||||
}
|
||||
|
||||
video.addEventListener('timeupdate', () => persistProgress(false));
|
||||
video.addEventListener('pause', () => persistProgress(true));
|
||||
video.addEventListener('seeked', () => persistProgress(true));
|
||||
video.addEventListener('ended', () => SR.storage.remove(keyFor()));
|
||||
window.addEventListener('pagehide', () => persistProgress(true));
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden) persistProgress(true);
|
||||
});
|
||||
|
||||
/* ---- episodes ------------------------------------------------------------------------ */
|
||||
|
||||
async function loadSeasons() {
|
||||
const data = await SR.api.seasons(id);
|
||||
state.seasons = data.seasons || [];
|
||||
for (const s of state.seasons) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = s.season_number;
|
||||
opt.textContent = `${s.name} (${s.episode_count})`;
|
||||
seasonSelect.appendChild(opt);
|
||||
}
|
||||
}
|
||||
|
||||
function showGridSpinner() {
|
||||
episodeGrid.replaceChildren();
|
||||
const cell = document.createElement('div');
|
||||
cell.className = 'loading-cell';
|
||||
cell.innerHTML = '<div class="spinner"></div>';
|
||||
episodeGrid.appendChild(cell);
|
||||
}
|
||||
|
||||
function renderEpisodes() {
|
||||
episodeGrid.replaceChildren();
|
||||
if (!state.episodes.length) {
|
||||
const empty = SR.cards.emptyState('No episodes listed');
|
||||
empty.style.gridColumn = '1 / -1';
|
||||
episodeGrid.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
for (const ep of state.episodes) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = ep.episode_number === state.episode ? 'episode episode--current' : 'episode';
|
||||
const date = ep.air_date ? ` · ${SR.util.escapeHtml(ep.air_date)}` : '';
|
||||
b.innerHTML = `
|
||||
<span class="episode__thumb"><span class="episode__play">▶</span></span>
|
||||
<span class="episode__body">
|
||||
<span class="episode__num">S${state.season} · E${ep.episode_number}${date}</span>
|
||||
<span class="episode__title">${SR.util.escapeHtml(ep.name || `Episode ${ep.episode_number}`)}</span>
|
||||
</span>`;
|
||||
b.addEventListener('click', () => playEpisode(ep.episode_number));
|
||||
episodeGrid.appendChild(b);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEpisodes(season, autoplayEpisode) {
|
||||
state.season = season;
|
||||
seasonSelect.value = String(season);
|
||||
showGridSpinner();
|
||||
const data = await SR.api.episodes(id, season);
|
||||
state.episodes = data.episodes || [];
|
||||
renderEpisodes();
|
||||
syncUrl();
|
||||
if (autoplayEpisode && state.episodes.some((e) => e.episode_number === autoplayEpisode)) {
|
||||
playEpisode(autoplayEpisode);
|
||||
}
|
||||
}
|
||||
|
||||
function playEpisode(n) {
|
||||
state.episode = n;
|
||||
syncUrl();
|
||||
renderEpisodes();
|
||||
loadStreams();
|
||||
document.getElementById('playerSection').scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
|
||||
seasonSelect.addEventListener('change', async () => {
|
||||
const season = parseInt(seasonSelect.value, 10);
|
||||
if (!season) return;
|
||||
try {
|
||||
await loadEpisodes(season);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load episodes');
|
||||
}
|
||||
});
|
||||
|
||||
async function stepEpisode(delta) {
|
||||
if (type !== 'tv') return;
|
||||
const idx = state.episodes.findIndex((e) => e.episode_number === state.episode);
|
||||
if (idx >= 0 && idx + delta >= 0 && idx + delta < state.episodes.length) {
|
||||
playEpisode(state.episodes[idx + delta].episode_number);
|
||||
return;
|
||||
}
|
||||
const sIdx = state.seasons.findIndex((s) => s.season_number === state.season);
|
||||
if (sIdx < 0 || sIdx + delta < 0 || sIdx + delta >= state.seasons.length) return;
|
||||
try {
|
||||
await loadEpisodes(state.seasons[sIdx + delta].season_number);
|
||||
const first = state.episodes[0];
|
||||
if (first) playEpisode(first.episode_number);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load episodes');
|
||||
}
|
||||
}
|
||||
|
||||
prevBtn.addEventListener('click', () => stepEpisode(-1));
|
||||
nextBtn.addEventListener('click', () => stepEpisode(1));
|
||||
|
||||
/* ---- init ------------------------------------------------------------------------------ */
|
||||
|
||||
(async function init() {
|
||||
let details;
|
||||
try {
|
||||
details = await SR.api.details(type, id);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load this title');
|
||||
showStatus('Could not load this title.', true);
|
||||
return;
|
||||
}
|
||||
state.details = details;
|
||||
renderHero(details);
|
||||
|
||||
if (type !== 'tv') {
|
||||
loadStreams();
|
||||
return;
|
||||
}
|
||||
|
||||
episodeSection.hidden = false;
|
||||
showStatus('Pick an episode to start.');
|
||||
|
||||
try {
|
||||
await loadSeasons();
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load seasons');
|
||||
return;
|
||||
}
|
||||
if (!state.seasons.length) {
|
||||
showStatus('No seasons found for this show.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const sParam = parseInt(params.get('s'), 10);
|
||||
const eParam = parseInt(params.get('e'), 10);
|
||||
const season = state.seasons.some((s) => s.season_number === sParam)
|
||||
? sParam
|
||||
: state.seasons[0].season_number;
|
||||
try {
|
||||
await loadEpisodes(season, eParam || null);
|
||||
} catch (e) {
|
||||
SR.app.showError(e, 'failed to load episodes');
|
||||
showStatus('Failed to load episodes.', true);
|
||||
}
|
||||
})();
|
||||
})();
|
||||
Reference in New Issue
Block a user