Fetch lyrics from LRCLIB (synced when available) and serve an admin media library of uploaded video and audio with cover art and embedded lyrics

This commit is contained in:
Jonathan Sykes
2026-09-20 05:59:50 +08:00
parent 9c1ec4ac51
commit b983c6ca3c
14 changed files with 963 additions and 25 deletions

View File

@@ -1085,8 +1085,15 @@ function warmThumb(url) {
fetch(url, { mode: 'cors', credentials: 'omit' }).catch(() => {});
}
// A YouTube id, or one of the server's own uploads (server/uploads.js).
const YT_ID_RE = /^[A-Za-z0-9_-]{11}$/;
const UPLOAD_ID_RE = /^upl_[a-f0-9]{12}$/;
const isUploadId = (id) => UPLOAD_ID_RE.test(String(id || ''));
const isMediaId = (id) => YT_ID_RE.test(String(id || '')) || isUploadId(id);
function thumbUrlFor(id, known) {
if (known && known.thumbnail) return known.thumbnail;
if (isUploadId(id)) return `/api/uploads/${id}/art`; // 404s when the file has no cover
if (String(id).startsWith('edit_')) return ''; // edited copies have no YouTube art
return `https://i.ytimg.com/vi/${id}/mqdefault.jpg`;
}
@@ -1763,7 +1770,9 @@ const Player = {
attach(quality) {
const V = els.video, A = els.audio;
const audioOnly = data.settings.audioOnly;
// An uploaded audio file has no picture track: play it like audio-only and
// show its cover art where the video would be.
const audioOnly = data.settings.audioOnly || (current && current.kind === 'audio');
// Reset
V.pause(); A.pause();
@@ -2357,7 +2366,7 @@ const Notes = (() => {
};
// ---- small helpers ----
const supported = (meta) => WEB && meta && !meta.custom && /^[A-Za-z0-9_-]{11}$/.test(meta.id || '');
const supported = (meta) => WEB && meta && !meta.custom && isMediaId(meta.id || '');
const profileName = () => (data.profile && data.profile.name) || '';
const lines = () => (st.sync ? st.sync.lines : (st.lyrics && st.lyrics.data && st.lyrics.data.lines) || []);
const chapters = () => (st.chapters && st.chapters.data && st.chapters.data.items) || [];
@@ -2474,8 +2483,9 @@ const Notes = (() => {
<div class="notes-empty">
<div>No lyrics yet for this song.</div>
<div class="notes-empty-actions">
<button class="np-btn" type="button" data-act="web">🌐 Find lyrics online</button>
<button class="np-btn" type="button" data-act="paste">✎ Add lyrics</button>
<button class="np-btn" type="button" data-act="captions">⤓ Import YouTube captions</button>
${isUploadId(st.videoId) ? '' : '<button class="np-btn" type="button" data-act="captions">⤓ Import YouTube captions</button>'}
</div>
<div class="notes-empty-hint">Lyrics and chapters are shared with everyone who plays this song.</div>
</div>`;
@@ -2743,6 +2753,27 @@ const Notes = (() => {
else setTimeout(() => ta.focus(), 50);
}
// Look the song up on LRCLIB (published, often synced lyrics) and save it.
async function fetchWebLyrics(overwrite = false) {
const id = st.videoId;
if (!id || !requireProfile()) return;
setStatus('Looking up lyrics online…');
try {
const res = await fetch(`/api/notes/${encodeURIComponent(id)}/lyrics/web`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ profile: profileName(), overwrite }),
});
const j = await res.json().catch(() => null);
if (!j || !j.ok) { toast('⚠ ' + ((j && j.error) || `HTTP ${res.status}`), { duration: 5000 }); setStatus(''); return; }
toast(`🌐 ${j.lines} ${j.synced ? 'timed' : 'untimed'} lines from LRCLIB (${j.match.artist} – ${j.match.track})`, { duration: 5000 });
setStatus('');
load(current && current.meta ? current.meta : { id });
} catch (err) {
toast('⚠ ' + err.message);
setStatus('');
}
}
// ---- tap-sync ----
function startSync() {
if (!st.videoId || !requireProfile()) return;
@@ -3134,7 +3165,10 @@ const Notes = (() => {
const q = $('tsQuery').value.trim().toLowerCase();
const srcSel = $('tsSource');
const haveLyrics = !!(st.lyrics && st.lyrics.data && st.lyrics.data.lines.length);
if (!haveLyrics && srcSel.value === 'lyrics' && !srcSel.dataset.touched) srcSel.value = 'captions';
const ytOnly = !isUploadId(st.videoId);
srcSel.querySelector('option[value="captions"]').disabled = !ytOnly;
if (!ytOnly) srcSel.value = 'lyrics';
else if (!haveLyrics && srcSel.value === 'lyrics' && !srcSel.dataset.touched) srcSel.value = 'captions';
const info = $('tsInfo');
const out = $('tsResults');
let src, label, shift = 0;
@@ -3221,6 +3255,7 @@ const Notes = (() => {
if (act) {
if (act.dataset.act === 'paste') openEditor('');
else if (act.dataset.act === 'captions') openEditor('', { importCaptions: true });
else if (act.dataset.act === 'web') fetchWebLyrics();
return;
}
const row = e.target.closest('[data-i]');
@@ -3439,7 +3474,7 @@ const Remote = (() => {
}
case 'add': {
const v = m.video;
if (!v || typeof v.id !== 'string' || !/^[A-Za-z0-9_-]{11}$/.test(v.id)) break;
if (!v || typeof v.id !== 'string' || !isMediaId(v.id)) break;
const item = slim({ ...v, title: String(v.title || v.id).slice(0, 300), channel: String(v.channel || '').slice(0, 200) });
if (!current || !queue.length) { playFromList([item], 0, 'remote'); }
else if (!queue.slice(queueIndex + 1).some((x) => x.id === item.id)) { queue.push(item); renderUpNext(); }
@@ -4183,7 +4218,7 @@ const Wave = (() => {
st.id = meta && meta.id;
st.peaks = null;
refresh();
if (!WEB || !st.id || meta.custom || !/^[A-Za-z0-9_-]{11}$/.test(st.id)) return;
if (!WEB || !st.id || meta.custom || !isMediaId(st.id)) return;
const cached = fromCache(st.id);
if (cached) { st.peaks = cached; refresh(); }
for (let attempt = 0; attempt < 3; attempt++) {
@@ -4548,7 +4583,7 @@ const Presenter = (() => {
st.all = [];
st.docOff = 0;
render(v);
if (!id || !/^[A-Za-z0-9_-]{11}$/.test(id)) return;
if (!id || !isMediaId(id)) return;
let notes = st.notes.get(id);
if (!notes) {
try {
@@ -4680,6 +4715,40 @@ async function playVideoAt(v, t = 0) {
}
}
// ============================================================================
// 📁 Library — video/audio uploaded to this server
// ============================================================================
async function renderLibrary() {
els.listTitle.textContent = 'Library';
els.listActions.innerHTML = '';
els.status.classList.add('hidden');
els.cards.innerHTML = '<div class="sm-busy">Loading the server library…</div>';
let list = [];
try {
const j = await (await fetch('/api/uploads?limit=200')).json();
list = (j && j.ok && j.uploads) || [];
} catch {
els.cards.innerHTML = '<div class="sm-err">⚠ Could not reach the server</div>';
return;
}
if (view.type !== 'library') return;
if (!list.length) {
els.cards.innerHTML = `
<div class="empty-state">
<div class="empty-icon">📁</div>
<h3 class="empty-title">Nothing uploaded yet</h3>
<p class="empty-desc">An admin can upload videos and audio at <b>/admin</b>; they show up here and in search, with their cover art and any embedded lyrics.</p>
</div>`;
return;
}
const cards = list.map((u) => ({
id: u.id, title: u.title, channel: u.artist || u.album || 'Uploaded', duration: u.duration,
thumbnail: u.art ? `/api/uploads/${u.id}/art` : '', kind: u.kind, upload: true,
}));
els.cards.innerHTML = '';
cards.forEach((v, i) => els.cards.appendChild(renderCard(v, i, cards)));
}
// ============================================================================
// 📝 Notes view — every video's personal notes & bookmarks
// ============================================================================
@@ -4776,7 +4845,7 @@ const Share = (() => {
<label class="sm-row">Moment <input class="sm-time" inputmode="decimal" value="${LyricsCore.fmtClock(t0)}" /></label>
<div class="sm-links">
<div class="sm-link"><span>This app</span><code class="sm-app"></code><button class="np-btn" type="button" data-act="app">Copy</button></div>
<div class="sm-link"><span>YouTube</span><code class="sm-yt"></code><button class="np-btn" type="button" data-act="yt">Copy</button></div>
${isUploadId(meta.id) ? '' : '<div class="sm-link"><span>YouTube</span><code class="sm-yt"></code><button class="np-btn" type="button" data-act="yt">Copy</button></div>'}
</div>
<div class="sm-gif">
<div class="sm-gif-controls">
@@ -4798,7 +4867,8 @@ const Share = (() => {
const cur = () => { const v = LyricsCore.parseStamp(timeIn.value); return v === null ? t0 : v; };
const refresh = () => {
body.querySelector('.sm-app').textContent = appLink(meta.id, cur());
body.querySelector('.sm-yt').textContent = ytLink(meta.id, cur());
const yt = body.querySelector('.sm-yt');
if (yt) yt.textContent = ytLink(meta.id, cur());
};
timeIn.addEventListener('input', refresh);
timeIn.addEventListener('keydown', (e) => e.stopPropagation());
@@ -4890,7 +4960,7 @@ const Share = (() => {
id = (q.get('v') || '').trim();
t = Math.max(0, parseFloat(q.get('t')) || 0);
} catch { return; }
if (!/^[A-Za-z0-9_-]{11}$/.test(id)) return;
if (!isMediaId(id)) return;
try {
const u = new URL(location.href);
u.searchParams.delete('v');
@@ -5213,8 +5283,9 @@ const Gestures = (() => {
const External = (() => {
const isAndroid = /Android/i.test(navigator.userAgent);
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
const streamUrl = (id) => `${location.origin}/api/media/${encodeURIComponent(id)}`;
const streamUrl = (id) => `${location.origin}${isUploadId(id) ? '/api/uploads/' : '/api/media/'}${encodeURIComponent(id)}`;
async function cached(id) {
if (isUploadId(id)) return true; // uploads are always a single file on the server
try { const j = await (await fetch(`/api/media/${encodeURIComponent(id)}/status`)).json(); return j && j.status === 'ready'; } catch { return false; }
}
const intent = (url, title, pkg) => `intent:${url}#Intent;action=android.intent.action.VIEW;type=video/*;${pkg ? `package=${pkg};` : ''}S.title=${encodeURIComponent(title || '')};end`;
@@ -6364,6 +6435,7 @@ function renderList() {
if (view.type === 'downloads') { renderDownloads(); return; }
if (view.type === 'stats') { renderStats(); return; }
if (view.type === 'notes') { renderNotesView(); return; }
if (view.type === 'library') { renderLibrary(); return; }
// Filter bar — show for filterable views
const filterableViews = ['history', 'playlist', 'queue', 'channel', 'smart'];
@@ -6651,7 +6723,8 @@ async function renderSaved() {
row.className = 'card saved-card' + (isCustom ? ' custom' : '');
row.dataset.id = it.id;
row.innerHTML = `
<div class="thumb"><img loading="lazy" src="${escapeHtml(v.thumbnail || '')}" alt="" />${isCustom ? '<span class="edit-badge" title="Edited copy">✂</span>' : ''}</div>
<div class="thumb"><img loading="lazy" src="${escapeHtml(v.thumbnail || thumbUrlFor(v.id, null) || '')}" alt=""
onerror="this.classList.add('no-art')" />${isCustom ? '<span class="edit-badge" title="Edited copy">✂</span>' : ''}${isUploadId(v.id) ? `<span class="upload-badge" title="On this server">${v.kind === 'audio' ? '♪' : '📁'}</span>` : ''}</div>
<div class="card-info">
<div class="card-title"></div>
<div class="card-channel saved-size">${isCustom ? '✂ edited · ' : ''}${fmtBytes(it.size)}</div>