initial commit for test

This commit is contained in:
seanland committed 2026-11-24 13:22:37 -05:00
commit 8d256d259d
56 files changed
+2355

No files matched your search

+830
View File
@@ -0,0 +1,830 @@
const app = document.getElementById('app');
const toastEl = document.getElementById('toast');
const searchInput = document.getElementById('search-input');
const body = document.body;
let toastTimer = null;
let currentUser = null;
let currentRoute = 'home';
let autoplayMode = localStorage.getItem('vidhive_autoplay') || 'off';
function setAutoplayMode(m) { autoplayMode = m; localStorage.setItem('vidhive_autoplay', m); }
let autoplayIntent = false;
const THEME_ORDER = ['dark', 'light', 'classic'];
const THEME_ICONS = { dark: '🌙', light: '☀️', classic: '🖥' };
const themeBtn = document.getElementById('theme-toggle');
function applyTheme(t) {
document.documentElement.setAttribute('data-theme', t);
if (themeBtn) {
themeBtn.textContent = THEME_ICONS[t] || '🌙';
const next = THEME_ORDER[(THEME_ORDER.indexOf(t) + 1) % THEME_ORDER.length];
themeBtn.title = `Theme: ${t} — click for ${next}`;
}
}
function initTheme() {
const stored = localStorage.getItem('vidhive_theme');
const prefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
applyTheme(stored || (prefersLight ? 'light' : 'dark'));
}
if (themeBtn) themeBtn.addEventListener('click', () => {
const current = document.documentElement.getAttribute('data-theme') || 'dark';
const next = THEME_ORDER[(THEME_ORDER.indexOf(current) + 1) % THEME_ORDER.length];
localStorage.setItem('vidhive_theme', next);
applyTheme(next);
});
initTheme();
const state = {
q: '',
channel: null,
sort: 'newest',
offset: 0,
limit: 24,
total: 0,
};
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
function fmtDur(sec) {
if (!sec || !isFinite(sec)) return '0:00';
sec = Math.floor(sec);
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
return `${m}:${String(s).padStart(2, '0')}`;
}
function fmtTime(sec) {
sec = Math.floor(sec || 0);
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60);
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m} min`;
return `${sec}s`;
}
function fmtDate(ts) {
if (!ts) return '';
const d = new Date(ts * 1000);
const diff = (Date.now() - d.getTime()) / 1000;
if (diff < 60) return 'just now';
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
if (diff < 2592000) return `${Math.floor(diff / 86400)}d ago`;
return d.toLocaleDateString();
}
function fmtViews(n) {
if (!n) return '0 views';
if (n < 1000) return `${n} views`;
if (n < 1e6) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k views`;
return `${(n / 1e6).toFixed(1)}M views`;
}
async function api(path, opts) {
const res = await fetch(path, opts);
if (res.status === 401) {
showLoginScreen();
throw new Error('Unauthorized');
}
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const j = await res.json(); if (j && j.error) msg = j.error; } catch {}
throw new Error(msg);
}
return res.json();
}
function toast(msg) {
toastEl.textContent = msg;
toastEl.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastEl.classList.remove('show'), 2600);
}
async function getMe() {
const r = await fetch('/api/auth/me');
if (!r.ok) return null;
try { const j = await r.json(); return j.user || null; } catch { return null; }
}
function showLoginScreen() {
currentUser = null;
body.classList.add('logged-out');
document.getElementById('app-header').style.display = 'none';
app.innerHTML = `
<div class="login-screen">
<form class="login-card" id="login-form">
<div class="logo" style="justify-content:center;margin-bottom:18px"><span class="mark">▶</span> Seantube</div>
<h1 id="login-title">Welcome back</h1>
<p class="login-sub" id="login-sub">Sign in to your account</p>
<div class="mode-toggle">
<button type="button" id="mode-login" class="active">Log in</button>
<button type="button" id="mode-register">Create account</button>
</div>
<input type="text" id="login-username" placeholder="Username" autocomplete="username" autocapitalize="none" spellcheck="false" required>
<input type="password" id="login-password" placeholder="Password" autocomplete="current-password" required>
<p class="login-error" id="login-error"></p>
<button type="submit" class="login-submit" id="login-submit">Log in</button>
</form>
</div>`;
let authMode = 'login';
const titleEl = document.getElementById('login-title');
const subEl = document.getElementById('login-sub');
const submitEl = document.getElementById('login-submit');
const errEl = document.getElementById('login-error');
const setMode = (mode) => {
authMode = mode;
document.getElementById('mode-login').classList.toggle('active', mode === 'login');
document.getElementById('mode-register').classList.toggle('active', mode === 'register');
if (mode === 'login') {
titleEl.textContent = 'Welcome back'; subEl.textContent = 'Sign in to your account'; submitEl.textContent = 'Log in';
document.getElementById('login-password').autocomplete = 'current-password';
} else {
titleEl.textContent = 'Create account'; subEl.textContent = 'Pick a username and password (min 6 characters)'; submitEl.textContent = 'Create account';
document.getElementById('login-password').autocomplete = 'new-password';
}
errEl.textContent = '';
};
document.getElementById('mode-login').addEventListener('click', () => setMode('login'));
document.getElementById('mode-register').addEventListener('click', () => setMode('register'));
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('login-username').value.trim();
const password = document.getElementById('login-password').value;
errEl.textContent = '';
submitEl.disabled = true;
try {
const res = await fetch(`/api/auth/${authMode === 'login' ? 'login' : 'register'}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) { errEl.textContent = data.error || 'Something went wrong'; submitEl.disabled = false; return; }
currentUser = data.user;
if (location.hash !== '#/') { location.hash = '#/'; return; }
render();
} catch (err) {
errEl.textContent = 'Network error — is the server running?';
submitEl.disabled = false;
}
});
}
async function showApp(user) {
currentUser = user;
body.classList.remove('logged-out');
document.getElementById('app-header').style.display = '';
const initial = esc((user.username || '?').charAt(0).toUpperCase());
document.getElementById('user-area').innerHTML = `
<span class="avatar">${initial}</span>
<span class="uname" title="${esc(user.username)}">${esc(user.username)}</span>
<button id="logout-btn" class="btn icon-btn" title="Log out">⏻</button>`;
document.getElementById('logout-btn').addEventListener('click', async () => {
try { await fetch('/api/auth/logout', { method: 'POST' }); } catch {}
currentUser = null;
render();
});
const status = await api('/api/status').catch(() => null);
if (status && status.lastRescanAt) {
document.getElementById('rescan-btn').title = `Rescan video folder (last: ${fmtDate(Math.floor(new Date(status.lastRescanAt).getTime() / 1000))})`;
}
}
function cardHtml(v) {
const dur = fmtDur(v.duration);
const progress = v.watched_position > 0 && v.duration > 0 ? Math.min(1, v.watched_position / v.duration) : 0;
const done = v.watch_completed || (progress >= 0.9);
return `
<div class="card" data-href="#/watch/${v.id}">
<div class="thumb">
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=placeholder>▶</div>'">
<button class="fav-btn ${v.favorite ? '' : 'off'}" data-video-id="${v.id}" title="Toggle favorite">${v.favorite ? '★' : '☆'}</button>
<span class="badge">${dur}</span>
<div class="play-overlay"><div class="circle">▶</div></div>
${progress > 0 ? `<div class="progress"><div class="fill${done ? ' done' : ''}" style="width:${(progress * 100).toFixed(1)}%"></div></div>` : ''}
</div>
<div class="title">${esc(v.title)}</div>
<div class="meta">${esc(v.channel)} · ${fmtViews(v.views)}</div>
</div>`;
}
async function loadGrid() {
let url, noun;
if (currentRoute === 'favorites') {
url = `/api/favorites?limit=${state.limit}&offset=${state.offset}`;
noun = 'videos';
} else {
const q = state.q ? `&q=${encodeURIComponent(state.q)}` : '';
const ch = state.channel ? `&channel=${encodeURIComponent(state.channel)}` : '';
url = `/api/videos?limit=${state.limit}&offset=${state.offset}&sort=${encodeURIComponent(state.sort)}${q}${ch}`;
noun = state.q ? 'results' : 'videos';
}
try {
const data = await api(url);
state.total = data.total;
const grid = document.getElementById('video-grid');
const empty = document.getElementById('empty-msg');
if (state.offset === 0) {
if (data.videos.length === 0) {
grid.innerHTML = '';
empty.style.display = 'block';
} else {
empty.style.display = 'none';
grid.innerHTML = data.videos.map(cardHtml).join('');
}
} else {
data.videos.forEach(v => grid.insertAdjacentHTML('beforeend', cardHtml(v)));
}
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.style.display = state.offset + data.videos.length < state.total ? 'block' : 'none';
}
const countEl = document.getElementById('result-count');
if (countEl) countEl.textContent = `${state.total} ${noun}`;
} catch (err) {
if (err.message !== 'Unauthorized') toast('Failed to load videos: ' + err.message);
}
}
function wireGridControls() {
const sortSelect = document.getElementById('sort-select');
if (sortSelect) {
sortSelect.value = state.sort;
sortSelect.addEventListener('change', () => { state.sort = sortSelect.value; state.offset = 0; loadGrid(); });
}
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.addEventListener('click', () => { state.offset += state.limit; loadGrid(); });
}
}
async function renderHome() {
currentRoute = 'home';
const channels = await api('/api/channels').catch(() => []);
const historyItems = await api('/api/history?limit=8').catch(() => []);
const continueWatching = historyItems.filter(h => !h.completed && h.position > 0 && (h.duration || h.watch_duration) > 0 && h.position < (h.duration || h.watch_duration) * 0.95).slice(0, 8);
app.innerHTML = `
${continueWatching.length ? `
<h2 class="section-title">Continue watching</h2>
<div class="continue-strip">
${continueWatching.map(v => {
const dur = v.duration || v.watch_duration || 0;
const p = dur > 0 ? Math.min(1, v.position / dur) : 0;
return `<div class="card continue-card" data-href="#/watch/${v.id}">
<div class="thumb">
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=placeholder>▶</div>'">
<span class="badge">${fmtDur(v.duration)}</span>
<div class="progress"><div class="fill" style="width:${(p * 100).toFixed(1)}%"></div></div>
</div>
<div class="title">${esc(v.title)}</div>
<div class="meta">${fmtDate(v.watched_at)} · ${Math.round(p * 100)}% watched</div>
</div>`;
}).join('')}
</div>` : ''}
<h2 class="section-title">${state.q ? 'Search results' : 'All videos'}</h2>
<div class="toolbar">
<span class="result-count" id="result-count"></span>
<select class="sort" id="sort-select">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
<option value="views">Most viewed</option>
<option value="recent">Recently watched</option>
<option value="az">Title A–Z</option>
</select>
</div>
<div class="chips" id="channel-chips">
<button class="chip ${!state.channel ? 'active' : ''}" data-channel="">All channels</button>
${channels.map(c => `<button class="chip ${state.channel === c.name ? 'active' : ''}" data-channel="${esc(c.name)}">${esc(c.name)} <span style="opacity:.55;font-weight:500">${c.count}</span></button>`).join('')}
</div>
<div class="grid" id="video-grid"></div>
<div class="empty" id="empty-msg" style="display:none">
<div class="big">🎬</div>
<p>${state.q ? 'No videos match your search.' : 'No videos found. Drop video files into the video folder and click ⟳ to rescan.'}</p>
</div>
<button class="load-more" id="load-more" style="display:none">Load more</button>`;
wireGridControls();
document.getElementById('channel-chips').addEventListener('click', (e) => {
const btn = e.target.closest('.chip');
if (!btn) return;
state.channel = btn.dataset.channel || null;
state.offset = 0;
renderHome();
});
await loadGrid();
}
async function renderChannel(name) {
currentRoute = 'channel';
const channels = await api('/api/channels').catch(() => []);
const channel = channels.find(c => c.name === name);
const stats = await api(`/api/channel/${encodeURIComponent(name)}/stats`).catch(() => null);
searchInput.value = '';
app.innerHTML = `
<div class="toolbar">
<h2 class="section-title" style="margin:0">${esc(name)}</h2>
<select class="sort" id="sort-select">
<option value="newest">Newest first</option>
<option value="oldest">Oldest first</option>
<option value="views">Most viewed</option>
<option value="recent">Recently watched</option>
<option value="az">Title A–Z</option>
</select>
</div>
${stats ? `<div class="channel-stats">
<span class="cs"><b>${stats.videos}</b> videos</span>
<span class="cs"><b>${fmtTime(stats.totalSeconds)}</b> total</span>
<span class="cs"><b>${fmtTime(stats.watchedSeconds)}</b> watched by you</span>
<span class="cs"><b>${stats.completedCount}</b> completed</span>
</div>` : ''}
<div class="grid" id="video-grid"></div>
<div class="empty" id="empty-msg" style="display:none">
<div class="big">📺</div><p>No videos in this channel yet.</p>
</div>
<button class="load-more" id="load-more" style="display:none">Load more</button>`;
state.channel = name;
state.q = '';
state.offset = 0;
wireGridControls();
await loadGrid();
}
async function renderFavorites() {
currentRoute = 'favorites';
searchInput.value = '';
app.innerHTML = `
<h2 class="section-title">Favorites <span class="count" id="result-count"></span></h2>
<div class="grid" id="video-grid"></div>
<div class="empty" id="empty-msg" style="display:none">
<div class="big">★</div><p>No favorites yet. Click the star on any video to add it here.</p>
</div>
<button class="load-more" id="load-more" style="display:none">Load more</button>`;
state.offset = 0;
wireGridControls();
await loadGrid();
}
async function renderHistory() {
currentRoute = 'history';
const items = await api('/api/history?limit=50').catch(() => []);
app.innerHTML = `
<h2 class="section-title">Watch history <span class="count">${items.length} videos</span></h2>
${items.length ? items.map(v => {
const p = v.duration > 0 ? Math.min(1, v.position / v.duration) : 0;
return `<a class="history-row" href="#/watch/${v.id}">
<div class="thumb">
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=placeholder>▶</div>'">
</div>
<div class="info">
<div class="title">${esc(v.title)}</div>
<div class="meta">${esc(v.channel)} · ${fmtDate(v.watched_at)}</div>
<div class="bar"><div class="fill${v.completed ? ' done' : ''}" style="width:${(p * 100).toFixed(1)}%"></div></div>
</div>
<div class="time">${v.completed ? '✓ Watched' : fmtDur(v.position) + ' / ' + fmtDur(v.duration || 0)}</div>
</a>`;
}).join('') : `<div class="empty"><div class="big">🕘</div><p>Nothing watched yet. Play something and it will show up here.</p></div>`}`;
}
async function renderPlaylists() {
currentRoute = 'playlists';
searchInput.value = '';
const playlists = await api('/api/playlists').catch(() => []);
app.innerHTML = `
<h2 class="section-title">Playlists <span class="count">${playlists.length}</span></h2>
<form class="new-playlist-bar" id="new-playlist-form">
<input id="new-playlist-name" type="text" placeholder="New playlist name…" maxlength="80" required>
<button class="btn primary" type="submit">Create</button>
</form>
<div class="grid" id="playlist-grid" style="grid-template-columns:repeat(auto-fill,minmax(240px,1fr))">
${playlists.map(p => `<div class="playlist-card" data-href="#/playlists/${p.id}">
<button class="del-btn" data-delete-playlist="${p.id}" title="Delete playlist">✕</button>
<div class="name">${esc(p.name)}</div>
<div class="meta">${p.count} video${p.count === 1 ? '' : 's'} · ${fmtDate(p.created_at)}</div>
</div>`).join('') || `<div class="empty" style="grid-column:1/-1;padding:44px"><div class="big">📋</div><p>No playlists yet. Create one above, then add videos from the watch page.</p></div>`}
</div>`;
document.getElementById('new-playlist-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('new-playlist-name').value.trim();
if (!name) return;
try {
await api('/api/playlists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
toast(`Created "${name}"`);
renderPlaylists();
} catch (err) { toast(err.message); }
});
app.querySelectorAll('[data-delete-playlist]').forEach(btn => btn.addEventListener('click', async (e) => {
e.stopPropagation();
if (!confirm('Delete this playlist? Videos are not deleted.')) return;
try {
await api(`/api/playlists/${btn.dataset.deletePlaylist}`, { method: 'DELETE' });
renderPlaylists();
} catch (err) { toast(err.message); }
}));
}
async function renderPlaylistDetail(id) {
currentRoute = 'playlists';
const data = await api(`/api/playlists/${id}`).catch(() => null);
if (!data) {
app.innerHTML = `<div class="empty"><div class="big">🚫</div><p>Playlist not found.</p></div>`;
return;
}
const { playlist, videos } = data;
app.innerHTML = `
<a href="#/playlists" style="color:var(--muted);text-decoration:none;font-size:13px">← All playlists</a>
<h2 class="section-title" style="margin-top:10px">${esc(playlist.name)} <span class="count">${videos.length} videos</span></h2>
${videos.length ? videos.map((v, i) => `<div class="pl-row" data-id="${v.id}">
<span class="num">${i + 1}</span>
<img src="/thumb/${v.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=ph>▶</div>'">
<div class="body" data-href="#/watch/${v.id}">
<div class="t">${esc(v.title)}</div>
<div class="m">${fmtDur(v.duration)} · ${fmtViews(v.views)}</div>
</div>
<div class="actions">
<button data-move="up" title="Move up" ${i === 0 ? 'disabled' : ''}>↑</button>
<button data-move="down" title="Move down" ${i === videos.length - 1 ? 'disabled' : ''}>↓</button>
<button data-remove title="Remove from playlist">✕</button>
</div>
</div>`).join('') : `<div class="empty"><div class="big">📋</div><p>This playlist is empty. Add videos from the watch page.</p></div>`}`;
const ids = videos.map(v => v.id);
app.querySelectorAll('.pl-row').forEach(row => {
const rowId = parseInt(row.dataset.id, 10);
const upBtn = row.querySelector('[data-move="up"]');
const downBtn = row.querySelector('[data-move="down"]');
const removeBtn = row.querySelector('[data-remove]');
const idx = ids.indexOf(rowId);
const move = (dir) => {
const j = idx + dir;
if (j < 0 || j >= ids.length) return;
[ids[idx], ids[j]] = [ids[j], ids[idx]];
api(`/api/playlists/${id}/reorder`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_ids: ids }) })
.then(() => renderPlaylistDetail(id))
.catch(err => toast(err.message));
};
if (upBtn) upBtn.addEventListener('click', () => move(-1));
if (downBtn) downBtn.addEventListener('click', () => move(1));
if (removeBtn) removeBtn.addEventListener('click', async () => {
try {
await api(`/api/playlists/${id}/items/${rowId}`, { method: 'DELETE' });
renderPlaylistDetail(id);
} catch (err) { toast(err.message); }
});
});
}
async function renderStats() {
currentRoute = 'stats';
searchInput.value = '';
const s = await api('/api/stats').catch(() => null);
if (!s) {
app.innerHTML = `<div class="empty"><div class="big">📊</div><p>Unable to load stats.</p></div>`;
return;
}
const maxSec = Math.max(1, ...s.daily.map(d => d.seconds));
const days = [];
for (let i = 13; i >= 0; i--) {
const d = new Date(Date.now() - i * 86400000);
days.push({ key: d.toISOString().slice(0, 10), label: d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }), seconds: 0 });
}
const byDay = {};
s.daily.forEach(d => { byDay[d.day] = d.seconds; });
days.forEach(d => { d.seconds = byDay[d.key] || 0; });
const maxSecAll = Math.max(1, ...s.topChannels.map(c => c.seconds));
const maxVideosSec = Math.max(1, ...s.topVideos.map(v => v.seconds));
app.innerHTML = `
<h2 class="section-title">Watch stats</h2>
<div class="stats-grid">
<div class="stat-card"><div class="num">${fmtTime(s.totalSeconds)}</div><div class="lbl">Total watch time</div></div>
<div class="stat-card"><div class="num">${fmtTime(s.thisMonthSeconds)}</div><div class="lbl">This month</div></div>
<div class="stat-card"><div class="num">${s.startedCount}</div><div class="lbl">Videos started</div></div>
<div class="stat-card"><div class="num">${s.completedCount}</div><div class="lbl">Completed</div></div>
</div>
<div class="chart-wrap">
<h3>Last 14 days</h3>
<div class="chart-bars">
${days.map(d => `<div class="chart-bar" title="${d.key}: ${fmtTime(d.seconds)}">
<div class="fill" style="height:${Math.max(3, Math.round((d.seconds / maxSec) * 105))}px"></div>
<div class="day">${d.label}</div>
</div>`).join('')}
</div>
</div>
<div class="stats-cols">
<div class="stats-list">
<h3>Top channels</h3>
${s.topChannels.length ? s.topChannels.map((c, i) => `<div class="stats-item">
<span class="rank">${i + 1}</span>
<div class="body">
<div class="t">${esc(c.channel)}</div>
<div class="m">${c.videos} videos</div>
<div class="bar"><div class="fill" style="width:${((c.seconds / maxSecAll) * 100).toFixed(1)}%"></div></div>
</div>
<span class="secs">${fmtTime(c.seconds)}</span>
</div>`).join('') : '<p style="color:var(--muted);font-size:13px">No watch time yet.</p>'}
</div>
<div class="stats-list">
<h3>Top videos</h3>
${s.topVideos.length ? s.topVideos.map((v, i) => `<a class="stats-item" href="#/watch/${v.id}" style="text-decoration:none;color:inherit">
<span class="rank">${i + 1}</span>
<div class="body">
<div class="t">${esc(v.title)}</div>
<div class="m">${esc(v.channel)}</div>
<div class="bar"><div class="fill" style="width:${((v.seconds / maxVideosSec) * 100).toFixed(1)}%"></div></div>
</div>
<span class="secs">${fmtTime(v.seconds)}</span>
</a>`).join('') : '<p style="color:var(--muted);font-size:13px">No watch time yet.</p>'}
</div>
</div>`;
}
let playerCleanup = null;
async function renderWatch(id) {
currentRoute = 'watch';
const shouldAutoplay = autoplayIntent;
autoplayIntent = false;
const data = await api(`/api/video/${id}`).catch(() => null);
if (!data) {
app.innerHTML = `<div class="empty"><div class="big">🚫</div><p>Video not found or no longer in the library.</p></div>`;
return;
}
const v = data.video;
const history = data.history;
const fav = !!data.favorite;
app.innerHTML = `
<a href="#/" style="color:var(--muted);text-decoration:none;font-size:13px">← Back to library</a>
<div class="watch-layout">
<div>
<div class="player-wrap" id="player-wrap">
<video id="player" controls preload="metadata" src="/video/${v.id}"></video>
</div>
<h1 class="watch-title">${esc(v.title)}</h1>
<div class="watch-meta">
<a href="#/channel/${encodeURIComponent(v.channel)}">${esc(v.channel)}</a>
<span>${fmtViews(v.views)}</span>
<span>${fmtDur(v.duration)}</span>
</div>
<div class="watch-actions">
<button class="btn primary" id="fav-btn">${fav ? '★ Favorited' : '☆ Add to favorites'}</button>
<div class="seg" id="autoplay-seg" title="Autoplay next video">
<button data-mode="off" class="${autoplayMode === 'off' ? 'active' : ''}">Off</button>
<button data-mode="channel" class="${autoplayMode === 'channel' ? 'active' : ''}">Channel</button>
<button data-mode="random" class="${autoplayMode === 'random' ? 'active' : ''}">Random</button>
</div>
<button class="btn ghost" id="playlist-btn">+ Playlist</button>
</div>
<div class="add-playlist-panel" id="playlist-panel" style="display:none"></div>
</div>
<aside class="related">
<h3>More from ${esc(v.channel)}</h3>
<div id="related-list"></div>
</aside>
</div>`;
try { api('/api/view', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id }) }); } catch {}
const player = document.getElementById('player');
const wrap = document.getElementById('player-wrap');
let resumeAt = 0;
if (history && history.position > 5 && !history.completed && v.duration > 0 && history.position < v.duration * 0.95) {
resumeAt = history.position;
}
let lastSave = -1;
const saveProgress = (force = false) => {
if (!player.duration || !isFinite(player.duration)) return;
const pos = player.currentTime;
if (!force && Math.abs(pos - lastSave) < 1 && lastSave >= 0) return;
lastSave = pos;
api('/api/progress', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id, position: pos, duration: player.duration }) }).catch(() => {});
};
const onLoaded = () => {
if (resumeAt > 0 && !player.dataset.resumed) {
player.currentTime = resumeAt;
player.dataset.resumed = '1';
}
if (shouldAutoplay) {
player.play().catch(() => {});
}
};
player.addEventListener('loadedmetadata', onLoaded);
const interval = setInterval(saveProgress, 10000);
const onPause = () => saveProgress(true);
const startNext = async () => {
if (autoplayMode === 'off') return;
try {
const r = await api(`/api/videos/${v.id}/next?mode=${autoplayMode}`);
if (!r.video) return;
autoplayIntent = true;
location.hash = `#/watch/${r.video.id}`;
} catch {}
};
const onEnded = () => {
saveProgress(true);
api('/api/progress', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id, position: player.duration, duration: player.duration }) }).catch(() => {});
startNext();
};
const onError = () => {
wrap.innerHTML = '<div class="player-error"><p>⚠ Unable to play this video. The file may be missing or unsupported.</p></div>';
};
player.addEventListener('pause', onPause);
player.addEventListener('ended', onEnded);
player.addEventListener('error', onError);
document.getElementById('autoplay-seg').addEventListener('click', (e) => {
const btn = e.target.closest('button[data-mode]');
if (!btn) return;
setAutoplayMode(btn.dataset.mode);
document.querySelectorAll('#autoplay-seg button').forEach(b => b.classList.toggle('active', b === btn));
});
const favBtn = document.getElementById('fav-btn');
favBtn.addEventListener('click', async () => {
try {
const r = await api('/api/favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: v.id }) });
favBtn.textContent = r.favorite ? '★ Favorited' : '☆ Add to favorites';
toast(r.favorite ? 'Added to favorites' : 'Removed from favorites');
} catch (err) { if (err.message !== 'Unauthorized') toast('Error: ' + err.message); }
});
const panel = document.getElementById('playlist-panel');
const playlistBtn = document.getElementById('playlist-btn');
playlistBtn.addEventListener('click', async () => {
if (panel.style.display === 'none') {
panel.style.display = 'block';
await renderPlaylistPanel(panel, v.id);
} else {
panel.style.display = 'none';
}
});
playerCleanup = () => {
clearInterval(interval);
player.removeEventListener('loadedmetadata', onLoaded);
player.removeEventListener('pause', onPause);
player.removeEventListener('ended', onEnded);
player.removeEventListener('error', onError);
};
const related = await api(`/api/videos?channel=${encodeURIComponent(v.channel)}&sort=newest&limit=6`).catch(() => ({ videos: [] }));
const list = document.getElementById('related-list');
if (list) {
const others = related.videos.filter(x => x.id !== v.id).slice(0, 6);
list.innerHTML = others.length ? others.map(x => `
<a class="related-item" href="#/watch/${x.id}">
<img src="/thumb/${x.id}" alt="" loading="lazy" onerror="this.outerHTML='<div class=ph>▶</div>'">
<div><div class="t">${esc(x.title)}</div><div class="m">${fmtDur(x.duration)} · ${fmtViews(x.views)}</div></div>
</a>`).join('') : '<p style="color:var(--muted);font-size:13px">No other videos in this channel.</p>';
}
}
async function renderPlaylistPanel(panel, videoId) {
panel.innerHTML = '<div style="color:var(--muted);font-size:13px;padding:4px 2px">Loading playlists…</div>';
const playlists = await api('/api/playlists').catch(() => []);
const details = await Promise.all(playlists.map(async p => {
try {
const d = await api(`/api/playlists/${p.id}`);
return { ...p, videos: d.videos };
} catch { return { ...p, videos: [] }; }
}));
panel.innerHTML = `
<div class="pl-list">
${details.length ? details.map(p => `<div class="pl-item" data-playlist-id="${p.id}">
<span>${esc(p.name)} <span style="opacity:.55;font-weight:400">(${p.videos.length})</span></span>
<span class="check">${p.videos.some(x => x.id === videoId) ? '✓ In playlist' : ''}</span>
</div>`).join('') : '<p style="color:var(--muted);font-size:13px;padding:2px">No playlists yet — create one below.</p>'}
</div>
<form class="new-pl" id="panel-new-playlist">
<input type="text" id="panel-new-name" placeholder="New playlist name…" maxlength="80" required>
<button type="submit">Create</button>
</form>`;
panel.querySelectorAll('.pl-item').forEach(item => {
item.addEventListener('click', async () => {
const pid = parseInt(item.dataset.playlistId, 10);
const isMember = item.querySelector('.check').textContent.trim() !== '';
try {
if (isMember) {
await api(`/api/playlists/${pid}/items/${videoId}`, { method: 'DELETE' });
} else {
await api(`/api/playlists/${pid}/items`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: videoId }) });
}
await renderPlaylistPanel(panel, videoId);
} catch (err) { toast(err.message); }
});
});
panel.querySelector('#panel-new-playlist').addEventListener('submit', async (e) => {
e.preventDefault();
const name = document.getElementById('panel-new-name').value.trim();
if (!name) return;
try {
const r = await api('/api/playlists', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) });
await api(`/api/playlists/${r.id}/items`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: videoId }) });
await renderPlaylistPanel(panel, videoId);
} catch (err) { toast(err.message); }
});
}
async function render() {
const hash = location.hash.slice(2);
if (playerCleanup) { playerCleanup(); playerCleanup = null; }
const user = await getMe();
if (!user) { showLoginScreen(); return; }
showApp(user);
document.querySelectorAll('nav a[data-nav]').forEach(a => a.classList.toggle('active',
(hash === '' || hash === '/') && a.dataset.nav === 'home' ||
hash.startsWith('/playlists') && a.dataset.nav === 'playlists' ||
hash.startsWith('/favorites') && a.dataset.nav === 'favorites' ||
hash.startsWith('/history') && a.dataset.nav === 'history' ||
hash.startsWith('/stats') && a.dataset.nav === 'stats'));
const parts = hash.split('/').filter(Boolean);
if (parts[0] === 'channel' && parts[1]) {
await renderChannel(decodeURIComponent(parts.slice(1).join('/')));
} else if (parts[0] === 'watch' && parts[1]) {
await renderWatch(parseInt(parts[1], 10));
} else if (parts[0] === 'playlists' && parts[1]) {
await renderPlaylistDetail(parseInt(parts[1], 10));
} else if (parts[0] === 'playlists') {
await renderPlaylists();
} else if (parts[0] === 'favorites') {
state.q = ''; searchInput.value = '';
await renderFavorites();
} else if (parts[0] === 'history') {
await renderHistory();
} else if (parts[0] === 'stats') {
await renderStats();
} else {
currentRoute = 'home';
state.channel = null;
await renderHome();
}
}
app.addEventListener('click', (e) => {
const favBtn = e.target.closest('.fav-btn');
if (favBtn) {
e.preventDefault();
e.stopPropagation();
toggleFavoriteButton(favBtn);
return;
}
const link = e.target.closest('[data-href]');
if (link) {
e.preventDefault();
location.hash = link.dataset.href;
}
});
async function toggleFavoriteButton(btn) {
const id = parseInt(btn.dataset.videoId, 10);
try {
const r = await api('/api/favorite', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: id }) });
btn.classList.toggle('off', !r.favorite);
btn.textContent = r.favorite ? '★' : '☆';
toast(r.favorite ? 'Added to favorites' : 'Removed from favorites');
} catch (err) { if (err.message !== 'Unauthorized') toast('Error: ' + err.message); }
}
let searchTimer = null;
searchInput.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
state.q = searchInput.value.trim();
state.offset = 0;
if (location.hash !== '#/') {
location.hash = '#/';
} else {
renderHome();
}
}, 250);
});
document.getElementById('rescan-btn').addEventListener('click', async () => {
const btn = document.getElementById('rescan-btn');
btn.disabled = true; btn.textContent = '…';
try {
const r = await api('/api/rescan', { method: 'POST' });
toast(`Rescan done — ${r.added} added, ${r.updated} updated, ${r.removed} removed`);
render();
} catch (err) { if (err.message !== 'Unauthorized') toast('Rescan failed: ' + err.message); }
finally { btn.disabled = false; btn.textContent = '⟳'; }
});
window.addEventListener('hashchange', render);
render();